graph.c (init_graph_slim_pretty_print): Remove.
[official-gcc.git] / gcc / profile.c
blobc469df56dba70c754d4f2be80e2ee8ccbbd0400b
1 /* Calculate branch probabilities, and basic block execution counts.
2 Copyright (C) 1990-2013 Free Software Foundation, Inc.
3 Contributed by James E. Wilson, UC Berkeley/Cygnus Support;
4 based on some ideas from Dain Samples of UC Berkeley.
5 Further mangling by Bob Manson, Cygnus Support.
7 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 for more details.
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
23 /* Generate basic block profile instrumentation and auxiliary files.
24 Profile generation is optimized, so that not all arcs in the basic
25 block graph need instrumenting. First, the BB graph is closed with
26 one entry (function start), and one exit (function exit). Any
27 ABNORMAL_EDGE cannot be instrumented (because there is no control
28 path to place the code). We close the graph by inserting fake
29 EDGE_FAKE edges to the EXIT_BLOCK, from the sources of abnormal
30 edges that do not go to the exit_block. We ignore such abnormal
31 edges. Naturally these fake edges are never directly traversed,
32 and so *cannot* be directly instrumented. Some other graph
33 massaging is done. To optimize the instrumentation we generate the
34 BB minimal span tree, only edges that are not on the span tree
35 (plus the entry point) need instrumenting. From that information
36 all other edge counts can be deduced. By construction all fake
37 edges must be on the spanning tree. We also attempt to place
38 EDGE_CRITICAL edges on the spanning tree.
40 The auxiliary files generated are <dumpbase>.gcno (at compile time)
41 and <dumpbase>.gcda (at run time). The format is
42 described in full in gcov-io.h. */
44 /* ??? Register allocation should use basic block execution counts to
45 give preference to the most commonly executed blocks. */
47 /* ??? Should calculate branch probabilities before instrumenting code, since
48 then we can use arc counts to help decide which arcs to instrument. */
50 #include "config.h"
51 #include "system.h"
52 #include "coretypes.h"
53 #include "tm.h"
54 #include "rtl.h"
55 #include "flags.h"
56 #include "regs.h"
57 #include "expr.h"
58 #include "function.h"
59 #include "basic-block.h"
60 #include "diagnostic-core.h"
61 #include "coverage.h"
62 #include "value-prof.h"
63 #include "tree.h"
64 #include "tree-flow.h"
65 #include "cfgloop.h"
66 #include "dumpfile.h"
68 #include "profile.h"
70 struct bb_info {
71 unsigned int count_valid : 1;
73 /* Number of successor and predecessor edges. */
74 gcov_type succ_count;
75 gcov_type pred_count;
78 #define BB_INFO(b) ((struct bb_info *) (b)->aux)
81 /* Counter summary from the last set of coverage counts read. */
83 const struct gcov_ctr_summary *profile_info;
85 /* Counter working set information computed from the current counter
86 summary. Not initialized unless profile_info summary is non-NULL. */
87 static gcov_working_set_t gcov_working_sets[NUM_GCOV_WORKING_SETS];
89 /* Collect statistics on the performance of this pass for the entire source
90 file. */
92 static int total_num_blocks;
93 static int total_num_edges;
94 static int total_num_edges_ignored;
95 static int total_num_edges_instrumented;
96 static int total_num_blocks_created;
97 static int total_num_passes;
98 static int total_num_times_called;
99 static int total_hist_br_prob[20];
100 static int total_num_branches;
102 /* Forward declarations. */
103 static void find_spanning_tree (struct edge_list *);
105 /* Add edge instrumentation code to the entire insn chain.
107 F is the first insn of the chain.
108 NUM_BLOCKS is the number of basic blocks found in F. */
110 static unsigned
111 instrument_edges (struct edge_list *el)
113 unsigned num_instr_edges = 0;
114 int num_edges = NUM_EDGES (el);
115 basic_block bb;
117 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
119 edge e;
120 edge_iterator ei;
122 FOR_EACH_EDGE (e, ei, bb->succs)
124 struct edge_info *inf = EDGE_INFO (e);
126 if (!inf->ignore && !inf->on_tree)
128 gcc_assert (!(e->flags & EDGE_ABNORMAL));
129 if (dump_file)
130 fprintf (dump_file, "Edge %d to %d instrumented%s\n",
131 e->src->index, e->dest->index,
132 EDGE_CRITICAL_P (e) ? " (and split)" : "");
133 gimple_gen_edge_profiler (num_instr_edges++, e);
138 total_num_blocks_created += num_edges;
139 if (dump_file)
140 fprintf (dump_file, "%d edges instrumented\n", num_instr_edges);
141 return num_instr_edges;
144 /* Add code to measure histograms for values in list VALUES. */
145 static void
146 instrument_values (histogram_values values)
148 unsigned i;
150 /* Emit code to generate the histograms before the insns. */
152 for (i = 0; i < values.length (); i++)
154 histogram_value hist = values[i];
155 unsigned t = COUNTER_FOR_HIST_TYPE (hist->type);
157 if (!coverage_counter_alloc (t, hist->n_counters))
158 continue;
160 switch (hist->type)
162 case HIST_TYPE_INTERVAL:
163 gimple_gen_interval_profiler (hist, t, 0);
164 break;
166 case HIST_TYPE_POW2:
167 gimple_gen_pow2_profiler (hist, t, 0);
168 break;
170 case HIST_TYPE_SINGLE_VALUE:
171 gimple_gen_one_value_profiler (hist, t, 0);
172 break;
174 case HIST_TYPE_CONST_DELTA:
175 gimple_gen_const_delta_profiler (hist, t, 0);
176 break;
178 case HIST_TYPE_INDIR_CALL:
179 gimple_gen_ic_profiler (hist, t, 0);
180 break;
182 case HIST_TYPE_AVERAGE:
183 gimple_gen_average_profiler (hist, t, 0);
184 break;
186 case HIST_TYPE_IOR:
187 gimple_gen_ior_profiler (hist, t, 0);
188 break;
190 default:
191 gcc_unreachable ();
197 /* Fill the working set information into the profile_info structure. */
199 void
200 get_working_sets (void)
202 unsigned ws_ix, pctinc, pct;
203 gcov_working_set_t *ws_info;
205 if (!profile_info)
206 return;
208 compute_working_sets (profile_info, gcov_working_sets);
210 if (dump_file)
212 fprintf (dump_file, "Counter working sets:\n");
213 /* Multiply the percentage by 100 to avoid float. */
214 pctinc = 100 * 100 / NUM_GCOV_WORKING_SETS;
215 for (ws_ix = 0, pct = pctinc; ws_ix < NUM_GCOV_WORKING_SETS;
216 ws_ix++, pct += pctinc)
218 if (ws_ix == NUM_GCOV_WORKING_SETS - 1)
219 pct = 9990;
220 ws_info = &gcov_working_sets[ws_ix];
221 /* Print out the percentage using int arithmatic to avoid float. */
222 fprintf (dump_file, "\t\t%u.%02u%%: num counts=%u, min counter="
223 HOST_WIDEST_INT_PRINT_DEC "\n",
224 pct / 100, pct - (pct / 100 * 100),
225 ws_info->num_counters,
226 (HOST_WIDEST_INT)ws_info->min_counter);
231 /* Given a the desired percentage of the full profile (sum_all from the
232 summary), multiplied by 10 to avoid float in PCT_TIMES_10, returns
233 the corresponding working set information. If an exact match for
234 the percentage isn't found, the closest value is used. */
236 gcov_working_set_t *
237 find_working_set (unsigned pct_times_10)
239 unsigned i;
240 if (!profile_info)
241 return NULL;
242 gcc_assert (pct_times_10 <= 1000);
243 if (pct_times_10 >= 999)
244 return &gcov_working_sets[NUM_GCOV_WORKING_SETS - 1];
245 i = pct_times_10 * NUM_GCOV_WORKING_SETS / 1000;
246 if (!i)
247 return &gcov_working_sets[0];
248 return &gcov_working_sets[i - 1];
251 /* Computes hybrid profile for all matching entries in da_file.
253 CFG_CHECKSUM is the precomputed checksum for the CFG. */
255 static gcov_type *
256 get_exec_counts (unsigned cfg_checksum, unsigned lineno_checksum)
258 unsigned num_edges = 0;
259 basic_block bb;
260 gcov_type *counts;
262 /* Count the edges to be (possibly) instrumented. */
263 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
265 edge e;
266 edge_iterator ei;
268 FOR_EACH_EDGE (e, ei, bb->succs)
269 if (!EDGE_INFO (e)->ignore && !EDGE_INFO (e)->on_tree)
270 num_edges++;
273 counts = get_coverage_counts (GCOV_COUNTER_ARCS, num_edges, cfg_checksum,
274 lineno_checksum, &profile_info);
275 if (!counts)
276 return NULL;
278 get_working_sets();
280 if (dump_file && profile_info)
281 fprintf(dump_file, "Merged %u profiles with maximal count %u.\n",
282 profile_info->runs, (unsigned) profile_info->sum_max);
284 return counts;
288 static bool
289 is_edge_inconsistent (vec<edge, va_gc> *edges)
291 edge e;
292 edge_iterator ei;
293 FOR_EACH_EDGE (e, ei, edges)
295 if (!EDGE_INFO (e)->ignore)
297 if (e->count < 0
298 && (!(e->flags & EDGE_FAKE)
299 || !block_ends_with_call_p (e->src)))
301 if (dump_file)
303 fprintf (dump_file,
304 "Edge %i->%i is inconsistent, count"HOST_WIDEST_INT_PRINT_DEC,
305 e->src->index, e->dest->index, e->count);
306 dump_bb (dump_file, e->src, 0, TDF_DETAILS);
307 dump_bb (dump_file, e->dest, 0, TDF_DETAILS);
309 return true;
313 return false;
316 static void
317 correct_negative_edge_counts (void)
319 basic_block bb;
320 edge e;
321 edge_iterator ei;
323 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
325 FOR_EACH_EDGE (e, ei, bb->succs)
327 if (e->count < 0)
328 e->count = 0;
333 /* Check consistency.
334 Return true if inconsistency is found. */
335 static bool
336 is_inconsistent (void)
338 basic_block bb;
339 bool inconsistent = false;
340 FOR_EACH_BB (bb)
342 inconsistent |= is_edge_inconsistent (bb->preds);
343 if (!dump_file && inconsistent)
344 return true;
345 inconsistent |= is_edge_inconsistent (bb->succs);
346 if (!dump_file && inconsistent)
347 return true;
348 if (bb->count < 0)
350 if (dump_file)
352 fprintf (dump_file, "BB %i count is negative "
353 HOST_WIDEST_INT_PRINT_DEC,
354 bb->index,
355 bb->count);
356 dump_bb (dump_file, bb, 0, TDF_DETAILS);
358 inconsistent = true;
360 if (bb->count != sum_edge_counts (bb->preds))
362 if (dump_file)
364 fprintf (dump_file, "BB %i count does not match sum of incoming edges "
365 HOST_WIDEST_INT_PRINT_DEC" should be " HOST_WIDEST_INT_PRINT_DEC,
366 bb->index,
367 bb->count,
368 sum_edge_counts (bb->preds));
369 dump_bb (dump_file, bb, 0, TDF_DETAILS);
371 inconsistent = true;
373 if (bb->count != sum_edge_counts (bb->succs) &&
374 ! (find_edge (bb, EXIT_BLOCK_PTR) != NULL && block_ends_with_call_p (bb)))
376 if (dump_file)
378 fprintf (dump_file, "BB %i count does not match sum of outgoing edges "
379 HOST_WIDEST_INT_PRINT_DEC" should be " HOST_WIDEST_INT_PRINT_DEC,
380 bb->index,
381 bb->count,
382 sum_edge_counts (bb->succs));
383 dump_bb (dump_file, bb, 0, TDF_DETAILS);
385 inconsistent = true;
387 if (!dump_file && inconsistent)
388 return true;
391 return inconsistent;
394 /* Set each basic block count to the sum of its outgoing edge counts */
395 static void
396 set_bb_counts (void)
398 basic_block bb;
399 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
401 bb->count = sum_edge_counts (bb->succs);
402 gcc_assert (bb->count >= 0);
406 /* Reads profile data and returns total number of edge counts read */
407 static int
408 read_profile_edge_counts (gcov_type *exec_counts)
410 basic_block bb;
411 int num_edges = 0;
412 int exec_counts_pos = 0;
413 /* For each edge not on the spanning tree, set its execution count from
414 the .da file. */
415 /* The first count in the .da file is the number of times that the function
416 was entered. This is the exec_count for block zero. */
418 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
420 edge e;
421 edge_iterator ei;
423 FOR_EACH_EDGE (e, ei, bb->succs)
424 if (!EDGE_INFO (e)->ignore && !EDGE_INFO (e)->on_tree)
426 num_edges++;
427 if (exec_counts)
429 e->count = exec_counts[exec_counts_pos++];
430 if (e->count > profile_info->sum_max)
432 if (flag_profile_correction)
434 static bool informed = 0;
435 if (!informed)
436 inform (input_location,
437 "corrupted profile info: edge count exceeds maximal count");
438 informed = 1;
440 else
441 error ("corrupted profile info: edge from %i to %i exceeds maximal count",
442 bb->index, e->dest->index);
445 else
446 e->count = 0;
448 EDGE_INFO (e)->count_valid = 1;
449 BB_INFO (bb)->succ_count--;
450 BB_INFO (e->dest)->pred_count--;
451 if (dump_file)
453 fprintf (dump_file, "\nRead edge from %i to %i, count:",
454 bb->index, e->dest->index);
455 fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
456 (HOST_WIDEST_INT) e->count);
461 return num_edges;
464 #define OVERLAP_BASE 10000
466 /* Compare the static estimated profile to the actual profile, and
467 return the "degree of overlap" measure between them.
469 Degree of overlap is a number between 0 and OVERLAP_BASE. It is
470 the sum of each basic block's minimum relative weights between
471 two profiles. And overlap of OVERLAP_BASE means two profiles are
472 identical. */
474 static int
475 compute_frequency_overlap (void)
477 gcov_type count_total = 0, freq_total = 0;
478 int overlap = 0;
479 basic_block bb;
481 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
483 count_total += bb->count;
484 freq_total += bb->frequency;
487 if (count_total == 0 || freq_total == 0)
488 return 0;
490 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
491 overlap += MIN (bb->count * OVERLAP_BASE / count_total,
492 bb->frequency * OVERLAP_BASE / freq_total);
494 return overlap;
497 /* Compute the branch probabilities for the various branches.
498 Annotate them accordingly.
500 CFG_CHECKSUM is the precomputed checksum for the CFG. */
502 static void
503 compute_branch_probabilities (unsigned cfg_checksum, unsigned lineno_checksum)
505 basic_block bb;
506 int i;
507 int num_edges = 0;
508 int changes;
509 int passes;
510 int hist_br_prob[20];
511 int num_branches;
512 gcov_type *exec_counts = get_exec_counts (cfg_checksum, lineno_checksum);
513 int inconsistent = 0;
515 /* Very simple sanity checks so we catch bugs in our profiling code. */
516 if (!profile_info)
517 return;
518 if (profile_info->run_max * profile_info->runs < profile_info->sum_max)
520 error ("corrupted profile info: run_max * runs < sum_max");
521 exec_counts = NULL;
524 if (profile_info->sum_all < profile_info->sum_max)
526 error ("corrupted profile info: sum_all is smaller than sum_max");
527 exec_counts = NULL;
530 /* Attach extra info block to each bb. */
531 alloc_aux_for_blocks (sizeof (struct bb_info));
532 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
534 edge e;
535 edge_iterator ei;
537 FOR_EACH_EDGE (e, ei, bb->succs)
538 if (!EDGE_INFO (e)->ignore)
539 BB_INFO (bb)->succ_count++;
540 FOR_EACH_EDGE (e, ei, bb->preds)
541 if (!EDGE_INFO (e)->ignore)
542 BB_INFO (bb)->pred_count++;
545 /* Avoid predicting entry on exit nodes. */
546 BB_INFO (EXIT_BLOCK_PTR)->succ_count = 2;
547 BB_INFO (ENTRY_BLOCK_PTR)->pred_count = 2;
549 num_edges = read_profile_edge_counts (exec_counts);
551 if (dump_file)
552 fprintf (dump_file, "\n%d edge counts read\n", num_edges);
554 /* For every block in the file,
555 - if every exit/entrance edge has a known count, then set the block count
556 - if the block count is known, and every exit/entrance edge but one has
557 a known execution count, then set the count of the remaining edge
559 As edge counts are set, decrement the succ/pred count, but don't delete
560 the edge, that way we can easily tell when all edges are known, or only
561 one edge is unknown. */
563 /* The order that the basic blocks are iterated through is important.
564 Since the code that finds spanning trees starts with block 0, low numbered
565 edges are put on the spanning tree in preference to high numbered edges.
566 Hence, most instrumented edges are at the end. Graph solving works much
567 faster if we propagate numbers from the end to the start.
569 This takes an average of slightly more than 3 passes. */
571 changes = 1;
572 passes = 0;
573 while (changes)
575 passes++;
576 changes = 0;
577 FOR_BB_BETWEEN (bb, EXIT_BLOCK_PTR, NULL, prev_bb)
579 struct bb_info *bi = BB_INFO (bb);
580 if (! bi->count_valid)
582 if (bi->succ_count == 0)
584 edge e;
585 edge_iterator ei;
586 gcov_type total = 0;
588 FOR_EACH_EDGE (e, ei, bb->succs)
589 total += e->count;
590 bb->count = total;
591 bi->count_valid = 1;
592 changes = 1;
594 else if (bi->pred_count == 0)
596 edge e;
597 edge_iterator ei;
598 gcov_type total = 0;
600 FOR_EACH_EDGE (e, ei, bb->preds)
601 total += e->count;
602 bb->count = total;
603 bi->count_valid = 1;
604 changes = 1;
607 if (bi->count_valid)
609 if (bi->succ_count == 1)
611 edge e;
612 edge_iterator ei;
613 gcov_type total = 0;
615 /* One of the counts will be invalid, but it is zero,
616 so adding it in also doesn't hurt. */
617 FOR_EACH_EDGE (e, ei, bb->succs)
618 total += e->count;
620 /* Search for the invalid edge, and set its count. */
621 FOR_EACH_EDGE (e, ei, bb->succs)
622 if (! EDGE_INFO (e)->count_valid && ! EDGE_INFO (e)->ignore)
623 break;
625 /* Calculate count for remaining edge by conservation. */
626 total = bb->count - total;
628 gcc_assert (e);
629 EDGE_INFO (e)->count_valid = 1;
630 e->count = total;
631 bi->succ_count--;
633 BB_INFO (e->dest)->pred_count--;
634 changes = 1;
636 if (bi->pred_count == 1)
638 edge e;
639 edge_iterator ei;
640 gcov_type total = 0;
642 /* One of the counts will be invalid, but it is zero,
643 so adding it in also doesn't hurt. */
644 FOR_EACH_EDGE (e, ei, bb->preds)
645 total += e->count;
647 /* Search for the invalid edge, and set its count. */
648 FOR_EACH_EDGE (e, ei, bb->preds)
649 if (!EDGE_INFO (e)->count_valid && !EDGE_INFO (e)->ignore)
650 break;
652 /* Calculate count for remaining edge by conservation. */
653 total = bb->count - total + e->count;
655 gcc_assert (e);
656 EDGE_INFO (e)->count_valid = 1;
657 e->count = total;
658 bi->pred_count--;
660 BB_INFO (e->src)->succ_count--;
661 changes = 1;
666 if (dump_file)
668 int overlap = compute_frequency_overlap ();
669 gimple_dump_cfg (dump_file, dump_flags);
670 fprintf (dump_file, "Static profile overlap: %d.%d%%\n",
671 overlap / (OVERLAP_BASE / 100),
672 overlap % (OVERLAP_BASE / 100));
675 total_num_passes += passes;
676 if (dump_file)
677 fprintf (dump_file, "Graph solving took %d passes.\n\n", passes);
679 /* If the graph has been correctly solved, every block will have a
680 succ and pred count of zero. */
681 FOR_EACH_BB (bb)
683 gcc_assert (!BB_INFO (bb)->succ_count && !BB_INFO (bb)->pred_count);
686 /* Check for inconsistent basic block counts */
687 inconsistent = is_inconsistent ();
689 if (inconsistent)
691 if (flag_profile_correction)
693 /* Inconsistency detected. Make it flow-consistent. */
694 static int informed = 0;
695 if (informed == 0)
697 informed = 1;
698 inform (input_location, "correcting inconsistent profile data");
700 correct_negative_edge_counts ();
701 /* Set bb counts to the sum of the outgoing edge counts */
702 set_bb_counts ();
703 if (dump_file)
704 fprintf (dump_file, "\nCalling mcf_smooth_cfg\n");
705 mcf_smooth_cfg ();
707 else
708 error ("corrupted profile info: profile data is not flow-consistent");
711 /* For every edge, calculate its branch probability and add a reg_note
712 to the branch insn to indicate this. */
714 for (i = 0; i < 20; i++)
715 hist_br_prob[i] = 0;
716 num_branches = 0;
718 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
720 edge e;
721 edge_iterator ei;
723 if (bb->count < 0)
725 error ("corrupted profile info: number of iterations for basic block %d thought to be %i",
726 bb->index, (int)bb->count);
727 bb->count = 0;
729 FOR_EACH_EDGE (e, ei, bb->succs)
731 /* Function may return twice in the cased the called function is
732 setjmp or calls fork, but we can't represent this by extra
733 edge from the entry, since extra edge from the exit is
734 already present. We get negative frequency from the entry
735 point. */
736 if ((e->count < 0
737 && e->dest == EXIT_BLOCK_PTR)
738 || (e->count > bb->count
739 && e->dest != EXIT_BLOCK_PTR))
741 if (block_ends_with_call_p (bb))
742 e->count = e->count < 0 ? 0 : bb->count;
744 if (e->count < 0 || e->count > bb->count)
746 error ("corrupted profile info: number of executions for edge %d-%d thought to be %i",
747 e->src->index, e->dest->index,
748 (int)e->count);
749 e->count = bb->count / 2;
752 if (bb->count)
754 FOR_EACH_EDGE (e, ei, bb->succs)
755 e->probability = GCOV_COMPUTE_SCALE (e->count, bb->count);
756 if (bb->index >= NUM_FIXED_BLOCKS
757 && block_ends_with_condjump_p (bb)
758 && EDGE_COUNT (bb->succs) >= 2)
760 int prob;
761 edge e;
762 int index;
764 /* Find the branch edge. It is possible that we do have fake
765 edges here. */
766 FOR_EACH_EDGE (e, ei, bb->succs)
767 if (!(e->flags & (EDGE_FAKE | EDGE_FALLTHRU)))
768 break;
770 prob = e->probability;
771 index = prob * 20 / REG_BR_PROB_BASE;
773 if (index == 20)
774 index = 19;
775 hist_br_prob[index]++;
777 num_branches++;
780 /* As a last resort, distribute the probabilities evenly.
781 Use simple heuristics that if there are normal edges,
782 give all abnormals frequency of 0, otherwise distribute the
783 frequency over abnormals (this is the case of noreturn
784 calls). */
785 else if (profile_status == PROFILE_ABSENT)
787 int total = 0;
789 FOR_EACH_EDGE (e, ei, bb->succs)
790 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
791 total ++;
792 if (total)
794 FOR_EACH_EDGE (e, ei, bb->succs)
795 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
796 e->probability = REG_BR_PROB_BASE / total;
797 else
798 e->probability = 0;
800 else
802 total += EDGE_COUNT (bb->succs);
803 FOR_EACH_EDGE (e, ei, bb->succs)
804 e->probability = REG_BR_PROB_BASE / total;
806 if (bb->index >= NUM_FIXED_BLOCKS
807 && block_ends_with_condjump_p (bb)
808 && EDGE_COUNT (bb->succs) >= 2)
809 num_branches++;
812 counts_to_freqs ();
813 profile_status = PROFILE_READ;
814 compute_function_frequency ();
816 if (dump_file)
818 fprintf (dump_file, "%d branches\n", num_branches);
819 if (num_branches)
820 for (i = 0; i < 10; i++)
821 fprintf (dump_file, "%d%% branches in range %d-%d%%\n",
822 (hist_br_prob[i] + hist_br_prob[19-i]) * 100 / num_branches,
823 5 * i, 5 * i + 5);
825 total_num_branches += num_branches;
826 for (i = 0; i < 20; i++)
827 total_hist_br_prob[i] += hist_br_prob[i];
829 fputc ('\n', dump_file);
830 fputc ('\n', dump_file);
833 free_aux_for_blocks ();
836 /* Load value histograms values whose description is stored in VALUES array
837 from .gcda file.
839 CFG_CHECKSUM is the precomputed checksum for the CFG. */
841 static void
842 compute_value_histograms (histogram_values values, unsigned cfg_checksum,
843 unsigned lineno_checksum)
845 unsigned i, j, t, any;
846 unsigned n_histogram_counters[GCOV_N_VALUE_COUNTERS];
847 gcov_type *histogram_counts[GCOV_N_VALUE_COUNTERS];
848 gcov_type *act_count[GCOV_N_VALUE_COUNTERS];
849 gcov_type *aact_count;
851 for (t = 0; t < GCOV_N_VALUE_COUNTERS; t++)
852 n_histogram_counters[t] = 0;
854 for (i = 0; i < values.length (); i++)
856 histogram_value hist = values[i];
857 n_histogram_counters[(int) hist->type] += hist->n_counters;
860 any = 0;
861 for (t = 0; t < GCOV_N_VALUE_COUNTERS; t++)
863 if (!n_histogram_counters[t])
865 histogram_counts[t] = NULL;
866 continue;
869 histogram_counts[t] =
870 get_coverage_counts (COUNTER_FOR_HIST_TYPE (t),
871 n_histogram_counters[t], cfg_checksum,
872 lineno_checksum, NULL);
873 if (histogram_counts[t])
874 any = 1;
875 act_count[t] = histogram_counts[t];
877 if (!any)
878 return;
880 for (i = 0; i < values.length (); i++)
882 histogram_value hist = values[i];
883 gimple stmt = hist->hvalue.stmt;
885 t = (int) hist->type;
887 aact_count = act_count[t];
888 if (act_count[t])
889 act_count[t] += hist->n_counters;
891 gimple_add_histogram_value (cfun, stmt, hist);
892 hist->hvalue.counters = XNEWVEC (gcov_type, hist->n_counters);
893 for (j = 0; j < hist->n_counters; j++)
894 if (aact_count)
895 hist->hvalue.counters[j] = aact_count[j];
896 else
897 hist->hvalue.counters[j] = 0;
900 for (t = 0; t < GCOV_N_VALUE_COUNTERS; t++)
901 free (histogram_counts[t]);
904 /* When passed NULL as file_name, initialize.
905 When passed something else, output the necessary commands to change
906 line to LINE and offset to FILE_NAME. */
907 static void
908 output_location (char const *file_name, int line,
909 gcov_position_t *offset, basic_block bb)
911 static char const *prev_file_name;
912 static int prev_line;
913 bool name_differs, line_differs;
915 if (!file_name)
917 prev_file_name = NULL;
918 prev_line = -1;
919 return;
922 name_differs = !prev_file_name || filename_cmp (file_name, prev_file_name);
923 line_differs = prev_line != line;
925 if (name_differs || line_differs)
927 if (!*offset)
929 *offset = gcov_write_tag (GCOV_TAG_LINES);
930 gcov_write_unsigned (bb->index);
931 name_differs = line_differs=true;
934 /* If this is a new source file, then output the
935 file's name to the .bb file. */
936 if (name_differs)
938 prev_file_name = file_name;
939 gcov_write_unsigned (0);
940 gcov_write_string (prev_file_name);
942 if (line_differs)
944 gcov_write_unsigned (line);
945 prev_line = line;
950 /* Instrument and/or analyze program behavior based on program the CFG.
952 This function creates a representation of the control flow graph (of
953 the function being compiled) that is suitable for the instrumentation
954 of edges and/or converting measured edge counts to counts on the
955 complete CFG.
957 When FLAG_PROFILE_ARCS is nonzero, this function instruments the edges in
958 the flow graph that are needed to reconstruct the dynamic behavior of the
959 flow graph. This data is written to the gcno file for gcov.
961 When FLAG_BRANCH_PROBABILITIES is nonzero, this function reads auxiliary
962 information from the gcda file containing edge count information from
963 previous executions of the function being compiled. In this case, the
964 control flow graph is annotated with actual execution counts by
965 compute_branch_probabilities().
967 Main entry point of this file. */
969 void
970 branch_prob (void)
972 basic_block bb;
973 unsigned i;
974 unsigned num_edges, ignored_edges;
975 unsigned num_instrumented;
976 struct edge_list *el;
977 histogram_values values = histogram_values();
978 unsigned cfg_checksum, lineno_checksum;
980 total_num_times_called++;
982 flow_call_edges_add (NULL);
983 add_noreturn_fake_exit_edges ();
985 /* We can't handle cyclic regions constructed using abnormal edges.
986 To avoid these we replace every source of abnormal edge by a fake
987 edge from entry node and every destination by fake edge to exit.
988 This keeps graph acyclic and our calculation exact for all normal
989 edges except for exit and entrance ones.
991 We also add fake exit edges for each call and asm statement in the
992 basic, since it may not return. */
994 FOR_EACH_BB (bb)
996 int need_exit_edge = 0, need_entry_edge = 0;
997 int have_exit_edge = 0, have_entry_edge = 0;
998 edge e;
999 edge_iterator ei;
1001 /* Functions returning multiple times are not handled by extra edges.
1002 Instead we simply allow negative counts on edges from exit to the
1003 block past call and corresponding probabilities. We can't go
1004 with the extra edges because that would result in flowgraph that
1005 needs to have fake edges outside the spanning tree. */
1007 FOR_EACH_EDGE (e, ei, bb->succs)
1009 gimple_stmt_iterator gsi;
1010 gimple last = NULL;
1012 /* It may happen that there are compiler generated statements
1013 without a locus at all. Go through the basic block from the
1014 last to the first statement looking for a locus. */
1015 for (gsi = gsi_last_nondebug_bb (bb);
1016 !gsi_end_p (gsi);
1017 gsi_prev_nondebug (&gsi))
1019 last = gsi_stmt (gsi);
1020 if (gimple_has_location (last))
1021 break;
1024 /* Edge with goto locus might get wrong coverage info unless
1025 it is the only edge out of BB.
1026 Don't do that when the locuses match, so
1027 if (blah) goto something;
1028 is not computed twice. */
1029 if (last
1030 && gimple_has_location (last)
1031 && LOCATION_LOCUS (e->goto_locus) != UNKNOWN_LOCATION
1032 && !single_succ_p (bb)
1033 && (LOCATION_FILE (e->goto_locus)
1034 != LOCATION_FILE (gimple_location (last))
1035 || (LOCATION_LINE (e->goto_locus)
1036 != LOCATION_LINE (gimple_location (last)))))
1038 basic_block new_bb = split_edge (e);
1039 edge ne = single_succ_edge (new_bb);
1040 ne->goto_locus = e->goto_locus;
1042 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
1043 && e->dest != EXIT_BLOCK_PTR)
1044 need_exit_edge = 1;
1045 if (e->dest == EXIT_BLOCK_PTR)
1046 have_exit_edge = 1;
1048 FOR_EACH_EDGE (e, ei, bb->preds)
1050 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
1051 && e->src != ENTRY_BLOCK_PTR)
1052 need_entry_edge = 1;
1053 if (e->src == ENTRY_BLOCK_PTR)
1054 have_entry_edge = 1;
1057 if (need_exit_edge && !have_exit_edge)
1059 if (dump_file)
1060 fprintf (dump_file, "Adding fake exit edge to bb %i\n",
1061 bb->index);
1062 make_edge (bb, EXIT_BLOCK_PTR, EDGE_FAKE);
1064 if (need_entry_edge && !have_entry_edge)
1066 if (dump_file)
1067 fprintf (dump_file, "Adding fake entry edge to bb %i\n",
1068 bb->index);
1069 make_edge (ENTRY_BLOCK_PTR, bb, EDGE_FAKE);
1070 /* Avoid bbs that have both fake entry edge and also some
1071 exit edge. One of those edges wouldn't be added to the
1072 spanning tree, but we can't instrument any of them. */
1073 if (have_exit_edge || need_exit_edge)
1075 gimple_stmt_iterator gsi;
1076 gimple first;
1077 tree fndecl;
1079 gsi = gsi_after_labels (bb);
1080 gcc_checking_assert (!gsi_end_p (gsi));
1081 first = gsi_stmt (gsi);
1082 if (is_gimple_debug (first))
1084 gsi_next_nondebug (&gsi);
1085 gcc_checking_assert (!gsi_end_p (gsi));
1086 first = gsi_stmt (gsi);
1088 /* Don't split the bbs containing __builtin_setjmp_receiver
1089 or __builtin_setjmp_dispatcher calls. These are very
1090 special and don't expect anything to be inserted before
1091 them. */
1092 if (is_gimple_call (first)
1093 && (((fndecl = gimple_call_fndecl (first)) != NULL
1094 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1095 && (DECL_FUNCTION_CODE (fndecl)
1096 == BUILT_IN_SETJMP_RECEIVER
1097 || (DECL_FUNCTION_CODE (fndecl)
1098 == BUILT_IN_SETJMP_DISPATCHER)))
1099 || gimple_call_flags (first) & ECF_RETURNS_TWICE))
1100 continue;
1102 if (dump_file)
1103 fprintf (dump_file, "Splitting bb %i after labels\n",
1104 bb->index);
1105 split_block_after_labels (bb);
1110 el = create_edge_list ();
1111 num_edges = NUM_EDGES (el);
1112 alloc_aux_for_edges (sizeof (struct edge_info));
1114 /* The basic blocks are expected to be numbered sequentially. */
1115 compact_blocks ();
1117 ignored_edges = 0;
1118 for (i = 0 ; i < num_edges ; i++)
1120 edge e = INDEX_EDGE (el, i);
1121 e->count = 0;
1123 /* Mark edges we've replaced by fake edges above as ignored. */
1124 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
1125 && e->src != ENTRY_BLOCK_PTR && e->dest != EXIT_BLOCK_PTR)
1127 EDGE_INFO (e)->ignore = 1;
1128 ignored_edges++;
1132 /* Create spanning tree from basic block graph, mark each edge that is
1133 on the spanning tree. We insert as many abnormal and critical edges
1134 as possible to minimize number of edge splits necessary. */
1136 find_spanning_tree (el);
1138 /* Fake edges that are not on the tree will not be instrumented, so
1139 mark them ignored. */
1140 for (num_instrumented = i = 0; i < num_edges; i++)
1142 edge e = INDEX_EDGE (el, i);
1143 struct edge_info *inf = EDGE_INFO (e);
1145 if (inf->ignore || inf->on_tree)
1146 /*NOP*/;
1147 else if (e->flags & EDGE_FAKE)
1149 inf->ignore = 1;
1150 ignored_edges++;
1152 else
1153 num_instrumented++;
1156 total_num_blocks += n_basic_blocks;
1157 if (dump_file)
1158 fprintf (dump_file, "%d basic blocks\n", n_basic_blocks);
1160 total_num_edges += num_edges;
1161 if (dump_file)
1162 fprintf (dump_file, "%d edges\n", num_edges);
1164 total_num_edges_ignored += ignored_edges;
1165 if (dump_file)
1166 fprintf (dump_file, "%d ignored edges\n", ignored_edges);
1168 total_num_edges_instrumented += num_instrumented;
1169 if (dump_file)
1170 fprintf (dump_file, "%d instrumentation edges\n", num_instrumented);
1172 /* Compute two different checksums. Note that we want to compute
1173 the checksum in only once place, since it depends on the shape
1174 of the control flow which can change during
1175 various transformations. */
1176 cfg_checksum = coverage_compute_cfg_checksum ();
1177 lineno_checksum = coverage_compute_lineno_checksum ();
1179 /* Write the data from which gcov can reconstruct the basic block
1180 graph and function line numbers (the gcno file). */
1181 if (coverage_begin_function (lineno_checksum, cfg_checksum))
1183 gcov_position_t offset;
1185 /* Basic block flags */
1186 offset = gcov_write_tag (GCOV_TAG_BLOCKS);
1187 for (i = 0; i != (unsigned) (n_basic_blocks); i++)
1188 gcov_write_unsigned (0);
1189 gcov_write_length (offset);
1191 /* Arcs */
1192 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
1194 edge e;
1195 edge_iterator ei;
1197 offset = gcov_write_tag (GCOV_TAG_ARCS);
1198 gcov_write_unsigned (bb->index);
1200 FOR_EACH_EDGE (e, ei, bb->succs)
1202 struct edge_info *i = EDGE_INFO (e);
1203 if (!i->ignore)
1205 unsigned flag_bits = 0;
1207 if (i->on_tree)
1208 flag_bits |= GCOV_ARC_ON_TREE;
1209 if (e->flags & EDGE_FAKE)
1210 flag_bits |= GCOV_ARC_FAKE;
1211 if (e->flags & EDGE_FALLTHRU)
1212 flag_bits |= GCOV_ARC_FALLTHROUGH;
1213 /* On trees we don't have fallthru flags, but we can
1214 recompute them from CFG shape. */
1215 if (e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)
1216 && e->src->next_bb == e->dest)
1217 flag_bits |= GCOV_ARC_FALLTHROUGH;
1219 gcov_write_unsigned (e->dest->index);
1220 gcov_write_unsigned (flag_bits);
1224 gcov_write_length (offset);
1227 /* Line numbers. */
1228 /* Initialize the output. */
1229 output_location (NULL, 0, NULL, NULL);
1231 FOR_EACH_BB (bb)
1233 gimple_stmt_iterator gsi;
1234 gcov_position_t offset = 0;
1236 if (bb == ENTRY_BLOCK_PTR->next_bb)
1238 expanded_location curr_location =
1239 expand_location (DECL_SOURCE_LOCATION (current_function_decl));
1240 output_location (curr_location.file, curr_location.line,
1241 &offset, bb);
1244 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1246 gimple stmt = gsi_stmt (gsi);
1247 if (gimple_has_location (stmt))
1248 output_location (gimple_filename (stmt), gimple_lineno (stmt),
1249 &offset, bb);
1252 /* Notice GOTO expressions eliminated while constructing the CFG. */
1253 if (single_succ_p (bb)
1254 && LOCATION_LOCUS (single_succ_edge (bb)->goto_locus)
1255 != UNKNOWN_LOCATION)
1257 expanded_location curr_location
1258 = expand_location (single_succ_edge (bb)->goto_locus);
1259 output_location (curr_location.file, curr_location.line,
1260 &offset, bb);
1263 if (offset)
1265 /* A file of NULL indicates the end of run. */
1266 gcov_write_unsigned (0);
1267 gcov_write_string (NULL);
1268 gcov_write_length (offset);
1273 if (flag_profile_values)
1274 gimple_find_values_to_profile (&values);
1276 if (flag_branch_probabilities)
1278 compute_branch_probabilities (cfg_checksum, lineno_checksum);
1279 if (flag_profile_values)
1280 compute_value_histograms (values, cfg_checksum, lineno_checksum);
1283 remove_fake_edges ();
1285 /* For each edge not on the spanning tree, add counting code. */
1286 if (profile_arc_flag
1287 && coverage_counter_alloc (GCOV_COUNTER_ARCS, num_instrumented))
1289 unsigned n_instrumented;
1291 gimple_init_edge_profiler ();
1293 n_instrumented = instrument_edges (el);
1295 gcc_assert (n_instrumented == num_instrumented);
1297 if (flag_profile_values)
1298 instrument_values (values);
1300 /* Commit changes done by instrumentation. */
1301 gsi_commit_edge_inserts ();
1304 free_aux_for_edges ();
1306 values.release ();
1307 free_edge_list (el);
1308 coverage_end_function (lineno_checksum, cfg_checksum);
1311 /* Union find algorithm implementation for the basic blocks using
1312 aux fields. */
1314 static basic_block
1315 find_group (basic_block bb)
1317 basic_block group = bb, bb1;
1319 while ((basic_block) group->aux != group)
1320 group = (basic_block) group->aux;
1322 /* Compress path. */
1323 while ((basic_block) bb->aux != group)
1325 bb1 = (basic_block) bb->aux;
1326 bb->aux = (void *) group;
1327 bb = bb1;
1329 return group;
1332 static void
1333 union_groups (basic_block bb1, basic_block bb2)
1335 basic_block bb1g = find_group (bb1);
1336 basic_block bb2g = find_group (bb2);
1338 /* ??? I don't have a place for the rank field. OK. Lets go w/o it,
1339 this code is unlikely going to be performance problem anyway. */
1340 gcc_assert (bb1g != bb2g);
1342 bb1g->aux = bb2g;
1345 /* This function searches all of the edges in the program flow graph, and puts
1346 as many bad edges as possible onto the spanning tree. Bad edges include
1347 abnormals edges, which can't be instrumented at the moment. Since it is
1348 possible for fake edges to form a cycle, we will have to develop some
1349 better way in the future. Also put critical edges to the tree, since they
1350 are more expensive to instrument. */
1352 static void
1353 find_spanning_tree (struct edge_list *el)
1355 int i;
1356 int num_edges = NUM_EDGES (el);
1357 basic_block bb;
1359 /* We use aux field for standard union-find algorithm. */
1360 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1361 bb->aux = bb;
1363 /* Add fake edge exit to entry we can't instrument. */
1364 union_groups (EXIT_BLOCK_PTR, ENTRY_BLOCK_PTR);
1366 /* First add all abnormal edges to the tree unless they form a cycle. Also
1367 add all edges to EXIT_BLOCK_PTR to avoid inserting profiling code behind
1368 setting return value from function. */
1369 for (i = 0; i < num_edges; i++)
1371 edge e = INDEX_EDGE (el, i);
1372 if (((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL | EDGE_FAKE))
1373 || e->dest == EXIT_BLOCK_PTR)
1374 && !EDGE_INFO (e)->ignore
1375 && (find_group (e->src) != find_group (e->dest)))
1377 if (dump_file)
1378 fprintf (dump_file, "Abnormal edge %d to %d put to tree\n",
1379 e->src->index, e->dest->index);
1380 EDGE_INFO (e)->on_tree = 1;
1381 union_groups (e->src, e->dest);
1385 /* Now insert all critical edges to the tree unless they form a cycle. */
1386 for (i = 0; i < num_edges; i++)
1388 edge e = INDEX_EDGE (el, i);
1389 if (EDGE_CRITICAL_P (e) && !EDGE_INFO (e)->ignore
1390 && find_group (e->src) != find_group (e->dest))
1392 if (dump_file)
1393 fprintf (dump_file, "Critical edge %d to %d put to tree\n",
1394 e->src->index, e->dest->index);
1395 EDGE_INFO (e)->on_tree = 1;
1396 union_groups (e->src, e->dest);
1400 /* And now the rest. */
1401 for (i = 0; i < num_edges; i++)
1403 edge e = INDEX_EDGE (el, i);
1404 if (!EDGE_INFO (e)->ignore
1405 && find_group (e->src) != find_group (e->dest))
1407 if (dump_file)
1408 fprintf (dump_file, "Normal edge %d to %d put to tree\n",
1409 e->src->index, e->dest->index);
1410 EDGE_INFO (e)->on_tree = 1;
1411 union_groups (e->src, e->dest);
1415 clear_aux_for_blocks ();
1418 /* Perform file-level initialization for branch-prob processing. */
1420 void
1421 init_branch_prob (void)
1423 int i;
1425 total_num_blocks = 0;
1426 total_num_edges = 0;
1427 total_num_edges_ignored = 0;
1428 total_num_edges_instrumented = 0;
1429 total_num_blocks_created = 0;
1430 total_num_passes = 0;
1431 total_num_times_called = 0;
1432 total_num_branches = 0;
1433 for (i = 0; i < 20; i++)
1434 total_hist_br_prob[i] = 0;
1437 /* Performs file-level cleanup after branch-prob processing
1438 is completed. */
1440 void
1441 end_branch_prob (void)
1443 if (dump_file)
1445 fprintf (dump_file, "\n");
1446 fprintf (dump_file, "Total number of blocks: %d\n",
1447 total_num_blocks);
1448 fprintf (dump_file, "Total number of edges: %d\n", total_num_edges);
1449 fprintf (dump_file, "Total number of ignored edges: %d\n",
1450 total_num_edges_ignored);
1451 fprintf (dump_file, "Total number of instrumented edges: %d\n",
1452 total_num_edges_instrumented);
1453 fprintf (dump_file, "Total number of blocks created: %d\n",
1454 total_num_blocks_created);
1455 fprintf (dump_file, "Total number of graph solution passes: %d\n",
1456 total_num_passes);
1457 if (total_num_times_called != 0)
1458 fprintf (dump_file, "Average number of graph solution passes: %d\n",
1459 (total_num_passes + (total_num_times_called >> 1))
1460 / total_num_times_called);
1461 fprintf (dump_file, "Total number of branches: %d\n",
1462 total_num_branches);
1463 if (total_num_branches)
1465 int i;
1467 for (i = 0; i < 10; i++)
1468 fprintf (dump_file, "%d%% branches in range %d-%d%%\n",
1469 (total_hist_br_prob[i] + total_hist_br_prob[19-i]) * 100
1470 / total_num_branches, 5*i, 5*i+5);