1 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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. A natural loop
12 // has exactly one entry-point, which is called the header. Note that natural
13 // loops may actually be several loops that share the same header node.
15 // This analysis calculates the nesting structure of loops in a function. For
16 // each natural loop identified, this analysis identifies natural loops
17 // contained entirely within the loop and the basic blocks the make up the loop.
19 // It can calculate on the fly various bits of information, for example:
21 // * whether there is a preheader for the loop
22 // * the number of back edges to the header
23 // * whether or not a particular block branches out of the loop
24 // * the successor blocks of the loop
29 //===----------------------------------------------------------------------===//
31 #ifndef LLVM_ANALYSIS_LOOP_INFO_H
32 #define LLVM_ANALYSIS_LOOP_INFO_H
34 #include "llvm/Pass.h"
35 #include "llvm/ADT/DepthFirstIterator.h"
36 #include "llvm/ADT/GraphTraits.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/Analysis/Dominators.h"
39 #include "llvm/Support/CFG.h"
40 #include "llvm/Support/raw_ostream.h"
46 static void RemoveFromVector(std::vector<T*> &V, T *N) {
47 typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
48 assert(I != V.end() && "N is not in this list!");
55 template<class N, class M> class LoopInfoBase;
56 template<class N, class M> class LoopBase;
58 //===----------------------------------------------------------------------===//
59 /// LoopBase class - Instances of this class are used to represent loops that
60 /// are detected in the flow graph
62 template<class BlockT, class LoopT>
65 // SubLoops - Loops contained entirely within this one.
66 std::vector<LoopT *> SubLoops;
68 // Blocks - The list of blocks in this loop. First entry is the header node.
69 std::vector<BlockT*> Blocks;
72 LoopBase(const LoopBase<BlockT, LoopT> &);
74 const LoopBase<BlockT, LoopT>&operator=(const LoopBase<BlockT, LoopT> &);
76 /// Loop ctor - This creates an empty loop.
77 LoopBase() : ParentLoop(0) {}
79 for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
83 /// getLoopDepth - Return the nesting level of this loop. An outer-most
84 /// loop has depth 1, for consistency with loop depth values used for basic
85 /// blocks, where depth 0 is used for blocks not inside any loops.
86 unsigned getLoopDepth() const {
88 for (const LoopT *CurLoop = ParentLoop; CurLoop;
89 CurLoop = CurLoop->ParentLoop)
93 BlockT *getHeader() const { return Blocks.front(); }
94 LoopT *getParentLoop() const { return ParentLoop; }
96 /// contains - Return true if the specified basic block is in this loop
98 bool contains(const BlockT *BB) const {
99 return std::find(block_begin(), block_end(), BB) != block_end();
102 /// iterator/begin/end - Return the loops contained entirely within this loop.
104 const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
105 typedef typename std::vector<LoopT *>::const_iterator iterator;
106 iterator begin() const { return SubLoops.begin(); }
107 iterator end() const { return SubLoops.end(); }
108 bool empty() const { return SubLoops.empty(); }
110 /// getBlocks - Get a list of the basic blocks which make up this loop.
112 const std::vector<BlockT*> &getBlocks() const { return Blocks; }
113 typedef typename std::vector<BlockT*>::const_iterator block_iterator;
114 block_iterator block_begin() const { return Blocks.begin(); }
115 block_iterator block_end() const { return Blocks.end(); }
117 /// isLoopExit - True if terminator in the block can branch to another block
118 /// that is outside of the current loop.
120 bool isLoopExit(const BlockT *BB) const {
121 typedef GraphTraits<BlockT*> BlockTraits;
122 for (typename BlockTraits::ChildIteratorType SI =
123 BlockTraits::child_begin(const_cast<BlockT*>(BB)),
124 SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
131 /// getNumBackEdges - Calculate the number of back edges to the loop header
133 unsigned getNumBackEdges() const {
134 unsigned NumBackEdges = 0;
135 BlockT *H = getHeader();
137 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
138 for (typename InvBlockTraits::ChildIteratorType I =
139 InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
140 E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
147 //===--------------------------------------------------------------------===//
148 // APIs for simple analysis of the loop.
150 // Note that all of these methods can fail on general loops (ie, there may not
151 // be a preheader, etc). For best success, the loop simplification and
152 // induction variable canonicalization pass should be used to normalize loops
153 // for easy analysis. These methods assume canonical loops.
155 /// getExitingBlocks - Return all blocks inside the loop that have successors
156 /// outside of the loop. These are the blocks _inside of the current loop_
157 /// which branch out. The returned list is always unique.
159 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
160 // Sort the blocks vector so that we can use binary search to do quick
162 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
163 std::sort(LoopBBs.begin(), LoopBBs.end());
165 typedef GraphTraits<BlockT*> BlockTraits;
166 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
167 for (typename BlockTraits::ChildIteratorType I =
168 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
170 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
171 // Not in current loop? It must be an exit block.
172 ExitingBlocks.push_back(*BI);
177 /// getExitingBlock - If getExitingBlocks would return exactly one block,
178 /// return that block. Otherwise return null.
179 BlockT *getExitingBlock() const {
180 SmallVector<BlockT*, 8> ExitingBlocks;
181 getExitingBlocks(ExitingBlocks);
182 if (ExitingBlocks.size() == 1)
183 return ExitingBlocks[0];
187 /// getExitBlocks - Return all of the successor blocks of this loop. These
188 /// are the blocks _outside of the current loop_ which are branched to.
190 void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
191 // Sort the blocks vector so that we can use binary search to do quick
193 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
194 std::sort(LoopBBs.begin(), LoopBBs.end());
196 typedef GraphTraits<BlockT*> BlockTraits;
197 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
198 for (typename BlockTraits::ChildIteratorType I =
199 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
201 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
202 // Not in current loop? It must be an exit block.
203 ExitBlocks.push_back(*I);
206 /// getExitBlock - If getExitBlocks would return exactly one block,
207 /// return that block. Otherwise return null.
208 BlockT *getExitBlock() const {
209 SmallVector<BlockT*, 8> ExitBlocks;
210 getExitBlocks(ExitBlocks);
211 if (ExitBlocks.size() == 1)
212 return ExitBlocks[0];
216 /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
217 typedef std::pair<const BlockT*,const BlockT*> Edge;
218 void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const {
219 // Sort the blocks vector so that we can use binary search to do quick
221 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
222 std::sort(LoopBBs.begin(), LoopBBs.end());
224 typedef GraphTraits<BlockT*> BlockTraits;
225 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
226 for (typename BlockTraits::ChildIteratorType I =
227 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
229 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
230 // Not in current loop? It must be an exit block.
231 ExitEdges.push_back(std::make_pair(*BI, *I));
234 /// getLoopPreheader - If there is a preheader for this loop, return it. A
235 /// loop has a preheader if there is only one edge to the header of the loop
236 /// from outside of the loop. If this is the case, the block branching to the
237 /// header of the loop is the preheader node.
239 /// This method returns null if there is no preheader for the loop.
241 BlockT *getLoopPreheader() const {
242 // Keep track of nodes outside the loop branching to the header...
245 // Loop over the predecessors of the header node...
246 BlockT *Header = getHeader();
247 typedef GraphTraits<BlockT*> BlockTraits;
248 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
249 for (typename InvBlockTraits::ChildIteratorType PI =
250 InvBlockTraits::child_begin(Header),
251 PE = InvBlockTraits::child_end(Header); PI != PE; ++PI)
252 if (!contains(*PI)) { // If the block is not in the loop...
253 if (Out && Out != *PI)
254 return 0; // Multiple predecessors outside the loop
258 // Make sure there is only one exit out of the preheader.
259 assert(Out && "Header of loop has no predecessors from outside loop?");
260 typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
262 if (SI != BlockTraits::child_end(Out))
263 return 0; // Multiple exits from the block, must not be a preheader.
265 // If there is exactly one preheader, return it. If there was zero, then
266 // Out is still null.
270 /// getLoopLatch - If there is a single latch block for this loop, return it.
271 /// A latch block is a block that contains a branch back to the header.
272 /// A loop header in normal form has two edges into it: one from a preheader
273 /// and one from a latch block.
274 BlockT *getLoopLatch() const {
275 BlockT *Header = getHeader();
276 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
277 typename InvBlockTraits::ChildIteratorType PI =
278 InvBlockTraits::child_begin(Header);
279 typename InvBlockTraits::ChildIteratorType PE =
280 InvBlockTraits::child_end(Header);
281 if (PI == PE) return 0; // no preds?
287 if (PI == PE) return 0; // only one pred?
290 if (Latch) return 0; // multiple backedges
294 if (PI != PE) return 0; // more than two preds
299 //===--------------------------------------------------------------------===//
300 // APIs for updating loop information after changing the CFG
303 /// addBasicBlockToLoop - This method is used by other analyses to update loop
304 /// information. NewBB is set to be a new member of the current loop.
305 /// Because of this, it is added as a member of all parent loops, and is added
306 /// to the specified LoopInfo object as being in the current basic block. It
307 /// is not valid to replace the loop header with this method.
309 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
311 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
312 /// the OldChild entry in our children list with NewChild, and updates the
313 /// parent pointer of OldChild to be null and the NewChild to be this loop.
314 /// This updates the loop depth of the new child.
315 void replaceChildLoopWith(LoopT *OldChild,
317 assert(OldChild->ParentLoop == this && "This loop is already broken!");
318 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
319 typename std::vector<LoopT *>::iterator I =
320 std::find(SubLoops.begin(), SubLoops.end(), OldChild);
321 assert(I != SubLoops.end() && "OldChild not in loop!");
323 OldChild->ParentLoop = 0;
324 NewChild->ParentLoop = static_cast<LoopT *>(this);
327 /// addChildLoop - Add the specified loop to be a child of this loop. This
328 /// updates the loop depth of the new child.
330 void addChildLoop(LoopT *NewChild) {
331 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
332 NewChild->ParentLoop = static_cast<LoopT *>(this);
333 SubLoops.push_back(NewChild);
336 /// removeChildLoop - This removes the specified child from being a subloop of
337 /// this loop. The loop is not deleted, as it will presumably be inserted
338 /// into another loop.
339 LoopT *removeChildLoop(iterator I) {
340 assert(I != SubLoops.end() && "Cannot remove end iterator!");
342 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
343 SubLoops.erase(SubLoops.begin()+(I-begin()));
344 Child->ParentLoop = 0;
348 /// addBlockEntry - This adds a basic block directly to the basic block list.
349 /// This should only be used by transformations that create new loops. Other
350 /// transformations should use addBasicBlockToLoop.
351 void addBlockEntry(BlockT *BB) {
352 Blocks.push_back(BB);
355 /// moveToHeader - This method is used to move BB (which must be part of this
356 /// loop) to be the loop header of the loop (the block that dominates all
358 void moveToHeader(BlockT *BB) {
359 if (Blocks[0] == BB) return;
360 for (unsigned i = 0; ; ++i) {
361 assert(i != Blocks.size() && "Loop does not contain BB!");
362 if (Blocks[i] == BB) {
363 Blocks[i] = Blocks[0];
370 /// removeBlockFromLoop - This removes the specified basic block from the
371 /// current loop, updating the Blocks as appropriate. This does not update
372 /// the mapping in the LoopInfo class.
373 void removeBlockFromLoop(BlockT *BB) {
374 RemoveFromVector(Blocks, BB);
377 /// verifyLoop - Verify loop structure
378 void verifyLoop() const {
380 assert(!Blocks.empty() && "Loop header is missing");
381 assert(getHeader() && "Loop header is missing");
383 // Sort the blocks vector so that we can use binary search to do quick
385 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
386 std::sort(LoopBBs.begin(), LoopBBs.end());
388 // Check the individual blocks.
389 for (block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
391 bool HasInsideLoopSuccs = false;
392 bool HasInsideLoopPreds = false;
393 SmallVector<BlockT *, 2> OutsideLoopPreds;
395 typedef GraphTraits<BlockT*> BlockTraits;
396 for (typename BlockTraits::ChildIteratorType SI =
397 BlockTraits::child_begin(BB), SE = BlockTraits::child_end(BB);
399 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *SI)) {
400 HasInsideLoopSuccs = true;
403 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
404 for (typename InvBlockTraits::ChildIteratorType PI =
405 InvBlockTraits::child_begin(BB), PE = InvBlockTraits::child_end(BB);
407 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *PI))
408 HasInsideLoopPreds = true;
410 OutsideLoopPreds.push_back(*PI);
413 if (BB == getHeader()) {
414 assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
415 } else if (!OutsideLoopPreds.empty()) {
416 // A non-header loop shouldn't be reachable from outside the loop,
417 // though it is permitted if the predecessor is not itself actually
419 BlockT *EntryBB = BB->getParent()->begin();
420 for (df_iterator<BlockT *> NI = df_begin(EntryBB),
421 NE = df_end(EntryBB); NI != NE; ++NI)
422 for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
423 assert(*NI != OutsideLoopPreds[i] &&
424 "Loop has multiple entry points!");
426 assert(HasInsideLoopPreds && "Loop block has no in-loop predecessors!");
427 assert(HasInsideLoopSuccs && "Loop block has no in-loop successors!");
428 assert(BB != getHeader()->getParent()->begin() &&
429 "Loop contains function entry block!");
432 // Check the subloops.
433 for (iterator I = begin(), E = end(); I != E; ++I)
434 // Each block in each subloop should be contained within this loop.
435 for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
437 assert(std::binary_search(LoopBBs.begin(), LoopBBs.end(), *BI) &&
438 "Loop does not contain all the blocks of a subloop!");
441 // Check the parent loop pointer.
443 assert(std::find(ParentLoop->begin(), ParentLoop->end(), this) !=
445 "Loop is not a subloop of its parent!");
450 /// verifyLoop - Verify loop structure of this loop and all nested loops.
451 void verifyLoopNest() const {
454 // Verify the subloops.
455 for (iterator I = begin(), E = end(); I != E; ++I)
456 (*I)->verifyLoopNest();
459 void print(raw_ostream &OS, unsigned Depth = 0) const {
460 OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
463 for (unsigned i = 0; i < getBlocks().size(); ++i) {
465 BlockT *BB = getBlocks()[i];
466 WriteAsOperand(OS, BB, false);
467 if (BB == getHeader()) OS << "<header>";
468 if (BB == getLoopLatch()) OS << "<latch>";
469 if (isLoopExit(BB)) OS << "<exit>";
473 for (iterator I = begin(), E = end(); I != E; ++I)
474 (*I)->print(OS, Depth+2);
482 friend class LoopInfoBase<BlockT, LoopT>;
483 explicit LoopBase(BlockT *BB) : ParentLoop(0) {
484 Blocks.push_back(BB);
488 class Loop : public LoopBase<BasicBlock, Loop> {
492 /// isLoopInvariant - Return true if the specified value is loop invariant
494 bool isLoopInvariant(Value *V) const;
496 /// isLoopInvariant - Return true if the specified instruction is
499 bool isLoopInvariant(Instruction *I) const;
501 /// makeLoopInvariant - If the given value is an instruction inside of the
502 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
503 /// Return true if the value after any hoisting is loop invariant. This
504 /// function can be used as a slightly more aggressive replacement for
507 /// If InsertPt is specified, it is the point to hoist instructions to.
508 /// If null, the terminator of the loop preheader is used.
510 bool makeLoopInvariant(Value *V, bool &Changed,
511 Instruction *InsertPt = 0) const;
513 /// makeLoopInvariant - If the given instruction is inside of the
514 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
515 /// Return true if the instruction after any hoisting is loop invariant. This
516 /// function can be used as a slightly more aggressive replacement for
519 /// If InsertPt is specified, it is the point to hoist instructions to.
520 /// If null, the terminator of the loop preheader is used.
522 bool makeLoopInvariant(Instruction *I, bool &Changed,
523 Instruction *InsertPt = 0) const;
525 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
526 /// induction variable: an integer recurrence that starts at 0 and increments
527 /// by one each time through the loop. If so, return the phi node that
528 /// corresponds to it.
530 /// The IndVarSimplify pass transforms loops to have a canonical induction
533 PHINode *getCanonicalInductionVariable() const;
535 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
536 /// the canonical induction variable value for the "next" iteration of the
537 /// loop. This always succeeds if getCanonicalInductionVariable succeeds.
539 Instruction *getCanonicalInductionVariableIncrement() const;
541 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
542 /// times the loop will be executed. Note that this means that the backedge
543 /// of the loop executes N-1 times. If the trip-count cannot be determined,
544 /// this returns null.
546 /// The IndVarSimplify pass transforms loops to have a form that this
547 /// function easily understands.
549 Value *getTripCount() const;
551 /// getSmallConstantTripCount - Returns the trip count of this loop as a
552 /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
553 /// of not constant. Will also return 0 if the trip count is very large
555 unsigned getSmallConstantTripCount() const;
557 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
558 /// trip count of this loop as a normal unsigned value, if possible. This
559 /// means that the actual trip count is always a multiple of the returned
560 /// value (don't forget the trip count could very well be zero as well!).
562 /// Returns 1 if the trip count is unknown or not guaranteed to be the
563 /// multiple of a constant (which is also the case if the trip count is simply
564 /// constant, use getSmallConstantTripCount for that case), Will also return 1
565 /// if the trip count is very large (>= 2^32).
566 unsigned getSmallConstantTripMultiple() const;
568 /// isLCSSAForm - Return true if the Loop is in LCSSA form
569 bool isLCSSAForm() const;
571 /// isLoopSimplifyForm - Return true if the Loop is in the form that
572 /// the LoopSimplify form transforms loops to, which is sometimes called
574 bool isLoopSimplifyForm() const;
576 /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
577 /// These are the blocks _outside of the current loop_ which are branched to.
578 /// This assumes that loop is in canonical form.
580 void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
582 /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
583 /// block, return that block. Otherwise return null.
584 BasicBlock *getUniqueExitBlock() const;
587 friend class LoopInfoBase<BasicBlock, Loop>;
588 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
591 //===----------------------------------------------------------------------===//
592 /// LoopInfo - This class builds and contains all of the top level loop
593 /// structures in the specified function.
596 template<class BlockT, class LoopT>
598 // BBMap - Mapping of basic blocks to the inner most loop they occur in
599 std::map<BlockT *, LoopT *> BBMap;
600 std::vector<LoopT *> TopLevelLoops;
601 friend class LoopBase<BlockT, LoopT>;
603 void operator=(const LoopInfoBase &); // do not implement
604 LoopInfoBase(const LoopInfo &); // do not implement
607 ~LoopInfoBase() { releaseMemory(); }
609 void releaseMemory() {
610 for (typename std::vector<LoopT *>::iterator I =
611 TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
612 delete *I; // Delete all of the loops...
614 BBMap.clear(); // Reset internal state of analysis
615 TopLevelLoops.clear();
618 /// iterator/begin/end - The interface to the top-level loops in the current
621 typedef typename std::vector<LoopT *>::const_iterator iterator;
622 iterator begin() const { return TopLevelLoops.begin(); }
623 iterator end() const { return TopLevelLoops.end(); }
624 bool empty() const { return TopLevelLoops.empty(); }
626 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
627 /// block is in no loop (for example the entry node), null is returned.
629 LoopT *getLoopFor(const BlockT *BB) const {
630 typename std::map<BlockT *, LoopT *>::const_iterator I=
631 BBMap.find(const_cast<BlockT*>(BB));
632 return I != BBMap.end() ? I->second : 0;
635 /// operator[] - same as getLoopFor...
637 const LoopT *operator[](const BlockT *BB) const {
638 return getLoopFor(BB);
641 /// getLoopDepth - Return the loop nesting level of the specified block. A
642 /// depth of 0 means the block is not inside any loop.
644 unsigned getLoopDepth(const BlockT *BB) const {
645 const LoopT *L = getLoopFor(BB);
646 return L ? L->getLoopDepth() : 0;
649 // isLoopHeader - True if the block is a loop header node
650 bool isLoopHeader(BlockT *BB) const {
651 const LoopT *L = getLoopFor(BB);
652 return L && L->getHeader() == BB;
655 /// removeLoop - This removes the specified top-level loop from this loop info
656 /// object. The loop is not deleted, as it will presumably be inserted into
658 LoopT *removeLoop(iterator I) {
659 assert(I != end() && "Cannot remove end iterator!");
661 assert(L->getParentLoop() == 0 && "Not a top-level loop!");
662 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
666 /// changeLoopFor - Change the top-level loop that contains BB to the
667 /// specified loop. This should be used by transformations that restructure
668 /// the loop hierarchy tree.
669 void changeLoopFor(BlockT *BB, LoopT *L) {
670 LoopT *&OldLoop = BBMap[BB];
671 assert(OldLoop && "Block not in a loop yet!");
675 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
676 /// list with the indicated loop.
677 void changeTopLevelLoop(LoopT *OldLoop,
679 typename std::vector<LoopT *>::iterator I =
680 std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
681 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
683 assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
684 "Loops already embedded into a subloop!");
687 /// addTopLevelLoop - This adds the specified loop to the collection of
689 void addTopLevelLoop(LoopT *New) {
690 assert(New->getParentLoop() == 0 && "Loop already in subloop!");
691 TopLevelLoops.push_back(New);
694 /// removeBlock - This method completely removes BB from all data structures,
695 /// including all of the Loop objects it is nested in and our mapping from
696 /// BasicBlocks to loops.
697 void removeBlock(BlockT *BB) {
698 typename std::map<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
699 if (I != BBMap.end()) {
700 for (LoopT *L = I->second; L; L = L->getParentLoop())
701 L->removeBlockFromLoop(BB);
709 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
710 const LoopT *ParentLoop) {
711 if (SubLoop == 0) return true;
712 if (SubLoop == ParentLoop) return false;
713 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
716 void Calculate(DominatorTreeBase<BlockT> &DT) {
717 BlockT *RootNode = DT.getRootNode()->getBlock();
719 for (df_iterator<BlockT*> NI = df_begin(RootNode),
720 NE = df_end(RootNode); NI != NE; ++NI)
721 if (LoopT *L = ConsiderForLoop(*NI, DT))
722 TopLevelLoops.push_back(L);
725 LoopT *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
726 if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node?
728 std::vector<BlockT *> TodoStack;
730 // Scan the predecessors of BB, checking to see if BB dominates any of
731 // them. This identifies backedges which target this node...
732 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
733 for (typename InvBlockTraits::ChildIteratorType I =
734 InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
736 if (DT.dominates(BB, *I)) // If BB dominates its predecessor...
737 TodoStack.push_back(*I);
739 if (TodoStack.empty()) return 0; // No backedges to this block...
741 // Create a new loop to represent this basic block...
742 LoopT *L = new LoopT(BB);
745 BlockT *EntryBlock = BB->getParent()->begin();
747 while (!TodoStack.empty()) { // Process all the nodes in the loop
748 BlockT *X = TodoStack.back();
749 TodoStack.pop_back();
751 if (!L->contains(X) && // As of yet unprocessed??
752 DT.dominates(EntryBlock, X)) { // X is reachable from entry block?
753 // Check to see if this block already belongs to a loop. If this occurs
754 // then we have a case where a loop that is supposed to be a child of
755 // the current loop was processed before the current loop. When this
756 // occurs, this child loop gets added to a part of the current loop,
757 // making it a sibling to the current loop. We have to reparent this
760 const_cast<LoopT *>(getLoopFor(X)))
761 if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)){
762 // Remove the subloop from its current parent...
763 assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
764 LoopT *SLP = SubLoop->ParentLoop; // SubLoopParent
765 typename std::vector<LoopT *>::iterator I =
766 std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
767 assert(I != SLP->SubLoops.end() &&"SubLoop not a child of parent?");
768 SLP->SubLoops.erase(I); // Remove from parent...
770 // Add the subloop to THIS loop...
771 SubLoop->ParentLoop = L;
772 L->SubLoops.push_back(SubLoop);
775 // Normal case, add the block to our loop...
776 L->Blocks.push_back(X);
778 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
780 // Add all of the predecessors of X to the end of the work stack...
781 TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X),
782 InvBlockTraits::child_end(X));
786 // If there are any loops nested within this loop, create them now!
787 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
788 E = L->Blocks.end(); I != E; ++I)
789 if (LoopT *NewLoop = ConsiderForLoop(*I, DT)) {
790 L->SubLoops.push_back(NewLoop);
791 NewLoop->ParentLoop = L;
794 // Add the basic blocks that comprise this loop to the BBMap so that this
795 // loop can be found for them.
797 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
798 E = L->Blocks.end(); I != E; ++I)
799 BBMap.insert(std::make_pair(*I, L));
801 // Now that we have a list of all of the child loops of this loop, check to
802 // see if any of them should actually be nested inside of each other. We
803 // can accidentally pull loops our of their parents, so we must make sure to
804 // organize the loop nests correctly now.
806 std::map<BlockT *, LoopT *> ContainingLoops;
807 for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
808 LoopT *Child = L->SubLoops[i];
809 assert(Child->getParentLoop() == L && "Not proper child loop?");
811 if (LoopT *ContainingLoop = ContainingLoops[Child->getHeader()]) {
812 // If there is already a loop which contains this loop, move this loop
813 // into the containing loop.
814 MoveSiblingLoopInto(Child, ContainingLoop);
815 --i; // The loop got removed from the SubLoops list.
817 // This is currently considered to be a top-level loop. Check to see
818 // if any of the contained blocks are loop headers for subloops we
819 // have already processed.
820 for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
821 LoopT *&BlockLoop = ContainingLoops[Child->Blocks[b]];
822 if (BlockLoop == 0) { // Child block not processed yet...
824 } else if (BlockLoop != Child) {
825 LoopT *SubLoop = BlockLoop;
826 // Reparent all of the blocks which used to belong to BlockLoops
827 for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
828 ContainingLoops[SubLoop->Blocks[j]] = Child;
830 // There is already a loop which contains this block, that means
831 // that we should reparent the loop which the block is currently
832 // considered to belong to to be a child of this loop.
833 MoveSiblingLoopInto(SubLoop, Child);
834 --i; // We just shrunk the SubLoops list.
844 /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside
845 /// of the NewParent Loop, instead of being a sibling of it.
846 void MoveSiblingLoopInto(LoopT *NewChild,
848 LoopT *OldParent = NewChild->getParentLoop();
849 assert(OldParent && OldParent == NewParent->getParentLoop() &&
850 NewChild != NewParent && "Not sibling loops!");
852 // Remove NewChild from being a child of OldParent
853 typename std::vector<LoopT *>::iterator I =
854 std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(),
856 assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
857 OldParent->SubLoops.erase(I); // Remove from parent's subloops list
858 NewChild->ParentLoop = 0;
860 InsertLoopInto(NewChild, NewParent);
863 /// InsertLoopInto - This inserts loop L into the specified parent loop. If
864 /// the parent loop contains a loop which should contain L, the loop gets
865 /// inserted into L instead.
866 void InsertLoopInto(LoopT *L, LoopT *Parent) {
867 BlockT *LHeader = L->getHeader();
868 assert(Parent->contains(LHeader) &&
869 "This loop should not be inserted here!");
871 // Check to see if it belongs in a child loop...
872 for (unsigned i = 0, e = static_cast<unsigned>(Parent->SubLoops.size());
874 if (Parent->SubLoops[i]->contains(LHeader)) {
875 InsertLoopInto(L, Parent->SubLoops[i]);
879 // If not, insert it here!
880 Parent->SubLoops.push_back(L);
881 L->ParentLoop = Parent;
886 void print(raw_ostream &OS) const {
887 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
888 TopLevelLoops[i]->print(OS);
890 for (std::map<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
891 E = BBMap.end(); I != E; ++I)
892 OS << "BB '" << I->first->getName() << "' level = "
893 << I->second->getLoopDepth() << "\n";
898 class LoopInfo : public FunctionPass {
899 LoopInfoBase<BasicBlock, Loop> LI;
900 friend class LoopBase<BasicBlock, Loop>;
902 void operator=(const LoopInfo &); // do not implement
903 LoopInfo(const LoopInfo &); // do not implement
905 static char ID; // Pass identification, replacement for typeid
907 LoopInfo() : FunctionPass(&ID) {}
909 LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
911 /// iterator/begin/end - The interface to the top-level loops in the current
914 typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
915 inline iterator begin() const { return LI.begin(); }
916 inline iterator end() const { return LI.end(); }
917 bool empty() const { return LI.empty(); }
919 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
920 /// block is in no loop (for example the entry node), null is returned.
922 inline Loop *getLoopFor(const BasicBlock *BB) const {
923 return LI.getLoopFor(BB);
926 /// operator[] - same as getLoopFor...
928 inline const Loop *operator[](const BasicBlock *BB) const {
929 return LI.getLoopFor(BB);
932 /// getLoopDepth - Return the loop nesting level of the specified block. A
933 /// depth of 0 means the block is not inside any loop.
935 inline unsigned getLoopDepth(const BasicBlock *BB) const {
936 return LI.getLoopDepth(BB);
939 // isLoopHeader - True if the block is a loop header node
940 inline bool isLoopHeader(BasicBlock *BB) const {
941 return LI.isLoopHeader(BB);
944 /// runOnFunction - Calculate the natural loop information.
946 virtual bool runOnFunction(Function &F);
948 virtual void verifyAnalysis() const;
950 virtual void releaseMemory() { LI.releaseMemory(); }
952 virtual void print(raw_ostream &O, const Module* M = 0) const;
954 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
956 /// removeLoop - This removes the specified top-level loop from this loop info
957 /// object. The loop is not deleted, as it will presumably be inserted into
959 inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
961 /// changeLoopFor - Change the top-level loop that contains BB to the
962 /// specified loop. This should be used by transformations that restructure
963 /// the loop hierarchy tree.
964 inline void changeLoopFor(BasicBlock *BB, Loop *L) {
965 LI.changeLoopFor(BB, L);
968 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
969 /// list with the indicated loop.
970 inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
971 LI.changeTopLevelLoop(OldLoop, NewLoop);
974 /// addTopLevelLoop - This adds the specified loop to the collection of
976 inline void addTopLevelLoop(Loop *New) {
977 LI.addTopLevelLoop(New);
980 /// removeBlock - This method completely removes BB from all data structures,
981 /// including all of the Loop objects it is nested in and our mapping from
982 /// BasicBlocks to loops.
983 void removeBlock(BasicBlock *BB) {
987 static bool isNotAlreadyContainedIn(const Loop *SubLoop,
988 const Loop *ParentLoop) {
990 LoopInfoBase<BasicBlock, Loop>::isNotAlreadyContainedIn(SubLoop,
996 // Allow clients to walk the list of nested loops...
997 template <> struct GraphTraits<const Loop*> {
998 typedef const Loop NodeType;
999 typedef LoopInfo::iterator ChildIteratorType;
1001 static NodeType *getEntryNode(const Loop *L) { return L; }
1002 static inline ChildIteratorType child_begin(NodeType *N) {
1005 static inline ChildIteratorType child_end(NodeType *N) {
1010 template <> struct GraphTraits<Loop*> {
1011 typedef Loop NodeType;
1012 typedef LoopInfo::iterator ChildIteratorType;
1014 static NodeType *getEntryNode(Loop *L) { return L; }
1015 static inline ChildIteratorType child_begin(NodeType *N) {
1018 static inline ChildIteratorType child_end(NodeType *N) {
1023 template<class BlockT, class LoopT>
1025 LoopBase<BlockT, LoopT>::addBasicBlockToLoop(BlockT *NewBB,
1026 LoopInfoBase<BlockT, LoopT> &LIB) {
1027 assert((Blocks.empty() || LIB[getHeader()] == this) &&
1028 "Incorrect LI specified for this loop!");
1029 assert(NewBB && "Cannot add a null basic block to the loop!");
1030 assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
1032 LoopT *L = static_cast<LoopT *>(this);
1034 // Add the loop mapping to the LoopInfo object...
1035 LIB.BBMap[NewBB] = L;
1037 // Add the basic block to this loop and all parent loops...
1039 L->Blocks.push_back(NewBB);
1040 L = L->getParentLoop();
1044 } // End llvm namespace