bb-reorder.c (make_reorder_chain, [...]): Use FOR_EACH_BB macros to iterate over...
[gcc.git] / gcc / predict.c
1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000, 2001, 2002 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
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
9 version.
10
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
14 for more details.
15
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
19 02111-1307, USA. */
20
21 /* References:
22
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. */
29
30
31 #include "config.h"
32 #include "system.h"
33 #include "tree.h"
34 #include "rtl.h"
35 #include "tm_p.h"
36 #include "hard-reg-set.h"
37 #include "basic-block.h"
38 #include "insn-config.h"
39 #include "regs.h"
40 #include "flags.h"
41 #include "output.h"
42 #include "function.h"
43 #include "except.h"
44 #include "toplev.h"
45 #include "recog.h"
46 #include "expr.h"
47 #include "predict.h"
48 #include "profile.h"
49 #include "real.h"
50 #include "params.h"
51 #include "target.h"
52
53 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE, 0.5,
54 REAL_BB_FREQ_MAX. */
55 static REAL_VALUE_TYPE real_zero, real_one, real_almost_one, real_br_prob_base,
56 real_one_half, real_bb_freq_max;
57
58 /* Random guesstimation given names. */
59 #define PROB_NEVER (0)
60 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 10 - 1)
61 #define PROB_UNLIKELY (REG_BR_PROB_BASE * 4 / 10 - 1)
62 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
63 #define PROB_LIKELY (REG_BR_PROB_BASE - PROB_UNLIKELY)
64 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
65 #define PROB_ALWAYS (REG_BR_PROB_BASE)
66
67 static bool predicted_by_p PARAMS ((basic_block,
68 enum br_predictor));
69 static void combine_predictions_for_insn PARAMS ((rtx, basic_block));
70 static void dump_prediction PARAMS ((enum br_predictor, int,
71 basic_block, int));
72 static void estimate_loops_at_level PARAMS ((struct loop *loop));
73 static void propagate_freq PARAMS ((basic_block));
74 static void estimate_bb_frequencies PARAMS ((struct loops *));
75 static void counts_to_freqs PARAMS ((void));
76 static void process_note_predictions PARAMS ((basic_block, int *, int *,
77 sbitmap *));
78 static void process_note_prediction PARAMS ((basic_block, int *, int *,
79 sbitmap *, int, int));
80 static bool last_basic_block_p PARAMS ((basic_block));
81 static void compute_function_frequency PARAMS ((void));
82 static void choose_function_section PARAMS ((void));
83
84 /* Information we hold about each branch predictor.
85 Filled using information from predict.def. */
86
87 struct predictor_info
88 {
89 const char *const name; /* Name used in the debugging dumps. */
90 const int hitrate; /* Expected hitrate used by
91 predict_insn_def call. */
92 const int flags;
93 };
94
95 /* Use given predictor without Dempster-Shaffer theory if it matches
96 using first_match heuristics. */
97 #define PRED_FLAG_FIRST_MATCH 1
98
99 /* Recompute hitrate in percent to our representation. */
100
101 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
102
103 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
104 static const struct predictor_info predictor_info[]= {
105 #include "predict.def"
106
107 /* Upper bound on predictors. */
108 {NULL, 0, 0}
109 };
110 #undef DEF_PREDICTOR
111
112 /* Return true in case BB can be CPU intensive and should be optimized
113 for maximal perofmrance. */
114
115 bool
116 maybe_hot_bb_p (bb)
117 basic_block bb;
118 {
119 if (profile_info.count_profiles_merged
120 && flag_branch_probabilities
121 && (bb->count
122 < profile_info.max_counter_in_program
123 / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
124 return false;
125 if (bb->frequency < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
126 return false;
127 return true;
128 }
129
130 /* Return true in case BB is cold and should be optimized for size. */
131
132 bool
133 probably_cold_bb_p (bb)
134 basic_block bb;
135 {
136 if (profile_info.count_profiles_merged
137 && flag_branch_probabilities
138 && (bb->count
139 < profile_info.max_counter_in_program
140 / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
141 return true;
142 if (bb->frequency < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
143 return true;
144 return false;
145 }
146
147 /* Return true in case BB is probably never executed. */
148 bool
149 probably_never_executed_bb_p (bb)
150 basic_block bb;
151 {
152 if (profile_info.count_profiles_merged
153 && flag_branch_probabilities)
154 return ((bb->count + profile_info.count_profiles_merged / 2)
155 / profile_info.count_profiles_merged) == 0;
156 return false;
157 }
158
159 /* Return true if the one of outgoing edges is already predicted by
160 PREDICTOR. */
161
162 static bool
163 predicted_by_p (bb, predictor)
164 basic_block bb;
165 enum br_predictor predictor;
166 {
167 rtx note;
168 if (!INSN_P (bb->end))
169 return false;
170 for (note = REG_NOTES (bb->end); note; note = XEXP (note, 1))
171 if (REG_NOTE_KIND (note) == REG_BR_PRED
172 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
173 return true;
174 return false;
175 }
176
177 void
178 predict_insn (insn, predictor, probability)
179 rtx insn;
180 int probability;
181 enum br_predictor predictor;
182 {
183 if (!any_condjump_p (insn))
184 abort ();
185
186 REG_NOTES (insn)
187 = gen_rtx_EXPR_LIST (REG_BR_PRED,
188 gen_rtx_CONCAT (VOIDmode,
189 GEN_INT ((int) predictor),
190 GEN_INT ((int) probability)),
191 REG_NOTES (insn));
192 }
193
194 /* Predict insn by given predictor. */
195
196 void
197 predict_insn_def (insn, predictor, taken)
198 rtx insn;
199 enum br_predictor predictor;
200 enum prediction taken;
201 {
202 int probability = predictor_info[(int) predictor].hitrate;
203
204 if (taken != TAKEN)
205 probability = REG_BR_PROB_BASE - probability;
206
207 predict_insn (insn, predictor, probability);
208 }
209
210 /* Predict edge E with given probability if possible. */
211
212 void
213 predict_edge (e, predictor, probability)
214 edge e;
215 int probability;
216 enum br_predictor predictor;
217 {
218 rtx last_insn;
219 last_insn = e->src->end;
220
221 /* We can store the branch prediction information only about
222 conditional jumps. */
223 if (!any_condjump_p (last_insn))
224 return;
225
226 /* We always store probability of branching. */
227 if (e->flags & EDGE_FALLTHRU)
228 probability = REG_BR_PROB_BASE - probability;
229
230 predict_insn (last_insn, predictor, probability);
231 }
232
233 /* Predict edge E by given predictor if possible. */
234
235 void
236 predict_edge_def (e, predictor, taken)
237 edge e;
238 enum br_predictor predictor;
239 enum prediction taken;
240 {
241 int probability = predictor_info[(int) predictor].hitrate;
242
243 if (taken != TAKEN)
244 probability = REG_BR_PROB_BASE - probability;
245
246 predict_edge (e, predictor, probability);
247 }
248
249 /* Invert all branch predictions or probability notes in the INSN. This needs
250 to be done each time we invert the condition used by the jump. */
251
252 void
253 invert_br_probabilities (insn)
254 rtx insn;
255 {
256 rtx note;
257
258 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
259 if (REG_NOTE_KIND (note) == REG_BR_PROB)
260 XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
261 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
262 XEXP (XEXP (note, 0), 1)
263 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
264 }
265
266 /* Dump information about the branch prediction to the output file. */
267
268 static void
269 dump_prediction (predictor, probability, bb, used)
270 enum br_predictor predictor;
271 int probability;
272 basic_block bb;
273 int used;
274 {
275 edge e = bb->succ;
276
277 if (!rtl_dump_file)
278 return;
279
280 while (e && (e->flags & EDGE_FALLTHRU))
281 e = e->succ_next;
282
283 fprintf (rtl_dump_file, " %s heuristics%s: %.1f%%",
284 predictor_info[predictor].name,
285 used ? "" : " (ignored)", probability * 100.0 / REG_BR_PROB_BASE);
286
287 if (bb->count)
288 {
289 fprintf (rtl_dump_file, " exec ");
290 fprintf (rtl_dump_file, HOST_WIDEST_INT_PRINT_DEC, bb->count);
291 if (e)
292 {
293 fprintf (rtl_dump_file, " hit ");
294 fprintf (rtl_dump_file, HOST_WIDEST_INT_PRINT_DEC, e->count);
295 fprintf (rtl_dump_file, " (%.1f%%)", e->count * 100.0 / bb->count);
296 }
297 }
298
299 fprintf (rtl_dump_file, "\n");
300 }
301
302 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
303 note if not already present. Remove now useless REG_BR_PRED notes. */
304
305 static void
306 combine_predictions_for_insn (insn, bb)
307 rtx insn;
308 basic_block bb;
309 {
310 rtx prob_note = find_reg_note (insn, REG_BR_PROB, 0);
311 rtx *pnote = &REG_NOTES (insn);
312 rtx note;
313 int best_probability = PROB_EVEN;
314 int best_predictor = END_PREDICTORS;
315 int combined_probability = REG_BR_PROB_BASE / 2;
316 int d;
317 bool first_match = false;
318 bool found = false;
319
320 if (rtl_dump_file)
321 fprintf (rtl_dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
322 bb->index);
323
324 /* We implement "first match" heuristics and use probability guessed
325 by predictor with smallest index. In the future we will use better
326 probability combination techniques. */
327 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
328 if (REG_NOTE_KIND (note) == REG_BR_PRED)
329 {
330 int predictor = INTVAL (XEXP (XEXP (note, 0), 0));
331 int probability = INTVAL (XEXP (XEXP (note, 0), 1));
332
333 found = true;
334 if (best_predictor > predictor)
335 best_probability = probability, best_predictor = predictor;
336
337 d = (combined_probability * probability
338 + (REG_BR_PROB_BASE - combined_probability)
339 * (REG_BR_PROB_BASE - probability));
340
341 /* Use FP math to avoid overflows of 32bit integers. */
342 if (d == 0)
343 /* If one probability is 0% and one 100%, avoid division by zero. */
344 combined_probability = REG_BR_PROB_BASE / 2;
345 else
346 combined_probability = (((double) combined_probability) * probability
347 * REG_BR_PROB_BASE / d + 0.5);
348 }
349
350 /* Decide which heuristic to use. In case we didn't match anything,
351 use no_prediction heuristic, in case we did match, use either
352 first match or Dempster-Shaffer theory depending on the flags. */
353
354 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
355 first_match = true;
356
357 if (!found)
358 dump_prediction (PRED_NO_PREDICTION, combined_probability, bb, true);
359 else
360 {
361 dump_prediction (PRED_DS_THEORY, combined_probability, bb, !first_match);
362 dump_prediction (PRED_FIRST_MATCH, best_probability, bb, first_match);
363 }
364
365 if (first_match)
366 combined_probability = best_probability;
367 dump_prediction (PRED_COMBINED, combined_probability, bb, true);
368
369 while (*pnote)
370 {
371 if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
372 {
373 int predictor = INTVAL (XEXP (XEXP (*pnote, 0), 0));
374 int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
375
376 dump_prediction (predictor, probability, bb,
377 !first_match || best_predictor == predictor);
378 *pnote = XEXP (*pnote, 1);
379 }
380 else
381 pnote = &XEXP (*pnote, 1);
382 }
383
384 if (!prob_note)
385 {
386 REG_NOTES (insn)
387 = gen_rtx_EXPR_LIST (REG_BR_PROB,
388 GEN_INT (combined_probability), REG_NOTES (insn));
389
390 /* Save the prediction into CFG in case we are seeing non-degenerated
391 conditional jump. */
392 if (bb->succ->succ_next)
393 {
394 BRANCH_EDGE (bb)->probability = combined_probability;
395 FALLTHRU_EDGE (bb)->probability
396 = REG_BR_PROB_BASE - combined_probability;
397 }
398 }
399 }
400
401 /* Statically estimate the probability that a branch will be taken.
402 ??? In the next revision there will be a number of other predictors added
403 from the above references. Further, each heuristic will be factored out
404 into its own function for clarity (and to facilitate the combination of
405 predictions). */
406
407 void
408 estimate_probability (loops_info)
409 struct loops *loops_info;
410 {
411 sbitmap *dominators, *post_dominators;
412 basic_block bb;
413 int i;
414
415 dominators = sbitmap_vector_alloc (n_basic_blocks, n_basic_blocks);
416 post_dominators = sbitmap_vector_alloc (n_basic_blocks, n_basic_blocks);
417 calculate_dominance_info (NULL, dominators, CDI_DOMINATORS);
418 calculate_dominance_info (NULL, post_dominators, CDI_POST_DOMINATORS);
419
420 /* Try to predict out blocks in a loop that are not part of a
421 natural loop. */
422 for (i = 0; i < loops_info->num; i++)
423 {
424 int exits;
425 struct loop *loop = &loops_info->array[i];
426
427 flow_loop_scan (loops_info, loop, LOOP_EXIT_EDGES);
428 exits = loop->num_exits;
429
430 FOR_BB_BETWEEN (bb, loop->first, loop->last->next_bb, next_bb)
431 if (TEST_BIT (loop->nodes, bb->index))
432 {
433 int header_found = 0;
434 edge e;
435
436 /* Bypass loop heuristics on continue statement. These
437 statements construct loops via "non-loop" constructs
438 in the source language and are better to be handled
439 separately. */
440 if (predicted_by_p (bb, PRED_CONTINUE))
441 continue;
442
443 /* Loop branch heuristics - predict an edge back to a
444 loop's head as taken. */
445 for (e = bb->succ; e; e = e->succ_next)
446 if (e->dest == loop->header
447 && e->src == loop->latch)
448 {
449 header_found = 1;
450 predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
451 }
452
453 /* Loop exit heuristics - predict an edge exiting the loop if the
454 conditinal has no loop header successors as not taken. */
455 if (!header_found)
456 for (e = bb->succ; e; e = e->succ_next)
457 if (e->dest->index < 0
458 || !TEST_BIT (loop->nodes, e->dest->index))
459 predict_edge
460 (e, PRED_LOOP_EXIT,
461 (REG_BR_PROB_BASE
462 - predictor_info [(int) PRED_LOOP_EXIT].hitrate)
463 / exits);
464 }
465 }
466
467 /* Attempt to predict conditional jumps using a number of heuristics. */
468 FOR_EACH_BB (bb)
469 {
470 rtx last_insn = bb->end;
471 rtx cond, earliest;
472 edge e;
473
474 if (GET_CODE (last_insn) != JUMP_INSN || ! any_condjump_p (last_insn))
475 continue;
476
477 for (e = bb->succ; e; e = e->succ_next)
478 {
479 /* Predict early returns to be probable, as we've already taken
480 care for error returns and other are often used for fast paths
481 trought function. */
482 if ((e->dest == EXIT_BLOCK_PTR
483 || (e->dest->succ && !e->dest->succ->succ_next
484 && e->dest->succ->dest == EXIT_BLOCK_PTR))
485 && !predicted_by_p (bb, PRED_NULL_RETURN)
486 && !predicted_by_p (bb, PRED_CONST_RETURN)
487 && !predicted_by_p (bb, PRED_NEGATIVE_RETURN)
488 && !last_basic_block_p (e->dest))
489 predict_edge_def (e, PRED_EARLY_RETURN, TAKEN);
490
491 /* Look for block we are guarding (ie we dominate it,
492 but it doesn't postdominate us). */
493 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
494 && TEST_BIT (dominators[e->dest->index], e->src->index)
495 && !TEST_BIT (post_dominators[e->src->index], e->dest->index))
496 {
497 rtx insn;
498
499 /* The call heuristic claims that a guarded function call
500 is improbable. This is because such calls are often used
501 to signal exceptional situations such as printing error
502 messages. */
503 for (insn = e->dest->head; insn != NEXT_INSN (e->dest->end);
504 insn = NEXT_INSN (insn))
505 if (GET_CODE (insn) == CALL_INSN
506 /* Constant and pure calls are hardly used to signalize
507 something exceptional. */
508 && ! CONST_OR_PURE_CALL_P (insn))
509 {
510 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
511 break;
512 }
513 }
514 }
515
516 cond = get_condition (last_insn, &earliest);
517 if (! cond)
518 continue;
519
520 /* Try "pointer heuristic."
521 A comparison ptr == 0 is predicted as false.
522 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
523 if (GET_RTX_CLASS (GET_CODE (cond)) == '<'
524 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
525 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
526 {
527 if (GET_CODE (cond) == EQ)
528 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
529 else if (GET_CODE (cond) == NE)
530 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
531 }
532 else
533
534 /* Try "opcode heuristic."
535 EQ tests are usually false and NE tests are usually true. Also,
536 most quantities are positive, so we can make the appropriate guesses
537 about signed comparisons against zero. */
538 switch (GET_CODE (cond))
539 {
540 case CONST_INT:
541 /* Unconditional branch. */
542 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
543 cond == const0_rtx ? NOT_TAKEN : TAKEN);
544 break;
545
546 case EQ:
547 case UNEQ:
548 /* Floating point comparisons appears to behave in a very
549 inpredictable way because of special role of = tests in
550 FP code. */
551 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
552 ;
553 /* Comparisons with 0 are often used for booleans and there is
554 nothing usefull to predict about them. */
555 else if (XEXP (cond, 1) == const0_rtx
556 || XEXP (cond, 0) == const0_rtx)
557 ;
558 else
559 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
560 break;
561
562 case NE:
563 case LTGT:
564 /* Floating point comparisons appears to behave in a very
565 inpredictable way because of special role of = tests in
566 FP code. */
567 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
568 ;
569 /* Comparisons with 0 are often used for booleans and there is
570 nothing usefull to predict about them. */
571 else if (XEXP (cond, 1) == const0_rtx
572 || XEXP (cond, 0) == const0_rtx)
573 ;
574 else
575 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
576 break;
577
578 case ORDERED:
579 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
580 break;
581
582 case UNORDERED:
583 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
584 break;
585
586 case LE:
587 case LT:
588 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
589 || XEXP (cond, 1) == constm1_rtx)
590 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
591 break;
592
593 case GE:
594 case GT:
595 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
596 || XEXP (cond, 1) == constm1_rtx)
597 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
598 break;
599
600 default:
601 break;
602 }
603 }
604
605 /* Attach the combined probability to each conditional jump. */
606 FOR_EACH_BB (bb)
607 if (GET_CODE (bb->end) == JUMP_INSN
608 && any_condjump_p (bb->end)
609 && bb->succ->succ_next != NULL)
610 combine_predictions_for_insn (bb->end, bb);
611
612 sbitmap_vector_free (post_dominators);
613 sbitmap_vector_free (dominators);
614
615 estimate_bb_frequencies (loops_info);
616 }
617 \f
618 /* __builtin_expect dropped tokens into the insn stream describing expected
619 values of registers. Generate branch probabilities based off these
620 values. */
621
622 void
623 expected_value_to_br_prob ()
624 {
625 rtx insn, cond, ev = NULL_RTX, ev_reg = NULL_RTX;
626
627 for (insn = get_insns (); insn ; insn = NEXT_INSN (insn))
628 {
629 switch (GET_CODE (insn))
630 {
631 case NOTE:
632 /* Look for expected value notes. */
633 if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_EXPECTED_VALUE)
634 {
635 ev = NOTE_EXPECTED_VALUE (insn);
636 ev_reg = XEXP (ev, 0);
637 delete_insn (insn);
638 }
639 continue;
640
641 case CODE_LABEL:
642 /* Never propagate across labels. */
643 ev = NULL_RTX;
644 continue;
645
646 case JUMP_INSN:
647 /* Look for simple conditional branches. If we haven't got an
648 expected value yet, no point going further. */
649 if (GET_CODE (insn) != JUMP_INSN || ev == NULL_RTX
650 || ! any_condjump_p (insn))
651 continue;
652 break;
653
654 default:
655 /* Look for insns that clobber the EV register. */
656 if (ev && reg_set_p (ev_reg, insn))
657 ev = NULL_RTX;
658 continue;
659 }
660
661 /* Collect the branch condition, hopefully relative to EV_REG. */
662 /* ??? At present we'll miss things like
663 (expected_value (eq r70 0))
664 (set r71 -1)
665 (set r80 (lt r70 r71))
666 (set pc (if_then_else (ne r80 0) ...))
667 as canonicalize_condition will render this to us as
668 (lt r70, r71)
669 Could use cselib to try and reduce this further. */
670 cond = XEXP (SET_SRC (pc_set (insn)), 0);
671 cond = canonicalize_condition (insn, cond, 0, NULL, ev_reg);
672 if (! cond || XEXP (cond, 0) != ev_reg
673 || GET_CODE (XEXP (cond, 1)) != CONST_INT)
674 continue;
675
676 /* Substitute and simplify. Given that the expression we're
677 building involves two constants, we should wind up with either
678 true or false. */
679 cond = gen_rtx_fmt_ee (GET_CODE (cond), VOIDmode,
680 XEXP (ev, 1), XEXP (cond, 1));
681 cond = simplify_rtx (cond);
682
683 /* Turn the condition into a scaled branch probability. */
684 if (cond != const_true_rtx && cond != const0_rtx)
685 abort ();
686 predict_insn_def (insn, PRED_BUILTIN_EXPECT,
687 cond == const_true_rtx ? TAKEN : NOT_TAKEN);
688 }
689 }
690 \f
691 /* Check whether this is the last basic block of function. Commonly tehre
692 is one extra common cleanup block. */
693 static bool
694 last_basic_block_p (bb)
695 basic_block bb;
696 {
697 if (bb == EXIT_BLOCK_PTR)
698 return false;
699
700 return (bb->next_bb == EXIT_BLOCK_PTR
701 || (bb->next_bb->next_bb == EXIT_BLOCK_PTR
702 && bb->succ && !bb->succ->succ_next
703 && bb->succ->dest->next_bb == EXIT_BLOCK_PTR));
704 }
705
706 /* Sets branch probabilities according to PREDiction and FLAGS. HEADS[bb->index]
707 should be index of basic block in that we need to alter branch predictions
708 (i.e. the first of our dominators such that we do not post-dominate it)
709 (but we fill this information on demand, so -1 may be there in case this
710 was not needed yet). */
711
712 static void
713 process_note_prediction (bb, heads, dominators, post_dominators, pred, flags)
714 basic_block bb;
715 int *heads;
716 int *dominators;
717 sbitmap *post_dominators;
718 int pred;
719 int flags;
720 {
721 edge e;
722 int y;
723 bool taken;
724
725 taken = flags & IS_TAKEN;
726
727 if (heads[bb->index] < 0)
728 {
729 /* This is first time we need this field in heads array; so
730 find first dominator that we do not post-dominate (we are
731 using already known members of heads array). */
732 int ai = bb->index;
733 int next_ai = dominators[bb->index];
734 int head;
735
736 while (heads[next_ai] < 0)
737 {
738 if (!TEST_BIT (post_dominators[next_ai], bb->index))
739 break;
740 heads[next_ai] = ai;
741 ai = next_ai;
742 next_ai = dominators[next_ai];
743 }
744 if (!TEST_BIT (post_dominators[next_ai], bb->index))
745 head = next_ai;
746 else
747 head = heads[next_ai];
748 while (next_ai != bb->index)
749 {
750 next_ai = ai;
751 ai = heads[ai];
752 heads[next_ai] = head;
753 }
754 }
755 y = heads[bb->index];
756
757 /* Now find the edge that leads to our branch and aply the prediction. */
758
759 if (y == n_basic_blocks)
760 return;
761 for (e = BASIC_BLOCK (y)->succ; e; e = e->succ_next)
762 if (e->dest->index >= 0
763 && TEST_BIT (post_dominators[e->dest->index], bb->index))
764 predict_edge_def (e, pred, taken);
765 }
766
767 /* Gathers NOTE_INSN_PREDICTIONs in given basic block and turns them
768 into branch probabilities. For description of heads array, see
769 process_note_prediction. */
770
771 static void
772 process_note_predictions (bb, heads, dominators, post_dominators)
773 basic_block bb;
774 int *heads;
775 int *dominators;
776 sbitmap *post_dominators;
777 {
778 rtx insn;
779 edge e;
780
781 /* Additionaly, we check here for blocks with no successors. */
782 int contained_noreturn_call = 0;
783 int was_bb_head = 0;
784 int noreturn_block = 1;
785
786 for (insn = bb->end; insn;
787 was_bb_head |= (insn == bb->head), insn = PREV_INSN (insn))
788 {
789 if (GET_CODE (insn) != NOTE)
790 {
791 if (was_bb_head)
792 break;
793 else
794 {
795 /* Noreturn calls cause program to exit, therefore they are
796 always predicted as not taken. */
797 if (GET_CODE (insn) == CALL_INSN
798 && find_reg_note (insn, REG_NORETURN, NULL))
799 contained_noreturn_call = 1;
800 continue;
801 }
802 }
803 if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_PREDICTION)
804 {
805 int alg = (int) NOTE_PREDICTION_ALG (insn);
806 /* Process single prediction note. */
807 process_note_prediction (bb,
808 heads,
809 dominators,
810 post_dominators,
811 alg, (int) NOTE_PREDICTION_FLAGS (insn));
812 delete_insn (insn);
813 }
814 }
815 for (e = bb->succ; e; e = e->succ_next)
816 if (!(e->flags & EDGE_FAKE))
817 noreturn_block = 0;
818 if (contained_noreturn_call)
819 {
820 /* This block ended from other reasons than because of return.
821 If it is because of noreturn call, this should certainly not
822 be taken. Otherwise it is probably some error recovery. */
823 process_note_prediction (bb,
824 heads,
825 dominators,
826 post_dominators, PRED_NORETURN, NOT_TAKEN);
827 }
828 }
829
830 /* Gathers NOTE_INSN_PREDICTIONs and turns them into
831 branch probabilities. */
832
833 void
834 note_prediction_to_br_prob ()
835 {
836 basic_block bb;
837 sbitmap *post_dominators;
838 int *dominators, *heads;
839
840 /* To enable handling of noreturn blocks. */
841 add_noreturn_fake_exit_edges ();
842 connect_infinite_loops_to_exit ();
843
844 dominators = xmalloc (sizeof (int) * n_basic_blocks);
845 memset (dominators, -1, sizeof (int) * n_basic_blocks);
846 post_dominators = sbitmap_vector_alloc (n_basic_blocks, n_basic_blocks);
847 calculate_dominance_info (NULL, post_dominators, CDI_POST_DOMINATORS);
848 calculate_dominance_info (dominators, NULL, CDI_DOMINATORS);
849
850 heads = xmalloc (sizeof (int) * n_basic_blocks);
851 memset (heads, -1, sizeof (int) * n_basic_blocks);
852 heads[ENTRY_BLOCK_PTR->next_bb->index] = n_basic_blocks;
853
854 /* Process all prediction notes. */
855
856 FOR_EACH_BB (bb)
857 process_note_predictions (bb, heads, dominators, post_dominators);
858
859 sbitmap_vector_free (post_dominators);
860 free (dominators);
861 free (heads);
862
863 remove_fake_edges ();
864 }
865 \f
866 /* This is used to carry information about basic blocks. It is
867 attached to the AUX field of the standard CFG block. */
868
869 typedef struct block_info_def
870 {
871 /* Estimated frequency of execution of basic_block. */
872 REAL_VALUE_TYPE frequency;
873
874 /* To keep queue of basic blocks to process. */
875 basic_block next;
876
877 /* True if block needs to be visited in prop_freqency. */
878 int tovisit:1;
879
880 /* Number of predecessors we need to visit first. */
881 int npredecessors;
882 } *block_info;
883
884 /* Similar information for edges. */
885 typedef struct edge_info_def
886 {
887 /* In case edge is an loopback edge, the probability edge will be reached
888 in case header is. Estimated number of iterations of the loop can be
889 then computed as 1 / (1 - back_edge_prob). */
890 REAL_VALUE_TYPE back_edge_prob;
891 /* True if the edge is an loopback edge in the natural loop. */
892 int back_edge:1;
893 } *edge_info;
894
895 #define BLOCK_INFO(B) ((block_info) (B)->aux)
896 #define EDGE_INFO(E) ((edge_info) (E)->aux)
897
898 /* Helper function for estimate_bb_frequencies.
899 Propagate the frequencies for loops headed by HEAD. */
900
901 static void
902 propagate_freq (head)
903 basic_block head;
904 {
905 basic_block bb;
906 basic_block last;
907 edge e;
908 basic_block nextbb;
909
910 /* For each basic block we need to visit count number of his predecessors
911 we need to visit first. */
912 FOR_EACH_BB (bb)
913 {
914 if (BLOCK_INFO (bb)->tovisit)
915 {
916 int count = 0;
917
918 for (e = bb->pred; e; e = e->pred_next)
919 if (BLOCK_INFO (e->src)->tovisit && !(e->flags & EDGE_DFS_BACK))
920 count++;
921 else if (BLOCK_INFO (e->src)->tovisit
922 && rtl_dump_file && !EDGE_INFO (e)->back_edge)
923 fprintf (rtl_dump_file,
924 "Irreducible region hit, ignoring edge to %i->%i\n",
925 e->src->index, bb->index);
926 BLOCK_INFO (bb)->npredecessors = count;
927 }
928 }
929
930 memcpy (&BLOCK_INFO (head)->frequency, &real_one, sizeof (real_one));
931 last = head;
932 for (bb = head; bb; bb = nextbb)
933 {
934 REAL_VALUE_TYPE cyclic_probability, frequency;
935
936 memcpy (&cyclic_probability, &real_zero, sizeof (real_zero));
937 memcpy (&frequency, &real_zero, sizeof (real_zero));
938
939 nextbb = BLOCK_INFO (bb)->next;
940 BLOCK_INFO (bb)->next = NULL;
941
942 /* Compute frequency of basic block. */
943 if (bb != head)
944 {
945 #ifdef ENABLE_CHECKING
946 for (e = bb->pred; e; e = e->pred_next)
947 if (BLOCK_INFO (e->src)->tovisit && !(e->flags & EDGE_DFS_BACK))
948 abort ();
949 #endif
950
951 for (e = bb->pred; e; e = e->pred_next)
952 if (EDGE_INFO (e)->back_edge)
953 {
954 REAL_ARITHMETIC (cyclic_probability, PLUS_EXPR,
955 cyclic_probability,
956 EDGE_INFO (e)->back_edge_prob);
957 }
958 else if (!(e->flags & EDGE_DFS_BACK))
959 {
960 REAL_VALUE_TYPE tmp;
961
962 /* frequency += (e->probability
963 * BLOCK_INFO (e->src)->frequency /
964 REG_BR_PROB_BASE); */
965
966 REAL_VALUE_FROM_INT (tmp, e->probability, 0,
967 TYPE_MODE (double_type_node));
968 REAL_ARITHMETIC (tmp, MULT_EXPR, tmp,
969 BLOCK_INFO (e->src)->frequency);
970 REAL_ARITHMETIC (tmp, RDIV_EXPR, tmp, real_br_prob_base);
971 REAL_ARITHMETIC (frequency, PLUS_EXPR, frequency, tmp);
972 }
973
974 if (REAL_VALUES_LESS (real_almost_one, cyclic_probability))
975 memcpy (&cyclic_probability, &real_almost_one, sizeof (real_zero));
976
977 /* BLOCK_INFO (bb)->frequency = frequency / (1 - cyclic_probability)
978 */
979
980 REAL_ARITHMETIC (cyclic_probability, MINUS_EXPR, real_one,
981 cyclic_probability);
982 REAL_ARITHMETIC (BLOCK_INFO (bb)->frequency,
983 RDIV_EXPR, frequency, cyclic_probability);
984 }
985
986 BLOCK_INFO (bb)->tovisit = 0;
987
988 /* Compute back edge frequencies. */
989 for (e = bb->succ; e; e = e->succ_next)
990 if (e->dest == head)
991 {
992 REAL_VALUE_TYPE tmp;
993
994 /* EDGE_INFO (e)->back_edge_prob
995 = ((e->probability * BLOCK_INFO (bb)->frequency)
996 / REG_BR_PROB_BASE); */
997 REAL_VALUE_FROM_INT (tmp, e->probability, 0,
998 TYPE_MODE (double_type_node));
999 REAL_ARITHMETIC (tmp, MULT_EXPR, tmp,
1000 BLOCK_INFO (bb)->frequency);
1001 REAL_ARITHMETIC (EDGE_INFO (e)->back_edge_prob,
1002 RDIV_EXPR, tmp, real_br_prob_base);
1003
1004 }
1005
1006 /* Propagate to successor blocks. */
1007 for (e = bb->succ; e; e = e->succ_next)
1008 if (!(e->flags & EDGE_DFS_BACK)
1009 && BLOCK_INFO (e->dest)->npredecessors)
1010 {
1011 BLOCK_INFO (e->dest)->npredecessors--;
1012 if (!BLOCK_INFO (e->dest)->npredecessors)
1013 {
1014 if (!nextbb)
1015 nextbb = e->dest;
1016 else
1017 BLOCK_INFO (last)->next = e->dest;
1018
1019 last = e->dest;
1020 }
1021 }
1022 }
1023 }
1024
1025 /* Estimate probabilities of loopback edges in loops at same nest level. */
1026
1027 static void
1028 estimate_loops_at_level (first_loop)
1029 struct loop *first_loop;
1030 {
1031 struct loop *l, *loop = first_loop;
1032
1033 for (loop = first_loop; loop; loop = loop->next)
1034 {
1035 int n;
1036 edge e;
1037
1038 estimate_loops_at_level (loop->inner);
1039
1040 /* Find current loop back edge and mark it. */
1041 for (e = loop->latch->succ; e->dest != loop->header; e = e->succ_next)
1042 ;
1043
1044 EDGE_INFO (e)->back_edge = 1;
1045
1046 /* In case the loop header is shared, ensure that it is the last
1047 one sharing the same header, so we avoid redundant work. */
1048 if (loop->shared)
1049 {
1050 for (l = loop->next; l; l = l->next)
1051 if (l->header == loop->header)
1052 break;
1053
1054 if (l)
1055 continue;
1056 }
1057
1058 /* Now merge all nodes of all loops with given header as not visited. */
1059 for (l = loop->shared ? first_loop : loop; l != loop->next; l = l->next)
1060 if (loop->header == l->header)
1061 EXECUTE_IF_SET_IN_SBITMAP (l->nodes, 0, n,
1062 BLOCK_INFO (BASIC_BLOCK (n))->tovisit = 1
1063 );
1064
1065 propagate_freq (loop->header);
1066 }
1067 }
1068
1069 /* Convert counts measured by profile driven feedback to frequencies. */
1070
1071 static void
1072 counts_to_freqs ()
1073 {
1074 HOST_WIDEST_INT count_max = 1;
1075 basic_block bb;
1076
1077 FOR_EACH_BB (bb)
1078 count_max = MAX (bb->count, count_max);
1079
1080 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1081 bb->frequency = (bb->count * BB_FREQ_MAX + count_max / 2) / count_max;
1082 }
1083
1084 /* Return true if function is likely to be expensive, so there is no point to
1085 optimize performance of prologue, epilogue or do inlining at the expense
1086 of code size growth. THRESHOLD is the limit of number of isntructions
1087 function can execute at average to be still considered not expensive. */
1088
1089 bool
1090 expensive_function_p (threshold)
1091 int threshold;
1092 {
1093 unsigned int sum = 0;
1094 basic_block bb;
1095 unsigned int limit;
1096
1097 /* We can not compute accurately for large thresholds due to scaled
1098 frequencies. */
1099 if (threshold > BB_FREQ_MAX)
1100 abort ();
1101
1102 /* Frequencies are out of range. This either means that function contains
1103 internal loop executing more than BB_FREQ_MAX times or profile feedback
1104 is available and function has not been executed at all. */
1105 if (ENTRY_BLOCK_PTR->frequency == 0)
1106 return true;
1107
1108 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
1109 limit = ENTRY_BLOCK_PTR->frequency * threshold;
1110 FOR_EACH_BB (bb)
1111 {
1112 rtx insn;
1113
1114 for (insn = bb->head; insn != NEXT_INSN (bb->end);
1115 insn = NEXT_INSN (insn))
1116 if (active_insn_p (insn))
1117 {
1118 sum += bb->frequency;
1119 if (sum > limit)
1120 return true;
1121 }
1122 }
1123
1124 return false;
1125 }
1126
1127 /* Estimate basic blocks frequency by given branch probabilities. */
1128
1129 static void
1130 estimate_bb_frequencies (loops)
1131 struct loops *loops;
1132 {
1133 basic_block bb;
1134 REAL_VALUE_TYPE freq_max;
1135 enum machine_mode double_mode = TYPE_MODE (double_type_node);
1136
1137 if (flag_branch_probabilities)
1138 counts_to_freqs ();
1139 else
1140 {
1141 REAL_VALUE_FROM_INT (real_zero, 0, 0, double_mode);
1142 REAL_VALUE_FROM_INT (real_one, 1, 0, double_mode);
1143 REAL_VALUE_FROM_INT (real_br_prob_base, REG_BR_PROB_BASE, 0, double_mode);
1144 REAL_VALUE_FROM_INT (real_bb_freq_max, BB_FREQ_MAX, 0, double_mode);
1145 REAL_VALUE_FROM_INT (real_one_half, 2, 0, double_mode);
1146
1147 REAL_ARITHMETIC (real_one_half, RDIV_EXPR, real_one, real_one_half);
1148
1149 REAL_ARITHMETIC (real_almost_one, RDIV_EXPR, real_one, real_br_prob_base);
1150 REAL_ARITHMETIC (real_almost_one, MINUS_EXPR, real_one, real_almost_one);
1151
1152 mark_dfs_back_edges ();
1153 /* Fill in the probability values in flowgraph based on the REG_BR_PROB
1154 notes. */
1155 FOR_EACH_BB (bb)
1156 {
1157 rtx last_insn = bb->end;
1158
1159 if (GET_CODE (last_insn) != JUMP_INSN || !any_condjump_p (last_insn)
1160 /* Avoid handling of conditional jumps jumping to fallthru edge. */
1161 || bb->succ->succ_next == NULL)
1162 {
1163 /* We can predict only conditional jumps at the moment.
1164 Expect each edge to be equally probable.
1165 ?? In the future we want to make abnormal edges improbable. */
1166 int nedges = 0;
1167 edge e;
1168
1169 for (e = bb->succ; e; e = e->succ_next)
1170 {
1171 nedges++;
1172 if (e->probability != 0)
1173 break;
1174 }
1175 if (!e)
1176 for (e = bb->succ; e; e = e->succ_next)
1177 e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
1178 }
1179 }
1180
1181 ENTRY_BLOCK_PTR->succ->probability = REG_BR_PROB_BASE;
1182
1183 /* Set up block info for each basic block. */
1184 alloc_aux_for_blocks (sizeof (struct block_info_def));
1185 alloc_aux_for_edges (sizeof (struct edge_info_def));
1186 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1187 {
1188 edge e;
1189
1190 BLOCK_INFO (bb)->tovisit = 0;
1191 for (e = bb->succ; e; e = e->succ_next)
1192 {
1193 REAL_VALUE_FROM_INT (EDGE_INFO (e)->back_edge_prob,
1194 e->probability, 0, double_mode);
1195 REAL_ARITHMETIC (EDGE_INFO (e)->back_edge_prob,
1196 RDIV_EXPR, EDGE_INFO (e)->back_edge_prob,
1197 real_br_prob_base);
1198 }
1199 }
1200
1201 /* First compute probabilities locally for each loop from innermost
1202 to outermost to examine probabilities for back edges. */
1203 estimate_loops_at_level (loops->tree_root);
1204
1205 /* Now fake loop around whole function to finalize probabilities. */
1206 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1207 BLOCK_INFO (bb)->tovisit = 1;
1208
1209 BLOCK_INFO (ENTRY_BLOCK_PTR)->tovisit = 1;
1210 BLOCK_INFO (EXIT_BLOCK_PTR)->tovisit = 1;
1211 propagate_freq (ENTRY_BLOCK_PTR);
1212
1213 memcpy (&freq_max, &real_zero, sizeof (real_zero));
1214 FOR_EACH_BB (bb)
1215 if (REAL_VALUES_LESS
1216 (freq_max, BLOCK_INFO (bb)->frequency))
1217 memcpy (&freq_max, &BLOCK_INFO (bb)->frequency,
1218 sizeof (freq_max));
1219
1220 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1221 {
1222 REAL_VALUE_TYPE tmp;
1223
1224 REAL_ARITHMETIC (tmp, MULT_EXPR, BLOCK_INFO (bb)->frequency,
1225 real_bb_freq_max);
1226 REAL_ARITHMETIC (tmp, RDIV_EXPR, tmp, freq_max);
1227 REAL_ARITHMETIC (tmp, PLUS_EXPR, tmp, real_one_half);
1228 bb->frequency = REAL_VALUE_UNSIGNED_FIX (tmp);
1229 }
1230
1231 free_aux_for_blocks ();
1232 free_aux_for_edges ();
1233 }
1234 compute_function_frequency ();
1235 if (flag_reorder_functions)
1236 choose_function_section ();
1237 }
1238
1239 /* Decide whether function is hot, cold or unlikely executed. */
1240 static void
1241 compute_function_frequency ()
1242 {
1243 basic_block bb;
1244
1245 if (!profile_info.count_profiles_merged
1246 || !flag_branch_probabilities)
1247 return;
1248 cfun->function_frequency = FUNCTION_FREQUENCY_UNLIKELY_EXECUTED;
1249 FOR_EACH_BB (bb)
1250 {
1251 if (maybe_hot_bb_p (bb))
1252 {
1253 cfun->function_frequency = FUNCTION_FREQUENCY_HOT;
1254 return;
1255 }
1256 if (!probably_never_executed_bb_p (bb))
1257 cfun->function_frequency = FUNCTION_FREQUENCY_NORMAL;
1258 }
1259 }
1260
1261 /* Choose appropriate section for the function. */
1262 static void
1263 choose_function_section ()
1264 {
1265 if (DECL_SECTION_NAME (current_function_decl)
1266 || !targetm.have_named_sections)
1267 return;
1268 if (cfun->function_frequency == FUNCTION_FREQUENCY_HOT)
1269 DECL_SECTION_NAME (current_function_decl) =
1270 build_string (strlen (HOT_TEXT_SECTION_NAME), HOT_TEXT_SECTION_NAME);
1271 if (cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
1272 DECL_SECTION_NAME (current_function_decl) =
1273 build_string (strlen (UNLIKELY_EXECUTED_TEXT_SECTION_NAME),
1274 UNLIKELY_EXECUTED_TEXT_SECTION_NAME);
1275 }