2015-06-11 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / gcc / mcf.c
blob81c12651b13f2290106056cddb3f0c701fb50dda
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
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 "predict.h"
49 #include "tm.h"
50 #include "hard-reg-set.h"
51 #include "input.h"
52 #include "function.h"
53 #include "dominance.h"
54 #include "cfg.h"
55 #include "basic-block.h"
56 #include "gcov-io.h"
57 #include "profile.h"
58 #include "dumpfile.h"
60 /* CAP_INFINITY: Constant to represent infinite capacity. */
61 #define CAP_INFINITY INTTYPE_MAXIMUM (int64_t)
63 /* COST FUNCTION. */
64 #define K_POS(b) ((b))
65 #define K_NEG(b) (50 * (b))
66 #define COST(k, w) ((k) / mcf_ln ((w) + 2))
67 /* Limit the number of iterations for cancel_negative_cycles() to ensure
68 reasonable compile time. */
69 #define MAX_ITER(n, e) 10 + (1000000 / ((n) * (e)))
70 typedef enum
72 INVALID_EDGE,
73 VERTEX_SPLIT_EDGE, /* Edge to represent vertex with w(e) = w(v). */
74 REDIRECT_EDGE, /* Edge after vertex transformation. */
75 REVERSE_EDGE,
76 SOURCE_CONNECT_EDGE, /* Single edge connecting to single source. */
77 SINK_CONNECT_EDGE, /* Single edge connecting to single sink. */
78 BALANCE_EDGE, /* Edge connecting with source/sink: cp(e) = 0. */
79 REDIRECT_NORMALIZED_EDGE, /* Normalized edge for a redirect edge. */
80 REVERSE_NORMALIZED_EDGE /* Normalized edge for a reverse edge. */
81 } edge_type;
83 /* Structure to represent an edge in the fixup graph. */
84 typedef struct fixup_edge_d
86 int src;
87 int dest;
88 /* Flag denoting type of edge and attributes for the flow field. */
89 edge_type type;
90 bool is_rflow_valid;
91 /* Index to the normalization vertex added for this edge. */
92 int norm_vertex_index;
93 /* Flow for this edge. */
94 gcov_type flow;
95 /* Residual flow for this edge - used during negative cycle canceling. */
96 gcov_type rflow;
97 gcov_type weight;
98 gcov_type cost;
99 gcov_type max_capacity;
100 } fixup_edge_type;
102 typedef fixup_edge_type *fixup_edge_p;
105 /* Structure to represent a vertex in the fixup graph. */
106 typedef struct fixup_vertex_d
108 vec<fixup_edge_p> succ_edges;
109 } fixup_vertex_type;
111 typedef fixup_vertex_type *fixup_vertex_p;
113 /* Fixup graph used in the MCF algorithm. */
114 typedef struct fixup_graph_d
116 /* Current number of vertices for the graph. */
117 int num_vertices;
118 /* Current number of edges for the graph. */
119 int num_edges;
120 /* Index of new entry vertex. */
121 int new_entry_index;
122 /* Index of new exit vertex. */
123 int new_exit_index;
124 /* Fixup vertex list. Adjacency list for fixup graph. */
125 fixup_vertex_p vertex_list;
126 /* Fixup edge list. */
127 fixup_edge_p edge_list;
128 } fixup_graph_type;
130 typedef struct queue_d
132 int *queue;
133 int head;
134 int tail;
135 int size;
136 } queue_type;
138 /* Structure used in the maximal flow routines to find augmenting path. */
139 typedef struct augmenting_path_d
141 /* Queue used to hold vertex indices. */
142 queue_type queue_list;
143 /* Vector to hold chain of pred vertex indices in augmenting path. */
144 int *bb_pred;
145 /* Vector that indicates if basic block i has been visited. */
146 int *is_visited;
147 } augmenting_path_type;
150 /* Function definitions. */
152 /* Dump routines to aid debugging. */
154 /* Print basic block with index N for FIXUP_GRAPH in n' and n'' format. */
156 static void
157 print_basic_block (FILE *file, fixup_graph_type *fixup_graph, int n)
159 if (n == ENTRY_BLOCK)
160 fputs ("ENTRY", file);
161 else if (n == ENTRY_BLOCK + 1)
162 fputs ("ENTRY''", file);
163 else if (n == 2 * EXIT_BLOCK)
164 fputs ("EXIT", file);
165 else if (n == 2 * EXIT_BLOCK + 1)
166 fputs ("EXIT''", file);
167 else if (n == fixup_graph->new_exit_index)
168 fputs ("NEW_EXIT", file);
169 else if (n == fixup_graph->new_entry_index)
170 fputs ("NEW_ENTRY", file);
171 else
173 fprintf (file, "%d", n / 2);
174 if (n % 2)
175 fputs ("''", file);
176 else
177 fputs ("'", file);
182 /* Print edge S->D for given fixup_graph with n' and n'' format.
183 PARAMETERS:
184 S is the index of the source vertex of the edge (input) and
185 D is the index of the destination vertex of the edge (input) for the given
186 fixup_graph (input). */
188 static void
189 print_edge (FILE *file, fixup_graph_type *fixup_graph, int s, int d)
191 print_basic_block (file, fixup_graph, s);
192 fputs ("->", file);
193 print_basic_block (file, fixup_graph, d);
197 /* Dump out the attributes of a given edge FEDGE in the fixup_graph to a
198 file. */
199 static void
200 dump_fixup_edge (FILE *file, fixup_graph_type *fixup_graph, fixup_edge_p fedge)
202 if (!fedge)
204 fputs ("NULL fixup graph edge.\n", file);
205 return;
208 print_edge (file, fixup_graph, fedge->src, fedge->dest);
209 fputs (": ", file);
211 if (fedge->type)
213 fprintf (file, "flow/capacity=%" PRId64 "/",
214 fedge->flow);
215 if (fedge->max_capacity == CAP_INFINITY)
216 fputs ("+oo,", file);
217 else
218 fprintf (file, "%" PRId64 ",", fedge->max_capacity);
221 if (fedge->is_rflow_valid)
223 if (fedge->rflow == CAP_INFINITY)
224 fputs (" rflow=+oo.", file);
225 else
226 fprintf (file, " rflow=%" PRId64 ",", fedge->rflow);
229 fprintf (file, " cost=%" PRId64 ".", fedge->cost);
231 fprintf (file, "\t(%d->%d)", fedge->src, fedge->dest);
233 if (fedge->type)
235 switch (fedge->type)
237 case VERTEX_SPLIT_EDGE:
238 fputs (" @VERTEX_SPLIT_EDGE", file);
239 break;
241 case REDIRECT_EDGE:
242 fputs (" @REDIRECT_EDGE", file);
243 break;
245 case SOURCE_CONNECT_EDGE:
246 fputs (" @SOURCE_CONNECT_EDGE", file);
247 break;
249 case SINK_CONNECT_EDGE:
250 fputs (" @SINK_CONNECT_EDGE", file);
251 break;
253 case REVERSE_EDGE:
254 fputs (" @REVERSE_EDGE", file);
255 break;
257 case BALANCE_EDGE:
258 fputs (" @BALANCE_EDGE", file);
259 break;
261 case REDIRECT_NORMALIZED_EDGE:
262 case REVERSE_NORMALIZED_EDGE:
263 fputs (" @NORMALIZED_EDGE", file);
264 break;
266 default:
267 fputs (" @INVALID_EDGE", file);
268 break;
271 fputs ("\n", file);
275 /* Print out the edges and vertices of the given FIXUP_GRAPH, into the dump
276 file. The input string MSG is printed out as a heading. */
278 static void
279 dump_fixup_graph (FILE *file, fixup_graph_type *fixup_graph, const char *msg)
281 int i, j;
282 int fnum_vertices, fnum_edges;
284 fixup_vertex_p fvertex_list, pfvertex;
285 fixup_edge_p pfedge;
287 gcc_assert (fixup_graph);
288 fvertex_list = fixup_graph->vertex_list;
289 fnum_vertices = fixup_graph->num_vertices;
290 fnum_edges = fixup_graph->num_edges;
292 fprintf (file, "\nDump fixup graph for %s(): %s.\n",
293 current_function_name (), msg);
294 fprintf (file,
295 "There are %d vertices and %d edges. new_exit_index is %d.\n\n",
296 fnum_vertices, fnum_edges, fixup_graph->new_exit_index);
298 for (i = 0; i < fnum_vertices; i++)
300 pfvertex = fvertex_list + i;
301 fprintf (file, "vertex_list[%d]: %d succ fixup edges.\n",
302 i, pfvertex->succ_edges.length ());
304 for (j = 0; pfvertex->succ_edges.iterate (j, &pfedge);
305 j++)
307 /* Distinguish forward edges and backward edges in the residual flow
308 network. */
309 if (pfedge->type)
310 fputs ("(f) ", file);
311 else if (pfedge->is_rflow_valid)
312 fputs ("(b) ", file);
313 dump_fixup_edge (file, fixup_graph, pfedge);
317 fputs ("\n", file);
321 /* Utility routines. */
322 /* ln() implementation: approximate calculation. Returns ln of X. */
324 static double
325 mcf_ln (double x)
327 #define E 2.71828
328 int l = 1;
329 double m = E;
331 gcc_assert (x >= 0);
333 while (m < x)
335 m *= E;
336 l++;
339 return l;
343 /* sqrt() implementation: based on open source QUAKE3 code (magic sqrt
344 implementation) by John Carmack. Returns sqrt of X. */
346 static double
347 mcf_sqrt (double x)
349 #define MAGIC_CONST1 0x1fbcf800
350 #define MAGIC_CONST2 0x5f3759df
351 union {
352 int intPart;
353 float floatPart;
354 } convertor, convertor2;
356 gcc_assert (x >= 0);
358 convertor.floatPart = x;
359 convertor2.floatPart = x;
360 convertor.intPart = MAGIC_CONST1 + (convertor.intPart >> 1);
361 convertor2.intPart = MAGIC_CONST2 - (convertor2.intPart >> 1);
363 return 0.5f * (convertor.floatPart + (x * convertor2.floatPart));
367 /* Common code shared between add_fixup_edge and add_rfixup_edge. Adds an edge
368 (SRC->DEST) to the edge_list maintained in FIXUP_GRAPH with cost of the edge
369 added set to COST. */
371 static fixup_edge_p
372 add_edge (fixup_graph_type *fixup_graph, int src, int dest, gcov_type cost)
374 fixup_vertex_p curr_vertex = fixup_graph->vertex_list + src;
375 fixup_edge_p curr_edge = fixup_graph->edge_list + fixup_graph->num_edges;
376 curr_edge->src = src;
377 curr_edge->dest = dest;
378 curr_edge->cost = cost;
379 fixup_graph->num_edges++;
380 if (dump_file)
381 dump_fixup_edge (dump_file, fixup_graph, curr_edge);
382 curr_vertex->succ_edges.safe_push (curr_edge);
383 return curr_edge;
387 /* Add a fixup edge (src->dest) with attributes TYPE, WEIGHT, COST and
388 MAX_CAPACITY to the edge_list in the fixup graph. */
390 static void
391 add_fixup_edge (fixup_graph_type *fixup_graph, int src, int dest,
392 edge_type type, gcov_type weight, gcov_type cost,
393 gcov_type max_capacity)
395 fixup_edge_p curr_edge = add_edge (fixup_graph, src, dest, cost);
396 curr_edge->type = type;
397 curr_edge->weight = weight;
398 curr_edge->max_capacity = max_capacity;
402 /* Add a residual edge (SRC->DEST) with attributes RFLOW and COST
403 to the fixup graph. */
405 static void
406 add_rfixup_edge (fixup_graph_type *fixup_graph, int src, int dest,
407 gcov_type rflow, gcov_type cost)
409 fixup_edge_p curr_edge = add_edge (fixup_graph, src, dest, cost);
410 curr_edge->rflow = rflow;
411 curr_edge->is_rflow_valid = true;
412 /* This edge is not a valid edge - merely used to hold residual flow. */
413 curr_edge->type = INVALID_EDGE;
417 /* Return the pointer to fixup edge SRC->DEST or NULL if edge does not
418 exist in the FIXUP_GRAPH. */
420 static fixup_edge_p
421 find_fixup_edge (fixup_graph_type *fixup_graph, int src, int dest)
423 int j;
424 fixup_edge_p pfedge;
425 fixup_vertex_p pfvertex;
427 gcc_assert (src < fixup_graph->num_vertices);
429 pfvertex = fixup_graph->vertex_list + src;
431 for (j = 0; pfvertex->succ_edges.iterate (j, &pfedge);
432 j++)
433 if (pfedge->dest == dest)
434 return pfedge;
436 return NULL;
440 /* Cleanup routine to free structures in FIXUP_GRAPH. */
442 static void
443 delete_fixup_graph (fixup_graph_type *fixup_graph)
445 int i;
446 int fnum_vertices = fixup_graph->num_vertices;
447 fixup_vertex_p pfvertex = fixup_graph->vertex_list;
449 for (i = 0; i < fnum_vertices; i++, pfvertex++)
450 pfvertex->succ_edges.release ();
452 free (fixup_graph->vertex_list);
453 free (fixup_graph->edge_list);
457 /* Creates a fixup graph FIXUP_GRAPH from the function CFG. */
459 static void
460 create_fixup_graph (fixup_graph_type *fixup_graph)
462 double sqrt_avg_vertex_weight = 0;
463 double total_vertex_weight = 0;
464 double k_pos = 0;
465 double k_neg = 0;
466 /* Vector to hold D(v) = sum_out_edges(v) - sum_in_edges(v). */
467 gcov_type *diff_out_in = NULL;
468 gcov_type supply_value = 1, demand_value = 0;
469 gcov_type fcost = 0;
470 int new_entry_index = 0, new_exit_index = 0;
471 int i = 0, j = 0;
472 int new_index = 0;
473 basic_block bb;
474 edge e;
475 edge_iterator ei;
476 fixup_edge_p pfedge, r_pfedge;
477 fixup_edge_p fedge_list;
478 int fnum_edges;
480 /* Each basic_block will be split into 2 during vertex transformation. */
481 int fnum_vertices_after_transform = 2 * n_basic_blocks_for_fn (cfun);
482 int fnum_edges_after_transform =
483 n_edges_for_fn (cfun) + n_basic_blocks_for_fn (cfun);
485 /* Count the new SOURCE and EXIT vertices to be added. */
486 int fmax_num_vertices =
487 (fnum_vertices_after_transform + n_edges_for_fn (cfun)
488 + n_basic_blocks_for_fn (cfun) + 2);
490 /* In create_fixup_graph: Each basic block and edge can be split into 3
491 edges. Number of balance edges = n_basic_blocks. So after
492 create_fixup_graph:
493 max_edges = 4 * n_basic_blocks + 3 * n_edges
494 Accounting for residual flow edges
495 max_edges = 2 * (4 * n_basic_blocks + 3 * n_edges)
496 = 8 * n_basic_blocks + 6 * n_edges
497 < 8 * n_basic_blocks + 8 * n_edges. */
498 int fmax_num_edges = 8 * (n_basic_blocks_for_fn (cfun) +
499 n_edges_for_fn (cfun));
501 /* Initial num of vertices in the fixup graph. */
502 fixup_graph->num_vertices = n_basic_blocks_for_fn (cfun);
504 /* Fixup graph vertex list. */
505 fixup_graph->vertex_list =
506 (fixup_vertex_p) xcalloc (fmax_num_vertices, sizeof (fixup_vertex_type));
508 /* Fixup graph edge list. */
509 fixup_graph->edge_list =
510 (fixup_edge_p) xcalloc (fmax_num_edges, sizeof (fixup_edge_type));
512 diff_out_in =
513 (gcov_type *) xcalloc (1 + fnum_vertices_after_transform,
514 sizeof (gcov_type));
516 /* Compute constants b, k_pos, k_neg used in the cost function calculation.
517 b = sqrt(avg_vertex_weight(cfg)); k_pos = b; k_neg = 50b. */
518 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
519 total_vertex_weight += bb->count;
521 sqrt_avg_vertex_weight = mcf_sqrt (total_vertex_weight /
522 n_basic_blocks_for_fn (cfun));
524 k_pos = K_POS (sqrt_avg_vertex_weight);
525 k_neg = K_NEG (sqrt_avg_vertex_weight);
527 /* 1. Vertex Transformation: Split each vertex v into two vertices v' and v'',
528 connected by an edge e from v' to v''. w(e) = w(v). */
530 if (dump_file)
531 fprintf (dump_file, "\nVertex transformation:\n");
533 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
535 /* v'->v'': index1->(index1+1). */
536 i = 2 * bb->index;
537 fcost = (gcov_type) COST (k_pos, bb->count);
538 add_fixup_edge (fixup_graph, i, i + 1, VERTEX_SPLIT_EDGE, bb->count,
539 fcost, CAP_INFINITY);
540 fixup_graph->num_vertices++;
542 FOR_EACH_EDGE (e, ei, bb->succs)
544 /* Edges with ignore attribute set should be treated like they don't
545 exist. */
546 if (EDGE_INFO (e) && EDGE_INFO (e)->ignore)
547 continue;
548 j = 2 * e->dest->index;
549 fcost = (gcov_type) COST (k_pos, e->count);
550 add_fixup_edge (fixup_graph, i + 1, j, REDIRECT_EDGE, e->count, fcost,
551 CAP_INFINITY);
555 /* After vertex transformation. */
556 gcc_assert (fixup_graph->num_vertices == fnum_vertices_after_transform);
557 /* Redirect edges are not added for edges with ignore attribute. */
558 gcc_assert (fixup_graph->num_edges <= fnum_edges_after_transform);
560 fnum_edges_after_transform = fixup_graph->num_edges;
562 /* 2. Initialize D(v). */
563 for (i = 0; i < fnum_edges_after_transform; i++)
565 pfedge = fixup_graph->edge_list + i;
566 diff_out_in[pfedge->src] += pfedge->weight;
567 diff_out_in[pfedge->dest] -= pfedge->weight;
570 /* Entry block - vertex indices 0, 1; EXIT block - vertex indices 2, 3. */
571 for (i = 0; i <= 3; i++)
572 diff_out_in[i] = 0;
574 /* 3. Add reverse edges: needed to decrease counts during smoothing. */
575 if (dump_file)
576 fprintf (dump_file, "\nReverse edges:\n");
577 for (i = 0; i < fnum_edges_after_transform; i++)
579 pfedge = fixup_graph->edge_list + i;
580 if ((pfedge->src == 0) || (pfedge->src == 2))
581 continue;
582 r_pfedge = find_fixup_edge (fixup_graph, pfedge->dest, pfedge->src);
583 if (!r_pfedge && pfedge->weight)
585 /* Skip adding reverse edges for edges with w(e) = 0, as its maximum
586 capacity is 0. */
587 fcost = (gcov_type) COST (k_neg, pfedge->weight);
588 add_fixup_edge (fixup_graph, pfedge->dest, pfedge->src,
589 REVERSE_EDGE, 0, fcost, pfedge->weight);
593 /* 4. Create single source and sink. Connect new source vertex s' to function
594 entry block. Connect sink vertex t' to function exit. */
595 if (dump_file)
596 fprintf (dump_file, "\ns'->S, T->t':\n");
598 new_entry_index = fixup_graph->new_entry_index = fixup_graph->num_vertices;
599 fixup_graph->num_vertices++;
600 /* Set supply_value to 1 to avoid zero count function ENTRY. */
601 add_fixup_edge (fixup_graph, new_entry_index, ENTRY_BLOCK, SOURCE_CONNECT_EDGE,
602 1 /* supply_value */, 0, 1 /* supply_value */);
604 /* Create new exit with EXIT_BLOCK as single pred. */
605 new_exit_index = fixup_graph->new_exit_index = fixup_graph->num_vertices;
606 fixup_graph->num_vertices++;
607 add_fixup_edge (fixup_graph, 2 * EXIT_BLOCK + 1, new_exit_index,
608 SINK_CONNECT_EDGE,
609 0 /* demand_value */, 0, 0 /* demand_value */);
611 /* Connect vertices with unbalanced D(v) to source/sink. */
612 if (dump_file)
613 fprintf (dump_file, "\nD(v) balance:\n");
614 /* Skip vertices for ENTRY (0, 1) and EXIT (2,3) blocks, so start with i = 4.
615 diff_out_in[v''] will be 0, so skip v'' vertices, hence i += 2. */
616 for (i = 4; i < new_entry_index; i += 2)
618 if (diff_out_in[i] > 0)
620 add_fixup_edge (fixup_graph, i, new_exit_index, BALANCE_EDGE, 0, 0,
621 diff_out_in[i]);
622 demand_value += diff_out_in[i];
624 else if (diff_out_in[i] < 0)
626 add_fixup_edge (fixup_graph, new_entry_index, i, BALANCE_EDGE, 0, 0,
627 -diff_out_in[i]);
628 supply_value -= diff_out_in[i];
632 /* Set supply = demand. */
633 if (dump_file)
635 fprintf (dump_file, "\nAdjust supply and demand:\n");
636 fprintf (dump_file, "supply_value=%" PRId64 "\n",
637 supply_value);
638 fprintf (dump_file, "demand_value=%" PRId64 "\n",
639 demand_value);
642 if (demand_value > supply_value)
644 pfedge = find_fixup_edge (fixup_graph, new_entry_index, ENTRY_BLOCK);
645 pfedge->max_capacity += (demand_value - supply_value);
647 else
649 pfedge = find_fixup_edge (fixup_graph, 2 * EXIT_BLOCK + 1, new_exit_index);
650 pfedge->max_capacity += (supply_value - demand_value);
653 /* 6. Normalize edges: remove anti-parallel edges. Anti-parallel edges are
654 created by the vertex transformation step from self-edges in the original
655 CFG and by the reverse edges added earlier. */
656 if (dump_file)
657 fprintf (dump_file, "\nNormalize edges:\n");
659 fnum_edges = fixup_graph->num_edges;
660 fedge_list = fixup_graph->edge_list;
662 for (i = 0; i < fnum_edges; i++)
664 pfedge = fedge_list + i;
665 r_pfedge = find_fixup_edge (fixup_graph, pfedge->dest, pfedge->src);
666 if (((pfedge->type == VERTEX_SPLIT_EDGE)
667 || (pfedge->type == REDIRECT_EDGE)) && r_pfedge)
669 new_index = fixup_graph->num_vertices;
670 fixup_graph->num_vertices++;
672 if (dump_file)
674 fprintf (dump_file, "\nAnti-parallel edge:\n");
675 dump_fixup_edge (dump_file, fixup_graph, pfedge);
676 dump_fixup_edge (dump_file, fixup_graph, r_pfedge);
677 fprintf (dump_file, "New vertex is %d.\n", new_index);
678 fprintf (dump_file, "------------------\n");
681 pfedge->cost /= 2;
682 pfedge->norm_vertex_index = new_index;
683 if (dump_file)
685 fprintf (dump_file, "After normalization:\n");
686 dump_fixup_edge (dump_file, fixup_graph, pfedge);
689 /* Add a new fixup edge: new_index->src. */
690 add_fixup_edge (fixup_graph, new_index, pfedge->src,
691 REVERSE_NORMALIZED_EDGE, 0, r_pfedge->cost,
692 r_pfedge->max_capacity);
693 gcc_assert (fixup_graph->num_vertices <= fmax_num_vertices);
695 /* Edge: r_pfedge->src -> r_pfedge->dest
696 ==> r_pfedge->src -> new_index. */
697 r_pfedge->dest = new_index;
698 r_pfedge->type = REVERSE_NORMALIZED_EDGE;
699 r_pfedge->cost = pfedge->cost;
700 r_pfedge->max_capacity = pfedge->max_capacity;
701 if (dump_file)
702 dump_fixup_edge (dump_file, fixup_graph, r_pfedge);
706 if (dump_file)
707 dump_fixup_graph (dump_file, fixup_graph, "After create_fixup_graph()");
709 /* Cleanup. */
710 free (diff_out_in);
714 /* Allocates space for the structures in AUGMENTING_PATH. The space needed is
715 proportional to the number of nodes in the graph, which is given by
716 GRAPH_SIZE. */
718 static void
719 init_augmenting_path (augmenting_path_type *augmenting_path, int graph_size)
721 augmenting_path->queue_list.queue = (int *)
722 xcalloc (graph_size + 2, sizeof (int));
723 augmenting_path->queue_list.size = graph_size + 2;
724 augmenting_path->bb_pred = (int *) xcalloc (graph_size, sizeof (int));
725 augmenting_path->is_visited = (int *) xcalloc (graph_size, sizeof (int));
728 /* Free the structures in AUGMENTING_PATH. */
729 static void
730 free_augmenting_path (augmenting_path_type *augmenting_path)
732 free (augmenting_path->queue_list.queue);
733 free (augmenting_path->bb_pred);
734 free (augmenting_path->is_visited);
738 /* Queue routines. Assumes queue will never overflow. */
740 static void
741 init_queue (queue_type *queue_list)
743 gcc_assert (queue_list);
744 queue_list->head = 0;
745 queue_list->tail = 0;
748 /* Return true if QUEUE_LIST is empty. */
749 static bool
750 is_empty (queue_type *queue_list)
752 return (queue_list->head == queue_list->tail);
755 /* Insert element X into QUEUE_LIST. */
756 static void
757 enqueue (queue_type *queue_list, int x)
759 gcc_assert (queue_list->tail < queue_list->size);
760 queue_list->queue[queue_list->tail] = x;
761 (queue_list->tail)++;
764 /* Return the first element in QUEUE_LIST. */
765 static int
766 dequeue (queue_type *queue_list)
768 int x;
769 gcc_assert (queue_list->head >= 0);
770 x = queue_list->queue[queue_list->head];
771 (queue_list->head)++;
772 return x;
776 /* Finds a negative cycle in the residual network using
777 the Bellman-Ford algorithm. The flow on the found cycle is reversed by the
778 minimum residual capacity of that cycle. ENTRY and EXIT vertices are not
779 considered.
781 Parameters:
782 FIXUP_GRAPH - Residual graph (input/output)
783 The following are allocated/freed by the caller:
784 PI - Vector to hold predecessors in path (pi = pred index)
785 D - D[I] holds minimum cost of path from i to sink
786 CYCLE - Vector to hold the minimum cost cycle
788 Return:
789 true if a negative cycle was found, false otherwise. */
791 static bool
792 cancel_negative_cycle (fixup_graph_type *fixup_graph,
793 int *pi, gcov_type *d, int *cycle)
795 int i, j, k;
796 int fnum_vertices, fnum_edges;
797 fixup_edge_p fedge_list, pfedge, r_pfedge;
798 bool found_cycle = false;
799 int cycle_start = 0, cycle_end = 0;
800 gcov_type sum_cost = 0, cycle_flow = 0;
801 int new_entry_index;
802 bool propagated = false;
804 gcc_assert (fixup_graph);
805 fnum_vertices = fixup_graph->num_vertices;
806 fnum_edges = fixup_graph->num_edges;
807 fedge_list = fixup_graph->edge_list;
808 new_entry_index = fixup_graph->new_entry_index;
810 /* Initialize. */
811 /* Skip ENTRY. */
812 for (i = 1; i < fnum_vertices; i++)
814 d[i] = CAP_INFINITY;
815 pi[i] = -1;
816 cycle[i] = -1;
818 d[ENTRY_BLOCK] = 0;
820 /* Relax. */
821 for (k = 1; k < fnum_vertices; k++)
823 propagated = false;
824 for (i = 0; i < fnum_edges; i++)
826 pfedge = fedge_list + i;
827 if (pfedge->src == new_entry_index)
828 continue;
829 if (pfedge->is_rflow_valid && pfedge->rflow
830 && d[pfedge->src] != CAP_INFINITY
831 && (d[pfedge->dest] > d[pfedge->src] + pfedge->cost))
833 d[pfedge->dest] = d[pfedge->src] + pfedge->cost;
834 pi[pfedge->dest] = pfedge->src;
835 propagated = true;
838 if (!propagated)
839 break;
842 if (!propagated)
843 /* No negative cycles exist. */
844 return 0;
846 /* Detect. */
847 for (i = 0; i < fnum_edges; i++)
849 pfedge = fedge_list + i;
850 if (pfedge->src == new_entry_index)
851 continue;
852 if (pfedge->is_rflow_valid && pfedge->rflow
853 && d[pfedge->src] != CAP_INFINITY
854 && (d[pfedge->dest] > d[pfedge->src] + pfedge->cost))
856 found_cycle = true;
857 break;
861 if (!found_cycle)
862 return 0;
864 /* Augment the cycle with the cycle's minimum residual capacity. */
865 found_cycle = false;
866 cycle[0] = pfedge->dest;
867 j = pfedge->dest;
869 for (i = 1; i < fnum_vertices; i++)
871 j = pi[j];
872 cycle[i] = j;
873 for (k = 0; k < i; k++)
875 if (cycle[k] == j)
877 /* cycle[k] -> ... -> cycle[i]. */
878 cycle_start = k;
879 cycle_end = i;
880 found_cycle = true;
881 break;
884 if (found_cycle)
885 break;
888 gcc_assert (cycle[cycle_start] == cycle[cycle_end]);
889 if (dump_file)
890 fprintf (dump_file, "\nNegative cycle length is %d:\n",
891 cycle_end - cycle_start);
893 sum_cost = 0;
894 cycle_flow = CAP_INFINITY;
895 for (k = cycle_start; k < cycle_end; k++)
897 pfedge = find_fixup_edge (fixup_graph, cycle[k + 1], cycle[k]);
898 cycle_flow = MIN (cycle_flow, pfedge->rflow);
899 sum_cost += pfedge->cost;
900 if (dump_file)
901 fprintf (dump_file, "%d ", cycle[k]);
904 if (dump_file)
906 fprintf (dump_file, "%d", cycle[k]);
907 fprintf (dump_file,
908 ": (%" PRId64 ", %" PRId64
909 ")\n", sum_cost, cycle_flow);
910 fprintf (dump_file,
911 "Augment cycle with %" PRId64 "\n",
912 cycle_flow);
915 for (k = cycle_start; k < cycle_end; k++)
917 pfedge = find_fixup_edge (fixup_graph, cycle[k + 1], cycle[k]);
918 r_pfedge = find_fixup_edge (fixup_graph, cycle[k], cycle[k + 1]);
919 pfedge->rflow -= cycle_flow;
920 if (pfedge->type)
921 pfedge->flow += cycle_flow;
922 r_pfedge->rflow += cycle_flow;
923 if (r_pfedge->type)
924 r_pfedge->flow -= cycle_flow;
927 return true;
931 /* Computes the residual flow for FIXUP_GRAPH by setting the rflow field of
932 the edges. ENTRY and EXIT vertices should not be considered. */
934 static void
935 compute_residual_flow (fixup_graph_type *fixup_graph)
937 int i;
938 int fnum_edges;
939 fixup_edge_p fedge_list, pfedge;
941 gcc_assert (fixup_graph);
943 if (dump_file)
944 fputs ("\ncompute_residual_flow():\n", dump_file);
946 fnum_edges = fixup_graph->num_edges;
947 fedge_list = fixup_graph->edge_list;
949 for (i = 0; i < fnum_edges; i++)
951 pfedge = fedge_list + i;
952 pfedge->rflow = pfedge->max_capacity - pfedge->flow;
953 pfedge->is_rflow_valid = true;
954 add_rfixup_edge (fixup_graph, pfedge->dest, pfedge->src, pfedge->flow,
955 -pfedge->cost);
960 /* Uses Edmonds-Karp algorithm - BFS to find augmenting path from SOURCE to
961 SINK. The fields in the edge vector in the FIXUP_GRAPH are not modified by
962 this routine. The vector bb_pred in the AUGMENTING_PATH structure is updated
963 to reflect the path found.
964 Returns: 0 if no augmenting path is found, 1 otherwise. */
966 static int
967 find_augmenting_path (fixup_graph_type *fixup_graph,
968 augmenting_path_type *augmenting_path, int source,
969 int sink)
971 int u = 0;
972 int i;
973 fixup_vertex_p fvertex_list, pfvertex;
974 fixup_edge_p pfedge;
975 int *bb_pred, *is_visited;
976 queue_type *queue_list;
978 gcc_assert (augmenting_path);
979 bb_pred = augmenting_path->bb_pred;
980 gcc_assert (bb_pred);
981 is_visited = augmenting_path->is_visited;
982 gcc_assert (is_visited);
983 queue_list = &(augmenting_path->queue_list);
985 gcc_assert (fixup_graph);
987 fvertex_list = fixup_graph->vertex_list;
989 for (u = 0; u < fixup_graph->num_vertices; u++)
990 is_visited[u] = 0;
992 init_queue (queue_list);
993 enqueue (queue_list, source);
994 bb_pred[source] = -1;
996 while (!is_empty (queue_list))
998 u = dequeue (queue_list);
999 is_visited[u] = 1;
1000 pfvertex = fvertex_list + u;
1001 for (i = 0; pfvertex->succ_edges.iterate (i, &pfedge);
1002 i++)
1004 int dest = pfedge->dest;
1005 if ((pfedge->rflow > 0) && (is_visited[dest] == 0))
1007 enqueue (queue_list, dest);
1008 bb_pred[dest] = u;
1009 is_visited[dest] = 1;
1010 if (dest == sink)
1011 return 1;
1016 return 0;
1020 /* Routine to find the maximal flow:
1021 Algorithm:
1022 1. Initialize flow to 0
1023 2. Find an augmenting path form source to sink.
1024 3. Send flow equal to the path's residual capacity along the edges of this path.
1025 4. Repeat steps 2 and 3 until no new augmenting path is found.
1027 Parameters:
1028 SOURCE: index of source vertex (input)
1029 SINK: index of sink vertex (input)
1030 FIXUP_GRAPH: adjacency matrix representing the graph. The flow of the edges will be
1031 set to have a valid maximal flow by this routine. (input)
1032 Return: Maximum flow possible. */
1034 static gcov_type
1035 find_max_flow (fixup_graph_type *fixup_graph, int source, int sink)
1037 int fnum_edges;
1038 augmenting_path_type augmenting_path;
1039 int *bb_pred;
1040 gcov_type max_flow = 0;
1041 int i, u;
1042 fixup_edge_p fedge_list, pfedge, r_pfedge;
1044 gcc_assert (fixup_graph);
1046 fnum_edges = fixup_graph->num_edges;
1047 fedge_list = fixup_graph->edge_list;
1049 /* Initialize flow to 0. */
1050 for (i = 0; i < fnum_edges; i++)
1052 pfedge = fedge_list + i;
1053 pfedge->flow = 0;
1056 compute_residual_flow (fixup_graph);
1058 init_augmenting_path (&augmenting_path, fixup_graph->num_vertices);
1060 bb_pred = augmenting_path.bb_pred;
1061 while (find_augmenting_path (fixup_graph, &augmenting_path, source, sink))
1063 /* Determine the amount by which we can increment the flow. */
1064 gcov_type increment = CAP_INFINITY;
1065 for (u = sink; u != source; u = bb_pred[u])
1067 pfedge = find_fixup_edge (fixup_graph, bb_pred[u], u);
1068 increment = MIN (increment, pfedge->rflow);
1070 max_flow += increment;
1072 /* Now increment the flow. EXIT vertex index is 1. */
1073 for (u = sink; u != source; u = bb_pred[u])
1075 pfedge = find_fixup_edge (fixup_graph, bb_pred[u], u);
1076 r_pfedge = find_fixup_edge (fixup_graph, u, bb_pred[u]);
1077 if (pfedge->type)
1079 /* forward edge. */
1080 pfedge->flow += increment;
1081 pfedge->rflow -= increment;
1082 r_pfedge->rflow += increment;
1084 else
1086 /* backward edge. */
1087 gcc_assert (r_pfedge->type);
1088 r_pfedge->rflow += increment;
1089 r_pfedge->flow -= increment;
1090 pfedge->rflow -= increment;
1094 if (dump_file)
1096 fprintf (dump_file, "\nDump augmenting path:\n");
1097 for (u = sink; u != source; u = bb_pred[u])
1099 print_basic_block (dump_file, fixup_graph, u);
1100 fprintf (dump_file, "<-");
1102 fprintf (dump_file,
1103 "ENTRY (path_capacity=%" PRId64 ")\n",
1104 increment);
1105 fprintf (dump_file,
1106 "Network flow is %" PRId64 ".\n",
1107 max_flow);
1111 free_augmenting_path (&augmenting_path);
1112 if (dump_file)
1113 dump_fixup_graph (dump_file, fixup_graph, "After find_max_flow()");
1114 return max_flow;
1118 /* Computes the corrected edge and basic block weights using FIXUP_GRAPH
1119 after applying the find_minimum_cost_flow() routine. */
1121 static void
1122 adjust_cfg_counts (fixup_graph_type *fixup_graph)
1124 basic_block bb;
1125 edge e;
1126 edge_iterator ei;
1127 int i, j;
1128 fixup_edge_p pfedge, pfedge_n;
1130 gcc_assert (fixup_graph);
1132 if (dump_file)
1133 fprintf (dump_file, "\nadjust_cfg_counts():\n");
1135 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun),
1136 EXIT_BLOCK_PTR_FOR_FN (cfun), next_bb)
1138 i = 2 * bb->index;
1140 /* Fixup BB. */
1141 if (dump_file)
1142 fprintf (dump_file,
1143 "BB%d: %" PRId64 "", bb->index, bb->count);
1145 pfedge = find_fixup_edge (fixup_graph, i, i + 1);
1146 if (pfedge->flow)
1148 bb->count += pfedge->flow;
1149 if (dump_file)
1151 fprintf (dump_file, " + %" PRId64 "(",
1152 pfedge->flow);
1153 print_edge (dump_file, fixup_graph, i, i + 1);
1154 fprintf (dump_file, ")");
1158 pfedge_n =
1159 find_fixup_edge (fixup_graph, i + 1, pfedge->norm_vertex_index);
1160 /* Deduct flow from normalized reverse edge. */
1161 if (pfedge->norm_vertex_index && pfedge_n->flow)
1163 bb->count -= pfedge_n->flow;
1164 if (dump_file)
1166 fprintf (dump_file, " - %" PRId64 "(",
1167 pfedge_n->flow);
1168 print_edge (dump_file, fixup_graph, i + 1,
1169 pfedge->norm_vertex_index);
1170 fprintf (dump_file, ")");
1173 if (dump_file)
1174 fprintf (dump_file, " = %" PRId64 "\n", bb->count);
1176 /* Fixup edge. */
1177 FOR_EACH_EDGE (e, ei, bb->succs)
1179 /* Treat edges with ignore attribute set as if they don't exist. */
1180 if (EDGE_INFO (e) && EDGE_INFO (e)->ignore)
1181 continue;
1183 j = 2 * e->dest->index;
1184 if (dump_file)
1185 fprintf (dump_file, "%d->%d: %" PRId64 "",
1186 bb->index, e->dest->index, e->count);
1188 pfedge = find_fixup_edge (fixup_graph, i + 1, j);
1190 if (bb->index != e->dest->index)
1192 /* Non-self edge. */
1193 if (pfedge->flow)
1195 e->count += pfedge->flow;
1196 if (dump_file)
1198 fprintf (dump_file, " + %" PRId64 "(",
1199 pfedge->flow);
1200 print_edge (dump_file, fixup_graph, i + 1, j);
1201 fprintf (dump_file, ")");
1205 pfedge_n =
1206 find_fixup_edge (fixup_graph, j, pfedge->norm_vertex_index);
1207 /* Deduct flow from normalized reverse edge. */
1208 if (pfedge->norm_vertex_index && pfedge_n->flow)
1210 e->count -= pfedge_n->flow;
1211 if (dump_file)
1213 fprintf (dump_file, " - %" PRId64 "(",
1214 pfedge_n->flow);
1215 print_edge (dump_file, fixup_graph, j,
1216 pfedge->norm_vertex_index);
1217 fprintf (dump_file, ")");
1221 else
1223 /* Handle self edges. Self edge is split with a normalization
1224 vertex. Here i=j. */
1225 pfedge = find_fixup_edge (fixup_graph, j, i + 1);
1226 pfedge_n =
1227 find_fixup_edge (fixup_graph, i + 1, pfedge->norm_vertex_index);
1228 e->count += pfedge_n->flow;
1229 bb->count += pfedge_n->flow;
1230 if (dump_file)
1232 fprintf (dump_file, "(self edge)");
1233 fprintf (dump_file, " + %" PRId64 "(",
1234 pfedge_n->flow);
1235 print_edge (dump_file, fixup_graph, i + 1,
1236 pfedge->norm_vertex_index);
1237 fprintf (dump_file, ")");
1241 if (bb->count)
1242 e->probability = REG_BR_PROB_BASE * e->count / bb->count;
1243 if (dump_file)
1244 fprintf (dump_file, " = %" PRId64 "\t(%.1f%%)\n",
1245 e->count, e->probability * 100.0 / REG_BR_PROB_BASE);
1249 ENTRY_BLOCK_PTR_FOR_FN (cfun)->count =
1250 sum_edge_counts (ENTRY_BLOCK_PTR_FOR_FN (cfun)->succs);
1251 EXIT_BLOCK_PTR_FOR_FN (cfun)->count =
1252 sum_edge_counts (EXIT_BLOCK_PTR_FOR_FN (cfun)->preds);
1254 /* Compute edge probabilities. */
1255 FOR_ALL_BB_FN (bb, cfun)
1257 if (bb->count)
1259 FOR_EACH_EDGE (e, ei, bb->succs)
1260 e->probability = REG_BR_PROB_BASE * e->count / bb->count;
1262 else
1264 int total = 0;
1265 FOR_EACH_EDGE (e, ei, bb->succs)
1266 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
1267 total++;
1268 if (total)
1270 FOR_EACH_EDGE (e, ei, bb->succs)
1272 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
1273 e->probability = REG_BR_PROB_BASE / total;
1274 else
1275 e->probability = 0;
1278 else
1280 total += EDGE_COUNT (bb->succs);
1281 FOR_EACH_EDGE (e, ei, bb->succs)
1282 e->probability = REG_BR_PROB_BASE / total;
1287 if (dump_file)
1289 fprintf (dump_file, "\nCheck %s() CFG flow conservation:\n",
1290 current_function_name ());
1291 FOR_EACH_BB_FN (bb, cfun)
1293 if ((bb->count != sum_edge_counts (bb->preds))
1294 || (bb->count != sum_edge_counts (bb->succs)))
1296 fprintf (dump_file,
1297 "BB%d(%" PRId64 ") **INVALID**: ",
1298 bb->index, bb->count);
1299 fprintf (stderr,
1300 "******** BB%d(%" PRId64
1301 ") **INVALID**: \n", bb->index, bb->count);
1302 fprintf (dump_file, "in_edges=%" PRId64 " ",
1303 sum_edge_counts (bb->preds));
1304 fprintf (dump_file, "out_edges=%" PRId64 "\n",
1305 sum_edge_counts (bb->succs));
1312 /* Implements the negative cycle canceling algorithm to compute a minimum cost
1313 flow.
1314 Algorithm:
1315 1. Find maximal flow.
1316 2. Form residual network
1317 3. Repeat:
1318 While G contains a negative cost cycle C, reverse the flow on the found cycle
1319 by the minimum residual capacity in that cycle.
1320 4. Form the minimal cost flow
1321 f(u,v) = rf(v, u)
1322 Input:
1323 FIXUP_GRAPH - Initial fixup graph.
1324 The flow field is modified to represent the minimum cost flow. */
1326 static void
1327 find_minimum_cost_flow (fixup_graph_type *fixup_graph)
1329 /* Holds the index of predecessor in path. */
1330 int *pred;
1331 /* Used to hold the minimum cost cycle. */
1332 int *cycle;
1333 /* Used to record the number of iterations of cancel_negative_cycle. */
1334 int iteration;
1335 /* Vector d[i] holds the minimum cost of path from i to sink. */
1336 gcov_type *d;
1337 int fnum_vertices;
1338 int new_exit_index;
1339 int new_entry_index;
1341 gcc_assert (fixup_graph);
1342 fnum_vertices = fixup_graph->num_vertices;
1343 new_exit_index = fixup_graph->new_exit_index;
1344 new_entry_index = fixup_graph->new_entry_index;
1346 find_max_flow (fixup_graph, new_entry_index, new_exit_index);
1348 /* Initialize the structures for find_negative_cycle(). */
1349 pred = (int *) xcalloc (fnum_vertices, sizeof (int));
1350 d = (gcov_type *) xcalloc (fnum_vertices, sizeof (gcov_type));
1351 cycle = (int *) xcalloc (fnum_vertices, sizeof (int));
1353 /* Repeatedly find and cancel negative cost cycles, until
1354 no more negative cycles exist. This also updates the flow field
1355 to represent the minimum cost flow so far. */
1356 iteration = 0;
1357 while (cancel_negative_cycle (fixup_graph, pred, d, cycle))
1359 iteration++;
1360 if (iteration > MAX_ITER (fixup_graph->num_vertices,
1361 fixup_graph->num_edges))
1362 break;
1365 if (dump_file)
1366 dump_fixup_graph (dump_file, fixup_graph,
1367 "After find_minimum_cost_flow()");
1369 /* Cleanup structures. */
1370 free (pred);
1371 free (d);
1372 free (cycle);
1376 /* Compute the sum of the edge counts in TO_EDGES. */
1378 gcov_type
1379 sum_edge_counts (vec<edge, va_gc> *to_edges)
1381 gcov_type sum = 0;
1382 edge e;
1383 edge_iterator ei;
1385 FOR_EACH_EDGE (e, ei, to_edges)
1387 if (EDGE_INFO (e) && EDGE_INFO (e)->ignore)
1388 continue;
1389 sum += e->count;
1391 return sum;
1395 /* Main routine. Smoothes the initial assigned basic block and edge counts using
1396 a minimum cost flow algorithm, to ensure that the flow consistency rule is
1397 obeyed: sum of outgoing edges = sum of incoming edges for each basic
1398 block. */
1400 void
1401 mcf_smooth_cfg (void)
1403 fixup_graph_type fixup_graph;
1404 memset (&fixup_graph, 0, sizeof (fixup_graph));
1405 create_fixup_graph (&fixup_graph);
1406 find_minimum_cost_flow (&fixup_graph);
1407 adjust_cfg_counts (&fixup_graph);
1408 delete_fixup_graph (&fixup_graph);