Merge trunk version 190524 into gupc branch.
[official-gcc.git] / gcc / profile.c
blob3d0689afac31dca3d9d534d053a0e4ab9e13565c
1 /* Calculate branch probabilities, and basic block execution counts.
2 Copyright (C) 1990, 1991, 1992, 1993, 1994, 1996, 1997, 1998, 1999,
3 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009, 2010, 2011, 2012
4 Free Software Foundation, Inc.
5 Contributed by James E. Wilson, UC Berkeley/Cygnus Support;
6 based on some ideas from Dain Samples of UC Berkeley.
7 Further mangling by Bob Manson, Cygnus Support.
9 This file is part of GCC.
11 GCC is free software; you can redistribute it and/or modify it under
12 the terms of the GNU General Public License as published by the Free
13 Software Foundation; either version 3, or (at your option) any later
14 version.
16 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
17 WARRANTY; without even the implied warranty of MERCHANTABILITY or
18 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19 for more details.
21 You should have received a copy of the GNU General Public License
22 along with GCC; see the file COPYING3. If not see
23 <http://www.gnu.org/licenses/>. */
25 /* Generate basic block profile instrumentation and auxiliary files.
26 Profile generation is optimized, so that not all arcs in the basic
27 block graph need instrumenting. First, the BB graph is closed with
28 one entry (function start), and one exit (function exit). Any
29 ABNORMAL_EDGE cannot be instrumented (because there is no control
30 path to place the code). We close the graph by inserting fake
31 EDGE_FAKE edges to the EXIT_BLOCK, from the sources of abnormal
32 edges that do not go to the exit_block. We ignore such abnormal
33 edges. Naturally these fake edges are never directly traversed,
34 and so *cannot* be directly instrumented. Some other graph
35 massaging is done. To optimize the instrumentation we generate the
36 BB minimal span tree, only edges that are not on the span tree
37 (plus the entry point) need instrumenting. From that information
38 all other edge counts can be deduced. By construction all fake
39 edges must be on the spanning tree. We also attempt to place
40 EDGE_CRITICAL edges on the spanning tree.
42 The auxiliary files generated are <dumpbase>.gcno (at compile time)
43 and <dumpbase>.gcda (at run time). The format is
44 described in full in gcov-io.h. */
46 /* ??? Register allocation should use basic block execution counts to
47 give preference to the most commonly executed blocks. */
49 /* ??? Should calculate branch probabilities before instrumenting code, since
50 then we can use arc counts to help decide which arcs to instrument. */
52 #include "config.h"
53 #include "system.h"
54 #include "coretypes.h"
55 #include "tm.h"
56 #include "rtl.h"
57 #include "flags.h"
58 #include "regs.h"
59 #include "expr.h"
60 #include "function.h"
61 #include "basic-block.h"
62 #include "diagnostic-core.h"
63 #include "coverage.h"
64 #include "value-prof.h"
65 #include "tree.h"
66 #include "tree-flow.h"
67 #include "cfgloop.h"
68 #include "dumpfile.h"
70 #include "profile.h"
72 struct bb_info {
73 unsigned int count_valid : 1;
75 /* Number of successor and predecessor edges. */
76 gcov_type succ_count;
77 gcov_type pred_count;
80 #define BB_INFO(b) ((struct bb_info *) (b)->aux)
83 /* Counter summary from the last set of coverage counts read. */
85 const struct gcov_ctr_summary *profile_info;
87 /* Collect statistics on the performance of this pass for the entire source
88 file. */
90 static int total_num_blocks;
91 static int total_num_edges;
92 static int total_num_edges_ignored;
93 static int total_num_edges_instrumented;
94 static int total_num_blocks_created;
95 static int total_num_passes;
96 static int total_num_times_called;
97 static int total_hist_br_prob[20];
98 static int total_num_branches;
100 /* Forward declarations. */
101 static void find_spanning_tree (struct edge_list *);
103 /* Add edge instrumentation code to the entire insn chain.
105 F is the first insn of the chain.
106 NUM_BLOCKS is the number of basic blocks found in F. */
108 static unsigned
109 instrument_edges (struct edge_list *el)
111 unsigned num_instr_edges = 0;
112 int num_edges = NUM_EDGES (el);
113 basic_block bb;
115 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
117 edge e;
118 edge_iterator ei;
120 FOR_EACH_EDGE (e, ei, bb->succs)
122 struct edge_info *inf = EDGE_INFO (e);
124 if (!inf->ignore && !inf->on_tree)
126 gcc_assert (!(e->flags & EDGE_ABNORMAL));
127 if (dump_file)
128 fprintf (dump_file, "Edge %d to %d instrumented%s\n",
129 e->src->index, e->dest->index,
130 EDGE_CRITICAL_P (e) ? " (and split)" : "");
131 gimple_gen_edge_profiler (num_instr_edges++, e);
136 total_num_blocks_created += num_edges;
137 if (dump_file)
138 fprintf (dump_file, "%d edges instrumented\n", num_instr_edges);
139 return num_instr_edges;
142 /* Add code to measure histograms for values in list VALUES. */
143 static void
144 instrument_values (histogram_values values)
146 unsigned i;
148 /* Emit code to generate the histograms before the insns. */
150 for (i = 0; i < VEC_length (histogram_value, values); i++)
152 histogram_value hist = VEC_index (histogram_value, values, i);
153 unsigned t = COUNTER_FOR_HIST_TYPE (hist->type);
155 if (!coverage_counter_alloc (t, hist->n_counters))
156 continue;
158 switch (hist->type)
160 case HIST_TYPE_INTERVAL:
161 gimple_gen_interval_profiler (hist, t, 0);
162 break;
164 case HIST_TYPE_POW2:
165 gimple_gen_pow2_profiler (hist, t, 0);
166 break;
168 case HIST_TYPE_SINGLE_VALUE:
169 gimple_gen_one_value_profiler (hist, t, 0);
170 break;
172 case HIST_TYPE_CONST_DELTA:
173 gimple_gen_const_delta_profiler (hist, t, 0);
174 break;
176 case HIST_TYPE_INDIR_CALL:
177 gimple_gen_ic_profiler (hist, t, 0);
178 break;
180 case HIST_TYPE_AVERAGE:
181 gimple_gen_average_profiler (hist, t, 0);
182 break;
184 case HIST_TYPE_IOR:
185 gimple_gen_ior_profiler (hist, t, 0);
186 break;
188 default:
189 gcc_unreachable ();
195 /* Computes hybrid profile for all matching entries in da_file.
197 CFG_CHECKSUM is the precomputed checksum for the CFG. */
199 static gcov_type *
200 get_exec_counts (unsigned cfg_checksum, unsigned lineno_checksum)
202 unsigned num_edges = 0;
203 basic_block bb;
204 gcov_type *counts;
206 /* Count the edges to be (possibly) instrumented. */
207 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
209 edge e;
210 edge_iterator ei;
212 FOR_EACH_EDGE (e, ei, bb->succs)
213 if (!EDGE_INFO (e)->ignore && !EDGE_INFO (e)->on_tree)
214 num_edges++;
217 counts = get_coverage_counts (GCOV_COUNTER_ARCS, num_edges, cfg_checksum,
218 lineno_checksum, &profile_info);
219 if (!counts)
220 return NULL;
222 if (dump_file && profile_info)
223 fprintf(dump_file, "Merged %u profiles with maximal count %u.\n",
224 profile_info->runs, (unsigned) profile_info->sum_max);
226 return counts;
230 static bool
231 is_edge_inconsistent (VEC(edge,gc) *edges)
233 edge e;
234 edge_iterator ei;
235 FOR_EACH_EDGE (e, ei, edges)
237 if (!EDGE_INFO (e)->ignore)
239 if (e->count < 0
240 && (!(e->flags & EDGE_FAKE)
241 || !block_ends_with_call_p (e->src)))
243 if (dump_file)
245 fprintf (dump_file,
246 "Edge %i->%i is inconsistent, count"HOST_WIDEST_INT_PRINT_DEC,
247 e->src->index, e->dest->index, e->count);
248 dump_bb (dump_file, e->src, 0, TDF_DETAILS);
249 dump_bb (dump_file, e->dest, 0, TDF_DETAILS);
251 return true;
255 return false;
258 static void
259 correct_negative_edge_counts (void)
261 basic_block bb;
262 edge e;
263 edge_iterator ei;
265 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
267 FOR_EACH_EDGE (e, ei, bb->succs)
269 if (e->count < 0)
270 e->count = 0;
275 /* Check consistency.
276 Return true if inconsistency is found. */
277 static bool
278 is_inconsistent (void)
280 basic_block bb;
281 bool inconsistent = false;
282 FOR_EACH_BB (bb)
284 inconsistent |= is_edge_inconsistent (bb->preds);
285 if (!dump_file && inconsistent)
286 return true;
287 inconsistent |= is_edge_inconsistent (bb->succs);
288 if (!dump_file && inconsistent)
289 return true;
290 if (bb->count < 0)
292 if (dump_file)
294 fprintf (dump_file, "BB %i count is negative "
295 HOST_WIDEST_INT_PRINT_DEC,
296 bb->index,
297 bb->count);
298 dump_bb (dump_file, bb, 0, TDF_DETAILS);
300 inconsistent = true;
302 if (bb->count != sum_edge_counts (bb->preds))
304 if (dump_file)
306 fprintf (dump_file, "BB %i count does not match sum of incoming edges "
307 HOST_WIDEST_INT_PRINT_DEC" should be " HOST_WIDEST_INT_PRINT_DEC,
308 bb->index,
309 bb->count,
310 sum_edge_counts (bb->preds));
311 dump_bb (dump_file, bb, 0, TDF_DETAILS);
313 inconsistent = true;
315 if (bb->count != sum_edge_counts (bb->succs) &&
316 ! (find_edge (bb, EXIT_BLOCK_PTR) != NULL && block_ends_with_call_p (bb)))
318 if (dump_file)
320 fprintf (dump_file, "BB %i count does not match sum of outgoing edges "
321 HOST_WIDEST_INT_PRINT_DEC" should be " HOST_WIDEST_INT_PRINT_DEC,
322 bb->index,
323 bb->count,
324 sum_edge_counts (bb->succs));
325 dump_bb (dump_file, bb, 0, TDF_DETAILS);
327 inconsistent = true;
329 if (!dump_file && inconsistent)
330 return true;
333 return inconsistent;
336 /* Set each basic block count to the sum of its outgoing edge counts */
337 static void
338 set_bb_counts (void)
340 basic_block bb;
341 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
343 bb->count = sum_edge_counts (bb->succs);
344 gcc_assert (bb->count >= 0);
348 /* Reads profile data and returns total number of edge counts read */
349 static int
350 read_profile_edge_counts (gcov_type *exec_counts)
352 basic_block bb;
353 int num_edges = 0;
354 int exec_counts_pos = 0;
355 /* For each edge not on the spanning tree, set its execution count from
356 the .da file. */
357 /* The first count in the .da file is the number of times that the function
358 was entered. This is the exec_count for block zero. */
360 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
362 edge e;
363 edge_iterator ei;
365 FOR_EACH_EDGE (e, ei, bb->succs)
366 if (!EDGE_INFO (e)->ignore && !EDGE_INFO (e)->on_tree)
368 num_edges++;
369 if (exec_counts)
371 e->count = exec_counts[exec_counts_pos++];
372 if (e->count > profile_info->sum_max)
374 if (flag_profile_correction)
376 static bool informed = 0;
377 if (!informed)
378 inform (input_location,
379 "corrupted profile info: edge count exceeds maximal count");
380 informed = 1;
382 else
383 error ("corrupted profile info: edge from %i to %i exceeds maximal count",
384 bb->index, e->dest->index);
387 else
388 e->count = 0;
390 EDGE_INFO (e)->count_valid = 1;
391 BB_INFO (bb)->succ_count--;
392 BB_INFO (e->dest)->pred_count--;
393 if (dump_file)
395 fprintf (dump_file, "\nRead edge from %i to %i, count:",
396 bb->index, e->dest->index);
397 fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
398 (HOST_WIDEST_INT) e->count);
403 return num_edges;
406 #define OVERLAP_BASE 10000
408 /* Compare the static estimated profile to the actual profile, and
409 return the "degree of overlap" measure between them.
411 Degree of overlap is a number between 0 and OVERLAP_BASE. It is
412 the sum of each basic block's minimum relative weights between
413 two profiles. And overlap of OVERLAP_BASE means two profiles are
414 identical. */
416 static int
417 compute_frequency_overlap (void)
419 gcov_type count_total = 0, freq_total = 0;
420 int overlap = 0;
421 basic_block bb;
423 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
425 count_total += bb->count;
426 freq_total += bb->frequency;
429 if (count_total == 0 || freq_total == 0)
430 return 0;
432 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
433 overlap += MIN (bb->count * OVERLAP_BASE / count_total,
434 bb->frequency * OVERLAP_BASE / freq_total);
436 return overlap;
439 /* Compute the branch probabilities for the various branches.
440 Annotate them accordingly.
442 CFG_CHECKSUM is the precomputed checksum for the CFG. */
444 static void
445 compute_branch_probabilities (unsigned cfg_checksum, unsigned lineno_checksum)
447 basic_block bb;
448 int i;
449 int num_edges = 0;
450 int changes;
451 int passes;
452 int hist_br_prob[20];
453 int num_branches;
454 gcov_type *exec_counts = get_exec_counts (cfg_checksum, lineno_checksum);
455 int inconsistent = 0;
457 /* Very simple sanity checks so we catch bugs in our profiling code. */
458 if (!profile_info)
459 return;
460 if (profile_info->run_max * profile_info->runs < profile_info->sum_max)
462 error ("corrupted profile info: run_max * runs < sum_max");
463 exec_counts = NULL;
466 if (profile_info->sum_all < profile_info->sum_max)
468 error ("corrupted profile info: sum_all is smaller than sum_max");
469 exec_counts = NULL;
472 /* Attach extra info block to each bb. */
473 alloc_aux_for_blocks (sizeof (struct bb_info));
474 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
476 edge e;
477 edge_iterator ei;
479 FOR_EACH_EDGE (e, ei, bb->succs)
480 if (!EDGE_INFO (e)->ignore)
481 BB_INFO (bb)->succ_count++;
482 FOR_EACH_EDGE (e, ei, bb->preds)
483 if (!EDGE_INFO (e)->ignore)
484 BB_INFO (bb)->pred_count++;
487 /* Avoid predicting entry on exit nodes. */
488 BB_INFO (EXIT_BLOCK_PTR)->succ_count = 2;
489 BB_INFO (ENTRY_BLOCK_PTR)->pred_count = 2;
491 num_edges = read_profile_edge_counts (exec_counts);
493 if (dump_file)
494 fprintf (dump_file, "\n%d edge counts read\n", num_edges);
496 /* For every block in the file,
497 - if every exit/entrance edge has a known count, then set the block count
498 - if the block count is known, and every exit/entrance edge but one has
499 a known execution count, then set the count of the remaining edge
501 As edge counts are set, decrement the succ/pred count, but don't delete
502 the edge, that way we can easily tell when all edges are known, or only
503 one edge is unknown. */
505 /* The order that the basic blocks are iterated through is important.
506 Since the code that finds spanning trees starts with block 0, low numbered
507 edges are put on the spanning tree in preference to high numbered edges.
508 Hence, most instrumented edges are at the end. Graph solving works much
509 faster if we propagate numbers from the end to the start.
511 This takes an average of slightly more than 3 passes. */
513 changes = 1;
514 passes = 0;
515 while (changes)
517 passes++;
518 changes = 0;
519 FOR_BB_BETWEEN (bb, EXIT_BLOCK_PTR, NULL, prev_bb)
521 struct bb_info *bi = BB_INFO (bb);
522 if (! bi->count_valid)
524 if (bi->succ_count == 0)
526 edge e;
527 edge_iterator ei;
528 gcov_type total = 0;
530 FOR_EACH_EDGE (e, ei, bb->succs)
531 total += e->count;
532 bb->count = total;
533 bi->count_valid = 1;
534 changes = 1;
536 else if (bi->pred_count == 0)
538 edge e;
539 edge_iterator ei;
540 gcov_type total = 0;
542 FOR_EACH_EDGE (e, ei, bb->preds)
543 total += e->count;
544 bb->count = total;
545 bi->count_valid = 1;
546 changes = 1;
549 if (bi->count_valid)
551 if (bi->succ_count == 1)
553 edge e;
554 edge_iterator ei;
555 gcov_type total = 0;
557 /* One of the counts will be invalid, but it is zero,
558 so adding it in also doesn't hurt. */
559 FOR_EACH_EDGE (e, ei, bb->succs)
560 total += e->count;
562 /* Search for the invalid edge, and set its count. */
563 FOR_EACH_EDGE (e, ei, bb->succs)
564 if (! EDGE_INFO (e)->count_valid && ! EDGE_INFO (e)->ignore)
565 break;
567 /* Calculate count for remaining edge by conservation. */
568 total = bb->count - total;
570 gcc_assert (e);
571 EDGE_INFO (e)->count_valid = 1;
572 e->count = total;
573 bi->succ_count--;
575 BB_INFO (e->dest)->pred_count--;
576 changes = 1;
578 if (bi->pred_count == 1)
580 edge e;
581 edge_iterator ei;
582 gcov_type total = 0;
584 /* One of the counts will be invalid, but it is zero,
585 so adding it in also doesn't hurt. */
586 FOR_EACH_EDGE (e, ei, bb->preds)
587 total += e->count;
589 /* Search for the invalid edge, and set its count. */
590 FOR_EACH_EDGE (e, ei, bb->preds)
591 if (!EDGE_INFO (e)->count_valid && !EDGE_INFO (e)->ignore)
592 break;
594 /* Calculate count for remaining edge by conservation. */
595 total = bb->count - total + e->count;
597 gcc_assert (e);
598 EDGE_INFO (e)->count_valid = 1;
599 e->count = total;
600 bi->pred_count--;
602 BB_INFO (e->src)->succ_count--;
603 changes = 1;
608 if (dump_file)
610 int overlap = compute_frequency_overlap ();
611 gimple_dump_cfg (dump_file, dump_flags);
612 fprintf (dump_file, "Static profile overlap: %d.%d%%\n",
613 overlap / (OVERLAP_BASE / 100),
614 overlap % (OVERLAP_BASE / 100));
617 total_num_passes += passes;
618 if (dump_file)
619 fprintf (dump_file, "Graph solving took %d passes.\n\n", passes);
621 /* If the graph has been correctly solved, every block will have a
622 succ and pred count of zero. */
623 FOR_EACH_BB (bb)
625 gcc_assert (!BB_INFO (bb)->succ_count && !BB_INFO (bb)->pred_count);
628 /* Check for inconsistent basic block counts */
629 inconsistent = is_inconsistent ();
631 if (inconsistent)
633 if (flag_profile_correction)
635 /* Inconsistency detected. Make it flow-consistent. */
636 static int informed = 0;
637 if (informed == 0)
639 informed = 1;
640 inform (input_location, "correcting inconsistent profile data");
642 correct_negative_edge_counts ();
643 /* Set bb counts to the sum of the outgoing edge counts */
644 set_bb_counts ();
645 if (dump_file)
646 fprintf (dump_file, "\nCalling mcf_smooth_cfg\n");
647 mcf_smooth_cfg ();
649 else
650 error ("corrupted profile info: profile data is not flow-consistent");
653 /* For every edge, calculate its branch probability and add a reg_note
654 to the branch insn to indicate this. */
656 for (i = 0; i < 20; i++)
657 hist_br_prob[i] = 0;
658 num_branches = 0;
660 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
662 edge e;
663 edge_iterator ei;
665 if (bb->count < 0)
667 error ("corrupted profile info: number of iterations for basic block %d thought to be %i",
668 bb->index, (int)bb->count);
669 bb->count = 0;
671 FOR_EACH_EDGE (e, ei, bb->succs)
673 /* Function may return twice in the cased the called function is
674 setjmp or calls fork, but we can't represent this by extra
675 edge from the entry, since extra edge from the exit is
676 already present. We get negative frequency from the entry
677 point. */
678 if ((e->count < 0
679 && e->dest == EXIT_BLOCK_PTR)
680 || (e->count > bb->count
681 && e->dest != EXIT_BLOCK_PTR))
683 if (block_ends_with_call_p (bb))
684 e->count = e->count < 0 ? 0 : bb->count;
686 if (e->count < 0 || e->count > bb->count)
688 error ("corrupted profile info: number of executions for edge %d-%d thought to be %i",
689 e->src->index, e->dest->index,
690 (int)e->count);
691 e->count = bb->count / 2;
694 if (bb->count)
696 FOR_EACH_EDGE (e, ei, bb->succs)
697 e->probability = (e->count * REG_BR_PROB_BASE + bb->count / 2) / bb->count;
698 if (bb->index >= NUM_FIXED_BLOCKS
699 && block_ends_with_condjump_p (bb)
700 && EDGE_COUNT (bb->succs) >= 2)
702 int prob;
703 edge e;
704 int index;
706 /* Find the branch edge. It is possible that we do have fake
707 edges here. */
708 FOR_EACH_EDGE (e, ei, bb->succs)
709 if (!(e->flags & (EDGE_FAKE | EDGE_FALLTHRU)))
710 break;
712 prob = e->probability;
713 index = prob * 20 / REG_BR_PROB_BASE;
715 if (index == 20)
716 index = 19;
717 hist_br_prob[index]++;
719 num_branches++;
722 /* As a last resort, distribute the probabilities evenly.
723 Use simple heuristics that if there are normal edges,
724 give all abnormals frequency of 0, otherwise distribute the
725 frequency over abnormals (this is the case of noreturn
726 calls). */
727 else if (profile_status == PROFILE_ABSENT)
729 int total = 0;
731 FOR_EACH_EDGE (e, ei, bb->succs)
732 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
733 total ++;
734 if (total)
736 FOR_EACH_EDGE (e, ei, bb->succs)
737 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
738 e->probability = REG_BR_PROB_BASE / total;
739 else
740 e->probability = 0;
742 else
744 total += EDGE_COUNT (bb->succs);
745 FOR_EACH_EDGE (e, ei, bb->succs)
746 e->probability = REG_BR_PROB_BASE / total;
748 if (bb->index >= NUM_FIXED_BLOCKS
749 && block_ends_with_condjump_p (bb)
750 && EDGE_COUNT (bb->succs) >= 2)
751 num_branches++;
754 counts_to_freqs ();
755 profile_status = PROFILE_READ;
756 compute_function_frequency ();
758 if (dump_file)
760 fprintf (dump_file, "%d branches\n", num_branches);
761 if (num_branches)
762 for (i = 0; i < 10; i++)
763 fprintf (dump_file, "%d%% branches in range %d-%d%%\n",
764 (hist_br_prob[i] + hist_br_prob[19-i]) * 100 / num_branches,
765 5 * i, 5 * i + 5);
767 total_num_branches += num_branches;
768 for (i = 0; i < 20; i++)
769 total_hist_br_prob[i] += hist_br_prob[i];
771 fputc ('\n', dump_file);
772 fputc ('\n', dump_file);
775 free_aux_for_blocks ();
778 /* Load value histograms values whose description is stored in VALUES array
779 from .gcda file.
781 CFG_CHECKSUM is the precomputed checksum for the CFG. */
783 static void
784 compute_value_histograms (histogram_values values, unsigned cfg_checksum,
785 unsigned lineno_checksum)
787 unsigned i, j, t, any;
788 unsigned n_histogram_counters[GCOV_N_VALUE_COUNTERS];
789 gcov_type *histogram_counts[GCOV_N_VALUE_COUNTERS];
790 gcov_type *act_count[GCOV_N_VALUE_COUNTERS];
791 gcov_type *aact_count;
793 for (t = 0; t < GCOV_N_VALUE_COUNTERS; t++)
794 n_histogram_counters[t] = 0;
796 for (i = 0; i < VEC_length (histogram_value, values); i++)
798 histogram_value hist = VEC_index (histogram_value, values, i);
799 n_histogram_counters[(int) hist->type] += hist->n_counters;
802 any = 0;
803 for (t = 0; t < GCOV_N_VALUE_COUNTERS; t++)
805 if (!n_histogram_counters[t])
807 histogram_counts[t] = NULL;
808 continue;
811 histogram_counts[t] =
812 get_coverage_counts (COUNTER_FOR_HIST_TYPE (t),
813 n_histogram_counters[t], cfg_checksum,
814 lineno_checksum, NULL);
815 if (histogram_counts[t])
816 any = 1;
817 act_count[t] = histogram_counts[t];
819 if (!any)
820 return;
822 for (i = 0; i < VEC_length (histogram_value, values); i++)
824 histogram_value hist = VEC_index (histogram_value, values, i);
825 gimple stmt = hist->hvalue.stmt;
827 t = (int) hist->type;
829 aact_count = act_count[t];
830 act_count[t] += hist->n_counters;
832 gimple_add_histogram_value (cfun, stmt, hist);
833 hist->hvalue.counters = XNEWVEC (gcov_type, hist->n_counters);
834 for (j = 0; j < hist->n_counters; j++)
835 hist->hvalue.counters[j] = aact_count[j];
838 for (t = 0; t < GCOV_N_VALUE_COUNTERS; t++)
839 free (histogram_counts[t]);
842 /* When passed NULL as file_name, initialize.
843 When passed something else, output the necessary commands to change
844 line to LINE and offset to FILE_NAME. */
845 static void
846 output_location (char const *file_name, int line,
847 gcov_position_t *offset, basic_block bb)
849 static char const *prev_file_name;
850 static int prev_line;
851 bool name_differs, line_differs;
853 if (!file_name)
855 prev_file_name = NULL;
856 prev_line = -1;
857 return;
860 name_differs = !prev_file_name || filename_cmp (file_name, prev_file_name);
861 line_differs = prev_line != line;
863 if (name_differs || line_differs)
865 if (!*offset)
867 *offset = gcov_write_tag (GCOV_TAG_LINES);
868 gcov_write_unsigned (bb->index);
869 name_differs = line_differs=true;
872 /* If this is a new source file, then output the
873 file's name to the .bb file. */
874 if (name_differs)
876 prev_file_name = file_name;
877 gcov_write_unsigned (0);
878 gcov_write_string (prev_file_name);
880 if (line_differs)
882 gcov_write_unsigned (line);
883 prev_line = line;
888 /* Instrument and/or analyze program behavior based on program the CFG.
890 This function creates a representation of the control flow graph (of
891 the function being compiled) that is suitable for the instrumentation
892 of edges and/or converting measured edge counts to counts on the
893 complete CFG.
895 When FLAG_PROFILE_ARCS is nonzero, this function instruments the edges in
896 the flow graph that are needed to reconstruct the dynamic behavior of the
897 flow graph. This data is written to the gcno file for gcov.
899 When FLAG_BRANCH_PROBABILITIES is nonzero, this function reads auxiliary
900 information from the gcda file containing edge count information from
901 previous executions of the function being compiled. In this case, the
902 control flow graph is annotated with actual execution counts by
903 compute_branch_probabilities().
905 Main entry point of this file. */
907 void
908 branch_prob (void)
910 basic_block bb;
911 unsigned i;
912 unsigned num_edges, ignored_edges;
913 unsigned num_instrumented;
914 struct edge_list *el;
915 histogram_values values = NULL;
916 unsigned cfg_checksum, lineno_checksum;
918 total_num_times_called++;
920 flow_call_edges_add (NULL);
921 add_noreturn_fake_exit_edges ();
923 /* We can't handle cyclic regions constructed using abnormal edges.
924 To avoid these we replace every source of abnormal edge by a fake
925 edge from entry node and every destination by fake edge to exit.
926 This keeps graph acyclic and our calculation exact for all normal
927 edges except for exit and entrance ones.
929 We also add fake exit edges for each call and asm statement in the
930 basic, since it may not return. */
932 FOR_EACH_BB (bb)
934 int need_exit_edge = 0, need_entry_edge = 0;
935 int have_exit_edge = 0, have_entry_edge = 0;
936 edge e;
937 edge_iterator ei;
939 /* Functions returning multiple times are not handled by extra edges.
940 Instead we simply allow negative counts on edges from exit to the
941 block past call and corresponding probabilities. We can't go
942 with the extra edges because that would result in flowgraph that
943 needs to have fake edges outside the spanning tree. */
945 FOR_EACH_EDGE (e, ei, bb->succs)
947 gimple_stmt_iterator gsi;
948 gimple last = NULL;
950 /* It may happen that there are compiler generated statements
951 without a locus at all. Go through the basic block from the
952 last to the first statement looking for a locus. */
953 for (gsi = gsi_last_nondebug_bb (bb);
954 !gsi_end_p (gsi);
955 gsi_prev_nondebug (&gsi))
957 last = gsi_stmt (gsi);
958 if (gimple_has_location (last))
959 break;
962 /* Edge with goto locus might get wrong coverage info unless
963 it is the only edge out of BB.
964 Don't do that when the locuses match, so
965 if (blah) goto something;
966 is not computed twice. */
967 if (last
968 && gimple_has_location (last)
969 && e->goto_locus != UNKNOWN_LOCATION
970 && !single_succ_p (bb)
971 && (LOCATION_FILE (e->goto_locus)
972 != LOCATION_FILE (gimple_location (last))
973 || (LOCATION_LINE (e->goto_locus)
974 != LOCATION_LINE (gimple_location (last)))))
976 basic_block new_bb = split_edge (e);
977 edge ne = single_succ_edge (new_bb);
978 ne->goto_locus = e->goto_locus;
979 ne->goto_block = e->goto_block;
981 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
982 && e->dest != EXIT_BLOCK_PTR)
983 need_exit_edge = 1;
984 if (e->dest == EXIT_BLOCK_PTR)
985 have_exit_edge = 1;
987 FOR_EACH_EDGE (e, ei, bb->preds)
989 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
990 && e->src != ENTRY_BLOCK_PTR)
991 need_entry_edge = 1;
992 if (e->src == ENTRY_BLOCK_PTR)
993 have_entry_edge = 1;
996 if (need_exit_edge && !have_exit_edge)
998 if (dump_file)
999 fprintf (dump_file, "Adding fake exit edge to bb %i\n",
1000 bb->index);
1001 make_edge (bb, EXIT_BLOCK_PTR, EDGE_FAKE);
1003 if (need_entry_edge && !have_entry_edge)
1005 if (dump_file)
1006 fprintf (dump_file, "Adding fake entry edge to bb %i\n",
1007 bb->index);
1008 make_edge (ENTRY_BLOCK_PTR, bb, EDGE_FAKE);
1009 /* Avoid bbs that have both fake entry edge and also some
1010 exit edge. One of those edges wouldn't be added to the
1011 spanning tree, but we can't instrument any of them. */
1012 if (have_exit_edge || need_exit_edge)
1014 gimple_stmt_iterator gsi;
1015 gimple first;
1016 tree fndecl;
1018 gsi = gsi_after_labels (bb);
1019 gcc_checking_assert (!gsi_end_p (gsi));
1020 first = gsi_stmt (gsi);
1021 if (is_gimple_debug (first))
1023 gsi_next_nondebug (&gsi);
1024 gcc_checking_assert (!gsi_end_p (gsi));
1025 first = gsi_stmt (gsi);
1027 /* Don't split the bbs containing __builtin_setjmp_receiver
1028 or __builtin_setjmp_dispatcher calls. These are very
1029 special and don't expect anything to be inserted before
1030 them. */
1031 if (!is_gimple_call (first)
1032 || (fndecl = gimple_call_fndecl (first)) == NULL
1033 || DECL_BUILT_IN_CLASS (fndecl) != BUILT_IN_NORMAL
1034 || (DECL_FUNCTION_CODE (fndecl) != BUILT_IN_SETJMP_RECEIVER
1035 && (DECL_FUNCTION_CODE (fndecl)
1036 != BUILT_IN_SETJMP_DISPATCHER)))
1038 if (dump_file)
1039 fprintf (dump_file, "Splitting bb %i after labels\n",
1040 bb->index);
1041 split_block_after_labels (bb);
1047 el = create_edge_list ();
1048 num_edges = NUM_EDGES (el);
1049 alloc_aux_for_edges (sizeof (struct edge_info));
1051 /* The basic blocks are expected to be numbered sequentially. */
1052 compact_blocks ();
1054 ignored_edges = 0;
1055 for (i = 0 ; i < num_edges ; i++)
1057 edge e = INDEX_EDGE (el, i);
1058 e->count = 0;
1060 /* Mark edges we've replaced by fake edges above as ignored. */
1061 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
1062 && e->src != ENTRY_BLOCK_PTR && e->dest != EXIT_BLOCK_PTR)
1064 EDGE_INFO (e)->ignore = 1;
1065 ignored_edges++;
1069 /* Create spanning tree from basic block graph, mark each edge that is
1070 on the spanning tree. We insert as many abnormal and critical edges
1071 as possible to minimize number of edge splits necessary. */
1073 find_spanning_tree (el);
1075 /* Fake edges that are not on the tree will not be instrumented, so
1076 mark them ignored. */
1077 for (num_instrumented = i = 0; i < num_edges; i++)
1079 edge e = INDEX_EDGE (el, i);
1080 struct edge_info *inf = EDGE_INFO (e);
1082 if (inf->ignore || inf->on_tree)
1083 /*NOP*/;
1084 else if (e->flags & EDGE_FAKE)
1086 inf->ignore = 1;
1087 ignored_edges++;
1089 else
1090 num_instrumented++;
1093 total_num_blocks += n_basic_blocks;
1094 if (dump_file)
1095 fprintf (dump_file, "%d basic blocks\n", n_basic_blocks);
1097 total_num_edges += num_edges;
1098 if (dump_file)
1099 fprintf (dump_file, "%d edges\n", num_edges);
1101 total_num_edges_ignored += ignored_edges;
1102 if (dump_file)
1103 fprintf (dump_file, "%d ignored edges\n", ignored_edges);
1105 total_num_edges_instrumented += num_instrumented;
1106 if (dump_file)
1107 fprintf (dump_file, "%d instrumentation edges\n", num_instrumented);
1109 /* Compute two different checksums. Note that we want to compute
1110 the checksum in only once place, since it depends on the shape
1111 of the control flow which can change during
1112 various transformations. */
1113 cfg_checksum = coverage_compute_cfg_checksum ();
1114 lineno_checksum = coverage_compute_lineno_checksum ();
1116 /* Write the data from which gcov can reconstruct the basic block
1117 graph and function line numbers (the gcno file). */
1118 if (coverage_begin_function (lineno_checksum, cfg_checksum))
1120 gcov_position_t offset;
1122 /* Basic block flags */
1123 offset = gcov_write_tag (GCOV_TAG_BLOCKS);
1124 for (i = 0; i != (unsigned) (n_basic_blocks); i++)
1125 gcov_write_unsigned (0);
1126 gcov_write_length (offset);
1128 /* Arcs */
1129 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
1131 edge e;
1132 edge_iterator ei;
1134 offset = gcov_write_tag (GCOV_TAG_ARCS);
1135 gcov_write_unsigned (bb->index);
1137 FOR_EACH_EDGE (e, ei, bb->succs)
1139 struct edge_info *i = EDGE_INFO (e);
1140 if (!i->ignore)
1142 unsigned flag_bits = 0;
1144 if (i->on_tree)
1145 flag_bits |= GCOV_ARC_ON_TREE;
1146 if (e->flags & EDGE_FAKE)
1147 flag_bits |= GCOV_ARC_FAKE;
1148 if (e->flags & EDGE_FALLTHRU)
1149 flag_bits |= GCOV_ARC_FALLTHROUGH;
1150 /* On trees we don't have fallthru flags, but we can
1151 recompute them from CFG shape. */
1152 if (e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)
1153 && e->src->next_bb == e->dest)
1154 flag_bits |= GCOV_ARC_FALLTHROUGH;
1156 gcov_write_unsigned (e->dest->index);
1157 gcov_write_unsigned (flag_bits);
1161 gcov_write_length (offset);
1164 /* Line numbers. */
1165 /* Initialize the output. */
1166 output_location (NULL, 0, NULL, NULL);
1168 FOR_EACH_BB (bb)
1170 gimple_stmt_iterator gsi;
1171 gcov_position_t offset = 0;
1173 if (bb == ENTRY_BLOCK_PTR->next_bb)
1175 expanded_location curr_location =
1176 expand_location (DECL_SOURCE_LOCATION (current_function_decl));
1177 output_location (curr_location.file, curr_location.line,
1178 &offset, bb);
1181 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1183 gimple stmt = gsi_stmt (gsi);
1184 if (gimple_has_location (stmt))
1185 output_location (gimple_filename (stmt), gimple_lineno (stmt),
1186 &offset, bb);
1189 /* Notice GOTO expressions eliminated while constructing the CFG. */
1190 if (single_succ_p (bb)
1191 && single_succ_edge (bb)->goto_locus != UNKNOWN_LOCATION)
1193 expanded_location curr_location
1194 = expand_location (single_succ_edge (bb)->goto_locus);
1195 output_location (curr_location.file, curr_location.line,
1196 &offset, bb);
1199 if (offset)
1201 /* A file of NULL indicates the end of run. */
1202 gcov_write_unsigned (0);
1203 gcov_write_string (NULL);
1204 gcov_write_length (offset);
1209 if (flag_profile_values)
1210 gimple_find_values_to_profile (&values);
1212 if (flag_branch_probabilities)
1214 compute_branch_probabilities (cfg_checksum, lineno_checksum);
1215 if (flag_profile_values)
1216 compute_value_histograms (values, cfg_checksum, lineno_checksum);
1219 remove_fake_edges ();
1221 /* For each edge not on the spanning tree, add counting code. */
1222 if (profile_arc_flag
1223 && coverage_counter_alloc (GCOV_COUNTER_ARCS, num_instrumented))
1225 unsigned n_instrumented;
1227 gimple_init_edge_profiler ();
1229 n_instrumented = instrument_edges (el);
1231 gcc_assert (n_instrumented == num_instrumented);
1233 if (flag_profile_values)
1234 instrument_values (values);
1236 /* Commit changes done by instrumentation. */
1237 gsi_commit_edge_inserts ();
1240 free_aux_for_edges ();
1242 VEC_free (histogram_value, heap, values);
1243 free_edge_list (el);
1244 coverage_end_function (lineno_checksum, cfg_checksum);
1247 /* Union find algorithm implementation for the basic blocks using
1248 aux fields. */
1250 static basic_block
1251 find_group (basic_block bb)
1253 basic_block group = bb, bb1;
1255 while ((basic_block) group->aux != group)
1256 group = (basic_block) group->aux;
1258 /* Compress path. */
1259 while ((basic_block) bb->aux != group)
1261 bb1 = (basic_block) bb->aux;
1262 bb->aux = (void *) group;
1263 bb = bb1;
1265 return group;
1268 static void
1269 union_groups (basic_block bb1, basic_block bb2)
1271 basic_block bb1g = find_group (bb1);
1272 basic_block bb2g = find_group (bb2);
1274 /* ??? I don't have a place for the rank field. OK. Lets go w/o it,
1275 this code is unlikely going to be performance problem anyway. */
1276 gcc_assert (bb1g != bb2g);
1278 bb1g->aux = bb2g;
1281 /* This function searches all of the edges in the program flow graph, and puts
1282 as many bad edges as possible onto the spanning tree. Bad edges include
1283 abnormals edges, which can't be instrumented at the moment. Since it is
1284 possible for fake edges to form a cycle, we will have to develop some
1285 better way in the future. Also put critical edges to the tree, since they
1286 are more expensive to instrument. */
1288 static void
1289 find_spanning_tree (struct edge_list *el)
1291 int i;
1292 int num_edges = NUM_EDGES (el);
1293 basic_block bb;
1295 /* We use aux field for standard union-find algorithm. */
1296 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1297 bb->aux = bb;
1299 /* Add fake edge exit to entry we can't instrument. */
1300 union_groups (EXIT_BLOCK_PTR, ENTRY_BLOCK_PTR);
1302 /* First add all abnormal edges to the tree unless they form a cycle. Also
1303 add all edges to EXIT_BLOCK_PTR to avoid inserting profiling code behind
1304 setting return value from function. */
1305 for (i = 0; i < num_edges; i++)
1307 edge e = INDEX_EDGE (el, i);
1308 if (((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL | EDGE_FAKE))
1309 || e->dest == EXIT_BLOCK_PTR)
1310 && !EDGE_INFO (e)->ignore
1311 && (find_group (e->src) != find_group (e->dest)))
1313 if (dump_file)
1314 fprintf (dump_file, "Abnormal edge %d to %d put to tree\n",
1315 e->src->index, e->dest->index);
1316 EDGE_INFO (e)->on_tree = 1;
1317 union_groups (e->src, e->dest);
1321 /* Now insert all critical edges to the tree unless they form a cycle. */
1322 for (i = 0; i < num_edges; i++)
1324 edge e = INDEX_EDGE (el, i);
1325 if (EDGE_CRITICAL_P (e) && !EDGE_INFO (e)->ignore
1326 && find_group (e->src) != find_group (e->dest))
1328 if (dump_file)
1329 fprintf (dump_file, "Critical edge %d to %d put to tree\n",
1330 e->src->index, e->dest->index);
1331 EDGE_INFO (e)->on_tree = 1;
1332 union_groups (e->src, e->dest);
1336 /* And now the rest. */
1337 for (i = 0; i < num_edges; i++)
1339 edge e = INDEX_EDGE (el, i);
1340 if (!EDGE_INFO (e)->ignore
1341 && find_group (e->src) != find_group (e->dest))
1343 if (dump_file)
1344 fprintf (dump_file, "Normal edge %d to %d put to tree\n",
1345 e->src->index, e->dest->index);
1346 EDGE_INFO (e)->on_tree = 1;
1347 union_groups (e->src, e->dest);
1351 clear_aux_for_blocks ();
1354 /* Perform file-level initialization for branch-prob processing. */
1356 void
1357 init_branch_prob (void)
1359 int i;
1361 total_num_blocks = 0;
1362 total_num_edges = 0;
1363 total_num_edges_ignored = 0;
1364 total_num_edges_instrumented = 0;
1365 total_num_blocks_created = 0;
1366 total_num_passes = 0;
1367 total_num_times_called = 0;
1368 total_num_branches = 0;
1369 for (i = 0; i < 20; i++)
1370 total_hist_br_prob[i] = 0;
1373 /* Performs file-level cleanup after branch-prob processing
1374 is completed. */
1376 void
1377 end_branch_prob (void)
1379 if (dump_file)
1381 fprintf (dump_file, "\n");
1382 fprintf (dump_file, "Total number of blocks: %d\n",
1383 total_num_blocks);
1384 fprintf (dump_file, "Total number of edges: %d\n", total_num_edges);
1385 fprintf (dump_file, "Total number of ignored edges: %d\n",
1386 total_num_edges_ignored);
1387 fprintf (dump_file, "Total number of instrumented edges: %d\n",
1388 total_num_edges_instrumented);
1389 fprintf (dump_file, "Total number of blocks created: %d\n",
1390 total_num_blocks_created);
1391 fprintf (dump_file, "Total number of graph solution passes: %d\n",
1392 total_num_passes);
1393 if (total_num_times_called != 0)
1394 fprintf (dump_file, "Average number of graph solution passes: %d\n",
1395 (total_num_passes + (total_num_times_called >> 1))
1396 / total_num_times_called);
1397 fprintf (dump_file, "Total number of branches: %d\n",
1398 total_num_branches);
1399 if (total_num_branches)
1401 int i;
1403 for (i = 0; i < 10; i++)
1404 fprintf (dump_file, "%d%% branches in range %d-%d%%\n",
1405 (total_hist_br_prob[i] + total_hist_br_prob[19-i]) * 100
1406 / total_num_branches, 5*i, 5*i+5);