1 /* Routines to implement minimum-cost maximal flow algorithm used to smooth
2 basic block and edge frequency counts.
3 Copyright (C) 2008-2014 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_for_fn (cfun
);
475 int fnum_edges_after_transform
=
476 n_edges_for_fn (cfun
) + n_basic_blocks_for_fn (cfun
);
478 /* Count the new SOURCE and EXIT vertices to be added. */
479 int fmax_num_vertices
=
480 (fnum_vertices_after_transform
+ n_edges_for_fn (cfun
)
481 + n_basic_blocks_for_fn (cfun
) + 2);
483 /* In create_fixup_graph: Each basic block and edge can be split into 3
484 edges. Number of balance edges = n_basic_blocks. So after
486 max_edges = 4 * n_basic_blocks + 3 * n_edges
487 Accounting for residual flow edges
488 max_edges = 2 * (4 * n_basic_blocks + 3 * n_edges)
489 = 8 * n_basic_blocks + 6 * n_edges
490 < 8 * n_basic_blocks + 8 * n_edges. */
491 int fmax_num_edges
= 8 * (n_basic_blocks_for_fn (cfun
) +
492 n_edges_for_fn (cfun
));
494 /* Initial num of vertices in the fixup graph. */
495 fixup_graph
->num_vertices
= n_basic_blocks_for_fn (cfun
);
497 /* Fixup graph vertex list. */
498 fixup_graph
->vertex_list
=
499 (fixup_vertex_p
) xcalloc (fmax_num_vertices
, sizeof (fixup_vertex_type
));
501 /* Fixup graph edge list. */
502 fixup_graph
->edge_list
=
503 (fixup_edge_p
) xcalloc (fmax_num_edges
, sizeof (fixup_edge_type
));
506 (gcov_type
*) xcalloc (1 + fnum_vertices_after_transform
,
509 /* Compute constants b, k_pos, k_neg used in the cost function calculation.
510 b = sqrt(avg_vertex_weight(cfg)); k_pos = b; k_neg = 50b. */
511 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR_FOR_FN (cfun
), NULL
, next_bb
)
512 total_vertex_weight
+= bb
->count
;
514 sqrt_avg_vertex_weight
= mcf_sqrt (total_vertex_weight
/
515 n_basic_blocks_for_fn (cfun
));
517 k_pos
= K_POS (sqrt_avg_vertex_weight
);
518 k_neg
= K_NEG (sqrt_avg_vertex_weight
);
520 /* 1. Vertex Transformation: Split each vertex v into two vertices v' and v'',
521 connected by an edge e from v' to v''. w(e) = w(v). */
524 fprintf (dump_file
, "\nVertex transformation:\n");
526 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR_FOR_FN (cfun
), NULL
, next_bb
)
528 /* v'->v'': index1->(index1+1). */
530 fcost
= (gcov_type
) COST (k_pos
, bb
->count
);
531 add_fixup_edge (fixup_graph
, i
, i
+ 1, VERTEX_SPLIT_EDGE
, bb
->count
,
532 fcost
, CAP_INFINITY
);
533 fixup_graph
->num_vertices
++;
535 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
537 /* Edges with ignore attribute set should be treated like they don't
539 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
541 j
= 2 * e
->dest
->index
;
542 fcost
= (gcov_type
) COST (k_pos
, e
->count
);
543 add_fixup_edge (fixup_graph
, i
+ 1, j
, REDIRECT_EDGE
, e
->count
, fcost
,
548 /* After vertex transformation. */
549 gcc_assert (fixup_graph
->num_vertices
== fnum_vertices_after_transform
);
550 /* Redirect edges are not added for edges with ignore attribute. */
551 gcc_assert (fixup_graph
->num_edges
<= fnum_edges_after_transform
);
553 fnum_edges_after_transform
= fixup_graph
->num_edges
;
555 /* 2. Initialize D(v). */
556 for (i
= 0; i
< fnum_edges_after_transform
; i
++)
558 pfedge
= fixup_graph
->edge_list
+ i
;
559 diff_out_in
[pfedge
->src
] += pfedge
->weight
;
560 diff_out_in
[pfedge
->dest
] -= pfedge
->weight
;
563 /* Entry block - vertex indices 0, 1; EXIT block - vertex indices 2, 3. */
564 for (i
= 0; i
<= 3; i
++)
567 /* 3. Add reverse edges: needed to decrease counts during smoothing. */
569 fprintf (dump_file
, "\nReverse edges:\n");
570 for (i
= 0; i
< fnum_edges_after_transform
; i
++)
572 pfedge
= fixup_graph
->edge_list
+ i
;
573 if ((pfedge
->src
== 0) || (pfedge
->src
== 2))
575 r_pfedge
= find_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
);
576 if (!r_pfedge
&& pfedge
->weight
)
578 /* Skip adding reverse edges for edges with w(e) = 0, as its maximum
580 fcost
= (gcov_type
) COST (k_neg
, pfedge
->weight
);
581 add_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
,
582 REVERSE_EDGE
, 0, fcost
, pfedge
->weight
);
586 /* 4. Create single source and sink. Connect new source vertex s' to function
587 entry block. Connect sink vertex t' to function exit. */
589 fprintf (dump_file
, "\ns'->S, T->t':\n");
591 new_entry_index
= fixup_graph
->new_entry_index
= fixup_graph
->num_vertices
;
592 fixup_graph
->num_vertices
++;
593 /* Set supply_value to 1 to avoid zero count function ENTRY. */
594 add_fixup_edge (fixup_graph
, new_entry_index
, ENTRY_BLOCK
, SOURCE_CONNECT_EDGE
,
595 1 /* supply_value */, 0, 1 /* supply_value */);
597 /* Create new exit with EXIT_BLOCK as single pred. */
598 new_exit_index
= fixup_graph
->new_exit_index
= fixup_graph
->num_vertices
;
599 fixup_graph
->num_vertices
++;
600 add_fixup_edge (fixup_graph
, 2 * EXIT_BLOCK
+ 1, new_exit_index
,
602 0 /* demand_value */, 0, 0 /* demand_value */);
604 /* Connect vertices with unbalanced D(v) to source/sink. */
606 fprintf (dump_file
, "\nD(v) balance:\n");
607 /* Skip vertices for ENTRY (0, 1) and EXIT (2,3) blocks, so start with i = 4.
608 diff_out_in[v''] will be 0, so skip v'' vertices, hence i += 2. */
609 for (i
= 4; i
< new_entry_index
; i
+= 2)
611 if (diff_out_in
[i
] > 0)
613 add_fixup_edge (fixup_graph
, i
, new_exit_index
, BALANCE_EDGE
, 0, 0,
615 demand_value
+= diff_out_in
[i
];
617 else if (diff_out_in
[i
] < 0)
619 add_fixup_edge (fixup_graph
, new_entry_index
, i
, BALANCE_EDGE
, 0, 0,
621 supply_value
-= diff_out_in
[i
];
625 /* Set supply = demand. */
628 fprintf (dump_file
, "\nAdjust supply and demand:\n");
629 fprintf (dump_file
, "supply_value=" HOST_WIDEST_INT_PRINT_DEC
"\n",
631 fprintf (dump_file
, "demand_value=" HOST_WIDEST_INT_PRINT_DEC
"\n",
635 if (demand_value
> supply_value
)
637 pfedge
= find_fixup_edge (fixup_graph
, new_entry_index
, ENTRY_BLOCK
);
638 pfedge
->max_capacity
+= (demand_value
- supply_value
);
642 pfedge
= find_fixup_edge (fixup_graph
, 2 * EXIT_BLOCK
+ 1, new_exit_index
);
643 pfedge
->max_capacity
+= (supply_value
- demand_value
);
646 /* 6. Normalize edges: remove anti-parallel edges. Anti-parallel edges are
647 created by the vertex transformation step from self-edges in the original
648 CFG and by the reverse edges added earlier. */
650 fprintf (dump_file
, "\nNormalize edges:\n");
652 fnum_edges
= fixup_graph
->num_edges
;
653 fedge_list
= fixup_graph
->edge_list
;
655 for (i
= 0; i
< fnum_edges
; i
++)
657 pfedge
= fedge_list
+ i
;
658 r_pfedge
= find_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
);
659 if (((pfedge
->type
== VERTEX_SPLIT_EDGE
)
660 || (pfedge
->type
== REDIRECT_EDGE
)) && r_pfedge
)
662 new_index
= fixup_graph
->num_vertices
;
663 fixup_graph
->num_vertices
++;
667 fprintf (dump_file
, "\nAnti-parallel edge:\n");
668 dump_fixup_edge (dump_file
, fixup_graph
, pfedge
);
669 dump_fixup_edge (dump_file
, fixup_graph
, r_pfedge
);
670 fprintf (dump_file
, "New vertex is %d.\n", new_index
);
671 fprintf (dump_file
, "------------------\n");
675 pfedge
->norm_vertex_index
= new_index
;
678 fprintf (dump_file
, "After normalization:\n");
679 dump_fixup_edge (dump_file
, fixup_graph
, pfedge
);
682 /* Add a new fixup edge: new_index->src. */
683 add_fixup_edge (fixup_graph
, new_index
, pfedge
->src
,
684 REVERSE_NORMALIZED_EDGE
, 0, r_pfedge
->cost
,
685 r_pfedge
->max_capacity
);
686 gcc_assert (fixup_graph
->num_vertices
<= fmax_num_vertices
);
688 /* Edge: r_pfedge->src -> r_pfedge->dest
689 ==> r_pfedge->src -> new_index. */
690 r_pfedge
->dest
= new_index
;
691 r_pfedge
->type
= REVERSE_NORMALIZED_EDGE
;
692 r_pfedge
->cost
= pfedge
->cost
;
693 r_pfedge
->max_capacity
= pfedge
->max_capacity
;
695 dump_fixup_edge (dump_file
, fixup_graph
, r_pfedge
);
700 dump_fixup_graph (dump_file
, fixup_graph
, "After create_fixup_graph()");
707 /* Allocates space for the structures in AUGMENTING_PATH. The space needed is
708 proportional to the number of nodes in the graph, which is given by
712 init_augmenting_path (augmenting_path_type
*augmenting_path
, int graph_size
)
714 augmenting_path
->queue_list
.queue
= (int *)
715 xcalloc (graph_size
+ 2, sizeof (int));
716 augmenting_path
->queue_list
.size
= graph_size
+ 2;
717 augmenting_path
->bb_pred
= (int *) xcalloc (graph_size
, sizeof (int));
718 augmenting_path
->is_visited
= (int *) xcalloc (graph_size
, sizeof (int));
721 /* Free the structures in AUGMENTING_PATH. */
723 free_augmenting_path (augmenting_path_type
*augmenting_path
)
725 free (augmenting_path
->queue_list
.queue
);
726 free (augmenting_path
->bb_pred
);
727 free (augmenting_path
->is_visited
);
731 /* Queue routines. Assumes queue will never overflow. */
734 init_queue (queue_type
*queue_list
)
736 gcc_assert (queue_list
);
737 queue_list
->head
= 0;
738 queue_list
->tail
= 0;
741 /* Return true if QUEUE_LIST is empty. */
743 is_empty (queue_type
*queue_list
)
745 return (queue_list
->head
== queue_list
->tail
);
748 /* Insert element X into QUEUE_LIST. */
750 enqueue (queue_type
*queue_list
, int x
)
752 gcc_assert (queue_list
->tail
< queue_list
->size
);
753 queue_list
->queue
[queue_list
->tail
] = x
;
754 (queue_list
->tail
)++;
757 /* Return the first element in QUEUE_LIST. */
759 dequeue (queue_type
*queue_list
)
762 gcc_assert (queue_list
->head
>= 0);
763 x
= queue_list
->queue
[queue_list
->head
];
764 (queue_list
->head
)++;
769 /* Finds a negative cycle in the residual network using
770 the Bellman-Ford algorithm. The flow on the found cycle is reversed by the
771 minimum residual capacity of that cycle. ENTRY and EXIT vertices are not
775 FIXUP_GRAPH - Residual graph (input/output)
776 The following are allocated/freed by the caller:
777 PI - Vector to hold predecessors in path (pi = pred index)
778 D - D[I] holds minimum cost of path from i to sink
779 CYCLE - Vector to hold the minimum cost cycle
782 true if a negative cycle was found, false otherwise. */
785 cancel_negative_cycle (fixup_graph_type
*fixup_graph
,
786 int *pi
, gcov_type
*d
, int *cycle
)
789 int fnum_vertices
, fnum_edges
;
790 fixup_edge_p fedge_list
, pfedge
, r_pfedge
;
791 bool found_cycle
= false;
792 int cycle_start
= 0, cycle_end
= 0;
793 gcov_type sum_cost
= 0, cycle_flow
= 0;
795 bool propagated
= false;
797 gcc_assert (fixup_graph
);
798 fnum_vertices
= fixup_graph
->num_vertices
;
799 fnum_edges
= fixup_graph
->num_edges
;
800 fedge_list
= fixup_graph
->edge_list
;
801 new_entry_index
= fixup_graph
->new_entry_index
;
805 for (i
= 1; i
< fnum_vertices
; i
++)
814 for (k
= 1; k
< fnum_vertices
; k
++)
817 for (i
= 0; i
< fnum_edges
; i
++)
819 pfedge
= fedge_list
+ i
;
820 if (pfedge
->src
== new_entry_index
)
822 if (pfedge
->is_rflow_valid
&& pfedge
->rflow
823 && d
[pfedge
->src
] != CAP_INFINITY
824 && (d
[pfedge
->dest
] > d
[pfedge
->src
] + pfedge
->cost
))
826 d
[pfedge
->dest
] = d
[pfedge
->src
] + pfedge
->cost
;
827 pi
[pfedge
->dest
] = pfedge
->src
;
836 /* No negative cycles exist. */
840 for (i
= 0; i
< fnum_edges
; i
++)
842 pfedge
= fedge_list
+ i
;
843 if (pfedge
->src
== new_entry_index
)
845 if (pfedge
->is_rflow_valid
&& pfedge
->rflow
846 && d
[pfedge
->src
] != CAP_INFINITY
847 && (d
[pfedge
->dest
] > d
[pfedge
->src
] + pfedge
->cost
))
857 /* Augment the cycle with the cycle's minimum residual capacity. */
859 cycle
[0] = pfedge
->dest
;
862 for (i
= 1; i
< fnum_vertices
; i
++)
866 for (k
= 0; k
< i
; k
++)
870 /* cycle[k] -> ... -> cycle[i]. */
881 gcc_assert (cycle
[cycle_start
] == cycle
[cycle_end
]);
883 fprintf (dump_file
, "\nNegative cycle length is %d:\n",
884 cycle_end
- cycle_start
);
887 cycle_flow
= CAP_INFINITY
;
888 for (k
= cycle_start
; k
< cycle_end
; k
++)
890 pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
+ 1], cycle
[k
]);
891 cycle_flow
= MIN (cycle_flow
, pfedge
->rflow
);
892 sum_cost
+= pfedge
->cost
;
894 fprintf (dump_file
, "%d ", cycle
[k
]);
899 fprintf (dump_file
, "%d", cycle
[k
]);
901 ": (" HOST_WIDEST_INT_PRINT_DEC
", " HOST_WIDEST_INT_PRINT_DEC
902 ")\n", sum_cost
, cycle_flow
);
904 "Augment cycle with " HOST_WIDEST_INT_PRINT_DEC
"\n",
908 for (k
= cycle_start
; k
< cycle_end
; k
++)
910 pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
+ 1], cycle
[k
]);
911 r_pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
], cycle
[k
+ 1]);
912 pfedge
->rflow
-= cycle_flow
;
914 pfedge
->flow
+= cycle_flow
;
915 r_pfedge
->rflow
+= cycle_flow
;
917 r_pfedge
->flow
-= cycle_flow
;
924 /* Computes the residual flow for FIXUP_GRAPH by setting the rflow field of
925 the edges. ENTRY and EXIT vertices should not be considered. */
928 compute_residual_flow (fixup_graph_type
*fixup_graph
)
932 fixup_edge_p fedge_list
, pfedge
;
934 gcc_assert (fixup_graph
);
937 fputs ("\ncompute_residual_flow():\n", dump_file
);
939 fnum_edges
= fixup_graph
->num_edges
;
940 fedge_list
= fixup_graph
->edge_list
;
942 for (i
= 0; i
< fnum_edges
; i
++)
944 pfedge
= fedge_list
+ i
;
945 pfedge
->rflow
= pfedge
->max_capacity
- pfedge
->flow
;
946 pfedge
->is_rflow_valid
= true;
947 add_rfixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
, pfedge
->flow
,
953 /* Uses Edmonds-Karp algorithm - BFS to find augmenting path from SOURCE to
954 SINK. The fields in the edge vector in the FIXUP_GRAPH are not modified by
955 this routine. The vector bb_pred in the AUGMENTING_PATH structure is updated
956 to reflect the path found.
957 Returns: 0 if no augmenting path is found, 1 otherwise. */
960 find_augmenting_path (fixup_graph_type
*fixup_graph
,
961 augmenting_path_type
*augmenting_path
, int source
,
966 fixup_vertex_p fvertex_list
, pfvertex
;
968 int *bb_pred
, *is_visited
;
969 queue_type
*queue_list
;
971 gcc_assert (augmenting_path
);
972 bb_pred
= augmenting_path
->bb_pred
;
973 gcc_assert (bb_pred
);
974 is_visited
= augmenting_path
->is_visited
;
975 gcc_assert (is_visited
);
976 queue_list
= &(augmenting_path
->queue_list
);
978 gcc_assert (fixup_graph
);
980 fvertex_list
= fixup_graph
->vertex_list
;
982 for (u
= 0; u
< fixup_graph
->num_vertices
; u
++)
985 init_queue (queue_list
);
986 enqueue (queue_list
, source
);
987 bb_pred
[source
] = -1;
989 while (!is_empty (queue_list
))
991 u
= dequeue (queue_list
);
993 pfvertex
= fvertex_list
+ u
;
994 for (i
= 0; pfvertex
->succ_edges
.iterate (i
, &pfedge
);
997 int dest
= pfedge
->dest
;
998 if ((pfedge
->rflow
> 0) && (is_visited
[dest
] == 0))
1000 enqueue (queue_list
, dest
);
1002 is_visited
[dest
] = 1;
1013 /* Routine to find the maximal flow:
1015 1. Initialize flow to 0
1016 2. Find an augmenting path form source to sink.
1017 3. Send flow equal to the path's residual capacity along the edges of this path.
1018 4. Repeat steps 2 and 3 until no new augmenting path is found.
1021 SOURCE: index of source vertex (input)
1022 SINK: index of sink vertex (input)
1023 FIXUP_GRAPH: adjacency matrix representing the graph. The flow of the edges will be
1024 set to have a valid maximal flow by this routine. (input)
1025 Return: Maximum flow possible. */
1028 find_max_flow (fixup_graph_type
*fixup_graph
, int source
, int sink
)
1031 augmenting_path_type augmenting_path
;
1033 gcov_type max_flow
= 0;
1035 fixup_edge_p fedge_list
, pfedge
, r_pfedge
;
1037 gcc_assert (fixup_graph
);
1039 fnum_edges
= fixup_graph
->num_edges
;
1040 fedge_list
= fixup_graph
->edge_list
;
1042 /* Initialize flow to 0. */
1043 for (i
= 0; i
< fnum_edges
; i
++)
1045 pfedge
= fedge_list
+ i
;
1049 compute_residual_flow (fixup_graph
);
1051 init_augmenting_path (&augmenting_path
, fixup_graph
->num_vertices
);
1053 bb_pred
= augmenting_path
.bb_pred
;
1054 while (find_augmenting_path (fixup_graph
, &augmenting_path
, source
, sink
))
1056 /* Determine the amount by which we can increment the flow. */
1057 gcov_type increment
= CAP_INFINITY
;
1058 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1060 pfedge
= find_fixup_edge (fixup_graph
, bb_pred
[u
], u
);
1061 increment
= MIN (increment
, pfedge
->rflow
);
1063 max_flow
+= increment
;
1065 /* Now increment the flow. EXIT vertex index is 1. */
1066 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1068 pfedge
= find_fixup_edge (fixup_graph
, bb_pred
[u
], u
);
1069 r_pfedge
= find_fixup_edge (fixup_graph
, u
, bb_pred
[u
]);
1073 pfedge
->flow
+= increment
;
1074 pfedge
->rflow
-= increment
;
1075 r_pfedge
->rflow
+= increment
;
1079 /* backward edge. */
1080 gcc_assert (r_pfedge
->type
);
1081 r_pfedge
->rflow
+= increment
;
1082 r_pfedge
->flow
-= increment
;
1083 pfedge
->rflow
-= increment
;
1089 fprintf (dump_file
, "\nDump augmenting path:\n");
1090 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1092 print_basic_block (dump_file
, fixup_graph
, u
);
1093 fprintf (dump_file
, "<-");
1096 "ENTRY (path_capacity=" HOST_WIDEST_INT_PRINT_DEC
")\n",
1099 "Network flow is " HOST_WIDEST_INT_PRINT_DEC
".\n",
1104 free_augmenting_path (&augmenting_path
);
1106 dump_fixup_graph (dump_file
, fixup_graph
, "After find_max_flow()");
1111 /* Computes the corrected edge and basic block weights using FIXUP_GRAPH
1112 after applying the find_minimum_cost_flow() routine. */
1115 adjust_cfg_counts (fixup_graph_type
*fixup_graph
)
1121 fixup_edge_p pfedge
, pfedge_n
;
1123 gcc_assert (fixup_graph
);
1126 fprintf (dump_file
, "\nadjust_cfg_counts():\n");
1128 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR_FOR_FN (cfun
),
1129 EXIT_BLOCK_PTR_FOR_FN (cfun
), next_bb
)
1136 "BB%d: " HOST_WIDEST_INT_PRINT_DEC
"", bb
->index
, bb
->count
);
1138 pfedge
= find_fixup_edge (fixup_graph
, i
, i
+ 1);
1141 bb
->count
+= pfedge
->flow
;
1144 fprintf (dump_file
, " + " HOST_WIDEST_INT_PRINT_DEC
"(",
1146 print_edge (dump_file
, fixup_graph
, i
, i
+ 1);
1147 fprintf (dump_file
, ")");
1152 find_fixup_edge (fixup_graph
, i
+ 1, pfedge
->norm_vertex_index
);
1153 /* Deduct flow from normalized reverse edge. */
1154 if (pfedge
->norm_vertex_index
&& pfedge_n
->flow
)
1156 bb
->count
-= pfedge_n
->flow
;
1159 fprintf (dump_file
, " - " HOST_WIDEST_INT_PRINT_DEC
"(",
1161 print_edge (dump_file
, fixup_graph
, i
+ 1,
1162 pfedge
->norm_vertex_index
);
1163 fprintf (dump_file
, ")");
1167 fprintf (dump_file
, " = " HOST_WIDEST_INT_PRINT_DEC
"\n", bb
->count
);
1170 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1172 /* Treat edges with ignore attribute set as if they don't exist. */
1173 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
1176 j
= 2 * e
->dest
->index
;
1178 fprintf (dump_file
, "%d->%d: " HOST_WIDEST_INT_PRINT_DEC
"",
1179 bb
->index
, e
->dest
->index
, e
->count
);
1181 pfedge
= find_fixup_edge (fixup_graph
, i
+ 1, j
);
1183 if (bb
->index
!= e
->dest
->index
)
1185 /* Non-self edge. */
1188 e
->count
+= pfedge
->flow
;
1191 fprintf (dump_file
, " + " HOST_WIDEST_INT_PRINT_DEC
"(",
1193 print_edge (dump_file
, fixup_graph
, i
+ 1, j
);
1194 fprintf (dump_file
, ")");
1199 find_fixup_edge (fixup_graph
, j
, pfedge
->norm_vertex_index
);
1200 /* Deduct flow from normalized reverse edge. */
1201 if (pfedge
->norm_vertex_index
&& pfedge_n
->flow
)
1203 e
->count
-= pfedge_n
->flow
;
1206 fprintf (dump_file
, " - " HOST_WIDEST_INT_PRINT_DEC
"(",
1208 print_edge (dump_file
, fixup_graph
, j
,
1209 pfedge
->norm_vertex_index
);
1210 fprintf (dump_file
, ")");
1216 /* Handle self edges. Self edge is split with a normalization
1217 vertex. Here i=j. */
1218 pfedge
= find_fixup_edge (fixup_graph
, j
, i
+ 1);
1220 find_fixup_edge (fixup_graph
, i
+ 1, pfedge
->norm_vertex_index
);
1221 e
->count
+= pfedge_n
->flow
;
1222 bb
->count
+= pfedge_n
->flow
;
1225 fprintf (dump_file
, "(self edge)");
1226 fprintf (dump_file
, " + " HOST_WIDEST_INT_PRINT_DEC
"(",
1228 print_edge (dump_file
, fixup_graph
, i
+ 1,
1229 pfedge
->norm_vertex_index
);
1230 fprintf (dump_file
, ")");
1235 e
->probability
= REG_BR_PROB_BASE
* e
->count
/ bb
->count
;
1237 fprintf (dump_file
, " = " HOST_WIDEST_INT_PRINT_DEC
"\t(%.1f%%)\n",
1238 e
->count
, e
->probability
* 100.0 / REG_BR_PROB_BASE
);
1242 ENTRY_BLOCK_PTR_FOR_FN (cfun
)->count
=
1243 sum_edge_counts (ENTRY_BLOCK_PTR_FOR_FN (cfun
)->succs
);
1244 EXIT_BLOCK_PTR_FOR_FN (cfun
)->count
=
1245 sum_edge_counts (EXIT_BLOCK_PTR_FOR_FN (cfun
)->preds
);
1247 /* Compute edge probabilities. */
1248 FOR_ALL_BB_FN (bb
, cfun
)
1252 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1253 e
->probability
= REG_BR_PROB_BASE
* e
->count
/ bb
->count
;
1258 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1259 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
1263 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1265 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
1266 e
->probability
= REG_BR_PROB_BASE
/ total
;
1273 total
+= EDGE_COUNT (bb
->succs
);
1274 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1275 e
->probability
= REG_BR_PROB_BASE
/ total
;
1282 fprintf (dump_file
, "\nCheck %s() CFG flow conservation:\n",
1283 current_function_name ());
1284 FOR_EACH_BB_FN (bb
, cfun
)
1286 if ((bb
->count
!= sum_edge_counts (bb
->preds
))
1287 || (bb
->count
!= sum_edge_counts (bb
->succs
)))
1290 "BB%d(" HOST_WIDEST_INT_PRINT_DEC
") **INVALID**: ",
1291 bb
->index
, bb
->count
);
1293 "******** BB%d(" HOST_WIDEST_INT_PRINT_DEC
1294 ") **INVALID**: \n", bb
->index
, bb
->count
);
1295 fprintf (dump_file
, "in_edges=" HOST_WIDEST_INT_PRINT_DEC
" ",
1296 sum_edge_counts (bb
->preds
));
1297 fprintf (dump_file
, "out_edges=" HOST_WIDEST_INT_PRINT_DEC
"\n",
1298 sum_edge_counts (bb
->succs
));
1305 /* Implements the negative cycle canceling algorithm to compute a minimum cost
1308 1. Find maximal flow.
1309 2. Form residual network
1311 While G contains a negative cost cycle C, reverse the flow on the found cycle
1312 by the minimum residual capacity in that cycle.
1313 4. Form the minimal cost flow
1316 FIXUP_GRAPH - Initial fixup graph.
1317 The flow field is modified to represent the minimum cost flow. */
1320 find_minimum_cost_flow (fixup_graph_type
*fixup_graph
)
1322 /* Holds the index of predecessor in path. */
1324 /* Used to hold the minimum cost cycle. */
1326 /* Used to record the number of iterations of cancel_negative_cycle. */
1328 /* Vector d[i] holds the minimum cost of path from i to sink. */
1332 int new_entry_index
;
1334 gcc_assert (fixup_graph
);
1335 fnum_vertices
= fixup_graph
->num_vertices
;
1336 new_exit_index
= fixup_graph
->new_exit_index
;
1337 new_entry_index
= fixup_graph
->new_entry_index
;
1339 find_max_flow (fixup_graph
, new_entry_index
, new_exit_index
);
1341 /* Initialize the structures for find_negative_cycle(). */
1342 pred
= (int *) xcalloc (fnum_vertices
, sizeof (int));
1343 d
= (gcov_type
*) xcalloc (fnum_vertices
, sizeof (gcov_type
));
1344 cycle
= (int *) xcalloc (fnum_vertices
, sizeof (int));
1346 /* Repeatedly find and cancel negative cost cycles, until
1347 no more negative cycles exist. This also updates the flow field
1348 to represent the minimum cost flow so far. */
1350 while (cancel_negative_cycle (fixup_graph
, pred
, d
, cycle
))
1353 if (iteration
> MAX_ITER (fixup_graph
->num_vertices
,
1354 fixup_graph
->num_edges
))
1359 dump_fixup_graph (dump_file
, fixup_graph
,
1360 "After find_minimum_cost_flow()");
1362 /* Cleanup structures. */
1369 /* Compute the sum of the edge counts in TO_EDGES. */
1372 sum_edge_counts (vec
<edge
, va_gc
> *to_edges
)
1378 FOR_EACH_EDGE (e
, ei
, to_edges
)
1380 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
1388 /* Main routine. Smoothes the initial assigned basic block and edge counts using
1389 a minimum cost flow algorithm, to ensure that the flow consistency rule is
1390 obeyed: sum of outgoing edges = sum of incoming edges for each basic
1394 mcf_smooth_cfg (void)
1396 fixup_graph_type fixup_graph
;
1397 memset (&fixup_graph
, 0, sizeof (fixup_graph
));
1398 create_fixup_graph (&fixup_graph
);
1399 find_minimum_cost_flow (&fixup_graph
);
1400 adjust_cfg_counts (&fixup_graph
);
1401 delete_fixup_graph (&fixup_graph
);