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
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
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. */
52 #include "coretypes.h"
59 #include "basic-block.h"
60 #include "diagnostic-core.h"
62 #include "value-prof.h"
64 #include "tree-flow.h"
71 unsigned int count_valid
: 1;
73 /* Number of successor and predecessor edges. */
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
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. */
111 instrument_edges (struct edge_list
*el
)
113 unsigned num_instr_edges
= 0;
114 int num_edges
= NUM_EDGES (el
);
117 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
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
));
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
;
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. */
146 instrument_values (histogram_values values
)
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
))
162 case HIST_TYPE_INTERVAL
:
163 gimple_gen_interval_profiler (hist
, t
, 0);
167 gimple_gen_pow2_profiler (hist
, t
, 0);
170 case HIST_TYPE_SINGLE_VALUE
:
171 gimple_gen_one_value_profiler (hist
, t
, 0);
174 case HIST_TYPE_CONST_DELTA
:
175 gimple_gen_const_delta_profiler (hist
, t
, 0);
178 case HIST_TYPE_INDIR_CALL
:
179 gimple_gen_ic_profiler (hist
, t
, 0);
182 case HIST_TYPE_AVERAGE
:
183 gimple_gen_average_profiler (hist
, t
, 0);
187 gimple_gen_ior_profiler (hist
, t
, 0);
197 /* Fill the working set information into the profile_info structure. */
200 get_working_sets (void)
202 unsigned ws_ix
, pctinc
, pct
;
203 gcov_working_set_t
*ws_info
;
208 compute_working_sets (profile_info
, gcov_working_sets
);
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)
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. */
237 find_working_set (unsigned pct_times_10
)
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;
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. */
256 get_exec_counts (unsigned cfg_checksum
, unsigned lineno_checksum
)
258 unsigned num_edges
= 0;
262 /* Count the edges to be (possibly) instrumented. */
263 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
268 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
269 if (!EDGE_INFO (e
)->ignore
&& !EDGE_INFO (e
)->on_tree
)
273 counts
= get_coverage_counts (GCOV_COUNTER_ARCS
, num_edges
, cfg_checksum
,
274 lineno_checksum
, &profile_info
);
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
);
289 is_edge_inconsistent (vec
<edge
, va_gc
> *edges
)
293 FOR_EACH_EDGE (e
, ei
, edges
)
295 if (!EDGE_INFO (e
)->ignore
)
298 && (!(e
->flags
& EDGE_FAKE
)
299 || !block_ends_with_call_p (e
->src
)))
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
);
317 correct_negative_edge_counts (void)
323 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
325 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
333 /* Check consistency.
334 Return true if inconsistency is found. */
336 is_inconsistent (void)
339 bool inconsistent
= false;
342 inconsistent
|= is_edge_inconsistent (bb
->preds
);
343 if (!dump_file
&& inconsistent
)
345 inconsistent
|= is_edge_inconsistent (bb
->succs
);
346 if (!dump_file
&& inconsistent
)
352 fprintf (dump_file
, "BB %i count is negative "
353 HOST_WIDEST_INT_PRINT_DEC
,
356 dump_bb (dump_file
, bb
, 0, TDF_DETAILS
);
360 if (bb
->count
!= sum_edge_counts (bb
->preds
))
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
,
368 sum_edge_counts (bb
->preds
));
369 dump_bb (dump_file
, bb
, 0, TDF_DETAILS
);
373 if (bb
->count
!= sum_edge_counts (bb
->succs
) &&
374 ! (find_edge (bb
, EXIT_BLOCK_PTR
) != NULL
&& block_ends_with_call_p (bb
)))
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
,
382 sum_edge_counts (bb
->succs
));
383 dump_bb (dump_file
, bb
, 0, TDF_DETAILS
);
387 if (!dump_file
&& inconsistent
)
394 /* Set each basic block count to the sum of its outgoing edge counts */
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 */
408 read_profile_edge_counts (gcov_type
*exec_counts
)
412 int exec_counts_pos
= 0;
413 /* For each edge not on the spanning tree, set its execution count from
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
)
423 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
424 if (!EDGE_INFO (e
)->ignore
&& !EDGE_INFO (e
)->on_tree
)
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 (dump_enabled_p () && !informed
)
436 dump_printf_loc (MSG_NOTE
, input_location
,
437 "corrupted profile info: edge count exceeds maximal count");
441 error ("corrupted profile info: edge from %i to %i exceeds maximal count",
442 bb
->index
, e
->dest
->index
);
448 EDGE_INFO (e
)->count_valid
= 1;
449 BB_INFO (bb
)->succ_count
--;
450 BB_INFO (e
->dest
)->pred_count
--;
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
);
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
475 compute_frequency_overlap (void)
477 gcov_type count_total
= 0, freq_total
= 0;
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)
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
);
497 /* Compute the branch probabilities for the various branches.
498 Annotate them accordingly.
500 CFG_CHECKSUM is the precomputed checksum for the CFG. */
503 compute_branch_probabilities (unsigned cfg_checksum
, unsigned lineno_checksum
)
510 int hist_br_prob
[20];
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. */
518 if (profile_info
->run_max
* profile_info
->runs
< profile_info
->sum_max
)
520 error ("corrupted profile info: run_max * runs < sum_max");
524 if (profile_info
->sum_all
< profile_info
->sum_max
)
526 error ("corrupted profile info: sum_all is smaller than sum_max");
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
)
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
);
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. */
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)
588 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
594 else if (bi
->pred_count
== 0)
600 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
609 if (bi
->succ_count
== 1)
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
)
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
)
625 /* Calculate count for remaining edge by conservation. */
626 total
= bb
->count
- total
;
629 EDGE_INFO (e
)->count_valid
= 1;
633 BB_INFO (e
->dest
)->pred_count
--;
636 if (bi
->pred_count
== 1)
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
)
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
)
652 /* Calculate count for remaining edge by conservation. */
653 total
= bb
->count
- total
+ e
->count
;
656 EDGE_INFO (e
)->count_valid
= 1;
660 BB_INFO (e
->src
)->succ_count
--;
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
;
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. */
683 gcc_assert (!BB_INFO (bb
)->succ_count
&& !BB_INFO (bb
)->pred_count
);
686 /* Check for inconsistent basic block counts */
687 inconsistent
= is_inconsistent ();
691 if (flag_profile_correction
)
693 /* Inconsistency detected. Make it flow-consistent. */
694 static int informed
= 0;
695 if (dump_enabled_p () && informed
== 0)
698 dump_printf_loc (MSG_NOTE
, input_location
,
699 "correcting inconsistent profile data");
701 correct_negative_edge_counts ();
702 /* Set bb counts to the sum of the outgoing edge counts */
705 fprintf (dump_file
, "\nCalling mcf_smooth_cfg\n");
709 error ("corrupted profile info: profile data is not flow-consistent");
712 /* For every edge, calculate its branch probability and add a reg_note
713 to the branch insn to indicate this. */
715 for (i
= 0; i
< 20; i
++)
719 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
726 error ("corrupted profile info: number of iterations for basic block %d thought to be %i",
727 bb
->index
, (int)bb
->count
);
730 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
732 /* Function may return twice in the cased the called function is
733 setjmp or calls fork, but we can't represent this by extra
734 edge from the entry, since extra edge from the exit is
735 already present. We get negative frequency from the entry
738 && e
->dest
== EXIT_BLOCK_PTR
)
739 || (e
->count
> bb
->count
740 && e
->dest
!= EXIT_BLOCK_PTR
))
742 if (block_ends_with_call_p (bb
))
743 e
->count
= e
->count
< 0 ? 0 : bb
->count
;
745 if (e
->count
< 0 || e
->count
> bb
->count
)
747 error ("corrupted profile info: number of executions for edge %d-%d thought to be %i",
748 e
->src
->index
, e
->dest
->index
,
750 e
->count
= bb
->count
/ 2;
755 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
756 e
->probability
= GCOV_COMPUTE_SCALE (e
->count
, bb
->count
);
757 if (bb
->index
>= NUM_FIXED_BLOCKS
758 && block_ends_with_condjump_p (bb
)
759 && EDGE_COUNT (bb
->succs
) >= 2)
765 /* Find the branch edge. It is possible that we do have fake
767 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
768 if (!(e
->flags
& (EDGE_FAKE
| EDGE_FALLTHRU
)))
771 prob
= e
->probability
;
772 index
= prob
* 20 / REG_BR_PROB_BASE
;
776 hist_br_prob
[index
]++;
781 /* As a last resort, distribute the probabilities evenly.
782 Use simple heuristics that if there are normal edges,
783 give all abnormals frequency of 0, otherwise distribute the
784 frequency over abnormals (this is the case of noreturn
786 else if (profile_status
== PROFILE_ABSENT
)
790 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
791 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
795 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
796 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
797 e
->probability
= REG_BR_PROB_BASE
/ total
;
803 total
+= EDGE_COUNT (bb
->succs
);
804 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
805 e
->probability
= REG_BR_PROB_BASE
/ total
;
807 if (bb
->index
>= NUM_FIXED_BLOCKS
808 && block_ends_with_condjump_p (bb
)
809 && EDGE_COUNT (bb
->succs
) >= 2)
814 profile_status
= PROFILE_READ
;
815 compute_function_frequency ();
819 fprintf (dump_file
, "%d branches\n", num_branches
);
821 for (i
= 0; i
< 10; i
++)
822 fprintf (dump_file
, "%d%% branches in range %d-%d%%\n",
823 (hist_br_prob
[i
] + hist_br_prob
[19-i
]) * 100 / num_branches
,
826 total_num_branches
+= num_branches
;
827 for (i
= 0; i
< 20; i
++)
828 total_hist_br_prob
[i
] += hist_br_prob
[i
];
830 fputc ('\n', dump_file
);
831 fputc ('\n', dump_file
);
834 free_aux_for_blocks ();
837 /* Load value histograms values whose description is stored in VALUES array
840 CFG_CHECKSUM is the precomputed checksum for the CFG. */
843 compute_value_histograms (histogram_values values
, unsigned cfg_checksum
,
844 unsigned lineno_checksum
)
846 unsigned i
, j
, t
, any
;
847 unsigned n_histogram_counters
[GCOV_N_VALUE_COUNTERS
];
848 gcov_type
*histogram_counts
[GCOV_N_VALUE_COUNTERS
];
849 gcov_type
*act_count
[GCOV_N_VALUE_COUNTERS
];
850 gcov_type
*aact_count
;
852 for (t
= 0; t
< GCOV_N_VALUE_COUNTERS
; t
++)
853 n_histogram_counters
[t
] = 0;
855 for (i
= 0; i
< values
.length (); i
++)
857 histogram_value hist
= values
[i
];
858 n_histogram_counters
[(int) hist
->type
] += hist
->n_counters
;
862 for (t
= 0; t
< GCOV_N_VALUE_COUNTERS
; t
++)
864 if (!n_histogram_counters
[t
])
866 histogram_counts
[t
] = NULL
;
870 histogram_counts
[t
] =
871 get_coverage_counts (COUNTER_FOR_HIST_TYPE (t
),
872 n_histogram_counters
[t
], cfg_checksum
,
873 lineno_checksum
, NULL
);
874 if (histogram_counts
[t
])
876 act_count
[t
] = histogram_counts
[t
];
881 for (i
= 0; i
< values
.length (); i
++)
883 histogram_value hist
= values
[i
];
884 gimple stmt
= hist
->hvalue
.stmt
;
886 t
= (int) hist
->type
;
888 aact_count
= act_count
[t
];
890 act_count
[t
] += hist
->n_counters
;
892 gimple_add_histogram_value (cfun
, stmt
, hist
);
893 hist
->hvalue
.counters
= XNEWVEC (gcov_type
, hist
->n_counters
);
894 for (j
= 0; j
< hist
->n_counters
; j
++)
896 hist
->hvalue
.counters
[j
] = aact_count
[j
];
898 hist
->hvalue
.counters
[j
] = 0;
901 for (t
= 0; t
< GCOV_N_VALUE_COUNTERS
; t
++)
902 free (histogram_counts
[t
]);
905 /* When passed NULL as file_name, initialize.
906 When passed something else, output the necessary commands to change
907 line to LINE and offset to FILE_NAME. */
909 output_location (char const *file_name
, int line
,
910 gcov_position_t
*offset
, basic_block bb
)
912 static char const *prev_file_name
;
913 static int prev_line
;
914 bool name_differs
, line_differs
;
918 prev_file_name
= NULL
;
923 name_differs
= !prev_file_name
|| filename_cmp (file_name
, prev_file_name
);
924 line_differs
= prev_line
!= line
;
926 if (name_differs
|| line_differs
)
930 *offset
= gcov_write_tag (GCOV_TAG_LINES
);
931 gcov_write_unsigned (bb
->index
);
932 name_differs
= line_differs
=true;
935 /* If this is a new source file, then output the
936 file's name to the .bb file. */
939 prev_file_name
= file_name
;
940 gcov_write_unsigned (0);
941 gcov_write_string (prev_file_name
);
945 gcov_write_unsigned (line
);
951 /* Instrument and/or analyze program behavior based on program the CFG.
953 This function creates a representation of the control flow graph (of
954 the function being compiled) that is suitable for the instrumentation
955 of edges and/or converting measured edge counts to counts on the
958 When FLAG_PROFILE_ARCS is nonzero, this function instruments the edges in
959 the flow graph that are needed to reconstruct the dynamic behavior of the
960 flow graph. This data is written to the gcno file for gcov.
962 When FLAG_BRANCH_PROBABILITIES is nonzero, this function reads auxiliary
963 information from the gcda file containing edge count information from
964 previous executions of the function being compiled. In this case, the
965 control flow graph is annotated with actual execution counts by
966 compute_branch_probabilities().
968 Main entry point of this file. */
975 unsigned num_edges
, ignored_edges
;
976 unsigned num_instrumented
;
977 struct edge_list
*el
;
978 histogram_values values
= histogram_values();
979 unsigned cfg_checksum
, lineno_checksum
;
981 total_num_times_called
++;
983 flow_call_edges_add (NULL
);
984 add_noreturn_fake_exit_edges ();
986 /* We can't handle cyclic regions constructed using abnormal edges.
987 To avoid these we replace every source of abnormal edge by a fake
988 edge from entry node and every destination by fake edge to exit.
989 This keeps graph acyclic and our calculation exact for all normal
990 edges except for exit and entrance ones.
992 We also add fake exit edges for each call and asm statement in the
993 basic, since it may not return. */
997 int need_exit_edge
= 0, need_entry_edge
= 0;
998 int have_exit_edge
= 0, have_entry_edge
= 0;
1002 /* Functions returning multiple times are not handled by extra edges.
1003 Instead we simply allow negative counts on edges from exit to the
1004 block past call and corresponding probabilities. We can't go
1005 with the extra edges because that would result in flowgraph that
1006 needs to have fake edges outside the spanning tree. */
1008 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1010 gimple_stmt_iterator gsi
;
1013 /* It may happen that there are compiler generated statements
1014 without a locus at all. Go through the basic block from the
1015 last to the first statement looking for a locus. */
1016 for (gsi
= gsi_last_nondebug_bb (bb
);
1018 gsi_prev_nondebug (&gsi
))
1020 last
= gsi_stmt (gsi
);
1021 if (gimple_has_location (last
))
1025 /* Edge with goto locus might get wrong coverage info unless
1026 it is the only edge out of BB.
1027 Don't do that when the locuses match, so
1028 if (blah) goto something;
1029 is not computed twice. */
1031 && gimple_has_location (last
)
1032 && LOCATION_LOCUS (e
->goto_locus
) != UNKNOWN_LOCATION
1033 && !single_succ_p (bb
)
1034 && (LOCATION_FILE (e
->goto_locus
)
1035 != LOCATION_FILE (gimple_location (last
))
1036 || (LOCATION_LINE (e
->goto_locus
)
1037 != LOCATION_LINE (gimple_location (last
)))))
1039 basic_block new_bb
= split_edge (e
);
1040 edge ne
= single_succ_edge (new_bb
);
1041 ne
->goto_locus
= e
->goto_locus
;
1043 if ((e
->flags
& (EDGE_ABNORMAL
| EDGE_ABNORMAL_CALL
))
1044 && e
->dest
!= EXIT_BLOCK_PTR
)
1046 if (e
->dest
== EXIT_BLOCK_PTR
)
1049 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
1051 if ((e
->flags
& (EDGE_ABNORMAL
| EDGE_ABNORMAL_CALL
))
1052 && e
->src
!= ENTRY_BLOCK_PTR
)
1053 need_entry_edge
= 1;
1054 if (e
->src
== ENTRY_BLOCK_PTR
)
1055 have_entry_edge
= 1;
1058 if (need_exit_edge
&& !have_exit_edge
)
1061 fprintf (dump_file
, "Adding fake exit edge to bb %i\n",
1063 make_edge (bb
, EXIT_BLOCK_PTR
, EDGE_FAKE
);
1065 if (need_entry_edge
&& !have_entry_edge
)
1068 fprintf (dump_file
, "Adding fake entry edge to bb %i\n",
1070 make_edge (ENTRY_BLOCK_PTR
, bb
, EDGE_FAKE
);
1071 /* Avoid bbs that have both fake entry edge and also some
1072 exit edge. One of those edges wouldn't be added to the
1073 spanning tree, but we can't instrument any of them. */
1074 if (have_exit_edge
|| need_exit_edge
)
1076 gimple_stmt_iterator gsi
;
1080 gsi
= gsi_after_labels (bb
);
1081 gcc_checking_assert (!gsi_end_p (gsi
));
1082 first
= gsi_stmt (gsi
);
1083 if (is_gimple_debug (first
))
1085 gsi_next_nondebug (&gsi
);
1086 gcc_checking_assert (!gsi_end_p (gsi
));
1087 first
= gsi_stmt (gsi
);
1089 /* Don't split the bbs containing __builtin_setjmp_receiver
1090 or __builtin_setjmp_dispatcher calls. These are very
1091 special and don't expect anything to be inserted before
1093 if (is_gimple_call (first
)
1094 && (((fndecl
= gimple_call_fndecl (first
)) != NULL
1095 && DECL_BUILT_IN_CLASS (fndecl
) == BUILT_IN_NORMAL
1096 && (DECL_FUNCTION_CODE (fndecl
)
1097 == BUILT_IN_SETJMP_RECEIVER
1098 || (DECL_FUNCTION_CODE (fndecl
)
1099 == BUILT_IN_SETJMP_DISPATCHER
)))
1100 || gimple_call_flags (first
) & ECF_RETURNS_TWICE
))
1104 fprintf (dump_file
, "Splitting bb %i after labels\n",
1106 split_block_after_labels (bb
);
1111 el
= create_edge_list ();
1112 num_edges
= NUM_EDGES (el
);
1113 alloc_aux_for_edges (sizeof (struct edge_info
));
1115 /* The basic blocks are expected to be numbered sequentially. */
1119 for (i
= 0 ; i
< num_edges
; i
++)
1121 edge e
= INDEX_EDGE (el
, i
);
1124 /* Mark edges we've replaced by fake edges above as ignored. */
1125 if ((e
->flags
& (EDGE_ABNORMAL
| EDGE_ABNORMAL_CALL
))
1126 && e
->src
!= ENTRY_BLOCK_PTR
&& e
->dest
!= EXIT_BLOCK_PTR
)
1128 EDGE_INFO (e
)->ignore
= 1;
1133 /* Create spanning tree from basic block graph, mark each edge that is
1134 on the spanning tree. We insert as many abnormal and critical edges
1135 as possible to minimize number of edge splits necessary. */
1137 find_spanning_tree (el
);
1139 /* Fake edges that are not on the tree will not be instrumented, so
1140 mark them ignored. */
1141 for (num_instrumented
= i
= 0; i
< num_edges
; i
++)
1143 edge e
= INDEX_EDGE (el
, i
);
1144 struct edge_info
*inf
= EDGE_INFO (e
);
1146 if (inf
->ignore
|| inf
->on_tree
)
1148 else if (e
->flags
& EDGE_FAKE
)
1157 total_num_blocks
+= n_basic_blocks
;
1159 fprintf (dump_file
, "%d basic blocks\n", n_basic_blocks
);
1161 total_num_edges
+= num_edges
;
1163 fprintf (dump_file
, "%d edges\n", num_edges
);
1165 total_num_edges_ignored
+= ignored_edges
;
1167 fprintf (dump_file
, "%d ignored edges\n", ignored_edges
);
1169 total_num_edges_instrumented
+= num_instrumented
;
1171 fprintf (dump_file
, "%d instrumentation edges\n", num_instrumented
);
1173 /* Compute two different checksums. Note that we want to compute
1174 the checksum in only once place, since it depends on the shape
1175 of the control flow which can change during
1176 various transformations. */
1177 cfg_checksum
= coverage_compute_cfg_checksum ();
1178 lineno_checksum
= coverage_compute_lineno_checksum ();
1180 /* Write the data from which gcov can reconstruct the basic block
1181 graph and function line numbers (the gcno file). */
1182 if (coverage_begin_function (lineno_checksum
, cfg_checksum
))
1184 gcov_position_t offset
;
1186 /* Basic block flags */
1187 offset
= gcov_write_tag (GCOV_TAG_BLOCKS
);
1188 for (i
= 0; i
!= (unsigned) (n_basic_blocks
); i
++)
1189 gcov_write_unsigned (0);
1190 gcov_write_length (offset
);
1193 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, EXIT_BLOCK_PTR
, next_bb
)
1198 offset
= gcov_write_tag (GCOV_TAG_ARCS
);
1199 gcov_write_unsigned (bb
->index
);
1201 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1203 struct edge_info
*i
= EDGE_INFO (e
);
1206 unsigned flag_bits
= 0;
1209 flag_bits
|= GCOV_ARC_ON_TREE
;
1210 if (e
->flags
& EDGE_FAKE
)
1211 flag_bits
|= GCOV_ARC_FAKE
;
1212 if (e
->flags
& EDGE_FALLTHRU
)
1213 flag_bits
|= GCOV_ARC_FALLTHROUGH
;
1214 /* On trees we don't have fallthru flags, but we can
1215 recompute them from CFG shape. */
1216 if (e
->flags
& (EDGE_TRUE_VALUE
| EDGE_FALSE_VALUE
)
1217 && e
->src
->next_bb
== e
->dest
)
1218 flag_bits
|= GCOV_ARC_FALLTHROUGH
;
1220 gcov_write_unsigned (e
->dest
->index
);
1221 gcov_write_unsigned (flag_bits
);
1225 gcov_write_length (offset
);
1229 /* Initialize the output. */
1230 output_location (NULL
, 0, NULL
, NULL
);
1234 gimple_stmt_iterator gsi
;
1235 gcov_position_t offset
= 0;
1237 if (bb
== ENTRY_BLOCK_PTR
->next_bb
)
1239 expanded_location curr_location
=
1240 expand_location (DECL_SOURCE_LOCATION (current_function_decl
));
1241 output_location (curr_location
.file
, curr_location
.line
,
1245 for (gsi
= gsi_start_bb (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
1247 gimple stmt
= gsi_stmt (gsi
);
1248 if (gimple_has_location (stmt
))
1249 output_location (gimple_filename (stmt
), gimple_lineno (stmt
),
1253 /* Notice GOTO expressions eliminated while constructing the CFG. */
1254 if (single_succ_p (bb
)
1255 && LOCATION_LOCUS (single_succ_edge (bb
)->goto_locus
)
1256 != UNKNOWN_LOCATION
)
1258 expanded_location curr_location
1259 = expand_location (single_succ_edge (bb
)->goto_locus
);
1260 output_location (curr_location
.file
, curr_location
.line
,
1266 /* A file of NULL indicates the end of run. */
1267 gcov_write_unsigned (0);
1268 gcov_write_string (NULL
);
1269 gcov_write_length (offset
);
1274 if (flag_profile_values
)
1275 gimple_find_values_to_profile (&values
);
1277 if (flag_branch_probabilities
)
1279 compute_branch_probabilities (cfg_checksum
, lineno_checksum
);
1280 if (flag_profile_values
)
1281 compute_value_histograms (values
, cfg_checksum
, lineno_checksum
);
1284 remove_fake_edges ();
1286 /* For each edge not on the spanning tree, add counting code. */
1287 if (profile_arc_flag
1288 && coverage_counter_alloc (GCOV_COUNTER_ARCS
, num_instrumented
))
1290 unsigned n_instrumented
;
1292 gimple_init_edge_profiler ();
1294 n_instrumented
= instrument_edges (el
);
1296 gcc_assert (n_instrumented
== num_instrumented
);
1298 if (flag_profile_values
)
1299 instrument_values (values
);
1301 /* Commit changes done by instrumentation. */
1302 gsi_commit_edge_inserts ();
1305 free_aux_for_edges ();
1308 free_edge_list (el
);
1309 coverage_end_function (lineno_checksum
, cfg_checksum
);
1312 /* Union find algorithm implementation for the basic blocks using
1316 find_group (basic_block bb
)
1318 basic_block group
= bb
, bb1
;
1320 while ((basic_block
) group
->aux
!= group
)
1321 group
= (basic_block
) group
->aux
;
1323 /* Compress path. */
1324 while ((basic_block
) bb
->aux
!= group
)
1326 bb1
= (basic_block
) bb
->aux
;
1327 bb
->aux
= (void *) group
;
1334 union_groups (basic_block bb1
, basic_block bb2
)
1336 basic_block bb1g
= find_group (bb1
);
1337 basic_block bb2g
= find_group (bb2
);
1339 /* ??? I don't have a place for the rank field. OK. Lets go w/o it,
1340 this code is unlikely going to be performance problem anyway. */
1341 gcc_assert (bb1g
!= bb2g
);
1346 /* This function searches all of the edges in the program flow graph, and puts
1347 as many bad edges as possible onto the spanning tree. Bad edges include
1348 abnormals edges, which can't be instrumented at the moment. Since it is
1349 possible for fake edges to form a cycle, we will have to develop some
1350 better way in the future. Also put critical edges to the tree, since they
1351 are more expensive to instrument. */
1354 find_spanning_tree (struct edge_list
*el
)
1357 int num_edges
= NUM_EDGES (el
);
1360 /* We use aux field for standard union-find algorithm. */
1361 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
1364 /* Add fake edge exit to entry we can't instrument. */
1365 union_groups (EXIT_BLOCK_PTR
, ENTRY_BLOCK_PTR
);
1367 /* First add all abnormal edges to the tree unless they form a cycle. Also
1368 add all edges to EXIT_BLOCK_PTR to avoid inserting profiling code behind
1369 setting return value from function. */
1370 for (i
= 0; i
< num_edges
; i
++)
1372 edge e
= INDEX_EDGE (el
, i
);
1373 if (((e
->flags
& (EDGE_ABNORMAL
| EDGE_ABNORMAL_CALL
| EDGE_FAKE
))
1374 || e
->dest
== EXIT_BLOCK_PTR
)
1375 && !EDGE_INFO (e
)->ignore
1376 && (find_group (e
->src
) != find_group (e
->dest
)))
1379 fprintf (dump_file
, "Abnormal edge %d to %d put to tree\n",
1380 e
->src
->index
, e
->dest
->index
);
1381 EDGE_INFO (e
)->on_tree
= 1;
1382 union_groups (e
->src
, e
->dest
);
1386 /* Now insert all critical edges to the tree unless they form a cycle. */
1387 for (i
= 0; i
< num_edges
; i
++)
1389 edge e
= INDEX_EDGE (el
, i
);
1390 if (EDGE_CRITICAL_P (e
) && !EDGE_INFO (e
)->ignore
1391 && find_group (e
->src
) != find_group (e
->dest
))
1394 fprintf (dump_file
, "Critical edge %d to %d put to tree\n",
1395 e
->src
->index
, e
->dest
->index
);
1396 EDGE_INFO (e
)->on_tree
= 1;
1397 union_groups (e
->src
, e
->dest
);
1401 /* And now the rest. */
1402 for (i
= 0; i
< num_edges
; i
++)
1404 edge e
= INDEX_EDGE (el
, i
);
1405 if (!EDGE_INFO (e
)->ignore
1406 && find_group (e
->src
) != find_group (e
->dest
))
1409 fprintf (dump_file
, "Normal edge %d to %d put to tree\n",
1410 e
->src
->index
, e
->dest
->index
);
1411 EDGE_INFO (e
)->on_tree
= 1;
1412 union_groups (e
->src
, e
->dest
);
1416 clear_aux_for_blocks ();
1419 /* Perform file-level initialization for branch-prob processing. */
1422 init_branch_prob (void)
1426 total_num_blocks
= 0;
1427 total_num_edges
= 0;
1428 total_num_edges_ignored
= 0;
1429 total_num_edges_instrumented
= 0;
1430 total_num_blocks_created
= 0;
1431 total_num_passes
= 0;
1432 total_num_times_called
= 0;
1433 total_num_branches
= 0;
1434 for (i
= 0; i
< 20; i
++)
1435 total_hist_br_prob
[i
] = 0;
1438 /* Performs file-level cleanup after branch-prob processing
1442 end_branch_prob (void)
1446 fprintf (dump_file
, "\n");
1447 fprintf (dump_file
, "Total number of blocks: %d\n",
1449 fprintf (dump_file
, "Total number of edges: %d\n", total_num_edges
);
1450 fprintf (dump_file
, "Total number of ignored edges: %d\n",
1451 total_num_edges_ignored
);
1452 fprintf (dump_file
, "Total number of instrumented edges: %d\n",
1453 total_num_edges_instrumented
);
1454 fprintf (dump_file
, "Total number of blocks created: %d\n",
1455 total_num_blocks_created
);
1456 fprintf (dump_file
, "Total number of graph solution passes: %d\n",
1458 if (total_num_times_called
!= 0)
1459 fprintf (dump_file
, "Average number of graph solution passes: %d\n",
1460 (total_num_passes
+ (total_num_times_called
>> 1))
1461 / total_num_times_called
);
1462 fprintf (dump_file
, "Total number of branches: %d\n",
1463 total_num_branches
);
1464 if (total_num_branches
)
1468 for (i
= 0; i
< 10; i
++)
1469 fprintf (dump_file
, "%d%% branches in range %d-%d%%\n",
1470 (total_hist_br_prob
[i
] + total_hist_br_prob
[19-i
]) * 100
1471 / total_num_branches
, 5*i
, 5*i
+5);