1 /* Routines to implement minimum-cost maximal flow algorithm used to smooth
2 basic block and edge frequency counts.
3 Copyright (C) 2008-2015 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"
49 #include "hard-reg-set.h"
54 /* CAP_INFINITY: Constant to represent infinite capacity. */
55 #define CAP_INFINITY INTTYPE_MAXIMUM (int64_t)
58 #define K_POS(b) ((b))
59 #define K_NEG(b) (50 * (b))
60 #define COST(k, w) ((k) / mcf_ln ((w) + 2))
61 /* Limit the number of iterations for cancel_negative_cycles() to ensure
62 reasonable compile time. */
63 #define MAX_ITER(n, e) 10 + (1000000 / ((n) * (e)))
67 VERTEX_SPLIT_EDGE
, /* Edge to represent vertex with w(e) = w(v). */
68 REDIRECT_EDGE
, /* Edge after vertex transformation. */
70 SOURCE_CONNECT_EDGE
, /* Single edge connecting to single source. */
71 SINK_CONNECT_EDGE
, /* Single edge connecting to single sink. */
72 BALANCE_EDGE
, /* Edge connecting with source/sink: cp(e) = 0. */
73 REDIRECT_NORMALIZED_EDGE
, /* Normalized edge for a redirect edge. */
74 REVERSE_NORMALIZED_EDGE
/* Normalized edge for a reverse edge. */
77 /* Structure to represent an edge in the fixup graph. */
78 typedef struct fixup_edge_d
82 /* Flag denoting type of edge and attributes for the flow field. */
85 /* Index to the normalization vertex added for this edge. */
86 int norm_vertex_index
;
87 /* Flow for this edge. */
89 /* Residual flow for this edge - used during negative cycle canceling. */
93 gcov_type max_capacity
;
96 typedef fixup_edge_type
*fixup_edge_p
;
99 /* Structure to represent a vertex in the fixup graph. */
100 typedef struct fixup_vertex_d
102 vec
<fixup_edge_p
> succ_edges
;
105 typedef fixup_vertex_type
*fixup_vertex_p
;
107 /* Fixup graph used in the MCF algorithm. */
108 typedef struct fixup_graph_d
110 /* Current number of vertices for the graph. */
112 /* Current number of edges for the graph. */
114 /* Index of new entry vertex. */
116 /* Index of new exit vertex. */
118 /* Fixup vertex list. Adjacency list for fixup graph. */
119 fixup_vertex_p vertex_list
;
120 /* Fixup edge list. */
121 fixup_edge_p edge_list
;
124 typedef struct queue_d
132 /* Structure used in the maximal flow routines to find augmenting path. */
133 typedef struct augmenting_path_d
135 /* Queue used to hold vertex indices. */
136 queue_type queue_list
;
137 /* Vector to hold chain of pred vertex indices in augmenting path. */
139 /* Vector that indicates if basic block i has been visited. */
141 } augmenting_path_type
;
144 /* Function definitions. */
146 /* Dump routines to aid debugging. */
148 /* Print basic block with index N for FIXUP_GRAPH in n' and n'' format. */
151 print_basic_block (FILE *file
, fixup_graph_type
*fixup_graph
, int n
)
153 if (n
== ENTRY_BLOCK
)
154 fputs ("ENTRY", file
);
155 else if (n
== ENTRY_BLOCK
+ 1)
156 fputs ("ENTRY''", file
);
157 else if (n
== 2 * EXIT_BLOCK
)
158 fputs ("EXIT", file
);
159 else if (n
== 2 * EXIT_BLOCK
+ 1)
160 fputs ("EXIT''", file
);
161 else if (n
== fixup_graph
->new_exit_index
)
162 fputs ("NEW_EXIT", file
);
163 else if (n
== fixup_graph
->new_entry_index
)
164 fputs ("NEW_ENTRY", file
);
167 fprintf (file
, "%d", n
/ 2);
176 /* Print edge S->D for given fixup_graph with n' and n'' format.
178 S is the index of the source vertex of the edge (input) and
179 D is the index of the destination vertex of the edge (input) for the given
180 fixup_graph (input). */
183 print_edge (FILE *file
, fixup_graph_type
*fixup_graph
, int s
, int d
)
185 print_basic_block (file
, fixup_graph
, s
);
187 print_basic_block (file
, fixup_graph
, d
);
191 /* Dump out the attributes of a given edge FEDGE in the fixup_graph to a
194 dump_fixup_edge (FILE *file
, fixup_graph_type
*fixup_graph
, fixup_edge_p fedge
)
198 fputs ("NULL fixup graph edge.\n", file
);
202 print_edge (file
, fixup_graph
, fedge
->src
, fedge
->dest
);
207 fprintf (file
, "flow/capacity=%" PRId64
"/",
209 if (fedge
->max_capacity
== CAP_INFINITY
)
210 fputs ("+oo,", file
);
212 fprintf (file
, "%" PRId64
",", fedge
->max_capacity
);
215 if (fedge
->is_rflow_valid
)
217 if (fedge
->rflow
== CAP_INFINITY
)
218 fputs (" rflow=+oo.", file
);
220 fprintf (file
, " rflow=%" PRId64
",", fedge
->rflow
);
223 fprintf (file
, " cost=%" PRId64
".", fedge
->cost
);
225 fprintf (file
, "\t(%d->%d)", fedge
->src
, fedge
->dest
);
231 case VERTEX_SPLIT_EDGE
:
232 fputs (" @VERTEX_SPLIT_EDGE", file
);
236 fputs (" @REDIRECT_EDGE", file
);
239 case SOURCE_CONNECT_EDGE
:
240 fputs (" @SOURCE_CONNECT_EDGE", file
);
243 case SINK_CONNECT_EDGE
:
244 fputs (" @SINK_CONNECT_EDGE", file
);
248 fputs (" @REVERSE_EDGE", file
);
252 fputs (" @BALANCE_EDGE", file
);
255 case REDIRECT_NORMALIZED_EDGE
:
256 case REVERSE_NORMALIZED_EDGE
:
257 fputs (" @NORMALIZED_EDGE", file
);
261 fputs (" @INVALID_EDGE", file
);
269 /* Print out the edges and vertices of the given FIXUP_GRAPH, into the dump
270 file. The input string MSG is printed out as a heading. */
273 dump_fixup_graph (FILE *file
, fixup_graph_type
*fixup_graph
, const char *msg
)
276 int fnum_vertices
, fnum_edges
;
278 fixup_vertex_p fvertex_list
, pfvertex
;
281 gcc_assert (fixup_graph
);
282 fvertex_list
= fixup_graph
->vertex_list
;
283 fnum_vertices
= fixup_graph
->num_vertices
;
284 fnum_edges
= fixup_graph
->num_edges
;
286 fprintf (file
, "\nDump fixup graph for %s(): %s.\n",
287 current_function_name (), msg
);
289 "There are %d vertices and %d edges. new_exit_index is %d.\n\n",
290 fnum_vertices
, fnum_edges
, fixup_graph
->new_exit_index
);
292 for (i
= 0; i
< fnum_vertices
; i
++)
294 pfvertex
= fvertex_list
+ i
;
295 fprintf (file
, "vertex_list[%d]: %d succ fixup edges.\n",
296 i
, pfvertex
->succ_edges
.length ());
298 for (j
= 0; pfvertex
->succ_edges
.iterate (j
, &pfedge
);
301 /* Distinguish forward edges and backward edges in the residual flow
304 fputs ("(f) ", file
);
305 else if (pfedge
->is_rflow_valid
)
306 fputs ("(b) ", file
);
307 dump_fixup_edge (file
, fixup_graph
, pfedge
);
315 /* Utility routines. */
316 /* ln() implementation: approximate calculation. Returns ln of X. */
337 /* sqrt() implementation: based on open source QUAKE3 code (magic sqrt
338 implementation) by John Carmack. Returns sqrt of X. */
343 #define MAGIC_CONST1 0x1fbcf800
344 #define MAGIC_CONST2 0x5f3759df
348 } convertor
, convertor2
;
352 convertor
.floatPart
= x
;
353 convertor2
.floatPart
= x
;
354 convertor
.intPart
= MAGIC_CONST1
+ (convertor
.intPart
>> 1);
355 convertor2
.intPart
= MAGIC_CONST2
- (convertor2
.intPart
>> 1);
357 return 0.5f
* (convertor
.floatPart
+ (x
* convertor2
.floatPart
));
361 /* Common code shared between add_fixup_edge and add_rfixup_edge. Adds an edge
362 (SRC->DEST) to the edge_list maintained in FIXUP_GRAPH with cost of the edge
363 added set to COST. */
366 add_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
, gcov_type cost
)
368 fixup_vertex_p curr_vertex
= fixup_graph
->vertex_list
+ src
;
369 fixup_edge_p curr_edge
= fixup_graph
->edge_list
+ fixup_graph
->num_edges
;
370 curr_edge
->src
= src
;
371 curr_edge
->dest
= dest
;
372 curr_edge
->cost
= cost
;
373 fixup_graph
->num_edges
++;
375 dump_fixup_edge (dump_file
, fixup_graph
, curr_edge
);
376 curr_vertex
->succ_edges
.safe_push (curr_edge
);
381 /* Add a fixup edge (src->dest) with attributes TYPE, WEIGHT, COST and
382 MAX_CAPACITY to the edge_list in the fixup graph. */
385 add_fixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
,
386 edge_type type
, gcov_type weight
, gcov_type cost
,
387 gcov_type max_capacity
)
389 fixup_edge_p curr_edge
= add_edge (fixup_graph
, src
, dest
, cost
);
390 curr_edge
->type
= type
;
391 curr_edge
->weight
= weight
;
392 curr_edge
->max_capacity
= max_capacity
;
396 /* Add a residual edge (SRC->DEST) with attributes RFLOW and COST
397 to the fixup graph. */
400 add_rfixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
,
401 gcov_type rflow
, gcov_type cost
)
403 fixup_edge_p curr_edge
= add_edge (fixup_graph
, src
, dest
, cost
);
404 curr_edge
->rflow
= rflow
;
405 curr_edge
->is_rflow_valid
= true;
406 /* This edge is not a valid edge - merely used to hold residual flow. */
407 curr_edge
->type
= INVALID_EDGE
;
411 /* Return the pointer to fixup edge SRC->DEST or NULL if edge does not
412 exist in the FIXUP_GRAPH. */
415 find_fixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
)
419 fixup_vertex_p pfvertex
;
421 gcc_assert (src
< fixup_graph
->num_vertices
);
423 pfvertex
= fixup_graph
->vertex_list
+ src
;
425 for (j
= 0; pfvertex
->succ_edges
.iterate (j
, &pfedge
);
427 if (pfedge
->dest
== dest
)
434 /* Cleanup routine to free structures in FIXUP_GRAPH. */
437 delete_fixup_graph (fixup_graph_type
*fixup_graph
)
440 int fnum_vertices
= fixup_graph
->num_vertices
;
441 fixup_vertex_p pfvertex
= fixup_graph
->vertex_list
;
443 for (i
= 0; i
< fnum_vertices
; i
++, pfvertex
++)
444 pfvertex
->succ_edges
.release ();
446 free (fixup_graph
->vertex_list
);
447 free (fixup_graph
->edge_list
);
451 /* Creates a fixup graph FIXUP_GRAPH from the function CFG. */
454 create_fixup_graph (fixup_graph_type
*fixup_graph
)
456 double sqrt_avg_vertex_weight
= 0;
457 double total_vertex_weight
= 0;
460 /* Vector to hold D(v) = sum_out_edges(v) - sum_in_edges(v). */
461 gcov_type
*diff_out_in
= NULL
;
462 gcov_type supply_value
= 1, demand_value
= 0;
464 int new_entry_index
= 0, new_exit_index
= 0;
470 fixup_edge_p pfedge
, r_pfedge
;
471 fixup_edge_p fedge_list
;
474 /* Each basic_block will be split into 2 during vertex transformation. */
475 int fnum_vertices_after_transform
= 2 * n_basic_blocks_for_fn (cfun
);
476 int fnum_edges_after_transform
=
477 n_edges_for_fn (cfun
) + n_basic_blocks_for_fn (cfun
);
479 /* Count the new SOURCE and EXIT vertices to be added. */
480 int fmax_num_vertices
=
481 (fnum_vertices_after_transform
+ n_edges_for_fn (cfun
)
482 + n_basic_blocks_for_fn (cfun
) + 2);
484 /* In create_fixup_graph: Each basic block and edge can be split into 3
485 edges. Number of balance edges = n_basic_blocks. So after
487 max_edges = 4 * n_basic_blocks + 3 * n_edges
488 Accounting for residual flow edges
489 max_edges = 2 * (4 * n_basic_blocks + 3 * n_edges)
490 = 8 * n_basic_blocks + 6 * n_edges
491 < 8 * n_basic_blocks + 8 * n_edges. */
492 int fmax_num_edges
= 8 * (n_basic_blocks_for_fn (cfun
) +
493 n_edges_for_fn (cfun
));
495 /* Initial num of vertices in the fixup graph. */
496 fixup_graph
->num_vertices
= n_basic_blocks_for_fn (cfun
);
498 /* Fixup graph vertex list. */
499 fixup_graph
->vertex_list
=
500 (fixup_vertex_p
) xcalloc (fmax_num_vertices
, sizeof (fixup_vertex_type
));
502 /* Fixup graph edge list. */
503 fixup_graph
->edge_list
=
504 (fixup_edge_p
) xcalloc (fmax_num_edges
, sizeof (fixup_edge_type
));
507 (gcov_type
*) xcalloc (1 + fnum_vertices_after_transform
,
510 /* Compute constants b, k_pos, k_neg used in the cost function calculation.
511 b = sqrt(avg_vertex_weight(cfg)); k_pos = b; k_neg = 50b. */
512 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR_FOR_FN (cfun
), NULL
, next_bb
)
513 total_vertex_weight
+= bb
->count
;
515 sqrt_avg_vertex_weight
= mcf_sqrt (total_vertex_weight
/
516 n_basic_blocks_for_fn (cfun
));
518 k_pos
= K_POS (sqrt_avg_vertex_weight
);
519 k_neg
= K_NEG (sqrt_avg_vertex_weight
);
521 /* 1. Vertex Transformation: Split each vertex v into two vertices v' and v'',
522 connected by an edge e from v' to v''. w(e) = w(v). */
525 fprintf (dump_file
, "\nVertex transformation:\n");
527 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR_FOR_FN (cfun
), NULL
, next_bb
)
529 /* v'->v'': index1->(index1+1). */
531 fcost
= (gcov_type
) COST (k_pos
, bb
->count
);
532 add_fixup_edge (fixup_graph
, i
, i
+ 1, VERTEX_SPLIT_EDGE
, bb
->count
,
533 fcost
, CAP_INFINITY
);
534 fixup_graph
->num_vertices
++;
536 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
538 /* Edges with ignore attribute set should be treated like they don't
540 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
542 j
= 2 * e
->dest
->index
;
543 fcost
= (gcov_type
) COST (k_pos
, e
->count
);
544 add_fixup_edge (fixup_graph
, i
+ 1, j
, REDIRECT_EDGE
, e
->count
, fcost
,
549 /* After vertex transformation. */
550 gcc_assert (fixup_graph
->num_vertices
== fnum_vertices_after_transform
);
551 /* Redirect edges are not added for edges with ignore attribute. */
552 gcc_assert (fixup_graph
->num_edges
<= fnum_edges_after_transform
);
554 fnum_edges_after_transform
= fixup_graph
->num_edges
;
556 /* 2. Initialize D(v). */
557 for (i
= 0; i
< fnum_edges_after_transform
; i
++)
559 pfedge
= fixup_graph
->edge_list
+ i
;
560 diff_out_in
[pfedge
->src
] += pfedge
->weight
;
561 diff_out_in
[pfedge
->dest
] -= pfedge
->weight
;
564 /* Entry block - vertex indices 0, 1; EXIT block - vertex indices 2, 3. */
565 for (i
= 0; i
<= 3; i
++)
568 /* 3. Add reverse edges: needed to decrease counts during smoothing. */
570 fprintf (dump_file
, "\nReverse edges:\n");
571 for (i
= 0; i
< fnum_edges_after_transform
; i
++)
573 pfedge
= fixup_graph
->edge_list
+ i
;
574 if ((pfedge
->src
== 0) || (pfedge
->src
== 2))
576 r_pfedge
= find_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
);
577 if (!r_pfedge
&& pfedge
->weight
)
579 /* Skip adding reverse edges for edges with w(e) = 0, as its maximum
581 fcost
= (gcov_type
) COST (k_neg
, pfedge
->weight
);
582 add_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
,
583 REVERSE_EDGE
, 0, fcost
, pfedge
->weight
);
587 /* 4. Create single source and sink. Connect new source vertex s' to function
588 entry block. Connect sink vertex t' to function exit. */
590 fprintf (dump_file
, "\ns'->S, T->t':\n");
592 new_entry_index
= fixup_graph
->new_entry_index
= fixup_graph
->num_vertices
;
593 fixup_graph
->num_vertices
++;
594 /* Set supply_value to 1 to avoid zero count function ENTRY. */
595 add_fixup_edge (fixup_graph
, new_entry_index
, ENTRY_BLOCK
, SOURCE_CONNECT_EDGE
,
596 1 /* supply_value */, 0, 1 /* supply_value */);
598 /* Create new exit with EXIT_BLOCK as single pred. */
599 new_exit_index
= fixup_graph
->new_exit_index
= fixup_graph
->num_vertices
;
600 fixup_graph
->num_vertices
++;
601 add_fixup_edge (fixup_graph
, 2 * EXIT_BLOCK
+ 1, new_exit_index
,
603 0 /* demand_value */, 0, 0 /* demand_value */);
605 /* Connect vertices with unbalanced D(v) to source/sink. */
607 fprintf (dump_file
, "\nD(v) balance:\n");
608 /* Skip vertices for ENTRY (0, 1) and EXIT (2,3) blocks, so start with i = 4.
609 diff_out_in[v''] will be 0, so skip v'' vertices, hence i += 2. */
610 for (i
= 4; i
< new_entry_index
; i
+= 2)
612 if (diff_out_in
[i
] > 0)
614 add_fixup_edge (fixup_graph
, i
, new_exit_index
, BALANCE_EDGE
, 0, 0,
616 demand_value
+= diff_out_in
[i
];
618 else if (diff_out_in
[i
] < 0)
620 add_fixup_edge (fixup_graph
, new_entry_index
, i
, BALANCE_EDGE
, 0, 0,
622 supply_value
-= diff_out_in
[i
];
626 /* Set supply = demand. */
629 fprintf (dump_file
, "\nAdjust supply and demand:\n");
630 fprintf (dump_file
, "supply_value=%" PRId64
"\n",
632 fprintf (dump_file
, "demand_value=%" PRId64
"\n",
636 if (demand_value
> supply_value
)
638 pfedge
= find_fixup_edge (fixup_graph
, new_entry_index
, ENTRY_BLOCK
);
639 pfedge
->max_capacity
+= (demand_value
- supply_value
);
643 pfedge
= find_fixup_edge (fixup_graph
, 2 * EXIT_BLOCK
+ 1, new_exit_index
);
644 pfedge
->max_capacity
+= (supply_value
- demand_value
);
647 /* 6. Normalize edges: remove anti-parallel edges. Anti-parallel edges are
648 created by the vertex transformation step from self-edges in the original
649 CFG and by the reverse edges added earlier. */
651 fprintf (dump_file
, "\nNormalize edges:\n");
653 fnum_edges
= fixup_graph
->num_edges
;
654 fedge_list
= fixup_graph
->edge_list
;
656 for (i
= 0; i
< fnum_edges
; i
++)
658 pfedge
= fedge_list
+ i
;
659 r_pfedge
= find_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
);
660 if (((pfedge
->type
== VERTEX_SPLIT_EDGE
)
661 || (pfedge
->type
== REDIRECT_EDGE
)) && r_pfedge
)
663 new_index
= fixup_graph
->num_vertices
;
664 fixup_graph
->num_vertices
++;
668 fprintf (dump_file
, "\nAnti-parallel edge:\n");
669 dump_fixup_edge (dump_file
, fixup_graph
, pfedge
);
670 dump_fixup_edge (dump_file
, fixup_graph
, r_pfedge
);
671 fprintf (dump_file
, "New vertex is %d.\n", new_index
);
672 fprintf (dump_file
, "------------------\n");
676 pfedge
->norm_vertex_index
= new_index
;
679 fprintf (dump_file
, "After normalization:\n");
680 dump_fixup_edge (dump_file
, fixup_graph
, pfedge
);
683 /* Add a new fixup edge: new_index->src. */
684 add_fixup_edge (fixup_graph
, new_index
, pfedge
->src
,
685 REVERSE_NORMALIZED_EDGE
, 0, r_pfedge
->cost
,
686 r_pfedge
->max_capacity
);
687 gcc_assert (fixup_graph
->num_vertices
<= fmax_num_vertices
);
689 /* Edge: r_pfedge->src -> r_pfedge->dest
690 ==> r_pfedge->src -> new_index. */
691 r_pfedge
->dest
= new_index
;
692 r_pfedge
->type
= REVERSE_NORMALIZED_EDGE
;
693 r_pfedge
->cost
= pfedge
->cost
;
694 r_pfedge
->max_capacity
= pfedge
->max_capacity
;
696 dump_fixup_edge (dump_file
, fixup_graph
, r_pfedge
);
701 dump_fixup_graph (dump_file
, fixup_graph
, "After create_fixup_graph()");
708 /* Allocates space for the structures in AUGMENTING_PATH. The space needed is
709 proportional to the number of nodes in the graph, which is given by
713 init_augmenting_path (augmenting_path_type
*augmenting_path
, int graph_size
)
715 augmenting_path
->queue_list
.queue
= (int *)
716 xcalloc (graph_size
+ 2, sizeof (int));
717 augmenting_path
->queue_list
.size
= graph_size
+ 2;
718 augmenting_path
->bb_pred
= (int *) xcalloc (graph_size
, sizeof (int));
719 augmenting_path
->is_visited
= (int *) xcalloc (graph_size
, sizeof (int));
722 /* Free the structures in AUGMENTING_PATH. */
724 free_augmenting_path (augmenting_path_type
*augmenting_path
)
726 free (augmenting_path
->queue_list
.queue
);
727 free (augmenting_path
->bb_pred
);
728 free (augmenting_path
->is_visited
);
732 /* Queue routines. Assumes queue will never overflow. */
735 init_queue (queue_type
*queue_list
)
737 gcc_assert (queue_list
);
738 queue_list
->head
= 0;
739 queue_list
->tail
= 0;
742 /* Return true if QUEUE_LIST is empty. */
744 is_empty (queue_type
*queue_list
)
746 return (queue_list
->head
== queue_list
->tail
);
749 /* Insert element X into QUEUE_LIST. */
751 enqueue (queue_type
*queue_list
, int x
)
753 gcc_assert (queue_list
->tail
< queue_list
->size
);
754 queue_list
->queue
[queue_list
->tail
] = x
;
755 (queue_list
->tail
)++;
758 /* Return the first element in QUEUE_LIST. */
760 dequeue (queue_type
*queue_list
)
763 gcc_assert (queue_list
->head
>= 0);
764 x
= queue_list
->queue
[queue_list
->head
];
765 (queue_list
->head
)++;
770 /* Finds a negative cycle in the residual network using
771 the Bellman-Ford algorithm. The flow on the found cycle is reversed by the
772 minimum residual capacity of that cycle. ENTRY and EXIT vertices are not
776 FIXUP_GRAPH - Residual graph (input/output)
777 The following are allocated/freed by the caller:
778 PI - Vector to hold predecessors in path (pi = pred index)
779 D - D[I] holds minimum cost of path from i to sink
780 CYCLE - Vector to hold the minimum cost cycle
783 true if a negative cycle was found, false otherwise. */
786 cancel_negative_cycle (fixup_graph_type
*fixup_graph
,
787 int *pi
, gcov_type
*d
, int *cycle
)
790 int fnum_vertices
, fnum_edges
;
791 fixup_edge_p fedge_list
, pfedge
, r_pfedge
;
792 bool found_cycle
= false;
793 int cycle_start
= 0, cycle_end
= 0;
794 gcov_type sum_cost
= 0, cycle_flow
= 0;
796 bool propagated
= false;
798 gcc_assert (fixup_graph
);
799 fnum_vertices
= fixup_graph
->num_vertices
;
800 fnum_edges
= fixup_graph
->num_edges
;
801 fedge_list
= fixup_graph
->edge_list
;
802 new_entry_index
= fixup_graph
->new_entry_index
;
806 for (i
= 1; i
< fnum_vertices
; i
++)
815 for (k
= 1; k
< fnum_vertices
; k
++)
818 for (i
= 0; i
< fnum_edges
; i
++)
820 pfedge
= fedge_list
+ i
;
821 if (pfedge
->src
== new_entry_index
)
823 if (pfedge
->is_rflow_valid
&& pfedge
->rflow
824 && d
[pfedge
->src
] != CAP_INFINITY
825 && (d
[pfedge
->dest
] > d
[pfedge
->src
] + pfedge
->cost
))
827 d
[pfedge
->dest
] = d
[pfedge
->src
] + pfedge
->cost
;
828 pi
[pfedge
->dest
] = pfedge
->src
;
837 /* No negative cycles exist. */
841 for (i
= 0; i
< fnum_edges
; i
++)
843 pfedge
= fedge_list
+ i
;
844 if (pfedge
->src
== new_entry_index
)
846 if (pfedge
->is_rflow_valid
&& pfedge
->rflow
847 && d
[pfedge
->src
] != CAP_INFINITY
848 && (d
[pfedge
->dest
] > d
[pfedge
->src
] + pfedge
->cost
))
858 /* Augment the cycle with the cycle's minimum residual capacity. */
860 cycle
[0] = pfedge
->dest
;
863 for (i
= 1; i
< fnum_vertices
; i
++)
867 for (k
= 0; k
< i
; k
++)
871 /* cycle[k] -> ... -> cycle[i]. */
882 gcc_assert (cycle
[cycle_start
] == cycle
[cycle_end
]);
884 fprintf (dump_file
, "\nNegative cycle length is %d:\n",
885 cycle_end
- cycle_start
);
888 cycle_flow
= CAP_INFINITY
;
889 for (k
= cycle_start
; k
< cycle_end
; k
++)
891 pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
+ 1], cycle
[k
]);
892 cycle_flow
= MIN (cycle_flow
, pfedge
->rflow
);
893 sum_cost
+= pfedge
->cost
;
895 fprintf (dump_file
, "%d ", cycle
[k
]);
900 fprintf (dump_file
, "%d", cycle
[k
]);
902 ": (%" PRId64
", %" PRId64
903 ")\n", sum_cost
, cycle_flow
);
905 "Augment cycle with %" PRId64
"\n",
909 for (k
= cycle_start
; k
< cycle_end
; k
++)
911 pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
+ 1], cycle
[k
]);
912 r_pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
], cycle
[k
+ 1]);
913 pfedge
->rflow
-= cycle_flow
;
915 pfedge
->flow
+= cycle_flow
;
916 r_pfedge
->rflow
+= cycle_flow
;
918 r_pfedge
->flow
-= cycle_flow
;
925 /* Computes the residual flow for FIXUP_GRAPH by setting the rflow field of
926 the edges. ENTRY and EXIT vertices should not be considered. */
929 compute_residual_flow (fixup_graph_type
*fixup_graph
)
933 fixup_edge_p fedge_list
, pfedge
;
935 gcc_assert (fixup_graph
);
938 fputs ("\ncompute_residual_flow():\n", dump_file
);
940 fnum_edges
= fixup_graph
->num_edges
;
941 fedge_list
= fixup_graph
->edge_list
;
943 for (i
= 0; i
< fnum_edges
; i
++)
945 pfedge
= fedge_list
+ i
;
946 pfedge
->rflow
= pfedge
->max_capacity
- pfedge
->flow
;
947 pfedge
->is_rflow_valid
= true;
948 add_rfixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
, pfedge
->flow
,
954 /* Uses Edmonds-Karp algorithm - BFS to find augmenting path from SOURCE to
955 SINK. The fields in the edge vector in the FIXUP_GRAPH are not modified by
956 this routine. The vector bb_pred in the AUGMENTING_PATH structure is updated
957 to reflect the path found.
958 Returns: 0 if no augmenting path is found, 1 otherwise. */
961 find_augmenting_path (fixup_graph_type
*fixup_graph
,
962 augmenting_path_type
*augmenting_path
, int source
,
967 fixup_vertex_p fvertex_list
, pfvertex
;
969 int *bb_pred
, *is_visited
;
970 queue_type
*queue_list
;
972 gcc_assert (augmenting_path
);
973 bb_pred
= augmenting_path
->bb_pred
;
974 gcc_assert (bb_pred
);
975 is_visited
= augmenting_path
->is_visited
;
976 gcc_assert (is_visited
);
977 queue_list
= &(augmenting_path
->queue_list
);
979 gcc_assert (fixup_graph
);
981 fvertex_list
= fixup_graph
->vertex_list
;
983 for (u
= 0; u
< fixup_graph
->num_vertices
; u
++)
986 init_queue (queue_list
);
987 enqueue (queue_list
, source
);
988 bb_pred
[source
] = -1;
990 while (!is_empty (queue_list
))
992 u
= dequeue (queue_list
);
994 pfvertex
= fvertex_list
+ u
;
995 for (i
= 0; pfvertex
->succ_edges
.iterate (i
, &pfedge
);
998 int dest
= pfedge
->dest
;
999 if ((pfedge
->rflow
> 0) && (is_visited
[dest
] == 0))
1001 enqueue (queue_list
, dest
);
1003 is_visited
[dest
] = 1;
1014 /* Routine to find the maximal flow:
1016 1. Initialize flow to 0
1017 2. Find an augmenting path form source to sink.
1018 3. Send flow equal to the path's residual capacity along the edges of this path.
1019 4. Repeat steps 2 and 3 until no new augmenting path is found.
1022 SOURCE: index of source vertex (input)
1023 SINK: index of sink vertex (input)
1024 FIXUP_GRAPH: adjacency matrix representing the graph. The flow of the edges will be
1025 set to have a valid maximal flow by this routine. (input)
1026 Return: Maximum flow possible. */
1029 find_max_flow (fixup_graph_type
*fixup_graph
, int source
, int sink
)
1032 augmenting_path_type augmenting_path
;
1034 gcov_type max_flow
= 0;
1036 fixup_edge_p fedge_list
, pfedge
, r_pfedge
;
1038 gcc_assert (fixup_graph
);
1040 fnum_edges
= fixup_graph
->num_edges
;
1041 fedge_list
= fixup_graph
->edge_list
;
1043 /* Initialize flow to 0. */
1044 for (i
= 0; i
< fnum_edges
; i
++)
1046 pfedge
= fedge_list
+ i
;
1050 compute_residual_flow (fixup_graph
);
1052 init_augmenting_path (&augmenting_path
, fixup_graph
->num_vertices
);
1054 bb_pred
= augmenting_path
.bb_pred
;
1055 while (find_augmenting_path (fixup_graph
, &augmenting_path
, source
, sink
))
1057 /* Determine the amount by which we can increment the flow. */
1058 gcov_type increment
= CAP_INFINITY
;
1059 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1061 pfedge
= find_fixup_edge (fixup_graph
, bb_pred
[u
], u
);
1062 increment
= MIN (increment
, pfedge
->rflow
);
1064 max_flow
+= increment
;
1066 /* Now increment the flow. EXIT vertex index is 1. */
1067 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1069 pfedge
= find_fixup_edge (fixup_graph
, bb_pred
[u
], u
);
1070 r_pfedge
= find_fixup_edge (fixup_graph
, u
, bb_pred
[u
]);
1074 pfedge
->flow
+= increment
;
1075 pfedge
->rflow
-= increment
;
1076 r_pfedge
->rflow
+= increment
;
1080 /* backward edge. */
1081 gcc_assert (r_pfedge
->type
);
1082 r_pfedge
->rflow
+= increment
;
1083 r_pfedge
->flow
-= increment
;
1084 pfedge
->rflow
-= increment
;
1090 fprintf (dump_file
, "\nDump augmenting path:\n");
1091 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1093 print_basic_block (dump_file
, fixup_graph
, u
);
1094 fprintf (dump_file
, "<-");
1097 "ENTRY (path_capacity=%" PRId64
")\n",
1100 "Network flow is %" PRId64
".\n",
1105 free_augmenting_path (&augmenting_path
);
1107 dump_fixup_graph (dump_file
, fixup_graph
, "After find_max_flow()");
1112 /* Computes the corrected edge and basic block weights using FIXUP_GRAPH
1113 after applying the find_minimum_cost_flow() routine. */
1116 adjust_cfg_counts (fixup_graph_type
*fixup_graph
)
1122 fixup_edge_p pfedge
, pfedge_n
;
1124 gcc_assert (fixup_graph
);
1127 fprintf (dump_file
, "\nadjust_cfg_counts():\n");
1129 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR_FOR_FN (cfun
),
1130 EXIT_BLOCK_PTR_FOR_FN (cfun
), next_bb
)
1137 "BB%d: %" PRId64
"", bb
->index
, bb
->count
);
1139 pfedge
= find_fixup_edge (fixup_graph
, i
, i
+ 1);
1142 bb
->count
+= pfedge
->flow
;
1145 fprintf (dump_file
, " + %" PRId64
"(",
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
, " - %" PRId64
"(",
1162 print_edge (dump_file
, fixup_graph
, i
+ 1,
1163 pfedge
->norm_vertex_index
);
1164 fprintf (dump_file
, ")");
1168 fprintf (dump_file
, " = %" PRId64
"\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: %" PRId64
"",
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
, " + %" PRId64
"(",
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
, " - %" PRId64
"(",
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
, " + %" PRId64
"(",
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
, " = %" PRId64
"\t(%.1f%%)\n",
1239 e
->count
, e
->probability
* 100.0 / REG_BR_PROB_BASE
);
1243 ENTRY_BLOCK_PTR_FOR_FN (cfun
)->count
=
1244 sum_edge_counts (ENTRY_BLOCK_PTR_FOR_FN (cfun
)->succs
);
1245 EXIT_BLOCK_PTR_FOR_FN (cfun
)->count
=
1246 sum_edge_counts (EXIT_BLOCK_PTR_FOR_FN (cfun
)->preds
);
1248 /* Compute edge probabilities. */
1249 FOR_ALL_BB_FN (bb
, cfun
)
1253 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1254 e
->probability
= REG_BR_PROB_BASE
* e
->count
/ bb
->count
;
1259 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1260 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
1264 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1266 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
1267 e
->probability
= REG_BR_PROB_BASE
/ total
;
1274 total
+= EDGE_COUNT (bb
->succs
);
1275 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1276 e
->probability
= REG_BR_PROB_BASE
/ total
;
1283 fprintf (dump_file
, "\nCheck %s() CFG flow conservation:\n",
1284 current_function_name ());
1285 FOR_EACH_BB_FN (bb
, cfun
)
1287 if ((bb
->count
!= sum_edge_counts (bb
->preds
))
1288 || (bb
->count
!= sum_edge_counts (bb
->succs
)))
1291 "BB%d(%" PRId64
") **INVALID**: ",
1292 bb
->index
, bb
->count
);
1294 "******** BB%d(%" PRId64
1295 ") **INVALID**: \n", bb
->index
, bb
->count
);
1296 fprintf (dump_file
, "in_edges=%" PRId64
" ",
1297 sum_edge_counts (bb
->preds
));
1298 fprintf (dump_file
, "out_edges=%" PRId64
"\n",
1299 sum_edge_counts (bb
->succs
));
1306 /* Implements the negative cycle canceling algorithm to compute a minimum cost
1309 1. Find maximal flow.
1310 2. Form residual network
1312 While G contains a negative cost cycle C, reverse the flow on the found cycle
1313 by the minimum residual capacity in that cycle.
1314 4. Form the minimal cost flow
1317 FIXUP_GRAPH - Initial fixup graph.
1318 The flow field is modified to represent the minimum cost flow. */
1321 find_minimum_cost_flow (fixup_graph_type
*fixup_graph
)
1323 /* Holds the index of predecessor in path. */
1325 /* Used to hold the minimum cost cycle. */
1327 /* Used to record the number of iterations of cancel_negative_cycle. */
1329 /* Vector d[i] holds the minimum cost of path from i to sink. */
1333 int new_entry_index
;
1335 gcc_assert (fixup_graph
);
1336 fnum_vertices
= fixup_graph
->num_vertices
;
1337 new_exit_index
= fixup_graph
->new_exit_index
;
1338 new_entry_index
= fixup_graph
->new_entry_index
;
1340 find_max_flow (fixup_graph
, new_entry_index
, new_exit_index
);
1342 /* Initialize the structures for find_negative_cycle(). */
1343 pred
= (int *) xcalloc (fnum_vertices
, sizeof (int));
1344 d
= (gcov_type
*) xcalloc (fnum_vertices
, sizeof (gcov_type
));
1345 cycle
= (int *) xcalloc (fnum_vertices
, sizeof (int));
1347 /* Repeatedly find and cancel negative cost cycles, until
1348 no more negative cycles exist. This also updates the flow field
1349 to represent the minimum cost flow so far. */
1351 while (cancel_negative_cycle (fixup_graph
, pred
, d
, cycle
))
1354 if (iteration
> MAX_ITER (fixup_graph
->num_vertices
,
1355 fixup_graph
->num_edges
))
1360 dump_fixup_graph (dump_file
, fixup_graph
,
1361 "After find_minimum_cost_flow()");
1363 /* Cleanup structures. */
1370 /* Compute the sum of the edge counts in TO_EDGES. */
1373 sum_edge_counts (vec
<edge
, va_gc
> *to_edges
)
1379 FOR_EACH_EDGE (e
, ei
, to_edges
)
1381 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
1389 /* Main routine. Smoothes the initial assigned basic block and edge counts using
1390 a minimum cost flow algorithm, to ensure that the flow consistency rule is
1391 obeyed: sum of outgoing edges = sum of incoming edges for each basic
1395 mcf_smooth_cfg (void)
1397 fixup_graph_type fixup_graph
;
1398 memset (&fixup_graph
, 0, sizeof (fixup_graph
));
1399 create_fixup_graph (&fixup_graph
);
1400 find_minimum_cost_flow (&fixup_graph
);
1401 adjust_cfg_counts (&fixup_graph
);
1402 delete_fixup_graph (&fixup_graph
);