control_flow_insn_p takes an insn
[official-gcc.git] / gcc / mcf.c
blob709092352f05af5c5599bd175f3a0934c5166634
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
11 version.
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
16 for more details.
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/>. */
22 /* References:
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;
28 HiPEAC '08.
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.
35 4. Repeat:
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
38 cycle.
39 5. Form the minimal cost flow
40 f(u,v) = rf(v, u).
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). */
45 #include "config.h"
46 #include "system.h"
47 #include "coretypes.h"
48 #include "basic-block.h"
49 #include "gcov-io.h"
50 #include "profile.h"
51 #include "dumpfile.h"
53 /* CAP_INFINITY: Constant to represent infinite capacity. */
54 #define CAP_INFINITY INTTYPE_MAXIMUM (int64_t)
56 /* COST FUNCTION. */
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)))
63 typedef enum
65 INVALID_EDGE,
66 VERTEX_SPLIT_EDGE, /* Edge to represent vertex with w(e) = w(v). */
67 REDIRECT_EDGE, /* Edge after vertex transformation. */
68 REVERSE_EDGE,
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. */
74 } edge_type;
76 /* Structure to represent an edge in the fixup graph. */
77 typedef struct fixup_edge_d
79 int src;
80 int dest;
81 /* Flag denoting type of edge and attributes for the flow field. */
82 edge_type type;
83 bool is_rflow_valid;
84 /* Index to the normalization vertex added for this edge. */
85 int norm_vertex_index;
86 /* Flow for this edge. */
87 gcov_type flow;
88 /* Residual flow for this edge - used during negative cycle canceling. */
89 gcov_type rflow;
90 gcov_type weight;
91 gcov_type cost;
92 gcov_type max_capacity;
93 } fixup_edge_type;
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;
102 } fixup_vertex_type;
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. */
110 int num_vertices;
111 /* Current number of edges for the graph. */
112 int num_edges;
113 /* Index of new entry vertex. */
114 int new_entry_index;
115 /* Index of new exit vertex. */
116 int new_exit_index;
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;
121 } fixup_graph_type;
123 typedef struct queue_d
125 int *queue;
126 int head;
127 int tail;
128 int size;
129 } queue_type;
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. */
137 int *bb_pred;
138 /* Vector that indicates if basic block i has been visited. */
139 int *is_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. */
149 static void
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);
164 else
166 fprintf (file, "%d", n / 2);
167 if (n % 2)
168 fputs ("''", file);
169 else
170 fputs ("'", file);
175 /* Print edge S->D for given fixup_graph with n' and n'' format.
176 PARAMETERS:
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). */
181 static void
182 print_edge (FILE *file, fixup_graph_type *fixup_graph, int s, int d)
184 print_basic_block (file, fixup_graph, s);
185 fputs ("->", file);
186 print_basic_block (file, fixup_graph, d);
190 /* Dump out the attributes of a given edge FEDGE in the fixup_graph to a
191 file. */
192 static void
193 dump_fixup_edge (FILE *file, fixup_graph_type *fixup_graph, fixup_edge_p fedge)
195 if (!fedge)
197 fputs ("NULL fixup graph edge.\n", file);
198 return;
201 print_edge (file, fixup_graph, fedge->src, fedge->dest);
202 fputs (": ", file);
204 if (fedge->type)
206 fprintf (file, "flow/capacity=%"PRId64 "/",
207 fedge->flow);
208 if (fedge->max_capacity == CAP_INFINITY)
209 fputs ("+oo,", file);
210 else
211 fprintf (file, "%"PRId64 ",", fedge->max_capacity);
214 if (fedge->is_rflow_valid)
216 if (fedge->rflow == CAP_INFINITY)
217 fputs (" rflow=+oo.", file);
218 else
219 fprintf (file, " rflow=%"PRId64 ",", fedge->rflow);
222 fprintf (file, " cost=%"PRId64 ".", fedge->cost);
224 fprintf (file, "\t(%d->%d)", fedge->src, fedge->dest);
226 if (fedge->type)
228 switch (fedge->type)
230 case VERTEX_SPLIT_EDGE:
231 fputs (" @VERTEX_SPLIT_EDGE", file);
232 break;
234 case REDIRECT_EDGE:
235 fputs (" @REDIRECT_EDGE", file);
236 break;
238 case SOURCE_CONNECT_EDGE:
239 fputs (" @SOURCE_CONNECT_EDGE", file);
240 break;
242 case SINK_CONNECT_EDGE:
243 fputs (" @SINK_CONNECT_EDGE", file);
244 break;
246 case REVERSE_EDGE:
247 fputs (" @REVERSE_EDGE", file);
248 break;
250 case BALANCE_EDGE:
251 fputs (" @BALANCE_EDGE", file);
252 break;
254 case REDIRECT_NORMALIZED_EDGE:
255 case REVERSE_NORMALIZED_EDGE:
256 fputs (" @NORMALIZED_EDGE", file);
257 break;
259 default:
260 fputs (" @INVALID_EDGE", file);
261 break;
264 fputs ("\n", 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. */
271 static void
272 dump_fixup_graph (FILE *file, fixup_graph_type *fixup_graph, const char *msg)
274 int i, j;
275 int fnum_vertices, fnum_edges;
277 fixup_vertex_p fvertex_list, pfvertex;
278 fixup_edge_p pfedge;
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);
287 fprintf (file,
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);
298 j++)
300 /* Distinguish forward edges and backward edges in the residual flow
301 network. */
302 if (pfedge->type)
303 fputs ("(f) ", file);
304 else if (pfedge->is_rflow_valid)
305 fputs ("(b) ", file);
306 dump_fixup_edge (file, fixup_graph, pfedge);
310 fputs ("\n", file);
314 /* Utility routines. */
315 /* ln() implementation: approximate calculation. Returns ln of X. */
317 static double
318 mcf_ln (double x)
320 #define E 2.71828
321 int l = 1;
322 double m = E;
324 gcc_assert (x >= 0);
326 while (m < x)
328 m *= E;
329 l++;
332 return l;
336 /* sqrt() implementation: based on open source QUAKE3 code (magic sqrt
337 implementation) by John Carmack. Returns sqrt of X. */
339 static double
340 mcf_sqrt (double x)
342 #define MAGIC_CONST1 0x1fbcf800
343 #define MAGIC_CONST2 0x5f3759df
344 union {
345 int intPart;
346 float floatPart;
347 } convertor, convertor2;
349 gcc_assert (x >= 0);
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. */
364 static fixup_edge_p
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++;
373 if (dump_file)
374 dump_fixup_edge (dump_file, fixup_graph, curr_edge);
375 curr_vertex->succ_edges.safe_push (curr_edge);
376 return 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. */
383 static void
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. */
398 static void
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. */
413 static fixup_edge_p
414 find_fixup_edge (fixup_graph_type *fixup_graph, int src, int dest)
416 int j;
417 fixup_edge_p pfedge;
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);
425 j++)
426 if (pfedge->dest == dest)
427 return pfedge;
429 return NULL;
433 /* Cleanup routine to free structures in FIXUP_GRAPH. */
435 static void
436 delete_fixup_graph (fixup_graph_type *fixup_graph)
438 int i;
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. */
452 static void
453 create_fixup_graph (fixup_graph_type *fixup_graph)
455 double sqrt_avg_vertex_weight = 0;
456 double total_vertex_weight = 0;
457 double k_pos = 0;
458 double k_neg = 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;
462 gcov_type fcost = 0;
463 int new_entry_index = 0, new_exit_index = 0;
464 int i = 0, j = 0;
465 int new_index = 0;
466 basic_block bb;
467 edge e;
468 edge_iterator ei;
469 fixup_edge_p pfedge, r_pfedge;
470 fixup_edge_p fedge_list;
471 int fnum_edges;
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
485 create_fixup_graph:
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));
505 diff_out_in =
506 (gcov_type *) xcalloc (1 + fnum_vertices_after_transform,
507 sizeof (gcov_type));
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). */
523 if (dump_file)
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). */
529 i = 2 * bb->index;
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
538 exist. */
539 if (EDGE_INFO (e) && EDGE_INFO (e)->ignore)
540 continue;
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,
544 CAP_INFINITY);
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++)
565 diff_out_in[i] = 0;
567 /* 3. Add reverse edges: needed to decrease counts during smoothing. */
568 if (dump_file)
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))
574 continue;
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
579 capacity is 0. */
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. */
588 if (dump_file)
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,
601 SINK_CONNECT_EDGE,
602 0 /* demand_value */, 0, 0 /* demand_value */);
604 /* Connect vertices with unbalanced D(v) to source/sink. */
605 if (dump_file)
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,
614 diff_out_in[i]);
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,
620 -diff_out_in[i]);
621 supply_value -= diff_out_in[i];
625 /* Set supply = demand. */
626 if (dump_file)
628 fprintf (dump_file, "\nAdjust supply and demand:\n");
629 fprintf (dump_file, "supply_value=%"PRId64 "\n",
630 supply_value);
631 fprintf (dump_file, "demand_value=%"PRId64 "\n",
632 demand_value);
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);
640 else
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. */
649 if (dump_file)
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++;
665 if (dump_file)
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");
674 pfedge->cost /= 2;
675 pfedge->norm_vertex_index = new_index;
676 if (dump_file)
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;
694 if (dump_file)
695 dump_fixup_edge (dump_file, fixup_graph, r_pfedge);
699 if (dump_file)
700 dump_fixup_graph (dump_file, fixup_graph, "After create_fixup_graph()");
702 /* Cleanup. */
703 free (diff_out_in);
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
709 GRAPH_SIZE. */
711 static void
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. */
722 static void
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. */
733 static void
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. */
742 static bool
743 is_empty (queue_type *queue_list)
745 return (queue_list->head == queue_list->tail);
748 /* Insert element X into QUEUE_LIST. */
749 static void
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. */
758 static int
759 dequeue (queue_type *queue_list)
761 int x;
762 gcc_assert (queue_list->head >= 0);
763 x = queue_list->queue[queue_list->head];
764 (queue_list->head)++;
765 return x;
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
772 considered.
774 Parameters:
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
781 Return:
782 true if a negative cycle was found, false otherwise. */
784 static bool
785 cancel_negative_cycle (fixup_graph_type *fixup_graph,
786 int *pi, gcov_type *d, int *cycle)
788 int i, j, k;
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;
794 int new_entry_index;
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;
803 /* Initialize. */
804 /* Skip ENTRY. */
805 for (i = 1; i < fnum_vertices; i++)
807 d[i] = CAP_INFINITY;
808 pi[i] = -1;
809 cycle[i] = -1;
811 d[ENTRY_BLOCK] = 0;
813 /* Relax. */
814 for (k = 1; k < fnum_vertices; k++)
816 propagated = false;
817 for (i = 0; i < fnum_edges; i++)
819 pfedge = fedge_list + i;
820 if (pfedge->src == new_entry_index)
821 continue;
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;
828 propagated = true;
831 if (!propagated)
832 break;
835 if (!propagated)
836 /* No negative cycles exist. */
837 return 0;
839 /* Detect. */
840 for (i = 0; i < fnum_edges; i++)
842 pfedge = fedge_list + i;
843 if (pfedge->src == new_entry_index)
844 continue;
845 if (pfedge->is_rflow_valid && pfedge->rflow
846 && d[pfedge->src] != CAP_INFINITY
847 && (d[pfedge->dest] > d[pfedge->src] + pfedge->cost))
849 found_cycle = true;
850 break;
854 if (!found_cycle)
855 return 0;
857 /* Augment the cycle with the cycle's minimum residual capacity. */
858 found_cycle = false;
859 cycle[0] = pfedge->dest;
860 j = pfedge->dest;
862 for (i = 1; i < fnum_vertices; i++)
864 j = pi[j];
865 cycle[i] = j;
866 for (k = 0; k < i; k++)
868 if (cycle[k] == j)
870 /* cycle[k] -> ... -> cycle[i]. */
871 cycle_start = k;
872 cycle_end = i;
873 found_cycle = true;
874 break;
877 if (found_cycle)
878 break;
881 gcc_assert (cycle[cycle_start] == cycle[cycle_end]);
882 if (dump_file)
883 fprintf (dump_file, "\nNegative cycle length is %d:\n",
884 cycle_end - cycle_start);
886 sum_cost = 0;
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;
893 if (dump_file)
894 fprintf (dump_file, "%d ", cycle[k]);
897 if (dump_file)
899 fprintf (dump_file, "%d", cycle[k]);
900 fprintf (dump_file,
901 ": (%"PRId64 ", %"PRId64
902 ")\n", sum_cost, cycle_flow);
903 fprintf (dump_file,
904 "Augment cycle with %"PRId64 "\n",
905 cycle_flow);
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;
913 if (pfedge->type)
914 pfedge->flow += cycle_flow;
915 r_pfedge->rflow += cycle_flow;
916 if (r_pfedge->type)
917 r_pfedge->flow -= cycle_flow;
920 return true;
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. */
927 static void
928 compute_residual_flow (fixup_graph_type *fixup_graph)
930 int i;
931 int fnum_edges;
932 fixup_edge_p fedge_list, pfedge;
934 gcc_assert (fixup_graph);
936 if (dump_file)
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,
948 -pfedge->cost);
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. */
959 static int
960 find_augmenting_path (fixup_graph_type *fixup_graph,
961 augmenting_path_type *augmenting_path, int source,
962 int sink)
964 int u = 0;
965 int i;
966 fixup_vertex_p fvertex_list, pfvertex;
967 fixup_edge_p pfedge;
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++)
983 is_visited[u] = 0;
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);
992 is_visited[u] = 1;
993 pfvertex = fvertex_list + u;
994 for (i = 0; pfvertex->succ_edges.iterate (i, &pfedge);
995 i++)
997 int dest = pfedge->dest;
998 if ((pfedge->rflow > 0) && (is_visited[dest] == 0))
1000 enqueue (queue_list, dest);
1001 bb_pred[dest] = u;
1002 is_visited[dest] = 1;
1003 if (dest == sink)
1004 return 1;
1009 return 0;
1013 /* Routine to find the maximal flow:
1014 Algorithm:
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.
1020 Parameters:
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. */
1027 static gcov_type
1028 find_max_flow (fixup_graph_type *fixup_graph, int source, int sink)
1030 int fnum_edges;
1031 augmenting_path_type augmenting_path;
1032 int *bb_pred;
1033 gcov_type max_flow = 0;
1034 int i, u;
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;
1046 pfedge->flow = 0;
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]);
1070 if (pfedge->type)
1072 /* forward edge. */
1073 pfedge->flow += increment;
1074 pfedge->rflow -= increment;
1075 r_pfedge->rflow += increment;
1077 else
1079 /* backward edge. */
1080 gcc_assert (r_pfedge->type);
1081 r_pfedge->rflow += increment;
1082 r_pfedge->flow -= increment;
1083 pfedge->rflow -= increment;
1087 if (dump_file)
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, "<-");
1095 fprintf (dump_file,
1096 "ENTRY (path_capacity=%"PRId64 ")\n",
1097 increment);
1098 fprintf (dump_file,
1099 "Network flow is %"PRId64 ".\n",
1100 max_flow);
1104 free_augmenting_path (&augmenting_path);
1105 if (dump_file)
1106 dump_fixup_graph (dump_file, fixup_graph, "After find_max_flow()");
1107 return max_flow;
1111 /* Computes the corrected edge and basic block weights using FIXUP_GRAPH
1112 after applying the find_minimum_cost_flow() routine. */
1114 static void
1115 adjust_cfg_counts (fixup_graph_type *fixup_graph)
1117 basic_block bb;
1118 edge e;
1119 edge_iterator ei;
1120 int i, j;
1121 fixup_edge_p pfedge, pfedge_n;
1123 gcc_assert (fixup_graph);
1125 if (dump_file)
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)
1131 i = 2 * bb->index;
1133 /* Fixup BB. */
1134 if (dump_file)
1135 fprintf (dump_file,
1136 "BB%d: %"PRId64 "", bb->index, bb->count);
1138 pfedge = find_fixup_edge (fixup_graph, i, i + 1);
1139 if (pfedge->flow)
1141 bb->count += pfedge->flow;
1142 if (dump_file)
1144 fprintf (dump_file, " + %"PRId64 "(",
1145 pfedge->flow);
1146 print_edge (dump_file, fixup_graph, i, i + 1);
1147 fprintf (dump_file, ")");
1151 pfedge_n =
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;
1157 if (dump_file)
1159 fprintf (dump_file, " - %"PRId64 "(",
1160 pfedge_n->flow);
1161 print_edge (dump_file, fixup_graph, i + 1,
1162 pfedge->norm_vertex_index);
1163 fprintf (dump_file, ")");
1166 if (dump_file)
1167 fprintf (dump_file, " = %"PRId64 "\n", bb->count);
1169 /* Fixup edge. */
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)
1174 continue;
1176 j = 2 * e->dest->index;
1177 if (dump_file)
1178 fprintf (dump_file, "%d->%d: %"PRId64 "",
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. */
1186 if (pfedge->flow)
1188 e->count += pfedge->flow;
1189 if (dump_file)
1191 fprintf (dump_file, " + %"PRId64 "(",
1192 pfedge->flow);
1193 print_edge (dump_file, fixup_graph, i + 1, j);
1194 fprintf (dump_file, ")");
1198 pfedge_n =
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;
1204 if (dump_file)
1206 fprintf (dump_file, " - %"PRId64 "(",
1207 pfedge_n->flow);
1208 print_edge (dump_file, fixup_graph, j,
1209 pfedge->norm_vertex_index);
1210 fprintf (dump_file, ")");
1214 else
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);
1219 pfedge_n =
1220 find_fixup_edge (fixup_graph, i + 1, pfedge->norm_vertex_index);
1221 e->count += pfedge_n->flow;
1222 bb->count += pfedge_n->flow;
1223 if (dump_file)
1225 fprintf (dump_file, "(self edge)");
1226 fprintf (dump_file, " + %"PRId64 "(",
1227 pfedge_n->flow);
1228 print_edge (dump_file, fixup_graph, i + 1,
1229 pfedge->norm_vertex_index);
1230 fprintf (dump_file, ")");
1234 if (bb->count)
1235 e->probability = REG_BR_PROB_BASE * e->count / bb->count;
1236 if (dump_file)
1237 fprintf (dump_file, " = %"PRId64 "\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)
1250 if (bb->count)
1252 FOR_EACH_EDGE (e, ei, bb->succs)
1253 e->probability = REG_BR_PROB_BASE * e->count / bb->count;
1255 else
1257 int total = 0;
1258 FOR_EACH_EDGE (e, ei, bb->succs)
1259 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
1260 total++;
1261 if (total)
1263 FOR_EACH_EDGE (e, ei, bb->succs)
1265 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
1266 e->probability = REG_BR_PROB_BASE / total;
1267 else
1268 e->probability = 0;
1271 else
1273 total += EDGE_COUNT (bb->succs);
1274 FOR_EACH_EDGE (e, ei, bb->succs)
1275 e->probability = REG_BR_PROB_BASE / total;
1280 if (dump_file)
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)))
1289 fprintf (dump_file,
1290 "BB%d(%"PRId64 ") **INVALID**: ",
1291 bb->index, bb->count);
1292 fprintf (stderr,
1293 "******** BB%d(%"PRId64
1294 ") **INVALID**: \n", bb->index, bb->count);
1295 fprintf (dump_file, "in_edges=%"PRId64 " ",
1296 sum_edge_counts (bb->preds));
1297 fprintf (dump_file, "out_edges=%"PRId64 "\n",
1298 sum_edge_counts (bb->succs));
1305 /* Implements the negative cycle canceling algorithm to compute a minimum cost
1306 flow.
1307 Algorithm:
1308 1. Find maximal flow.
1309 2. Form residual network
1310 3. Repeat:
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
1314 f(u,v) = rf(v, u)
1315 Input:
1316 FIXUP_GRAPH - Initial fixup graph.
1317 The flow field is modified to represent the minimum cost flow. */
1319 static void
1320 find_minimum_cost_flow (fixup_graph_type *fixup_graph)
1322 /* Holds the index of predecessor in path. */
1323 int *pred;
1324 /* Used to hold the minimum cost cycle. */
1325 int *cycle;
1326 /* Used to record the number of iterations of cancel_negative_cycle. */
1327 int iteration;
1328 /* Vector d[i] holds the minimum cost of path from i to sink. */
1329 gcov_type *d;
1330 int fnum_vertices;
1331 int new_exit_index;
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. */
1349 iteration = 0;
1350 while (cancel_negative_cycle (fixup_graph, pred, d, cycle))
1352 iteration++;
1353 if (iteration > MAX_ITER (fixup_graph->num_vertices,
1354 fixup_graph->num_edges))
1355 break;
1358 if (dump_file)
1359 dump_fixup_graph (dump_file, fixup_graph,
1360 "After find_minimum_cost_flow()");
1362 /* Cleanup structures. */
1363 free (pred);
1364 free (d);
1365 free (cycle);
1369 /* Compute the sum of the edge counts in TO_EDGES. */
1371 gcov_type
1372 sum_edge_counts (vec<edge, va_gc> *to_edges)
1374 gcov_type sum = 0;
1375 edge e;
1376 edge_iterator ei;
1378 FOR_EACH_EDGE (e, ei, to_edges)
1380 if (EDGE_INFO (e) && EDGE_INFO (e)->ignore)
1381 continue;
1382 sum += e->count;
1384 return sum;
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
1391 block. */
1393 void
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);