Simplify.
[oota-llvm.git] / lib / Transforms / Utils / LoopSimplify.cpp
1 //===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs several transformations to transform natural loops into a
11 // simpler form, which makes subsequent analyses and transformations simpler and
12 // more effective.
13 //
14 // Loop pre-header insertion guarantees that there is a single, non-critical
15 // entry edge from outside of the loop to the loop header.  This simplifies a
16 // number of analyses and transformations, such as LICM.
17 //
18 // Loop exit-block insertion guarantees that all exit blocks from the loop
19 // (blocks which are outside of the loop that have predecessors inside of the
20 // loop) only have predecessors from inside of the loop (and are thus dominated
21 // by the loop header).  This simplifies transformations such as store-sinking
22 // that are built into LICM.
23 //
24 // This pass also guarantees that loops will have exactly one backedge.
25 //
26 // Note that the simplifycfg pass will clean up blocks which are split out but
27 // end up being unnecessary, so usage of this pass should not pessimize
28 // generated code.
29 //
30 // This pass obviously modifies the CFG, but updates loop information and
31 // dominator information.
32 //
33 //===----------------------------------------------------------------------===//
34
35 #define DEBUG_TYPE "loopsimplify"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Constant.h"
38 #include "llvm/Instructions.h"
39 #include "llvm/Function.h"
40 #include "llvm/Type.h"
41 #include "llvm/Analysis/AliasAnalysis.h"
42 #include "llvm/Analysis/Dominators.h"
43 #include "llvm/Analysis/LoopInfo.h"
44 #include "llvm/Support/CFG.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/ADT/SetOperations.h"
47 #include "llvm/ADT/SetVector.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/ADT/DepthFirstIterator.h"
50 using namespace llvm;
51
52 STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
53 STATISTIC(NumNested  , "Number of nested loops split out");
54
55 namespace {
56   struct VISIBILITY_HIDDEN LoopSimplify : public FunctionPass {
57     static char ID; // Pass identification, replacement for typeid
58     LoopSimplify() : FunctionPass((intptr_t)&ID) {}
59
60     // AA - If we have an alias analysis object to update, this is it, otherwise
61     // this is null.
62     AliasAnalysis *AA;
63     LoopInfo *LI;
64
65     virtual bool runOnFunction(Function &F);
66
67     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68       // We need loop information to identify the loops...
69       AU.addRequired<LoopInfo>();
70       AU.addRequired<DominatorTree>();
71
72       AU.addPreserved<LoopInfo>();
73       AU.addPreserved<DominatorTree>();
74       AU.addPreserved<DominanceFrontier>();
75       AU.addPreservedID(BreakCriticalEdgesID);  // No critical edges added.
76     }
77   private:
78     bool ProcessLoop(Loop *L);
79     BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
80                                        const std::vector<BasicBlock*> &Preds);
81     BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
82     void InsertPreheaderForLoop(Loop *L);
83     Loop *SeparateNestedLoop(Loop *L);
84     void InsertUniqueBackedgeBlock(Loop *L);
85     void PlaceSplitBlockCarefully(BasicBlock *NewBB,
86                                   std::vector<BasicBlock*> &SplitPreds,
87                                   Loop *L);
88       
89     void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
90                                          std::vector<BasicBlock*> &PredBlocks);
91   };
92
93   char LoopSimplify::ID = 0;
94   RegisterPass<LoopSimplify>
95   X("loopsimplify", "Canonicalize natural loops", true);
96 }
97
98 // Publically exposed interface to pass...
99 const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
100 FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
101
102 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
103 /// it in any convenient order) inserting preheaders...
104 ///
105 bool LoopSimplify::runOnFunction(Function &F) {
106   bool Changed = false;
107   LI = &getAnalysis<LoopInfo>();
108   AA = getAnalysisToUpdate<AliasAnalysis>();
109
110   // Check to see that no blocks (other than the header) in loops have
111   // predecessors that are not in loops.  This is not valid for natural loops,
112   // but can occur if the blocks are unreachable.  Since they are unreachable we
113   // can just shamelessly destroy their terminators to make them not branch into
114   // the loop!
115   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
116     // This case can only occur for unreachable blocks.  Blocks that are
117     // unreachable can't be in loops, so filter those blocks out.
118     if (LI->getLoopFor(BB)) continue;
119     
120     bool BlockUnreachable = false;
121     TerminatorInst *TI = BB->getTerminator();
122
123     // Check to see if any successors of this block are non-loop-header loops
124     // that are not the header.
125     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
126       // If this successor is not in a loop, BB is clearly ok.
127       Loop *L = LI->getLoopFor(TI->getSuccessor(i));
128       if (!L) continue;
129       
130       // If the succ is the loop header, and if L is a top-level loop, then this
131       // is an entrance into a loop through the header, which is also ok.
132       if (L->getHeader() == TI->getSuccessor(i) && L->getParentLoop() == 0)
133         continue;
134       
135       // Otherwise, this is an entrance into a loop from some place invalid.
136       // Either the loop structure is invalid and this is not a natural loop (in
137       // which case the compiler is buggy somewhere else) or BB is unreachable.
138       BlockUnreachable = true;
139       break;
140     }
141     
142     // If this block is ok, check the next one.
143     if (!BlockUnreachable) continue;
144     
145     // Otherwise, this block is dead.  To clean up the CFG and to allow later
146     // loop transformations to ignore this case, we delete the edges into the
147     // loop by replacing the terminator.
148     
149     // Remove PHI entries from the successors.
150     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
151       TI->getSuccessor(i)->removePredecessor(BB);
152    
153     // Add a new unreachable instruction.
154     new UnreachableInst(TI);
155     
156     // Delete the dead terminator.
157     if (AA) AA->deleteValue(&BB->back());
158     BB->getInstList().pop_back();
159     Changed |= true;
160   }
161   
162   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
163     Changed |= ProcessLoop(*I);
164
165   return Changed;
166 }
167
168 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
169 /// all loops have preheaders.
170 ///
171 bool LoopSimplify::ProcessLoop(Loop *L) {
172   bool Changed = false;
173 ReprocessLoop:
174   
175   // Canonicalize inner loops before outer loops.  Inner loop canonicalization
176   // can provide work for the outer loop to canonicalize.
177   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
178     Changed |= ProcessLoop(*I);
179   
180   assert(L->getBlocks()[0] == L->getHeader() &&
181          "Header isn't first block in loop?");
182
183   // Does the loop already have a preheader?  If so, don't insert one.
184   if (L->getLoopPreheader() == 0) {
185     InsertPreheaderForLoop(L);
186     NumInserted++;
187     Changed = true;
188   }
189
190   // Next, check to make sure that all exit nodes of the loop only have
191   // predecessors that are inside of the loop.  This check guarantees that the
192   // loop preheader/header will dominate the exit blocks.  If the exit block has
193   // predecessors from outside of the loop, split the edge now.
194   std::vector<BasicBlock*> ExitBlocks;
195   L->getExitBlocks(ExitBlocks);
196     
197   SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
198   for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
199          E = ExitBlockSet.end(); I != E; ++I) {
200     BasicBlock *ExitBlock = *I;
201     for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
202          PI != PE; ++PI)
203       // Must be exactly this loop: no subloops, parent loops, or non-loop preds
204       // allowed.
205       if (!L->contains(*PI)) {
206         RewriteLoopExitBlock(L, ExitBlock);
207         NumInserted++;
208         Changed = true;
209         break;
210       }
211   }
212
213   // If the header has more than two predecessors at this point (from the
214   // preheader and from multiple backedges), we must adjust the loop.
215   unsigned NumBackedges = L->getNumBackEdges();
216   if (NumBackedges != 1) {
217     // If this is really a nested loop, rip it out into a child loop.  Don't do
218     // this for loops with a giant number of backedges, just factor them into a
219     // common backedge instead.
220     if (NumBackedges < 8) {
221       if (Loop *NL = SeparateNestedLoop(L)) {
222         ++NumNested;
223         // This is a big restructuring change, reprocess the whole loop.
224         ProcessLoop(NL);
225         Changed = true;
226         // GCC doesn't tail recursion eliminate this.
227         goto ReprocessLoop;
228       }
229     }
230
231     // If we either couldn't, or didn't want to, identify nesting of the loops,
232     // insert a new block that all backedges target, then make it jump to the
233     // loop header.
234     InsertUniqueBackedgeBlock(L);
235     NumInserted++;
236     Changed = true;
237   }
238
239   // Scan over the PHI nodes in the loop header.  Since they now have only two
240   // incoming values (the loop is canonicalized), we may have simplified the PHI
241   // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
242   PHINode *PN;
243   for (BasicBlock::iterator I = L->getHeader()->begin();
244        (PN = dyn_cast<PHINode>(I++)); )
245     if (Value *V = PN->hasConstantValue()) {
246         PN->replaceAllUsesWith(V);
247         PN->eraseFromParent();
248       }
249
250   return Changed;
251 }
252
253 /// SplitBlockPredecessors - Split the specified block into two blocks.  We want
254 /// to move the predecessors specified in the Preds list to point to the new
255 /// block, leaving the remaining predecessors pointing to BB.  This method
256 /// updates the SSA PHINode's, but no other analyses.
257 ///
258 BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
259                                                  const char *Suffix,
260                                        const std::vector<BasicBlock*> &Preds) {
261
262   // Create new basic block, insert right before the original block...
263   BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
264
265   // The preheader first gets an unconditional branch to the loop header...
266   BranchInst *BI = new BranchInst(BB, NewBB);
267
268   // For every PHI node in the block, insert a PHI node into NewBB where the
269   // incoming values from the out of loop edges are moved to NewBB.  We have two
270   // possible cases here.  If the loop is dead, we just insert dummy entries
271   // into the PHI nodes for the new edge.  If the loop is not dead, we move the
272   // incoming edges in BB into new PHI nodes in NewBB.
273   //
274   if (!Preds.empty()) {  // Is the loop not obviously dead?
275     // Check to see if the values being merged into the new block need PHI
276     // nodes.  If so, insert them.
277     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
278       PHINode *PN = cast<PHINode>(I);
279       ++I;
280
281       // Check to see if all of the values coming in are the same.  If so, we
282       // don't need to create a new PHI node.
283       Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
284       for (unsigned i = 1, e = Preds.size(); i != e; ++i)
285         if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
286           InVal = 0;
287           break;
288         }
289
290       // If the values coming into the block are not the same, we need a PHI.
291       if (InVal == 0) {
292         // Create the new PHI node, insert it into NewBB at the end of the block
293         PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
294         if (AA) AA->copyValue(PN, NewPHI);
295
296         // Move all of the edges from blocks outside the loop to the new PHI
297         for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
298           Value *V = PN->removeIncomingValue(Preds[i], false);
299           NewPHI->addIncoming(V, Preds[i]);
300         }
301         InVal = NewPHI;
302       } else {
303         // Remove all of the edges coming into the PHI nodes from outside of the
304         // block.
305         for (unsigned i = 0, e = Preds.size(); i != e; ++i)
306           PN->removeIncomingValue(Preds[i], false);
307       }
308
309       // Add an incoming value to the PHI node in the loop for the preheader
310       // edge.
311       PN->addIncoming(InVal, NewBB);
312
313       // Can we eliminate this phi node now?
314       if (Value *V = PN->hasConstantValue(true)) {
315         Instruction *I = dyn_cast<Instruction>(V);
316         // If I is in NewBB, the Dominator call will fail, because NewBB isn't
317         // registered in DominatorTree yet.  Handle this case explicitly.
318         if (!I || (I->getParent() != NewBB &&
319                    getAnalysis<DominatorTree>().dominates(I, PN))) {
320           PN->replaceAllUsesWith(V);
321           if (AA) AA->deleteValue(PN);
322           BB->getInstList().erase(PN);
323         }
324       }
325     }
326
327     // Now that the PHI nodes are updated, actually move the edges from
328     // Preds to point to NewBB instead of BB.
329     //
330     for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
331       TerminatorInst *TI = Preds[i]->getTerminator();
332       for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
333         if (TI->getSuccessor(s) == BB)
334           TI->setSuccessor(s, NewBB);
335     }
336
337   } else {                       // Otherwise the loop is dead...
338     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
339       PHINode *PN = cast<PHINode>(I);
340       // Insert dummy values as the incoming value...
341       PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
342     }
343   }
344   return NewBB;
345 }
346
347 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
348 /// preheader, this method is called to insert one.  This method has two phases:
349 /// preheader insertion and analysis updating.
350 ///
351 void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
352   BasicBlock *Header = L->getHeader();
353
354   // Compute the set of predecessors of the loop that are not in the loop.
355   std::vector<BasicBlock*> OutsideBlocks;
356   for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
357        PI != PE; ++PI)
358     if (!L->contains(*PI))           // Coming in from outside the loop?
359       OutsideBlocks.push_back(*PI);  // Keep track of it...
360
361   // Split out the loop pre-header.
362   BasicBlock *NewBB =
363     SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
364   
365
366   //===--------------------------------------------------------------------===//
367   //  Update analysis results now that we have performed the transformation
368   //
369
370   // We know that we have loop information to update... update it now.
371   if (Loop *Parent = L->getParentLoop())
372     Parent->addBasicBlockToLoop(NewBB, *LI);
373
374   UpdateDomInfoForRevectoredPreds(NewBB, OutsideBlocks);
375   
376   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
377   // code layout too horribly.
378   PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
379 }
380
381 /// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
382 /// blocks.  This method is used to split exit blocks that have predecessors
383 /// outside of the loop.
384 BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
385   std::vector<BasicBlock*> LoopBlocks;
386   for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
387     if (L->contains(*I))
388       LoopBlocks.push_back(*I);
389
390   assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
391   BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
392
393   // Update Loop Information - we know that the new block will be in whichever
394   // loop the Exit block is in.  Note that it may not be in that immediate loop,
395   // if the successor is some other loop header.  In that case, we continue 
396   // walking up the loop tree to find a loop that contains both the successor
397   // block and the predecessor block.
398   Loop *SuccLoop = LI->getLoopFor(Exit);
399   while (SuccLoop && !SuccLoop->contains(L->getHeader()))
400     SuccLoop = SuccLoop->getParentLoop();
401   if (SuccLoop)
402     SuccLoop->addBasicBlockToLoop(NewBB, *LI);
403
404   // Update dominator information (set, immdom, domtree, and domfrontier)
405   UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
406   return NewBB;
407 }
408
409 /// AddBlockAndPredsToSet - Add the specified block, and all of its
410 /// predecessors, to the specified set, if it's not already in there.  Stop
411 /// predecessor traversal when we reach StopBlock.
412 static void AddBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
413                                   std::set<BasicBlock*> &Blocks) {
414   std::vector<BasicBlock *> WorkList;
415   WorkList.push_back(InputBB);
416   do {
417     BasicBlock *BB = WorkList.back(); WorkList.pop_back();
418     if (Blocks.insert(BB).second && BB != StopBlock)
419       // If BB is not already processed and it is not a stop block then
420       // insert its predecessor in the work list
421       for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
422         BasicBlock *WBB = *I;
423         WorkList.push_back(WBB);
424       }
425   } while(!WorkList.empty());
426 }
427
428 /// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
429 /// PHI node that tells us how to partition the loops.
430 static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorTree *DT,
431                                         AliasAnalysis *AA) {
432   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
433     PHINode *PN = cast<PHINode>(I);
434     ++I;
435     if (Value *V = PN->hasConstantValue())
436       if (!isa<Instruction>(V) || DT->dominates(cast<Instruction>(V), PN)) {
437         // This is a degenerate PHI already, don't modify it!
438         PN->replaceAllUsesWith(V);
439         if (AA) AA->deleteValue(PN);
440         PN->eraseFromParent();
441         continue;
442       }
443
444     // Scan this PHI node looking for a use of the PHI node by itself.
445     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
446       if (PN->getIncomingValue(i) == PN &&
447           L->contains(PN->getIncomingBlock(i)))
448         // We found something tasty to remove.
449         return PN;
450   }
451   return 0;
452 }
453
454 // PlaceSplitBlockCarefully - If the block isn't already, move the new block to
455 // right after some 'outside block' block.  This prevents the preheader from
456 // being placed inside the loop body, e.g. when the loop hasn't been rotated.
457 void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
458                                             std::vector<BasicBlock*>&SplitPreds,
459                                             Loop *L) {
460   // Check to see if NewBB is already well placed.
461   Function::iterator BBI = NewBB; --BBI;
462   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
463     if (&*BBI == SplitPreds[i])
464       return;
465   }
466   
467   // If it isn't already after an outside block, move it after one.  This is
468   // always good as it makes the uncond branch from the outside block into a
469   // fall-through.
470   
471   // Figure out *which* outside block to put this after.  Prefer an outside
472   // block that neighbors a BB actually in the loop.
473   BasicBlock *FoundBB = 0;
474   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
475     Function::iterator BBI = SplitPreds[i];
476     if (++BBI != NewBB->getParent()->end() && 
477         L->contains(BBI)) {
478       FoundBB = SplitPreds[i];
479       break;
480     }
481   }
482   
483   // If our heuristic for a *good* bb to place this after doesn't find
484   // anything, just pick something.  It's likely better than leaving it within
485   // the loop.
486   if (!FoundBB)
487     FoundBB = SplitPreds[0];
488   NewBB->moveAfter(FoundBB);
489 }
490
491
492 /// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
493 /// them out into a nested loop.  This is important for code that looks like
494 /// this:
495 ///
496 ///  Loop:
497 ///     ...
498 ///     br cond, Loop, Next
499 ///     ...
500 ///     br cond2, Loop, Out
501 ///
502 /// To identify this common case, we look at the PHI nodes in the header of the
503 /// loop.  PHI nodes with unchanging values on one backedge correspond to values
504 /// that change in the "outer" loop, but not in the "inner" loop.
505 ///
506 /// If we are able to separate out a loop, return the new outer loop that was
507 /// created.
508 ///
509 Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
510   DominatorTree *DT = getAnalysisToUpdate<DominatorTree>();
511   PHINode *PN = FindPHIToPartitionLoops(L, DT, AA);
512   if (PN == 0) return 0;  // No known way to partition.
513
514   // Pull out all predecessors that have varying values in the loop.  This
515   // handles the case when a PHI node has multiple instances of itself as
516   // arguments.
517   std::vector<BasicBlock*> OuterLoopPreds;
518   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
519     if (PN->getIncomingValue(i) != PN ||
520         !L->contains(PN->getIncomingBlock(i)))
521       OuterLoopPreds.push_back(PN->getIncomingBlock(i));
522
523   BasicBlock *Header = L->getHeader();
524   BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
525
526   // Update dominator information (set, immdom, domtree, and domfrontier)
527   UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
528
529   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
530   // code layout too horribly.
531   PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
532   
533   // Create the new outer loop.
534   Loop *NewOuter = new Loop();
535
536   // Change the parent loop to use the outer loop as its child now.
537   if (Loop *Parent = L->getParentLoop())
538     Parent->replaceChildLoopWith(L, NewOuter);
539   else
540     LI->changeTopLevelLoop(L, NewOuter);
541
542   // This block is going to be our new header block: add it to this loop and all
543   // parent loops.
544   NewOuter->addBasicBlockToLoop(NewBB, *LI);
545
546   // L is now a subloop of our outer loop.
547   NewOuter->addChildLoop(L);
548
549   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
550     NewOuter->addBlockEntry(L->getBlocks()[i]);
551
552   // Determine which blocks should stay in L and which should be moved out to
553   // the Outer loop now.
554   std::set<BasicBlock*> BlocksInL;
555   for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
556     if (DT->dominates(Header, *PI))
557       AddBlockAndPredsToSet(*PI, Header, BlocksInL);
558
559
560   // Scan all of the loop children of L, moving them to OuterLoop if they are
561   // not part of the inner loop.
562   for (Loop::iterator I = L->begin(); I != L->end(); )
563     if (BlocksInL.count((*I)->getHeader()))
564       ++I;   // Loop remains in L
565     else
566       NewOuter->addChildLoop(L->removeChildLoop(I));
567
568   // Now that we know which blocks are in L and which need to be moved to
569   // OuterLoop, move any blocks that need it.
570   for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
571     BasicBlock *BB = L->getBlocks()[i];
572     if (!BlocksInL.count(BB)) {
573       // Move this block to the parent, updating the exit blocks sets
574       L->removeBlockFromLoop(BB);
575       if ((*LI)[BB] == L)
576         LI->changeLoopFor(BB, NewOuter);
577       --i;
578     }
579   }
580
581   return NewOuter;
582 }
583
584
585
586 /// InsertUniqueBackedgeBlock - This method is called when the specified loop
587 /// has more than one backedge in it.  If this occurs, revector all of these
588 /// backedges to target a new basic block and have that block branch to the loop
589 /// header.  This ensures that loops have exactly one backedge.
590 ///
591 void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
592   assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
593
594   // Get information about the loop
595   BasicBlock *Preheader = L->getLoopPreheader();
596   BasicBlock *Header = L->getHeader();
597   Function *F = Header->getParent();
598
599   // Figure out which basic blocks contain back-edges to the loop header.
600   std::vector<BasicBlock*> BackedgeBlocks;
601   for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
602     if (*I != Preheader) BackedgeBlocks.push_back(*I);
603
604   // Create and insert the new backedge block...
605   BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
606   BranchInst *BETerminator = new BranchInst(Header, BEBlock);
607
608   // Move the new backedge block to right after the last backedge block.
609   Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
610   F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
611
612   // Now that the block has been inserted into the function, create PHI nodes in
613   // the backedge block which correspond to any PHI nodes in the header block.
614   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
615     PHINode *PN = cast<PHINode>(I);
616     PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
617                                  BETerminator);
618     NewPN->reserveOperandSpace(BackedgeBlocks.size());
619     if (AA) AA->copyValue(PN, NewPN);
620
621     // Loop over the PHI node, moving all entries except the one for the
622     // preheader over to the new PHI node.
623     unsigned PreheaderIdx = ~0U;
624     bool HasUniqueIncomingValue = true;
625     Value *UniqueValue = 0;
626     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
627       BasicBlock *IBB = PN->getIncomingBlock(i);
628       Value *IV = PN->getIncomingValue(i);
629       if (IBB == Preheader) {
630         PreheaderIdx = i;
631       } else {
632         NewPN->addIncoming(IV, IBB);
633         if (HasUniqueIncomingValue) {
634           if (UniqueValue == 0)
635             UniqueValue = IV;
636           else if (UniqueValue != IV)
637             HasUniqueIncomingValue = false;
638         }
639       }
640     }
641
642     // Delete all of the incoming values from the old PN except the preheader's
643     assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
644     if (PreheaderIdx != 0) {
645       PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
646       PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
647     }
648     // Nuke all entries except the zero'th.
649     for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
650       PN->removeIncomingValue(e-i, false);
651
652     // Finally, add the newly constructed PHI node as the entry for the BEBlock.
653     PN->addIncoming(NewPN, BEBlock);
654
655     // As an optimization, if all incoming values in the new PhiNode (which is a
656     // subset of the incoming values of the old PHI node) have the same value,
657     // eliminate the PHI Node.
658     if (HasUniqueIncomingValue) {
659       NewPN->replaceAllUsesWith(UniqueValue);
660       if (AA) AA->deleteValue(NewPN);
661       BEBlock->getInstList().erase(NewPN);
662     }
663   }
664
665   // Now that all of the PHI nodes have been inserted and adjusted, modify the
666   // backedge blocks to just to the BEBlock instead of the header.
667   for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
668     TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
669     for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
670       if (TI->getSuccessor(Op) == Header)
671         TI->setSuccessor(Op, BEBlock);
672   }
673
674   //===--- Update all analyses which we must preserve now -----------------===//
675
676   // Update Loop Information - we know that this block is now in the current
677   // loop and all parent loops.
678   L->addBasicBlockToLoop(BEBlock, *LI);
679
680   // Update dominator information (set, immdom, domtree, and domfrontier)
681   UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
682 }
683
684 // Returns true if BasicBlock A dominates at least one block in vector B
685 // Helper function for UpdateDomInfoForRevectoredPreds
686 static bool BlockDominatesAny(BasicBlock* A, const std::vector<BasicBlock*>& B,
687                               DominatorTree &DT) {
688   for (std::vector<BasicBlock*>::const_iterator BI = B.begin(), BE = B.end();
689        BI != BE; ++BI) {
690     if (DT.dominates(A, *BI))
691       return true;
692   }
693   return false;
694 }
695
696 /// UpdateDomInfoForRevectoredPreds - This method is used to update
697 /// dominator trees and dominance frontiers after a new block has
698 /// been added to the CFG.
699 ///
700 /// This only supports the case when an existing block (known as "NewBBSucc"),
701 /// had some of its predecessors factored into a new basic block.  This
702 /// transformation inserts a new basic block ("NewBB"), with a single
703 /// unconditional branch to NewBBSucc, and moves some predecessors of
704 /// "NewBBSucc" to now branch to NewBB.  These predecessors are listed in
705 /// PredBlocks, even though they are the same as
706 /// pred_begin(NewBB)/pred_end(NewBB).
707 ///
708 void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
709                                          std::vector<BasicBlock*> &PredBlocks) {
710   assert(!PredBlocks.empty() && "No predblocks??");
711   assert(NewBB->getTerminator()->getNumSuccessors() == 1
712          && "NewBB should have a single successor!");
713   BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
714   DominatorTree &DT = getAnalysis<DominatorTree>();
715
716   // The newly inserted basic block will dominate existing basic blocks iff the
717   // PredBlocks dominate all of the non-pred blocks.  If all predblocks dominate
718   // the non-pred blocks, then they all must be the same block!
719   //
720   bool NewBBDominatesNewBBSucc = true;
721   {
722     BasicBlock *OnePred = PredBlocks[0];
723     unsigned i = 1, e = PredBlocks.size();
724     for (i = 1; !DT.isReachableFromEntry(OnePred); ++i) {
725       assert(i != e && "Didn't find reachable pred?");
726       OnePred = PredBlocks[i];
727     }
728     
729     for (; i != e; ++i)
730       if (PredBlocks[i] != OnePred && DT.isReachableFromEntry(OnePred)){
731         NewBBDominatesNewBBSucc = false;
732         break;
733       }
734
735     if (NewBBDominatesNewBBSucc)
736       for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
737            PI != E; ++PI)
738         if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
739           NewBBDominatesNewBBSucc = false;
740           break;
741         }
742   }
743
744   // The other scenario where the new block can dominate its successors are when
745   // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
746   // already.
747   if (!NewBBDominatesNewBBSucc) {
748     NewBBDominatesNewBBSucc = true;
749     for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
750          PI != E; ++PI)
751       if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
752         NewBBDominatesNewBBSucc = false;
753         break;
754       }
755   }
756
757
758   // Update DominatorTree information if it is active.
759
760   // Find NewBB's immediate dominator and create new dominator tree node for NewBB.
761   BasicBlock *NewBBIDom = 0;
762   unsigned i = 0;
763   for (i = 0; i < PredBlocks.size(); ++i)
764     if (DT.isReachableFromEntry(PredBlocks[i])) {
765       NewBBIDom = PredBlocks[i];
766       break;
767     }
768   assert(i != PredBlocks.size() && "No reachable preds?");
769   for (i = i + 1; i < PredBlocks.size(); ++i) {
770     if (DT.isReachableFromEntry(PredBlocks[i]))
771       NewBBIDom = DT.nearestCommonDominator(NewBBIDom, PredBlocks[i]);
772   }
773   assert(NewBBIDom && "No immediate dominator found??");
774   
775   // Create the new dominator tree node... and set the idom of NewBB.
776   DomTreeNode *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
777   
778   // If NewBB strictly dominates other blocks, then it is now the immediate
779   // dominator of NewBBSucc.  Update the dominator tree as appropriate.
780   if (NewBBDominatesNewBBSucc) {
781     DomTreeNode *NewBBSuccNode = DT.getNode(NewBBSucc);
782     DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
783   }
784
785   // Update dominance frontier information...
786   if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
787     // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
788     // DF(PredBlocks[0]) without the stuff that the new block does not dominate
789     // a predecessor of.
790     if (NewBBDominatesNewBBSucc) {
791       DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
792       if (DFI != DF->end()) {
793         DominanceFrontier::DomSetType Set = DFI->second;
794         // Filter out stuff in Set that we do not dominate a predecessor of.
795         for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
796                E = Set.end(); SetI != E;) {
797           bool DominatesPred = false;
798           for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
799                PI != E; ++PI)
800             if (DT.dominates(NewBB, *PI))
801               DominatesPred = true;
802           if (!DominatesPred)
803             Set.erase(SetI++);
804           else
805             ++SetI;
806         }
807
808         DF->addBasicBlock(NewBB, Set);
809       }
810
811     } else {
812       // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
813       // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
814       // NewBBSucc)).  NewBBSucc is the single successor of NewBB.
815       DominanceFrontier::DomSetType NewDFSet;
816       NewDFSet.insert(NewBBSucc);
817       DF->addBasicBlock(NewBB, NewDFSet);
818     }
819
820     // Now we must loop over all of the dominance frontiers in the function,
821     // replacing occurrences of NewBBSucc with NewBB in some cases.  All
822     // blocks that dominate a block in PredBlocks and contained NewBBSucc in
823     // their dominance frontier must be updated to contain NewBB instead.
824     //
825     for (Function::iterator FI = NewBB->getParent()->begin(),
826          FE = NewBB->getParent()->end(); FI != FE; ++FI) {
827       DominanceFrontier::iterator DFI = DF->find(FI);
828       if (DFI == DF->end()) continue;  // unreachable block.
829       
830       // Only consider dominators of NewBBSucc
831       if (!DFI->second.count(NewBBSucc)) continue;
832       
833       if (BlockDominatesAny(FI, PredBlocks, DT)) {
834         // If NewBBSucc should not stay in our dominator frontier, remove it.
835         // We remove it unless there is a predecessor of NewBBSucc that we
836         // dominate, but we don't strictly dominate NewBBSucc.
837         bool ShouldRemove = true;
838         if ((BasicBlock*)FI == NewBBSucc
839             || !DT.dominates(FI, NewBBSucc)) {
840           // Okay, we know that PredDom does not strictly dominate NewBBSucc.
841           // Check to see if it dominates any predecessors of NewBBSucc.
842           for (pred_iterator PI = pred_begin(NewBBSucc),
843                E = pred_end(NewBBSucc); PI != E; ++PI)
844             if (DT.dominates(FI, *PI)) {
845               ShouldRemove = false;
846               break;
847             }
848           
849           if (ShouldRemove)
850             DF->removeFromFrontier(DFI, NewBBSucc);
851           DF->addToFrontier(DFI, NewBB);
852           
853           break;
854         }
855       }
856     }
857   }
858 }
859
860