OSDN Git Service

e51128264dbef9cd31aa0e3f6f8d05ee01a7fa12
[pf3gnuchains/gcc-fork.git] / gcc / predict.c
1 /* Branch prediction routines for the GNU compiler.
2    Copyright (C) 2000, 2001 Free Software Foundation, Inc.
3
4    This file is part of GNU CC.
5
6    GNU CC is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    GNU CC is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with GNU CC; see the file COPYING.  If not, write to
18    the Free Software Foundation, 59 Temple Place - Suite 330,
19    Boston, MA 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
32
33 #include "config.h"
34 #include "system.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
51 /* Random guesstimation given names.  */
52 #define PROB_NEVER              (0)
53 #define PROB_VERY_UNLIKELY      (REG_BR_PROB_BASE / 10 - 1)
54 #define PROB_UNLIKELY           (REG_BR_PROB_BASE * 4 / 10 - 1)
55 #define PROB_EVEN               (REG_BR_PROB_BASE / 2)
56 #define PROB_LIKELY             (REG_BR_PROB_BASE - PROB_UNLIKELY)
57 #define PROB_VERY_LIKELY        (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
58 #define PROB_ALWAYS             (REG_BR_PROB_BASE)
59
60 static void combine_predictions_for_insn PARAMS ((rtx, basic_block));
61 static void dump_prediction              PARAMS ((enum br_predictor, int,
62                                                   basic_block));
63 static void estimate_loops_at_level      PARAMS ((struct loop *loop));
64 static void propagate_freq               PARAMS ((basic_block));
65 static void estimate_bb_frequencies      PARAMS ((struct loops *));
66 static void counts_to_freqs              PARAMS ((void));
67
68 /* Information we hold about each branch predictor.
69    Filled using information from predict.def.  */
70 struct predictor_info
71 {
72   const char *name;     /* Name used in the debugging dumps.  */
73   int hitrate;          /* Expected hitrate used by
74                            predict_insn_def call.  */
75 };
76
77 #define DEF_PREDICTOR(ENUM, NAME, HITRATE) {NAME, HITRATE},
78 struct predictor_info predictor_info[] = {
79 #include "predict.def"
80
81   /* Upper bound on non-language-specific builtins. */
82   {NULL, 0}
83 };
84 #undef DEF_PREDICTOR
85
86 void
87 predict_insn (insn, predictor, probability)
88      rtx insn;
89      int probability;
90      enum br_predictor predictor;
91 {
92   if (!any_condjump_p (insn))
93     abort ();
94   REG_NOTES (insn)
95     = gen_rtx_EXPR_LIST (REG_BR_PRED,
96                          gen_rtx_CONCAT (VOIDmode,
97                                          GEN_INT ((int) predictor),
98                                          GEN_INT ((int) probability)),
99                          REG_NOTES (insn));
100 }
101
102 /* Predict insn by given predictor.  */
103 void
104 predict_insn_def (insn, predictor, taken)
105      rtx insn;
106      enum br_predictor predictor;
107      enum prediction taken;
108 {
109    int probability = predictor_info[(int) predictor].hitrate;
110    if (taken != TAKEN)
111      probability = REG_BR_PROB_BASE - probability;
112    predict_insn (insn, predictor, probability);
113 }
114
115 /* Predict edge E with given probability if possible.  */
116 void
117 predict_edge (e, predictor, probability)
118      edge e;
119      int probability;
120      enum br_predictor predictor;
121 {
122   rtx last_insn;
123   last_insn = e->src->end;
124
125   /* We can store the branch prediction information only about
126      conditional jumps.  */
127   if (!any_condjump_p (last_insn))
128     return;
129
130   /* We always store probability of branching.  */
131   if (e->flags & EDGE_FALLTHRU)
132     probability = REG_BR_PROB_BASE - probability;
133
134   predict_insn (last_insn, predictor, probability);
135 }
136
137 /* Predict edge E by given predictor if possible.  */
138 void
139 predict_edge_def (e, predictor, taken)
140      edge e;
141      enum br_predictor predictor;
142      enum prediction taken;
143 {
144    int probability = predictor_info[(int) predictor].hitrate;
145
146    if (taken != TAKEN)
147      probability = REG_BR_PROB_BASE - probability;
148    predict_edge (e, predictor, probability);
149 }
150
151 /* Invert all branch predictions or probability notes in the INSN.  This needs
152    to be done each time we invert the condition used by the jump.  */
153 void
154 invert_br_probabilities (insn)
155      rtx insn;
156 {
157   rtx note = REG_NOTES (insn);
158
159   while (note)
160     {
161       if (REG_NOTE_KIND (note) == REG_BR_PROB)
162         XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
163       else if (REG_NOTE_KIND (note) == REG_BR_PRED)
164         XEXP (XEXP (note, 0), 1)
165           = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
166       note = XEXP (note, 1);
167     }
168 }
169
170 /* Dump information about the branch prediction to the output file.  */
171 static void
172 dump_prediction (predictor, probability, bb)
173      enum br_predictor predictor;
174      int probability;
175      basic_block bb;
176 {
177   edge e = bb->succ;
178
179   if (!rtl_dump_file)
180     return;
181
182   while (e->flags & EDGE_FALLTHRU)
183     e = e->succ_next;
184
185   fprintf (rtl_dump_file, "  %s heuristics: %.1f%%",
186            predictor_info[predictor].name,
187            probability * 100.0 / REG_BR_PROB_BASE);
188
189   if (bb->count)
190     {
191       fprintf (rtl_dump_file, "  exec ",
192                bb->count, e->count, e->count * 100.0 / bb->count);
193       fprintf (rtl_dump_file, HOST_WIDEST_INT_PRINT_DEC,
194                (HOST_WIDEST_INT) bb->count);
195       fprintf (rtl_dump_file, " hit ",
196                e->count, e->count * 100.0 / bb->count);
197       fprintf (rtl_dump_file, HOST_WIDEST_INT_PRINT_DEC,
198                (HOST_WIDEST_INT) e->count);
199       fprintf (rtl_dump_file, " (%.1f%%)",
200                e->count, e->count * 100.0 / bb->count);
201     }
202   fprintf (rtl_dump_file, "\n");
203 }
204
205 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
206    note if not already present.  Remove now useless REG_BR_PRED notes.  */
207 static void
208 combine_predictions_for_insn (insn, bb)
209      rtx insn;
210      basic_block bb;
211 {
212   rtx prob_note = find_reg_note (insn, REG_BR_PROB, 0);
213   rtx *pnote = &REG_NOTES (insn);
214   int best_probability = PROB_EVEN;
215   int best_predictor = END_PREDICTORS;
216
217   if (rtl_dump_file)
218     fprintf (rtl_dump_file, "Predictions for insn %i\n", INSN_UID (insn));
219
220   /* We implement "first match" heuristics and use probability guessed
221      by predictor with smallest index.  In future we will use better
222      probability combination techniques.  */
223   while (*pnote)
224     {
225       if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
226         {
227           int predictor = INTVAL (XEXP (XEXP (*pnote, 0), 0));
228           int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
229
230           dump_prediction (predictor, probability, bb);
231           if (best_predictor > predictor)
232             best_probability = probability, best_predictor = predictor;
233           *pnote = XEXP (*pnote, 1);
234         }
235       else
236         pnote = &XEXP (*pnote, 1);
237     }
238   dump_prediction (PRED_FIRST_MATCH, best_probability, bb);
239   if (!prob_note)
240     {
241       REG_NOTES (insn)
242         = gen_rtx_EXPR_LIST (REG_BR_PROB,
243                              GEN_INT (best_probability), REG_NOTES (insn));
244     }
245 }
246
247 /* Statically estimate the probability that a branch will be taken.
248    ??? In the next revision there will be a number of other predictors added
249    from the above references. Further, each heuristic will be factored out
250    into its own function for clarity (and to facilitate the combination of
251    predictions).  */
252
253 void
254 estimate_probability (loops_info)
255      struct loops *loops_info;
256 {
257   sbitmap *dominators, *post_dominators;
258   int i;
259
260   dominators = sbitmap_vector_alloc (n_basic_blocks, n_basic_blocks);
261   post_dominators = sbitmap_vector_alloc (n_basic_blocks, n_basic_blocks);
262   calculate_dominance_info (NULL, dominators, 0);
263   calculate_dominance_info (NULL, post_dominators, 1);
264
265   /* Try to predict out blocks in a loop that are not part of a
266      natural loop.  */
267   for (i = 0; i < loops_info->num; i++)
268     {
269       int j;
270
271       for (j = loops_info->array[i].first->index;
272            j <= loops_info->array[i].last->index;
273            ++j)
274         {
275           if (TEST_BIT (loops_info->array[i].nodes, j))
276             {
277               int header_found = 0;
278               edge e;
279           
280               /* Loop branch heruistics - predict as taken an edge back to
281                  a loop's head.  */
282               for (e = BASIC_BLOCK(j)->succ; e; e = e->succ_next)
283                 if (e->dest == loops_info->array[i].header)
284                   {
285                     header_found = 1;
286                     predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
287                   }
288               /* Loop exit heruistics - predict as not taken an edge exiting
289                  the loop if the conditinal has no loop header successors  */
290               if (!header_found)
291                 for (e = BASIC_BLOCK(j)->succ; e; e = e->succ_next)
292                   if (e->dest->index <= 0
293                       || !TEST_BIT (loops_info->array[i].nodes, e->dest->index))
294                     predict_edge_def (e, PRED_LOOP_EXIT, NOT_TAKEN);
295             }
296         }
297     }
298
299   /* Attempt to predict conditional jumps using a number of heuristics.
300      For each conditional jump, we try each heuristic in a fixed order.
301      If more than one heuristic applies to a particular branch, the first
302      is used as the prediction for the branch.  */
303   for (i = 0; i < n_basic_blocks; i++)
304     {
305       basic_block bb = BASIC_BLOCK (i);
306       rtx last_insn = bb->end;
307       rtx cond, earliest;
308       edge e;
309
310       /* If block has no sucessor, predict all possible paths to
311          it as improbable, as the block contains a call to a noreturn
312          function and thus can be executed only once.  */
313       if (bb->succ == NULL)
314         {
315           int y;
316           for (y = 0; y < n_basic_blocks; y++)
317             if (!TEST_BIT (post_dominators[y], i))
318               {
319                 for (e = BASIC_BLOCK (y)->succ; e; e = e->succ_next)
320                 if (e->dest->index >= 0
321                     && TEST_BIT (post_dominators[e->dest->index], i))
322                   predict_edge_def (e, PRED_NORETURN, NOT_TAKEN);
323               }
324         }
325
326       if (GET_CODE (last_insn) != JUMP_INSN
327           || ! any_condjump_p (last_insn))
328         continue;
329
330       for (e = bb->succ; e; e = e->succ_next)
331         {
332           /* Predict edges to blocks that return immediately to be
333              improbable.  These are usually used to signal error states.  */
334           if (e->dest == EXIT_BLOCK_PTR
335               || (e->dest->succ && !e->dest->succ->succ_next
336                   && e->dest->succ->dest == EXIT_BLOCK_PTR))
337             predict_edge_def (e, PRED_ERROR_RETURN, NOT_TAKEN);
338
339           /* Look for block we are guarding (ie we dominate it,
340              but it doesn't postdominate us).  */
341           if (e->dest != EXIT_BLOCK_PTR
342               && e->dest != bb
343               && TEST_BIT (dominators[e->dest->index], e->src->index)
344               && !TEST_BIT (post_dominators[e->src->index], e->dest->index))
345             {
346               rtx insn;
347               /* The call heuristic claims that a guarded function call
348                  is improbable.  This is because such calls are often used
349                  to signal exceptional situations such as printing error
350                  messages.  */
351               for (insn = e->dest->head; insn != NEXT_INSN (e->dest->end);
352                    insn = NEXT_INSN (insn))
353                 if (GET_CODE (insn) == CALL_INSN
354                     /* Constant and pure calls are hardly used to signalize
355                        something exceptional.  */
356                     && ! CONST_CALL_P (insn))
357                   {
358                     predict_edge_def (e, PRED_CALL, NOT_TAKEN);
359                     break;
360                   }
361             }
362         }
363
364       cond = get_condition (last_insn, &earliest);
365       if (! cond)
366         continue;
367
368       /* Try "pointer heuristic."
369          A comparison ptr == 0 is predicted as false.
370          Similarly, a comparison ptr1 == ptr2 is predicted as false.  */
371       switch (GET_CODE (cond))
372         {
373         case EQ:
374           if (GET_CODE (XEXP (cond, 0)) == REG
375               && REG_POINTER (XEXP (cond, 0))
376               && (XEXP (cond, 1) == const0_rtx
377                   || (GET_CODE (XEXP (cond, 1)) == REG
378                       && REG_POINTER (XEXP (cond, 1)))))
379             
380             predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
381           break;
382         case NE:
383           if (GET_CODE (XEXP (cond, 0)) == REG
384               && REG_POINTER (XEXP (cond, 0))
385               && (XEXP (cond, 1) == const0_rtx
386                   || (GET_CODE (XEXP (cond, 1)) == REG
387                       && REG_POINTER (XEXP (cond, 1)))))
388             predict_insn_def (last_insn, PRED_POINTER, TAKEN);
389           break;
390
391         default:
392           break;
393         }
394
395       /* Try "opcode heuristic."
396          EQ tests are usually false and NE tests are usually true. Also,
397          most quantities are positive, so we can make the appropriate guesses
398          about signed comparisons against zero.  */
399       switch (GET_CODE (cond))
400         {
401         case CONST_INT:
402           /* Unconditional branch.  */
403           predict_insn_def (last_insn, PRED_UNCONDITIONAL,
404                             cond == const0_rtx ? NOT_TAKEN : TAKEN);
405           break;
406
407         case EQ:
408         case UNEQ:
409           predict_insn_def (last_insn, PRED_OPCODE, NOT_TAKEN);
410           break;
411         case NE:
412         case LTGT:
413           predict_insn_def (last_insn, PRED_OPCODE, TAKEN);
414           break;
415         case ORDERED:
416           predict_insn_def (last_insn, PRED_OPCODE, TAKEN);
417           break;
418         case UNORDERED:
419           predict_insn_def (last_insn, PRED_OPCODE, NOT_TAKEN);
420           break;
421         case LE:
422         case LT:
423           if (XEXP (cond, 1) == const0_rtx
424               || (GET_CODE (XEXP (cond, 1)) == CONST_INT
425                   && INTVAL (XEXP (cond, 1)) == -1))
426             predict_insn_def (last_insn, PRED_OPCODE, NOT_TAKEN);
427           break;
428         case GE:
429         case GT:
430           if (XEXP (cond, 1) == const0_rtx
431               || (GET_CODE (XEXP (cond, 1)) == CONST_INT
432                   && INTVAL (XEXP (cond, 1)) == -1))
433             predict_insn_def (last_insn, PRED_OPCODE, TAKEN);
434           break;
435
436         default:
437           break;
438         }
439     }
440
441   /* Attach the combined probability to each conditional jump.  */
442   for (i = 0; i < n_basic_blocks; i++)
443     {
444       rtx last_insn = BLOCK_END (i);
445
446       if (GET_CODE (last_insn) != JUMP_INSN
447           || ! any_condjump_p (last_insn))
448         continue;
449       combine_predictions_for_insn (last_insn, BASIC_BLOCK (i));
450     }
451   sbitmap_vector_free (post_dominators);
452   sbitmap_vector_free (dominators);
453
454   estimate_bb_frequencies (loops_info);
455 }
456 \f
457 /* __builtin_expect dropped tokens into the insn stream describing
458    expected values of registers.  Generate branch probabilities 
459    based off these values.  */
460
461 void
462 expected_value_to_br_prob ()
463 {
464   rtx insn, cond, ev = NULL_RTX, ev_reg = NULL_RTX;
465
466   for (insn = get_insns (); insn ; insn = NEXT_INSN (insn))
467     {
468       switch (GET_CODE (insn))
469         {
470         case NOTE:
471           /* Look for expected value notes.  */
472           if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_EXPECTED_VALUE)
473             {
474               ev = NOTE_EXPECTED_VALUE (insn);
475               ev_reg = XEXP (ev, 0);
476             }
477           continue;
478
479         case CODE_LABEL:
480           /* Never propagate across labels.  */
481           ev = NULL_RTX;
482           continue;
483
484         default:
485           /* Look for insns that clobber the EV register.  */
486           if (ev && reg_set_p (ev_reg, insn))
487             ev = NULL_RTX;
488           continue;
489
490         case JUMP_INSN:
491           /* Look for simple conditional branches.  If we havn't got an
492              expected value yet, no point going further.  */
493           if (GET_CODE (insn) != JUMP_INSN || ev == NULL_RTX)
494             continue;
495           if (! any_condjump_p (insn))
496             continue;
497           break;
498         }
499
500       /* Collect the branch condition, hopefully relative to EV_REG.  */
501       /* ???  At present we'll miss things like
502                 (expected_value (eq r70 0))
503                 (set r71 -1)
504                 (set r80 (lt r70 r71))
505                 (set pc (if_then_else (ne r80 0) ...))
506          as canonicalize_condition will render this to us as 
507                 (lt r70, r71)
508          Could use cselib to try and reduce this further.  */
509       cond = XEXP (SET_SRC (PATTERN (insn)), 0);
510       cond = canonicalize_condition (insn, cond, 0, NULL, ev_reg);
511       if (! cond
512           || XEXP (cond, 0) != ev_reg
513           || GET_CODE (XEXP (cond, 1)) != CONST_INT)
514         continue;
515
516       /* Substitute and simplify.  Given that the expression we're 
517          building involves two constants, we should wind up with either
518          true or false.  */
519       cond = gen_rtx_fmt_ee (GET_CODE (cond), VOIDmode,
520                              XEXP (ev, 1), XEXP (cond, 1));
521       cond = simplify_rtx (cond);
522
523       /* Turn the condition into a scaled branch probability.  */
524       if (cond != const1_rtx && cond != const0_rtx)
525         abort ();
526       predict_insn_def (insn, PRED_BUILTIN_EXPECT,
527                         cond == const1_rtx ? TAKEN : NOT_TAKEN);
528     }
529 }
530 \f
531 /* This is used to carry information about basic blocks.  It is 
532    attached to the AUX field of the standard CFG block.  */
533
534 typedef struct block_info_def
535 {
536   /* Estimated frequency of execution of basic_block.  */
537   double frequency;
538
539   /* To keep queue of basic blocks to process.  */
540   basic_block next;
541
542   /* True if block already converted.  */
543   int visited:1;
544 } *block_info;
545
546 /* Similar information for edges.  */
547 typedef struct edge_info_def
548 {
549   /* In case edge is an loopback edge, the probability edge will be reached
550      in case header is.  Estimated number of iterations of the loop can be
551      then computed as 1 / (1 - back_edge_prob).  */
552   double back_edge_prob;
553   /* True if the edge is an loopback edge in the natural loop.  */
554   int back_edge:1;
555 } *edge_info;
556
557 #define BLOCK_INFO(B)   ((block_info) (B)->aux)
558 #define EDGE_INFO(E)    ((edge_info) (E)->aux)
559
560 /* Helper function for estimate_bb_frequencies.
561    Propagate the frequencies for loops headed by HEAD.  */
562 static void
563 propagate_freq (head)
564      basic_block head;
565 {
566   basic_block bb = head;
567   basic_block last = bb;
568   edge e;
569   basic_block nextbb;
570
571   BLOCK_INFO (head)->frequency = 1;
572   for (; bb; bb = nextbb)
573     {
574       double cyclic_probability = 0, frequency = 0;
575
576       nextbb = BLOCK_INFO (bb)->next;
577       BLOCK_INFO (bb)->next = NULL;
578
579       /* Compute frequency of basic block.  */
580       if (bb != head)
581         {
582           for (e = bb->pred; e; e = e->pred_next)
583             if (!BLOCK_INFO (e->src)->visited && !EDGE_INFO (e)->back_edge)
584               continue;
585
586           for (e = bb->pred; e; e = e->pred_next)
587             if (EDGE_INFO (e)->back_edge)
588               cyclic_probability += EDGE_INFO (e)->back_edge_prob;
589             else
590               frequency += (e->probability
591                             * BLOCK_INFO (e->src)->frequency /
592                             REG_BR_PROB_BASE);
593
594           if (cyclic_probability > 1.0 - 1.0 / REG_BR_PROB_BASE)
595             cyclic_probability = 1.0 - 1.0 / REG_BR_PROB_BASE;
596
597           BLOCK_INFO (bb)->frequency = frequency / (1 - cyclic_probability);
598         }
599
600       BLOCK_INFO (bb)->visited = 1;
601
602       /* Compute back edge frequencies.  */
603       for (e = bb->succ; e; e = e->succ_next)
604         if (e->dest == head)
605           EDGE_INFO (e)->back_edge_prob = (e->probability
606                                            * BLOCK_INFO (bb)->frequency
607                                            / REG_BR_PROB_BASE);
608
609       /* Propagate to succesor blocks.  */
610       for (e = bb->succ; e; e = e->succ_next)
611         if (!EDGE_INFO (e)->back_edge
612             && !BLOCK_INFO (e->dest)->visited
613             && !BLOCK_INFO (e->dest)->next && e->dest != last)
614           {
615             if (!nextbb)
616               nextbb = e->dest;
617             else
618               BLOCK_INFO (last)->next = e->dest;
619             last = e->dest;
620           }
621     }
622 }
623
624 /* Estimate probabilities of the loopback edges in loops at same nest level.  */
625 static void
626 estimate_loops_at_level (first_loop)
627      struct loop *first_loop;
628 {
629   struct loop *l, *loop = first_loop;
630
631   for (loop = first_loop; loop; loop = loop->next)
632     {
633       int n;
634       edge e;
635
636       estimate_loops_at_level (loop->inner);
637
638       /* find current loop back edge and mark it.  */
639       for (e = loop->latch->succ; e->dest != loop->header; e = e->succ_next);
640
641       EDGE_INFO (e)->back_edge = 1;
642
643       /* In case loop header is shared, ensure that it is the last one sharing
644          same header, so we avoid redundant work.  */
645       if (loop->shared)
646         {
647           for (l = loop->next; l; l = l->next)
648             if (l->header == loop->header)
649               break;
650           if (l)
651             continue;
652         }
653
654       /* Now merge all nodes of all loops with given header as not visited.  */
655       for (l = loop->shared ? first_loop : loop; l != loop->next; l = l->next)
656         if (loop->header == l->header)
657           EXECUTE_IF_SET_IN_SBITMAP (l->nodes, 0, n,
658                                      BLOCK_INFO (BASIC_BLOCK (n))->visited =
659                                      0);
660       propagate_freq (loop->header);
661     }
662 }
663
664 /* Convert counts measured by profile driven feedback to frequencies.  */
665 static void
666 counts_to_freqs ()
667 {
668   HOST_WIDEST_INT count_max = 1;
669   int i;
670
671   for (i = 0; i < n_basic_blocks; i++)
672     if (BASIC_BLOCK (i)->count > count_max)
673       count_max = BASIC_BLOCK (i)->count;
674
675   for (i = -2; i < n_basic_blocks; i++)
676     {
677       basic_block bb;
678       if (i == -2)
679         bb = ENTRY_BLOCK_PTR;
680       else if (i == -1)
681         bb = EXIT_BLOCK_PTR;
682       else
683         bb = BASIC_BLOCK (i);
684       bb->frequency = ((bb->count * BB_FREQ_MAX + count_max / 2)
685                        / count_max);
686     }
687 }
688
689 /* Estimate basic blocks frequency by given branch probabilities.  */
690 static void
691 estimate_bb_frequencies (loops)
692      struct loops *loops;
693 {
694   block_info bi;
695   edge_info ei;
696   int edgenum = 0;
697   int i;
698   double freq_max = 0;
699
700   if (flag_branch_probabilities)
701     {
702       counts_to_freqs ();
703       return;
704     }
705
706   /* Fill in the probability values in flowgraph based on the REG_BR_PROB
707      notes.  */
708   for (i = 0; i < n_basic_blocks; i++)
709     {
710       rtx last_insn = BLOCK_END (i);
711       int probability;
712       edge fallthru, branch;
713
714       if (GET_CODE (last_insn) != JUMP_INSN || !any_condjump_p (last_insn)
715           /* Avoid handling of conditionals jump jumping to fallthru edge.  */
716           || BASIC_BLOCK (i)->succ->succ_next == NULL)
717         {
718           /* We can predict only conditional jumps at the moment.
719              Expect each edge to be equall probable.
720              ?? In future we want to make abnormal edges improbable.  */
721           int nedges = 0;
722           edge e;
723
724           for (e = BASIC_BLOCK (i)->succ; e; e = e->succ_next)
725             {
726               nedges++;
727               if (e->probability != 0)
728                 break;
729             }
730           if (!e)
731             for (e = BASIC_BLOCK (i)->succ; e; e = e->succ_next)
732               e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
733         }
734       else
735         {
736           probability = INTVAL (XEXP (find_reg_note (last_insn,
737                                                      REG_BR_PROB, 0), 0));
738           fallthru = BASIC_BLOCK (i)->succ;
739           if (!fallthru->flags & EDGE_FALLTHRU)
740             fallthru = fallthru->succ_next;
741           branch = BASIC_BLOCK (i)->succ;
742           if (branch->flags & EDGE_FALLTHRU)
743             branch = branch->succ_next;
744
745           branch->probability = probability;
746           fallthru->probability = REG_BR_PROB_BASE - probability;
747         }
748     }
749   ENTRY_BLOCK_PTR->succ->probability = REG_BR_PROB_BASE;
750
751   /* Set up block info for each basic block.  */
752   bi = (block_info) xcalloc ((n_basic_blocks + 2), sizeof (*bi));
753   ei = (edge_info) xcalloc ((n_edges), sizeof (*ei));
754   for (i = -2; i < n_basic_blocks; i++)
755     {
756       edge e;
757       basic_block bb;
758
759       if (i == -2)
760         bb = ENTRY_BLOCK_PTR;
761       else if (i == -1)
762         bb = EXIT_BLOCK_PTR;
763       else
764         bb = BASIC_BLOCK (i);
765       bb->aux = bi + i + 2;
766       BLOCK_INFO (bb)->visited = 1;
767       for (e = bb->succ; e; e = e->succ_next)
768         {
769           e->aux = ei + edgenum, edgenum++;
770           EDGE_INFO (e)->back_edge_prob = ((double) e->probability
771                                            / REG_BR_PROB_BASE);
772         }
773     }
774   /* First compute probabilities locally for each loop from innermost
775      to outermost to examine probabilities for back edges.  */
776   estimate_loops_at_level (loops->tree);
777
778   /* Now fake loop around whole function to finalize probabilities.  */
779   for (i = 0; i < n_basic_blocks; i++)
780     BLOCK_INFO (BASIC_BLOCK (i))->visited = 0;
781   BLOCK_INFO (ENTRY_BLOCK_PTR)->visited = 0;
782   BLOCK_INFO (EXIT_BLOCK_PTR)->visited = 0;
783   propagate_freq (ENTRY_BLOCK_PTR);
784
785   for (i = 0; i < n_basic_blocks; i++)
786     if (BLOCK_INFO (BASIC_BLOCK (i))->frequency > freq_max)
787       freq_max = BLOCK_INFO (BASIC_BLOCK (i))->frequency;
788   for (i = -2; i < n_basic_blocks; i++)
789     {
790       basic_block bb;
791       if (i == -2)
792         bb = ENTRY_BLOCK_PTR;
793       else if (i == -1)
794         bb = EXIT_BLOCK_PTR;
795       else
796         bb = BASIC_BLOCK (i);
797       bb->frequency = (BLOCK_INFO (bb)->frequency * BB_FREQ_MAX / freq_max
798                        + 0.5);
799     }
800
801   free (ei);
802   free (bi);
803 }