1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004 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"
56 #include "tree-flow.h"
58 #include "tree-dump.h"
59 #include "tree-pass.h"
61 #include "tree-scalar-evolution.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 / 10 - 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 estimate_loops_at_level (struct loop *loop);
78 static void propagate_freq (struct loop *);
79 static void estimate_bb_frequencies (struct loops *);
80 static int counts_to_freqs (void);
81 static bool last_basic_block_p (basic_block);
82 static void compute_function_frequency (void);
83 static void choose_function_section (void);
84 static bool can_predict_insn_p (rtx);
86 /* Information we hold about each branch predictor.
87 Filled using information from predict.def. */
91 const char *const name; /* Name used in the debugging dumps. */
92 const int hitrate; /* Expected hitrate used by
93 predict_insn_def call. */
97 /* Use given predictor without Dempster-Shaffer theory if it matches
98 using first_match heuristics. */
99 #define PRED_FLAG_FIRST_MATCH 1
101 /* Recompute hitrate in percent to our representation. */
103 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
105 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
106 static const struct predictor_info predictor_info[]= {
107 #include "predict.def"
109 /* Upper bound on predictors. */
114 /* Return true in case BB can be CPU intensive and should be optimized
115 for maximal performance. */
118 maybe_hot_bb_p (basic_block bb)
120 if (profile_info && flag_branch_probabilities
122 < profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
124 if (bb->frequency < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
129 /* Return true in case BB is cold and should be optimized for size. */
132 probably_cold_bb_p (basic_block bb)
134 if (profile_info && flag_branch_probabilities
136 < profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
138 if (bb->frequency < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
143 /* Return true in case BB is probably never executed. */
145 probably_never_executed_bb_p (basic_block bb)
147 if (profile_info && flag_branch_probabilities)
148 return ((bb->count + profile_info->runs / 2) / profile_info->runs) == 0;
152 /* Return true if the one of outgoing edges is already predicted by
156 rtl_predicted_by_p (basic_block bb, enum br_predictor predictor)
159 if (!INSN_P (BB_END (bb)))
161 for (note = REG_NOTES (BB_END (bb)); note; note = XEXP (note, 1))
162 if (REG_NOTE_KIND (note) == REG_BR_PRED
163 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
168 /* Return true if the one of outgoing edges is already predicted by
172 tree_predicted_by_p (basic_block bb, enum br_predictor predictor)
174 struct edge_prediction *i = bb_ann (bb)->predictions;
175 for (i = bb_ann (bb)->predictions; i; i = i->next)
176 if (i->predictor == predictor)
182 predict_insn (rtx insn, enum br_predictor predictor, int probability)
184 if (!any_condjump_p (insn))
186 if (!flag_guess_branch_prob)
190 = gen_rtx_EXPR_LIST (REG_BR_PRED,
191 gen_rtx_CONCAT (VOIDmode,
192 GEN_INT ((int) predictor),
193 GEN_INT ((int) probability)),
197 /* Predict insn by given predictor. */
200 predict_insn_def (rtx insn, enum br_predictor predictor,
201 enum prediction taken)
203 int probability = predictor_info[(int) predictor].hitrate;
206 probability = REG_BR_PROB_BASE - probability;
208 predict_insn (insn, predictor, probability);
211 /* Predict edge E with given probability if possible. */
214 rtl_predict_edge (edge e, enum br_predictor predictor, int probability)
217 last_insn = BB_END (e->src);
219 /* We can store the branch prediction information only about
220 conditional jumps. */
221 if (!any_condjump_p (last_insn))
224 /* We always store probability of branching. */
225 if (e->flags & EDGE_FALLTHRU)
226 probability = REG_BR_PROB_BASE - probability;
228 predict_insn (last_insn, predictor, probability);
231 /* Predict edge E with the given PROBABILITY. */
233 tree_predict_edge (edge e, enum br_predictor predictor, int probability)
235 struct edge_prediction *i = ggc_alloc (sizeof (struct edge_prediction));
237 i->next = bb_ann (e->src)->predictions;
238 bb_ann (e->src)->predictions = i;
239 i->probability = probability;
240 i->predictor = predictor;
244 /* Return true when we can store prediction on insn INSN.
245 At the moment we represent predictions only on conditional
246 jumps, not at computed jump or other complicated cases. */
248 can_predict_insn_p (rtx insn)
250 return (JUMP_P (insn)
251 && any_condjump_p (insn)
252 && BLOCK_FOR_INSN (insn)->succ->succ_next);
255 /* Predict edge E by given predictor if possible. */
258 predict_edge_def (edge e, enum br_predictor predictor,
259 enum prediction taken)
261 int probability = predictor_info[(int) predictor].hitrate;
264 probability = REG_BR_PROB_BASE - probability;
266 predict_edge (e, predictor, probability);
269 /* Invert all branch predictions or probability notes in the INSN. This needs
270 to be done each time we invert the condition used by the jump. */
273 invert_br_probabilities (rtx insn)
277 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
278 if (REG_NOTE_KIND (note) == REG_BR_PROB)
279 XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
280 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
281 XEXP (XEXP (note, 0), 1)
282 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
285 /* Dump information about the branch prediction to the output file. */
288 dump_prediction (FILE *file, enum br_predictor predictor, int probability,
289 basic_block bb, int used)
296 while (e && (e->flags & EDGE_FALLTHRU))
299 fprintf (file, " %s heuristics%s: %.1f%%",
300 predictor_info[predictor].name,
301 used ? "" : " (ignored)", probability * 100.0 / REG_BR_PROB_BASE);
305 fprintf (file, " exec ");
306 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, bb->count);
309 fprintf (file, " hit ");
310 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, e->count);
311 fprintf (file, " (%.1f%%)", e->count * 100.0 / bb->count);
315 fprintf (file, "\n");
318 /* We can not predict the probabilities of outgoing edges of bb. Set them
319 evenly and hope for the best. */
321 set_even_probabilities (basic_block bb)
326 for (e = bb->succ; e; e = e->succ_next)
327 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
329 for (e = bb->succ; e; e = e->succ_next)
330 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
331 e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
336 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
337 note if not already present. Remove now useless REG_BR_PRED notes. */
340 combine_predictions_for_insn (rtx insn, basic_block bb)
345 int best_probability = PROB_EVEN;
346 int best_predictor = END_PREDICTORS;
347 int combined_probability = REG_BR_PROB_BASE / 2;
349 bool first_match = false;
352 if (!can_predict_insn_p (insn))
354 set_even_probabilities (bb);
358 prob_note = find_reg_note (insn, REG_BR_PROB, 0);
359 pnote = ®_NOTES (insn);
361 fprintf (dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
364 /* We implement "first match" heuristics and use probability guessed
365 by predictor with smallest index. */
366 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
367 if (REG_NOTE_KIND (note) == REG_BR_PRED)
369 int predictor = INTVAL (XEXP (XEXP (note, 0), 0));
370 int probability = INTVAL (XEXP (XEXP (note, 0), 1));
373 if (best_predictor > predictor)
374 best_probability = probability, best_predictor = predictor;
376 d = (combined_probability * probability
377 + (REG_BR_PROB_BASE - combined_probability)
378 * (REG_BR_PROB_BASE - probability));
380 /* Use FP math to avoid overflows of 32bit integers. */
382 /* If one probability is 0% and one 100%, avoid division by zero. */
383 combined_probability = REG_BR_PROB_BASE / 2;
385 combined_probability = (((double) combined_probability) * probability
386 * REG_BR_PROB_BASE / d + 0.5);
389 /* Decide which heuristic to use. In case we didn't match anything,
390 use no_prediction heuristic, in case we did match, use either
391 first match or Dempster-Shaffer theory depending on the flags. */
393 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
397 dump_prediction (dump_file, PRED_NO_PREDICTION,
398 combined_probability, bb, true);
401 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability,
403 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability,
408 combined_probability = best_probability;
409 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
413 if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
415 int predictor = INTVAL (XEXP (XEXP (*pnote, 0), 0));
416 int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
418 dump_prediction (dump_file, predictor, probability, bb,
419 !first_match || best_predictor == predictor);
420 *pnote = XEXP (*pnote, 1);
423 pnote = &XEXP (*pnote, 1);
429 = gen_rtx_EXPR_LIST (REG_BR_PROB,
430 GEN_INT (combined_probability), REG_NOTES (insn));
432 /* Save the prediction into CFG in case we are seeing non-degenerated
434 if (bb->succ->succ_next)
436 BRANCH_EDGE (bb)->probability = combined_probability;
437 FALLTHRU_EDGE (bb)->probability
438 = REG_BR_PROB_BASE - combined_probability;
443 /* Combine predictions into single probability and store them into CFG.
444 Remove now useless prediction entries. */
447 combine_predictions_for_bb (FILE *file, basic_block bb)
449 int best_probability = PROB_EVEN;
450 int best_predictor = END_PREDICTORS;
451 int combined_probability = REG_BR_PROB_BASE / 2;
453 bool first_match = false;
455 struct edge_prediction *pred;
457 edge e, first = NULL, second = NULL;
459 for (e = bb->succ; e; e = e->succ_next)
460 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
463 if (first && !second)
469 /* When there is no successor or only one choice, prediction is easy.
471 We are lazy for now and predict only basic blocks with two outgoing
472 edges. It is possible to predict generic case too, but we have to
473 ignore first match heuristics and do more involved combining. Implement
478 set_even_probabilities (bb);
479 bb_ann (bb)->predictions = NULL;
481 fprintf (file, "%i edges in bb %i predicted to even probabilities\n",
487 fprintf (file, "Predictions for bb %i\n", bb->index);
489 /* We implement "first match" heuristics and use probability guessed
490 by predictor with smallest index. */
491 for (pred = bb_ann (bb)->predictions; pred; pred = pred->next)
493 int predictor = pred->predictor;
494 int probability = pred->probability;
496 if (pred->edge != first)
497 probability = REG_BR_PROB_BASE - probability;
500 if (best_predictor > predictor)
501 best_probability = probability, best_predictor = predictor;
503 d = (combined_probability * probability
504 + (REG_BR_PROB_BASE - combined_probability)
505 * (REG_BR_PROB_BASE - probability));
507 /* Use FP math to avoid overflows of 32bit integers. */
509 /* If one probability is 0% and one 100%, avoid division by zero. */
510 combined_probability = REG_BR_PROB_BASE / 2;
512 combined_probability = (((double) combined_probability) * probability
513 * REG_BR_PROB_BASE / d + 0.5);
516 /* Decide which heuristic to use. In case we didn't match anything,
517 use no_prediction heuristic, in case we did match, use either
518 first match or Dempster-Shaffer theory depending on the flags. */
520 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
524 dump_prediction (file, PRED_NO_PREDICTION, combined_probability, bb, true);
527 dump_prediction (file, PRED_DS_THEORY, combined_probability, bb,
529 dump_prediction (file, PRED_FIRST_MATCH, best_probability, bb,
534 combined_probability = best_probability;
535 dump_prediction (file, PRED_COMBINED, combined_probability, bb, true);
537 for (pred = bb_ann (bb)->predictions; pred; pred = pred->next)
539 int predictor = pred->predictor;
540 int probability = pred->probability;
542 if (pred->edge != bb->succ)
543 probability = REG_BR_PROB_BASE - probability;
544 dump_prediction (file, predictor, probability, bb,
545 !first_match || best_predictor == predictor);
547 bb_ann (bb)->predictions = NULL;
551 first->probability = combined_probability;
552 second->probability = REG_BR_PROB_BASE - combined_probability;
556 /* Predict edge probabilities by exploiting loop structure.
557 When RTLSIMPLELOOPS is set, attempt to count number of iterations by analyzing
558 RTL otherwise use tree based approach. */
560 predict_loops (struct loops *loops_info, bool rtlsimpleloops)
565 scev_initialize (loops_info);
567 /* Try to predict out blocks in a loop that are not part of a
569 for (i = 1; i < loops_info->num; i++)
571 basic_block bb, *bbs;
574 struct loop *loop = loops_info->parray[i];
575 struct niter_desc desc;
576 unsigned HOST_WIDE_INT niter;
578 flow_loop_scan (loop, LOOP_EXIT_EDGES);
579 exits = loop->num_exits;
583 iv_analysis_loop_init (loop);
584 find_simple_exit (loop, &desc);
586 if (desc.simple_p && desc.const_iter)
589 niter = desc.niter + 1;
590 if (niter == 0) /* We might overflow here. */
593 prob = (REG_BR_PROB_BASE
594 - (REG_BR_PROB_BASE + niter /2) / niter);
595 /* Branch prediction algorithm gives 0 frequency for everything
596 after the end of loop for loop having 0 probability to finish. */
597 if (prob == REG_BR_PROB_BASE)
598 prob = REG_BR_PROB_BASE - 1;
599 predict_edge (desc.in_edge, PRED_LOOP_ITERATIONS,
607 struct tree_niter_desc niter_desc;
609 exits = get_loop_exit_edges (loop, &n_exits);
610 for (j = 0; j < n_exits; j++)
614 if (number_of_iterations_exit (loop, exits[j], &niter_desc))
615 niter = niter_desc.niter;
616 if (!niter || TREE_CODE (niter_desc.niter) != INTEGER_CST)
617 niter = loop_niter_by_eval (loop, exits[j]);
619 if (TREE_CODE (niter) == INTEGER_CST)
622 if (host_integerp (niter, 1)
623 && tree_int_cst_lt (niter,
624 build_int_cstu (NULL_TREE,
625 REG_BR_PROB_BASE - 1)))
627 HOST_WIDE_INT nitercst = tree_low_cst (niter, 1) + 1;
628 probability = (REG_BR_PROB_BASE + nitercst / 2) / nitercst;
633 predict_edge (exits[j], PRED_LOOP_ITERATIONS, probability);
640 bbs = get_loop_body (loop);
642 for (j = 0; j < loop->num_nodes; j++)
644 int header_found = 0;
649 /* Bypass loop heuristics on continue statement. These
650 statements construct loops via "non-loop" constructs
651 in the source language and are better to be handled
653 if ((rtlsimpleloops && !can_predict_insn_p (BB_END (bb)))
654 || predicted_by_p (bb, PRED_CONTINUE))
657 /* Loop branch heuristics - predict an edge back to a
658 loop's head as taken. */
659 for (e = bb->succ; e; e = e->succ_next)
660 if (e->dest == loop->header
661 && e->src == loop->latch)
664 predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
667 /* Loop exit heuristics - predict an edge exiting the loop if the
668 conditional has no loop header successors as not taken. */
670 for (e = bb->succ; e; e = e->succ_next)
671 if (e->dest->index < 0
672 || !flow_bb_inside_loop_p (loop, e->dest))
676 - predictor_info [(int) PRED_LOOP_EXIT].hitrate)
680 /* Free basic blocks from get_loop_body. */
688 /* Attempt to predict probabilities of BB outgoing edges using local
691 bb_estimate_probability_locally (basic_block bb)
693 rtx last_insn = BB_END (bb);
696 if (! can_predict_insn_p (last_insn))
698 cond = get_condition (last_insn, NULL, false, false);
702 /* Try "pointer heuristic."
703 A comparison ptr == 0 is predicted as false.
704 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
705 if (COMPARISON_P (cond)
706 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
707 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
709 if (GET_CODE (cond) == EQ)
710 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
711 else if (GET_CODE (cond) == NE)
712 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
716 /* Try "opcode heuristic."
717 EQ tests are usually false and NE tests are usually true. Also,
718 most quantities are positive, so we can make the appropriate guesses
719 about signed comparisons against zero. */
720 switch (GET_CODE (cond))
723 /* Unconditional branch. */
724 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
725 cond == const0_rtx ? NOT_TAKEN : TAKEN);
730 /* Floating point comparisons appears to behave in a very
731 unpredictable way because of special role of = tests in
733 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
735 /* Comparisons with 0 are often used for booleans and there is
736 nothing useful to predict about them. */
737 else if (XEXP (cond, 1) == const0_rtx
738 || XEXP (cond, 0) == const0_rtx)
741 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
746 /* Floating point comparisons appears to behave in a very
747 unpredictable way because of special role of = tests in
749 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
751 /* Comparisons with 0 are often used for booleans and there is
752 nothing useful to predict about them. */
753 else if (XEXP (cond, 1) == const0_rtx
754 || XEXP (cond, 0) == const0_rtx)
757 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
761 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
765 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
770 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
771 || XEXP (cond, 1) == constm1_rtx)
772 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
777 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
778 || XEXP (cond, 1) == constm1_rtx)
779 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
787 /* Statically estimate the probability that a branch will be taken and produce
788 estimated profile. When profile feedback is present never executed portions
789 of function gets estimated. */
792 estimate_probability (struct loops *loops_info)
796 connect_infinite_loops_to_exit ();
797 calculate_dominance_info (CDI_DOMINATORS);
798 calculate_dominance_info (CDI_POST_DOMINATORS);
800 predict_loops (loops_info, true);
804 /* Attempt to predict conditional jumps using a number of heuristics. */
807 rtx last_insn = BB_END (bb);
810 if (! can_predict_insn_p (last_insn))
813 for (e = bb->succ; e; e = e->succ_next)
815 /* Predict early returns to be probable, as we've already taken
816 care for error returns and other are often used for fast paths
818 if ((e->dest == EXIT_BLOCK_PTR
819 || (e->dest->succ && !e->dest->succ->succ_next
820 && e->dest->succ->dest == EXIT_BLOCK_PTR))
821 && !predicted_by_p (bb, PRED_NULL_RETURN)
822 && !predicted_by_p (bb, PRED_CONST_RETURN)
823 && !predicted_by_p (bb, PRED_NEGATIVE_RETURN)
824 && !last_basic_block_p (e->dest))
825 predict_edge_def (e, PRED_EARLY_RETURN, TAKEN);
827 /* Look for block we are guarding (ie we dominate it,
828 but it doesn't postdominate us). */
829 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
830 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
831 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
835 /* The call heuristic claims that a guarded function call
836 is improbable. This is because such calls are often used
837 to signal exceptional situations such as printing error
839 for (insn = BB_HEAD (e->dest); insn != NEXT_INSN (BB_END (e->dest));
840 insn = NEXT_INSN (insn))
842 /* Constant and pure calls are hardly used to signalize
843 something exceptional. */
844 && ! CONST_OR_PURE_CALL_P (insn))
846 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
851 bb_estimate_probability_locally (bb);
854 /* Attach the combined probability to each conditional jump. */
856 if (JUMP_P (BB_END (bb))
857 && any_condjump_p (BB_END (bb))
858 && bb->succ->succ_next != NULL)
859 combine_predictions_for_insn (BB_END (bb), bb);
861 remove_fake_exit_edges ();
862 /* Fill in the probability values in flowgraph based on the REG_BR_PROB
866 rtx last_insn = BB_END (bb);
868 if (!can_predict_insn_p (last_insn))
870 /* We can predict only conditional jumps at the moment.
871 Expect each edge to be equally probable.
872 ?? In the future we want to make abnormal edges improbable. */
876 for (e = bb->succ; e; e = e->succ_next)
879 if (e->probability != 0)
883 for (e = bb->succ; e; e = e->succ_next)
884 e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
887 estimate_bb_frequencies (loops_info);
888 free_dominance_info (CDI_POST_DOMINATORS);
889 if (profile_status == PROFILE_ABSENT)
890 profile_status = PROFILE_GUESSED;
893 /* Set edge->probability for each successor edge of BB. */
895 guess_outgoing_edge_probabilities (basic_block bb)
897 bb_estimate_probability_locally (bb);
898 combine_predictions_for_insn (BB_END (bb), bb);
902 /* Predict using opcode of the last statement in basic block. */
904 tree_predict_by_opcode (basic_block bb)
906 tree stmt = last_stmt (bb);
912 if (!stmt || TREE_CODE (stmt) != COND_EXPR)
914 for (then_edge = bb->succ; then_edge; then_edge = then_edge->succ_next)
915 if (then_edge->flags & EDGE_TRUE_VALUE)
917 cond = TREE_OPERAND (stmt, 0);
918 if (TREE_CODE_CLASS (TREE_CODE (cond)) != '<')
920 op0 = TREE_OPERAND (cond, 0);
921 type = TREE_TYPE (op0);
922 /* Try "pointer heuristic."
923 A comparison ptr == 0 is predicted as false.
924 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
925 if (POINTER_TYPE_P (type))
927 if (TREE_CODE (cond) == EQ_EXPR)
928 predict_edge_def (then_edge, PRED_TREE_POINTER, NOT_TAKEN);
929 else if (TREE_CODE (cond) == NE_EXPR)
930 predict_edge_def (then_edge, PRED_TREE_POINTER, TAKEN);
934 /* Try "opcode heuristic."
935 EQ tests are usually false and NE tests are usually true. Also,
936 most quantities are positive, so we can make the appropriate guesses
937 about signed comparisons against zero. */
938 switch (TREE_CODE (cond))
942 /* Floating point comparisons appears to behave in a very
943 unpredictable way because of special role of = tests in
945 if (FLOAT_TYPE_P (type))
947 /* Comparisons with 0 are often used for booleans and there is
948 nothing useful to predict about them. */
949 else if (integer_zerop (op0)
950 || integer_zerop (TREE_OPERAND (cond, 1)))
953 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, NOT_TAKEN);
958 /* Floating point comparisons appears to behave in a very
959 unpredictable way because of special role of = tests in
961 if (FLOAT_TYPE_P (type))
963 /* Comparisons with 0 are often used for booleans and there is
964 nothing useful to predict about them. */
965 else if (integer_zerop (op0)
966 || integer_zerop (TREE_OPERAND (cond, 1)))
969 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, TAKEN);
973 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, TAKEN);
977 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, NOT_TAKEN);
982 if (integer_zerop (TREE_OPERAND (cond, 1))
983 || integer_onep (TREE_OPERAND (cond, 1))
984 || integer_all_onesp (TREE_OPERAND (cond, 1))
985 || real_zerop (TREE_OPERAND (cond, 1))
986 || real_onep (TREE_OPERAND (cond, 1))
987 || real_minus_onep (TREE_OPERAND (cond, 1)))
988 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, NOT_TAKEN);
993 if (integer_zerop (TREE_OPERAND (cond, 1))
994 || integer_onep (TREE_OPERAND (cond, 1))
995 || integer_all_onesp (TREE_OPERAND (cond, 1))
996 || real_zerop (TREE_OPERAND (cond, 1))
997 || real_onep (TREE_OPERAND (cond, 1))
998 || real_minus_onep (TREE_OPERAND (cond, 1)))
999 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, TAKEN);
1007 /* Predict branch probabilities and estimate profile of the tree CFG. */
1009 tree_estimate_probability (void)
1012 struct loops loops_info;
1014 flow_loops_find (&loops_info, LOOP_TREE);
1015 if (dump_file && (dump_flags & TDF_DETAILS))
1016 flow_loops_dump (&loops_info, dump_file, NULL, 0);
1018 connect_infinite_loops_to_exit ();
1019 calculate_dominance_info (CDI_DOMINATORS);
1020 calculate_dominance_info (CDI_POST_DOMINATORS);
1022 predict_loops (&loops_info, false);
1028 for (e = bb->succ; e; e = e->succ_next)
1030 /* Predict early returns to be probable, as we've already taken
1031 care for error returns and other are often used for fast paths
1032 trought function. */
1033 if ((e->dest == EXIT_BLOCK_PTR
1034 || (e->dest->succ && !e->dest->succ->succ_next
1035 && e->dest->succ->dest == EXIT_BLOCK_PTR))
1036 && !predicted_by_p (bb, PRED_NULL_RETURN)
1037 && !predicted_by_p (bb, PRED_CONST_RETURN)
1038 && !predicted_by_p (bb, PRED_NEGATIVE_RETURN)
1039 && !last_basic_block_p (e->dest))
1040 predict_edge_def (e, PRED_EARLY_RETURN, TAKEN);
1042 /* Look for block we are guarding (ie we dominate it,
1043 but it doesn't postdominate us). */
1044 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
1045 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
1046 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
1048 block_stmt_iterator bi;
1050 /* The call heuristic claims that a guarded function call
1051 is improbable. This is because such calls are often used
1052 to signal exceptional situations such as printing error
1054 for (bi = bsi_start (e->dest); !bsi_end_p (bi);
1057 tree stmt = bsi_stmt (bi);
1058 if ((TREE_CODE (stmt) == CALL_EXPR
1059 || (TREE_CODE (stmt) == MODIFY_EXPR
1060 && TREE_CODE (TREE_OPERAND (stmt, 1)) == CALL_EXPR))
1061 /* Constant and pure calls are hardly used to signalize
1062 something exceptional. */
1063 && TREE_SIDE_EFFECTS (stmt))
1065 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
1071 tree_predict_by_opcode (bb);
1074 combine_predictions_for_bb (dump_file, bb);
1076 estimate_bb_frequencies (&loops_info);
1077 free_dominance_info (CDI_POST_DOMINATORS);
1078 remove_fake_exit_edges ();
1079 flow_loops_free (&loops_info);
1080 if (dump_file && (dump_flags & TDF_DETAILS))
1081 dump_tree_cfg (dump_file, dump_flags);
1082 if (profile_status == PROFILE_ABSENT)
1083 profile_status = PROFILE_GUESSED;
1086 /* __builtin_expect dropped tokens into the insn stream describing expected
1087 values of registers. Generate branch probabilities based off these
1091 expected_value_to_br_prob (void)
1093 rtx insn, cond, ev = NULL_RTX, ev_reg = NULL_RTX;
1095 for (insn = get_insns (); insn ; insn = NEXT_INSN (insn))
1097 switch (GET_CODE (insn))
1100 /* Look for expected value notes. */
1101 if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_EXPECTED_VALUE)
1103 ev = NOTE_EXPECTED_VALUE (insn);
1104 ev_reg = XEXP (ev, 0);
1110 /* Never propagate across labels. */
1115 /* Look for simple conditional branches. If we haven't got an
1116 expected value yet, no point going further. */
1117 if (!JUMP_P (insn) || ev == NULL_RTX
1118 || ! any_condjump_p (insn))
1123 /* Look for insns that clobber the EV register. */
1124 if (ev && reg_set_p (ev_reg, insn))
1129 /* Collect the branch condition, hopefully relative to EV_REG. */
1130 /* ??? At present we'll miss things like
1131 (expected_value (eq r70 0))
1133 (set r80 (lt r70 r71))
1134 (set pc (if_then_else (ne r80 0) ...))
1135 as canonicalize_condition will render this to us as
1137 Could use cselib to try and reduce this further. */
1138 cond = XEXP (SET_SRC (pc_set (insn)), 0);
1139 cond = canonicalize_condition (insn, cond, 0, NULL, ev_reg,
1141 if (! cond || XEXP (cond, 0) != ev_reg
1142 || GET_CODE (XEXP (cond, 1)) != CONST_INT)
1145 /* Substitute and simplify. Given that the expression we're
1146 building involves two constants, we should wind up with either
1148 cond = gen_rtx_fmt_ee (GET_CODE (cond), VOIDmode,
1149 XEXP (ev, 1), XEXP (cond, 1));
1150 cond = simplify_rtx (cond);
1152 /* Turn the condition into a scaled branch probability. */
1153 if (cond != const_true_rtx && cond != const0_rtx)
1155 predict_insn_def (insn, PRED_BUILTIN_EXPECT,
1156 cond == const_true_rtx ? TAKEN : NOT_TAKEN);
1160 /* Check whether this is the last basic block of function. Commonly
1161 there is one extra common cleanup block. */
1163 last_basic_block_p (basic_block bb)
1165 if (bb == EXIT_BLOCK_PTR)
1168 return (bb->next_bb == EXIT_BLOCK_PTR
1169 || (bb->next_bb->next_bb == EXIT_BLOCK_PTR
1170 && bb->succ && !bb->succ->succ_next
1171 && bb->succ->dest->next_bb == EXIT_BLOCK_PTR));
1174 /* This is used to carry information about basic blocks. It is
1175 attached to the AUX field of the standard CFG block. */
1177 typedef struct block_info_def
1179 /* Estimated frequency of execution of basic_block. */
1182 /* To keep queue of basic blocks to process. */
1185 /* True if block needs to be visited in propagate_freq. */
1186 unsigned int tovisit:1;
1188 /* Number of predecessors we need to visit first. */
1192 /* Similar information for edges. */
1193 typedef struct edge_info_def
1195 /* In case edge is an loopback edge, the probability edge will be reached
1196 in case header is. Estimated number of iterations of the loop can be
1197 then computed as 1 / (1 - back_edge_prob). */
1198 sreal back_edge_prob;
1199 /* True if the edge is an loopback edge in the natural loop. */
1200 unsigned int back_edge:1;
1203 #define BLOCK_INFO(B) ((block_info) (B)->aux)
1204 #define EDGE_INFO(E) ((edge_info) (E)->aux)
1206 /* Helper function for estimate_bb_frequencies.
1207 Propagate the frequencies for LOOP. */
1210 propagate_freq (struct loop *loop)
1212 basic_block head = loop->header;
1218 /* For each basic block we need to visit count number of his predecessors
1219 we need to visit first. */
1220 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1222 if (BLOCK_INFO (bb)->tovisit)
1226 for (e = bb->pred; e; e = e->pred_next)
1227 if (BLOCK_INFO (e->src)->tovisit && !(e->flags & EDGE_DFS_BACK))
1229 else if (BLOCK_INFO (e->src)->tovisit
1230 && dump_file && !EDGE_INFO (e)->back_edge)
1232 "Irreducible region hit, ignoring edge to %i->%i\n",
1233 e->src->index, bb->index);
1234 BLOCK_INFO (bb)->npredecessors = count;
1238 memcpy (&BLOCK_INFO (head)->frequency, &real_one, sizeof (real_one));
1240 for (bb = head; bb; bb = nextbb)
1242 sreal cyclic_probability, frequency;
1244 memcpy (&cyclic_probability, &real_zero, sizeof (real_zero));
1245 memcpy (&frequency, &real_zero, sizeof (real_zero));
1247 nextbb = BLOCK_INFO (bb)->next;
1248 BLOCK_INFO (bb)->next = NULL;
1250 /* Compute frequency of basic block. */
1253 #ifdef ENABLE_CHECKING
1254 for (e = bb->pred; e; e = e->pred_next)
1255 if (BLOCK_INFO (e->src)->tovisit && !(e->flags & EDGE_DFS_BACK))
1259 for (e = bb->pred; e; e = e->pred_next)
1260 if (EDGE_INFO (e)->back_edge)
1262 sreal_add (&cyclic_probability, &cyclic_probability,
1263 &EDGE_INFO (e)->back_edge_prob);
1265 else if (!(e->flags & EDGE_DFS_BACK))
1269 /* frequency += (e->probability
1270 * BLOCK_INFO (e->src)->frequency /
1271 REG_BR_PROB_BASE); */
1273 sreal_init (&tmp, e->probability, 0);
1274 sreal_mul (&tmp, &tmp, &BLOCK_INFO (e->src)->frequency);
1275 sreal_mul (&tmp, &tmp, &real_inv_br_prob_base);
1276 sreal_add (&frequency, &frequency, &tmp);
1279 if (sreal_compare (&cyclic_probability, &real_zero) == 0)
1281 memcpy (&BLOCK_INFO (bb)->frequency, &frequency,
1282 sizeof (frequency));
1286 if (sreal_compare (&cyclic_probability, &real_almost_one) > 0)
1288 memcpy (&cyclic_probability, &real_almost_one,
1289 sizeof (real_almost_one));
1292 /* BLOCK_INFO (bb)->frequency = frequency
1293 / (1 - cyclic_probability) */
1295 sreal_sub (&cyclic_probability, &real_one, &cyclic_probability);
1296 sreal_div (&BLOCK_INFO (bb)->frequency,
1297 &frequency, &cyclic_probability);
1301 BLOCK_INFO (bb)->tovisit = 0;
1303 /* Compute back edge frequencies. */
1304 for (e = bb->succ; e; e = e->succ_next)
1305 if (e->dest == head)
1309 /* EDGE_INFO (e)->back_edge_prob
1310 = ((e->probability * BLOCK_INFO (bb)->frequency)
1311 / REG_BR_PROB_BASE); */
1313 sreal_init (&tmp, e->probability, 0);
1314 sreal_mul (&tmp, &tmp, &BLOCK_INFO (bb)->frequency);
1315 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
1316 &tmp, &real_inv_br_prob_base);
1319 /* Propagate to successor blocks. */
1320 for (e = bb->succ; e; e = e->succ_next)
1321 if (!(e->flags & EDGE_DFS_BACK)
1322 && BLOCK_INFO (e->dest)->npredecessors)
1324 BLOCK_INFO (e->dest)->npredecessors--;
1325 if (!BLOCK_INFO (e->dest)->npredecessors)
1330 BLOCK_INFO (last)->next = e->dest;
1338 /* Estimate probabilities of loopback edges in loops at same nest level. */
1341 estimate_loops_at_level (struct loop *first_loop)
1345 for (loop = first_loop; loop; loop = loop->next)
1351 estimate_loops_at_level (loop->inner);
1353 if (loop->latch->succ) /* Do not do this for dummy function loop. */
1355 /* Find current loop back edge and mark it. */
1356 e = loop_latch_edge (loop);
1357 EDGE_INFO (e)->back_edge = 1;
1360 bbs = get_loop_body (loop);
1361 for (i = 0; i < loop->num_nodes; i++)
1362 BLOCK_INFO (bbs[i])->tovisit = 1;
1364 propagate_freq (loop);
1368 /* Convert counts measured by profile driven feedback to frequencies.
1369 Return nonzero iff there was any nonzero execution count. */
1372 counts_to_freqs (void)
1374 gcov_type count_max, true_count_max = 0;
1378 true_count_max = MAX (bb->count, true_count_max);
1380 count_max = MAX (true_count_max, 1);
1381 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1382 bb->frequency = (bb->count * BB_FREQ_MAX + count_max / 2) / count_max;
1383 return true_count_max;
1386 /* Return true if function is likely to be expensive, so there is no point to
1387 optimize performance of prologue, epilogue or do inlining at the expense
1388 of code size growth. THRESHOLD is the limit of number of instructions
1389 function can execute at average to be still considered not expensive. */
1392 expensive_function_p (int threshold)
1394 unsigned int sum = 0;
1398 /* We can not compute accurately for large thresholds due to scaled
1400 if (threshold > BB_FREQ_MAX)
1403 /* Frequencies are out of range. This either means that function contains
1404 internal loop executing more than BB_FREQ_MAX times or profile feedback
1405 is available and function has not been executed at all. */
1406 if (ENTRY_BLOCK_PTR->frequency == 0)
1409 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
1410 limit = ENTRY_BLOCK_PTR->frequency * threshold;
1415 for (insn = BB_HEAD (bb); insn != NEXT_INSN (BB_END (bb));
1416 insn = NEXT_INSN (insn))
1417 if (active_insn_p (insn))
1419 sum += bb->frequency;
1428 /* Estimate basic blocks frequency by given branch probabilities. */
1431 estimate_bb_frequencies (struct loops *loops)
1436 if (!flag_branch_probabilities || !counts_to_freqs ())
1438 static int real_values_initialized = 0;
1440 if (!real_values_initialized)
1442 real_values_initialized = 1;
1443 sreal_init (&real_zero, 0, 0);
1444 sreal_init (&real_one, 1, 0);
1445 sreal_init (&real_br_prob_base, REG_BR_PROB_BASE, 0);
1446 sreal_init (&real_bb_freq_max, BB_FREQ_MAX, 0);
1447 sreal_init (&real_one_half, 1, -1);
1448 sreal_div (&real_inv_br_prob_base, &real_one, &real_br_prob_base);
1449 sreal_sub (&real_almost_one, &real_one, &real_inv_br_prob_base);
1452 mark_dfs_back_edges ();
1454 ENTRY_BLOCK_PTR->succ->probability = REG_BR_PROB_BASE;
1456 /* Set up block info for each basic block. */
1457 alloc_aux_for_blocks (sizeof (struct block_info_def));
1458 alloc_aux_for_edges (sizeof (struct edge_info_def));
1459 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1463 BLOCK_INFO (bb)->tovisit = 0;
1464 for (e = bb->succ; e; e = e->succ_next)
1466 sreal_init (&EDGE_INFO (e)->back_edge_prob, e->probability, 0);
1467 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
1468 &EDGE_INFO (e)->back_edge_prob,
1469 &real_inv_br_prob_base);
1473 /* First compute probabilities locally for each loop from innermost
1474 to outermost to examine probabilities for back edges. */
1475 estimate_loops_at_level (loops->tree_root);
1477 memcpy (&freq_max, &real_zero, sizeof (real_zero));
1479 if (sreal_compare (&freq_max, &BLOCK_INFO (bb)->frequency) < 0)
1480 memcpy (&freq_max, &BLOCK_INFO (bb)->frequency, sizeof (freq_max));
1482 sreal_div (&freq_max, &real_bb_freq_max, &freq_max);
1483 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1487 sreal_mul (&tmp, &BLOCK_INFO (bb)->frequency, &freq_max);
1488 sreal_add (&tmp, &tmp, &real_one_half);
1489 bb->frequency = sreal_to_int (&tmp);
1492 free_aux_for_blocks ();
1493 free_aux_for_edges ();
1495 compute_function_frequency ();
1496 if (flag_reorder_functions)
1497 choose_function_section ();
1500 /* Decide whether function is hot, cold or unlikely executed. */
1502 compute_function_frequency (void)
1506 if (!profile_info || !flag_branch_probabilities)
1508 cfun->function_frequency = FUNCTION_FREQUENCY_UNLIKELY_EXECUTED;
1511 if (maybe_hot_bb_p (bb))
1513 cfun->function_frequency = FUNCTION_FREQUENCY_HOT;
1516 if (!probably_never_executed_bb_p (bb))
1517 cfun->function_frequency = FUNCTION_FREQUENCY_NORMAL;
1521 /* Choose appropriate section for the function. */
1523 choose_function_section (void)
1525 if (DECL_SECTION_NAME (current_function_decl)
1526 || !targetm.have_named_sections
1527 /* Theoretically we can split the gnu.linkonce text section too,
1528 but this requires more work as the frequency needs to match
1529 for all generated objects so we need to merge the frequency
1530 of all instances. For now just never set frequency for these. */
1531 || DECL_ONE_ONLY (current_function_decl))
1534 /* If we are doing the partitioning optimization, let the optimization
1535 choose the correct section into which to put things. */
1537 if (flag_reorder_blocks_and_partition)
1540 if (cfun->function_frequency == FUNCTION_FREQUENCY_HOT)
1541 DECL_SECTION_NAME (current_function_decl) =
1542 build_string (strlen (HOT_TEXT_SECTION_NAME), HOT_TEXT_SECTION_NAME);
1543 if (cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
1544 DECL_SECTION_NAME (current_function_decl) =
1545 build_string (strlen (UNLIKELY_EXECUTED_TEXT_SECTION_NAME),
1546 UNLIKELY_EXECUTED_TEXT_SECTION_NAME);
1550 struct tree_opt_pass pass_profile =
1552 "profile", /* name */
1554 tree_estimate_probability, /* execute */
1557 0, /* static_pass_number */
1558 TV_BRANCH_PROB, /* tv_id */
1559 PROP_cfg, /* properties_required */
1560 0, /* properties_provided */
1561 0, /* properties_destroyed */
1562 0, /* todo_flags_start */
1563 TODO_ggc_collect | TODO_verify_ssa, /* todo_flags_finish */