* fi.po: Update.
[official-gcc.git] / gcc / profile.c
blobb8333987e02ad24d1504cbbc55e0b4c5e223d712
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 act_count[t] += hist->n_counters;
890 gimple_add_histogram_value (cfun, stmt, hist);
891 hist->hvalue.counters = XNEWVEC (gcov_type, hist->n_counters);
892 for (j = 0; j < hist->n_counters; j++)
893 hist->hvalue.counters[j] = aact_count[j];
896 for (t = 0; t < GCOV_N_VALUE_COUNTERS; t++)
897 free (histogram_counts[t]);
900 /* When passed NULL as file_name, initialize.
901 When passed something else, output the necessary commands to change
902 line to LINE and offset to FILE_NAME. */
903 static void
904 output_location (char const *file_name, int line,
905 gcov_position_t *offset, basic_block bb)
907 static char const *prev_file_name;
908 static int prev_line;
909 bool name_differs, line_differs;
911 if (!file_name)
913 prev_file_name = NULL;
914 prev_line = -1;
915 return;
918 name_differs = !prev_file_name || filename_cmp (file_name, prev_file_name);
919 line_differs = prev_line != line;
921 if (name_differs || line_differs)
923 if (!*offset)
925 *offset = gcov_write_tag (GCOV_TAG_LINES);
926 gcov_write_unsigned (bb->index);
927 name_differs = line_differs=true;
930 /* If this is a new source file, then output the
931 file's name to the .bb file. */
932 if (name_differs)
934 prev_file_name = file_name;
935 gcov_write_unsigned (0);
936 gcov_write_string (prev_file_name);
938 if (line_differs)
940 gcov_write_unsigned (line);
941 prev_line = line;
946 /* Instrument and/or analyze program behavior based on program the CFG.
948 This function creates a representation of the control flow graph (of
949 the function being compiled) that is suitable for the instrumentation
950 of edges and/or converting measured edge counts to counts on the
951 complete CFG.
953 When FLAG_PROFILE_ARCS is nonzero, this function instruments the edges in
954 the flow graph that are needed to reconstruct the dynamic behavior of the
955 flow graph. This data is written to the gcno file for gcov.
957 When FLAG_BRANCH_PROBABILITIES is nonzero, this function reads auxiliary
958 information from the gcda file containing edge count information from
959 previous executions of the function being compiled. In this case, the
960 control flow graph is annotated with actual execution counts by
961 compute_branch_probabilities().
963 Main entry point of this file. */
965 void
966 branch_prob (void)
968 basic_block bb;
969 unsigned i;
970 unsigned num_edges, ignored_edges;
971 unsigned num_instrumented;
972 struct edge_list *el;
973 histogram_values values = histogram_values();
974 unsigned cfg_checksum, lineno_checksum;
976 total_num_times_called++;
978 flow_call_edges_add (NULL);
979 add_noreturn_fake_exit_edges ();
981 /* We can't handle cyclic regions constructed using abnormal edges.
982 To avoid these we replace every source of abnormal edge by a fake
983 edge from entry node and every destination by fake edge to exit.
984 This keeps graph acyclic and our calculation exact for all normal
985 edges except for exit and entrance ones.
987 We also add fake exit edges for each call and asm statement in the
988 basic, since it may not return. */
990 FOR_EACH_BB (bb)
992 int need_exit_edge = 0, need_entry_edge = 0;
993 int have_exit_edge = 0, have_entry_edge = 0;
994 edge e;
995 edge_iterator ei;
997 /* Functions returning multiple times are not handled by extra edges.
998 Instead we simply allow negative counts on edges from exit to the
999 block past call and corresponding probabilities. We can't go
1000 with the extra edges because that would result in flowgraph that
1001 needs to have fake edges outside the spanning tree. */
1003 FOR_EACH_EDGE (e, ei, bb->succs)
1005 gimple_stmt_iterator gsi;
1006 gimple last = NULL;
1008 /* It may happen that there are compiler generated statements
1009 without a locus at all. Go through the basic block from the
1010 last to the first statement looking for a locus. */
1011 for (gsi = gsi_last_nondebug_bb (bb);
1012 !gsi_end_p (gsi);
1013 gsi_prev_nondebug (&gsi))
1015 last = gsi_stmt (gsi);
1016 if (gimple_has_location (last))
1017 break;
1020 /* Edge with goto locus might get wrong coverage info unless
1021 it is the only edge out of BB.
1022 Don't do that when the locuses match, so
1023 if (blah) goto something;
1024 is not computed twice. */
1025 if (last
1026 && gimple_has_location (last)
1027 && LOCATION_LOCUS (e->goto_locus) != UNKNOWN_LOCATION
1028 && !single_succ_p (bb)
1029 && (LOCATION_FILE (e->goto_locus)
1030 != LOCATION_FILE (gimple_location (last))
1031 || (LOCATION_LINE (e->goto_locus)
1032 != LOCATION_LINE (gimple_location (last)))))
1034 basic_block new_bb = split_edge (e);
1035 edge ne = single_succ_edge (new_bb);
1036 ne->goto_locus = e->goto_locus;
1038 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
1039 && e->dest != EXIT_BLOCK_PTR)
1040 need_exit_edge = 1;
1041 if (e->dest == EXIT_BLOCK_PTR)
1042 have_exit_edge = 1;
1044 FOR_EACH_EDGE (e, ei, bb->preds)
1046 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
1047 && e->src != ENTRY_BLOCK_PTR)
1048 need_entry_edge = 1;
1049 if (e->src == ENTRY_BLOCK_PTR)
1050 have_entry_edge = 1;
1053 if (need_exit_edge && !have_exit_edge)
1055 if (dump_file)
1056 fprintf (dump_file, "Adding fake exit edge to bb %i\n",
1057 bb->index);
1058 make_edge (bb, EXIT_BLOCK_PTR, EDGE_FAKE);
1060 if (need_entry_edge && !have_entry_edge)
1062 if (dump_file)
1063 fprintf (dump_file, "Adding fake entry edge to bb %i\n",
1064 bb->index);
1065 make_edge (ENTRY_BLOCK_PTR, bb, EDGE_FAKE);
1066 /* Avoid bbs that have both fake entry edge and also some
1067 exit edge. One of those edges wouldn't be added to the
1068 spanning tree, but we can't instrument any of them. */
1069 if (have_exit_edge || need_exit_edge)
1071 gimple_stmt_iterator gsi;
1072 gimple first;
1073 tree fndecl;
1075 gsi = gsi_after_labels (bb);
1076 gcc_checking_assert (!gsi_end_p (gsi));
1077 first = gsi_stmt (gsi);
1078 if (is_gimple_debug (first))
1080 gsi_next_nondebug (&gsi);
1081 gcc_checking_assert (!gsi_end_p (gsi));
1082 first = gsi_stmt (gsi);
1084 /* Don't split the bbs containing __builtin_setjmp_receiver
1085 or __builtin_setjmp_dispatcher calls. These are very
1086 special and don't expect anything to be inserted before
1087 them. */
1088 if (is_gimple_call (first)
1089 && (((fndecl = gimple_call_fndecl (first)) != NULL
1090 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1091 && (DECL_FUNCTION_CODE (fndecl)
1092 == BUILT_IN_SETJMP_RECEIVER
1093 || (DECL_FUNCTION_CODE (fndecl)
1094 == BUILT_IN_SETJMP_DISPATCHER)))
1095 || gimple_call_flags (first) & ECF_RETURNS_TWICE))
1096 continue;
1098 if (dump_file)
1099 fprintf (dump_file, "Splitting bb %i after labels\n",
1100 bb->index);
1101 split_block_after_labels (bb);
1106 el = create_edge_list ();
1107 num_edges = NUM_EDGES (el);
1108 alloc_aux_for_edges (sizeof (struct edge_info));
1110 /* The basic blocks are expected to be numbered sequentially. */
1111 compact_blocks ();
1113 ignored_edges = 0;
1114 for (i = 0 ; i < num_edges ; i++)
1116 edge e = INDEX_EDGE (el, i);
1117 e->count = 0;
1119 /* Mark edges we've replaced by fake edges above as ignored. */
1120 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
1121 && e->src != ENTRY_BLOCK_PTR && e->dest != EXIT_BLOCK_PTR)
1123 EDGE_INFO (e)->ignore = 1;
1124 ignored_edges++;
1128 /* Create spanning tree from basic block graph, mark each edge that is
1129 on the spanning tree. We insert as many abnormal and critical edges
1130 as possible to minimize number of edge splits necessary. */
1132 find_spanning_tree (el);
1134 /* Fake edges that are not on the tree will not be instrumented, so
1135 mark them ignored. */
1136 for (num_instrumented = i = 0; i < num_edges; i++)
1138 edge e = INDEX_EDGE (el, i);
1139 struct edge_info *inf = EDGE_INFO (e);
1141 if (inf->ignore || inf->on_tree)
1142 /*NOP*/;
1143 else if (e->flags & EDGE_FAKE)
1145 inf->ignore = 1;
1146 ignored_edges++;
1148 else
1149 num_instrumented++;
1152 total_num_blocks += n_basic_blocks;
1153 if (dump_file)
1154 fprintf (dump_file, "%d basic blocks\n", n_basic_blocks);
1156 total_num_edges += num_edges;
1157 if (dump_file)
1158 fprintf (dump_file, "%d edges\n", num_edges);
1160 total_num_edges_ignored += ignored_edges;
1161 if (dump_file)
1162 fprintf (dump_file, "%d ignored edges\n", ignored_edges);
1164 total_num_edges_instrumented += num_instrumented;
1165 if (dump_file)
1166 fprintf (dump_file, "%d instrumentation edges\n", num_instrumented);
1168 /* Compute two different checksums. Note that we want to compute
1169 the checksum in only once place, since it depends on the shape
1170 of the control flow which can change during
1171 various transformations. */
1172 cfg_checksum = coverage_compute_cfg_checksum ();
1173 lineno_checksum = coverage_compute_lineno_checksum ();
1175 /* Write the data from which gcov can reconstruct the basic block
1176 graph and function line numbers (the gcno file). */
1177 if (coverage_begin_function (lineno_checksum, cfg_checksum))
1179 gcov_position_t offset;
1181 /* Basic block flags */
1182 offset = gcov_write_tag (GCOV_TAG_BLOCKS);
1183 for (i = 0; i != (unsigned) (n_basic_blocks); i++)
1184 gcov_write_unsigned (0);
1185 gcov_write_length (offset);
1187 /* Arcs */
1188 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
1190 edge e;
1191 edge_iterator ei;
1193 offset = gcov_write_tag (GCOV_TAG_ARCS);
1194 gcov_write_unsigned (bb->index);
1196 FOR_EACH_EDGE (e, ei, bb->succs)
1198 struct edge_info *i = EDGE_INFO (e);
1199 if (!i->ignore)
1201 unsigned flag_bits = 0;
1203 if (i->on_tree)
1204 flag_bits |= GCOV_ARC_ON_TREE;
1205 if (e->flags & EDGE_FAKE)
1206 flag_bits |= GCOV_ARC_FAKE;
1207 if (e->flags & EDGE_FALLTHRU)
1208 flag_bits |= GCOV_ARC_FALLTHROUGH;
1209 /* On trees we don't have fallthru flags, but we can
1210 recompute them from CFG shape. */
1211 if (e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)
1212 && e->src->next_bb == e->dest)
1213 flag_bits |= GCOV_ARC_FALLTHROUGH;
1215 gcov_write_unsigned (e->dest->index);
1216 gcov_write_unsigned (flag_bits);
1220 gcov_write_length (offset);
1223 /* Line numbers. */
1224 /* Initialize the output. */
1225 output_location (NULL, 0, NULL, NULL);
1227 FOR_EACH_BB (bb)
1229 gimple_stmt_iterator gsi;
1230 gcov_position_t offset = 0;
1232 if (bb == ENTRY_BLOCK_PTR->next_bb)
1234 expanded_location curr_location =
1235 expand_location (DECL_SOURCE_LOCATION (current_function_decl));
1236 output_location (curr_location.file, curr_location.line,
1237 &offset, bb);
1240 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1242 gimple stmt = gsi_stmt (gsi);
1243 if (gimple_has_location (stmt))
1244 output_location (gimple_filename (stmt), gimple_lineno (stmt),
1245 &offset, bb);
1248 /* Notice GOTO expressions eliminated while constructing the CFG. */
1249 if (single_succ_p (bb)
1250 && LOCATION_LOCUS (single_succ_edge (bb)->goto_locus)
1251 != UNKNOWN_LOCATION)
1253 expanded_location curr_location
1254 = expand_location (single_succ_edge (bb)->goto_locus);
1255 output_location (curr_location.file, curr_location.line,
1256 &offset, bb);
1259 if (offset)
1261 /* A file of NULL indicates the end of run. */
1262 gcov_write_unsigned (0);
1263 gcov_write_string (NULL);
1264 gcov_write_length (offset);
1269 if (flag_profile_values)
1270 gimple_find_values_to_profile (&values);
1272 if (flag_branch_probabilities)
1274 compute_branch_probabilities (cfg_checksum, lineno_checksum);
1275 if (flag_profile_values)
1276 compute_value_histograms (values, cfg_checksum, lineno_checksum);
1279 remove_fake_edges ();
1281 /* For each edge not on the spanning tree, add counting code. */
1282 if (profile_arc_flag
1283 && coverage_counter_alloc (GCOV_COUNTER_ARCS, num_instrumented))
1285 unsigned n_instrumented;
1287 gimple_init_edge_profiler ();
1289 n_instrumented = instrument_edges (el);
1291 gcc_assert (n_instrumented == num_instrumented);
1293 if (flag_profile_values)
1294 instrument_values (values);
1296 /* Commit changes done by instrumentation. */
1297 gsi_commit_edge_inserts ();
1300 free_aux_for_edges ();
1302 values.release ();
1303 free_edge_list (el);
1304 coverage_end_function (lineno_checksum, cfg_checksum);
1307 /* Union find algorithm implementation for the basic blocks using
1308 aux fields. */
1310 static basic_block
1311 find_group (basic_block bb)
1313 basic_block group = bb, bb1;
1315 while ((basic_block) group->aux != group)
1316 group = (basic_block) group->aux;
1318 /* Compress path. */
1319 while ((basic_block) bb->aux != group)
1321 bb1 = (basic_block) bb->aux;
1322 bb->aux = (void *) group;
1323 bb = bb1;
1325 return group;
1328 static void
1329 union_groups (basic_block bb1, basic_block bb2)
1331 basic_block bb1g = find_group (bb1);
1332 basic_block bb2g = find_group (bb2);
1334 /* ??? I don't have a place for the rank field. OK. Lets go w/o it,
1335 this code is unlikely going to be performance problem anyway. */
1336 gcc_assert (bb1g != bb2g);
1338 bb1g->aux = bb2g;
1341 /* This function searches all of the edges in the program flow graph, and puts
1342 as many bad edges as possible onto the spanning tree. Bad edges include
1343 abnormals edges, which can't be instrumented at the moment. Since it is
1344 possible for fake edges to form a cycle, we will have to develop some
1345 better way in the future. Also put critical edges to the tree, since they
1346 are more expensive to instrument. */
1348 static void
1349 find_spanning_tree (struct edge_list *el)
1351 int i;
1352 int num_edges = NUM_EDGES (el);
1353 basic_block bb;
1355 /* We use aux field for standard union-find algorithm. */
1356 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1357 bb->aux = bb;
1359 /* Add fake edge exit to entry we can't instrument. */
1360 union_groups (EXIT_BLOCK_PTR, ENTRY_BLOCK_PTR);
1362 /* First add all abnormal edges to the tree unless they form a cycle. Also
1363 add all edges to EXIT_BLOCK_PTR to avoid inserting profiling code behind
1364 setting return value from function. */
1365 for (i = 0; i < num_edges; i++)
1367 edge e = INDEX_EDGE (el, i);
1368 if (((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL | EDGE_FAKE))
1369 || e->dest == EXIT_BLOCK_PTR)
1370 && !EDGE_INFO (e)->ignore
1371 && (find_group (e->src) != find_group (e->dest)))
1373 if (dump_file)
1374 fprintf (dump_file, "Abnormal edge %d to %d put to tree\n",
1375 e->src->index, e->dest->index);
1376 EDGE_INFO (e)->on_tree = 1;
1377 union_groups (e->src, e->dest);
1381 /* Now insert all critical edges to the tree unless they form a cycle. */
1382 for (i = 0; i < num_edges; i++)
1384 edge e = INDEX_EDGE (el, i);
1385 if (EDGE_CRITICAL_P (e) && !EDGE_INFO (e)->ignore
1386 && find_group (e->src) != find_group (e->dest))
1388 if (dump_file)
1389 fprintf (dump_file, "Critical edge %d to %d put to tree\n",
1390 e->src->index, e->dest->index);
1391 EDGE_INFO (e)->on_tree = 1;
1392 union_groups (e->src, e->dest);
1396 /* And now the rest. */
1397 for (i = 0; i < num_edges; i++)
1399 edge e = INDEX_EDGE (el, i);
1400 if (!EDGE_INFO (e)->ignore
1401 && find_group (e->src) != find_group (e->dest))
1403 if (dump_file)
1404 fprintf (dump_file, "Normal edge %d to %d put to tree\n",
1405 e->src->index, e->dest->index);
1406 EDGE_INFO (e)->on_tree = 1;
1407 union_groups (e->src, e->dest);
1411 clear_aux_for_blocks ();
1414 /* Perform file-level initialization for branch-prob processing. */
1416 void
1417 init_branch_prob (void)
1419 int i;
1421 total_num_blocks = 0;
1422 total_num_edges = 0;
1423 total_num_edges_ignored = 0;
1424 total_num_edges_instrumented = 0;
1425 total_num_blocks_created = 0;
1426 total_num_passes = 0;
1427 total_num_times_called = 0;
1428 total_num_branches = 0;
1429 for (i = 0; i < 20; i++)
1430 total_hist_br_prob[i] = 0;
1433 /* Performs file-level cleanup after branch-prob processing
1434 is completed. */
1436 void
1437 end_branch_prob (void)
1439 if (dump_file)
1441 fprintf (dump_file, "\n");
1442 fprintf (dump_file, "Total number of blocks: %d\n",
1443 total_num_blocks);
1444 fprintf (dump_file, "Total number of edges: %d\n", total_num_edges);
1445 fprintf (dump_file, "Total number of ignored edges: %d\n",
1446 total_num_edges_ignored);
1447 fprintf (dump_file, "Total number of instrumented edges: %d\n",
1448 total_num_edges_instrumented);
1449 fprintf (dump_file, "Total number of blocks created: %d\n",
1450 total_num_blocks_created);
1451 fprintf (dump_file, "Total number of graph solution passes: %d\n",
1452 total_num_passes);
1453 if (total_num_times_called != 0)
1454 fprintf (dump_file, "Average number of graph solution passes: %d\n",
1455 (total_num_passes + (total_num_times_called >> 1))
1456 / total_num_times_called);
1457 fprintf (dump_file, "Total number of branches: %d\n",
1458 total_num_branches);
1459 if (total_num_branches)
1461 int i;
1463 for (i = 0; i < 10; i++)
1464 fprintf (dump_file, "%d%% branches in range %d-%d%%\n",
1465 (total_hist_br_prob[i] + total_hist_br_prob[19-i]) * 100
1466 / total_num_branches, 5*i, 5*i+5);