1 /* Routines to implement minimum-cost maximal flow algorithm used to smooth
2 basic block and edge frequency counts.
3 Copyright (C) 2008-2013 Free Software Foundation, Inc.
4 Contributed by Paul Yuan (yingbo.com@gmail.com) and
5 Vinodha Ramasamy (vinodha@google.com).
7 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
23 [1] "Feedback-directed Optimizations in GCC with Estimated Edge Profiles
24 from Hardware Event Sampling", Vinodha Ramasamy, Paul Yuan, Dehao Chen,
25 and Robert Hundt; GCC Summit 2008.
26 [2] "Complementing Missing and Inaccurate Profiling Using a Minimum Cost
27 Circulation Algorithm", Roy Levin, Ilan Newman and Gadi Haber;
30 Algorithm to smooth basic block and edge counts:
31 1. create_fixup_graph: Create fixup graph by translating function CFG into
32 a graph that satisfies MCF algorithm requirements.
33 2. find_max_flow: Find maximal flow.
34 3. compute_residual_flow: Form residual network.
36 cancel_negative_cycle: While G contains a negative cost cycle C, reverse
37 the flow on the found cycle by the minimum residual capacity in that
39 5. Form the minimal cost flow
41 6. adjust_cfg_counts: Update initial edge weights with corrected weights.
42 delta(u.v) = f(u,v) -f(v,u).
43 w*(u,v) = w(u,v) + delta(u,v). */
47 #include "coretypes.h"
48 #include "basic-block.h"
53 /* CAP_INFINITY: Constant to represent infinite capacity. */
54 #define CAP_INFINITY INTTYPE_MAXIMUM (HOST_WIDEST_INT)
57 #define K_POS(b) ((b))
58 #define K_NEG(b) (50 * (b))
59 #define COST(k, w) ((k) / mcf_ln ((w) + 2))
60 /* Limit the number of iterations for cancel_negative_cycles() to ensure
61 reasonable compile time. */
62 #define MAX_ITER(n, e) 10 + (1000000 / ((n) * (e)))
66 VERTEX_SPLIT_EDGE
, /* Edge to represent vertex with w(e) = w(v). */
67 REDIRECT_EDGE
, /* Edge after vertex transformation. */
69 SOURCE_CONNECT_EDGE
, /* Single edge connecting to single source. */
70 SINK_CONNECT_EDGE
, /* Single edge connecting to single sink. */
71 BALANCE_EDGE
, /* Edge connecting with source/sink: cp(e) = 0. */
72 REDIRECT_NORMALIZED_EDGE
, /* Normalized edge for a redirect edge. */
73 REVERSE_NORMALIZED_EDGE
/* Normalized edge for a reverse edge. */
76 /* Structure to represent an edge in the fixup graph. */
77 typedef struct fixup_edge_d
81 /* Flag denoting type of edge and attributes for the flow field. */
84 /* Index to the normalization vertex added for this edge. */
85 int norm_vertex_index
;
86 /* Flow for this edge. */
88 /* Residual flow for this edge - used during negative cycle canceling. */
92 gcov_type max_capacity
;
95 typedef fixup_edge_type
*fixup_edge_p
;
98 /* Structure to represent a vertex in the fixup graph. */
99 typedef struct fixup_vertex_d
101 vec
<fixup_edge_p
> succ_edges
;
104 typedef fixup_vertex_type
*fixup_vertex_p
;
106 /* Fixup graph used in the MCF algorithm. */
107 typedef struct fixup_graph_d
109 /* Current number of vertices for the graph. */
111 /* Current number of edges for the graph. */
113 /* Index of new entry vertex. */
115 /* Index of new exit vertex. */
117 /* Fixup vertex list. Adjacency list for fixup graph. */
118 fixup_vertex_p vertex_list
;
119 /* Fixup edge list. */
120 fixup_edge_p edge_list
;
123 typedef struct queue_d
131 /* Structure used in the maximal flow routines to find augmenting path. */
132 typedef struct augmenting_path_d
134 /* Queue used to hold vertex indices. */
135 queue_type queue_list
;
136 /* Vector to hold chain of pred vertex indices in augmenting path. */
138 /* Vector that indicates if basic block i has been visited. */
140 } augmenting_path_type
;
143 /* Function definitions. */
145 /* Dump routines to aid debugging. */
147 /* Print basic block with index N for FIXUP_GRAPH in n' and n'' format. */
150 print_basic_block (FILE *file
, fixup_graph_type
*fixup_graph
, int n
)
152 if (n
== ENTRY_BLOCK
)
153 fputs ("ENTRY", file
);
154 else if (n
== ENTRY_BLOCK
+ 1)
155 fputs ("ENTRY''", file
);
156 else if (n
== 2 * EXIT_BLOCK
)
157 fputs ("EXIT", file
);
158 else if (n
== 2 * EXIT_BLOCK
+ 1)
159 fputs ("EXIT''", file
);
160 else if (n
== fixup_graph
->new_exit_index
)
161 fputs ("NEW_EXIT", file
);
162 else if (n
== fixup_graph
->new_entry_index
)
163 fputs ("NEW_ENTRY", file
);
166 fprintf (file
, "%d", n
/ 2);
175 /* Print edge S->D for given fixup_graph with n' and n'' format.
177 S is the index of the source vertex of the edge (input) and
178 D is the index of the destination vertex of the edge (input) for the given
179 fixup_graph (input). */
182 print_edge (FILE *file
, fixup_graph_type
*fixup_graph
, int s
, int d
)
184 print_basic_block (file
, fixup_graph
, s
);
186 print_basic_block (file
, fixup_graph
, d
);
190 /* Dump out the attributes of a given edge FEDGE in the fixup_graph to a
193 dump_fixup_edge (FILE *file
, fixup_graph_type
*fixup_graph
, fixup_edge_p fedge
)
197 fputs ("NULL fixup graph edge.\n", file
);
201 print_edge (file
, fixup_graph
, fedge
->src
, fedge
->dest
);
206 fprintf (file
, "flow/capacity=" HOST_WIDEST_INT_PRINT_DEC
"/",
208 if (fedge
->max_capacity
== CAP_INFINITY
)
209 fputs ("+oo,", file
);
211 fprintf (file
, "" HOST_WIDEST_INT_PRINT_DEC
",", fedge
->max_capacity
);
214 if (fedge
->is_rflow_valid
)
216 if (fedge
->rflow
== CAP_INFINITY
)
217 fputs (" rflow=+oo.", file
);
219 fprintf (file
, " rflow=" HOST_WIDEST_INT_PRINT_DEC
",", fedge
->rflow
);
222 fprintf (file
, " cost=" HOST_WIDEST_INT_PRINT_DEC
".", fedge
->cost
);
224 fprintf (file
, "\t(%d->%d)", fedge
->src
, fedge
->dest
);
230 case VERTEX_SPLIT_EDGE
:
231 fputs (" @VERTEX_SPLIT_EDGE", file
);
235 fputs (" @REDIRECT_EDGE", file
);
238 case SOURCE_CONNECT_EDGE
:
239 fputs (" @SOURCE_CONNECT_EDGE", file
);
242 case SINK_CONNECT_EDGE
:
243 fputs (" @SINK_CONNECT_EDGE", file
);
247 fputs (" @REVERSE_EDGE", file
);
251 fputs (" @BALANCE_EDGE", file
);
254 case REDIRECT_NORMALIZED_EDGE
:
255 case REVERSE_NORMALIZED_EDGE
:
256 fputs (" @NORMALIZED_EDGE", file
);
260 fputs (" @INVALID_EDGE", file
);
268 /* Print out the edges and vertices of the given FIXUP_GRAPH, into the dump
269 file. The input string MSG is printed out as a heading. */
272 dump_fixup_graph (FILE *file
, fixup_graph_type
*fixup_graph
, const char *msg
)
275 int fnum_vertices
, fnum_edges
;
277 fixup_vertex_p fvertex_list
, pfvertex
;
280 gcc_assert (fixup_graph
);
281 fvertex_list
= fixup_graph
->vertex_list
;
282 fnum_vertices
= fixup_graph
->num_vertices
;
283 fnum_edges
= fixup_graph
->num_edges
;
285 fprintf (file
, "\nDump fixup graph for %s(): %s.\n",
286 current_function_name (), msg
);
288 "There are %d vertices and %d edges. new_exit_index is %d.\n\n",
289 fnum_vertices
, fnum_edges
, fixup_graph
->new_exit_index
);
291 for (i
= 0; i
< fnum_vertices
; i
++)
293 pfvertex
= fvertex_list
+ i
;
294 fprintf (file
, "vertex_list[%d]: %d succ fixup edges.\n",
295 i
, pfvertex
->succ_edges
.length ());
297 for (j
= 0; pfvertex
->succ_edges
.iterate (j
, &pfedge
);
300 /* Distinguish forward edges and backward edges in the residual flow
303 fputs ("(f) ", file
);
304 else if (pfedge
->is_rflow_valid
)
305 fputs ("(b) ", file
);
306 dump_fixup_edge (file
, fixup_graph
, pfedge
);
314 /* Utility routines. */
315 /* ln() implementation: approximate calculation. Returns ln of X. */
336 /* sqrt() implementation: based on open source QUAKE3 code (magic sqrt
337 implementation) by John Carmack. Returns sqrt of X. */
342 #define MAGIC_CONST1 0x1fbcf800
343 #define MAGIC_CONST2 0x5f3759df
347 } convertor
, convertor2
;
351 convertor
.floatPart
= x
;
352 convertor2
.floatPart
= x
;
353 convertor
.intPart
= MAGIC_CONST1
+ (convertor
.intPart
>> 1);
354 convertor2
.intPart
= MAGIC_CONST2
- (convertor2
.intPart
>> 1);
356 return 0.5f
* (convertor
.floatPart
+ (x
* convertor2
.floatPart
));
360 /* Common code shared between add_fixup_edge and add_rfixup_edge. Adds an edge
361 (SRC->DEST) to the edge_list maintained in FIXUP_GRAPH with cost of the edge
362 added set to COST. */
365 add_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
, gcov_type cost
)
367 fixup_vertex_p curr_vertex
= fixup_graph
->vertex_list
+ src
;
368 fixup_edge_p curr_edge
= fixup_graph
->edge_list
+ fixup_graph
->num_edges
;
369 curr_edge
->src
= src
;
370 curr_edge
->dest
= dest
;
371 curr_edge
->cost
= cost
;
372 fixup_graph
->num_edges
++;
374 dump_fixup_edge (dump_file
, fixup_graph
, curr_edge
);
375 curr_vertex
->succ_edges
.safe_push (curr_edge
);
380 /* Add a fixup edge (src->dest) with attributes TYPE, WEIGHT, COST and
381 MAX_CAPACITY to the edge_list in the fixup graph. */
384 add_fixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
,
385 edge_type type
, gcov_type weight
, gcov_type cost
,
386 gcov_type max_capacity
)
388 fixup_edge_p curr_edge
= add_edge(fixup_graph
, src
, dest
, cost
);
389 curr_edge
->type
= type
;
390 curr_edge
->weight
= weight
;
391 curr_edge
->max_capacity
= max_capacity
;
395 /* Add a residual edge (SRC->DEST) with attributes RFLOW and COST
396 to the fixup graph. */
399 add_rfixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
,
400 gcov_type rflow
, gcov_type cost
)
402 fixup_edge_p curr_edge
= add_edge (fixup_graph
, src
, dest
, cost
);
403 curr_edge
->rflow
= rflow
;
404 curr_edge
->is_rflow_valid
= true;
405 /* This edge is not a valid edge - merely used to hold residual flow. */
406 curr_edge
->type
= INVALID_EDGE
;
410 /* Return the pointer to fixup edge SRC->DEST or NULL if edge does not
411 exist in the FIXUP_GRAPH. */
414 find_fixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
)
418 fixup_vertex_p pfvertex
;
420 gcc_assert (src
< fixup_graph
->num_vertices
);
422 pfvertex
= fixup_graph
->vertex_list
+ src
;
424 for (j
= 0; pfvertex
->succ_edges
.iterate (j
, &pfedge
);
426 if (pfedge
->dest
== dest
)
433 /* Cleanup routine to free structures in FIXUP_GRAPH. */
436 delete_fixup_graph (fixup_graph_type
*fixup_graph
)
439 int fnum_vertices
= fixup_graph
->num_vertices
;
440 fixup_vertex_p pfvertex
= fixup_graph
->vertex_list
;
442 for (i
= 0; i
< fnum_vertices
; i
++, pfvertex
++)
443 pfvertex
->succ_edges
.release ();
445 free (fixup_graph
->vertex_list
);
446 free (fixup_graph
->edge_list
);
450 /* Creates a fixup graph FIXUP_GRAPH from the function CFG. */
453 create_fixup_graph (fixup_graph_type
*fixup_graph
)
455 double sqrt_avg_vertex_weight
= 0;
456 double total_vertex_weight
= 0;
459 /* Vector to hold D(v) = sum_out_edges(v) - sum_in_edges(v). */
460 gcov_type
*diff_out_in
= NULL
;
461 gcov_type supply_value
= 1, demand_value
= 0;
463 int new_entry_index
= 0, new_exit_index
= 0;
469 fixup_edge_p pfedge
, r_pfedge
;
470 fixup_edge_p fedge_list
;
473 /* Each basic_block will be split into 2 during vertex transformation. */
474 int fnum_vertices_after_transform
= 2 * n_basic_blocks
;
475 int fnum_edges_after_transform
= n_edges
+ n_basic_blocks
;
477 /* Count the new SOURCE and EXIT vertices to be added. */
478 int fmax_num_vertices
=
479 fnum_vertices_after_transform
+ n_edges
+ n_basic_blocks
+ 2;
481 /* In create_fixup_graph: Each basic block and edge can be split into 3
482 edges. Number of balance edges = n_basic_blocks. So after
484 max_edges = 4 * n_basic_blocks + 3 * n_edges
485 Accounting for residual flow edges
486 max_edges = 2 * (4 * n_basic_blocks + 3 * n_edges)
487 = 8 * n_basic_blocks + 6 * n_edges
488 < 8 * n_basic_blocks + 8 * n_edges. */
489 int fmax_num_edges
= 8 * (n_basic_blocks
+ n_edges
);
491 /* Initial num of vertices in the fixup graph. */
492 fixup_graph
->num_vertices
= n_basic_blocks
;
494 /* Fixup graph vertex list. */
495 fixup_graph
->vertex_list
=
496 (fixup_vertex_p
) xcalloc (fmax_num_vertices
, sizeof (fixup_vertex_type
));
498 /* Fixup graph edge list. */
499 fixup_graph
->edge_list
=
500 (fixup_edge_p
) xcalloc (fmax_num_edges
, sizeof (fixup_edge_type
));
503 (gcov_type
*) xcalloc (1 + fnum_vertices_after_transform
,
506 /* Compute constants b, k_pos, k_neg used in the cost function calculation.
507 b = sqrt(avg_vertex_weight(cfg)); k_pos = b; k_neg = 50b. */
508 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
509 total_vertex_weight
+= bb
->count
;
511 sqrt_avg_vertex_weight
= mcf_sqrt (total_vertex_weight
/ n_basic_blocks
);
513 k_pos
= K_POS (sqrt_avg_vertex_weight
);
514 k_neg
= K_NEG (sqrt_avg_vertex_weight
);
516 /* 1. Vertex Transformation: Split each vertex v into two vertices v' and v'',
517 connected by an edge e from v' to v''. w(e) = w(v). */
520 fprintf (dump_file
, "\nVertex transformation:\n");
522 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
524 /* v'->v'': index1->(index1+1). */
526 fcost
= (gcov_type
) COST (k_pos
, bb
->count
);
527 add_fixup_edge (fixup_graph
, i
, i
+ 1, VERTEX_SPLIT_EDGE
, bb
->count
,
528 fcost
, CAP_INFINITY
);
529 fixup_graph
->num_vertices
++;
531 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
533 /* Edges with ignore attribute set should be treated like they don't
535 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
537 j
= 2 * e
->dest
->index
;
538 fcost
= (gcov_type
) COST (k_pos
, e
->count
);
539 add_fixup_edge (fixup_graph
, i
+ 1, j
, REDIRECT_EDGE
, e
->count
, fcost
,
544 /* After vertex transformation. */
545 gcc_assert (fixup_graph
->num_vertices
== fnum_vertices_after_transform
);
546 /* Redirect edges are not added for edges with ignore attribute. */
547 gcc_assert (fixup_graph
->num_edges
<= fnum_edges_after_transform
);
549 fnum_edges_after_transform
= fixup_graph
->num_edges
;
551 /* 2. Initialize D(v). */
552 for (i
= 0; i
< fnum_edges_after_transform
; i
++)
554 pfedge
= fixup_graph
->edge_list
+ i
;
555 diff_out_in
[pfedge
->src
] += pfedge
->weight
;
556 diff_out_in
[pfedge
->dest
] -= pfedge
->weight
;
559 /* Entry block - vertex indices 0, 1; EXIT block - vertex indices 2, 3. */
560 for (i
= 0; i
<= 3; i
++)
563 /* 3. Add reverse edges: needed to decrease counts during smoothing. */
565 fprintf (dump_file
, "\nReverse edges:\n");
566 for (i
= 0; i
< fnum_edges_after_transform
; i
++)
568 pfedge
= fixup_graph
->edge_list
+ i
;
569 if ((pfedge
->src
== 0) || (pfedge
->src
== 2))
571 r_pfedge
= find_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
);
572 if (!r_pfedge
&& pfedge
->weight
)
574 /* Skip adding reverse edges for edges with w(e) = 0, as its maximum
576 fcost
= (gcov_type
) COST (k_neg
, pfedge
->weight
);
577 add_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
,
578 REVERSE_EDGE
, 0, fcost
, pfedge
->weight
);
582 /* 4. Create single source and sink. Connect new source vertex s' to function
583 entry block. Connect sink vertex t' to function exit. */
585 fprintf (dump_file
, "\ns'->S, T->t':\n");
587 new_entry_index
= fixup_graph
->new_entry_index
= fixup_graph
->num_vertices
;
588 fixup_graph
->num_vertices
++;
589 /* Set supply_value to 1 to avoid zero count function ENTRY. */
590 add_fixup_edge (fixup_graph
, new_entry_index
, ENTRY_BLOCK
, SOURCE_CONNECT_EDGE
,
591 1 /* supply_value */, 0, 1 /* supply_value */);
593 /* Create new exit with EXIT_BLOCK as single pred. */
594 new_exit_index
= fixup_graph
->new_exit_index
= fixup_graph
->num_vertices
;
595 fixup_graph
->num_vertices
++;
596 add_fixup_edge (fixup_graph
, 2 * EXIT_BLOCK
+ 1, new_exit_index
,
598 0 /* demand_value */, 0, 0 /* demand_value */);
600 /* Connect vertices with unbalanced D(v) to source/sink. */
602 fprintf (dump_file
, "\nD(v) balance:\n");
603 /* Skip vertices for ENTRY (0, 1) and EXIT (2,3) blocks, so start with i = 4.
604 diff_out_in[v''] will be 0, so skip v'' vertices, hence i += 2. */
605 for (i
= 4; i
< new_entry_index
; i
+= 2)
607 if (diff_out_in
[i
] > 0)
609 add_fixup_edge (fixup_graph
, i
, new_exit_index
, BALANCE_EDGE
, 0, 0,
611 demand_value
+= diff_out_in
[i
];
613 else if (diff_out_in
[i
] < 0)
615 add_fixup_edge (fixup_graph
, new_entry_index
, i
, BALANCE_EDGE
, 0, 0,
617 supply_value
-= diff_out_in
[i
];
621 /* Set supply = demand. */
624 fprintf (dump_file
, "\nAdjust supply and demand:\n");
625 fprintf (dump_file
, "supply_value=" HOST_WIDEST_INT_PRINT_DEC
"\n",
627 fprintf (dump_file
, "demand_value=" HOST_WIDEST_INT_PRINT_DEC
"\n",
631 if (demand_value
> supply_value
)
633 pfedge
= find_fixup_edge (fixup_graph
, new_entry_index
, ENTRY_BLOCK
);
634 pfedge
->max_capacity
+= (demand_value
- supply_value
);
638 pfedge
= find_fixup_edge (fixup_graph
, 2 * EXIT_BLOCK
+ 1, new_exit_index
);
639 pfedge
->max_capacity
+= (supply_value
- demand_value
);
642 /* 6. Normalize edges: remove anti-parallel edges. Anti-parallel edges are
643 created by the vertex transformation step from self-edges in the original
644 CFG and by the reverse edges added earlier. */
646 fprintf (dump_file
, "\nNormalize edges:\n");
648 fnum_edges
= fixup_graph
->num_edges
;
649 fedge_list
= fixup_graph
->edge_list
;
651 for (i
= 0; i
< fnum_edges
; i
++)
653 pfedge
= fedge_list
+ i
;
654 r_pfedge
= find_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
);
655 if (((pfedge
->type
== VERTEX_SPLIT_EDGE
)
656 || (pfedge
->type
== REDIRECT_EDGE
)) && r_pfedge
)
658 new_index
= fixup_graph
->num_vertices
;
659 fixup_graph
->num_vertices
++;
663 fprintf (dump_file
, "\nAnti-parallel edge:\n");
664 dump_fixup_edge (dump_file
, fixup_graph
, pfedge
);
665 dump_fixup_edge (dump_file
, fixup_graph
, r_pfedge
);
666 fprintf (dump_file
, "New vertex is %d.\n", new_index
);
667 fprintf (dump_file
, "------------------\n");
671 pfedge
->norm_vertex_index
= new_index
;
674 fprintf (dump_file
, "After normalization:\n");
675 dump_fixup_edge (dump_file
, fixup_graph
, pfedge
);
678 /* Add a new fixup edge: new_index->src. */
679 add_fixup_edge (fixup_graph
, new_index
, pfedge
->src
,
680 REVERSE_NORMALIZED_EDGE
, 0, r_pfedge
->cost
,
681 r_pfedge
->max_capacity
);
682 gcc_assert (fixup_graph
->num_vertices
<= fmax_num_vertices
);
684 /* Edge: r_pfedge->src -> r_pfedge->dest
685 ==> r_pfedge->src -> new_index. */
686 r_pfedge
->dest
= new_index
;
687 r_pfedge
->type
= REVERSE_NORMALIZED_EDGE
;
688 r_pfedge
->cost
= pfedge
->cost
;
689 r_pfedge
->max_capacity
= pfedge
->max_capacity
;
691 dump_fixup_edge (dump_file
, fixup_graph
, r_pfedge
);
696 dump_fixup_graph (dump_file
, fixup_graph
, "After create_fixup_graph()");
703 /* Allocates space for the structures in AUGMENTING_PATH. The space needed is
704 proportional to the number of nodes in the graph, which is given by
708 init_augmenting_path (augmenting_path_type
*augmenting_path
, int graph_size
)
710 augmenting_path
->queue_list
.queue
= (int *)
711 xcalloc (graph_size
+ 2, sizeof (int));
712 augmenting_path
->queue_list
.size
= graph_size
+ 2;
713 augmenting_path
->bb_pred
= (int *) xcalloc (graph_size
, sizeof (int));
714 augmenting_path
->is_visited
= (int *) xcalloc (graph_size
, sizeof (int));
717 /* Free the structures in AUGMENTING_PATH. */
719 free_augmenting_path (augmenting_path_type
*augmenting_path
)
721 free (augmenting_path
->queue_list
.queue
);
722 free (augmenting_path
->bb_pred
);
723 free (augmenting_path
->is_visited
);
727 /* Queue routines. Assumes queue will never overflow. */
730 init_queue (queue_type
*queue_list
)
732 gcc_assert (queue_list
);
733 queue_list
->head
= 0;
734 queue_list
->tail
= 0;
737 /* Return true if QUEUE_LIST is empty. */
739 is_empty (queue_type
*queue_list
)
741 return (queue_list
->head
== queue_list
->tail
);
744 /* Insert element X into QUEUE_LIST. */
746 enqueue (queue_type
*queue_list
, int x
)
748 gcc_assert (queue_list
->tail
< queue_list
->size
);
749 queue_list
->queue
[queue_list
->tail
] = x
;
750 (queue_list
->tail
)++;
753 /* Return the first element in QUEUE_LIST. */
755 dequeue (queue_type
*queue_list
)
758 gcc_assert (queue_list
->head
>= 0);
759 x
= queue_list
->queue
[queue_list
->head
];
760 (queue_list
->head
)++;
765 /* Finds a negative cycle in the residual network using
766 the Bellman-Ford algorithm. The flow on the found cycle is reversed by the
767 minimum residual capacity of that cycle. ENTRY and EXIT vertices are not
771 FIXUP_GRAPH - Residual graph (input/output)
772 The following are allocated/freed by the caller:
773 PI - Vector to hold predecessors in path (pi = pred index)
774 D - D[I] holds minimum cost of path from i to sink
775 CYCLE - Vector to hold the minimum cost cycle
778 true if a negative cycle was found, false otherwise. */
781 cancel_negative_cycle (fixup_graph_type
*fixup_graph
,
782 int *pi
, gcov_type
*d
, int *cycle
)
785 int fnum_vertices
, fnum_edges
;
786 fixup_edge_p fedge_list
, pfedge
, r_pfedge
;
787 bool found_cycle
= false;
788 int cycle_start
= 0, cycle_end
= 0;
789 gcov_type sum_cost
= 0, cycle_flow
= 0;
791 bool propagated
= false;
793 gcc_assert (fixup_graph
);
794 fnum_vertices
= fixup_graph
->num_vertices
;
795 fnum_edges
= fixup_graph
->num_edges
;
796 fedge_list
= fixup_graph
->edge_list
;
797 new_entry_index
= fixup_graph
->new_entry_index
;
801 for (i
= 1; i
< fnum_vertices
; i
++)
810 for (k
= 1; k
< fnum_vertices
; k
++)
813 for (i
= 0; i
< fnum_edges
; i
++)
815 pfedge
= fedge_list
+ i
;
816 if (pfedge
->src
== new_entry_index
)
818 if (pfedge
->is_rflow_valid
&& pfedge
->rflow
819 && d
[pfedge
->src
] != CAP_INFINITY
820 && (d
[pfedge
->dest
] > d
[pfedge
->src
] + pfedge
->cost
))
822 d
[pfedge
->dest
] = d
[pfedge
->src
] + pfedge
->cost
;
823 pi
[pfedge
->dest
] = pfedge
->src
;
832 /* No negative cycles exist. */
836 for (i
= 0; i
< fnum_edges
; i
++)
838 pfedge
= fedge_list
+ i
;
839 if (pfedge
->src
== new_entry_index
)
841 if (pfedge
->is_rflow_valid
&& pfedge
->rflow
842 && d
[pfedge
->src
] != CAP_INFINITY
843 && (d
[pfedge
->dest
] > d
[pfedge
->src
] + pfedge
->cost
))
853 /* Augment the cycle with the cycle's minimum residual capacity. */
855 cycle
[0] = pfedge
->dest
;
858 for (i
= 1; i
< fnum_vertices
; i
++)
862 for (k
= 0; k
< i
; k
++)
866 /* cycle[k] -> ... -> cycle[i]. */
877 gcc_assert (cycle
[cycle_start
] == cycle
[cycle_end
]);
879 fprintf (dump_file
, "\nNegative cycle length is %d:\n",
880 cycle_end
- cycle_start
);
883 cycle_flow
= CAP_INFINITY
;
884 for (k
= cycle_start
; k
< cycle_end
; k
++)
886 pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
+ 1], cycle
[k
]);
887 cycle_flow
= MIN (cycle_flow
, pfedge
->rflow
);
888 sum_cost
+= pfedge
->cost
;
890 fprintf (dump_file
, "%d ", cycle
[k
]);
895 fprintf (dump_file
, "%d", cycle
[k
]);
897 ": (" HOST_WIDEST_INT_PRINT_DEC
", " HOST_WIDEST_INT_PRINT_DEC
898 ")\n", sum_cost
, cycle_flow
);
900 "Augment cycle with " HOST_WIDEST_INT_PRINT_DEC
"\n",
904 for (k
= cycle_start
; k
< cycle_end
; k
++)
906 pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
+ 1], cycle
[k
]);
907 r_pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
], cycle
[k
+ 1]);
908 pfedge
->rflow
-= cycle_flow
;
910 pfedge
->flow
+= cycle_flow
;
911 r_pfedge
->rflow
+= cycle_flow
;
913 r_pfedge
->flow
-= cycle_flow
;
920 /* Computes the residual flow for FIXUP_GRAPH by setting the rflow field of
921 the edges. ENTRY and EXIT vertices should not be considered. */
924 compute_residual_flow (fixup_graph_type
*fixup_graph
)
928 fixup_edge_p fedge_list
, pfedge
;
930 gcc_assert (fixup_graph
);
933 fputs ("\ncompute_residual_flow():\n", dump_file
);
935 fnum_edges
= fixup_graph
->num_edges
;
936 fedge_list
= fixup_graph
->edge_list
;
938 for (i
= 0; i
< fnum_edges
; i
++)
940 pfedge
= fedge_list
+ i
;
941 pfedge
->rflow
= pfedge
->max_capacity
- pfedge
->flow
;
942 pfedge
->is_rflow_valid
= true;
943 add_rfixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
, pfedge
->flow
,
949 /* Uses Edmonds-Karp algorithm - BFS to find augmenting path from SOURCE to
950 SINK. The fields in the edge vector in the FIXUP_GRAPH are not modified by
951 this routine. The vector bb_pred in the AUGMENTING_PATH structure is updated
952 to reflect the path found.
953 Returns: 0 if no augmenting path is found, 1 otherwise. */
956 find_augmenting_path (fixup_graph_type
*fixup_graph
,
957 augmenting_path_type
*augmenting_path
, int source
,
962 fixup_vertex_p fvertex_list
, pfvertex
;
964 int *bb_pred
, *is_visited
;
965 queue_type
*queue_list
;
967 gcc_assert (augmenting_path
);
968 bb_pred
= augmenting_path
->bb_pred
;
969 gcc_assert (bb_pred
);
970 is_visited
= augmenting_path
->is_visited
;
971 gcc_assert (is_visited
);
972 queue_list
= &(augmenting_path
->queue_list
);
974 gcc_assert (fixup_graph
);
976 fvertex_list
= fixup_graph
->vertex_list
;
978 for (u
= 0; u
< fixup_graph
->num_vertices
; u
++)
981 init_queue (queue_list
);
982 enqueue (queue_list
, source
);
983 bb_pred
[source
] = -1;
985 while (!is_empty (queue_list
))
987 u
= dequeue (queue_list
);
989 pfvertex
= fvertex_list
+ u
;
990 for (i
= 0; pfvertex
->succ_edges
.iterate (i
, &pfedge
);
993 int dest
= pfedge
->dest
;
994 if ((pfedge
->rflow
> 0) && (is_visited
[dest
] == 0))
996 enqueue (queue_list
, dest
);
998 is_visited
[dest
] = 1;
1009 /* Routine to find the maximal flow:
1011 1. Initialize flow to 0
1012 2. Find an augmenting path form source to sink.
1013 3. Send flow equal to the path's residual capacity along the edges of this path.
1014 4. Repeat steps 2 and 3 until no new augmenting path is found.
1017 SOURCE: index of source vertex (input)
1018 SINK: index of sink vertex (input)
1019 FIXUP_GRAPH: adjacency matrix representing the graph. The flow of the edges will be
1020 set to have a valid maximal flow by this routine. (input)
1021 Return: Maximum flow possible. */
1024 find_max_flow (fixup_graph_type
*fixup_graph
, int source
, int sink
)
1027 augmenting_path_type augmenting_path
;
1029 gcov_type max_flow
= 0;
1031 fixup_edge_p fedge_list
, pfedge
, r_pfedge
;
1033 gcc_assert (fixup_graph
);
1035 fnum_edges
= fixup_graph
->num_edges
;
1036 fedge_list
= fixup_graph
->edge_list
;
1038 /* Initialize flow to 0. */
1039 for (i
= 0; i
< fnum_edges
; i
++)
1041 pfedge
= fedge_list
+ i
;
1045 compute_residual_flow (fixup_graph
);
1047 init_augmenting_path (&augmenting_path
, fixup_graph
->num_vertices
);
1049 bb_pred
= augmenting_path
.bb_pred
;
1050 while (find_augmenting_path (fixup_graph
, &augmenting_path
, source
, sink
))
1052 /* Determine the amount by which we can increment the flow. */
1053 gcov_type increment
= CAP_INFINITY
;
1054 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1056 pfedge
= find_fixup_edge (fixup_graph
, bb_pred
[u
], u
);
1057 increment
= MIN (increment
, pfedge
->rflow
);
1059 max_flow
+= increment
;
1061 /* Now increment the flow. EXIT vertex index is 1. */
1062 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1064 pfedge
= find_fixup_edge (fixup_graph
, bb_pred
[u
], u
);
1065 r_pfedge
= find_fixup_edge (fixup_graph
, u
, bb_pred
[u
]);
1069 pfedge
->flow
+= increment
;
1070 pfedge
->rflow
-= increment
;
1071 r_pfedge
->rflow
+= increment
;
1075 /* backward edge. */
1076 gcc_assert (r_pfedge
->type
);
1077 r_pfedge
->rflow
+= increment
;
1078 r_pfedge
->flow
-= increment
;
1079 pfedge
->rflow
-= increment
;
1085 fprintf (dump_file
, "\nDump augmenting path:\n");
1086 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1088 print_basic_block (dump_file
, fixup_graph
, u
);
1089 fprintf (dump_file
, "<-");
1092 "ENTRY (path_capacity=" HOST_WIDEST_INT_PRINT_DEC
")\n",
1095 "Network flow is " HOST_WIDEST_INT_PRINT_DEC
".\n",
1100 free_augmenting_path (&augmenting_path
);
1102 dump_fixup_graph (dump_file
, fixup_graph
, "After find_max_flow()");
1107 /* Computes the corrected edge and basic block weights using FIXUP_GRAPH
1108 after applying the find_minimum_cost_flow() routine. */
1111 adjust_cfg_counts (fixup_graph_type
*fixup_graph
)
1117 fixup_edge_p pfedge
, pfedge_n
;
1119 gcc_assert (fixup_graph
);
1122 fprintf (dump_file
, "\nadjust_cfg_counts():\n");
1124 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, EXIT_BLOCK_PTR
, next_bb
)
1131 "BB%d: " HOST_WIDEST_INT_PRINT_DEC
"", bb
->index
, bb
->count
);
1133 pfedge
= find_fixup_edge (fixup_graph
, i
, i
+ 1);
1136 bb
->count
+= pfedge
->flow
;
1139 fprintf (dump_file
, " + " HOST_WIDEST_INT_PRINT_DEC
"(",
1141 print_edge (dump_file
, fixup_graph
, i
, i
+ 1);
1142 fprintf (dump_file
, ")");
1147 find_fixup_edge (fixup_graph
, i
+ 1, pfedge
->norm_vertex_index
);
1148 /* Deduct flow from normalized reverse edge. */
1149 if (pfedge
->norm_vertex_index
&& pfedge_n
->flow
)
1151 bb
->count
-= pfedge_n
->flow
;
1154 fprintf (dump_file
, " - " HOST_WIDEST_INT_PRINT_DEC
"(",
1156 print_edge (dump_file
, fixup_graph
, i
+ 1,
1157 pfedge
->norm_vertex_index
);
1158 fprintf (dump_file
, ")");
1162 fprintf (dump_file
, " = " HOST_WIDEST_INT_PRINT_DEC
"\n", bb
->count
);
1165 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1167 /* Treat edges with ignore attribute set as if they don't exist. */
1168 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
1171 j
= 2 * e
->dest
->index
;
1173 fprintf (dump_file
, "%d->%d: " HOST_WIDEST_INT_PRINT_DEC
"",
1174 bb
->index
, e
->dest
->index
, e
->count
);
1176 pfedge
= find_fixup_edge (fixup_graph
, i
+ 1, j
);
1178 if (bb
->index
!= e
->dest
->index
)
1180 /* Non-self edge. */
1183 e
->count
+= pfedge
->flow
;
1186 fprintf (dump_file
, " + " HOST_WIDEST_INT_PRINT_DEC
"(",
1188 print_edge (dump_file
, fixup_graph
, i
+ 1, j
);
1189 fprintf (dump_file
, ")");
1194 find_fixup_edge (fixup_graph
, j
, pfedge
->norm_vertex_index
);
1195 /* Deduct flow from normalized reverse edge. */
1196 if (pfedge
->norm_vertex_index
&& pfedge_n
->flow
)
1198 e
->count
-= pfedge_n
->flow
;
1201 fprintf (dump_file
, " - " HOST_WIDEST_INT_PRINT_DEC
"(",
1203 print_edge (dump_file
, fixup_graph
, j
,
1204 pfedge
->norm_vertex_index
);
1205 fprintf (dump_file
, ")");
1211 /* Handle self edges. Self edge is split with a normalization
1212 vertex. Here i=j. */
1213 pfedge
= find_fixup_edge (fixup_graph
, j
, i
+ 1);
1215 find_fixup_edge (fixup_graph
, i
+ 1, pfedge
->norm_vertex_index
);
1216 e
->count
+= pfedge_n
->flow
;
1217 bb
->count
+= pfedge_n
->flow
;
1220 fprintf (dump_file
, "(self edge)");
1221 fprintf (dump_file
, " + " HOST_WIDEST_INT_PRINT_DEC
"(",
1223 print_edge (dump_file
, fixup_graph
, i
+ 1,
1224 pfedge
->norm_vertex_index
);
1225 fprintf (dump_file
, ")");
1230 e
->probability
= REG_BR_PROB_BASE
* e
->count
/ bb
->count
;
1232 fprintf (dump_file
, " = " HOST_WIDEST_INT_PRINT_DEC
"\t(%.1f%%)\n",
1233 e
->count
, e
->probability
* 100.0 / REG_BR_PROB_BASE
);
1237 ENTRY_BLOCK_PTR
->count
= sum_edge_counts (ENTRY_BLOCK_PTR
->succs
);
1238 EXIT_BLOCK_PTR
->count
= sum_edge_counts (EXIT_BLOCK_PTR
->preds
);
1240 /* Compute edge probabilities. */
1245 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1246 e
->probability
= REG_BR_PROB_BASE
* e
->count
/ bb
->count
;
1251 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1252 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
1256 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1258 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
1259 e
->probability
= REG_BR_PROB_BASE
/ total
;
1266 total
+= EDGE_COUNT (bb
->succs
);
1267 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1268 e
->probability
= REG_BR_PROB_BASE
/ total
;
1275 fprintf (dump_file
, "\nCheck %s() CFG flow conservation:\n",
1276 current_function_name ());
1279 if ((bb
->count
!= sum_edge_counts (bb
->preds
))
1280 || (bb
->count
!= sum_edge_counts (bb
->succs
)))
1283 "BB%d(" HOST_WIDEST_INT_PRINT_DEC
") **INVALID**: ",
1284 bb
->index
, bb
->count
);
1286 "******** BB%d(" HOST_WIDEST_INT_PRINT_DEC
1287 ") **INVALID**: \n", bb
->index
, bb
->count
);
1288 fprintf (dump_file
, "in_edges=" HOST_WIDEST_INT_PRINT_DEC
" ",
1289 sum_edge_counts (bb
->preds
));
1290 fprintf (dump_file
, "out_edges=" HOST_WIDEST_INT_PRINT_DEC
"\n",
1291 sum_edge_counts (bb
->succs
));
1298 /* Implements the negative cycle canceling algorithm to compute a minimum cost
1301 1. Find maximal flow.
1302 2. Form residual network
1304 While G contains a negative cost cycle C, reverse the flow on the found cycle
1305 by the minimum residual capacity in that cycle.
1306 4. Form the minimal cost flow
1309 FIXUP_GRAPH - Initial fixup graph.
1310 The flow field is modified to represent the minimum cost flow. */
1313 find_minimum_cost_flow (fixup_graph_type
*fixup_graph
)
1315 /* Holds the index of predecessor in path. */
1317 /* Used to hold the minimum cost cycle. */
1319 /* Used to record the number of iterations of cancel_negative_cycle. */
1321 /* Vector d[i] holds the minimum cost of path from i to sink. */
1325 int new_entry_index
;
1327 gcc_assert (fixup_graph
);
1328 fnum_vertices
= fixup_graph
->num_vertices
;
1329 new_exit_index
= fixup_graph
->new_exit_index
;
1330 new_entry_index
= fixup_graph
->new_entry_index
;
1332 find_max_flow (fixup_graph
, new_entry_index
, new_exit_index
);
1334 /* Initialize the structures for find_negative_cycle(). */
1335 pred
= (int *) xcalloc (fnum_vertices
, sizeof (int));
1336 d
= (gcov_type
*) xcalloc (fnum_vertices
, sizeof (gcov_type
));
1337 cycle
= (int *) xcalloc (fnum_vertices
, sizeof (int));
1339 /* Repeatedly find and cancel negative cost cycles, until
1340 no more negative cycles exist. This also updates the flow field
1341 to represent the minimum cost flow so far. */
1343 while (cancel_negative_cycle (fixup_graph
, pred
, d
, cycle
))
1346 if (iteration
> MAX_ITER (fixup_graph
->num_vertices
,
1347 fixup_graph
->num_edges
))
1352 dump_fixup_graph (dump_file
, fixup_graph
,
1353 "After find_minimum_cost_flow()");
1355 /* Cleanup structures. */
1362 /* Compute the sum of the edge counts in TO_EDGES. */
1365 sum_edge_counts (vec
<edge
, va_gc
> *to_edges
)
1371 FOR_EACH_EDGE (e
, ei
, to_edges
)
1373 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
1381 /* Main routine. Smoothes the initial assigned basic block and edge counts using
1382 a minimum cost flow algorithm, to ensure that the flow consistency rule is
1383 obeyed: sum of outgoing edges = sum of incoming edges for each basic
1387 mcf_smooth_cfg (void)
1389 fixup_graph_type fixup_graph
;
1390 memset (&fixup_graph
, 0, sizeof (fixup_graph
));
1391 create_fixup_graph (&fixup_graph
);
1392 find_minimum_cost_flow (&fixup_graph
);
1393 adjust_cfg_counts (&fixup_graph
);
1394 delete_fixup_graph (&fixup_graph
);