OSDN Git Service

gcc/
[pf3gnuchains/gcc-fork.git] / gcc / cfgloopmanip.c
1 /* Loop manipulation code for GNU compiler.
2    Copyright (C) 2002, 2003, 2004, 2005 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, 51 Franklin Street, Fifth Floor, Boston, MA
19 02110-1301, 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 "obstack.h"
28 #include "basic-block.h"
29 #include "cfgloop.h"
30 #include "cfglayout.h"
31 #include "cfghooks.h"
32 #include "output.h"
33
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 loops *, 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 basic_block create_preheader (struct loop *, int);
50 static void fix_irreducible_loops (basic_block);
51 static void unloop (struct loops *, struct loop *);
52
53 #define RDIV(X,Y) (((X) + (Y) / 2) / (Y))
54
55 /* Checks whether basic block BB is dominated by DATA.  */
56 static bool
57 rpe_enum_p (basic_block bb, void *data)
58 {
59   return dominated_by_p (CDI_DOMINATORS, bb, data);
60 }
61
62 /* Remove basic blocks BBS from loop structure and dominance info,
63    and delete them afterwards.  */
64 static void
65 remove_bbs (basic_block *bbs, int nbbs)
66 {
67   int i;
68
69   for (i = 0; i < nbbs; i++)
70     {
71       remove_bb_from_loops (bbs[i]);
72       delete_basic_block (bbs[i]);
73     }
74 }
75
76 /* Find path -- i.e. the basic blocks dominated by edge E and put them
77    into array BBS, that will be allocated large enough to contain them.
78    E->dest must have exactly one predecessor for this to work (it is
79    easy to achieve and we do not put it here because we do not want to
80    alter anything by this function).  The number of basic blocks in the
81    path is returned.  */
82 static int
83 find_path (edge e, basic_block **bbs)
84 {
85   gcc_assert (EDGE_COUNT (e->dest->preds) <= 1);
86
87   /* Find bbs in the path.  */
88   *bbs = XCNEWVEC (basic_block, n_basic_blocks);
89   return dfs_enumerate_from (e->dest, 0, rpe_enum_p, *bbs,
90                              n_basic_blocks, e->dest);
91 }
92
93 /* Fix placement of basic block BB inside loop hierarchy stored in LOOPS --
94    Let L be a loop to that BB belongs.  Then every successor of BB must either
95      1) belong to some superloop of loop L, or
96      2) be a header of loop K such that K->outer is superloop of L
97    Returns true if we had to move BB into other loop to enforce this condition,
98    false if the placement of BB was already correct (provided that placements
99    of its successors are correct).  */
100 static bool
101 fix_bb_placement (struct loops *loops, basic_block bb)
102 {
103   edge e;
104   edge_iterator ei;
105   struct loop *loop = loops->tree_root, *act;
106
107   FOR_EACH_EDGE (e, ei, bb->succs)
108     {
109       if (e->dest == EXIT_BLOCK_PTR)
110         continue;
111
112       act = e->dest->loop_father;
113       if (act->header == e->dest)
114         act = act->outer;
115
116       if (flow_loop_nested_p (loop, act))
117         loop = act;
118     }
119
120   if (loop == bb->loop_father)
121     return false;
122
123   remove_bb_from_loops (bb);
124   add_bb_to_loop (bb, loop);
125
126   return true;
127 }
128
129 /* Fix placements of basic blocks inside loop hierarchy stored in loops; i.e.
130    enforce condition condition stated in description of fix_bb_placement. We
131    start from basic block FROM that had some of its successors removed, so that
132    his placement no longer has to be correct, and iteratively fix placement of
133    its predecessors that may change if placement of FROM changed.  Also fix
134    placement of subloops of FROM->loop_father, that might also be altered due
135    to this change; the condition for them is similar, except that instead of
136    successors we consider edges coming out of the loops.  */
137 static void
138 fix_bb_placements (struct loops *loops, basic_block from)
139 {
140   sbitmap in_queue;
141   basic_block *queue, *qtop, *qbeg, *qend;
142   struct loop *base_loop;
143   edge e;
144
145   /* We pass through blocks back-reachable from FROM, testing whether some
146      of their successors moved to outer loop.  It may be necessary to
147      iterate several times, but it is finite, as we stop unless we move
148      the basic block up the loop structure.  The whole story is a bit
149      more complicated due to presence of subloops, those are moved using
150      fix_loop_placement.  */
151
152   base_loop = from->loop_father;
153   if (base_loop == loops->tree_root)
154     return;
155
156   in_queue = sbitmap_alloc (last_basic_block);
157   sbitmap_zero (in_queue);
158   SET_BIT (in_queue, from->index);
159   /* Prevent us from going out of the base_loop.  */
160   SET_BIT (in_queue, base_loop->header->index);
161
162   queue = XNEWVEC (basic_block, base_loop->num_nodes + 1);
163   qtop = queue + base_loop->num_nodes + 1;
164   qbeg = queue;
165   qend = queue + 1;
166   *qbeg = from;
167
168   while (qbeg != qend)
169     {
170       edge_iterator ei;
171       from = *qbeg;
172       qbeg++;
173       if (qbeg == qtop)
174         qbeg = queue;
175       RESET_BIT (in_queue, from->index);
176
177       if (from->loop_father->header == from)
178         {
179           /* Subloop header, maybe move the loop upward.  */
180           if (!fix_loop_placement (from->loop_father))
181             continue;
182         }
183       else
184         {
185           /* Ordinary basic block.  */
186           if (!fix_bb_placement (loops, from))
187             continue;
188         }
189
190       /* Something has changed, insert predecessors into queue.  */
191       FOR_EACH_EDGE (e, ei, from->preds)
192         {
193           basic_block pred = e->src;
194           struct loop *nca;
195
196           if (TEST_BIT (in_queue, pred->index))
197             continue;
198
199           /* If it is subloop, then it either was not moved, or
200              the path up the loop tree from base_loop do not contain
201              it.  */
202           nca = find_common_loop (pred->loop_father, base_loop);
203           if (pred->loop_father != base_loop
204               && (nca == base_loop
205                   || nca != pred->loop_father))
206             pred = pred->loop_father->header;
207           else if (!flow_loop_nested_p (from->loop_father, pred->loop_father))
208             {
209               /* No point in processing it.  */
210               continue;
211             }
212
213           if (TEST_BIT (in_queue, pred->index))
214             continue;
215
216           /* Schedule the basic block.  */
217           *qend = pred;
218           qend++;
219           if (qend == qtop)
220             qend = queue;
221           SET_BIT (in_queue, pred->index);
222         }
223     }
224   free (in_queue);
225   free (queue);
226 }
227
228 /* Basic block from has lost one or more of its predecessors, so it might
229    mo longer be part irreducible loop.  Fix it and proceed recursively
230    for its successors if needed.  */
231 static void
232 fix_irreducible_loops (basic_block from)
233 {
234   basic_block bb;
235   basic_block *stack;
236   int stack_top;
237   sbitmap on_stack;
238   edge *edges, e;
239   unsigned num_edges, i;
240
241   if (!(from->flags & BB_IRREDUCIBLE_LOOP))
242     return;
243
244   on_stack = sbitmap_alloc (last_basic_block);
245   sbitmap_zero (on_stack);
246   SET_BIT (on_stack, from->index);
247   stack = XNEWVEC (basic_block, from->loop_father->num_nodes);
248   stack[0] = from;
249   stack_top = 1;
250
251   while (stack_top)
252     {
253       edge_iterator ei;
254       bb = stack[--stack_top];
255       RESET_BIT (on_stack, bb->index);
256
257       FOR_EACH_EDGE (e, ei, bb->preds)
258         if (e->flags & EDGE_IRREDUCIBLE_LOOP)
259           break;
260       if (e)
261         continue;
262
263       bb->flags &= ~BB_IRREDUCIBLE_LOOP;
264       if (bb->loop_father->header == bb)
265         edges = get_loop_exit_edges (bb->loop_father, &num_edges);
266       else
267         {
268           num_edges = EDGE_COUNT (bb->succs);
269           edges = XNEWVEC (edge, num_edges);
270           FOR_EACH_EDGE (e, ei, bb->succs)
271             edges[ei.index] = e;
272         }
273
274       for (i = 0; i < num_edges; i++)
275         {
276           e = edges[i];
277
278           if (e->flags & EDGE_IRREDUCIBLE_LOOP)
279             {
280               if (!flow_bb_inside_loop_p (from->loop_father, e->dest))
281                 continue;
282
283               e->flags &= ~EDGE_IRREDUCIBLE_LOOP;
284               if (TEST_BIT (on_stack, e->dest->index))
285                 continue;
286
287               SET_BIT (on_stack, e->dest->index);
288               stack[stack_top++] = e->dest;
289             }
290         }
291       free (edges);
292     }
293
294   free (on_stack);
295   free (stack);
296 }
297
298 /* Removes path beginning at edge E, i.e. remove basic blocks dominated by E
299    and update loop structure stored in LOOPS and dominators.  Return true if
300    we were able to remove the path, false otherwise (and nothing is affected
301    then).  */
302 bool
303 remove_path (struct loops *loops, edge e)
304 {
305   edge ae;
306   basic_block *rem_bbs, *bord_bbs, *dom_bbs, from, bb;
307   int i, nrem, n_bord_bbs, n_dom_bbs;
308   sbitmap seen;
309   bool deleted;
310
311   if (!loop_delete_branch_edge (e, 0))
312     return false;
313
314   /* We need to check whether basic blocks are dominated by the edge
315      e, but we only have basic block dominators.  This is easy to
316      fix -- when e->dest has exactly one predecessor, this corresponds
317      to blocks dominated by e->dest, if not, split the edge.  */
318   if (!single_pred_p (e->dest))
319     e = single_pred_edge (loop_split_edge_with (e, NULL_RTX));
320
321   /* It may happen that by removing path we remove one or more loops
322      we belong to.  In this case first unloop the loops, then proceed
323      normally.   We may assume that e->dest is not a header of any loop,
324      as it now has exactly one predecessor.  */
325   while (e->src->loop_father->outer
326          && dominated_by_p (CDI_DOMINATORS,
327                             e->src->loop_father->latch, e->dest))
328     unloop (loops, e->src->loop_father);
329
330   /* Identify the path.  */
331   nrem = find_path (e, &rem_bbs);
332
333   n_bord_bbs = 0;
334   bord_bbs = XCNEWVEC (basic_block, n_basic_blocks);
335   seen = sbitmap_alloc (last_basic_block);
336   sbitmap_zero (seen);
337
338   /* Find "border" hexes -- i.e. those with predecessor in removed path.  */
339   for (i = 0; i < nrem; i++)
340     SET_BIT (seen, rem_bbs[i]->index);
341   for (i = 0; i < nrem; i++)
342     {
343       edge_iterator ei;
344       bb = rem_bbs[i];
345       FOR_EACH_EDGE (ae, ei, rem_bbs[i]->succs)
346         if (ae->dest != EXIT_BLOCK_PTR && !TEST_BIT (seen, ae->dest->index))
347           {
348             SET_BIT (seen, ae->dest->index);
349             bord_bbs[n_bord_bbs++] = ae->dest;
350           }
351     }
352
353   /* Remove the path.  */
354   from = e->src;
355   deleted = loop_delete_branch_edge (e, 1);
356   gcc_assert (deleted);
357   dom_bbs = XCNEWVEC (basic_block, n_basic_blocks);
358
359   /* Cancel loops contained in the path.  */
360   for (i = 0; i < nrem; i++)
361     if (rem_bbs[i]->loop_father->header == rem_bbs[i])
362       cancel_loop_tree (loops, rem_bbs[i]->loop_father);
363
364   remove_bbs (rem_bbs, nrem);
365   free (rem_bbs);
366
367   /* Find blocks whose dominators may be affected.  */
368   n_dom_bbs = 0;
369   sbitmap_zero (seen);
370   for (i = 0; i < n_bord_bbs; i++)
371     {
372       basic_block ldom;
373
374       bb = get_immediate_dominator (CDI_DOMINATORS, bord_bbs[i]);
375       if (TEST_BIT (seen, bb->index))
376         continue;
377       SET_BIT (seen, bb->index);
378
379       for (ldom = first_dom_son (CDI_DOMINATORS, bb);
380            ldom;
381            ldom = next_dom_son (CDI_DOMINATORS, ldom))
382         if (!dominated_by_p (CDI_DOMINATORS, from, ldom))
383           dom_bbs[n_dom_bbs++] = ldom;
384     }
385
386   free (seen);
387
388   /* Recount dominators.  */
389   iterate_fix_dominators (CDI_DOMINATORS, dom_bbs, n_dom_bbs);
390   free (dom_bbs);
391
392   /* These blocks have lost some predecessor(s), thus their irreducible
393      status could be changed.  */
394   for (i = 0; i < n_bord_bbs; i++)
395     fix_irreducible_loops (bord_bbs[i]);
396   free (bord_bbs);
397
398   /* Fix placements of basic blocks inside loops and the placement of
399      loops in the loop tree.  */
400   fix_bb_placements (loops, from);
401   fix_loop_placements (loops, from->loop_father);
402
403   return true;
404 }
405
406 /* Predicate for enumeration in add_loop.  */
407 static bool
408 alp_enum_p (basic_block bb, void *alp_header)
409 {
410   return bb != (basic_block) alp_header;
411 }
412
413 /* Given LOOP structure with filled header and latch, find the body of the
414    corresponding loop and add it to LOOPS tree.  */
415 static void
416 add_loop (struct loops *loops, struct loop *loop)
417 {
418   basic_block *bbs;
419   int i, n;
420
421   /* Add it to loop structure.  */
422   place_new_loop (loops, loop);
423   loop->level = 1;
424
425   /* Find its nodes.  */
426   bbs = XCNEWVEC (basic_block, n_basic_blocks);
427   n = dfs_enumerate_from (loop->latch, 1, alp_enum_p,
428                           bbs, n_basic_blocks, loop->header);
429
430   for (i = 0; i < n; i++)
431     add_bb_to_loop (bbs[i], loop);
432   add_bb_to_loop (loop->header, loop);
433
434   free (bbs);
435 }
436
437 /* Multiply all frequencies in LOOP by NUM/DEN.  */
438 static void
439 scale_loop_frequencies (struct loop *loop, int num, int den)
440 {
441   basic_block *bbs;
442
443   bbs = get_loop_body (loop);
444   scale_bbs_frequencies_int (bbs, loop->num_nodes, num, den);
445   free (bbs);
446 }
447
448 /* Make area between HEADER_EDGE and LATCH_EDGE a loop by connecting
449    latch to header and update loop tree stored in LOOPS and dominators
450    accordingly. Everything between them plus LATCH_EDGE destination must
451    be dominated by HEADER_EDGE destination, and back-reachable from
452    LATCH_EDGE source.  HEADER_EDGE is redirected to basic block SWITCH_BB,
453    FALSE_EDGE of SWITCH_BB to original destination of HEADER_EDGE and
454    TRUE_EDGE of SWITCH_BB to original destination of LATCH_EDGE.
455    Returns newly created loop.  */
456
457 struct loop *
458 loopify (struct loops *loops, edge latch_edge, edge header_edge, 
459          basic_block switch_bb, edge true_edge, edge false_edge,
460          bool redirect_all_edges)
461 {
462   basic_block succ_bb = latch_edge->dest;
463   basic_block pred_bb = header_edge->src;
464   basic_block *dom_bbs, *body;
465   unsigned n_dom_bbs, i;
466   sbitmap seen;
467   struct loop *loop = XCNEW (struct loop);
468   struct loop *outer = succ_bb->loop_father->outer;
469   int freq, prob, tot_prob;
470   gcov_type cnt;
471   edge e;
472   edge_iterator ei;
473
474   loop->header = header_edge->dest;
475   loop->latch = latch_edge->src;
476
477   freq = EDGE_FREQUENCY (header_edge);
478   cnt = header_edge->count;
479   prob = EDGE_SUCC (switch_bb, 0)->probability;
480   tot_prob = prob + EDGE_SUCC (switch_bb, 1)->probability;
481   if (tot_prob == 0)
482     tot_prob = 1;
483
484   /* Redirect edges.  */
485   loop_redirect_edge (latch_edge, loop->header);
486   loop_redirect_edge (true_edge, succ_bb);
487
488   /* During loop versioning, one of the switch_bb edge is already properly
489      set. Do not redirect it again unless redirect_all_edges is true.  */
490   if (redirect_all_edges)
491     {
492       loop_redirect_edge (header_edge, switch_bb);
493       loop_redirect_edge (false_edge, loop->header); 
494      
495       /* Update dominators.  */
496       set_immediate_dominator (CDI_DOMINATORS, switch_bb, pred_bb);
497       set_immediate_dominator (CDI_DOMINATORS, loop->header, switch_bb);
498     }
499
500   set_immediate_dominator (CDI_DOMINATORS, succ_bb, switch_bb);
501
502   /* Compute new loop.  */
503   add_loop (loops, loop);
504   flow_loop_tree_node_add (outer, loop);
505
506   /* Add switch_bb to appropriate loop.  */
507   add_bb_to_loop (switch_bb, outer);
508
509   /* Fix frequencies.  */
510   switch_bb->frequency = freq;
511   switch_bb->count = cnt;
512   FOR_EACH_EDGE (e, ei, switch_bb->succs)
513     e->count = (switch_bb->count * e->probability) / REG_BR_PROB_BASE;
514   scale_loop_frequencies (loop, prob, tot_prob);
515   scale_loop_frequencies (succ_bb->loop_father, tot_prob - prob, tot_prob);
516
517   /* Update dominators of blocks outside of LOOP.  */
518   dom_bbs = XCNEWVEC (basic_block, n_basic_blocks);
519   n_dom_bbs = 0;
520   seen = sbitmap_alloc (last_basic_block);
521   sbitmap_zero (seen);
522   body = get_loop_body (loop);
523
524   for (i = 0; i < loop->num_nodes; i++)
525     SET_BIT (seen, body[i]->index);
526
527   for (i = 0; i < loop->num_nodes; i++)
528     {
529       basic_block ldom;
530
531       for (ldom = first_dom_son (CDI_DOMINATORS, body[i]);
532            ldom;
533            ldom = next_dom_son (CDI_DOMINATORS, ldom))
534         if (!TEST_BIT (seen, ldom->index))
535           {
536             SET_BIT (seen, ldom->index);
537             dom_bbs[n_dom_bbs++] = ldom;
538           }
539     }
540
541   iterate_fix_dominators (CDI_DOMINATORS, dom_bbs, n_dom_bbs);
542
543   free (body);
544   free (seen);
545   free (dom_bbs);
546
547   return loop;
548 }
549
550 /* Remove the latch edge of a LOOP and update LOOPS tree to indicate that
551    the LOOP was removed.  After this function, original loop latch will
552    have no successor, which caller is expected to fix somehow.  */
553 static void
554 unloop (struct loops *loops, struct loop *loop)
555 {
556   basic_block *body;
557   struct loop *ploop;
558   unsigned i, n;
559   basic_block latch = loop->latch;
560   edge *edges;
561   unsigned num_edges;
562
563   /* This is relatively straightforward.  The dominators are unchanged, as
564      loop header dominates loop latch, so the only thing we have to care of
565      is the placement of loops and basic blocks inside the loop tree.  We
566      move them all to the loop->outer, and then let fix_bb_placements do
567      its work.  */
568
569   body = get_loop_body (loop);
570   edges = get_loop_exit_edges (loop, &num_edges);
571   n = loop->num_nodes;
572   for (i = 0; i < n; i++)
573     if (body[i]->loop_father == loop)
574       {
575         remove_bb_from_loops (body[i]);
576         add_bb_to_loop (body[i], loop->outer);
577       }
578   free(body);
579
580   while (loop->inner)
581     {
582       ploop = loop->inner;
583       flow_loop_tree_node_remove (ploop);
584       flow_loop_tree_node_add (loop->outer, ploop);
585     }
586
587   /* Remove the loop and free its data.  */
588   flow_loop_tree_node_remove (loop);
589   loops->parray[loop->num] = NULL;
590   flow_loop_free (loop);
591
592   remove_edge (single_succ_edge (latch));
593   fix_bb_placements (loops, latch);
594
595   /* If the loop was inside an irreducible region, we would have to somehow
596      update the irreducible marks inside its body.  While it is certainly
597      possible to do, it is a bit complicated and this situation should be
598      very rare, so we just remark all loops in this case.  */
599   for (i = 0; i < num_edges; i++)
600     if (edges[i]->flags & EDGE_IRREDUCIBLE_LOOP)
601       break;
602   if (i != num_edges)
603     mark_irreducible_loops (loops);
604   free (edges);
605 }
606
607 /* Fix placement of LOOP inside loop tree, i.e. find the innermost superloop
608    FATHER of LOOP such that all of the edges coming out of LOOP belong to
609    FATHER, and set it as outer loop of LOOP.  Return 1 if placement of
610    LOOP changed.  */
611 int
612 fix_loop_placement (struct loop *loop)
613 {
614   basic_block *body;
615   unsigned i;
616   edge e;
617   edge_iterator ei;
618   struct loop *father = loop->pred[0], *act;
619
620   body = get_loop_body (loop);
621   for (i = 0; i < loop->num_nodes; i++)
622     FOR_EACH_EDGE (e, ei, body[i]->succs)
623       if (!flow_bb_inside_loop_p (loop, e->dest))
624         {
625           act = find_common_loop (loop, e->dest->loop_father);
626           if (flow_loop_nested_p (father, act))
627             father = act;
628         }
629   free (body);
630
631   if (father != loop->outer)
632     {
633       for (act = loop->outer; act != father; act = act->outer)
634         act->num_nodes -= loop->num_nodes;
635       flow_loop_tree_node_remove (loop);
636       flow_loop_tree_node_add (father, loop);
637       return 1;
638     }
639   return 0;
640 }
641
642 /* Fix placement of superloops of LOOP inside loop tree, i.e. ensure that
643    condition stated in description of fix_loop_placement holds for them.
644    It is used in case when we removed some edges coming out of LOOP, which
645    may cause the right placement of LOOP inside loop tree to change.  */
646 static void
647 fix_loop_placements (struct loops *loops, struct loop *loop)
648 {
649   struct loop *outer;
650
651   while (loop->outer)
652     {
653       outer = loop->outer;
654       if (!fix_loop_placement (loop))
655         break;
656
657       /* Changing the placement of a loop in the loop tree may alter the
658          validity of condition 2) of the description of fix_bb_placement
659          for its preheader, because the successor is the header and belongs
660          to the loop.  So call fix_bb_placements to fix up the placement
661          of the preheader and (possibly) of its predecessors.  */
662       fix_bb_placements (loops, loop_preheader_edge (loop)->src);
663       loop = outer;
664     }
665 }
666
667 /* Creates place for a new LOOP in LOOPS structure.  */
668 static void
669 place_new_loop (struct loops *loops, struct loop *loop)
670 {
671   loops->parray =
672     xrealloc (loops->parray, (loops->num + 1) * sizeof (struct loop *));
673   loops->parray[loops->num] = loop;
674
675   loop->num = loops->num++;
676 }
677
678 /* Copies copy of LOOP as subloop of TARGET loop, placing newly
679    created loop into LOOPS structure.  */
680 struct loop *
681 duplicate_loop (struct loops *loops, struct loop *loop, struct loop *target)
682 {
683   struct loop *cloop;
684   cloop = XCNEW (struct loop);
685   place_new_loop (loops, cloop);
686
687   /* Initialize copied loop.  */
688   cloop->level = loop->level;
689
690   /* Set it as copy of loop.  */
691   loop->copy = cloop;
692
693   /* Add it to target.  */
694   flow_loop_tree_node_add (target, cloop);
695
696   return cloop;
697 }
698
699 /* Copies structure of subloops of LOOP into TARGET loop, placing
700    newly created loops into loop tree stored in LOOPS.  */
701 static void
702 duplicate_subloops (struct loops *loops, struct loop *loop, struct loop *target)
703 {
704   struct loop *aloop, *cloop;
705
706   for (aloop = loop->inner; aloop; aloop = aloop->next)
707     {
708       cloop = duplicate_loop (loops, aloop, target);
709       duplicate_subloops (loops, aloop, cloop);
710     }
711 }
712
713 /* Copies structure of subloops of N loops, stored in array COPIED_LOOPS,
714    into TARGET loop, placing newly created loops into loop tree LOOPS.  */
715 static void
716 copy_loops_to (struct loops *loops, struct loop **copied_loops, int n, struct loop *target)
717 {
718   struct loop *aloop;
719   int i;
720
721   for (i = 0; i < n; i++)
722     {
723       aloop = duplicate_loop (loops, copied_loops[i], target);
724       duplicate_subloops (loops, copied_loops[i], aloop);
725     }
726 }
727
728 /* Redirects edge E to basic block DEST.  */
729 static void
730 loop_redirect_edge (edge e, basic_block dest)
731 {
732   if (e->dest == dest)
733     return;
734
735   redirect_edge_and_branch_force (e, dest);
736 }
737
738 /* Deletes edge E from a branch if possible.  Unless REALLY_DELETE is set,
739    just test whether it is possible to remove the edge.  */
740 static bool
741 loop_delete_branch_edge (edge e, int really_delete)
742 {
743   basic_block src = e->src;
744   basic_block newdest;
745   int irr;
746   edge snd;
747
748   gcc_assert (EDGE_COUNT (src->succs) > 1);
749   
750   /* Cannot handle more than two exit edges.  */
751   if (EDGE_COUNT (src->succs) > 2)
752     return false;
753   /* And it must be just a simple branch.  */
754   if (!any_condjump_p (BB_END (src)))
755     return false;
756
757   snd = e == EDGE_SUCC (src, 0) ? EDGE_SUCC (src, 1) : EDGE_SUCC (src, 0);
758   newdest = snd->dest;
759   if (newdest == EXIT_BLOCK_PTR)
760     return false;
761
762   /* Hopefully the above conditions should suffice.  */
763   if (!really_delete)
764     return true;
765
766   /* Redirecting behaves wrongly wrto this flag.  */
767   irr = snd->flags & EDGE_IRREDUCIBLE_LOOP;
768
769   if (!redirect_edge_and_branch (e, newdest))
770     return false;
771   single_succ_edge (src)->flags &= ~EDGE_IRREDUCIBLE_LOOP;
772   single_succ_edge (src)->flags |= irr;
773   
774   return true;
775 }
776
777 /* Check whether LOOP's body can be duplicated.  */
778 bool
779 can_duplicate_loop_p (struct loop *loop)
780 {
781   int ret;
782   basic_block *bbs = get_loop_body (loop);
783
784   ret = can_copy_bbs_p (bbs, loop->num_nodes);
785   free (bbs);
786   
787   return ret;
788 }
789
790 /* The NBBS blocks in BBS will get duplicated and the copies will be placed
791    to LOOP.  Update the single_exit information in superloops of LOOP.  */
792
793 static void
794 update_single_exits_after_duplication (basic_block *bbs, unsigned nbbs,
795                                        struct loop *loop)
796 {
797   unsigned i;
798
799   for (i = 0; i < nbbs; i++)
800     bbs[i]->flags |= BB_DUPLICATED;
801
802   for (; loop->outer; loop = loop->outer)
803     {
804       if (!loop->single_exit)
805         continue;
806
807       if (loop->single_exit->src->flags & BB_DUPLICATED)
808         loop->single_exit = NULL;
809     }
810
811   for (i = 0; i < nbbs; i++)
812     bbs[i]->flags &= ~BB_DUPLICATED;
813 }
814
815 /* Duplicates body of LOOP to given edge E NDUPL times.  Takes care of updating
816    LOOPS structure and dominators.  E's destination must be LOOP header for
817    this to work, i.e. it must be entry or latch edge of this loop; these are
818    unique, as the loops must have preheaders for this function to work
819    correctly (in case E is latch, the function unrolls the loop, if E is entry
820    edge, it peels the loop).  Store edges created by copying ORIG edge from
821    copies corresponding to set bits in WONT_EXIT bitmap (bit 0 corresponds to
822    original LOOP body, the other copies are numbered in order given by control
823    flow through them) into TO_REMOVE array.  Returns false if duplication is
824    impossible.  */
825 bool
826 duplicate_loop_to_header_edge (struct loop *loop, edge e, struct loops *loops,
827                                unsigned int ndupl, sbitmap wont_exit,
828                                edge orig, edge *to_remove,
829                                unsigned int *n_to_remove, int flags)
830 {
831   struct loop *target, *aloop;
832   struct loop **orig_loops;
833   unsigned n_orig_loops;
834   basic_block header = loop->header, latch = loop->latch;
835   basic_block *new_bbs, *bbs, *first_active;
836   basic_block new_bb, bb, first_active_latch = NULL;
837   edge ae, latch_edge;
838   edge spec_edges[2], new_spec_edges[2];
839 #define SE_LATCH 0
840 #define SE_ORIG 1
841   unsigned i, j, n;
842   int is_latch = (latch == e->src);
843   int scale_act = 0, *scale_step = NULL, scale_main = 0;
844   int p, freq_in, freq_le, freq_out_orig;
845   int prob_pass_thru, prob_pass_wont_exit, prob_pass_main;
846   int add_irreducible_flag;
847   basic_block place_after;
848
849   gcc_assert (e->dest == loop->header);
850   gcc_assert (ndupl > 0);
851
852   if (orig)
853     {
854       /* Orig must be edge out of the loop.  */
855       gcc_assert (flow_bb_inside_loop_p (loop, orig->src));
856       gcc_assert (!flow_bb_inside_loop_p (loop, orig->dest));
857     }
858
859   n = loop->num_nodes;
860   bbs = get_loop_body_in_dom_order (loop);
861   gcc_assert (bbs[0] == loop->header);
862   gcc_assert (bbs[n  - 1] == loop->latch);
863
864   /* Check whether duplication is possible.  */
865   if (!can_copy_bbs_p (bbs, loop->num_nodes))
866     {
867       free (bbs);
868       return false;
869     }
870   new_bbs = XNEWVEC (basic_block, loop->num_nodes);
871
872   /* In case we are doing loop peeling and the loop is in the middle of
873      irreducible region, the peeled copies will be inside it too.  */
874   add_irreducible_flag = e->flags & EDGE_IRREDUCIBLE_LOOP;
875   gcc_assert (!is_latch || !add_irreducible_flag);
876
877   /* Find edge from latch.  */
878   latch_edge = loop_latch_edge (loop);
879
880   if (flags & DLTHE_FLAG_UPDATE_FREQ)
881     {
882       /* Calculate coefficients by that we have to scale frequencies
883          of duplicated loop bodies.  */
884       freq_in = header->frequency;
885       freq_le = EDGE_FREQUENCY (latch_edge);
886       if (freq_in == 0)
887         freq_in = 1;
888       if (freq_in < freq_le)
889         freq_in = freq_le;
890       freq_out_orig = orig ? EDGE_FREQUENCY (orig) : freq_in - freq_le;
891       if (freq_out_orig > freq_in - freq_le)
892         freq_out_orig = freq_in - freq_le;
893       prob_pass_thru = RDIV (REG_BR_PROB_BASE * freq_le, freq_in);
894       prob_pass_wont_exit =
895               RDIV (REG_BR_PROB_BASE * (freq_le + freq_out_orig), freq_in);
896
897       scale_step = XNEWVEC (int, ndupl);
898
899         for (i = 1; i <= ndupl; i++)
900           scale_step[i - 1] = TEST_BIT (wont_exit, i)
901                                 ? prob_pass_wont_exit
902                                 : prob_pass_thru;
903
904       /* Complete peeling is special as the probability of exit in last
905          copy becomes 1.  */
906       if (flags & DLTHE_FLAG_COMPLETTE_PEEL)
907         {
908           int wanted_freq = EDGE_FREQUENCY (e);
909
910           if (wanted_freq > freq_in)
911             wanted_freq = freq_in;
912
913           gcc_assert (!is_latch);
914           /* First copy has frequency of incoming edge.  Each subsequent
915              frequency should be reduced by prob_pass_wont_exit.  Caller
916              should've managed the flags so all except for original loop
917              has won't exist set.  */
918           scale_act = RDIV (wanted_freq * REG_BR_PROB_BASE, freq_in);
919           /* Now simulate the duplication adjustments and compute header
920              frequency of the last copy.  */
921           for (i = 0; i < ndupl; i++)
922             wanted_freq = RDIV (wanted_freq * scale_step[i], REG_BR_PROB_BASE);
923           scale_main = RDIV (wanted_freq * REG_BR_PROB_BASE, freq_in);
924         }
925       else if (is_latch)
926         {
927           prob_pass_main = TEST_BIT (wont_exit, 0)
928                                 ? prob_pass_wont_exit
929                                 : prob_pass_thru;
930           p = prob_pass_main;
931           scale_main = REG_BR_PROB_BASE;
932           for (i = 0; i < ndupl; i++)
933             {
934               scale_main += p;
935               p = RDIV (p * scale_step[i], REG_BR_PROB_BASE);
936             }
937           scale_main = RDIV (REG_BR_PROB_BASE * REG_BR_PROB_BASE, scale_main);
938           scale_act = RDIV (scale_main * prob_pass_main, REG_BR_PROB_BASE);
939         }
940       else
941         {
942           scale_main = REG_BR_PROB_BASE;
943           for (i = 0; i < ndupl; i++)
944             scale_main = RDIV (scale_main * scale_step[i], REG_BR_PROB_BASE);
945           scale_act = REG_BR_PROB_BASE - prob_pass_thru;
946         }
947       for (i = 0; i < ndupl; i++)
948         gcc_assert (scale_step[i] >= 0 && scale_step[i] <= REG_BR_PROB_BASE);
949       gcc_assert (scale_main >= 0 && scale_main <= REG_BR_PROB_BASE
950                   && scale_act >= 0  && scale_act <= REG_BR_PROB_BASE);
951     }
952
953   /* Loop the new bbs will belong to.  */
954   target = e->src->loop_father;
955
956   /* Original loops.  */
957   n_orig_loops = 0;
958   for (aloop = loop->inner; aloop; aloop = aloop->next)
959     n_orig_loops++;
960   orig_loops = XCNEWVEC (struct loop *, n_orig_loops);
961   for (aloop = loop->inner, i = 0; aloop; aloop = aloop->next, i++)
962     orig_loops[i] = aloop;
963
964   loop->copy = target;
965
966   first_active = XNEWVEC (basic_block, n);
967   if (is_latch)
968     {
969       memcpy (first_active, bbs, n * sizeof (basic_block));
970       first_active_latch = latch;
971     }
972
973   /* Update the information about single exits.  */
974   if (loops->state & LOOPS_HAVE_MARKED_SINGLE_EXITS)
975     update_single_exits_after_duplication (bbs, n, target);
976
977   /* Record exit edge in original loop body.  */
978   if (orig && TEST_BIT (wont_exit, 0))
979     to_remove[(*n_to_remove)++] = orig;
980
981   spec_edges[SE_ORIG] = orig;
982   spec_edges[SE_LATCH] = latch_edge;
983
984   place_after = e->src;
985   for (j = 0; j < ndupl; j++)
986     {
987       /* Copy loops.  */
988       copy_loops_to (loops, orig_loops, n_orig_loops, target);
989
990       /* Copy bbs.  */
991       copy_bbs (bbs, n, new_bbs, spec_edges, 2, new_spec_edges, loop,
992                 place_after);
993       place_after = new_spec_edges[SE_LATCH]->src;
994
995       if (flags & DLTHE_RECORD_COPY_NUMBER)
996         for (i = 0; i < n; i++)
997           {
998             gcc_assert (!new_bbs[i]->aux);
999             new_bbs[i]->aux = (void *)(size_t)(j + 1);
1000           }
1001
1002       /* Note whether the blocks and edges belong to an irreducible loop.  */
1003       if (add_irreducible_flag)
1004         {
1005           for (i = 0; i < n; i++)
1006             new_bbs[i]->flags |= BB_DUPLICATED;
1007           for (i = 0; i < n; i++)
1008             {
1009               edge_iterator ei;
1010               new_bb = new_bbs[i];
1011               if (new_bb->loop_father == target)
1012                 new_bb->flags |= BB_IRREDUCIBLE_LOOP;
1013
1014               FOR_EACH_EDGE (ae, ei, new_bb->succs)
1015                 if ((ae->dest->flags & BB_DUPLICATED)
1016                     && (ae->src->loop_father == target
1017                         || ae->dest->loop_father == target))
1018                   ae->flags |= EDGE_IRREDUCIBLE_LOOP;
1019             }
1020           for (i = 0; i < n; i++)
1021             new_bbs[i]->flags &= ~BB_DUPLICATED;
1022         }
1023
1024       /* Redirect the special edges.  */
1025       if (is_latch)
1026         {
1027           redirect_edge_and_branch_force (latch_edge, new_bbs[0]);
1028           redirect_edge_and_branch_force (new_spec_edges[SE_LATCH],
1029                                           loop->header);
1030           set_immediate_dominator (CDI_DOMINATORS, new_bbs[0], latch);
1031           latch = loop->latch = new_bbs[n - 1];
1032           e = latch_edge = new_spec_edges[SE_LATCH];
1033         }
1034       else
1035         {
1036           redirect_edge_and_branch_force (new_spec_edges[SE_LATCH],
1037                                           loop->header);
1038           redirect_edge_and_branch_force (e, new_bbs[0]);
1039           set_immediate_dominator (CDI_DOMINATORS, new_bbs[0], e->src);
1040           e = new_spec_edges[SE_LATCH];
1041         }
1042
1043       /* Record exit edge in this copy.  */
1044       if (orig && TEST_BIT (wont_exit, j + 1))
1045         to_remove[(*n_to_remove)++] = new_spec_edges[SE_ORIG];
1046
1047       /* Record the first copy in the control flow order if it is not
1048          the original loop (i.e. in case of peeling).  */
1049       if (!first_active_latch)
1050         {
1051           memcpy (first_active, new_bbs, n * sizeof (basic_block));
1052           first_active_latch = new_bbs[n - 1];
1053         }
1054
1055       /* Set counts and frequencies.  */
1056       if (flags & DLTHE_FLAG_UPDATE_FREQ)
1057         {
1058           scale_bbs_frequencies_int (new_bbs, n, scale_act, REG_BR_PROB_BASE);
1059           scale_act = RDIV (scale_act * scale_step[j], REG_BR_PROB_BASE);
1060         }
1061     }
1062   free (new_bbs);
1063   free (orig_loops);
1064   
1065   /* Update the original loop.  */
1066   if (!is_latch)
1067     set_immediate_dominator (CDI_DOMINATORS, e->dest, e->src);
1068   if (flags & DLTHE_FLAG_UPDATE_FREQ)
1069     {
1070       scale_bbs_frequencies_int (bbs, n, scale_main, REG_BR_PROB_BASE);
1071       free (scale_step);
1072     }
1073
1074   /* Update dominators of outer blocks if affected.  */
1075   for (i = 0; i < n; i++)
1076     {
1077       basic_block dominated, dom_bb, *dom_bbs;
1078       int n_dom_bbs,j;
1079
1080       bb = bbs[i];
1081       bb->aux = 0;
1082
1083       n_dom_bbs = get_dominated_by (CDI_DOMINATORS, bb, &dom_bbs);
1084       for (j = 0; j < n_dom_bbs; j++)
1085         {
1086           dominated = dom_bbs[j];
1087           if (flow_bb_inside_loop_p (loop, dominated))
1088             continue;
1089           dom_bb = nearest_common_dominator (
1090                         CDI_DOMINATORS, first_active[i], first_active_latch);
1091           set_immediate_dominator (CDI_DOMINATORS, dominated, dom_bb);
1092         }
1093       free (dom_bbs);
1094     }
1095   free (first_active);
1096
1097   free (bbs);
1098
1099   return true;
1100 }
1101
1102 /* A callback for make_forwarder block, to redirect all edges except for
1103    MFB_KJ_EDGE to the entry part.  E is the edge for that we should decide
1104    whether to redirect it.  */
1105
1106 static edge mfb_kj_edge;
1107 static bool
1108 mfb_keep_just (edge e)
1109 {
1110   return e != mfb_kj_edge;
1111 }
1112
1113 /* A callback for make_forwarder block, to update data structures for a basic
1114    block JUMP created by redirecting an edge (only the latch edge is being
1115    redirected).  */
1116
1117 static void
1118 mfb_update_loops (basic_block jump)
1119 {
1120   struct loop *loop = single_succ (jump)->loop_father;
1121
1122   if (dom_computed[CDI_DOMINATORS])
1123     set_immediate_dominator (CDI_DOMINATORS, jump, single_pred (jump));
1124   add_bb_to_loop (jump, loop);
1125   loop->latch = jump;
1126 }
1127
1128 /* Creates a pre-header for a LOOP.  Returns newly created block.  Unless
1129    CP_SIMPLE_PREHEADERS is set in FLAGS, we only force LOOP to have single
1130    entry; otherwise we also force preheader block to have only one successor.
1131    The function also updates dominators.  */
1132
1133 static basic_block
1134 create_preheader (struct loop *loop, int flags)
1135 {
1136   edge e, fallthru;
1137   basic_block dummy;
1138   struct loop *cloop, *ploop;
1139   int nentry = 0;
1140   bool irred = false;
1141   bool latch_edge_was_fallthru;
1142   edge one_succ_pred = 0;
1143   edge_iterator ei;
1144
1145   cloop = loop->outer;
1146
1147   FOR_EACH_EDGE (e, ei, loop->header->preds)
1148     {
1149       if (e->src == loop->latch)
1150         continue;
1151       irred |= (e->flags & EDGE_IRREDUCIBLE_LOOP) != 0;
1152       nentry++;
1153       if (single_succ_p (e->src))
1154         one_succ_pred = e;
1155     }
1156   gcc_assert (nentry);
1157   if (nentry == 1)
1158     {
1159       /* Get an edge that is different from the one from loop->latch
1160          to loop->header.  */
1161       e = EDGE_PRED (loop->header,
1162                      EDGE_PRED (loop->header, 0)->src == loop->latch);
1163
1164       if (!(flags & CP_SIMPLE_PREHEADERS) || single_succ_p (e->src))
1165         return NULL;
1166     }
1167
1168   mfb_kj_edge = loop_latch_edge (loop);
1169   latch_edge_was_fallthru = (mfb_kj_edge->flags & EDGE_FALLTHRU) != 0;
1170   fallthru = make_forwarder_block (loop->header, mfb_keep_just,
1171                                    mfb_update_loops);
1172   dummy = fallthru->src;
1173   loop->header = fallthru->dest;
1174
1175   /* The header could be a latch of some superloop(s); due to design of
1176      split_block, it would now move to fallthru->dest.  */
1177   for (ploop = loop; ploop; ploop = ploop->outer)
1178     if (ploop->latch == dummy)
1179       ploop->latch = fallthru->dest;
1180
1181   /* Try to be clever in placing the newly created preheader.  The idea is to
1182      avoid breaking any "fallthruness" relationship between blocks.
1183
1184      The preheader was created just before the header and all incoming edges
1185      to the header were redirected to the preheader, except the latch edge.
1186      So the only problematic case is when this latch edge was a fallthru
1187      edge: it is not anymore after the preheader creation so we have broken
1188      the fallthruness.  We're therefore going to look for a better place.  */
1189   if (latch_edge_was_fallthru)
1190     {
1191       if (one_succ_pred)
1192         e = one_succ_pred;
1193       else
1194         e = EDGE_PRED (dummy, 0);
1195
1196       move_block_after (dummy, e->src);
1197     }
1198
1199   loop->header->loop_father = loop;
1200   add_bb_to_loop (dummy, cloop);
1201
1202   if (irred)
1203     {
1204       dummy->flags |= BB_IRREDUCIBLE_LOOP;
1205       single_succ_edge (dummy)->flags |= EDGE_IRREDUCIBLE_LOOP;
1206     }
1207
1208   if (dump_file)
1209     fprintf (dump_file, "Created preheader block for loop %i\n",
1210              loop->num);
1211
1212   return dummy;
1213 }
1214
1215 /* Create preheaders for each loop from loop tree stored in LOOPS; for meaning
1216    of FLAGS see create_preheader.  */
1217 void
1218 create_preheaders (struct loops *loops, int flags)
1219 {
1220   unsigned i;
1221   for (i = 1; i < loops->num; i++)
1222     create_preheader (loops->parray[i], flags);
1223   loops->state |= LOOPS_HAVE_PREHEADERS;
1224 }
1225
1226 /* Forces all loop latches of loops from loop tree LOOPS to have only single
1227    successor.  */
1228 void
1229 force_single_succ_latches (struct loops *loops)
1230 {
1231   unsigned i;
1232   struct loop *loop;
1233   edge e;
1234
1235   for (i = 1; i < loops->num; i++)
1236     {
1237       loop = loops->parray[i];
1238       if (loop->latch != loop->header && single_succ_p (loop->latch))
1239         continue;
1240
1241       e = find_edge (loop->latch, loop->header);
1242
1243       loop_split_edge_with (e, NULL_RTX);
1244     }
1245   loops->state |= LOOPS_HAVE_SIMPLE_LATCHES;
1246 }
1247
1248 /* A quite stupid function to put INSNS on edge E. They are supposed to form
1249    just one basic block.  Jumps in INSNS are not handled, so cfg do not have to
1250    be ok after this function.  The created block is placed on correct place
1251    in LOOPS structure and its dominator is set.  */
1252 basic_block
1253 loop_split_edge_with (edge e, rtx insns)
1254 {
1255   basic_block src, dest, new_bb;
1256   struct loop *loop_c;
1257
1258   src = e->src;
1259   dest = e->dest;
1260
1261   loop_c = find_common_loop (src->loop_father, dest->loop_father);
1262
1263   /* Create basic block for it.  */
1264
1265   new_bb = split_edge (e);
1266   add_bb_to_loop (new_bb, loop_c);
1267   new_bb->flags |= (insns ? BB_SUPERBLOCK : 0);
1268
1269   if (insns)
1270     emit_insn_after (insns, BB_END (new_bb));
1271
1272   if (dest->loop_father->latch == src)
1273     dest->loop_father->latch = new_bb;
1274
1275   return new_bb;
1276 }
1277
1278 /* Uses the natural loop discovery to recreate loop notes.  */
1279 void
1280 create_loop_notes (void)
1281 {
1282   rtx insn, head, end;
1283   struct loops loops;
1284   struct loop *loop;
1285   basic_block *first, *last, bb, pbb;
1286   struct loop **stack, **top;
1287
1288 #ifdef ENABLE_CHECKING
1289   /* Verify that there really are no loop notes.  */
1290   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
1291     gcc_assert (!NOTE_P (insn) ||
1292                 NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
1293 #endif
1294
1295   flow_loops_find (&loops);
1296   free_dominance_info (CDI_DOMINATORS);
1297   if (loops.num > 1)
1298     {
1299       last = XCNEWVEC (basic_block, loops.num);
1300
1301       FOR_EACH_BB (bb)
1302         {
1303           for (loop = bb->loop_father; loop->outer; loop = loop->outer)
1304             last[loop->num] = bb;
1305         }
1306
1307       first = XCNEWVEC (basic_block, loops.num);
1308       stack = XCNEWVEC (struct loop *, loops.num);
1309       top = stack;
1310
1311       FOR_EACH_BB (bb)
1312         {
1313           for (loop = bb->loop_father; loop->outer; loop = loop->outer)
1314             {
1315               if (!first[loop->num])
1316                 {
1317                   *top++ = loop;
1318                   first[loop->num] = bb;
1319                 }
1320
1321               if (bb == last[loop->num])
1322                 {
1323                   /* Prevent loops from overlapping.  */
1324                   while (*--top != loop)
1325                     last[(*top)->num] = EXIT_BLOCK_PTR;
1326
1327                   /* If loop starts with jump into it, place the note in
1328                      front of the jump.  */
1329                   insn = PREV_INSN (BB_HEAD (first[loop->num]));
1330                   if (insn
1331                       && BARRIER_P (insn))
1332                     insn = PREV_INSN (insn);
1333                   
1334                   if (insn
1335                       && JUMP_P (insn)
1336                       && any_uncondjump_p (insn)
1337                       && onlyjump_p (insn))
1338                     {
1339                       pbb = BLOCK_FOR_INSN (insn);
1340                       gcc_assert (pbb && single_succ_p (pbb));
1341
1342                       if (!flow_bb_inside_loop_p (loop, single_succ (pbb)))
1343                         insn = BB_HEAD (first[loop->num]);
1344                     }
1345                   else
1346                     insn = BB_HEAD (first[loop->num]);
1347                     
1348                   head = BB_HEAD (first[loop->num]);
1349                   emit_note_before (NOTE_INSN_LOOP_BEG, insn);
1350                   BB_HEAD (first[loop->num]) = head;
1351
1352                   /* Position the note correctly wrto barrier.  */
1353                   insn = BB_END (last[loop->num]);
1354                   if (NEXT_INSN (insn)
1355                       && BARRIER_P (NEXT_INSN (insn)))
1356                     insn = NEXT_INSN (insn);
1357                   
1358                   end = BB_END (last[loop->num]);
1359                   emit_note_after (NOTE_INSN_LOOP_END, insn);
1360                   BB_END (last[loop->num]) = end;
1361                 }
1362             }
1363         }
1364
1365       free (first);
1366       free (last);
1367       free (stack);
1368     }
1369   flow_loops_free (&loops);
1370 }
1371
1372 /* This function is called from loop_version.  It splits the entry edge
1373    of the loop we want to version, adds the versioning condition, and
1374    adjust the edges to the two versions of the loop appropriately.
1375    e is an incoming edge. Returns the basic block containing the
1376    condition.
1377
1378    --- edge e ---- > [second_head]
1379
1380    Split it and insert new conditional expression and adjust edges.
1381
1382     --- edge e ---> [cond expr] ---> [first_head]
1383                         |
1384                         +---------> [second_head]
1385 */
1386
1387 static basic_block
1388 lv_adjust_loop_entry_edge (basic_block first_head,
1389                            basic_block second_head,
1390                            edge e,
1391                            void *cond_expr)
1392 {
1393   basic_block new_head = NULL;
1394   edge e1;
1395
1396   gcc_assert (e->dest == second_head);
1397
1398   /* Split edge 'e'. This will create a new basic block, where we can
1399      insert conditional expr.  */
1400   new_head = split_edge (e);
1401
1402
1403   lv_add_condition_to_bb (first_head, second_head, new_head,
1404                           cond_expr);
1405
1406   /* Don't set EDGE_TRUE_VALUE in RTL mode, as it's invalid there.  */
1407   e1 = make_edge (new_head, first_head, ir_type () ? EDGE_TRUE_VALUE : 0);
1408   set_immediate_dominator (CDI_DOMINATORS, first_head, new_head);
1409   set_immediate_dominator (CDI_DOMINATORS, second_head, new_head);
1410
1411   /* Adjust loop header phi nodes.  */
1412   lv_adjust_loop_header_phi (first_head, second_head, new_head, e1);
1413
1414   return new_head;
1415 }
1416
1417 /* Main entry point for Loop Versioning transformation.
1418    
1419    This transformation given a condition and a loop, creates
1420    -if (condition) { loop_copy1 } else { loop_copy2 },
1421    where loop_copy1 is the loop transformed in one way, and loop_copy2
1422    is the loop transformed in another way (or unchanged). 'condition'
1423    may be a run time test for things that were not resolved by static
1424    analysis (overlapping ranges (anti-aliasing), alignment, etc.).
1425
1426    If PLACE_AFTER is true, we place the new loop after LOOP in the
1427    instruction stream, otherwise it is placed before LOOP.  */
1428
1429 struct loop *
1430 loop_version (struct loops *loops, struct loop * loop, 
1431               void *cond_expr, basic_block *condition_bb,
1432               bool place_after)
1433 {
1434   basic_block first_head, second_head;
1435   edge entry, latch_edge, exit, true_edge, false_edge;
1436   int irred_flag;
1437   struct loop *nloop;
1438   basic_block cond_bb;
1439
1440   /* CHECKME: Loop versioning does not handle nested loop at this point.  */
1441   if (loop->inner)
1442     return NULL;
1443
1444   /* Record entry and latch edges for the loop */
1445   entry = loop_preheader_edge (loop);
1446   irred_flag = entry->flags & EDGE_IRREDUCIBLE_LOOP;
1447   entry->flags &= ~EDGE_IRREDUCIBLE_LOOP;
1448   
1449   /* Note down head of loop as first_head.  */
1450   first_head = entry->dest;
1451
1452   /* Duplicate loop.  */
1453   if (!cfg_hook_duplicate_loop_to_header_edge (loop, entry, loops, 1,
1454                                                NULL, NULL, NULL, NULL, 0))
1455     return NULL;
1456
1457   /* After duplication entry edge now points to new loop head block.
1458      Note down new head as second_head.  */
1459   second_head = entry->dest;
1460
1461   /* Split loop entry edge and insert new block with cond expr.  */
1462   cond_bb =  lv_adjust_loop_entry_edge (first_head, second_head,
1463                                         entry, cond_expr);
1464   if (condition_bb)
1465     *condition_bb = cond_bb;
1466
1467   if (!cond_bb)
1468     {
1469       entry->flags |= irred_flag;
1470       return NULL;
1471     }
1472
1473   latch_edge = single_succ_edge (get_bb_copy (loop->latch));
1474   
1475   extract_cond_bb_edges (cond_bb, &true_edge, &false_edge);
1476   nloop = loopify (loops,
1477                    latch_edge,
1478                    single_pred_edge (get_bb_copy (loop->header)),
1479                    cond_bb, true_edge, false_edge,
1480                    false /* Do not redirect all edges.  */);
1481
1482   exit = loop->single_exit;
1483   if (exit)
1484     nloop->single_exit = find_edge (get_bb_copy (exit->src), exit->dest);
1485
1486   /* loopify redirected latch_edge. Update its PENDING_STMTS.  */ 
1487   lv_flush_pending_stmts (latch_edge);
1488
1489   /* loopify redirected condition_bb's succ edge. Update its PENDING_STMTS.  */ 
1490   extract_cond_bb_edges (cond_bb, &true_edge, &false_edge);
1491   lv_flush_pending_stmts (false_edge);
1492   /* Adjust irreducible flag.  */
1493   if (irred_flag)
1494     {
1495       cond_bb->flags |= BB_IRREDUCIBLE_LOOP;
1496       loop_preheader_edge (loop)->flags |= EDGE_IRREDUCIBLE_LOOP;
1497       loop_preheader_edge (nloop)->flags |= EDGE_IRREDUCIBLE_LOOP;
1498       single_pred_edge (cond_bb)->flags |= EDGE_IRREDUCIBLE_LOOP;
1499     }
1500
1501   if (place_after)
1502     {
1503       basic_block *bbs = get_loop_body_in_dom_order (nloop), after;
1504       unsigned i;
1505
1506       after = loop->latch;
1507
1508       for (i = 0; i < nloop->num_nodes; i++)
1509         {
1510           move_block_after (bbs[i], after);
1511           after = bbs[i];
1512         }
1513       free (bbs);
1514     }
1515
1516   /* At this point condition_bb is loop predheader with two successors, 
1517      first_head and second_head.   Make sure that loop predheader has only 
1518      one successor.  */
1519   loop_split_edge_with (loop_preheader_edge (loop), NULL);
1520   loop_split_edge_with (loop_preheader_edge (nloop), NULL);
1521
1522   return nloop;
1523 }
1524
1525 /* The structure of LOOPS might have changed.  Some loops might get removed
1526    (and their headers and latches were set to NULL), loop exists might get
1527    removed (thus the loop nesting may be wrong), and some blocks and edges
1528    were changed (so the information about bb --> loop mapping does not have
1529    to be correct).  But still for the remaining loops the header dominates
1530    the latch, and loops did not get new subloobs (new loops might possibly
1531    get created, but we are not interested in them).  Fix up the mess.
1532  
1533    If CHANGED_BBS is not NULL, basic blocks whose loop has changed are
1534    marked in it.  */
1535
1536 void
1537 fix_loop_structure (struct loops *loops, bitmap changed_bbs)
1538 {
1539   basic_block bb;
1540   struct loop *loop, *ploop;
1541   unsigned i;
1542
1543   /* Remove the old bb -> loop mapping.  */
1544   FOR_EACH_BB (bb)
1545     {
1546       bb->aux = (void *) (size_t) bb->loop_father->depth;
1547       bb->loop_father = loops->tree_root;
1548     }
1549
1550   /* Remove the dead loops from structures.  */
1551   loops->tree_root->num_nodes = n_basic_blocks; 
1552   for (i = 1; i < loops->num; i++)
1553     {
1554       loop = loops->parray[i];
1555       if (!loop)
1556         continue;
1557
1558       loop->num_nodes = 0;
1559       if (loop->header)
1560         continue;
1561
1562       while (loop->inner)
1563         {
1564           ploop = loop->inner;
1565           flow_loop_tree_node_remove (ploop);
1566           flow_loop_tree_node_add (loop->outer, ploop);
1567         }
1568
1569       /* Remove the loop and free its data.  */
1570       flow_loop_tree_node_remove (loop);
1571       loops->parray[loop->num] = NULL;
1572       flow_loop_free (loop);
1573     }
1574
1575   /* Rescan the bodies of loops, starting from the outermost.  */
1576   loop = loops->tree_root;
1577   while (1)
1578     {
1579       if (loop->inner)
1580         loop = loop->inner;
1581       else
1582         {
1583           while (!loop->next
1584                  && loop != loops->tree_root)
1585             loop = loop->outer;
1586           if (loop == loops->tree_root)
1587             break;
1588
1589           loop = loop->next;
1590         }
1591
1592       loop->num_nodes = flow_loop_nodes_find (loop->header, loop);
1593     }
1594
1595   /* Now fix the loop nesting.  */
1596   for (i = 1; i < loops->num; i++)
1597     {
1598       loop = loops->parray[i];
1599       if (!loop)
1600         continue;
1601
1602       bb = loop_preheader_edge (loop)->src;
1603       if (bb->loop_father != loop->outer)
1604         {
1605           flow_loop_tree_node_remove (loop);
1606           flow_loop_tree_node_add (bb->loop_father, loop);
1607         }
1608     }
1609
1610   /* Mark the blocks whose loop has changed.  */
1611   FOR_EACH_BB (bb)
1612     {
1613       if (changed_bbs
1614           && (void *) (size_t) bb->loop_father->depth != bb->aux)
1615         bitmap_set_bit (changed_bbs, bb->index);
1616
1617       bb->aux = NULL;
1618     }
1619
1620   if (loops->state & LOOPS_HAVE_MARKED_SINGLE_EXITS)
1621     mark_single_exit_loops (loops);
1622   if (loops->state & LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS)
1623     mark_irreducible_loops (loops);
1624 }