OSDN Git Service

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