OSDN Git Service

* config/mips/iris5.h (UNALIGNED_INT_ASM_OP,
[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 bb %i\n", INSN_UID (insn),
219              bb->index);
220
221   /* We implement "first match" heuristics and use probability guessed
222      by predictor with smallest index.  In future we will use better
223      probability combination techniques.  */
224   while (*pnote)
225     {
226       if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
227         {
228           int predictor = INTVAL (XEXP (XEXP (*pnote, 0), 0));
229           int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
230
231           dump_prediction (predictor, probability, bb);
232           if (best_predictor > predictor)
233             best_probability = probability, best_predictor = predictor;
234           *pnote = XEXP (*pnote, 1);
235         }
236       else
237         pnote = &XEXP (*pnote, 1);
238     }
239   dump_prediction (PRED_FIRST_MATCH, best_probability, bb);
240   if (!prob_note)
241     {
242       REG_NOTES (insn)
243         = gen_rtx_EXPR_LIST (REG_BR_PROB,
244                              GEN_INT (best_probability), REG_NOTES (insn));
245     }
246 }
247
248 /* Statically estimate the probability that a branch will be taken.
249    ??? In the next revision there will be a number of other predictors added
250    from the above references. Further, each heuristic will be factored out
251    into its own function for clarity (and to facilitate the combination of
252    predictions).  */
253
254 void
255 estimate_probability (loops_info)
256      struct loops *loops_info;
257 {
258   sbitmap *dominators, *post_dominators;
259   int i;
260
261   dominators = sbitmap_vector_alloc (n_basic_blocks, n_basic_blocks);
262   post_dominators = sbitmap_vector_alloc (n_basic_blocks, n_basic_blocks);
263   calculate_dominance_info (NULL, dominators, 0);
264   calculate_dominance_info (NULL, post_dominators, 1);
265
266   /* Try to predict out blocks in a loop that are not part of a
267      natural loop.  */
268   for (i = 0; i < loops_info->num; i++)
269     {
270       int j;
271
272       for (j = loops_info->array[i].first->index;
273            j <= loops_info->array[i].last->index;
274            ++j)
275         {
276           if (TEST_BIT (loops_info->array[i].nodes, j))
277             {
278               int header_found = 0;
279               edge e;
280           
281               /* Loop branch heruistics - predict as taken an edge back to
282                  a loop's head.  */
283               for (e = BASIC_BLOCK(j)->succ; e; e = e->succ_next)
284                 if (e->dest == loops_info->array[i].header)
285                   {
286                     header_found = 1;
287                     predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
288                   }
289               /* Loop exit heruistics - predict as not taken an edge exiting
290                  the loop if the conditinal has no loop header successors  */
291               if (!header_found)
292                 for (e = BASIC_BLOCK(j)->succ; e; e = e->succ_next)
293                   if (e->dest->index <= 0
294                       || !TEST_BIT (loops_info->array[i].nodes, e->dest->index))
295                     predict_edge_def (e, PRED_LOOP_EXIT, NOT_TAKEN);
296             }
297         }
298     }
299
300   /* Attempt to predict conditional jumps using a number of heuristics.
301      For each conditional jump, we try each heuristic in a fixed order.
302      If more than one heuristic applies to a particular branch, the first
303      is used as the prediction for the branch.  */
304   for (i = 0; i < n_basic_blocks; i++)
305     {
306       basic_block bb = BASIC_BLOCK (i);
307       rtx last_insn = bb->end;
308       rtx cond, earliest;
309       edge e;
310
311       /* If block has no sucessor, predict all possible paths to
312          it as improbable, as the block contains a call to a noreturn
313          function and thus can be executed only once.  */
314       if (bb->succ == NULL)
315         {
316           int y;
317           for (y = 0; y < n_basic_blocks; y++)
318             if (!TEST_BIT (post_dominators[y], i))
319               {
320                 for (e = BASIC_BLOCK (y)->succ; e; e = e->succ_next)
321                 if (e->dest->index >= 0
322                     && TEST_BIT (post_dominators[e->dest->index], i))
323                   predict_edge_def (e, PRED_NORETURN, NOT_TAKEN);
324               }
325         }
326
327       if (GET_CODE (last_insn) != JUMP_INSN
328           || ! any_condjump_p (last_insn))
329         continue;
330
331       for (e = bb->succ; e; e = e->succ_next)
332         {
333           /* Predict edges to blocks that return immediately to be
334              improbable.  These are usually used to signal error states.  */
335           if (e->dest == EXIT_BLOCK_PTR
336               || (e->dest->succ && !e->dest->succ->succ_next
337                   && e->dest->succ->dest == EXIT_BLOCK_PTR))
338             predict_edge_def (e, PRED_ERROR_RETURN, NOT_TAKEN);
339
340           /* Look for block we are guarding (ie we dominate it,
341              but it doesn't postdominate us).  */
342           if (e->dest != EXIT_BLOCK_PTR
343               && e->dest != bb
344               && TEST_BIT (dominators[e->dest->index], e->src->index)
345               && !TEST_BIT (post_dominators[e->src->index], e->dest->index))
346             {
347               rtx insn;
348               /* The call heuristic claims that a guarded function call
349                  is improbable.  This is because such calls are often used
350                  to signal exceptional situations such as printing error
351                  messages.  */
352               for (insn = e->dest->head; insn != NEXT_INSN (e->dest->end);
353                    insn = NEXT_INSN (insn))
354                 if (GET_CODE (insn) == CALL_INSN
355                     /* Constant and pure calls are hardly used to signalize
356                        something exceptional.  */
357                     && ! CONST_CALL_P (insn))
358                   {
359                     predict_edge_def (e, PRED_CALL, NOT_TAKEN);
360                     break;
361                   }
362             }
363         }
364
365       cond = get_condition (last_insn, &earliest);
366       if (! cond)
367         continue;
368
369       /* Try "pointer heuristic."
370          A comparison ptr == 0 is predicted as false.
371          Similarly, a comparison ptr1 == ptr2 is predicted as false.  */
372       switch (GET_CODE (cond))
373         {
374         case EQ:
375           if (GET_CODE (XEXP (cond, 0)) == REG
376               && REG_POINTER (XEXP (cond, 0))
377               && (XEXP (cond, 1) == const0_rtx
378                   || (GET_CODE (XEXP (cond, 1)) == REG
379                       && REG_POINTER (XEXP (cond, 1)))))
380             
381             predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
382           break;
383         case NE:
384           if (GET_CODE (XEXP (cond, 0)) == REG
385               && REG_POINTER (XEXP (cond, 0))
386               && (XEXP (cond, 1) == const0_rtx
387                   || (GET_CODE (XEXP (cond, 1)) == REG
388                       && REG_POINTER (XEXP (cond, 1)))))
389             predict_insn_def (last_insn, PRED_POINTER, TAKEN);
390           break;
391
392         default:
393           break;
394         }
395
396       /* Try "opcode heuristic."
397          EQ tests are usually false and NE tests are usually true. Also,
398          most quantities are positive, so we can make the appropriate guesses
399          about signed comparisons against zero.  */
400       switch (GET_CODE (cond))
401         {
402         case CONST_INT:
403           /* Unconditional branch.  */
404           predict_insn_def (last_insn, PRED_UNCONDITIONAL,
405                             cond == const0_rtx ? NOT_TAKEN : TAKEN);
406           break;
407
408         case EQ:
409         case UNEQ:
410           predict_insn_def (last_insn, PRED_OPCODE, NOT_TAKEN);
411           break;
412         case NE:
413         case LTGT:
414           predict_insn_def (last_insn, PRED_OPCODE, TAKEN);
415           break;
416         case ORDERED:
417           predict_insn_def (last_insn, PRED_OPCODE, TAKEN);
418           break;
419         case UNORDERED:
420           predict_insn_def (last_insn, PRED_OPCODE, NOT_TAKEN);
421           break;
422         case LE:
423         case LT:
424           if (XEXP (cond, 1) == const0_rtx
425               || (GET_CODE (XEXP (cond, 1)) == CONST_INT
426                   && INTVAL (XEXP (cond, 1)) == -1))
427             predict_insn_def (last_insn, PRED_OPCODE, NOT_TAKEN);
428           break;
429         case GE:
430         case GT:
431           if (XEXP (cond, 1) == const0_rtx
432               || (GET_CODE (XEXP (cond, 1)) == CONST_INT
433                   && INTVAL (XEXP (cond, 1)) == -1))
434             predict_insn_def (last_insn, PRED_OPCODE, TAKEN);
435           break;
436
437         default:
438           break;
439         }
440     }
441
442   /* Attach the combined probability to each conditional jump.  */
443   for (i = 0; i < n_basic_blocks; i++)
444     {
445       rtx last_insn = BLOCK_END (i);
446
447       if (GET_CODE (last_insn) != JUMP_INSN
448           || ! any_condjump_p (last_insn))
449         continue;
450       combine_predictions_for_insn (last_insn, BASIC_BLOCK (i));
451     }
452   sbitmap_vector_free (post_dominators);
453   sbitmap_vector_free (dominators);
454
455   estimate_bb_frequencies (loops_info);
456 }
457 \f
458 /* __builtin_expect dropped tokens into the insn stream describing
459    expected values of registers.  Generate branch probabilities 
460    based off these values.  */
461
462 void
463 expected_value_to_br_prob ()
464 {
465   rtx insn, cond, ev = NULL_RTX, ev_reg = NULL_RTX;
466
467   for (insn = get_insns (); insn ; insn = NEXT_INSN (insn))
468     {
469       switch (GET_CODE (insn))
470         {
471         case NOTE:
472           /* Look for expected value notes.  */
473           if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_EXPECTED_VALUE)
474             {
475               ev = NOTE_EXPECTED_VALUE (insn);
476               ev_reg = XEXP (ev, 0);
477             }
478           continue;
479
480         case CODE_LABEL:
481           /* Never propagate across labels.  */
482           ev = NULL_RTX;
483           continue;
484
485         default:
486           /* Look for insns that clobber the EV register.  */
487           if (ev && reg_set_p (ev_reg, insn))
488             ev = NULL_RTX;
489           continue;
490
491         case JUMP_INSN:
492           /* Look for simple conditional branches.  If we havn't got an
493              expected value yet, no point going further.  */
494           if (GET_CODE (insn) != JUMP_INSN || ev == NULL_RTX)
495             continue;
496           if (! any_condjump_p (insn))
497             continue;
498           break;
499         }
500
501       /* Collect the branch condition, hopefully relative to EV_REG.  */
502       /* ???  At present we'll miss things like
503                 (expected_value (eq r70 0))
504                 (set r71 -1)
505                 (set r80 (lt r70 r71))
506                 (set pc (if_then_else (ne r80 0) ...))
507          as canonicalize_condition will render this to us as 
508                 (lt r70, r71)
509          Could use cselib to try and reduce this further.  */
510       cond = XEXP (SET_SRC (PATTERN (insn)), 0);
511       cond = canonicalize_condition (insn, cond, 0, NULL, ev_reg);
512       if (! cond
513           || XEXP (cond, 0) != ev_reg
514           || GET_CODE (XEXP (cond, 1)) != CONST_INT)
515         continue;
516
517       /* Substitute and simplify.  Given that the expression we're 
518          building involves two constants, we should wind up with either
519          true or false.  */
520       cond = gen_rtx_fmt_ee (GET_CODE (cond), VOIDmode,
521                              XEXP (ev, 1), XEXP (cond, 1));
522       cond = simplify_rtx (cond);
523
524       /* Turn the condition into a scaled branch probability.  */
525       if (cond != const_true_rtx && cond != const0_rtx)
526         abort ();
527       predict_insn_def (insn, PRED_BUILTIN_EXPECT,
528                         cond == const_true_rtx ? TAKEN : NOT_TAKEN);
529     }
530 }
531 \f
532 /* This is used to carry information about basic blocks.  It is 
533    attached to the AUX field of the standard CFG block.  */
534
535 typedef struct block_info_def
536 {
537   /* Estimated frequency of execution of basic_block.  */
538   double frequency;
539
540   /* To keep queue of basic blocks to process.  */
541   basic_block next;
542
543   /* True if block already converted.  */
544   int visited:1;
545
546   /* Number of block proceeded before adding basic block to the queue.  Used
547      to recognize irregular regions.  */
548   int nvisited;
549 } *block_info;
550
551 /* Similar information for edges.  */
552 typedef struct edge_info_def
553 {
554   /* In case edge is an loopback edge, the probability edge will be reached
555      in case header is.  Estimated number of iterations of the loop can be
556      then computed as 1 / (1 - back_edge_prob).  */
557   double back_edge_prob;
558   /* True if the edge is an loopback edge in the natural loop.  */
559   int back_edge:1;
560 } *edge_info;
561
562 #define BLOCK_INFO(B)   ((block_info) (B)->aux)
563 #define EDGE_INFO(E)    ((edge_info) (E)->aux)
564
565 /* Helper function for estimate_bb_frequencies.
566    Propagate the frequencies for loops headed by HEAD.  */
567 static void
568 propagate_freq (head)
569      basic_block head;
570 {
571   basic_block bb = head;
572   basic_block last = bb;
573   edge e;
574   basic_block nextbb;
575   int nvisited = 0;
576
577   BLOCK_INFO (head)->frequency = 1;
578   for (; bb; bb = nextbb)
579     {
580       double cyclic_probability = 0, frequency = 0;
581
582       nextbb = BLOCK_INFO (bb)->next;
583       BLOCK_INFO (bb)->next = NULL;
584
585       /* Compute frequency of basic block.  */
586       if (bb != head)
587         {
588           for (e = bb->pred; e; e = e->pred_next)
589             if (!BLOCK_INFO (e->src)->visited && !EDGE_INFO (e)->back_edge)
590               break;
591
592           /* We didn't proceeded all predecesors of edge e yet.  These may
593              be waiting in the queue or we may hit irreducible region.
594
595              To avoid infinite looping on irrecudible regions, count number
596              of block proceeded at the time basic block has been queued.  In the
597              case number didn't changed, we've hit irreducible region and we
598              forget the backward edge.  This can increase time complexity
599              by the number of irreducible blocks, but in same way standard the
600              loop does, so it should not result in noticeable slowodwn.
601
602              Alternativly we may distinquish backward and cross edges in the
603              DFS tree by preprocesing pass and ignore existence of non-loop
604              backward edges.  */
605           if (e && BLOCK_INFO (bb)->nvisited != nvisited)
606             {
607               if (!nextbb)
608                 nextbb = e->dest;
609               else
610                 BLOCK_INFO (last)->next = e->dest;
611               BLOCK_INFO (last)->nvisited = nvisited;
612               last = e->dest;
613               continue;
614             }
615           else if (e && rtl_dump_file)
616             fprintf (rtl_dump_file, "Irreducible region hit, ignoring edge to bb %i\n",
617                      bb->index);
618
619           for (e = bb->pred; e; e = e->pred_next)
620             if (EDGE_INFO (e)->back_edge)
621               cyclic_probability += EDGE_INFO (e)->back_edge_prob;
622             else if (BLOCK_INFO (e->src)->visited)
623               frequency += (e->probability
624                             * BLOCK_INFO (e->src)->frequency /
625                             REG_BR_PROB_BASE);
626
627           if (cyclic_probability > 1.0 - 1.0 / REG_BR_PROB_BASE)
628             cyclic_probability = 1.0 - 1.0 / REG_BR_PROB_BASE;
629
630           BLOCK_INFO (bb)->frequency = frequency / (1 - cyclic_probability);
631         }
632
633       BLOCK_INFO (bb)->visited = 1;
634
635       /* Compute back edge frequencies.  */
636       for (e = bb->succ; e; e = e->succ_next)
637         if (e->dest == head)
638           EDGE_INFO (e)->back_edge_prob = (e->probability
639                                            * BLOCK_INFO (bb)->frequency
640                                            / REG_BR_PROB_BASE);
641
642       /* Propagate to succesor blocks.  */
643       for (e = bb->succ; e; e = e->succ_next)
644         if (!EDGE_INFO (e)->back_edge
645             && !BLOCK_INFO (e->dest)->visited
646             && !BLOCK_INFO (e->dest)->next && e->dest != last)
647           {
648             if (!nextbb)
649               nextbb = e->dest;
650             else
651               BLOCK_INFO (last)->next = e->dest;
652             BLOCK_INFO (last)->nvisited = nvisited;
653             last = e->dest;
654           }
655       nvisited ++;
656     }
657 }
658
659 /* Estimate probabilities of the loopback edges in loops at same nest level.  */
660 static void
661 estimate_loops_at_level (first_loop)
662      struct loop *first_loop;
663 {
664   struct loop *l, *loop = first_loop;
665
666   for (loop = first_loop; loop; loop = loop->next)
667     {
668       int n;
669       edge e;
670
671       estimate_loops_at_level (loop->inner);
672
673       /* find current loop back edge and mark it.  */
674       for (e = loop->latch->succ; e->dest != loop->header; e = e->succ_next);
675
676       EDGE_INFO (e)->back_edge = 1;
677
678       /* In case loop header is shared, ensure that it is the last one sharing
679          same header, so we avoid redundant work.  */
680       if (loop->shared)
681         {
682           for (l = loop->next; l; l = l->next)
683             if (l->header == loop->header)
684               break;
685           if (l)
686             continue;
687         }
688
689       /* Now merge all nodes of all loops with given header as not visited.  */
690       for (l = loop->shared ? first_loop : loop; l != loop->next; l = l->next)
691         if (loop->header == l->header)
692           EXECUTE_IF_SET_IN_SBITMAP (l->nodes, 0, n,
693                                      BLOCK_INFO (BASIC_BLOCK (n))->visited =
694                                      0);
695       propagate_freq (loop->header);
696     }
697 }
698
699 /* Convert counts measured by profile driven feedback to frequencies.  */
700 static void
701 counts_to_freqs ()
702 {
703   HOST_WIDEST_INT count_max = 1;
704   int i;
705
706   for (i = 0; i < n_basic_blocks; i++)
707     if (BASIC_BLOCK (i)->count > count_max)
708       count_max = BASIC_BLOCK (i)->count;
709
710   for (i = -2; i < n_basic_blocks; i++)
711     {
712       basic_block bb;
713       if (i == -2)
714         bb = ENTRY_BLOCK_PTR;
715       else if (i == -1)
716         bb = EXIT_BLOCK_PTR;
717       else
718         bb = BASIC_BLOCK (i);
719       bb->frequency = ((bb->count * BB_FREQ_MAX + count_max / 2)
720                        / count_max);
721     }
722 }
723
724 /* Estimate basic blocks frequency by given branch probabilities.  */
725 static void
726 estimate_bb_frequencies (loops)
727      struct loops *loops;
728 {
729   block_info bi;
730   edge_info ei;
731   int edgenum = 0;
732   int i;
733   double freq_max = 0;
734
735   if (flag_branch_probabilities)
736     {
737       counts_to_freqs ();
738       return;
739     }
740
741   /* Fill in the probability values in flowgraph based on the REG_BR_PROB
742      notes.  */
743   for (i = 0; i < n_basic_blocks; i++)
744     {
745       rtx last_insn = BLOCK_END (i);
746       int probability;
747       edge fallthru, branch;
748
749       if (GET_CODE (last_insn) != JUMP_INSN || !any_condjump_p (last_insn)
750           /* Avoid handling of conditionals jump jumping to fallthru edge.  */
751           || BASIC_BLOCK (i)->succ->succ_next == NULL)
752         {
753           /* We can predict only conditional jumps at the moment.
754              Expect each edge to be equall probable.
755              ?? In future we want to make abnormal edges improbable.  */
756           int nedges = 0;
757           edge e;
758
759           for (e = BASIC_BLOCK (i)->succ; e; e = e->succ_next)
760             {
761               nedges++;
762               if (e->probability != 0)
763                 break;
764             }
765           if (!e)
766             for (e = BASIC_BLOCK (i)->succ; e; e = e->succ_next)
767               e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
768         }
769       else
770         {
771           probability = INTVAL (XEXP (find_reg_note (last_insn,
772                                                      REG_BR_PROB, 0), 0));
773           fallthru = BASIC_BLOCK (i)->succ;
774           if (!fallthru->flags & EDGE_FALLTHRU)
775             fallthru = fallthru->succ_next;
776           branch = BASIC_BLOCK (i)->succ;
777           if (branch->flags & EDGE_FALLTHRU)
778             branch = branch->succ_next;
779
780           branch->probability = probability;
781           fallthru->probability = REG_BR_PROB_BASE - probability;
782         }
783     }
784   ENTRY_BLOCK_PTR->succ->probability = REG_BR_PROB_BASE;
785
786   /* Set up block info for each basic block.  */
787   bi = (block_info) xcalloc ((n_basic_blocks + 2), sizeof (*bi));
788   ei = (edge_info) xcalloc ((n_edges), sizeof (*ei));
789   for (i = -2; i < n_basic_blocks; i++)
790     {
791       edge e;
792       basic_block bb;
793
794       if (i == -2)
795         bb = ENTRY_BLOCK_PTR;
796       else if (i == -1)
797         bb = EXIT_BLOCK_PTR;
798       else
799         bb = BASIC_BLOCK (i);
800       bb->aux = bi + i + 2;
801       BLOCK_INFO (bb)->visited = 1;
802       for (e = bb->succ; e; e = e->succ_next)
803         {
804           e->aux = ei + edgenum, edgenum++;
805           EDGE_INFO (e)->back_edge_prob = ((double) e->probability
806                                            / REG_BR_PROB_BASE);
807         }
808     }
809   /* First compute probabilities locally for each loop from innermost
810      to outermost to examine probabilities for back edges.  */
811   estimate_loops_at_level (loops->tree);
812
813   /* Now fake loop around whole function to finalize probabilities.  */
814   for (i = 0; i < n_basic_blocks; i++)
815     BLOCK_INFO (BASIC_BLOCK (i))->visited = 0;
816   BLOCK_INFO (ENTRY_BLOCK_PTR)->visited = 0;
817   BLOCK_INFO (EXIT_BLOCK_PTR)->visited = 0;
818   propagate_freq (ENTRY_BLOCK_PTR);
819
820   for (i = 0; i < n_basic_blocks; i++)
821     if (BLOCK_INFO (BASIC_BLOCK (i))->frequency > freq_max)
822       freq_max = BLOCK_INFO (BASIC_BLOCK (i))->frequency;
823   for (i = -2; i < n_basic_blocks; i++)
824     {
825       basic_block bb;
826       if (i == -2)
827         bb = ENTRY_BLOCK_PTR;
828       else if (i == -1)
829         bb = EXIT_BLOCK_PTR;
830       else
831         bb = BASIC_BLOCK (i);
832       bb->frequency = (BLOCK_INFO (bb)->frequency * BB_FREQ_MAX / freq_max
833                        + 0.5);
834     }
835
836   free (ei);
837   free (bi);
838 }