1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008
3 Free Software Foundation, Inc.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
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
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/>. */
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. */
33 #include "coretypes.h"
38 #include "hard-reg-set.h"
39 #include "basic-block.h"
40 #include "insn-config.h"
55 #include "tree-flow.h"
57 #include "tree-dump.h"
58 #include "tree-pass.h"
60 #include "tree-scalar-evolution.h"
62 #include "pointer-set.h"
64 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
65 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
66 static sreal real_zero
, real_one
, real_almost_one
, real_br_prob_base
,
67 real_inv_br_prob_base
, real_one_half
, real_bb_freq_max
;
69 /* Random guesstimation given names. */
70 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 100 - 1)
71 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
72 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
73 #define PROB_ALWAYS (REG_BR_PROB_BASE)
75 static void combine_predictions_for_insn (rtx
, basic_block
);
76 static void dump_prediction (FILE *, enum br_predictor
, int, basic_block
, int);
77 static void predict_paths_leading_to (basic_block
, enum br_predictor
, enum prediction
);
78 static void compute_function_frequency (void);
79 static void choose_function_section (void);
80 static bool can_predict_insn_p (const_rtx
);
82 /* Information we hold about each branch predictor.
83 Filled using information from predict.def. */
87 const char *const name
; /* Name used in the debugging dumps. */
88 const int hitrate
; /* Expected hitrate used by
89 predict_insn_def call. */
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. */
110 /* Return TRUE if frequency FREQ is considered to be hot. */
112 maybe_hot_frequency_p (int freq
)
114 if (!profile_info
|| !flag_branch_probabilities
)
116 if (cfun
->function_frequency
== FUNCTION_FREQUENCY_UNLIKELY_EXECUTED
)
118 if (cfun
->function_frequency
== FUNCTION_FREQUENCY_HOT
)
121 if (profile_status
== PROFILE_ABSENT
)
123 if (freq
< BB_FREQ_MAX
/ PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION
))
128 /* Return true in case BB can be CPU intensive and should be optimized
129 for maximal performance. */
132 maybe_hot_bb_p (const_basic_block bb
)
134 if (profile_info
&& flag_branch_probabilities
136 < profile_info
->sum_max
/ PARAM_VALUE (HOT_BB_COUNT_FRACTION
)))
138 return maybe_hot_frequency_p (bb
->frequency
);
141 /* Return true in case BB can be CPU intensive and should be optimized
142 for maximal performance. */
145 maybe_hot_edge_p (edge e
)
147 if (profile_info
&& flag_branch_probabilities
149 < profile_info
->sum_max
/ PARAM_VALUE (HOT_BB_COUNT_FRACTION
)))
151 return maybe_hot_frequency_p (EDGE_FREQUENCY (e
));
154 /* Return true in case BB is cold and should be optimized for size. */
157 probably_cold_bb_p (const_basic_block bb
)
159 if (profile_info
&& flag_branch_probabilities
161 < profile_info
->sum_max
/ PARAM_VALUE (HOT_BB_COUNT_FRACTION
)))
163 if ((!profile_info
|| !flag_branch_probabilities
)
164 && cfun
->function_frequency
== FUNCTION_FREQUENCY_UNLIKELY_EXECUTED
)
166 if (bb
->frequency
< BB_FREQ_MAX
/ PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION
))
171 /* Return true in case BB is probably never executed. */
173 probably_never_executed_bb_p (const_basic_block bb
)
175 if (profile_info
&& flag_branch_probabilities
)
176 return ((bb
->count
+ profile_info
->runs
/ 2) / profile_info
->runs
) == 0;
177 if ((!profile_info
|| !flag_branch_probabilities
)
178 && cfun
->function_frequency
== FUNCTION_FREQUENCY_UNLIKELY_EXECUTED
)
183 /* Return true when current function should always be optimized for size. */
186 always_optimize_for_size_p (void)
188 return (optimize_size
189 || cfun
->function_frequency
== FUNCTION_FREQUENCY_UNLIKELY_EXECUTED
);
192 /* Return TRUE when BB should be optimized for size. */
195 optimize_bb_for_size_p (basic_block bb
)
197 return always_optimize_for_size_p () || !maybe_hot_bb_p (bb
);
200 /* Return TRUE when BB should be optimized for speed. */
203 optimize_bb_for_speed_p (basic_block bb
)
205 return !optimize_bb_for_size_p (bb
);
208 /* Return TRUE when BB should be optimized for size. */
211 optimize_edge_for_size_p (edge e
)
213 return always_optimize_for_size_p () || !maybe_hot_edge_p (e
);
216 /* Return TRUE when BB should be optimized for speed. */
219 optimize_edge_for_speed_p (edge e
)
221 return !optimize_edge_for_size_p (e
);
224 /* Return TRUE when BB should be optimized for size. */
227 optimize_insn_for_size_p (void)
229 return always_optimize_for_size_p () || !crtl
->maybe_hot_insn_p
;
232 /* Return TRUE when BB should be optimized for speed. */
235 optimize_insn_for_speed_p (void)
237 return !optimize_insn_for_size_p ();
240 /* Set RTL expansion for BB profile. */
243 rtl_profile_for_bb (basic_block bb
)
245 crtl
->maybe_hot_insn_p
= maybe_hot_bb_p (bb
);
248 /* Set RTL expansion for edge profile. */
251 rtl_profile_for_edge (edge e
)
253 crtl
->maybe_hot_insn_p
= maybe_hot_edge_p (e
);
256 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
258 default_rtl_profile (void)
260 crtl
->maybe_hot_insn_p
= true;
263 /* Return true if the one of outgoing edges is already predicted by
267 rtl_predicted_by_p (const_basic_block bb
, enum br_predictor predictor
)
270 if (!INSN_P (BB_END (bb
)))
272 for (note
= REG_NOTES (BB_END (bb
)); note
; note
= XEXP (note
, 1))
273 if (REG_NOTE_KIND (note
) == REG_BR_PRED
274 && INTVAL (XEXP (XEXP (note
, 0), 0)) == (int)predictor
)
279 /* This map contains for a basic block the list of predictions for the
282 static struct pointer_map_t
*bb_predictions
;
284 /* Return true if the one of outgoing edges is already predicted by
288 gimple_predicted_by_p (const_basic_block bb
, enum br_predictor predictor
)
290 struct edge_prediction
*i
;
291 void **preds
= pointer_map_contains (bb_predictions
, bb
);
296 for (i
= (struct edge_prediction
*) *preds
; i
; i
= i
->ep_next
)
297 if (i
->ep_predictor
== predictor
)
302 /* Return true when the probability of edge is reliable.
304 The profile guessing code is good at predicting branch outcome (ie.
305 taken/not taken), that is predicted right slightly over 75% of time.
306 It is however notoriously poor on predicting the probability itself.
307 In general the profile appear a lot flatter (with probabilities closer
308 to 50%) than the reality so it is bad idea to use it to drive optimization
309 such as those disabling dynamic branch prediction for well predictable
312 There are two exceptions - edges leading to noreturn edges and edges
313 predicted by number of iterations heuristics are predicted well. This macro
314 should be able to distinguish those, but at the moment it simply check for
315 noreturn heuristic that is only one giving probability over 99% or bellow
316 1%. In future we might want to propagate reliability information across the
317 CFG if we find this information useful on multiple places. */
319 probability_reliable_p (int prob
)
321 return (profile_status
== PROFILE_READ
322 || (profile_status
== PROFILE_GUESSED
323 && (prob
<= HITRATE (1) || prob
>= HITRATE (99))));
326 /* Same predicate as above, working on edges. */
328 edge_probability_reliable_p (const_edge e
)
330 return probability_reliable_p (e
->probability
);
333 /* Same predicate as edge_probability_reliable_p, working on notes. */
335 br_prob_note_reliable_p (const_rtx note
)
337 gcc_assert (REG_NOTE_KIND (note
) == REG_BR_PROB
);
338 return probability_reliable_p (INTVAL (XEXP (note
, 0)));
342 predict_insn (rtx insn
, enum br_predictor predictor
, int probability
)
344 gcc_assert (any_condjump_p (insn
));
345 if (!flag_guess_branch_prob
)
348 add_reg_note (insn
, REG_BR_PRED
,
349 gen_rtx_CONCAT (VOIDmode
,
350 GEN_INT ((int) predictor
),
351 GEN_INT ((int) probability
)));
354 /* Predict insn by given predictor. */
357 predict_insn_def (rtx insn
, enum br_predictor predictor
,
358 enum prediction taken
)
360 int probability
= predictor_info
[(int) predictor
].hitrate
;
363 probability
= REG_BR_PROB_BASE
- probability
;
365 predict_insn (insn
, predictor
, probability
);
368 /* Predict edge E with given probability if possible. */
371 rtl_predict_edge (edge e
, enum br_predictor predictor
, int probability
)
374 last_insn
= BB_END (e
->src
);
376 /* We can store the branch prediction information only about
377 conditional jumps. */
378 if (!any_condjump_p (last_insn
))
381 /* We always store probability of branching. */
382 if (e
->flags
& EDGE_FALLTHRU
)
383 probability
= REG_BR_PROB_BASE
- probability
;
385 predict_insn (last_insn
, predictor
, probability
);
388 /* Predict edge E with the given PROBABILITY. */
390 gimple_predict_edge (edge e
, enum br_predictor predictor
, int probability
)
392 gcc_assert (profile_status
!= PROFILE_GUESSED
);
393 if ((e
->src
!= ENTRY_BLOCK_PTR
&& EDGE_COUNT (e
->src
->succs
) > 1)
394 && flag_guess_branch_prob
&& optimize
)
396 struct edge_prediction
*i
= XNEW (struct edge_prediction
);
397 void **preds
= pointer_map_insert (bb_predictions
, e
->src
);
399 i
->ep_next
= (struct edge_prediction
*) *preds
;
401 i
->ep_probability
= probability
;
402 i
->ep_predictor
= predictor
;
407 /* Remove all predictions on given basic block that are attached
410 remove_predictions_associated_with_edge (edge e
)
417 preds
= pointer_map_contains (bb_predictions
, e
->src
);
421 struct edge_prediction
**prediction
= (struct edge_prediction
**) preds
;
422 struct edge_prediction
*next
;
426 if ((*prediction
)->ep_edge
== e
)
428 next
= (*prediction
)->ep_next
;
433 prediction
= &((*prediction
)->ep_next
);
438 /* Clears the list of predictions stored for BB. */
441 clear_bb_predictions (basic_block bb
)
443 void **preds
= pointer_map_contains (bb_predictions
, bb
);
444 struct edge_prediction
*pred
, *next
;
449 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= next
)
451 next
= pred
->ep_next
;
457 /* Return true when we can store prediction on insn INSN.
458 At the moment we represent predictions only on conditional
459 jumps, not at computed jump or other complicated cases. */
461 can_predict_insn_p (const_rtx insn
)
463 return (JUMP_P (insn
)
464 && any_condjump_p (insn
)
465 && EDGE_COUNT (BLOCK_FOR_INSN (insn
)->succs
) >= 2);
468 /* Predict edge E by given predictor if possible. */
471 predict_edge_def (edge e
, enum br_predictor predictor
,
472 enum prediction taken
)
474 int probability
= predictor_info
[(int) predictor
].hitrate
;
477 probability
= REG_BR_PROB_BASE
- probability
;
479 predict_edge (e
, predictor
, probability
);
482 /* Invert all branch predictions or probability notes in the INSN. This needs
483 to be done each time we invert the condition used by the jump. */
486 invert_br_probabilities (rtx insn
)
490 for (note
= REG_NOTES (insn
); note
; note
= XEXP (note
, 1))
491 if (REG_NOTE_KIND (note
) == REG_BR_PROB
)
492 XEXP (note
, 0) = GEN_INT (REG_BR_PROB_BASE
- INTVAL (XEXP (note
, 0)));
493 else if (REG_NOTE_KIND (note
) == REG_BR_PRED
)
494 XEXP (XEXP (note
, 0), 1)
495 = GEN_INT (REG_BR_PROB_BASE
- INTVAL (XEXP (XEXP (note
, 0), 1)));
498 /* Dump information about the branch prediction to the output file. */
501 dump_prediction (FILE *file
, enum br_predictor predictor
, int probability
,
502 basic_block bb
, int used
)
510 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
511 if (! (e
->flags
& EDGE_FALLTHRU
))
514 fprintf (file
, " %s heuristics%s: %.1f%%",
515 predictor_info
[predictor
].name
,
516 used
? "" : " (ignored)", probability
* 100.0 / REG_BR_PROB_BASE
);
520 fprintf (file
, " exec ");
521 fprintf (file
, HOST_WIDEST_INT_PRINT_DEC
, bb
->count
);
524 fprintf (file
, " hit ");
525 fprintf (file
, HOST_WIDEST_INT_PRINT_DEC
, e
->count
);
526 fprintf (file
, " (%.1f%%)", e
->count
* 100.0 / bb
->count
);
530 fprintf (file
, "\n");
533 /* We can not predict the probabilities of outgoing edges of bb. Set them
534 evenly and hope for the best. */
536 set_even_probabilities (basic_block bb
)
542 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
543 if (!(e
->flags
& (EDGE_EH
| EDGE_FAKE
)))
545 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
546 if (!(e
->flags
& (EDGE_EH
| EDGE_FAKE
)))
547 e
->probability
= (REG_BR_PROB_BASE
+ nedges
/ 2) / nedges
;
552 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
553 note if not already present. Remove now useless REG_BR_PRED notes. */
556 combine_predictions_for_insn (rtx insn
, basic_block bb
)
561 int best_probability
= PROB_EVEN
;
562 int best_predictor
= END_PREDICTORS
;
563 int combined_probability
= REG_BR_PROB_BASE
/ 2;
565 bool first_match
= false;
568 if (!can_predict_insn_p (insn
))
570 set_even_probabilities (bb
);
574 prob_note
= find_reg_note (insn
, REG_BR_PROB
, 0);
575 pnote
= ®_NOTES (insn
);
577 fprintf (dump_file
, "Predictions for insn %i bb %i\n", INSN_UID (insn
),
580 /* We implement "first match" heuristics and use probability guessed
581 by predictor with smallest index. */
582 for (note
= REG_NOTES (insn
); note
; note
= XEXP (note
, 1))
583 if (REG_NOTE_KIND (note
) == REG_BR_PRED
)
585 int predictor
= INTVAL (XEXP (XEXP (note
, 0), 0));
586 int probability
= INTVAL (XEXP (XEXP (note
, 0), 1));
589 if (best_predictor
> predictor
)
590 best_probability
= probability
, best_predictor
= predictor
;
592 d
= (combined_probability
* probability
593 + (REG_BR_PROB_BASE
- combined_probability
)
594 * (REG_BR_PROB_BASE
- probability
));
596 /* Use FP math to avoid overflows of 32bit integers. */
598 /* If one probability is 0% and one 100%, avoid division by zero. */
599 combined_probability
= REG_BR_PROB_BASE
/ 2;
601 combined_probability
= (((double) combined_probability
) * probability
602 * REG_BR_PROB_BASE
/ d
+ 0.5);
605 /* Decide which heuristic to use. In case we didn't match anything,
606 use no_prediction heuristic, in case we did match, use either
607 first match or Dempster-Shaffer theory depending on the flags. */
609 if (predictor_info
[best_predictor
].flags
& PRED_FLAG_FIRST_MATCH
)
613 dump_prediction (dump_file
, PRED_NO_PREDICTION
,
614 combined_probability
, bb
, true);
617 dump_prediction (dump_file
, PRED_DS_THEORY
, combined_probability
,
619 dump_prediction (dump_file
, PRED_FIRST_MATCH
, best_probability
,
624 combined_probability
= best_probability
;
625 dump_prediction (dump_file
, PRED_COMBINED
, combined_probability
, bb
, true);
629 if (REG_NOTE_KIND (*pnote
) == REG_BR_PRED
)
631 int predictor
= INTVAL (XEXP (XEXP (*pnote
, 0), 0));
632 int probability
= INTVAL (XEXP (XEXP (*pnote
, 0), 1));
634 dump_prediction (dump_file
, predictor
, probability
, bb
,
635 !first_match
|| best_predictor
== predictor
);
636 *pnote
= XEXP (*pnote
, 1);
639 pnote
= &XEXP (*pnote
, 1);
644 add_reg_note (insn
, REG_BR_PROB
, GEN_INT (combined_probability
));
646 /* Save the prediction into CFG in case we are seeing non-degenerated
648 if (!single_succ_p (bb
))
650 BRANCH_EDGE (bb
)->probability
= combined_probability
;
651 FALLTHRU_EDGE (bb
)->probability
652 = REG_BR_PROB_BASE
- combined_probability
;
655 else if (!single_succ_p (bb
))
657 int prob
= INTVAL (XEXP (prob_note
, 0));
659 BRANCH_EDGE (bb
)->probability
= prob
;
660 FALLTHRU_EDGE (bb
)->probability
= REG_BR_PROB_BASE
- prob
;
663 single_succ_edge (bb
)->probability
= REG_BR_PROB_BASE
;
666 /* Combine predictions into single probability and store them into CFG.
667 Remove now useless prediction entries. */
670 combine_predictions_for_bb (basic_block bb
)
672 int best_probability
= PROB_EVEN
;
673 int best_predictor
= END_PREDICTORS
;
674 int combined_probability
= REG_BR_PROB_BASE
/ 2;
676 bool first_match
= false;
678 struct edge_prediction
*pred
;
680 edge e
, first
= NULL
, second
= NULL
;
684 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
685 if (!(e
->flags
& (EDGE_EH
| EDGE_FAKE
)))
688 if (first
&& !second
)
694 /* When there is no successor or only one choice, prediction is easy.
696 We are lazy for now and predict only basic blocks with two outgoing
697 edges. It is possible to predict generic case too, but we have to
698 ignore first match heuristics and do more involved combining. Implement
703 set_even_probabilities (bb
);
704 clear_bb_predictions (bb
);
706 fprintf (dump_file
, "%i edges in bb %i predicted to even probabilities\n",
712 fprintf (dump_file
, "Predictions for bb %i\n", bb
->index
);
714 preds
= pointer_map_contains (bb_predictions
, bb
);
717 /* We implement "first match" heuristics and use probability guessed
718 by predictor with smallest index. */
719 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= pred
->ep_next
)
721 int predictor
= pred
->ep_predictor
;
722 int probability
= pred
->ep_probability
;
724 if (pred
->ep_edge
!= first
)
725 probability
= REG_BR_PROB_BASE
- probability
;
728 if (best_predictor
> predictor
)
729 best_probability
= probability
, best_predictor
= predictor
;
731 d
= (combined_probability
* probability
732 + (REG_BR_PROB_BASE
- combined_probability
)
733 * (REG_BR_PROB_BASE
- probability
));
735 /* Use FP math to avoid overflows of 32bit integers. */
737 /* If one probability is 0% and one 100%, avoid division by zero. */
738 combined_probability
= REG_BR_PROB_BASE
/ 2;
740 combined_probability
= (((double) combined_probability
)
742 * REG_BR_PROB_BASE
/ d
+ 0.5);
746 /* Decide which heuristic to use. In case we didn't match anything,
747 use no_prediction heuristic, in case we did match, use either
748 first match or Dempster-Shaffer theory depending on the flags. */
750 if (predictor_info
[best_predictor
].flags
& PRED_FLAG_FIRST_MATCH
)
754 dump_prediction (dump_file
, PRED_NO_PREDICTION
, combined_probability
, bb
, true);
757 dump_prediction (dump_file
, PRED_DS_THEORY
, combined_probability
, bb
,
759 dump_prediction (dump_file
, PRED_FIRST_MATCH
, best_probability
, bb
,
764 combined_probability
= best_probability
;
765 dump_prediction (dump_file
, PRED_COMBINED
, combined_probability
, bb
, true);
769 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= pred
->ep_next
)
771 int predictor
= pred
->ep_predictor
;
772 int probability
= pred
->ep_probability
;
774 if (pred
->ep_edge
!= EDGE_SUCC (bb
, 0))
775 probability
= REG_BR_PROB_BASE
- probability
;
776 dump_prediction (dump_file
, predictor
, probability
, bb
,
777 !first_match
|| best_predictor
== predictor
);
780 clear_bb_predictions (bb
);
784 first
->probability
= combined_probability
;
785 second
->probability
= REG_BR_PROB_BASE
- combined_probability
;
789 /* Predict edge probabilities by exploiting loop structure. */
799 /* Try to predict out blocks in a loop that are not part of a
801 FOR_EACH_LOOP (li
, loop
, 0)
803 basic_block bb
, *bbs
;
805 VEC (edge
, heap
) *exits
;
806 struct tree_niter_desc niter_desc
;
809 exits
= get_loop_exit_edges (loop
);
810 n_exits
= VEC_length (edge
, exits
);
812 for (j
= 0; VEC_iterate (edge
, exits
, j
, ex
); j
++)
815 HOST_WIDE_INT nitercst
;
816 int max
= PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS
);
818 enum br_predictor predictor
;
820 if (number_of_iterations_exit (loop
, ex
, &niter_desc
, false))
821 niter
= niter_desc
.niter
;
822 if (!niter
|| TREE_CODE (niter_desc
.niter
) != INTEGER_CST
)
823 niter
= loop_niter_by_eval (loop
, ex
);
825 if (TREE_CODE (niter
) == INTEGER_CST
)
827 if (host_integerp (niter
, 1)
828 && compare_tree_int (niter
, max
-1) == -1)
829 nitercst
= tree_low_cst (niter
, 1) + 1;
832 predictor
= PRED_LOOP_ITERATIONS
;
834 /* If we have just one exit and we can derive some information about
835 the number of iterations of the loop from the statements inside
836 the loop, use it to predict this exit. */
837 else if (n_exits
== 1)
839 nitercst
= estimated_loop_iterations_int (loop
, false);
845 predictor
= PRED_LOOP_ITERATIONS_GUESSED
;
850 probability
= ((REG_BR_PROB_BASE
+ nitercst
/ 2) / nitercst
);
851 predict_edge (ex
, predictor
, probability
);
853 VEC_free (edge
, heap
, exits
);
855 bbs
= get_loop_body (loop
);
857 for (j
= 0; j
< loop
->num_nodes
; j
++)
859 int header_found
= 0;
865 /* Bypass loop heuristics on continue statement. These
866 statements construct loops via "non-loop" constructs
867 in the source language and are better to be handled
869 if (predicted_by_p (bb
, PRED_CONTINUE
))
872 /* Loop branch heuristics - predict an edge back to a
873 loop's head as taken. */
874 if (bb
== loop
->latch
)
876 e
= find_edge (loop
->latch
, loop
->header
);
880 predict_edge_def (e
, PRED_LOOP_BRANCH
, TAKEN
);
884 /* Loop exit heuristics - predict an edge exiting the loop if the
885 conditional has no loop header successors as not taken. */
887 /* If we already used more reliable loop exit predictors, do not
888 bother with PRED_LOOP_EXIT. */
889 && !predicted_by_p (bb
, PRED_LOOP_ITERATIONS_GUESSED
)
890 && !predicted_by_p (bb
, PRED_LOOP_ITERATIONS
))
892 /* For loop with many exits we don't want to predict all exits
893 with the pretty large probability, because if all exits are
894 considered in row, the loop would be predicted to iterate
895 almost never. The code to divide probability by number of
896 exits is very rough. It should compute the number of exits
897 taken in each patch through function (not the overall number
898 of exits that might be a lot higher for loops with wide switch
899 statements in them) and compute n-th square root.
901 We limit the minimal probability by 2% to avoid
902 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
903 as this was causing regression in perl benchmark containing such
906 int probability
= ((REG_BR_PROB_BASE
907 - predictor_info
[(int) PRED_LOOP_EXIT
].hitrate
)
909 if (probability
< HITRATE (2))
910 probability
= HITRATE (2);
911 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
912 if (e
->dest
->index
< NUM_FIXED_BLOCKS
913 || !flow_bb_inside_loop_p (loop
, e
->dest
))
914 predict_edge (e
, PRED_LOOP_EXIT
, probability
);
918 /* Free basic blocks from get_loop_body. */
925 /* Attempt to predict probabilities of BB outgoing edges using local
928 bb_estimate_probability_locally (basic_block bb
)
930 rtx last_insn
= BB_END (bb
);
933 if (! can_predict_insn_p (last_insn
))
935 cond
= get_condition (last_insn
, NULL
, false, false);
939 /* Try "pointer heuristic."
940 A comparison ptr == 0 is predicted as false.
941 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
942 if (COMPARISON_P (cond
)
943 && ((REG_P (XEXP (cond
, 0)) && REG_POINTER (XEXP (cond
, 0)))
944 || (REG_P (XEXP (cond
, 1)) && REG_POINTER (XEXP (cond
, 1)))))
946 if (GET_CODE (cond
) == EQ
)
947 predict_insn_def (last_insn
, PRED_POINTER
, NOT_TAKEN
);
948 else if (GET_CODE (cond
) == NE
)
949 predict_insn_def (last_insn
, PRED_POINTER
, TAKEN
);
953 /* Try "opcode heuristic."
954 EQ tests are usually false and NE tests are usually true. Also,
955 most quantities are positive, so we can make the appropriate guesses
956 about signed comparisons against zero. */
957 switch (GET_CODE (cond
))
960 /* Unconditional branch. */
961 predict_insn_def (last_insn
, PRED_UNCONDITIONAL
,
962 cond
== const0_rtx
? NOT_TAKEN
: TAKEN
);
967 /* Floating point comparisons appears to behave in a very
968 unpredictable way because of special role of = tests in
970 if (FLOAT_MODE_P (GET_MODE (XEXP (cond
, 0))))
972 /* Comparisons with 0 are often used for booleans and there is
973 nothing useful to predict about them. */
974 else if (XEXP (cond
, 1) == const0_rtx
975 || XEXP (cond
, 0) == const0_rtx
)
978 predict_insn_def (last_insn
, PRED_OPCODE_NONEQUAL
, NOT_TAKEN
);
983 /* Floating point comparisons appears to behave in a very
984 unpredictable way because of special role of = tests in
986 if (FLOAT_MODE_P (GET_MODE (XEXP (cond
, 0))))
988 /* Comparisons with 0 are often used for booleans and there is
989 nothing useful to predict about them. */
990 else if (XEXP (cond
, 1) == const0_rtx
991 || XEXP (cond
, 0) == const0_rtx
)
994 predict_insn_def (last_insn
, PRED_OPCODE_NONEQUAL
, TAKEN
);
998 predict_insn_def (last_insn
, PRED_FPOPCODE
, TAKEN
);
1002 predict_insn_def (last_insn
, PRED_FPOPCODE
, NOT_TAKEN
);
1007 if (XEXP (cond
, 1) == const0_rtx
|| XEXP (cond
, 1) == const1_rtx
1008 || XEXP (cond
, 1) == constm1_rtx
)
1009 predict_insn_def (last_insn
, PRED_OPCODE_POSITIVE
, NOT_TAKEN
);
1014 if (XEXP (cond
, 1) == const0_rtx
|| XEXP (cond
, 1) == const1_rtx
1015 || XEXP (cond
, 1) == constm1_rtx
)
1016 predict_insn_def (last_insn
, PRED_OPCODE_POSITIVE
, TAKEN
);
1024 /* Set edge->probability for each successor edge of BB. */
1026 guess_outgoing_edge_probabilities (basic_block bb
)
1028 bb_estimate_probability_locally (bb
);
1029 combine_predictions_for_insn (BB_END (bb
), bb
);
1032 static tree
expr_expected_value (tree
, bitmap
);
1034 /* Helper function for expr_expected_value. */
1037 expr_expected_value_1 (tree type
, tree op0
, enum tree_code code
, tree op1
, bitmap visited
)
1041 if (get_gimple_rhs_class (code
) == GIMPLE_SINGLE_RHS
)
1043 if (TREE_CONSTANT (op0
))
1046 if (code
!= SSA_NAME
)
1049 def
= SSA_NAME_DEF_STMT (op0
);
1051 /* If we were already here, break the infinite cycle. */
1052 if (bitmap_bit_p (visited
, SSA_NAME_VERSION (op0
)))
1054 bitmap_set_bit (visited
, SSA_NAME_VERSION (op0
));
1056 if (gimple_code (def
) == GIMPLE_PHI
)
1058 /* All the arguments of the PHI node must have the same constant
1060 int i
, n
= gimple_phi_num_args (def
);
1061 tree val
= NULL
, new_val
;
1063 for (i
= 0; i
< n
; i
++)
1065 tree arg
= PHI_ARG_DEF (def
, i
);
1067 /* If this PHI has itself as an argument, we cannot
1068 determine the string length of this argument. However,
1069 if we can find an expected constant value for the other
1070 PHI args then we can still be sure that this is
1071 likely a constant. So be optimistic and just
1072 continue with the next argument. */
1073 if (arg
== PHI_RESULT (def
))
1076 new_val
= expr_expected_value (arg
, visited
);
1081 else if (!operand_equal_p (val
, new_val
, false))
1086 if (is_gimple_assign (def
))
1088 if (gimple_assign_lhs (def
) != op0
)
1091 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def
)),
1092 gimple_assign_rhs1 (def
),
1093 gimple_assign_rhs_code (def
),
1094 gimple_assign_rhs2 (def
),
1098 if (is_gimple_call (def
))
1100 tree decl
= gimple_call_fndecl (def
);
1103 if (DECL_BUILT_IN_CLASS (decl
) == BUILT_IN_NORMAL
1104 && DECL_FUNCTION_CODE (decl
) == BUILT_IN_EXPECT
)
1108 if (gimple_call_num_args (def
) != 2)
1110 val
= gimple_call_arg (def
, 0);
1111 if (TREE_CONSTANT (val
))
1113 return gimple_call_arg (def
, 1);
1120 if (get_gimple_rhs_class (code
) == GIMPLE_BINARY_RHS
)
1123 op0
= expr_expected_value (op0
, visited
);
1126 op1
= expr_expected_value (op1
, visited
);
1129 res
= fold_build2 (code
, type
, op0
, op1
);
1130 if (TREE_CONSTANT (res
))
1134 if (get_gimple_rhs_class (code
) == GIMPLE_UNARY_RHS
)
1137 op0
= expr_expected_value (op0
, visited
);
1140 res
= fold_build1 (code
, type
, op0
);
1141 if (TREE_CONSTANT (res
))
1148 /* Return constant EXPR will likely have at execution time, NULL if unknown.
1149 The function is used by builtin_expect branch predictor so the evidence
1150 must come from this construct and additional possible constant folding.
1152 We may want to implement more involved value guess (such as value range
1153 propagation based prediction), but such tricks shall go to new
1157 expr_expected_value (tree expr
, bitmap visited
)
1159 enum tree_code code
;
1162 if (TREE_CONSTANT (expr
))
1165 extract_ops_from_tree (expr
, &code
, &op0
, &op1
);
1166 return expr_expected_value_1 (TREE_TYPE (expr
),
1167 op0
, code
, op1
, visited
);
1171 /* Get rid of all builtin_expect calls we no longer need. */
1173 strip_builtin_expect (void)
1181 gimple_stmt_iterator bi
;
1182 for (bi
= gsi_start_bb (bb
); !gsi_end_p (bi
); gsi_next (&bi
))
1184 gimple stmt
= gsi_stmt (bi
);
1187 if (gimple_code (stmt
) != GIMPLE_CALL
)
1190 fndecl
= gimple_call_fndecl (stmt
);
1193 && DECL_BUILT_IN_CLASS (fndecl
) == BUILT_IN_NORMAL
1194 && DECL_FUNCTION_CODE (fndecl
) == BUILT_IN_EXPECT
1195 && gimple_call_num_args (stmt
) == 2)
1197 var
= gimple_call_lhs (stmt
);
1198 ass_stmt
= gimple_build_assign (var
, gimple_call_arg (stmt
, 0));
1200 gsi_replace (&bi
, ass_stmt
, true);
1206 /* Predict using opcode of the last statement in basic block. */
1208 tree_predict_by_opcode (basic_block bb
)
1210 gimple stmt
= last_stmt (bb
);
1219 if (!stmt
|| gimple_code (stmt
) != GIMPLE_COND
)
1221 FOR_EACH_EDGE (then_edge
, ei
, bb
->succs
)
1222 if (then_edge
->flags
& EDGE_TRUE_VALUE
)
1224 op0
= gimple_cond_lhs (stmt
);
1225 op1
= gimple_cond_rhs (stmt
);
1226 cmp
= gimple_cond_code (stmt
);
1227 type
= TREE_TYPE (op0
);
1228 visited
= BITMAP_ALLOC (NULL
);
1229 val
= expr_expected_value_1 (boolean_type_node
, op0
, cmp
, op1
, visited
);
1230 BITMAP_FREE (visited
);
1233 if (integer_zerop (val
))
1234 predict_edge_def (then_edge
, PRED_BUILTIN_EXPECT
, NOT_TAKEN
);
1236 predict_edge_def (then_edge
, PRED_BUILTIN_EXPECT
, TAKEN
);
1239 /* Try "pointer heuristic."
1240 A comparison ptr == 0 is predicted as false.
1241 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1242 if (POINTER_TYPE_P (type
))
1245 predict_edge_def (then_edge
, PRED_TREE_POINTER
, NOT_TAKEN
);
1246 else if (cmp
== NE_EXPR
)
1247 predict_edge_def (then_edge
, PRED_TREE_POINTER
, TAKEN
);
1251 /* Try "opcode heuristic."
1252 EQ tests are usually false and NE tests are usually true. Also,
1253 most quantities are positive, so we can make the appropriate guesses
1254 about signed comparisons against zero. */
1259 /* Floating point comparisons appears to behave in a very
1260 unpredictable way because of special role of = tests in
1262 if (FLOAT_TYPE_P (type
))
1264 /* Comparisons with 0 are often used for booleans and there is
1265 nothing useful to predict about them. */
1266 else if (integer_zerop (op0
) || integer_zerop (op1
))
1269 predict_edge_def (then_edge
, PRED_TREE_OPCODE_NONEQUAL
, NOT_TAKEN
);
1274 /* Floating point comparisons appears to behave in a very
1275 unpredictable way because of special role of = tests in
1277 if (FLOAT_TYPE_P (type
))
1279 /* Comparisons with 0 are often used for booleans and there is
1280 nothing useful to predict about them. */
1281 else if (integer_zerop (op0
)
1282 || integer_zerop (op1
))
1285 predict_edge_def (then_edge
, PRED_TREE_OPCODE_NONEQUAL
, TAKEN
);
1289 predict_edge_def (then_edge
, PRED_TREE_FPOPCODE
, TAKEN
);
1292 case UNORDERED_EXPR
:
1293 predict_edge_def (then_edge
, PRED_TREE_FPOPCODE
, NOT_TAKEN
);
1298 if (integer_zerop (op1
)
1299 || integer_onep (op1
)
1300 || integer_all_onesp (op1
)
1303 || real_minus_onep (op1
))
1304 predict_edge_def (then_edge
, PRED_TREE_OPCODE_POSITIVE
, NOT_TAKEN
);
1309 if (integer_zerop (op1
)
1310 || integer_onep (op1
)
1311 || integer_all_onesp (op1
)
1314 || real_minus_onep (op1
))
1315 predict_edge_def (then_edge
, PRED_TREE_OPCODE_POSITIVE
, TAKEN
);
1323 /* Try to guess whether the value of return means error code. */
1325 static enum br_predictor
1326 return_prediction (tree val
, enum prediction
*prediction
)
1330 return PRED_NO_PREDICTION
;
1331 /* Different heuristics for pointers and scalars. */
1332 if (POINTER_TYPE_P (TREE_TYPE (val
)))
1334 /* NULL is usually not returned. */
1335 if (integer_zerop (val
))
1337 *prediction
= NOT_TAKEN
;
1338 return PRED_NULL_RETURN
;
1341 else if (INTEGRAL_TYPE_P (TREE_TYPE (val
)))
1343 /* Negative return values are often used to indicate
1345 if (TREE_CODE (val
) == INTEGER_CST
1346 && tree_int_cst_sgn (val
) < 0)
1348 *prediction
= NOT_TAKEN
;
1349 return PRED_NEGATIVE_RETURN
;
1351 /* Constant return values seems to be commonly taken.
1352 Zero/one often represent booleans so exclude them from the
1354 if (TREE_CONSTANT (val
)
1355 && (!integer_zerop (val
) && !integer_onep (val
)))
1357 *prediction
= TAKEN
;
1358 return PRED_CONST_RETURN
;
1361 return PRED_NO_PREDICTION
;
1364 /* Find the basic block with return expression and look up for possible
1365 return value trying to apply RETURN_PREDICTION heuristics. */
1367 apply_return_prediction (void)
1369 gimple return_stmt
= NULL
;
1373 int phi_num_args
, i
;
1374 enum br_predictor pred
;
1375 enum prediction direction
;
1378 FOR_EACH_EDGE (e
, ei
, EXIT_BLOCK_PTR
->preds
)
1380 return_stmt
= last_stmt (e
->src
);
1382 && gimple_code (return_stmt
) == GIMPLE_RETURN
)
1387 return_val
= gimple_return_retval (return_stmt
);
1390 if (TREE_CODE (return_val
) != SSA_NAME
1391 || !SSA_NAME_DEF_STMT (return_val
)
1392 || gimple_code (SSA_NAME_DEF_STMT (return_val
)) != GIMPLE_PHI
)
1394 phi
= SSA_NAME_DEF_STMT (return_val
);
1395 phi_num_args
= gimple_phi_num_args (phi
);
1396 pred
= return_prediction (PHI_ARG_DEF (phi
, 0), &direction
);
1398 /* Avoid the degenerate case where all return values form the function
1399 belongs to same category (ie they are all positive constants)
1400 so we can hardly say something about them. */
1401 for (i
= 1; i
< phi_num_args
; i
++)
1402 if (pred
!= return_prediction (PHI_ARG_DEF (phi
, i
), &direction
))
1404 if (i
!= phi_num_args
)
1405 for (i
= 0; i
< phi_num_args
; i
++)
1407 pred
= return_prediction (PHI_ARG_DEF (phi
, i
), &direction
);
1408 if (pred
!= PRED_NO_PREDICTION
)
1409 predict_paths_leading_to (gimple_phi_arg_edge (phi
, i
)->src
, pred
,
1414 /* Look for basic block that contains unlikely to happen events
1415 (such as noreturn calls) and mark all paths leading to execution
1416 of this basic blocks as unlikely. */
1419 tree_bb_level_predictions (void)
1423 apply_return_prediction ();
1427 gimple_stmt_iterator gsi
;
1429 for (gsi
= gsi_start_bb (bb
); !gsi_end_p (gsi
);)
1431 gimple stmt
= gsi_stmt (gsi
);
1434 if (is_gimple_call (stmt
))
1436 if (gimple_call_flags (stmt
) & ECF_NORETURN
)
1437 predict_paths_leading_to (bb
, PRED_NORETURN
,
1439 decl
= gimple_call_fndecl (stmt
);
1441 && lookup_attribute ("cold",
1442 DECL_ATTRIBUTES (decl
)))
1443 predict_paths_leading_to (bb
, PRED_COLD_FUNCTION
,
1446 else if (gimple_code (stmt
) == GIMPLE_PREDICT
)
1448 predict_paths_leading_to (bb
, gimple_predict_predictor (stmt
),
1449 gimple_predict_outcome (stmt
));
1450 gsi_remove (&gsi
, true);
1459 #ifdef ENABLE_CHECKING
1461 /* Callback for pointer_map_traverse, asserts that the pointer map is
1465 assert_is_empty (const void *key ATTRIBUTE_UNUSED
, void **value
,
1466 void *data ATTRIBUTE_UNUSED
)
1468 gcc_assert (!*value
);
1473 /* Predict branch probabilities and estimate profile of the tree CFG. */
1475 tree_estimate_probability (void)
1479 loop_optimizer_init (0);
1480 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1481 flow_loops_dump (dump_file
, NULL
, 0);
1483 add_noreturn_fake_exit_edges ();
1484 connect_infinite_loops_to_exit ();
1485 /* We use loop_niter_by_eval, which requires that the loops have
1487 create_preheaders (CP_SIMPLE_PREHEADERS
);
1488 calculate_dominance_info (CDI_POST_DOMINATORS
);
1490 bb_predictions
= pointer_map_create ();
1491 tree_bb_level_predictions ();
1493 mark_irreducible_loops ();
1494 record_loop_exits ();
1495 if (number_of_loops () > 1)
1503 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1505 /* Predict early returns to be probable, as we've already taken
1506 care for error returns and other cases are often used for
1507 fast paths through function.
1509 Since we've already removed the return statements, we are
1510 looking for CFG like:
1520 if (e
->dest
!= bb
->next_bb
1521 && e
->dest
!= EXIT_BLOCK_PTR
1522 && single_succ_p (e
->dest
)
1523 && single_succ_edge (e
->dest
)->dest
== EXIT_BLOCK_PTR
1524 && gimple_code (last_stmt (e
->dest
)) == GIMPLE_RETURN
)
1529 if (single_succ_p (bb
))
1531 FOR_EACH_EDGE (e1
, ei1
, bb
->preds
)
1532 if (!predicted_by_p (e1
->src
, PRED_NULL_RETURN
)
1533 && !predicted_by_p (e1
->src
, PRED_CONST_RETURN
)
1534 && !predicted_by_p (e1
->src
, PRED_NEGATIVE_RETURN
))
1535 predict_edge_def (e1
, PRED_TREE_EARLY_RETURN
, NOT_TAKEN
);
1538 if (!predicted_by_p (e
->src
, PRED_NULL_RETURN
)
1539 && !predicted_by_p (e
->src
, PRED_CONST_RETURN
)
1540 && !predicted_by_p (e
->src
, PRED_NEGATIVE_RETURN
))
1541 predict_edge_def (e
, PRED_TREE_EARLY_RETURN
, NOT_TAKEN
);
1544 /* Look for block we are guarding (ie we dominate it,
1545 but it doesn't postdominate us). */
1546 if (e
->dest
!= EXIT_BLOCK_PTR
&& e
->dest
!= bb
1547 && dominated_by_p (CDI_DOMINATORS
, e
->dest
, e
->src
)
1548 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, e
->dest
))
1550 gimple_stmt_iterator bi
;
1552 /* The call heuristic claims that a guarded function call
1553 is improbable. This is because such calls are often used
1554 to signal exceptional situations such as printing error
1556 for (bi
= gsi_start_bb (e
->dest
); !gsi_end_p (bi
);
1559 gimple stmt
= gsi_stmt (bi
);
1560 if (is_gimple_call (stmt
)
1561 /* Constant and pure calls are hardly used to signalize
1562 something exceptional. */
1563 && gimple_has_side_effects (stmt
))
1565 predict_edge_def (e
, PRED_CALL
, NOT_TAKEN
);
1571 tree_predict_by_opcode (bb
);
1574 combine_predictions_for_bb (bb
);
1576 #ifdef ENABLE_CHECKING
1577 pointer_map_traverse (bb_predictions
, assert_is_empty
, NULL
);
1579 pointer_map_destroy (bb_predictions
);
1580 bb_predictions
= NULL
;
1582 strip_builtin_expect ();
1583 estimate_bb_frequencies ();
1584 free_dominance_info (CDI_POST_DOMINATORS
);
1585 remove_fake_exit_edges ();
1586 loop_optimizer_finalize ();
1587 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1588 gimple_dump_cfg (dump_file
, dump_flags
);
1589 if (profile_status
== PROFILE_ABSENT
)
1590 profile_status
= PROFILE_GUESSED
;
1594 /* Predict edges to successors of CUR whose sources are not postdominated by
1595 BB by PRED and recurse to all postdominators. */
1598 predict_paths_for_bb (basic_block cur
, basic_block bb
,
1599 enum br_predictor pred
,
1600 enum prediction taken
)
1606 /* We are looking for all edges forming edge cut induced by
1607 set of all blocks postdominated by BB. */
1608 FOR_EACH_EDGE (e
, ei
, cur
->preds
)
1609 if (e
->src
->index
>= NUM_FIXED_BLOCKS
1610 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, bb
))
1612 gcc_assert (bb
== cur
|| dominated_by_p (CDI_POST_DOMINATORS
, cur
, bb
));
1613 predict_edge_def (e
, pred
, taken
);
1615 for (son
= first_dom_son (CDI_POST_DOMINATORS
, cur
);
1617 son
= next_dom_son (CDI_POST_DOMINATORS
, son
))
1618 predict_paths_for_bb (son
, bb
, pred
, taken
);
1621 /* Sets branch probabilities according to PREDiction and
1625 predict_paths_leading_to (basic_block bb
, enum br_predictor pred
,
1626 enum prediction taken
)
1628 predict_paths_for_bb (bb
, bb
, pred
, taken
);
1631 /* This is used to carry information about basic blocks. It is
1632 attached to the AUX field of the standard CFG block. */
1634 typedef struct block_info_def
1636 /* Estimated frequency of execution of basic_block. */
1639 /* To keep queue of basic blocks to process. */
1642 /* Number of predecessors we need to visit first. */
1646 /* Similar information for edges. */
1647 typedef struct edge_info_def
1649 /* In case edge is a loopback edge, the probability edge will be reached
1650 in case header is. Estimated number of iterations of the loop can be
1651 then computed as 1 / (1 - back_edge_prob). */
1652 sreal back_edge_prob
;
1653 /* True if the edge is a loopback edge in the natural loop. */
1654 unsigned int back_edge
:1;
1657 #define BLOCK_INFO(B) ((block_info) (B)->aux)
1658 #define EDGE_INFO(E) ((edge_info) (E)->aux)
1660 /* Helper function for estimate_bb_frequencies.
1661 Propagate the frequencies in blocks marked in
1662 TOVISIT, starting in HEAD. */
1665 propagate_freq (basic_block head
, bitmap tovisit
)
1674 /* For each basic block we need to visit count number of his predecessors
1675 we need to visit first. */
1676 EXECUTE_IF_SET_IN_BITMAP (tovisit
, 0, i
, bi
)
1681 /* The outermost "loop" includes the exit block, which we can not
1682 look up via BASIC_BLOCK. Detect this and use EXIT_BLOCK_PTR
1683 directly. Do the same for the entry block. */
1684 bb
= BASIC_BLOCK (i
);
1686 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
1688 bool visit
= bitmap_bit_p (tovisit
, e
->src
->index
);
1690 if (visit
&& !(e
->flags
& EDGE_DFS_BACK
))
1692 else if (visit
&& dump_file
&& !EDGE_INFO (e
)->back_edge
)
1694 "Irreducible region hit, ignoring edge to %i->%i\n",
1695 e
->src
->index
, bb
->index
);
1697 BLOCK_INFO (bb
)->npredecessors
= count
;
1700 memcpy (&BLOCK_INFO (head
)->frequency
, &real_one
, sizeof (real_one
));
1702 for (bb
= head
; bb
; bb
= nextbb
)
1705 sreal cyclic_probability
, frequency
;
1707 memcpy (&cyclic_probability
, &real_zero
, sizeof (real_zero
));
1708 memcpy (&frequency
, &real_zero
, sizeof (real_zero
));
1710 nextbb
= BLOCK_INFO (bb
)->next
;
1711 BLOCK_INFO (bb
)->next
= NULL
;
1713 /* Compute frequency of basic block. */
1716 #ifdef ENABLE_CHECKING
1717 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
1718 gcc_assert (!bitmap_bit_p (tovisit
, e
->src
->index
)
1719 || (e
->flags
& EDGE_DFS_BACK
));
1722 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
1723 if (EDGE_INFO (e
)->back_edge
)
1725 sreal_add (&cyclic_probability
, &cyclic_probability
,
1726 &EDGE_INFO (e
)->back_edge_prob
);
1728 else if (!(e
->flags
& EDGE_DFS_BACK
))
1732 /* frequency += (e->probability
1733 * BLOCK_INFO (e->src)->frequency /
1734 REG_BR_PROB_BASE); */
1736 sreal_init (&tmp
, e
->probability
, 0);
1737 sreal_mul (&tmp
, &tmp
, &BLOCK_INFO (e
->src
)->frequency
);
1738 sreal_mul (&tmp
, &tmp
, &real_inv_br_prob_base
);
1739 sreal_add (&frequency
, &frequency
, &tmp
);
1742 if (sreal_compare (&cyclic_probability
, &real_zero
) == 0)
1744 memcpy (&BLOCK_INFO (bb
)->frequency
, &frequency
,
1745 sizeof (frequency
));
1749 if (sreal_compare (&cyclic_probability
, &real_almost_one
) > 0)
1751 memcpy (&cyclic_probability
, &real_almost_one
,
1752 sizeof (real_almost_one
));
1755 /* BLOCK_INFO (bb)->frequency = frequency
1756 / (1 - cyclic_probability) */
1758 sreal_sub (&cyclic_probability
, &real_one
, &cyclic_probability
);
1759 sreal_div (&BLOCK_INFO (bb
)->frequency
,
1760 &frequency
, &cyclic_probability
);
1764 bitmap_clear_bit (tovisit
, bb
->index
);
1766 e
= find_edge (bb
, head
);
1771 /* EDGE_INFO (e)->back_edge_prob
1772 = ((e->probability * BLOCK_INFO (bb)->frequency)
1773 / REG_BR_PROB_BASE); */
1775 sreal_init (&tmp
, e
->probability
, 0);
1776 sreal_mul (&tmp
, &tmp
, &BLOCK_INFO (bb
)->frequency
);
1777 sreal_mul (&EDGE_INFO (e
)->back_edge_prob
,
1778 &tmp
, &real_inv_br_prob_base
);
1781 /* Propagate to successor blocks. */
1782 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1783 if (!(e
->flags
& EDGE_DFS_BACK
)
1784 && BLOCK_INFO (e
->dest
)->npredecessors
)
1786 BLOCK_INFO (e
->dest
)->npredecessors
--;
1787 if (!BLOCK_INFO (e
->dest
)->npredecessors
)
1792 BLOCK_INFO (last
)->next
= e
->dest
;
1800 /* Estimate probabilities of loopback edges in loops at same nest level. */
1803 estimate_loops_at_level (struct loop
*first_loop
)
1807 for (loop
= first_loop
; loop
; loop
= loop
->next
)
1812 bitmap tovisit
= BITMAP_ALLOC (NULL
);
1814 estimate_loops_at_level (loop
->inner
);
1816 /* Find current loop back edge and mark it. */
1817 e
= loop_latch_edge (loop
);
1818 EDGE_INFO (e
)->back_edge
= 1;
1820 bbs
= get_loop_body (loop
);
1821 for (i
= 0; i
< loop
->num_nodes
; i
++)
1822 bitmap_set_bit (tovisit
, bbs
[i
]->index
);
1824 propagate_freq (loop
->header
, tovisit
);
1825 BITMAP_FREE (tovisit
);
1829 /* Propagates frequencies through structure of loops. */
1832 estimate_loops (void)
1834 bitmap tovisit
= BITMAP_ALLOC (NULL
);
1837 /* Start by estimating the frequencies in the loops. */
1838 if (number_of_loops () > 1)
1839 estimate_loops_at_level (current_loops
->tree_root
->inner
);
1841 /* Now propagate the frequencies through all the blocks. */
1844 bitmap_set_bit (tovisit
, bb
->index
);
1846 propagate_freq (ENTRY_BLOCK_PTR
, tovisit
);
1847 BITMAP_FREE (tovisit
);
1850 /* Convert counts measured by profile driven feedback to frequencies.
1851 Return nonzero iff there was any nonzero execution count. */
1854 counts_to_freqs (void)
1856 gcov_type count_max
, true_count_max
= 0;
1860 true_count_max
= MAX (bb
->count
, true_count_max
);
1862 count_max
= MAX (true_count_max
, 1);
1863 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
1864 bb
->frequency
= (bb
->count
* BB_FREQ_MAX
+ count_max
/ 2) / count_max
;
1866 return true_count_max
;
1869 /* Return true if function is likely to be expensive, so there is no point to
1870 optimize performance of prologue, epilogue or do inlining at the expense
1871 of code size growth. THRESHOLD is the limit of number of instructions
1872 function can execute at average to be still considered not expensive. */
1875 expensive_function_p (int threshold
)
1877 unsigned int sum
= 0;
1881 /* We can not compute accurately for large thresholds due to scaled
1883 gcc_assert (threshold
<= BB_FREQ_MAX
);
1885 /* Frequencies are out of range. This either means that function contains
1886 internal loop executing more than BB_FREQ_MAX times or profile feedback
1887 is available and function has not been executed at all. */
1888 if (ENTRY_BLOCK_PTR
->frequency
== 0)
1891 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
1892 limit
= ENTRY_BLOCK_PTR
->frequency
* threshold
;
1897 for (insn
= BB_HEAD (bb
); insn
!= NEXT_INSN (BB_END (bb
));
1898 insn
= NEXT_INSN (insn
))
1899 if (active_insn_p (insn
))
1901 sum
+= bb
->frequency
;
1910 /* Estimate basic blocks frequency by given branch probabilities. */
1913 estimate_bb_frequencies (void)
1918 if (!flag_branch_probabilities
|| !counts_to_freqs ())
1920 static int real_values_initialized
= 0;
1922 if (!real_values_initialized
)
1924 real_values_initialized
= 1;
1925 sreal_init (&real_zero
, 0, 0);
1926 sreal_init (&real_one
, 1, 0);
1927 sreal_init (&real_br_prob_base
, REG_BR_PROB_BASE
, 0);
1928 sreal_init (&real_bb_freq_max
, BB_FREQ_MAX
, 0);
1929 sreal_init (&real_one_half
, 1, -1);
1930 sreal_div (&real_inv_br_prob_base
, &real_one
, &real_br_prob_base
);
1931 sreal_sub (&real_almost_one
, &real_one
, &real_inv_br_prob_base
);
1934 mark_dfs_back_edges ();
1936 single_succ_edge (ENTRY_BLOCK_PTR
)->probability
= REG_BR_PROB_BASE
;
1938 /* Set up block info for each basic block. */
1939 alloc_aux_for_blocks (sizeof (struct block_info_def
));
1940 alloc_aux_for_edges (sizeof (struct edge_info_def
));
1941 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
1946 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1948 sreal_init (&EDGE_INFO (e
)->back_edge_prob
, e
->probability
, 0);
1949 sreal_mul (&EDGE_INFO (e
)->back_edge_prob
,
1950 &EDGE_INFO (e
)->back_edge_prob
,
1951 &real_inv_br_prob_base
);
1955 /* First compute probabilities locally for each loop from innermost
1956 to outermost to examine probabilities for back edges. */
1959 memcpy (&freq_max
, &real_zero
, sizeof (real_zero
));
1961 if (sreal_compare (&freq_max
, &BLOCK_INFO (bb
)->frequency
) < 0)
1962 memcpy (&freq_max
, &BLOCK_INFO (bb
)->frequency
, sizeof (freq_max
));
1964 sreal_div (&freq_max
, &real_bb_freq_max
, &freq_max
);
1965 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
1969 sreal_mul (&tmp
, &BLOCK_INFO (bb
)->frequency
, &freq_max
);
1970 sreal_add (&tmp
, &tmp
, &real_one_half
);
1971 bb
->frequency
= sreal_to_int (&tmp
);
1974 free_aux_for_blocks ();
1975 free_aux_for_edges ();
1977 compute_function_frequency ();
1978 if (flag_reorder_functions
)
1979 choose_function_section ();
1982 /* Decide whether function is hot, cold or unlikely executed. */
1984 compute_function_frequency (void)
1988 if (!profile_info
|| !flag_branch_probabilities
)
1990 if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl
))
1992 cfun
->function_frequency
= FUNCTION_FREQUENCY_UNLIKELY_EXECUTED
;
1993 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl
))
1995 cfun
->function_frequency
= FUNCTION_FREQUENCY_HOT
;
1998 cfun
->function_frequency
= FUNCTION_FREQUENCY_UNLIKELY_EXECUTED
;
2001 if (maybe_hot_bb_p (bb
))
2003 cfun
->function_frequency
= FUNCTION_FREQUENCY_HOT
;
2006 if (!probably_never_executed_bb_p (bb
))
2007 cfun
->function_frequency
= FUNCTION_FREQUENCY_NORMAL
;
2011 /* Choose appropriate section for the function. */
2013 choose_function_section (void)
2015 if (DECL_SECTION_NAME (current_function_decl
)
2016 || !targetm
.have_named_sections
2017 /* Theoretically we can split the gnu.linkonce text section too,
2018 but this requires more work as the frequency needs to match
2019 for all generated objects so we need to merge the frequency
2020 of all instances. For now just never set frequency for these. */
2021 || DECL_ONE_ONLY (current_function_decl
))
2024 /* If we are doing the partitioning optimization, let the optimization
2025 choose the correct section into which to put things. */
2027 if (flag_reorder_blocks_and_partition
)
2030 if (cfun
->function_frequency
== FUNCTION_FREQUENCY_HOT
)
2031 DECL_SECTION_NAME (current_function_decl
) =
2032 build_string (strlen (HOT_TEXT_SECTION_NAME
), HOT_TEXT_SECTION_NAME
);
2033 if (cfun
->function_frequency
== FUNCTION_FREQUENCY_UNLIKELY_EXECUTED
)
2034 DECL_SECTION_NAME (current_function_decl
) =
2035 build_string (strlen (UNLIKELY_EXECUTED_TEXT_SECTION_NAME
),
2036 UNLIKELY_EXECUTED_TEXT_SECTION_NAME
);
2040 gate_estimate_probability (void)
2042 return flag_guess_branch_prob
;
2045 /* Build PREDICT_EXPR. */
2047 build_predict_expr (enum br_predictor predictor
, enum prediction taken
)
2049 tree t
= build1 (PREDICT_EXPR
, void_type_node
,
2050 build_int_cst (NULL
, predictor
));
2051 PREDICT_EXPR_OUTCOME (t
) = taken
;
2056 predictor_name (enum br_predictor predictor
)
2058 return predictor_info
[predictor
].name
;
2061 struct gimple_opt_pass pass_profile
=
2065 "profile", /* name */
2066 gate_estimate_probability
, /* gate */
2067 tree_estimate_probability
, /* execute */
2070 0, /* static_pass_number */
2071 TV_BRANCH_PROB
, /* tv_id */
2072 PROP_cfg
, /* properties_required */
2073 0, /* properties_provided */
2074 0, /* properties_destroyed */
2075 0, /* todo_flags_start */
2076 TODO_ggc_collect
| TODO_verify_ssa
/* todo_flags_finish */