1 /* Routines to implement minimum-cost maximal flow algorithm used to smooth
2 basic block and edge frequency counts.
3 Copyright (C) 2008, 2009
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"
49 #include "basic-block.h"
54 /* CAP_INFINITY: Constant to represent infinite capacity. */
55 #define CAP_INFINITY INTTYPE_MAXIMUM (HOST_WIDEST_INT)
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=" HOST_WIDEST_INT_PRINT_DEC
"/",
209 if (fedge
->max_capacity
== CAP_INFINITY
)
210 fputs ("+oo,", file
);
212 fprintf (file
, "" HOST_WIDEST_INT_PRINT_DEC
",", fedge
->max_capacity
);
215 if (fedge
->is_rflow_valid
)
217 if (fedge
->rflow
== CAP_INFINITY
)
218 fputs (" rflow=+oo.", file
);
220 fprintf (file
, " rflow=" HOST_WIDEST_INT_PRINT_DEC
",", fedge
->rflow
);
223 fprintf (file
, " cost=" HOST_WIDEST_INT_PRINT_DEC
".", 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
;
476 int fnum_edges_after_transform
= n_edges
+ n_basic_blocks
;
478 /* Count the new SOURCE and EXIT vertices to be added. */
479 int fmax_num_vertices
=
480 fnum_vertices_after_transform
+ n_edges
+ n_basic_blocks
+ 2;
482 /* In create_fixup_graph: Each basic block and edge can be split into 3
483 edges. Number of balance edges = n_basic_blocks. So after
485 max_edges = 4 * n_basic_blocks + 3 * n_edges
486 Accounting for residual flow edges
487 max_edges = 2 * (4 * n_basic_blocks + 3 * n_edges)
488 = 8 * n_basic_blocks + 6 * n_edges
489 < 8 * n_basic_blocks + 8 * n_edges. */
490 int fmax_num_edges
= 8 * (n_basic_blocks
+ n_edges
);
492 /* Initial num of vertices in the fixup graph. */
493 fixup_graph
->num_vertices
= n_basic_blocks
;
495 /* Fixup graph vertex list. */
496 fixup_graph
->vertex_list
=
497 (fixup_vertex_p
) xcalloc (fmax_num_vertices
, sizeof (fixup_vertex_type
));
499 /* Fixup graph edge list. */
500 fixup_graph
->edge_list
=
501 (fixup_edge_p
) xcalloc (fmax_num_edges
, sizeof (fixup_edge_type
));
504 (gcov_type
*) xcalloc (1 + fnum_vertices_after_transform
,
507 /* Compute constants b, k_pos, k_neg used in the cost function calculation.
508 b = sqrt(avg_vertex_weight(cfg)); k_pos = b; k_neg = 50b. */
509 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
510 total_vertex_weight
+= bb
->count
;
512 sqrt_avg_vertex_weight
= mcf_sqrt (total_vertex_weight
/ n_basic_blocks
);
514 k_pos
= K_POS (sqrt_avg_vertex_weight
);
515 k_neg
= K_NEG (sqrt_avg_vertex_weight
);
517 /* 1. Vertex Transformation: Split each vertex v into two vertices v' and v'',
518 connected by an edge e from v' to v''. w(e) = w(v). */
521 fprintf (dump_file
, "\nVertex transformation:\n");
523 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
525 /* v'->v'': index1->(index1+1). */
527 fcost
= (gcov_type
) COST (k_pos
, bb
->count
);
528 add_fixup_edge (fixup_graph
, i
, i
+ 1, VERTEX_SPLIT_EDGE
, bb
->count
,
529 fcost
, CAP_INFINITY
);
530 fixup_graph
->num_vertices
++;
532 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
534 /* Edges with ignore attribute set should be treated like they don't
536 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
538 j
= 2 * e
->dest
->index
;
539 fcost
= (gcov_type
) COST (k_pos
, e
->count
);
540 add_fixup_edge (fixup_graph
, i
+ 1, j
, REDIRECT_EDGE
, e
->count
, fcost
,
545 /* After vertex transformation. */
546 gcc_assert (fixup_graph
->num_vertices
== fnum_vertices_after_transform
);
547 /* Redirect edges are not added for edges with ignore attribute. */
548 gcc_assert (fixup_graph
->num_edges
<= fnum_edges_after_transform
);
550 fnum_edges_after_transform
= fixup_graph
->num_edges
;
552 /* 2. Initialize D(v). */
553 for (i
= 0; i
< fnum_edges_after_transform
; i
++)
555 pfedge
= fixup_graph
->edge_list
+ i
;
556 diff_out_in
[pfedge
->src
] += pfedge
->weight
;
557 diff_out_in
[pfedge
->dest
] -= pfedge
->weight
;
560 /* Entry block - vertex indices 0, 1; EXIT block - vertex indices 2, 3. */
561 for (i
= 0; i
<= 3; i
++)
564 /* 3. Add reverse edges: needed to decrease counts during smoothing. */
566 fprintf (dump_file
, "\nReverse edges:\n");
567 for (i
= 0; i
< fnum_edges_after_transform
; i
++)
569 pfedge
= fixup_graph
->edge_list
+ i
;
570 if ((pfedge
->src
== 0) || (pfedge
->src
== 2))
572 r_pfedge
= find_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
);
573 if (!r_pfedge
&& pfedge
->weight
)
575 /* Skip adding reverse edges for edges with w(e) = 0, as its maximum
577 fcost
= (gcov_type
) COST (k_neg
, pfedge
->weight
);
578 add_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
,
579 REVERSE_EDGE
, 0, fcost
, pfedge
->weight
);
583 /* 4. Create single source and sink. Connect new source vertex s' to function
584 entry block. Connect sink vertex t' to function exit. */
586 fprintf (dump_file
, "\ns'->S, T->t':\n");
588 new_entry_index
= fixup_graph
->new_entry_index
= fixup_graph
->num_vertices
;
589 fixup_graph
->num_vertices
++;
590 /* Set supply_value to 1 to avoid zero count function ENTRY. */
591 add_fixup_edge (fixup_graph
, new_entry_index
, ENTRY_BLOCK
, SOURCE_CONNECT_EDGE
,
592 1 /* supply_value */, 0, 1 /* supply_value */);
594 /* Create new exit with EXIT_BLOCK as single pred. */
595 new_exit_index
= fixup_graph
->new_exit_index
= fixup_graph
->num_vertices
;
596 fixup_graph
->num_vertices
++;
597 add_fixup_edge (fixup_graph
, 2 * EXIT_BLOCK
+ 1, new_exit_index
,
599 0 /* demand_value */, 0, 0 /* demand_value */);
601 /* Connect vertices with unbalanced D(v) to source/sink. */
603 fprintf (dump_file
, "\nD(v) balance:\n");
604 /* Skip vertices for ENTRY (0, 1) and EXIT (2,3) blocks, so start with i = 4.
605 diff_out_in[v''] will be 0, so skip v'' vertices, hence i += 2. */
606 for (i
= 4; i
< new_entry_index
; i
+= 2)
608 if (diff_out_in
[i
] > 0)
610 add_fixup_edge (fixup_graph
, i
, new_exit_index
, BALANCE_EDGE
, 0, 0,
612 demand_value
+= diff_out_in
[i
];
614 else if (diff_out_in
[i
] < 0)
616 add_fixup_edge (fixup_graph
, new_entry_index
, i
, BALANCE_EDGE
, 0, 0,
618 supply_value
-= diff_out_in
[i
];
622 /* Set supply = demand. */
625 fprintf (dump_file
, "\nAdjust supply and demand:\n");
626 fprintf (dump_file
, "supply_value=" HOST_WIDEST_INT_PRINT_DEC
"\n",
628 fprintf (dump_file
, "demand_value=" HOST_WIDEST_INT_PRINT_DEC
"\n",
632 if (demand_value
> supply_value
)
634 pfedge
= find_fixup_edge (fixup_graph
, new_entry_index
, ENTRY_BLOCK
);
635 pfedge
->max_capacity
+= (demand_value
- supply_value
);
639 pfedge
= find_fixup_edge (fixup_graph
, 2 * EXIT_BLOCK
+ 1, new_exit_index
);
640 pfedge
->max_capacity
+= (supply_value
- demand_value
);
643 /* 6. Normalize edges: remove anti-parallel edges. Anti-parallel edges are
644 created by the vertex transformation step from self-edges in the original
645 CFG and by the reverse edges added earlier. */
647 fprintf (dump_file
, "\nNormalize edges:\n");
649 fnum_edges
= fixup_graph
->num_edges
;
650 fedge_list
= fixup_graph
->edge_list
;
652 for (i
= 0; i
< fnum_edges
; i
++)
654 pfedge
= fedge_list
+ i
;
655 r_pfedge
= find_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
);
656 if (((pfedge
->type
== VERTEX_SPLIT_EDGE
)
657 || (pfedge
->type
== REDIRECT_EDGE
)) && r_pfedge
)
659 new_index
= fixup_graph
->num_vertices
;
660 fixup_graph
->num_vertices
++;
664 fprintf (dump_file
, "\nAnti-parallel edge:\n");
665 dump_fixup_edge (dump_file
, fixup_graph
, pfedge
);
666 dump_fixup_edge (dump_file
, fixup_graph
, r_pfedge
);
667 fprintf (dump_file
, "New vertex is %d.\n", new_index
);
668 fprintf (dump_file
, "------------------\n");
672 pfedge
->norm_vertex_index
= new_index
;
675 fprintf (dump_file
, "After normalization:\n");
676 dump_fixup_edge (dump_file
, fixup_graph
, pfedge
);
679 /* Add a new fixup edge: new_index->src. */
680 add_fixup_edge (fixup_graph
, new_index
, pfedge
->src
,
681 REVERSE_NORMALIZED_EDGE
, 0, r_pfedge
->cost
,
682 r_pfedge
->max_capacity
);
683 gcc_assert (fixup_graph
->num_vertices
<= fmax_num_vertices
);
685 /* Edge: r_pfedge->src -> r_pfedge->dest
686 ==> r_pfedge->src -> new_index. */
687 r_pfedge
->dest
= new_index
;
688 r_pfedge
->type
= REVERSE_NORMALIZED_EDGE
;
689 r_pfedge
->cost
= pfedge
->cost
;
690 r_pfedge
->max_capacity
= pfedge
->max_capacity
;
692 dump_fixup_edge (dump_file
, fixup_graph
, r_pfedge
);
697 dump_fixup_graph (dump_file
, fixup_graph
, "After create_fixup_graph()");
704 /* Allocates space for the structures in AUGMENTING_PATH. The space needed is
705 proportional to the number of nodes in the graph, which is given by
709 init_augmenting_path (augmenting_path_type
*augmenting_path
, int graph_size
)
711 augmenting_path
->queue_list
.queue
= (int *)
712 xcalloc (graph_size
+ 2, sizeof (int));
713 augmenting_path
->queue_list
.size
= graph_size
+ 2;
714 augmenting_path
->bb_pred
= (int *) xcalloc (graph_size
, sizeof (int));
715 augmenting_path
->is_visited
= (int *) xcalloc (graph_size
, sizeof (int));
718 /* Free the structures in AUGMENTING_PATH. */
720 free_augmenting_path (augmenting_path_type
*augmenting_path
)
722 free (augmenting_path
->queue_list
.queue
);
723 free (augmenting_path
->bb_pred
);
724 free (augmenting_path
->is_visited
);
728 /* Queue routines. Assumes queue will never overflow. */
731 init_queue (queue_type
*queue_list
)
733 gcc_assert (queue_list
);
734 queue_list
->head
= 0;
735 queue_list
->tail
= 0;
738 /* Return true if QUEUE_LIST is empty. */
740 is_empty (queue_type
*queue_list
)
742 return (queue_list
->head
== queue_list
->tail
);
745 /* Insert element X into QUEUE_LIST. */
747 enqueue (queue_type
*queue_list
, int x
)
749 gcc_assert (queue_list
->tail
< queue_list
->size
);
750 queue_list
->queue
[queue_list
->tail
] = x
;
751 (queue_list
->tail
)++;
754 /* Return the first element in QUEUE_LIST. */
756 dequeue (queue_type
*queue_list
)
759 gcc_assert (queue_list
->head
>= 0);
760 x
= queue_list
->queue
[queue_list
->head
];
761 (queue_list
->head
)++;
766 /* Finds a negative cycle in the residual network using
767 the Bellman-Ford algorithm. The flow on the found cycle is reversed by the
768 minimum residual capacity of that cycle. ENTRY and EXIT vertices are not
772 FIXUP_GRAPH - Residual graph (input/output)
773 The following are allocated/freed by the caller:
774 PI - Vector to hold predecessors in path (pi = pred index)
775 D - D[I] holds minimum cost of path from i to sink
776 CYCLE - Vector to hold the minimum cost cycle
779 true if a negative cycle was found, false otherwise. */
782 cancel_negative_cycle (fixup_graph_type
*fixup_graph
,
783 int *pi
, gcov_type
*d
, int *cycle
)
786 int fnum_vertices
, fnum_edges
;
787 fixup_edge_p fedge_list
, pfedge
, r_pfedge
;
788 bool found_cycle
= false;
789 int cycle_start
= 0, cycle_end
= 0;
790 gcov_type sum_cost
= 0, cycle_flow
= 0;
792 bool propagated
= false;
794 gcc_assert (fixup_graph
);
795 fnum_vertices
= fixup_graph
->num_vertices
;
796 fnum_edges
= fixup_graph
->num_edges
;
797 fedge_list
= fixup_graph
->edge_list
;
798 new_entry_index
= fixup_graph
->new_entry_index
;
802 for (i
= 1; i
< fnum_vertices
; i
++)
811 for (k
= 1; k
< fnum_vertices
; k
++)
814 for (i
= 0; i
< fnum_edges
; i
++)
816 pfedge
= fedge_list
+ i
;
817 if (pfedge
->src
== new_entry_index
)
819 if (pfedge
->is_rflow_valid
&& pfedge
->rflow
820 && d
[pfedge
->src
] != CAP_INFINITY
821 && (d
[pfedge
->dest
] > d
[pfedge
->src
] + pfedge
->cost
))
823 d
[pfedge
->dest
] = d
[pfedge
->src
] + pfedge
->cost
;
824 pi
[pfedge
->dest
] = pfedge
->src
;
833 /* No negative cycles exist. */
837 for (i
= 0; i
< fnum_edges
; i
++)
839 pfedge
= fedge_list
+ i
;
840 if (pfedge
->src
== new_entry_index
)
842 if (pfedge
->is_rflow_valid
&& pfedge
->rflow
843 && d
[pfedge
->src
] != CAP_INFINITY
844 && (d
[pfedge
->dest
] > d
[pfedge
->src
] + pfedge
->cost
))
854 /* Augment the cycle with the cycle's minimum residual capacity. */
856 cycle
[0] = pfedge
->dest
;
859 for (i
= 1; i
< fnum_vertices
; i
++)
863 for (k
= 0; k
< i
; k
++)
867 /* cycle[k] -> ... -> cycle[i]. */
878 gcc_assert (cycle
[cycle_start
] == cycle
[cycle_end
]);
880 fprintf (dump_file
, "\nNegative cycle length is %d:\n",
881 cycle_end
- cycle_start
);
884 cycle_flow
= CAP_INFINITY
;
885 for (k
= cycle_start
; k
< cycle_end
; k
++)
887 pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
+ 1], cycle
[k
]);
888 cycle_flow
= MIN (cycle_flow
, pfedge
->rflow
);
889 sum_cost
+= pfedge
->cost
;
891 fprintf (dump_file
, "%d ", cycle
[k
]);
896 fprintf (dump_file
, "%d", cycle
[k
]);
898 ": (" HOST_WIDEST_INT_PRINT_DEC
", " HOST_WIDEST_INT_PRINT_DEC
899 ")\n", sum_cost
, cycle_flow
);
901 "Augment cycle with " HOST_WIDEST_INT_PRINT_DEC
"\n",
905 for (k
= cycle_start
; k
< cycle_end
; k
++)
907 pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
+ 1], cycle
[k
]);
908 r_pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
], cycle
[k
+ 1]);
909 pfedge
->rflow
-= cycle_flow
;
911 pfedge
->flow
+= cycle_flow
;
912 r_pfedge
->rflow
+= cycle_flow
;
914 r_pfedge
->flow
-= cycle_flow
;
921 /* Computes the residual flow for FIXUP_GRAPH by setting the rflow field of
922 the edges. ENTRY and EXIT vertices should not be considered. */
925 compute_residual_flow (fixup_graph_type
*fixup_graph
)
929 fixup_edge_p fedge_list
, pfedge
;
931 gcc_assert (fixup_graph
);
934 fputs ("\ncompute_residual_flow():\n", dump_file
);
936 fnum_edges
= fixup_graph
->num_edges
;
937 fedge_list
= fixup_graph
->edge_list
;
939 for (i
= 0; i
< fnum_edges
; i
++)
941 pfedge
= fedge_list
+ i
;
942 pfedge
->rflow
= pfedge
->max_capacity
- pfedge
->flow
;
943 pfedge
->is_rflow_valid
= true;
944 add_rfixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
, pfedge
->flow
,
950 /* Uses Edmonds-Karp algorithm - BFS to find augmenting path from SOURCE to
951 SINK. The fields in the edge vector in the FIXUP_GRAPH are not modified by
952 this routine. The vector bb_pred in the AUGMENTING_PATH structure is updated
953 to reflect the path found.
954 Returns: 0 if no augmenting path is found, 1 otherwise. */
957 find_augmenting_path (fixup_graph_type
*fixup_graph
,
958 augmenting_path_type
*augmenting_path
, int source
,
963 fixup_vertex_p fvertex_list
, pfvertex
;
965 int *bb_pred
, *is_visited
;
966 queue_type
*queue_list
;
968 gcc_assert (augmenting_path
);
969 bb_pred
= augmenting_path
->bb_pred
;
970 gcc_assert (bb_pred
);
971 is_visited
= augmenting_path
->is_visited
;
972 gcc_assert (is_visited
);
973 queue_list
= &(augmenting_path
->queue_list
);
975 gcc_assert (fixup_graph
);
977 fvertex_list
= fixup_graph
->vertex_list
;
979 for (u
= 0; u
< fixup_graph
->num_vertices
; u
++)
982 init_queue (queue_list
);
983 enqueue (queue_list
, source
);
984 bb_pred
[source
] = -1;
986 while (!is_empty (queue_list
))
988 u
= dequeue (queue_list
);
990 pfvertex
= fvertex_list
+ u
;
991 for (i
= 0; pfvertex
->succ_edges
.iterate (i
, &pfedge
);
994 int dest
= pfedge
->dest
;
995 if ((pfedge
->rflow
> 0) && (is_visited
[dest
] == 0))
997 enqueue (queue_list
, dest
);
999 is_visited
[dest
] = 1;
1010 /* Routine to find the maximal flow:
1012 1. Initialize flow to 0
1013 2. Find an augmenting path form source to sink.
1014 3. Send flow equal to the path's residual capacity along the edges of this path.
1015 4. Repeat steps 2 and 3 until no new augmenting path is found.
1018 SOURCE: index of source vertex (input)
1019 SINK: index of sink vertex (input)
1020 FIXUP_GRAPH: adjacency matrix representing the graph. The flow of the edges will be
1021 set to have a valid maximal flow by this routine. (input)
1022 Return: Maximum flow possible. */
1025 find_max_flow (fixup_graph_type
*fixup_graph
, int source
, int sink
)
1028 augmenting_path_type augmenting_path
;
1030 gcov_type max_flow
= 0;
1032 fixup_edge_p fedge_list
, pfedge
, r_pfedge
;
1034 gcc_assert (fixup_graph
);
1036 fnum_edges
= fixup_graph
->num_edges
;
1037 fedge_list
= fixup_graph
->edge_list
;
1039 /* Initialize flow to 0. */
1040 for (i
= 0; i
< fnum_edges
; i
++)
1042 pfedge
= fedge_list
+ i
;
1046 compute_residual_flow (fixup_graph
);
1048 init_augmenting_path (&augmenting_path
, fixup_graph
->num_vertices
);
1050 bb_pred
= augmenting_path
.bb_pred
;
1051 while (find_augmenting_path (fixup_graph
, &augmenting_path
, source
, sink
))
1053 /* Determine the amount by which we can increment the flow. */
1054 gcov_type increment
= CAP_INFINITY
;
1055 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1057 pfedge
= find_fixup_edge (fixup_graph
, bb_pred
[u
], u
);
1058 increment
= MIN (increment
, pfedge
->rflow
);
1060 max_flow
+= increment
;
1062 /* Now increment the flow. EXIT vertex index is 1. */
1063 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1065 pfedge
= find_fixup_edge (fixup_graph
, bb_pred
[u
], u
);
1066 r_pfedge
= find_fixup_edge (fixup_graph
, u
, bb_pred
[u
]);
1070 pfedge
->flow
+= increment
;
1071 pfedge
->rflow
-= increment
;
1072 r_pfedge
->rflow
+= increment
;
1076 /* backward edge. */
1077 gcc_assert (r_pfedge
->type
);
1078 r_pfedge
->rflow
+= increment
;
1079 r_pfedge
->flow
-= increment
;
1080 pfedge
->rflow
-= increment
;
1086 fprintf (dump_file
, "\nDump augmenting path:\n");
1087 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1089 print_basic_block (dump_file
, fixup_graph
, u
);
1090 fprintf (dump_file
, "<-");
1093 "ENTRY (path_capacity=" HOST_WIDEST_INT_PRINT_DEC
")\n",
1096 "Network flow is " HOST_WIDEST_INT_PRINT_DEC
".\n",
1101 free_augmenting_path (&augmenting_path
);
1103 dump_fixup_graph (dump_file
, fixup_graph
, "After find_max_flow()");
1108 /* Computes the corrected edge and basic block weights using FIXUP_GRAPH
1109 after applying the find_minimum_cost_flow() routine. */
1112 adjust_cfg_counts (fixup_graph_type
*fixup_graph
)
1118 fixup_edge_p pfedge
, pfedge_n
;
1120 gcc_assert (fixup_graph
);
1123 fprintf (dump_file
, "\nadjust_cfg_counts():\n");
1125 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, EXIT_BLOCK_PTR
, next_bb
)
1132 "BB%d: " HOST_WIDEST_INT_PRINT_DEC
"", bb
->index
, bb
->count
);
1134 pfedge
= find_fixup_edge (fixup_graph
, i
, i
+ 1);
1137 bb
->count
+= pfedge
->flow
;
1140 fprintf (dump_file
, " + " HOST_WIDEST_INT_PRINT_DEC
"(",
1142 print_edge (dump_file
, fixup_graph
, i
, i
+ 1);
1143 fprintf (dump_file
, ")");
1148 find_fixup_edge (fixup_graph
, i
+ 1, pfedge
->norm_vertex_index
);
1149 /* Deduct flow from normalized reverse edge. */
1150 if (pfedge
->norm_vertex_index
&& pfedge_n
->flow
)
1152 bb
->count
-= pfedge_n
->flow
;
1155 fprintf (dump_file
, " - " HOST_WIDEST_INT_PRINT_DEC
"(",
1157 print_edge (dump_file
, fixup_graph
, i
+ 1,
1158 pfedge
->norm_vertex_index
);
1159 fprintf (dump_file
, ")");
1163 fprintf (dump_file
, " = " HOST_WIDEST_INT_PRINT_DEC
"\n", bb
->count
);
1166 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1168 /* Treat edges with ignore attribute set as if they don't exist. */
1169 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
1172 j
= 2 * e
->dest
->index
;
1174 fprintf (dump_file
, "%d->%d: " HOST_WIDEST_INT_PRINT_DEC
"",
1175 bb
->index
, e
->dest
->index
, e
->count
);
1177 pfedge
= find_fixup_edge (fixup_graph
, i
+ 1, j
);
1179 if (bb
->index
!= e
->dest
->index
)
1181 /* Non-self edge. */
1184 e
->count
+= pfedge
->flow
;
1187 fprintf (dump_file
, " + " HOST_WIDEST_INT_PRINT_DEC
"(",
1189 print_edge (dump_file
, fixup_graph
, i
+ 1, j
);
1190 fprintf (dump_file
, ")");
1195 find_fixup_edge (fixup_graph
, j
, pfedge
->norm_vertex_index
);
1196 /* Deduct flow from normalized reverse edge. */
1197 if (pfedge
->norm_vertex_index
&& pfedge_n
->flow
)
1199 e
->count
-= pfedge_n
->flow
;
1202 fprintf (dump_file
, " - " HOST_WIDEST_INT_PRINT_DEC
"(",
1204 print_edge (dump_file
, fixup_graph
, j
,
1205 pfedge
->norm_vertex_index
);
1206 fprintf (dump_file
, ")");
1212 /* Handle self edges. Self edge is split with a normalization
1213 vertex. Here i=j. */
1214 pfedge
= find_fixup_edge (fixup_graph
, j
, i
+ 1);
1216 find_fixup_edge (fixup_graph
, i
+ 1, pfedge
->norm_vertex_index
);
1217 e
->count
+= pfedge_n
->flow
;
1218 bb
->count
+= pfedge_n
->flow
;
1221 fprintf (dump_file
, "(self edge)");
1222 fprintf (dump_file
, " + " HOST_WIDEST_INT_PRINT_DEC
"(",
1224 print_edge (dump_file
, fixup_graph
, i
+ 1,
1225 pfedge
->norm_vertex_index
);
1226 fprintf (dump_file
, ")");
1231 e
->probability
= REG_BR_PROB_BASE
* e
->count
/ bb
->count
;
1233 fprintf (dump_file
, " = " HOST_WIDEST_INT_PRINT_DEC
"\t(%.1f%%)\n",
1234 e
->count
, e
->probability
* 100.0 / REG_BR_PROB_BASE
);
1238 ENTRY_BLOCK_PTR
->count
= sum_edge_counts (ENTRY_BLOCK_PTR
->succs
);
1239 EXIT_BLOCK_PTR
->count
= sum_edge_counts (EXIT_BLOCK_PTR
->preds
);
1241 /* Compute edge probabilities. */
1246 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1247 e
->probability
= REG_BR_PROB_BASE
* e
->count
/ bb
->count
;
1252 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1253 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
1257 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1259 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
1260 e
->probability
= REG_BR_PROB_BASE
/ total
;
1267 total
+= EDGE_COUNT (bb
->succs
);
1268 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1269 e
->probability
= REG_BR_PROB_BASE
/ total
;
1276 fprintf (dump_file
, "\nCheck %s() CFG flow conservation:\n",
1277 current_function_name ());
1280 if ((bb
->count
!= sum_edge_counts (bb
->preds
))
1281 || (bb
->count
!= sum_edge_counts (bb
->succs
)))
1284 "BB%d(" HOST_WIDEST_INT_PRINT_DEC
") **INVALID**: ",
1285 bb
->index
, bb
->count
);
1287 "******** BB%d(" HOST_WIDEST_INT_PRINT_DEC
1288 ") **INVALID**: \n", bb
->index
, bb
->count
);
1289 fprintf (dump_file
, "in_edges=" HOST_WIDEST_INT_PRINT_DEC
" ",
1290 sum_edge_counts (bb
->preds
));
1291 fprintf (dump_file
, "out_edges=" HOST_WIDEST_INT_PRINT_DEC
"\n",
1292 sum_edge_counts (bb
->succs
));
1299 /* Implements the negative cycle canceling algorithm to compute a minimum cost
1302 1. Find maximal flow.
1303 2. Form residual network
1305 While G contains a negative cost cycle C, reverse the flow on the found cycle
1306 by the minimum residual capacity in that cycle.
1307 4. Form the minimal cost flow
1310 FIXUP_GRAPH - Initial fixup graph.
1311 The flow field is modified to represent the minimum cost flow. */
1314 find_minimum_cost_flow (fixup_graph_type
*fixup_graph
)
1316 /* Holds the index of predecessor in path. */
1318 /* Used to hold the minimum cost cycle. */
1320 /* Used to record the number of iterations of cancel_negative_cycle. */
1322 /* Vector d[i] holds the minimum cost of path from i to sink. */
1326 int new_entry_index
;
1328 gcc_assert (fixup_graph
);
1329 fnum_vertices
= fixup_graph
->num_vertices
;
1330 new_exit_index
= fixup_graph
->new_exit_index
;
1331 new_entry_index
= fixup_graph
->new_entry_index
;
1333 find_max_flow (fixup_graph
, new_entry_index
, new_exit_index
);
1335 /* Initialize the structures for find_negative_cycle(). */
1336 pred
= (int *) xcalloc (fnum_vertices
, sizeof (int));
1337 d
= (gcov_type
*) xcalloc (fnum_vertices
, sizeof (gcov_type
));
1338 cycle
= (int *) xcalloc (fnum_vertices
, sizeof (int));
1340 /* Repeatedly find and cancel negative cost cycles, until
1341 no more negative cycles exist. This also updates the flow field
1342 to represent the minimum cost flow so far. */
1344 while (cancel_negative_cycle (fixup_graph
, pred
, d
, cycle
))
1347 if (iteration
> MAX_ITER (fixup_graph
->num_vertices
,
1348 fixup_graph
->num_edges
))
1353 dump_fixup_graph (dump_file
, fixup_graph
,
1354 "After find_minimum_cost_flow()");
1356 /* Cleanup structures. */
1363 /* Compute the sum of the edge counts in TO_EDGES. */
1366 sum_edge_counts (vec
<edge
, va_gc
> *to_edges
)
1372 FOR_EACH_EDGE (e
, ei
, to_edges
)
1374 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
1382 /* Main routine. Smoothes the initial assigned basic block and edge counts using
1383 a minimum cost flow algorithm, to ensure that the flow consistency rule is
1384 obeyed: sum of outgoing edges = sum of incoming edges for each basic
1388 mcf_smooth_cfg (void)
1390 fixup_graph_type fixup_graph
;
1391 memset (&fixup_graph
, 0, sizeof (fixup_graph
));
1392 create_fixup_graph (&fixup_graph
);
1393 find_minimum_cost_flow (&fixup_graph
);
1394 adjust_cfg_counts (&fixup_graph
);
1395 delete_fixup_graph (&fixup_graph
);