OSDN Git Service

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