1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
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. 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.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Analysis/LoopInfoImpl.h"
22 #include "llvm/Analysis/LoopIterator.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/Assembly/Writer.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
33 // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
34 template class llvm::LoopBase<BasicBlock, Loop>;
35 template class llvm::LoopInfoBase<BasicBlock, Loop>;
37 // Always verify loopinfo if expensive checking is enabled.
39 static bool VerifyLoopInfo = true;
41 static bool VerifyLoopInfo = false;
43 static cl::opt<bool,true>
44 VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
45 cl::desc("Verify loop info (time consuming)"));
47 char LoopInfo::ID = 0;
48 INITIALIZE_PASS_BEGIN(LoopInfo, "loops", "Natural Loop Information", true, true)
49 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
50 INITIALIZE_PASS_END(LoopInfo, "loops", "Natural Loop Information", true, true)
52 //===----------------------------------------------------------------------===//
53 // Loop implementation
56 /// isLoopInvariant - Return true if the specified value is loop invariant
58 bool Loop::isLoopInvariant(Value *V) const {
59 if (Instruction *I = dyn_cast<Instruction>(V))
61 return true; // All non-instructions are loop invariant
64 /// hasLoopInvariantOperands - Return true if all the operands of the
65 /// specified instruction are loop invariant.
66 bool Loop::hasLoopInvariantOperands(Instruction *I) const {
67 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
68 if (!isLoopInvariant(I->getOperand(i)))
74 /// makeLoopInvariant - If the given value is an instruciton inside of the
75 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
76 /// Return true if the value after any hoisting is loop invariant. This
77 /// function can be used as a slightly more aggressive replacement for
80 /// If InsertPt is specified, it is the point to hoist instructions to.
81 /// If null, the terminator of the loop preheader is used.
83 bool Loop::makeLoopInvariant(Value *V, bool &Changed,
84 Instruction *InsertPt) const {
85 if (Instruction *I = dyn_cast<Instruction>(V))
86 return makeLoopInvariant(I, Changed, InsertPt);
87 return true; // All non-instructions are loop-invariant.
90 /// makeLoopInvariant - If the given instruction is inside of the
91 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
92 /// Return true if the instruction after any hoisting is loop invariant. This
93 /// function can be used as a slightly more aggressive replacement for
96 /// If InsertPt is specified, it is the point to hoist instructions to.
97 /// If null, the terminator of the loop preheader is used.
99 bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
100 Instruction *InsertPt) const {
101 // Test if the value is already loop-invariant.
102 if (isLoopInvariant(I))
104 if (!isSafeToSpeculativelyExecute(I))
106 if (I->mayReadFromMemory())
108 // The landingpad instruction is immobile.
109 if (isa<LandingPadInst>(I))
111 // Determine the insertion point, unless one was given.
113 BasicBlock *Preheader = getLoopPreheader();
114 // Without a preheader, hoisting is not feasible.
117 InsertPt = Preheader->getTerminator();
119 // Don't hoist instructions with loop-variant operands.
120 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
121 if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
125 I->moveBefore(InsertPt);
130 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
131 /// induction variable: an integer recurrence that starts at 0 and increments
132 /// by one each time through the loop. If so, return the phi node that
133 /// corresponds to it.
135 /// The IndVarSimplify pass transforms loops to have a canonical induction
138 PHINode *Loop::getCanonicalInductionVariable() const {
139 BasicBlock *H = getHeader();
141 BasicBlock *Incoming = 0, *Backedge = 0;
142 pred_iterator PI = pred_begin(H);
143 assert(PI != pred_end(H) &&
144 "Loop must have at least one backedge!");
146 if (PI == pred_end(H)) return 0; // dead loop
148 if (PI != pred_end(H)) return 0; // multiple backedges?
150 if (contains(Incoming)) {
151 if (contains(Backedge))
153 std::swap(Incoming, Backedge);
154 } else if (!contains(Backedge))
157 // Loop over all of the PHI nodes, looking for a canonical indvar.
158 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
159 PHINode *PN = cast<PHINode>(I);
160 if (ConstantInt *CI =
161 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
162 if (CI->isNullValue())
163 if (Instruction *Inc =
164 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
165 if (Inc->getOpcode() == Instruction::Add &&
166 Inc->getOperand(0) == PN)
167 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
168 if (CI->equalsInt(1))
174 /// isLCSSAForm - Return true if the Loop is in LCSSA form
175 bool Loop::isLCSSAForm(DominatorTree &DT) const {
176 // Sort the blocks vector so that we can use binary search to do quick
178 SmallPtrSet<BasicBlock*, 16> LoopBBs(block_begin(), block_end());
180 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
181 BasicBlock *BB = *BI;
182 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I)
183 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
186 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
187 if (PHINode *P = dyn_cast<PHINode>(U))
188 UserBB = P->getIncomingBlock(UI);
190 // Check the current block, as a fast-path, before checking whether
191 // the use is anywhere in the loop. Most values are used in the same
192 // block they are defined in. Also, blocks not reachable from the
193 // entry are special; uses in them don't need to go through PHIs.
195 !LoopBBs.count(UserBB) &&
196 DT.isReachableFromEntry(UserBB))
204 /// isLoopSimplifyForm - Return true if the Loop is in the form that
205 /// the LoopSimplify form transforms loops to, which is sometimes called
207 bool Loop::isLoopSimplifyForm() const {
208 // Normal-form loops have a preheader, a single backedge, and all of their
209 // exits have all their predecessors inside the loop.
210 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
213 /// isSafeToClone - Return true if the loop body is safe to clone in practice.
214 /// Routines that reform the loop CFG and split edges often fail on indirectbr.
215 bool Loop::isSafeToClone() const {
216 // Return false if any loop blocks contain indirectbrs, or there are any calls
217 // to noduplicate functions.
218 for (Loop::block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
219 if (isa<IndirectBrInst>((*I)->getTerminator())) {
221 } else if (const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator())) {
222 if (II->hasFnAttr(Attribute::NoDuplicate))
226 for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end(); BI != BE; ++BI) {
227 if (const CallInst *CI = dyn_cast<CallInst>(BI)) {
228 if (CI->hasFnAttr(Attribute::NoDuplicate))
236 /// hasDedicatedExits - Return true if no exit block for the loop
237 /// has a predecessor that is outside the loop.
238 bool Loop::hasDedicatedExits() const {
239 // Sort the blocks vector so that we can use binary search to do quick
241 SmallPtrSet<BasicBlock *, 16> LoopBBs(block_begin(), block_end());
242 // Each predecessor of each exit block of a normal loop is contained
244 SmallVector<BasicBlock *, 4> ExitBlocks;
245 getExitBlocks(ExitBlocks);
246 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
247 for (pred_iterator PI = pred_begin(ExitBlocks[i]),
248 PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
249 if (!LoopBBs.count(*PI))
251 // All the requirements are met.
255 /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
256 /// These are the blocks _outside of the current loop_ which are branched to.
257 /// This assumes that loop exits are in canonical form.
260 Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
261 assert(hasDedicatedExits() &&
262 "getUniqueExitBlocks assumes the loop has canonical form exits!");
264 // Sort the blocks vector so that we can use binary search to do quick
266 SmallVector<BasicBlock *, 128> LoopBBs(block_begin(), block_end());
267 std::sort(LoopBBs.begin(), LoopBBs.end());
269 SmallVector<BasicBlock *, 32> switchExitBlocks;
271 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
273 BasicBlock *current = *BI;
274 switchExitBlocks.clear();
276 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
277 // If block is inside the loop then it is not a exit block.
278 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
281 pred_iterator PI = pred_begin(*I);
282 BasicBlock *firstPred = *PI;
284 // If current basic block is this exit block's first predecessor
285 // then only insert exit block in to the output ExitBlocks vector.
286 // This ensures that same exit block is not inserted twice into
287 // ExitBlocks vector.
288 if (current != firstPred)
291 // If a terminator has more then two successors, for example SwitchInst,
292 // then it is possible that there are multiple edges from current block
293 // to one exit block.
294 if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
295 ExitBlocks.push_back(*I);
299 // In case of multiple edges from current block to exit block, collect
300 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
302 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
303 == switchExitBlocks.end()) {
304 switchExitBlocks.push_back(*I);
305 ExitBlocks.push_back(*I);
311 /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
312 /// block, return that block. Otherwise return null.
313 BasicBlock *Loop::getUniqueExitBlock() const {
314 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
315 getUniqueExitBlocks(UniqueExitBlocks);
316 if (UniqueExitBlocks.size() == 1)
317 return UniqueExitBlocks[0];
321 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
322 void Loop::dump() const {
327 //===----------------------------------------------------------------------===//
328 // UnloopUpdater implementation
332 /// Find the new parent loop for all blocks within the "unloop" whose last
333 /// backedges has just been removed.
334 class UnloopUpdater {
340 // Map unloop's immediate subloops to their nearest reachable parents. Nested
341 // loops within these subloops will not change parents. However, an immediate
342 // subloop's new parent will be the nearest loop reachable from either its own
343 // exits *or* any of its nested loop's exits.
344 DenseMap<Loop*, Loop*> SubloopParents;
346 // Flag the presence of an irreducible backedge whose destination is a block
347 // directly contained by the original unloop.
351 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
352 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
354 void updateBlockParents();
356 void removeBlocksFromAncestors();
358 void updateSubloopParents();
361 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
363 } // end anonymous namespace
365 /// updateBlockParents - Update the parent loop for all blocks that are directly
366 /// contained within the original "unloop".
367 void UnloopUpdater::updateBlockParents() {
368 if (Unloop->getNumBlocks()) {
369 // Perform a post order CFG traversal of all blocks within this loop,
370 // propagating the nearest loop from sucessors to predecessors.
371 LoopBlocksTraversal Traversal(DFS, LI);
372 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
373 POE = Traversal.end(); POI != POE; ++POI) {
375 Loop *L = LI->getLoopFor(*POI);
376 Loop *NL = getNearestLoop(*POI, L);
379 // For reducible loops, NL is now an ancestor of Unloop.
380 assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
381 "uninitialized successor");
382 LI->changeLoopFor(*POI, NL);
385 // Or the current block is part of a subloop, in which case its parent
387 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
391 // Each irreducible loop within the unloop induces a round of iteration using
392 // the DFS result cached by Traversal.
393 bool Changed = FoundIB;
394 for (unsigned NIters = 0; Changed; ++NIters) {
395 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
397 // Iterate over the postorder list of blocks, propagating the nearest loop
398 // from successors to predecessors as before.
400 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
401 POE = DFS.endPostorder(); POI != POE; ++POI) {
403 Loop *L = LI->getLoopFor(*POI);
404 Loop *NL = getNearestLoop(*POI, L);
406 assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
407 "uninitialized successor");
408 LI->changeLoopFor(*POI, NL);
415 /// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
416 /// their new parents.
417 void UnloopUpdater::removeBlocksFromAncestors() {
418 // Remove all unloop's blocks (including those in nested subloops) from
419 // ancestors below the new parent loop.
420 for (Loop::block_iterator BI = Unloop->block_begin(),
421 BE = Unloop->block_end(); BI != BE; ++BI) {
422 Loop *OuterParent = LI->getLoopFor(*BI);
423 if (Unloop->contains(OuterParent)) {
424 while (OuterParent->getParentLoop() != Unloop)
425 OuterParent = OuterParent->getParentLoop();
426 OuterParent = SubloopParents[OuterParent];
428 // Remove blocks from former Ancestors except Unloop itself which will be
430 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
431 OldParent = OldParent->getParentLoop()) {
432 assert(OldParent && "new loop is not an ancestor of the original");
433 OldParent->removeBlockFromLoop(*BI);
438 /// updateSubloopParents - Update the parent loop for all subloops directly
439 /// nested within unloop.
440 void UnloopUpdater::updateSubloopParents() {
441 while (!Unloop->empty()) {
442 Loop *Subloop = *llvm::prior(Unloop->end());
443 Unloop->removeChildLoop(llvm::prior(Unloop->end()));
445 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
446 if (Loop *Parent = SubloopParents[Subloop])
447 Parent->addChildLoop(Subloop);
449 LI->addTopLevelLoop(Subloop);
453 /// getNearestLoop - Return the nearest parent loop among this block's
454 /// successors. If a successor is a subloop header, consider its parent to be
455 /// the nearest parent of the subloop's exits.
457 /// For subloop blocks, simply update SubloopParents and return NULL.
458 Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
460 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
461 // is considered uninitialized.
462 Loop *NearLoop = BBLoop;
465 if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
467 // Find the subloop ancestor that is directly contained within Unloop.
468 while (Subloop->getParentLoop() != Unloop) {
469 Subloop = Subloop->getParentLoop();
470 assert(Subloop && "subloop is not an ancestor of the original loop");
472 // Get the current nearest parent of the Subloop exits, initially Unloop.
474 SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second;
477 succ_iterator I = succ_begin(BB), E = succ_end(BB);
479 assert(!Subloop && "subloop blocks must have a successor");
480 NearLoop = 0; // unloop blocks may now exit the function.
482 for (; I != E; ++I) {
484 continue; // self loops are uninteresting
486 Loop *L = LI->getLoopFor(*I);
488 // This successor has not been processed. This path must lead to an
489 // irreducible backedge.
490 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
493 if (L != Unloop && Unloop->contains(L)) {
494 // Successor is in a subloop.
496 continue; // Branching within subloops. Ignore it.
498 // BB branches from the original into a subloop header.
499 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
501 // Get the current nearest parent of the Subloop's exits.
502 L = SubloopParents[L];
503 // L could be Unloop if the only exit was an irreducible backedge.
508 // Handle critical edges from Unloop into a sibling loop.
509 if (L && !L->contains(Unloop)) {
510 L = L->getParentLoop();
512 // Remember the nearest parent loop among successors or subloop exits.
513 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
517 SubloopParents[Subloop] = NearLoop;
523 //===----------------------------------------------------------------------===//
524 // LoopInfo implementation
526 bool LoopInfo::runOnFunction(Function &) {
528 LI.Analyze(getAnalysis<DominatorTree>().getBase());
532 /// updateUnloop - The last backedge has been removed from a loop--now the
533 /// "unloop". Find a new parent for the blocks contained within unloop and
534 /// update the loop tree. We don't necessarily have valid dominators at this
535 /// point, but LoopInfo is still valid except for the removal of this loop.
537 /// Note that Unloop may now be an empty loop. Calling Loop::getHeader without
538 /// checking first is illegal.
539 void LoopInfo::updateUnloop(Loop *Unloop) {
541 // First handle the special case of no parent loop to simplify the algorithm.
542 if (!Unloop->getParentLoop()) {
543 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
544 for (Loop::block_iterator I = Unloop->block_begin(),
545 E = Unloop->block_end(); I != E; ++I) {
547 // Don't reparent blocks in subloops.
548 if (getLoopFor(*I) != Unloop)
551 // Blocks no longer have a parent but are still referenced by Unloop until
552 // the Unloop object is deleted.
553 LI.changeLoopFor(*I, 0);
556 // Remove the loop from the top-level LoopInfo object.
557 for (LoopInfo::iterator I = LI.begin();; ++I) {
558 assert(I != LI.end() && "Couldn't find loop");
565 // Move all of the subloops to the top-level.
566 while (!Unloop->empty())
567 LI.addTopLevelLoop(Unloop->removeChildLoop(llvm::prior(Unloop->end())));
572 // Update the parent loop for all blocks within the loop. Blocks within
573 // subloops will not change parents.
574 UnloopUpdater Updater(Unloop, this);
575 Updater.updateBlockParents();
577 // Remove blocks from former ancestor loops.
578 Updater.removeBlocksFromAncestors();
580 // Add direct subloops as children in their new parent loop.
581 Updater.updateSubloopParents();
583 // Remove unloop from its parent loop.
584 Loop *ParentLoop = Unloop->getParentLoop();
585 for (Loop::iterator I = ParentLoop->begin();; ++I) {
586 assert(I != ParentLoop->end() && "Couldn't find loop");
588 ParentLoop->removeChildLoop(I);
594 void LoopInfo::verifyAnalysis() const {
595 // LoopInfo is a FunctionPass, but verifying every loop in the function
596 // each time verifyAnalysis is called is very expensive. The
597 // -verify-loop-info option can enable this. In order to perform some
598 // checking by default, LoopPass has been taught to call verifyLoop
599 // manually during loop pass sequences.
601 if (!VerifyLoopInfo) return;
603 DenseSet<const Loop*> Loops;
604 for (iterator I = begin(), E = end(); I != E; ++I) {
605 assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
606 (*I)->verifyLoopNest(&Loops);
609 // Verify that blocks are mapped to valid loops.
610 for (DenseMap<BasicBlock*, Loop*>::const_iterator I = LI.BBMap.begin(),
611 E = LI.BBMap.end(); I != E; ++I) {
612 assert(Loops.count(I->second) && "orphaned loop");
613 assert(I->second->contains(I->first) && "orphaned block");
617 void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
618 AU.setPreservesAll();
619 AU.addRequired<DominatorTree>();
622 void LoopInfo::print(raw_ostream &OS, const Module*) const {
626 //===----------------------------------------------------------------------===//
627 // LoopBlocksDFS implementation
630 /// Traverse the loop blocks and store the DFS result.
631 /// Useful for clients that just want the final DFS result and don't need to
632 /// visit blocks during the initial traversal.
633 void LoopBlocksDFS::perform(LoopInfo *LI) {
634 LoopBlocksTraversal Traversal(*this, LI);
635 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
636 POE = Traversal.end(); POI != POE; ++POI) ;