1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000-2013 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
22 [1] "Branch Prediction for Free"
23 Ball and Larus; PLDI '93.
24 [2] "Static Branch Frequency and Program Profile Analysis"
25 Wu and Larus; MICRO-27.
26 [3] "Corpus-based Static Branch Prediction"
27 Calder, Grunwald, Lindsay, Martin, Mozer, and Zorn; PLDI '95. */
32 #include "coretypes.h"
37 #include "hard-reg-set.h"
38 #include "basic-block.h"
39 #include "insn-config.h"
44 #include "diagnostic-core.h"
53 #include "tree-flow.h"
55 #include "tree-pass.h"
56 #include "tree-scalar-evolution.h"
58 #include "pointer-set.h"
60 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
61 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
62 static sreal real_zero
, real_one
, real_almost_one
, real_br_prob_base
,
63 real_inv_br_prob_base
, real_one_half
, real_bb_freq_max
;
65 /* Random guesstimation given names.
66 PROV_VERY_UNLIKELY should be small enough so basic block predicted
67 by it gets bellow HOT_BB_FREQUENCY_FRANCTION. */
68 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 2000 - 1)
69 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
70 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
71 #define PROB_ALWAYS (REG_BR_PROB_BASE)
73 static void combine_predictions_for_insn (rtx
, basic_block
);
74 static void dump_prediction (FILE *, enum br_predictor
, int, basic_block
, int);
75 static void predict_paths_leading_to (basic_block
, enum br_predictor
, enum prediction
);
76 static void predict_paths_leading_to_edge (edge
, enum br_predictor
, enum prediction
);
77 static bool can_predict_insn_p (const_rtx
);
79 /* Information we hold about each branch predictor.
80 Filled using information from predict.def. */
84 const char *const name
; /* Name used in the debugging dumps. */
85 const int hitrate
; /* Expected hitrate used by
86 predict_insn_def call. */
90 /* Use given predictor without Dempster-Shaffer theory if it matches
91 using first_match heuristics. */
92 #define PRED_FLAG_FIRST_MATCH 1
94 /* Recompute hitrate in percent to our representation. */
96 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
98 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
99 static const struct predictor_info predictor_info
[]= {
100 #include "predict.def"
102 /* Upper bound on predictors. */
107 /* Return TRUE if frequency FREQ is considered to be hot. */
110 maybe_hot_frequency_p (struct function
*fun
, int freq
)
112 struct cgraph_node
*node
= cgraph_get_node (fun
->decl
);
113 if (!profile_info
|| !flag_branch_probabilities
)
115 if (node
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
)
117 if (node
->frequency
== NODE_FREQUENCY_HOT
)
120 if (profile_status_for_function (fun
) == PROFILE_ABSENT
)
122 if (node
->frequency
== NODE_FREQUENCY_EXECUTED_ONCE
123 && freq
< (ENTRY_BLOCK_PTR_FOR_FUNCTION (fun
)->frequency
* 2 / 3))
125 if (freq
< (ENTRY_BLOCK_PTR_FOR_FUNCTION (fun
)->frequency
126 / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION
)))
131 /* Return TRUE if frequency FREQ is considered to be hot. */
134 maybe_hot_count_p (struct function
*fun
, gcov_type count
)
136 gcov_working_set_t
*ws
;
137 static gcov_type min_count
= -1;
138 if (fun
&& profile_status_for_function (fun
) != PROFILE_READ
)
140 /* Code executed at most once is not hot. */
141 if (profile_info
->runs
>= count
)
145 ws
= find_working_set (PARAM_VALUE (HOT_BB_COUNT_WS_PERMILLE
));
147 min_count
= ws
->min_counter
;
149 return (count
>= min_count
);
152 /* Return true in case BB can be CPU intensive and should be optimized
153 for maximal performance. */
156 maybe_hot_bb_p (struct function
*fun
, const_basic_block bb
)
158 gcc_checking_assert (fun
);
159 if (profile_status_for_function (fun
) == PROFILE_READ
)
160 return maybe_hot_count_p (fun
, bb
->count
);
161 return maybe_hot_frequency_p (fun
, bb
->frequency
);
164 /* Return true if the call can be hot. */
167 cgraph_maybe_hot_edge_p (struct cgraph_edge
*edge
)
169 if (profile_info
&& flag_branch_probabilities
170 && !maybe_hot_count_p (NULL
,
173 if (edge
->caller
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
175 && edge
->callee
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
))
177 if (edge
->caller
->frequency
> NODE_FREQUENCY_UNLIKELY_EXECUTED
179 && edge
->callee
->frequency
<= NODE_FREQUENCY_EXECUTED_ONCE
))
183 if (edge
->caller
->frequency
== NODE_FREQUENCY_HOT
)
185 if (edge
->caller
->frequency
== NODE_FREQUENCY_EXECUTED_ONCE
186 && edge
->frequency
< CGRAPH_FREQ_BASE
* 3 / 2)
188 if (flag_guess_branch_prob
189 && edge
->frequency
<= (CGRAPH_FREQ_BASE
190 / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION
)))
195 /* Return true in case BB can be CPU intensive and should be optimized
196 for maximal performance. */
199 maybe_hot_edge_p (edge e
)
201 if (profile_status
== PROFILE_READ
)
202 return maybe_hot_count_p (cfun
, e
->count
);
203 return maybe_hot_frequency_p (cfun
, EDGE_FREQUENCY (e
));
207 /* Return true in case BB is probably never executed. */
210 probably_never_executed_bb_p (struct function
*fun
, const_basic_block bb
)
212 gcc_checking_assert (fun
);
213 if (profile_info
&& flag_branch_probabilities
)
214 return ((bb
->count
+ profile_info
->runs
/ 2) / profile_info
->runs
) == 0;
215 if ((!profile_info
|| !flag_branch_probabilities
)
216 && (cgraph_get_node (fun
->decl
)->frequency
217 == NODE_FREQUENCY_UNLIKELY_EXECUTED
))
222 /* Return true if NODE should be optimized for size. */
225 cgraph_optimize_for_size_p (struct cgraph_node
*node
)
229 if (node
&& (node
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
))
235 /* Return true when current function should always be optimized for size. */
238 optimize_function_for_size_p (struct function
*fun
)
242 if (!fun
|| !fun
->decl
)
244 return cgraph_optimize_for_size_p (cgraph_get_node (fun
->decl
));
247 /* Return true when current function should always be optimized for speed. */
250 optimize_function_for_speed_p (struct function
*fun
)
252 return !optimize_function_for_size_p (fun
);
255 /* Return TRUE when BB should be optimized for size. */
258 optimize_bb_for_size_p (const_basic_block bb
)
260 return optimize_function_for_size_p (cfun
) || !maybe_hot_bb_p (cfun
, bb
);
263 /* Return TRUE when BB should be optimized for speed. */
266 optimize_bb_for_speed_p (const_basic_block bb
)
268 return !optimize_bb_for_size_p (bb
);
271 /* Return TRUE when BB should be optimized for size. */
274 optimize_edge_for_size_p (edge e
)
276 return optimize_function_for_size_p (cfun
) || !maybe_hot_edge_p (e
);
279 /* Return TRUE when BB should be optimized for speed. */
282 optimize_edge_for_speed_p (edge e
)
284 return !optimize_edge_for_size_p (e
);
287 /* Return TRUE when BB should be optimized for size. */
290 optimize_insn_for_size_p (void)
292 return optimize_function_for_size_p (cfun
) || !crtl
->maybe_hot_insn_p
;
295 /* Return TRUE when BB should be optimized for speed. */
298 optimize_insn_for_speed_p (void)
300 return !optimize_insn_for_size_p ();
303 /* Return TRUE when LOOP should be optimized for size. */
306 optimize_loop_for_size_p (struct loop
*loop
)
308 return optimize_bb_for_size_p (loop
->header
);
311 /* Return TRUE when LOOP should be optimized for speed. */
314 optimize_loop_for_speed_p (struct loop
*loop
)
316 return optimize_bb_for_speed_p (loop
->header
);
319 /* Return TRUE when LOOP nest should be optimized for speed. */
322 optimize_loop_nest_for_speed_p (struct loop
*loop
)
324 struct loop
*l
= loop
;
325 if (optimize_loop_for_speed_p (loop
))
328 while (l
&& l
!= loop
)
330 if (optimize_loop_for_speed_p (l
))
338 while (l
!= loop
&& !l
->next
)
347 /* Return TRUE when LOOP nest should be optimized for size. */
350 optimize_loop_nest_for_size_p (struct loop
*loop
)
352 return !optimize_loop_nest_for_speed_p (loop
);
355 /* Return true when edge E is likely to be well predictable by branch
359 predictable_edge_p (edge e
)
361 if (profile_status
== PROFILE_ABSENT
)
364 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME
) * REG_BR_PROB_BASE
/ 100)
365 || (REG_BR_PROB_BASE
- e
->probability
366 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME
) * REG_BR_PROB_BASE
/ 100))
372 /* Set RTL expansion for BB profile. */
375 rtl_profile_for_bb (basic_block bb
)
377 crtl
->maybe_hot_insn_p
= maybe_hot_bb_p (cfun
, bb
);
380 /* Set RTL expansion for edge profile. */
383 rtl_profile_for_edge (edge e
)
385 crtl
->maybe_hot_insn_p
= maybe_hot_edge_p (e
);
388 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
390 default_rtl_profile (void)
392 crtl
->maybe_hot_insn_p
= true;
395 /* Return true if the one of outgoing edges is already predicted by
399 rtl_predicted_by_p (const_basic_block bb
, enum br_predictor predictor
)
402 if (!INSN_P (BB_END (bb
)))
404 for (note
= REG_NOTES (BB_END (bb
)); note
; note
= XEXP (note
, 1))
405 if (REG_NOTE_KIND (note
) == REG_BR_PRED
406 && INTVAL (XEXP (XEXP (note
, 0), 0)) == (int)predictor
)
411 /* This map contains for a basic block the list of predictions for the
414 static struct pointer_map_t
*bb_predictions
;
416 /* Structure representing predictions in tree level. */
418 struct edge_prediction
{
419 struct edge_prediction
*ep_next
;
421 enum br_predictor ep_predictor
;
425 /* Return true if the one of outgoing edges is already predicted by
429 gimple_predicted_by_p (const_basic_block bb
, enum br_predictor predictor
)
431 struct edge_prediction
*i
;
432 void **preds
= pointer_map_contains (bb_predictions
, bb
);
437 for (i
= (struct edge_prediction
*) *preds
; i
; i
= i
->ep_next
)
438 if (i
->ep_predictor
== predictor
)
443 /* Return true when the probability of edge is reliable.
445 The profile guessing code is good at predicting branch outcome (ie.
446 taken/not taken), that is predicted right slightly over 75% of time.
447 It is however notoriously poor on predicting the probability itself.
448 In general the profile appear a lot flatter (with probabilities closer
449 to 50%) than the reality so it is bad idea to use it to drive optimization
450 such as those disabling dynamic branch prediction for well predictable
453 There are two exceptions - edges leading to noreturn edges and edges
454 predicted by number of iterations heuristics are predicted well. This macro
455 should be able to distinguish those, but at the moment it simply check for
456 noreturn heuristic that is only one giving probability over 99% or bellow
457 1%. In future we might want to propagate reliability information across the
458 CFG if we find this information useful on multiple places. */
460 probability_reliable_p (int prob
)
462 return (profile_status
== PROFILE_READ
463 || (profile_status
== PROFILE_GUESSED
464 && (prob
<= HITRATE (1) || prob
>= HITRATE (99))));
467 /* Same predicate as above, working on edges. */
469 edge_probability_reliable_p (const_edge e
)
471 return probability_reliable_p (e
->probability
);
474 /* Same predicate as edge_probability_reliable_p, working on notes. */
476 br_prob_note_reliable_p (const_rtx note
)
478 gcc_assert (REG_NOTE_KIND (note
) == REG_BR_PROB
);
479 return probability_reliable_p (INTVAL (XEXP (note
, 0)));
483 predict_insn (rtx insn
, enum br_predictor predictor
, int probability
)
485 gcc_assert (any_condjump_p (insn
));
486 if (!flag_guess_branch_prob
)
489 add_reg_note (insn
, REG_BR_PRED
,
490 gen_rtx_CONCAT (VOIDmode
,
491 GEN_INT ((int) predictor
),
492 GEN_INT ((int) probability
)));
495 /* Predict insn by given predictor. */
498 predict_insn_def (rtx insn
, enum br_predictor predictor
,
499 enum prediction taken
)
501 int probability
= predictor_info
[(int) predictor
].hitrate
;
504 probability
= REG_BR_PROB_BASE
- probability
;
506 predict_insn (insn
, predictor
, probability
);
509 /* Predict edge E with given probability if possible. */
512 rtl_predict_edge (edge e
, enum br_predictor predictor
, int probability
)
515 last_insn
= BB_END (e
->src
);
517 /* We can store the branch prediction information only about
518 conditional jumps. */
519 if (!any_condjump_p (last_insn
))
522 /* We always store probability of branching. */
523 if (e
->flags
& EDGE_FALLTHRU
)
524 probability
= REG_BR_PROB_BASE
- probability
;
526 predict_insn (last_insn
, predictor
, probability
);
529 /* Predict edge E with the given PROBABILITY. */
531 gimple_predict_edge (edge e
, enum br_predictor predictor
, int probability
)
533 gcc_assert (profile_status
!= PROFILE_GUESSED
);
534 if ((e
->src
!= ENTRY_BLOCK_PTR
&& EDGE_COUNT (e
->src
->succs
) > 1)
535 && flag_guess_branch_prob
&& optimize
)
537 struct edge_prediction
*i
= XNEW (struct edge_prediction
);
538 void **preds
= pointer_map_insert (bb_predictions
, e
->src
);
540 i
->ep_next
= (struct edge_prediction
*) *preds
;
542 i
->ep_probability
= probability
;
543 i
->ep_predictor
= predictor
;
548 /* Remove all predictions on given basic block that are attached
551 remove_predictions_associated_with_edge (edge e
)
558 preds
= pointer_map_contains (bb_predictions
, e
->src
);
562 struct edge_prediction
**prediction
= (struct edge_prediction
**) preds
;
563 struct edge_prediction
*next
;
567 if ((*prediction
)->ep_edge
== e
)
569 next
= (*prediction
)->ep_next
;
574 prediction
= &((*prediction
)->ep_next
);
579 /* Clears the list of predictions stored for BB. */
582 clear_bb_predictions (basic_block bb
)
584 void **preds
= pointer_map_contains (bb_predictions
, bb
);
585 struct edge_prediction
*pred
, *next
;
590 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= next
)
592 next
= pred
->ep_next
;
598 /* Return true when we can store prediction on insn INSN.
599 At the moment we represent predictions only on conditional
600 jumps, not at computed jump or other complicated cases. */
602 can_predict_insn_p (const_rtx insn
)
604 return (JUMP_P (insn
)
605 && any_condjump_p (insn
)
606 && EDGE_COUNT (BLOCK_FOR_INSN (insn
)->succs
) >= 2);
609 /* Predict edge E by given predictor if possible. */
612 predict_edge_def (edge e
, enum br_predictor predictor
,
613 enum prediction taken
)
615 int probability
= predictor_info
[(int) predictor
].hitrate
;
618 probability
= REG_BR_PROB_BASE
- probability
;
620 predict_edge (e
, predictor
, probability
);
623 /* Invert all branch predictions or probability notes in the INSN. This needs
624 to be done each time we invert the condition used by the jump. */
627 invert_br_probabilities (rtx insn
)
631 for (note
= REG_NOTES (insn
); note
; note
= XEXP (note
, 1))
632 if (REG_NOTE_KIND (note
) == REG_BR_PROB
)
633 XEXP (note
, 0) = GEN_INT (REG_BR_PROB_BASE
- INTVAL (XEXP (note
, 0)));
634 else if (REG_NOTE_KIND (note
) == REG_BR_PRED
)
635 XEXP (XEXP (note
, 0), 1)
636 = GEN_INT (REG_BR_PROB_BASE
- INTVAL (XEXP (XEXP (note
, 0), 1)));
639 /* Dump information about the branch prediction to the output file. */
642 dump_prediction (FILE *file
, enum br_predictor predictor
, int probability
,
643 basic_block bb
, int used
)
651 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
652 if (! (e
->flags
& EDGE_FALLTHRU
))
655 fprintf (file
, " %s heuristics%s: %.1f%%",
656 predictor_info
[predictor
].name
,
657 used
? "" : " (ignored)", probability
* 100.0 / REG_BR_PROB_BASE
);
661 fprintf (file
, " exec ");
662 fprintf (file
, HOST_WIDEST_INT_PRINT_DEC
, bb
->count
);
665 fprintf (file
, " hit ");
666 fprintf (file
, HOST_WIDEST_INT_PRINT_DEC
, e
->count
);
667 fprintf (file
, " (%.1f%%)", e
->count
* 100.0 / bb
->count
);
671 fprintf (file
, "\n");
674 /* We can not predict the probabilities of outgoing edges of bb. Set them
675 evenly and hope for the best. */
677 set_even_probabilities (basic_block bb
)
683 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
684 if (!(e
->flags
& (EDGE_EH
| EDGE_FAKE
)))
686 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
687 if (!(e
->flags
& (EDGE_EH
| EDGE_FAKE
)))
688 e
->probability
= (REG_BR_PROB_BASE
+ nedges
/ 2) / nedges
;
693 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
694 note if not already present. Remove now useless REG_BR_PRED notes. */
697 combine_predictions_for_insn (rtx insn
, basic_block bb
)
702 int best_probability
= PROB_EVEN
;
703 enum br_predictor best_predictor
= END_PREDICTORS
;
704 int combined_probability
= REG_BR_PROB_BASE
/ 2;
706 bool first_match
= false;
709 if (!can_predict_insn_p (insn
))
711 set_even_probabilities (bb
);
715 prob_note
= find_reg_note (insn
, REG_BR_PROB
, 0);
716 pnote
= ®_NOTES (insn
);
718 fprintf (dump_file
, "Predictions for insn %i bb %i\n", INSN_UID (insn
),
721 /* We implement "first match" heuristics and use probability guessed
722 by predictor with smallest index. */
723 for (note
= REG_NOTES (insn
); note
; note
= XEXP (note
, 1))
724 if (REG_NOTE_KIND (note
) == REG_BR_PRED
)
726 enum br_predictor predictor
= ((enum br_predictor
)
727 INTVAL (XEXP (XEXP (note
, 0), 0)));
728 int probability
= INTVAL (XEXP (XEXP (note
, 0), 1));
731 if (best_predictor
> predictor
)
732 best_probability
= probability
, best_predictor
= predictor
;
734 d
= (combined_probability
* probability
735 + (REG_BR_PROB_BASE
- combined_probability
)
736 * (REG_BR_PROB_BASE
- probability
));
738 /* Use FP math to avoid overflows of 32bit integers. */
740 /* If one probability is 0% and one 100%, avoid division by zero. */
741 combined_probability
= REG_BR_PROB_BASE
/ 2;
743 combined_probability
= (((double) combined_probability
) * probability
744 * REG_BR_PROB_BASE
/ d
+ 0.5);
747 /* Decide which heuristic to use. In case we didn't match anything,
748 use no_prediction heuristic, in case we did match, use either
749 first match or Dempster-Shaffer theory depending on the flags. */
751 if (predictor_info
[best_predictor
].flags
& PRED_FLAG_FIRST_MATCH
)
755 dump_prediction (dump_file
, PRED_NO_PREDICTION
,
756 combined_probability
, bb
, true);
759 dump_prediction (dump_file
, PRED_DS_THEORY
, combined_probability
,
761 dump_prediction (dump_file
, PRED_FIRST_MATCH
, best_probability
,
766 combined_probability
= best_probability
;
767 dump_prediction (dump_file
, PRED_COMBINED
, combined_probability
, bb
, true);
771 if (REG_NOTE_KIND (*pnote
) == REG_BR_PRED
)
773 enum br_predictor predictor
= ((enum br_predictor
)
774 INTVAL (XEXP (XEXP (*pnote
, 0), 0)));
775 int probability
= INTVAL (XEXP (XEXP (*pnote
, 0), 1));
777 dump_prediction (dump_file
, predictor
, probability
, bb
,
778 !first_match
|| best_predictor
== predictor
);
779 *pnote
= XEXP (*pnote
, 1);
782 pnote
= &XEXP (*pnote
, 1);
787 add_reg_note (insn
, REG_BR_PROB
, GEN_INT (combined_probability
));
789 /* Save the prediction into CFG in case we are seeing non-degenerated
791 if (!single_succ_p (bb
))
793 BRANCH_EDGE (bb
)->probability
= combined_probability
;
794 FALLTHRU_EDGE (bb
)->probability
795 = REG_BR_PROB_BASE
- combined_probability
;
798 else if (!single_succ_p (bb
))
800 int prob
= INTVAL (XEXP (prob_note
, 0));
802 BRANCH_EDGE (bb
)->probability
= prob
;
803 FALLTHRU_EDGE (bb
)->probability
= REG_BR_PROB_BASE
- prob
;
806 single_succ_edge (bb
)->probability
= REG_BR_PROB_BASE
;
809 /* Combine predictions into single probability and store them into CFG.
810 Remove now useless prediction entries. */
813 combine_predictions_for_bb (basic_block bb
)
815 int best_probability
= PROB_EVEN
;
816 enum br_predictor best_predictor
= END_PREDICTORS
;
817 int combined_probability
= REG_BR_PROB_BASE
/ 2;
819 bool first_match
= false;
821 struct edge_prediction
*pred
;
823 edge e
, first
= NULL
, second
= NULL
;
827 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
828 if (!(e
->flags
& (EDGE_EH
| EDGE_FAKE
)))
831 if (first
&& !second
)
837 /* When there is no successor or only one choice, prediction is easy.
839 We are lazy for now and predict only basic blocks with two outgoing
840 edges. It is possible to predict generic case too, but we have to
841 ignore first match heuristics and do more involved combining. Implement
846 set_even_probabilities (bb
);
847 clear_bb_predictions (bb
);
849 fprintf (dump_file
, "%i edges in bb %i predicted to even probabilities\n",
855 fprintf (dump_file
, "Predictions for bb %i\n", bb
->index
);
857 preds
= pointer_map_contains (bb_predictions
, bb
);
860 /* We implement "first match" heuristics and use probability guessed
861 by predictor with smallest index. */
862 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= pred
->ep_next
)
864 enum br_predictor predictor
= pred
->ep_predictor
;
865 int probability
= pred
->ep_probability
;
867 if (pred
->ep_edge
!= first
)
868 probability
= REG_BR_PROB_BASE
- probability
;
871 /* First match heuristics would be widly confused if we predicted
873 if (best_predictor
> predictor
)
875 struct edge_prediction
*pred2
;
876 int prob
= probability
;
878 for (pred2
= (struct edge_prediction
*) *preds
; pred2
; pred2
= pred2
->ep_next
)
879 if (pred2
!= pred
&& pred2
->ep_predictor
== pred
->ep_predictor
)
881 int probability2
= pred
->ep_probability
;
883 if (pred2
->ep_edge
!= first
)
884 probability2
= REG_BR_PROB_BASE
- probability2
;
886 if ((probability
< REG_BR_PROB_BASE
/ 2) !=
887 (probability2
< REG_BR_PROB_BASE
/ 2))
890 /* If the same predictor later gave better result, go for it! */
891 if ((probability
>= REG_BR_PROB_BASE
/ 2 && (probability2
> probability
))
892 || (probability
<= REG_BR_PROB_BASE
/ 2 && (probability2
< probability
)))
896 best_probability
= prob
, best_predictor
= predictor
;
899 d
= (combined_probability
* probability
900 + (REG_BR_PROB_BASE
- combined_probability
)
901 * (REG_BR_PROB_BASE
- probability
));
903 /* Use FP math to avoid overflows of 32bit integers. */
905 /* If one probability is 0% and one 100%, avoid division by zero. */
906 combined_probability
= REG_BR_PROB_BASE
/ 2;
908 combined_probability
= (((double) combined_probability
)
910 * REG_BR_PROB_BASE
/ d
+ 0.5);
914 /* Decide which heuristic to use. In case we didn't match anything,
915 use no_prediction heuristic, in case we did match, use either
916 first match or Dempster-Shaffer theory depending on the flags. */
918 if (predictor_info
[best_predictor
].flags
& PRED_FLAG_FIRST_MATCH
)
922 dump_prediction (dump_file
, PRED_NO_PREDICTION
, combined_probability
, bb
, true);
925 dump_prediction (dump_file
, PRED_DS_THEORY
, combined_probability
, bb
,
927 dump_prediction (dump_file
, PRED_FIRST_MATCH
, best_probability
, bb
,
932 combined_probability
= best_probability
;
933 dump_prediction (dump_file
, PRED_COMBINED
, combined_probability
, bb
, true);
937 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= pred
->ep_next
)
939 enum br_predictor predictor
= pred
->ep_predictor
;
940 int probability
= pred
->ep_probability
;
942 if (pred
->ep_edge
!= EDGE_SUCC (bb
, 0))
943 probability
= REG_BR_PROB_BASE
- probability
;
944 dump_prediction (dump_file
, predictor
, probability
, bb
,
945 !first_match
|| best_predictor
== predictor
);
948 clear_bb_predictions (bb
);
952 first
->probability
= combined_probability
;
953 second
->probability
= REG_BR_PROB_BASE
- combined_probability
;
957 /* Check if T1 and T2 satisfy the IV_COMPARE condition.
958 Return the SSA_NAME if the condition satisfies, NULL otherwise.
960 T1 and T2 should be one of the following cases:
961 1. T1 is SSA_NAME, T2 is NULL
962 2. T1 is SSA_NAME, T2 is INTEGER_CST between [-4, 4]
963 3. T2 is SSA_NAME, T1 is INTEGER_CST between [-4, 4] */
966 strips_small_constant (tree t1
, tree t2
)
973 else if (TREE_CODE (t1
) == SSA_NAME
)
975 else if (host_integerp (t1
, 0))
976 value
= tree_low_cst (t1
, 0);
982 else if (host_integerp (t2
, 0))
983 value
= tree_low_cst (t2
, 0);
984 else if (TREE_CODE (t2
) == SSA_NAME
)
992 if (value
<= 4 && value
>= -4)
998 /* Return the SSA_NAME in T or T's operands.
999 Return NULL if SSA_NAME cannot be found. */
1002 get_base_value (tree t
)
1004 if (TREE_CODE (t
) == SSA_NAME
)
1007 if (!BINARY_CLASS_P (t
))
1010 switch (TREE_OPERAND_LENGTH (t
))
1013 return strips_small_constant (TREE_OPERAND (t
, 0), NULL
);
1015 return strips_small_constant (TREE_OPERAND (t
, 0),
1016 TREE_OPERAND (t
, 1));
1022 /* Check the compare STMT in LOOP. If it compares an induction
1023 variable to a loop invariant, return true, and save
1024 LOOP_INVARIANT, COMPARE_CODE and LOOP_STEP.
1025 Otherwise return false and set LOOP_INVAIANT to NULL. */
1028 is_comparison_with_loop_invariant_p (gimple stmt
, struct loop
*loop
,
1029 tree
*loop_invariant
,
1030 enum tree_code
*compare_code
,
1034 tree op0
, op1
, bound
, base
;
1036 enum tree_code code
;
1039 code
= gimple_cond_code (stmt
);
1040 *loop_invariant
= NULL
;
1056 op0
= gimple_cond_lhs (stmt
);
1057 op1
= gimple_cond_rhs (stmt
);
1059 if ((TREE_CODE (op0
) != SSA_NAME
&& TREE_CODE (op0
) != INTEGER_CST
)
1060 || (TREE_CODE (op1
) != SSA_NAME
&& TREE_CODE (op1
) != INTEGER_CST
))
1062 if (!simple_iv (loop
, loop_containing_stmt (stmt
), op0
, &iv0
, true))
1064 if (!simple_iv (loop
, loop_containing_stmt (stmt
), op1
, &iv1
, true))
1066 if (TREE_CODE (iv0
.step
) != INTEGER_CST
1067 || TREE_CODE (iv1
.step
) != INTEGER_CST
)
1069 if ((integer_zerop (iv0
.step
) && integer_zerop (iv1
.step
))
1070 || (!integer_zerop (iv0
.step
) && !integer_zerop (iv1
.step
)))
1073 if (integer_zerop (iv0
.step
))
1075 if (code
!= NE_EXPR
&& code
!= EQ_EXPR
)
1076 code
= invert_tree_comparison (code
, false);
1079 if (host_integerp (iv1
.step
, 0))
1088 if (host_integerp (iv0
.step
, 0))
1094 if (TREE_CODE (bound
) != INTEGER_CST
)
1095 bound
= get_base_value (bound
);
1098 if (TREE_CODE (base
) != INTEGER_CST
)
1099 base
= get_base_value (base
);
1103 *loop_invariant
= bound
;
1104 *compare_code
= code
;
1106 *loop_iv_base
= base
;
1110 /* Compare two SSA_NAMEs: returns TRUE if T1 and T2 are value coherent. */
1113 expr_coherent_p (tree t1
, tree t2
)
1116 tree ssa_name_1
= NULL
;
1117 tree ssa_name_2
= NULL
;
1119 gcc_assert (TREE_CODE (t1
) == SSA_NAME
|| TREE_CODE (t1
) == INTEGER_CST
);
1120 gcc_assert (TREE_CODE (t2
) == SSA_NAME
|| TREE_CODE (t2
) == INTEGER_CST
);
1125 if (TREE_CODE (t1
) == INTEGER_CST
&& TREE_CODE (t2
) == INTEGER_CST
)
1127 if (TREE_CODE (t1
) == INTEGER_CST
|| TREE_CODE (t2
) == INTEGER_CST
)
1130 /* Check to see if t1 is expressed/defined with t2. */
1131 stmt
= SSA_NAME_DEF_STMT (t1
);
1132 gcc_assert (stmt
!= NULL
);
1133 if (is_gimple_assign (stmt
))
1135 ssa_name_1
= SINGLE_SSA_TREE_OPERAND (stmt
, SSA_OP_USE
);
1136 if (ssa_name_1
&& ssa_name_1
== t2
)
1140 /* Check to see if t2 is expressed/defined with t1. */
1141 stmt
= SSA_NAME_DEF_STMT (t2
);
1142 gcc_assert (stmt
!= NULL
);
1143 if (is_gimple_assign (stmt
))
1145 ssa_name_2
= SINGLE_SSA_TREE_OPERAND (stmt
, SSA_OP_USE
);
1146 if (ssa_name_2
&& ssa_name_2
== t1
)
1150 /* Compare if t1 and t2's def_stmts are identical. */
1151 if (ssa_name_2
!= NULL
&& ssa_name_1
== ssa_name_2
)
1157 /* Predict branch probability of BB when BB contains a branch that compares
1158 an induction variable in LOOP with LOOP_IV_BASE_VAR to LOOP_BOUND_VAR. The
1159 loop exit is compared using LOOP_BOUND_CODE, with step of LOOP_BOUND_STEP.
1162 for (int i = 0; i < bound; i++) {
1169 In this loop, we will predict the branch inside the loop to be taken. */
1172 predict_iv_comparison (struct loop
*loop
, basic_block bb
,
1173 tree loop_bound_var
,
1174 tree loop_iv_base_var
,
1175 enum tree_code loop_bound_code
,
1176 int loop_bound_step
)
1179 tree compare_var
, compare_base
;
1180 enum tree_code compare_code
;
1181 tree compare_step_var
;
1185 if (predicted_by_p (bb
, PRED_LOOP_ITERATIONS_GUESSED
)
1186 || predicted_by_p (bb
, PRED_LOOP_ITERATIONS
)
1187 || predicted_by_p (bb
, PRED_LOOP_EXIT
))
1190 stmt
= last_stmt (bb
);
1191 if (!stmt
|| gimple_code (stmt
) != GIMPLE_COND
)
1193 if (!is_comparison_with_loop_invariant_p (stmt
, loop
, &compare_var
,
1199 /* Find the taken edge. */
1200 FOR_EACH_EDGE (then_edge
, ei
, bb
->succs
)
1201 if (then_edge
->flags
& EDGE_TRUE_VALUE
)
1204 /* When comparing an IV to a loop invariant, NE is more likely to be
1205 taken while EQ is more likely to be not-taken. */
1206 if (compare_code
== NE_EXPR
)
1208 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1211 else if (compare_code
== EQ_EXPR
)
1213 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1217 if (!expr_coherent_p (loop_iv_base_var
, compare_base
))
1220 /* If loop bound, base and compare bound are all constants, we can
1221 calculate the probability directly. */
1222 if (host_integerp (loop_bound_var
, 0)
1223 && host_integerp (compare_var
, 0)
1224 && host_integerp (compare_base
, 0))
1227 bool of
, overflow
= false;
1228 double_int mod
, compare_count
, tem
, loop_count
;
1230 double_int loop_bound
= tree_to_double_int (loop_bound_var
);
1231 double_int compare_bound
= tree_to_double_int (compare_var
);
1232 double_int base
= tree_to_double_int (compare_base
);
1233 double_int compare_step
= tree_to_double_int (compare_step_var
);
1235 /* (loop_bound - base) / compare_step */
1236 tem
= loop_bound
.sub_with_overflow (base
, &of
);
1238 loop_count
= tem
.divmod_with_overflow (compare_step
,
1243 if ((!compare_step
.is_negative ())
1244 ^ (compare_code
== LT_EXPR
|| compare_code
== LE_EXPR
))
1246 /* (loop_bound - compare_bound) / compare_step */
1247 tem
= loop_bound
.sub_with_overflow (compare_bound
, &of
);
1249 compare_count
= tem
.divmod_with_overflow (compare_step
,
1256 /* (compare_bound - base) / compare_step */
1257 tem
= compare_bound
.sub_with_overflow (base
, &of
);
1259 compare_count
= tem
.divmod_with_overflow (compare_step
,
1264 if (compare_code
== LE_EXPR
|| compare_code
== GE_EXPR
)
1266 if (loop_bound_code
== LE_EXPR
|| loop_bound_code
== GE_EXPR
)
1268 if (compare_count
.is_negative ())
1269 compare_count
= double_int_zero
;
1270 if (loop_count
.is_negative ())
1271 loop_count
= double_int_zero
;
1272 if (loop_count
.is_zero ())
1274 else if (compare_count
.scmp (loop_count
) == 1)
1275 probability
= REG_BR_PROB_BASE
;
1278 /* If loop_count is too big, such that REG_BR_PROB_BASE * loop_count
1279 could overflow, shift both loop_count and compare_count right
1280 a bit so that it doesn't overflow. Note both counts are known not
1281 to be negative at this point. */
1282 int clz_bits
= clz_hwi (loop_count
.high
);
1283 gcc_assert (REG_BR_PROB_BASE
< 32768);
1286 loop_count
.arshift (16 - clz_bits
, HOST_BITS_PER_DOUBLE_INT
);
1287 compare_count
.arshift (16 - clz_bits
, HOST_BITS_PER_DOUBLE_INT
);
1289 tem
= compare_count
.mul_with_sign (double_int::from_shwi
1290 (REG_BR_PROB_BASE
), true, &of
);
1292 tem
= tem
.divmod (loop_count
, true, TRUNC_DIV_EXPR
, &mod
);
1293 probability
= tem
.to_uhwi ();
1297 predict_edge (then_edge
, PRED_LOOP_IV_COMPARE
, probability
);
1302 if (expr_coherent_p (loop_bound_var
, compare_var
))
1304 if ((loop_bound_code
== LT_EXPR
|| loop_bound_code
== LE_EXPR
)
1305 && (compare_code
== LT_EXPR
|| compare_code
== LE_EXPR
))
1306 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1307 else if ((loop_bound_code
== GT_EXPR
|| loop_bound_code
== GE_EXPR
)
1308 && (compare_code
== GT_EXPR
|| compare_code
== GE_EXPR
))
1309 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1310 else if (loop_bound_code
== NE_EXPR
)
1312 /* If the loop backedge condition is "(i != bound)", we do
1313 the comparison based on the step of IV:
1314 * step < 0 : backedge condition is like (i > bound)
1315 * step > 0 : backedge condition is like (i < bound) */
1316 gcc_assert (loop_bound_step
!= 0);
1317 if (loop_bound_step
> 0
1318 && (compare_code
== LT_EXPR
1319 || compare_code
== LE_EXPR
))
1320 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1321 else if (loop_bound_step
< 0
1322 && (compare_code
== GT_EXPR
1323 || compare_code
== GE_EXPR
))
1324 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1326 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1329 /* The branch is predicted not-taken if loop_bound_code is
1330 opposite with compare_code. */
1331 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1333 else if (expr_coherent_p (loop_iv_base_var
, compare_var
))
1336 for (i = s; i < h; i++)
1338 The branch should be predicted taken. */
1339 if (loop_bound_step
> 0
1340 && (compare_code
== GT_EXPR
|| compare_code
== GE_EXPR
))
1341 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1342 else if (loop_bound_step
< 0
1343 && (compare_code
== LT_EXPR
|| compare_code
== LE_EXPR
))
1344 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1346 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1350 /* Predict for extra loop exits that will lead to EXIT_EDGE. The extra loop
1351 exits are resulted from short-circuit conditions that will generate an
1354 if (foo() || global > 10)
1357 This will be translated into:
1362 if foo() goto BB6 else goto BB5
1364 if global > 10 goto BB6 else goto BB7
1368 iftmp = (PHI 0(BB5), 1(BB6))
1369 if iftmp == 1 goto BB8 else goto BB3
1371 outside of the loop...
1373 The edge BB7->BB8 is loop exit because BB8 is outside of the loop.
1374 From the dataflow, we can infer that BB4->BB6 and BB5->BB6 are also loop
1375 exits. This function takes BB7->BB8 as input, and finds out the extra loop
1376 exits to predict them using PRED_LOOP_EXIT. */
1379 predict_extra_loop_exits (edge exit_edge
)
1382 bool check_value_one
;
1384 tree cmp_rhs
, cmp_lhs
;
1385 gimple cmp_stmt
= last_stmt (exit_edge
->src
);
1387 if (!cmp_stmt
|| gimple_code (cmp_stmt
) != GIMPLE_COND
)
1389 cmp_rhs
= gimple_cond_rhs (cmp_stmt
);
1390 cmp_lhs
= gimple_cond_lhs (cmp_stmt
);
1391 if (!TREE_CONSTANT (cmp_rhs
)
1392 || !(integer_zerop (cmp_rhs
) || integer_onep (cmp_rhs
)))
1394 if (TREE_CODE (cmp_lhs
) != SSA_NAME
)
1397 /* If check_value_one is true, only the phi_args with value '1' will lead
1398 to loop exit. Otherwise, only the phi_args with value '0' will lead to
1400 check_value_one
= (((integer_onep (cmp_rhs
))
1401 ^ (gimple_cond_code (cmp_stmt
) == EQ_EXPR
))
1402 ^ ((exit_edge
->flags
& EDGE_TRUE_VALUE
) != 0));
1404 phi_stmt
= SSA_NAME_DEF_STMT (cmp_lhs
);
1405 if (!phi_stmt
|| gimple_code (phi_stmt
) != GIMPLE_PHI
)
1408 for (i
= 0; i
< gimple_phi_num_args (phi_stmt
); i
++)
1412 tree val
= gimple_phi_arg_def (phi_stmt
, i
);
1413 edge e
= gimple_phi_arg_edge (phi_stmt
, i
);
1415 if (!TREE_CONSTANT (val
) || !(integer_zerop (val
) || integer_onep (val
)))
1417 if ((check_value_one
^ integer_onep (val
)) == 1)
1419 if (EDGE_COUNT (e
->src
->succs
) != 1)
1421 predict_paths_leading_to_edge (e
, PRED_LOOP_EXIT
, NOT_TAKEN
);
1425 FOR_EACH_EDGE (e1
, ei
, e
->src
->preds
)
1426 predict_paths_leading_to_edge (e1
, PRED_LOOP_EXIT
, NOT_TAKEN
);
1430 /* Predict edge probabilities by exploiting loop structure. */
1433 predict_loops (void)
1438 /* Try to predict out blocks in a loop that are not part of a
1440 FOR_EACH_LOOP (li
, loop
, 0)
1442 basic_block bb
, *bbs
;
1443 unsigned j
, n_exits
;
1445 struct tree_niter_desc niter_desc
;
1447 struct nb_iter_bound
*nb_iter
;
1448 enum tree_code loop_bound_code
= ERROR_MARK
;
1449 tree loop_bound_step
= NULL
;
1450 tree loop_bound_var
= NULL
;
1451 tree loop_iv_base
= NULL
;
1454 exits
= get_loop_exit_edges (loop
);
1455 n_exits
= exits
.length ();
1462 FOR_EACH_VEC_ELT (exits
, j
, ex
)
1465 HOST_WIDE_INT nitercst
;
1466 int max
= PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS
);
1468 enum br_predictor predictor
;
1470 predict_extra_loop_exits (ex
);
1472 if (number_of_iterations_exit (loop
, ex
, &niter_desc
, false, false))
1473 niter
= niter_desc
.niter
;
1474 if (!niter
|| TREE_CODE (niter_desc
.niter
) != INTEGER_CST
)
1475 niter
= loop_niter_by_eval (loop
, ex
);
1477 if (TREE_CODE (niter
) == INTEGER_CST
)
1479 if (host_integerp (niter
, 1)
1481 && compare_tree_int (niter
, max
- 1) == -1)
1482 nitercst
= tree_low_cst (niter
, 1) + 1;
1485 predictor
= PRED_LOOP_ITERATIONS
;
1487 /* If we have just one exit and we can derive some information about
1488 the number of iterations of the loop from the statements inside
1489 the loop, use it to predict this exit. */
1490 else if (n_exits
== 1)
1492 nitercst
= estimated_stmt_executions_int (loop
);
1498 predictor
= PRED_LOOP_ITERATIONS_GUESSED
;
1503 /* If the prediction for number of iterations is zero, do not
1504 predict the exit edges. */
1508 probability
= ((REG_BR_PROB_BASE
+ nitercst
/ 2) / nitercst
);
1509 predict_edge (ex
, predictor
, probability
);
1513 /* Find information about loop bound variables. */
1514 for (nb_iter
= loop
->bounds
; nb_iter
;
1515 nb_iter
= nb_iter
->next
)
1517 && gimple_code (nb_iter
->stmt
) == GIMPLE_COND
)
1519 stmt
= nb_iter
->stmt
;
1522 if (!stmt
&& last_stmt (loop
->header
)
1523 && gimple_code (last_stmt (loop
->header
)) == GIMPLE_COND
)
1524 stmt
= last_stmt (loop
->header
);
1526 is_comparison_with_loop_invariant_p (stmt
, loop
,
1532 bbs
= get_loop_body (loop
);
1534 for (j
= 0; j
< loop
->num_nodes
; j
++)
1536 int header_found
= 0;
1542 /* Bypass loop heuristics on continue statement. These
1543 statements construct loops via "non-loop" constructs
1544 in the source language and are better to be handled
1546 if (predicted_by_p (bb
, PRED_CONTINUE
))
1549 /* Loop branch heuristics - predict an edge back to a
1550 loop's head as taken. */
1551 if (bb
== loop
->latch
)
1553 e
= find_edge (loop
->latch
, loop
->header
);
1557 predict_edge_def (e
, PRED_LOOP_BRANCH
, TAKEN
);
1561 /* Loop exit heuristics - predict an edge exiting the loop if the
1562 conditional has no loop header successors as not taken. */
1564 /* If we already used more reliable loop exit predictors, do not
1565 bother with PRED_LOOP_EXIT. */
1566 && !predicted_by_p (bb
, PRED_LOOP_ITERATIONS_GUESSED
)
1567 && !predicted_by_p (bb
, PRED_LOOP_ITERATIONS
))
1569 /* For loop with many exits we don't want to predict all exits
1570 with the pretty large probability, because if all exits are
1571 considered in row, the loop would be predicted to iterate
1572 almost never. The code to divide probability by number of
1573 exits is very rough. It should compute the number of exits
1574 taken in each patch through function (not the overall number
1575 of exits that might be a lot higher for loops with wide switch
1576 statements in them) and compute n-th square root.
1578 We limit the minimal probability by 2% to avoid
1579 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
1580 as this was causing regression in perl benchmark containing such
1583 int probability
= ((REG_BR_PROB_BASE
1584 - predictor_info
[(int) PRED_LOOP_EXIT
].hitrate
)
1586 if (probability
< HITRATE (2))
1587 probability
= HITRATE (2);
1588 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1589 if (e
->dest
->index
< NUM_FIXED_BLOCKS
1590 || !flow_bb_inside_loop_p (loop
, e
->dest
))
1591 predict_edge (e
, PRED_LOOP_EXIT
, probability
);
1594 predict_iv_comparison (loop
, bb
, loop_bound_var
, loop_iv_base
,
1596 tree_low_cst (loop_bound_step
, 0));
1599 /* Free basic blocks from get_loop_body. */
1604 /* Attempt to predict probabilities of BB outgoing edges using local
1607 bb_estimate_probability_locally (basic_block bb
)
1609 rtx last_insn
= BB_END (bb
);
1612 if (! can_predict_insn_p (last_insn
))
1614 cond
= get_condition (last_insn
, NULL
, false, false);
1618 /* Try "pointer heuristic."
1619 A comparison ptr == 0 is predicted as false.
1620 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1621 if (COMPARISON_P (cond
)
1622 && ((REG_P (XEXP (cond
, 0)) && REG_POINTER (XEXP (cond
, 0)))
1623 || (REG_P (XEXP (cond
, 1)) && REG_POINTER (XEXP (cond
, 1)))))
1625 if (GET_CODE (cond
) == EQ
)
1626 predict_insn_def (last_insn
, PRED_POINTER
, NOT_TAKEN
);
1627 else if (GET_CODE (cond
) == NE
)
1628 predict_insn_def (last_insn
, PRED_POINTER
, TAKEN
);
1632 /* Try "opcode heuristic."
1633 EQ tests are usually false and NE tests are usually true. Also,
1634 most quantities are positive, so we can make the appropriate guesses
1635 about signed comparisons against zero. */
1636 switch (GET_CODE (cond
))
1639 /* Unconditional branch. */
1640 predict_insn_def (last_insn
, PRED_UNCONDITIONAL
,
1641 cond
== const0_rtx
? NOT_TAKEN
: TAKEN
);
1646 /* Floating point comparisons appears to behave in a very
1647 unpredictable way because of special role of = tests in
1649 if (FLOAT_MODE_P (GET_MODE (XEXP (cond
, 0))))
1651 /* Comparisons with 0 are often used for booleans and there is
1652 nothing useful to predict about them. */
1653 else if (XEXP (cond
, 1) == const0_rtx
1654 || XEXP (cond
, 0) == const0_rtx
)
1657 predict_insn_def (last_insn
, PRED_OPCODE_NONEQUAL
, NOT_TAKEN
);
1662 /* Floating point comparisons appears to behave in a very
1663 unpredictable way because of special role of = tests in
1665 if (FLOAT_MODE_P (GET_MODE (XEXP (cond
, 0))))
1667 /* Comparisons with 0 are often used for booleans and there is
1668 nothing useful to predict about them. */
1669 else if (XEXP (cond
, 1) == const0_rtx
1670 || XEXP (cond
, 0) == const0_rtx
)
1673 predict_insn_def (last_insn
, PRED_OPCODE_NONEQUAL
, TAKEN
);
1677 predict_insn_def (last_insn
, PRED_FPOPCODE
, TAKEN
);
1681 predict_insn_def (last_insn
, PRED_FPOPCODE
, NOT_TAKEN
);
1686 if (XEXP (cond
, 1) == const0_rtx
|| XEXP (cond
, 1) == const1_rtx
1687 || XEXP (cond
, 1) == constm1_rtx
)
1688 predict_insn_def (last_insn
, PRED_OPCODE_POSITIVE
, NOT_TAKEN
);
1693 if (XEXP (cond
, 1) == const0_rtx
|| XEXP (cond
, 1) == const1_rtx
1694 || XEXP (cond
, 1) == constm1_rtx
)
1695 predict_insn_def (last_insn
, PRED_OPCODE_POSITIVE
, TAKEN
);
1703 /* Set edge->probability for each successor edge of BB. */
1705 guess_outgoing_edge_probabilities (basic_block bb
)
1707 bb_estimate_probability_locally (bb
);
1708 combine_predictions_for_insn (BB_END (bb
), bb
);
1711 static tree
expr_expected_value (tree
, bitmap
);
1713 /* Helper function for expr_expected_value. */
1716 expr_expected_value_1 (tree type
, tree op0
, enum tree_code code
,
1717 tree op1
, bitmap visited
)
1721 if (get_gimple_rhs_class (code
) == GIMPLE_SINGLE_RHS
)
1723 if (TREE_CONSTANT (op0
))
1726 if (code
!= SSA_NAME
)
1729 def
= SSA_NAME_DEF_STMT (op0
);
1731 /* If we were already here, break the infinite cycle. */
1732 if (!bitmap_set_bit (visited
, SSA_NAME_VERSION (op0
)))
1735 if (gimple_code (def
) == GIMPLE_PHI
)
1737 /* All the arguments of the PHI node must have the same constant
1739 int i
, n
= gimple_phi_num_args (def
);
1740 tree val
= NULL
, new_val
;
1742 for (i
= 0; i
< n
; i
++)
1744 tree arg
= PHI_ARG_DEF (def
, i
);
1746 /* If this PHI has itself as an argument, we cannot
1747 determine the string length of this argument. However,
1748 if we can find an expected constant value for the other
1749 PHI args then we can still be sure that this is
1750 likely a constant. So be optimistic and just
1751 continue with the next argument. */
1752 if (arg
== PHI_RESULT (def
))
1755 new_val
= expr_expected_value (arg
, visited
);
1760 else if (!operand_equal_p (val
, new_val
, false))
1765 if (is_gimple_assign (def
))
1767 if (gimple_assign_lhs (def
) != op0
)
1770 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def
)),
1771 gimple_assign_rhs1 (def
),
1772 gimple_assign_rhs_code (def
),
1773 gimple_assign_rhs2 (def
),
1777 if (is_gimple_call (def
))
1779 tree decl
= gimple_call_fndecl (def
);
1782 if (DECL_BUILT_IN_CLASS (decl
) == BUILT_IN_NORMAL
)
1783 switch (DECL_FUNCTION_CODE (decl
))
1785 case BUILT_IN_EXPECT
:
1788 if (gimple_call_num_args (def
) != 2)
1790 val
= gimple_call_arg (def
, 0);
1791 if (TREE_CONSTANT (val
))
1793 return gimple_call_arg (def
, 1);
1796 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
:
1797 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1
:
1798 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2
:
1799 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4
:
1800 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8
:
1801 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16
:
1802 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE
:
1803 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N
:
1804 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1
:
1805 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2
:
1806 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4
:
1807 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8
:
1808 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16
:
1809 /* Assume that any given atomic operation has low contention,
1810 and thus the compare-and-swap operation succeeds. */
1811 return boolean_true_node
;
1818 if (get_gimple_rhs_class (code
) == GIMPLE_BINARY_RHS
)
1821 op0
= expr_expected_value (op0
, visited
);
1824 op1
= expr_expected_value (op1
, visited
);
1827 res
= fold_build2 (code
, type
, op0
, op1
);
1828 if (TREE_CONSTANT (res
))
1832 if (get_gimple_rhs_class (code
) == GIMPLE_UNARY_RHS
)
1835 op0
= expr_expected_value (op0
, visited
);
1838 res
= fold_build1 (code
, type
, op0
);
1839 if (TREE_CONSTANT (res
))
1846 /* Return constant EXPR will likely have at execution time, NULL if unknown.
1847 The function is used by builtin_expect branch predictor so the evidence
1848 must come from this construct and additional possible constant folding.
1850 We may want to implement more involved value guess (such as value range
1851 propagation based prediction), but such tricks shall go to new
1855 expr_expected_value (tree expr
, bitmap visited
)
1857 enum tree_code code
;
1860 if (TREE_CONSTANT (expr
))
1863 extract_ops_from_tree (expr
, &code
, &op0
, &op1
);
1864 return expr_expected_value_1 (TREE_TYPE (expr
),
1865 op0
, code
, op1
, visited
);
1869 /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
1870 we no longer need. */
1872 strip_predict_hints (void)
1880 gimple_stmt_iterator bi
;
1881 for (bi
= gsi_start_bb (bb
); !gsi_end_p (bi
);)
1883 gimple stmt
= gsi_stmt (bi
);
1885 if (gimple_code (stmt
) == GIMPLE_PREDICT
)
1887 gsi_remove (&bi
, true);
1890 else if (gimple_code (stmt
) == GIMPLE_CALL
)
1892 tree fndecl
= gimple_call_fndecl (stmt
);
1895 && DECL_BUILT_IN_CLASS (fndecl
) == BUILT_IN_NORMAL
1896 && DECL_FUNCTION_CODE (fndecl
) == BUILT_IN_EXPECT
1897 && gimple_call_num_args (stmt
) == 2)
1899 var
= gimple_call_lhs (stmt
);
1903 = gimple_build_assign (var
, gimple_call_arg (stmt
, 0));
1904 gsi_replace (&bi
, ass_stmt
, true);
1908 gsi_remove (&bi
, true);
1919 /* Predict using opcode of the last statement in basic block. */
1921 tree_predict_by_opcode (basic_block bb
)
1923 gimple stmt
= last_stmt (bb
);
1932 if (!stmt
|| gimple_code (stmt
) != GIMPLE_COND
)
1934 FOR_EACH_EDGE (then_edge
, ei
, bb
->succs
)
1935 if (then_edge
->flags
& EDGE_TRUE_VALUE
)
1937 op0
= gimple_cond_lhs (stmt
);
1938 op1
= gimple_cond_rhs (stmt
);
1939 cmp
= gimple_cond_code (stmt
);
1940 type
= TREE_TYPE (op0
);
1941 visited
= BITMAP_ALLOC (NULL
);
1942 val
= expr_expected_value_1 (boolean_type_node
, op0
, cmp
, op1
, visited
);
1943 BITMAP_FREE (visited
);
1946 if (integer_zerop (val
))
1947 predict_edge_def (then_edge
, PRED_BUILTIN_EXPECT
, NOT_TAKEN
);
1949 predict_edge_def (then_edge
, PRED_BUILTIN_EXPECT
, TAKEN
);
1952 /* Try "pointer heuristic."
1953 A comparison ptr == 0 is predicted as false.
1954 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1955 if (POINTER_TYPE_P (type
))
1958 predict_edge_def (then_edge
, PRED_TREE_POINTER
, NOT_TAKEN
);
1959 else if (cmp
== NE_EXPR
)
1960 predict_edge_def (then_edge
, PRED_TREE_POINTER
, TAKEN
);
1964 /* Try "opcode heuristic."
1965 EQ tests are usually false and NE tests are usually true. Also,
1966 most quantities are positive, so we can make the appropriate guesses
1967 about signed comparisons against zero. */
1972 /* Floating point comparisons appears to behave in a very
1973 unpredictable way because of special role of = tests in
1975 if (FLOAT_TYPE_P (type
))
1977 /* Comparisons with 0 are often used for booleans and there is
1978 nothing useful to predict about them. */
1979 else if (integer_zerop (op0
) || integer_zerop (op1
))
1982 predict_edge_def (then_edge
, PRED_TREE_OPCODE_NONEQUAL
, NOT_TAKEN
);
1987 /* Floating point comparisons appears to behave in a very
1988 unpredictable way because of special role of = tests in
1990 if (FLOAT_TYPE_P (type
))
1992 /* Comparisons with 0 are often used for booleans and there is
1993 nothing useful to predict about them. */
1994 else if (integer_zerop (op0
)
1995 || integer_zerop (op1
))
1998 predict_edge_def (then_edge
, PRED_TREE_OPCODE_NONEQUAL
, TAKEN
);
2002 predict_edge_def (then_edge
, PRED_TREE_FPOPCODE
, TAKEN
);
2005 case UNORDERED_EXPR
:
2006 predict_edge_def (then_edge
, PRED_TREE_FPOPCODE
, NOT_TAKEN
);
2011 if (integer_zerop (op1
)
2012 || integer_onep (op1
)
2013 || integer_all_onesp (op1
)
2016 || real_minus_onep (op1
))
2017 predict_edge_def (then_edge
, PRED_TREE_OPCODE_POSITIVE
, NOT_TAKEN
);
2022 if (integer_zerop (op1
)
2023 || integer_onep (op1
)
2024 || integer_all_onesp (op1
)
2027 || real_minus_onep (op1
))
2028 predict_edge_def (then_edge
, PRED_TREE_OPCODE_POSITIVE
, TAKEN
);
2036 /* Try to guess whether the value of return means error code. */
2038 static enum br_predictor
2039 return_prediction (tree val
, enum prediction
*prediction
)
2043 return PRED_NO_PREDICTION
;
2044 /* Different heuristics for pointers and scalars. */
2045 if (POINTER_TYPE_P (TREE_TYPE (val
)))
2047 /* NULL is usually not returned. */
2048 if (integer_zerop (val
))
2050 *prediction
= NOT_TAKEN
;
2051 return PRED_NULL_RETURN
;
2054 else if (INTEGRAL_TYPE_P (TREE_TYPE (val
)))
2056 /* Negative return values are often used to indicate
2058 if (TREE_CODE (val
) == INTEGER_CST
2059 && tree_int_cst_sgn (val
) < 0)
2061 *prediction
= NOT_TAKEN
;
2062 return PRED_NEGATIVE_RETURN
;
2064 /* Constant return values seems to be commonly taken.
2065 Zero/one often represent booleans so exclude them from the
2067 if (TREE_CONSTANT (val
)
2068 && (!integer_zerop (val
) && !integer_onep (val
)))
2070 *prediction
= TAKEN
;
2071 return PRED_CONST_RETURN
;
2074 return PRED_NO_PREDICTION
;
2077 /* Find the basic block with return expression and look up for possible
2078 return value trying to apply RETURN_PREDICTION heuristics. */
2080 apply_return_prediction (void)
2082 gimple return_stmt
= NULL
;
2086 int phi_num_args
, i
;
2087 enum br_predictor pred
;
2088 enum prediction direction
;
2091 FOR_EACH_EDGE (e
, ei
, EXIT_BLOCK_PTR
->preds
)
2093 return_stmt
= last_stmt (e
->src
);
2095 && gimple_code (return_stmt
) == GIMPLE_RETURN
)
2100 return_val
= gimple_return_retval (return_stmt
);
2103 if (TREE_CODE (return_val
) != SSA_NAME
2104 || !SSA_NAME_DEF_STMT (return_val
)
2105 || gimple_code (SSA_NAME_DEF_STMT (return_val
)) != GIMPLE_PHI
)
2107 phi
= SSA_NAME_DEF_STMT (return_val
);
2108 phi_num_args
= gimple_phi_num_args (phi
);
2109 pred
= return_prediction (PHI_ARG_DEF (phi
, 0), &direction
);
2111 /* Avoid the degenerate case where all return values form the function
2112 belongs to same category (ie they are all positive constants)
2113 so we can hardly say something about them. */
2114 for (i
= 1; i
< phi_num_args
; i
++)
2115 if (pred
!= return_prediction (PHI_ARG_DEF (phi
, i
), &direction
))
2117 if (i
!= phi_num_args
)
2118 for (i
= 0; i
< phi_num_args
; i
++)
2120 pred
= return_prediction (PHI_ARG_DEF (phi
, i
), &direction
);
2121 if (pred
!= PRED_NO_PREDICTION
)
2122 predict_paths_leading_to_edge (gimple_phi_arg_edge (phi
, i
), pred
,
2127 /* Look for basic block that contains unlikely to happen events
2128 (such as noreturn calls) and mark all paths leading to execution
2129 of this basic blocks as unlikely. */
2132 tree_bb_level_predictions (void)
2135 bool has_return_edges
= false;
2139 FOR_EACH_EDGE (e
, ei
, EXIT_BLOCK_PTR
->preds
)
2140 if (!(e
->flags
& (EDGE_ABNORMAL
| EDGE_FAKE
| EDGE_EH
)))
2142 has_return_edges
= true;
2146 apply_return_prediction ();
2150 gimple_stmt_iterator gsi
;
2152 for (gsi
= gsi_start_bb (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
2154 gimple stmt
= gsi_stmt (gsi
);
2157 if (is_gimple_call (stmt
))
2159 if ((gimple_call_flags (stmt
) & ECF_NORETURN
)
2160 && has_return_edges
)
2161 predict_paths_leading_to (bb
, PRED_NORETURN
,
2163 decl
= gimple_call_fndecl (stmt
);
2165 && lookup_attribute ("cold",
2166 DECL_ATTRIBUTES (decl
)))
2167 predict_paths_leading_to (bb
, PRED_COLD_FUNCTION
,
2170 else if (gimple_code (stmt
) == GIMPLE_PREDICT
)
2172 predict_paths_leading_to (bb
, gimple_predict_predictor (stmt
),
2173 gimple_predict_outcome (stmt
));
2174 /* Keep GIMPLE_PREDICT around so early inlining will propagate
2175 hints to callers. */
2181 #ifdef ENABLE_CHECKING
2183 /* Callback for pointer_map_traverse, asserts that the pointer map is
2187 assert_is_empty (const void *key ATTRIBUTE_UNUSED
, void **value
,
2188 void *data ATTRIBUTE_UNUSED
)
2190 gcc_assert (!*value
);
2195 /* Predict branch probabilities and estimate profile for basic block BB. */
2198 tree_estimate_probability_bb (basic_block bb
)
2204 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2206 /* Predict edges to user labels with attributes. */
2207 if (e
->dest
!= EXIT_BLOCK_PTR
)
2209 gimple_stmt_iterator gi
;
2210 for (gi
= gsi_start_bb (e
->dest
); !gsi_end_p (gi
); gsi_next (&gi
))
2212 gimple stmt
= gsi_stmt (gi
);
2215 if (gimple_code (stmt
) != GIMPLE_LABEL
)
2217 decl
= gimple_label_label (stmt
);
2218 if (DECL_ARTIFICIAL (decl
))
2221 /* Finally, we have a user-defined label. */
2222 if (lookup_attribute ("cold", DECL_ATTRIBUTES (decl
)))
2223 predict_edge_def (e
, PRED_COLD_LABEL
, NOT_TAKEN
);
2224 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (decl
)))
2225 predict_edge_def (e
, PRED_HOT_LABEL
, TAKEN
);
2229 /* Predict early returns to be probable, as we've already taken
2230 care for error returns and other cases are often used for
2231 fast paths through function.
2233 Since we've already removed the return statements, we are
2234 looking for CFG like:
2244 if (e
->dest
!= bb
->next_bb
2245 && e
->dest
!= EXIT_BLOCK_PTR
2246 && single_succ_p (e
->dest
)
2247 && single_succ_edge (e
->dest
)->dest
== EXIT_BLOCK_PTR
2248 && (last
= last_stmt (e
->dest
)) != NULL
2249 && gimple_code (last
) == GIMPLE_RETURN
)
2254 if (single_succ_p (bb
))
2256 FOR_EACH_EDGE (e1
, ei1
, bb
->preds
)
2257 if (!predicted_by_p (e1
->src
, PRED_NULL_RETURN
)
2258 && !predicted_by_p (e1
->src
, PRED_CONST_RETURN
)
2259 && !predicted_by_p (e1
->src
, PRED_NEGATIVE_RETURN
))
2260 predict_edge_def (e1
, PRED_TREE_EARLY_RETURN
, NOT_TAKEN
);
2263 if (!predicted_by_p (e
->src
, PRED_NULL_RETURN
)
2264 && !predicted_by_p (e
->src
, PRED_CONST_RETURN
)
2265 && !predicted_by_p (e
->src
, PRED_NEGATIVE_RETURN
))
2266 predict_edge_def (e
, PRED_TREE_EARLY_RETURN
, NOT_TAKEN
);
2269 /* Look for block we are guarding (ie we dominate it,
2270 but it doesn't postdominate us). */
2271 if (e
->dest
!= EXIT_BLOCK_PTR
&& e
->dest
!= bb
2272 && dominated_by_p (CDI_DOMINATORS
, e
->dest
, e
->src
)
2273 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, e
->dest
))
2275 gimple_stmt_iterator bi
;
2277 /* The call heuristic claims that a guarded function call
2278 is improbable. This is because such calls are often used
2279 to signal exceptional situations such as printing error
2281 for (bi
= gsi_start_bb (e
->dest
); !gsi_end_p (bi
);
2284 gimple stmt
= gsi_stmt (bi
);
2285 if (is_gimple_call (stmt
)
2286 /* Constant and pure calls are hardly used to signalize
2287 something exceptional. */
2288 && gimple_has_side_effects (stmt
))
2290 predict_edge_def (e
, PRED_CALL
, NOT_TAKEN
);
2296 tree_predict_by_opcode (bb
);
2299 /* Predict branch probabilities and estimate profile of the tree CFG.
2300 This function can be called from the loop optimizers to recompute
2301 the profile information. */
2304 tree_estimate_probability (void)
2308 add_noreturn_fake_exit_edges ();
2309 connect_infinite_loops_to_exit ();
2310 /* We use loop_niter_by_eval, which requires that the loops have
2312 create_preheaders (CP_SIMPLE_PREHEADERS
);
2313 calculate_dominance_info (CDI_POST_DOMINATORS
);
2315 bb_predictions
= pointer_map_create ();
2316 tree_bb_level_predictions ();
2317 record_loop_exits ();
2319 if (number_of_loops () > 1)
2323 tree_estimate_probability_bb (bb
);
2326 combine_predictions_for_bb (bb
);
2328 #ifdef ENABLE_CHECKING
2329 pointer_map_traverse (bb_predictions
, assert_is_empty
, NULL
);
2331 pointer_map_destroy (bb_predictions
);
2332 bb_predictions
= NULL
;
2334 estimate_bb_frequencies ();
2335 free_dominance_info (CDI_POST_DOMINATORS
);
2336 remove_fake_exit_edges ();
2339 /* Predict branch probabilities and estimate profile of the tree CFG.
2340 This is the driver function for PASS_PROFILE. */
2343 tree_estimate_probability_driver (void)
2347 loop_optimizer_init (LOOPS_NORMAL
);
2348 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2349 flow_loops_dump (dump_file
, NULL
, 0);
2351 mark_irreducible_loops ();
2353 nb_loops
= number_of_loops ();
2357 tree_estimate_probability ();
2362 loop_optimizer_finalize ();
2363 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2364 gimple_dump_cfg (dump_file
, dump_flags
);
2365 if (profile_status
== PROFILE_ABSENT
)
2366 profile_status
= PROFILE_GUESSED
;
2370 /* Predict edges to successors of CUR whose sources are not postdominated by
2371 BB by PRED and recurse to all postdominators. */
2374 predict_paths_for_bb (basic_block cur
, basic_block bb
,
2375 enum br_predictor pred
,
2376 enum prediction taken
,
2383 /* We are looking for all edges forming edge cut induced by
2384 set of all blocks postdominated by BB. */
2385 FOR_EACH_EDGE (e
, ei
, cur
->preds
)
2386 if (e
->src
->index
>= NUM_FIXED_BLOCKS
2387 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, bb
))
2393 /* Ignore fake edges and eh, we predict them as not taken anyway. */
2394 if (e
->flags
& (EDGE_EH
| EDGE_FAKE
))
2396 gcc_assert (bb
== cur
|| dominated_by_p (CDI_POST_DOMINATORS
, cur
, bb
));
2398 /* See if there is an edge from e->src that is not abnormal
2399 and does not lead to BB. */
2400 FOR_EACH_EDGE (e2
, ei2
, e
->src
->succs
)
2402 && !(e2
->flags
& (EDGE_EH
| EDGE_FAKE
))
2403 && !dominated_by_p (CDI_POST_DOMINATORS
, e2
->dest
, bb
))
2409 /* If there is non-abnormal path leaving e->src, predict edge
2410 using predictor. Otherwise we need to look for paths
2413 The second may lead to infinite loop in the case we are predicitng
2414 regions that are only reachable by abnormal edges. We simply
2415 prevent visiting given BB twice. */
2417 predict_edge_def (e
, pred
, taken
);
2418 else if (bitmap_set_bit (visited
, e
->src
->index
))
2419 predict_paths_for_bb (e
->src
, e
->src
, pred
, taken
, visited
);
2421 for (son
= first_dom_son (CDI_POST_DOMINATORS
, cur
);
2423 son
= next_dom_son (CDI_POST_DOMINATORS
, son
))
2424 predict_paths_for_bb (son
, bb
, pred
, taken
, visited
);
2427 /* Sets branch probabilities according to PREDiction and
2431 predict_paths_leading_to (basic_block bb
, enum br_predictor pred
,
2432 enum prediction taken
)
2434 bitmap visited
= BITMAP_ALLOC (NULL
);
2435 predict_paths_for_bb (bb
, bb
, pred
, taken
, visited
);
2436 BITMAP_FREE (visited
);
2439 /* Like predict_paths_leading_to but take edge instead of basic block. */
2442 predict_paths_leading_to_edge (edge e
, enum br_predictor pred
,
2443 enum prediction taken
)
2445 bool has_nonloop_edge
= false;
2449 basic_block bb
= e
->src
;
2450 FOR_EACH_EDGE (e2
, ei
, bb
->succs
)
2451 if (e2
->dest
!= e
->src
&& e2
->dest
!= e
->dest
2452 && !(e
->flags
& (EDGE_EH
| EDGE_FAKE
))
2453 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, e2
->dest
))
2455 has_nonloop_edge
= true;
2458 if (!has_nonloop_edge
)
2460 bitmap visited
= BITMAP_ALLOC (NULL
);
2461 predict_paths_for_bb (bb
, bb
, pred
, taken
, visited
);
2462 BITMAP_FREE (visited
);
2465 predict_edge_def (e
, pred
, taken
);
2468 /* This is used to carry information about basic blocks. It is
2469 attached to the AUX field of the standard CFG block. */
2471 typedef struct block_info_def
2473 /* Estimated frequency of execution of basic_block. */
2476 /* To keep queue of basic blocks to process. */
2479 /* Number of predecessors we need to visit first. */
2483 /* Similar information for edges. */
2484 typedef struct edge_info_def
2486 /* In case edge is a loopback edge, the probability edge will be reached
2487 in case header is. Estimated number of iterations of the loop can be
2488 then computed as 1 / (1 - back_edge_prob). */
2489 sreal back_edge_prob
;
2490 /* True if the edge is a loopback edge in the natural loop. */
2491 unsigned int back_edge
:1;
2494 #define BLOCK_INFO(B) ((block_info) (B)->aux)
2495 #define EDGE_INFO(E) ((edge_info) (E)->aux)
2497 /* Helper function for estimate_bb_frequencies.
2498 Propagate the frequencies in blocks marked in
2499 TOVISIT, starting in HEAD. */
2502 propagate_freq (basic_block head
, bitmap tovisit
)
2511 /* For each basic block we need to visit count number of his predecessors
2512 we need to visit first. */
2513 EXECUTE_IF_SET_IN_BITMAP (tovisit
, 0, i
, bi
)
2518 bb
= BASIC_BLOCK (i
);
2520 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
2522 bool visit
= bitmap_bit_p (tovisit
, e
->src
->index
);
2524 if (visit
&& !(e
->flags
& EDGE_DFS_BACK
))
2526 else if (visit
&& dump_file
&& !EDGE_INFO (e
)->back_edge
)
2528 "Irreducible region hit, ignoring edge to %i->%i\n",
2529 e
->src
->index
, bb
->index
);
2531 BLOCK_INFO (bb
)->npredecessors
= count
;
2532 /* When function never returns, we will never process exit block. */
2533 if (!count
&& bb
== EXIT_BLOCK_PTR
)
2534 bb
->count
= bb
->frequency
= 0;
2537 memcpy (&BLOCK_INFO (head
)->frequency
, &real_one
, sizeof (real_one
));
2539 for (bb
= head
; bb
; bb
= nextbb
)
2542 sreal cyclic_probability
, frequency
;
2544 memcpy (&cyclic_probability
, &real_zero
, sizeof (real_zero
));
2545 memcpy (&frequency
, &real_zero
, sizeof (real_zero
));
2547 nextbb
= BLOCK_INFO (bb
)->next
;
2548 BLOCK_INFO (bb
)->next
= NULL
;
2550 /* Compute frequency of basic block. */
2553 #ifdef ENABLE_CHECKING
2554 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
2555 gcc_assert (!bitmap_bit_p (tovisit
, e
->src
->index
)
2556 || (e
->flags
& EDGE_DFS_BACK
));
2559 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
2560 if (EDGE_INFO (e
)->back_edge
)
2562 sreal_add (&cyclic_probability
, &cyclic_probability
,
2563 &EDGE_INFO (e
)->back_edge_prob
);
2565 else if (!(e
->flags
& EDGE_DFS_BACK
))
2569 /* frequency += (e->probability
2570 * BLOCK_INFO (e->src)->frequency /
2571 REG_BR_PROB_BASE); */
2573 sreal_init (&tmp
, e
->probability
, 0);
2574 sreal_mul (&tmp
, &tmp
, &BLOCK_INFO (e
->src
)->frequency
);
2575 sreal_mul (&tmp
, &tmp
, &real_inv_br_prob_base
);
2576 sreal_add (&frequency
, &frequency
, &tmp
);
2579 if (sreal_compare (&cyclic_probability
, &real_zero
) == 0)
2581 memcpy (&BLOCK_INFO (bb
)->frequency
, &frequency
,
2582 sizeof (frequency
));
2586 if (sreal_compare (&cyclic_probability
, &real_almost_one
) > 0)
2588 memcpy (&cyclic_probability
, &real_almost_one
,
2589 sizeof (real_almost_one
));
2592 /* BLOCK_INFO (bb)->frequency = frequency
2593 / (1 - cyclic_probability) */
2595 sreal_sub (&cyclic_probability
, &real_one
, &cyclic_probability
);
2596 sreal_div (&BLOCK_INFO (bb
)->frequency
,
2597 &frequency
, &cyclic_probability
);
2601 bitmap_clear_bit (tovisit
, bb
->index
);
2603 e
= find_edge (bb
, head
);
2608 /* EDGE_INFO (e)->back_edge_prob
2609 = ((e->probability * BLOCK_INFO (bb)->frequency)
2610 / REG_BR_PROB_BASE); */
2612 sreal_init (&tmp
, e
->probability
, 0);
2613 sreal_mul (&tmp
, &tmp
, &BLOCK_INFO (bb
)->frequency
);
2614 sreal_mul (&EDGE_INFO (e
)->back_edge_prob
,
2615 &tmp
, &real_inv_br_prob_base
);
2618 /* Propagate to successor blocks. */
2619 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2620 if (!(e
->flags
& EDGE_DFS_BACK
)
2621 && BLOCK_INFO (e
->dest
)->npredecessors
)
2623 BLOCK_INFO (e
->dest
)->npredecessors
--;
2624 if (!BLOCK_INFO (e
->dest
)->npredecessors
)
2629 BLOCK_INFO (last
)->next
= e
->dest
;
2637 /* Estimate probabilities of loopback edges in loops at same nest level. */
2640 estimate_loops_at_level (struct loop
*first_loop
)
2644 for (loop
= first_loop
; loop
; loop
= loop
->next
)
2649 bitmap tovisit
= BITMAP_ALLOC (NULL
);
2651 estimate_loops_at_level (loop
->inner
);
2653 /* Find current loop back edge and mark it. */
2654 e
= loop_latch_edge (loop
);
2655 EDGE_INFO (e
)->back_edge
= 1;
2657 bbs
= get_loop_body (loop
);
2658 for (i
= 0; i
< loop
->num_nodes
; i
++)
2659 bitmap_set_bit (tovisit
, bbs
[i
]->index
);
2661 propagate_freq (loop
->header
, tovisit
);
2662 BITMAP_FREE (tovisit
);
2666 /* Propagates frequencies through structure of loops. */
2669 estimate_loops (void)
2671 bitmap tovisit
= BITMAP_ALLOC (NULL
);
2674 /* Start by estimating the frequencies in the loops. */
2675 if (number_of_loops () > 1)
2676 estimate_loops_at_level (current_loops
->tree_root
->inner
);
2678 /* Now propagate the frequencies through all the blocks. */
2681 bitmap_set_bit (tovisit
, bb
->index
);
2683 propagate_freq (ENTRY_BLOCK_PTR
, tovisit
);
2684 BITMAP_FREE (tovisit
);
2687 /* Convert counts measured by profile driven feedback to frequencies.
2688 Return nonzero iff there was any nonzero execution count. */
2691 counts_to_freqs (void)
2693 gcov_type count_max
, true_count_max
= 0;
2696 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2697 true_count_max
= MAX (bb
->count
, true_count_max
);
2699 count_max
= MAX (true_count_max
, 1);
2700 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2701 bb
->frequency
= (bb
->count
* BB_FREQ_MAX
+ count_max
/ 2) / count_max
;
2703 return true_count_max
;
2706 /* Return true if function is likely to be expensive, so there is no point to
2707 optimize performance of prologue, epilogue or do inlining at the expense
2708 of code size growth. THRESHOLD is the limit of number of instructions
2709 function can execute at average to be still considered not expensive. */
2712 expensive_function_p (int threshold
)
2714 unsigned int sum
= 0;
2718 /* We can not compute accurately for large thresholds due to scaled
2720 gcc_assert (threshold
<= BB_FREQ_MAX
);
2722 /* Frequencies are out of range. This either means that function contains
2723 internal loop executing more than BB_FREQ_MAX times or profile feedback
2724 is available and function has not been executed at all. */
2725 if (ENTRY_BLOCK_PTR
->frequency
== 0)
2728 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
2729 limit
= ENTRY_BLOCK_PTR
->frequency
* threshold
;
2734 for (insn
= BB_HEAD (bb
); insn
!= NEXT_INSN (BB_END (bb
));
2735 insn
= NEXT_INSN (insn
))
2736 if (active_insn_p (insn
))
2738 sum
+= bb
->frequency
;
2747 /* Estimate basic blocks frequency by given branch probabilities. */
2750 estimate_bb_frequencies (void)
2755 if (profile_status
!= PROFILE_READ
|| !counts_to_freqs ())
2757 static int real_values_initialized
= 0;
2759 if (!real_values_initialized
)
2761 real_values_initialized
= 1;
2762 sreal_init (&real_zero
, 0, 0);
2763 sreal_init (&real_one
, 1, 0);
2764 sreal_init (&real_br_prob_base
, REG_BR_PROB_BASE
, 0);
2765 sreal_init (&real_bb_freq_max
, BB_FREQ_MAX
, 0);
2766 sreal_init (&real_one_half
, 1, -1);
2767 sreal_div (&real_inv_br_prob_base
, &real_one
, &real_br_prob_base
);
2768 sreal_sub (&real_almost_one
, &real_one
, &real_inv_br_prob_base
);
2771 mark_dfs_back_edges ();
2773 single_succ_edge (ENTRY_BLOCK_PTR
)->probability
= REG_BR_PROB_BASE
;
2775 /* Set up block info for each basic block. */
2776 alloc_aux_for_blocks (sizeof (struct block_info_def
));
2777 alloc_aux_for_edges (sizeof (struct edge_info_def
));
2778 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2783 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2785 sreal_init (&EDGE_INFO (e
)->back_edge_prob
, e
->probability
, 0);
2786 sreal_mul (&EDGE_INFO (e
)->back_edge_prob
,
2787 &EDGE_INFO (e
)->back_edge_prob
,
2788 &real_inv_br_prob_base
);
2792 /* First compute probabilities locally for each loop from innermost
2793 to outermost to examine probabilities for back edges. */
2796 memcpy (&freq_max
, &real_zero
, sizeof (real_zero
));
2798 if (sreal_compare (&freq_max
, &BLOCK_INFO (bb
)->frequency
) < 0)
2799 memcpy (&freq_max
, &BLOCK_INFO (bb
)->frequency
, sizeof (freq_max
));
2801 sreal_div (&freq_max
, &real_bb_freq_max
, &freq_max
);
2802 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2806 sreal_mul (&tmp
, &BLOCK_INFO (bb
)->frequency
, &freq_max
);
2807 sreal_add (&tmp
, &tmp
, &real_one_half
);
2808 bb
->frequency
= sreal_to_int (&tmp
);
2811 free_aux_for_blocks ();
2812 free_aux_for_edges ();
2814 compute_function_frequency ();
2817 /* Decide whether function is hot, cold or unlikely executed. */
2819 compute_function_frequency (void)
2822 struct cgraph_node
*node
= cgraph_get_node (current_function_decl
);
2823 if (DECL_STATIC_CONSTRUCTOR (current_function_decl
)
2824 || MAIN_NAME_P (DECL_NAME (current_function_decl
)))
2825 node
->only_called_at_startup
= true;
2826 if (DECL_STATIC_DESTRUCTOR (current_function_decl
))
2827 node
->only_called_at_exit
= true;
2829 if (!profile_info
|| !flag_branch_probabilities
)
2831 int flags
= flags_from_decl_or_type (current_function_decl
);
2832 if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl
))
2834 node
->frequency
= NODE_FREQUENCY_UNLIKELY_EXECUTED
;
2835 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl
))
2837 node
->frequency
= NODE_FREQUENCY_HOT
;
2838 else if (flags
& ECF_NORETURN
)
2839 node
->frequency
= NODE_FREQUENCY_EXECUTED_ONCE
;
2840 else if (MAIN_NAME_P (DECL_NAME (current_function_decl
)))
2841 node
->frequency
= NODE_FREQUENCY_EXECUTED_ONCE
;
2842 else if (DECL_STATIC_CONSTRUCTOR (current_function_decl
)
2843 || DECL_STATIC_DESTRUCTOR (current_function_decl
))
2844 node
->frequency
= NODE_FREQUENCY_EXECUTED_ONCE
;
2847 node
->frequency
= NODE_FREQUENCY_UNLIKELY_EXECUTED
;
2850 if (maybe_hot_bb_p (cfun
, bb
))
2852 node
->frequency
= NODE_FREQUENCY_HOT
;
2855 if (!probably_never_executed_bb_p (cfun
, bb
))
2856 node
->frequency
= NODE_FREQUENCY_NORMAL
;
2861 gate_estimate_probability (void)
2863 return flag_guess_branch_prob
;
2866 /* Build PREDICT_EXPR. */
2868 build_predict_expr (enum br_predictor predictor
, enum prediction taken
)
2870 tree t
= build1 (PREDICT_EXPR
, void_type_node
,
2871 build_int_cst (integer_type_node
, predictor
));
2872 SET_PREDICT_EXPR_OUTCOME (t
, taken
);
2877 predictor_name (enum br_predictor predictor
)
2879 return predictor_info
[predictor
].name
;
2882 struct gimple_opt_pass pass_profile
=
2886 "profile_estimate", /* name */
2887 OPTGROUP_NONE
, /* optinfo_flags */
2888 gate_estimate_probability
, /* gate */
2889 tree_estimate_probability_driver
, /* execute */
2892 0, /* static_pass_number */
2893 TV_BRANCH_PROB
, /* tv_id */
2894 PROP_cfg
, /* properties_required */
2895 0, /* properties_provided */
2896 0, /* properties_destroyed */
2897 0, /* todo_flags_start */
2898 TODO_ggc_collect
| TODO_verify_ssa
/* todo_flags_finish */
2902 struct gimple_opt_pass pass_strip_predict_hints
=
2906 "*strip_predict_hints", /* name */
2907 OPTGROUP_NONE
, /* optinfo_flags */
2909 strip_predict_hints
, /* execute */
2912 0, /* static_pass_number */
2913 TV_BRANCH_PROB
, /* tv_id */
2914 PROP_cfg
, /* properties_required */
2915 0, /* properties_provided */
2916 0, /* properties_destroyed */
2917 0, /* todo_flags_start */
2918 TODO_ggc_collect
| TODO_verify_ssa
/* todo_flags_finish */
2922 /* Rebuild function frequencies. Passes are in general expected to
2923 maintain profile by hand, however in some cases this is not possible:
2924 for example when inlining several functions with loops freuqencies might run
2925 out of scale and thus needs to be recomputed. */
2928 rebuild_frequencies (void)
2930 timevar_push (TV_REBUILD_FREQUENCIES
);
2931 if (profile_status
== PROFILE_GUESSED
)
2933 loop_optimizer_init (0);
2934 add_noreturn_fake_exit_edges ();
2935 mark_irreducible_loops ();
2936 connect_infinite_loops_to_exit ();
2937 estimate_bb_frequencies ();
2938 remove_fake_exit_edges ();
2939 loop_optimizer_finalize ();
2941 else if (profile_status
== PROFILE_READ
)
2945 timevar_pop (TV_REBUILD_FREQUENCIES
);