2011-11-04 Tom de Vries <tom@codesourcery.com>
[official-gcc.git] / gcc / predict.c
blobeeca172ce45f245fb7349b4a91e21c9da5b17e1a
1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009, 2010
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 "diagnostic-core.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 predict_paths_leading_to_edge (edge, enum br_predictor, enum prediction);
81 static bool can_predict_insn_p (const_rtx);
83 /* Information we hold about each branch predictor.
84 Filled using information from predict.def. */
86 struct predictor_info
88 const char *const name; /* Name used in the debugging dumps. */
89 const int hitrate; /* Expected hitrate used by
90 predict_insn_def call. */
91 const int flags;
94 /* Use given predictor without Dempster-Shaffer theory if it matches
95 using first_match heuristics. */
96 #define PRED_FLAG_FIRST_MATCH 1
98 /* Recompute hitrate in percent to our representation. */
100 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
102 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
103 static const struct predictor_info predictor_info[]= {
104 #include "predict.def"
106 /* Upper bound on predictors. */
107 {NULL, 0, 0}
109 #undef DEF_PREDICTOR
111 /* Return TRUE if frequency FREQ is considered to be hot. */
113 static inline bool
114 maybe_hot_frequency_p (int freq)
116 struct cgraph_node *node = cgraph_get_node (current_function_decl);
117 if (!profile_info || !flag_branch_probabilities)
119 if (node->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED)
120 return false;
121 if (node->frequency == NODE_FREQUENCY_HOT)
122 return true;
124 if (profile_status == PROFILE_ABSENT)
125 return true;
126 if (node->frequency == NODE_FREQUENCY_EXECUTED_ONCE
127 && freq < (ENTRY_BLOCK_PTR->frequency * 2 / 3))
128 return false;
129 if (freq < ENTRY_BLOCK_PTR->frequency / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
130 return false;
131 return true;
134 /* Return TRUE if frequency FREQ is considered to be hot. */
136 static inline bool
137 maybe_hot_count_p (gcov_type count)
139 if (profile_status != PROFILE_READ)
140 return true;
141 /* Code executed at most once is not hot. */
142 if (profile_info->runs >= count)
143 return false;
144 return (count
145 > profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION));
148 /* Return true in case BB can be CPU intensive and should be optimized
149 for maximal performance. */
151 bool
152 maybe_hot_bb_p (const_basic_block bb)
154 if (profile_status == PROFILE_READ)
155 return maybe_hot_count_p (bb->count);
156 return maybe_hot_frequency_p (bb->frequency);
159 /* Return true if the call can be hot. */
161 bool
162 cgraph_maybe_hot_edge_p (struct cgraph_edge *edge)
164 if (profile_info && flag_branch_probabilities
165 && (edge->count
166 <= profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
167 return false;
168 if (edge->caller->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED
169 || edge->callee->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED)
170 return false;
171 if (edge->caller->frequency > NODE_FREQUENCY_UNLIKELY_EXECUTED
172 && edge->callee->frequency <= NODE_FREQUENCY_EXECUTED_ONCE)
173 return false;
174 if (optimize_size)
175 return false;
176 if (edge->caller->frequency == NODE_FREQUENCY_HOT)
177 return true;
178 if (edge->caller->frequency == NODE_FREQUENCY_EXECUTED_ONCE
179 && edge->frequency < CGRAPH_FREQ_BASE * 3 / 2)
180 return false;
181 if (flag_guess_branch_prob
182 && edge->frequency <= (CGRAPH_FREQ_BASE
183 / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION)))
184 return false;
185 return true;
188 /* Return true in case BB can be CPU intensive and should be optimized
189 for maximal performance. */
191 bool
192 maybe_hot_edge_p (edge e)
194 if (profile_status == PROFILE_READ)
195 return maybe_hot_count_p (e->count);
196 return maybe_hot_frequency_p (EDGE_FREQUENCY (e));
200 /* Return true in case BB is probably never executed. */
202 bool
203 probably_never_executed_bb_p (const_basic_block bb)
205 if (profile_info && flag_branch_probabilities)
206 return ((bb->count + profile_info->runs / 2) / profile_info->runs) == 0;
207 if ((!profile_info || !flag_branch_probabilities)
208 && (cgraph_get_node (current_function_decl)->frequency
209 == NODE_FREQUENCY_UNLIKELY_EXECUTED))
210 return true;
211 return false;
214 /* Return true if NODE should be optimized for size. */
216 bool
217 cgraph_optimize_for_size_p (struct cgraph_node *node)
219 if (optimize_size)
220 return true;
221 if (node && (node->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED))
222 return true;
223 else
224 return false;
227 /* Return true when current function should always be optimized for size. */
229 bool
230 optimize_function_for_size_p (struct function *fun)
232 if (optimize_size)
233 return true;
234 if (!fun || !fun->decl)
235 return false;
236 return cgraph_optimize_for_size_p (cgraph_get_node (fun->decl));
239 /* Return true when current function should always be optimized for speed. */
241 bool
242 optimize_function_for_speed_p (struct function *fun)
244 return !optimize_function_for_size_p (fun);
247 /* Return TRUE when BB should be optimized for size. */
249 bool
250 optimize_bb_for_size_p (const_basic_block bb)
252 return optimize_function_for_size_p (cfun) || !maybe_hot_bb_p (bb);
255 /* Return TRUE when BB should be optimized for speed. */
257 bool
258 optimize_bb_for_speed_p (const_basic_block bb)
260 return !optimize_bb_for_size_p (bb);
263 /* Return TRUE when BB should be optimized for size. */
265 bool
266 optimize_edge_for_size_p (edge e)
268 return optimize_function_for_size_p (cfun) || !maybe_hot_edge_p (e);
271 /* Return TRUE when BB should be optimized for speed. */
273 bool
274 optimize_edge_for_speed_p (edge e)
276 return !optimize_edge_for_size_p (e);
279 /* Return TRUE when BB should be optimized for size. */
281 bool
282 optimize_insn_for_size_p (void)
284 return optimize_function_for_size_p (cfun) || !crtl->maybe_hot_insn_p;
287 /* Return TRUE when BB should be optimized for speed. */
289 bool
290 optimize_insn_for_speed_p (void)
292 return !optimize_insn_for_size_p ();
295 /* Return TRUE when LOOP should be optimized for size. */
297 bool
298 optimize_loop_for_size_p (struct loop *loop)
300 return optimize_bb_for_size_p (loop->header);
303 /* Return TRUE when LOOP should be optimized for speed. */
305 bool
306 optimize_loop_for_speed_p (struct loop *loop)
308 return optimize_bb_for_speed_p (loop->header);
311 /* Return TRUE when LOOP nest should be optimized for speed. */
313 bool
314 optimize_loop_nest_for_speed_p (struct loop *loop)
316 struct loop *l = loop;
317 if (optimize_loop_for_speed_p (loop))
318 return true;
319 l = loop->inner;
320 while (l && l != loop)
322 if (optimize_loop_for_speed_p (l))
323 return true;
324 if (l->inner)
325 l = l->inner;
326 else if (l->next)
327 l = l->next;
328 else
330 while (l != loop && !l->next)
331 l = loop_outer (l);
332 if (l != loop)
333 l = l->next;
336 return false;
339 /* Return TRUE when LOOP nest should be optimized for size. */
341 bool
342 optimize_loop_nest_for_size_p (struct loop *loop)
344 return !optimize_loop_nest_for_speed_p (loop);
347 /* Return true when edge E is likely to be well predictable by branch
348 predictor. */
350 bool
351 predictable_edge_p (edge e)
353 if (profile_status == PROFILE_ABSENT)
354 return false;
355 if ((e->probability
356 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100)
357 || (REG_BR_PROB_BASE - e->probability
358 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100))
359 return true;
360 return false;
364 /* Set RTL expansion for BB profile. */
366 void
367 rtl_profile_for_bb (basic_block bb)
369 crtl->maybe_hot_insn_p = maybe_hot_bb_p (bb);
372 /* Set RTL expansion for edge profile. */
374 void
375 rtl_profile_for_edge (edge e)
377 crtl->maybe_hot_insn_p = maybe_hot_edge_p (e);
380 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
381 void
382 default_rtl_profile (void)
384 crtl->maybe_hot_insn_p = true;
387 /* Return true if the one of outgoing edges is already predicted by
388 PREDICTOR. */
390 bool
391 rtl_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
393 rtx note;
394 if (!INSN_P (BB_END (bb)))
395 return false;
396 for (note = REG_NOTES (BB_END (bb)); note; note = XEXP (note, 1))
397 if (REG_NOTE_KIND (note) == REG_BR_PRED
398 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
399 return true;
400 return false;
403 /* This map contains for a basic block the list of predictions for the
404 outgoing edges. */
406 static struct pointer_map_t *bb_predictions;
408 /* Structure representing predictions in tree level. */
410 struct edge_prediction {
411 struct edge_prediction *ep_next;
412 edge ep_edge;
413 enum br_predictor ep_predictor;
414 int ep_probability;
417 /* Return true if the one of outgoing edges is already predicted by
418 PREDICTOR. */
420 bool
421 gimple_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
423 struct edge_prediction *i;
424 void **preds = pointer_map_contains (bb_predictions, bb);
426 if (!preds)
427 return false;
429 for (i = (struct edge_prediction *) *preds; i; i = i->ep_next)
430 if (i->ep_predictor == predictor)
431 return true;
432 return false;
435 /* Return true when the probability of edge is reliable.
437 The profile guessing code is good at predicting branch outcome (ie.
438 taken/not taken), that is predicted right slightly over 75% of time.
439 It is however notoriously poor on predicting the probability itself.
440 In general the profile appear a lot flatter (with probabilities closer
441 to 50%) than the reality so it is bad idea to use it to drive optimization
442 such as those disabling dynamic branch prediction for well predictable
443 branches.
445 There are two exceptions - edges leading to noreturn edges and edges
446 predicted by number of iterations heuristics are predicted well. This macro
447 should be able to distinguish those, but at the moment it simply check for
448 noreturn heuristic that is only one giving probability over 99% or bellow
449 1%. In future we might want to propagate reliability information across the
450 CFG if we find this information useful on multiple places. */
451 static bool
452 probability_reliable_p (int prob)
454 return (profile_status == PROFILE_READ
455 || (profile_status == PROFILE_GUESSED
456 && (prob <= HITRATE (1) || prob >= HITRATE (99))));
459 /* Same predicate as above, working on edges. */
460 bool
461 edge_probability_reliable_p (const_edge e)
463 return probability_reliable_p (e->probability);
466 /* Same predicate as edge_probability_reliable_p, working on notes. */
467 bool
468 br_prob_note_reliable_p (const_rtx note)
470 gcc_assert (REG_NOTE_KIND (note) == REG_BR_PROB);
471 return probability_reliable_p (INTVAL (XEXP (note, 0)));
474 static void
475 predict_insn (rtx insn, enum br_predictor predictor, int probability)
477 gcc_assert (any_condjump_p (insn));
478 if (!flag_guess_branch_prob)
479 return;
481 add_reg_note (insn, REG_BR_PRED,
482 gen_rtx_CONCAT (VOIDmode,
483 GEN_INT ((int) predictor),
484 GEN_INT ((int) probability)));
487 /* Predict insn by given predictor. */
489 void
490 predict_insn_def (rtx insn, enum br_predictor predictor,
491 enum prediction taken)
493 int probability = predictor_info[(int) predictor].hitrate;
495 if (taken != TAKEN)
496 probability = REG_BR_PROB_BASE - probability;
498 predict_insn (insn, predictor, probability);
501 /* Predict edge E with given probability if possible. */
503 void
504 rtl_predict_edge (edge e, enum br_predictor predictor, int probability)
506 rtx last_insn;
507 last_insn = BB_END (e->src);
509 /* We can store the branch prediction information only about
510 conditional jumps. */
511 if (!any_condjump_p (last_insn))
512 return;
514 /* We always store probability of branching. */
515 if (e->flags & EDGE_FALLTHRU)
516 probability = REG_BR_PROB_BASE - probability;
518 predict_insn (last_insn, predictor, probability);
521 /* Predict edge E with the given PROBABILITY. */
522 void
523 gimple_predict_edge (edge e, enum br_predictor predictor, int probability)
525 gcc_assert (profile_status != PROFILE_GUESSED);
526 if ((e->src != ENTRY_BLOCK_PTR && EDGE_COUNT (e->src->succs) > 1)
527 && flag_guess_branch_prob && optimize)
529 struct edge_prediction *i = XNEW (struct edge_prediction);
530 void **preds = pointer_map_insert (bb_predictions, e->src);
532 i->ep_next = (struct edge_prediction *) *preds;
533 *preds = i;
534 i->ep_probability = probability;
535 i->ep_predictor = predictor;
536 i->ep_edge = e;
540 /* Remove all predictions on given basic block that are attached
541 to edge E. */
542 void
543 remove_predictions_associated_with_edge (edge e)
545 void **preds;
547 if (!bb_predictions)
548 return;
550 preds = pointer_map_contains (bb_predictions, e->src);
552 if (preds)
554 struct edge_prediction **prediction = (struct edge_prediction **) preds;
555 struct edge_prediction *next;
557 while (*prediction)
559 if ((*prediction)->ep_edge == e)
561 next = (*prediction)->ep_next;
562 free (*prediction);
563 *prediction = next;
565 else
566 prediction = &((*prediction)->ep_next);
571 /* Clears the list of predictions stored for BB. */
573 static void
574 clear_bb_predictions (basic_block bb)
576 void **preds = pointer_map_contains (bb_predictions, bb);
577 struct edge_prediction *pred, *next;
579 if (!preds)
580 return;
582 for (pred = (struct edge_prediction *) *preds; pred; pred = next)
584 next = pred->ep_next;
585 free (pred);
587 *preds = NULL;
590 /* Return true when we can store prediction on insn INSN.
591 At the moment we represent predictions only on conditional
592 jumps, not at computed jump or other complicated cases. */
593 static bool
594 can_predict_insn_p (const_rtx insn)
596 return (JUMP_P (insn)
597 && any_condjump_p (insn)
598 && EDGE_COUNT (BLOCK_FOR_INSN (insn)->succs) >= 2);
601 /* Predict edge E by given predictor if possible. */
603 void
604 predict_edge_def (edge e, enum br_predictor predictor,
605 enum prediction taken)
607 int probability = predictor_info[(int) predictor].hitrate;
609 if (taken != TAKEN)
610 probability = REG_BR_PROB_BASE - probability;
612 predict_edge (e, predictor, probability);
615 /* Invert all branch predictions or probability notes in the INSN. This needs
616 to be done each time we invert the condition used by the jump. */
618 void
619 invert_br_probabilities (rtx insn)
621 rtx note;
623 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
624 if (REG_NOTE_KIND (note) == REG_BR_PROB)
625 XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
626 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
627 XEXP (XEXP (note, 0), 1)
628 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
631 /* Dump information about the branch prediction to the output file. */
633 static void
634 dump_prediction (FILE *file, enum br_predictor predictor, int probability,
635 basic_block bb, int used)
637 edge e;
638 edge_iterator ei;
640 if (!file)
641 return;
643 FOR_EACH_EDGE (e, ei, bb->succs)
644 if (! (e->flags & EDGE_FALLTHRU))
645 break;
647 fprintf (file, " %s heuristics%s: %.1f%%",
648 predictor_info[predictor].name,
649 used ? "" : " (ignored)", probability * 100.0 / REG_BR_PROB_BASE);
651 if (bb->count)
653 fprintf (file, " exec ");
654 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, bb->count);
655 if (e)
657 fprintf (file, " hit ");
658 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, e->count);
659 fprintf (file, " (%.1f%%)", e->count * 100.0 / bb->count);
663 fprintf (file, "\n");
666 /* We can not predict the probabilities of outgoing edges of bb. Set them
667 evenly and hope for the best. */
668 static void
669 set_even_probabilities (basic_block bb)
671 int nedges = 0;
672 edge e;
673 edge_iterator ei;
675 FOR_EACH_EDGE (e, ei, bb->succs)
676 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
677 nedges ++;
678 FOR_EACH_EDGE (e, ei, bb->succs)
679 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
680 e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
681 else
682 e->probability = 0;
685 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
686 note if not already present. Remove now useless REG_BR_PRED notes. */
688 static void
689 combine_predictions_for_insn (rtx insn, basic_block bb)
691 rtx prob_note;
692 rtx *pnote;
693 rtx note;
694 int best_probability = PROB_EVEN;
695 enum br_predictor best_predictor = END_PREDICTORS;
696 int combined_probability = REG_BR_PROB_BASE / 2;
697 int d;
698 bool first_match = false;
699 bool found = false;
701 if (!can_predict_insn_p (insn))
703 set_even_probabilities (bb);
704 return;
707 prob_note = find_reg_note (insn, REG_BR_PROB, 0);
708 pnote = &REG_NOTES (insn);
709 if (dump_file)
710 fprintf (dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
711 bb->index);
713 /* We implement "first match" heuristics and use probability guessed
714 by predictor with smallest index. */
715 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
716 if (REG_NOTE_KIND (note) == REG_BR_PRED)
718 enum br_predictor predictor = ((enum br_predictor)
719 INTVAL (XEXP (XEXP (note, 0), 0)));
720 int probability = INTVAL (XEXP (XEXP (note, 0), 1));
722 found = true;
723 if (best_predictor > predictor)
724 best_probability = probability, best_predictor = predictor;
726 d = (combined_probability * probability
727 + (REG_BR_PROB_BASE - combined_probability)
728 * (REG_BR_PROB_BASE - probability));
730 /* Use FP math to avoid overflows of 32bit integers. */
731 if (d == 0)
732 /* If one probability is 0% and one 100%, avoid division by zero. */
733 combined_probability = REG_BR_PROB_BASE / 2;
734 else
735 combined_probability = (((double) combined_probability) * probability
736 * REG_BR_PROB_BASE / d + 0.5);
739 /* Decide which heuristic to use. In case we didn't match anything,
740 use no_prediction heuristic, in case we did match, use either
741 first match or Dempster-Shaffer theory depending on the flags. */
743 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
744 first_match = true;
746 if (!found)
747 dump_prediction (dump_file, PRED_NO_PREDICTION,
748 combined_probability, bb, true);
749 else
751 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability,
752 bb, !first_match);
753 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability,
754 bb, first_match);
757 if (first_match)
758 combined_probability = best_probability;
759 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
761 while (*pnote)
763 if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
765 enum br_predictor predictor = ((enum br_predictor)
766 INTVAL (XEXP (XEXP (*pnote, 0), 0)));
767 int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
769 dump_prediction (dump_file, predictor, probability, bb,
770 !first_match || best_predictor == predictor);
771 *pnote = XEXP (*pnote, 1);
773 else
774 pnote = &XEXP (*pnote, 1);
777 if (!prob_note)
779 add_reg_note (insn, REG_BR_PROB, GEN_INT (combined_probability));
781 /* Save the prediction into CFG in case we are seeing non-degenerated
782 conditional jump. */
783 if (!single_succ_p (bb))
785 BRANCH_EDGE (bb)->probability = combined_probability;
786 FALLTHRU_EDGE (bb)->probability
787 = REG_BR_PROB_BASE - combined_probability;
790 else if (!single_succ_p (bb))
792 int prob = INTVAL (XEXP (prob_note, 0));
794 BRANCH_EDGE (bb)->probability = prob;
795 FALLTHRU_EDGE (bb)->probability = REG_BR_PROB_BASE - prob;
797 else
798 single_succ_edge (bb)->probability = REG_BR_PROB_BASE;
801 /* Combine predictions into single probability and store them into CFG.
802 Remove now useless prediction entries. */
804 static void
805 combine_predictions_for_bb (basic_block bb)
807 int best_probability = PROB_EVEN;
808 enum br_predictor best_predictor = END_PREDICTORS;
809 int combined_probability = REG_BR_PROB_BASE / 2;
810 int d;
811 bool first_match = false;
812 bool found = false;
813 struct edge_prediction *pred;
814 int nedges = 0;
815 edge e, first = NULL, second = NULL;
816 edge_iterator ei;
817 void **preds;
819 FOR_EACH_EDGE (e, ei, bb->succs)
820 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
822 nedges ++;
823 if (first && !second)
824 second = e;
825 if (!first)
826 first = e;
829 /* When there is no successor or only one choice, prediction is easy.
831 We are lazy for now and predict only basic blocks with two outgoing
832 edges. It is possible to predict generic case too, but we have to
833 ignore first match heuristics and do more involved combining. Implement
834 this later. */
835 if (nedges != 2)
837 if (!bb->count)
838 set_even_probabilities (bb);
839 clear_bb_predictions (bb);
840 if (dump_file)
841 fprintf (dump_file, "%i edges in bb %i predicted to even probabilities\n",
842 nedges, bb->index);
843 return;
846 if (dump_file)
847 fprintf (dump_file, "Predictions for bb %i\n", bb->index);
849 preds = pointer_map_contains (bb_predictions, bb);
850 if (preds)
852 /* We implement "first match" heuristics and use probability guessed
853 by predictor with smallest index. */
854 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
856 enum br_predictor predictor = pred->ep_predictor;
857 int probability = pred->ep_probability;
859 if (pred->ep_edge != first)
860 probability = REG_BR_PROB_BASE - probability;
862 found = true;
863 /* First match heuristics would be widly confused if we predicted
864 both directions. */
865 if (best_predictor > predictor)
867 struct edge_prediction *pred2;
868 int prob = probability;
870 for (pred2 = (struct edge_prediction *) *preds; pred2; pred2 = pred2->ep_next)
871 if (pred2 != pred && pred2->ep_predictor == pred->ep_predictor)
873 int probability2 = pred->ep_probability;
875 if (pred2->ep_edge != first)
876 probability2 = REG_BR_PROB_BASE - probability2;
878 if ((probability < REG_BR_PROB_BASE / 2) !=
879 (probability2 < REG_BR_PROB_BASE / 2))
880 break;
882 /* If the same predictor later gave better result, go for it! */
883 if ((probability >= REG_BR_PROB_BASE / 2 && (probability2 > probability))
884 || (probability <= REG_BR_PROB_BASE / 2 && (probability2 < probability)))
885 prob = probability2;
887 if (!pred2)
888 best_probability = prob, best_predictor = predictor;
891 d = (combined_probability * probability
892 + (REG_BR_PROB_BASE - combined_probability)
893 * (REG_BR_PROB_BASE - probability));
895 /* Use FP math to avoid overflows of 32bit integers. */
896 if (d == 0)
897 /* If one probability is 0% and one 100%, avoid division by zero. */
898 combined_probability = REG_BR_PROB_BASE / 2;
899 else
900 combined_probability = (((double) combined_probability)
901 * probability
902 * REG_BR_PROB_BASE / d + 0.5);
906 /* Decide which heuristic to use. In case we didn't match anything,
907 use no_prediction heuristic, in case we did match, use either
908 first match or Dempster-Shaffer theory depending on the flags. */
910 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
911 first_match = true;
913 if (!found)
914 dump_prediction (dump_file, PRED_NO_PREDICTION, combined_probability, bb, true);
915 else
917 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability, bb,
918 !first_match);
919 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability, bb,
920 first_match);
923 if (first_match)
924 combined_probability = best_probability;
925 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
927 if (preds)
929 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
931 enum br_predictor predictor = pred->ep_predictor;
932 int probability = pred->ep_probability;
934 if (pred->ep_edge != EDGE_SUCC (bb, 0))
935 probability = REG_BR_PROB_BASE - probability;
936 dump_prediction (dump_file, predictor, probability, bb,
937 !first_match || best_predictor == predictor);
940 clear_bb_predictions (bb);
942 if (!bb->count)
944 first->probability = combined_probability;
945 second->probability = REG_BR_PROB_BASE - combined_probability;
949 /* Predict edge probabilities by exploiting loop structure. */
951 static void
952 predict_loops (void)
954 loop_iterator li;
955 struct loop *loop;
957 /* Try to predict out blocks in a loop that are not part of a
958 natural loop. */
959 FOR_EACH_LOOP (li, loop, 0)
961 basic_block bb, *bbs;
962 unsigned j, n_exits;
963 VEC (edge, heap) *exits;
964 struct tree_niter_desc niter_desc;
965 edge ex;
967 exits = get_loop_exit_edges (loop);
968 n_exits = VEC_length (edge, exits);
970 FOR_EACH_VEC_ELT (edge, exits, j, ex)
972 tree niter = NULL;
973 HOST_WIDE_INT nitercst;
974 int max = PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS);
975 int probability;
976 enum br_predictor predictor;
978 if (number_of_iterations_exit (loop, ex, &niter_desc, false))
979 niter = niter_desc.niter;
980 if (!niter || TREE_CODE (niter_desc.niter) != INTEGER_CST)
981 niter = loop_niter_by_eval (loop, ex);
983 if (TREE_CODE (niter) == INTEGER_CST)
985 if (host_integerp (niter, 1)
986 && compare_tree_int (niter, max-1) == -1)
987 nitercst = tree_low_cst (niter, 1) + 1;
988 else
989 nitercst = max;
990 predictor = PRED_LOOP_ITERATIONS;
992 /* If we have just one exit and we can derive some information about
993 the number of iterations of the loop from the statements inside
994 the loop, use it to predict this exit. */
995 else if (n_exits == 1)
997 nitercst = max_stmt_executions_int (loop, false);
998 if (nitercst < 0)
999 continue;
1000 if (nitercst > max)
1001 nitercst = max;
1003 predictor = PRED_LOOP_ITERATIONS_GUESSED;
1005 else
1006 continue;
1008 probability = ((REG_BR_PROB_BASE + nitercst / 2) / nitercst);
1009 predict_edge (ex, predictor, probability);
1011 VEC_free (edge, heap, exits);
1013 bbs = get_loop_body (loop);
1015 for (j = 0; j < loop->num_nodes; j++)
1017 int header_found = 0;
1018 edge e;
1019 edge_iterator ei;
1021 bb = bbs[j];
1023 /* Bypass loop heuristics on continue statement. These
1024 statements construct loops via "non-loop" constructs
1025 in the source language and are better to be handled
1026 separately. */
1027 if (predicted_by_p (bb, PRED_CONTINUE))
1028 continue;
1030 /* Loop branch heuristics - predict an edge back to a
1031 loop's head as taken. */
1032 if (bb == loop->latch)
1034 e = find_edge (loop->latch, loop->header);
1035 if (e)
1037 header_found = 1;
1038 predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
1042 /* Loop exit heuristics - predict an edge exiting the loop if the
1043 conditional has no loop header successors as not taken. */
1044 if (!header_found
1045 /* If we already used more reliable loop exit predictors, do not
1046 bother with PRED_LOOP_EXIT. */
1047 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS_GUESSED)
1048 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS))
1050 /* For loop with many exits we don't want to predict all exits
1051 with the pretty large probability, because if all exits are
1052 considered in row, the loop would be predicted to iterate
1053 almost never. The code to divide probability by number of
1054 exits is very rough. It should compute the number of exits
1055 taken in each patch through function (not the overall number
1056 of exits that might be a lot higher for loops with wide switch
1057 statements in them) and compute n-th square root.
1059 We limit the minimal probability by 2% to avoid
1060 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
1061 as this was causing regression in perl benchmark containing such
1062 a wide loop. */
1064 int probability = ((REG_BR_PROB_BASE
1065 - predictor_info [(int) PRED_LOOP_EXIT].hitrate)
1066 / n_exits);
1067 if (probability < HITRATE (2))
1068 probability = HITRATE (2);
1069 FOR_EACH_EDGE (e, ei, bb->succs)
1070 if (e->dest->index < NUM_FIXED_BLOCKS
1071 || !flow_bb_inside_loop_p (loop, e->dest))
1072 predict_edge (e, PRED_LOOP_EXIT, probability);
1076 /* Free basic blocks from get_loop_body. */
1077 free (bbs);
1081 /* Attempt to predict probabilities of BB outgoing edges using local
1082 properties. */
1083 static void
1084 bb_estimate_probability_locally (basic_block bb)
1086 rtx last_insn = BB_END (bb);
1087 rtx cond;
1089 if (! can_predict_insn_p (last_insn))
1090 return;
1091 cond = get_condition (last_insn, NULL, false, false);
1092 if (! cond)
1093 return;
1095 /* Try "pointer heuristic."
1096 A comparison ptr == 0 is predicted as false.
1097 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1098 if (COMPARISON_P (cond)
1099 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
1100 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
1102 if (GET_CODE (cond) == EQ)
1103 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
1104 else if (GET_CODE (cond) == NE)
1105 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
1107 else
1109 /* Try "opcode heuristic."
1110 EQ tests are usually false and NE tests are usually true. Also,
1111 most quantities are positive, so we can make the appropriate guesses
1112 about signed comparisons against zero. */
1113 switch (GET_CODE (cond))
1115 case CONST_INT:
1116 /* Unconditional branch. */
1117 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
1118 cond == const0_rtx ? NOT_TAKEN : TAKEN);
1119 break;
1121 case EQ:
1122 case UNEQ:
1123 /* Floating point comparisons appears to behave in a very
1124 unpredictable way because of special role of = tests in
1125 FP code. */
1126 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
1128 /* Comparisons with 0 are often used for booleans and there is
1129 nothing useful to predict about them. */
1130 else if (XEXP (cond, 1) == const0_rtx
1131 || XEXP (cond, 0) == const0_rtx)
1133 else
1134 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
1135 break;
1137 case NE:
1138 case LTGT:
1139 /* Floating point comparisons appears to behave in a very
1140 unpredictable way because of special role of = tests in
1141 FP code. */
1142 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
1144 /* Comparisons with 0 are often used for booleans and there is
1145 nothing useful to predict about them. */
1146 else if (XEXP (cond, 1) == const0_rtx
1147 || XEXP (cond, 0) == const0_rtx)
1149 else
1150 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
1151 break;
1153 case ORDERED:
1154 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
1155 break;
1157 case UNORDERED:
1158 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
1159 break;
1161 case LE:
1162 case LT:
1163 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1164 || XEXP (cond, 1) == constm1_rtx)
1165 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
1166 break;
1168 case GE:
1169 case GT:
1170 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1171 || XEXP (cond, 1) == constm1_rtx)
1172 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
1173 break;
1175 default:
1176 break;
1180 /* Set edge->probability for each successor edge of BB. */
1181 void
1182 guess_outgoing_edge_probabilities (basic_block bb)
1184 bb_estimate_probability_locally (bb);
1185 combine_predictions_for_insn (BB_END (bb), bb);
1188 static tree expr_expected_value (tree, bitmap);
1190 /* Helper function for expr_expected_value. */
1192 static tree
1193 expr_expected_value_1 (tree type, tree op0, enum tree_code code, tree op1, bitmap visited)
1195 gimple def;
1197 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1199 if (TREE_CONSTANT (op0))
1200 return op0;
1202 if (code != SSA_NAME)
1203 return NULL_TREE;
1205 def = SSA_NAME_DEF_STMT (op0);
1207 /* If we were already here, break the infinite cycle. */
1208 if (!bitmap_set_bit (visited, SSA_NAME_VERSION (op0)))
1209 return NULL;
1211 if (gimple_code (def) == GIMPLE_PHI)
1213 /* All the arguments of the PHI node must have the same constant
1214 length. */
1215 int i, n = gimple_phi_num_args (def);
1216 tree val = NULL, new_val;
1218 for (i = 0; i < n; i++)
1220 tree arg = PHI_ARG_DEF (def, i);
1222 /* If this PHI has itself as an argument, we cannot
1223 determine the string length of this argument. However,
1224 if we can find an expected constant value for the other
1225 PHI args then we can still be sure that this is
1226 likely a constant. So be optimistic and just
1227 continue with the next argument. */
1228 if (arg == PHI_RESULT (def))
1229 continue;
1231 new_val = expr_expected_value (arg, visited);
1232 if (!new_val)
1233 return NULL;
1234 if (!val)
1235 val = new_val;
1236 else if (!operand_equal_p (val, new_val, false))
1237 return NULL;
1239 return val;
1241 if (is_gimple_assign (def))
1243 if (gimple_assign_lhs (def) != op0)
1244 return NULL;
1246 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def)),
1247 gimple_assign_rhs1 (def),
1248 gimple_assign_rhs_code (def),
1249 gimple_assign_rhs2 (def),
1250 visited);
1253 if (is_gimple_call (def))
1255 tree decl = gimple_call_fndecl (def);
1256 if (!decl)
1257 return NULL;
1258 if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
1259 && DECL_FUNCTION_CODE (decl) == BUILT_IN_EXPECT)
1261 tree val;
1263 if (gimple_call_num_args (def) != 2)
1264 return NULL;
1265 val = gimple_call_arg (def, 0);
1266 if (TREE_CONSTANT (val))
1267 return val;
1268 return gimple_call_arg (def, 1);
1272 return NULL;
1275 if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS)
1277 tree res;
1278 op0 = expr_expected_value (op0, visited);
1279 if (!op0)
1280 return NULL;
1281 op1 = expr_expected_value (op1, visited);
1282 if (!op1)
1283 return NULL;
1284 res = fold_build2 (code, type, op0, op1);
1285 if (TREE_CONSTANT (res))
1286 return res;
1287 return NULL;
1289 if (get_gimple_rhs_class (code) == GIMPLE_UNARY_RHS)
1291 tree res;
1292 op0 = expr_expected_value (op0, visited);
1293 if (!op0)
1294 return NULL;
1295 res = fold_build1 (code, type, op0);
1296 if (TREE_CONSTANT (res))
1297 return res;
1298 return NULL;
1300 return NULL;
1303 /* Return constant EXPR will likely have at execution time, NULL if unknown.
1304 The function is used by builtin_expect branch predictor so the evidence
1305 must come from this construct and additional possible constant folding.
1307 We may want to implement more involved value guess (such as value range
1308 propagation based prediction), but such tricks shall go to new
1309 implementation. */
1311 static tree
1312 expr_expected_value (tree expr, bitmap visited)
1314 enum tree_code code;
1315 tree op0, op1;
1317 if (TREE_CONSTANT (expr))
1318 return expr;
1320 extract_ops_from_tree (expr, &code, &op0, &op1);
1321 return expr_expected_value_1 (TREE_TYPE (expr),
1322 op0, code, op1, visited);
1326 /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
1327 we no longer need. */
1328 static unsigned int
1329 strip_predict_hints (void)
1331 basic_block bb;
1332 gimple ass_stmt;
1333 tree var;
1335 FOR_EACH_BB (bb)
1337 gimple_stmt_iterator bi;
1338 for (bi = gsi_start_bb (bb); !gsi_end_p (bi);)
1340 gimple stmt = gsi_stmt (bi);
1342 if (gimple_code (stmt) == GIMPLE_PREDICT)
1344 gsi_remove (&bi, true);
1345 continue;
1347 else if (gimple_code (stmt) == GIMPLE_CALL)
1349 tree fndecl = gimple_call_fndecl (stmt);
1351 if (fndecl
1352 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1353 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT
1354 && gimple_call_num_args (stmt) == 2)
1356 var = gimple_call_lhs (stmt);
1357 if (var)
1359 ass_stmt
1360 = gimple_build_assign (var, gimple_call_arg (stmt, 0));
1361 gsi_replace (&bi, ass_stmt, true);
1363 else
1365 gsi_remove (&bi, true);
1366 continue;
1370 gsi_next (&bi);
1373 return 0;
1376 /* Predict using opcode of the last statement in basic block. */
1377 static void
1378 tree_predict_by_opcode (basic_block bb)
1380 gimple stmt = last_stmt (bb);
1381 edge then_edge;
1382 tree op0, op1;
1383 tree type;
1384 tree val;
1385 enum tree_code cmp;
1386 bitmap visited;
1387 edge_iterator ei;
1389 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
1390 return;
1391 FOR_EACH_EDGE (then_edge, ei, bb->succs)
1392 if (then_edge->flags & EDGE_TRUE_VALUE)
1393 break;
1394 op0 = gimple_cond_lhs (stmt);
1395 op1 = gimple_cond_rhs (stmt);
1396 cmp = gimple_cond_code (stmt);
1397 type = TREE_TYPE (op0);
1398 visited = BITMAP_ALLOC (NULL);
1399 val = expr_expected_value_1 (boolean_type_node, op0, cmp, op1, visited);
1400 BITMAP_FREE (visited);
1401 if (val)
1403 if (integer_zerop (val))
1404 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, NOT_TAKEN);
1405 else
1406 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, TAKEN);
1407 return;
1409 /* Try "pointer heuristic."
1410 A comparison ptr == 0 is predicted as false.
1411 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1412 if (POINTER_TYPE_P (type))
1414 if (cmp == EQ_EXPR)
1415 predict_edge_def (then_edge, PRED_TREE_POINTER, NOT_TAKEN);
1416 else if (cmp == NE_EXPR)
1417 predict_edge_def (then_edge, PRED_TREE_POINTER, TAKEN);
1419 else
1421 /* Try "opcode heuristic."
1422 EQ tests are usually false and NE tests are usually true. Also,
1423 most quantities are positive, so we can make the appropriate guesses
1424 about signed comparisons against zero. */
1425 switch (cmp)
1427 case EQ_EXPR:
1428 case UNEQ_EXPR:
1429 /* Floating point comparisons appears to behave in a very
1430 unpredictable way because of special role of = tests in
1431 FP code. */
1432 if (FLOAT_TYPE_P (type))
1434 /* Comparisons with 0 are often used for booleans and there is
1435 nothing useful to predict about them. */
1436 else if (integer_zerop (op0) || integer_zerop (op1))
1438 else
1439 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, NOT_TAKEN);
1440 break;
1442 case NE_EXPR:
1443 case LTGT_EXPR:
1444 /* Floating point comparisons appears to behave in a very
1445 unpredictable way because of special role of = tests in
1446 FP code. */
1447 if (FLOAT_TYPE_P (type))
1449 /* Comparisons with 0 are often used for booleans and there is
1450 nothing useful to predict about them. */
1451 else if (integer_zerop (op0)
1452 || integer_zerop (op1))
1454 else
1455 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, TAKEN);
1456 break;
1458 case ORDERED_EXPR:
1459 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, TAKEN);
1460 break;
1462 case UNORDERED_EXPR:
1463 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, NOT_TAKEN);
1464 break;
1466 case LE_EXPR:
1467 case LT_EXPR:
1468 if (integer_zerop (op1)
1469 || integer_onep (op1)
1470 || integer_all_onesp (op1)
1471 || real_zerop (op1)
1472 || real_onep (op1)
1473 || real_minus_onep (op1))
1474 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, NOT_TAKEN);
1475 break;
1477 case GE_EXPR:
1478 case GT_EXPR:
1479 if (integer_zerop (op1)
1480 || integer_onep (op1)
1481 || integer_all_onesp (op1)
1482 || real_zerop (op1)
1483 || real_onep (op1)
1484 || real_minus_onep (op1))
1485 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, TAKEN);
1486 break;
1488 default:
1489 break;
1493 /* Try to guess whether the value of return means error code. */
1495 static enum br_predictor
1496 return_prediction (tree val, enum prediction *prediction)
1498 /* VOID. */
1499 if (!val)
1500 return PRED_NO_PREDICTION;
1501 /* Different heuristics for pointers and scalars. */
1502 if (POINTER_TYPE_P (TREE_TYPE (val)))
1504 /* NULL is usually not returned. */
1505 if (integer_zerop (val))
1507 *prediction = NOT_TAKEN;
1508 return PRED_NULL_RETURN;
1511 else if (INTEGRAL_TYPE_P (TREE_TYPE (val)))
1513 /* Negative return values are often used to indicate
1514 errors. */
1515 if (TREE_CODE (val) == INTEGER_CST
1516 && tree_int_cst_sgn (val) < 0)
1518 *prediction = NOT_TAKEN;
1519 return PRED_NEGATIVE_RETURN;
1521 /* Constant return values seems to be commonly taken.
1522 Zero/one often represent booleans so exclude them from the
1523 heuristics. */
1524 if (TREE_CONSTANT (val)
1525 && (!integer_zerop (val) && !integer_onep (val)))
1527 *prediction = TAKEN;
1528 return PRED_CONST_RETURN;
1531 return PRED_NO_PREDICTION;
1534 /* Find the basic block with return expression and look up for possible
1535 return value trying to apply RETURN_PREDICTION heuristics. */
1536 static void
1537 apply_return_prediction (void)
1539 gimple return_stmt = NULL;
1540 tree return_val;
1541 edge e;
1542 gimple phi;
1543 int phi_num_args, i;
1544 enum br_predictor pred;
1545 enum prediction direction;
1546 edge_iterator ei;
1548 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
1550 return_stmt = last_stmt (e->src);
1551 if (return_stmt
1552 && gimple_code (return_stmt) == GIMPLE_RETURN)
1553 break;
1555 if (!e)
1556 return;
1557 return_val = gimple_return_retval (return_stmt);
1558 if (!return_val)
1559 return;
1560 if (TREE_CODE (return_val) != SSA_NAME
1561 || !SSA_NAME_DEF_STMT (return_val)
1562 || gimple_code (SSA_NAME_DEF_STMT (return_val)) != GIMPLE_PHI)
1563 return;
1564 phi = SSA_NAME_DEF_STMT (return_val);
1565 phi_num_args = gimple_phi_num_args (phi);
1566 pred = return_prediction (PHI_ARG_DEF (phi, 0), &direction);
1568 /* Avoid the degenerate case where all return values form the function
1569 belongs to same category (ie they are all positive constants)
1570 so we can hardly say something about them. */
1571 for (i = 1; i < phi_num_args; i++)
1572 if (pred != return_prediction (PHI_ARG_DEF (phi, i), &direction))
1573 break;
1574 if (i != phi_num_args)
1575 for (i = 0; i < phi_num_args; i++)
1577 pred = return_prediction (PHI_ARG_DEF (phi, i), &direction);
1578 if (pred != PRED_NO_PREDICTION)
1579 predict_paths_leading_to_edge (gimple_phi_arg_edge (phi, i), pred,
1580 direction);
1584 /* Look for basic block that contains unlikely to happen events
1585 (such as noreturn calls) and mark all paths leading to execution
1586 of this basic blocks as unlikely. */
1588 static void
1589 tree_bb_level_predictions (void)
1591 basic_block bb;
1592 bool has_return_edges = false;
1593 edge e;
1594 edge_iterator ei;
1596 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
1597 if (!(e->flags & (EDGE_ABNORMAL | EDGE_FAKE | EDGE_EH)))
1599 has_return_edges = true;
1600 break;
1603 apply_return_prediction ();
1605 FOR_EACH_BB (bb)
1607 gimple_stmt_iterator gsi;
1609 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1611 gimple stmt = gsi_stmt (gsi);
1612 tree decl;
1614 if (is_gimple_call (stmt))
1616 if ((gimple_call_flags (stmt) & ECF_NORETURN)
1617 && has_return_edges)
1618 predict_paths_leading_to (bb, PRED_NORETURN,
1619 NOT_TAKEN);
1620 decl = gimple_call_fndecl (stmt);
1621 if (decl
1622 && lookup_attribute ("cold",
1623 DECL_ATTRIBUTES (decl)))
1624 predict_paths_leading_to (bb, PRED_COLD_FUNCTION,
1625 NOT_TAKEN);
1627 else if (gimple_code (stmt) == GIMPLE_PREDICT)
1629 predict_paths_leading_to (bb, gimple_predict_predictor (stmt),
1630 gimple_predict_outcome (stmt));
1631 /* Keep GIMPLE_PREDICT around so early inlining will propagate
1632 hints to callers. */
1638 #ifdef ENABLE_CHECKING
1640 /* Callback for pointer_map_traverse, asserts that the pointer map is
1641 empty. */
1643 static bool
1644 assert_is_empty (const void *key ATTRIBUTE_UNUSED, void **value,
1645 void *data ATTRIBUTE_UNUSED)
1647 gcc_assert (!*value);
1648 return false;
1650 #endif
1652 /* Predict branch probabilities and estimate profile for basic block BB. */
1654 static void
1655 tree_estimate_probability_bb (basic_block bb)
1657 edge e;
1658 edge_iterator ei;
1659 gimple last;
1661 FOR_EACH_EDGE (e, ei, bb->succs)
1663 /* Predict early returns to be probable, as we've already taken
1664 care for error returns and other cases are often used for
1665 fast paths through function.
1667 Since we've already removed the return statements, we are
1668 looking for CFG like:
1670 if (conditional)
1673 goto return_block
1675 some other blocks
1676 return_block:
1677 return_stmt. */
1678 if (e->dest != bb->next_bb
1679 && e->dest != EXIT_BLOCK_PTR
1680 && single_succ_p (e->dest)
1681 && single_succ_edge (e->dest)->dest == EXIT_BLOCK_PTR
1682 && (last = last_stmt (e->dest)) != NULL
1683 && gimple_code (last) == GIMPLE_RETURN)
1685 edge e1;
1686 edge_iterator ei1;
1688 if (single_succ_p (bb))
1690 FOR_EACH_EDGE (e1, ei1, bb->preds)
1691 if (!predicted_by_p (e1->src, PRED_NULL_RETURN)
1692 && !predicted_by_p (e1->src, PRED_CONST_RETURN)
1693 && !predicted_by_p (e1->src, PRED_NEGATIVE_RETURN))
1694 predict_edge_def (e1, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
1696 else
1697 if (!predicted_by_p (e->src, PRED_NULL_RETURN)
1698 && !predicted_by_p (e->src, PRED_CONST_RETURN)
1699 && !predicted_by_p (e->src, PRED_NEGATIVE_RETURN))
1700 predict_edge_def (e, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
1703 /* Look for block we are guarding (ie we dominate it,
1704 but it doesn't postdominate us). */
1705 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
1706 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
1707 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
1709 gimple_stmt_iterator bi;
1711 /* The call heuristic claims that a guarded function call
1712 is improbable. This is because such calls are often used
1713 to signal exceptional situations such as printing error
1714 messages. */
1715 for (bi = gsi_start_bb (e->dest); !gsi_end_p (bi);
1716 gsi_next (&bi))
1718 gimple stmt = gsi_stmt (bi);
1719 if (is_gimple_call (stmt)
1720 /* Constant and pure calls are hardly used to signalize
1721 something exceptional. */
1722 && gimple_has_side_effects (stmt))
1724 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
1725 break;
1730 tree_predict_by_opcode (bb);
1733 /* Predict branch probabilities and estimate profile of the tree CFG.
1734 This function can be called from the loop optimizers to recompute
1735 the profile information. */
1737 void
1738 tree_estimate_probability (void)
1740 basic_block bb;
1742 add_noreturn_fake_exit_edges ();
1743 connect_infinite_loops_to_exit ();
1744 /* We use loop_niter_by_eval, which requires that the loops have
1745 preheaders. */
1746 create_preheaders (CP_SIMPLE_PREHEADERS);
1747 calculate_dominance_info (CDI_POST_DOMINATORS);
1749 bb_predictions = pointer_map_create ();
1750 tree_bb_level_predictions ();
1751 record_loop_exits ();
1753 if (number_of_loops () > 1)
1754 predict_loops ();
1756 FOR_EACH_BB (bb)
1757 tree_estimate_probability_bb (bb);
1759 FOR_EACH_BB (bb)
1760 combine_predictions_for_bb (bb);
1762 #ifdef ENABLE_CHECKING
1763 pointer_map_traverse (bb_predictions, assert_is_empty, NULL);
1764 #endif
1765 pointer_map_destroy (bb_predictions);
1766 bb_predictions = NULL;
1768 estimate_bb_frequencies ();
1769 free_dominance_info (CDI_POST_DOMINATORS);
1770 remove_fake_exit_edges ();
1773 /* Predict branch probabilities and estimate profile of the tree CFG.
1774 This is the driver function for PASS_PROFILE. */
1776 static unsigned int
1777 tree_estimate_probability_driver (void)
1779 unsigned nb_loops;
1781 loop_optimizer_init (0);
1782 if (dump_file && (dump_flags & TDF_DETAILS))
1783 flow_loops_dump (dump_file, NULL, 0);
1785 mark_irreducible_loops ();
1787 nb_loops = number_of_loops ();
1788 if (nb_loops > 1)
1789 scev_initialize ();
1791 tree_estimate_probability ();
1793 if (nb_loops > 1)
1794 scev_finalize ();
1796 loop_optimizer_finalize ();
1797 if (dump_file && (dump_flags & TDF_DETAILS))
1798 gimple_dump_cfg (dump_file, dump_flags);
1799 if (profile_status == PROFILE_ABSENT)
1800 profile_status = PROFILE_GUESSED;
1801 return 0;
1804 /* Predict edges to successors of CUR whose sources are not postdominated by
1805 BB by PRED and recurse to all postdominators. */
1807 static void
1808 predict_paths_for_bb (basic_block cur, basic_block bb,
1809 enum br_predictor pred,
1810 enum prediction taken)
1812 edge e;
1813 edge_iterator ei;
1814 basic_block son;
1816 /* We are looking for all edges forming edge cut induced by
1817 set of all blocks postdominated by BB. */
1818 FOR_EACH_EDGE (e, ei, cur->preds)
1819 if (e->src->index >= NUM_FIXED_BLOCKS
1820 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, bb))
1822 edge e2;
1823 edge_iterator ei2;
1824 bool found = false;
1826 /* Ignore fake edges and eh, we predict them as not taken anyway. */
1827 if (e->flags & (EDGE_EH | EDGE_FAKE))
1828 continue;
1829 gcc_assert (bb == cur || dominated_by_p (CDI_POST_DOMINATORS, cur, bb));
1831 /* See if there is how many edge from e->src that is not abnormal
1832 and does not lead to BB. */
1833 FOR_EACH_EDGE (e2, ei2, e->src->succs)
1834 if (e2 != e
1835 && !(e2->flags & (EDGE_EH | EDGE_FAKE))
1836 && !dominated_by_p (CDI_POST_DOMINATORS, e2->dest, bb))
1838 found = true;
1839 break;
1842 /* If there is non-abnormal path leaving e->src, predict edge
1843 using predictor. Otherwise we need to look for paths
1844 leading to e->src. */
1845 if (found)
1846 predict_edge_def (e, pred, taken);
1847 else
1848 predict_paths_for_bb (e->src, e->src, pred, taken);
1850 for (son = first_dom_son (CDI_POST_DOMINATORS, cur);
1851 son;
1852 son = next_dom_son (CDI_POST_DOMINATORS, son))
1853 predict_paths_for_bb (son, bb, pred, taken);
1856 /* Sets branch probabilities according to PREDiction and
1857 FLAGS. */
1859 static void
1860 predict_paths_leading_to (basic_block bb, enum br_predictor pred,
1861 enum prediction taken)
1863 predict_paths_for_bb (bb, bb, pred, taken);
1866 /* Like predict_paths_leading_to but take edge instead of basic block. */
1868 static void
1869 predict_paths_leading_to_edge (edge e, enum br_predictor pred,
1870 enum prediction taken)
1872 bool has_nonloop_edge = false;
1873 edge_iterator ei;
1874 edge e2;
1876 basic_block bb = e->src;
1877 FOR_EACH_EDGE (e2, ei, bb->succs)
1878 if (e2->dest != e->src && e2->dest != e->dest
1879 && !(e->flags & (EDGE_EH | EDGE_FAKE))
1880 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e2->dest))
1882 has_nonloop_edge = true;
1883 break;
1885 if (!has_nonloop_edge)
1886 predict_paths_for_bb (bb, bb, pred, taken);
1887 else
1888 predict_edge_def (e, pred, taken);
1891 /* This is used to carry information about basic blocks. It is
1892 attached to the AUX field of the standard CFG block. */
1894 typedef struct block_info_def
1896 /* Estimated frequency of execution of basic_block. */
1897 sreal frequency;
1899 /* To keep queue of basic blocks to process. */
1900 basic_block next;
1902 /* Number of predecessors we need to visit first. */
1903 int npredecessors;
1904 } *block_info;
1906 /* Similar information for edges. */
1907 typedef struct edge_info_def
1909 /* In case edge is a loopback edge, the probability edge will be reached
1910 in case header is. Estimated number of iterations of the loop can be
1911 then computed as 1 / (1 - back_edge_prob). */
1912 sreal back_edge_prob;
1913 /* True if the edge is a loopback edge in the natural loop. */
1914 unsigned int back_edge:1;
1915 } *edge_info;
1917 #define BLOCK_INFO(B) ((block_info) (B)->aux)
1918 #define EDGE_INFO(E) ((edge_info) (E)->aux)
1920 /* Helper function for estimate_bb_frequencies.
1921 Propagate the frequencies in blocks marked in
1922 TOVISIT, starting in HEAD. */
1924 static void
1925 propagate_freq (basic_block head, bitmap tovisit)
1927 basic_block bb;
1928 basic_block last;
1929 unsigned i;
1930 edge e;
1931 basic_block nextbb;
1932 bitmap_iterator bi;
1934 /* For each basic block we need to visit count number of his predecessors
1935 we need to visit first. */
1936 EXECUTE_IF_SET_IN_BITMAP (tovisit, 0, i, bi)
1938 edge_iterator ei;
1939 int count = 0;
1941 bb = BASIC_BLOCK (i);
1943 FOR_EACH_EDGE (e, ei, bb->preds)
1945 bool visit = bitmap_bit_p (tovisit, e->src->index);
1947 if (visit && !(e->flags & EDGE_DFS_BACK))
1948 count++;
1949 else if (visit && dump_file && !EDGE_INFO (e)->back_edge)
1950 fprintf (dump_file,
1951 "Irreducible region hit, ignoring edge to %i->%i\n",
1952 e->src->index, bb->index);
1954 BLOCK_INFO (bb)->npredecessors = count;
1955 /* When function never returns, we will never process exit block. */
1956 if (!count && bb == EXIT_BLOCK_PTR)
1957 bb->count = bb->frequency = 0;
1960 memcpy (&BLOCK_INFO (head)->frequency, &real_one, sizeof (real_one));
1961 last = head;
1962 for (bb = head; bb; bb = nextbb)
1964 edge_iterator ei;
1965 sreal cyclic_probability, frequency;
1967 memcpy (&cyclic_probability, &real_zero, sizeof (real_zero));
1968 memcpy (&frequency, &real_zero, sizeof (real_zero));
1970 nextbb = BLOCK_INFO (bb)->next;
1971 BLOCK_INFO (bb)->next = NULL;
1973 /* Compute frequency of basic block. */
1974 if (bb != head)
1976 #ifdef ENABLE_CHECKING
1977 FOR_EACH_EDGE (e, ei, bb->preds)
1978 gcc_assert (!bitmap_bit_p (tovisit, e->src->index)
1979 || (e->flags & EDGE_DFS_BACK));
1980 #endif
1982 FOR_EACH_EDGE (e, ei, bb->preds)
1983 if (EDGE_INFO (e)->back_edge)
1985 sreal_add (&cyclic_probability, &cyclic_probability,
1986 &EDGE_INFO (e)->back_edge_prob);
1988 else if (!(e->flags & EDGE_DFS_BACK))
1990 sreal tmp;
1992 /* frequency += (e->probability
1993 * BLOCK_INFO (e->src)->frequency /
1994 REG_BR_PROB_BASE); */
1996 sreal_init (&tmp, e->probability, 0);
1997 sreal_mul (&tmp, &tmp, &BLOCK_INFO (e->src)->frequency);
1998 sreal_mul (&tmp, &tmp, &real_inv_br_prob_base);
1999 sreal_add (&frequency, &frequency, &tmp);
2002 if (sreal_compare (&cyclic_probability, &real_zero) == 0)
2004 memcpy (&BLOCK_INFO (bb)->frequency, &frequency,
2005 sizeof (frequency));
2007 else
2009 if (sreal_compare (&cyclic_probability, &real_almost_one) > 0)
2011 memcpy (&cyclic_probability, &real_almost_one,
2012 sizeof (real_almost_one));
2015 /* BLOCK_INFO (bb)->frequency = frequency
2016 / (1 - cyclic_probability) */
2018 sreal_sub (&cyclic_probability, &real_one, &cyclic_probability);
2019 sreal_div (&BLOCK_INFO (bb)->frequency,
2020 &frequency, &cyclic_probability);
2024 bitmap_clear_bit (tovisit, bb->index);
2026 e = find_edge (bb, head);
2027 if (e)
2029 sreal tmp;
2031 /* EDGE_INFO (e)->back_edge_prob
2032 = ((e->probability * BLOCK_INFO (bb)->frequency)
2033 / REG_BR_PROB_BASE); */
2035 sreal_init (&tmp, e->probability, 0);
2036 sreal_mul (&tmp, &tmp, &BLOCK_INFO (bb)->frequency);
2037 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
2038 &tmp, &real_inv_br_prob_base);
2041 /* Propagate to successor blocks. */
2042 FOR_EACH_EDGE (e, ei, bb->succs)
2043 if (!(e->flags & EDGE_DFS_BACK)
2044 && BLOCK_INFO (e->dest)->npredecessors)
2046 BLOCK_INFO (e->dest)->npredecessors--;
2047 if (!BLOCK_INFO (e->dest)->npredecessors)
2049 if (!nextbb)
2050 nextbb = e->dest;
2051 else
2052 BLOCK_INFO (last)->next = e->dest;
2054 last = e->dest;
2060 /* Estimate probabilities of loopback edges in loops at same nest level. */
2062 static void
2063 estimate_loops_at_level (struct loop *first_loop)
2065 struct loop *loop;
2067 for (loop = first_loop; loop; loop = loop->next)
2069 edge e;
2070 basic_block *bbs;
2071 unsigned i;
2072 bitmap tovisit = BITMAP_ALLOC (NULL);
2074 estimate_loops_at_level (loop->inner);
2076 /* Find current loop back edge and mark it. */
2077 e = loop_latch_edge (loop);
2078 EDGE_INFO (e)->back_edge = 1;
2080 bbs = get_loop_body (loop);
2081 for (i = 0; i < loop->num_nodes; i++)
2082 bitmap_set_bit (tovisit, bbs[i]->index);
2083 free (bbs);
2084 propagate_freq (loop->header, tovisit);
2085 BITMAP_FREE (tovisit);
2089 /* Propagates frequencies through structure of loops. */
2091 static void
2092 estimate_loops (void)
2094 bitmap tovisit = BITMAP_ALLOC (NULL);
2095 basic_block bb;
2097 /* Start by estimating the frequencies in the loops. */
2098 if (number_of_loops () > 1)
2099 estimate_loops_at_level (current_loops->tree_root->inner);
2101 /* Now propagate the frequencies through all the blocks. */
2102 FOR_ALL_BB (bb)
2104 bitmap_set_bit (tovisit, bb->index);
2106 propagate_freq (ENTRY_BLOCK_PTR, tovisit);
2107 BITMAP_FREE (tovisit);
2110 /* Convert counts measured by profile driven feedback to frequencies.
2111 Return nonzero iff there was any nonzero execution count. */
2114 counts_to_freqs (void)
2116 gcov_type count_max, true_count_max = 0;
2117 basic_block bb;
2119 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2120 true_count_max = MAX (bb->count, true_count_max);
2122 count_max = MAX (true_count_max, 1);
2123 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2124 bb->frequency = (bb->count * BB_FREQ_MAX + count_max / 2) / count_max;
2126 return true_count_max;
2129 /* Return true if function is likely to be expensive, so there is no point to
2130 optimize performance of prologue, epilogue or do inlining at the expense
2131 of code size growth. THRESHOLD is the limit of number of instructions
2132 function can execute at average to be still considered not expensive. */
2134 bool
2135 expensive_function_p (int threshold)
2137 unsigned int sum = 0;
2138 basic_block bb;
2139 unsigned int limit;
2141 /* We can not compute accurately for large thresholds due to scaled
2142 frequencies. */
2143 gcc_assert (threshold <= BB_FREQ_MAX);
2145 /* Frequencies are out of range. This either means that function contains
2146 internal loop executing more than BB_FREQ_MAX times or profile feedback
2147 is available and function has not been executed at all. */
2148 if (ENTRY_BLOCK_PTR->frequency == 0)
2149 return true;
2151 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
2152 limit = ENTRY_BLOCK_PTR->frequency * threshold;
2153 FOR_EACH_BB (bb)
2155 rtx insn;
2157 for (insn = BB_HEAD (bb); insn != NEXT_INSN (BB_END (bb));
2158 insn = NEXT_INSN (insn))
2159 if (active_insn_p (insn))
2161 sum += bb->frequency;
2162 if (sum > limit)
2163 return true;
2167 return false;
2170 /* Estimate basic blocks frequency by given branch probabilities. */
2172 void
2173 estimate_bb_frequencies (void)
2175 basic_block bb;
2176 sreal freq_max;
2178 if (profile_status != PROFILE_READ || !counts_to_freqs ())
2180 static int real_values_initialized = 0;
2182 if (!real_values_initialized)
2184 real_values_initialized = 1;
2185 sreal_init (&real_zero, 0, 0);
2186 sreal_init (&real_one, 1, 0);
2187 sreal_init (&real_br_prob_base, REG_BR_PROB_BASE, 0);
2188 sreal_init (&real_bb_freq_max, BB_FREQ_MAX, 0);
2189 sreal_init (&real_one_half, 1, -1);
2190 sreal_div (&real_inv_br_prob_base, &real_one, &real_br_prob_base);
2191 sreal_sub (&real_almost_one, &real_one, &real_inv_br_prob_base);
2194 mark_dfs_back_edges ();
2196 single_succ_edge (ENTRY_BLOCK_PTR)->probability = REG_BR_PROB_BASE;
2198 /* Set up block info for each basic block. */
2199 alloc_aux_for_blocks (sizeof (struct block_info_def));
2200 alloc_aux_for_edges (sizeof (struct edge_info_def));
2201 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2203 edge e;
2204 edge_iterator ei;
2206 FOR_EACH_EDGE (e, ei, bb->succs)
2208 sreal_init (&EDGE_INFO (e)->back_edge_prob, e->probability, 0);
2209 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
2210 &EDGE_INFO (e)->back_edge_prob,
2211 &real_inv_br_prob_base);
2215 /* First compute probabilities locally for each loop from innermost
2216 to outermost to examine probabilities for back edges. */
2217 estimate_loops ();
2219 memcpy (&freq_max, &real_zero, sizeof (real_zero));
2220 FOR_EACH_BB (bb)
2221 if (sreal_compare (&freq_max, &BLOCK_INFO (bb)->frequency) < 0)
2222 memcpy (&freq_max, &BLOCK_INFO (bb)->frequency, sizeof (freq_max));
2224 sreal_div (&freq_max, &real_bb_freq_max, &freq_max);
2225 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2227 sreal tmp;
2229 sreal_mul (&tmp, &BLOCK_INFO (bb)->frequency, &freq_max);
2230 sreal_add (&tmp, &tmp, &real_one_half);
2231 bb->frequency = sreal_to_int (&tmp);
2234 free_aux_for_blocks ();
2235 free_aux_for_edges ();
2237 compute_function_frequency ();
2240 /* Decide whether function is hot, cold or unlikely executed. */
2241 void
2242 compute_function_frequency (void)
2244 basic_block bb;
2245 struct cgraph_node *node = cgraph_get_node (current_function_decl);
2246 if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
2247 || MAIN_NAME_P (DECL_NAME (current_function_decl)))
2248 node->only_called_at_startup = true;
2249 if (DECL_STATIC_DESTRUCTOR (current_function_decl))
2250 node->only_called_at_exit = true;
2252 if (!profile_info || !flag_branch_probabilities)
2254 int flags = flags_from_decl_or_type (current_function_decl);
2255 if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl))
2256 != NULL)
2257 node->frequency = NODE_FREQUENCY_UNLIKELY_EXECUTED;
2258 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl))
2259 != NULL)
2260 node->frequency = NODE_FREQUENCY_HOT;
2261 else if (flags & ECF_NORETURN)
2262 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
2263 else if (MAIN_NAME_P (DECL_NAME (current_function_decl)))
2264 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
2265 else if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
2266 || DECL_STATIC_DESTRUCTOR (current_function_decl))
2267 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
2268 return;
2270 node->frequency = NODE_FREQUENCY_UNLIKELY_EXECUTED;
2271 FOR_EACH_BB (bb)
2273 if (maybe_hot_bb_p (bb))
2275 node->frequency = NODE_FREQUENCY_HOT;
2276 return;
2278 if (!probably_never_executed_bb_p (bb))
2279 node->frequency = NODE_FREQUENCY_NORMAL;
2283 static bool
2284 gate_estimate_probability (void)
2286 return flag_guess_branch_prob;
2289 /* Build PREDICT_EXPR. */
2290 tree
2291 build_predict_expr (enum br_predictor predictor, enum prediction taken)
2293 tree t = build1 (PREDICT_EXPR, void_type_node,
2294 build_int_cst (integer_type_node, predictor));
2295 SET_PREDICT_EXPR_OUTCOME (t, taken);
2296 return t;
2299 const char *
2300 predictor_name (enum br_predictor predictor)
2302 return predictor_info[predictor].name;
2305 struct gimple_opt_pass pass_profile =
2308 GIMPLE_PASS,
2309 "profile_estimate", /* name */
2310 gate_estimate_probability, /* gate */
2311 tree_estimate_probability_driver, /* execute */
2312 NULL, /* sub */
2313 NULL, /* next */
2314 0, /* static_pass_number */
2315 TV_BRANCH_PROB, /* tv_id */
2316 PROP_cfg, /* properties_required */
2317 0, /* properties_provided */
2318 0, /* properties_destroyed */
2319 0, /* todo_flags_start */
2320 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
2324 struct gimple_opt_pass pass_strip_predict_hints =
2327 GIMPLE_PASS,
2328 "*strip_predict_hints", /* name */
2329 NULL, /* gate */
2330 strip_predict_hints, /* execute */
2331 NULL, /* sub */
2332 NULL, /* next */
2333 0, /* static_pass_number */
2334 TV_BRANCH_PROB, /* tv_id */
2335 PROP_cfg, /* properties_required */
2336 0, /* properties_provided */
2337 0, /* properties_destroyed */
2338 0, /* todo_flags_start */
2339 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
2343 /* Rebuild function frequencies. Passes are in general expected to
2344 maintain profile by hand, however in some cases this is not possible:
2345 for example when inlining several functions with loops freuqencies might run
2346 out of scale and thus needs to be recomputed. */
2348 void
2349 rebuild_frequencies (void)
2351 timevar_push (TV_REBUILD_FREQUENCIES);
2352 if (profile_status == PROFILE_GUESSED)
2354 loop_optimizer_init (0);
2355 add_noreturn_fake_exit_edges ();
2356 mark_irreducible_loops ();
2357 connect_infinite_loops_to_exit ();
2358 estimate_bb_frequencies ();
2359 remove_fake_exit_edges ();
2360 loop_optimizer_finalize ();
2362 else if (profile_status == PROFILE_READ)
2363 counts_to_freqs ();
2364 else
2365 gcc_unreachable ();
2366 timevar_pop (TV_REBUILD_FREQUENCIES);