config/
[official-gcc.git] / gcc / predict.c
blob7eaee34d2eb209faa9b862a0de40742da8f056d0
1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING. If not, write to the Free
18 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA. */
21 /* References:
23 [1] "Branch Prediction for Free"
24 Ball and Larus; PLDI '93.
25 [2] "Static Branch Frequency and Program Profile Analysis"
26 Wu and Larus; MICRO-27.
27 [3] "Corpus-based Static Branch Prediction"
28 Calder, Grunwald, Lindsay, Martin, Mozer, and Zorn; PLDI '95. */
31 #include "config.h"
32 #include "system.h"
33 #include "coretypes.h"
34 #include "tm.h"
35 #include "tree.h"
36 #include "rtl.h"
37 #include "tm_p.h"
38 #include "hard-reg-set.h"
39 #include "basic-block.h"
40 #include "insn-config.h"
41 #include "regs.h"
42 #include "flags.h"
43 #include "output.h"
44 #include "function.h"
45 #include "except.h"
46 #include "toplev.h"
47 #include "recog.h"
48 #include "expr.h"
49 #include "predict.h"
50 #include "coverage.h"
51 #include "sreal.h"
52 #include "params.h"
53 #include "target.h"
54 #include "cfgloop.h"
55 #include "tree-flow.h"
56 #include "ggc.h"
57 #include "tree-dump.h"
58 #include "tree-pass.h"
59 #include "timevar.h"
60 #include "tree-scalar-evolution.h"
61 #include "cfgloop.h"
63 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
64 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
65 static sreal real_zero, real_one, real_almost_one, real_br_prob_base,
66 real_inv_br_prob_base, real_one_half, real_bb_freq_max;
68 /* Random guesstimation given names. */
69 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 10 - 1)
70 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
71 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
72 #define PROB_ALWAYS (REG_BR_PROB_BASE)
74 static void combine_predictions_for_insn (rtx, basic_block);
75 static void dump_prediction (FILE *, enum br_predictor, int, basic_block, int);
76 static void estimate_loops_at_level (struct loop *loop);
77 static void propagate_freq (struct loop *);
78 static void estimate_bb_frequencies (struct loops *);
79 static int counts_to_freqs (void);
80 static void predict_paths_leading_to (basic_block, int *, enum br_predictor, enum prediction);
81 static bool last_basic_block_p (basic_block);
82 static void compute_function_frequency (void);
83 static void choose_function_section (void);
84 static bool can_predict_insn_p (rtx);
86 /* Information we hold about each branch predictor.
87 Filled using information from predict.def. */
89 struct predictor_info
91 const char *const name; /* Name used in the debugging dumps. */
92 const int hitrate; /* Expected hitrate used by
93 predict_insn_def call. */
94 const int flags;
97 /* Use given predictor without Dempster-Shaffer theory if it matches
98 using first_match heuristics. */
99 #define PRED_FLAG_FIRST_MATCH 1
101 /* Recompute hitrate in percent to our representation. */
103 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
105 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
106 static const struct predictor_info predictor_info[]= {
107 #include "predict.def"
109 /* Upper bound on predictors. */
110 {NULL, 0, 0}
112 #undef DEF_PREDICTOR
114 /* Return true in case BB can be CPU intensive and should be optimized
115 for maximal performance. */
117 bool
118 maybe_hot_bb_p (basic_block bb)
120 if (profile_info && flag_branch_probabilities
121 && (bb->count
122 < profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
123 return false;
124 if (bb->frequency < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
125 return false;
126 return true;
129 /* Return true in case BB is cold and should be optimized for size. */
131 bool
132 probably_cold_bb_p (basic_block bb)
134 if (profile_info && flag_branch_probabilities
135 && (bb->count
136 < profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
137 return true;
138 if (bb->frequency < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
139 return true;
140 return false;
143 /* Return true in case BB is probably never executed. */
144 bool
145 probably_never_executed_bb_p (basic_block bb)
147 if (profile_info && flag_branch_probabilities)
148 return ((bb->count + profile_info->runs / 2) / profile_info->runs) == 0;
149 return false;
152 /* Return true if the one of outgoing edges is already predicted by
153 PREDICTOR. */
155 bool
156 rtl_predicted_by_p (basic_block bb, enum br_predictor predictor)
158 rtx note;
159 if (!INSN_P (BB_END (bb)))
160 return false;
161 for (note = REG_NOTES (BB_END (bb)); note; note = XEXP (note, 1))
162 if (REG_NOTE_KIND (note) == REG_BR_PRED
163 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
164 return true;
165 return false;
168 /* Return true if the one of outgoing edges is already predicted by
169 PREDICTOR. */
171 bool
172 tree_predicted_by_p (basic_block bb, enum br_predictor predictor)
174 struct edge_prediction *i = bb_ann (bb)->predictions;
175 for (i = bb_ann (bb)->predictions; i; i = i->next)
176 if (i->predictor == predictor)
177 return true;
178 return false;
181 void
182 predict_insn (rtx insn, enum br_predictor predictor, int probability)
184 if (!any_condjump_p (insn))
185 abort ();
186 if (!flag_guess_branch_prob)
187 return;
189 REG_NOTES (insn)
190 = gen_rtx_EXPR_LIST (REG_BR_PRED,
191 gen_rtx_CONCAT (VOIDmode,
192 GEN_INT ((int) predictor),
193 GEN_INT ((int) probability)),
194 REG_NOTES (insn));
197 /* Predict insn by given predictor. */
199 void
200 predict_insn_def (rtx insn, enum br_predictor predictor,
201 enum prediction taken)
203 int probability = predictor_info[(int) predictor].hitrate;
205 if (taken != TAKEN)
206 probability = REG_BR_PROB_BASE - probability;
208 predict_insn (insn, predictor, probability);
211 /* Predict edge E with given probability if possible. */
213 void
214 rtl_predict_edge (edge e, enum br_predictor predictor, int probability)
216 rtx last_insn;
217 last_insn = BB_END (e->src);
219 /* We can store the branch prediction information only about
220 conditional jumps. */
221 if (!any_condjump_p (last_insn))
222 return;
224 /* We always store probability of branching. */
225 if (e->flags & EDGE_FALLTHRU)
226 probability = REG_BR_PROB_BASE - probability;
228 predict_insn (last_insn, predictor, probability);
231 /* Predict edge E with the given PROBABILITY. */
232 void
233 tree_predict_edge (edge e, enum br_predictor predictor, int probability)
235 struct edge_prediction *i = ggc_alloc (sizeof (struct edge_prediction));
237 i->next = bb_ann (e->src)->predictions;
238 bb_ann (e->src)->predictions = i;
239 i->probability = probability;
240 i->predictor = predictor;
241 i->edge = e;
244 /* Return true when we can store prediction on insn INSN.
245 At the moment we represent predictions only on conditional
246 jumps, not at computed jump or other complicated cases. */
247 static bool
248 can_predict_insn_p (rtx insn)
250 return (JUMP_P (insn)
251 && any_condjump_p (insn)
252 && BLOCK_FOR_INSN (insn)->succ->succ_next);
255 /* Predict edge E by given predictor if possible. */
257 void
258 predict_edge_def (edge e, enum br_predictor predictor,
259 enum prediction taken)
261 int probability = predictor_info[(int) predictor].hitrate;
263 if (taken != TAKEN)
264 probability = REG_BR_PROB_BASE - probability;
266 predict_edge (e, predictor, probability);
269 /* Invert all branch predictions or probability notes in the INSN. This needs
270 to be done each time we invert the condition used by the jump. */
272 void
273 invert_br_probabilities (rtx insn)
275 rtx note;
277 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
278 if (REG_NOTE_KIND (note) == REG_BR_PROB)
279 XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
280 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
281 XEXP (XEXP (note, 0), 1)
282 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
285 /* Dump information about the branch prediction to the output file. */
287 static void
288 dump_prediction (FILE *file, enum br_predictor predictor, int probability,
289 basic_block bb, int used)
291 edge e = bb->succ;
293 if (!file)
294 return;
296 while (e && (e->flags & EDGE_FALLTHRU))
297 e = e->succ_next;
299 fprintf (file, " %s heuristics%s: %.1f%%",
300 predictor_info[predictor].name,
301 used ? "" : " (ignored)", probability * 100.0 / REG_BR_PROB_BASE);
303 if (bb->count)
305 fprintf (file, " exec ");
306 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, bb->count);
307 if (e)
309 fprintf (file, " hit ");
310 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, e->count);
311 fprintf (file, " (%.1f%%)", e->count * 100.0 / bb->count);
315 fprintf (file, "\n");
318 /* We can not predict the probabilities of outgoing edges of bb. Set them
319 evenly and hope for the best. */
320 static void
321 set_even_probabilities (basic_block bb)
323 int nedges = 0;
324 edge e;
326 for (e = bb->succ; e; e = e->succ_next)
327 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
328 nedges ++;
329 for (e = bb->succ; e; e = e->succ_next)
330 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
331 e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
332 else
333 e->probability = 0;
336 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
337 note if not already present. Remove now useless REG_BR_PRED notes. */
339 static void
340 combine_predictions_for_insn (rtx insn, basic_block bb)
342 rtx prob_note;
343 rtx *pnote;
344 rtx note;
345 int best_probability = PROB_EVEN;
346 int best_predictor = END_PREDICTORS;
347 int combined_probability = REG_BR_PROB_BASE / 2;
348 int d;
349 bool first_match = false;
350 bool found = false;
352 if (!can_predict_insn_p (insn))
354 set_even_probabilities (bb);
355 return;
358 prob_note = find_reg_note (insn, REG_BR_PROB, 0);
359 pnote = &REG_NOTES (insn);
360 if (dump_file)
361 fprintf (dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
362 bb->index);
364 /* We implement "first match" heuristics and use probability guessed
365 by predictor with smallest index. */
366 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
367 if (REG_NOTE_KIND (note) == REG_BR_PRED)
369 int predictor = INTVAL (XEXP (XEXP (note, 0), 0));
370 int probability = INTVAL (XEXP (XEXP (note, 0), 1));
372 found = true;
373 if (best_predictor > predictor)
374 best_probability = probability, best_predictor = predictor;
376 d = (combined_probability * probability
377 + (REG_BR_PROB_BASE - combined_probability)
378 * (REG_BR_PROB_BASE - probability));
380 /* Use FP math to avoid overflows of 32bit integers. */
381 if (d == 0)
382 /* If one probability is 0% and one 100%, avoid division by zero. */
383 combined_probability = REG_BR_PROB_BASE / 2;
384 else
385 combined_probability = (((double) combined_probability) * probability
386 * REG_BR_PROB_BASE / d + 0.5);
389 /* Decide which heuristic to use. In case we didn't match anything,
390 use no_prediction heuristic, in case we did match, use either
391 first match or Dempster-Shaffer theory depending on the flags. */
393 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
394 first_match = true;
396 if (!found)
397 dump_prediction (dump_file, PRED_NO_PREDICTION,
398 combined_probability, bb, true);
399 else
401 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability,
402 bb, !first_match);
403 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability,
404 bb, first_match);
407 if (first_match)
408 combined_probability = best_probability;
409 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
411 while (*pnote)
413 if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
415 int predictor = INTVAL (XEXP (XEXP (*pnote, 0), 0));
416 int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
418 dump_prediction (dump_file, predictor, probability, bb,
419 !first_match || best_predictor == predictor);
420 *pnote = XEXP (*pnote, 1);
422 else
423 pnote = &XEXP (*pnote, 1);
426 if (!prob_note)
428 REG_NOTES (insn)
429 = gen_rtx_EXPR_LIST (REG_BR_PROB,
430 GEN_INT (combined_probability), REG_NOTES (insn));
432 /* Save the prediction into CFG in case we are seeing non-degenerated
433 conditional jump. */
434 if (bb->succ->succ_next)
436 BRANCH_EDGE (bb)->probability = combined_probability;
437 FALLTHRU_EDGE (bb)->probability
438 = REG_BR_PROB_BASE - combined_probability;
443 /* Combine predictions into single probability and store them into CFG.
444 Remove now useless prediction entries. */
446 static void
447 combine_predictions_for_bb (FILE *file, basic_block bb)
449 int best_probability = PROB_EVEN;
450 int best_predictor = END_PREDICTORS;
451 int combined_probability = REG_BR_PROB_BASE / 2;
452 int d;
453 bool first_match = false;
454 bool found = false;
455 struct edge_prediction *pred;
456 int nedges = 0;
457 edge e, first = NULL, second = NULL;
459 for (e = bb->succ; e; e = e->succ_next)
460 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
462 nedges ++;
463 if (first && !second)
464 second = e;
465 if (!first)
466 first = e;
469 /* When there is no successor or only one choice, prediction is easy.
471 We are lazy for now and predict only basic blocks with two outgoing
472 edges. It is possible to predict generic case too, but we have to
473 ignore first match heuristics and do more involved combining. Implement
474 this later. */
475 if (nedges != 2)
477 if (!bb->count)
478 set_even_probabilities (bb);
479 bb_ann (bb)->predictions = NULL;
480 if (file)
481 fprintf (file, "%i edges in bb %i predicted to even probabilities\n",
482 nedges, bb->index);
483 return;
486 if (file)
487 fprintf (file, "Predictions for bb %i\n", bb->index);
489 /* We implement "first match" heuristics and use probability guessed
490 by predictor with smallest index. */
491 for (pred = bb_ann (bb)->predictions; pred; pred = pred->next)
493 int predictor = pred->predictor;
494 int probability = pred->probability;
496 if (pred->edge != first)
497 probability = REG_BR_PROB_BASE - probability;
499 found = true;
500 if (best_predictor > predictor)
501 best_probability = probability, best_predictor = predictor;
503 d = (combined_probability * probability
504 + (REG_BR_PROB_BASE - combined_probability)
505 * (REG_BR_PROB_BASE - probability));
507 /* Use FP math to avoid overflows of 32bit integers. */
508 if (d == 0)
509 /* If one probability is 0% and one 100%, avoid division by zero. */
510 combined_probability = REG_BR_PROB_BASE / 2;
511 else
512 combined_probability = (((double) combined_probability) * probability
513 * REG_BR_PROB_BASE / d + 0.5);
516 /* Decide which heuristic to use. In case we didn't match anything,
517 use no_prediction heuristic, in case we did match, use either
518 first match or Dempster-Shaffer theory depending on the flags. */
520 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
521 first_match = true;
523 if (!found)
524 dump_prediction (file, PRED_NO_PREDICTION, combined_probability, bb, true);
525 else
527 dump_prediction (file, PRED_DS_THEORY, combined_probability, bb,
528 !first_match);
529 dump_prediction (file, PRED_FIRST_MATCH, best_probability, bb,
530 first_match);
533 if (first_match)
534 combined_probability = best_probability;
535 dump_prediction (file, PRED_COMBINED, combined_probability, bb, true);
537 for (pred = bb_ann (bb)->predictions; pred; pred = pred->next)
539 int predictor = pred->predictor;
540 int probability = pred->probability;
542 if (pred->edge != bb->succ)
543 probability = REG_BR_PROB_BASE - probability;
544 dump_prediction (file, predictor, probability, bb,
545 !first_match || best_predictor == predictor);
547 bb_ann (bb)->predictions = NULL;
549 if (!bb->count)
551 first->probability = combined_probability;
552 second->probability = REG_BR_PROB_BASE - combined_probability;
556 /* Predict edge probabilities by exploiting loop structure.
557 When RTLSIMPLELOOPS is set, attempt to count number of iterations by analyzing
558 RTL otherwise use tree based approach. */
559 static void
560 predict_loops (struct loops *loops_info, bool rtlsimpleloops)
562 unsigned i;
564 if (!rtlsimpleloops)
565 scev_initialize (loops_info);
567 /* Try to predict out blocks in a loop that are not part of a
568 natural loop. */
569 for (i = 1; i < loops_info->num; i++)
571 basic_block bb, *bbs;
572 unsigned j;
573 int exits;
574 struct loop *loop = loops_info->parray[i];
575 struct niter_desc desc;
576 unsigned HOST_WIDE_INT niter;
578 flow_loop_scan (loop, LOOP_EXIT_EDGES);
579 exits = loop->num_exits;
581 if (rtlsimpleloops)
583 iv_analysis_loop_init (loop);
584 find_simple_exit (loop, &desc);
586 if (desc.simple_p && desc.const_iter)
588 int prob;
589 niter = desc.niter + 1;
590 if (niter == 0) /* We might overflow here. */
591 niter = desc.niter;
593 prob = (REG_BR_PROB_BASE
594 - (REG_BR_PROB_BASE + niter /2) / niter);
595 /* Branch prediction algorithm gives 0 frequency for everything
596 after the end of loop for loop having 0 probability to finish. */
597 if (prob == REG_BR_PROB_BASE)
598 prob = REG_BR_PROB_BASE - 1;
599 predict_edge (desc.in_edge, PRED_LOOP_ITERATIONS,
600 prob);
603 else
605 edge *exits;
606 unsigned j, n_exits;
607 struct tree_niter_desc niter_desc;
609 exits = get_loop_exit_edges (loop, &n_exits);
610 for (j = 0; j < n_exits; j++)
612 tree niter = NULL;
614 if (number_of_iterations_exit (loop, exits[j], &niter_desc))
615 niter = niter_desc.niter;
616 if (!niter || TREE_CODE (niter_desc.niter) != INTEGER_CST)
617 niter = loop_niter_by_eval (loop, exits[j]);
619 if (TREE_CODE (niter) == INTEGER_CST)
621 int probability;
622 if (host_integerp (niter, 1)
623 && tree_int_cst_lt (niter,
624 build_int_cstu (NULL_TREE,
625 REG_BR_PROB_BASE - 1)))
627 HOST_WIDE_INT nitercst = tree_low_cst (niter, 1) + 1;
628 probability = (REG_BR_PROB_BASE + nitercst / 2) / nitercst;
630 else
631 probability = 1;
633 predict_edge (exits[j], PRED_LOOP_ITERATIONS, probability);
637 free (exits);
640 bbs = get_loop_body (loop);
642 for (j = 0; j < loop->num_nodes; j++)
644 int header_found = 0;
645 edge e;
647 bb = bbs[j];
649 /* Bypass loop heuristics on continue statement. These
650 statements construct loops via "non-loop" constructs
651 in the source language and are better to be handled
652 separately. */
653 if ((rtlsimpleloops && !can_predict_insn_p (BB_END (bb)))
654 || predicted_by_p (bb, PRED_CONTINUE))
655 continue;
657 /* Loop branch heuristics - predict an edge back to a
658 loop's head as taken. */
659 for (e = bb->succ; e; e = e->succ_next)
660 if (e->dest == loop->header
661 && e->src == loop->latch)
663 header_found = 1;
664 predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
667 /* Loop exit heuristics - predict an edge exiting the loop if the
668 conditional has no loop header successors as not taken. */
669 if (!header_found)
670 for (e = bb->succ; e; e = e->succ_next)
671 if (e->dest->index < 0
672 || !flow_bb_inside_loop_p (loop, e->dest))
673 predict_edge
674 (e, PRED_LOOP_EXIT,
675 (REG_BR_PROB_BASE
676 - predictor_info [(int) PRED_LOOP_EXIT].hitrate)
677 / exits);
680 /* Free basic blocks from get_loop_body. */
681 free (bbs);
684 if (!rtlsimpleloops)
685 scev_reset ();
688 /* Attempt to predict probabilities of BB outgoing edges using local
689 properties. */
690 static void
691 bb_estimate_probability_locally (basic_block bb)
693 rtx last_insn = BB_END (bb);
694 rtx cond;
696 if (! can_predict_insn_p (last_insn))
697 return;
698 cond = get_condition (last_insn, NULL, false, false);
699 if (! cond)
700 return;
702 /* Try "pointer heuristic."
703 A comparison ptr == 0 is predicted as false.
704 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
705 if (COMPARISON_P (cond)
706 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
707 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
709 if (GET_CODE (cond) == EQ)
710 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
711 else if (GET_CODE (cond) == NE)
712 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
714 else
716 /* Try "opcode heuristic."
717 EQ tests are usually false and NE tests are usually true. Also,
718 most quantities are positive, so we can make the appropriate guesses
719 about signed comparisons against zero. */
720 switch (GET_CODE (cond))
722 case CONST_INT:
723 /* Unconditional branch. */
724 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
725 cond == const0_rtx ? NOT_TAKEN : TAKEN);
726 break;
728 case EQ:
729 case UNEQ:
730 /* Floating point comparisons appears to behave in a very
731 unpredictable way because of special role of = tests in
732 FP code. */
733 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
735 /* Comparisons with 0 are often used for booleans and there is
736 nothing useful to predict about them. */
737 else if (XEXP (cond, 1) == const0_rtx
738 || XEXP (cond, 0) == const0_rtx)
740 else
741 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
742 break;
744 case NE:
745 case LTGT:
746 /* Floating point comparisons appears to behave in a very
747 unpredictable way because of special role of = tests in
748 FP code. */
749 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
751 /* Comparisons with 0 are often used for booleans and there is
752 nothing useful to predict about them. */
753 else if (XEXP (cond, 1) == const0_rtx
754 || XEXP (cond, 0) == const0_rtx)
756 else
757 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
758 break;
760 case ORDERED:
761 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
762 break;
764 case UNORDERED:
765 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
766 break;
768 case LE:
769 case LT:
770 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
771 || XEXP (cond, 1) == constm1_rtx)
772 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
773 break;
775 case GE:
776 case GT:
777 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
778 || XEXP (cond, 1) == constm1_rtx)
779 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
780 break;
782 default:
783 break;
787 /* Statically estimate the probability that a branch will be taken and produce
788 estimated profile. When profile feedback is present never executed portions
789 of function gets estimated. */
791 void
792 estimate_probability (struct loops *loops_info)
794 basic_block bb;
796 connect_infinite_loops_to_exit ();
797 calculate_dominance_info (CDI_DOMINATORS);
798 calculate_dominance_info (CDI_POST_DOMINATORS);
800 predict_loops (loops_info, true);
802 iv_analysis_done ();
804 /* Attempt to predict conditional jumps using a number of heuristics. */
805 FOR_EACH_BB (bb)
807 rtx last_insn = BB_END (bb);
808 edge e;
810 if (! can_predict_insn_p (last_insn))
811 continue;
813 for (e = bb->succ; e; e = e->succ_next)
815 /* Predict early returns to be probable, as we've already taken
816 care for error returns and other are often used for fast paths
817 trought function. */
818 if ((e->dest == EXIT_BLOCK_PTR
819 || (e->dest->succ && !e->dest->succ->succ_next
820 && e->dest->succ->dest == EXIT_BLOCK_PTR))
821 && !predicted_by_p (bb, PRED_NULL_RETURN)
822 && !predicted_by_p (bb, PRED_CONST_RETURN)
823 && !predicted_by_p (bb, PRED_NEGATIVE_RETURN)
824 && !last_basic_block_p (e->dest))
825 predict_edge_def (e, PRED_EARLY_RETURN, TAKEN);
827 /* Look for block we are guarding (i.e. we dominate it,
828 but it doesn't postdominate us). */
829 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
830 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
831 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
833 rtx insn;
835 /* The call heuristic claims that a guarded function call
836 is improbable. This is because such calls are often used
837 to signal exceptional situations such as printing error
838 messages. */
839 for (insn = BB_HEAD (e->dest); insn != NEXT_INSN (BB_END (e->dest));
840 insn = NEXT_INSN (insn))
841 if (CALL_P (insn)
842 /* Constant and pure calls are hardly used to signalize
843 something exceptional. */
844 && ! CONST_OR_PURE_CALL_P (insn))
846 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
847 break;
851 bb_estimate_probability_locally (bb);
854 /* Attach the combined probability to each conditional jump. */
855 FOR_EACH_BB (bb)
856 combine_predictions_for_insn (BB_END (bb), bb);
858 remove_fake_edges ();
859 estimate_bb_frequencies (loops_info);
860 free_dominance_info (CDI_POST_DOMINATORS);
861 if (profile_status == PROFILE_ABSENT)
862 profile_status = PROFILE_GUESSED;
865 /* Set edge->probability for each successor edge of BB. */
866 void
867 guess_outgoing_edge_probabilities (basic_block bb)
869 bb_estimate_probability_locally (bb);
870 combine_predictions_for_insn (BB_END (bb), bb);
873 /* Return constant EXPR will likely have at execution time, NULL if unknown.
874 The function is used by builtin_expect branch predictor so the evidence
875 must come from this construct and additional possible constant folding.
877 We may want to implement more involved value guess (such as value range
878 propagation based prediction), but such tricks shall go to new
879 implementation. */
881 static tree
882 expr_expected_value (tree expr, bitmap visited)
884 if (TREE_CONSTANT (expr))
885 return expr;
886 else if (TREE_CODE (expr) == SSA_NAME)
888 tree def = SSA_NAME_DEF_STMT (expr);
890 /* If we were already here, break the infinite cycle. */
891 if (bitmap_bit_p (visited, SSA_NAME_VERSION (expr)))
892 return NULL;
893 bitmap_set_bit (visited, SSA_NAME_VERSION (expr));
895 if (TREE_CODE (def) == PHI_NODE)
897 /* All the arguments of the PHI node must have the same constant
898 length. */
899 int i;
900 tree val = NULL, new_val;
902 for (i = 0; i < PHI_NUM_ARGS (def); i++)
904 tree arg = PHI_ARG_DEF (def, i);
906 /* If this PHI has itself as an argument, we cannot
907 determine the string length of this argument. However,
908 if we can find a expected constant value for the other
909 PHI args then we can still be sure that this is
910 likely a constant. So be optimistic and just
911 continue with the next argument. */
912 if (arg == PHI_RESULT (def))
913 continue;
915 new_val = expr_expected_value (arg, visited);
916 if (!new_val)
917 return NULL;
918 if (!val)
919 val = new_val;
920 else if (!operand_equal_p (val, new_val, false))
921 return NULL;
923 return val;
925 if (TREE_CODE (def) != MODIFY_EXPR || TREE_OPERAND (def, 0) != expr)
926 return NULL;
927 return expr_expected_value (TREE_OPERAND (def, 1), visited);
929 else if (TREE_CODE (expr) == CALL_EXPR)
931 tree decl = get_callee_fndecl (expr);
932 if (!decl)
933 return NULL;
934 if (DECL_BUILT_IN (decl) && DECL_FUNCTION_CODE (decl) == BUILT_IN_EXPECT)
936 tree arglist = TREE_OPERAND (expr, 1);
937 tree val;
939 if (arglist == NULL_TREE
940 || TREE_CHAIN (arglist) == NULL_TREE)
941 return NULL;
942 val = TREE_VALUE (TREE_CHAIN (TREE_OPERAND (expr, 1)));
943 if (TREE_CONSTANT (val))
944 return val;
945 return TREE_VALUE (TREE_CHAIN (TREE_OPERAND (expr, 1)));
948 if (BINARY_CLASS_P (expr) || COMPARISON_CLASS_P (expr))
950 tree op0, op1, res;
951 op0 = expr_expected_value (TREE_OPERAND (expr, 0), visited);
952 if (!op0)
953 return NULL;
954 op1 = expr_expected_value (TREE_OPERAND (expr, 1), visited);
955 if (!op1)
956 return NULL;
957 res = fold (build (TREE_CODE (expr), TREE_TYPE (expr), op0, op1));
958 if (TREE_CONSTANT (res))
959 return res;
960 return NULL;
962 if (UNARY_CLASS_P (expr))
964 tree op0, res;
965 op0 = expr_expected_value (TREE_OPERAND (expr, 0), visited);
966 if (!op0)
967 return NULL;
968 res = fold (build1 (TREE_CODE (expr), TREE_TYPE (expr), op0));
969 if (TREE_CONSTANT (res))
970 return res;
971 return NULL;
973 return NULL;
976 /* Get rid of all builtin_expect calls we no longer need. */
977 static void
978 strip_builtin_expect (void)
980 basic_block bb;
981 FOR_EACH_BB (bb)
983 block_stmt_iterator bi;
984 for (bi = bsi_start (bb); !bsi_end_p (bi); bsi_next (&bi))
986 tree stmt = bsi_stmt (bi);
987 tree fndecl;
988 tree arglist;
990 if (TREE_CODE (stmt) == MODIFY_EXPR
991 && TREE_CODE (TREE_OPERAND (stmt, 1)) == CALL_EXPR
992 && (fndecl = get_callee_fndecl (TREE_OPERAND (stmt, 1)))
993 && DECL_BUILT_IN (fndecl)
994 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT
995 && (arglist = TREE_OPERAND (TREE_OPERAND (stmt, 1), 1))
996 && TREE_CHAIN (arglist))
998 TREE_OPERAND (stmt, 1) = TREE_VALUE (arglist);
999 modify_stmt (stmt);
1005 /* Predict using opcode of the last statement in basic block. */
1006 static void
1007 tree_predict_by_opcode (basic_block bb)
1009 tree stmt = last_stmt (bb);
1010 edge then_edge;
1011 tree cond;
1012 tree op0;
1013 tree type;
1014 tree val;
1015 bitmap visited;
1017 if (!stmt || TREE_CODE (stmt) != COND_EXPR)
1018 return;
1019 for (then_edge = bb->succ; then_edge; then_edge = then_edge->succ_next)
1020 if (then_edge->flags & EDGE_TRUE_VALUE)
1021 break;
1022 cond = TREE_OPERAND (stmt, 0);
1023 if (!COMPARISON_CLASS_P (cond))
1024 return;
1025 op0 = TREE_OPERAND (cond, 0);
1026 type = TREE_TYPE (op0);
1027 visited = BITMAP_XMALLOC ();
1028 val = expr_expected_value (cond, visited);
1029 BITMAP_XFREE (visited);
1030 if (val)
1032 if (integer_zerop (val))
1033 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, NOT_TAKEN);
1034 else
1035 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, TAKEN);
1036 return;
1038 /* Try "pointer heuristic."
1039 A comparison ptr == 0 is predicted as false.
1040 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1041 if (POINTER_TYPE_P (type))
1043 if (TREE_CODE (cond) == EQ_EXPR)
1044 predict_edge_def (then_edge, PRED_TREE_POINTER, NOT_TAKEN);
1045 else if (TREE_CODE (cond) == NE_EXPR)
1046 predict_edge_def (then_edge, PRED_TREE_POINTER, TAKEN);
1048 else
1050 /* Try "opcode heuristic."
1051 EQ tests are usually false and NE tests are usually true. Also,
1052 most quantities are positive, so we can make the appropriate guesses
1053 about signed comparisons against zero. */
1054 switch (TREE_CODE (cond))
1056 case EQ_EXPR:
1057 case UNEQ_EXPR:
1058 /* Floating point comparisons appears to behave in a very
1059 unpredictable way because of special role of = tests in
1060 FP code. */
1061 if (FLOAT_TYPE_P (type))
1063 /* Comparisons with 0 are often used for booleans and there is
1064 nothing useful to predict about them. */
1065 else if (integer_zerop (op0)
1066 || integer_zerop (TREE_OPERAND (cond, 1)))
1068 else
1069 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, NOT_TAKEN);
1070 break;
1072 case NE_EXPR:
1073 case LTGT_EXPR:
1074 /* Floating point comparisons appears to behave in a very
1075 unpredictable way because of special role of = tests in
1076 FP code. */
1077 if (FLOAT_TYPE_P (type))
1079 /* Comparisons with 0 are often used for booleans and there is
1080 nothing useful to predict about them. */
1081 else if (integer_zerop (op0)
1082 || integer_zerop (TREE_OPERAND (cond, 1)))
1084 else
1085 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, TAKEN);
1086 break;
1088 case ORDERED_EXPR:
1089 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, TAKEN);
1090 break;
1092 case UNORDERED_EXPR:
1093 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, NOT_TAKEN);
1094 break;
1096 case LE_EXPR:
1097 case LT_EXPR:
1098 if (integer_zerop (TREE_OPERAND (cond, 1))
1099 || integer_onep (TREE_OPERAND (cond, 1))
1100 || integer_all_onesp (TREE_OPERAND (cond, 1))
1101 || real_zerop (TREE_OPERAND (cond, 1))
1102 || real_onep (TREE_OPERAND (cond, 1))
1103 || real_minus_onep (TREE_OPERAND (cond, 1)))
1104 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, NOT_TAKEN);
1105 break;
1107 case GE_EXPR:
1108 case GT_EXPR:
1109 if (integer_zerop (TREE_OPERAND (cond, 1))
1110 || integer_onep (TREE_OPERAND (cond, 1))
1111 || integer_all_onesp (TREE_OPERAND (cond, 1))
1112 || real_zerop (TREE_OPERAND (cond, 1))
1113 || real_onep (TREE_OPERAND (cond, 1))
1114 || real_minus_onep (TREE_OPERAND (cond, 1)))
1115 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, TAKEN);
1116 break;
1118 default:
1119 break;
1123 /* Try to guess whether the value of return means error code. */
1124 static enum br_predictor
1125 return_prediction (tree val, enum prediction *prediction)
1127 /* VOID. */
1128 if (!val)
1129 return PRED_NO_PREDICTION;
1130 /* Different heuristics for pointers and scalars. */
1131 if (POINTER_TYPE_P (TREE_TYPE (val)))
1133 /* NULL is usually not returned. */
1134 if (integer_zerop (val))
1136 *prediction = NOT_TAKEN;
1137 return PRED_NULL_RETURN;
1140 else if (INTEGRAL_TYPE_P (TREE_TYPE (val)))
1142 /* Negative return values are often used to indicate
1143 errors. */
1144 if (TREE_CODE (val) == INTEGER_CST
1145 && tree_int_cst_sgn (val) < 0)
1147 *prediction = NOT_TAKEN;
1148 return PRED_NEGATIVE_RETURN;
1150 /* Constant return values seems to be commonly taken.
1151 Zero/one often represent booleans so exclude them from the
1152 heuristics. */
1153 if (TREE_CONSTANT (val)
1154 && (!integer_zerop (val) && !integer_onep (val)))
1156 *prediction = TAKEN;
1157 return PRED_NEGATIVE_RETURN;
1160 return PRED_NO_PREDICTION;
1163 /* Find the basic block with return expression and look up for possible
1164 return value trying to apply RETURN_PREDICTION heuristics. */
1165 static void
1166 apply_return_prediction (int *heads)
1168 tree return_stmt;
1169 tree return_val;
1170 edge e;
1171 tree phi;
1172 int phi_num_args, i;
1173 enum br_predictor pred;
1174 enum prediction direction;
1176 for (e = EXIT_BLOCK_PTR->pred; e ; e = e->pred_next)
1178 return_stmt = last_stmt (e->src);
1179 if (TREE_CODE (return_stmt) == RETURN_EXPR)
1180 break;
1182 if (!e)
1183 return;
1184 return_val = TREE_OPERAND (return_stmt, 0);
1185 if (!return_val)
1186 return;
1187 if (TREE_CODE (return_val) == MODIFY_EXPR)
1188 return_val = TREE_OPERAND (return_val, 1);
1189 if (TREE_CODE (return_val) != SSA_NAME
1190 || !SSA_NAME_DEF_STMT (return_val)
1191 || TREE_CODE (SSA_NAME_DEF_STMT (return_val)) != PHI_NODE)
1192 return;
1193 phi = SSA_NAME_DEF_STMT (return_val);
1194 while (phi)
1196 tree next = PHI_CHAIN (phi);
1197 if (PHI_RESULT (phi) == return_val)
1198 break;
1199 phi = next;
1201 if (!phi)
1202 return;
1203 phi_num_args = PHI_NUM_ARGS (phi);
1204 pred = return_prediction (PHI_ARG_DEF (phi, 0), &direction);
1206 /* Avoid the degenerate case where all return values form the function
1207 belongs to same category (ie they are all positive constants)
1208 so we can hardly say something about them. */
1209 for (i = 1; i < phi_num_args; i++)
1210 if (pred != return_prediction (PHI_ARG_DEF (phi, i), &direction))
1211 break;
1212 if (i != phi_num_args)
1213 for (i = 0; i < phi_num_args; i++)
1215 pred = return_prediction (PHI_ARG_DEF (phi, i), &direction);
1216 if (pred != PRED_NO_PREDICTION)
1217 predict_paths_leading_to (PHI_ARG_EDGE (phi, i)->src, heads, pred,
1218 direction);
1222 /* Look for basic block that contains unlikely to happen events
1223 (such as noreturn calls) and mark all paths leading to execution
1224 of this basic blocks as unlikely. */
1226 static void
1227 tree_bb_level_predictions (void)
1229 basic_block bb;
1230 int *heads;
1232 heads = xmalloc (sizeof (int) * last_basic_block);
1233 memset (heads, -1, sizeof (int) * last_basic_block);
1234 heads[ENTRY_BLOCK_PTR->next_bb->index] = last_basic_block;
1236 apply_return_prediction (heads);
1238 FOR_EACH_BB (bb)
1240 block_stmt_iterator bsi = bsi_last (bb);
1242 for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1244 tree stmt = bsi_stmt (bsi);
1245 switch (TREE_CODE (stmt))
1247 case MODIFY_EXPR:
1248 if (TREE_CODE (TREE_OPERAND (stmt, 1)) == CALL_EXPR)
1250 stmt = TREE_OPERAND (stmt, 1);
1251 goto call_expr;
1253 break;
1254 case CALL_EXPR:
1255 call_expr:;
1256 if (call_expr_flags (stmt) & ECF_NORETURN)
1257 predict_paths_leading_to (bb, heads, PRED_NORETURN,
1258 NOT_TAKEN);
1259 break;
1260 default:
1261 break;
1266 free (heads);
1269 /* Predict branch probabilities and estimate profile of the tree CFG. */
1270 static void
1271 tree_estimate_probability (void)
1273 basic_block bb;
1274 struct loops loops_info;
1276 flow_loops_find (&loops_info, LOOP_TREE);
1277 if (dump_file && (dump_flags & TDF_DETAILS))
1278 flow_loops_dump (&loops_info, dump_file, NULL, 0);
1280 add_noreturn_fake_exit_edges ();
1281 connect_infinite_loops_to_exit ();
1282 calculate_dominance_info (CDI_DOMINATORS);
1283 calculate_dominance_info (CDI_POST_DOMINATORS);
1285 tree_bb_level_predictions ();
1287 predict_loops (&loops_info, false);
1289 FOR_EACH_BB (bb)
1291 edge e;
1293 for (e = bb->succ; e; e = e->succ_next)
1295 /* Predict early returns to be probable, as we've already taken
1296 care for error returns and other cases are often used for
1297 fast paths trought function. */
1298 if (e->dest == EXIT_BLOCK_PTR
1299 && TREE_CODE (last_stmt (bb)) == RETURN_EXPR
1300 && bb->pred && bb->pred->pred_next)
1302 edge e1;
1304 for (e1 = bb->pred; e1; e1 = e1->pred_next)
1305 if (!predicted_by_p (e1->src, PRED_NULL_RETURN)
1306 && !predicted_by_p (e1->src, PRED_CONST_RETURN)
1307 && !predicted_by_p (e1->src, PRED_NEGATIVE_RETURN)
1308 && !last_basic_block_p (e1->src))
1309 predict_edge_def (e1, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
1312 /* Look for block we are guarding (ie we dominate it,
1313 but it doesn't postdominate us). */
1314 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
1315 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
1316 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
1318 block_stmt_iterator bi;
1320 /* The call heuristic claims that a guarded function call
1321 is improbable. This is because such calls are often used
1322 to signal exceptional situations such as printing error
1323 messages. */
1324 for (bi = bsi_start (e->dest); !bsi_end_p (bi);
1325 bsi_next (&bi))
1327 tree stmt = bsi_stmt (bi);
1328 if ((TREE_CODE (stmt) == CALL_EXPR
1329 || (TREE_CODE (stmt) == MODIFY_EXPR
1330 && TREE_CODE (TREE_OPERAND (stmt, 1)) == CALL_EXPR))
1331 /* Constant and pure calls are hardly used to signalize
1332 something exceptional. */
1333 && TREE_SIDE_EFFECTS (stmt))
1335 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
1336 break;
1341 tree_predict_by_opcode (bb);
1343 FOR_EACH_BB (bb)
1344 combine_predictions_for_bb (dump_file, bb);
1346 if (0) /* FIXME: Enable once we are pass down the profile to RTL level. */
1347 strip_builtin_expect ();
1348 estimate_bb_frequencies (&loops_info);
1349 free_dominance_info (CDI_POST_DOMINATORS);
1350 remove_fake_exit_edges ();
1351 flow_loops_free (&loops_info);
1352 if (dump_file && (dump_flags & TDF_DETAILS))
1353 dump_tree_cfg (dump_file, dump_flags);
1354 if (profile_status == PROFILE_ABSENT)
1355 profile_status = PROFILE_GUESSED;
1358 /* __builtin_expect dropped tokens into the insn stream describing expected
1359 values of registers. Generate branch probabilities based off these
1360 values. */
1362 void
1363 expected_value_to_br_prob (void)
1365 rtx insn, cond, ev = NULL_RTX, ev_reg = NULL_RTX;
1367 for (insn = get_insns (); insn ; insn = NEXT_INSN (insn))
1369 switch (GET_CODE (insn))
1371 case NOTE:
1372 /* Look for expected value notes. */
1373 if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_EXPECTED_VALUE)
1375 ev = NOTE_EXPECTED_VALUE (insn);
1376 ev_reg = XEXP (ev, 0);
1377 delete_insn (insn);
1379 continue;
1381 case CODE_LABEL:
1382 /* Never propagate across labels. */
1383 ev = NULL_RTX;
1384 continue;
1386 case JUMP_INSN:
1387 /* Look for simple conditional branches. If we haven't got an
1388 expected value yet, no point going further. */
1389 if (!JUMP_P (insn) || ev == NULL_RTX
1390 || ! any_condjump_p (insn))
1391 continue;
1392 break;
1394 default:
1395 /* Look for insns that clobber the EV register. */
1396 if (ev && reg_set_p (ev_reg, insn))
1397 ev = NULL_RTX;
1398 continue;
1401 /* Collect the branch condition, hopefully relative to EV_REG. */
1402 /* ??? At present we'll miss things like
1403 (expected_value (eq r70 0))
1404 (set r71 -1)
1405 (set r80 (lt r70 r71))
1406 (set pc (if_then_else (ne r80 0) ...))
1407 as canonicalize_condition will render this to us as
1408 (lt r70, r71)
1409 Could use cselib to try and reduce this further. */
1410 cond = XEXP (SET_SRC (pc_set (insn)), 0);
1411 cond = canonicalize_condition (insn, cond, 0, NULL, ev_reg,
1412 false, false);
1413 if (! cond || XEXP (cond, 0) != ev_reg
1414 || GET_CODE (XEXP (cond, 1)) != CONST_INT)
1415 continue;
1417 /* Substitute and simplify. Given that the expression we're
1418 building involves two constants, we should wind up with either
1419 true or false. */
1420 cond = gen_rtx_fmt_ee (GET_CODE (cond), VOIDmode,
1421 XEXP (ev, 1), XEXP (cond, 1));
1422 cond = simplify_rtx (cond);
1424 /* Turn the condition into a scaled branch probability. */
1425 if (cond != const_true_rtx && cond != const0_rtx)
1426 abort ();
1427 predict_insn_def (insn, PRED_BUILTIN_EXPECT,
1428 cond == const_true_rtx ? TAKEN : NOT_TAKEN);
1432 /* Check whether this is the last basic block of function. Commonly
1433 there is one extra common cleanup block. */
1434 static bool
1435 last_basic_block_p (basic_block bb)
1437 if (bb == EXIT_BLOCK_PTR)
1438 return false;
1440 return (bb->next_bb == EXIT_BLOCK_PTR
1441 || (bb->next_bb->next_bb == EXIT_BLOCK_PTR
1442 && bb->succ && !bb->succ->succ_next
1443 && bb->succ->dest->next_bb == EXIT_BLOCK_PTR));
1446 /* Sets branch probabilities according to PREDiction and
1447 FLAGS. HEADS[bb->index] should be index of basic block in that we
1448 need to alter branch predictions (i.e. the first of our dominators
1449 such that we do not post-dominate it) (but we fill this information
1450 on demand, so -1 may be there in case this was not needed yet). */
1452 static void
1453 predict_paths_leading_to (basic_block bb, int *heads, enum br_predictor pred,
1454 enum prediction taken)
1456 edge e;
1457 int y;
1459 if (heads[bb->index] < 0)
1461 /* This is first time we need this field in heads array; so
1462 find first dominator that we do not post-dominate (we are
1463 using already known members of heads array). */
1464 basic_block ai = bb;
1465 basic_block next_ai = get_immediate_dominator (CDI_DOMINATORS, bb);
1466 int head;
1468 while (heads[next_ai->index] < 0)
1470 if (!dominated_by_p (CDI_POST_DOMINATORS, next_ai, bb))
1471 break;
1472 heads[next_ai->index] = ai->index;
1473 ai = next_ai;
1474 next_ai = get_immediate_dominator (CDI_DOMINATORS, next_ai);
1476 if (!dominated_by_p (CDI_POST_DOMINATORS, next_ai, bb))
1477 head = next_ai->index;
1478 else
1479 head = heads[next_ai->index];
1480 while (next_ai != bb)
1482 next_ai = ai;
1483 if (heads[ai->index] == ENTRY_BLOCK)
1484 ai = ENTRY_BLOCK_PTR;
1485 else
1486 ai = BASIC_BLOCK (heads[ai->index]);
1487 heads[next_ai->index] = head;
1490 y = heads[bb->index];
1492 /* Now find the edge that leads to our branch and aply the prediction. */
1494 if (y == last_basic_block)
1495 return;
1496 for (e = BASIC_BLOCK (y)->succ; e; e = e->succ_next)
1497 if (e->dest->index >= 0
1498 && dominated_by_p (CDI_POST_DOMINATORS, e->dest, bb))
1499 predict_edge_def (e, pred, taken);
1502 /* This is used to carry information about basic blocks. It is
1503 attached to the AUX field of the standard CFG block. */
1505 typedef struct block_info_def
1507 /* Estimated frequency of execution of basic_block. */
1508 sreal frequency;
1510 /* To keep queue of basic blocks to process. */
1511 basic_block next;
1513 /* True if block needs to be visited in propagate_freq. */
1514 unsigned int tovisit:1;
1516 /* Number of predecessors we need to visit first. */
1517 int npredecessors;
1518 } *block_info;
1520 /* Similar information for edges. */
1521 typedef struct edge_info_def
1523 /* In case edge is an loopback edge, the probability edge will be reached
1524 in case header is. Estimated number of iterations of the loop can be
1525 then computed as 1 / (1 - back_edge_prob). */
1526 sreal back_edge_prob;
1527 /* True if the edge is an loopback edge in the natural loop. */
1528 unsigned int back_edge:1;
1529 } *edge_info;
1531 #define BLOCK_INFO(B) ((block_info) (B)->aux)
1532 #define EDGE_INFO(E) ((edge_info) (E)->aux)
1534 /* Helper function for estimate_bb_frequencies.
1535 Propagate the frequencies for LOOP. */
1537 static void
1538 propagate_freq (struct loop *loop)
1540 basic_block head = loop->header;
1541 basic_block bb;
1542 basic_block last;
1543 edge e;
1544 basic_block nextbb;
1546 /* For each basic block we need to visit count number of his predecessors
1547 we need to visit first. */
1548 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1550 if (BLOCK_INFO (bb)->tovisit)
1552 int count = 0;
1554 for (e = bb->pred; e; e = e->pred_next)
1555 if (BLOCK_INFO (e->src)->tovisit && !(e->flags & EDGE_DFS_BACK))
1556 count++;
1557 else if (BLOCK_INFO (e->src)->tovisit
1558 && dump_file && !EDGE_INFO (e)->back_edge)
1559 fprintf (dump_file,
1560 "Irreducible region hit, ignoring edge to %i->%i\n",
1561 e->src->index, bb->index);
1562 BLOCK_INFO (bb)->npredecessors = count;
1566 memcpy (&BLOCK_INFO (head)->frequency, &real_one, sizeof (real_one));
1567 last = head;
1568 for (bb = head; bb; bb = nextbb)
1570 sreal cyclic_probability, frequency;
1572 memcpy (&cyclic_probability, &real_zero, sizeof (real_zero));
1573 memcpy (&frequency, &real_zero, sizeof (real_zero));
1575 nextbb = BLOCK_INFO (bb)->next;
1576 BLOCK_INFO (bb)->next = NULL;
1578 /* Compute frequency of basic block. */
1579 if (bb != head)
1581 #ifdef ENABLE_CHECKING
1582 for (e = bb->pred; e; e = e->pred_next)
1583 if (BLOCK_INFO (e->src)->tovisit && !(e->flags & EDGE_DFS_BACK))
1584 abort ();
1585 #endif
1587 for (e = bb->pred; e; e = e->pred_next)
1588 if (EDGE_INFO (e)->back_edge)
1590 sreal_add (&cyclic_probability, &cyclic_probability,
1591 &EDGE_INFO (e)->back_edge_prob);
1593 else if (!(e->flags & EDGE_DFS_BACK))
1595 sreal tmp;
1597 /* frequency += (e->probability
1598 * BLOCK_INFO (e->src)->frequency /
1599 REG_BR_PROB_BASE); */
1601 sreal_init (&tmp, e->probability, 0);
1602 sreal_mul (&tmp, &tmp, &BLOCK_INFO (e->src)->frequency);
1603 sreal_mul (&tmp, &tmp, &real_inv_br_prob_base);
1604 sreal_add (&frequency, &frequency, &tmp);
1607 if (sreal_compare (&cyclic_probability, &real_zero) == 0)
1609 memcpy (&BLOCK_INFO (bb)->frequency, &frequency,
1610 sizeof (frequency));
1612 else
1614 if (sreal_compare (&cyclic_probability, &real_almost_one) > 0)
1616 memcpy (&cyclic_probability, &real_almost_one,
1617 sizeof (real_almost_one));
1620 /* BLOCK_INFO (bb)->frequency = frequency
1621 / (1 - cyclic_probability) */
1623 sreal_sub (&cyclic_probability, &real_one, &cyclic_probability);
1624 sreal_div (&BLOCK_INFO (bb)->frequency,
1625 &frequency, &cyclic_probability);
1629 BLOCK_INFO (bb)->tovisit = 0;
1631 /* Compute back edge frequencies. */
1632 for (e = bb->succ; e; e = e->succ_next)
1633 if (e->dest == head)
1635 sreal tmp;
1637 /* EDGE_INFO (e)->back_edge_prob
1638 = ((e->probability * BLOCK_INFO (bb)->frequency)
1639 / REG_BR_PROB_BASE); */
1641 sreal_init (&tmp, e->probability, 0);
1642 sreal_mul (&tmp, &tmp, &BLOCK_INFO (bb)->frequency);
1643 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
1644 &tmp, &real_inv_br_prob_base);
1647 /* Propagate to successor blocks. */
1648 for (e = bb->succ; e; e = e->succ_next)
1649 if (!(e->flags & EDGE_DFS_BACK)
1650 && BLOCK_INFO (e->dest)->npredecessors)
1652 BLOCK_INFO (e->dest)->npredecessors--;
1653 if (!BLOCK_INFO (e->dest)->npredecessors)
1655 if (!nextbb)
1656 nextbb = e->dest;
1657 else
1658 BLOCK_INFO (last)->next = e->dest;
1660 last = e->dest;
1666 /* Estimate probabilities of loopback edges in loops at same nest level. */
1668 static void
1669 estimate_loops_at_level (struct loop *first_loop)
1671 struct loop *loop;
1673 for (loop = first_loop; loop; loop = loop->next)
1675 edge e;
1676 basic_block *bbs;
1677 unsigned i;
1679 estimate_loops_at_level (loop->inner);
1681 if (loop->latch->succ) /* Do not do this for dummy function loop. */
1683 /* Find current loop back edge and mark it. */
1684 e = loop_latch_edge (loop);
1685 EDGE_INFO (e)->back_edge = 1;
1688 bbs = get_loop_body (loop);
1689 for (i = 0; i < loop->num_nodes; i++)
1690 BLOCK_INFO (bbs[i])->tovisit = 1;
1691 free (bbs);
1692 propagate_freq (loop);
1696 /* Convert counts measured by profile driven feedback to frequencies.
1697 Return nonzero iff there was any nonzero execution count. */
1699 static int
1700 counts_to_freqs (void)
1702 gcov_type count_max, true_count_max = 0;
1703 basic_block bb;
1705 FOR_EACH_BB (bb)
1706 true_count_max = MAX (bb->count, true_count_max);
1708 count_max = MAX (true_count_max, 1);
1709 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1710 bb->frequency = (bb->count * BB_FREQ_MAX + count_max / 2) / count_max;
1711 return true_count_max;
1714 /* Return true if function is likely to be expensive, so there is no point to
1715 optimize performance of prologue, epilogue or do inlining at the expense
1716 of code size growth. THRESHOLD is the limit of number of instructions
1717 function can execute at average to be still considered not expensive. */
1719 bool
1720 expensive_function_p (int threshold)
1722 unsigned int sum = 0;
1723 basic_block bb;
1724 unsigned int limit;
1726 /* We can not compute accurately for large thresholds due to scaled
1727 frequencies. */
1728 if (threshold > BB_FREQ_MAX)
1729 abort ();
1731 /* Frequencies are out of range. This either means that function contains
1732 internal loop executing more than BB_FREQ_MAX times or profile feedback
1733 is available and function has not been executed at all. */
1734 if (ENTRY_BLOCK_PTR->frequency == 0)
1735 return true;
1737 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
1738 limit = ENTRY_BLOCK_PTR->frequency * threshold;
1739 FOR_EACH_BB (bb)
1741 rtx insn;
1743 for (insn = BB_HEAD (bb); insn != NEXT_INSN (BB_END (bb));
1744 insn = NEXT_INSN (insn))
1745 if (active_insn_p (insn))
1747 sum += bb->frequency;
1748 if (sum > limit)
1749 return true;
1753 return false;
1756 /* Estimate basic blocks frequency by given branch probabilities. */
1758 static void
1759 estimate_bb_frequencies (struct loops *loops)
1761 basic_block bb;
1762 sreal freq_max;
1764 if (!flag_branch_probabilities || !counts_to_freqs ())
1766 static int real_values_initialized = 0;
1768 if (!real_values_initialized)
1770 real_values_initialized = 1;
1771 sreal_init (&real_zero, 0, 0);
1772 sreal_init (&real_one, 1, 0);
1773 sreal_init (&real_br_prob_base, REG_BR_PROB_BASE, 0);
1774 sreal_init (&real_bb_freq_max, BB_FREQ_MAX, 0);
1775 sreal_init (&real_one_half, 1, -1);
1776 sreal_div (&real_inv_br_prob_base, &real_one, &real_br_prob_base);
1777 sreal_sub (&real_almost_one, &real_one, &real_inv_br_prob_base);
1780 mark_dfs_back_edges ();
1782 ENTRY_BLOCK_PTR->succ->probability = REG_BR_PROB_BASE;
1784 /* Set up block info for each basic block. */
1785 alloc_aux_for_blocks (sizeof (struct block_info_def));
1786 alloc_aux_for_edges (sizeof (struct edge_info_def));
1787 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1789 edge e;
1791 BLOCK_INFO (bb)->tovisit = 0;
1792 for (e = bb->succ; e; e = e->succ_next)
1794 sreal_init (&EDGE_INFO (e)->back_edge_prob, e->probability, 0);
1795 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
1796 &EDGE_INFO (e)->back_edge_prob,
1797 &real_inv_br_prob_base);
1801 /* First compute probabilities locally for each loop from innermost
1802 to outermost to examine probabilities for back edges. */
1803 estimate_loops_at_level (loops->tree_root);
1805 memcpy (&freq_max, &real_zero, sizeof (real_zero));
1806 FOR_EACH_BB (bb)
1807 if (sreal_compare (&freq_max, &BLOCK_INFO (bb)->frequency) < 0)
1808 memcpy (&freq_max, &BLOCK_INFO (bb)->frequency, sizeof (freq_max));
1810 sreal_div (&freq_max, &real_bb_freq_max, &freq_max);
1811 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1813 sreal tmp;
1815 sreal_mul (&tmp, &BLOCK_INFO (bb)->frequency, &freq_max);
1816 sreal_add (&tmp, &tmp, &real_one_half);
1817 bb->frequency = sreal_to_int (&tmp);
1820 free_aux_for_blocks ();
1821 free_aux_for_edges ();
1823 compute_function_frequency ();
1824 if (flag_reorder_functions)
1825 choose_function_section ();
1828 /* Decide whether function is hot, cold or unlikely executed. */
1829 static void
1830 compute_function_frequency (void)
1832 basic_block bb;
1834 if (!profile_info || !flag_branch_probabilities)
1835 return;
1836 cfun->function_frequency = FUNCTION_FREQUENCY_UNLIKELY_EXECUTED;
1837 FOR_EACH_BB (bb)
1839 if (maybe_hot_bb_p (bb))
1841 cfun->function_frequency = FUNCTION_FREQUENCY_HOT;
1842 return;
1844 if (!probably_never_executed_bb_p (bb))
1845 cfun->function_frequency = FUNCTION_FREQUENCY_NORMAL;
1849 /* Choose appropriate section for the function. */
1850 static void
1851 choose_function_section (void)
1853 if (DECL_SECTION_NAME (current_function_decl)
1854 || !targetm.have_named_sections
1855 /* Theoretically we can split the gnu.linkonce text section too,
1856 but this requires more work as the frequency needs to match
1857 for all generated objects so we need to merge the frequency
1858 of all instances. For now just never set frequency for these. */
1859 || DECL_ONE_ONLY (current_function_decl))
1860 return;
1862 /* If we are doing the partitioning optimization, let the optimization
1863 choose the correct section into which to put things. */
1865 if (flag_reorder_blocks_and_partition)
1866 return;
1868 if (cfun->function_frequency == FUNCTION_FREQUENCY_HOT)
1869 DECL_SECTION_NAME (current_function_decl) =
1870 build_string (strlen (HOT_TEXT_SECTION_NAME), HOT_TEXT_SECTION_NAME);
1871 if (cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
1872 DECL_SECTION_NAME (current_function_decl) =
1873 build_string (strlen (UNLIKELY_EXECUTED_TEXT_SECTION_NAME),
1874 UNLIKELY_EXECUTED_TEXT_SECTION_NAME);
1878 struct tree_opt_pass pass_profile =
1880 "profile", /* name */
1881 NULL, /* gate */
1882 tree_estimate_probability, /* execute */
1883 NULL, /* sub */
1884 NULL, /* next */
1885 0, /* static_pass_number */
1886 TV_BRANCH_PROB, /* tv_id */
1887 PROP_cfg, /* properties_required */
1888 0, /* properties_provided */
1889 0, /* properties_destroyed */
1890 0, /* todo_flags_start */
1891 TODO_ggc_collect | TODO_verify_ssa, /* todo_flags_finish */
1892 0 /* letter */