1 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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 natural
12 // loops may actually be several loops that share the same header node.
14 // This analysis calculates the nesting structure of loops in a function. For
15 // each natural loop identified, this analysis identifies natural loops
16 // contained entirely within the loop and the basic blocks the make up the loop.
18 // It can calculate on the fly various bits of information, for example:
20 // * whether there is a preheader for the loop
21 // * the number of back edges to the header
22 // * whether or not a particular block branches out of the loop
23 // * the successor blocks of the loop
28 //===----------------------------------------------------------------------===//
30 #ifndef LLVM_ANALYSIS_LOOP_INFO_H
31 #define LLVM_ANALYSIS_LOOP_INFO_H
33 #include "llvm/Pass.h"
34 #include "llvm/Constants.h"
35 #include "llvm/Instructions.h"
36 #include "llvm/ADT/DepthFirstIterator.h"
37 #include "llvm/ADT/GraphTraits.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/Analysis/Dominators.h"
41 #include "llvm/Support/CFG.h"
42 #include "llvm/Support/Streams.h"
47 static void RemoveFromVector(std::vector<T*> &V, T *N) {
48 typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
49 assert(I != V.end() && "N is not in this list!");
59 template<class N> class LoopInfoBase;
61 //===----------------------------------------------------------------------===//
62 /// LoopBase class - Instances of this class are used to represent loops that are
63 /// detected in the flow graph
65 template<class BlockT>
67 LoopBase<BlockT> *ParentLoop;
68 std::vector<LoopBase<BlockT>*> SubLoops; // Loops contained entirely within this one
69 std::vector<BlockT*> Blocks; // First entry is the header node
71 LoopBase(const LoopBase<BlockT> &); // DO NOT IMPLEMENT
72 const LoopBase<BlockT> &operator=(const LoopBase<BlockT> &); // DO NOT IMPLEMENT
74 /// Loop ctor - This creates an empty loop.
75 LoopBase() : ParentLoop(0) {}
77 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
81 unsigned getLoopDepth() const {
83 for (const LoopBase<BlockT> *CurLoop = this; CurLoop;
84 CurLoop = CurLoop->ParentLoop)
88 BlockT *getHeader() const { return Blocks.front(); }
89 LoopBase<BlockT> *getParentLoop() const { return ParentLoop; }
91 /// contains - Return true of the specified basic block is in this loop
93 bool contains(const BlockT *BB) const {
94 return std::find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
97 /// iterator/begin/end - Return the loops contained entirely within this loop.
99 const std::vector<LoopBase<BlockT>*> &getSubLoops() const { return SubLoops; }
100 typedef typename std::vector<LoopBase<BlockT>*>::const_iterator iterator;
101 iterator begin() const { return SubLoops.begin(); }
102 iterator end() const { return SubLoops.end(); }
103 bool empty() const { return SubLoops.empty(); }
105 /// getBlocks - Get a list of the basic blocks which make up this loop.
107 const std::vector<BlockT*> &getBlocks() const { return Blocks; }
108 typedef typename std::vector<BlockT*>::const_iterator block_iterator;
109 block_iterator block_begin() const { return Blocks.begin(); }
110 block_iterator block_end() const { return Blocks.end(); }
112 /// isLoopExit - True if terminator in the block can branch to another block
113 /// that is outside of the current loop.
115 bool isLoopExit(const BlockT *BB) const {
116 typedef GraphTraits<BlockT*> BlockTraits;
117 for (typename BlockTraits::ChildIteratorType SI =
118 BlockTraits::child_begin(const_cast<BlockT*>(BB)),
119 SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
126 /// getNumBackEdges - Calculate the number of back edges to the loop header
128 unsigned getNumBackEdges() const {
129 unsigned NumBackEdges = 0;
130 BlockT *H = getHeader();
132 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
133 for (typename InvBlockTraits::ChildIteratorType I =
134 InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
135 E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
142 /// isLoopInvariant - Return true if the specified value is loop invariant
144 bool isLoopInvariant(Value *V) const {
145 if (Instruction *I = dyn_cast<Instruction>(V))
146 return !contains(I->getParent());
147 return true; // All non-instructions are loop invariant
150 //===--------------------------------------------------------------------===//
151 // APIs for simple analysis of the loop.
153 // Note that all of these methods can fail on general loops (ie, there may not
154 // be a preheader, etc). For best success, the loop simplification and
155 // induction variable canonicalization pass should be used to normalize loops
156 // for easy analysis. These methods assume canonical loops.
158 /// getExitingBlocks - Return all blocks inside the loop that have successors
159 /// outside of the loop. These are the blocks _inside of the current loop_
160 /// which branch out. The returned list is always unique.
162 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
163 // Sort the blocks vector so that we can use binary search to do quick
165 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
166 std::sort(LoopBBs.begin(), LoopBBs.end());
168 typedef GraphTraits<BlockT*> BlockTraits;
169 for (typename std::vector<BlockT*>::const_iterator BI = Blocks.begin(),
170 BE = Blocks.end(); BI != BE; ++BI)
171 for (typename BlockTraits::ChildIteratorType I =
172 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
174 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
175 // Not in current loop? It must be an exit block.
176 ExitingBlocks.push_back(*BI);
181 /// getExitBlocks - Return all of the successor blocks of this loop. These
182 /// are the blocks _outside of the current loop_ which are branched to.
184 void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
185 // Sort the blocks vector so that we can use binary search to do quick
187 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
188 std::sort(LoopBBs.begin(), LoopBBs.end());
190 typedef GraphTraits<BlockT*> BlockTraits;
191 for (typename std::vector<BlockT*>::const_iterator BI = Blocks.begin(),
192 BE = Blocks.end(); BI != BE; ++BI)
193 for (typename BlockTraits::ChildIteratorType I =
194 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
196 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
197 // Not in current loop? It must be an exit block.
198 ExitBlocks.push_back(*I);
201 /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
202 /// These are the blocks _outside of the current loop_ which are branched to.
203 /// This assumes that loop is in canonical form.
205 void getUniqueExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
206 // Sort the blocks vector so that we can use binary search to do quick
208 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
209 std::sort(LoopBBs.begin(), LoopBBs.end());
211 std::vector<BlockT*> switchExitBlocks;
213 for (typename std::vector<BlockT*>::const_iterator BI = Blocks.begin(),
214 BE = Blocks.end(); BI != BE; ++BI) {
216 BlockT *current = *BI;
217 switchExitBlocks.clear();
219 typedef GraphTraits<BlockT*> BlockTraits;
220 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
221 for (typename BlockTraits::ChildIteratorType I =
222 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
224 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
225 // If block is inside the loop then it is not a exit block.
228 typename InvBlockTraits::ChildIteratorType PI =
229 InvBlockTraits::child_begin(*I);
230 BlockT *firstPred = *PI;
232 // If current basic block is this exit block's first predecessor
233 // then only insert exit block in to the output ExitBlocks vector.
234 // This ensures that same exit block is not inserted twice into
235 // ExitBlocks vector.
236 if (current != firstPred)
239 // If a terminator has more then two successors, for example SwitchInst,
240 // then it is possible that there are multiple edges from current block
241 // to one exit block.
242 if (std::distance(BlockTraits::child_begin(current),
243 BlockTraits::child_end(current)) <= 2) {
244 ExitBlocks.push_back(*I);
248 // In case of multiple edges from current block to exit block, collect
249 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
251 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
252 == switchExitBlocks.end()) {
253 switchExitBlocks.push_back(*I);
254 ExitBlocks.push_back(*I);
260 /// getLoopPreheader - If there is a preheader for this loop, return it. A
261 /// loop has a preheader if there is only one edge to the header of the loop
262 /// from outside of the loop. If this is the case, the block branching to the
263 /// header of the loop is the preheader node.
265 /// This method returns null if there is no preheader for the loop.
267 BlockT *getLoopPreheader() const {
268 // Keep track of nodes outside the loop branching to the header...
271 // Loop over the predecessors of the header node...
272 BlockT *Header = getHeader();
273 typedef GraphTraits<BlockT*> BlockTraits;
274 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
275 for (typename InvBlockTraits::ChildIteratorType PI =
276 InvBlockTraits::child_begin(Header),
277 PE = InvBlockTraits::child_end(Header); PI != PE; ++PI)
278 if (!contains(*PI)) { // If the block is not in the loop...
279 if (Out && Out != *PI)
280 return 0; // Multiple predecessors outside the loop
284 // Make sure there is only one exit out of the preheader.
285 assert(Out && "Header of loop has no predecessors from outside loop?");
286 typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
288 if (SI != BlockTraits::child_end(Out))
289 return 0; // Multiple exits from the block, must not be a preheader.
291 // If there is exactly one preheader, return it. If there was zero, then Out
296 /// getLoopLatch - If there is a latch block for this loop, return it. A
297 /// latch block is the canonical backedge for a loop. A loop header in normal
298 /// form has two edges into it: one from a preheader and one from a latch
300 BlockT *getLoopLatch() const {
301 BlockT *Header = getHeader();
302 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
303 typename InvBlockTraits::ChildIteratorType PI =
304 InvBlockTraits::child_begin(Header);
305 typename InvBlockTraits::ChildIteratorType PE =
306 InvBlockTraits::child_end(Header);
307 if (PI == PE) return 0; // no preds?
313 if (PI == PE) return 0; // only one pred?
316 if (Latch) return 0; // multiple backedges
320 if (PI != PE) return 0; // more than two preds
325 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
326 /// induction variable: an integer recurrence that starts at 0 and increments
327 /// by one each time through the loop. If so, return the phi node that
328 /// corresponds to it.
330 PHINode *getCanonicalInductionVariable() const {
331 BlockT *H = getHeader();
333 BlockT *Incoming = 0, *Backedge = 0;
334 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
335 typename InvBlockTraits::ChildIteratorType PI =
336 InvBlockTraits::child_begin(H);
337 assert(PI != InvBlockTraits::child_end(H) &&
338 "Loop must have at least one backedge!");
340 if (PI == InvBlockTraits::child_end(H)) return 0; // dead loop
342 if (PI != InvBlockTraits::child_end(H)) return 0; // multiple backedges?
344 if (contains(Incoming)) {
345 if (contains(Backedge))
347 std::swap(Incoming, Backedge);
348 } else if (!contains(Backedge))
351 // Loop over all of the PHI nodes, looking for a canonical indvar.
352 for (typename BlockT::iterator I = H->begin(); isa<PHINode>(I); ++I) {
353 PHINode *PN = cast<PHINode>(I);
354 if (Instruction *Inc =
355 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
356 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
357 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
358 if (CI->equalsInt(1))
364 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
365 /// the canonical induction variable value for the "next" iteration of the
366 /// loop. This always succeeds if getCanonicalInductionVariable succeeds.
368 Instruction *getCanonicalInductionVariableIncrement() const {
369 if (PHINode *PN = getCanonicalInductionVariable()) {
370 bool P1InLoop = contains(PN->getIncomingBlock(1));
371 return cast<Instruction>(PN->getIncomingValue(P1InLoop));
376 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
377 /// times the loop will be executed. Note that this means that the backedge
378 /// of the loop executes N-1 times. If the trip-count cannot be determined,
379 /// this returns null.
381 Value *getTripCount() const {
382 // Canonical loops will end with a 'cmp ne I, V', where I is the incremented
383 // canonical induction variable and V is the trip count of the loop.
384 Instruction *Inc = getCanonicalInductionVariableIncrement();
385 if (Inc == 0) return 0;
386 PHINode *IV = cast<PHINode>(Inc->getOperand(0));
388 BlockT *BackedgeBlock =
389 IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
391 if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
392 if (BI->isConditional()) {
393 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
394 if (ICI->getOperand(0) == Inc)
395 if (BI->getSuccessor(0) == getHeader()) {
396 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
397 return ICI->getOperand(1);
398 } else if (ICI->getPredicate() == ICmpInst::ICMP_EQ) {
399 return ICI->getOperand(1);
407 /// isLCSSAForm - Return true if the Loop is in LCSSA form
408 bool isLCSSAForm() const {
409 // Sort the blocks vector so that we can use binary search to do quick
411 SmallPtrSet<BlockT*, 16> LoopBBs(block_begin(), block_end());
413 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
415 for (typename BlockT::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
416 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
418 BlockT *UserBB = cast<Instruction>(*UI)->getParent();
419 if (PHINode *P = dyn_cast<PHINode>(*UI)) {
420 unsigned OperandNo = UI.getOperandNo();
421 UserBB = P->getIncomingBlock(OperandNo/2);
424 // Check the current block, as a fast-path. Most values are used in the
425 // same block they are defined in.
426 if (UserBB != BB && !LoopBBs.count(UserBB))
434 //===--------------------------------------------------------------------===//
435 // APIs for updating loop information after changing the CFG
438 /// addBasicBlockToLoop - This method is used by other analyses to update loop
439 /// information. NewBB is set to be a new member of the current loop.
440 /// Because of this, it is added as a member of all parent loops, and is added
441 /// to the specified LoopInfo object as being in the current basic block. It
442 /// is not valid to replace the loop header with this method.
444 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT> &LI);
446 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
447 /// the OldChild entry in our children list with NewChild, and updates the
448 /// parent pointer of OldChild to be null and the NewChild to be this loop.
449 /// This updates the loop depth of the new child.
450 void replaceChildLoopWith(LoopBase<BlockT> *OldChild,
451 LoopBase<BlockT> *NewChild) {
452 assert(OldChild->ParentLoop == this && "This loop is already broken!");
453 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
454 typename std::vector<LoopBase<BlockT>*>::iterator I =
455 std::find(SubLoops.begin(), SubLoops.end(), OldChild);
456 assert(I != SubLoops.end() && "OldChild not in loop!");
458 OldChild->ParentLoop = 0;
459 NewChild->ParentLoop = this;
462 /// addChildLoop - Add the specified loop to be a child of this loop. This
463 /// updates the loop depth of the new child.
465 void addChildLoop(LoopBase<BlockT> *NewChild) {
466 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
467 NewChild->ParentLoop = this;
468 SubLoops.push_back(NewChild);
471 /// removeChildLoop - This removes the specified child from being a subloop of
472 /// this loop. The loop is not deleted, as it will presumably be inserted
473 /// into another loop.
474 LoopBase<BlockT> *removeChildLoop(iterator I) {
475 assert(I != SubLoops.end() && "Cannot remove end iterator!");
476 LoopBase<BlockT> *Child = *I;
477 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
478 SubLoops.erase(SubLoops.begin()+(I-begin()));
479 Child->ParentLoop = 0;
483 /// addBlockEntry - This adds a basic block directly to the basic block list.
484 /// This should only be used by transformations that create new loops. Other
485 /// transformations should use addBasicBlockToLoop.
486 void addBlockEntry(BlockT *BB) {
487 Blocks.push_back(BB);
490 /// moveToHeader - This method is used to move BB (which must be part of this
491 /// loop) to be the loop header of the loop (the block that dominates all
493 void moveToHeader(BlockT *BB) {
494 if (Blocks[0] == BB) return;
495 for (unsigned i = 0; ; ++i) {
496 assert(i != Blocks.size() && "Loop does not contain BB!");
497 if (Blocks[i] == BB) {
498 Blocks[i] = Blocks[0];
505 /// removeBlockFromLoop - This removes the specified basic block from the
506 /// current loop, updating the Blocks as appropriate. This does not update
507 /// the mapping in the LoopInfo class.
508 void removeBlockFromLoop(BlockT *BB) {
509 RemoveFromVector(Blocks, BB);
512 /// verifyLoop - Verify loop structure
513 void verifyLoop() const {
515 assert (getHeader() && "Loop header is missing");
516 assert (getLoopPreheader() && "Loop preheader is missing");
517 assert (getLoopLatch() && "Loop latch is missing");
518 for (typename std::vector<LoopBase<BlockT>*>::const_iterator I =
519 SubLoops.begin(), E = SubLoops.end(); I != E; ++I)
524 void print(std::ostream &OS, unsigned Depth = 0) const {
525 OS << std::string(Depth*2, ' ') << "Loop Containing: ";
527 for (unsigned i = 0; i < getBlocks().size(); ++i) {
529 WriteAsOperand(OS, getBlocks()[i], false);
533 for (iterator I = begin(), E = end(); I != E; ++I)
534 (*I)->print(OS, Depth+2);
537 void print(std::ostream *O, unsigned Depth = 0) const {
538 if (O) print(*O, Depth);
546 friend class LoopInfoBase<BlockT>;
547 LoopBase(BlockT *BB) : ParentLoop(0) {
548 Blocks.push_back(BB);
552 typedef LoopBase<BasicBlock> Loop;
555 //===----------------------------------------------------------------------===//
556 /// LoopInfo - This class builds and contains all of the top level loop
557 /// structures in the specified function.
560 template<class BlockT>
562 // BBMap - Mapping of basic blocks to the inner most loop they occur in
563 std::map<BlockT*, LoopBase<BlockT>*> BBMap;
564 std::vector<LoopBase<BlockT>*> TopLevelLoops;
565 friend class LoopBase<BlockT>;
569 ~LoopInfoBase() { releaseMemory(); }
571 void releaseMemory() {
572 for (typename std::vector<LoopBase<BlockT>* >::iterator I =
573 TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
574 delete *I; // Delete all of the loops...
576 BBMap.clear(); // Reset internal state of analysis
577 TopLevelLoops.clear();
580 /// iterator/begin/end - The interface to the top-level loops in the current
583 typedef typename std::vector<LoopBase<BlockT>*>::const_iterator iterator;
584 iterator begin() const { return TopLevelLoops.begin(); }
585 iterator end() const { return TopLevelLoops.end(); }
587 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
588 /// block is in no loop (for example the entry node), null is returned.
590 LoopBase<BlockT> *getLoopFor(const BlockT *BB) const {
591 typename std::map<BlockT *, LoopBase<BlockT>*>::const_iterator I=
592 BBMap.find(const_cast<BlockT*>(BB));
593 return I != BBMap.end() ? I->second : 0;
596 /// operator[] - same as getLoopFor...
598 const LoopBase<BlockT> *operator[](const BlockT *BB) const {
599 return getLoopFor(BB);
602 /// getLoopDepth - Return the loop nesting level of the specified block...
604 unsigned getLoopDepth(const BlockT *BB) const {
605 const LoopBase<BlockT> *L = getLoopFor(BB);
606 return L ? L->getLoopDepth() : 0;
609 // isLoopHeader - True if the block is a loop header node
610 bool isLoopHeader(BlockT *BB) const {
611 const LoopBase<BlockT> *L = getLoopFor(BB);
612 return L && L->getHeader() == BB;
615 /// removeLoop - This removes the specified top-level loop from this loop info
616 /// object. The loop is not deleted, as it will presumably be inserted into
618 LoopBase<BlockT> *removeLoop(iterator I) {
619 assert(I != end() && "Cannot remove end iterator!");
620 LoopBase<BlockT> *L = *I;
621 assert(L->getParentLoop() == 0 && "Not a top-level loop!");
622 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
626 /// changeLoopFor - Change the top-level loop that contains BB to the
627 /// specified loop. This should be used by transformations that restructure
628 /// the loop hierarchy tree.
629 void changeLoopFor(BlockT *BB, LoopBase<BlockT> *L) {
630 LoopBase<BlockT> *&OldLoop = BBMap[BB];
631 assert(OldLoop && "Block not in a loop yet!");
635 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
636 /// list with the indicated loop.
637 void changeTopLevelLoop(LoopBase<BlockT> *OldLoop,
638 LoopBase<BlockT> *NewLoop) {
639 typename std::vector<LoopBase<BlockT>*>::iterator I =
640 std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
641 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
643 assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
644 "Loops already embedded into a subloop!");
647 /// addTopLevelLoop - This adds the specified loop to the collection of
649 void addTopLevelLoop(LoopBase<BlockT> *New) {
650 assert(New->getParentLoop() == 0 && "Loop already in subloop!");
651 TopLevelLoops.push_back(New);
654 /// removeBlock - This method completely removes BB from all data structures,
655 /// including all of the Loop objects it is nested in and our mapping from
656 /// BasicBlocks to loops.
657 void removeBlock(BlockT *BB) {
658 typename std::map<BlockT *, LoopBase<BlockT>*>::iterator I = BBMap.find(BB);
659 if (I != BBMap.end()) {
660 for (LoopBase<BlockT> *L = I->second; L; L = L->getParentLoop())
661 L->removeBlockFromLoop(BB);
669 static bool isNotAlreadyContainedIn(LoopBase<BlockT> *SubLoop,
670 LoopBase<BlockT> *ParentLoop) {
671 if (SubLoop == 0) return true;
672 if (SubLoop == ParentLoop) return false;
673 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
676 void Calculate(DominatorTreeBase<BlockT> &DT) {
677 BlockT *RootNode = DT.getRootNode()->getBlock();
679 for (df_iterator<BlockT*> NI = df_begin(RootNode),
680 NE = df_end(RootNode); NI != NE; ++NI)
681 if (LoopBase<BlockT> *L = ConsiderForLoop(*NI, DT))
682 TopLevelLoops.push_back(L);
685 LoopBase<BlockT> *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
686 if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node?
688 std::vector<BlockT *> TodoStack;
690 // Scan the predecessors of BB, checking to see if BB dominates any of
691 // them. This identifies backedges which target this node...
692 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
693 for (typename InvBlockTraits::ChildIteratorType I =
694 InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
696 if (DT.dominates(BB, *I)) // If BB dominates it's predecessor...
697 TodoStack.push_back(*I);
699 if (TodoStack.empty()) return 0; // No backedges to this block...
701 // Create a new loop to represent this basic block...
702 LoopBase<BlockT> *L = new LoopBase<BlockT>(BB);
705 BlockT *EntryBlock = BB->getParent()->begin();
707 while (!TodoStack.empty()) { // Process all the nodes in the loop
708 BlockT *X = TodoStack.back();
709 TodoStack.pop_back();
711 if (!L->contains(X) && // As of yet unprocessed??
712 DT.dominates(EntryBlock, X)) { // X is reachable from entry block?
713 // Check to see if this block already belongs to a loop. If this occurs
714 // then we have a case where a loop that is supposed to be a child of the
715 // current loop was processed before the current loop. When this occurs,
716 // this child loop gets added to a part of the current loop, making it a
717 // sibling to the current loop. We have to reparent this loop.
718 if (LoopBase<BlockT> *SubLoop =
719 const_cast<LoopBase<BlockT>*>(getLoopFor(X)))
720 if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) {
721 // Remove the subloop from it's current parent...
722 assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
723 LoopBase<BlockT> *SLP = SubLoop->ParentLoop; // SubLoopParent
724 typename std::vector<LoopBase<BlockT>*>::iterator I =
725 std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
726 assert(I != SLP->SubLoops.end() && "SubLoop not a child of parent?");
727 SLP->SubLoops.erase(I); // Remove from parent...
729 // Add the subloop to THIS loop...
730 SubLoop->ParentLoop = L;
731 L->SubLoops.push_back(SubLoop);
734 // Normal case, add the block to our loop...
735 L->Blocks.push_back(X);
737 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
739 // Add all of the predecessors of X to the end of the work stack...
740 TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X),
741 InvBlockTraits::child_end(X));
745 // If there are any loops nested within this loop, create them now!
746 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
747 E = L->Blocks.end(); I != E; ++I)
748 if (LoopBase<BlockT> *NewLoop = ConsiderForLoop(*I, DT)) {
749 L->SubLoops.push_back(NewLoop);
750 NewLoop->ParentLoop = L;
753 // Add the basic blocks that comprise this loop to the BBMap so that this
754 // loop can be found for them.
756 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
757 E = L->Blocks.end(); I != E; ++I) {
758 typename std::map<BlockT*, LoopBase<BlockT>*>::iterator BBMI =
759 BBMap.lower_bound(*I);
760 if (BBMI == BBMap.end() || BBMI->first != *I) // Not in map yet...
761 BBMap.insert(BBMI, std::make_pair(*I, L)); // Must be at this level
764 // Now that we have a list of all of the child loops of this loop, check to
765 // see if any of them should actually be nested inside of each other. We can
766 // accidentally pull loops our of their parents, so we must make sure to
767 // organize the loop nests correctly now.
769 std::map<BlockT*, LoopBase<BlockT>*> ContainingLoops;
770 for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
771 LoopBase<BlockT> *Child = L->SubLoops[i];
772 assert(Child->getParentLoop() == L && "Not proper child loop?");
774 if (LoopBase<BlockT> *ContainingLoop =
775 ContainingLoops[Child->getHeader()]) {
776 // If there is already a loop which contains this loop, move this loop
777 // into the containing loop.
778 MoveSiblingLoopInto(Child, ContainingLoop);
779 --i; // The loop got removed from the SubLoops list.
781 // This is currently considered to be a top-level loop. Check to see if
782 // any of the contained blocks are loop headers for subloops we have
783 // already processed.
784 for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
785 LoopBase<BlockT> *&BlockLoop = ContainingLoops[Child->Blocks[b]];
786 if (BlockLoop == 0) { // Child block not processed yet...
788 } else if (BlockLoop != Child) {
789 LoopBase<BlockT> *SubLoop = BlockLoop;
790 // Reparent all of the blocks which used to belong to BlockLoops
791 for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
792 ContainingLoops[SubLoop->Blocks[j]] = Child;
794 // There is already a loop which contains this block, that means
795 // that we should reparent the loop which the block is currently
796 // considered to belong to to be a child of this loop.
797 MoveSiblingLoopInto(SubLoop, Child);
798 --i; // We just shrunk the SubLoops list.
808 /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside of
809 /// the NewParent Loop, instead of being a sibling of it.
810 void MoveSiblingLoopInto(LoopBase<BlockT> *NewChild,
811 LoopBase<BlockT> *NewParent) {
812 LoopBase<BlockT> *OldParent = NewChild->getParentLoop();
813 assert(OldParent && OldParent == NewParent->getParentLoop() &&
814 NewChild != NewParent && "Not sibling loops!");
816 // Remove NewChild from being a child of OldParent
817 typename std::vector<LoopBase<BlockT>*>::iterator I =
818 std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(), NewChild);
819 assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
820 OldParent->SubLoops.erase(I); // Remove from parent's subloops list
821 NewChild->ParentLoop = 0;
823 InsertLoopInto(NewChild, NewParent);
826 /// InsertLoopInto - This inserts loop L into the specified parent loop. If the
827 /// parent loop contains a loop which should contain L, the loop gets inserted
829 void InsertLoopInto(LoopBase<BlockT> *L, LoopBase<BlockT> *Parent) {
830 BlockT *LHeader = L->getHeader();
831 assert(Parent->contains(LHeader) && "This loop should not be inserted here!");
833 // Check to see if it belongs in a child loop...
834 for (unsigned i = 0, e = Parent->SubLoops.size(); i != e; ++i)
835 if (Parent->SubLoops[i]->contains(LHeader)) {
836 InsertLoopInto(L, Parent->SubLoops[i]);
840 // If not, insert it here!
841 Parent->SubLoops.push_back(L);
842 L->ParentLoop = Parent;
847 void print(std::ostream &OS, const Module* ) const {
848 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
849 TopLevelLoops[i]->print(OS);
851 for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(),
852 E = BBMap.end(); I != E; ++I)
853 OS << "BB '" << I->first->getName() << "' level = "
854 << I->second->getLoopDepth() << "\n";
859 class LoopInfo : public FunctionPass {
860 LoopInfoBase<BasicBlock>* LI;
861 friend class LoopBase<BasicBlock>;
864 static char ID; // Pass identification, replacement for typeid
866 LoopInfo() : FunctionPass(intptr_t(&ID)) {
867 LI = new LoopInfoBase<BasicBlock>();
870 ~LoopInfo() { delete LI; }
872 LoopInfoBase<BasicBlock>& getBase() { return *LI; }
874 /// iterator/begin/end - The interface to the top-level loops in the current
877 typedef std::vector<Loop*>::const_iterator iterator;
878 inline iterator begin() const { return LI->begin(); }
879 inline iterator end() const { return LI->end(); }
881 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
882 /// block is in no loop (for example the entry node), null is returned.
884 inline Loop *getLoopFor(const BasicBlock *BB) const {
885 return LI->getLoopFor(BB);
888 /// operator[] - same as getLoopFor...
890 inline const Loop *operator[](const BasicBlock *BB) const {
891 return LI->getLoopFor(BB);
894 /// getLoopDepth - Return the loop nesting level of the specified block...
896 inline unsigned getLoopDepth(const BasicBlock *BB) const {
897 return LI->getLoopDepth(BB);
900 // isLoopHeader - True if the block is a loop header node
901 inline bool isLoopHeader(BasicBlock *BB) const {
902 return LI->isLoopHeader(BB);
905 /// runOnFunction - Calculate the natural loop information.
907 virtual bool runOnFunction(Function &F);
909 virtual void releaseMemory() { LI->releaseMemory(); }
911 virtual void print(std::ostream &O, const Module* M = 0) const {
912 if (O) LI->print(O, M);
915 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
917 /// removeLoop - This removes the specified top-level loop from this loop info
918 /// object. The loop is not deleted, as it will presumably be inserted into
920 inline Loop *removeLoop(iterator I) { return LI->removeLoop(I); }
922 /// changeLoopFor - Change the top-level loop that contains BB to the
923 /// specified loop. This should be used by transformations that restructure
924 /// the loop hierarchy tree.
925 inline void changeLoopFor(BasicBlock *BB, Loop *L) {
926 LI->changeLoopFor(BB, L);
929 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
930 /// list with the indicated loop.
931 inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
932 LI->changeTopLevelLoop(OldLoop, NewLoop);
935 /// addTopLevelLoop - This adds the specified loop to the collection of
937 inline void addTopLevelLoop(Loop *New) {
938 LI->addTopLevelLoop(New);
941 /// removeBlock - This method completely removes BB from all data structures,
942 /// including all of the Loop objects it is nested in and our mapping from
943 /// BasicBlocks to loops.
944 void removeBlock(BasicBlock *BB) {
950 // Allow clients to walk the list of nested loops...
951 template <> struct GraphTraits<const Loop*> {
952 typedef const Loop NodeType;
953 typedef std::vector<Loop*>::const_iterator ChildIteratorType;
955 static NodeType *getEntryNode(const Loop *L) { return L; }
956 static inline ChildIteratorType child_begin(NodeType *N) {
959 static inline ChildIteratorType child_end(NodeType *N) {
964 template <> struct GraphTraits<Loop*> {
965 typedef Loop NodeType;
966 typedef std::vector<Loop*>::const_iterator ChildIteratorType;
968 static NodeType *getEntryNode(Loop *L) { return L; }
969 static inline ChildIteratorType child_begin(NodeType *N) {
972 static inline ChildIteratorType child_end(NodeType *N) {
977 template<class BlockT>
978 void LoopBase<BlockT>::addBasicBlockToLoop(BlockT *NewBB,
979 LoopInfoBase<BlockT> &LIB) {
980 assert((Blocks.empty() || LIB[getHeader()] == this) &&
981 "Incorrect LI specified for this loop!");
982 assert(NewBB && "Cannot add a null basic block to the loop!");
983 assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
985 // Add the loop mapping to the LoopInfo object...
986 LIB.BBMap[NewBB] = this;
988 // Add the basic block to this loop and all parent loops...
989 LoopBase<BlockT> *L = this;
991 L->Blocks.push_back(NewBB);
992 L = L->getParentLoop();
996 } // End llvm namespace
998 // Make sure that any clients of this file link in LoopInfo.cpp
999 FORCE_DEFINING_FILE_TO_BE_LINKED(LoopInfo)