Fix computation of exit blocks
[oota-llvm.git] / lib / Analysis / LoopInfo.cpp
1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
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 file defines the LoopInfo class that is used to identify natural loops
11 // and determine the loop depth of various nodes of the CFG.  Note that the
12 // loops identified may actually be several natural loops that share the same
13 // header node... not just a single natural loop.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/Support/CFG.h"
23 #include "Support/DepthFirstIterator.h"
24 #include <algorithm>
25 using namespace llvm;
26
27 static RegisterAnalysis<LoopInfo>
28 X("loops", "Natural Loop Construction", true);
29
30 //===----------------------------------------------------------------------===//
31 // Loop implementation
32 //
33 bool Loop::contains(const BasicBlock *BB) const {
34   return find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
35 }
36
37 bool Loop::isLoopExit(const BasicBlock *BB) const {
38   for (succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB);
39        SI != SE; ++SI) {
40     if (!contains(*SI))
41       return true;
42   }
43   return false;
44 }
45
46 /// getNumBackEdges - Calculate the number of back edges to the loop header.
47 ///
48 unsigned Loop::getNumBackEdges() const {
49   unsigned NumBackEdges = 0;
50   BasicBlock *H = getHeader();
51
52   for (pred_iterator I = pred_begin(H), E = pred_end(H); I != E; ++I)
53     if (contains(*I))
54       ++NumBackEdges;
55
56   return NumBackEdges;
57 }
58
59 void Loop::print(std::ostream &OS, unsigned Depth) const {
60   OS << std::string(Depth*2, ' ') << "Loop Containing: ";
61
62   for (unsigned i = 0; i < getBlocks().size(); ++i) {
63     if (i) OS << ",";
64     WriteAsOperand(OS, getBlocks()[i], false);
65   }
66   OS << "\n";
67
68   for (iterator I = begin(), E = end(); I != E; ++I)
69     (*I)->print(OS, Depth+2);
70 }
71
72 void Loop::dump() const {
73   print(std::cerr);
74 }
75
76
77 //===----------------------------------------------------------------------===//
78 // LoopInfo implementation
79 //
80 void LoopInfo::stub() {}
81
82 bool LoopInfo::runOnFunction(Function &) {
83   releaseMemory();
84   Calculate(getAnalysis<DominatorSet>());    // Update
85   return false;
86 }
87
88 void LoopInfo::releaseMemory() {
89   for (std::vector<Loop*>::iterator I = TopLevelLoops.begin(),
90          E = TopLevelLoops.end(); I != E; ++I)
91     delete *I;   // Delete all of the loops...
92
93   BBMap.clear();                             // Reset internal state of analysis
94   TopLevelLoops.clear();
95 }
96
97
98 void LoopInfo::Calculate(const DominatorSet &DS) {
99   BasicBlock *RootNode = DS.getRoot();
100
101   for (df_iterator<BasicBlock*> NI = df_begin(RootNode),
102          NE = df_end(RootNode); NI != NE; ++NI)
103     if (Loop *L = ConsiderForLoop(*NI, DS))
104       TopLevelLoops.push_back(L);
105
106   for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
107     TopLevelLoops[i]->setLoopDepth(1);
108 }
109
110 void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
111   AU.setPreservesAll();
112   AU.addRequired<DominatorSet>();
113 }
114
115 void LoopInfo::print(std::ostream &OS) const {
116   for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
117     TopLevelLoops[i]->print(OS);
118 #if 0
119   for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(),
120          E = BBMap.end(); I != E; ++I)
121     OS << "BB '" << I->first->getName() << "' level = "
122        << I->second->LoopDepth << "\n";
123 #endif
124 }
125
126 static bool isNotAlreadyContainedIn(Loop *SubLoop, Loop *ParentLoop) {
127   if (SubLoop == 0) return true;
128   if (SubLoop == ParentLoop) return false;
129   return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
130 }
131
132 Loop *LoopInfo::ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS) {
133   if (BBMap.find(BB) != BBMap.end()) return 0;   // Haven't processed this node?
134
135   std::vector<BasicBlock *> TodoStack;
136
137   // Scan the predecessors of BB, checking to see if BB dominates any of
138   // them.  This identifies backedges which target this node...
139   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
140     if (DS.dominates(BB, *I))   // If BB dominates it's predecessor...
141       TodoStack.push_back(*I);
142
143   if (TodoStack.empty()) return 0;  // No backedges to this block...
144
145   // Create a new loop to represent this basic block...
146   Loop *L = new Loop(BB);
147   BBMap[BB] = L;
148
149   BasicBlock *EntryBlock = &BB->getParent()->getEntryBlock();
150
151   while (!TodoStack.empty()) {  // Process all the nodes in the loop
152     BasicBlock *X = TodoStack.back();
153     TodoStack.pop_back();
154
155     if (!L->contains(X) &&         // As of yet unprocessed??
156         DS.dominates(EntryBlock, X)) {   // X is reachable from entry block?
157       // Check to see if this block already belongs to a loop.  If this occurs
158       // then we have a case where a loop that is supposed to be a child of the
159       // current loop was processed before the current loop.  When this occurs,
160       // this child loop gets added to a part of the current loop, making it a
161       // sibling to the current loop.  We have to reparent this loop.
162       if (Loop *SubLoop = const_cast<Loop*>(getLoopFor(X)))
163         if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) {
164           // Remove the subloop from it's current parent...
165           assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
166           Loop *SLP = SubLoop->ParentLoop;  // SubLoopParent
167           std::vector<Loop*>::iterator I =
168             std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
169           assert(I != SLP->SubLoops.end() && "SubLoop not a child of parent?");
170           SLP->SubLoops.erase(I);   // Remove from parent...
171           
172           // Add the subloop to THIS loop...
173           SubLoop->ParentLoop = L;
174           L->SubLoops.push_back(SubLoop);
175         }
176
177       // Normal case, add the block to our loop...
178       L->Blocks.push_back(X);
179         
180       // Add all of the predecessors of X to the end of the work stack...
181       TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X));
182     }
183   }
184
185   // If there are any loops nested within this loop, create them now!
186   for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
187          E = L->Blocks.end(); I != E; ++I)
188     if (Loop *NewLoop = ConsiderForLoop(*I, DS)) {
189       L->SubLoops.push_back(NewLoop);
190       NewLoop->ParentLoop = L;
191     }
192
193   // Add the basic blocks that comprise this loop to the BBMap so that this
194   // loop can be found for them.
195   //
196   for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
197          E = L->Blocks.end(); I != E; ++I) {
198     std::map<BasicBlock*, Loop*>::iterator BBMI = BBMap.lower_bound(*I);
199     if (BBMI == BBMap.end() || BBMI->first != *I)  // Not in map yet...
200       BBMap.insert(BBMI, std::make_pair(*I, L));   // Must be at this level
201   }
202
203   // Now that we have a list of all of the child loops of this loop, check to
204   // see if any of them should actually be nested inside of each other.  We can
205   // accidentally pull loops our of their parents, so we must make sure to
206   // organize the loop nests correctly now.
207   {
208     std::map<BasicBlock*, Loop*> ContainingLoops;
209     for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
210       Loop *Child = L->SubLoops[i];
211       assert(Child->getParentLoop() == L && "Not proper child loop?");
212
213       if (Loop *ContainingLoop = ContainingLoops[Child->getHeader()]) {
214         // If there is already a loop which contains this loop, move this loop
215         // into the containing loop.
216         MoveSiblingLoopInto(Child, ContainingLoop);
217         --i;  // The loop got removed from the SubLoops list.
218       } else {
219         // This is currently considered to be a top-level loop.  Check to see if
220         // any of the contained blocks are loop headers for subloops we have
221         // already processed.
222         for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
223           Loop *&BlockLoop = ContainingLoops[Child->Blocks[b]];
224           if (BlockLoop == 0) {   // Child block not processed yet...
225             BlockLoop = Child;
226           } else if (BlockLoop != Child) {
227             Loop *SubLoop = BlockLoop;
228             // Reparent all of the blocks which used to belong to BlockLoops
229             for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
230               ContainingLoops[SubLoop->Blocks[j]] = Child;
231
232             // There is already a loop which contains this block, that means
233             // that we should reparent the loop which the block is currently
234             // considered to belong to to be a child of this loop.
235             MoveSiblingLoopInto(SubLoop, Child);
236             --i;  // We just shrunk the SubLoops list.
237           }
238         }
239       }      
240     }
241   }
242
243   return L;
244 }
245
246 /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside of
247 /// the NewParent Loop, instead of being a sibling of it.
248 void LoopInfo::MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent) {
249   Loop *OldParent = NewChild->getParentLoop();
250   assert(OldParent && OldParent == NewParent->getParentLoop() &&
251          NewChild != NewParent && "Not sibling loops!");
252
253   // Remove NewChild from being a child of OldParent
254   std::vector<Loop*>::iterator I =
255     std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(), NewChild);
256   assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
257   OldParent->SubLoops.erase(I);   // Remove from parent's subloops list
258   NewChild->ParentLoop = 0;
259   
260   InsertLoopInto(NewChild, NewParent);  
261 }
262
263 /// InsertLoopInto - This inserts loop L into the specified parent loop.  If the
264 /// parent loop contains a loop which should contain L, the loop gets inserted
265 /// into L instead.
266 void LoopInfo::InsertLoopInto(Loop *L, Loop *Parent) {
267   BasicBlock *LHeader = L->getHeader();
268   assert(Parent->contains(LHeader) && "This loop should not be inserted here!");
269   
270   // Check to see if it belongs in a child loop...
271   for (unsigned i = 0, e = Parent->SubLoops.size(); i != e; ++i)
272     if (Parent->SubLoops[i]->contains(LHeader)) {
273       InsertLoopInto(L, Parent->SubLoops[i]);
274       return;
275     }      
276
277   // If not, insert it here!
278   Parent->SubLoops.push_back(L);
279   L->ParentLoop = Parent;
280 }
281
282 /// changeLoopFor - Change the top-level loop that contains BB to the
283 /// specified loop.  This should be used by transformations that restructure
284 /// the loop hierarchy tree.
285 void LoopInfo::changeLoopFor(BasicBlock *BB, Loop *L) {
286   Loop *&OldLoop = BBMap[BB];
287   assert(OldLoop && "Block not in a loop yet!");
288   OldLoop = L;
289 }
290
291 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
292 /// list with the indicated loop.
293 void LoopInfo::changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
294   std::vector<Loop*>::iterator I = std::find(TopLevelLoops.begin(),
295                                              TopLevelLoops.end(), OldLoop);
296   assert(I != TopLevelLoops.end() && "Old loop not at top level!");
297   *I = NewLoop;
298   assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
299          "Loops already embedded into a subloop!");
300 }
301
302 /// removeLoop - This removes the specified top-level loop from this loop info
303 /// object.  The loop is not deleted, as it will presumably be inserted into
304 /// another loop.
305 Loop *LoopInfo::removeLoop(iterator I) {
306   assert(I != end() && "Cannot remove end iterator!");
307   Loop *L = *I;
308   assert(L->getParentLoop() == 0 && "Not a top-level loop!");
309   TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
310   return L;
311 }
312
313 /// removeBlock - This method completely removes BB from all data structures,
314 /// including all of the Loop objects it is nested in and our mapping from
315 /// BasicBlocks to loops.
316 void LoopInfo::removeBlock(BasicBlock *BB) {
317   std::map<BasicBlock *, Loop*>::iterator I = BBMap.find(BB);
318   if (I != BBMap.end()) {
319     for (Loop *L = I->second; L; L = L->getParentLoop())
320       L->removeBlockFromLoop(BB);
321     
322     BBMap.erase(I);
323   }
324 }
325
326
327 //===----------------------------------------------------------------------===//
328 // APIs for simple analysis of the loop.
329 //
330
331 /// getExitBlocks - Return all of the successor blocks of this loop.  These
332 /// are the blocks _outside of the current loop_ which are branched to.
333 ///
334 void Loop::getExitBlocks(std::vector<BasicBlock*> &ExitBlocks) const {
335   for (std::vector<BasicBlock*>::const_iterator BI = Blocks.begin(),
336          BE = Blocks.end(); BI != BE; ++BI)
337     for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I)
338       if (!contains(*I))               // Not in current loop?
339         ExitBlocks.push_back(*I);          // It must be an exit block...
340 }
341
342
343 /// getLoopPreheader - If there is a preheader for this loop, return it.  A
344 /// loop has a preheader if there is only one edge to the header of the loop
345 /// from outside of the loop.  If this is the case, the block branching to the
346 /// header of the loop is the preheader node.
347 ///
348 /// This method returns null if there is no preheader for the loop.
349 ///
350 BasicBlock *Loop::getLoopPreheader() const {
351   // Keep track of nodes outside the loop branching to the header...
352   BasicBlock *Out = 0;
353
354   // Loop over the predecessors of the header node...
355   BasicBlock *Header = getHeader();
356   for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
357        PI != PE; ++PI)
358     if (!contains(*PI)) {     // If the block is not in the loop...
359       if (Out && Out != *PI)
360         return 0;             // Multiple predecessors outside the loop
361       Out = *PI;
362     }
363   
364   // Make sure there is only one exit out of the preheader...
365   succ_iterator SI = succ_begin(Out);
366   ++SI;
367   if (SI != succ_end(Out))
368     return 0;  // Multiple exits from the block, must not be a preheader.
369
370
371   // If there is exactly one preheader, return it.  If there was zero, then Out
372   // is still null.
373   return Out;
374 }
375
376 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
377 /// induction variable: an integer recurrence that starts at 0 and increments by
378 /// one each time through the loop.  If so, return the phi node that corresponds
379 /// to it.
380 ///
381 PHINode *Loop::getCanonicalInductionVariable() const {
382   BasicBlock *H = getHeader();
383
384   BasicBlock *Incoming = 0, *Backedge = 0;
385   pred_iterator PI = pred_begin(H);
386   assert(PI != pred_end(H) && "Loop must have at least one backedge!");
387   Backedge = *PI++;
388   if (PI == pred_end(H)) return 0;  // dead loop
389   Incoming = *PI++;
390   if (PI != pred_end(H)) return 0;  // multiple backedges?
391
392   if (contains(Incoming)) {
393     if (contains(Backedge))
394       return 0;
395     std::swap(Incoming, Backedge);
396   } else if (!contains(Backedge))
397     return 0;
398
399   // Loop over all of the PHI nodes, looking for a canonical indvar.
400   for (BasicBlock::iterator I = H->begin();
401        PHINode *PN = dyn_cast<PHINode>(I); ++I)
402     if (Instruction *Inc =
403         dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
404       if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
405         if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
406           if (CI->equalsInt(1))
407             return PN;
408
409   return 0;
410 }
411
412 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
413 /// the canonical induction variable value for the "next" iteration of the loop.
414 /// This always succeeds if getCanonicalInductionVariable succeeds.
415 ///
416 Instruction *Loop::getCanonicalInductionVariableIncrement() const {
417   if (PHINode *PN = getCanonicalInductionVariable()) {
418     bool P1InLoop = contains(PN->getIncomingBlock(1));
419     return cast<Instruction>(PN->getIncomingValue(P1InLoop));
420   }
421   return 0;
422 }
423
424 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
425 /// times the loop will be executed.  Note that this means that the backedge of
426 /// the loop executes N-1 times.  If the trip-count cannot be determined, this
427 /// returns null.
428 ///
429 Value *Loop::getTripCount() const {
430   // Canonical loops will end with a 'setne I, V', where I is the incremented
431   // canonical induction variable and V is the trip count of the loop.
432   Instruction *Inc = getCanonicalInductionVariableIncrement();
433   if (Inc == 0) return 0;
434   PHINode *IV = cast<PHINode>(Inc->getOperand(0));
435   
436   BasicBlock *BackedgeBlock =
437     IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
438
439   if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
440     if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
441       if (SCI->getOperand(0) == Inc)
442         if (BI->getSuccessor(0) == getHeader()) {
443           if (SCI->getOpcode() == Instruction::SetNE)
444             return SCI->getOperand(1);
445         } else if (SCI->getOpcode() == Instruction::SetEQ) {
446           return SCI->getOperand(1);
447         }
448   
449   return 0;
450 }
451
452
453 //===-------------------------------------------------------------------===//
454 // APIs for updating loop information after changing the CFG
455 //
456
457 /// addBasicBlockToLoop - This function is used by other analyses to update loop
458 /// information.  NewBB is set to be a new member of the current loop.  Because
459 /// of this, it is added as a member of all parent loops, and is added to the
460 /// specified LoopInfo object as being in the current basic block.  It is not
461 /// valid to replace the loop header with this method.
462 ///
463 void Loop::addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI) {
464   assert((Blocks.empty() || LI[getHeader()] == this) &&
465          "Incorrect LI specified for this loop!");
466   assert(NewBB && "Cannot add a null basic block to the loop!");
467   assert(LI[NewBB] == 0 && "BasicBlock already in the loop!");
468
469   // Add the loop mapping to the LoopInfo object...
470   LI.BBMap[NewBB] = this;
471
472   // Add the basic block to this loop and all parent loops...
473   Loop *L = this;
474   while (L) {
475     L->Blocks.push_back(NewBB);
476     L = L->getParentLoop();
477   }
478 }
479
480 /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
481 /// the OldChild entry in our children list with NewChild, and updates the
482 /// parent pointers of the two loops as appropriate.
483 void Loop::replaceChildLoopWith(Loop *OldChild, Loop *NewChild) {
484   assert(OldChild->ParentLoop == this && "This loop is already broken!");
485   assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
486   std::vector<Loop*>::iterator I = std::find(SubLoops.begin(), SubLoops.end(),
487                                              OldChild);
488   assert(I != SubLoops.end() && "OldChild not in loop!");
489   *I = NewChild;
490   OldChild->ParentLoop = 0;
491   NewChild->ParentLoop = this;
492
493   // Update the loop depth of the new child.
494   NewChild->setLoopDepth(LoopDepth+1);
495 }
496
497 /// addChildLoop - Add the specified loop to be a child of this loop.
498 ///
499 void Loop::addChildLoop(Loop *NewChild) {
500   assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
501   NewChild->ParentLoop = this;
502   SubLoops.push_back(NewChild);
503
504   // Update the loop depth of the new child.
505   NewChild->setLoopDepth(LoopDepth+1);
506 }
507
508 template<typename T>
509 static void RemoveFromVector(std::vector<T*> &V, T *N) {
510   typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
511   assert(I != V.end() && "N is not in this list!");
512   V.erase(I);
513 }
514
515 /// removeChildLoop - This removes the specified child from being a subloop of
516 /// this loop.  The loop is not deleted, as it will presumably be inserted
517 /// into another loop.
518 Loop *Loop::removeChildLoop(iterator I) {
519   assert(I != SubLoops.end() && "Cannot remove end iterator!");
520   Loop *Child = *I;
521   assert(Child->ParentLoop == this && "Child is not a child of this loop!");
522   SubLoops.erase(SubLoops.begin()+(I-begin()));
523   Child->ParentLoop = 0;
524   return Child;
525 }
526
527
528 /// removeBlockFromLoop - This removes the specified basic block from the
529 /// current loop, updating the Blocks and ExitBlocks lists as appropriate.  This
530 /// does not update the mapping in the LoopInfo class.
531 void Loop::removeBlockFromLoop(BasicBlock *BB) {
532   RemoveFromVector(Blocks, BB);
533 }