OSDN Git Service

2007-02-23 Gary Benson <gbenson@redhat.com>
[pf3gnuchains/gcc-fork.git] / gcc / predict.c
1 /* Branch prediction routines for the GNU compiler.
2    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005
3    Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to the Free
19 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
20 02110-1301, USA.  */
21
22 /* References:
23
24    [1] "Branch Prediction for Free"
25        Ball and Larus; PLDI '93.
26    [2] "Static Branch Frequency and Program Profile Analysis"
27        Wu and Larus; MICRO-27.
28    [3] "Corpus-based Static Branch Prediction"
29        Calder, Grunwald, Lindsay, Martin, Mozer, and Zorn; PLDI '95.  */
30
31
32 #include "config.h"
33 #include "system.h"
34 #include "coretypes.h"
35 #include "tm.h"
36 #include "tree.h"
37 #include "rtl.h"
38 #include "tm_p.h"
39 #include "hard-reg-set.h"
40 #include "basic-block.h"
41 #include "insn-config.h"
42 #include "regs.h"
43 #include "flags.h"
44 #include "output.h"
45 #include "function.h"
46 #include "except.h"
47 #include "toplev.h"
48 #include "recog.h"
49 #include "expr.h"
50 #include "predict.h"
51 #include "coverage.h"
52 #include "sreal.h"
53 #include "params.h"
54 #include "target.h"
55 #include "cfgloop.h"
56 #include "tree-flow.h"
57 #include "ggc.h"
58 #include "tree-dump.h"
59 #include "tree-pass.h"
60 #include "timevar.h"
61 #include "tree-scalar-evolution.h"
62 #include "cfgloop.h"
63
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;
68
69 /* Random guesstimation given names.  */
70 #define PROB_VERY_UNLIKELY      (REG_BR_PROB_BASE / 100 - 1)
71 #define PROB_EVEN               (REG_BR_PROB_BASE / 2)
72 #define PROB_VERY_LIKELY        (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
73 #define PROB_ALWAYS             (REG_BR_PROB_BASE)
74
75 static void combine_predictions_for_insn (rtx, basic_block);
76 static void dump_prediction (FILE *, enum br_predictor, int, basic_block, int);
77 static void predict_paths_leading_to (basic_block, int *, enum br_predictor, enum prediction);
78 static bool last_basic_block_p (basic_block);
79 static void compute_function_frequency (void);
80 static void choose_function_section (void);
81 static bool can_predict_insn_p (rtx);
82
83 /* Information we hold about each branch predictor.
84    Filled using information from predict.def.  */
85
86 struct predictor_info
87 {
88   const char *const name;       /* Name used in the debugging dumps.  */
89   const int hitrate;            /* Expected hitrate used by
90                                    predict_insn_def call.  */
91   const int flags;
92 };
93
94 /* Use given predictor without Dempster-Shaffer theory if it matches
95    using first_match heuristics.  */
96 #define PRED_FLAG_FIRST_MATCH 1
97
98 /* Recompute hitrate in percent to our representation.  */
99
100 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
101
102 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
103 static const struct predictor_info predictor_info[]= {
104 #include "predict.def"
105
106   /* Upper bound on predictors.  */
107   {NULL, 0, 0}
108 };
109 #undef DEF_PREDICTOR
110
111 /* Return true in case BB can be CPU intensive and should be optimized
112    for maximal performance.  */
113
114 bool
115 maybe_hot_bb_p (basic_block bb)
116 {
117   if (profile_info && flag_branch_probabilities
118       && (bb->count
119           < profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
120     return false;
121   if (bb->frequency < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
122     return false;
123   return true;
124 }
125
126 /* Return true in case BB is cold and should be optimized for size.  */
127
128 bool
129 probably_cold_bb_p (basic_block bb)
130 {
131   if (profile_info && flag_branch_probabilities
132       && (bb->count
133           < profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
134     return true;
135   if (bb->frequency < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
136     return true;
137   return false;
138 }
139
140 /* Return true in case BB is probably never executed.  */
141 bool
142 probably_never_executed_bb_p (basic_block bb)
143 {
144   if (profile_info && flag_branch_probabilities)
145     return ((bb->count + profile_info->runs / 2) / profile_info->runs) == 0;
146   return false;
147 }
148
149 /* Return true if the one of outgoing edges is already predicted by
150    PREDICTOR.  */
151
152 bool
153 rtl_predicted_by_p (basic_block bb, enum br_predictor predictor)
154 {
155   rtx note;
156   if (!INSN_P (BB_END (bb)))
157     return false;
158   for (note = REG_NOTES (BB_END (bb)); note; note = XEXP (note, 1))
159     if (REG_NOTE_KIND (note) == REG_BR_PRED
160         && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
161       return true;
162   return false;
163 }
164
165 /* Return true if the one of outgoing edges is already predicted by
166    PREDICTOR.  */
167
168 bool
169 tree_predicted_by_p (basic_block bb, enum br_predictor predictor)
170 {
171   struct edge_prediction *i;
172   for (i = bb->predictions; i; i = i->ep_next)
173     if (i->ep_predictor == predictor)
174       return true;
175   return false;
176 }
177
178 /* Return true when the probability of edge is reliable.
179   
180    The profile guessing code is good at predicting branch outcome (ie.
181    taken/not taken), that is predicted right slightly over 75% of time.
182    It is however notoriously poor on predicting the probability itself.
183    In general the profile appear a lot flatter (with probabilities closer
184    to 50%) than the reality so it is bad idea to use it to drive optimization
185    such as those disabling dynamic branch prediction for well predictable
186    branches.
187
188    There are two exceptions - edges leading to noreturn edges and edges
189    predicted by number of iterations heuristics are predicted well.  This macro
190    should be able to distinguish those, but at the moment it simply check for
191    noreturn heuristic that is only one giving probability over 99% or bellow
192    1%.  In future we might want to propagate reliability information across the
193    CFG if we find this information useful on multiple places.   */
194 static bool
195 probability_reliable_p (int prob)
196 {
197   return (profile_status == PROFILE_READ
198           || (profile_status == PROFILE_GUESSED
199               && (prob <= HITRATE (1) || prob >= HITRATE (99))));
200 }
201
202 /* Same predicate as above, working on edges.  */
203 bool
204 edge_probability_reliable_p (edge e)
205 {
206   return probability_reliable_p (e->probability);
207 }
208
209 /* Same predicate as edge_probability_reliable_p, working on notes.  */
210 bool
211 br_prob_note_reliable_p (rtx note)
212 {
213   gcc_assert (REG_NOTE_KIND (note) == REG_BR_PROB);
214   return probability_reliable_p (INTVAL (XEXP (note, 0)));
215 }
216
217 static void
218 predict_insn (rtx insn, enum br_predictor predictor, int probability)
219 {
220   gcc_assert (any_condjump_p (insn));
221   if (!flag_guess_branch_prob)
222     return;
223
224   REG_NOTES (insn)
225     = gen_rtx_EXPR_LIST (REG_BR_PRED,
226                          gen_rtx_CONCAT (VOIDmode,
227                                          GEN_INT ((int) predictor),
228                                          GEN_INT ((int) probability)),
229                          REG_NOTES (insn));
230 }
231
232 /* Predict insn by given predictor.  */
233
234 void
235 predict_insn_def (rtx insn, enum br_predictor predictor,
236                   enum prediction taken)
237 {
238    int probability = predictor_info[(int) predictor].hitrate;
239
240    if (taken != TAKEN)
241      probability = REG_BR_PROB_BASE - probability;
242
243    predict_insn (insn, predictor, probability);
244 }
245
246 /* Predict edge E with given probability if possible.  */
247
248 void
249 rtl_predict_edge (edge e, enum br_predictor predictor, int probability)
250 {
251   rtx last_insn;
252   last_insn = BB_END (e->src);
253
254   /* We can store the branch prediction information only about
255      conditional jumps.  */
256   if (!any_condjump_p (last_insn))
257     return;
258
259   /* We always store probability of branching.  */
260   if (e->flags & EDGE_FALLTHRU)
261     probability = REG_BR_PROB_BASE - probability;
262
263   predict_insn (last_insn, predictor, probability);
264 }
265
266 /* Predict edge E with the given PROBABILITY.  */
267 void
268 tree_predict_edge (edge e, enum br_predictor predictor, int probability)
269 {
270   gcc_assert (profile_status != PROFILE_GUESSED);
271   if ((e->src != ENTRY_BLOCK_PTR && EDGE_COUNT (e->src->succs) > 1)
272       && flag_guess_branch_prob && optimize)
273     {
274       struct edge_prediction *i = ggc_alloc (sizeof (struct edge_prediction));
275
276       i->ep_next = e->src->predictions;
277       e->src->predictions = i;
278       i->ep_probability = probability;
279       i->ep_predictor = predictor;
280       i->ep_edge = e;
281     }
282 }
283
284 /* Remove all predictions on given basic block that are attached
285    to edge E.  */
286 void
287 remove_predictions_associated_with_edge (edge e)
288 {
289   if (e->src->predictions)
290     {
291       struct edge_prediction **prediction = &e->src->predictions;
292       while (*prediction)
293         {
294           if ((*prediction)->ep_edge == e)
295             *prediction = (*prediction)->ep_next;
296           else
297             prediction = &((*prediction)->ep_next);
298         }
299     }
300 }
301
302 /* Return true when we can store prediction on insn INSN.
303    At the moment we represent predictions only on conditional
304    jumps, not at computed jump or other complicated cases.  */
305 static bool
306 can_predict_insn_p (rtx insn)
307 {
308   return (JUMP_P (insn)
309           && any_condjump_p (insn)
310           && EDGE_COUNT (BLOCK_FOR_INSN (insn)->succs) >= 2);
311 }
312
313 /* Predict edge E by given predictor if possible.  */
314
315 void
316 predict_edge_def (edge e, enum br_predictor predictor,
317                   enum prediction taken)
318 {
319    int probability = predictor_info[(int) predictor].hitrate;
320
321    if (taken != TAKEN)
322      probability = REG_BR_PROB_BASE - probability;
323
324    predict_edge (e, predictor, probability);
325 }
326
327 /* Invert all branch predictions or probability notes in the INSN.  This needs
328    to be done each time we invert the condition used by the jump.  */
329
330 void
331 invert_br_probabilities (rtx insn)
332 {
333   rtx note;
334
335   for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
336     if (REG_NOTE_KIND (note) == REG_BR_PROB)
337       XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
338     else if (REG_NOTE_KIND (note) == REG_BR_PRED)
339       XEXP (XEXP (note, 0), 1)
340         = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
341 }
342
343 /* Dump information about the branch prediction to the output file.  */
344
345 static void
346 dump_prediction (FILE *file, enum br_predictor predictor, int probability,
347                  basic_block bb, int used)
348 {
349   edge e;
350   edge_iterator ei;
351
352   if (!file)
353     return;
354
355   FOR_EACH_EDGE (e, ei, bb->succs)
356     if (! (e->flags & EDGE_FALLTHRU))
357       break;
358
359   fprintf (file, "  %s heuristics%s: %.1f%%",
360            predictor_info[predictor].name,
361            used ? "" : " (ignored)", probability * 100.0 / REG_BR_PROB_BASE);
362
363   if (bb->count)
364     {
365       fprintf (file, "  exec ");
366       fprintf (file, HOST_WIDEST_INT_PRINT_DEC, bb->count);
367       if (e)
368         {
369           fprintf (file, " hit ");
370           fprintf (file, HOST_WIDEST_INT_PRINT_DEC, e->count);
371           fprintf (file, " (%.1f%%)", e->count * 100.0 / bb->count);
372         }
373     }
374
375   fprintf (file, "\n");
376 }
377
378 /* We can not predict the probabilities of outgoing edges of bb.  Set them
379    evenly and hope for the best.  */
380 static void
381 set_even_probabilities (basic_block bb)
382 {
383   int nedges = 0;
384   edge e;
385   edge_iterator ei;
386
387   FOR_EACH_EDGE (e, ei, bb->succs)
388     if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
389       nedges ++;
390   FOR_EACH_EDGE (e, ei, bb->succs)
391     if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
392       e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
393     else
394       e->probability = 0;
395 }
396
397 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
398    note if not already present.  Remove now useless REG_BR_PRED notes.  */
399
400 static void
401 combine_predictions_for_insn (rtx insn, basic_block bb)
402 {
403   rtx prob_note;
404   rtx *pnote;
405   rtx note;
406   int best_probability = PROB_EVEN;
407   int best_predictor = END_PREDICTORS;
408   int combined_probability = REG_BR_PROB_BASE / 2;
409   int d;
410   bool first_match = false;
411   bool found = false;
412
413   if (!can_predict_insn_p (insn))
414     {
415       set_even_probabilities (bb);
416       return;
417     }
418
419   prob_note = find_reg_note (insn, REG_BR_PROB, 0);
420   pnote = &REG_NOTES (insn);
421   if (dump_file)
422     fprintf (dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
423              bb->index);
424
425   /* We implement "first match" heuristics and use probability guessed
426      by predictor with smallest index.  */
427   for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
428     if (REG_NOTE_KIND (note) == REG_BR_PRED)
429       {
430         int predictor = INTVAL (XEXP (XEXP (note, 0), 0));
431         int probability = INTVAL (XEXP (XEXP (note, 0), 1));
432
433         found = true;
434         if (best_predictor > predictor)
435           best_probability = probability, best_predictor = predictor;
436
437         d = (combined_probability * probability
438              + (REG_BR_PROB_BASE - combined_probability)
439              * (REG_BR_PROB_BASE - probability));
440
441         /* Use FP math to avoid overflows of 32bit integers.  */
442         if (d == 0)
443           /* If one probability is 0% and one 100%, avoid division by zero.  */
444           combined_probability = REG_BR_PROB_BASE / 2;
445         else
446           combined_probability = (((double) combined_probability) * probability
447                                   * REG_BR_PROB_BASE / d + 0.5);
448       }
449
450   /* Decide which heuristic to use.  In case we didn't match anything,
451      use no_prediction heuristic, in case we did match, use either
452      first match or Dempster-Shaffer theory depending on the flags.  */
453
454   if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
455     first_match = true;
456
457   if (!found)
458     dump_prediction (dump_file, PRED_NO_PREDICTION,
459                      combined_probability, bb, true);
460   else
461     {
462       dump_prediction (dump_file, PRED_DS_THEORY, combined_probability,
463                        bb, !first_match);
464       dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability,
465                        bb, first_match);
466     }
467
468   if (first_match)
469     combined_probability = best_probability;
470   dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
471
472   while (*pnote)
473     {
474       if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
475         {
476           int predictor = INTVAL (XEXP (XEXP (*pnote, 0), 0));
477           int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
478
479           dump_prediction (dump_file, predictor, probability, bb,
480                            !first_match || best_predictor == predictor);
481           *pnote = XEXP (*pnote, 1);
482         }
483       else
484         pnote = &XEXP (*pnote, 1);
485     }
486
487   if (!prob_note)
488     {
489       REG_NOTES (insn)
490         = gen_rtx_EXPR_LIST (REG_BR_PROB,
491                              GEN_INT (combined_probability), REG_NOTES (insn));
492
493       /* Save the prediction into CFG in case we are seeing non-degenerated
494          conditional jump.  */
495       if (!single_succ_p (bb))
496         {
497           BRANCH_EDGE (bb)->probability = combined_probability;
498           FALLTHRU_EDGE (bb)->probability
499             = REG_BR_PROB_BASE - combined_probability;
500         }
501     }
502   else if (!single_succ_p (bb))
503     {
504       int prob = INTVAL (XEXP (prob_note, 0));
505
506       BRANCH_EDGE (bb)->probability = prob;
507       FALLTHRU_EDGE (bb)->probability = REG_BR_PROB_BASE - prob;
508     }
509   else
510     single_succ_edge (bb)->probability = REG_BR_PROB_BASE;
511 }
512
513 /* Combine predictions into single probability and store them into CFG.
514    Remove now useless prediction entries.  */
515
516 static void
517 combine_predictions_for_bb (basic_block bb)
518 {
519   int best_probability = PROB_EVEN;
520   int best_predictor = END_PREDICTORS;
521   int combined_probability = REG_BR_PROB_BASE / 2;
522   int d;
523   bool first_match = false;
524   bool found = false;
525   struct edge_prediction *pred;
526   int nedges = 0;
527   edge e, first = NULL, second = NULL;
528   edge_iterator ei;
529
530   FOR_EACH_EDGE (e, ei, bb->succs)
531     if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
532       {
533         nedges ++;
534         if (first && !second)
535           second = e;
536         if (!first)
537           first = e;
538       }
539
540   /* When there is no successor or only one choice, prediction is easy. 
541
542      We are lazy for now and predict only basic blocks with two outgoing
543      edges.  It is possible to predict generic case too, but we have to
544      ignore first match heuristics and do more involved combining.  Implement
545      this later.  */
546   if (nedges != 2)
547     {
548       if (!bb->count)
549         set_even_probabilities (bb);
550       bb->predictions = NULL;
551       if (dump_file)
552         fprintf (dump_file, "%i edges in bb %i predicted to even probabilities\n",
553                  nedges, bb->index);
554       return;
555     }
556
557   if (dump_file)
558     fprintf (dump_file, "Predictions for bb %i\n", bb->index);
559
560   /* We implement "first match" heuristics and use probability guessed
561      by predictor with smallest index.  */
562   for (pred = bb->predictions; pred; pred = pred->ep_next)
563     {
564       int predictor = pred->ep_predictor;
565       int probability = pred->ep_probability;
566
567       if (pred->ep_edge != first)
568         probability = REG_BR_PROB_BASE - probability;
569
570       found = true;
571       if (best_predictor > predictor)
572         best_probability = probability, best_predictor = predictor;
573
574       d = (combined_probability * probability
575            + (REG_BR_PROB_BASE - combined_probability)
576            * (REG_BR_PROB_BASE - probability));
577
578       /* Use FP math to avoid overflows of 32bit integers.  */
579       if (d == 0)
580         /* If one probability is 0% and one 100%, avoid division by zero.  */
581         combined_probability = REG_BR_PROB_BASE / 2;
582       else
583         combined_probability = (((double) combined_probability) * probability
584                                 * REG_BR_PROB_BASE / d + 0.5);
585     }
586
587   /* Decide which heuristic to use.  In case we didn't match anything,
588      use no_prediction heuristic, in case we did match, use either
589      first match or Dempster-Shaffer theory depending on the flags.  */
590
591   if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
592     first_match = true;
593
594   if (!found)
595     dump_prediction (dump_file, PRED_NO_PREDICTION, combined_probability, bb, true);
596   else
597     {
598       dump_prediction (dump_file, PRED_DS_THEORY, combined_probability, bb,
599                        !first_match);
600       dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability, bb,
601                        first_match);
602     }
603
604   if (first_match)
605     combined_probability = best_probability;
606   dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
607
608   for (pred = bb->predictions; pred; pred = pred->ep_next)
609     {
610       int predictor = pred->ep_predictor;
611       int probability = pred->ep_probability;
612
613       if (pred->ep_edge != EDGE_SUCC (bb, 0))
614         probability = REG_BR_PROB_BASE - probability;
615       dump_prediction (dump_file, predictor, probability, bb,
616                        !first_match || best_predictor == predictor);
617     }
618   bb->predictions = NULL;
619
620   if (!bb->count)
621     {
622       first->probability = combined_probability;
623       second->probability = REG_BR_PROB_BASE - combined_probability;
624     }
625 }
626
627 /* Predict edge probabilities by exploiting loop structure.  */
628
629 static void
630 predict_loops (void)
631 {
632   loop_iterator li;
633   struct loop *loop;
634
635   scev_initialize ();
636
637   /* Try to predict out blocks in a loop that are not part of a
638      natural loop.  */
639   FOR_EACH_LOOP (li, loop, 0)
640     {
641       basic_block bb, *bbs;
642       unsigned j, n_exits;
643       VEC (edge, heap) *exits;
644       struct tree_niter_desc niter_desc;
645       edge ex;
646
647       exits = get_loop_exit_edges (loop);
648       n_exits = VEC_length (edge, exits);
649
650       for (j = 0; VEC_iterate (edge, exits, j, ex); j++)
651         {
652           tree niter = NULL;
653
654           if (number_of_iterations_exit (loop, ex, &niter_desc, false))
655             niter = niter_desc.niter;
656           if (!niter || TREE_CODE (niter_desc.niter) != INTEGER_CST)
657             niter = loop_niter_by_eval (loop, ex);
658
659           if (TREE_CODE (niter) == INTEGER_CST)
660             {
661               int probability;
662               int max = PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS);
663               if (host_integerp (niter, 1)
664                   && compare_tree_int (niter, max-1) == -1)
665                 {
666                   HOST_WIDE_INT nitercst = tree_low_cst (niter, 1) + 1;
667                   probability = ((REG_BR_PROB_BASE + nitercst / 2)
668                                  / nitercst);
669                 }
670               else
671                 probability = ((REG_BR_PROB_BASE + max / 2) / max);
672
673               predict_edge (ex, PRED_LOOP_ITERATIONS, probability);
674             }
675         }
676       VEC_free (edge, heap, exits);
677
678       bbs = get_loop_body (loop);
679
680       for (j = 0; j < loop->num_nodes; j++)
681         {
682           int header_found = 0;
683           edge e;
684           edge_iterator ei;
685
686           bb = bbs[j];
687
688           /* Bypass loop heuristics on continue statement.  These
689              statements construct loops via "non-loop" constructs
690              in the source language and are better to be handled
691              separately.  */
692           if (predicted_by_p (bb, PRED_CONTINUE))
693             continue;
694
695           /* Loop branch heuristics - predict an edge back to a
696              loop's head as taken.  */
697           if (bb == loop->latch)
698             {
699               e = find_edge (loop->latch, loop->header);
700               if (e)
701                 {
702                   header_found = 1;
703                   predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
704                 }
705             }
706
707           /* Loop exit heuristics - predict an edge exiting the loop if the
708              conditional has no loop header successors as not taken.  */
709           if (!header_found)
710             {
711               /* For loop with many exits we don't want to predict all exits
712                  with the pretty large probability, because if all exits are
713                  considered in row, the loop would be predicted to iterate
714                  almost never.  The code to divide probability by number of
715                  exits is very rough.  It should compute the number of exits
716                  taken in each patch through function (not the overall number
717                  of exits that might be a lot higher for loops with wide switch
718                  statements in them) and compute n-th square root.
719
720                  We limit the minimal probability by 2% to avoid
721                  EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
722                  as this was causing regression in perl benchmark containing such
723                  a wide loop.  */
724                 
725               int probability = ((REG_BR_PROB_BASE
726                                   - predictor_info [(int) PRED_LOOP_EXIT].hitrate)
727                                  / n_exits);
728               if (probability < HITRATE (2))
729                 probability = HITRATE (2);
730               FOR_EACH_EDGE (e, ei, bb->succs)
731                 if (e->dest->index < NUM_FIXED_BLOCKS
732                     || !flow_bb_inside_loop_p (loop, e->dest))
733                   predict_edge (e, PRED_LOOP_EXIT, probability);
734             }
735         }
736       
737       /* Free basic blocks from get_loop_body.  */
738       free (bbs);
739     }
740
741   scev_finalize ();
742 }
743
744 /* Attempt to predict probabilities of BB outgoing edges using local
745    properties.  */
746 static void
747 bb_estimate_probability_locally (basic_block bb)
748 {
749   rtx last_insn = BB_END (bb);
750   rtx cond;
751
752   if (! can_predict_insn_p (last_insn))
753     return;
754   cond = get_condition (last_insn, NULL, false, false);
755   if (! cond)
756     return;
757
758   /* Try "pointer heuristic."
759      A comparison ptr == 0 is predicted as false.
760      Similarly, a comparison ptr1 == ptr2 is predicted as false.  */
761   if (COMPARISON_P (cond)
762       && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
763           || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
764     {
765       if (GET_CODE (cond) == EQ)
766         predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
767       else if (GET_CODE (cond) == NE)
768         predict_insn_def (last_insn, PRED_POINTER, TAKEN);
769     }
770   else
771
772   /* Try "opcode heuristic."
773      EQ tests are usually false and NE tests are usually true. Also,
774      most quantities are positive, so we can make the appropriate guesses
775      about signed comparisons against zero.  */
776     switch (GET_CODE (cond))
777       {
778       case CONST_INT:
779         /* Unconditional branch.  */
780         predict_insn_def (last_insn, PRED_UNCONDITIONAL,
781                           cond == const0_rtx ? NOT_TAKEN : TAKEN);
782         break;
783
784       case EQ:
785       case UNEQ:
786         /* Floating point comparisons appears to behave in a very
787            unpredictable way because of special role of = tests in
788            FP code.  */
789         if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
790           ;
791         /* Comparisons with 0 are often used for booleans and there is
792            nothing useful to predict about them.  */
793         else if (XEXP (cond, 1) == const0_rtx
794                  || XEXP (cond, 0) == const0_rtx)
795           ;
796         else
797           predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
798         break;
799
800       case NE:
801       case LTGT:
802         /* Floating point comparisons appears to behave in a very
803            unpredictable way because of special role of = tests in
804            FP code.  */
805         if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
806           ;
807         /* Comparisons with 0 are often used for booleans and there is
808            nothing useful to predict about them.  */
809         else if (XEXP (cond, 1) == const0_rtx
810                  || XEXP (cond, 0) == const0_rtx)
811           ;
812         else
813           predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
814         break;
815
816       case ORDERED:
817         predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
818         break;
819
820       case UNORDERED:
821         predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
822         break;
823
824       case LE:
825       case LT:
826         if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
827             || XEXP (cond, 1) == constm1_rtx)
828           predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
829         break;
830
831       case GE:
832       case GT:
833         if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
834             || XEXP (cond, 1) == constm1_rtx)
835           predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
836         break;
837
838       default:
839         break;
840       }
841 }
842
843 /* Set edge->probability for each successor edge of BB.  */
844 void
845 guess_outgoing_edge_probabilities (basic_block bb)
846 {
847   bb_estimate_probability_locally (bb);
848   combine_predictions_for_insn (BB_END (bb), bb);
849 }
850 \f
851 /* Return constant EXPR will likely have at execution time, NULL if unknown. 
852    The function is used by builtin_expect branch predictor so the evidence
853    must come from this construct and additional possible constant folding.
854   
855    We may want to implement more involved value guess (such as value range
856    propagation based prediction), but such tricks shall go to new
857    implementation.  */
858
859 static tree
860 expr_expected_value (tree expr, bitmap visited)
861 {
862   if (TREE_CONSTANT (expr))
863     return expr;
864   else if (TREE_CODE (expr) == SSA_NAME)
865     {
866       tree def = SSA_NAME_DEF_STMT (expr);
867
868       /* If we were already here, break the infinite cycle.  */
869       if (bitmap_bit_p (visited, SSA_NAME_VERSION (expr)))
870         return NULL;
871       bitmap_set_bit (visited, SSA_NAME_VERSION (expr));
872
873       if (TREE_CODE (def) == PHI_NODE)
874         {
875           /* All the arguments of the PHI node must have the same constant
876              length.  */
877           int i;
878           tree val = NULL, new_val;
879
880           for (i = 0; i < PHI_NUM_ARGS (def); i++)
881             {
882               tree arg = PHI_ARG_DEF (def, i);
883
884               /* If this PHI has itself as an argument, we cannot
885                  determine the string length of this argument.  However,
886                  if we can find an expected constant value for the other
887                  PHI args then we can still be sure that this is
888                  likely a constant.  So be optimistic and just
889                  continue with the next argument.  */
890               if (arg == PHI_RESULT (def))
891                 continue;
892
893               new_val = expr_expected_value (arg, visited);
894               if (!new_val)
895                 return NULL;
896               if (!val)
897                 val = new_val;
898               else if (!operand_equal_p (val, new_val, false))
899                 return NULL;
900             }
901           return val;
902         }
903       if (TREE_CODE (def) != GIMPLE_MODIFY_STMT
904           || GIMPLE_STMT_OPERAND (def, 0) != expr)
905         return NULL;
906       return expr_expected_value (GIMPLE_STMT_OPERAND (def, 1), visited);
907     }
908   else if (TREE_CODE (expr) == CALL_EXPR)
909     {
910       tree decl = get_callee_fndecl (expr);
911       if (!decl)
912         return NULL;
913       if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
914           && DECL_FUNCTION_CODE (decl) == BUILT_IN_EXPECT)
915         {
916           tree val;
917
918           if (call_expr_nargs (expr) != 2)
919             return NULL;
920           val = CALL_EXPR_ARG (expr, 0);
921           if (TREE_CONSTANT (val))
922             return val;
923           return CALL_EXPR_ARG (expr, 1);
924         }
925     }
926   if (BINARY_CLASS_P (expr) || COMPARISON_CLASS_P (expr))
927     {
928       tree op0, op1, res;
929       op0 = expr_expected_value (TREE_OPERAND (expr, 0), visited);
930       if (!op0)
931         return NULL;
932       op1 = expr_expected_value (TREE_OPERAND (expr, 1), visited);
933       if (!op1)
934         return NULL;
935       res = fold_build2 (TREE_CODE (expr), TREE_TYPE (expr), op0, op1);
936       if (TREE_CONSTANT (res))
937         return res;
938       return NULL;
939     }
940   if (UNARY_CLASS_P (expr))
941     {
942       tree op0, res;
943       op0 = expr_expected_value (TREE_OPERAND (expr, 0), visited);
944       if (!op0)
945         return NULL;
946       res = fold_build1 (TREE_CODE (expr), TREE_TYPE (expr), op0);
947       if (TREE_CONSTANT (res))
948         return res;
949       return NULL;
950     }
951   return NULL;
952 }
953 \f
954 /* Get rid of all builtin_expect calls we no longer need.  */
955 static void
956 strip_builtin_expect (void)
957 {
958   basic_block bb;
959   FOR_EACH_BB (bb)
960     {
961       block_stmt_iterator bi;
962       for (bi = bsi_start (bb); !bsi_end_p (bi); bsi_next (&bi))
963         {
964           tree stmt = bsi_stmt (bi);
965           tree fndecl;
966           tree call;
967
968           if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
969               && (call = GIMPLE_STMT_OPERAND (stmt, 1))
970               && TREE_CODE (call) == CALL_EXPR
971               && (fndecl = get_callee_fndecl (call))
972               && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
973               && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT
974               && call_expr_nargs (call) == 2)
975             {
976               GIMPLE_STMT_OPERAND (stmt, 1) = CALL_EXPR_ARG (call, 0);
977               update_stmt (stmt);
978             }
979         }
980     }
981 }
982 \f
983 /* Predict using opcode of the last statement in basic block.  */
984 static void
985 tree_predict_by_opcode (basic_block bb)
986 {
987   tree stmt = last_stmt (bb);
988   edge then_edge;
989   tree cond;
990   tree op0;
991   tree type;
992   tree val;
993   bitmap visited;
994   edge_iterator ei;
995
996   if (!stmt || TREE_CODE (stmt) != COND_EXPR)
997     return;
998   FOR_EACH_EDGE (then_edge, ei, bb->succs)
999     if (then_edge->flags & EDGE_TRUE_VALUE)
1000       break;
1001   cond = TREE_OPERAND (stmt, 0);
1002   if (!COMPARISON_CLASS_P (cond))
1003     return;
1004   op0 = TREE_OPERAND (cond, 0);
1005   type = TREE_TYPE (op0);
1006   visited = BITMAP_ALLOC (NULL);
1007   val = expr_expected_value (cond, visited);
1008   BITMAP_FREE (visited);
1009   if (val)
1010     {
1011       if (integer_zerop (val))
1012         predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, NOT_TAKEN);
1013       else
1014         predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, TAKEN);
1015       return;
1016     }
1017   /* Try "pointer heuristic."
1018      A comparison ptr == 0 is predicted as false.
1019      Similarly, a comparison ptr1 == ptr2 is predicted as false.  */
1020   if (POINTER_TYPE_P (type))
1021     {
1022       if (TREE_CODE (cond) == EQ_EXPR)
1023         predict_edge_def (then_edge, PRED_TREE_POINTER, NOT_TAKEN);
1024       else if (TREE_CODE (cond) == NE_EXPR)
1025         predict_edge_def (then_edge, PRED_TREE_POINTER, TAKEN);
1026     }
1027   else
1028
1029   /* Try "opcode heuristic."
1030      EQ tests are usually false and NE tests are usually true. Also,
1031      most quantities are positive, so we can make the appropriate guesses
1032      about signed comparisons against zero.  */
1033     switch (TREE_CODE (cond))
1034       {
1035       case EQ_EXPR:
1036       case UNEQ_EXPR:
1037         /* Floating point comparisons appears to behave in a very
1038            unpredictable way because of special role of = tests in
1039            FP code.  */
1040         if (FLOAT_TYPE_P (type))
1041           ;
1042         /* Comparisons with 0 are often used for booleans and there is
1043            nothing useful to predict about them.  */
1044         else if (integer_zerop (op0)
1045                  || integer_zerop (TREE_OPERAND (cond, 1)))
1046           ;
1047         else
1048           predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, NOT_TAKEN);
1049         break;
1050
1051       case NE_EXPR:
1052       case LTGT_EXPR:
1053         /* Floating point comparisons appears to behave in a very
1054            unpredictable way because of special role of = tests in
1055            FP code.  */
1056         if (FLOAT_TYPE_P (type))
1057           ;
1058         /* Comparisons with 0 are often used for booleans and there is
1059            nothing useful to predict about them.  */
1060         else if (integer_zerop (op0)
1061                  || integer_zerop (TREE_OPERAND (cond, 1)))
1062           ;
1063         else
1064           predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, TAKEN);
1065         break;
1066
1067       case ORDERED_EXPR:
1068         predict_edge_def (then_edge, PRED_TREE_FPOPCODE, TAKEN);
1069         break;
1070
1071       case UNORDERED_EXPR:
1072         predict_edge_def (then_edge, PRED_TREE_FPOPCODE, NOT_TAKEN);
1073         break;
1074
1075       case LE_EXPR:
1076       case LT_EXPR:
1077         if (integer_zerop (TREE_OPERAND (cond, 1))
1078             || integer_onep (TREE_OPERAND (cond, 1))
1079             || integer_all_onesp (TREE_OPERAND (cond, 1))
1080             || real_zerop (TREE_OPERAND (cond, 1))
1081             || real_onep (TREE_OPERAND (cond, 1))
1082             || real_minus_onep (TREE_OPERAND (cond, 1)))
1083           predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, NOT_TAKEN);
1084         break;
1085
1086       case GE_EXPR:
1087       case GT_EXPR:
1088         if (integer_zerop (TREE_OPERAND (cond, 1))
1089             || integer_onep (TREE_OPERAND (cond, 1))
1090             || integer_all_onesp (TREE_OPERAND (cond, 1))
1091             || real_zerop (TREE_OPERAND (cond, 1))
1092             || real_onep (TREE_OPERAND (cond, 1))
1093             || real_minus_onep (TREE_OPERAND (cond, 1)))
1094           predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, TAKEN);
1095         break;
1096
1097       default:
1098         break;
1099       }
1100 }
1101
1102 /* Try to guess whether the value of return means error code.  */
1103 static enum br_predictor
1104 return_prediction (tree val, enum prediction *prediction)
1105 {
1106   /* VOID.  */
1107   if (!val)
1108     return PRED_NO_PREDICTION;
1109   /* Different heuristics for pointers and scalars.  */
1110   if (POINTER_TYPE_P (TREE_TYPE (val)))
1111     {
1112       /* NULL is usually not returned.  */
1113       if (integer_zerop (val))
1114         {
1115           *prediction = NOT_TAKEN;
1116           return PRED_NULL_RETURN;
1117         }
1118     }
1119   else if (INTEGRAL_TYPE_P (TREE_TYPE (val)))
1120     {
1121       /* Negative return values are often used to indicate
1122          errors.  */
1123       if (TREE_CODE (val) == INTEGER_CST
1124           && tree_int_cst_sgn (val) < 0)
1125         {
1126           *prediction = NOT_TAKEN;
1127           return PRED_NEGATIVE_RETURN;
1128         }
1129       /* Constant return values seems to be commonly taken.
1130          Zero/one often represent booleans so exclude them from the
1131          heuristics.  */
1132       if (TREE_CONSTANT (val)
1133           && (!integer_zerop (val) && !integer_onep (val)))
1134         {
1135           *prediction = TAKEN;
1136           return PRED_NEGATIVE_RETURN;
1137         }
1138     }
1139   return PRED_NO_PREDICTION;
1140 }
1141
1142 /* Find the basic block with return expression and look up for possible
1143    return value trying to apply RETURN_PREDICTION heuristics.  */
1144 static void
1145 apply_return_prediction (int *heads)
1146 {
1147   tree return_stmt = NULL;
1148   tree return_val;
1149   edge e;
1150   tree phi;
1151   int phi_num_args, i;
1152   enum br_predictor pred;
1153   enum prediction direction;
1154   edge_iterator ei;
1155
1156   FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
1157     {
1158       return_stmt = last_stmt (e->src);
1159       if (TREE_CODE (return_stmt) == RETURN_EXPR)
1160         break;
1161     }
1162   if (!e)
1163     return;
1164   return_val = TREE_OPERAND (return_stmt, 0);
1165   if (!return_val)
1166     return;
1167   if (TREE_CODE (return_val) == GIMPLE_MODIFY_STMT)
1168     return_val = GIMPLE_STMT_OPERAND (return_val, 1);
1169   if (TREE_CODE (return_val) != SSA_NAME
1170       || !SSA_NAME_DEF_STMT (return_val)
1171       || TREE_CODE (SSA_NAME_DEF_STMT (return_val)) != PHI_NODE)
1172     return;
1173   for (phi = SSA_NAME_DEF_STMT (return_val); phi; phi = PHI_CHAIN (phi))
1174     if (PHI_RESULT (phi) == return_val)
1175       break;
1176   if (!phi)
1177     return;
1178   phi_num_args = PHI_NUM_ARGS (phi);
1179   pred = return_prediction (PHI_ARG_DEF (phi, 0), &direction);
1180
1181   /* Avoid the degenerate case where all return values form the function
1182      belongs to same category (ie they are all positive constants)
1183      so we can hardly say something about them.  */
1184   for (i = 1; i < phi_num_args; i++)
1185     if (pred != return_prediction (PHI_ARG_DEF (phi, i), &direction))
1186       break;
1187   if (i != phi_num_args)
1188     for (i = 0; i < phi_num_args; i++)
1189       {
1190         pred = return_prediction (PHI_ARG_DEF (phi, i), &direction);
1191         if (pred != PRED_NO_PREDICTION)
1192           predict_paths_leading_to (PHI_ARG_EDGE (phi, i)->src, heads, pred,
1193                                     direction);
1194       }
1195 }
1196
1197 /* Look for basic block that contains unlikely to happen events
1198    (such as noreturn calls) and mark all paths leading to execution
1199    of this basic blocks as unlikely.  */
1200
1201 static void
1202 tree_bb_level_predictions (void)
1203 {
1204   basic_block bb;
1205   int *heads;
1206
1207   heads = XCNEWVEC (int, last_basic_block);
1208   heads[ENTRY_BLOCK_PTR->next_bb->index] = last_basic_block;
1209
1210   apply_return_prediction (heads);
1211
1212   FOR_EACH_BB (bb)
1213     {
1214       block_stmt_iterator bsi = bsi_last (bb);
1215
1216       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1217         {
1218           tree stmt = bsi_stmt (bsi);
1219           switch (TREE_CODE (stmt))
1220             {
1221               case GIMPLE_MODIFY_STMT:
1222                 if (TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 1)) == CALL_EXPR)
1223                   {
1224                     stmt = GIMPLE_STMT_OPERAND (stmt, 1);
1225                     goto call_expr;
1226                   }
1227                 break;
1228               case CALL_EXPR:
1229 call_expr:;
1230                 if (call_expr_flags (stmt) & ECF_NORETURN)
1231                   predict_paths_leading_to (bb, heads, PRED_NORETURN,
1232                                             NOT_TAKEN);
1233                 break;
1234               default:
1235                 break;
1236             }
1237         }
1238     }
1239
1240   free (heads);
1241 }
1242
1243 /* Predict branch probabilities and estimate profile of the tree CFG.  */
1244 static unsigned int
1245 tree_estimate_probability (void)
1246 {
1247   basic_block bb;
1248
1249   loop_optimizer_init (0);
1250   if (current_loops && dump_file && (dump_flags & TDF_DETAILS))
1251     flow_loops_dump (dump_file, NULL, 0);
1252
1253   add_noreturn_fake_exit_edges ();
1254   connect_infinite_loops_to_exit ();
1255   calculate_dominance_info (CDI_DOMINATORS);
1256   calculate_dominance_info (CDI_POST_DOMINATORS);
1257
1258   tree_bb_level_predictions ();
1259
1260   mark_irreducible_loops ();
1261   if (current_loops)
1262     predict_loops ();
1263
1264   FOR_EACH_BB (bb)
1265     {
1266       edge e;
1267       edge_iterator ei;
1268
1269       FOR_EACH_EDGE (e, ei, bb->succs)
1270         {
1271           /* Predict early returns to be probable, as we've already taken
1272              care for error returns and other cases are often used for
1273              fast paths through function.  */
1274           if (e->dest == EXIT_BLOCK_PTR
1275               && TREE_CODE (last_stmt (bb)) == RETURN_EXPR
1276               && !single_pred_p (bb))
1277             {
1278               edge e1;
1279               edge_iterator ei1;
1280
1281               FOR_EACH_EDGE (e1, ei1, bb->preds)
1282                 if (!predicted_by_p (e1->src, PRED_NULL_RETURN)
1283                     && !predicted_by_p (e1->src, PRED_CONST_RETURN)
1284                     && !predicted_by_p (e1->src, PRED_NEGATIVE_RETURN)
1285                     && !last_basic_block_p (e1->src))
1286                   predict_edge_def (e1, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
1287             }
1288
1289           /* Look for block we are guarding (ie we dominate it,
1290              but it doesn't postdominate us).  */
1291           if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
1292               && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
1293               && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
1294             {
1295               block_stmt_iterator bi;
1296
1297               /* The call heuristic claims that a guarded function call
1298                  is improbable.  This is because such calls are often used
1299                  to signal exceptional situations such as printing error
1300                  messages.  */
1301               for (bi = bsi_start (e->dest); !bsi_end_p (bi);
1302                    bsi_next (&bi))
1303                 {
1304                   tree stmt = bsi_stmt (bi);
1305                   if ((TREE_CODE (stmt) == CALL_EXPR
1306                        || (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
1307                            && TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 1))
1308                               == CALL_EXPR))
1309                       /* Constant and pure calls are hardly used to signalize
1310                          something exceptional.  */
1311                       && TREE_SIDE_EFFECTS (stmt))
1312                     {
1313                       predict_edge_def (e, PRED_CALL, NOT_TAKEN);
1314                       break;
1315                     }
1316                 }
1317             }
1318         }
1319       tree_predict_by_opcode (bb);
1320     }
1321   FOR_EACH_BB (bb)
1322     combine_predictions_for_bb (bb);
1323
1324   strip_builtin_expect ();
1325   estimate_bb_frequencies ();
1326   free_dominance_info (CDI_POST_DOMINATORS);
1327   remove_fake_exit_edges ();
1328   loop_optimizer_finalize ();
1329   if (dump_file && (dump_flags & TDF_DETAILS))
1330     dump_tree_cfg (dump_file, dump_flags);
1331   if (profile_status == PROFILE_ABSENT)
1332     profile_status = PROFILE_GUESSED;
1333   return 0;
1334 }
1335 \f
1336 /* Check whether this is the last basic block of function.  Commonly
1337    there is one extra common cleanup block.  */
1338 static bool
1339 last_basic_block_p (basic_block bb)
1340 {
1341   if (bb == EXIT_BLOCK_PTR)
1342     return false;
1343
1344   return (bb->next_bb == EXIT_BLOCK_PTR
1345           || (bb->next_bb->next_bb == EXIT_BLOCK_PTR
1346               && single_succ_p (bb)
1347               && single_succ (bb)->next_bb == EXIT_BLOCK_PTR));
1348 }
1349
1350 /* Sets branch probabilities according to PREDiction and
1351    FLAGS. HEADS[bb->index] should be index of basic block in that we
1352    need to alter branch predictions (i.e. the first of our dominators
1353    such that we do not post-dominate it) (but we fill this information
1354    on demand, so -1 may be there in case this was not needed yet).  */
1355
1356 static void
1357 predict_paths_leading_to (basic_block bb, int *heads, enum br_predictor pred,
1358                           enum prediction taken)
1359 {
1360   edge e;
1361   edge_iterator ei;
1362   int y;
1363
1364   if (heads[bb->index] == ENTRY_BLOCK)
1365     {
1366       /* This is first time we need this field in heads array; so
1367          find first dominator that we do not post-dominate (we are
1368          using already known members of heads array).  */
1369       basic_block ai = bb;
1370       basic_block next_ai = get_immediate_dominator (CDI_DOMINATORS, bb);
1371       int head;
1372
1373       while (heads[next_ai->index] == ENTRY_BLOCK)
1374         {
1375           if (!dominated_by_p (CDI_POST_DOMINATORS, next_ai, bb))
1376             break;
1377           heads[next_ai->index] = ai->index;
1378           ai = next_ai;
1379           next_ai = get_immediate_dominator (CDI_DOMINATORS, next_ai);
1380         }
1381       if (!dominated_by_p (CDI_POST_DOMINATORS, next_ai, bb))
1382         head = next_ai->index;
1383       else
1384         head = heads[next_ai->index];
1385       while (next_ai != bb)
1386         {
1387           next_ai = ai;
1388           ai = BASIC_BLOCK (heads[ai->index]);
1389           heads[next_ai->index] = head;
1390         }
1391     }
1392   y = heads[bb->index];
1393
1394   /* Now find the edge that leads to our branch and aply the prediction.  */
1395
1396   if (y == last_basic_block)
1397     return;
1398   FOR_EACH_EDGE (e, ei, BASIC_BLOCK (y)->succs)
1399     if (e->dest->index >= NUM_FIXED_BLOCKS
1400         && dominated_by_p (CDI_POST_DOMINATORS, e->dest, bb))
1401       predict_edge_def (e, pred, taken);
1402 }
1403 \f
1404 /* This is used to carry information about basic blocks.  It is
1405    attached to the AUX field of the standard CFG block.  */
1406
1407 typedef struct block_info_def
1408 {
1409   /* Estimated frequency of execution of basic_block.  */
1410   sreal frequency;
1411
1412   /* To keep queue of basic blocks to process.  */
1413   basic_block next;
1414
1415   /* Number of predecessors we need to visit first.  */
1416   int npredecessors;
1417 } *block_info;
1418
1419 /* Similar information for edges.  */
1420 typedef struct edge_info_def
1421 {
1422   /* In case edge is a loopback edge, the probability edge will be reached
1423      in case header is.  Estimated number of iterations of the loop can be
1424      then computed as 1 / (1 - back_edge_prob).  */
1425   sreal back_edge_prob;
1426   /* True if the edge is a loopback edge in the natural loop.  */
1427   unsigned int back_edge:1;
1428 } *edge_info;
1429
1430 #define BLOCK_INFO(B)   ((block_info) (B)->aux)
1431 #define EDGE_INFO(E)    ((edge_info) (E)->aux)
1432
1433 /* Helper function for estimate_bb_frequencies.
1434    Propagate the frequencies in blocks marked in
1435    TOVISIT, starting in HEAD.  */
1436
1437 static void
1438 propagate_freq (basic_block head, bitmap tovisit)
1439 {
1440   basic_block bb;
1441   basic_block last;
1442   unsigned i;
1443   edge e;
1444   basic_block nextbb;
1445   bitmap_iterator bi;
1446
1447   /* For each basic block we need to visit count number of his predecessors
1448      we need to visit first.  */
1449   EXECUTE_IF_SET_IN_BITMAP (tovisit, 0, i, bi)
1450     {
1451       edge_iterator ei;
1452       int count = 0;
1453
1454        /* The outermost "loop" includes the exit block, which we can not
1455           look up via BASIC_BLOCK.  Detect this and use EXIT_BLOCK_PTR
1456           directly.  Do the same for the entry block.  */
1457       bb = BASIC_BLOCK (i);
1458
1459       FOR_EACH_EDGE (e, ei, bb->preds)
1460         {
1461           bool visit = bitmap_bit_p (tovisit, e->src->index);
1462
1463           if (visit && !(e->flags & EDGE_DFS_BACK))
1464             count++;
1465           else if (visit && dump_file && !EDGE_INFO (e)->back_edge)
1466             fprintf (dump_file,
1467                      "Irreducible region hit, ignoring edge to %i->%i\n",
1468                      e->src->index, bb->index);
1469         }
1470       BLOCK_INFO (bb)->npredecessors = count;
1471     }
1472
1473   memcpy (&BLOCK_INFO (head)->frequency, &real_one, sizeof (real_one));
1474   last = head;
1475   for (bb = head; bb; bb = nextbb)
1476     {
1477       edge_iterator ei;
1478       sreal cyclic_probability, frequency;
1479
1480       memcpy (&cyclic_probability, &real_zero, sizeof (real_zero));
1481       memcpy (&frequency, &real_zero, sizeof (real_zero));
1482
1483       nextbb = BLOCK_INFO (bb)->next;
1484       BLOCK_INFO (bb)->next = NULL;
1485
1486       /* Compute frequency of basic block.  */
1487       if (bb != head)
1488         {
1489 #ifdef ENABLE_CHECKING
1490           FOR_EACH_EDGE (e, ei, bb->preds)
1491             gcc_assert (!bitmap_bit_p (tovisit, e->src->index)
1492                         || (e->flags & EDGE_DFS_BACK));
1493 #endif
1494
1495           FOR_EACH_EDGE (e, ei, bb->preds)
1496             if (EDGE_INFO (e)->back_edge)
1497               {
1498                 sreal_add (&cyclic_probability, &cyclic_probability,
1499                            &EDGE_INFO (e)->back_edge_prob);
1500               }
1501             else if (!(e->flags & EDGE_DFS_BACK))
1502               {
1503                 sreal tmp;
1504
1505                 /*  frequency += (e->probability
1506                                   * BLOCK_INFO (e->src)->frequency /
1507                                   REG_BR_PROB_BASE);  */
1508
1509                 sreal_init (&tmp, e->probability, 0);
1510                 sreal_mul (&tmp, &tmp, &BLOCK_INFO (e->src)->frequency);
1511                 sreal_mul (&tmp, &tmp, &real_inv_br_prob_base);
1512                 sreal_add (&frequency, &frequency, &tmp);
1513               }
1514
1515           if (sreal_compare (&cyclic_probability, &real_zero) == 0)
1516             {
1517               memcpy (&BLOCK_INFO (bb)->frequency, &frequency,
1518                       sizeof (frequency));
1519             }
1520           else
1521             {
1522               if (sreal_compare (&cyclic_probability, &real_almost_one) > 0)
1523                 {
1524                   memcpy (&cyclic_probability, &real_almost_one,
1525                           sizeof (real_almost_one));
1526                 }
1527
1528               /* BLOCK_INFO (bb)->frequency = frequency
1529                                               / (1 - cyclic_probability) */
1530
1531               sreal_sub (&cyclic_probability, &real_one, &cyclic_probability);
1532               sreal_div (&BLOCK_INFO (bb)->frequency,
1533                          &frequency, &cyclic_probability);
1534             }
1535         }
1536
1537       bitmap_clear_bit (tovisit, bb->index);
1538
1539       e = find_edge (bb, head);
1540       if (e)
1541         {
1542           sreal tmp;
1543             
1544           /* EDGE_INFO (e)->back_edge_prob
1545              = ((e->probability * BLOCK_INFO (bb)->frequency)
1546              / REG_BR_PROB_BASE); */
1547             
1548           sreal_init (&tmp, e->probability, 0);
1549           sreal_mul (&tmp, &tmp, &BLOCK_INFO (bb)->frequency);
1550           sreal_mul (&EDGE_INFO (e)->back_edge_prob,
1551                      &tmp, &real_inv_br_prob_base);
1552         }
1553
1554       /* Propagate to successor blocks.  */
1555       FOR_EACH_EDGE (e, ei, bb->succs)
1556         if (!(e->flags & EDGE_DFS_BACK)
1557             && BLOCK_INFO (e->dest)->npredecessors)
1558           {
1559             BLOCK_INFO (e->dest)->npredecessors--;
1560             if (!BLOCK_INFO (e->dest)->npredecessors)
1561               {
1562                 if (!nextbb)
1563                   nextbb = e->dest;
1564                 else
1565                   BLOCK_INFO (last)->next = e->dest;
1566                 
1567                 last = e->dest;
1568               }
1569           }
1570     }
1571 }
1572
1573 /* Estimate probabilities of loopback edges in loops at same nest level.  */
1574
1575 static void
1576 estimate_loops_at_level (struct loop *first_loop)
1577 {
1578   struct loop *loop;
1579
1580   for (loop = first_loop; loop; loop = loop->next)
1581     {
1582       edge e;
1583       basic_block *bbs;
1584       unsigned i;
1585       bitmap tovisit = BITMAP_ALLOC (NULL);
1586
1587       estimate_loops_at_level (loop->inner);
1588
1589       /* Find current loop back edge and mark it.  */
1590       e = loop_latch_edge (loop);
1591       EDGE_INFO (e)->back_edge = 1;
1592
1593       bbs = get_loop_body (loop);
1594       for (i = 0; i < loop->num_nodes; i++)
1595         bitmap_set_bit (tovisit, bbs[i]->index);
1596       free (bbs);
1597       propagate_freq (loop->header, tovisit);
1598       BITMAP_FREE (tovisit);
1599     }
1600 }
1601
1602 /* Propagates frequencies through structure of loops.  */
1603
1604 static void
1605 estimate_loops (void)
1606 {
1607   bitmap tovisit = BITMAP_ALLOC (NULL);
1608   basic_block bb;
1609
1610   /* Start by estimating the frequencies in the loops.  */
1611   if (current_loops)
1612     estimate_loops_at_level (current_loops->tree_root->inner);
1613
1614   /* Now propagate the frequencies through all the blocks.  */
1615   FOR_ALL_BB (bb)
1616     {
1617       bitmap_set_bit (tovisit, bb->index);
1618     }
1619   propagate_freq (ENTRY_BLOCK_PTR, tovisit);
1620   BITMAP_FREE (tovisit);
1621 }
1622
1623 /* Convert counts measured by profile driven feedback to frequencies.
1624    Return nonzero iff there was any nonzero execution count.  */
1625
1626 int
1627 counts_to_freqs (void)
1628 {
1629   gcov_type count_max, true_count_max = 0;
1630   basic_block bb;
1631
1632   FOR_EACH_BB (bb)
1633     true_count_max = MAX (bb->count, true_count_max);
1634
1635   count_max = MAX (true_count_max, 1);
1636   FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1637     bb->frequency = (bb->count * BB_FREQ_MAX + count_max / 2) / count_max;
1638
1639   return true_count_max;
1640 }
1641
1642 /* Return true if function is likely to be expensive, so there is no point to
1643    optimize performance of prologue, epilogue or do inlining at the expense
1644    of code size growth.  THRESHOLD is the limit of number of instructions
1645    function can execute at average to be still considered not expensive.  */
1646
1647 bool
1648 expensive_function_p (int threshold)
1649 {
1650   unsigned int sum = 0;
1651   basic_block bb;
1652   unsigned int limit;
1653
1654   /* We can not compute accurately for large thresholds due to scaled
1655      frequencies.  */
1656   gcc_assert (threshold <= BB_FREQ_MAX);
1657
1658   /* Frequencies are out of range.  This either means that function contains
1659      internal loop executing more than BB_FREQ_MAX times or profile feedback
1660      is available and function has not been executed at all.  */
1661   if (ENTRY_BLOCK_PTR->frequency == 0)
1662     return true;
1663
1664   /* Maximally BB_FREQ_MAX^2 so overflow won't happen.  */
1665   limit = ENTRY_BLOCK_PTR->frequency * threshold;
1666   FOR_EACH_BB (bb)
1667     {
1668       rtx insn;
1669
1670       for (insn = BB_HEAD (bb); insn != NEXT_INSN (BB_END (bb));
1671            insn = NEXT_INSN (insn))
1672         if (active_insn_p (insn))
1673           {
1674             sum += bb->frequency;
1675             if (sum > limit)
1676               return true;
1677         }
1678     }
1679
1680   return false;
1681 }
1682
1683 /* Estimate basic blocks frequency by given branch probabilities.  */
1684
1685 void
1686 estimate_bb_frequencies (void)
1687 {
1688   basic_block bb;
1689   sreal freq_max;
1690
1691   if (!flag_branch_probabilities || !counts_to_freqs ())
1692     {
1693       static int real_values_initialized = 0;
1694
1695       if (!real_values_initialized)
1696         {
1697           real_values_initialized = 1;
1698           sreal_init (&real_zero, 0, 0);
1699           sreal_init (&real_one, 1, 0);
1700           sreal_init (&real_br_prob_base, REG_BR_PROB_BASE, 0);
1701           sreal_init (&real_bb_freq_max, BB_FREQ_MAX, 0);
1702           sreal_init (&real_one_half, 1, -1);
1703           sreal_div (&real_inv_br_prob_base, &real_one, &real_br_prob_base);
1704           sreal_sub (&real_almost_one, &real_one, &real_inv_br_prob_base);
1705         }
1706
1707       mark_dfs_back_edges ();
1708
1709       single_succ_edge (ENTRY_BLOCK_PTR)->probability = REG_BR_PROB_BASE;
1710
1711       /* Set up block info for each basic block.  */
1712       alloc_aux_for_blocks (sizeof (struct block_info_def));
1713       alloc_aux_for_edges (sizeof (struct edge_info_def));
1714       FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1715         {
1716           edge e;
1717           edge_iterator ei;
1718
1719           FOR_EACH_EDGE (e, ei, bb->succs)
1720             {
1721               sreal_init (&EDGE_INFO (e)->back_edge_prob, e->probability, 0);
1722               sreal_mul (&EDGE_INFO (e)->back_edge_prob,
1723                          &EDGE_INFO (e)->back_edge_prob,
1724                          &real_inv_br_prob_base);
1725             }
1726         }
1727
1728       /* First compute probabilities locally for each loop from innermost
1729          to outermost to examine probabilities for back edges.  */
1730       estimate_loops ();
1731
1732       memcpy (&freq_max, &real_zero, sizeof (real_zero));
1733       FOR_EACH_BB (bb)
1734         if (sreal_compare (&freq_max, &BLOCK_INFO (bb)->frequency) < 0)
1735           memcpy (&freq_max, &BLOCK_INFO (bb)->frequency, sizeof (freq_max));
1736
1737       sreal_div (&freq_max, &real_bb_freq_max, &freq_max);
1738       FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1739         {
1740           sreal tmp;
1741
1742           sreal_mul (&tmp, &BLOCK_INFO (bb)->frequency, &freq_max);
1743           sreal_add (&tmp, &tmp, &real_one_half);
1744           bb->frequency = sreal_to_int (&tmp);
1745         }
1746
1747       free_aux_for_blocks ();
1748       free_aux_for_edges ();
1749     }
1750   compute_function_frequency ();
1751   if (flag_reorder_functions)
1752     choose_function_section ();
1753 }
1754
1755 /* Decide whether function is hot, cold or unlikely executed.  */
1756 static void
1757 compute_function_frequency (void)
1758 {
1759   basic_block bb;
1760
1761   if (!profile_info || !flag_branch_probabilities)
1762     return;
1763   cfun->function_frequency = FUNCTION_FREQUENCY_UNLIKELY_EXECUTED;
1764   FOR_EACH_BB (bb)
1765     {
1766       if (maybe_hot_bb_p (bb))
1767         {
1768           cfun->function_frequency = FUNCTION_FREQUENCY_HOT;
1769           return;
1770         }
1771       if (!probably_never_executed_bb_p (bb))
1772         cfun->function_frequency = FUNCTION_FREQUENCY_NORMAL;
1773     }
1774 }
1775
1776 /* Choose appropriate section for the function.  */
1777 static void
1778 choose_function_section (void)
1779 {
1780   if (DECL_SECTION_NAME (current_function_decl)
1781       || !targetm.have_named_sections
1782       /* Theoretically we can split the gnu.linkonce text section too,
1783          but this requires more work as the frequency needs to match
1784          for all generated objects so we need to merge the frequency
1785          of all instances.  For now just never set frequency for these.  */
1786       || DECL_ONE_ONLY (current_function_decl))
1787     return;
1788
1789   /* If we are doing the partitioning optimization, let the optimization
1790      choose the correct section into which to put things.  */
1791
1792   if (flag_reorder_blocks_and_partition)
1793     return;
1794
1795   if (cfun->function_frequency == FUNCTION_FREQUENCY_HOT)
1796     DECL_SECTION_NAME (current_function_decl) =
1797       build_string (strlen (HOT_TEXT_SECTION_NAME), HOT_TEXT_SECTION_NAME);
1798   if (cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
1799     DECL_SECTION_NAME (current_function_decl) =
1800       build_string (strlen (UNLIKELY_EXECUTED_TEXT_SECTION_NAME),
1801                     UNLIKELY_EXECUTED_TEXT_SECTION_NAME);
1802 }
1803
1804 static bool
1805 gate_estimate_probability (void)
1806 {
1807   return flag_guess_branch_prob;
1808 }
1809
1810 struct tree_opt_pass pass_profile = 
1811 {
1812   "profile",                            /* name */
1813   gate_estimate_probability,            /* gate */
1814   tree_estimate_probability,            /* execute */
1815   NULL,                                 /* sub */
1816   NULL,                                 /* next */
1817   0,                                    /* static_pass_number */
1818   TV_BRANCH_PROB,                       /* tv_id */
1819   PROP_cfg,                             /* properties_required */
1820   0,                                    /* properties_provided */
1821   0,                                    /* properties_destroyed */
1822   0,                                    /* todo_flags_start */
1823   TODO_ggc_collect | TODO_verify_ssa,                   /* todo_flags_finish */
1824   0                                     /* letter */
1825 };