* arm.h (TARGET_CPU_CPP_BUILTINS): Remove Maverick support.
[official-gcc.git] / gcc / predict.c
blob776ea7e9a79d9d4cba0d5902e372f10dea140fd5
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 "function.h"
44 #include "except.h"
45 #include "diagnostic-core.h"
46 #include "recog.h"
47 #include "expr.h"
48 #include "predict.h"
49 #include "coverage.h"
50 #include "sreal.h"
51 #include "params.h"
52 #include "target.h"
53 #include "cfgloop.h"
54 #include "tree-flow.h"
55 #include "ggc.h"
56 #include "tree-dump.h"
57 #include "tree-pass.h"
58 #include "timevar.h"
59 #include "tree-scalar-evolution.h"
60 #include "cfgloop.h"
61 #include "pointer-set.h"
63 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
64 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
65 static sreal real_zero, real_one, real_almost_one, real_br_prob_base,
66 real_inv_br_prob_base, real_one_half, real_bb_freq_max;
68 /* Random guesstimation given names.
69 PROV_VERY_UNLIKELY should be small enough so basic block predicted
70 by it gets bellow HOT_BB_FREQUENCY_FRANCTION. */
71 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 2000 - 1)
72 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
73 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
74 #define PROB_ALWAYS (REG_BR_PROB_BASE)
76 static void combine_predictions_for_insn (rtx, basic_block);
77 static void dump_prediction (FILE *, enum br_predictor, int, basic_block, int);
78 static void predict_paths_leading_to (basic_block, enum br_predictor, enum prediction);
79 static void predict_paths_leading_to_edge (edge, enum br_predictor, enum prediction);
80 static bool can_predict_insn_p (const_rtx);
82 /* Information we hold about each branch predictor.
83 Filled using information from predict.def. */
85 struct predictor_info
87 const char *const name; /* Name used in the debugging dumps. */
88 const int hitrate; /* Expected hitrate used by
89 predict_insn_def call. */
90 const int flags;
93 /* Use given predictor without Dempster-Shaffer theory if it matches
94 using first_match heuristics. */
95 #define PRED_FLAG_FIRST_MATCH 1
97 /* Recompute hitrate in percent to our representation. */
99 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
101 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
102 static const struct predictor_info predictor_info[]= {
103 #include "predict.def"
105 /* Upper bound on predictors. */
106 {NULL, 0, 0}
108 #undef DEF_PREDICTOR
110 /* Return TRUE if frequency FREQ is considered to be hot. */
112 static inline bool
113 maybe_hot_frequency_p (int freq)
115 struct cgraph_node *node = cgraph_get_node (current_function_decl);
116 if (!profile_info || !flag_branch_probabilities)
118 if (node->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED)
119 return false;
120 if (node->frequency == NODE_FREQUENCY_HOT)
121 return true;
123 if (profile_status == PROFILE_ABSENT)
124 return true;
125 if (node->frequency == NODE_FREQUENCY_EXECUTED_ONCE
126 && freq < (ENTRY_BLOCK_PTR->frequency * 2 / 3))
127 return false;
128 if (freq < ENTRY_BLOCK_PTR->frequency / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
129 return false;
130 return true;
133 /* Return TRUE if frequency FREQ is considered to be hot. */
135 static inline bool
136 maybe_hot_count_p (gcov_type count)
138 if (profile_status != PROFILE_READ)
139 return true;
140 /* Code executed at most once is not hot. */
141 if (profile_info->runs >= count)
142 return false;
143 return (count
144 > profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION));
147 /* Return true in case BB can be CPU intensive and should be optimized
148 for maximal performance. */
150 bool
151 maybe_hot_bb_p (const_basic_block bb)
153 if (profile_status == PROFILE_READ)
154 return maybe_hot_count_p (bb->count);
155 return maybe_hot_frequency_p (bb->frequency);
158 /* Return true if the call can be hot. */
160 bool
161 cgraph_maybe_hot_edge_p (struct cgraph_edge *edge)
163 if (profile_info && flag_branch_probabilities
164 && (edge->count
165 <= profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
166 return false;
167 if (edge->caller->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED
168 || edge->callee->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED)
169 return false;
170 if (edge->caller->frequency > NODE_FREQUENCY_UNLIKELY_EXECUTED
171 && edge->callee->frequency <= NODE_FREQUENCY_EXECUTED_ONCE)
172 return false;
173 if (optimize_size)
174 return false;
175 if (edge->caller->frequency == NODE_FREQUENCY_HOT)
176 return true;
177 if (edge->caller->frequency == NODE_FREQUENCY_EXECUTED_ONCE
178 && edge->frequency < CGRAPH_FREQ_BASE * 3 / 2)
179 return false;
180 if (flag_guess_branch_prob
181 && edge->frequency <= (CGRAPH_FREQ_BASE
182 / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION)))
183 return false;
184 return true;
187 /* Return true in case BB can be CPU intensive and should be optimized
188 for maximal performance. */
190 bool
191 maybe_hot_edge_p (edge e)
193 if (profile_status == PROFILE_READ)
194 return maybe_hot_count_p (e->count);
195 return maybe_hot_frequency_p (EDGE_FREQUENCY (e));
199 /* Return true in case BB is probably never executed. */
201 bool
202 probably_never_executed_bb_p (const_basic_block bb)
204 if (profile_info && flag_branch_probabilities)
205 return ((bb->count + profile_info->runs / 2) / profile_info->runs) == 0;
206 if ((!profile_info || !flag_branch_probabilities)
207 && (cgraph_get_node (current_function_decl)->frequency
208 == NODE_FREQUENCY_UNLIKELY_EXECUTED))
209 return true;
210 return false;
213 /* Return true if NODE should be optimized for size. */
215 bool
216 cgraph_optimize_for_size_p (struct cgraph_node *node)
218 if (optimize_size)
219 return true;
220 if (node && (node->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED))
221 return true;
222 else
223 return false;
226 /* Return true when current function should always be optimized for size. */
228 bool
229 optimize_function_for_size_p (struct function *fun)
231 if (optimize_size)
232 return true;
233 if (!fun || !fun->decl)
234 return false;
235 return cgraph_optimize_for_size_p (cgraph_get_node (fun->decl));
238 /* Return true when current function should always be optimized for speed. */
240 bool
241 optimize_function_for_speed_p (struct function *fun)
243 return !optimize_function_for_size_p (fun);
246 /* Return TRUE when BB should be optimized for size. */
248 bool
249 optimize_bb_for_size_p (const_basic_block bb)
251 return optimize_function_for_size_p (cfun) || !maybe_hot_bb_p (bb);
254 /* Return TRUE when BB should be optimized for speed. */
256 bool
257 optimize_bb_for_speed_p (const_basic_block bb)
259 return !optimize_bb_for_size_p (bb);
262 /* Return TRUE when BB should be optimized for size. */
264 bool
265 optimize_edge_for_size_p (edge e)
267 return optimize_function_for_size_p (cfun) || !maybe_hot_edge_p (e);
270 /* Return TRUE when BB should be optimized for speed. */
272 bool
273 optimize_edge_for_speed_p (edge e)
275 return !optimize_edge_for_size_p (e);
278 /* Return TRUE when BB should be optimized for size. */
280 bool
281 optimize_insn_for_size_p (void)
283 return optimize_function_for_size_p (cfun) || !crtl->maybe_hot_insn_p;
286 /* Return TRUE when BB should be optimized for speed. */
288 bool
289 optimize_insn_for_speed_p (void)
291 return !optimize_insn_for_size_p ();
294 /* Return TRUE when LOOP should be optimized for size. */
296 bool
297 optimize_loop_for_size_p (struct loop *loop)
299 return optimize_bb_for_size_p (loop->header);
302 /* Return TRUE when LOOP should be optimized for speed. */
304 bool
305 optimize_loop_for_speed_p (struct loop *loop)
307 return optimize_bb_for_speed_p (loop->header);
310 /* Return TRUE when LOOP nest should be optimized for speed. */
312 bool
313 optimize_loop_nest_for_speed_p (struct loop *loop)
315 struct loop *l = loop;
316 if (optimize_loop_for_speed_p (loop))
317 return true;
318 l = loop->inner;
319 while (l && l != loop)
321 if (optimize_loop_for_speed_p (l))
322 return true;
323 if (l->inner)
324 l = l->inner;
325 else if (l->next)
326 l = l->next;
327 else
329 while (l != loop && !l->next)
330 l = loop_outer (l);
331 if (l != loop)
332 l = l->next;
335 return false;
338 /* Return TRUE when LOOP nest should be optimized for size. */
340 bool
341 optimize_loop_nest_for_size_p (struct loop *loop)
343 return !optimize_loop_nest_for_speed_p (loop);
346 /* Return true when edge E is likely to be well predictable by branch
347 predictor. */
349 bool
350 predictable_edge_p (edge e)
352 if (profile_status == PROFILE_ABSENT)
353 return false;
354 if ((e->probability
355 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100)
356 || (REG_BR_PROB_BASE - e->probability
357 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100))
358 return true;
359 return false;
363 /* Set RTL expansion for BB profile. */
365 void
366 rtl_profile_for_bb (basic_block bb)
368 crtl->maybe_hot_insn_p = maybe_hot_bb_p (bb);
371 /* Set RTL expansion for edge profile. */
373 void
374 rtl_profile_for_edge (edge e)
376 crtl->maybe_hot_insn_p = maybe_hot_edge_p (e);
379 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
380 void
381 default_rtl_profile (void)
383 crtl->maybe_hot_insn_p = true;
386 /* Return true if the one of outgoing edges is already predicted by
387 PREDICTOR. */
389 bool
390 rtl_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
392 rtx note;
393 if (!INSN_P (BB_END (bb)))
394 return false;
395 for (note = REG_NOTES (BB_END (bb)); note; note = XEXP (note, 1))
396 if (REG_NOTE_KIND (note) == REG_BR_PRED
397 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
398 return true;
399 return false;
402 /* This map contains for a basic block the list of predictions for the
403 outgoing edges. */
405 static struct pointer_map_t *bb_predictions;
407 /* Structure representing predictions in tree level. */
409 struct edge_prediction {
410 struct edge_prediction *ep_next;
411 edge ep_edge;
412 enum br_predictor ep_predictor;
413 int ep_probability;
416 /* Return true if the one of outgoing edges is already predicted by
417 PREDICTOR. */
419 bool
420 gimple_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
422 struct edge_prediction *i;
423 void **preds = pointer_map_contains (bb_predictions, bb);
425 if (!preds)
426 return false;
428 for (i = (struct edge_prediction *) *preds; i; i = i->ep_next)
429 if (i->ep_predictor == predictor)
430 return true;
431 return false;
434 /* Return true when the probability of edge is reliable.
436 The profile guessing code is good at predicting branch outcome (ie.
437 taken/not taken), that is predicted right slightly over 75% of time.
438 It is however notoriously poor on predicting the probability itself.
439 In general the profile appear a lot flatter (with probabilities closer
440 to 50%) than the reality so it is bad idea to use it to drive optimization
441 such as those disabling dynamic branch prediction for well predictable
442 branches.
444 There are two exceptions - edges leading to noreturn edges and edges
445 predicted by number of iterations heuristics are predicted well. This macro
446 should be able to distinguish those, but at the moment it simply check for
447 noreturn heuristic that is only one giving probability over 99% or bellow
448 1%. In future we might want to propagate reliability information across the
449 CFG if we find this information useful on multiple places. */
450 static bool
451 probability_reliable_p (int prob)
453 return (profile_status == PROFILE_READ
454 || (profile_status == PROFILE_GUESSED
455 && (prob <= HITRATE (1) || prob >= HITRATE (99))));
458 /* Same predicate as above, working on edges. */
459 bool
460 edge_probability_reliable_p (const_edge e)
462 return probability_reliable_p (e->probability);
465 /* Same predicate as edge_probability_reliable_p, working on notes. */
466 bool
467 br_prob_note_reliable_p (const_rtx note)
469 gcc_assert (REG_NOTE_KIND (note) == REG_BR_PROB);
470 return probability_reliable_p (INTVAL (XEXP (note, 0)));
473 static void
474 predict_insn (rtx insn, enum br_predictor predictor, int probability)
476 gcc_assert (any_condjump_p (insn));
477 if (!flag_guess_branch_prob)
478 return;
480 add_reg_note (insn, REG_BR_PRED,
481 gen_rtx_CONCAT (VOIDmode,
482 GEN_INT ((int) predictor),
483 GEN_INT ((int) probability)));
486 /* Predict insn by given predictor. */
488 void
489 predict_insn_def (rtx insn, enum br_predictor predictor,
490 enum prediction taken)
492 int probability = predictor_info[(int) predictor].hitrate;
494 if (taken != TAKEN)
495 probability = REG_BR_PROB_BASE - probability;
497 predict_insn (insn, predictor, probability);
500 /* Predict edge E with given probability if possible. */
502 void
503 rtl_predict_edge (edge e, enum br_predictor predictor, int probability)
505 rtx last_insn;
506 last_insn = BB_END (e->src);
508 /* We can store the branch prediction information only about
509 conditional jumps. */
510 if (!any_condjump_p (last_insn))
511 return;
513 /* We always store probability of branching. */
514 if (e->flags & EDGE_FALLTHRU)
515 probability = REG_BR_PROB_BASE - probability;
517 predict_insn (last_insn, predictor, probability);
520 /* Predict edge E with the given PROBABILITY. */
521 void
522 gimple_predict_edge (edge e, enum br_predictor predictor, int probability)
524 gcc_assert (profile_status != PROFILE_GUESSED);
525 if ((e->src != ENTRY_BLOCK_PTR && EDGE_COUNT (e->src->succs) > 1)
526 && flag_guess_branch_prob && optimize)
528 struct edge_prediction *i = XNEW (struct edge_prediction);
529 void **preds = pointer_map_insert (bb_predictions, e->src);
531 i->ep_next = (struct edge_prediction *) *preds;
532 *preds = i;
533 i->ep_probability = probability;
534 i->ep_predictor = predictor;
535 i->ep_edge = e;
539 /* Remove all predictions on given basic block that are attached
540 to edge E. */
541 void
542 remove_predictions_associated_with_edge (edge e)
544 void **preds;
546 if (!bb_predictions)
547 return;
549 preds = pointer_map_contains (bb_predictions, e->src);
551 if (preds)
553 struct edge_prediction **prediction = (struct edge_prediction **) preds;
554 struct edge_prediction *next;
556 while (*prediction)
558 if ((*prediction)->ep_edge == e)
560 next = (*prediction)->ep_next;
561 free (*prediction);
562 *prediction = next;
564 else
565 prediction = &((*prediction)->ep_next);
570 /* Clears the list of predictions stored for BB. */
572 static void
573 clear_bb_predictions (basic_block bb)
575 void **preds = pointer_map_contains (bb_predictions, bb);
576 struct edge_prediction *pred, *next;
578 if (!preds)
579 return;
581 for (pred = (struct edge_prediction *) *preds; pred; pred = next)
583 next = pred->ep_next;
584 free (pred);
586 *preds = NULL;
589 /* Return true when we can store prediction on insn INSN.
590 At the moment we represent predictions only on conditional
591 jumps, not at computed jump or other complicated cases. */
592 static bool
593 can_predict_insn_p (const_rtx insn)
595 return (JUMP_P (insn)
596 && any_condjump_p (insn)
597 && EDGE_COUNT (BLOCK_FOR_INSN (insn)->succs) >= 2);
600 /* Predict edge E by given predictor if possible. */
602 void
603 predict_edge_def (edge e, enum br_predictor predictor,
604 enum prediction taken)
606 int probability = predictor_info[(int) predictor].hitrate;
608 if (taken != TAKEN)
609 probability = REG_BR_PROB_BASE - probability;
611 predict_edge (e, predictor, probability);
614 /* Invert all branch predictions or probability notes in the INSN. This needs
615 to be done each time we invert the condition used by the jump. */
617 void
618 invert_br_probabilities (rtx insn)
620 rtx note;
622 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
623 if (REG_NOTE_KIND (note) == REG_BR_PROB)
624 XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
625 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
626 XEXP (XEXP (note, 0), 1)
627 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
630 /* Dump information about the branch prediction to the output file. */
632 static void
633 dump_prediction (FILE *file, enum br_predictor predictor, int probability,
634 basic_block bb, int used)
636 edge e;
637 edge_iterator ei;
639 if (!file)
640 return;
642 FOR_EACH_EDGE (e, ei, bb->succs)
643 if (! (e->flags & EDGE_FALLTHRU))
644 break;
646 fprintf (file, " %s heuristics%s: %.1f%%",
647 predictor_info[predictor].name,
648 used ? "" : " (ignored)", probability * 100.0 / REG_BR_PROB_BASE);
650 if (bb->count)
652 fprintf (file, " exec ");
653 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, bb->count);
654 if (e)
656 fprintf (file, " hit ");
657 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, e->count);
658 fprintf (file, " (%.1f%%)", e->count * 100.0 / bb->count);
662 fprintf (file, "\n");
665 /* We can not predict the probabilities of outgoing edges of bb. Set them
666 evenly and hope for the best. */
667 static void
668 set_even_probabilities (basic_block bb)
670 int nedges = 0;
671 edge e;
672 edge_iterator ei;
674 FOR_EACH_EDGE (e, ei, bb->succs)
675 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
676 nedges ++;
677 FOR_EACH_EDGE (e, ei, bb->succs)
678 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
679 e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
680 else
681 e->probability = 0;
684 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
685 note if not already present. Remove now useless REG_BR_PRED notes. */
687 static void
688 combine_predictions_for_insn (rtx insn, basic_block bb)
690 rtx prob_note;
691 rtx *pnote;
692 rtx note;
693 int best_probability = PROB_EVEN;
694 enum br_predictor best_predictor = END_PREDICTORS;
695 int combined_probability = REG_BR_PROB_BASE / 2;
696 int d;
697 bool first_match = false;
698 bool found = false;
700 if (!can_predict_insn_p (insn))
702 set_even_probabilities (bb);
703 return;
706 prob_note = find_reg_note (insn, REG_BR_PROB, 0);
707 pnote = &REG_NOTES (insn);
708 if (dump_file)
709 fprintf (dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
710 bb->index);
712 /* We implement "first match" heuristics and use probability guessed
713 by predictor with smallest index. */
714 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
715 if (REG_NOTE_KIND (note) == REG_BR_PRED)
717 enum br_predictor predictor = ((enum br_predictor)
718 INTVAL (XEXP (XEXP (note, 0), 0)));
719 int probability = INTVAL (XEXP (XEXP (note, 0), 1));
721 found = true;
722 if (best_predictor > predictor)
723 best_probability = probability, best_predictor = predictor;
725 d = (combined_probability * probability
726 + (REG_BR_PROB_BASE - combined_probability)
727 * (REG_BR_PROB_BASE - probability));
729 /* Use FP math to avoid overflows of 32bit integers. */
730 if (d == 0)
731 /* If one probability is 0% and one 100%, avoid division by zero. */
732 combined_probability = REG_BR_PROB_BASE / 2;
733 else
734 combined_probability = (((double) combined_probability) * probability
735 * REG_BR_PROB_BASE / d + 0.5);
738 /* Decide which heuristic to use. In case we didn't match anything,
739 use no_prediction heuristic, in case we did match, use either
740 first match or Dempster-Shaffer theory depending on the flags. */
742 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
743 first_match = true;
745 if (!found)
746 dump_prediction (dump_file, PRED_NO_PREDICTION,
747 combined_probability, bb, true);
748 else
750 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability,
751 bb, !first_match);
752 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability,
753 bb, first_match);
756 if (first_match)
757 combined_probability = best_probability;
758 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
760 while (*pnote)
762 if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
764 enum br_predictor predictor = ((enum br_predictor)
765 INTVAL (XEXP (XEXP (*pnote, 0), 0)));
766 int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
768 dump_prediction (dump_file, predictor, probability, bb,
769 !first_match || best_predictor == predictor);
770 *pnote = XEXP (*pnote, 1);
772 else
773 pnote = &XEXP (*pnote, 1);
776 if (!prob_note)
778 add_reg_note (insn, REG_BR_PROB, GEN_INT (combined_probability));
780 /* Save the prediction into CFG in case we are seeing non-degenerated
781 conditional jump. */
782 if (!single_succ_p (bb))
784 BRANCH_EDGE (bb)->probability = combined_probability;
785 FALLTHRU_EDGE (bb)->probability
786 = REG_BR_PROB_BASE - combined_probability;
789 else if (!single_succ_p (bb))
791 int prob = INTVAL (XEXP (prob_note, 0));
793 BRANCH_EDGE (bb)->probability = prob;
794 FALLTHRU_EDGE (bb)->probability = REG_BR_PROB_BASE - prob;
796 else
797 single_succ_edge (bb)->probability = REG_BR_PROB_BASE;
800 /* Combine predictions into single probability and store them into CFG.
801 Remove now useless prediction entries. */
803 static void
804 combine_predictions_for_bb (basic_block bb)
806 int best_probability = PROB_EVEN;
807 enum br_predictor best_predictor = END_PREDICTORS;
808 int combined_probability = REG_BR_PROB_BASE / 2;
809 int d;
810 bool first_match = false;
811 bool found = false;
812 struct edge_prediction *pred;
813 int nedges = 0;
814 edge e, first = NULL, second = NULL;
815 edge_iterator ei;
816 void **preds;
818 FOR_EACH_EDGE (e, ei, bb->succs)
819 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
821 nedges ++;
822 if (first && !second)
823 second = e;
824 if (!first)
825 first = e;
828 /* When there is no successor or only one choice, prediction is easy.
830 We are lazy for now and predict only basic blocks with two outgoing
831 edges. It is possible to predict generic case too, but we have to
832 ignore first match heuristics and do more involved combining. Implement
833 this later. */
834 if (nedges != 2)
836 if (!bb->count)
837 set_even_probabilities (bb);
838 clear_bb_predictions (bb);
839 if (dump_file)
840 fprintf (dump_file, "%i edges in bb %i predicted to even probabilities\n",
841 nedges, bb->index);
842 return;
845 if (dump_file)
846 fprintf (dump_file, "Predictions for bb %i\n", bb->index);
848 preds = pointer_map_contains (bb_predictions, bb);
849 if (preds)
851 /* We implement "first match" heuristics and use probability guessed
852 by predictor with smallest index. */
853 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
855 enum br_predictor predictor = pred->ep_predictor;
856 int probability = pred->ep_probability;
858 if (pred->ep_edge != first)
859 probability = REG_BR_PROB_BASE - probability;
861 found = true;
862 /* First match heuristics would be widly confused if we predicted
863 both directions. */
864 if (best_predictor > predictor)
866 struct edge_prediction *pred2;
867 int prob = probability;
869 for (pred2 = (struct edge_prediction *) *preds; pred2; pred2 = pred2->ep_next)
870 if (pred2 != pred && pred2->ep_predictor == pred->ep_predictor)
872 int probability2 = pred->ep_probability;
874 if (pred2->ep_edge != first)
875 probability2 = REG_BR_PROB_BASE - probability2;
877 if ((probability < REG_BR_PROB_BASE / 2) !=
878 (probability2 < REG_BR_PROB_BASE / 2))
879 break;
881 /* If the same predictor later gave better result, go for it! */
882 if ((probability >= REG_BR_PROB_BASE / 2 && (probability2 > probability))
883 || (probability <= REG_BR_PROB_BASE / 2 && (probability2 < probability)))
884 prob = probability2;
886 if (!pred2)
887 best_probability = prob, best_predictor = predictor;
890 d = (combined_probability * probability
891 + (REG_BR_PROB_BASE - combined_probability)
892 * (REG_BR_PROB_BASE - probability));
894 /* Use FP math to avoid overflows of 32bit integers. */
895 if (d == 0)
896 /* If one probability is 0% and one 100%, avoid division by zero. */
897 combined_probability = REG_BR_PROB_BASE / 2;
898 else
899 combined_probability = (((double) combined_probability)
900 * probability
901 * REG_BR_PROB_BASE / d + 0.5);
905 /* Decide which heuristic to use. In case we didn't match anything,
906 use no_prediction heuristic, in case we did match, use either
907 first match or Dempster-Shaffer theory depending on the flags. */
909 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
910 first_match = true;
912 if (!found)
913 dump_prediction (dump_file, PRED_NO_PREDICTION, combined_probability, bb, true);
914 else
916 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability, bb,
917 !first_match);
918 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability, bb,
919 first_match);
922 if (first_match)
923 combined_probability = best_probability;
924 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
926 if (preds)
928 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
930 enum br_predictor predictor = pred->ep_predictor;
931 int probability = pred->ep_probability;
933 if (pred->ep_edge != EDGE_SUCC (bb, 0))
934 probability = REG_BR_PROB_BASE - probability;
935 dump_prediction (dump_file, predictor, probability, bb,
936 !first_match || best_predictor == predictor);
939 clear_bb_predictions (bb);
941 if (!bb->count)
943 first->probability = combined_probability;
944 second->probability = REG_BR_PROB_BASE - combined_probability;
948 /* Check if T1 and T2 satisfy the IV_COMPARE condition.
949 Return the SSA_NAME if the condition satisfies, NULL otherwise.
951 T1 and T2 should be one of the following cases:
952 1. T1 is SSA_NAME, T2 is NULL
953 2. T1 is SSA_NAME, T2 is INTEGER_CST between [-4, 4]
954 3. T2 is SSA_NAME, T1 is INTEGER_CST between [-4, 4] */
956 static tree
957 strips_small_constant (tree t1, tree t2)
959 tree ret = NULL;
960 int value = 0;
962 if (!t1)
963 return NULL;
964 else if (TREE_CODE (t1) == SSA_NAME)
965 ret = t1;
966 else if (host_integerp (t1, 0))
967 value = tree_low_cst (t1, 0);
968 else
969 return NULL;
971 if (!t2)
972 return ret;
973 else if (host_integerp (t2, 0))
974 value = tree_low_cst (t2, 0);
975 else if (TREE_CODE (t2) == SSA_NAME)
977 if (ret)
978 return NULL;
979 else
980 ret = t2;
983 if (value <= 4 && value >= -4)
984 return ret;
985 else
986 return NULL;
989 /* Return the SSA_NAME in T or T's operands.
990 Return NULL if SSA_NAME cannot be found. */
992 static tree
993 get_base_value (tree t)
995 if (TREE_CODE (t) == SSA_NAME)
996 return t;
998 if (!BINARY_CLASS_P (t))
999 return NULL;
1001 switch (TREE_OPERAND_LENGTH (t))
1003 case 1:
1004 return strips_small_constant (TREE_OPERAND (t, 0), NULL);
1005 case 2:
1006 return strips_small_constant (TREE_OPERAND (t, 0),
1007 TREE_OPERAND (t, 1));
1008 default:
1009 return NULL;
1013 /* Check the compare STMT in LOOP. If it compares an induction
1014 variable to a loop invariant, return true, and save
1015 LOOP_INVARIANT, COMPARE_CODE and LOOP_STEP.
1016 Otherwise return false and set LOOP_INVAIANT to NULL. */
1018 static bool
1019 is_comparison_with_loop_invariant_p (gimple stmt, struct loop *loop,
1020 tree *loop_invariant,
1021 enum tree_code *compare_code,
1022 int *loop_step,
1023 tree *loop_iv_base)
1025 tree op0, op1, bound, base;
1026 affine_iv iv0, iv1;
1027 enum tree_code code;
1028 int step;
1030 code = gimple_cond_code (stmt);
1031 *loop_invariant = NULL;
1033 switch (code)
1035 case GT_EXPR:
1036 case GE_EXPR:
1037 case NE_EXPR:
1038 case LT_EXPR:
1039 case LE_EXPR:
1040 case EQ_EXPR:
1041 break;
1043 default:
1044 return false;
1047 op0 = gimple_cond_lhs (stmt);
1048 op1 = gimple_cond_rhs (stmt);
1050 if ((TREE_CODE (op0) != SSA_NAME && TREE_CODE (op0) != INTEGER_CST)
1051 || (TREE_CODE (op1) != SSA_NAME && TREE_CODE (op1) != INTEGER_CST))
1052 return false;
1053 if (!simple_iv (loop, loop_containing_stmt (stmt), op0, &iv0, true))
1054 return false;
1055 if (!simple_iv (loop, loop_containing_stmt (stmt), op1, &iv1, true))
1056 return false;
1057 if (TREE_CODE (iv0.step) != INTEGER_CST
1058 || TREE_CODE (iv1.step) != INTEGER_CST)
1059 return false;
1060 if ((integer_zerop (iv0.step) && integer_zerop (iv1.step))
1061 || (!integer_zerop (iv0.step) && !integer_zerop (iv1.step)))
1062 return false;
1064 if (integer_zerop (iv0.step))
1066 if (code != NE_EXPR && code != EQ_EXPR)
1067 code = invert_tree_comparison (code, false);
1068 bound = iv0.base;
1069 base = iv1.base;
1070 if (host_integerp (iv1.step, 0))
1071 step = tree_low_cst (iv1.step, 0);
1072 else
1073 return false;
1075 else
1077 bound = iv1.base;
1078 base = iv0.base;
1079 if (host_integerp (iv0.step, 0))
1080 step = tree_low_cst (iv0.step, 0);
1081 else
1082 return false;
1085 if (TREE_CODE (bound) != INTEGER_CST)
1086 bound = get_base_value (bound);
1087 if (!bound)
1088 return false;
1089 if (TREE_CODE (base) != INTEGER_CST)
1090 base = get_base_value (base);
1091 if (!base)
1092 return false;
1094 *loop_invariant = bound;
1095 *compare_code = code;
1096 *loop_step = step;
1097 *loop_iv_base = base;
1098 return true;
1101 /* Compare two SSA_NAMEs: returns TRUE if T1 and T2 are value coherent. */
1103 static bool
1104 expr_coherent_p (tree t1, tree t2)
1106 gimple stmt;
1107 tree ssa_name_1 = NULL;
1108 tree ssa_name_2 = NULL;
1110 gcc_assert (TREE_CODE (t1) == SSA_NAME || TREE_CODE (t1) == INTEGER_CST);
1111 gcc_assert (TREE_CODE (t2) == SSA_NAME || TREE_CODE (t2) == INTEGER_CST);
1113 if (t1 == t2)
1114 return true;
1116 if (TREE_CODE (t1) == INTEGER_CST && TREE_CODE (t2) == INTEGER_CST)
1117 return true;
1118 if (TREE_CODE (t1) == INTEGER_CST || TREE_CODE (t2) == INTEGER_CST)
1119 return false;
1121 /* Check to see if t1 is expressed/defined with t2. */
1122 stmt = SSA_NAME_DEF_STMT (t1);
1123 gcc_assert (stmt != NULL);
1124 if (is_gimple_assign (stmt))
1126 ssa_name_1 = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1127 if (ssa_name_1 && ssa_name_1 == t2)
1128 return true;
1131 /* Check to see if t2 is expressed/defined with t1. */
1132 stmt = SSA_NAME_DEF_STMT (t2);
1133 gcc_assert (stmt != NULL);
1134 if (is_gimple_assign (stmt))
1136 ssa_name_2 = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1137 if (ssa_name_2 && ssa_name_2 == t1)
1138 return true;
1141 /* Compare if t1 and t2's def_stmts are identical. */
1142 if (ssa_name_2 != NULL && ssa_name_1 == ssa_name_2)
1143 return true;
1144 else
1145 return false;
1148 /* Predict branch probability of BB when BB contains a branch that compares
1149 an induction variable in LOOP with LOOP_IV_BASE_VAR to LOOP_BOUND_VAR. The
1150 loop exit is compared using LOOP_BOUND_CODE, with step of LOOP_BOUND_STEP.
1152 E.g.
1153 for (int i = 0; i < bound; i++) {
1154 if (i < bound - 2)
1155 computation_1();
1156 else
1157 computation_2();
1160 In this loop, we will predict the branch inside the loop to be taken. */
1162 static void
1163 predict_iv_comparison (struct loop *loop, basic_block bb,
1164 tree loop_bound_var,
1165 tree loop_iv_base_var,
1166 enum tree_code loop_bound_code,
1167 int loop_bound_step)
1169 gimple stmt;
1170 tree compare_var, compare_base;
1171 enum tree_code compare_code;
1172 int compare_step;
1173 edge then_edge;
1174 edge_iterator ei;
1176 if (predicted_by_p (bb, PRED_LOOP_ITERATIONS_GUESSED)
1177 || predicted_by_p (bb, PRED_LOOP_ITERATIONS)
1178 || predicted_by_p (bb, PRED_LOOP_EXIT))
1179 return;
1181 stmt = last_stmt (bb);
1182 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
1183 return;
1184 if (!is_comparison_with_loop_invariant_p (stmt, loop, &compare_var,
1185 &compare_code,
1186 &compare_step,
1187 &compare_base))
1188 return;
1190 /* Find the taken edge. */
1191 FOR_EACH_EDGE (then_edge, ei, bb->succs)
1192 if (then_edge->flags & EDGE_TRUE_VALUE)
1193 break;
1195 /* When comparing an IV to a loop invariant, NE is more likely to be
1196 taken while EQ is more likely to be not-taken. */
1197 if (compare_code == NE_EXPR)
1199 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1200 return;
1202 else if (compare_code == EQ_EXPR)
1204 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1205 return;
1208 if (!expr_coherent_p (loop_iv_base_var, compare_base))
1209 return;
1211 /* If loop bound, base and compare bound are all constants, we can
1212 calculate the probability directly. */
1213 if (host_integerp (loop_bound_var, 0)
1214 && host_integerp (compare_var, 0)
1215 && host_integerp (compare_base, 0))
1217 int probability;
1218 HOST_WIDE_INT compare_count;
1219 HOST_WIDE_INT loop_bound = tree_low_cst (loop_bound_var, 0);
1220 HOST_WIDE_INT compare_bound = tree_low_cst (compare_var, 0);
1221 HOST_WIDE_INT base = tree_low_cst (compare_base, 0);
1222 HOST_WIDE_INT loop_count = (loop_bound - base) / compare_step;
1224 if ((compare_step > 0)
1225 ^ (compare_code == LT_EXPR || compare_code == LE_EXPR))
1226 compare_count = (loop_bound - compare_bound) / compare_step;
1227 else
1228 compare_count = (compare_bound - base) / compare_step;
1230 if (compare_code == LE_EXPR || compare_code == GE_EXPR)
1231 compare_count ++;
1232 if (loop_bound_code == LE_EXPR || loop_bound_code == GE_EXPR)
1233 loop_count ++;
1234 if (compare_count < 0)
1235 compare_count = 0;
1236 if (loop_count < 0)
1237 loop_count = 0;
1239 if (loop_count == 0)
1240 probability = 0;
1241 else if (compare_count > loop_count)
1242 probability = REG_BR_PROB_BASE;
1243 else
1244 probability = (double) REG_BR_PROB_BASE * compare_count / loop_count;
1245 predict_edge (then_edge, PRED_LOOP_IV_COMPARE, probability);
1246 return;
1249 if (expr_coherent_p (loop_bound_var, compare_var))
1251 if ((loop_bound_code == LT_EXPR || loop_bound_code == LE_EXPR)
1252 && (compare_code == LT_EXPR || compare_code == LE_EXPR))
1253 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1254 else if ((loop_bound_code == GT_EXPR || loop_bound_code == GE_EXPR)
1255 && (compare_code == GT_EXPR || compare_code == GE_EXPR))
1256 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1257 else if (loop_bound_code == NE_EXPR)
1259 /* If the loop backedge condition is "(i != bound)", we do
1260 the comparison based on the step of IV:
1261 * step < 0 : backedge condition is like (i > bound)
1262 * step > 0 : backedge condition is like (i < bound) */
1263 gcc_assert (loop_bound_step != 0);
1264 if (loop_bound_step > 0
1265 && (compare_code == LT_EXPR
1266 || compare_code == LE_EXPR))
1267 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1268 else if (loop_bound_step < 0
1269 && (compare_code == GT_EXPR
1270 || compare_code == GE_EXPR))
1271 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1272 else
1273 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1275 else
1276 /* The branch is predicted not-taken if loop_bound_code is
1277 opposite with compare_code. */
1278 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1280 else if (expr_coherent_p (loop_iv_base_var, compare_var))
1282 /* For cases like:
1283 for (i = s; i < h; i++)
1284 if (i > s + 2) ....
1285 The branch should be predicted taken. */
1286 if (loop_bound_step > 0
1287 && (compare_code == GT_EXPR || compare_code == GE_EXPR))
1288 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1289 else if (loop_bound_step < 0
1290 && (compare_code == LT_EXPR || compare_code == LE_EXPR))
1291 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1292 else
1293 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1297 /* Predict edge probabilities by exploiting loop structure. */
1299 static void
1300 predict_loops (void)
1302 loop_iterator li;
1303 struct loop *loop;
1305 /* Try to predict out blocks in a loop that are not part of a
1306 natural loop. */
1307 FOR_EACH_LOOP (li, loop, 0)
1309 basic_block bb, *bbs;
1310 unsigned j, n_exits;
1311 VEC (edge, heap) *exits;
1312 struct tree_niter_desc niter_desc;
1313 edge ex;
1314 struct nb_iter_bound *nb_iter;
1315 enum tree_code loop_bound_code = ERROR_MARK;
1316 int loop_bound_step = 0;
1317 tree loop_bound_var = NULL;
1318 tree loop_iv_base = NULL;
1319 gimple stmt = NULL;
1321 exits = get_loop_exit_edges (loop);
1322 n_exits = VEC_length (edge, exits);
1324 FOR_EACH_VEC_ELT (edge, exits, j, ex)
1326 tree niter = NULL;
1327 HOST_WIDE_INT nitercst;
1328 int max = PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS);
1329 int probability;
1330 enum br_predictor predictor;
1332 if (number_of_iterations_exit (loop, ex, &niter_desc, false))
1333 niter = niter_desc.niter;
1334 if (!niter || TREE_CODE (niter_desc.niter) != INTEGER_CST)
1335 niter = loop_niter_by_eval (loop, ex);
1337 if (TREE_CODE (niter) == INTEGER_CST)
1339 if (host_integerp (niter, 1)
1340 && compare_tree_int (niter, max-1) == -1)
1341 nitercst = tree_low_cst (niter, 1) + 1;
1342 else
1343 nitercst = max;
1344 predictor = PRED_LOOP_ITERATIONS;
1346 /* If we have just one exit and we can derive some information about
1347 the number of iterations of the loop from the statements inside
1348 the loop, use it to predict this exit. */
1349 else if (n_exits == 1)
1351 nitercst = estimated_stmt_executions_int (loop);
1352 if (nitercst < 0)
1353 continue;
1354 if (nitercst > max)
1355 nitercst = max;
1357 predictor = PRED_LOOP_ITERATIONS_GUESSED;
1359 else
1360 continue;
1362 probability = ((REG_BR_PROB_BASE + nitercst / 2) / nitercst);
1363 predict_edge (ex, predictor, probability);
1365 VEC_free (edge, heap, exits);
1367 /* Find information about loop bound variables. */
1368 for (nb_iter = loop->bounds; nb_iter;
1369 nb_iter = nb_iter->next)
1370 if (nb_iter->stmt
1371 && gimple_code (nb_iter->stmt) == GIMPLE_COND)
1373 stmt = nb_iter->stmt;
1374 break;
1376 if (!stmt && last_stmt (loop->header)
1377 && gimple_code (last_stmt (loop->header)) == GIMPLE_COND)
1378 stmt = last_stmt (loop->header);
1379 if (stmt)
1380 is_comparison_with_loop_invariant_p (stmt, loop,
1381 &loop_bound_var,
1382 &loop_bound_code,
1383 &loop_bound_step,
1384 &loop_iv_base);
1386 bbs = get_loop_body (loop);
1388 for (j = 0; j < loop->num_nodes; j++)
1390 int header_found = 0;
1391 edge e;
1392 edge_iterator ei;
1394 bb = bbs[j];
1396 /* Bypass loop heuristics on continue statement. These
1397 statements construct loops via "non-loop" constructs
1398 in the source language and are better to be handled
1399 separately. */
1400 if (predicted_by_p (bb, PRED_CONTINUE))
1401 continue;
1403 /* Loop branch heuristics - predict an edge back to a
1404 loop's head as taken. */
1405 if (bb == loop->latch)
1407 e = find_edge (loop->latch, loop->header);
1408 if (e)
1410 header_found = 1;
1411 predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
1415 /* Loop exit heuristics - predict an edge exiting the loop if the
1416 conditional has no loop header successors as not taken. */
1417 if (!header_found
1418 /* If we already used more reliable loop exit predictors, do not
1419 bother with PRED_LOOP_EXIT. */
1420 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS_GUESSED)
1421 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS))
1423 /* For loop with many exits we don't want to predict all exits
1424 with the pretty large probability, because if all exits are
1425 considered in row, the loop would be predicted to iterate
1426 almost never. The code to divide probability by number of
1427 exits is very rough. It should compute the number of exits
1428 taken in each patch through function (not the overall number
1429 of exits that might be a lot higher for loops with wide switch
1430 statements in them) and compute n-th square root.
1432 We limit the minimal probability by 2% to avoid
1433 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
1434 as this was causing regression in perl benchmark containing such
1435 a wide loop. */
1437 int probability = ((REG_BR_PROB_BASE
1438 - predictor_info [(int) PRED_LOOP_EXIT].hitrate)
1439 / n_exits);
1440 if (probability < HITRATE (2))
1441 probability = HITRATE (2);
1442 FOR_EACH_EDGE (e, ei, bb->succs)
1443 if (e->dest->index < NUM_FIXED_BLOCKS
1444 || !flow_bb_inside_loop_p (loop, e->dest))
1445 predict_edge (e, PRED_LOOP_EXIT, probability);
1447 if (loop_bound_var)
1448 predict_iv_comparison (loop, bb, loop_bound_var, loop_iv_base,
1449 loop_bound_code,
1450 loop_bound_step);
1453 /* Free basic blocks from get_loop_body. */
1454 free (bbs);
1458 /* Attempt to predict probabilities of BB outgoing edges using local
1459 properties. */
1460 static void
1461 bb_estimate_probability_locally (basic_block bb)
1463 rtx last_insn = BB_END (bb);
1464 rtx cond;
1466 if (! can_predict_insn_p (last_insn))
1467 return;
1468 cond = get_condition (last_insn, NULL, false, false);
1469 if (! cond)
1470 return;
1472 /* Try "pointer heuristic."
1473 A comparison ptr == 0 is predicted as false.
1474 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1475 if (COMPARISON_P (cond)
1476 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
1477 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
1479 if (GET_CODE (cond) == EQ)
1480 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
1481 else if (GET_CODE (cond) == NE)
1482 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
1484 else
1486 /* Try "opcode heuristic."
1487 EQ tests are usually false and NE tests are usually true. Also,
1488 most quantities are positive, so we can make the appropriate guesses
1489 about signed comparisons against zero. */
1490 switch (GET_CODE (cond))
1492 case CONST_INT:
1493 /* Unconditional branch. */
1494 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
1495 cond == const0_rtx ? NOT_TAKEN : TAKEN);
1496 break;
1498 case EQ:
1499 case UNEQ:
1500 /* Floating point comparisons appears to behave in a very
1501 unpredictable way because of special role of = tests in
1502 FP code. */
1503 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
1505 /* Comparisons with 0 are often used for booleans and there is
1506 nothing useful to predict about them. */
1507 else if (XEXP (cond, 1) == const0_rtx
1508 || XEXP (cond, 0) == const0_rtx)
1510 else
1511 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
1512 break;
1514 case NE:
1515 case LTGT:
1516 /* Floating point comparisons appears to behave in a very
1517 unpredictable way because of special role of = tests in
1518 FP code. */
1519 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
1521 /* Comparisons with 0 are often used for booleans and there is
1522 nothing useful to predict about them. */
1523 else if (XEXP (cond, 1) == const0_rtx
1524 || XEXP (cond, 0) == const0_rtx)
1526 else
1527 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
1528 break;
1530 case ORDERED:
1531 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
1532 break;
1534 case UNORDERED:
1535 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
1536 break;
1538 case LE:
1539 case LT:
1540 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1541 || XEXP (cond, 1) == constm1_rtx)
1542 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
1543 break;
1545 case GE:
1546 case GT:
1547 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1548 || XEXP (cond, 1) == constm1_rtx)
1549 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
1550 break;
1552 default:
1553 break;
1557 /* Set edge->probability for each successor edge of BB. */
1558 void
1559 guess_outgoing_edge_probabilities (basic_block bb)
1561 bb_estimate_probability_locally (bb);
1562 combine_predictions_for_insn (BB_END (bb), bb);
1565 static tree expr_expected_value (tree, bitmap);
1567 /* Helper function for expr_expected_value. */
1569 static tree
1570 expr_expected_value_1 (tree type, tree op0, enum tree_code code,
1571 tree op1, bitmap visited)
1573 gimple def;
1575 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1577 if (TREE_CONSTANT (op0))
1578 return op0;
1580 if (code != SSA_NAME)
1581 return NULL_TREE;
1583 def = SSA_NAME_DEF_STMT (op0);
1585 /* If we were already here, break the infinite cycle. */
1586 if (!bitmap_set_bit (visited, SSA_NAME_VERSION (op0)))
1587 return NULL;
1589 if (gimple_code (def) == GIMPLE_PHI)
1591 /* All the arguments of the PHI node must have the same constant
1592 length. */
1593 int i, n = gimple_phi_num_args (def);
1594 tree val = NULL, new_val;
1596 for (i = 0; i < n; i++)
1598 tree arg = PHI_ARG_DEF (def, i);
1600 /* If this PHI has itself as an argument, we cannot
1601 determine the string length of this argument. However,
1602 if we can find an expected constant value for the other
1603 PHI args then we can still be sure that this is
1604 likely a constant. So be optimistic and just
1605 continue with the next argument. */
1606 if (arg == PHI_RESULT (def))
1607 continue;
1609 new_val = expr_expected_value (arg, visited);
1610 if (!new_val)
1611 return NULL;
1612 if (!val)
1613 val = new_val;
1614 else if (!operand_equal_p (val, new_val, false))
1615 return NULL;
1617 return val;
1619 if (is_gimple_assign (def))
1621 if (gimple_assign_lhs (def) != op0)
1622 return NULL;
1624 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def)),
1625 gimple_assign_rhs1 (def),
1626 gimple_assign_rhs_code (def),
1627 gimple_assign_rhs2 (def),
1628 visited);
1631 if (is_gimple_call (def))
1633 tree decl = gimple_call_fndecl (def);
1634 if (!decl)
1635 return NULL;
1636 if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
1637 switch (DECL_FUNCTION_CODE (decl))
1639 case BUILT_IN_EXPECT:
1641 tree val;
1642 if (gimple_call_num_args (def) != 2)
1643 return NULL;
1644 val = gimple_call_arg (def, 0);
1645 if (TREE_CONSTANT (val))
1646 return val;
1647 return gimple_call_arg (def, 1);
1650 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N:
1651 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1:
1652 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2:
1653 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4:
1654 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8:
1655 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16:
1656 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
1657 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N:
1658 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
1659 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
1660 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
1661 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
1662 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
1663 /* Assume that any given atomic operation has low contention,
1664 and thus the compare-and-swap operation succeeds. */
1665 return boolean_true_node;
1669 return NULL;
1672 if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS)
1674 tree res;
1675 op0 = expr_expected_value (op0, visited);
1676 if (!op0)
1677 return NULL;
1678 op1 = expr_expected_value (op1, visited);
1679 if (!op1)
1680 return NULL;
1681 res = fold_build2 (code, type, op0, op1);
1682 if (TREE_CONSTANT (res))
1683 return res;
1684 return NULL;
1686 if (get_gimple_rhs_class (code) == GIMPLE_UNARY_RHS)
1688 tree res;
1689 op0 = expr_expected_value (op0, visited);
1690 if (!op0)
1691 return NULL;
1692 res = fold_build1 (code, type, op0);
1693 if (TREE_CONSTANT (res))
1694 return res;
1695 return NULL;
1697 return NULL;
1700 /* Return constant EXPR will likely have at execution time, NULL if unknown.
1701 The function is used by builtin_expect branch predictor so the evidence
1702 must come from this construct and additional possible constant folding.
1704 We may want to implement more involved value guess (such as value range
1705 propagation based prediction), but such tricks shall go to new
1706 implementation. */
1708 static tree
1709 expr_expected_value (tree expr, bitmap visited)
1711 enum tree_code code;
1712 tree op0, op1;
1714 if (TREE_CONSTANT (expr))
1715 return expr;
1717 extract_ops_from_tree (expr, &code, &op0, &op1);
1718 return expr_expected_value_1 (TREE_TYPE (expr),
1719 op0, code, op1, visited);
1723 /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
1724 we no longer need. */
1725 static unsigned int
1726 strip_predict_hints (void)
1728 basic_block bb;
1729 gimple ass_stmt;
1730 tree var;
1732 FOR_EACH_BB (bb)
1734 gimple_stmt_iterator bi;
1735 for (bi = gsi_start_bb (bb); !gsi_end_p (bi);)
1737 gimple stmt = gsi_stmt (bi);
1739 if (gimple_code (stmt) == GIMPLE_PREDICT)
1741 gsi_remove (&bi, true);
1742 continue;
1744 else if (gimple_code (stmt) == GIMPLE_CALL)
1746 tree fndecl = gimple_call_fndecl (stmt);
1748 if (fndecl
1749 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1750 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT
1751 && gimple_call_num_args (stmt) == 2)
1753 var = gimple_call_lhs (stmt);
1754 if (var)
1756 ass_stmt
1757 = gimple_build_assign (var, gimple_call_arg (stmt, 0));
1758 gsi_replace (&bi, ass_stmt, true);
1760 else
1762 gsi_remove (&bi, true);
1763 continue;
1767 gsi_next (&bi);
1770 return 0;
1773 /* Predict using opcode of the last statement in basic block. */
1774 static void
1775 tree_predict_by_opcode (basic_block bb)
1777 gimple stmt = last_stmt (bb);
1778 edge then_edge;
1779 tree op0, op1;
1780 tree type;
1781 tree val;
1782 enum tree_code cmp;
1783 bitmap visited;
1784 edge_iterator ei;
1786 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
1787 return;
1788 FOR_EACH_EDGE (then_edge, ei, bb->succs)
1789 if (then_edge->flags & EDGE_TRUE_VALUE)
1790 break;
1791 op0 = gimple_cond_lhs (stmt);
1792 op1 = gimple_cond_rhs (stmt);
1793 cmp = gimple_cond_code (stmt);
1794 type = TREE_TYPE (op0);
1795 visited = BITMAP_ALLOC (NULL);
1796 val = expr_expected_value_1 (boolean_type_node, op0, cmp, op1, visited);
1797 BITMAP_FREE (visited);
1798 if (val)
1800 if (integer_zerop (val))
1801 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, NOT_TAKEN);
1802 else
1803 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, TAKEN);
1804 return;
1806 /* Try "pointer heuristic."
1807 A comparison ptr == 0 is predicted as false.
1808 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1809 if (POINTER_TYPE_P (type))
1811 if (cmp == EQ_EXPR)
1812 predict_edge_def (then_edge, PRED_TREE_POINTER, NOT_TAKEN);
1813 else if (cmp == NE_EXPR)
1814 predict_edge_def (then_edge, PRED_TREE_POINTER, TAKEN);
1816 else
1818 /* Try "opcode heuristic."
1819 EQ tests are usually false and NE tests are usually true. Also,
1820 most quantities are positive, so we can make the appropriate guesses
1821 about signed comparisons against zero. */
1822 switch (cmp)
1824 case EQ_EXPR:
1825 case UNEQ_EXPR:
1826 /* Floating point comparisons appears to behave in a very
1827 unpredictable way because of special role of = tests in
1828 FP code. */
1829 if (FLOAT_TYPE_P (type))
1831 /* Comparisons with 0 are often used for booleans and there is
1832 nothing useful to predict about them. */
1833 else if (integer_zerop (op0) || integer_zerop (op1))
1835 else
1836 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, NOT_TAKEN);
1837 break;
1839 case NE_EXPR:
1840 case LTGT_EXPR:
1841 /* Floating point comparisons appears to behave in a very
1842 unpredictable way because of special role of = tests in
1843 FP code. */
1844 if (FLOAT_TYPE_P (type))
1846 /* Comparisons with 0 are often used for booleans and there is
1847 nothing useful to predict about them. */
1848 else if (integer_zerop (op0)
1849 || integer_zerop (op1))
1851 else
1852 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, TAKEN);
1853 break;
1855 case ORDERED_EXPR:
1856 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, TAKEN);
1857 break;
1859 case UNORDERED_EXPR:
1860 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, NOT_TAKEN);
1861 break;
1863 case LE_EXPR:
1864 case LT_EXPR:
1865 if (integer_zerop (op1)
1866 || integer_onep (op1)
1867 || integer_all_onesp (op1)
1868 || real_zerop (op1)
1869 || real_onep (op1)
1870 || real_minus_onep (op1))
1871 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, NOT_TAKEN);
1872 break;
1874 case GE_EXPR:
1875 case GT_EXPR:
1876 if (integer_zerop (op1)
1877 || integer_onep (op1)
1878 || integer_all_onesp (op1)
1879 || real_zerop (op1)
1880 || real_onep (op1)
1881 || real_minus_onep (op1))
1882 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, TAKEN);
1883 break;
1885 default:
1886 break;
1890 /* Try to guess whether the value of return means error code. */
1892 static enum br_predictor
1893 return_prediction (tree val, enum prediction *prediction)
1895 /* VOID. */
1896 if (!val)
1897 return PRED_NO_PREDICTION;
1898 /* Different heuristics for pointers and scalars. */
1899 if (POINTER_TYPE_P (TREE_TYPE (val)))
1901 /* NULL is usually not returned. */
1902 if (integer_zerop (val))
1904 *prediction = NOT_TAKEN;
1905 return PRED_NULL_RETURN;
1908 else if (INTEGRAL_TYPE_P (TREE_TYPE (val)))
1910 /* Negative return values are often used to indicate
1911 errors. */
1912 if (TREE_CODE (val) == INTEGER_CST
1913 && tree_int_cst_sgn (val) < 0)
1915 *prediction = NOT_TAKEN;
1916 return PRED_NEGATIVE_RETURN;
1918 /* Constant return values seems to be commonly taken.
1919 Zero/one often represent booleans so exclude them from the
1920 heuristics. */
1921 if (TREE_CONSTANT (val)
1922 && (!integer_zerop (val) && !integer_onep (val)))
1924 *prediction = TAKEN;
1925 return PRED_CONST_RETURN;
1928 return PRED_NO_PREDICTION;
1931 /* Find the basic block with return expression and look up for possible
1932 return value trying to apply RETURN_PREDICTION heuristics. */
1933 static void
1934 apply_return_prediction (void)
1936 gimple return_stmt = NULL;
1937 tree return_val;
1938 edge e;
1939 gimple phi;
1940 int phi_num_args, i;
1941 enum br_predictor pred;
1942 enum prediction direction;
1943 edge_iterator ei;
1945 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
1947 return_stmt = last_stmt (e->src);
1948 if (return_stmt
1949 && gimple_code (return_stmt) == GIMPLE_RETURN)
1950 break;
1952 if (!e)
1953 return;
1954 return_val = gimple_return_retval (return_stmt);
1955 if (!return_val)
1956 return;
1957 if (TREE_CODE (return_val) != SSA_NAME
1958 || !SSA_NAME_DEF_STMT (return_val)
1959 || gimple_code (SSA_NAME_DEF_STMT (return_val)) != GIMPLE_PHI)
1960 return;
1961 phi = SSA_NAME_DEF_STMT (return_val);
1962 phi_num_args = gimple_phi_num_args (phi);
1963 pred = return_prediction (PHI_ARG_DEF (phi, 0), &direction);
1965 /* Avoid the degenerate case where all return values form the function
1966 belongs to same category (ie they are all positive constants)
1967 so we can hardly say something about them. */
1968 for (i = 1; i < phi_num_args; i++)
1969 if (pred != return_prediction (PHI_ARG_DEF (phi, i), &direction))
1970 break;
1971 if (i != phi_num_args)
1972 for (i = 0; i < phi_num_args; i++)
1974 pred = return_prediction (PHI_ARG_DEF (phi, i), &direction);
1975 if (pred != PRED_NO_PREDICTION)
1976 predict_paths_leading_to_edge (gimple_phi_arg_edge (phi, i), pred,
1977 direction);
1981 /* Look for basic block that contains unlikely to happen events
1982 (such as noreturn calls) and mark all paths leading to execution
1983 of this basic blocks as unlikely. */
1985 static void
1986 tree_bb_level_predictions (void)
1988 basic_block bb;
1989 bool has_return_edges = false;
1990 edge e;
1991 edge_iterator ei;
1993 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
1994 if (!(e->flags & (EDGE_ABNORMAL | EDGE_FAKE | EDGE_EH)))
1996 has_return_edges = true;
1997 break;
2000 apply_return_prediction ();
2002 FOR_EACH_BB (bb)
2004 gimple_stmt_iterator gsi;
2006 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2008 gimple stmt = gsi_stmt (gsi);
2009 tree decl;
2011 if (is_gimple_call (stmt))
2013 if ((gimple_call_flags (stmt) & ECF_NORETURN)
2014 && has_return_edges)
2015 predict_paths_leading_to (bb, PRED_NORETURN,
2016 NOT_TAKEN);
2017 decl = gimple_call_fndecl (stmt);
2018 if (decl
2019 && lookup_attribute ("cold",
2020 DECL_ATTRIBUTES (decl)))
2021 predict_paths_leading_to (bb, PRED_COLD_FUNCTION,
2022 NOT_TAKEN);
2024 else if (gimple_code (stmt) == GIMPLE_PREDICT)
2026 predict_paths_leading_to (bb, gimple_predict_predictor (stmt),
2027 gimple_predict_outcome (stmt));
2028 /* Keep GIMPLE_PREDICT around so early inlining will propagate
2029 hints to callers. */
2035 #ifdef ENABLE_CHECKING
2037 /* Callback for pointer_map_traverse, asserts that the pointer map is
2038 empty. */
2040 static bool
2041 assert_is_empty (const void *key ATTRIBUTE_UNUSED, void **value,
2042 void *data ATTRIBUTE_UNUSED)
2044 gcc_assert (!*value);
2045 return false;
2047 #endif
2049 /* Predict branch probabilities and estimate profile for basic block BB. */
2051 static void
2052 tree_estimate_probability_bb (basic_block bb)
2054 edge e;
2055 edge_iterator ei;
2056 gimple last;
2058 FOR_EACH_EDGE (e, ei, bb->succs)
2060 /* Predict early returns to be probable, as we've already taken
2061 care for error returns and other cases are often used for
2062 fast paths through function.
2064 Since we've already removed the return statements, we are
2065 looking for CFG like:
2067 if (conditional)
2070 goto return_block
2072 some other blocks
2073 return_block:
2074 return_stmt. */
2075 if (e->dest != bb->next_bb
2076 && e->dest != EXIT_BLOCK_PTR
2077 && single_succ_p (e->dest)
2078 && single_succ_edge (e->dest)->dest == EXIT_BLOCK_PTR
2079 && (last = last_stmt (e->dest)) != NULL
2080 && gimple_code (last) == GIMPLE_RETURN)
2082 edge e1;
2083 edge_iterator ei1;
2085 if (single_succ_p (bb))
2087 FOR_EACH_EDGE (e1, ei1, bb->preds)
2088 if (!predicted_by_p (e1->src, PRED_NULL_RETURN)
2089 && !predicted_by_p (e1->src, PRED_CONST_RETURN)
2090 && !predicted_by_p (e1->src, PRED_NEGATIVE_RETURN))
2091 predict_edge_def (e1, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
2093 else
2094 if (!predicted_by_p (e->src, PRED_NULL_RETURN)
2095 && !predicted_by_p (e->src, PRED_CONST_RETURN)
2096 && !predicted_by_p (e->src, PRED_NEGATIVE_RETURN))
2097 predict_edge_def (e, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
2100 /* Look for block we are guarding (ie we dominate it,
2101 but it doesn't postdominate us). */
2102 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
2103 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
2104 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
2106 gimple_stmt_iterator bi;
2108 /* The call heuristic claims that a guarded function call
2109 is improbable. This is because such calls are often used
2110 to signal exceptional situations such as printing error
2111 messages. */
2112 for (bi = gsi_start_bb (e->dest); !gsi_end_p (bi);
2113 gsi_next (&bi))
2115 gimple stmt = gsi_stmt (bi);
2116 if (is_gimple_call (stmt)
2117 /* Constant and pure calls are hardly used to signalize
2118 something exceptional. */
2119 && gimple_has_side_effects (stmt))
2121 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
2122 break;
2127 tree_predict_by_opcode (bb);
2130 /* Predict branch probabilities and estimate profile of the tree CFG.
2131 This function can be called from the loop optimizers to recompute
2132 the profile information. */
2134 void
2135 tree_estimate_probability (void)
2137 basic_block bb;
2139 add_noreturn_fake_exit_edges ();
2140 connect_infinite_loops_to_exit ();
2141 /* We use loop_niter_by_eval, which requires that the loops have
2142 preheaders. */
2143 create_preheaders (CP_SIMPLE_PREHEADERS);
2144 calculate_dominance_info (CDI_POST_DOMINATORS);
2146 bb_predictions = pointer_map_create ();
2147 tree_bb_level_predictions ();
2148 record_loop_exits ();
2150 if (number_of_loops () > 1)
2151 predict_loops ();
2153 FOR_EACH_BB (bb)
2154 tree_estimate_probability_bb (bb);
2156 FOR_EACH_BB (bb)
2157 combine_predictions_for_bb (bb);
2159 #ifdef ENABLE_CHECKING
2160 pointer_map_traverse (bb_predictions, assert_is_empty, NULL);
2161 #endif
2162 pointer_map_destroy (bb_predictions);
2163 bb_predictions = NULL;
2165 estimate_bb_frequencies ();
2166 free_dominance_info (CDI_POST_DOMINATORS);
2167 remove_fake_exit_edges ();
2170 /* Predict branch probabilities and estimate profile of the tree CFG.
2171 This is the driver function for PASS_PROFILE. */
2173 static unsigned int
2174 tree_estimate_probability_driver (void)
2176 unsigned nb_loops;
2178 loop_optimizer_init (0);
2179 if (dump_file && (dump_flags & TDF_DETAILS))
2180 flow_loops_dump (dump_file, NULL, 0);
2182 mark_irreducible_loops ();
2184 nb_loops = number_of_loops ();
2185 if (nb_loops > 1)
2186 scev_initialize ();
2188 tree_estimate_probability ();
2190 if (nb_loops > 1)
2191 scev_finalize ();
2193 loop_optimizer_finalize ();
2194 if (dump_file && (dump_flags & TDF_DETAILS))
2195 gimple_dump_cfg (dump_file, dump_flags);
2196 if (profile_status == PROFILE_ABSENT)
2197 profile_status = PROFILE_GUESSED;
2198 return 0;
2201 /* Predict edges to successors of CUR whose sources are not postdominated by
2202 BB by PRED and recurse to all postdominators. */
2204 static void
2205 predict_paths_for_bb (basic_block cur, basic_block bb,
2206 enum br_predictor pred,
2207 enum prediction taken,
2208 bitmap visited)
2210 edge e;
2211 edge_iterator ei;
2212 basic_block son;
2214 /* We are looking for all edges forming edge cut induced by
2215 set of all blocks postdominated by BB. */
2216 FOR_EACH_EDGE (e, ei, cur->preds)
2217 if (e->src->index >= NUM_FIXED_BLOCKS
2218 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, bb))
2220 edge e2;
2221 edge_iterator ei2;
2222 bool found = false;
2224 /* Ignore fake edges and eh, we predict them as not taken anyway. */
2225 if (e->flags & (EDGE_EH | EDGE_FAKE))
2226 continue;
2227 gcc_assert (bb == cur || dominated_by_p (CDI_POST_DOMINATORS, cur, bb));
2229 /* See if there is an edge from e->src that is not abnormal
2230 and does not lead to BB. */
2231 FOR_EACH_EDGE (e2, ei2, e->src->succs)
2232 if (e2 != e
2233 && !(e2->flags & (EDGE_EH | EDGE_FAKE))
2234 && !dominated_by_p (CDI_POST_DOMINATORS, e2->dest, bb))
2236 found = true;
2237 break;
2240 /* If there is non-abnormal path leaving e->src, predict edge
2241 using predictor. Otherwise we need to look for paths
2242 leading to e->src.
2244 The second may lead to infinite loop in the case we are predicitng
2245 regions that are only reachable by abnormal edges. We simply
2246 prevent visiting given BB twice. */
2247 if (found)
2248 predict_edge_def (e, pred, taken);
2249 else if (bitmap_set_bit (visited, e->src->index))
2250 predict_paths_for_bb (e->src, e->src, pred, taken, visited);
2252 for (son = first_dom_son (CDI_POST_DOMINATORS, cur);
2253 son;
2254 son = next_dom_son (CDI_POST_DOMINATORS, son))
2255 predict_paths_for_bb (son, bb, pred, taken, visited);
2258 /* Sets branch probabilities according to PREDiction and
2259 FLAGS. */
2261 static void
2262 predict_paths_leading_to (basic_block bb, enum br_predictor pred,
2263 enum prediction taken)
2265 bitmap visited = BITMAP_ALLOC (NULL);
2266 predict_paths_for_bb (bb, bb, pred, taken, visited);
2267 BITMAP_FREE (visited);
2270 /* Like predict_paths_leading_to but take edge instead of basic block. */
2272 static void
2273 predict_paths_leading_to_edge (edge e, enum br_predictor pred,
2274 enum prediction taken)
2276 bool has_nonloop_edge = false;
2277 edge_iterator ei;
2278 edge e2;
2280 basic_block bb = e->src;
2281 FOR_EACH_EDGE (e2, ei, bb->succs)
2282 if (e2->dest != e->src && e2->dest != e->dest
2283 && !(e->flags & (EDGE_EH | EDGE_FAKE))
2284 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e2->dest))
2286 has_nonloop_edge = true;
2287 break;
2289 if (!has_nonloop_edge)
2291 bitmap visited = BITMAP_ALLOC (NULL);
2292 predict_paths_for_bb (bb, bb, pred, taken, visited);
2293 BITMAP_FREE (visited);
2295 else
2296 predict_edge_def (e, pred, taken);
2299 /* This is used to carry information about basic blocks. It is
2300 attached to the AUX field of the standard CFG block. */
2302 typedef struct block_info_def
2304 /* Estimated frequency of execution of basic_block. */
2305 sreal frequency;
2307 /* To keep queue of basic blocks to process. */
2308 basic_block next;
2310 /* Number of predecessors we need to visit first. */
2311 int npredecessors;
2312 } *block_info;
2314 /* Similar information for edges. */
2315 typedef struct edge_info_def
2317 /* In case edge is a loopback edge, the probability edge will be reached
2318 in case header is. Estimated number of iterations of the loop can be
2319 then computed as 1 / (1 - back_edge_prob). */
2320 sreal back_edge_prob;
2321 /* True if the edge is a loopback edge in the natural loop. */
2322 unsigned int back_edge:1;
2323 } *edge_info;
2325 #define BLOCK_INFO(B) ((block_info) (B)->aux)
2326 #define EDGE_INFO(E) ((edge_info) (E)->aux)
2328 /* Helper function for estimate_bb_frequencies.
2329 Propagate the frequencies in blocks marked in
2330 TOVISIT, starting in HEAD. */
2332 static void
2333 propagate_freq (basic_block head, bitmap tovisit)
2335 basic_block bb;
2336 basic_block last;
2337 unsigned i;
2338 edge e;
2339 basic_block nextbb;
2340 bitmap_iterator bi;
2342 /* For each basic block we need to visit count number of his predecessors
2343 we need to visit first. */
2344 EXECUTE_IF_SET_IN_BITMAP (tovisit, 0, i, bi)
2346 edge_iterator ei;
2347 int count = 0;
2349 bb = BASIC_BLOCK (i);
2351 FOR_EACH_EDGE (e, ei, bb->preds)
2353 bool visit = bitmap_bit_p (tovisit, e->src->index);
2355 if (visit && !(e->flags & EDGE_DFS_BACK))
2356 count++;
2357 else if (visit && dump_file && !EDGE_INFO (e)->back_edge)
2358 fprintf (dump_file,
2359 "Irreducible region hit, ignoring edge to %i->%i\n",
2360 e->src->index, bb->index);
2362 BLOCK_INFO (bb)->npredecessors = count;
2363 /* When function never returns, we will never process exit block. */
2364 if (!count && bb == EXIT_BLOCK_PTR)
2365 bb->count = bb->frequency = 0;
2368 memcpy (&BLOCK_INFO (head)->frequency, &real_one, sizeof (real_one));
2369 last = head;
2370 for (bb = head; bb; bb = nextbb)
2372 edge_iterator ei;
2373 sreal cyclic_probability, frequency;
2375 memcpy (&cyclic_probability, &real_zero, sizeof (real_zero));
2376 memcpy (&frequency, &real_zero, sizeof (real_zero));
2378 nextbb = BLOCK_INFO (bb)->next;
2379 BLOCK_INFO (bb)->next = NULL;
2381 /* Compute frequency of basic block. */
2382 if (bb != head)
2384 #ifdef ENABLE_CHECKING
2385 FOR_EACH_EDGE (e, ei, bb->preds)
2386 gcc_assert (!bitmap_bit_p (tovisit, e->src->index)
2387 || (e->flags & EDGE_DFS_BACK));
2388 #endif
2390 FOR_EACH_EDGE (e, ei, bb->preds)
2391 if (EDGE_INFO (e)->back_edge)
2393 sreal_add (&cyclic_probability, &cyclic_probability,
2394 &EDGE_INFO (e)->back_edge_prob);
2396 else if (!(e->flags & EDGE_DFS_BACK))
2398 sreal tmp;
2400 /* frequency += (e->probability
2401 * BLOCK_INFO (e->src)->frequency /
2402 REG_BR_PROB_BASE); */
2404 sreal_init (&tmp, e->probability, 0);
2405 sreal_mul (&tmp, &tmp, &BLOCK_INFO (e->src)->frequency);
2406 sreal_mul (&tmp, &tmp, &real_inv_br_prob_base);
2407 sreal_add (&frequency, &frequency, &tmp);
2410 if (sreal_compare (&cyclic_probability, &real_zero) == 0)
2412 memcpy (&BLOCK_INFO (bb)->frequency, &frequency,
2413 sizeof (frequency));
2415 else
2417 if (sreal_compare (&cyclic_probability, &real_almost_one) > 0)
2419 memcpy (&cyclic_probability, &real_almost_one,
2420 sizeof (real_almost_one));
2423 /* BLOCK_INFO (bb)->frequency = frequency
2424 / (1 - cyclic_probability) */
2426 sreal_sub (&cyclic_probability, &real_one, &cyclic_probability);
2427 sreal_div (&BLOCK_INFO (bb)->frequency,
2428 &frequency, &cyclic_probability);
2432 bitmap_clear_bit (tovisit, bb->index);
2434 e = find_edge (bb, head);
2435 if (e)
2437 sreal tmp;
2439 /* EDGE_INFO (e)->back_edge_prob
2440 = ((e->probability * BLOCK_INFO (bb)->frequency)
2441 / REG_BR_PROB_BASE); */
2443 sreal_init (&tmp, e->probability, 0);
2444 sreal_mul (&tmp, &tmp, &BLOCK_INFO (bb)->frequency);
2445 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
2446 &tmp, &real_inv_br_prob_base);
2449 /* Propagate to successor blocks. */
2450 FOR_EACH_EDGE (e, ei, bb->succs)
2451 if (!(e->flags & EDGE_DFS_BACK)
2452 && BLOCK_INFO (e->dest)->npredecessors)
2454 BLOCK_INFO (e->dest)->npredecessors--;
2455 if (!BLOCK_INFO (e->dest)->npredecessors)
2457 if (!nextbb)
2458 nextbb = e->dest;
2459 else
2460 BLOCK_INFO (last)->next = e->dest;
2462 last = e->dest;
2468 /* Estimate probabilities of loopback edges in loops at same nest level. */
2470 static void
2471 estimate_loops_at_level (struct loop *first_loop)
2473 struct loop *loop;
2475 for (loop = first_loop; loop; loop = loop->next)
2477 edge e;
2478 basic_block *bbs;
2479 unsigned i;
2480 bitmap tovisit = BITMAP_ALLOC (NULL);
2482 estimate_loops_at_level (loop->inner);
2484 /* Find current loop back edge and mark it. */
2485 e = loop_latch_edge (loop);
2486 EDGE_INFO (e)->back_edge = 1;
2488 bbs = get_loop_body (loop);
2489 for (i = 0; i < loop->num_nodes; i++)
2490 bitmap_set_bit (tovisit, bbs[i]->index);
2491 free (bbs);
2492 propagate_freq (loop->header, tovisit);
2493 BITMAP_FREE (tovisit);
2497 /* Propagates frequencies through structure of loops. */
2499 static void
2500 estimate_loops (void)
2502 bitmap tovisit = BITMAP_ALLOC (NULL);
2503 basic_block bb;
2505 /* Start by estimating the frequencies in the loops. */
2506 if (number_of_loops () > 1)
2507 estimate_loops_at_level (current_loops->tree_root->inner);
2509 /* Now propagate the frequencies through all the blocks. */
2510 FOR_ALL_BB (bb)
2512 bitmap_set_bit (tovisit, bb->index);
2514 propagate_freq (ENTRY_BLOCK_PTR, tovisit);
2515 BITMAP_FREE (tovisit);
2518 /* Convert counts measured by profile driven feedback to frequencies.
2519 Return nonzero iff there was any nonzero execution count. */
2522 counts_to_freqs (void)
2524 gcov_type count_max, true_count_max = 0;
2525 basic_block bb;
2527 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2528 true_count_max = MAX (bb->count, true_count_max);
2530 count_max = MAX (true_count_max, 1);
2531 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2532 bb->frequency = (bb->count * BB_FREQ_MAX + count_max / 2) / count_max;
2534 return true_count_max;
2537 /* Return true if function is likely to be expensive, so there is no point to
2538 optimize performance of prologue, epilogue or do inlining at the expense
2539 of code size growth. THRESHOLD is the limit of number of instructions
2540 function can execute at average to be still considered not expensive. */
2542 bool
2543 expensive_function_p (int threshold)
2545 unsigned int sum = 0;
2546 basic_block bb;
2547 unsigned int limit;
2549 /* We can not compute accurately for large thresholds due to scaled
2550 frequencies. */
2551 gcc_assert (threshold <= BB_FREQ_MAX);
2553 /* Frequencies are out of range. This either means that function contains
2554 internal loop executing more than BB_FREQ_MAX times or profile feedback
2555 is available and function has not been executed at all. */
2556 if (ENTRY_BLOCK_PTR->frequency == 0)
2557 return true;
2559 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
2560 limit = ENTRY_BLOCK_PTR->frequency * threshold;
2561 FOR_EACH_BB (bb)
2563 rtx insn;
2565 for (insn = BB_HEAD (bb); insn != NEXT_INSN (BB_END (bb));
2566 insn = NEXT_INSN (insn))
2567 if (active_insn_p (insn))
2569 sum += bb->frequency;
2570 if (sum > limit)
2571 return true;
2575 return false;
2578 /* Estimate basic blocks frequency by given branch probabilities. */
2580 void
2581 estimate_bb_frequencies (void)
2583 basic_block bb;
2584 sreal freq_max;
2586 if (profile_status != PROFILE_READ || !counts_to_freqs ())
2588 static int real_values_initialized = 0;
2590 if (!real_values_initialized)
2592 real_values_initialized = 1;
2593 sreal_init (&real_zero, 0, 0);
2594 sreal_init (&real_one, 1, 0);
2595 sreal_init (&real_br_prob_base, REG_BR_PROB_BASE, 0);
2596 sreal_init (&real_bb_freq_max, BB_FREQ_MAX, 0);
2597 sreal_init (&real_one_half, 1, -1);
2598 sreal_div (&real_inv_br_prob_base, &real_one, &real_br_prob_base);
2599 sreal_sub (&real_almost_one, &real_one, &real_inv_br_prob_base);
2602 mark_dfs_back_edges ();
2604 single_succ_edge (ENTRY_BLOCK_PTR)->probability = REG_BR_PROB_BASE;
2606 /* Set up block info for each basic block. */
2607 alloc_aux_for_blocks (sizeof (struct block_info_def));
2608 alloc_aux_for_edges (sizeof (struct edge_info_def));
2609 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2611 edge e;
2612 edge_iterator ei;
2614 FOR_EACH_EDGE (e, ei, bb->succs)
2616 sreal_init (&EDGE_INFO (e)->back_edge_prob, e->probability, 0);
2617 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
2618 &EDGE_INFO (e)->back_edge_prob,
2619 &real_inv_br_prob_base);
2623 /* First compute probabilities locally for each loop from innermost
2624 to outermost to examine probabilities for back edges. */
2625 estimate_loops ();
2627 memcpy (&freq_max, &real_zero, sizeof (real_zero));
2628 FOR_EACH_BB (bb)
2629 if (sreal_compare (&freq_max, &BLOCK_INFO (bb)->frequency) < 0)
2630 memcpy (&freq_max, &BLOCK_INFO (bb)->frequency, sizeof (freq_max));
2632 sreal_div (&freq_max, &real_bb_freq_max, &freq_max);
2633 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2635 sreal tmp;
2637 sreal_mul (&tmp, &BLOCK_INFO (bb)->frequency, &freq_max);
2638 sreal_add (&tmp, &tmp, &real_one_half);
2639 bb->frequency = sreal_to_int (&tmp);
2642 free_aux_for_blocks ();
2643 free_aux_for_edges ();
2645 compute_function_frequency ();
2648 /* Decide whether function is hot, cold or unlikely executed. */
2649 void
2650 compute_function_frequency (void)
2652 basic_block bb;
2653 struct cgraph_node *node = cgraph_get_node (current_function_decl);
2654 if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
2655 || MAIN_NAME_P (DECL_NAME (current_function_decl)))
2656 node->only_called_at_startup = true;
2657 if (DECL_STATIC_DESTRUCTOR (current_function_decl))
2658 node->only_called_at_exit = true;
2660 if (!profile_info || !flag_branch_probabilities)
2662 int flags = flags_from_decl_or_type (current_function_decl);
2663 if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl))
2664 != NULL)
2665 node->frequency = NODE_FREQUENCY_UNLIKELY_EXECUTED;
2666 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl))
2667 != NULL)
2668 node->frequency = NODE_FREQUENCY_HOT;
2669 else if (flags & ECF_NORETURN)
2670 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
2671 else if (MAIN_NAME_P (DECL_NAME (current_function_decl)))
2672 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
2673 else if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
2674 || DECL_STATIC_DESTRUCTOR (current_function_decl))
2675 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
2676 return;
2678 node->frequency = NODE_FREQUENCY_UNLIKELY_EXECUTED;
2679 FOR_EACH_BB (bb)
2681 if (maybe_hot_bb_p (bb))
2683 node->frequency = NODE_FREQUENCY_HOT;
2684 return;
2686 if (!probably_never_executed_bb_p (bb))
2687 node->frequency = NODE_FREQUENCY_NORMAL;
2691 static bool
2692 gate_estimate_probability (void)
2694 return flag_guess_branch_prob;
2697 /* Build PREDICT_EXPR. */
2698 tree
2699 build_predict_expr (enum br_predictor predictor, enum prediction taken)
2701 tree t = build1 (PREDICT_EXPR, void_type_node,
2702 build_int_cst (integer_type_node, predictor));
2703 SET_PREDICT_EXPR_OUTCOME (t, taken);
2704 return t;
2707 const char *
2708 predictor_name (enum br_predictor predictor)
2710 return predictor_info[predictor].name;
2713 struct gimple_opt_pass pass_profile =
2716 GIMPLE_PASS,
2717 "profile_estimate", /* name */
2718 gate_estimate_probability, /* gate */
2719 tree_estimate_probability_driver, /* execute */
2720 NULL, /* sub */
2721 NULL, /* next */
2722 0, /* static_pass_number */
2723 TV_BRANCH_PROB, /* tv_id */
2724 PROP_cfg, /* properties_required */
2725 0, /* properties_provided */
2726 0, /* properties_destroyed */
2727 0, /* todo_flags_start */
2728 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
2732 struct gimple_opt_pass pass_strip_predict_hints =
2735 GIMPLE_PASS,
2736 "*strip_predict_hints", /* name */
2737 NULL, /* gate */
2738 strip_predict_hints, /* execute */
2739 NULL, /* sub */
2740 NULL, /* next */
2741 0, /* static_pass_number */
2742 TV_BRANCH_PROB, /* tv_id */
2743 PROP_cfg, /* properties_required */
2744 0, /* properties_provided */
2745 0, /* properties_destroyed */
2746 0, /* todo_flags_start */
2747 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
2751 /* Rebuild function frequencies. Passes are in general expected to
2752 maintain profile by hand, however in some cases this is not possible:
2753 for example when inlining several functions with loops freuqencies might run
2754 out of scale and thus needs to be recomputed. */
2756 void
2757 rebuild_frequencies (void)
2759 timevar_push (TV_REBUILD_FREQUENCIES);
2760 if (profile_status == PROFILE_GUESSED)
2762 loop_optimizer_init (0);
2763 add_noreturn_fake_exit_edges ();
2764 mark_irreducible_loops ();
2765 connect_infinite_loops_to_exit ();
2766 estimate_bb_frequencies ();
2767 remove_fake_exit_edges ();
2768 loop_optimizer_finalize ();
2770 else if (profile_status == PROFILE_READ)
2771 counts_to_freqs ();
2772 else
2773 gcc_unreachable ();
2774 timevar_pop (TV_REBUILD_FREQUENCIES);