2011-04-28 Tobias Burnus <burnus@net-b.de>
[official-gcc.git] / gcc / profile.c
blobe40bfecca90fa5d9692436eed4f85612d9ee0f72
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
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 "output.h"
59 #include "regs.h"
60 #include "expr.h"
61 #include "function.h"
62 #include "basic-block.h"
63 #include "diagnostic-core.h"
64 #include "coverage.h"
65 #include "value-prof.h"
66 #include "tree.h"
67 #include "cfghooks.h"
68 #include "tree-flow.h"
69 #include "timevar.h"
70 #include "cfgloop.h"
71 #include "tree-pass.h"
73 #include "profile.h"
75 struct bb_info {
76 unsigned int count_valid : 1;
78 /* Number of successor and predecessor edges. */
79 gcov_type succ_count;
80 gcov_type pred_count;
83 #define BB_INFO(b) ((struct bb_info *) (b)->aux)
86 /* Counter summary from the last set of coverage counts read. */
88 const struct gcov_ctr_summary *profile_info;
90 /* Collect statistics on the performance of this pass for the entire source
91 file. */
93 static int total_num_blocks;
94 static int total_num_edges;
95 static int total_num_edges_ignored;
96 static int total_num_edges_instrumented;
97 static int total_num_blocks_created;
98 static int total_num_passes;
99 static int total_num_times_called;
100 static int total_hist_br_prob[20];
101 static int total_num_branches;
103 /* Forward declarations. */
104 static void find_spanning_tree (struct edge_list *);
105 static unsigned instrument_edges (struct edge_list *);
106 static void instrument_values (histogram_values);
107 static void compute_branch_probabilities (void);
108 static void compute_value_histograms (histogram_values);
109 static gcov_type * get_exec_counts (void);
110 static basic_block find_group (basic_block);
111 static void union_groups (basic_block, basic_block);
113 /* Add edge instrumentation code to the entire insn chain.
115 F is the first insn of the chain.
116 NUM_BLOCKS is the number of basic blocks found in F. */
118 static unsigned
119 instrument_edges (struct edge_list *el)
121 unsigned num_instr_edges = 0;
122 int num_edges = NUM_EDGES (el);
123 basic_block bb;
125 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
127 edge e;
128 edge_iterator ei;
130 FOR_EACH_EDGE (e, ei, bb->succs)
132 struct edge_info *inf = EDGE_INFO (e);
134 if (!inf->ignore && !inf->on_tree)
136 gcc_assert (!(e->flags & EDGE_ABNORMAL));
137 if (dump_file)
138 fprintf (dump_file, "Edge %d to %d instrumented%s\n",
139 e->src->index, e->dest->index,
140 EDGE_CRITICAL_P (e) ? " (and split)" : "");
141 gimple_gen_edge_profiler (num_instr_edges++, e);
146 total_num_blocks_created += num_edges;
147 if (dump_file)
148 fprintf (dump_file, "%d edges instrumented\n", num_instr_edges);
149 return num_instr_edges;
152 /* Add code to measure histograms for values in list VALUES. */
153 static void
154 instrument_values (histogram_values values)
156 unsigned i, t;
158 /* Emit code to generate the histograms before the insns. */
160 for (i = 0; i < VEC_length (histogram_value, values); i++)
162 histogram_value hist = VEC_index (histogram_value, values, i);
163 switch (hist->type)
165 case HIST_TYPE_INTERVAL:
166 t = GCOV_COUNTER_V_INTERVAL;
167 break;
169 case HIST_TYPE_POW2:
170 t = GCOV_COUNTER_V_POW2;
171 break;
173 case HIST_TYPE_SINGLE_VALUE:
174 t = GCOV_COUNTER_V_SINGLE;
175 break;
177 case HIST_TYPE_CONST_DELTA:
178 t = GCOV_COUNTER_V_DELTA;
179 break;
181 case HIST_TYPE_INDIR_CALL:
182 t = GCOV_COUNTER_V_INDIR;
183 break;
185 case HIST_TYPE_AVERAGE:
186 t = GCOV_COUNTER_AVERAGE;
187 break;
189 case HIST_TYPE_IOR:
190 t = GCOV_COUNTER_IOR;
191 break;
193 default:
194 gcc_unreachable ();
196 if (!coverage_counter_alloc (t, hist->n_counters))
197 continue;
199 switch (hist->type)
201 case HIST_TYPE_INTERVAL:
202 gimple_gen_interval_profiler (hist, t, 0);
203 break;
205 case HIST_TYPE_POW2:
206 gimple_gen_pow2_profiler (hist, t, 0);
207 break;
209 case HIST_TYPE_SINGLE_VALUE:
210 gimple_gen_one_value_profiler (hist, t, 0);
211 break;
213 case HIST_TYPE_CONST_DELTA:
214 gimple_gen_const_delta_profiler (hist, t, 0);
215 break;
217 case HIST_TYPE_INDIR_CALL:
218 gimple_gen_ic_profiler (hist, t, 0);
219 break;
221 case HIST_TYPE_AVERAGE:
222 gimple_gen_average_profiler (hist, t, 0);
223 break;
225 case HIST_TYPE_IOR:
226 gimple_gen_ior_profiler (hist, t, 0);
227 break;
229 default:
230 gcc_unreachable ();
236 /* Computes hybrid profile for all matching entries in da_file. */
238 static gcov_type *
239 get_exec_counts (void)
241 unsigned num_edges = 0;
242 basic_block bb;
243 gcov_type *counts;
245 /* Count the edges to be (possibly) instrumented. */
246 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
248 edge e;
249 edge_iterator ei;
251 FOR_EACH_EDGE (e, ei, bb->succs)
252 if (!EDGE_INFO (e)->ignore && !EDGE_INFO (e)->on_tree)
253 num_edges++;
256 counts = get_coverage_counts (GCOV_COUNTER_ARCS, num_edges, &profile_info);
257 if (!counts)
258 return NULL;
260 if (dump_file && profile_info)
261 fprintf(dump_file, "Merged %u profiles with maximal count %u.\n",
262 profile_info->runs, (unsigned) profile_info->sum_max);
264 return counts;
268 static bool
269 is_edge_inconsistent (VEC(edge,gc) *edges)
271 edge e;
272 edge_iterator ei;
273 FOR_EACH_EDGE (e, ei, edges)
275 if (!EDGE_INFO (e)->ignore)
277 if (e->count < 0
278 && (!(e->flags & EDGE_FAKE)
279 || !block_ends_with_call_p (e->src)))
281 if (dump_file)
283 fprintf (dump_file,
284 "Edge %i->%i is inconsistent, count"HOST_WIDEST_INT_PRINT_DEC,
285 e->src->index, e->dest->index, e->count);
286 dump_bb (e->src, dump_file, 0);
287 dump_bb (e->dest, dump_file, 0);
289 return true;
293 return false;
296 static void
297 correct_negative_edge_counts (void)
299 basic_block bb;
300 edge e;
301 edge_iterator ei;
303 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
305 FOR_EACH_EDGE (e, ei, bb->succs)
307 if (e->count < 0)
308 e->count = 0;
313 /* Check consistency.
314 Return true if inconsistency is found. */
315 static bool
316 is_inconsistent (void)
318 basic_block bb;
319 bool inconsistent = false;
320 FOR_EACH_BB (bb)
322 inconsistent |= is_edge_inconsistent (bb->preds);
323 if (!dump_file && inconsistent)
324 return true;
325 inconsistent |= is_edge_inconsistent (bb->succs);
326 if (!dump_file && inconsistent)
327 return true;
328 if (bb->count < 0)
330 if (dump_file)
332 fprintf (dump_file, "BB %i count is negative "
333 HOST_WIDEST_INT_PRINT_DEC,
334 bb->index,
335 bb->count);
336 dump_bb (bb, dump_file, 0);
338 inconsistent = true;
340 if (bb->count != sum_edge_counts (bb->preds))
342 if (dump_file)
344 fprintf (dump_file, "BB %i count does not match sum of incoming edges "
345 HOST_WIDEST_INT_PRINT_DEC" should be " HOST_WIDEST_INT_PRINT_DEC,
346 bb->index,
347 bb->count,
348 sum_edge_counts (bb->preds));
349 dump_bb (bb, dump_file, 0);
351 inconsistent = true;
353 if (bb->count != sum_edge_counts (bb->succs) &&
354 ! (find_edge (bb, EXIT_BLOCK_PTR) != NULL && block_ends_with_call_p (bb)))
356 if (dump_file)
358 fprintf (dump_file, "BB %i count does not match sum of outgoing edges "
359 HOST_WIDEST_INT_PRINT_DEC" should be " HOST_WIDEST_INT_PRINT_DEC,
360 bb->index,
361 bb->count,
362 sum_edge_counts (bb->succs));
363 dump_bb (bb, dump_file, 0);
365 inconsistent = true;
367 if (!dump_file && inconsistent)
368 return true;
371 return inconsistent;
374 /* Set each basic block count to the sum of its outgoing edge counts */
375 static void
376 set_bb_counts (void)
378 basic_block bb;
379 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
381 bb->count = sum_edge_counts (bb->succs);
382 gcc_assert (bb->count >= 0);
386 /* Reads profile data and returns total number of edge counts read */
387 static int
388 read_profile_edge_counts (gcov_type *exec_counts)
390 basic_block bb;
391 int num_edges = 0;
392 int exec_counts_pos = 0;
393 /* For each edge not on the spanning tree, set its execution count from
394 the .da file. */
395 /* The first count in the .da file is the number of times that the function
396 was entered. This is the exec_count for block zero. */
398 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
400 edge e;
401 edge_iterator ei;
403 FOR_EACH_EDGE (e, ei, bb->succs)
404 if (!EDGE_INFO (e)->ignore && !EDGE_INFO (e)->on_tree)
406 num_edges++;
407 if (exec_counts)
409 e->count = exec_counts[exec_counts_pos++];
410 if (e->count > profile_info->sum_max)
412 if (flag_profile_correction)
414 static bool informed = 0;
415 if (!informed)
416 inform (input_location,
417 "corrupted profile info: edge count exceeds maximal count");
418 informed = 1;
420 else
421 error ("corrupted profile info: edge from %i to %i exceeds maximal count",
422 bb->index, e->dest->index);
425 else
426 e->count = 0;
428 EDGE_INFO (e)->count_valid = 1;
429 BB_INFO (bb)->succ_count--;
430 BB_INFO (e->dest)->pred_count--;
431 if (dump_file)
433 fprintf (dump_file, "\nRead edge from %i to %i, count:",
434 bb->index, e->dest->index);
435 fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
436 (HOST_WIDEST_INT) e->count);
441 return num_edges;
444 /* Compute the branch probabilities for the various branches.
445 Annotate them accordingly. */
447 static void
448 compute_branch_probabilities (void)
450 basic_block bb;
451 int i;
452 int num_edges = 0;
453 int changes;
454 int passes;
455 int hist_br_prob[20];
456 int num_branches;
457 gcov_type *exec_counts = get_exec_counts ();
458 int inconsistent = 0;
460 /* Very simple sanity checks so we catch bugs in our profiling code. */
461 if (!profile_info)
462 return;
463 if (profile_info->run_max * profile_info->runs < profile_info->sum_max)
465 error ("corrupted profile info: run_max * runs < sum_max");
466 exec_counts = NULL;
469 if (profile_info->sum_all < profile_info->sum_max)
471 error ("corrupted profile info: sum_all is smaller than sum_max");
472 exec_counts = NULL;
475 /* Attach extra info block to each bb. */
476 alloc_aux_for_blocks (sizeof (struct bb_info));
477 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
479 edge e;
480 edge_iterator ei;
482 FOR_EACH_EDGE (e, ei, bb->succs)
483 if (!EDGE_INFO (e)->ignore)
484 BB_INFO (bb)->succ_count++;
485 FOR_EACH_EDGE (e, ei, bb->preds)
486 if (!EDGE_INFO (e)->ignore)
487 BB_INFO (bb)->pred_count++;
490 /* Avoid predicting entry on exit nodes. */
491 BB_INFO (EXIT_BLOCK_PTR)->succ_count = 2;
492 BB_INFO (ENTRY_BLOCK_PTR)->pred_count = 2;
494 num_edges = read_profile_edge_counts (exec_counts);
496 if (dump_file)
497 fprintf (dump_file, "\n%d edge counts read\n", num_edges);
499 /* For every block in the file,
500 - if every exit/entrance edge has a known count, then set the block count
501 - if the block count is known, and every exit/entrance edge but one has
502 a known execution count, then set the count of the remaining edge
504 As edge counts are set, decrement the succ/pred count, but don't delete
505 the edge, that way we can easily tell when all edges are known, or only
506 one edge is unknown. */
508 /* The order that the basic blocks are iterated through is important.
509 Since the code that finds spanning trees starts with block 0, low numbered
510 edges are put on the spanning tree in preference to high numbered edges.
511 Hence, most instrumented edges are at the end. Graph solving works much
512 faster if we propagate numbers from the end to the start.
514 This takes an average of slightly more than 3 passes. */
516 changes = 1;
517 passes = 0;
518 while (changes)
520 passes++;
521 changes = 0;
522 FOR_BB_BETWEEN (bb, EXIT_BLOCK_PTR, NULL, prev_bb)
524 struct bb_info *bi = BB_INFO (bb);
525 if (! bi->count_valid)
527 if (bi->succ_count == 0)
529 edge e;
530 edge_iterator ei;
531 gcov_type total = 0;
533 FOR_EACH_EDGE (e, ei, bb->succs)
534 total += e->count;
535 bb->count = total;
536 bi->count_valid = 1;
537 changes = 1;
539 else if (bi->pred_count == 0)
541 edge e;
542 edge_iterator ei;
543 gcov_type total = 0;
545 FOR_EACH_EDGE (e, ei, bb->preds)
546 total += e->count;
547 bb->count = total;
548 bi->count_valid = 1;
549 changes = 1;
552 if (bi->count_valid)
554 if (bi->succ_count == 1)
556 edge e;
557 edge_iterator ei;
558 gcov_type total = 0;
560 /* One of the counts will be invalid, but it is zero,
561 so adding it in also doesn't hurt. */
562 FOR_EACH_EDGE (e, ei, bb->succs)
563 total += e->count;
565 /* Search for the invalid edge, and set its count. */
566 FOR_EACH_EDGE (e, ei, bb->succs)
567 if (! EDGE_INFO (e)->count_valid && ! EDGE_INFO (e)->ignore)
568 break;
570 /* Calculate count for remaining edge by conservation. */
571 total = bb->count - total;
573 gcc_assert (e);
574 EDGE_INFO (e)->count_valid = 1;
575 e->count = total;
576 bi->succ_count--;
578 BB_INFO (e->dest)->pred_count--;
579 changes = 1;
581 if (bi->pred_count == 1)
583 edge e;
584 edge_iterator ei;
585 gcov_type total = 0;
587 /* One of the counts will be invalid, but it is zero,
588 so adding it in also doesn't hurt. */
589 FOR_EACH_EDGE (e, ei, bb->preds)
590 total += e->count;
592 /* Search for the invalid edge, and set its count. */
593 FOR_EACH_EDGE (e, ei, bb->preds)
594 if (!EDGE_INFO (e)->count_valid && !EDGE_INFO (e)->ignore)
595 break;
597 /* Calculate count for remaining edge by conservation. */
598 total = bb->count - total + e->count;
600 gcc_assert (e);
601 EDGE_INFO (e)->count_valid = 1;
602 e->count = total;
603 bi->pred_count--;
605 BB_INFO (e->src)->succ_count--;
606 changes = 1;
611 if (dump_file)
612 dump_flow_info (dump_file, dump_flags);
614 total_num_passes += passes;
615 if (dump_file)
616 fprintf (dump_file, "Graph solving took %d passes.\n\n", passes);
618 /* If the graph has been correctly solved, every block will have a
619 succ and pred count of zero. */
620 FOR_EACH_BB (bb)
622 gcc_assert (!BB_INFO (bb)->succ_count && !BB_INFO (bb)->pred_count);
625 /* Check for inconsistent basic block counts */
626 inconsistent = is_inconsistent ();
628 if (inconsistent)
630 if (flag_profile_correction)
632 /* Inconsistency detected. Make it flow-consistent. */
633 static int informed = 0;
634 if (informed == 0)
636 informed = 1;
637 inform (input_location, "correcting inconsistent profile data");
639 correct_negative_edge_counts ();
640 /* Set bb counts to the sum of the outgoing edge counts */
641 set_bb_counts ();
642 if (dump_file)
643 fprintf (dump_file, "\nCalling mcf_smooth_cfg\n");
644 mcf_smooth_cfg ();
646 else
647 error ("corrupted profile info: profile data is not flow-consistent");
650 /* For every edge, calculate its branch probability and add a reg_note
651 to the branch insn to indicate this. */
653 for (i = 0; i < 20; i++)
654 hist_br_prob[i] = 0;
655 num_branches = 0;
657 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
659 edge e;
660 edge_iterator ei;
662 if (bb->count < 0)
664 error ("corrupted profile info: number of iterations for basic block %d thought to be %i",
665 bb->index, (int)bb->count);
666 bb->count = 0;
668 FOR_EACH_EDGE (e, ei, bb->succs)
670 /* Function may return twice in the cased the called function is
671 setjmp or calls fork, but we can't represent this by extra
672 edge from the entry, since extra edge from the exit is
673 already present. We get negative frequency from the entry
674 point. */
675 if ((e->count < 0
676 && e->dest == EXIT_BLOCK_PTR)
677 || (e->count > bb->count
678 && e->dest != EXIT_BLOCK_PTR))
680 if (block_ends_with_call_p (bb))
681 e->count = e->count < 0 ? 0 : bb->count;
683 if (e->count < 0 || e->count > bb->count)
685 error ("corrupted profile info: number of executions for edge %d-%d thought to be %i",
686 e->src->index, e->dest->index,
687 (int)e->count);
688 e->count = bb->count / 2;
691 if (bb->count)
693 FOR_EACH_EDGE (e, ei, bb->succs)
694 e->probability = (e->count * REG_BR_PROB_BASE + bb->count / 2) / bb->count;
695 if (bb->index >= NUM_FIXED_BLOCKS
696 && block_ends_with_condjump_p (bb)
697 && EDGE_COUNT (bb->succs) >= 2)
699 int prob;
700 edge e;
701 int index;
703 /* Find the branch edge. It is possible that we do have fake
704 edges here. */
705 FOR_EACH_EDGE (e, ei, bb->succs)
706 if (!(e->flags & (EDGE_FAKE | EDGE_FALLTHRU)))
707 break;
709 prob = e->probability;
710 index = prob * 20 / REG_BR_PROB_BASE;
712 if (index == 20)
713 index = 19;
714 hist_br_prob[index]++;
716 num_branches++;
719 /* As a last resort, distribute the probabilities evenly.
720 Use simple heuristics that if there are normal edges,
721 give all abnormals frequency of 0, otherwise distribute the
722 frequency over abnormals (this is the case of noreturn
723 calls). */
724 else if (profile_status == PROFILE_ABSENT)
726 int total = 0;
728 FOR_EACH_EDGE (e, ei, bb->succs)
729 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
730 total ++;
731 if (total)
733 FOR_EACH_EDGE (e, ei, bb->succs)
734 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
735 e->probability = REG_BR_PROB_BASE / total;
736 else
737 e->probability = 0;
739 else
741 total += EDGE_COUNT (bb->succs);
742 FOR_EACH_EDGE (e, ei, bb->succs)
743 e->probability = REG_BR_PROB_BASE / total;
745 if (bb->index >= NUM_FIXED_BLOCKS
746 && block_ends_with_condjump_p (bb)
747 && EDGE_COUNT (bb->succs) >= 2)
748 num_branches++;
751 counts_to_freqs ();
752 profile_status = PROFILE_READ;
754 if (dump_file)
756 fprintf (dump_file, "%d branches\n", num_branches);
757 if (num_branches)
758 for (i = 0; i < 10; i++)
759 fprintf (dump_file, "%d%% branches in range %d-%d%%\n",
760 (hist_br_prob[i] + hist_br_prob[19-i]) * 100 / num_branches,
761 5 * i, 5 * i + 5);
763 total_num_branches += num_branches;
764 for (i = 0; i < 20; i++)
765 total_hist_br_prob[i] += hist_br_prob[i];
767 fputc ('\n', dump_file);
768 fputc ('\n', dump_file);
771 free_aux_for_blocks ();
774 /* Load value histograms values whose description is stored in VALUES array
775 from .gcda file. */
777 static void
778 compute_value_histograms (histogram_values values)
780 unsigned i, j, t, any;
781 unsigned n_histogram_counters[GCOV_N_VALUE_COUNTERS];
782 gcov_type *histogram_counts[GCOV_N_VALUE_COUNTERS];
783 gcov_type *act_count[GCOV_N_VALUE_COUNTERS];
784 gcov_type *aact_count;
786 for (t = 0; t < GCOV_N_VALUE_COUNTERS; t++)
787 n_histogram_counters[t] = 0;
789 for (i = 0; i < VEC_length (histogram_value, values); i++)
791 histogram_value hist = VEC_index (histogram_value, values, i);
792 n_histogram_counters[(int) hist->type] += hist->n_counters;
795 any = 0;
796 for (t = 0; t < GCOV_N_VALUE_COUNTERS; t++)
798 if (!n_histogram_counters[t])
800 histogram_counts[t] = NULL;
801 continue;
804 histogram_counts[t] =
805 get_coverage_counts (COUNTER_FOR_HIST_TYPE (t),
806 n_histogram_counters[t], NULL);
807 if (histogram_counts[t])
808 any = 1;
809 act_count[t] = histogram_counts[t];
811 if (!any)
812 return;
814 for (i = 0; i < VEC_length (histogram_value, values); i++)
816 histogram_value hist = VEC_index (histogram_value, values, i);
817 gimple stmt = hist->hvalue.stmt;
819 t = (int) hist->type;
821 aact_count = act_count[t];
822 act_count[t] += hist->n_counters;
824 gimple_add_histogram_value (cfun, stmt, hist);
825 hist->hvalue.counters = XNEWVEC (gcov_type, hist->n_counters);
826 for (j = 0; j < hist->n_counters; j++)
827 hist->hvalue.counters[j] = aact_count[j];
830 for (t = 0; t < GCOV_N_VALUE_COUNTERS; t++)
831 free (histogram_counts[t]);
834 /* The entry basic block will be moved around so that it has index=1,
835 there is nothing at index 0 and the exit is at n_basic_block. */
836 #define BB_TO_GCOV_INDEX(bb) ((bb)->index - 1)
837 /* When passed NULL as file_name, initialize.
838 When passed something else, output the necessary commands to change
839 line to LINE and offset to FILE_NAME. */
840 static void
841 output_location (char const *file_name, int line,
842 gcov_position_t *offset, basic_block bb)
844 static char const *prev_file_name;
845 static int prev_line;
846 bool name_differs, line_differs;
848 if (!file_name)
850 prev_file_name = NULL;
851 prev_line = -1;
852 return;
855 name_differs = !prev_file_name || filename_cmp (file_name, prev_file_name);
856 line_differs = prev_line != line;
858 if (name_differs || line_differs)
860 if (!*offset)
862 *offset = gcov_write_tag (GCOV_TAG_LINES);
863 gcov_write_unsigned (BB_TO_GCOV_INDEX (bb));
864 name_differs = line_differs=true;
867 /* If this is a new source file, then output the
868 file's name to the .bb file. */
869 if (name_differs)
871 prev_file_name = file_name;
872 gcov_write_unsigned (0);
873 gcov_write_string (prev_file_name);
875 if (line_differs)
877 gcov_write_unsigned (line);
878 prev_line = line;
883 /* Instrument and/or analyze program behavior based on program flow graph.
884 In either case, this function builds a flow graph for the function being
885 compiled. The flow graph is stored in BB_GRAPH.
887 When FLAG_PROFILE_ARCS is nonzero, this function instruments the edges in
888 the flow graph that are needed to reconstruct the dynamic behavior of the
889 flow graph.
891 When FLAG_BRANCH_PROBABILITIES is nonzero, this function reads auxiliary
892 information from a data file containing edge count information from previous
893 executions of the function being compiled. In this case, the flow graph is
894 annotated with actual execution counts, which are later propagated into the
895 rtl for optimization purposes.
897 Main entry point of this file. */
899 void
900 branch_prob (void)
902 basic_block bb;
903 unsigned i;
904 unsigned num_edges, ignored_edges;
905 unsigned num_instrumented;
906 struct edge_list *el;
907 histogram_values values = NULL;
909 total_num_times_called++;
911 flow_call_edges_add (NULL);
912 add_noreturn_fake_exit_edges ();
914 /* We can't handle cyclic regions constructed using abnormal edges.
915 To avoid these we replace every source of abnormal edge by a fake
916 edge from entry node and every destination by fake edge to exit.
917 This keeps graph acyclic and our calculation exact for all normal
918 edges except for exit and entrance ones.
920 We also add fake exit edges for each call and asm statement in the
921 basic, since it may not return. */
923 FOR_EACH_BB (bb)
925 int need_exit_edge = 0, need_entry_edge = 0;
926 int have_exit_edge = 0, have_entry_edge = 0;
927 edge e;
928 edge_iterator ei;
930 /* Functions returning multiple times are not handled by extra edges.
931 Instead we simply allow negative counts on edges from exit to the
932 block past call and corresponding probabilities. We can't go
933 with the extra edges because that would result in flowgraph that
934 needs to have fake edges outside the spanning tree. */
936 FOR_EACH_EDGE (e, ei, bb->succs)
938 gimple_stmt_iterator gsi;
939 gimple last = NULL;
941 /* It may happen that there are compiler generated statements
942 without a locus at all. Go through the basic block from the
943 last to the first statement looking for a locus. */
944 for (gsi = gsi_last_nondebug_bb (bb);
945 !gsi_end_p (gsi);
946 gsi_prev_nondebug (&gsi))
948 last = gsi_stmt (gsi);
949 if (gimple_has_location (last))
950 break;
953 /* Edge with goto locus might get wrong coverage info unless
954 it is the only edge out of BB.
955 Don't do that when the locuses match, so
956 if (blah) goto something;
957 is not computed twice. */
958 if (last
959 && gimple_has_location (last)
960 && e->goto_locus != UNKNOWN_LOCATION
961 && !single_succ_p (bb)
962 && (LOCATION_FILE (e->goto_locus)
963 != LOCATION_FILE (gimple_location (last))
964 || (LOCATION_LINE (e->goto_locus)
965 != LOCATION_LINE (gimple_location (last)))))
967 basic_block new_bb = split_edge (e);
968 edge ne = single_succ_edge (new_bb);
969 ne->goto_locus = e->goto_locus;
970 ne->goto_block = e->goto_block;
972 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
973 && e->dest != EXIT_BLOCK_PTR)
974 need_exit_edge = 1;
975 if (e->dest == EXIT_BLOCK_PTR)
976 have_exit_edge = 1;
978 FOR_EACH_EDGE (e, ei, bb->preds)
980 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
981 && e->src != ENTRY_BLOCK_PTR)
982 need_entry_edge = 1;
983 if (e->src == ENTRY_BLOCK_PTR)
984 have_entry_edge = 1;
987 if (need_exit_edge && !have_exit_edge)
989 if (dump_file)
990 fprintf (dump_file, "Adding fake exit edge to bb %i\n",
991 bb->index);
992 make_edge (bb, EXIT_BLOCK_PTR, EDGE_FAKE);
994 if (need_entry_edge && !have_entry_edge)
996 if (dump_file)
997 fprintf (dump_file, "Adding fake entry edge to bb %i\n",
998 bb->index);
999 make_edge (ENTRY_BLOCK_PTR, bb, EDGE_FAKE);
1003 el = create_edge_list ();
1004 num_edges = NUM_EDGES (el);
1005 alloc_aux_for_edges (sizeof (struct edge_info));
1007 /* The basic blocks are expected to be numbered sequentially. */
1008 compact_blocks ();
1010 ignored_edges = 0;
1011 for (i = 0 ; i < num_edges ; i++)
1013 edge e = INDEX_EDGE (el, i);
1014 e->count = 0;
1016 /* Mark edges we've replaced by fake edges above as ignored. */
1017 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
1018 && e->src != ENTRY_BLOCK_PTR && e->dest != EXIT_BLOCK_PTR)
1020 EDGE_INFO (e)->ignore = 1;
1021 ignored_edges++;
1025 /* Create spanning tree from basic block graph, mark each edge that is
1026 on the spanning tree. We insert as many abnormal and critical edges
1027 as possible to minimize number of edge splits necessary. */
1029 find_spanning_tree (el);
1031 /* Fake edges that are not on the tree will not be instrumented, so
1032 mark them ignored. */
1033 for (num_instrumented = i = 0; i < num_edges; i++)
1035 edge e = INDEX_EDGE (el, i);
1036 struct edge_info *inf = EDGE_INFO (e);
1038 if (inf->ignore || inf->on_tree)
1039 /*NOP*/;
1040 else if (e->flags & EDGE_FAKE)
1042 inf->ignore = 1;
1043 ignored_edges++;
1045 else
1046 num_instrumented++;
1049 total_num_blocks += n_basic_blocks;
1050 if (dump_file)
1051 fprintf (dump_file, "%d basic blocks\n", n_basic_blocks);
1053 total_num_edges += num_edges;
1054 if (dump_file)
1055 fprintf (dump_file, "%d edges\n", num_edges);
1057 total_num_edges_ignored += ignored_edges;
1058 if (dump_file)
1059 fprintf (dump_file, "%d ignored edges\n", ignored_edges);
1061 /* Write the data from which gcov can reconstruct the basic block
1062 graph. */
1064 /* Basic block flags */
1065 if (coverage_begin_output ())
1067 gcov_position_t offset;
1069 offset = gcov_write_tag (GCOV_TAG_BLOCKS);
1070 for (i = 0; i != (unsigned) (n_basic_blocks); i++)
1071 gcov_write_unsigned (0);
1072 gcov_write_length (offset);
1075 /* Keep all basic block indexes nonnegative in the gcov output.
1076 Index 0 is used for entry block, last index is for exit block.
1078 ENTRY_BLOCK_PTR->index = 1;
1079 EXIT_BLOCK_PTR->index = last_basic_block;
1081 /* Arcs */
1082 if (coverage_begin_output ())
1084 gcov_position_t offset;
1086 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
1088 edge e;
1089 edge_iterator ei;
1091 offset = gcov_write_tag (GCOV_TAG_ARCS);
1092 gcov_write_unsigned (BB_TO_GCOV_INDEX (bb));
1094 FOR_EACH_EDGE (e, ei, bb->succs)
1096 struct edge_info *i = EDGE_INFO (e);
1097 if (!i->ignore)
1099 unsigned flag_bits = 0;
1101 if (i->on_tree)
1102 flag_bits |= GCOV_ARC_ON_TREE;
1103 if (e->flags & EDGE_FAKE)
1104 flag_bits |= GCOV_ARC_FAKE;
1105 if (e->flags & EDGE_FALLTHRU)
1106 flag_bits |= GCOV_ARC_FALLTHROUGH;
1107 /* On trees we don't have fallthru flags, but we can
1108 recompute them from CFG shape. */
1109 if (e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)
1110 && e->src->next_bb == e->dest)
1111 flag_bits |= GCOV_ARC_FALLTHROUGH;
1113 gcov_write_unsigned (BB_TO_GCOV_INDEX (e->dest));
1114 gcov_write_unsigned (flag_bits);
1118 gcov_write_length (offset);
1122 /* Line numbers. */
1123 if (coverage_begin_output ())
1125 /* Initialize the output. */
1126 output_location (NULL, 0, NULL, NULL);
1128 FOR_EACH_BB (bb)
1130 gimple_stmt_iterator gsi;
1131 gcov_position_t offset = 0;
1133 if (bb == ENTRY_BLOCK_PTR->next_bb)
1135 expanded_location curr_location =
1136 expand_location (DECL_SOURCE_LOCATION (current_function_decl));
1137 output_location (curr_location.file, curr_location.line,
1138 &offset, bb);
1141 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1143 gimple stmt = gsi_stmt (gsi);
1144 if (gimple_has_location (stmt))
1145 output_location (gimple_filename (stmt), gimple_lineno (stmt),
1146 &offset, bb);
1149 /* Notice GOTO expressions eliminated while constructing the CFG. */
1150 if (single_succ_p (bb)
1151 && single_succ_edge (bb)->goto_locus != UNKNOWN_LOCATION)
1153 expanded_location curr_location
1154 = expand_location (single_succ_edge (bb)->goto_locus);
1155 output_location (curr_location.file, curr_location.line,
1156 &offset, bb);
1159 if (offset)
1161 /* A file of NULL indicates the end of run. */
1162 gcov_write_unsigned (0);
1163 gcov_write_string (NULL);
1164 gcov_write_length (offset);
1169 ENTRY_BLOCK_PTR->index = ENTRY_BLOCK;
1170 EXIT_BLOCK_PTR->index = EXIT_BLOCK;
1171 #undef BB_TO_GCOV_INDEX
1173 if (flag_profile_values)
1174 gimple_find_values_to_profile (&values);
1176 if (flag_branch_probabilities)
1178 compute_branch_probabilities ();
1179 if (flag_profile_values)
1180 compute_value_histograms (values);
1183 remove_fake_edges ();
1185 /* For each edge not on the spanning tree, add counting code. */
1186 if (profile_arc_flag
1187 && coverage_counter_alloc (GCOV_COUNTER_ARCS, num_instrumented))
1189 unsigned n_instrumented;
1191 gimple_init_edge_profiler ();
1193 n_instrumented = instrument_edges (el);
1195 gcc_assert (n_instrumented == num_instrumented);
1197 if (flag_profile_values)
1198 instrument_values (values);
1200 /* Commit changes done by instrumentation. */
1201 gsi_commit_edge_inserts ();
1204 free_aux_for_edges ();
1206 VEC_free (histogram_value, heap, values);
1207 free_edge_list (el);
1208 coverage_end_function ();
1211 /* Union find algorithm implementation for the basic blocks using
1212 aux fields. */
1214 static basic_block
1215 find_group (basic_block bb)
1217 basic_block group = bb, bb1;
1219 while ((basic_block) group->aux != group)
1220 group = (basic_block) group->aux;
1222 /* Compress path. */
1223 while ((basic_block) bb->aux != group)
1225 bb1 = (basic_block) bb->aux;
1226 bb->aux = (void *) group;
1227 bb = bb1;
1229 return group;
1232 static void
1233 union_groups (basic_block bb1, basic_block bb2)
1235 basic_block bb1g = find_group (bb1);
1236 basic_block bb2g = find_group (bb2);
1238 /* ??? I don't have a place for the rank field. OK. Lets go w/o it,
1239 this code is unlikely going to be performance problem anyway. */
1240 gcc_assert (bb1g != bb2g);
1242 bb1g->aux = bb2g;
1245 /* This function searches all of the edges in the program flow graph, and puts
1246 as many bad edges as possible onto the spanning tree. Bad edges include
1247 abnormals edges, which can't be instrumented at the moment. Since it is
1248 possible for fake edges to form a cycle, we will have to develop some
1249 better way in the future. Also put critical edges to the tree, since they
1250 are more expensive to instrument. */
1252 static void
1253 find_spanning_tree (struct edge_list *el)
1255 int i;
1256 int num_edges = NUM_EDGES (el);
1257 basic_block bb;
1259 /* We use aux field for standard union-find algorithm. */
1260 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1261 bb->aux = bb;
1263 /* Add fake edge exit to entry we can't instrument. */
1264 union_groups (EXIT_BLOCK_PTR, ENTRY_BLOCK_PTR);
1266 /* First add all abnormal edges to the tree unless they form a cycle. Also
1267 add all edges to EXIT_BLOCK_PTR to avoid inserting profiling code behind
1268 setting return value from function. */
1269 for (i = 0; i < num_edges; i++)
1271 edge e = INDEX_EDGE (el, i);
1272 if (((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL | EDGE_FAKE))
1273 || e->dest == EXIT_BLOCK_PTR)
1274 && !EDGE_INFO (e)->ignore
1275 && (find_group (e->src) != find_group (e->dest)))
1277 if (dump_file)
1278 fprintf (dump_file, "Abnormal edge %d to %d put to tree\n",
1279 e->src->index, e->dest->index);
1280 EDGE_INFO (e)->on_tree = 1;
1281 union_groups (e->src, e->dest);
1285 /* Now insert all critical edges to the tree unless they form a cycle. */
1286 for (i = 0; i < num_edges; i++)
1288 edge e = INDEX_EDGE (el, i);
1289 if (EDGE_CRITICAL_P (e) && !EDGE_INFO (e)->ignore
1290 && find_group (e->src) != find_group (e->dest))
1292 if (dump_file)
1293 fprintf (dump_file, "Critical edge %d to %d put to tree\n",
1294 e->src->index, e->dest->index);
1295 EDGE_INFO (e)->on_tree = 1;
1296 union_groups (e->src, e->dest);
1300 /* And now the rest. */
1301 for (i = 0; i < num_edges; i++)
1303 edge e = INDEX_EDGE (el, i);
1304 if (!EDGE_INFO (e)->ignore
1305 && find_group (e->src) != find_group (e->dest))
1307 if (dump_file)
1308 fprintf (dump_file, "Normal edge %d to %d put to tree\n",
1309 e->src->index, e->dest->index);
1310 EDGE_INFO (e)->on_tree = 1;
1311 union_groups (e->src, e->dest);
1315 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1316 bb->aux = NULL;
1319 /* Perform file-level initialization for branch-prob processing. */
1321 void
1322 init_branch_prob (void)
1324 int i;
1326 total_num_blocks = 0;
1327 total_num_edges = 0;
1328 total_num_edges_ignored = 0;
1329 total_num_edges_instrumented = 0;
1330 total_num_blocks_created = 0;
1331 total_num_passes = 0;
1332 total_num_times_called = 0;
1333 total_num_branches = 0;
1334 for (i = 0; i < 20; i++)
1335 total_hist_br_prob[i] = 0;
1338 /* Performs file-level cleanup after branch-prob processing
1339 is completed. */
1341 void
1342 end_branch_prob (void)
1344 if (dump_file)
1346 fprintf (dump_file, "\n");
1347 fprintf (dump_file, "Total number of blocks: %d\n",
1348 total_num_blocks);
1349 fprintf (dump_file, "Total number of edges: %d\n", total_num_edges);
1350 fprintf (dump_file, "Total number of ignored edges: %d\n",
1351 total_num_edges_ignored);
1352 fprintf (dump_file, "Total number of instrumented edges: %d\n",
1353 total_num_edges_instrumented);
1354 fprintf (dump_file, "Total number of blocks created: %d\n",
1355 total_num_blocks_created);
1356 fprintf (dump_file, "Total number of graph solution passes: %d\n",
1357 total_num_passes);
1358 if (total_num_times_called != 0)
1359 fprintf (dump_file, "Average number of graph solution passes: %d\n",
1360 (total_num_passes + (total_num_times_called >> 1))
1361 / total_num_times_called);
1362 fprintf (dump_file, "Total number of branches: %d\n",
1363 total_num_branches);
1364 if (total_num_branches)
1366 int i;
1368 for (i = 0; i < 10; i++)
1369 fprintf (dump_file, "%d%% branches in range %d-%d%%\n",
1370 (total_hist_br_prob[i] + total_hist_br_prob[19-i]) * 100
1371 / total_num_branches, 5*i, 5*i+5);