[obvious] Fix typos above expand_cond_expr_using_cmove
[official-gcc.git] / gcc / mcf.c
blob6c2b87b4e68222e9b0aa6daaddfbaa572bc8e337
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 "backend.h"
49 #include "hard-reg-set.h"
50 #include "gcov-io.h"
51 #include "profile.h"
52 #include "dumpfile.h"
54 /* CAP_INFINITY: Constant to represent infinite capacity. */
55 #define CAP_INFINITY INTTYPE_MAXIMUM (int64_t)
57 /* COST FUNCTION. */
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)))
64 typedef enum
66 INVALID_EDGE,
67 VERTEX_SPLIT_EDGE, /* Edge to represent vertex with w(e) = w(v). */
68 REDIRECT_EDGE, /* Edge after vertex transformation. */
69 REVERSE_EDGE,
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. */
75 } edge_type;
77 /* Structure to represent an edge in the fixup graph. */
78 typedef struct fixup_edge_d
80 int src;
81 int dest;
82 /* Flag denoting type of edge and attributes for the flow field. */
83 edge_type type;
84 bool is_rflow_valid;
85 /* Index to the normalization vertex added for this edge. */
86 int norm_vertex_index;
87 /* Flow for this edge. */
88 gcov_type flow;
89 /* Residual flow for this edge - used during negative cycle canceling. */
90 gcov_type rflow;
91 gcov_type weight;
92 gcov_type cost;
93 gcov_type max_capacity;
94 } fixup_edge_type;
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;
103 } fixup_vertex_type;
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. */
111 int num_vertices;
112 /* Current number of edges for the graph. */
113 int num_edges;
114 /* Index of new entry vertex. */
115 int new_entry_index;
116 /* Index of new exit vertex. */
117 int new_exit_index;
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;
122 } fixup_graph_type;
124 typedef struct queue_d
126 int *queue;
127 int head;
128 int tail;
129 int size;
130 } queue_type;
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. */
138 int *bb_pred;
139 /* Vector that indicates if basic block i has been visited. */
140 int *is_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. */
150 static void
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);
165 else
167 fprintf (file, "%d", n / 2);
168 if (n % 2)
169 fputs ("''", file);
170 else
171 fputs ("'", file);
176 /* Print edge S->D for given fixup_graph with n' and n'' format.
177 PARAMETERS:
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). */
182 static void
183 print_edge (FILE *file, fixup_graph_type *fixup_graph, int s, int d)
185 print_basic_block (file, fixup_graph, s);
186 fputs ("->", file);
187 print_basic_block (file, fixup_graph, d);
191 /* Dump out the attributes of a given edge FEDGE in the fixup_graph to a
192 file. */
193 static void
194 dump_fixup_edge (FILE *file, fixup_graph_type *fixup_graph, fixup_edge_p fedge)
196 if (!fedge)
198 fputs ("NULL fixup graph edge.\n", file);
199 return;
202 print_edge (file, fixup_graph, fedge->src, fedge->dest);
203 fputs (": ", file);
205 if (fedge->type)
207 fprintf (file, "flow/capacity=%" PRId64 "/",
208 fedge->flow);
209 if (fedge->max_capacity == CAP_INFINITY)
210 fputs ("+oo,", file);
211 else
212 fprintf (file, "%" PRId64 ",", fedge->max_capacity);
215 if (fedge->is_rflow_valid)
217 if (fedge->rflow == CAP_INFINITY)
218 fputs (" rflow=+oo.", file);
219 else
220 fprintf (file, " rflow=%" PRId64 ",", fedge->rflow);
223 fprintf (file, " cost=%" PRId64 ".", fedge->cost);
225 fprintf (file, "\t(%d->%d)", fedge->src, fedge->dest);
227 if (fedge->type)
229 switch (fedge->type)
231 case VERTEX_SPLIT_EDGE:
232 fputs (" @VERTEX_SPLIT_EDGE", file);
233 break;
235 case REDIRECT_EDGE:
236 fputs (" @REDIRECT_EDGE", file);
237 break;
239 case SOURCE_CONNECT_EDGE:
240 fputs (" @SOURCE_CONNECT_EDGE", file);
241 break;
243 case SINK_CONNECT_EDGE:
244 fputs (" @SINK_CONNECT_EDGE", file);
245 break;
247 case REVERSE_EDGE:
248 fputs (" @REVERSE_EDGE", file);
249 break;
251 case BALANCE_EDGE:
252 fputs (" @BALANCE_EDGE", file);
253 break;
255 case REDIRECT_NORMALIZED_EDGE:
256 case REVERSE_NORMALIZED_EDGE:
257 fputs (" @NORMALIZED_EDGE", file);
258 break;
260 default:
261 fputs (" @INVALID_EDGE", file);
262 break;
265 fputs ("\n", 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. */
272 static void
273 dump_fixup_graph (FILE *file, fixup_graph_type *fixup_graph, const char *msg)
275 int i, j;
276 int fnum_vertices, fnum_edges;
278 fixup_vertex_p fvertex_list, pfvertex;
279 fixup_edge_p pfedge;
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);
288 fprintf (file,
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);
299 j++)
301 /* Distinguish forward edges and backward edges in the residual flow
302 network. */
303 if (pfedge->type)
304 fputs ("(f) ", file);
305 else if (pfedge->is_rflow_valid)
306 fputs ("(b) ", file);
307 dump_fixup_edge (file, fixup_graph, pfedge);
311 fputs ("\n", file);
315 /* Utility routines. */
316 /* ln() implementation: approximate calculation. Returns ln of X. */
318 static double
319 mcf_ln (double x)
321 #define E 2.71828
322 int l = 1;
323 double m = E;
325 gcc_assert (x >= 0);
327 while (m < x)
329 m *= E;
330 l++;
333 return l;
337 /* sqrt() implementation: based on open source QUAKE3 code (magic sqrt
338 implementation) by John Carmack. Returns sqrt of X. */
340 static double
341 mcf_sqrt (double x)
343 #define MAGIC_CONST1 0x1fbcf800
344 #define MAGIC_CONST2 0x5f3759df
345 union {
346 int intPart;
347 float floatPart;
348 } convertor, convertor2;
350 gcc_assert (x >= 0);
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. */
365 static fixup_edge_p
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++;
374 if (dump_file)
375 dump_fixup_edge (dump_file, fixup_graph, curr_edge);
376 curr_vertex->succ_edges.safe_push (curr_edge);
377 return 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. */
384 static void
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. */
399 static void
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. */
414 static fixup_edge_p
415 find_fixup_edge (fixup_graph_type *fixup_graph, int src, int dest)
417 int j;
418 fixup_edge_p pfedge;
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);
426 j++)
427 if (pfedge->dest == dest)
428 return pfedge;
430 return NULL;
434 /* Cleanup routine to free structures in FIXUP_GRAPH. */
436 static void
437 delete_fixup_graph (fixup_graph_type *fixup_graph)
439 int i;
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. */
453 static void
454 create_fixup_graph (fixup_graph_type *fixup_graph)
456 double sqrt_avg_vertex_weight = 0;
457 double total_vertex_weight = 0;
458 double k_pos = 0;
459 double k_neg = 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;
463 gcov_type fcost = 0;
464 int new_entry_index = 0, new_exit_index = 0;
465 int i = 0, j = 0;
466 int new_index = 0;
467 basic_block bb;
468 edge e;
469 edge_iterator ei;
470 fixup_edge_p pfedge, r_pfedge;
471 fixup_edge_p fedge_list;
472 int fnum_edges;
474 /* Each basic_block will be split into 2 during vertex transformation. */
475 int fnum_vertices_after_transform = 2 * n_basic_blocks_for_fn (cfun);
476 int fnum_edges_after_transform =
477 n_edges_for_fn (cfun) + n_basic_blocks_for_fn (cfun);
479 /* Count the new SOURCE and EXIT vertices to be added. */
480 int fmax_num_vertices =
481 (fnum_vertices_after_transform + n_edges_for_fn (cfun)
482 + n_basic_blocks_for_fn (cfun) + 2);
484 /* In create_fixup_graph: Each basic block and edge can be split into 3
485 edges. Number of balance edges = n_basic_blocks. So after
486 create_fixup_graph:
487 max_edges = 4 * n_basic_blocks + 3 * n_edges
488 Accounting for residual flow edges
489 max_edges = 2 * (4 * n_basic_blocks + 3 * n_edges)
490 = 8 * n_basic_blocks + 6 * n_edges
491 < 8 * n_basic_blocks + 8 * n_edges. */
492 int fmax_num_edges = 8 * (n_basic_blocks_for_fn (cfun) +
493 n_edges_for_fn (cfun));
495 /* Initial num of vertices in the fixup graph. */
496 fixup_graph->num_vertices = n_basic_blocks_for_fn (cfun);
498 /* Fixup graph vertex list. */
499 fixup_graph->vertex_list =
500 (fixup_vertex_p) xcalloc (fmax_num_vertices, sizeof (fixup_vertex_type));
502 /* Fixup graph edge list. */
503 fixup_graph->edge_list =
504 (fixup_edge_p) xcalloc (fmax_num_edges, sizeof (fixup_edge_type));
506 diff_out_in =
507 (gcov_type *) xcalloc (1 + fnum_vertices_after_transform,
508 sizeof (gcov_type));
510 /* Compute constants b, k_pos, k_neg used in the cost function calculation.
511 b = sqrt(avg_vertex_weight(cfg)); k_pos = b; k_neg = 50b. */
512 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
513 total_vertex_weight += bb->count;
515 sqrt_avg_vertex_weight = mcf_sqrt (total_vertex_weight /
516 n_basic_blocks_for_fn (cfun));
518 k_pos = K_POS (sqrt_avg_vertex_weight);
519 k_neg = K_NEG (sqrt_avg_vertex_weight);
521 /* 1. Vertex Transformation: Split each vertex v into two vertices v' and v'',
522 connected by an edge e from v' to v''. w(e) = w(v). */
524 if (dump_file)
525 fprintf (dump_file, "\nVertex transformation:\n");
527 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
529 /* v'->v'': index1->(index1+1). */
530 i = 2 * bb->index;
531 fcost = (gcov_type) COST (k_pos, bb->count);
532 add_fixup_edge (fixup_graph, i, i + 1, VERTEX_SPLIT_EDGE, bb->count,
533 fcost, CAP_INFINITY);
534 fixup_graph->num_vertices++;
536 FOR_EACH_EDGE (e, ei, bb->succs)
538 /* Edges with ignore attribute set should be treated like they don't
539 exist. */
540 if (EDGE_INFO (e) && EDGE_INFO (e)->ignore)
541 continue;
542 j = 2 * e->dest->index;
543 fcost = (gcov_type) COST (k_pos, e->count);
544 add_fixup_edge (fixup_graph, i + 1, j, REDIRECT_EDGE, e->count, fcost,
545 CAP_INFINITY);
549 /* After vertex transformation. */
550 gcc_assert (fixup_graph->num_vertices == fnum_vertices_after_transform);
551 /* Redirect edges are not added for edges with ignore attribute. */
552 gcc_assert (fixup_graph->num_edges <= fnum_edges_after_transform);
554 fnum_edges_after_transform = fixup_graph->num_edges;
556 /* 2. Initialize D(v). */
557 for (i = 0; i < fnum_edges_after_transform; i++)
559 pfedge = fixup_graph->edge_list + i;
560 diff_out_in[pfedge->src] += pfedge->weight;
561 diff_out_in[pfedge->dest] -= pfedge->weight;
564 /* Entry block - vertex indices 0, 1; EXIT block - vertex indices 2, 3. */
565 for (i = 0; i <= 3; i++)
566 diff_out_in[i] = 0;
568 /* 3. Add reverse edges: needed to decrease counts during smoothing. */
569 if (dump_file)
570 fprintf (dump_file, "\nReverse edges:\n");
571 for (i = 0; i < fnum_edges_after_transform; i++)
573 pfedge = fixup_graph->edge_list + i;
574 if ((pfedge->src == 0) || (pfedge->src == 2))
575 continue;
576 r_pfedge = find_fixup_edge (fixup_graph, pfedge->dest, pfedge->src);
577 if (!r_pfedge && pfedge->weight)
579 /* Skip adding reverse edges for edges with w(e) = 0, as its maximum
580 capacity is 0. */
581 fcost = (gcov_type) COST (k_neg, pfedge->weight);
582 add_fixup_edge (fixup_graph, pfedge->dest, pfedge->src,
583 REVERSE_EDGE, 0, fcost, pfedge->weight);
587 /* 4. Create single source and sink. Connect new source vertex s' to function
588 entry block. Connect sink vertex t' to function exit. */
589 if (dump_file)
590 fprintf (dump_file, "\ns'->S, T->t':\n");
592 new_entry_index = fixup_graph->new_entry_index = fixup_graph->num_vertices;
593 fixup_graph->num_vertices++;
594 /* Set supply_value to 1 to avoid zero count function ENTRY. */
595 add_fixup_edge (fixup_graph, new_entry_index, ENTRY_BLOCK, SOURCE_CONNECT_EDGE,
596 1 /* supply_value */, 0, 1 /* supply_value */);
598 /* Create new exit with EXIT_BLOCK as single pred. */
599 new_exit_index = fixup_graph->new_exit_index = fixup_graph->num_vertices;
600 fixup_graph->num_vertices++;
601 add_fixup_edge (fixup_graph, 2 * EXIT_BLOCK + 1, new_exit_index,
602 SINK_CONNECT_EDGE,
603 0 /* demand_value */, 0, 0 /* demand_value */);
605 /* Connect vertices with unbalanced D(v) to source/sink. */
606 if (dump_file)
607 fprintf (dump_file, "\nD(v) balance:\n");
608 /* Skip vertices for ENTRY (0, 1) and EXIT (2,3) blocks, so start with i = 4.
609 diff_out_in[v''] will be 0, so skip v'' vertices, hence i += 2. */
610 for (i = 4; i < new_entry_index; i += 2)
612 if (diff_out_in[i] > 0)
614 add_fixup_edge (fixup_graph, i, new_exit_index, BALANCE_EDGE, 0, 0,
615 diff_out_in[i]);
616 demand_value += diff_out_in[i];
618 else if (diff_out_in[i] < 0)
620 add_fixup_edge (fixup_graph, new_entry_index, i, BALANCE_EDGE, 0, 0,
621 -diff_out_in[i]);
622 supply_value -= diff_out_in[i];
626 /* Set supply = demand. */
627 if (dump_file)
629 fprintf (dump_file, "\nAdjust supply and demand:\n");
630 fprintf (dump_file, "supply_value=%" PRId64 "\n",
631 supply_value);
632 fprintf (dump_file, "demand_value=%" PRId64 "\n",
633 demand_value);
636 if (demand_value > supply_value)
638 pfedge = find_fixup_edge (fixup_graph, new_entry_index, ENTRY_BLOCK);
639 pfedge->max_capacity += (demand_value - supply_value);
641 else
643 pfedge = find_fixup_edge (fixup_graph, 2 * EXIT_BLOCK + 1, new_exit_index);
644 pfedge->max_capacity += (supply_value - demand_value);
647 /* 6. Normalize edges: remove anti-parallel edges. Anti-parallel edges are
648 created by the vertex transformation step from self-edges in the original
649 CFG and by the reverse edges added earlier. */
650 if (dump_file)
651 fprintf (dump_file, "\nNormalize edges:\n");
653 fnum_edges = fixup_graph->num_edges;
654 fedge_list = fixup_graph->edge_list;
656 for (i = 0; i < fnum_edges; i++)
658 pfedge = fedge_list + i;
659 r_pfedge = find_fixup_edge (fixup_graph, pfedge->dest, pfedge->src);
660 if (((pfedge->type == VERTEX_SPLIT_EDGE)
661 || (pfedge->type == REDIRECT_EDGE)) && r_pfedge)
663 new_index = fixup_graph->num_vertices;
664 fixup_graph->num_vertices++;
666 if (dump_file)
668 fprintf (dump_file, "\nAnti-parallel edge:\n");
669 dump_fixup_edge (dump_file, fixup_graph, pfedge);
670 dump_fixup_edge (dump_file, fixup_graph, r_pfedge);
671 fprintf (dump_file, "New vertex is %d.\n", new_index);
672 fprintf (dump_file, "------------------\n");
675 pfedge->cost /= 2;
676 pfedge->norm_vertex_index = new_index;
677 if (dump_file)
679 fprintf (dump_file, "After normalization:\n");
680 dump_fixup_edge (dump_file, fixup_graph, pfedge);
683 /* Add a new fixup edge: new_index->src. */
684 add_fixup_edge (fixup_graph, new_index, pfedge->src,
685 REVERSE_NORMALIZED_EDGE, 0, r_pfedge->cost,
686 r_pfedge->max_capacity);
687 gcc_assert (fixup_graph->num_vertices <= fmax_num_vertices);
689 /* Edge: r_pfedge->src -> r_pfedge->dest
690 ==> r_pfedge->src -> new_index. */
691 r_pfedge->dest = new_index;
692 r_pfedge->type = REVERSE_NORMALIZED_EDGE;
693 r_pfedge->cost = pfedge->cost;
694 r_pfedge->max_capacity = pfedge->max_capacity;
695 if (dump_file)
696 dump_fixup_edge (dump_file, fixup_graph, r_pfedge);
700 if (dump_file)
701 dump_fixup_graph (dump_file, fixup_graph, "After create_fixup_graph()");
703 /* Cleanup. */
704 free (diff_out_in);
708 /* Allocates space for the structures in AUGMENTING_PATH. The space needed is
709 proportional to the number of nodes in the graph, which is given by
710 GRAPH_SIZE. */
712 static void
713 init_augmenting_path (augmenting_path_type *augmenting_path, int graph_size)
715 augmenting_path->queue_list.queue = (int *)
716 xcalloc (graph_size + 2, sizeof (int));
717 augmenting_path->queue_list.size = graph_size + 2;
718 augmenting_path->bb_pred = (int *) xcalloc (graph_size, sizeof (int));
719 augmenting_path->is_visited = (int *) xcalloc (graph_size, sizeof (int));
722 /* Free the structures in AUGMENTING_PATH. */
723 static void
724 free_augmenting_path (augmenting_path_type *augmenting_path)
726 free (augmenting_path->queue_list.queue);
727 free (augmenting_path->bb_pred);
728 free (augmenting_path->is_visited);
732 /* Queue routines. Assumes queue will never overflow. */
734 static void
735 init_queue (queue_type *queue_list)
737 gcc_assert (queue_list);
738 queue_list->head = 0;
739 queue_list->tail = 0;
742 /* Return true if QUEUE_LIST is empty. */
743 static bool
744 is_empty (queue_type *queue_list)
746 return (queue_list->head == queue_list->tail);
749 /* Insert element X into QUEUE_LIST. */
750 static void
751 enqueue (queue_type *queue_list, int x)
753 gcc_assert (queue_list->tail < queue_list->size);
754 queue_list->queue[queue_list->tail] = x;
755 (queue_list->tail)++;
758 /* Return the first element in QUEUE_LIST. */
759 static int
760 dequeue (queue_type *queue_list)
762 int x;
763 gcc_assert (queue_list->head >= 0);
764 x = queue_list->queue[queue_list->head];
765 (queue_list->head)++;
766 return x;
770 /* Finds a negative cycle in the residual network using
771 the Bellman-Ford algorithm. The flow on the found cycle is reversed by the
772 minimum residual capacity of that cycle. ENTRY and EXIT vertices are not
773 considered.
775 Parameters:
776 FIXUP_GRAPH - Residual graph (input/output)
777 The following are allocated/freed by the caller:
778 PI - Vector to hold predecessors in path (pi = pred index)
779 D - D[I] holds minimum cost of path from i to sink
780 CYCLE - Vector to hold the minimum cost cycle
782 Return:
783 true if a negative cycle was found, false otherwise. */
785 static bool
786 cancel_negative_cycle (fixup_graph_type *fixup_graph,
787 int *pi, gcov_type *d, int *cycle)
789 int i, j, k;
790 int fnum_vertices, fnum_edges;
791 fixup_edge_p fedge_list, pfedge, r_pfedge;
792 bool found_cycle = false;
793 int cycle_start = 0, cycle_end = 0;
794 gcov_type sum_cost = 0, cycle_flow = 0;
795 int new_entry_index;
796 bool propagated = false;
798 gcc_assert (fixup_graph);
799 fnum_vertices = fixup_graph->num_vertices;
800 fnum_edges = fixup_graph->num_edges;
801 fedge_list = fixup_graph->edge_list;
802 new_entry_index = fixup_graph->new_entry_index;
804 /* Initialize. */
805 /* Skip ENTRY. */
806 for (i = 1; i < fnum_vertices; i++)
808 d[i] = CAP_INFINITY;
809 pi[i] = -1;
810 cycle[i] = -1;
812 d[ENTRY_BLOCK] = 0;
814 /* Relax. */
815 for (k = 1; k < fnum_vertices; k++)
817 propagated = false;
818 for (i = 0; i < fnum_edges; i++)
820 pfedge = fedge_list + i;
821 if (pfedge->src == new_entry_index)
822 continue;
823 if (pfedge->is_rflow_valid && pfedge->rflow
824 && d[pfedge->src] != CAP_INFINITY
825 && (d[pfedge->dest] > d[pfedge->src] + pfedge->cost))
827 d[pfedge->dest] = d[pfedge->src] + pfedge->cost;
828 pi[pfedge->dest] = pfedge->src;
829 propagated = true;
832 if (!propagated)
833 break;
836 if (!propagated)
837 /* No negative cycles exist. */
838 return 0;
840 /* Detect. */
841 for (i = 0; i < fnum_edges; i++)
843 pfedge = fedge_list + i;
844 if (pfedge->src == new_entry_index)
845 continue;
846 if (pfedge->is_rflow_valid && pfedge->rflow
847 && d[pfedge->src] != CAP_INFINITY
848 && (d[pfedge->dest] > d[pfedge->src] + pfedge->cost))
850 found_cycle = true;
851 break;
855 if (!found_cycle)
856 return 0;
858 /* Augment the cycle with the cycle's minimum residual capacity. */
859 found_cycle = false;
860 cycle[0] = pfedge->dest;
861 j = pfedge->dest;
863 for (i = 1; i < fnum_vertices; i++)
865 j = pi[j];
866 cycle[i] = j;
867 for (k = 0; k < i; k++)
869 if (cycle[k] == j)
871 /* cycle[k] -> ... -> cycle[i]. */
872 cycle_start = k;
873 cycle_end = i;
874 found_cycle = true;
875 break;
878 if (found_cycle)
879 break;
882 gcc_assert (cycle[cycle_start] == cycle[cycle_end]);
883 if (dump_file)
884 fprintf (dump_file, "\nNegative cycle length is %d:\n",
885 cycle_end - cycle_start);
887 sum_cost = 0;
888 cycle_flow = CAP_INFINITY;
889 for (k = cycle_start; k < cycle_end; k++)
891 pfedge = find_fixup_edge (fixup_graph, cycle[k + 1], cycle[k]);
892 cycle_flow = MIN (cycle_flow, pfedge->rflow);
893 sum_cost += pfedge->cost;
894 if (dump_file)
895 fprintf (dump_file, "%d ", cycle[k]);
898 if (dump_file)
900 fprintf (dump_file, "%d", cycle[k]);
901 fprintf (dump_file,
902 ": (%" PRId64 ", %" PRId64
903 ")\n", sum_cost, cycle_flow);
904 fprintf (dump_file,
905 "Augment cycle with %" PRId64 "\n",
906 cycle_flow);
909 for (k = cycle_start; k < cycle_end; k++)
911 pfedge = find_fixup_edge (fixup_graph, cycle[k + 1], cycle[k]);
912 r_pfedge = find_fixup_edge (fixup_graph, cycle[k], cycle[k + 1]);
913 pfedge->rflow -= cycle_flow;
914 if (pfedge->type)
915 pfedge->flow += cycle_flow;
916 r_pfedge->rflow += cycle_flow;
917 if (r_pfedge->type)
918 r_pfedge->flow -= cycle_flow;
921 return true;
925 /* Computes the residual flow for FIXUP_GRAPH by setting the rflow field of
926 the edges. ENTRY and EXIT vertices should not be considered. */
928 static void
929 compute_residual_flow (fixup_graph_type *fixup_graph)
931 int i;
932 int fnum_edges;
933 fixup_edge_p fedge_list, pfedge;
935 gcc_assert (fixup_graph);
937 if (dump_file)
938 fputs ("\ncompute_residual_flow():\n", dump_file);
940 fnum_edges = fixup_graph->num_edges;
941 fedge_list = fixup_graph->edge_list;
943 for (i = 0; i < fnum_edges; i++)
945 pfedge = fedge_list + i;
946 pfedge->rflow = pfedge->max_capacity - pfedge->flow;
947 pfedge->is_rflow_valid = true;
948 add_rfixup_edge (fixup_graph, pfedge->dest, pfedge->src, pfedge->flow,
949 -pfedge->cost);
954 /* Uses Edmonds-Karp algorithm - BFS to find augmenting path from SOURCE to
955 SINK. The fields in the edge vector in the FIXUP_GRAPH are not modified by
956 this routine. The vector bb_pred in the AUGMENTING_PATH structure is updated
957 to reflect the path found.
958 Returns: 0 if no augmenting path is found, 1 otherwise. */
960 static int
961 find_augmenting_path (fixup_graph_type *fixup_graph,
962 augmenting_path_type *augmenting_path, int source,
963 int sink)
965 int u = 0;
966 int i;
967 fixup_vertex_p fvertex_list, pfvertex;
968 fixup_edge_p pfedge;
969 int *bb_pred, *is_visited;
970 queue_type *queue_list;
972 gcc_assert (augmenting_path);
973 bb_pred = augmenting_path->bb_pred;
974 gcc_assert (bb_pred);
975 is_visited = augmenting_path->is_visited;
976 gcc_assert (is_visited);
977 queue_list = &(augmenting_path->queue_list);
979 gcc_assert (fixup_graph);
981 fvertex_list = fixup_graph->vertex_list;
983 for (u = 0; u < fixup_graph->num_vertices; u++)
984 is_visited[u] = 0;
986 init_queue (queue_list);
987 enqueue (queue_list, source);
988 bb_pred[source] = -1;
990 while (!is_empty (queue_list))
992 u = dequeue (queue_list);
993 is_visited[u] = 1;
994 pfvertex = fvertex_list + u;
995 for (i = 0; pfvertex->succ_edges.iterate (i, &pfedge);
996 i++)
998 int dest = pfedge->dest;
999 if ((pfedge->rflow > 0) && (is_visited[dest] == 0))
1001 enqueue (queue_list, dest);
1002 bb_pred[dest] = u;
1003 is_visited[dest] = 1;
1004 if (dest == sink)
1005 return 1;
1010 return 0;
1014 /* Routine to find the maximal flow:
1015 Algorithm:
1016 1. Initialize flow to 0
1017 2. Find an augmenting path form source to sink.
1018 3. Send flow equal to the path's residual capacity along the edges of this path.
1019 4. Repeat steps 2 and 3 until no new augmenting path is found.
1021 Parameters:
1022 SOURCE: index of source vertex (input)
1023 SINK: index of sink vertex (input)
1024 FIXUP_GRAPH: adjacency matrix representing the graph. The flow of the edges will be
1025 set to have a valid maximal flow by this routine. (input)
1026 Return: Maximum flow possible. */
1028 static gcov_type
1029 find_max_flow (fixup_graph_type *fixup_graph, int source, int sink)
1031 int fnum_edges;
1032 augmenting_path_type augmenting_path;
1033 int *bb_pred;
1034 gcov_type max_flow = 0;
1035 int i, u;
1036 fixup_edge_p fedge_list, pfedge, r_pfedge;
1038 gcc_assert (fixup_graph);
1040 fnum_edges = fixup_graph->num_edges;
1041 fedge_list = fixup_graph->edge_list;
1043 /* Initialize flow to 0. */
1044 for (i = 0; i < fnum_edges; i++)
1046 pfedge = fedge_list + i;
1047 pfedge->flow = 0;
1050 compute_residual_flow (fixup_graph);
1052 init_augmenting_path (&augmenting_path, fixup_graph->num_vertices);
1054 bb_pred = augmenting_path.bb_pred;
1055 while (find_augmenting_path (fixup_graph, &augmenting_path, source, sink))
1057 /* Determine the amount by which we can increment the flow. */
1058 gcov_type increment = CAP_INFINITY;
1059 for (u = sink; u != source; u = bb_pred[u])
1061 pfedge = find_fixup_edge (fixup_graph, bb_pred[u], u);
1062 increment = MIN (increment, pfedge->rflow);
1064 max_flow += increment;
1066 /* Now increment the flow. EXIT vertex index is 1. */
1067 for (u = sink; u != source; u = bb_pred[u])
1069 pfedge = find_fixup_edge (fixup_graph, bb_pred[u], u);
1070 r_pfedge = find_fixup_edge (fixup_graph, u, bb_pred[u]);
1071 if (pfedge->type)
1073 /* forward edge. */
1074 pfedge->flow += increment;
1075 pfedge->rflow -= increment;
1076 r_pfedge->rflow += increment;
1078 else
1080 /* backward edge. */
1081 gcc_assert (r_pfedge->type);
1082 r_pfedge->rflow += increment;
1083 r_pfedge->flow -= increment;
1084 pfedge->rflow -= increment;
1088 if (dump_file)
1090 fprintf (dump_file, "\nDump augmenting path:\n");
1091 for (u = sink; u != source; u = bb_pred[u])
1093 print_basic_block (dump_file, fixup_graph, u);
1094 fprintf (dump_file, "<-");
1096 fprintf (dump_file,
1097 "ENTRY (path_capacity=%" PRId64 ")\n",
1098 increment);
1099 fprintf (dump_file,
1100 "Network flow is %" PRId64 ".\n",
1101 max_flow);
1105 free_augmenting_path (&augmenting_path);
1106 if (dump_file)
1107 dump_fixup_graph (dump_file, fixup_graph, "After find_max_flow()");
1108 return max_flow;
1112 /* Computes the corrected edge and basic block weights using FIXUP_GRAPH
1113 after applying the find_minimum_cost_flow() routine. */
1115 static void
1116 adjust_cfg_counts (fixup_graph_type *fixup_graph)
1118 basic_block bb;
1119 edge e;
1120 edge_iterator ei;
1121 int i, j;
1122 fixup_edge_p pfedge, pfedge_n;
1124 gcc_assert (fixup_graph);
1126 if (dump_file)
1127 fprintf (dump_file, "\nadjust_cfg_counts():\n");
1129 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun),
1130 EXIT_BLOCK_PTR_FOR_FN (cfun), next_bb)
1132 i = 2 * bb->index;
1134 /* Fixup BB. */
1135 if (dump_file)
1136 fprintf (dump_file,
1137 "BB%d: %" PRId64 "", bb->index, bb->count);
1139 pfedge = find_fixup_edge (fixup_graph, i, i + 1);
1140 if (pfedge->flow)
1142 bb->count += pfedge->flow;
1143 if (dump_file)
1145 fprintf (dump_file, " + %" PRId64 "(",
1146 pfedge->flow);
1147 print_edge (dump_file, fixup_graph, i, i + 1);
1148 fprintf (dump_file, ")");
1152 pfedge_n =
1153 find_fixup_edge (fixup_graph, i + 1, pfedge->norm_vertex_index);
1154 /* Deduct flow from normalized reverse edge. */
1155 if (pfedge->norm_vertex_index && pfedge_n->flow)
1157 bb->count -= pfedge_n->flow;
1158 if (dump_file)
1160 fprintf (dump_file, " - %" PRId64 "(",
1161 pfedge_n->flow);
1162 print_edge (dump_file, fixup_graph, i + 1,
1163 pfedge->norm_vertex_index);
1164 fprintf (dump_file, ")");
1167 if (dump_file)
1168 fprintf (dump_file, " = %" PRId64 "\n", bb->count);
1170 /* Fixup edge. */
1171 FOR_EACH_EDGE (e, ei, bb->succs)
1173 /* Treat edges with ignore attribute set as if they don't exist. */
1174 if (EDGE_INFO (e) && EDGE_INFO (e)->ignore)
1175 continue;
1177 j = 2 * e->dest->index;
1178 if (dump_file)
1179 fprintf (dump_file, "%d->%d: %" PRId64 "",
1180 bb->index, e->dest->index, e->count);
1182 pfedge = find_fixup_edge (fixup_graph, i + 1, j);
1184 if (bb->index != e->dest->index)
1186 /* Non-self edge. */
1187 if (pfedge->flow)
1189 e->count += pfedge->flow;
1190 if (dump_file)
1192 fprintf (dump_file, " + %" PRId64 "(",
1193 pfedge->flow);
1194 print_edge (dump_file, fixup_graph, i + 1, j);
1195 fprintf (dump_file, ")");
1199 pfedge_n =
1200 find_fixup_edge (fixup_graph, j, pfedge->norm_vertex_index);
1201 /* Deduct flow from normalized reverse edge. */
1202 if (pfedge->norm_vertex_index && pfedge_n->flow)
1204 e->count -= pfedge_n->flow;
1205 if (dump_file)
1207 fprintf (dump_file, " - %" PRId64 "(",
1208 pfedge_n->flow);
1209 print_edge (dump_file, fixup_graph, j,
1210 pfedge->norm_vertex_index);
1211 fprintf (dump_file, ")");
1215 else
1217 /* Handle self edges. Self edge is split with a normalization
1218 vertex. Here i=j. */
1219 pfedge = find_fixup_edge (fixup_graph, j, i + 1);
1220 pfedge_n =
1221 find_fixup_edge (fixup_graph, i + 1, pfedge->norm_vertex_index);
1222 e->count += pfedge_n->flow;
1223 bb->count += pfedge_n->flow;
1224 if (dump_file)
1226 fprintf (dump_file, "(self edge)");
1227 fprintf (dump_file, " + %" PRId64 "(",
1228 pfedge_n->flow);
1229 print_edge (dump_file, fixup_graph, i + 1,
1230 pfedge->norm_vertex_index);
1231 fprintf (dump_file, ")");
1235 if (bb->count)
1236 e->probability = REG_BR_PROB_BASE * e->count / bb->count;
1237 if (dump_file)
1238 fprintf (dump_file, " = %" PRId64 "\t(%.1f%%)\n",
1239 e->count, e->probability * 100.0 / REG_BR_PROB_BASE);
1243 ENTRY_BLOCK_PTR_FOR_FN (cfun)->count =
1244 sum_edge_counts (ENTRY_BLOCK_PTR_FOR_FN (cfun)->succs);
1245 EXIT_BLOCK_PTR_FOR_FN (cfun)->count =
1246 sum_edge_counts (EXIT_BLOCK_PTR_FOR_FN (cfun)->preds);
1248 /* Compute edge probabilities. */
1249 FOR_ALL_BB_FN (bb, cfun)
1251 if (bb->count)
1253 FOR_EACH_EDGE (e, ei, bb->succs)
1254 e->probability = REG_BR_PROB_BASE * e->count / bb->count;
1256 else
1258 int total = 0;
1259 FOR_EACH_EDGE (e, ei, bb->succs)
1260 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
1261 total++;
1262 if (total)
1264 FOR_EACH_EDGE (e, ei, bb->succs)
1266 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
1267 e->probability = REG_BR_PROB_BASE / total;
1268 else
1269 e->probability = 0;
1272 else
1274 total += EDGE_COUNT (bb->succs);
1275 FOR_EACH_EDGE (e, ei, bb->succs)
1276 e->probability = REG_BR_PROB_BASE / total;
1281 if (dump_file)
1283 fprintf (dump_file, "\nCheck %s() CFG flow conservation:\n",
1284 current_function_name ());
1285 FOR_EACH_BB_FN (bb, cfun)
1287 if ((bb->count != sum_edge_counts (bb->preds))
1288 || (bb->count != sum_edge_counts (bb->succs)))
1290 fprintf (dump_file,
1291 "BB%d(%" PRId64 ") **INVALID**: ",
1292 bb->index, bb->count);
1293 fprintf (stderr,
1294 "******** BB%d(%" PRId64
1295 ") **INVALID**: \n", bb->index, bb->count);
1296 fprintf (dump_file, "in_edges=%" PRId64 " ",
1297 sum_edge_counts (bb->preds));
1298 fprintf (dump_file, "out_edges=%" PRId64 "\n",
1299 sum_edge_counts (bb->succs));
1306 /* Implements the negative cycle canceling algorithm to compute a minimum cost
1307 flow.
1308 Algorithm:
1309 1. Find maximal flow.
1310 2. Form residual network
1311 3. Repeat:
1312 While G contains a negative cost cycle C, reverse the flow on the found cycle
1313 by the minimum residual capacity in that cycle.
1314 4. Form the minimal cost flow
1315 f(u,v) = rf(v, u)
1316 Input:
1317 FIXUP_GRAPH - Initial fixup graph.
1318 The flow field is modified to represent the minimum cost flow. */
1320 static void
1321 find_minimum_cost_flow (fixup_graph_type *fixup_graph)
1323 /* Holds the index of predecessor in path. */
1324 int *pred;
1325 /* Used to hold the minimum cost cycle. */
1326 int *cycle;
1327 /* Used to record the number of iterations of cancel_negative_cycle. */
1328 int iteration;
1329 /* Vector d[i] holds the minimum cost of path from i to sink. */
1330 gcov_type *d;
1331 int fnum_vertices;
1332 int new_exit_index;
1333 int new_entry_index;
1335 gcc_assert (fixup_graph);
1336 fnum_vertices = fixup_graph->num_vertices;
1337 new_exit_index = fixup_graph->new_exit_index;
1338 new_entry_index = fixup_graph->new_entry_index;
1340 find_max_flow (fixup_graph, new_entry_index, new_exit_index);
1342 /* Initialize the structures for find_negative_cycle(). */
1343 pred = (int *) xcalloc (fnum_vertices, sizeof (int));
1344 d = (gcov_type *) xcalloc (fnum_vertices, sizeof (gcov_type));
1345 cycle = (int *) xcalloc (fnum_vertices, sizeof (int));
1347 /* Repeatedly find and cancel negative cost cycles, until
1348 no more negative cycles exist. This also updates the flow field
1349 to represent the minimum cost flow so far. */
1350 iteration = 0;
1351 while (cancel_negative_cycle (fixup_graph, pred, d, cycle))
1353 iteration++;
1354 if (iteration > MAX_ITER (fixup_graph->num_vertices,
1355 fixup_graph->num_edges))
1356 break;
1359 if (dump_file)
1360 dump_fixup_graph (dump_file, fixup_graph,
1361 "After find_minimum_cost_flow()");
1363 /* Cleanup structures. */
1364 free (pred);
1365 free (d);
1366 free (cycle);
1370 /* Compute the sum of the edge counts in TO_EDGES. */
1372 gcov_type
1373 sum_edge_counts (vec<edge, va_gc> *to_edges)
1375 gcov_type sum = 0;
1376 edge e;
1377 edge_iterator ei;
1379 FOR_EACH_EDGE (e, ei, to_edges)
1381 if (EDGE_INFO (e) && EDGE_INFO (e)->ignore)
1382 continue;
1383 sum += e->count;
1385 return sum;
1389 /* Main routine. Smoothes the initial assigned basic block and edge counts using
1390 a minimum cost flow algorithm, to ensure that the flow consistency rule is
1391 obeyed: sum of outgoing edges = sum of incoming edges for each basic
1392 block. */
1394 void
1395 mcf_smooth_cfg (void)
1397 fixup_graph_type fixup_graph;
1398 memset (&fixup_graph, 0, sizeof (fixup_graph));
1399 create_fixup_graph (&fixup_graph);
1400 find_minimum_cost_flow (&fixup_graph);
1401 adjust_cfg_counts (&fixup_graph);
1402 delete_fixup_graph (&fixup_graph);