re PR tree-optimization/35642 (short * short multiplication not vectorized on Power)
[gcc.git] / gcc / profile.c
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
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.
8
9 This file is part of GCC.
10
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.
15
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.
20
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/>. */
24
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.
41
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. */
45
46 /* ??? Register allocation should use basic block execution counts to
47 give preference to the most commonly executed blocks. */
48
49 /* ??? Should calculate branch probabilities before instrumenting code, since
50 then we can use arc counts to help decide which arcs to instrument. */
51
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 "toplev.h"
63 #include "coverage.h"
64 #include "value-prof.h"
65 #include "tree.h"
66 #include "cfghooks.h"
67 #include "tree-flow.h"
68 #include "timevar.h"
69 #include "cfgloop.h"
70 #include "tree-pass.h"
71
72 #include "profile.h"
73
74 /* Hooks for profiling. */
75 static struct profile_hooks* profile_hooks;
76
77 struct bb_info {
78 unsigned int count_valid : 1;
79
80 /* Number of successor and predecessor edges. */
81 gcov_type succ_count;
82 gcov_type pred_count;
83 };
84
85 #define BB_INFO(b) ((struct bb_info *) (b)->aux)
86
87
88 /* Counter summary from the last set of coverage counts read. */
89
90 const struct gcov_ctr_summary *profile_info;
91
92 /* Collect statistics on the performance of this pass for the entire source
93 file. */
94
95 static int total_num_blocks;
96 static int total_num_edges;
97 static int total_num_edges_ignored;
98 static int total_num_edges_instrumented;
99 static int total_num_blocks_created;
100 static int total_num_passes;
101 static int total_num_times_called;
102 static int total_hist_br_prob[20];
103 static int total_num_never_executed;
104 static int total_num_branches;
105
106 /* Forward declarations. */
107 static void find_spanning_tree (struct edge_list *);
108 static unsigned instrument_edges (struct edge_list *);
109 static void instrument_values (histogram_values);
110 static void compute_branch_probabilities (void);
111 static void compute_value_histograms (histogram_values);
112 static gcov_type * get_exec_counts (void);
113 static basic_block find_group (basic_block);
114 static void union_groups (basic_block, basic_block);
115
116 /* Add edge instrumentation code to the entire insn chain.
117
118 F is the first insn of the chain.
119 NUM_BLOCKS is the number of basic blocks found in F. */
120
121 static unsigned
122 instrument_edges (struct edge_list *el)
123 {
124 unsigned num_instr_edges = 0;
125 int num_edges = NUM_EDGES (el);
126 basic_block bb;
127
128 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
129 {
130 edge e;
131 edge_iterator ei;
132
133 FOR_EACH_EDGE (e, ei, bb->succs)
134 {
135 struct edge_info *inf = EDGE_INFO (e);
136
137 if (!inf->ignore && !inf->on_tree)
138 {
139 gcc_assert (!(e->flags & EDGE_ABNORMAL));
140 if (dump_file)
141 fprintf (dump_file, "Edge %d to %d instrumented%s\n",
142 e->src->index, e->dest->index,
143 EDGE_CRITICAL_P (e) ? " (and split)" : "");
144 (profile_hooks->gen_edge_profiler) (num_instr_edges++, e);
145 }
146 }
147 }
148
149 total_num_blocks_created += num_edges;
150 if (dump_file)
151 fprintf (dump_file, "%d edges instrumented\n", num_instr_edges);
152 return num_instr_edges;
153 }
154
155 /* Add code to measure histograms for values in list VALUES. */
156 static void
157 instrument_values (histogram_values values)
158 {
159 unsigned i, t;
160
161 /* Emit code to generate the histograms before the insns. */
162
163 for (i = 0; i < VEC_length (histogram_value, values); i++)
164 {
165 histogram_value hist = VEC_index (histogram_value, values, i);
166 switch (hist->type)
167 {
168 case HIST_TYPE_INTERVAL:
169 t = GCOV_COUNTER_V_INTERVAL;
170 break;
171
172 case HIST_TYPE_POW2:
173 t = GCOV_COUNTER_V_POW2;
174 break;
175
176 case HIST_TYPE_SINGLE_VALUE:
177 t = GCOV_COUNTER_V_SINGLE;
178 break;
179
180 case HIST_TYPE_CONST_DELTA:
181 t = GCOV_COUNTER_V_DELTA;
182 break;
183
184 case HIST_TYPE_INDIR_CALL:
185 t = GCOV_COUNTER_V_INDIR;
186 break;
187
188 case HIST_TYPE_AVERAGE:
189 t = GCOV_COUNTER_AVERAGE;
190 break;
191
192 case HIST_TYPE_IOR:
193 t = GCOV_COUNTER_IOR;
194 break;
195
196 default:
197 gcc_unreachable ();
198 }
199 if (!coverage_counter_alloc (t, hist->n_counters))
200 continue;
201
202 switch (hist->type)
203 {
204 case HIST_TYPE_INTERVAL:
205 (profile_hooks->gen_interval_profiler) (hist, t, 0);
206 break;
207
208 case HIST_TYPE_POW2:
209 (profile_hooks->gen_pow2_profiler) (hist, t, 0);
210 break;
211
212 case HIST_TYPE_SINGLE_VALUE:
213 (profile_hooks->gen_one_value_profiler) (hist, t, 0);
214 break;
215
216 case HIST_TYPE_CONST_DELTA:
217 (profile_hooks->gen_const_delta_profiler) (hist, t, 0);
218 break;
219
220 case HIST_TYPE_INDIR_CALL:
221 (profile_hooks->gen_ic_profiler) (hist, t, 0);
222 break;
223
224 case HIST_TYPE_AVERAGE:
225 (profile_hooks->gen_average_profiler) (hist, t, 0);
226 break;
227
228 case HIST_TYPE_IOR:
229 (profile_hooks->gen_ior_profiler) (hist, t, 0);
230 break;
231
232 default:
233 gcc_unreachable ();
234 }
235 }
236 }
237 \f
238
239 /* Computes hybrid profile for all matching entries in da_file. */
240
241 static gcov_type *
242 get_exec_counts (void)
243 {
244 unsigned num_edges = 0;
245 basic_block bb;
246 gcov_type *counts;
247
248 /* Count the edges to be (possibly) instrumented. */
249 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
250 {
251 edge e;
252 edge_iterator ei;
253
254 FOR_EACH_EDGE (e, ei, bb->succs)
255 if (!EDGE_INFO (e)->ignore && !EDGE_INFO (e)->on_tree)
256 num_edges++;
257 }
258
259 counts = get_coverage_counts (GCOV_COUNTER_ARCS, num_edges, &profile_info);
260 if (!counts)
261 return NULL;
262
263 if (dump_file && profile_info)
264 fprintf(dump_file, "Merged %u profiles with maximal count %u.\n",
265 profile_info->runs, (unsigned) profile_info->sum_max);
266
267 return counts;
268 }
269
270
271 static bool
272 is_edge_inconsistent (VEC(edge,gc) *edges)
273 {
274 edge e;
275 edge_iterator ei;
276 FOR_EACH_EDGE (e, ei, edges)
277 {
278 if (!EDGE_INFO (e)->ignore)
279 {
280 if (e->count < 0)
281 return true;
282 }
283 }
284 return false;
285 }
286
287 static void
288 correct_negative_edge_counts (void)
289 {
290 basic_block bb;
291 edge e;
292 edge_iterator ei;
293
294 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
295 {
296 FOR_EACH_EDGE (e, ei, bb->succs)
297 {
298 if (e->count < 0)
299 e->count = 0;
300 }
301 }
302 }
303
304 /* Check consistency.
305 Return true if inconsistency is found. */
306 static bool
307 is_inconsistent (void)
308 {
309 basic_block bb;
310 FOR_EACH_BB (bb)
311 {
312 if (is_edge_inconsistent (bb->preds))
313 return true;
314 if (is_edge_inconsistent (bb->succs))
315 return true;
316 if ( bb->count != sum_edge_counts (bb->preds)
317 || (bb->count != sum_edge_counts (bb->succs) &&
318 !(find_edge (bb, EXIT_BLOCK_PTR) != NULL &&
319 block_ends_with_call_p (bb))))
320 return true;
321 }
322
323 return false;
324 }
325
326 /* Set each basic block count to the sum of its outgoing edge counts */
327 static void
328 set_bb_counts (void)
329 {
330 basic_block bb;
331 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
332 {
333 bb->count = sum_edge_counts (bb->succs);
334 gcc_assert (bb->count >= 0);
335 }
336 }
337
338 /* Reads profile data and returns total number of edge counts read */
339 static int
340 read_profile_edge_counts (gcov_type *exec_counts)
341 {
342 basic_block bb;
343 int num_edges = 0;
344 int exec_counts_pos = 0;
345 /* For each edge not on the spanning tree, set its execution count from
346 the .da file. */
347 /* The first count in the .da file is the number of times that the function
348 was entered. This is the exec_count for block zero. */
349
350 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
351 {
352 edge e;
353 edge_iterator ei;
354
355 FOR_EACH_EDGE (e, ei, bb->succs)
356 if (!EDGE_INFO (e)->ignore && !EDGE_INFO (e)->on_tree)
357 {
358 num_edges++;
359 if (exec_counts)
360 {
361 e->count = exec_counts[exec_counts_pos++];
362 if (e->count > profile_info->sum_max)
363 {
364 error ("corrupted profile info: edge from %i to %i exceeds maximal count",
365 bb->index, e->dest->index);
366 }
367 }
368 else
369 e->count = 0;
370
371 EDGE_INFO (e)->count_valid = 1;
372 BB_INFO (bb)->succ_count--;
373 BB_INFO (e->dest)->pred_count--;
374 if (dump_file)
375 {
376 fprintf (dump_file, "\nRead edge from %i to %i, count:",
377 bb->index, e->dest->index);
378 fprintf (dump_file, HOST_WIDEST_INT_PRINT_DEC,
379 (HOST_WIDEST_INT) e->count);
380 }
381 }
382 }
383
384 return num_edges;
385 }
386
387 /* Compute the branch probabilities for the various branches.
388 Annotate them accordingly. */
389
390 static void
391 compute_branch_probabilities (void)
392 {
393 basic_block bb;
394 int i;
395 int num_edges = 0;
396 int changes;
397 int passes;
398 int hist_br_prob[20];
399 int num_never_executed;
400 int num_branches;
401 gcov_type *exec_counts = get_exec_counts ();
402 int inconsistent = 0;
403
404 /* Very simple sanity checks so we catch bugs in our profiling code. */
405 if (!profile_info)
406 return;
407 if (profile_info->run_max * profile_info->runs < profile_info->sum_max)
408 {
409 error ("corrupted profile info: run_max * runs < sum_max");
410 exec_counts = NULL;
411 }
412
413 if (profile_info->sum_all < profile_info->sum_max)
414 {
415 error ("corrupted profile info: sum_all is smaller than sum_max");
416 exec_counts = NULL;
417 }
418
419 /* Attach extra info block to each bb. */
420 alloc_aux_for_blocks (sizeof (struct bb_info));
421 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
422 {
423 edge e;
424 edge_iterator ei;
425
426 FOR_EACH_EDGE (e, ei, bb->succs)
427 if (!EDGE_INFO (e)->ignore)
428 BB_INFO (bb)->succ_count++;
429 FOR_EACH_EDGE (e, ei, bb->preds)
430 if (!EDGE_INFO (e)->ignore)
431 BB_INFO (bb)->pred_count++;
432 }
433
434 /* Avoid predicting entry on exit nodes. */
435 BB_INFO (EXIT_BLOCK_PTR)->succ_count = 2;
436 BB_INFO (ENTRY_BLOCK_PTR)->pred_count = 2;
437
438 num_edges = read_profile_edge_counts (exec_counts);
439
440 if (dump_file)
441 fprintf (dump_file, "\n%d edge counts read\n", num_edges);
442
443 /* For every block in the file,
444 - if every exit/entrance edge has a known count, then set the block count
445 - if the block count is known, and every exit/entrance edge but one has
446 a known execution count, then set the count of the remaining edge
447
448 As edge counts are set, decrement the succ/pred count, but don't delete
449 the edge, that way we can easily tell when all edges are known, or only
450 one edge is unknown. */
451
452 /* The order that the basic blocks are iterated through is important.
453 Since the code that finds spanning trees starts with block 0, low numbered
454 edges are put on the spanning tree in preference to high numbered edges.
455 Hence, most instrumented edges are at the end. Graph solving works much
456 faster if we propagate numbers from the end to the start.
457
458 This takes an average of slightly more than 3 passes. */
459
460 changes = 1;
461 passes = 0;
462 while (changes)
463 {
464 passes++;
465 changes = 0;
466 FOR_BB_BETWEEN (bb, EXIT_BLOCK_PTR, NULL, prev_bb)
467 {
468 struct bb_info *bi = BB_INFO (bb);
469 if (! bi->count_valid)
470 {
471 if (bi->succ_count == 0)
472 {
473 edge e;
474 edge_iterator ei;
475 gcov_type total = 0;
476
477 FOR_EACH_EDGE (e, ei, bb->succs)
478 total += e->count;
479 bb->count = total;
480 bi->count_valid = 1;
481 changes = 1;
482 }
483 else if (bi->pred_count == 0)
484 {
485 edge e;
486 edge_iterator ei;
487 gcov_type total = 0;
488
489 FOR_EACH_EDGE (e, ei, bb->preds)
490 total += e->count;
491 bb->count = total;
492 bi->count_valid = 1;
493 changes = 1;
494 }
495 }
496 if (bi->count_valid)
497 {
498 if (bi->succ_count == 1)
499 {
500 edge e;
501 edge_iterator ei;
502 gcov_type total = 0;
503
504 /* One of the counts will be invalid, but it is zero,
505 so adding it in also doesn't hurt. */
506 FOR_EACH_EDGE (e, ei, bb->succs)
507 total += e->count;
508
509 /* Search for the invalid edge, and set its count. */
510 FOR_EACH_EDGE (e, ei, bb->succs)
511 if (! EDGE_INFO (e)->count_valid && ! EDGE_INFO (e)->ignore)
512 break;
513
514 /* Calculate count for remaining edge by conservation. */
515 total = bb->count - total;
516
517 gcc_assert (e);
518 EDGE_INFO (e)->count_valid = 1;
519 e->count = total;
520 bi->succ_count--;
521
522 BB_INFO (e->dest)->pred_count--;
523 changes = 1;
524 }
525 if (bi->pred_count == 1)
526 {
527 edge e;
528 edge_iterator ei;
529 gcov_type total = 0;
530
531 /* One of the counts will be invalid, but it is zero,
532 so adding it in also doesn't hurt. */
533 FOR_EACH_EDGE (e, ei, bb->preds)
534 total += e->count;
535
536 /* Search for the invalid edge, and set its count. */
537 FOR_EACH_EDGE (e, ei, bb->preds)
538 if (!EDGE_INFO (e)->count_valid && !EDGE_INFO (e)->ignore)
539 break;
540
541 /* Calculate count for remaining edge by conservation. */
542 total = bb->count - total + e->count;
543
544 gcc_assert (e);
545 EDGE_INFO (e)->count_valid = 1;
546 e->count = total;
547 bi->pred_count--;
548
549 BB_INFO (e->src)->succ_count--;
550 changes = 1;
551 }
552 }
553 }
554 }
555 if (dump_file)
556 dump_flow_info (dump_file, dump_flags);
557
558 total_num_passes += passes;
559 if (dump_file)
560 fprintf (dump_file, "Graph solving took %d passes.\n\n", passes);
561
562 /* If the graph has been correctly solved, every block will have a
563 succ and pred count of zero. */
564 FOR_EACH_BB (bb)
565 {
566 gcc_assert (!BB_INFO (bb)->succ_count && !BB_INFO (bb)->pred_count);
567 }
568
569 /* Check for inconsistent basic block counts */
570 inconsistent = is_inconsistent ();
571
572 if (inconsistent)
573 {
574 if (flag_profile_correction)
575 {
576 /* Inconsistency detected. Make it flow-consistent. */
577 static int informed = 0;
578 if (informed == 0)
579 {
580 informed = 1;
581 inform (input_location, "correcting inconsistent profile data");
582 }
583 correct_negative_edge_counts ();
584 /* Set bb counts to the sum of the outgoing edge counts */
585 set_bb_counts ();
586 if (dump_file)
587 fprintf (dump_file, "\nCalling mcf_smooth_cfg\n");
588 mcf_smooth_cfg ();
589 }
590 else
591 error ("corrupted profile info: profile data is not flow-consistent");
592 }
593
594 /* For every edge, calculate its branch probability and add a reg_note
595 to the branch insn to indicate this. */
596
597 for (i = 0; i < 20; i++)
598 hist_br_prob[i] = 0;
599 num_never_executed = 0;
600 num_branches = 0;
601
602 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
603 {
604 edge e;
605 edge_iterator ei;
606
607 if (bb->count < 0)
608 {
609 error ("corrupted profile info: number of iterations for basic block %d thought to be %i",
610 bb->index, (int)bb->count);
611 bb->count = 0;
612 }
613 FOR_EACH_EDGE (e, ei, bb->succs)
614 {
615 /* Function may return twice in the cased the called function is
616 setjmp or calls fork, but we can't represent this by extra
617 edge from the entry, since extra edge from the exit is
618 already present. We get negative frequency from the entry
619 point. */
620 if ((e->count < 0
621 && e->dest == EXIT_BLOCK_PTR)
622 || (e->count > bb->count
623 && e->dest != EXIT_BLOCK_PTR))
624 {
625 if (block_ends_with_call_p (bb))
626 e->count = e->count < 0 ? 0 : bb->count;
627 }
628 if (e->count < 0 || e->count > bb->count)
629 {
630 error ("corrupted profile info: number of executions for edge %d-%d thought to be %i",
631 e->src->index, e->dest->index,
632 (int)e->count);
633 e->count = bb->count / 2;
634 }
635 }
636 if (bb->count)
637 {
638 FOR_EACH_EDGE (e, ei, bb->succs)
639 e->probability = (e->count * REG_BR_PROB_BASE + bb->count / 2) / bb->count;
640 if (bb->index >= NUM_FIXED_BLOCKS
641 && block_ends_with_condjump_p (bb)
642 && EDGE_COUNT (bb->succs) >= 2)
643 {
644 int prob;
645 edge e;
646 int index;
647
648 /* Find the branch edge. It is possible that we do have fake
649 edges here. */
650 FOR_EACH_EDGE (e, ei, bb->succs)
651 if (!(e->flags & (EDGE_FAKE | EDGE_FALLTHRU)))
652 break;
653
654 prob = e->probability;
655 index = prob * 20 / REG_BR_PROB_BASE;
656
657 if (index == 20)
658 index = 19;
659 hist_br_prob[index]++;
660
661 num_branches++;
662 }
663 }
664 /* As a last resort, distribute the probabilities evenly.
665 Use simple heuristics that if there are normal edges,
666 give all abnormals frequency of 0, otherwise distribute the
667 frequency over abnormals (this is the case of noreturn
668 calls). */
669 else if (profile_status == PROFILE_ABSENT)
670 {
671 int total = 0;
672
673 FOR_EACH_EDGE (e, ei, bb->succs)
674 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
675 total ++;
676 if (total)
677 {
678 FOR_EACH_EDGE (e, ei, bb->succs)
679 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
680 e->probability = REG_BR_PROB_BASE / total;
681 else
682 e->probability = 0;
683 }
684 else
685 {
686 total += EDGE_COUNT (bb->succs);
687 FOR_EACH_EDGE (e, ei, bb->succs)
688 e->probability = REG_BR_PROB_BASE / total;
689 }
690 if (bb->index >= NUM_FIXED_BLOCKS
691 && block_ends_with_condjump_p (bb)
692 && EDGE_COUNT (bb->succs) >= 2)
693 num_branches++, num_never_executed;
694 }
695 }
696 counts_to_freqs ();
697 profile_status = PROFILE_READ;
698
699 if (dump_file)
700 {
701 fprintf (dump_file, "%d branches\n", num_branches);
702 fprintf (dump_file, "%d branches never executed\n",
703 num_never_executed);
704 if (num_branches)
705 for (i = 0; i < 10; i++)
706 fprintf (dump_file, "%d%% branches in range %d-%d%%\n",
707 (hist_br_prob[i] + hist_br_prob[19-i]) * 100 / num_branches,
708 5 * i, 5 * i + 5);
709
710 total_num_branches += num_branches;
711 total_num_never_executed += num_never_executed;
712 for (i = 0; i < 20; i++)
713 total_hist_br_prob[i] += hist_br_prob[i];
714
715 fputc ('\n', dump_file);
716 fputc ('\n', dump_file);
717 }
718
719 free_aux_for_blocks ();
720 }
721
722 /* Load value histograms values whose description is stored in VALUES array
723 from .gcda file. */
724
725 static void
726 compute_value_histograms (histogram_values values)
727 {
728 unsigned i, j, t, any;
729 unsigned n_histogram_counters[GCOV_N_VALUE_COUNTERS];
730 gcov_type *histogram_counts[GCOV_N_VALUE_COUNTERS];
731 gcov_type *act_count[GCOV_N_VALUE_COUNTERS];
732 gcov_type *aact_count;
733
734 for (t = 0; t < GCOV_N_VALUE_COUNTERS; t++)
735 n_histogram_counters[t] = 0;
736
737 for (i = 0; i < VEC_length (histogram_value, values); i++)
738 {
739 histogram_value hist = VEC_index (histogram_value, values, i);
740 n_histogram_counters[(int) hist->type] += hist->n_counters;
741 }
742
743 any = 0;
744 for (t = 0; t < GCOV_N_VALUE_COUNTERS; t++)
745 {
746 if (!n_histogram_counters[t])
747 {
748 histogram_counts[t] = NULL;
749 continue;
750 }
751
752 histogram_counts[t] =
753 get_coverage_counts (COUNTER_FOR_HIST_TYPE (t),
754 n_histogram_counters[t], NULL);
755 if (histogram_counts[t])
756 any = 1;
757 act_count[t] = histogram_counts[t];
758 }
759 if (!any)
760 return;
761
762 for (i = 0; i < VEC_length (histogram_value, values); i++)
763 {
764 histogram_value hist = VEC_index (histogram_value, values, i);
765 gimple stmt = hist->hvalue.stmt;
766
767 t = (int) hist->type;
768
769 aact_count = act_count[t];
770 act_count[t] += hist->n_counters;
771
772 gimple_add_histogram_value (cfun, stmt, hist);
773 hist->hvalue.counters = XNEWVEC (gcov_type, hist->n_counters);
774 for (j = 0; j < hist->n_counters; j++)
775 hist->hvalue.counters[j] = aact_count[j];
776 }
777
778 for (t = 0; t < GCOV_N_VALUE_COUNTERS; t++)
779 if (histogram_counts[t])
780 free (histogram_counts[t]);
781 }
782
783 /* The entry basic block will be moved around so that it has index=1,
784 there is nothing at index 0 and the exit is at n_basic_block. */
785 #define BB_TO_GCOV_INDEX(bb) ((bb)->index - 1)
786 /* When passed NULL as file_name, initialize.
787 When passed something else, output the necessary commands to change
788 line to LINE and offset to FILE_NAME. */
789 static void
790 output_location (char const *file_name, int line,
791 gcov_position_t *offset, basic_block bb)
792 {
793 static char const *prev_file_name;
794 static int prev_line;
795 bool name_differs, line_differs;
796
797 if (!file_name)
798 {
799 prev_file_name = NULL;
800 prev_line = -1;
801 return;
802 }
803
804 name_differs = !prev_file_name || strcmp (file_name, prev_file_name);
805 line_differs = prev_line != line;
806
807 if (name_differs || line_differs)
808 {
809 if (!*offset)
810 {
811 *offset = gcov_write_tag (GCOV_TAG_LINES);
812 gcov_write_unsigned (BB_TO_GCOV_INDEX (bb));
813 name_differs = line_differs=true;
814 }
815
816 /* If this is a new source file, then output the
817 file's name to the .bb file. */
818 if (name_differs)
819 {
820 prev_file_name = file_name;
821 gcov_write_unsigned (0);
822 gcov_write_string (prev_file_name);
823 }
824 if (line_differs)
825 {
826 gcov_write_unsigned (line);
827 prev_line = line;
828 }
829 }
830 }
831
832 /* Instrument and/or analyze program behavior based on program flow graph.
833 In either case, this function builds a flow graph for the function being
834 compiled. The flow graph is stored in BB_GRAPH.
835
836 When FLAG_PROFILE_ARCS is nonzero, this function instruments the edges in
837 the flow graph that are needed to reconstruct the dynamic behavior of the
838 flow graph.
839
840 When FLAG_BRANCH_PROBABILITIES is nonzero, this function reads auxiliary
841 information from a data file containing edge count information from previous
842 executions of the function being compiled. In this case, the flow graph is
843 annotated with actual execution counts, which are later propagated into the
844 rtl for optimization purposes.
845
846 Main entry point of this file. */
847
848 void
849 branch_prob (void)
850 {
851 basic_block bb;
852 unsigned i;
853 unsigned num_edges, ignored_edges;
854 unsigned num_instrumented;
855 struct edge_list *el;
856 histogram_values values = NULL;
857
858 total_num_times_called++;
859
860 flow_call_edges_add (NULL);
861 add_noreturn_fake_exit_edges ();
862
863 /* We can't handle cyclic regions constructed using abnormal edges.
864 To avoid these we replace every source of abnormal edge by a fake
865 edge from entry node and every destination by fake edge to exit.
866 This keeps graph acyclic and our calculation exact for all normal
867 edges except for exit and entrance ones.
868
869 We also add fake exit edges for each call and asm statement in the
870 basic, since it may not return. */
871
872 FOR_EACH_BB (bb)
873 {
874 int need_exit_edge = 0, need_entry_edge = 0;
875 int have_exit_edge = 0, have_entry_edge = 0;
876 edge e;
877 edge_iterator ei;
878
879 /* Functions returning multiple times are not handled by extra edges.
880 Instead we simply allow negative counts on edges from exit to the
881 block past call and corresponding probabilities. We can't go
882 with the extra edges because that would result in flowgraph that
883 needs to have fake edges outside the spanning tree. */
884
885 FOR_EACH_EDGE (e, ei, bb->succs)
886 {
887 gimple_stmt_iterator gsi;
888 gimple last = NULL;
889
890 /* It may happen that there are compiler generated statements
891 without a locus at all. Go through the basic block from the
892 last to the first statement looking for a locus. */
893 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
894 {
895 last = gsi_stmt (gsi);
896 if (gimple_has_location (last))
897 break;
898 }
899
900 /* Edge with goto locus might get wrong coverage info unless
901 it is the only edge out of BB.
902 Don't do that when the locuses match, so
903 if (blah) goto something;
904 is not computed twice. */
905 if (last
906 && gimple_has_location (last)
907 && e->goto_locus != UNKNOWN_LOCATION
908 && !single_succ_p (bb)
909 && (LOCATION_FILE (e->goto_locus)
910 != LOCATION_FILE (gimple_location (last))
911 || (LOCATION_LINE (e->goto_locus)
912 != LOCATION_LINE (gimple_location (last)))))
913 {
914 basic_block new_bb = split_edge (e);
915 single_succ_edge (new_bb)->goto_locus = e->goto_locus;
916 }
917 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
918 && e->dest != EXIT_BLOCK_PTR)
919 need_exit_edge = 1;
920 if (e->dest == EXIT_BLOCK_PTR)
921 have_exit_edge = 1;
922 }
923 FOR_EACH_EDGE (e, ei, bb->preds)
924 {
925 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
926 && e->src != ENTRY_BLOCK_PTR)
927 need_entry_edge = 1;
928 if (e->src == ENTRY_BLOCK_PTR)
929 have_entry_edge = 1;
930 }
931
932 if (need_exit_edge && !have_exit_edge)
933 {
934 if (dump_file)
935 fprintf (dump_file, "Adding fake exit edge to bb %i\n",
936 bb->index);
937 make_edge (bb, EXIT_BLOCK_PTR, EDGE_FAKE);
938 }
939 if (need_entry_edge && !have_entry_edge)
940 {
941 if (dump_file)
942 fprintf (dump_file, "Adding fake entry edge to bb %i\n",
943 bb->index);
944 make_edge (ENTRY_BLOCK_PTR, bb, EDGE_FAKE);
945 }
946 }
947
948 el = create_edge_list ();
949 num_edges = NUM_EDGES (el);
950 alloc_aux_for_edges (sizeof (struct edge_info));
951
952 /* The basic blocks are expected to be numbered sequentially. */
953 compact_blocks ();
954
955 ignored_edges = 0;
956 for (i = 0 ; i < num_edges ; i++)
957 {
958 edge e = INDEX_EDGE (el, i);
959 e->count = 0;
960
961 /* Mark edges we've replaced by fake edges above as ignored. */
962 if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
963 && e->src != ENTRY_BLOCK_PTR && e->dest != EXIT_BLOCK_PTR)
964 {
965 EDGE_INFO (e)->ignore = 1;
966 ignored_edges++;
967 }
968 }
969
970 /* Create spanning tree from basic block graph, mark each edge that is
971 on the spanning tree. We insert as many abnormal and critical edges
972 as possible to minimize number of edge splits necessary. */
973
974 find_spanning_tree (el);
975
976 /* Fake edges that are not on the tree will not be instrumented, so
977 mark them ignored. */
978 for (num_instrumented = i = 0; i < num_edges; i++)
979 {
980 edge e = INDEX_EDGE (el, i);
981 struct edge_info *inf = EDGE_INFO (e);
982
983 if (inf->ignore || inf->on_tree)
984 /*NOP*/;
985 else if (e->flags & EDGE_FAKE)
986 {
987 inf->ignore = 1;
988 ignored_edges++;
989 }
990 else
991 num_instrumented++;
992 }
993
994 total_num_blocks += n_basic_blocks;
995 if (dump_file)
996 fprintf (dump_file, "%d basic blocks\n", n_basic_blocks);
997
998 total_num_edges += num_edges;
999 if (dump_file)
1000 fprintf (dump_file, "%d edges\n", num_edges);
1001
1002 total_num_edges_ignored += ignored_edges;
1003 if (dump_file)
1004 fprintf (dump_file, "%d ignored edges\n", ignored_edges);
1005
1006 /* Write the data from which gcov can reconstruct the basic block
1007 graph. */
1008
1009 /* Basic block flags */
1010 if (coverage_begin_output ())
1011 {
1012 gcov_position_t offset;
1013
1014 offset = gcov_write_tag (GCOV_TAG_BLOCKS);
1015 for (i = 0; i != (unsigned) (n_basic_blocks); i++)
1016 gcov_write_unsigned (0);
1017 gcov_write_length (offset);
1018 }
1019
1020 /* Keep all basic block indexes nonnegative in the gcov output.
1021 Index 0 is used for entry block, last index is for exit block.
1022 */
1023 ENTRY_BLOCK_PTR->index = 1;
1024 EXIT_BLOCK_PTR->index = last_basic_block;
1025
1026 /* Arcs */
1027 if (coverage_begin_output ())
1028 {
1029 gcov_position_t offset;
1030
1031 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
1032 {
1033 edge e;
1034 edge_iterator ei;
1035
1036 offset = gcov_write_tag (GCOV_TAG_ARCS);
1037 gcov_write_unsigned (BB_TO_GCOV_INDEX (bb));
1038
1039 FOR_EACH_EDGE (e, ei, bb->succs)
1040 {
1041 struct edge_info *i = EDGE_INFO (e);
1042 if (!i->ignore)
1043 {
1044 unsigned flag_bits = 0;
1045
1046 if (i->on_tree)
1047 flag_bits |= GCOV_ARC_ON_TREE;
1048 if (e->flags & EDGE_FAKE)
1049 flag_bits |= GCOV_ARC_FAKE;
1050 if (e->flags & EDGE_FALLTHRU)
1051 flag_bits |= GCOV_ARC_FALLTHROUGH;
1052 /* On trees we don't have fallthru flags, but we can
1053 recompute them from CFG shape. */
1054 if (e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)
1055 && e->src->next_bb == e->dest)
1056 flag_bits |= GCOV_ARC_FALLTHROUGH;
1057
1058 gcov_write_unsigned (BB_TO_GCOV_INDEX (e->dest));
1059 gcov_write_unsigned (flag_bits);
1060 }
1061 }
1062
1063 gcov_write_length (offset);
1064 }
1065 }
1066
1067 /* Line numbers. */
1068 if (coverage_begin_output ())
1069 {
1070 gcov_position_t offset;
1071
1072 /* Initialize the output. */
1073 output_location (NULL, 0, NULL, NULL);
1074
1075 FOR_EACH_BB (bb)
1076 {
1077 gimple_stmt_iterator gsi;
1078
1079 offset = 0;
1080
1081 if (bb == ENTRY_BLOCK_PTR->next_bb)
1082 {
1083 expanded_location curr_location =
1084 expand_location (DECL_SOURCE_LOCATION (current_function_decl));
1085 output_location (curr_location.file, curr_location.line,
1086 &offset, bb);
1087 }
1088
1089 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1090 {
1091 gimple stmt = gsi_stmt (gsi);
1092 if (gimple_has_location (stmt))
1093 output_location (gimple_filename (stmt), gimple_lineno (stmt),
1094 &offset, bb);
1095 }
1096
1097 /* Notice GOTO expressions we eliminated while constructing the
1098 CFG. */
1099 if (single_succ_p (bb)
1100 && single_succ_edge (bb)->goto_locus != UNKNOWN_LOCATION)
1101 {
1102 location_t curr_location = single_succ_edge (bb)->goto_locus;
1103 /* ??? The FILE/LINE API is inconsistent for these cases. */
1104 output_location (LOCATION_FILE (curr_location),
1105 LOCATION_LINE (curr_location), &offset, bb);
1106 }
1107
1108 if (offset)
1109 {
1110 /* A file of NULL indicates the end of run. */
1111 gcov_write_unsigned (0);
1112 gcov_write_string (NULL);
1113 gcov_write_length (offset);
1114 }
1115 }
1116 }
1117
1118 ENTRY_BLOCK_PTR->index = ENTRY_BLOCK;
1119 EXIT_BLOCK_PTR->index = EXIT_BLOCK;
1120 #undef BB_TO_GCOV_INDEX
1121
1122 if (flag_profile_values)
1123 find_values_to_profile (&values);
1124
1125 if (flag_branch_probabilities)
1126 {
1127 compute_branch_probabilities ();
1128 if (flag_profile_values)
1129 compute_value_histograms (values);
1130 }
1131
1132 remove_fake_edges ();
1133
1134 /* For each edge not on the spanning tree, add counting code. */
1135 if (profile_arc_flag
1136 && coverage_counter_alloc (GCOV_COUNTER_ARCS, num_instrumented))
1137 {
1138 unsigned n_instrumented;
1139
1140 profile_hooks->init_edge_profiler ();
1141
1142 n_instrumented = instrument_edges (el);
1143
1144 gcc_assert (n_instrumented == num_instrumented);
1145
1146 if (flag_profile_values)
1147 instrument_values (values);
1148
1149 /* Commit changes done by instrumentation. */
1150 gsi_commit_edge_inserts ();
1151 }
1152
1153 free_aux_for_edges ();
1154
1155 VEC_free (histogram_value, heap, values);
1156 free_edge_list (el);
1157 coverage_end_function ();
1158 }
1159 \f
1160 /* Union find algorithm implementation for the basic blocks using
1161 aux fields. */
1162
1163 static basic_block
1164 find_group (basic_block bb)
1165 {
1166 basic_block group = bb, bb1;
1167
1168 while ((basic_block) group->aux != group)
1169 group = (basic_block) group->aux;
1170
1171 /* Compress path. */
1172 while ((basic_block) bb->aux != group)
1173 {
1174 bb1 = (basic_block) bb->aux;
1175 bb->aux = (void *) group;
1176 bb = bb1;
1177 }
1178 return group;
1179 }
1180
1181 static void
1182 union_groups (basic_block bb1, basic_block bb2)
1183 {
1184 basic_block bb1g = find_group (bb1);
1185 basic_block bb2g = find_group (bb2);
1186
1187 /* ??? I don't have a place for the rank field. OK. Lets go w/o it,
1188 this code is unlikely going to be performance problem anyway. */
1189 gcc_assert (bb1g != bb2g);
1190
1191 bb1g->aux = bb2g;
1192 }
1193 \f
1194 /* This function searches all of the edges in the program flow graph, and puts
1195 as many bad edges as possible onto the spanning tree. Bad edges include
1196 abnormals edges, which can't be instrumented at the moment. Since it is
1197 possible for fake edges to form a cycle, we will have to develop some
1198 better way in the future. Also put critical edges to the tree, since they
1199 are more expensive to instrument. */
1200
1201 static void
1202 find_spanning_tree (struct edge_list *el)
1203 {
1204 int i;
1205 int num_edges = NUM_EDGES (el);
1206 basic_block bb;
1207
1208 /* We use aux field for standard union-find algorithm. */
1209 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1210 bb->aux = bb;
1211
1212 /* Add fake edge exit to entry we can't instrument. */
1213 union_groups (EXIT_BLOCK_PTR, ENTRY_BLOCK_PTR);
1214
1215 /* First add all abnormal edges to the tree unless they form a cycle. Also
1216 add all edges to EXIT_BLOCK_PTR to avoid inserting profiling code behind
1217 setting return value from function. */
1218 for (i = 0; i < num_edges; i++)
1219 {
1220 edge e = INDEX_EDGE (el, i);
1221 if (((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL | EDGE_FAKE))
1222 || e->dest == EXIT_BLOCK_PTR)
1223 && !EDGE_INFO (e)->ignore
1224 && (find_group (e->src) != find_group (e->dest)))
1225 {
1226 if (dump_file)
1227 fprintf (dump_file, "Abnormal edge %d to %d put to tree\n",
1228 e->src->index, e->dest->index);
1229 EDGE_INFO (e)->on_tree = 1;
1230 union_groups (e->src, e->dest);
1231 }
1232 }
1233
1234 /* Now insert all critical edges to the tree unless they form a cycle. */
1235 for (i = 0; i < num_edges; i++)
1236 {
1237 edge e = INDEX_EDGE (el, i);
1238 if (EDGE_CRITICAL_P (e) && !EDGE_INFO (e)->ignore
1239 && find_group (e->src) != find_group (e->dest))
1240 {
1241 if (dump_file)
1242 fprintf (dump_file, "Critical edge %d to %d put to tree\n",
1243 e->src->index, e->dest->index);
1244 EDGE_INFO (e)->on_tree = 1;
1245 union_groups (e->src, e->dest);
1246 }
1247 }
1248
1249 /* And now the rest. */
1250 for (i = 0; i < num_edges; i++)
1251 {
1252 edge e = INDEX_EDGE (el, i);
1253 if (!EDGE_INFO (e)->ignore
1254 && find_group (e->src) != find_group (e->dest))
1255 {
1256 if (dump_file)
1257 fprintf (dump_file, "Normal edge %d to %d put to tree\n",
1258 e->src->index, e->dest->index);
1259 EDGE_INFO (e)->on_tree = 1;
1260 union_groups (e->src, e->dest);
1261 }
1262 }
1263
1264 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1265 bb->aux = NULL;
1266 }
1267 \f
1268 /* Perform file-level initialization for branch-prob processing. */
1269
1270 void
1271 init_branch_prob (void)
1272 {
1273 int i;
1274
1275 total_num_blocks = 0;
1276 total_num_edges = 0;
1277 total_num_edges_ignored = 0;
1278 total_num_edges_instrumented = 0;
1279 total_num_blocks_created = 0;
1280 total_num_passes = 0;
1281 total_num_times_called = 0;
1282 total_num_branches = 0;
1283 total_num_never_executed = 0;
1284 for (i = 0; i < 20; i++)
1285 total_hist_br_prob[i] = 0;
1286 }
1287
1288 /* Performs file-level cleanup after branch-prob processing
1289 is completed. */
1290
1291 void
1292 end_branch_prob (void)
1293 {
1294 if (dump_file)
1295 {
1296 fprintf (dump_file, "\n");
1297 fprintf (dump_file, "Total number of blocks: %d\n",
1298 total_num_blocks);
1299 fprintf (dump_file, "Total number of edges: %d\n", total_num_edges);
1300 fprintf (dump_file, "Total number of ignored edges: %d\n",
1301 total_num_edges_ignored);
1302 fprintf (dump_file, "Total number of instrumented edges: %d\n",
1303 total_num_edges_instrumented);
1304 fprintf (dump_file, "Total number of blocks created: %d\n",
1305 total_num_blocks_created);
1306 fprintf (dump_file, "Total number of graph solution passes: %d\n",
1307 total_num_passes);
1308 if (total_num_times_called != 0)
1309 fprintf (dump_file, "Average number of graph solution passes: %d\n",
1310 (total_num_passes + (total_num_times_called >> 1))
1311 / total_num_times_called);
1312 fprintf (dump_file, "Total number of branches: %d\n",
1313 total_num_branches);
1314 fprintf (dump_file, "Total number of branches never executed: %d\n",
1315 total_num_never_executed);
1316 if (total_num_branches)
1317 {
1318 int i;
1319
1320 for (i = 0; i < 10; i++)
1321 fprintf (dump_file, "%d%% branches in range %d-%d%%\n",
1322 (total_hist_br_prob[i] + total_hist_br_prob[19-i]) * 100
1323 / total_num_branches, 5*i, 5*i+5);
1324 }
1325 }
1326 }
1327
1328 /* Set up hooks to enable tree-based profiling. */
1329
1330 void
1331 tree_register_profile_hooks (void)
1332 {
1333 gcc_assert (current_ir_type () == IR_GIMPLE);
1334 profile_hooks = &tree_profile_hooks;
1335 }