PR libgomp/38270
[official-gcc.git] / gcc / predict.c
blobc6e933f510110a6b7adb2662267b2fcc3e7faea4
1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008
3 Free Software Foundation, Inc.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
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"
62 #include "pointer-set.h"
64 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
65 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
66 static sreal real_zero, real_one, real_almost_one, real_br_prob_base,
67 real_inv_br_prob_base, real_one_half, real_bb_freq_max;
69 /* Random guesstimation given names.
70 PROV_VERY_UNLIKELY should be small enough so basic block predicted
71 by it gets bellow HOT_BB_FREQUENCY_FRANCTION. */
72 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 2000 - 1)
73 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
74 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
75 #define PROB_ALWAYS (REG_BR_PROB_BASE)
77 static void combine_predictions_for_insn (rtx, basic_block);
78 static void dump_prediction (FILE *, enum br_predictor, int, basic_block, int);
79 static void predict_paths_leading_to (basic_block, enum br_predictor, enum prediction);
80 static void compute_function_frequency (void);
81 static void choose_function_section (void);
82 static bool can_predict_insn_p (const_rtx);
84 /* Information we hold about each branch predictor.
85 Filled using information from predict.def. */
87 struct predictor_info
89 const char *const name; /* Name used in the debugging dumps. */
90 const int hitrate; /* Expected hitrate used by
91 predict_insn_def call. */
92 const int flags;
95 /* Use given predictor without Dempster-Shaffer theory if it matches
96 using first_match heuristics. */
97 #define PRED_FLAG_FIRST_MATCH 1
99 /* Recompute hitrate in percent to our representation. */
101 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
103 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
104 static const struct predictor_info predictor_info[]= {
105 #include "predict.def"
107 /* Upper bound on predictors. */
108 {NULL, 0, 0}
110 #undef DEF_PREDICTOR
112 /* Return TRUE if frequency FREQ is considered to be hot. */
114 static inline bool
115 maybe_hot_frequency_p (int freq)
117 if (!profile_info || !flag_branch_probabilities)
119 if (cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
120 return false;
121 if (cfun->function_frequency == FUNCTION_FREQUENCY_HOT)
122 return true;
124 if (profile_status == PROFILE_ABSENT)
125 return true;
126 if (freq < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
127 return false;
128 return true;
131 /* Return TRUE if frequency FREQ is considered to be hot. */
133 static inline bool
134 maybe_hot_count_p (gcov_type count)
136 if (profile_status != PROFILE_READ)
137 return true;
138 /* Code executed at most once is not hot. */
139 if (profile_info->runs >= count)
140 return false;
141 return (count
142 > profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION));
145 /* Return true in case BB can be CPU intensive and should be optimized
146 for maximal performance. */
148 bool
149 maybe_hot_bb_p (const_basic_block bb)
151 if (profile_status == PROFILE_READ)
152 return maybe_hot_count_p (bb->count);
153 return maybe_hot_frequency_p (bb->frequency);
156 /* Return true if the call can be hot. */
158 bool
159 cgraph_maybe_hot_edge_p (struct cgraph_edge *edge)
161 if (profile_info && flag_branch_probabilities
162 && (edge->count
163 <= profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
164 return false;
165 if (lookup_attribute ("cold", DECL_ATTRIBUTES (edge->callee->decl))
166 || lookup_attribute ("cold", DECL_ATTRIBUTES (edge->caller->decl)))
167 return false;
168 if (lookup_attribute ("hot", DECL_ATTRIBUTES (edge->caller->decl)))
169 return true;
170 if (flag_guess_branch_prob
171 && edge->frequency < (CGRAPH_FREQ_MAX
172 / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION)))
173 return false;
174 return true;
177 /* Return true in case BB can be CPU intensive and should be optimized
178 for maximal performance. */
180 bool
181 maybe_hot_edge_p (edge e)
183 if (profile_status == PROFILE_READ)
184 return maybe_hot_count_p (e->count);
185 return maybe_hot_frequency_p (EDGE_FREQUENCY (e));
188 /* Return true in case BB is probably never executed. */
189 bool
190 probably_never_executed_bb_p (const_basic_block bb)
192 if (profile_info && flag_branch_probabilities)
193 return ((bb->count + profile_info->runs / 2) / profile_info->runs) == 0;
194 if ((!profile_info || !flag_branch_probabilities)
195 && cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
196 return true;
197 return false;
200 /* Return true when current function should always be optimized for size. */
202 bool
203 optimize_function_for_size_p (struct function *fun)
205 return (optimize_size
206 || (fun && (fun->function_frequency
207 == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)));
210 /* Return true when current function should always be optimized for speed. */
212 bool
213 optimize_function_for_speed_p (struct function *fun)
215 return !optimize_function_for_size_p (fun);
218 /* Return TRUE when BB should be optimized for size. */
220 bool
221 optimize_bb_for_size_p (const_basic_block bb)
223 return optimize_function_for_size_p (cfun) || !maybe_hot_bb_p (bb);
226 /* Return TRUE when BB should be optimized for speed. */
228 bool
229 optimize_bb_for_speed_p (const_basic_block bb)
231 return !optimize_bb_for_size_p (bb);
234 /* Return TRUE when BB should be optimized for size. */
236 bool
237 optimize_edge_for_size_p (edge e)
239 return optimize_function_for_size_p (cfun) || !maybe_hot_edge_p (e);
242 /* Return TRUE when BB should be optimized for speed. */
244 bool
245 optimize_edge_for_speed_p (edge e)
247 return !optimize_edge_for_size_p (e);
250 /* Return TRUE when BB should be optimized for size. */
252 bool
253 optimize_insn_for_size_p (void)
255 return optimize_function_for_size_p (cfun) || !crtl->maybe_hot_insn_p;
258 /* Return TRUE when BB should be optimized for speed. */
260 bool
261 optimize_insn_for_speed_p (void)
263 return !optimize_insn_for_size_p ();
266 /* Return TRUE when LOOP should be optimized for size. */
268 bool
269 optimize_loop_for_size_p (struct loop *loop)
271 return optimize_bb_for_size_p (loop->header);
274 /* Return TRUE when LOOP should be optimized for speed. */
276 bool
277 optimize_loop_for_speed_p (struct loop *loop)
279 return optimize_bb_for_speed_p (loop->header);
282 /* Return TRUE when LOOP nest should be optimized for speed. */
284 bool
285 optimize_loop_nest_for_speed_p (struct loop *loop)
287 struct loop *l = loop;
288 if (optimize_loop_for_speed_p (loop))
289 return true;
290 l = loop->inner;
291 while (l && l != loop)
293 if (optimize_loop_for_speed_p (l))
294 return true;
295 if (l->inner)
296 l = l->inner;
297 else if (l->next)
298 l = l->next;
299 else
301 while (l != loop && !l->next)
302 l = loop_outer (l);
303 if (l != loop)
304 l = l->next;
307 return false;
310 /* Return TRUE when LOOP nest should be optimized for size. */
312 bool
313 optimize_loop_nest_for_size_p (struct loop *loop)
315 return !optimize_loop_nest_for_speed_p (loop);
318 /* Return true when edge E is likely to be well predictable by branch
319 predictor. */
321 bool
322 predictable_edge_p (edge e)
324 if (profile_status == PROFILE_ABSENT)
325 return false;
326 if ((e->probability
327 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100)
328 || (REG_BR_PROB_BASE - e->probability
329 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100))
330 return true;
331 return false;
335 /* Set RTL expansion for BB profile. */
337 void
338 rtl_profile_for_bb (basic_block bb)
340 crtl->maybe_hot_insn_p = maybe_hot_bb_p (bb);
343 /* Set RTL expansion for edge profile. */
345 void
346 rtl_profile_for_edge (edge e)
348 crtl->maybe_hot_insn_p = maybe_hot_edge_p (e);
351 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
352 void
353 default_rtl_profile (void)
355 crtl->maybe_hot_insn_p = true;
358 /* Return true if the one of outgoing edges is already predicted by
359 PREDICTOR. */
361 bool
362 rtl_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
364 rtx note;
365 if (!INSN_P (BB_END (bb)))
366 return false;
367 for (note = REG_NOTES (BB_END (bb)); note; note = XEXP (note, 1))
368 if (REG_NOTE_KIND (note) == REG_BR_PRED
369 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
370 return true;
371 return false;
374 /* This map contains for a basic block the list of predictions for the
375 outgoing edges. */
377 static struct pointer_map_t *bb_predictions;
379 /* Return true if the one of outgoing edges is already predicted by
380 PREDICTOR. */
382 bool
383 gimple_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
385 struct edge_prediction *i;
386 void **preds = pointer_map_contains (bb_predictions, bb);
388 if (!preds)
389 return false;
391 for (i = (struct edge_prediction *) *preds; i; i = i->ep_next)
392 if (i->ep_predictor == predictor)
393 return true;
394 return false;
397 /* Return true when the probability of edge is reliable.
399 The profile guessing code is good at predicting branch outcome (ie.
400 taken/not taken), that is predicted right slightly over 75% of time.
401 It is however notoriously poor on predicting the probability itself.
402 In general the profile appear a lot flatter (with probabilities closer
403 to 50%) than the reality so it is bad idea to use it to drive optimization
404 such as those disabling dynamic branch prediction for well predictable
405 branches.
407 There are two exceptions - edges leading to noreturn edges and edges
408 predicted by number of iterations heuristics are predicted well. This macro
409 should be able to distinguish those, but at the moment it simply check for
410 noreturn heuristic that is only one giving probability over 99% or bellow
411 1%. In future we might want to propagate reliability information across the
412 CFG if we find this information useful on multiple places. */
413 static bool
414 probability_reliable_p (int prob)
416 return (profile_status == PROFILE_READ
417 || (profile_status == PROFILE_GUESSED
418 && (prob <= HITRATE (1) || prob >= HITRATE (99))));
421 /* Same predicate as above, working on edges. */
422 bool
423 edge_probability_reliable_p (const_edge e)
425 return probability_reliable_p (e->probability);
428 /* Same predicate as edge_probability_reliable_p, working on notes. */
429 bool
430 br_prob_note_reliable_p (const_rtx note)
432 gcc_assert (REG_NOTE_KIND (note) == REG_BR_PROB);
433 return probability_reliable_p (INTVAL (XEXP (note, 0)));
436 static void
437 predict_insn (rtx insn, enum br_predictor predictor, int probability)
439 gcc_assert (any_condjump_p (insn));
440 if (!flag_guess_branch_prob)
441 return;
443 add_reg_note (insn, REG_BR_PRED,
444 gen_rtx_CONCAT (VOIDmode,
445 GEN_INT ((int) predictor),
446 GEN_INT ((int) probability)));
449 /* Predict insn by given predictor. */
451 void
452 predict_insn_def (rtx insn, enum br_predictor predictor,
453 enum prediction taken)
455 int probability = predictor_info[(int) predictor].hitrate;
457 if (taken != TAKEN)
458 probability = REG_BR_PROB_BASE - probability;
460 predict_insn (insn, predictor, probability);
463 /* Predict edge E with given probability if possible. */
465 void
466 rtl_predict_edge (edge e, enum br_predictor predictor, int probability)
468 rtx last_insn;
469 last_insn = BB_END (e->src);
471 /* We can store the branch prediction information only about
472 conditional jumps. */
473 if (!any_condjump_p (last_insn))
474 return;
476 /* We always store probability of branching. */
477 if (e->flags & EDGE_FALLTHRU)
478 probability = REG_BR_PROB_BASE - probability;
480 predict_insn (last_insn, predictor, probability);
483 /* Predict edge E with the given PROBABILITY. */
484 void
485 gimple_predict_edge (edge e, enum br_predictor predictor, int probability)
487 gcc_assert (profile_status != PROFILE_GUESSED);
488 if ((e->src != ENTRY_BLOCK_PTR && EDGE_COUNT (e->src->succs) > 1)
489 && flag_guess_branch_prob && optimize)
491 struct edge_prediction *i = XNEW (struct edge_prediction);
492 void **preds = pointer_map_insert (bb_predictions, e->src);
494 i->ep_next = (struct edge_prediction *) *preds;
495 *preds = i;
496 i->ep_probability = probability;
497 i->ep_predictor = predictor;
498 i->ep_edge = e;
502 /* Remove all predictions on given basic block that are attached
503 to edge E. */
504 void
505 remove_predictions_associated_with_edge (edge e)
507 void **preds;
509 if (!bb_predictions)
510 return;
512 preds = pointer_map_contains (bb_predictions, e->src);
514 if (preds)
516 struct edge_prediction **prediction = (struct edge_prediction **) preds;
517 struct edge_prediction *next;
519 while (*prediction)
521 if ((*prediction)->ep_edge == e)
523 next = (*prediction)->ep_next;
524 free (*prediction);
525 *prediction = next;
527 else
528 prediction = &((*prediction)->ep_next);
533 /* Clears the list of predictions stored for BB. */
535 static void
536 clear_bb_predictions (basic_block bb)
538 void **preds = pointer_map_contains (bb_predictions, bb);
539 struct edge_prediction *pred, *next;
541 if (!preds)
542 return;
544 for (pred = (struct edge_prediction *) *preds; pred; pred = next)
546 next = pred->ep_next;
547 free (pred);
549 *preds = NULL;
552 /* Return true when we can store prediction on insn INSN.
553 At the moment we represent predictions only on conditional
554 jumps, not at computed jump or other complicated cases. */
555 static bool
556 can_predict_insn_p (const_rtx insn)
558 return (JUMP_P (insn)
559 && any_condjump_p (insn)
560 && EDGE_COUNT (BLOCK_FOR_INSN (insn)->succs) >= 2);
563 /* Predict edge E by given predictor if possible. */
565 void
566 predict_edge_def (edge e, enum br_predictor predictor,
567 enum prediction taken)
569 int probability = predictor_info[(int) predictor].hitrate;
571 if (taken != TAKEN)
572 probability = REG_BR_PROB_BASE - probability;
574 predict_edge (e, predictor, probability);
577 /* Invert all branch predictions or probability notes in the INSN. This needs
578 to be done each time we invert the condition used by the jump. */
580 void
581 invert_br_probabilities (rtx insn)
583 rtx note;
585 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
586 if (REG_NOTE_KIND (note) == REG_BR_PROB)
587 XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
588 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
589 XEXP (XEXP (note, 0), 1)
590 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
593 /* Dump information about the branch prediction to the output file. */
595 static void
596 dump_prediction (FILE *file, enum br_predictor predictor, int probability,
597 basic_block bb, int used)
599 edge e;
600 edge_iterator ei;
602 if (!file)
603 return;
605 FOR_EACH_EDGE (e, ei, bb->succs)
606 if (! (e->flags & EDGE_FALLTHRU))
607 break;
609 fprintf (file, " %s heuristics%s: %.1f%%",
610 predictor_info[predictor].name,
611 used ? "" : " (ignored)", probability * 100.0 / REG_BR_PROB_BASE);
613 if (bb->count)
615 fprintf (file, " exec ");
616 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, bb->count);
617 if (e)
619 fprintf (file, " hit ");
620 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, e->count);
621 fprintf (file, " (%.1f%%)", e->count * 100.0 / bb->count);
625 fprintf (file, "\n");
628 /* We can not predict the probabilities of outgoing edges of bb. Set them
629 evenly and hope for the best. */
630 static void
631 set_even_probabilities (basic_block bb)
633 int nedges = 0;
634 edge e;
635 edge_iterator ei;
637 FOR_EACH_EDGE (e, ei, bb->succs)
638 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
639 nedges ++;
640 FOR_EACH_EDGE (e, ei, bb->succs)
641 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
642 e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
643 else
644 e->probability = 0;
647 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
648 note if not already present. Remove now useless REG_BR_PRED notes. */
650 static void
651 combine_predictions_for_insn (rtx insn, basic_block bb)
653 rtx prob_note;
654 rtx *pnote;
655 rtx note;
656 int best_probability = PROB_EVEN;
657 int best_predictor = END_PREDICTORS;
658 int combined_probability = REG_BR_PROB_BASE / 2;
659 int d;
660 bool first_match = false;
661 bool found = false;
663 if (!can_predict_insn_p (insn))
665 set_even_probabilities (bb);
666 return;
669 prob_note = find_reg_note (insn, REG_BR_PROB, 0);
670 pnote = &REG_NOTES (insn);
671 if (dump_file)
672 fprintf (dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
673 bb->index);
675 /* We implement "first match" heuristics and use probability guessed
676 by predictor with smallest index. */
677 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
678 if (REG_NOTE_KIND (note) == REG_BR_PRED)
680 int predictor = INTVAL (XEXP (XEXP (note, 0), 0));
681 int probability = INTVAL (XEXP (XEXP (note, 0), 1));
683 found = true;
684 if (best_predictor > predictor)
685 best_probability = probability, best_predictor = predictor;
687 d = (combined_probability * probability
688 + (REG_BR_PROB_BASE - combined_probability)
689 * (REG_BR_PROB_BASE - probability));
691 /* Use FP math to avoid overflows of 32bit integers. */
692 if (d == 0)
693 /* If one probability is 0% and one 100%, avoid division by zero. */
694 combined_probability = REG_BR_PROB_BASE / 2;
695 else
696 combined_probability = (((double) combined_probability) * probability
697 * REG_BR_PROB_BASE / d + 0.5);
700 /* Decide which heuristic to use. In case we didn't match anything,
701 use no_prediction heuristic, in case we did match, use either
702 first match or Dempster-Shaffer theory depending on the flags. */
704 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
705 first_match = true;
707 if (!found)
708 dump_prediction (dump_file, PRED_NO_PREDICTION,
709 combined_probability, bb, true);
710 else
712 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability,
713 bb, !first_match);
714 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability,
715 bb, first_match);
718 if (first_match)
719 combined_probability = best_probability;
720 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
722 while (*pnote)
724 if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
726 int predictor = INTVAL (XEXP (XEXP (*pnote, 0), 0));
727 int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
729 dump_prediction (dump_file, predictor, probability, bb,
730 !first_match || best_predictor == predictor);
731 *pnote = XEXP (*pnote, 1);
733 else
734 pnote = &XEXP (*pnote, 1);
737 if (!prob_note)
739 add_reg_note (insn, REG_BR_PROB, GEN_INT (combined_probability));
741 /* Save the prediction into CFG in case we are seeing non-degenerated
742 conditional jump. */
743 if (!single_succ_p (bb))
745 BRANCH_EDGE (bb)->probability = combined_probability;
746 FALLTHRU_EDGE (bb)->probability
747 = REG_BR_PROB_BASE - combined_probability;
750 else if (!single_succ_p (bb))
752 int prob = INTVAL (XEXP (prob_note, 0));
754 BRANCH_EDGE (bb)->probability = prob;
755 FALLTHRU_EDGE (bb)->probability = REG_BR_PROB_BASE - prob;
757 else
758 single_succ_edge (bb)->probability = REG_BR_PROB_BASE;
761 /* Combine predictions into single probability and store them into CFG.
762 Remove now useless prediction entries. */
764 static void
765 combine_predictions_for_bb (basic_block bb)
767 int best_probability = PROB_EVEN;
768 int best_predictor = END_PREDICTORS;
769 int combined_probability = REG_BR_PROB_BASE / 2;
770 int d;
771 bool first_match = false;
772 bool found = false;
773 struct edge_prediction *pred;
774 int nedges = 0;
775 edge e, first = NULL, second = NULL;
776 edge_iterator ei;
777 void **preds;
779 FOR_EACH_EDGE (e, ei, bb->succs)
780 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
782 nedges ++;
783 if (first && !second)
784 second = e;
785 if (!first)
786 first = e;
789 /* When there is no successor or only one choice, prediction is easy.
791 We are lazy for now and predict only basic blocks with two outgoing
792 edges. It is possible to predict generic case too, but we have to
793 ignore first match heuristics and do more involved combining. Implement
794 this later. */
795 if (nedges != 2)
797 if (!bb->count)
798 set_even_probabilities (bb);
799 clear_bb_predictions (bb);
800 if (dump_file)
801 fprintf (dump_file, "%i edges in bb %i predicted to even probabilities\n",
802 nedges, bb->index);
803 return;
806 if (dump_file)
807 fprintf (dump_file, "Predictions for bb %i\n", bb->index);
809 preds = pointer_map_contains (bb_predictions, bb);
810 if (preds)
812 /* We implement "first match" heuristics and use probability guessed
813 by predictor with smallest index. */
814 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
816 int predictor = pred->ep_predictor;
817 int probability = pred->ep_probability;
819 if (pred->ep_edge != first)
820 probability = REG_BR_PROB_BASE - probability;
822 found = true;
823 if (best_predictor > predictor)
824 best_probability = probability, best_predictor = predictor;
826 d = (combined_probability * probability
827 + (REG_BR_PROB_BASE - combined_probability)
828 * (REG_BR_PROB_BASE - probability));
830 /* Use FP math to avoid overflows of 32bit integers. */
831 if (d == 0)
832 /* If one probability is 0% and one 100%, avoid division by zero. */
833 combined_probability = REG_BR_PROB_BASE / 2;
834 else
835 combined_probability = (((double) combined_probability)
836 * probability
837 * REG_BR_PROB_BASE / d + 0.5);
841 /* Decide which heuristic to use. In case we didn't match anything,
842 use no_prediction heuristic, in case we did match, use either
843 first match or Dempster-Shaffer theory depending on the flags. */
845 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
846 first_match = true;
848 if (!found)
849 dump_prediction (dump_file, PRED_NO_PREDICTION, combined_probability, bb, true);
850 else
852 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability, bb,
853 !first_match);
854 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability, bb,
855 first_match);
858 if (first_match)
859 combined_probability = best_probability;
860 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
862 if (preds)
864 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
866 int predictor = pred->ep_predictor;
867 int probability = pred->ep_probability;
869 if (pred->ep_edge != EDGE_SUCC (bb, 0))
870 probability = REG_BR_PROB_BASE - probability;
871 dump_prediction (dump_file, predictor, probability, bb,
872 !first_match || best_predictor == predictor);
875 clear_bb_predictions (bb);
877 if (!bb->count)
879 first->probability = combined_probability;
880 second->probability = REG_BR_PROB_BASE - combined_probability;
884 /* Predict edge probabilities by exploiting loop structure. */
886 static void
887 predict_loops (void)
889 loop_iterator li;
890 struct loop *loop;
892 scev_initialize ();
894 /* Try to predict out blocks in a loop that are not part of a
895 natural loop. */
896 FOR_EACH_LOOP (li, loop, 0)
898 basic_block bb, *bbs;
899 unsigned j, n_exits;
900 VEC (edge, heap) *exits;
901 struct tree_niter_desc niter_desc;
902 edge ex;
904 exits = get_loop_exit_edges (loop);
905 n_exits = VEC_length (edge, exits);
907 for (j = 0; VEC_iterate (edge, exits, j, ex); j++)
909 tree niter = NULL;
910 HOST_WIDE_INT nitercst;
911 int max = PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS);
912 int probability;
913 enum br_predictor predictor;
915 if (number_of_iterations_exit (loop, ex, &niter_desc, false))
916 niter = niter_desc.niter;
917 if (!niter || TREE_CODE (niter_desc.niter) != INTEGER_CST)
918 niter = loop_niter_by_eval (loop, ex);
920 if (TREE_CODE (niter) == INTEGER_CST)
922 if (host_integerp (niter, 1)
923 && compare_tree_int (niter, max-1) == -1)
924 nitercst = tree_low_cst (niter, 1) + 1;
925 else
926 nitercst = max;
927 predictor = PRED_LOOP_ITERATIONS;
929 /* If we have just one exit and we can derive some information about
930 the number of iterations of the loop from the statements inside
931 the loop, use it to predict this exit. */
932 else if (n_exits == 1)
934 nitercst = estimated_loop_iterations_int (loop, false);
935 if (nitercst < 0)
936 continue;
937 if (nitercst > max)
938 nitercst = max;
940 predictor = PRED_LOOP_ITERATIONS_GUESSED;
942 else
943 continue;
945 probability = ((REG_BR_PROB_BASE + nitercst / 2) / nitercst);
946 predict_edge (ex, predictor, probability);
948 VEC_free (edge, heap, exits);
950 bbs = get_loop_body (loop);
952 for (j = 0; j < loop->num_nodes; j++)
954 int header_found = 0;
955 edge e;
956 edge_iterator ei;
958 bb = bbs[j];
960 /* Bypass loop heuristics on continue statement. These
961 statements construct loops via "non-loop" constructs
962 in the source language and are better to be handled
963 separately. */
964 if (predicted_by_p (bb, PRED_CONTINUE))
965 continue;
967 /* Loop branch heuristics - predict an edge back to a
968 loop's head as taken. */
969 if (bb == loop->latch)
971 e = find_edge (loop->latch, loop->header);
972 if (e)
974 header_found = 1;
975 predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
979 /* Loop exit heuristics - predict an edge exiting the loop if the
980 conditional has no loop header successors as not taken. */
981 if (!header_found
982 /* If we already used more reliable loop exit predictors, do not
983 bother with PRED_LOOP_EXIT. */
984 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS_GUESSED)
985 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS))
987 /* For loop with many exits we don't want to predict all exits
988 with the pretty large probability, because if all exits are
989 considered in row, the loop would be predicted to iterate
990 almost never. The code to divide probability by number of
991 exits is very rough. It should compute the number of exits
992 taken in each patch through function (not the overall number
993 of exits that might be a lot higher for loops with wide switch
994 statements in them) and compute n-th square root.
996 We limit the minimal probability by 2% to avoid
997 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
998 as this was causing regression in perl benchmark containing such
999 a wide loop. */
1001 int probability = ((REG_BR_PROB_BASE
1002 - predictor_info [(int) PRED_LOOP_EXIT].hitrate)
1003 / n_exits);
1004 if (probability < HITRATE (2))
1005 probability = HITRATE (2);
1006 FOR_EACH_EDGE (e, ei, bb->succs)
1007 if (e->dest->index < NUM_FIXED_BLOCKS
1008 || !flow_bb_inside_loop_p (loop, e->dest))
1009 predict_edge (e, PRED_LOOP_EXIT, probability);
1013 /* Free basic blocks from get_loop_body. */
1014 free (bbs);
1017 scev_finalize ();
1020 /* Attempt to predict probabilities of BB outgoing edges using local
1021 properties. */
1022 static void
1023 bb_estimate_probability_locally (basic_block bb)
1025 rtx last_insn = BB_END (bb);
1026 rtx cond;
1028 if (! can_predict_insn_p (last_insn))
1029 return;
1030 cond = get_condition (last_insn, NULL, false, false);
1031 if (! cond)
1032 return;
1034 /* Try "pointer heuristic."
1035 A comparison ptr == 0 is predicted as false.
1036 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1037 if (COMPARISON_P (cond)
1038 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
1039 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
1041 if (GET_CODE (cond) == EQ)
1042 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
1043 else if (GET_CODE (cond) == NE)
1044 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
1046 else
1048 /* Try "opcode heuristic."
1049 EQ tests are usually false and NE tests are usually true. Also,
1050 most quantities are positive, so we can make the appropriate guesses
1051 about signed comparisons against zero. */
1052 switch (GET_CODE (cond))
1054 case CONST_INT:
1055 /* Unconditional branch. */
1056 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
1057 cond == const0_rtx ? NOT_TAKEN : TAKEN);
1058 break;
1060 case EQ:
1061 case UNEQ:
1062 /* Floating point comparisons appears to behave in a very
1063 unpredictable way because of special role of = tests in
1064 FP code. */
1065 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
1067 /* Comparisons with 0 are often used for booleans and there is
1068 nothing useful to predict about them. */
1069 else if (XEXP (cond, 1) == const0_rtx
1070 || XEXP (cond, 0) == const0_rtx)
1072 else
1073 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
1074 break;
1076 case NE:
1077 case LTGT:
1078 /* Floating point comparisons appears to behave in a very
1079 unpredictable way because of special role of = tests in
1080 FP code. */
1081 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
1083 /* Comparisons with 0 are often used for booleans and there is
1084 nothing useful to predict about them. */
1085 else if (XEXP (cond, 1) == const0_rtx
1086 || XEXP (cond, 0) == const0_rtx)
1088 else
1089 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
1090 break;
1092 case ORDERED:
1093 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
1094 break;
1096 case UNORDERED:
1097 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
1098 break;
1100 case LE:
1101 case LT:
1102 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1103 || XEXP (cond, 1) == constm1_rtx)
1104 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
1105 break;
1107 case GE:
1108 case GT:
1109 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1110 || XEXP (cond, 1) == constm1_rtx)
1111 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
1112 break;
1114 default:
1115 break;
1119 /* Set edge->probability for each successor edge of BB. */
1120 void
1121 guess_outgoing_edge_probabilities (basic_block bb)
1123 bb_estimate_probability_locally (bb);
1124 combine_predictions_for_insn (BB_END (bb), bb);
1127 static tree expr_expected_value (tree, bitmap);
1129 /* Helper function for expr_expected_value. */
1131 static tree
1132 expr_expected_value_1 (tree type, tree op0, enum tree_code code, tree op1, bitmap visited)
1134 gimple def;
1136 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1138 if (TREE_CONSTANT (op0))
1139 return op0;
1141 if (code != SSA_NAME)
1142 return NULL_TREE;
1144 def = SSA_NAME_DEF_STMT (op0);
1146 /* If we were already here, break the infinite cycle. */
1147 if (bitmap_bit_p (visited, SSA_NAME_VERSION (op0)))
1148 return NULL;
1149 bitmap_set_bit (visited, SSA_NAME_VERSION (op0));
1151 if (gimple_code (def) == GIMPLE_PHI)
1153 /* All the arguments of the PHI node must have the same constant
1154 length. */
1155 int i, n = gimple_phi_num_args (def);
1156 tree val = NULL, new_val;
1158 for (i = 0; i < n; i++)
1160 tree arg = PHI_ARG_DEF (def, i);
1162 /* If this PHI has itself as an argument, we cannot
1163 determine the string length of this argument. However,
1164 if we can find an expected constant value for the other
1165 PHI args then we can still be sure that this is
1166 likely a constant. So be optimistic and just
1167 continue with the next argument. */
1168 if (arg == PHI_RESULT (def))
1169 continue;
1171 new_val = expr_expected_value (arg, visited);
1172 if (!new_val)
1173 return NULL;
1174 if (!val)
1175 val = new_val;
1176 else if (!operand_equal_p (val, new_val, false))
1177 return NULL;
1179 return val;
1181 if (is_gimple_assign (def))
1183 if (gimple_assign_lhs (def) != op0)
1184 return NULL;
1186 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def)),
1187 gimple_assign_rhs1 (def),
1188 gimple_assign_rhs_code (def),
1189 gimple_assign_rhs2 (def),
1190 visited);
1193 if (is_gimple_call (def))
1195 tree decl = gimple_call_fndecl (def);
1196 if (!decl)
1197 return NULL;
1198 if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
1199 && DECL_FUNCTION_CODE (decl) == BUILT_IN_EXPECT)
1201 tree val;
1203 if (gimple_call_num_args (def) != 2)
1204 return NULL;
1205 val = gimple_call_arg (def, 0);
1206 if (TREE_CONSTANT (val))
1207 return val;
1208 return gimple_call_arg (def, 1);
1212 return NULL;
1215 if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS)
1217 tree res;
1218 op0 = expr_expected_value (op0, visited);
1219 if (!op0)
1220 return NULL;
1221 op1 = expr_expected_value (op1, visited);
1222 if (!op1)
1223 return NULL;
1224 res = fold_build2 (code, type, op0, op1);
1225 if (TREE_CONSTANT (res))
1226 return res;
1227 return NULL;
1229 if (get_gimple_rhs_class (code) == GIMPLE_UNARY_RHS)
1231 tree res;
1232 op0 = expr_expected_value (op0, visited);
1233 if (!op0)
1234 return NULL;
1235 res = fold_build1 (code, type, op0);
1236 if (TREE_CONSTANT (res))
1237 return res;
1238 return NULL;
1240 return NULL;
1243 /* Return constant EXPR will likely have at execution time, NULL if unknown.
1244 The function is used by builtin_expect branch predictor so the evidence
1245 must come from this construct and additional possible constant folding.
1247 We may want to implement more involved value guess (such as value range
1248 propagation based prediction), but such tricks shall go to new
1249 implementation. */
1251 static tree
1252 expr_expected_value (tree expr, bitmap visited)
1254 enum tree_code code;
1255 tree op0, op1;
1257 if (TREE_CONSTANT (expr))
1258 return expr;
1260 extract_ops_from_tree (expr, &code, &op0, &op1);
1261 return expr_expected_value_1 (TREE_TYPE (expr),
1262 op0, code, op1, visited);
1266 /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
1267 we no longer need. */
1268 static unsigned int
1269 strip_predict_hints (void)
1271 basic_block bb;
1272 gimple ass_stmt;
1273 tree var;
1275 FOR_EACH_BB (bb)
1277 gimple_stmt_iterator bi;
1278 for (bi = gsi_start_bb (bb); !gsi_end_p (bi);)
1280 gimple stmt = gsi_stmt (bi);
1282 if (gimple_code (stmt) == GIMPLE_PREDICT)
1284 gsi_remove (&bi, true);
1285 continue;
1287 else if (gimple_code (stmt) == GIMPLE_CALL)
1289 tree fndecl = gimple_call_fndecl (stmt);
1291 if (fndecl
1292 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1293 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT
1294 && gimple_call_num_args (stmt) == 2)
1296 var = gimple_call_lhs (stmt);
1297 ass_stmt = gimple_build_assign (var, gimple_call_arg (stmt, 0));
1299 gsi_replace (&bi, ass_stmt, true);
1302 gsi_next (&bi);
1305 return 0;
1308 /* Predict using opcode of the last statement in basic block. */
1309 static void
1310 tree_predict_by_opcode (basic_block bb)
1312 gimple stmt = last_stmt (bb);
1313 edge then_edge;
1314 tree op0, op1;
1315 tree type;
1316 tree val;
1317 enum tree_code cmp;
1318 bitmap visited;
1319 edge_iterator ei;
1321 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
1322 return;
1323 FOR_EACH_EDGE (then_edge, ei, bb->succs)
1324 if (then_edge->flags & EDGE_TRUE_VALUE)
1325 break;
1326 op0 = gimple_cond_lhs (stmt);
1327 op1 = gimple_cond_rhs (stmt);
1328 cmp = gimple_cond_code (stmt);
1329 type = TREE_TYPE (op0);
1330 visited = BITMAP_ALLOC (NULL);
1331 val = expr_expected_value_1 (boolean_type_node, op0, cmp, op1, visited);
1332 BITMAP_FREE (visited);
1333 if (val)
1335 if (integer_zerop (val))
1336 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, NOT_TAKEN);
1337 else
1338 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, TAKEN);
1339 return;
1341 /* Try "pointer heuristic."
1342 A comparison ptr == 0 is predicted as false.
1343 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1344 if (POINTER_TYPE_P (type))
1346 if (cmp == EQ_EXPR)
1347 predict_edge_def (then_edge, PRED_TREE_POINTER, NOT_TAKEN);
1348 else if (cmp == NE_EXPR)
1349 predict_edge_def (then_edge, PRED_TREE_POINTER, TAKEN);
1351 else
1353 /* Try "opcode heuristic."
1354 EQ tests are usually false and NE tests are usually true. Also,
1355 most quantities are positive, so we can make the appropriate guesses
1356 about signed comparisons against zero. */
1357 switch (cmp)
1359 case EQ_EXPR:
1360 case UNEQ_EXPR:
1361 /* Floating point comparisons appears to behave in a very
1362 unpredictable way because of special role of = tests in
1363 FP code. */
1364 if (FLOAT_TYPE_P (type))
1366 /* Comparisons with 0 are often used for booleans and there is
1367 nothing useful to predict about them. */
1368 else if (integer_zerop (op0) || integer_zerop (op1))
1370 else
1371 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, NOT_TAKEN);
1372 break;
1374 case NE_EXPR:
1375 case LTGT_EXPR:
1376 /* Floating point comparisons appears to behave in a very
1377 unpredictable way because of special role of = tests in
1378 FP code. */
1379 if (FLOAT_TYPE_P (type))
1381 /* Comparisons with 0 are often used for booleans and there is
1382 nothing useful to predict about them. */
1383 else if (integer_zerop (op0)
1384 || integer_zerop (op1))
1386 else
1387 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, TAKEN);
1388 break;
1390 case ORDERED_EXPR:
1391 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, TAKEN);
1392 break;
1394 case UNORDERED_EXPR:
1395 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, NOT_TAKEN);
1396 break;
1398 case LE_EXPR:
1399 case LT_EXPR:
1400 if (integer_zerop (op1)
1401 || integer_onep (op1)
1402 || integer_all_onesp (op1)
1403 || real_zerop (op1)
1404 || real_onep (op1)
1405 || real_minus_onep (op1))
1406 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, NOT_TAKEN);
1407 break;
1409 case GE_EXPR:
1410 case GT_EXPR:
1411 if (integer_zerop (op1)
1412 || integer_onep (op1)
1413 || integer_all_onesp (op1)
1414 || real_zerop (op1)
1415 || real_onep (op1)
1416 || real_minus_onep (op1))
1417 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, TAKEN);
1418 break;
1420 default:
1421 break;
1425 /* Try to guess whether the value of return means error code. */
1427 static enum br_predictor
1428 return_prediction (tree val, enum prediction *prediction)
1430 /* VOID. */
1431 if (!val)
1432 return PRED_NO_PREDICTION;
1433 /* Different heuristics for pointers and scalars. */
1434 if (POINTER_TYPE_P (TREE_TYPE (val)))
1436 /* NULL is usually not returned. */
1437 if (integer_zerop (val))
1439 *prediction = NOT_TAKEN;
1440 return PRED_NULL_RETURN;
1443 else if (INTEGRAL_TYPE_P (TREE_TYPE (val)))
1445 /* Negative return values are often used to indicate
1446 errors. */
1447 if (TREE_CODE (val) == INTEGER_CST
1448 && tree_int_cst_sgn (val) < 0)
1450 *prediction = NOT_TAKEN;
1451 return PRED_NEGATIVE_RETURN;
1453 /* Constant return values seems to be commonly taken.
1454 Zero/one often represent booleans so exclude them from the
1455 heuristics. */
1456 if (TREE_CONSTANT (val)
1457 && (!integer_zerop (val) && !integer_onep (val)))
1459 *prediction = TAKEN;
1460 return PRED_CONST_RETURN;
1463 return PRED_NO_PREDICTION;
1466 /* Find the basic block with return expression and look up for possible
1467 return value trying to apply RETURN_PREDICTION heuristics. */
1468 static void
1469 apply_return_prediction (void)
1471 gimple return_stmt = NULL;
1472 tree return_val;
1473 edge e;
1474 gimple phi;
1475 int phi_num_args, i;
1476 enum br_predictor pred;
1477 enum prediction direction;
1478 edge_iterator ei;
1480 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
1482 return_stmt = last_stmt (e->src);
1483 if (return_stmt
1484 && gimple_code (return_stmt) == GIMPLE_RETURN)
1485 break;
1487 if (!e)
1488 return;
1489 return_val = gimple_return_retval (return_stmt);
1490 if (!return_val)
1491 return;
1492 if (TREE_CODE (return_val) != SSA_NAME
1493 || !SSA_NAME_DEF_STMT (return_val)
1494 || gimple_code (SSA_NAME_DEF_STMT (return_val)) != GIMPLE_PHI)
1495 return;
1496 phi = SSA_NAME_DEF_STMT (return_val);
1497 phi_num_args = gimple_phi_num_args (phi);
1498 pred = return_prediction (PHI_ARG_DEF (phi, 0), &direction);
1500 /* Avoid the degenerate case where all return values form the function
1501 belongs to same category (ie they are all positive constants)
1502 so we can hardly say something about them. */
1503 for (i = 1; i < phi_num_args; i++)
1504 if (pred != return_prediction (PHI_ARG_DEF (phi, i), &direction))
1505 break;
1506 if (i != phi_num_args)
1507 for (i = 0; i < phi_num_args; i++)
1509 pred = return_prediction (PHI_ARG_DEF (phi, i), &direction);
1510 if (pred != PRED_NO_PREDICTION)
1511 predict_paths_leading_to (gimple_phi_arg_edge (phi, i)->src, pred,
1512 direction);
1516 /* Look for basic block that contains unlikely to happen events
1517 (such as noreturn calls) and mark all paths leading to execution
1518 of this basic blocks as unlikely. */
1520 static void
1521 tree_bb_level_predictions (void)
1523 basic_block bb;
1525 apply_return_prediction ();
1527 FOR_EACH_BB (bb)
1529 gimple_stmt_iterator gsi;
1531 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1533 gimple stmt = gsi_stmt (gsi);
1534 tree decl;
1536 if (is_gimple_call (stmt))
1538 if (gimple_call_flags (stmt) & ECF_NORETURN)
1539 predict_paths_leading_to (bb, PRED_NORETURN,
1540 NOT_TAKEN);
1541 decl = gimple_call_fndecl (stmt);
1542 if (decl
1543 && lookup_attribute ("cold",
1544 DECL_ATTRIBUTES (decl)))
1545 predict_paths_leading_to (bb, PRED_COLD_FUNCTION,
1546 NOT_TAKEN);
1548 else if (gimple_code (stmt) == GIMPLE_PREDICT)
1550 predict_paths_leading_to (bb, gimple_predict_predictor (stmt),
1551 gimple_predict_outcome (stmt));
1552 /* Keep GIMPLE_PREDICT around so early inlining will propagate
1553 hints to callers. */
1559 #ifdef ENABLE_CHECKING
1561 /* Callback for pointer_map_traverse, asserts that the pointer map is
1562 empty. */
1564 static bool
1565 assert_is_empty (const void *key ATTRIBUTE_UNUSED, void **value,
1566 void *data ATTRIBUTE_UNUSED)
1568 gcc_assert (!*value);
1569 return false;
1571 #endif
1573 /* Predict branch probabilities and estimate profile of the tree CFG. */
1574 static unsigned int
1575 tree_estimate_probability (void)
1577 basic_block bb;
1579 loop_optimizer_init (0);
1580 if (dump_file && (dump_flags & TDF_DETAILS))
1581 flow_loops_dump (dump_file, NULL, 0);
1583 add_noreturn_fake_exit_edges ();
1584 connect_infinite_loops_to_exit ();
1585 /* We use loop_niter_by_eval, which requires that the loops have
1586 preheaders. */
1587 create_preheaders (CP_SIMPLE_PREHEADERS);
1588 calculate_dominance_info (CDI_POST_DOMINATORS);
1590 bb_predictions = pointer_map_create ();
1591 tree_bb_level_predictions ();
1593 mark_irreducible_loops ();
1594 record_loop_exits ();
1595 if (number_of_loops () > 1)
1596 predict_loops ();
1598 FOR_EACH_BB (bb)
1600 edge e;
1601 edge_iterator ei;
1602 gimple last;
1604 FOR_EACH_EDGE (e, ei, bb->succs)
1606 /* Predict early returns to be probable, as we've already taken
1607 care for error returns and other cases are often used for
1608 fast paths through function.
1610 Since we've already removed the return statements, we are
1611 looking for CFG like:
1613 if (conditional)
1616 goto return_block
1618 some other blocks
1619 return_block:
1620 return_stmt. */
1621 if (e->dest != bb->next_bb
1622 && e->dest != EXIT_BLOCK_PTR
1623 && single_succ_p (e->dest)
1624 && single_succ_edge (e->dest)->dest == EXIT_BLOCK_PTR
1625 && (last = last_stmt (e->dest)) != NULL
1626 && gimple_code (last) == GIMPLE_RETURN)
1628 edge e1;
1629 edge_iterator ei1;
1631 if (single_succ_p (bb))
1633 FOR_EACH_EDGE (e1, ei1, bb->preds)
1634 if (!predicted_by_p (e1->src, PRED_NULL_RETURN)
1635 && !predicted_by_p (e1->src, PRED_CONST_RETURN)
1636 && !predicted_by_p (e1->src, PRED_NEGATIVE_RETURN))
1637 predict_edge_def (e1, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
1639 else
1640 if (!predicted_by_p (e->src, PRED_NULL_RETURN)
1641 && !predicted_by_p (e->src, PRED_CONST_RETURN)
1642 && !predicted_by_p (e->src, PRED_NEGATIVE_RETURN))
1643 predict_edge_def (e, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
1646 /* Look for block we are guarding (ie we dominate it,
1647 but it doesn't postdominate us). */
1648 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
1649 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
1650 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
1652 gimple_stmt_iterator bi;
1654 /* The call heuristic claims that a guarded function call
1655 is improbable. This is because such calls are often used
1656 to signal exceptional situations such as printing error
1657 messages. */
1658 for (bi = gsi_start_bb (e->dest); !gsi_end_p (bi);
1659 gsi_next (&bi))
1661 gimple stmt = gsi_stmt (bi);
1662 if (is_gimple_call (stmt)
1663 /* Constant and pure calls are hardly used to signalize
1664 something exceptional. */
1665 && gimple_has_side_effects (stmt))
1667 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
1668 break;
1673 tree_predict_by_opcode (bb);
1675 FOR_EACH_BB (bb)
1676 combine_predictions_for_bb (bb);
1678 #ifdef ENABLE_CHECKING
1679 pointer_map_traverse (bb_predictions, assert_is_empty, NULL);
1680 #endif
1681 pointer_map_destroy (bb_predictions);
1682 bb_predictions = NULL;
1684 estimate_bb_frequencies ();
1685 free_dominance_info (CDI_POST_DOMINATORS);
1686 remove_fake_exit_edges ();
1687 loop_optimizer_finalize ();
1688 if (dump_file && (dump_flags & TDF_DETAILS))
1689 gimple_dump_cfg (dump_file, dump_flags);
1690 if (profile_status == PROFILE_ABSENT)
1691 profile_status = PROFILE_GUESSED;
1692 return 0;
1695 /* Predict edges to successors of CUR whose sources are not postdominated by
1696 BB by PRED and recurse to all postdominators. */
1698 static void
1699 predict_paths_for_bb (basic_block cur, basic_block bb,
1700 enum br_predictor pred,
1701 enum prediction taken)
1703 edge e;
1704 edge_iterator ei;
1705 basic_block son;
1707 /* We are looking for all edges forming edge cut induced by
1708 set of all blocks postdominated by BB. */
1709 FOR_EACH_EDGE (e, ei, cur->preds)
1710 if (e->src->index >= NUM_FIXED_BLOCKS
1711 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, bb))
1713 gcc_assert (bb == cur || dominated_by_p (CDI_POST_DOMINATORS, cur, bb));
1714 predict_edge_def (e, pred, taken);
1716 for (son = first_dom_son (CDI_POST_DOMINATORS, cur);
1717 son;
1718 son = next_dom_son (CDI_POST_DOMINATORS, son))
1719 predict_paths_for_bb (son, bb, pred, taken);
1722 /* Sets branch probabilities according to PREDiction and
1723 FLAGS. */
1725 static void
1726 predict_paths_leading_to (basic_block bb, enum br_predictor pred,
1727 enum prediction taken)
1729 predict_paths_for_bb (bb, bb, pred, taken);
1732 /* This is used to carry information about basic blocks. It is
1733 attached to the AUX field of the standard CFG block. */
1735 typedef struct block_info_def
1737 /* Estimated frequency of execution of basic_block. */
1738 sreal frequency;
1740 /* To keep queue of basic blocks to process. */
1741 basic_block next;
1743 /* Number of predecessors we need to visit first. */
1744 int npredecessors;
1745 } *block_info;
1747 /* Similar information for edges. */
1748 typedef struct edge_info_def
1750 /* In case edge is a loopback edge, the probability edge will be reached
1751 in case header is. Estimated number of iterations of the loop can be
1752 then computed as 1 / (1 - back_edge_prob). */
1753 sreal back_edge_prob;
1754 /* True if the edge is a loopback edge in the natural loop. */
1755 unsigned int back_edge:1;
1756 } *edge_info;
1758 #define BLOCK_INFO(B) ((block_info) (B)->aux)
1759 #define EDGE_INFO(E) ((edge_info) (E)->aux)
1761 /* Helper function for estimate_bb_frequencies.
1762 Propagate the frequencies in blocks marked in
1763 TOVISIT, starting in HEAD. */
1765 static void
1766 propagate_freq (basic_block head, bitmap tovisit)
1768 basic_block bb;
1769 basic_block last;
1770 unsigned i;
1771 edge e;
1772 basic_block nextbb;
1773 bitmap_iterator bi;
1775 /* For each basic block we need to visit count number of his predecessors
1776 we need to visit first. */
1777 EXECUTE_IF_SET_IN_BITMAP (tovisit, 0, i, bi)
1779 edge_iterator ei;
1780 int count = 0;
1782 /* The outermost "loop" includes the exit block, which we can not
1783 look up via BASIC_BLOCK. Detect this and use EXIT_BLOCK_PTR
1784 directly. Do the same for the entry block. */
1785 bb = BASIC_BLOCK (i);
1787 FOR_EACH_EDGE (e, ei, bb->preds)
1789 bool visit = bitmap_bit_p (tovisit, e->src->index);
1791 if (visit && !(e->flags & EDGE_DFS_BACK))
1792 count++;
1793 else if (visit && dump_file && !EDGE_INFO (e)->back_edge)
1794 fprintf (dump_file,
1795 "Irreducible region hit, ignoring edge to %i->%i\n",
1796 e->src->index, bb->index);
1798 BLOCK_INFO (bb)->npredecessors = count;
1801 memcpy (&BLOCK_INFO (head)->frequency, &real_one, sizeof (real_one));
1802 last = head;
1803 for (bb = head; bb; bb = nextbb)
1805 edge_iterator ei;
1806 sreal cyclic_probability, frequency;
1808 memcpy (&cyclic_probability, &real_zero, sizeof (real_zero));
1809 memcpy (&frequency, &real_zero, sizeof (real_zero));
1811 nextbb = BLOCK_INFO (bb)->next;
1812 BLOCK_INFO (bb)->next = NULL;
1814 /* Compute frequency of basic block. */
1815 if (bb != head)
1817 #ifdef ENABLE_CHECKING
1818 FOR_EACH_EDGE (e, ei, bb->preds)
1819 gcc_assert (!bitmap_bit_p (tovisit, e->src->index)
1820 || (e->flags & EDGE_DFS_BACK));
1821 #endif
1823 FOR_EACH_EDGE (e, ei, bb->preds)
1824 if (EDGE_INFO (e)->back_edge)
1826 sreal_add (&cyclic_probability, &cyclic_probability,
1827 &EDGE_INFO (e)->back_edge_prob);
1829 else if (!(e->flags & EDGE_DFS_BACK))
1831 sreal tmp;
1833 /* frequency += (e->probability
1834 * BLOCK_INFO (e->src)->frequency /
1835 REG_BR_PROB_BASE); */
1837 sreal_init (&tmp, e->probability, 0);
1838 sreal_mul (&tmp, &tmp, &BLOCK_INFO (e->src)->frequency);
1839 sreal_mul (&tmp, &tmp, &real_inv_br_prob_base);
1840 sreal_add (&frequency, &frequency, &tmp);
1843 if (sreal_compare (&cyclic_probability, &real_zero) == 0)
1845 memcpy (&BLOCK_INFO (bb)->frequency, &frequency,
1846 sizeof (frequency));
1848 else
1850 if (sreal_compare (&cyclic_probability, &real_almost_one) > 0)
1852 memcpy (&cyclic_probability, &real_almost_one,
1853 sizeof (real_almost_one));
1856 /* BLOCK_INFO (bb)->frequency = frequency
1857 / (1 - cyclic_probability) */
1859 sreal_sub (&cyclic_probability, &real_one, &cyclic_probability);
1860 sreal_div (&BLOCK_INFO (bb)->frequency,
1861 &frequency, &cyclic_probability);
1865 bitmap_clear_bit (tovisit, bb->index);
1867 e = find_edge (bb, head);
1868 if (e)
1870 sreal tmp;
1872 /* EDGE_INFO (e)->back_edge_prob
1873 = ((e->probability * BLOCK_INFO (bb)->frequency)
1874 / REG_BR_PROB_BASE); */
1876 sreal_init (&tmp, e->probability, 0);
1877 sreal_mul (&tmp, &tmp, &BLOCK_INFO (bb)->frequency);
1878 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
1879 &tmp, &real_inv_br_prob_base);
1882 /* Propagate to successor blocks. */
1883 FOR_EACH_EDGE (e, ei, bb->succs)
1884 if (!(e->flags & EDGE_DFS_BACK)
1885 && BLOCK_INFO (e->dest)->npredecessors)
1887 BLOCK_INFO (e->dest)->npredecessors--;
1888 if (!BLOCK_INFO (e->dest)->npredecessors)
1890 if (!nextbb)
1891 nextbb = e->dest;
1892 else
1893 BLOCK_INFO (last)->next = e->dest;
1895 last = e->dest;
1901 /* Estimate probabilities of loopback edges in loops at same nest level. */
1903 static void
1904 estimate_loops_at_level (struct loop *first_loop)
1906 struct loop *loop;
1908 for (loop = first_loop; loop; loop = loop->next)
1910 edge e;
1911 basic_block *bbs;
1912 unsigned i;
1913 bitmap tovisit = BITMAP_ALLOC (NULL);
1915 estimate_loops_at_level (loop->inner);
1917 /* Find current loop back edge and mark it. */
1918 e = loop_latch_edge (loop);
1919 EDGE_INFO (e)->back_edge = 1;
1921 bbs = get_loop_body (loop);
1922 for (i = 0; i < loop->num_nodes; i++)
1923 bitmap_set_bit (tovisit, bbs[i]->index);
1924 free (bbs);
1925 propagate_freq (loop->header, tovisit);
1926 BITMAP_FREE (tovisit);
1930 /* Propagates frequencies through structure of loops. */
1932 static void
1933 estimate_loops (void)
1935 bitmap tovisit = BITMAP_ALLOC (NULL);
1936 basic_block bb;
1938 /* Start by estimating the frequencies in the loops. */
1939 if (number_of_loops () > 1)
1940 estimate_loops_at_level (current_loops->tree_root->inner);
1942 /* Now propagate the frequencies through all the blocks. */
1943 FOR_ALL_BB (bb)
1945 bitmap_set_bit (tovisit, bb->index);
1947 propagate_freq (ENTRY_BLOCK_PTR, tovisit);
1948 BITMAP_FREE (tovisit);
1951 /* Convert counts measured by profile driven feedback to frequencies.
1952 Return nonzero iff there was any nonzero execution count. */
1955 counts_to_freqs (void)
1957 gcov_type count_max, true_count_max = 0;
1958 basic_block bb;
1960 FOR_EACH_BB (bb)
1961 true_count_max = MAX (bb->count, true_count_max);
1963 count_max = MAX (true_count_max, 1);
1964 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1965 bb->frequency = (bb->count * BB_FREQ_MAX + count_max / 2) / count_max;
1967 return true_count_max;
1970 /* Return true if function is likely to be expensive, so there is no point to
1971 optimize performance of prologue, epilogue or do inlining at the expense
1972 of code size growth. THRESHOLD is the limit of number of instructions
1973 function can execute at average to be still considered not expensive. */
1975 bool
1976 expensive_function_p (int threshold)
1978 unsigned int sum = 0;
1979 basic_block bb;
1980 unsigned int limit;
1982 /* We can not compute accurately for large thresholds due to scaled
1983 frequencies. */
1984 gcc_assert (threshold <= BB_FREQ_MAX);
1986 /* Frequencies are out of range. This either means that function contains
1987 internal loop executing more than BB_FREQ_MAX times or profile feedback
1988 is available and function has not been executed at all. */
1989 if (ENTRY_BLOCK_PTR->frequency == 0)
1990 return true;
1992 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
1993 limit = ENTRY_BLOCK_PTR->frequency * threshold;
1994 FOR_EACH_BB (bb)
1996 rtx insn;
1998 for (insn = BB_HEAD (bb); insn != NEXT_INSN (BB_END (bb));
1999 insn = NEXT_INSN (insn))
2000 if (active_insn_p (insn))
2002 sum += bb->frequency;
2003 if (sum > limit)
2004 return true;
2008 return false;
2011 /* Estimate basic blocks frequency by given branch probabilities. */
2013 void
2014 estimate_bb_frequencies (void)
2016 basic_block bb;
2017 sreal freq_max;
2019 if (cfun->function_frequency != PROFILE_READ || !counts_to_freqs ())
2021 static int real_values_initialized = 0;
2023 if (!real_values_initialized)
2025 real_values_initialized = 1;
2026 sreal_init (&real_zero, 0, 0);
2027 sreal_init (&real_one, 1, 0);
2028 sreal_init (&real_br_prob_base, REG_BR_PROB_BASE, 0);
2029 sreal_init (&real_bb_freq_max, BB_FREQ_MAX, 0);
2030 sreal_init (&real_one_half, 1, -1);
2031 sreal_div (&real_inv_br_prob_base, &real_one, &real_br_prob_base);
2032 sreal_sub (&real_almost_one, &real_one, &real_inv_br_prob_base);
2035 mark_dfs_back_edges ();
2037 single_succ_edge (ENTRY_BLOCK_PTR)->probability = REG_BR_PROB_BASE;
2039 /* Set up block info for each basic block. */
2040 alloc_aux_for_blocks (sizeof (struct block_info_def));
2041 alloc_aux_for_edges (sizeof (struct edge_info_def));
2042 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2044 edge e;
2045 edge_iterator ei;
2047 FOR_EACH_EDGE (e, ei, bb->succs)
2049 sreal_init (&EDGE_INFO (e)->back_edge_prob, e->probability, 0);
2050 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
2051 &EDGE_INFO (e)->back_edge_prob,
2052 &real_inv_br_prob_base);
2056 /* First compute probabilities locally for each loop from innermost
2057 to outermost to examine probabilities for back edges. */
2058 estimate_loops ();
2060 memcpy (&freq_max, &real_zero, sizeof (real_zero));
2061 FOR_EACH_BB (bb)
2062 if (sreal_compare (&freq_max, &BLOCK_INFO (bb)->frequency) < 0)
2063 memcpy (&freq_max, &BLOCK_INFO (bb)->frequency, sizeof (freq_max));
2065 sreal_div (&freq_max, &real_bb_freq_max, &freq_max);
2066 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2068 sreal tmp;
2070 sreal_mul (&tmp, &BLOCK_INFO (bb)->frequency, &freq_max);
2071 sreal_add (&tmp, &tmp, &real_one_half);
2072 bb->frequency = sreal_to_int (&tmp);
2075 free_aux_for_blocks ();
2076 free_aux_for_edges ();
2078 compute_function_frequency ();
2079 if (flag_reorder_functions)
2080 choose_function_section ();
2083 /* Decide whether function is hot, cold or unlikely executed. */
2084 static void
2085 compute_function_frequency (void)
2087 basic_block bb;
2089 if (!profile_info || !flag_branch_probabilities)
2091 if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl))
2092 != NULL)
2093 cfun->function_frequency = FUNCTION_FREQUENCY_UNLIKELY_EXECUTED;
2094 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl))
2095 != NULL)
2096 cfun->function_frequency = FUNCTION_FREQUENCY_HOT;
2097 return;
2099 cfun->function_frequency = FUNCTION_FREQUENCY_UNLIKELY_EXECUTED;
2100 FOR_EACH_BB (bb)
2102 if (maybe_hot_bb_p (bb))
2104 cfun->function_frequency = FUNCTION_FREQUENCY_HOT;
2105 return;
2107 if (!probably_never_executed_bb_p (bb))
2108 cfun->function_frequency = FUNCTION_FREQUENCY_NORMAL;
2112 /* Choose appropriate section for the function. */
2113 static void
2114 choose_function_section (void)
2116 if (DECL_SECTION_NAME (current_function_decl)
2117 || !targetm.have_named_sections
2118 /* Theoretically we can split the gnu.linkonce text section too,
2119 but this requires more work as the frequency needs to match
2120 for all generated objects so we need to merge the frequency
2121 of all instances. For now just never set frequency for these. */
2122 || DECL_ONE_ONLY (current_function_decl))
2123 return;
2125 /* If we are doing the partitioning optimization, let the optimization
2126 choose the correct section into which to put things. */
2128 if (flag_reorder_blocks_and_partition)
2129 return;
2131 if (cfun->function_frequency == FUNCTION_FREQUENCY_HOT)
2132 DECL_SECTION_NAME (current_function_decl) =
2133 build_string (strlen (HOT_TEXT_SECTION_NAME), HOT_TEXT_SECTION_NAME);
2134 if (cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
2135 DECL_SECTION_NAME (current_function_decl) =
2136 build_string (strlen (UNLIKELY_EXECUTED_TEXT_SECTION_NAME),
2137 UNLIKELY_EXECUTED_TEXT_SECTION_NAME);
2140 static bool
2141 gate_estimate_probability (void)
2143 return flag_guess_branch_prob;
2146 /* Build PREDICT_EXPR. */
2147 tree
2148 build_predict_expr (enum br_predictor predictor, enum prediction taken)
2150 tree t = build1 (PREDICT_EXPR, void_type_node,
2151 build_int_cst (NULL, predictor));
2152 PREDICT_EXPR_OUTCOME (t) = taken;
2153 return t;
2156 const char *
2157 predictor_name (enum br_predictor predictor)
2159 return predictor_info[predictor].name;
2162 struct gimple_opt_pass pass_profile =
2165 GIMPLE_PASS,
2166 "profile", /* name */
2167 gate_estimate_probability, /* gate */
2168 tree_estimate_probability, /* execute */
2169 NULL, /* sub */
2170 NULL, /* next */
2171 0, /* static_pass_number */
2172 TV_BRANCH_PROB, /* tv_id */
2173 PROP_cfg, /* properties_required */
2174 0, /* properties_provided */
2175 0, /* properties_destroyed */
2176 0, /* todo_flags_start */
2177 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
2181 struct gimple_opt_pass pass_strip_predict_hints =
2184 GIMPLE_PASS,
2185 NULL, /* name */
2186 NULL, /* gate */
2187 strip_predict_hints, /* execute */
2188 NULL, /* sub */
2189 NULL, /* next */
2190 0, /* static_pass_number */
2191 TV_BRANCH_PROB, /* tv_id */
2192 PROP_cfg, /* properties_required */
2193 0, /* properties_provided */
2194 0, /* properties_destroyed */
2195 0, /* todo_flags_start */
2196 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */