OSDN Git Service

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