1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000, 2001, 2002 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 2, 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 COPYING. If not, write to the Free
18 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
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"
57 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
58 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
59 static sreal real_zero
, real_one
, real_almost_one
, real_br_prob_base
,
60 real_inv_br_prob_base
, real_one_half
, real_bb_freq_max
;
62 /* Random guesstimation given names. */
63 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 10 - 1)
64 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
65 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
66 #define PROB_ALWAYS (REG_BR_PROB_BASE)
68 static bool predicted_by_p
PARAMS ((basic_block
,
70 static void combine_predictions_for_insn
PARAMS ((rtx
, basic_block
));
71 static void dump_prediction
PARAMS ((enum br_predictor
, int,
73 static void estimate_loops_at_level
PARAMS ((struct loop
*loop
));
74 static void propagate_freq
PARAMS ((struct loop
*));
75 static void estimate_bb_frequencies
PARAMS ((struct loops
*));
76 static void counts_to_freqs
PARAMS ((void));
77 static void process_note_predictions
PARAMS ((basic_block
, int *,
80 static void process_note_prediction
PARAMS ((basic_block
, int *,
82 dominance_info
, int, int));
83 static bool last_basic_block_p
PARAMS ((basic_block
));
84 static void compute_function_frequency
PARAMS ((void));
85 static void choose_function_section
PARAMS ((void));
86 static bool can_predict_insn_p
PARAMS ((rtx
));
88 /* Information we hold about each branch predictor.
89 Filled using information from predict.def. */
93 const char *const name
; /* Name used in the debugging dumps. */
94 const int hitrate
; /* Expected hitrate used by
95 predict_insn_def call. */
99 /* Use given predictor without Dempster-Shaffer theory if it matches
100 using first_match heuristics. */
101 #define PRED_FLAG_FIRST_MATCH 1
103 /* Recompute hitrate in percent to our representation. */
105 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
107 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
108 static const struct predictor_info predictor_info
[]= {
109 #include "predict.def"
111 /* Upper bound on predictors. */
116 /* Return true in case BB can be CPU intensive and should be optimized
117 for maximal performance. */
123 if (profile_info
.count_profiles_merged
124 && flag_branch_probabilities
126 < profile_info
.max_counter_in_program
127 / PARAM_VALUE (HOT_BB_COUNT_FRACTION
)))
129 if (bb
->frequency
< BB_FREQ_MAX
/ PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION
))
134 /* Return true in case BB is cold and should be optimized for size. */
137 probably_cold_bb_p (bb
)
140 if (profile_info
.count_profiles_merged
141 && flag_branch_probabilities
143 < profile_info
.max_counter_in_program
144 / PARAM_VALUE (HOT_BB_COUNT_FRACTION
)))
146 if (bb
->frequency
< BB_FREQ_MAX
/ PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION
))
151 /* Return true in case BB is probably never executed. */
153 probably_never_executed_bb_p (bb
)
156 if (profile_info
.count_profiles_merged
157 && flag_branch_probabilities
)
158 return ((bb
->count
+ profile_info
.count_profiles_merged
/ 2)
159 / profile_info
.count_profiles_merged
) == 0;
163 /* Return true if the one of outgoing edges is already predicted by
167 predicted_by_p (bb
, predictor
)
169 enum br_predictor predictor
;
172 if (!INSN_P (bb
->end
))
174 for (note
= REG_NOTES (bb
->end
); note
; note
= XEXP (note
, 1))
175 if (REG_NOTE_KIND (note
) == REG_BR_PRED
176 && INTVAL (XEXP (XEXP (note
, 0), 0)) == (int)predictor
)
182 predict_insn (insn
, predictor
, probability
)
185 enum br_predictor predictor
;
187 if (!any_condjump_p (insn
))
189 if (!flag_guess_branch_prob
)
193 = gen_rtx_EXPR_LIST (REG_BR_PRED
,
194 gen_rtx_CONCAT (VOIDmode
,
195 GEN_INT ((int) predictor
),
196 GEN_INT ((int) probability
)),
200 /* Predict insn by given predictor. */
203 predict_insn_def (insn
, predictor
, taken
)
205 enum br_predictor predictor
;
206 enum prediction taken
;
208 int probability
= predictor_info
[(int) predictor
].hitrate
;
211 probability
= REG_BR_PROB_BASE
- probability
;
213 predict_insn (insn
, predictor
, probability
);
216 /* Predict edge E with given probability if possible. */
219 predict_edge (e
, predictor
, probability
)
222 enum br_predictor predictor
;
225 last_insn
= e
->src
->end
;
227 /* We can store the branch prediction information only about
228 conditional jumps. */
229 if (!any_condjump_p (last_insn
))
232 /* We always store probability of branching. */
233 if (e
->flags
& EDGE_FALLTHRU
)
234 probability
= REG_BR_PROB_BASE
- probability
;
236 predict_insn (last_insn
, predictor
, probability
);
239 /* Return true when we can store prediction on insn INSN.
240 At the moment we represent predictions only on conditional
241 jumps, not at computed jump or other complicated cases. */
243 can_predict_insn_p (insn
)
246 return (GET_CODE (insn
) == JUMP_INSN
247 && any_condjump_p (insn
)
248 && BLOCK_FOR_INSN (insn
)->succ
->succ_next
);
251 /* Predict edge E by given predictor if possible. */
254 predict_edge_def (e
, predictor
, taken
)
256 enum br_predictor predictor
;
257 enum prediction taken
;
259 int probability
= predictor_info
[(int) predictor
].hitrate
;
262 probability
= REG_BR_PROB_BASE
- probability
;
264 predict_edge (e
, predictor
, probability
);
267 /* Invert all branch predictions or probability notes in the INSN. This needs
268 to be done each time we invert the condition used by the jump. */
271 invert_br_probabilities (insn
)
276 for (note
= REG_NOTES (insn
); note
; note
= XEXP (note
, 1))
277 if (REG_NOTE_KIND (note
) == REG_BR_PROB
)
278 XEXP (note
, 0) = GEN_INT (REG_BR_PROB_BASE
- INTVAL (XEXP (note
, 0)));
279 else if (REG_NOTE_KIND (note
) == REG_BR_PRED
)
280 XEXP (XEXP (note
, 0), 1)
281 = GEN_INT (REG_BR_PROB_BASE
- INTVAL (XEXP (XEXP (note
, 0), 1)));
284 /* Dump information about the branch prediction to the output file. */
287 dump_prediction (predictor
, probability
, bb
, used
)
288 enum br_predictor predictor
;
298 while (e
&& (e
->flags
& EDGE_FALLTHRU
))
301 fprintf (rtl_dump_file
, " %s heuristics%s: %.1f%%",
302 predictor_info
[predictor
].name
,
303 used
? "" : " (ignored)", probability
* 100.0 / REG_BR_PROB_BASE
);
307 fprintf (rtl_dump_file
, " exec ");
308 fprintf (rtl_dump_file
, HOST_WIDEST_INT_PRINT_DEC
, bb
->count
);
311 fprintf (rtl_dump_file
, " hit ");
312 fprintf (rtl_dump_file
, HOST_WIDEST_INT_PRINT_DEC
, e
->count
);
313 fprintf (rtl_dump_file
, " (%.1f%%)", e
->count
* 100.0 / bb
->count
);
317 fprintf (rtl_dump_file
, "\n");
320 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
321 note if not already present. Remove now useless REG_BR_PRED notes. */
324 combine_predictions_for_insn (insn
, bb
)
328 rtx prob_note
= find_reg_note (insn
, REG_BR_PROB
, 0);
329 rtx
*pnote
= ®_NOTES (insn
);
331 int best_probability
= PROB_EVEN
;
332 int best_predictor
= END_PREDICTORS
;
333 int combined_probability
= REG_BR_PROB_BASE
/ 2;
335 bool first_match
= false;
339 fprintf (rtl_dump_file
, "Predictions for insn %i bb %i\n", INSN_UID (insn
),
342 /* We implement "first match" heuristics and use probability guessed
343 by predictor with smallest index. In the future we will use better
344 probability combination techniques. */
345 for (note
= REG_NOTES (insn
); note
; note
= XEXP (note
, 1))
346 if (REG_NOTE_KIND (note
) == REG_BR_PRED
)
348 int predictor
= INTVAL (XEXP (XEXP (note
, 0), 0));
349 int probability
= INTVAL (XEXP (XEXP (note
, 0), 1));
352 if (best_predictor
> predictor
)
353 best_probability
= probability
, best_predictor
= predictor
;
355 d
= (combined_probability
* probability
356 + (REG_BR_PROB_BASE
- combined_probability
)
357 * (REG_BR_PROB_BASE
- probability
));
359 /* Use FP math to avoid overflows of 32bit integers. */
361 /* If one probability is 0% and one 100%, avoid division by zero. */
362 combined_probability
= REG_BR_PROB_BASE
/ 2;
364 combined_probability
= (((double) combined_probability
) * probability
365 * REG_BR_PROB_BASE
/ d
+ 0.5);
368 /* Decide which heuristic to use. In case we didn't match anything,
369 use no_prediction heuristic, in case we did match, use either
370 first match or Dempster-Shaffer theory depending on the flags. */
372 if (predictor_info
[best_predictor
].flags
& PRED_FLAG_FIRST_MATCH
)
376 dump_prediction (PRED_NO_PREDICTION
, combined_probability
, bb
, true);
379 dump_prediction (PRED_DS_THEORY
, combined_probability
, bb
, !first_match
);
380 dump_prediction (PRED_FIRST_MATCH
, best_probability
, bb
, first_match
);
384 combined_probability
= best_probability
;
385 dump_prediction (PRED_COMBINED
, combined_probability
, bb
, true);
389 if (REG_NOTE_KIND (*pnote
) == REG_BR_PRED
)
391 int predictor
= INTVAL (XEXP (XEXP (*pnote
, 0), 0));
392 int probability
= INTVAL (XEXP (XEXP (*pnote
, 0), 1));
394 dump_prediction (predictor
, probability
, bb
,
395 !first_match
|| best_predictor
== predictor
);
396 *pnote
= XEXP (*pnote
, 1);
399 pnote
= &XEXP (*pnote
, 1);
405 = gen_rtx_EXPR_LIST (REG_BR_PROB
,
406 GEN_INT (combined_probability
), REG_NOTES (insn
));
408 /* Save the prediction into CFG in case we are seeing non-degenerated
410 if (bb
->succ
->succ_next
)
412 BRANCH_EDGE (bb
)->probability
= combined_probability
;
413 FALLTHRU_EDGE (bb
)->probability
414 = REG_BR_PROB_BASE
- combined_probability
;
419 /* Statically estimate the probability that a branch will be taken.
420 ??? In the next revision there will be a number of other predictors added
421 from the above references. Further, each heuristic will be factored out
422 into its own function for clarity (and to facilitate the combination of
426 estimate_probability (loops_info
)
427 struct loops
*loops_info
;
429 dominance_info dominators
, post_dominators
;
433 connect_infinite_loops_to_exit ();
434 dominators
= calculate_dominance_info (CDI_DOMINATORS
);
435 post_dominators
= calculate_dominance_info (CDI_POST_DOMINATORS
);
437 /* Try to predict out blocks in a loop that are not part of a
439 for (i
= 1; i
< loops_info
->num
; i
++)
441 basic_block bb
, *bbs
;
444 struct loop
*loop
= loops_info
->parray
[i
];
445 struct loop_desc desc
;
446 unsigned HOST_WIDE_INT niter
;
448 flow_loop_scan (loops_info
, loop
, LOOP_EXIT_EDGES
);
449 exits
= loop
->num_exits
;
451 if (simple_loop_p (loops_info
, loop
, &desc
)
455 niter
= desc
.niter
+ 1;
456 if (niter
== 0) /* We might overflow here. */
459 prob
= (REG_BR_PROB_BASE
460 - (REG_BR_PROB_BASE
+ niter
/2) / niter
);
461 /* Branch prediction algorithm gives 0 frequency for everything
462 after the end of loop for loop having 0 probability to finish. */
463 if (prob
== REG_BR_PROB_BASE
)
464 prob
= REG_BR_PROB_BASE
- 1;
465 predict_edge (desc
.in_edge
, PRED_LOOP_ITERATIONS
,
469 bbs
= get_loop_body (loop
);
470 for (j
= 0; j
< loop
->num_nodes
; j
++)
472 int header_found
= 0;
477 /* Bypass loop heuristics on continue statement. These
478 statements construct loops via "non-loop" constructs
479 in the source language and are better to be handled
481 if (!can_predict_insn_p (bb
->end
)
482 || predicted_by_p (bb
, PRED_CONTINUE
))
485 /* Loop branch heuristics - predict an edge back to a
486 loop's head as taken. */
487 for (e
= bb
->succ
; e
; e
= e
->succ_next
)
488 if (e
->dest
== loop
->header
489 && e
->src
== loop
->latch
)
492 predict_edge_def (e
, PRED_LOOP_BRANCH
, TAKEN
);
495 /* Loop exit heuristics - predict an edge exiting the loop if the
496 conditional has no loop header successors as not taken. */
498 for (e
= bb
->succ
; e
; e
= e
->succ_next
)
499 if (e
->dest
->index
< 0
500 || !flow_bb_inside_loop_p (loop
, e
->dest
))
504 - predictor_info
[(int) PRED_LOOP_EXIT
].hitrate
)
509 /* Attempt to predict conditional jumps using a number of heuristics. */
512 rtx last_insn
= bb
->end
;
516 if (! can_predict_insn_p (last_insn
))
519 for (e
= bb
->succ
; e
; e
= e
->succ_next
)
521 /* Predict early returns to be probable, as we've already taken
522 care for error returns and other are often used for fast paths
524 if ((e
->dest
== EXIT_BLOCK_PTR
525 || (e
->dest
->succ
&& !e
->dest
->succ
->succ_next
526 && e
->dest
->succ
->dest
== EXIT_BLOCK_PTR
))
527 && !predicted_by_p (bb
, PRED_NULL_RETURN
)
528 && !predicted_by_p (bb
, PRED_CONST_RETURN
)
529 && !predicted_by_p (bb
, PRED_NEGATIVE_RETURN
)
530 && !last_basic_block_p (e
->dest
))
531 predict_edge_def (e
, PRED_EARLY_RETURN
, TAKEN
);
533 /* Look for block we are guarding (ie we dominate it,
534 but it doesn't postdominate us). */
535 if (e
->dest
!= EXIT_BLOCK_PTR
&& e
->dest
!= bb
536 && dominated_by_p (dominators
, e
->dest
, e
->src
)
537 && !dominated_by_p (post_dominators
, e
->src
, e
->dest
))
541 /* The call heuristic claims that a guarded function call
542 is improbable. This is because such calls are often used
543 to signal exceptional situations such as printing error
545 for (insn
= e
->dest
->head
; insn
!= NEXT_INSN (e
->dest
->end
);
546 insn
= NEXT_INSN (insn
))
547 if (GET_CODE (insn
) == CALL_INSN
548 /* Constant and pure calls are hardly used to signalize
549 something exceptional. */
550 && ! CONST_OR_PURE_CALL_P (insn
))
552 predict_edge_def (e
, PRED_CALL
, NOT_TAKEN
);
558 cond
= get_condition (last_insn
, &earliest
);
562 /* Try "pointer heuristic."
563 A comparison ptr == 0 is predicted as false.
564 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
565 if (GET_RTX_CLASS (GET_CODE (cond
)) == '<'
566 && ((REG_P (XEXP (cond
, 0)) && REG_POINTER (XEXP (cond
, 0)))
567 || (REG_P (XEXP (cond
, 1)) && REG_POINTER (XEXP (cond
, 1)))))
569 if (GET_CODE (cond
) == EQ
)
570 predict_insn_def (last_insn
, PRED_POINTER
, NOT_TAKEN
);
571 else if (GET_CODE (cond
) == NE
)
572 predict_insn_def (last_insn
, PRED_POINTER
, TAKEN
);
576 /* Try "opcode heuristic."
577 EQ tests are usually false and NE tests are usually true. Also,
578 most quantities are positive, so we can make the appropriate guesses
579 about signed comparisons against zero. */
580 switch (GET_CODE (cond
))
583 /* Unconditional branch. */
584 predict_insn_def (last_insn
, PRED_UNCONDITIONAL
,
585 cond
== const0_rtx
? NOT_TAKEN
: TAKEN
);
590 /* Floating point comparisons appears to behave in a very
591 unpredictable way because of special role of = tests in
593 if (FLOAT_MODE_P (GET_MODE (XEXP (cond
, 0))))
595 /* Comparisons with 0 are often used for booleans and there is
596 nothing useful to predict about them. */
597 else if (XEXP (cond
, 1) == const0_rtx
598 || XEXP (cond
, 0) == const0_rtx
)
601 predict_insn_def (last_insn
, PRED_OPCODE_NONEQUAL
, NOT_TAKEN
);
606 /* Floating point comparisons appears to behave in a very
607 unpredictable way because of special role of = tests in
609 if (FLOAT_MODE_P (GET_MODE (XEXP (cond
, 0))))
611 /* Comparisons with 0 are often used for booleans and there is
612 nothing useful to predict about them. */
613 else if (XEXP (cond
, 1) == const0_rtx
614 || XEXP (cond
, 0) == const0_rtx
)
617 predict_insn_def (last_insn
, PRED_OPCODE_NONEQUAL
, TAKEN
);
621 predict_insn_def (last_insn
, PRED_FPOPCODE
, TAKEN
);
625 predict_insn_def (last_insn
, PRED_FPOPCODE
, NOT_TAKEN
);
630 if (XEXP (cond
, 1) == const0_rtx
|| XEXP (cond
, 1) == const1_rtx
631 || XEXP (cond
, 1) == constm1_rtx
)
632 predict_insn_def (last_insn
, PRED_OPCODE_POSITIVE
, NOT_TAKEN
);
637 if (XEXP (cond
, 1) == const0_rtx
|| XEXP (cond
, 1) == const1_rtx
638 || XEXP (cond
, 1) == constm1_rtx
)
639 predict_insn_def (last_insn
, PRED_OPCODE_POSITIVE
, TAKEN
);
647 /* Attach the combined probability to each conditional jump. */
649 if (GET_CODE (bb
->end
) == JUMP_INSN
650 && any_condjump_p (bb
->end
)
651 && bb
->succ
->succ_next
!= NULL
)
652 combine_predictions_for_insn (bb
->end
, bb
);
654 free_dominance_info (post_dominators
);
655 free_dominance_info (dominators
);
657 remove_fake_edges ();
658 estimate_bb_frequencies (loops_info
);
661 /* __builtin_expect dropped tokens into the insn stream describing expected
662 values of registers. Generate branch probabilities based off these
666 expected_value_to_br_prob ()
668 rtx insn
, cond
, ev
= NULL_RTX
, ev_reg
= NULL_RTX
;
670 for (insn
= get_insns (); insn
; insn
= NEXT_INSN (insn
))
672 switch (GET_CODE (insn
))
675 /* Look for expected value notes. */
676 if (NOTE_LINE_NUMBER (insn
) == NOTE_INSN_EXPECTED_VALUE
)
678 ev
= NOTE_EXPECTED_VALUE (insn
);
679 ev_reg
= XEXP (ev
, 0);
685 /* Never propagate across labels. */
690 /* Look for simple conditional branches. If we haven't got an
691 expected value yet, no point going further. */
692 if (GET_CODE (insn
) != JUMP_INSN
|| ev
== NULL_RTX
693 || ! any_condjump_p (insn
))
698 /* Look for insns that clobber the EV register. */
699 if (ev
&& reg_set_p (ev_reg
, insn
))
704 /* Collect the branch condition, hopefully relative to EV_REG. */
705 /* ??? At present we'll miss things like
706 (expected_value (eq r70 0))
708 (set r80 (lt r70 r71))
709 (set pc (if_then_else (ne r80 0) ...))
710 as canonicalize_condition will render this to us as
712 Could use cselib to try and reduce this further. */
713 cond
= XEXP (SET_SRC (pc_set (insn
)), 0);
714 cond
= canonicalize_condition (insn
, cond
, 0, NULL
, ev_reg
);
715 if (! cond
|| XEXP (cond
, 0) != ev_reg
716 || GET_CODE (XEXP (cond
, 1)) != CONST_INT
)
719 /* Substitute and simplify. Given that the expression we're
720 building involves two constants, we should wind up with either
722 cond
= gen_rtx_fmt_ee (GET_CODE (cond
), VOIDmode
,
723 XEXP (ev
, 1), XEXP (cond
, 1));
724 cond
= simplify_rtx (cond
);
726 /* Turn the condition into a scaled branch probability. */
727 if (cond
!= const_true_rtx
&& cond
!= const0_rtx
)
729 predict_insn_def (insn
, PRED_BUILTIN_EXPECT
,
730 cond
== const_true_rtx
? TAKEN
: NOT_TAKEN
);
734 /* Check whether this is the last basic block of function. Commonly tehre
735 is one extra common cleanup block. */
737 last_basic_block_p (bb
)
740 if (bb
== EXIT_BLOCK_PTR
)
743 return (bb
->next_bb
== EXIT_BLOCK_PTR
744 || (bb
->next_bb
->next_bb
== EXIT_BLOCK_PTR
745 && bb
->succ
&& !bb
->succ
->succ_next
746 && bb
->succ
->dest
->next_bb
== EXIT_BLOCK_PTR
));
749 /* Sets branch probabilities according to PREDiction and FLAGS. HEADS[bb->index]
750 should be index of basic block in that we need to alter branch predictions
751 (i.e. the first of our dominators such that we do not post-dominate it)
752 (but we fill this information on demand, so -1 may be there in case this
753 was not needed yet). */
756 process_note_prediction (bb
, heads
, dominators
, post_dominators
, pred
, flags
)
759 dominance_info dominators
;
760 dominance_info post_dominators
;
768 taken
= flags
& IS_TAKEN
;
770 if (heads
[bb
->index
] < 0)
772 /* This is first time we need this field in heads array; so
773 find first dominator that we do not post-dominate (we are
774 using already known members of heads array). */
776 basic_block next_ai
= get_immediate_dominator (dominators
, bb
);
779 while (heads
[next_ai
->index
] < 0)
781 if (!dominated_by_p (post_dominators
, next_ai
, bb
))
783 heads
[next_ai
->index
] = ai
->index
;
785 next_ai
= get_immediate_dominator (dominators
, next_ai
);
787 if (!dominated_by_p (post_dominators
, next_ai
, bb
))
788 head
= next_ai
->index
;
790 head
= heads
[next_ai
->index
];
791 while (next_ai
!= bb
)
794 if (heads
[ai
->index
] == ENTRY_BLOCK
)
795 ai
= ENTRY_BLOCK_PTR
;
797 ai
= BASIC_BLOCK (heads
[ai
->index
]);
798 heads
[next_ai
->index
] = head
;
801 y
= heads
[bb
->index
];
803 /* Now find the edge that leads to our branch and aply the prediction. */
805 if (y
== last_basic_block
|| !can_predict_insn_p (BASIC_BLOCK (y
)->end
))
807 for (e
= BASIC_BLOCK (y
)->succ
; e
; e
= e
->succ_next
)
808 if (e
->dest
->index
>= 0
809 && dominated_by_p (post_dominators
, e
->dest
, bb
))
810 predict_edge_def (e
, pred
, taken
);
813 /* Gathers NOTE_INSN_PREDICTIONs in given basic block and turns them
814 into branch probabilities. For description of heads array, see
815 process_note_prediction. */
818 process_note_predictions (bb
, heads
, dominators
, post_dominators
)
821 dominance_info dominators
;
822 dominance_info post_dominators
;
827 /* Additionally, we check here for blocks with no successors. */
828 int contained_noreturn_call
= 0;
830 int noreturn_block
= 1;
832 for (insn
= bb
->end
; insn
;
833 was_bb_head
|= (insn
== bb
->head
), insn
= PREV_INSN (insn
))
835 if (GET_CODE (insn
) != NOTE
)
841 /* Noreturn calls cause program to exit, therefore they are
842 always predicted as not taken. */
843 if (GET_CODE (insn
) == CALL_INSN
844 && find_reg_note (insn
, REG_NORETURN
, NULL
))
845 contained_noreturn_call
= 1;
849 if (NOTE_LINE_NUMBER (insn
) == NOTE_INSN_PREDICTION
)
851 int alg
= (int) NOTE_PREDICTION_ALG (insn
);
852 /* Process single prediction note. */
853 process_note_prediction (bb
,
857 alg
, (int) NOTE_PREDICTION_FLAGS (insn
));
861 for (e
= bb
->succ
; e
; e
= e
->succ_next
)
862 if (!(e
->flags
& EDGE_FAKE
))
864 if (contained_noreturn_call
)
866 /* This block ended from other reasons than because of return.
867 If it is because of noreturn call, this should certainly not
868 be taken. Otherwise it is probably some error recovery. */
869 process_note_prediction (bb
,
872 post_dominators
, PRED_NORETURN
, NOT_TAKEN
);
876 /* Gathers NOTE_INSN_PREDICTIONs and turns them into
877 branch probabilities. */
880 note_prediction_to_br_prob ()
883 dominance_info post_dominators
, dominators
;
886 /* To enable handling of noreturn blocks. */
887 add_noreturn_fake_exit_edges ();
888 connect_infinite_loops_to_exit ();
890 post_dominators
= calculate_dominance_info (CDI_POST_DOMINATORS
);
891 dominators
= calculate_dominance_info (CDI_DOMINATORS
);
893 heads
= xmalloc (sizeof (int) * last_basic_block
);
894 memset (heads
, -1, sizeof (int) * last_basic_block
);
895 heads
[ENTRY_BLOCK_PTR
->next_bb
->index
] = last_basic_block
;
897 /* Process all prediction notes. */
900 process_note_predictions (bb
, heads
, dominators
, post_dominators
);
902 free_dominance_info (post_dominators
);
903 free_dominance_info (dominators
);
906 remove_fake_edges ();
909 /* This is used to carry information about basic blocks. It is
910 attached to the AUX field of the standard CFG block. */
912 typedef struct block_info_def
914 /* Estimated frequency of execution of basic_block. */
917 /* To keep queue of basic blocks to process. */
920 /* True if block needs to be visited in prop_freqency. */
923 /* Number of predecessors we need to visit first. */
927 /* Similar information for edges. */
928 typedef struct edge_info_def
930 /* In case edge is an loopback edge, the probability edge will be reached
931 in case header is. Estimated number of iterations of the loop can be
932 then computed as 1 / (1 - back_edge_prob). */
933 sreal back_edge_prob
;
934 /* True if the edge is an loopback edge in the natural loop. */
938 #define BLOCK_INFO(B) ((block_info) (B)->aux)
939 #define EDGE_INFO(E) ((edge_info) (E)->aux)
941 /* Helper function for estimate_bb_frequencies.
942 Propagate the frequencies for LOOP. */
945 propagate_freq (loop
)
948 basic_block head
= loop
->header
;
954 /* For each basic block we need to visit count number of his predecessors
955 we need to visit first. */
958 if (BLOCK_INFO (bb
)->tovisit
)
962 for (e
= bb
->pred
; e
; e
= e
->pred_next
)
963 if (BLOCK_INFO (e
->src
)->tovisit
&& !(e
->flags
& EDGE_DFS_BACK
))
965 else if (BLOCK_INFO (e
->src
)->tovisit
966 && rtl_dump_file
&& !EDGE_INFO (e
)->back_edge
)
967 fprintf (rtl_dump_file
,
968 "Irreducible region hit, ignoring edge to %i->%i\n",
969 e
->src
->index
, bb
->index
);
970 BLOCK_INFO (bb
)->npredecessors
= count
;
974 memcpy (&BLOCK_INFO (head
)->frequency
, &real_one
, sizeof (real_one
));
976 for (bb
= head
; bb
; bb
= nextbb
)
978 sreal cyclic_probability
, frequency
;
980 memcpy (&cyclic_probability
, &real_zero
, sizeof (real_zero
));
981 memcpy (&frequency
, &real_zero
, sizeof (real_zero
));
983 nextbb
= BLOCK_INFO (bb
)->next
;
984 BLOCK_INFO (bb
)->next
= NULL
;
986 /* Compute frequency of basic block. */
989 #ifdef ENABLE_CHECKING
990 for (e
= bb
->pred
; e
; e
= e
->pred_next
)
991 if (BLOCK_INFO (e
->src
)->tovisit
&& !(e
->flags
& EDGE_DFS_BACK
))
995 for (e
= bb
->pred
; e
; e
= e
->pred_next
)
996 if (EDGE_INFO (e
)->back_edge
)
998 sreal_add (&cyclic_probability
, &cyclic_probability
,
999 &EDGE_INFO (e
)->back_edge_prob
);
1001 else if (!(e
->flags
& EDGE_DFS_BACK
))
1005 /* frequency += (e->probability
1006 * BLOCK_INFO (e->src)->frequency /
1007 REG_BR_PROB_BASE); */
1009 sreal_init (&tmp
, e
->probability
, 0);
1010 sreal_mul (&tmp
, &tmp
, &BLOCK_INFO (e
->src
)->frequency
);
1011 sreal_mul (&tmp
, &tmp
, &real_inv_br_prob_base
);
1012 sreal_add (&frequency
, &frequency
, &tmp
);
1015 if (sreal_compare (&cyclic_probability
, &real_zero
) == 0)
1017 memcpy (&BLOCK_INFO (bb
)->frequency
, &frequency
,
1018 sizeof (frequency
));
1022 if (sreal_compare (&cyclic_probability
, &real_almost_one
) > 0)
1024 memcpy (&cyclic_probability
, &real_almost_one
,
1025 sizeof (real_almost_one
));
1028 /* BLOCK_INFO (bb)->frequency = frequency
1029 / (1 - cyclic_probability) */
1031 sreal_sub (&cyclic_probability
, &real_one
, &cyclic_probability
);
1032 sreal_div (&BLOCK_INFO (bb
)->frequency
,
1033 &frequency
, &cyclic_probability
);
1037 BLOCK_INFO (bb
)->tovisit
= 0;
1039 /* Compute back edge frequencies. */
1040 for (e
= bb
->succ
; e
; e
= e
->succ_next
)
1041 if (e
->dest
== head
)
1045 /* EDGE_INFO (e)->back_edge_prob
1046 = ((e->probability * BLOCK_INFO (bb)->frequency)
1047 / REG_BR_PROB_BASE); */
1049 sreal_init (&tmp
, e
->probability
, 0);
1050 sreal_mul (&tmp
, &tmp
, &BLOCK_INFO (bb
)->frequency
);
1051 sreal_mul (&EDGE_INFO (e
)->back_edge_prob
,
1052 &tmp
, &real_inv_br_prob_base
);
1055 /* Propagate to successor blocks. */
1056 for (e
= bb
->succ
; e
; e
= e
->succ_next
)
1057 if (!(e
->flags
& EDGE_DFS_BACK
)
1058 && BLOCK_INFO (e
->dest
)->npredecessors
)
1060 BLOCK_INFO (e
->dest
)->npredecessors
--;
1061 if (!BLOCK_INFO (e
->dest
)->npredecessors
)
1066 BLOCK_INFO (last
)->next
= e
->dest
;
1074 /* Estimate probabilities of loopback edges in loops at same nest level. */
1077 estimate_loops_at_level (first_loop
)
1078 struct loop
*first_loop
;
1082 for (loop
= first_loop
; loop
; loop
= loop
->next
)
1088 estimate_loops_at_level (loop
->inner
);
1090 if (loop
->latch
->succ
) /* Do not do this for dummy function loop. */
1092 /* Find current loop back edge and mark it. */
1093 e
= loop_latch_edge (loop
);
1094 EDGE_INFO (e
)->back_edge
= 1;
1097 bbs
= get_loop_body (loop
);
1098 for (i
= 0; i
< loop
->num_nodes
; i
++)
1099 BLOCK_INFO (bbs
[i
])->tovisit
= 1;
1101 propagate_freq (loop
);
1105 /* Convert counts measured by profile driven feedback to frequencies. */
1110 gcov_type count_max
= 1;
1114 count_max
= MAX (bb
->count
, count_max
);
1116 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
1117 bb
->frequency
= (bb
->count
* BB_FREQ_MAX
+ count_max
/ 2) / count_max
;
1120 /* Return true if function is likely to be expensive, so there is no point to
1121 optimize performance of prologue, epilogue or do inlining at the expense
1122 of code size growth. THRESHOLD is the limit of number of instructions
1123 function can execute at average to be still considered not expensive. */
1126 expensive_function_p (threshold
)
1129 unsigned int sum
= 0;
1133 /* We can not compute accurately for large thresholds due to scaled
1135 if (threshold
> BB_FREQ_MAX
)
1138 /* Frequencies are out of range. This either means that function contains
1139 internal loop executing more than BB_FREQ_MAX times or profile feedback
1140 is available and function has not been executed at all. */
1141 if (ENTRY_BLOCK_PTR
->frequency
== 0)
1144 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
1145 limit
= ENTRY_BLOCK_PTR
->frequency
* threshold
;
1150 for (insn
= bb
->head
; insn
!= NEXT_INSN (bb
->end
);
1151 insn
= NEXT_INSN (insn
))
1152 if (active_insn_p (insn
))
1154 sum
+= bb
->frequency
;
1163 /* Estimate basic blocks frequency by given branch probabilities. */
1166 estimate_bb_frequencies (loops
)
1167 struct loops
*loops
;
1172 if (flag_branch_probabilities
)
1176 sreal_init (&real_zero
, 0, 0);
1177 sreal_init (&real_one
, 1, 0);
1178 sreal_init (&real_br_prob_base
, REG_BR_PROB_BASE
, 0);
1179 sreal_init (&real_bb_freq_max
, BB_FREQ_MAX
, 0);
1180 sreal_init (&real_one_half
, 1, -1);
1181 sreal_div (&real_inv_br_prob_base
, &real_one
, &real_br_prob_base
);
1182 sreal_sub (&real_almost_one
, &real_one
, &real_inv_br_prob_base
);
1184 mark_dfs_back_edges ();
1185 /* Fill in the probability values in flowgraph based on the REG_BR_PROB
1189 rtx last_insn
= bb
->end
;
1191 if (!can_predict_insn_p (last_insn
))
1193 /* We can predict only conditional jumps at the moment.
1194 Expect each edge to be equally probable.
1195 ?? In the future we want to make abnormal edges improbable. */
1199 for (e
= bb
->succ
; e
; e
= e
->succ_next
)
1202 if (e
->probability
!= 0)
1206 for (e
= bb
->succ
; e
; e
= e
->succ_next
)
1207 e
->probability
= (REG_BR_PROB_BASE
+ nedges
/ 2) / nedges
;
1211 ENTRY_BLOCK_PTR
->succ
->probability
= REG_BR_PROB_BASE
;
1213 /* Set up block info for each basic block. */
1214 alloc_aux_for_blocks (sizeof (struct block_info_def
));
1215 alloc_aux_for_edges (sizeof (struct edge_info_def
));
1216 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
1220 BLOCK_INFO (bb
)->tovisit
= 0;
1221 for (e
= bb
->succ
; e
; e
= e
->succ_next
)
1223 sreal_init (&EDGE_INFO (e
)->back_edge_prob
, e
->probability
, 0);
1224 sreal_mul (&EDGE_INFO (e
)->back_edge_prob
,
1225 &EDGE_INFO (e
)->back_edge_prob
,
1226 &real_inv_br_prob_base
);
1230 /* First compute probabilities locally for each loop from innermost
1231 to outermost to examine probabilities for back edges. */
1232 estimate_loops_at_level (loops
->tree_root
);
1234 memcpy (&freq_max
, &real_zero
, sizeof (real_zero
));
1236 if (sreal_compare (&freq_max
, &BLOCK_INFO (bb
)->frequency
) < 0)
1237 memcpy (&freq_max
, &BLOCK_INFO (bb
)->frequency
, sizeof (freq_max
));
1239 sreal_div (&freq_max
, &real_bb_freq_max
, &freq_max
);
1240 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
1244 sreal_mul (&tmp
, &BLOCK_INFO (bb
)->frequency
, &freq_max
);
1245 sreal_add (&tmp
, &tmp
, &real_one_half
);
1246 bb
->frequency
= sreal_to_int (&tmp
);
1249 free_aux_for_blocks ();
1250 free_aux_for_edges ();
1252 compute_function_frequency ();
1253 if (flag_reorder_functions
)
1254 choose_function_section ();
1257 /* Decide whether function is hot, cold or unlikely executed. */
1259 compute_function_frequency ()
1263 if (!profile_info
.count_profiles_merged
1264 || !flag_branch_probabilities
)
1266 cfun
->function_frequency
= FUNCTION_FREQUENCY_UNLIKELY_EXECUTED
;
1269 if (maybe_hot_bb_p (bb
))
1271 cfun
->function_frequency
= FUNCTION_FREQUENCY_HOT
;
1274 if (!probably_never_executed_bb_p (bb
))
1275 cfun
->function_frequency
= FUNCTION_FREQUENCY_NORMAL
;
1279 /* Choose appropriate section for the function. */
1281 choose_function_section ()
1283 if (DECL_SECTION_NAME (current_function_decl
)
1284 || !targetm
.have_named_sections
1285 /* Theoretically we can split the gnu.linkonce text section too,
1286 but this requires more work as the frequency needs to match
1287 for all generated objects so we need to merge the frequency
1288 of all instances. For now just never set frequency for these. */
1289 || DECL_ONE_ONLY (current_function_decl
))
1291 if (cfun
->function_frequency
== FUNCTION_FREQUENCY_HOT
)
1292 DECL_SECTION_NAME (current_function_decl
) =
1293 build_string (strlen (HOT_TEXT_SECTION_NAME
), HOT_TEXT_SECTION_NAME
);
1294 if (cfun
->function_frequency
== FUNCTION_FREQUENCY_UNLIKELY_EXECUTED
)
1295 DECL_SECTION_NAME (current_function_decl
) =
1296 build_string (strlen (UNLIKELY_EXECUTED_TEXT_SECTION_NAME
),
1297 UNLIKELY_EXECUTED_TEXT_SECTION_NAME
);