1 /* Routines to implement minimum-cost maximal flow algorithm used to smooth
2 basic block and edge frequency counts.
4 Free Software Foundation, Inc.
5 Contributed by Paul Yuan (yingbo.com@gmail.com) and
6 Vinodha Ramasamy (vinodha@google.com).
8 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
24 [1] "Feedback-directed Optimizations in GCC with Estimated Edge Profiles
25 from Hardware Event Sampling", Vinodha Ramasamy, Paul Yuan, Dehao Chen,
26 and Robert Hundt; GCC Summit 2008.
27 [2] "Complementing Missing and Inaccurate Profiling Using a Minimum Cost
28 Circulation Algorithm", Roy Levin, Ilan Newman and Gadi Haber;
31 Algorithm to smooth basic block and edge counts:
32 1. create_fixup_graph: Create fixup graph by translating function CFG into
33 a graph that satisfies MCF algorithm requirements.
34 2. find_max_flow: Find maximal flow.
35 3. compute_residual_flow: Form residual network.
37 cancel_negative_cycle: While G contains a negative cost cycle C, reverse
38 the flow on the found cycle by the minimum residual capacity in that
40 5. Form the minimal cost flow
42 6. adjust_cfg_counts: Update initial edge weights with corrected weights.
43 delta(u.v) = f(u,v) -f(v,u).
44 w*(u,v) = w(u,v) + delta(u,v). */
48 #include "coretypes.h"
50 #include "basic-block.h"
52 #include "langhooks.h"
58 /* CAP_INFINITY: Constant to represent infinite capacity. */
59 #define CAP_INFINITY INTTYPE_MAXIMUM (HOST_WIDEST_INT)
62 #define K_POS(b) ((b))
63 #define K_NEG(b) (50 * (b))
64 #define COST(k, w) ((k) / mcf_ln ((w) + 2))
65 /* Limit the number of iterations for cancel_negative_cycles() to ensure
66 reasonable compile time. */
67 #define MAX_ITER(n, e) 10 + (1000000 / ((n) * (e)))
71 VERTEX_SPLIT_EDGE
, /* Edge to represent vertex with w(e) = w(v). */
72 REDIRECT_EDGE
, /* Edge after vertex transformation. */
74 SOURCE_CONNECT_EDGE
, /* Single edge connecting to single source. */
75 SINK_CONNECT_EDGE
, /* Single edge connecting to single sink. */
76 BALANCE_EDGE
, /* Edge connecting with source/sink: cp(e) = 0. */
77 REDIRECT_NORMALIZED_EDGE
, /* Normalized edge for a redirect edge. */
78 REVERSE_NORMALIZED_EDGE
/* Normalized edge for a reverse edge. */
81 /* Structure to represent an edge in the fixup graph. */
82 typedef struct fixup_edge_d
86 /* Flag denoting type of edge and attributes for the flow field. */
89 /* Index to the normalization vertex added for this edge. */
90 int norm_vertex_index
;
91 /* Flow for this edge. */
93 /* Residual flow for this edge - used during negative cycle canceling. */
97 gcov_type max_capacity
;
100 typedef fixup_edge_type
*fixup_edge_p
;
102 DEF_VEC_P (fixup_edge_p
);
103 DEF_VEC_ALLOC_P (fixup_edge_p
, heap
);
105 /* Structure to represent a vertex in the fixup graph. */
106 typedef struct fixup_vertex_d
108 VEC (fixup_edge_p
, heap
) *succ_edges
;
111 typedef fixup_vertex_type
*fixup_vertex_p
;
113 /* Fixup graph used in the MCF algorithm. */
114 typedef struct fixup_graph_d
116 /* Current number of vertices for the graph. */
118 /* Current number of edges for the graph. */
120 /* Index of new entry vertex. */
122 /* Index of new exit vertex. */
124 /* Fixup vertex list. Adjacency list for fixup graph. */
125 fixup_vertex_p vertex_list
;
126 /* Fixup edge list. */
127 fixup_edge_p edge_list
;
130 typedef struct queue_d
138 /* Structure used in the maximal flow routines to find augmenting path. */
139 typedef struct augmenting_path_d
141 /* Queue used to hold vertex indices. */
142 queue_type queue_list
;
143 /* Vector to hold chain of pred vertex indices in augmenting path. */
145 /* Vector that indicates if basic block i has been visited. */
147 } augmenting_path_type
;
150 /* Function definitions. */
152 /* Dump routines to aid debugging. */
154 /* Print basic block with index N for FIXUP_GRAPH in n' and n'' format. */
157 print_basic_block (FILE *file
, fixup_graph_type
*fixup_graph
, int n
)
159 if (n
== ENTRY_BLOCK
)
160 fputs ("ENTRY", file
);
161 else if (n
== ENTRY_BLOCK
+ 1)
162 fputs ("ENTRY''", file
);
163 else if (n
== 2 * EXIT_BLOCK
)
164 fputs ("EXIT", file
);
165 else if (n
== 2 * EXIT_BLOCK
+ 1)
166 fputs ("EXIT''", file
);
167 else if (n
== fixup_graph
->new_exit_index
)
168 fputs ("NEW_EXIT", file
);
169 else if (n
== fixup_graph
->new_entry_index
)
170 fputs ("NEW_ENTRY", file
);
173 fprintf (file
, "%d", n
/ 2);
182 /* Print edge S->D for given fixup_graph with n' and n'' format.
184 S is the index of the source vertex of the edge (input) and
185 D is the index of the destination vertex of the edge (input) for the given
186 fixup_graph (input). */
189 print_edge (FILE *file
, fixup_graph_type
*fixup_graph
, int s
, int d
)
191 print_basic_block (file
, fixup_graph
, s
);
193 print_basic_block (file
, fixup_graph
, d
);
197 /* Dump out the attributes of a given edge FEDGE in the fixup_graph to a
200 dump_fixup_edge (FILE *file
, fixup_graph_type
*fixup_graph
, fixup_edge_p fedge
)
204 fputs ("NULL fixup graph edge.\n", file
);
208 print_edge (file
, fixup_graph
, fedge
->src
, fedge
->dest
);
213 fprintf (file
, "flow/capacity=" HOST_WIDEST_INT_PRINT_DEC
"/",
215 if (fedge
->max_capacity
== CAP_INFINITY
)
216 fputs ("+oo,", file
);
218 fprintf (file
, "" HOST_WIDEST_INT_PRINT_DEC
",", fedge
->max_capacity
);
221 if (fedge
->is_rflow_valid
)
223 if (fedge
->rflow
== CAP_INFINITY
)
224 fputs (" rflow=+oo.", file
);
226 fprintf (file
, " rflow=" HOST_WIDEST_INT_PRINT_DEC
",", fedge
->rflow
);
229 fprintf (file
, " cost=" HOST_WIDEST_INT_PRINT_DEC
".", fedge
->cost
);
231 fprintf (file
, "\t(%d->%d)", fedge
->src
, fedge
->dest
);
237 case VERTEX_SPLIT_EDGE
:
238 fputs (" @VERTEX_SPLIT_EDGE", file
);
242 fputs (" @REDIRECT_EDGE", file
);
245 case SOURCE_CONNECT_EDGE
:
246 fputs (" @SOURCE_CONNECT_EDGE", file
);
249 case SINK_CONNECT_EDGE
:
250 fputs (" @SINK_CONNECT_EDGE", file
);
254 fputs (" @REVERSE_EDGE", file
);
258 fputs (" @BALANCE_EDGE", file
);
261 case REDIRECT_NORMALIZED_EDGE
:
262 case REVERSE_NORMALIZED_EDGE
:
263 fputs (" @NORMALIZED_EDGE", file
);
267 fputs (" @INVALID_EDGE", file
);
275 /* Print out the edges and vertices of the given FIXUP_GRAPH, into the dump
276 file. The input string MSG is printed out as a heading. */
279 dump_fixup_graph (FILE *file
, fixup_graph_type
*fixup_graph
, const char *msg
)
282 int fnum_vertices
, fnum_edges
;
284 fixup_vertex_p fvertex_list
, pfvertex
;
287 gcc_assert (fixup_graph
);
288 fvertex_list
= fixup_graph
->vertex_list
;
289 fnum_vertices
= fixup_graph
->num_vertices
;
290 fnum_edges
= fixup_graph
->num_edges
;
292 fprintf (file
, "\nDump fixup graph for %s(): %s.\n",
293 lang_hooks
.decl_printable_name (current_function_decl
, 2), msg
);
295 "There are %d vertices and %d edges. new_exit_index is %d.\n\n",
296 fnum_vertices
, fnum_edges
, fixup_graph
->new_exit_index
);
298 for (i
= 0; i
< fnum_vertices
; i
++)
300 pfvertex
= fvertex_list
+ i
;
301 fprintf (file
, "vertex_list[%d]: %d succ fixup edges.\n",
302 i
, VEC_length (fixup_edge_p
, pfvertex
->succ_edges
));
304 for (j
= 0; VEC_iterate (fixup_edge_p
, pfvertex
->succ_edges
, j
, pfedge
);
307 /* Distinguish forward edges and backward edges in the residual flow
310 fputs ("(f) ", file
);
311 else if (pfedge
->is_rflow_valid
)
312 fputs ("(b) ", file
);
313 dump_fixup_edge (file
, fixup_graph
, pfedge
);
321 /* Utility routines. */
322 /* ln() implementation: approximate calculation. Returns ln of X. */
343 /* sqrt() implementation: based on open source QUAKE3 code (magic sqrt
344 implementation) by John Carmack. Returns sqrt of X. */
349 #define MAGIC_CONST1 0x1fbcf800
350 #define MAGIC_CONST2 0x5f3759df
354 } convertor
, convertor2
;
358 convertor
.floatPart
= x
;
359 convertor2
.floatPart
= x
;
360 convertor
.intPart
= MAGIC_CONST1
+ (convertor
.intPart
>> 1);
361 convertor2
.intPart
= MAGIC_CONST2
- (convertor2
.intPart
>> 1);
363 return 0.5f
* (convertor
.floatPart
+ (x
* convertor2
.floatPart
));
367 /* Common code shared between add_fixup_edge and add_rfixup_edge. Adds an edge
368 (SRC->DEST) to the edge_list maintained in FIXUP_GRAPH with cost of the edge
369 added set to COST. */
372 add_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
, gcov_type cost
)
374 fixup_vertex_p curr_vertex
= fixup_graph
->vertex_list
+ src
;
375 fixup_edge_p curr_edge
= fixup_graph
->edge_list
+ fixup_graph
->num_edges
;
376 curr_edge
->src
= src
;
377 curr_edge
->dest
= dest
;
378 curr_edge
->cost
= cost
;
379 fixup_graph
->num_edges
++;
381 dump_fixup_edge (dump_file
, fixup_graph
, curr_edge
);
382 VEC_safe_push (fixup_edge_p
, heap
, curr_vertex
->succ_edges
, curr_edge
);
387 /* Add a fixup edge (src->dest) with attributes TYPE, WEIGHT, COST and
388 MAX_CAPACITY to the edge_list in the fixup graph. */
391 add_fixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
, int type
,
392 gcov_type weight
, gcov_type cost
, gcov_type max_capacity
)
394 fixup_edge_p curr_edge
= add_edge(fixup_graph
, src
, dest
, cost
);
395 curr_edge
->type
= type
;
396 curr_edge
->weight
= weight
;
397 curr_edge
->max_capacity
= max_capacity
;
401 /* Add a residual edge (SRC->DEST) with attributes RFLOW and COST
402 to the fixup graph. */
405 add_rfixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
,
406 gcov_type rflow
, gcov_type cost
)
408 fixup_edge_p curr_edge
= add_edge (fixup_graph
, src
, dest
, cost
);
409 curr_edge
->rflow
= rflow
;
410 curr_edge
->is_rflow_valid
= true;
411 /* This edge is not a valid edge - merely used to hold residual flow. */
412 curr_edge
->type
= INVALID_EDGE
;
416 /* Return the pointer to fixup edge SRC->DEST or NULL if edge does not
417 exist in the FIXUP_GRAPH. */
420 find_fixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
)
424 fixup_vertex_p pfvertex
;
426 gcc_assert (src
< fixup_graph
->num_vertices
);
428 pfvertex
= fixup_graph
->vertex_list
+ src
;
430 for (j
= 0; VEC_iterate (fixup_edge_p
, pfvertex
->succ_edges
, j
, pfedge
);
432 if (pfedge
->dest
== dest
)
439 /* Cleanup routine to free structures in FIXUP_GRAPH. */
442 delete_fixup_graph (fixup_graph_type
*fixup_graph
)
445 int fnum_vertices
= fixup_graph
->num_vertices
;
446 fixup_vertex_p pfvertex
= fixup_graph
->vertex_list
;
448 for (i
= 0; i
< fnum_vertices
; i
++, pfvertex
++)
449 VEC_free (fixup_edge_p
, heap
, pfvertex
->succ_edges
);
451 free (fixup_graph
->vertex_list
);
452 free (fixup_graph
->edge_list
);
456 /* Creates a fixup graph FIXUP_GRAPH from the function CFG. */
459 create_fixup_graph (fixup_graph_type
*fixup_graph
)
461 double sqrt_avg_vertex_weight
= 0;
462 double total_vertex_weight
= 0;
465 /* Vector to hold D(v) = sum_out_edges(v) - sum_in_edges(v). */
466 gcov_type
*diff_out_in
= NULL
;
467 gcov_type supply_value
= 1, demand_value
= 0;
469 int new_entry_index
= 0, new_exit_index
= 0;
475 fixup_edge_p pfedge
, r_pfedge
;
476 fixup_edge_p fedge_list
;
479 /* Each basic_block will be split into 2 during vertex transformation. */
480 int fnum_vertices_after_transform
= 2 * n_basic_blocks
;
481 int fnum_edges_after_transform
= n_edges
+ n_basic_blocks
;
483 /* Count the new SOURCE and EXIT vertices to be added. */
484 int fmax_num_vertices
=
485 fnum_vertices_after_transform
+ n_edges
+ n_basic_blocks
+ 2;
487 /* In create_fixup_graph: Each basic block and edge can be split into 3
488 edges. Number of balance edges = n_basic_blocks. So after
490 max_edges = 4 * n_basic_blocks + 3 * n_edges
491 Accounting for residual flow edges
492 max_edges = 2 * (4 * n_basic_blocks + 3 * n_edges)
493 = 8 * n_basic_blocks + 6 * n_edges
494 < 8 * n_basic_blocks + 8 * n_edges. */
495 int fmax_num_edges
= 8 * (n_basic_blocks
+ n_edges
);
497 /* Initial num of vertices in the fixup graph. */
498 fixup_graph
->num_vertices
= n_basic_blocks
;
500 /* Fixup graph vertex list. */
501 fixup_graph
->vertex_list
=
502 (fixup_vertex_p
) xcalloc (fmax_num_vertices
, sizeof (fixup_vertex_type
));
504 /* Fixup graph edge list. */
505 fixup_graph
->edge_list
=
506 (fixup_edge_p
) xcalloc (fmax_num_edges
, sizeof (fixup_edge_type
));
509 (gcov_type
*) xcalloc (1 + fnum_vertices_after_transform
,
512 /* Compute constants b, k_pos, k_neg used in the cost function calculation.
513 b = sqrt(avg_vertex_weight(cfg)); k_pos = b; k_neg = 50b. */
514 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
515 total_vertex_weight
+= bb
->count
;
517 sqrt_avg_vertex_weight
= mcf_sqrt (total_vertex_weight
/ n_basic_blocks
);
519 k_pos
= K_POS (sqrt_avg_vertex_weight
);
520 k_neg
= K_NEG (sqrt_avg_vertex_weight
);
522 /* 1. Vertex Transformation: Split each vertex v into two vertices v' and v'',
523 connected by an edge e from v' to v''. w(e) = w(v). */
526 fprintf (dump_file
, "\nVertex transformation:\n");
528 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
530 /* v'->v'': index1->(index1+1). */
532 fcost
= (gcov_type
) COST (k_pos
, bb
->count
);
533 add_fixup_edge (fixup_graph
, i
, i
+ 1, VERTEX_SPLIT_EDGE
, bb
->count
,
534 fcost
, CAP_INFINITY
);
535 fixup_graph
->num_vertices
++;
537 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
539 /* Edges with ignore attribute set should be treated like they don't
541 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
543 j
= 2 * e
->dest
->index
;
544 fcost
= (gcov_type
) COST (k_pos
, e
->count
);
545 add_fixup_edge (fixup_graph
, i
+ 1, j
, REDIRECT_EDGE
, e
->count
, fcost
,
550 /* After vertex transformation. */
551 gcc_assert (fixup_graph
->num_vertices
== fnum_vertices_after_transform
);
552 /* Redirect edges are not added for edges with ignore attribute. */
553 gcc_assert (fixup_graph
->num_edges
<= fnum_edges_after_transform
);
555 fnum_edges_after_transform
= fixup_graph
->num_edges
;
557 /* 2. Initialize D(v). */
558 for (i
= 0; i
< fnum_edges_after_transform
; i
++)
560 pfedge
= fixup_graph
->edge_list
+ i
;
561 diff_out_in
[pfedge
->src
] += pfedge
->weight
;
562 diff_out_in
[pfedge
->dest
] -= pfedge
->weight
;
565 /* Entry block - vertex indices 0, 1; EXIT block - vertex indices 2, 3. */
566 for (i
= 0; i
<= 3; i
++)
569 /* 3. Add reverse edges: needed to decrease counts during smoothing. */
571 fprintf (dump_file
, "\nReverse edges:\n");
572 for (i
= 0; i
< fnum_edges_after_transform
; i
++)
574 pfedge
= fixup_graph
->edge_list
+ i
;
575 if ((pfedge
->src
== 0) || (pfedge
->src
== 2))
577 r_pfedge
= find_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
);
578 if (!r_pfedge
&& pfedge
->weight
)
580 /* Skip adding reverse edges for edges with w(e) = 0, as its maximum
582 fcost
= (gcov_type
) COST (k_neg
, pfedge
->weight
);
583 add_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
,
584 REVERSE_EDGE
, 0, fcost
, pfedge
->weight
);
588 /* 4. Create single source and sink. Connect new source vertex s' to function
589 entry block. Connect sink vertex t' to function exit. */
591 fprintf (dump_file
, "\ns'->S, T->t':\n");
593 new_entry_index
= fixup_graph
->new_entry_index
= fixup_graph
->num_vertices
;
594 fixup_graph
->num_vertices
++;
595 /* Set supply_value to 1 to avoid zero count function ENTRY. */
596 add_fixup_edge (fixup_graph
, new_entry_index
, ENTRY_BLOCK
, SOURCE_CONNECT_EDGE
,
597 1 /* supply_value */, 0, 1 /* supply_value */);
599 /* Create new exit with EXIT_BLOCK as single pred. */
600 new_exit_index
= fixup_graph
->new_exit_index
= fixup_graph
->num_vertices
;
601 fixup_graph
->num_vertices
++;
602 add_fixup_edge (fixup_graph
, 2 * EXIT_BLOCK
+ 1, new_exit_index
,
604 0 /* demand_value */, 0, 0 /* demand_value */);
606 /* Connect vertices with unbalanced D(v) to source/sink. */
608 fprintf (dump_file
, "\nD(v) balance:\n");
609 /* Skip vertices for ENTRY (0, 1) and EXIT (2,3) blocks, so start with i = 4.
610 diff_out_in[v''] will be 0, so skip v'' vertices, hence i += 2. */
611 for (i
= 4; i
< new_entry_index
; i
+= 2)
613 if (diff_out_in
[i
] > 0)
615 add_fixup_edge (fixup_graph
, i
, new_exit_index
, BALANCE_EDGE
, 0, 0,
617 demand_value
+= diff_out_in
[i
];
619 else if (diff_out_in
[i
] < 0)
621 add_fixup_edge (fixup_graph
, new_entry_index
, i
, BALANCE_EDGE
, 0, 0,
623 supply_value
-= diff_out_in
[i
];
627 /* Set supply = demand. */
630 fprintf (dump_file
, "\nAdjust supply and demand:\n");
631 fprintf (dump_file
, "supply_value=" HOST_WIDEST_INT_PRINT_DEC
"\n",
633 fprintf (dump_file
, "demand_value=" HOST_WIDEST_INT_PRINT_DEC
"\n",
637 if (demand_value
> supply_value
)
639 pfedge
= find_fixup_edge (fixup_graph
, new_entry_index
, ENTRY_BLOCK
);
640 pfedge
->max_capacity
+= (demand_value
- supply_value
);
644 pfedge
= find_fixup_edge (fixup_graph
, 2 * EXIT_BLOCK
+ 1, new_exit_index
);
645 pfedge
->max_capacity
+= (supply_value
- demand_value
);
648 /* 6. Normalize edges: remove anti-parallel edges. Anti-parallel edges are
649 created by the vertex transformation step from self-edges in the original
650 CFG and by the reverse edges added earlier. */
652 fprintf (dump_file
, "\nNormalize edges:\n");
654 fnum_edges
= fixup_graph
->num_edges
;
655 fedge_list
= fixup_graph
->edge_list
;
657 for (i
= 0; i
< fnum_edges
; i
++)
659 pfedge
= fedge_list
+ i
;
660 r_pfedge
= find_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
);
661 if (((pfedge
->type
== VERTEX_SPLIT_EDGE
)
662 || (pfedge
->type
== REDIRECT_EDGE
)) && r_pfedge
)
664 new_index
= fixup_graph
->num_vertices
;
665 fixup_graph
->num_vertices
++;
669 fprintf (dump_file
, "\nAnti-parallel edge:\n");
670 dump_fixup_edge (dump_file
, fixup_graph
, pfedge
);
671 dump_fixup_edge (dump_file
, fixup_graph
, r_pfedge
);
672 fprintf (dump_file
, "New vertex is %d.\n", new_index
);
673 fprintf (dump_file
, "------------------\n");
677 pfedge
->norm_vertex_index
= new_index
;
680 fprintf (dump_file
, "After normalization:\n");
681 dump_fixup_edge (dump_file
, fixup_graph
, pfedge
);
684 /* Add a new fixup edge: new_index->src. */
685 add_fixup_edge (fixup_graph
, new_index
, pfedge
->src
,
686 REVERSE_NORMALIZED_EDGE
, 0, r_pfedge
->cost
,
687 r_pfedge
->max_capacity
);
688 gcc_assert (fixup_graph
->num_vertices
<= fmax_num_vertices
);
690 /* Edge: r_pfedge->src -> r_pfedge->dest
691 ==> r_pfedge->src -> new_index. */
692 r_pfedge
->dest
= new_index
;
693 r_pfedge
->type
= REVERSE_NORMALIZED_EDGE
;
694 r_pfedge
->cost
= pfedge
->cost
;
695 r_pfedge
->max_capacity
= pfedge
->max_capacity
;
697 dump_fixup_edge (dump_file
, fixup_graph
, r_pfedge
);
702 dump_fixup_graph (dump_file
, fixup_graph
, "After create_fixup_graph()");
709 /* Allocates space for the structures in AUGMENTING_PATH. The space needed is
710 proportional to the number of nodes in the graph, which is given by
714 init_augmenting_path (augmenting_path_type
*augmenting_path
, int graph_size
)
716 augmenting_path
->queue_list
.queue
= (int *)
717 xcalloc (graph_size
+ 2, sizeof (int));
718 augmenting_path
->queue_list
.size
= graph_size
+ 2;
719 augmenting_path
->bb_pred
= (int *) xcalloc (graph_size
, sizeof (int));
720 augmenting_path
->is_visited
= (int *) xcalloc (graph_size
, sizeof (int));
723 /* Free the structures in AUGMENTING_PATH. */
725 free_augmenting_path (augmenting_path_type
*augmenting_path
)
727 free (augmenting_path
->queue_list
.queue
);
728 free (augmenting_path
->bb_pred
);
729 free (augmenting_path
->is_visited
);
733 /* Queue routines. Assumes queue will never overflow. */
736 init_queue (queue_type
*queue_list
)
738 gcc_assert (queue_list
);
739 queue_list
->head
= 0;
740 queue_list
->tail
= 0;
743 /* Return true if QUEUE_LIST is empty. */
745 is_empty (queue_type
*queue_list
)
747 return (queue_list
->head
== queue_list
->tail
);
750 /* Insert element X into QUEUE_LIST. */
752 enqueue (queue_type
*queue_list
, int x
)
754 gcc_assert (queue_list
->tail
< queue_list
->size
);
755 queue_list
->queue
[queue_list
->tail
] = x
;
756 (queue_list
->tail
)++;
759 /* Return the first element in QUEUE_LIST. */
761 dequeue (queue_type
*queue_list
)
764 gcc_assert (queue_list
->head
>= 0);
765 x
= queue_list
->queue
[queue_list
->head
];
766 (queue_list
->head
)++;
771 /* Finds a negative cycle in the residual network using
772 the Bellman-Ford algorithm. The flow on the found cycle is reversed by the
773 minimum residual capacity of that cycle. ENTRY and EXIT vertices are not
777 FIXUP_GRAPH - Residual graph (input/output)
778 The following are allocated/freed by the caller:
779 PI - Vector to hold predecessors in path (pi = pred index)
780 D - D[I] holds minimum cost of path from i to sink
781 CYCLE - Vector to hold the minimum cost cycle
784 true if a negative cycle was found, false otherwise. */
787 cancel_negative_cycle (fixup_graph_type
*fixup_graph
,
788 int *pi
, gcov_type
*d
, int *cycle
)
791 int fnum_vertices
, fnum_edges
;
792 fixup_edge_p fedge_list
, pfedge
, r_pfedge
;
793 bool found_cycle
= false;
794 int cycle_start
= 0, cycle_end
= 0;
795 gcov_type sum_cost
= 0, cycle_flow
= 0;
797 bool propagated
= false;
799 gcc_assert (fixup_graph
);
800 fnum_vertices
= fixup_graph
->num_vertices
;
801 fnum_edges
= fixup_graph
->num_edges
;
802 fedge_list
= fixup_graph
->edge_list
;
803 new_entry_index
= fixup_graph
->new_entry_index
;
807 for (i
= 1; i
< fnum_vertices
; i
++)
816 for (k
= 1; k
< fnum_vertices
; k
++)
819 for (i
= 0; i
< fnum_edges
; i
++)
821 pfedge
= fedge_list
+ i
;
822 if (pfedge
->src
== new_entry_index
)
824 if (pfedge
->is_rflow_valid
&& pfedge
->rflow
825 && d
[pfedge
->src
] != CAP_INFINITY
826 && (d
[pfedge
->dest
] > d
[pfedge
->src
] + pfedge
->cost
))
828 d
[pfedge
->dest
] = d
[pfedge
->src
] + pfedge
->cost
;
829 pi
[pfedge
->dest
] = pfedge
->src
;
838 /* No negative cycles exist. */
842 for (i
= 0; i
< fnum_edges
; i
++)
844 pfedge
= fedge_list
+ i
;
845 if (pfedge
->src
== new_entry_index
)
847 if (pfedge
->is_rflow_valid
&& pfedge
->rflow
848 && d
[pfedge
->src
] != CAP_INFINITY
849 && (d
[pfedge
->dest
] > d
[pfedge
->src
] + pfedge
->cost
))
859 /* Augment the cycle with the cycle's minimum residual capacity. */
861 cycle
[0] = pfedge
->dest
;
864 for (i
= 1; i
< fnum_vertices
; i
++)
868 for (k
= 0; k
< i
; k
++)
872 /* cycle[k] -> ... -> cycle[i]. */
883 gcc_assert (cycle
[cycle_start
] == cycle
[cycle_end
]);
885 fprintf (dump_file
, "\nNegative cycle length is %d:\n",
886 cycle_end
- cycle_start
);
889 cycle_flow
= CAP_INFINITY
;
890 for (k
= cycle_start
; k
< cycle_end
; k
++)
892 pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
+ 1], cycle
[k
]);
893 cycle_flow
= MIN (cycle_flow
, pfedge
->rflow
);
894 sum_cost
+= pfedge
->cost
;
896 fprintf (dump_file
, "%d ", cycle
[k
]);
901 fprintf (dump_file
, "%d", cycle
[k
]);
903 ": (" HOST_WIDEST_INT_PRINT_DEC
", " HOST_WIDEST_INT_PRINT_DEC
904 ")\n", sum_cost
, cycle_flow
);
906 "Augment cycle with " HOST_WIDEST_INT_PRINT_DEC
"\n",
910 for (k
= cycle_start
; k
< cycle_end
; k
++)
912 pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
+ 1], cycle
[k
]);
913 r_pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
], cycle
[k
+ 1]);
914 pfedge
->rflow
-= cycle_flow
;
916 pfedge
->flow
+= cycle_flow
;
917 r_pfedge
->rflow
+= cycle_flow
;
919 r_pfedge
->flow
-= cycle_flow
;
926 /* Computes the residual flow for FIXUP_GRAPH by setting the rflow field of
927 the edges. ENTRY and EXIT vertices should not be considered. */
930 compute_residual_flow (fixup_graph_type
*fixup_graph
)
934 fixup_edge_p fedge_list
, pfedge
;
936 gcc_assert (fixup_graph
);
939 fputs ("\ncompute_residual_flow():\n", dump_file
);
941 fnum_edges
= fixup_graph
->num_edges
;
942 fedge_list
= fixup_graph
->edge_list
;
944 for (i
= 0; i
< fnum_edges
; i
++)
946 pfedge
= fedge_list
+ i
;
947 pfedge
->rflow
= pfedge
->max_capacity
- pfedge
->flow
;
948 pfedge
->is_rflow_valid
= true;
949 add_rfixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
, pfedge
->flow
,
955 /* Uses Edmonds-Karp algorithm - BFS to find augmenting path from SOURCE to
956 SINK. The fields in the edge vector in the FIXUP_GRAPH are not modified by
957 this routine. The vector bb_pred in the AUGMENTING_PATH structure is updated
958 to reflect the path found.
959 Returns: 0 if no augmenting path is found, 1 otherwise. */
962 find_augmenting_path (fixup_graph_type
*fixup_graph
,
963 augmenting_path_type
*augmenting_path
, int source
,
968 fixup_vertex_p fvertex_list
, pfvertex
;
970 int *bb_pred
, *is_visited
;
971 queue_type
*queue_list
;
973 gcc_assert (augmenting_path
);
974 bb_pred
= augmenting_path
->bb_pred
;
975 gcc_assert (bb_pred
);
976 is_visited
= augmenting_path
->is_visited
;
977 gcc_assert (is_visited
);
978 queue_list
= &(augmenting_path
->queue_list
);
980 gcc_assert (fixup_graph
);
982 fvertex_list
= fixup_graph
->vertex_list
;
984 for (u
= 0; u
< fixup_graph
->num_vertices
; u
++)
987 init_queue (queue_list
);
988 enqueue (queue_list
, source
);
989 bb_pred
[source
] = -1;
991 while (!is_empty (queue_list
))
993 u
= dequeue (queue_list
);
995 pfvertex
= fvertex_list
+ u
;
996 for (i
= 0; VEC_iterate (fixup_edge_p
, pfvertex
->succ_edges
, i
, pfedge
);
999 int dest
= pfedge
->dest
;
1000 if ((pfedge
->rflow
> 0) && (is_visited
[dest
] == 0))
1002 enqueue (queue_list
, dest
);
1004 is_visited
[dest
] = 1;
1015 /* Routine to find the maximal flow:
1017 1. Initialize flow to 0
1018 2. Find an augmenting path form source to sink.
1019 3. Send flow equal to the path's residual capacity along the edges of this path.
1020 4. Repeat steps 2 and 3 until no new augmenting path is found.
1023 SOURCE: index of source vertex (input)
1024 SINK: index of sink vertex (input)
1025 FIXUP_GRAPH: adjacency matrix representing the graph. The flow of the edges will be
1026 set to have a valid maximal flow by this routine. (input)
1027 Return: Maximum flow possible. */
1030 find_max_flow (fixup_graph_type
*fixup_graph
, int source
, int sink
)
1033 augmenting_path_type augmenting_path
;
1035 gcov_type max_flow
= 0;
1037 fixup_edge_p fedge_list
, pfedge
, r_pfedge
;
1039 gcc_assert (fixup_graph
);
1041 fnum_edges
= fixup_graph
->num_edges
;
1042 fedge_list
= fixup_graph
->edge_list
;
1044 /* Initialize flow to 0. */
1045 for (i
= 0; i
< fnum_edges
; i
++)
1047 pfedge
= fedge_list
+ i
;
1051 compute_residual_flow (fixup_graph
);
1053 init_augmenting_path (&augmenting_path
, fixup_graph
->num_vertices
);
1055 bb_pred
= augmenting_path
.bb_pred
;
1056 while (find_augmenting_path (fixup_graph
, &augmenting_path
, source
, sink
))
1058 /* Determine the amount by which we can increment the flow. */
1059 gcov_type increment
= CAP_INFINITY
;
1060 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1062 pfedge
= find_fixup_edge (fixup_graph
, bb_pred
[u
], u
);
1063 increment
= MIN (increment
, pfedge
->rflow
);
1065 max_flow
+= increment
;
1067 /* Now increment the flow. EXIT vertex index is 1. */
1068 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1070 pfedge
= find_fixup_edge (fixup_graph
, bb_pred
[u
], u
);
1071 r_pfedge
= find_fixup_edge (fixup_graph
, u
, bb_pred
[u
]);
1075 pfedge
->flow
+= increment
;
1076 pfedge
->rflow
-= increment
;
1077 r_pfedge
->rflow
+= increment
;
1081 /* backward edge. */
1082 gcc_assert (r_pfedge
->type
);
1083 r_pfedge
->rflow
+= increment
;
1084 r_pfedge
->flow
-= increment
;
1085 pfedge
->rflow
-= increment
;
1091 fprintf (dump_file
, "\nDump augmenting path:\n");
1092 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1094 print_basic_block (dump_file
, fixup_graph
, u
);
1095 fprintf (dump_file
, "<-");
1098 "ENTRY (path_capacity=" HOST_WIDEST_INT_PRINT_DEC
")\n",
1101 "Network flow is " HOST_WIDEST_INT_PRINT_DEC
".\n",
1106 free_augmenting_path (&augmenting_path
);
1108 dump_fixup_graph (dump_file
, fixup_graph
, "After find_max_flow()");
1113 /* Computes the corrected edge and basic block weights using FIXUP_GRAPH
1114 after applying the find_minimum_cost_flow() routine. */
1117 adjust_cfg_counts (fixup_graph_type
*fixup_graph
)
1123 fixup_edge_p pfedge
, pfedge_n
;
1125 gcc_assert (fixup_graph
);
1128 fprintf (dump_file
, "\nadjust_cfg_counts():\n");
1130 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, EXIT_BLOCK_PTR
, next_bb
)
1137 "BB%d: " HOST_WIDEST_INT_PRINT_DEC
"", bb
->index
, bb
->count
);
1139 pfedge
= find_fixup_edge (fixup_graph
, i
, i
+ 1);
1142 bb
->count
+= pfedge
->flow
;
1145 fprintf (dump_file
, " + " HOST_WIDEST_INT_PRINT_DEC
"(",
1147 print_edge (dump_file
, fixup_graph
, i
, i
+ 1);
1148 fprintf (dump_file
, ")");
1153 find_fixup_edge (fixup_graph
, i
+ 1, pfedge
->norm_vertex_index
);
1154 /* Deduct flow from normalized reverse edge. */
1155 if (pfedge
->norm_vertex_index
&& pfedge_n
->flow
)
1157 bb
->count
-= pfedge_n
->flow
;
1160 fprintf (dump_file
, " - " HOST_WIDEST_INT_PRINT_DEC
"(",
1162 print_edge (dump_file
, fixup_graph
, i
+ 1,
1163 pfedge
->norm_vertex_index
);
1164 fprintf (dump_file
, ")");
1168 fprintf (dump_file
, " = " HOST_WIDEST_INT_PRINT_DEC
"\n", bb
->count
);
1171 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1173 /* Treat edges with ignore attribute set as if they don't exist. */
1174 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
1177 j
= 2 * e
->dest
->index
;
1179 fprintf (dump_file
, "%d->%d: " HOST_WIDEST_INT_PRINT_DEC
"",
1180 bb
->index
, e
->dest
->index
, e
->count
);
1182 pfedge
= find_fixup_edge (fixup_graph
, i
+ 1, j
);
1184 if (bb
->index
!= e
->dest
->index
)
1186 /* Non-self edge. */
1189 e
->count
+= pfedge
->flow
;
1192 fprintf (dump_file
, " + " HOST_WIDEST_INT_PRINT_DEC
"(",
1194 print_edge (dump_file
, fixup_graph
, i
+ 1, j
);
1195 fprintf (dump_file
, ")");
1200 find_fixup_edge (fixup_graph
, j
, pfedge
->norm_vertex_index
);
1201 /* Deduct flow from normalized reverse edge. */
1202 if (pfedge
->norm_vertex_index
&& pfedge_n
->flow
)
1204 e
->count
-= pfedge_n
->flow
;
1207 fprintf (dump_file
, " - " HOST_WIDEST_INT_PRINT_DEC
"(",
1209 print_edge (dump_file
, fixup_graph
, j
,
1210 pfedge
->norm_vertex_index
);
1211 fprintf (dump_file
, ")");
1217 /* Handle self edges. Self edge is split with a normalization
1218 vertex. Here i=j. */
1219 pfedge
= find_fixup_edge (fixup_graph
, j
, i
+ 1);
1221 find_fixup_edge (fixup_graph
, i
+ 1, pfedge
->norm_vertex_index
);
1222 e
->count
+= pfedge_n
->flow
;
1223 bb
->count
+= pfedge_n
->flow
;
1226 fprintf (dump_file
, "(self edge)");
1227 fprintf (dump_file
, " + " HOST_WIDEST_INT_PRINT_DEC
"(",
1229 print_edge (dump_file
, fixup_graph
, i
+ 1,
1230 pfedge
->norm_vertex_index
);
1231 fprintf (dump_file
, ")");
1236 e
->probability
= REG_BR_PROB_BASE
* e
->count
/ bb
->count
;
1238 fprintf (dump_file
, " = " HOST_WIDEST_INT_PRINT_DEC
"\t(%.1f%%)\n",
1239 e
->count
, e
->probability
* 100.0 / REG_BR_PROB_BASE
);
1243 ENTRY_BLOCK_PTR
->count
= sum_edge_counts (ENTRY_BLOCK_PTR
->succs
);
1244 EXIT_BLOCK_PTR
->count
= sum_edge_counts (EXIT_BLOCK_PTR
->preds
);
1246 /* Compute edge probabilities. */
1251 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1252 e
->probability
= REG_BR_PROB_BASE
* e
->count
/ bb
->count
;
1257 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1258 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
1262 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1264 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
1265 e
->probability
= REG_BR_PROB_BASE
/ total
;
1272 total
+= EDGE_COUNT (bb
->succs
);
1273 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1274 e
->probability
= REG_BR_PROB_BASE
/ total
;
1281 fprintf (dump_file
, "\nCheck %s() CFG flow conservation:\n",
1282 lang_hooks
.decl_printable_name (current_function_decl
, 2));
1283 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
->next_bb
, EXIT_BLOCK_PTR
, next_bb
)
1285 if ((bb
->count
!= sum_edge_counts (bb
->preds
))
1286 || (bb
->count
!= sum_edge_counts (bb
->succs
)))
1289 "BB%d(" HOST_WIDEST_INT_PRINT_DEC
") **INVALID**: ",
1290 bb
->index
, bb
->count
);
1292 "******** BB%d(" HOST_WIDEST_INT_PRINT_DEC
1293 ") **INVALID**: \n", bb
->index
, bb
->count
);
1294 fprintf (dump_file
, "in_edges=" HOST_WIDEST_INT_PRINT_DEC
" ",
1295 sum_edge_counts (bb
->preds
));
1296 fprintf (dump_file
, "out_edges=" HOST_WIDEST_INT_PRINT_DEC
"\n",
1297 sum_edge_counts (bb
->succs
));
1304 /* Implements the negative cycle canceling algorithm to compute a minimum cost
1307 1. Find maximal flow.
1308 2. Form residual network
1310 While G contains a negative cost cycle C, reverse the flow on the found cycle
1311 by the minimum residual capacity in that cycle.
1312 4. Form the minimal cost flow
1315 FIXUP_GRAPH - Initial fixup graph.
1316 The flow field is modified to represent the minimum cost flow. */
1319 find_minimum_cost_flow (fixup_graph_type
*fixup_graph
)
1321 /* Holds the index of predecessor in path. */
1323 /* Used to hold the minimum cost cycle. */
1325 /* Used to record the number of iterations of cancel_negative_cycle. */
1327 /* Vector d[i] holds the minimum cost of path from i to sink. */
1331 int new_entry_index
;
1333 gcc_assert (fixup_graph
);
1334 fnum_vertices
= fixup_graph
->num_vertices
;
1335 new_exit_index
= fixup_graph
->new_exit_index
;
1336 new_entry_index
= fixup_graph
->new_entry_index
;
1338 find_max_flow (fixup_graph
, new_entry_index
, new_exit_index
);
1340 /* Initialize the structures for find_negative_cycle(). */
1341 pred
= (int *) xcalloc (fnum_vertices
, sizeof (int));
1342 d
= (gcov_type
*) xcalloc (fnum_vertices
, sizeof (gcov_type
));
1343 cycle
= (int *) xcalloc (fnum_vertices
, sizeof (int));
1345 /* Repeatedly find and cancel negative cost cycles, until
1346 no more negative cycles exist. This also updates the flow field
1347 to represent the minimum cost flow so far. */
1349 while (cancel_negative_cycle (fixup_graph
, pred
, d
, cycle
))
1352 if (iteration
> MAX_ITER (fixup_graph
->num_vertices
,
1353 fixup_graph
->num_edges
))
1358 dump_fixup_graph (dump_file
, fixup_graph
,
1359 "After find_minimum_cost_flow()");
1361 /* Cleanup structures. */
1368 /* Compute the sum of the edge counts in TO_EDGES. */
1371 sum_edge_counts (VEC (edge
, gc
) *to_edges
)
1377 FOR_EACH_EDGE (e
, ei
, to_edges
)
1379 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
1387 /* Main routine. Smoothes the intial assigned basic block and edge counts using
1388 a minimum cost flow algorithm, to ensure that the flow consistency rule is
1389 obeyed: sum of outgoing edges = sum of incoming edges for each basic
1393 mcf_smooth_cfg (void)
1395 fixup_graph_type fixup_graph
;
1396 memset (&fixup_graph
, 0, sizeof (fixup_graph
));
1397 create_fixup_graph (&fixup_graph
);
1398 find_minimum_cost_flow (&fixup_graph
);
1399 adjust_cfg_counts (&fixup_graph
);
1400 delete_fixup_graph (&fixup_graph
);