OSDN Git Service

59ae4a1ed7a2caaf56f77d9cbf54939749669cdf
[pf3gnuchains/gcc-fork.git] / gcc / cfgloopmanip.c
1 /* Loop manipulation code for GNU compiler.
2    Copyright (C) 2002, 2003, 2004 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 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "rtl.h"
26 #include "hard-reg-set.h"
27 #include "basic-block.h"
28 #include "cfgloop.h"
29 #include "cfglayout.h"
30 #include "output.h"
31
32 static struct loop * duplicate_loop (struct loops *, struct loop *,
33                                      struct loop *);
34 static void duplicate_subloops (struct loops *, struct loop *, struct loop *);
35 static void copy_loops_to (struct loops *, struct loop **, int,
36                            struct loop *);
37 static void loop_redirect_edge (edge, basic_block);
38 static bool loop_delete_branch_edge (edge, int);
39 static void remove_bbs (basic_block *, int);
40 static bool rpe_enum_p (basic_block, void *);
41 static int find_path (edge, basic_block **);
42 static bool alp_enum_p (basic_block, void *);
43 static void add_loop (struct loops *, struct loop *);
44 static void fix_loop_placements (struct loop *);
45 static bool fix_bb_placement (struct loops *, basic_block);
46 static void fix_bb_placements (struct loops *, basic_block);
47 static void place_new_loop (struct loops *, struct loop *);
48 static void scale_loop_frequencies (struct loop *, int, int);
49 static void scale_bbs_frequencies (basic_block *, int, int, int);
50 static basic_block create_preheader (struct loop *, int);
51 static void fix_irreducible_loops (basic_block);
52
53 #define RDIV(X,Y) (((X) + (Y) / 2) / (Y))
54
55 /* Splits basic block BB after INSN, returns created edge.  Updates loops
56    and dominators.  */
57 edge
58 split_loop_bb (basic_block bb, rtx insn)
59 {
60   edge e;
61
62   /* Split the block.  */
63   e = split_block (bb, insn);
64
65   /* Add dest to loop.  */
66   add_bb_to_loop (e->dest, e->src->loop_father);
67
68   return e;
69 }
70
71 /* Checks whether basic block BB is dominated by DATA.  */
72 static bool
73 rpe_enum_p (basic_block bb, void *data)
74 {
75   return dominated_by_p (CDI_DOMINATORS, bb, data);
76 }
77
78 /* Remove basic blocks BBS from loop structure and dominance info,
79    and delete them afterwards.  */
80 static void
81 remove_bbs (basic_block *bbs, int nbbs)
82 {
83   int i;
84
85   for (i = 0; i < nbbs; i++)
86     {
87       remove_bb_from_loops (bbs[i]);
88       delete_basic_block (bbs[i]);
89     }
90 }
91
92 /* Find path -- i.e. the basic blocks dominated by edge E and put them
93    into array BBS, that will be allocated large enough to contain them.
94    E->dest must have exactly one predecessor for this to work (it is
95    easy to achieve and we do not put it here because we do not want to
96    alter anything by this function).  The number of basic blocks in the
97    path is returned.  */
98 static int
99 find_path (edge e, basic_block **bbs)
100 {
101   if (e->dest->pred->pred_next)
102     abort ();
103
104   /* Find bbs in the path.  */
105   *bbs = xcalloc (n_basic_blocks, sizeof (basic_block));
106   return dfs_enumerate_from (e->dest, 0, rpe_enum_p, *bbs,
107                              n_basic_blocks, e->dest);
108 }
109
110 /* Fix placement of basic block BB inside loop hierarchy stored in LOOPS --
111    Let L be a loop to that BB belongs.  Then every successor of BB must either
112      1) belong to some superloop of loop L, or
113      2) be a header of loop K such that K->outer is superloop of L
114    Returns true if we had to move BB into other loop to enforce this condition,
115    false if the placement of BB was already correct (provided that placements
116    of its successors are correct).  */
117 static bool
118 fix_bb_placement (struct loops *loops, basic_block bb)
119 {
120   edge e;
121   struct loop *loop = loops->tree_root, *act;
122
123   for (e = bb->succ; e; e = e->succ_next)
124     {
125       if (e->dest == EXIT_BLOCK_PTR)
126         continue;
127
128       act = e->dest->loop_father;
129       if (act->header == e->dest)
130         act = act->outer;
131
132       if (flow_loop_nested_p (loop, act))
133         loop = act;
134     }
135
136   if (loop == bb->loop_father)
137     return false;
138
139   remove_bb_from_loops (bb);
140   add_bb_to_loop (bb, loop);
141
142   return true;
143 }
144
145 /* Fix placements of basic blocks inside loop hierarchy stored in loops; i.e.
146    enforce condition condition stated in description of fix_bb_placement. We
147    start from basic block FROM that had some of its successors removed, so that
148    his placement no longer has to be correct, and iteratively fix placement of
149    its predecessors that may change if placement of FROM changed.  Also fix
150    placement of subloops of FROM->loop_father, that might also be altered due
151    to this change; the condition for them is similar, except that instead of
152    successors we consider edges coming out of the loops.  */
153 static void
154 fix_bb_placements (struct loops *loops, basic_block from)
155 {
156   sbitmap in_queue;
157   basic_block *queue, *qtop, *qbeg, *qend;
158   struct loop *base_loop;
159   edge e;
160
161   /* We pass through blocks back-reachable from FROM, testing whether some
162      of their successors moved to outer loop.  It may be necessary to
163      iterate several times, but it is finite, as we stop unless we move
164      the basic block up the loop structure.  The whole story is a bit
165      more complicated due to presence of subloops, those are moved using
166      fix_loop_placement.  */
167
168   base_loop = from->loop_father;
169   if (base_loop == loops->tree_root)
170     return;
171
172   in_queue = sbitmap_alloc (last_basic_block);
173   sbitmap_zero (in_queue);
174   SET_BIT (in_queue, from->index);
175   /* Prevent us from going out of the base_loop.  */
176   SET_BIT (in_queue, base_loop->header->index);
177
178   queue = xmalloc ((base_loop->num_nodes + 1) * sizeof (basic_block));
179   qtop = queue + base_loop->num_nodes + 1;
180   qbeg = queue;
181   qend = queue + 1;
182   *qbeg = from;
183
184   while (qbeg != qend)
185     {
186       from = *qbeg;
187       qbeg++;
188       if (qbeg == qtop)
189         qbeg = queue;
190       RESET_BIT (in_queue, from->index);
191
192       if (from->loop_father->header == from)
193         {
194           /* Subloop header, maybe move the loop upward.  */
195           if (!fix_loop_placement (from->loop_father))
196             continue;
197         }
198       else
199         {
200           /* Ordinary basic block.  */
201           if (!fix_bb_placement (loops, from))
202             continue;
203         }
204
205       /* Something has changed, insert predecessors into queue.  */
206       for (e = from->pred; e; e = e->pred_next)
207         {
208           basic_block pred = e->src;
209           struct loop *nca;
210
211           if (TEST_BIT (in_queue, pred->index))
212             continue;
213
214           /* If it is subloop, then it either was not moved, or
215              the path up the loop tree from base_loop do not contain
216              it.  */
217           nca = find_common_loop (pred->loop_father, base_loop);
218           if (pred->loop_father != base_loop
219               && (nca == base_loop
220                   || nca != pred->loop_father))
221             pred = pred->loop_father->header;
222           else if (!flow_loop_nested_p (from->loop_father, pred->loop_father))
223             {
224               /* No point in processing it.  */
225               continue;
226             }
227
228           if (TEST_BIT (in_queue, pred->index))
229             continue;
230
231           /* Schedule the basic block.  */
232           *qend = pred;
233           qend++;
234           if (qend == qtop)
235             qend = queue;
236           SET_BIT (in_queue, pred->index);
237         }
238     }
239   free (in_queue);
240   free (queue);
241 }
242
243 /* Basic block from has lost one or more of its predecessors, so it might
244    mo longer be part irreducible loop.  Fix it and proceed recursively
245    for its successors if needed.  */
246 static void
247 fix_irreducible_loops (basic_block from)
248 {
249   basic_block bb;
250   basic_block *stack;
251   int stack_top;
252   sbitmap on_stack;
253   edge *edges, e;
254   unsigned n_edges, i;
255
256   if (!(from->flags & BB_IRREDUCIBLE_LOOP))
257     return;
258
259   on_stack = sbitmap_alloc (last_basic_block);
260   sbitmap_zero (on_stack);
261   SET_BIT (on_stack, from->index);
262   stack = xmalloc (from->loop_father->num_nodes * sizeof (basic_block));
263   stack[0] = from;
264   stack_top = 1;
265
266   while (stack_top)
267     {
268       bb = stack[--stack_top];
269       RESET_BIT (on_stack, bb->index);
270
271       for (e = bb->pred; e; e = e->pred_next)
272         if (e->flags & EDGE_IRREDUCIBLE_LOOP)
273           break;
274       if (e)
275         continue;
276
277       bb->flags &= ~BB_IRREDUCIBLE_LOOP;
278       if (bb->loop_father->header == bb)
279         edges = get_loop_exit_edges (bb->loop_father, &n_edges);
280       else
281         {
282           n_edges = 0;
283           for (e = bb->succ; e; e = e->succ_next)
284             n_edges++;
285           edges = xmalloc (n_edges * sizeof (edge));
286           n_edges = 0;
287           for (e = bb->succ; e; e = e->succ_next)
288             edges[n_edges++] = e;
289         }
290
291       for (i = 0; i < n_edges; i++)
292         {
293           e = edges[i];
294
295           if (e->flags & EDGE_IRREDUCIBLE_LOOP)
296             {
297               if (!flow_bb_inside_loop_p (from->loop_father, e->dest))
298                 continue;
299
300               e->flags &= ~EDGE_IRREDUCIBLE_LOOP;
301               if (TEST_BIT (on_stack, e->dest->index))
302                 continue;
303
304               SET_BIT (on_stack, e->dest->index);
305               stack[stack_top++] = e->dest;
306             }
307         }
308       free (edges);
309     }
310
311   free (on_stack);
312   free (stack);
313 }
314
315 /* Removes path beginning at edge E, i.e. remove basic blocks dominated by E
316    and update loop structure stored in LOOPS and dominators.  Return true if
317    we were able to remove the path, false otherwise (and nothing is affected
318    then).  */
319 bool
320 remove_path (struct loops *loops, edge e)
321 {
322   edge ae;
323   basic_block *rem_bbs, *bord_bbs, *dom_bbs, from, bb;
324   int i, nrem, n_bord_bbs, n_dom_bbs;
325   sbitmap seen;
326
327   if (!loop_delete_branch_edge (e, 0))
328     return false;
329
330   /* We need to check whether basic blocks are dominated by the edge
331      e, but we only have basic block dominators.  This is easy to
332      fix -- when e->dest has exactly one predecessor, this corresponds
333      to blocks dominated by e->dest, if not, split the edge.  */
334   if (e->dest->pred->pred_next)
335     e = loop_split_edge_with (e, NULL_RTX)->pred;
336
337   /* It may happen that by removing path we remove one or more loops
338      we belong to.  In this case first unloop the loops, then proceed
339      normally.   We may assume that e->dest is not a header of any loop,
340      as it now has exactly one predecessor.  */
341   while (e->src->loop_father->outer
342          && dominated_by_p (CDI_DOMINATORS,
343                             e->src->loop_father->latch, e->dest))
344     unloop (loops, e->src->loop_father);
345
346   /* Identify the path.  */
347   nrem = find_path (e, &rem_bbs);
348
349   n_bord_bbs = 0;
350   bord_bbs = xcalloc (n_basic_blocks, sizeof (basic_block));
351   seen = sbitmap_alloc (last_basic_block);
352   sbitmap_zero (seen);
353
354   /* Find "border" hexes -- i.e. those with predecessor in removed path.  */
355   for (i = 0; i < nrem; i++)
356     SET_BIT (seen, rem_bbs[i]->index);
357   for (i = 0; i < nrem; i++)
358     {
359       bb = rem_bbs[i];
360       for (ae = rem_bbs[i]->succ; ae; ae = ae->succ_next)
361         if (ae->dest != EXIT_BLOCK_PTR && !TEST_BIT (seen, ae->dest->index))
362           {
363             SET_BIT (seen, ae->dest->index);
364             bord_bbs[n_bord_bbs++] = ae->dest;
365           }
366     }
367
368   /* Remove the path.  */
369   from = e->src;
370   if (!loop_delete_branch_edge (e, 1))
371     abort ();
372   dom_bbs = xcalloc (n_basic_blocks, sizeof (basic_block));
373
374   /* Cancel loops contained in the path.  */
375   for (i = 0; i < nrem; i++)
376     if (rem_bbs[i]->loop_father->header == rem_bbs[i])
377       cancel_loop_tree (loops, rem_bbs[i]->loop_father);
378
379   remove_bbs (rem_bbs, nrem);
380   free (rem_bbs);
381
382   /* Find blocks whose dominators may be affected.  */
383   n_dom_bbs = 0;
384   sbitmap_zero (seen);
385   for (i = 0; i < n_bord_bbs; i++)
386     {
387       basic_block ldom;
388
389       bb = get_immediate_dominator (CDI_DOMINATORS, bord_bbs[i]);
390       if (TEST_BIT (seen, bb->index))
391         continue;
392       SET_BIT (seen, bb->index);
393
394       for (ldom = first_dom_son (CDI_DOMINATORS, bb);
395            ldom;
396            ldom = next_dom_son (CDI_DOMINATORS, ldom))
397         if (!dominated_by_p (CDI_DOMINATORS, from, ldom))
398           dom_bbs[n_dom_bbs++] = ldom;
399     }
400
401   free (seen);
402
403   /* Recount dominators.  */
404   iterate_fix_dominators (CDI_DOMINATORS, dom_bbs, n_dom_bbs);
405   free (dom_bbs);
406
407   /* These blocks have lost some predecessor(s), thus their irreducible
408      status could be changed.  */
409   for (i = 0; i < n_bord_bbs; i++)
410     fix_irreducible_loops (bord_bbs[i]);
411   free (bord_bbs);
412
413   /* Fix placements of basic blocks inside loops and the placement of
414      loops in the loop tree.  */
415   fix_bb_placements (loops, from);
416   fix_loop_placements (from->loop_father);
417
418   return true;
419 }
420
421 /* Predicate for enumeration in add_loop.  */
422 static bool
423 alp_enum_p (basic_block bb, void *alp_header)
424 {
425   return bb != (basic_block) alp_header;
426 }
427
428 /* Given LOOP structure with filled header and latch, find the body of the
429    corresponding loop and add it to LOOPS tree.  */
430 static void
431 add_loop (struct loops *loops, struct loop *loop)
432 {
433   basic_block *bbs;
434   int i, n;
435
436   /* Add it to loop structure.  */
437   place_new_loop (loops, loop);
438   loop->level = 1;
439
440   /* Find its nodes.  */
441   bbs = xcalloc (n_basic_blocks, sizeof (basic_block));
442   n = dfs_enumerate_from (loop->latch, 1, alp_enum_p,
443                           bbs, n_basic_blocks, loop->header);
444
445   for (i = 0; i < n; i++)
446     add_bb_to_loop (bbs[i], loop);
447   add_bb_to_loop (loop->header, loop);
448
449   free (bbs);
450 }
451
452 /* Multiply all frequencies of basic blocks in array BBS of length NBBS
453    by NUM/DEN.  */
454 static void
455 scale_bbs_frequencies (basic_block *bbs, int nbbs, int num, int den)
456 {
457   int i;
458   edge e;
459
460   for (i = 0; i < nbbs; i++)
461     {
462       bbs[i]->frequency = (bbs[i]->frequency * num) / den;
463       bbs[i]->count = RDIV (bbs[i]->count * num, den);
464       for (e = bbs[i]->succ; e; e = e->succ_next)
465         e->count = (e->count * num) /den;
466     }
467 }
468
469 /* Multiply all frequencies in LOOP by NUM/DEN.  */
470 static void
471 scale_loop_frequencies (struct loop *loop, int num, int den)
472 {
473   basic_block *bbs;
474
475   bbs = get_loop_body (loop);
476   scale_bbs_frequencies (bbs, loop->num_nodes, num, den);
477   free (bbs);
478 }
479
480 /* Make area between HEADER_EDGE and LATCH_EDGE a loop by connecting
481    latch to header and update loop tree stored in LOOPS and dominators
482    accordingly. Everything between them plus LATCH_EDGE destination must
483    be dominated by HEADER_EDGE destination, and back-reachable from
484    LATCH_EDGE source.  HEADER_EDGE is redirected to basic block SWITCH_BB,
485    FALLTHRU_EDGE (SWITCH_BB) to original destination of HEADER_EDGE and
486    BRANCH_EDGE (SWITCH_BB) to original destination of LATCH_EDGE.
487    Returns newly created loop.  */
488
489 struct loop *
490 loopify (struct loops *loops, edge latch_edge, edge header_edge, 
491          basic_block switch_bb)
492 {
493   basic_block succ_bb = latch_edge->dest;
494   basic_block pred_bb = header_edge->src;
495   basic_block *dom_bbs, *body;
496   unsigned n_dom_bbs, i;
497   sbitmap seen;
498   struct loop *loop = xcalloc (1, sizeof (struct loop));
499   struct loop *outer = succ_bb->loop_father->outer;
500   int freq, prob, tot_prob;
501   gcov_type cnt;
502   edge e;
503
504   loop->header = header_edge->dest;
505   loop->latch = latch_edge->src;
506
507   freq = EDGE_FREQUENCY (header_edge);
508   cnt = header_edge->count;
509   prob = switch_bb->succ->probability;
510   tot_prob = prob + switch_bb->succ->succ_next->probability;
511   if (tot_prob == 0)
512     tot_prob = 1;
513
514   /* Redirect edges.  */
515   loop_redirect_edge (latch_edge, loop->header);
516   loop_redirect_edge (BRANCH_EDGE (switch_bb), succ_bb);
517
518   loop_redirect_edge (header_edge, switch_bb);
519   loop_redirect_edge (FALLTHRU_EDGE (switch_bb), loop->header); 
520
521   /* Update dominators.  */
522   set_immediate_dominator (CDI_DOMINATORS, switch_bb, pred_bb);
523   set_immediate_dominator (CDI_DOMINATORS, loop->header, switch_bb);
524
525   set_immediate_dominator (CDI_DOMINATORS, succ_bb, switch_bb);
526
527   /* Compute new loop.  */
528   add_loop (loops, loop);
529   flow_loop_tree_node_add (outer, loop);
530
531   /* Add switch_bb to appropriate loop.  */
532   add_bb_to_loop (switch_bb, outer);
533
534   /* Fix frequencies.  */
535   switch_bb->frequency = freq;
536   switch_bb->count = cnt;
537   for (e = switch_bb->succ; e; e = e->succ_next)
538     e->count = (switch_bb->count * e->probability) / REG_BR_PROB_BASE;
539   scale_loop_frequencies (loop, prob, tot_prob);
540   scale_loop_frequencies (succ_bb->loop_father, tot_prob - prob, tot_prob);
541
542   /* Update dominators of blocks outside of LOOP.  */
543   dom_bbs = xcalloc (n_basic_blocks, sizeof (basic_block));
544   n_dom_bbs = 0;
545   seen = sbitmap_alloc (last_basic_block);
546   sbitmap_zero (seen);
547   body = get_loop_body (loop);
548
549   for (i = 0; i < loop->num_nodes; i++)
550     SET_BIT (seen, body[i]->index);
551
552   for (i = 0; i < loop->num_nodes; i++)
553     {
554       basic_block ldom;
555
556       for (ldom = first_dom_son (CDI_DOMINATORS, body[i]);
557            ldom;
558            ldom = next_dom_son (CDI_DOMINATORS, ldom))
559         if (!TEST_BIT (seen, ldom->index))
560           {
561             SET_BIT (seen, ldom->index);
562             dom_bbs[n_dom_bbs++] = ldom;
563           }
564     }
565
566   iterate_fix_dominators (CDI_DOMINATORS, dom_bbs, n_dom_bbs);
567
568   free (body);
569   free (seen);
570   free (dom_bbs);
571
572   return loop;
573 }
574
575 /* Remove the latch edge of a LOOP and update LOOPS tree to indicate that
576    the LOOP was removed.  After this function, original loop latch will
577    have no successor, which caller is expected to fix somehow.  */
578 void
579 unloop (struct loops *loops, struct loop *loop)
580 {
581   basic_block *body;
582   struct loop *ploop;
583   unsigned i, n;
584   basic_block latch = loop->latch;
585   edge *edges;
586   unsigned n_edges;
587
588   /* This is relatively straightforward.  The dominators are unchanged, as
589      loop header dominates loop latch, so the only thing we have to care of
590      is the placement of loops and basic blocks inside the loop tree.  We
591      move them all to the loop->outer, and then let fix_bb_placements do
592      its work.  */
593
594   body = get_loop_body (loop);
595   edges = get_loop_exit_edges (loop, &n_edges);
596   n = loop->num_nodes;
597   for (i = 0; i < n; i++)
598     if (body[i]->loop_father == loop)
599       {
600         remove_bb_from_loops (body[i]);
601         add_bb_to_loop (body[i], loop->outer);
602       }
603   free(body);
604
605   while (loop->inner)
606     {
607       ploop = loop->inner;
608       flow_loop_tree_node_remove (ploop);
609       flow_loop_tree_node_add (loop->outer, ploop);
610     }
611
612   /* Remove the loop and free its data.  */
613   flow_loop_tree_node_remove (loop);
614   loops->parray[loop->num] = NULL;
615   flow_loop_free (loop);
616
617   remove_edge (latch->succ);
618   fix_bb_placements (loops, latch);
619
620   /* If the loop was inside an irreducible region, we would have to somehow
621      update the irreducible marks inside its body.  While it is certainly
622      possible to do, it is a bit complicated and this situation should be
623      very rare, so we just remark all loops in this case.  */
624   for (i = 0; i < n_edges; i++)
625     if (edges[i]->flags & EDGE_IRREDUCIBLE_LOOP)
626       break;
627   if (i != n_edges)
628     mark_irreducible_loops (loops);
629   free (edges);
630 }
631
632 /* Fix placement of LOOP inside loop tree, i.e. find the innermost superloop
633    FATHER of LOOP such that all of the edges coming out of LOOP belong to
634    FATHER, and set it as outer loop of LOOP.  Return 1 if placement of
635    LOOP changed.  */
636 int
637 fix_loop_placement (struct loop *loop)
638 {
639   basic_block *body;
640   unsigned i;
641   edge e;
642   struct loop *father = loop->pred[0], *act;
643
644   body = get_loop_body (loop);
645   for (i = 0; i < loop->num_nodes; i++)
646     for (e = body[i]->succ; e; e = e->succ_next)
647       if (!flow_bb_inside_loop_p (loop, e->dest))
648         {
649           act = find_common_loop (loop, e->dest->loop_father);
650           if (flow_loop_nested_p (father, act))
651             father = act;
652         }
653   free (body);
654
655   if (father != loop->outer)
656     {
657       for (act = loop->outer; act != father; act = act->outer)
658         act->num_nodes -= loop->num_nodes;
659       flow_loop_tree_node_remove (loop);
660       flow_loop_tree_node_add (father, loop);
661       return 1;
662     }
663   return 0;
664 }
665
666 /* Fix placement of superloops of LOOP inside loop tree, i.e. ensure that
667    condition stated in description of fix_loop_placement holds for them.
668    It is used in case when we removed some edges coming out of LOOP, which
669    may cause the right placement of LOOP inside loop tree to change.  */
670 static void
671 fix_loop_placements (struct loop *loop)
672 {
673   struct loop *outer;
674
675   while (loop->outer)
676     {
677       outer = loop->outer;
678       if (!fix_loop_placement (loop))
679         break;
680       loop = outer;
681     }
682 }
683
684 /* Creates place for a new LOOP in LOOPS structure.  */
685 static void
686 place_new_loop (struct loops *loops, struct loop *loop)
687 {
688   loops->parray =
689     xrealloc (loops->parray, (loops->num + 1) * sizeof (struct loop *));
690   loops->parray[loops->num] = loop;
691
692   loop->num = loops->num++;
693 }
694
695 /* Copies copy of LOOP as subloop of TARGET loop, placing newly
696    created loop into LOOPS structure.  */
697 static struct loop *
698 duplicate_loop (struct loops *loops, struct loop *loop, struct loop *target)
699 {
700   struct loop *cloop;
701   cloop = xcalloc (1, sizeof (struct loop));
702   place_new_loop (loops, cloop);
703
704   /* Initialize copied loop.  */
705   cloop->level = loop->level;
706
707   /* Set it as copy of loop.  */
708   loop->copy = cloop;
709
710   /* Add it to target.  */
711   flow_loop_tree_node_add (target, cloop);
712
713   return cloop;
714 }
715
716 /* Copies structure of subloops of LOOP into TARGET loop, placing
717    newly created loops into loop tree stored in LOOPS.  */
718 static void
719 duplicate_subloops (struct loops *loops, struct loop *loop, struct loop *target)
720 {
721   struct loop *aloop, *cloop;
722
723   for (aloop = loop->inner; aloop; aloop = aloop->next)
724     {
725       cloop = duplicate_loop (loops, aloop, target);
726       duplicate_subloops (loops, aloop, cloop);
727     }
728 }
729
730 /* Copies structure of subloops of N loops, stored in array COPIED_LOOPS,
731    into TARGET loop, placing newly created loops into loop tree LOOPS.  */
732 static void
733 copy_loops_to (struct loops *loops, struct loop **copied_loops, int n, struct loop *target)
734 {
735   struct loop *aloop;
736   int i;
737
738   for (i = 0; i < n; i++)
739     {
740       aloop = duplicate_loop (loops, copied_loops[i], target);
741       duplicate_subloops (loops, copied_loops[i], aloop);
742     }
743 }
744
745 /* Redirects edge E to basic block DEST.  */
746 static void
747 loop_redirect_edge (edge e, basic_block dest)
748 {
749   if (e->dest == dest)
750     return;
751
752   redirect_edge_and_branch_force (e, dest);
753 }
754
755 /* Deletes edge E from a branch if possible.  Unless REALLY_DELETE is set,
756    just test whether it is possible to remove the edge.  */
757 static bool
758 loop_delete_branch_edge (edge e, int really_delete)
759 {
760   basic_block src = e->src;
761   int irr;
762   edge snd;
763
764   if (src->succ->succ_next)
765     {
766       basic_block newdest;
767
768       /* Cannot handle more than two exit edges.  */
769       if (src->succ->succ_next->succ_next)
770         return false;
771       /* And it must be just a simple branch.  */
772       if (!any_condjump_p (BB_END (src)))
773         return false;
774
775       snd = e == src->succ ? src->succ->succ_next : src->succ;
776       newdest = snd->dest;
777       if (newdest == EXIT_BLOCK_PTR)
778         return false;
779
780       /* Hopefully the above conditions should suffice.  */
781       if (!really_delete)
782         return true;
783
784       /* Redirecting behaves wrongly wrto this flag.  */
785       irr = snd->flags & EDGE_IRREDUCIBLE_LOOP;
786
787       if (!redirect_edge_and_branch (e, newdest))
788         return false;
789       src->succ->flags &= ~EDGE_IRREDUCIBLE_LOOP;
790       src->succ->flags |= irr;
791
792       return true;
793     }
794   else
795     {
796       /* Cannot happen -- we are using this only to remove an edge
797          from branch.  */
798       abort ();
799     }
800
801   return false;  /* To avoid warning, cannot get here.  */
802 }
803
804 /* Check whether LOOP's body can be duplicated.  */
805 bool
806 can_duplicate_loop_p (struct loop *loop)
807 {
808   int ret;
809   basic_block *bbs = get_loop_body (loop);
810
811   ret = can_copy_bbs_p (bbs, loop->num_nodes);
812   free (bbs);
813   
814   return ret;
815 }
816
817
818 /* Duplicates body of LOOP to given edge E NDUPL times.  Takes care of updating
819    LOOPS structure and dominators.  E's destination must be LOOP header for
820    this to work, i.e. it must be entry or latch edge of this loop; these are
821    unique, as the loops must have preheaders for this function to work
822    correctly (in case E is latch, the function unrolls the loop, if E is entry
823    edge, it peels the loop).  Store edges created by copying ORIG edge from
824    copies corresponding to set bits in WONT_EXIT bitmap (bit 0 corresponds to
825    original LOOP body, the other copies are numbered in order given by control
826    flow through them) into TO_REMOVE array.  Returns false if duplication is
827    impossible.  */
828 int
829 duplicate_loop_to_header_edge (struct loop *loop, edge e, struct loops *loops,
830                                unsigned int ndupl, sbitmap wont_exit,
831                                edge orig, edge *to_remove,
832                                unsigned int *n_to_remove, int flags)
833 {
834   struct loop *target, *aloop;
835   struct loop **orig_loops;
836   unsigned n_orig_loops;
837   basic_block header = loop->header, latch = loop->latch;
838   basic_block *new_bbs, *bbs, *first_active;
839   basic_block new_bb, bb, first_active_latch = NULL;
840   edge ae, latch_edge;
841   edge spec_edges[2], new_spec_edges[2];
842 #define SE_LATCH 0
843 #define SE_ORIG 1
844   unsigned i, j, n;
845   int is_latch = (latch == e->src);
846   int scale_act = 0, *scale_step = NULL, scale_main = 0;
847   int p, freq_in, freq_le, freq_out_orig;
848   int prob_pass_thru, prob_pass_wont_exit, prob_pass_main;
849   int add_irreducible_flag;
850
851   if (e->dest != loop->header)
852     abort ();
853   if (ndupl <= 0)
854     abort ();
855
856   if (orig)
857     {
858       /* Orig must be edge out of the loop.  */
859       if (!flow_bb_inside_loop_p (loop, orig->src))
860         abort ();
861       if (flow_bb_inside_loop_p (loop, orig->dest))
862         abort ();
863     }
864
865   bbs = get_loop_body (loop);
866
867   /* Check whether duplication is possible.  */
868   if (!can_copy_bbs_p (bbs, loop->num_nodes))
869     {
870       free (bbs);
871       return false;
872     }
873   new_bbs = xmalloc (sizeof (basic_block) * loop->num_nodes);
874
875   /* In case we are doing loop peeling and the loop is in the middle of
876      irreducible region, the peeled copies will be inside it too.  */
877   add_irreducible_flag = e->flags & EDGE_IRREDUCIBLE_LOOP;
878   if (is_latch && add_irreducible_flag)
879     abort ();
880
881   /* Find edge from latch.  */
882   latch_edge = loop_latch_edge (loop);
883
884   if (flags & DLTHE_FLAG_UPDATE_FREQ)
885     {
886       /* Calculate coefficients by that we have to scale frequencies
887          of duplicated loop bodies.  */
888       freq_in = header->frequency;
889       freq_le = EDGE_FREQUENCY (latch_edge);
890       if (freq_in == 0)
891         freq_in = 1;
892       if (freq_in < freq_le)
893         freq_in = freq_le;
894       freq_out_orig = orig ? EDGE_FREQUENCY (orig) : freq_in - freq_le;
895       if (freq_out_orig > freq_in - freq_le)
896         freq_out_orig = freq_in - freq_le;
897       prob_pass_thru = RDIV (REG_BR_PROB_BASE * freq_le, freq_in);
898       prob_pass_wont_exit =
899               RDIV (REG_BR_PROB_BASE * (freq_le + freq_out_orig), freq_in);
900
901       scale_step = xmalloc (ndupl * sizeof (int));
902
903         for (i = 1; i <= ndupl; i++)
904           scale_step[i - 1] = TEST_BIT (wont_exit, i)
905                                 ? prob_pass_wont_exit
906                                 : prob_pass_thru;
907
908       if (is_latch)
909         {
910           prob_pass_main = TEST_BIT (wont_exit, 0)
911                                 ? prob_pass_wont_exit
912                                 : prob_pass_thru;
913           p = prob_pass_main;
914           scale_main = REG_BR_PROB_BASE;
915           for (i = 0; i < ndupl; i++)
916             {
917               scale_main += p;
918               p = RDIV (p * scale_step[i], REG_BR_PROB_BASE);
919             }
920           scale_main = RDIV (REG_BR_PROB_BASE * REG_BR_PROB_BASE, scale_main);
921           scale_act = RDIV (scale_main * prob_pass_main, REG_BR_PROB_BASE);
922         }
923       else
924         {
925           scale_main = REG_BR_PROB_BASE;
926           for (i = 0; i < ndupl; i++)
927             scale_main = RDIV (scale_main * scale_step[i], REG_BR_PROB_BASE);
928           scale_act = REG_BR_PROB_BASE - prob_pass_thru;
929         }
930       for (i = 0; i < ndupl; i++)
931         if (scale_step[i] < 0 || scale_step[i] > REG_BR_PROB_BASE)
932           abort ();
933       if (scale_main < 0 || scale_main > REG_BR_PROB_BASE
934           || scale_act < 0  || scale_act > REG_BR_PROB_BASE)
935         abort ();
936     }
937
938   /* Loop the new bbs will belong to.  */
939   target = e->src->loop_father;
940
941   /* Original loops.  */
942   n_orig_loops = 0;
943   for (aloop = loop->inner; aloop; aloop = aloop->next)
944     n_orig_loops++;
945   orig_loops = xcalloc (n_orig_loops, sizeof (struct loop *));
946   for (aloop = loop->inner, i = 0; aloop; aloop = aloop->next, i++)
947     orig_loops[i] = aloop;
948
949   loop->copy = target;
950
951   n = loop->num_nodes;
952
953   first_active = xmalloc (n * sizeof (basic_block));
954   if (is_latch)
955     {
956       memcpy (first_active, bbs, n * sizeof (basic_block));
957       first_active_latch = latch;
958     }
959
960   /* Record exit edge in original loop body.  */
961   if (orig && TEST_BIT (wont_exit, 0))
962     to_remove[(*n_to_remove)++] = orig;
963
964   spec_edges[SE_ORIG] = orig;
965   spec_edges[SE_LATCH] = latch_edge;
966
967   for (j = 0; j < ndupl; j++)
968     {
969       /* Copy loops.  */
970       copy_loops_to (loops, orig_loops, n_orig_loops, target);
971
972       /* Copy bbs.  */
973       copy_bbs (bbs, n, new_bbs, spec_edges, 2, new_spec_edges, loop);
974
975       /* Note whether the blocks and edges belong to an irreducible loop.  */
976       if (add_irreducible_flag)
977         {
978           for (i = 0; i < n; i++)
979             new_bbs[i]->rbi->duplicated = 1;
980           for (i = 0; i < n; i++)
981             {
982               new_bb = new_bbs[i];
983               if (new_bb->loop_father == target)
984                 new_bb->flags |= BB_IRREDUCIBLE_LOOP;
985
986               for (ae = new_bb->succ; ae; ae = ae->succ_next)
987                 if (ae->dest->rbi->duplicated
988                     && (ae->src->loop_father == target
989                         || ae->dest->loop_father == target))
990                   ae->flags |= EDGE_IRREDUCIBLE_LOOP;
991             }
992           for (i = 0; i < n; i++)
993             new_bbs[i]->rbi->duplicated = 0;
994         }
995
996       /* Redirect the special edges.  */
997       if (is_latch)
998         {
999           redirect_edge_and_branch_force (latch_edge, new_bbs[0]);
1000           redirect_edge_and_branch_force (new_spec_edges[SE_LATCH],
1001                                           loop->header);
1002           set_immediate_dominator (CDI_DOMINATORS, new_bbs[0], latch);
1003           latch = loop->latch = new_bbs[1];
1004           e = latch_edge = new_spec_edges[SE_LATCH];
1005         }
1006       else
1007         {
1008           redirect_edge_and_branch_force (new_spec_edges[SE_LATCH],
1009                                           loop->header);
1010           redirect_edge_and_branch_force (e, new_bbs[0]);
1011           set_immediate_dominator (CDI_DOMINATORS, new_bbs[0], e->src);
1012           e = new_spec_edges[SE_LATCH];
1013         }
1014
1015       /* Record exit edge in this copy.  */
1016       if (orig && TEST_BIT (wont_exit, j + 1))
1017         to_remove[(*n_to_remove)++] = new_spec_edges[SE_ORIG];
1018
1019       /* Record the first copy in the control flow order if it is not
1020          the original loop (i.e. in case of peeling).  */
1021       if (!first_active_latch)
1022         {
1023           memcpy (first_active, new_bbs, n * sizeof (basic_block));
1024           first_active_latch = new_bbs[1];
1025         }
1026
1027       /* Set counts and frequencies.  */
1028       if (flags & DLTHE_FLAG_UPDATE_FREQ)
1029         {
1030           scale_bbs_frequencies (new_bbs, n, scale_act, REG_BR_PROB_BASE);
1031           scale_act = RDIV (scale_act * scale_step[j], REG_BR_PROB_BASE);
1032         }
1033     }
1034   free (new_bbs);
1035   free (orig_loops);
1036   
1037   /* Update the original loop.  */
1038   if (!is_latch)
1039     set_immediate_dominator (CDI_DOMINATORS, e->dest, e->src);
1040   if (flags & DLTHE_FLAG_UPDATE_FREQ)
1041     {
1042       scale_bbs_frequencies (bbs, n, scale_main, REG_BR_PROB_BASE);
1043       free (scale_step);
1044     }
1045
1046   /* Update dominators of outer blocks if affected.  */
1047   for (i = 0; i < n; i++)
1048     {
1049       basic_block dominated, dom_bb, *dom_bbs;
1050       int n_dom_bbs,j;
1051
1052       bb = bbs[i];
1053       n_dom_bbs = get_dominated_by (CDI_DOMINATORS, bb, &dom_bbs);
1054       for (j = 0; j < n_dom_bbs; j++)
1055         {
1056           dominated = dom_bbs[j];
1057           if (flow_bb_inside_loop_p (loop, dominated))
1058             continue;
1059           dom_bb = nearest_common_dominator (
1060                         CDI_DOMINATORS, first_active[i], first_active_latch);
1061           set_immediate_dominator (CDI_DOMINATORS, dominated, dom_bb);
1062         }
1063       free (dom_bbs);
1064     }
1065   free (first_active);
1066
1067   free (bbs);
1068
1069   return true;
1070 }
1071
1072 /* A callback for make_forwarder block, to redirect all edges except for
1073    MFB_KJ_EDGE to the entry part.  E is the edge for that we should decide
1074    whether to redirect it.  */
1075
1076 static edge mfb_kj_edge;
1077 static bool
1078 mfb_keep_just (edge e)
1079 {
1080   return e != mfb_kj_edge;
1081 }
1082
1083 /* A callback for make_forwarder block, to update data structures for a basic
1084    block JUMP created by redirecting an edge (only the latch edge is being
1085    redirected).  */
1086
1087 static void
1088 mfb_update_loops (basic_block jump)
1089 {
1090   struct loop *loop = jump->succ->dest->loop_father;
1091
1092   if (dom_computed[CDI_DOMINATORS])
1093     set_immediate_dominator (CDI_DOMINATORS, jump, jump->pred->src);
1094   add_bb_to_loop (jump, loop);
1095   loop->latch = jump;
1096 }
1097
1098 /* Creates a pre-header for a LOOP.  Returns newly created block.  Unless
1099    CP_SIMPLE_PREHEADERS is set in FLAGS, we only force LOOP to have single
1100    entry; otherwise we also force preheader block to have only one successor.
1101    The function also updates dominators.  */
1102
1103 static basic_block
1104 create_preheader (struct loop *loop, int flags)
1105 {
1106   edge e, fallthru;
1107   basic_block dummy;
1108   struct loop *cloop, *ploop;
1109   int nentry = 0;
1110   bool irred = false;
1111
1112   cloop = loop->outer;
1113
1114   for (e = loop->header->pred; e; e = e->pred_next)
1115     {
1116       if (e->src == loop->latch)
1117         continue;
1118       irred |= (e->flags & EDGE_IRREDUCIBLE_LOOP) != 0;
1119       nentry++;
1120     }
1121   if (!nentry)
1122     abort ();
1123   if (nentry == 1)
1124     {
1125       for (e = loop->header->pred; e->src == loop->latch; e = e->pred_next);
1126       if (!(flags & CP_SIMPLE_PREHEADERS)
1127           || !e->src->succ->succ_next)
1128         return NULL;
1129     }
1130
1131   mfb_kj_edge = loop_latch_edge (loop);
1132   fallthru = make_forwarder_block (loop->header, mfb_keep_just,
1133                                    mfb_update_loops);
1134   dummy = fallthru->src;
1135   loop->header = fallthru->dest;
1136
1137   /* The header could be a latch of some superloop(s); due to design of
1138      split_block, it would now move to fallthru->dest.  */
1139   for (ploop = loop; ploop; ploop = ploop->outer)
1140     if (ploop->latch == dummy)
1141       ploop->latch = fallthru->dest;
1142
1143   /* Reorganize blocks so that the preheader is not stuck in the middle of the
1144      loop.  */
1145   for (e = dummy->pred; e; e = e->pred_next)
1146     if (e->src != loop->latch)
1147       break;
1148   move_block_after (dummy, e->src);
1149
1150   loop->header->loop_father = loop;
1151   add_bb_to_loop (dummy, cloop);
1152
1153   if (irred)
1154     {
1155       dummy->flags |= BB_IRREDUCIBLE_LOOP;
1156       dummy->succ->flags |= EDGE_IRREDUCIBLE_LOOP;
1157     }
1158
1159   if (dump_file)
1160     fprintf (dump_file, "Created preheader block for loop %i\n",
1161              loop->num);
1162
1163   return dummy;
1164 }
1165
1166 /* Create preheaders for each loop from loop tree stored in LOOPS; for meaning
1167    of FLAGS see create_preheader.  */
1168 void
1169 create_preheaders (struct loops *loops, int flags)
1170 {
1171   unsigned i;
1172   for (i = 1; i < loops->num; i++)
1173     create_preheader (loops->parray[i], flags);
1174   loops->state |= LOOPS_HAVE_PREHEADERS;
1175 }
1176
1177 /* Forces all loop latches of loops from loop tree LOOPS to have only single
1178    successor.  */
1179 void
1180 force_single_succ_latches (struct loops *loops)
1181 {
1182   unsigned i;
1183   struct loop *loop;
1184   edge e;
1185
1186   for (i = 1; i < loops->num; i++)
1187     {
1188       loop = loops->parray[i];
1189       if (loop->latch != loop->header
1190           && !loop->latch->succ->succ_next)
1191         continue;
1192
1193       for (e = loop->header->pred; e->src != loop->latch; e = e->pred_next)
1194         continue;
1195
1196       loop_split_edge_with (e, NULL_RTX);
1197     }
1198   loops->state |= LOOPS_HAVE_SIMPLE_LATCHES;
1199 }
1200
1201 /* A quite stupid function to put INSNS on edge E. They are supposed to form
1202    just one basic block.  Jumps in INSNS are not handled, so cfg do not have to
1203    be ok after this function.  The created block is placed on correct place
1204    in LOOPS structure and its dominator is set.  */
1205 basic_block
1206 loop_split_edge_with (edge e, rtx insns)
1207 {
1208   basic_block src, dest, new_bb;
1209   struct loop *loop_c;
1210   edge new_e;
1211
1212   src = e->src;
1213   dest = e->dest;
1214
1215   loop_c = find_common_loop (src->loop_father, dest->loop_father);
1216
1217   /* Create basic block for it.  */
1218
1219   new_bb = split_edge (e);
1220   add_bb_to_loop (new_bb, loop_c);
1221   new_bb->flags = insns ? BB_SUPERBLOCK : 0;
1222
1223   new_e = new_bb->succ;
1224   if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1225     {
1226       new_bb->flags |= BB_IRREDUCIBLE_LOOP;
1227       new_e->flags |= EDGE_IRREDUCIBLE_LOOP;
1228     }
1229
1230   if (insns)
1231     emit_insn_after (insns, BB_END (new_bb));
1232
1233   if (dest->loop_father->latch == src)
1234     dest->loop_father->latch = new_bb;
1235
1236   return new_bb;
1237 }