LLVM API Documentation
00001 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines the LoopInfo class that is used to identify natural loops 00011 // and determine the loop depth of various nodes of the CFG. Note that the 00012 // loops identified may actually be several natural loops that share the same 00013 // header node... not just a single natural loop. 00014 // 00015 //===----------------------------------------------------------------------===// 00016 00017 #include "llvm/Analysis/LoopInfo.h" 00018 #include "llvm/ADT/DepthFirstIterator.h" 00019 #include "llvm/ADT/SmallPtrSet.h" 00020 #include "llvm/Analysis/LoopInfoImpl.h" 00021 #include "llvm/Analysis/LoopIterator.h" 00022 #include "llvm/Analysis/ValueTracking.h" 00023 #include "llvm/IR/CFG.h" 00024 #include "llvm/IR/Constants.h" 00025 #include "llvm/IR/Dominators.h" 00026 #include "llvm/IR/Instructions.h" 00027 #include "llvm/IR/Metadata.h" 00028 #include "llvm/Support/CommandLine.h" 00029 #include "llvm/Support/Debug.h" 00030 #include <algorithm> 00031 using namespace llvm; 00032 00033 // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops. 00034 template class llvm::LoopBase<BasicBlock, Loop>; 00035 template class llvm::LoopInfoBase<BasicBlock, Loop>; 00036 00037 // Always verify loopinfo if expensive checking is enabled. 00038 #ifdef XDEBUG 00039 static bool VerifyLoopInfo = true; 00040 #else 00041 static bool VerifyLoopInfo = false; 00042 #endif 00043 static cl::opt<bool,true> 00044 VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo), 00045 cl::desc("Verify loop info (time consuming)")); 00046 00047 char LoopInfo::ID = 0; 00048 INITIALIZE_PASS_BEGIN(LoopInfo, "loops", "Natural Loop Information", true, true) 00049 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 00050 INITIALIZE_PASS_END(LoopInfo, "loops", "Natural Loop Information", true, true) 00051 00052 // Loop identifier metadata name. 00053 static const char *const LoopMDName = "llvm.loop"; 00054 00055 //===----------------------------------------------------------------------===// 00056 // Loop implementation 00057 // 00058 00059 /// isLoopInvariant - Return true if the specified value is loop invariant 00060 /// 00061 bool Loop::isLoopInvariant(Value *V) const { 00062 if (Instruction *I = dyn_cast<Instruction>(V)) 00063 return !contains(I); 00064 return true; // All non-instructions are loop invariant 00065 } 00066 00067 /// hasLoopInvariantOperands - Return true if all the operands of the 00068 /// specified instruction are loop invariant. 00069 bool Loop::hasLoopInvariantOperands(Instruction *I) const { 00070 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 00071 if (!isLoopInvariant(I->getOperand(i))) 00072 return false; 00073 00074 return true; 00075 } 00076 00077 /// makeLoopInvariant - If the given value is an instruciton inside of the 00078 /// loop and it can be hoisted, do so to make it trivially loop-invariant. 00079 /// Return true if the value after any hoisting is loop invariant. This 00080 /// function can be used as a slightly more aggressive replacement for 00081 /// isLoopInvariant. 00082 /// 00083 /// If InsertPt is specified, it is the point to hoist instructions to. 00084 /// If null, the terminator of the loop preheader is used. 00085 /// 00086 bool Loop::makeLoopInvariant(Value *V, bool &Changed, 00087 Instruction *InsertPt) const { 00088 if (Instruction *I = dyn_cast<Instruction>(V)) 00089 return makeLoopInvariant(I, Changed, InsertPt); 00090 return true; // All non-instructions are loop-invariant. 00091 } 00092 00093 /// makeLoopInvariant - If the given instruction is inside of the 00094 /// loop and it can be hoisted, do so to make it trivially loop-invariant. 00095 /// Return true if the instruction after any hoisting is loop invariant. This 00096 /// function can be used as a slightly more aggressive replacement for 00097 /// isLoopInvariant. 00098 /// 00099 /// If InsertPt is specified, it is the point to hoist instructions to. 00100 /// If null, the terminator of the loop preheader is used. 00101 /// 00102 bool Loop::makeLoopInvariant(Instruction *I, bool &Changed, 00103 Instruction *InsertPt) const { 00104 // Test if the value is already loop-invariant. 00105 if (isLoopInvariant(I)) 00106 return true; 00107 if (!isSafeToSpeculativelyExecute(I)) 00108 return false; 00109 if (I->mayReadFromMemory()) 00110 return false; 00111 // The landingpad instruction is immobile. 00112 if (isa<LandingPadInst>(I)) 00113 return false; 00114 // Determine the insertion point, unless one was given. 00115 if (!InsertPt) { 00116 BasicBlock *Preheader = getLoopPreheader(); 00117 // Without a preheader, hoisting is not feasible. 00118 if (!Preheader) 00119 return false; 00120 InsertPt = Preheader->getTerminator(); 00121 } 00122 // Don't hoist instructions with loop-variant operands. 00123 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 00124 if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt)) 00125 return false; 00126 00127 // Hoist. 00128 I->moveBefore(InsertPt); 00129 Changed = true; 00130 return true; 00131 } 00132 00133 /// getCanonicalInductionVariable - Check to see if the loop has a canonical 00134 /// induction variable: an integer recurrence that starts at 0 and increments 00135 /// by one each time through the loop. If so, return the phi node that 00136 /// corresponds to it. 00137 /// 00138 /// The IndVarSimplify pass transforms loops to have a canonical induction 00139 /// variable. 00140 /// 00141 PHINode *Loop::getCanonicalInductionVariable() const { 00142 BasicBlock *H = getHeader(); 00143 00144 BasicBlock *Incoming = nullptr, *Backedge = nullptr; 00145 pred_iterator PI = pred_begin(H); 00146 assert(PI != pred_end(H) && 00147 "Loop must have at least one backedge!"); 00148 Backedge = *PI++; 00149 if (PI == pred_end(H)) return nullptr; // dead loop 00150 Incoming = *PI++; 00151 if (PI != pred_end(H)) return nullptr; // multiple backedges? 00152 00153 if (contains(Incoming)) { 00154 if (contains(Backedge)) 00155 return nullptr; 00156 std::swap(Incoming, Backedge); 00157 } else if (!contains(Backedge)) 00158 return nullptr; 00159 00160 // Loop over all of the PHI nodes, looking for a canonical indvar. 00161 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) { 00162 PHINode *PN = cast<PHINode>(I); 00163 if (ConstantInt *CI = 00164 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming))) 00165 if (CI->isNullValue()) 00166 if (Instruction *Inc = 00167 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge))) 00168 if (Inc->getOpcode() == Instruction::Add && 00169 Inc->getOperand(0) == PN) 00170 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1))) 00171 if (CI->equalsInt(1)) 00172 return PN; 00173 } 00174 return nullptr; 00175 } 00176 00177 /// isLCSSAForm - Return true if the Loop is in LCSSA form 00178 bool Loop::isLCSSAForm(DominatorTree &DT) const { 00179 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) { 00180 BasicBlock *BB = *BI; 00181 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I) 00182 for (Use &U : I->uses()) { 00183 Instruction *UI = cast<Instruction>(U.getUser()); 00184 BasicBlock *UserBB = UI->getParent(); 00185 if (PHINode *P = dyn_cast<PHINode>(UI)) 00186 UserBB = P->getIncomingBlock(U); 00187 00188 // Check the current block, as a fast-path, before checking whether 00189 // the use is anywhere in the loop. Most values are used in the same 00190 // block they are defined in. Also, blocks not reachable from the 00191 // entry are special; uses in them don't need to go through PHIs. 00192 if (UserBB != BB && 00193 !contains(UserBB) && 00194 DT.isReachableFromEntry(UserBB)) 00195 return false; 00196 } 00197 } 00198 00199 return true; 00200 } 00201 00202 /// isLoopSimplifyForm - Return true if the Loop is in the form that 00203 /// the LoopSimplify form transforms loops to, which is sometimes called 00204 /// normal form. 00205 bool Loop::isLoopSimplifyForm() const { 00206 // Normal-form loops have a preheader, a single backedge, and all of their 00207 // exits have all their predecessors inside the loop. 00208 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits(); 00209 } 00210 00211 /// isSafeToClone - Return true if the loop body is safe to clone in practice. 00212 /// Routines that reform the loop CFG and split edges often fail on indirectbr. 00213 bool Loop::isSafeToClone() const { 00214 // Return false if any loop blocks contain indirectbrs, or there are any calls 00215 // to noduplicate functions. 00216 for (Loop::block_iterator I = block_begin(), E = block_end(); I != E; ++I) { 00217 if (isa<IndirectBrInst>((*I)->getTerminator())) 00218 return false; 00219 00220 if (const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator())) 00221 if (II->cannotDuplicate()) 00222 return false; 00223 00224 for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end(); BI != BE; ++BI) { 00225 if (const CallInst *CI = dyn_cast<CallInst>(BI)) { 00226 if (CI->cannotDuplicate()) 00227 return false; 00228 } 00229 } 00230 } 00231 return true; 00232 } 00233 00234 MDNode *Loop::getLoopID() const { 00235 MDNode *LoopID = nullptr; 00236 if (isLoopSimplifyForm()) { 00237 LoopID = getLoopLatch()->getTerminator()->getMetadata(LoopMDName); 00238 } else { 00239 // Go through each predecessor of the loop header and check the 00240 // terminator for the metadata. 00241 BasicBlock *H = getHeader(); 00242 for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) { 00243 TerminatorInst *TI = (*I)->getTerminator(); 00244 MDNode *MD = nullptr; 00245 00246 // Check if this terminator branches to the loop header. 00247 for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) { 00248 if (TI->getSuccessor(i) == H) { 00249 MD = TI->getMetadata(LoopMDName); 00250 break; 00251 } 00252 } 00253 if (!MD) 00254 return nullptr; 00255 00256 if (!LoopID) 00257 LoopID = MD; 00258 else if (MD != LoopID) 00259 return nullptr; 00260 } 00261 } 00262 if (!LoopID || LoopID->getNumOperands() == 0 || 00263 LoopID->getOperand(0) != LoopID) 00264 return nullptr; 00265 return LoopID; 00266 } 00267 00268 void Loop::setLoopID(MDNode *LoopID) const { 00269 assert(LoopID && "Loop ID should not be null"); 00270 assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand"); 00271 assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself"); 00272 00273 if (isLoopSimplifyForm()) { 00274 getLoopLatch()->getTerminator()->setMetadata(LoopMDName, LoopID); 00275 return; 00276 } 00277 00278 BasicBlock *H = getHeader(); 00279 for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) { 00280 TerminatorInst *TI = (*I)->getTerminator(); 00281 for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) { 00282 if (TI->getSuccessor(i) == H) 00283 TI->setMetadata(LoopMDName, LoopID); 00284 } 00285 } 00286 } 00287 00288 bool Loop::isAnnotatedParallel() const { 00289 MDNode *desiredLoopIdMetadata = getLoopID(); 00290 00291 if (!desiredLoopIdMetadata) 00292 return false; 00293 00294 // The loop branch contains the parallel loop metadata. In order to ensure 00295 // that any parallel-loop-unaware optimization pass hasn't added loop-carried 00296 // dependencies (thus converted the loop back to a sequential loop), check 00297 // that all the memory instructions in the loop contain parallelism metadata 00298 // that point to the same unique "loop id metadata" the loop branch does. 00299 for (block_iterator BB = block_begin(), BE = block_end(); BB != BE; ++BB) { 00300 for (BasicBlock::iterator II = (*BB)->begin(), EE = (*BB)->end(); 00301 II != EE; II++) { 00302 00303 if (!II->mayReadOrWriteMemory()) 00304 continue; 00305 00306 // The memory instruction can refer to the loop identifier metadata 00307 // directly or indirectly through another list metadata (in case of 00308 // nested parallel loops). The loop identifier metadata refers to 00309 // itself so we can check both cases with the same routine. 00310 MDNode *loopIdMD = II->getMetadata("llvm.mem.parallel_loop_access"); 00311 00312 if (!loopIdMD) 00313 return false; 00314 00315 bool loopIdMDFound = false; 00316 for (unsigned i = 0, e = loopIdMD->getNumOperands(); i < e; ++i) { 00317 if (loopIdMD->getOperand(i) == desiredLoopIdMetadata) { 00318 loopIdMDFound = true; 00319 break; 00320 } 00321 } 00322 00323 if (!loopIdMDFound) 00324 return false; 00325 } 00326 } 00327 return true; 00328 } 00329 00330 00331 /// hasDedicatedExits - Return true if no exit block for the loop 00332 /// has a predecessor that is outside the loop. 00333 bool Loop::hasDedicatedExits() const { 00334 // Each predecessor of each exit block of a normal loop is contained 00335 // within the loop. 00336 SmallVector<BasicBlock *, 4> ExitBlocks; 00337 getExitBlocks(ExitBlocks); 00338 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 00339 for (pred_iterator PI = pred_begin(ExitBlocks[i]), 00340 PE = pred_end(ExitBlocks[i]); PI != PE; ++PI) 00341 if (!contains(*PI)) 00342 return false; 00343 // All the requirements are met. 00344 return true; 00345 } 00346 00347 /// getUniqueExitBlocks - Return all unique successor blocks of this loop. 00348 /// These are the blocks _outside of the current loop_ which are branched to. 00349 /// This assumes that loop exits are in canonical form. 00350 /// 00351 void 00352 Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const { 00353 assert(hasDedicatedExits() && 00354 "getUniqueExitBlocks assumes the loop has canonical form exits!"); 00355 00356 SmallVector<BasicBlock *, 32> switchExitBlocks; 00357 00358 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) { 00359 00360 BasicBlock *current = *BI; 00361 switchExitBlocks.clear(); 00362 00363 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) { 00364 // If block is inside the loop then it is not a exit block. 00365 if (contains(*I)) 00366 continue; 00367 00368 pred_iterator PI = pred_begin(*I); 00369 BasicBlock *firstPred = *PI; 00370 00371 // If current basic block is this exit block's first predecessor 00372 // then only insert exit block in to the output ExitBlocks vector. 00373 // This ensures that same exit block is not inserted twice into 00374 // ExitBlocks vector. 00375 if (current != firstPred) 00376 continue; 00377 00378 // If a terminator has more then two successors, for example SwitchInst, 00379 // then it is possible that there are multiple edges from current block 00380 // to one exit block. 00381 if (std::distance(succ_begin(current), succ_end(current)) <= 2) { 00382 ExitBlocks.push_back(*I); 00383 continue; 00384 } 00385 00386 // In case of multiple edges from current block to exit block, collect 00387 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of 00388 // duplicate edges. 00389 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I) 00390 == switchExitBlocks.end()) { 00391 switchExitBlocks.push_back(*I); 00392 ExitBlocks.push_back(*I); 00393 } 00394 } 00395 } 00396 } 00397 00398 /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one 00399 /// block, return that block. Otherwise return null. 00400 BasicBlock *Loop::getUniqueExitBlock() const { 00401 SmallVector<BasicBlock *, 8> UniqueExitBlocks; 00402 getUniqueExitBlocks(UniqueExitBlocks); 00403 if (UniqueExitBlocks.size() == 1) 00404 return UniqueExitBlocks[0]; 00405 return nullptr; 00406 } 00407 00408 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 00409 void Loop::dump() const { 00410 print(dbgs()); 00411 } 00412 #endif 00413 00414 //===----------------------------------------------------------------------===// 00415 // UnloopUpdater implementation 00416 // 00417 00418 namespace { 00419 /// Find the new parent loop for all blocks within the "unloop" whose last 00420 /// backedges has just been removed. 00421 class UnloopUpdater { 00422 Loop *Unloop; 00423 LoopInfo *LI; 00424 00425 LoopBlocksDFS DFS; 00426 00427 // Map unloop's immediate subloops to their nearest reachable parents. Nested 00428 // loops within these subloops will not change parents. However, an immediate 00429 // subloop's new parent will be the nearest loop reachable from either its own 00430 // exits *or* any of its nested loop's exits. 00431 DenseMap<Loop*, Loop*> SubloopParents; 00432 00433 // Flag the presence of an irreducible backedge whose destination is a block 00434 // directly contained by the original unloop. 00435 bool FoundIB; 00436 00437 public: 00438 UnloopUpdater(Loop *UL, LoopInfo *LInfo) : 00439 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {} 00440 00441 void updateBlockParents(); 00442 00443 void removeBlocksFromAncestors(); 00444 00445 void updateSubloopParents(); 00446 00447 protected: 00448 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop); 00449 }; 00450 } // end anonymous namespace 00451 00452 /// updateBlockParents - Update the parent loop for all blocks that are directly 00453 /// contained within the original "unloop". 00454 void UnloopUpdater::updateBlockParents() { 00455 if (Unloop->getNumBlocks()) { 00456 // Perform a post order CFG traversal of all blocks within this loop, 00457 // propagating the nearest loop from sucessors to predecessors. 00458 LoopBlocksTraversal Traversal(DFS, LI); 00459 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(), 00460 POE = Traversal.end(); POI != POE; ++POI) { 00461 00462 Loop *L = LI->getLoopFor(*POI); 00463 Loop *NL = getNearestLoop(*POI, L); 00464 00465 if (NL != L) { 00466 // For reducible loops, NL is now an ancestor of Unloop. 00467 assert((NL != Unloop && (!NL || NL->contains(Unloop))) && 00468 "uninitialized successor"); 00469 LI->changeLoopFor(*POI, NL); 00470 } 00471 else { 00472 // Or the current block is part of a subloop, in which case its parent 00473 // is unchanged. 00474 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor"); 00475 } 00476 } 00477 } 00478 // Each irreducible loop within the unloop induces a round of iteration using 00479 // the DFS result cached by Traversal. 00480 bool Changed = FoundIB; 00481 for (unsigned NIters = 0; Changed; ++NIters) { 00482 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm"); 00483 00484 // Iterate over the postorder list of blocks, propagating the nearest loop 00485 // from successors to predecessors as before. 00486 Changed = false; 00487 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(), 00488 POE = DFS.endPostorder(); POI != POE; ++POI) { 00489 00490 Loop *L = LI->getLoopFor(*POI); 00491 Loop *NL = getNearestLoop(*POI, L); 00492 if (NL != L) { 00493 assert(NL != Unloop && (!NL || NL->contains(Unloop)) && 00494 "uninitialized successor"); 00495 LI->changeLoopFor(*POI, NL); 00496 Changed = true; 00497 } 00498 } 00499 } 00500 } 00501 00502 /// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below 00503 /// their new parents. 00504 void UnloopUpdater::removeBlocksFromAncestors() { 00505 // Remove all unloop's blocks (including those in nested subloops) from 00506 // ancestors below the new parent loop. 00507 for (Loop::block_iterator BI = Unloop->block_begin(), 00508 BE = Unloop->block_end(); BI != BE; ++BI) { 00509 Loop *OuterParent = LI->getLoopFor(*BI); 00510 if (Unloop->contains(OuterParent)) { 00511 while (OuterParent->getParentLoop() != Unloop) 00512 OuterParent = OuterParent->getParentLoop(); 00513 OuterParent = SubloopParents[OuterParent]; 00514 } 00515 // Remove blocks from former Ancestors except Unloop itself which will be 00516 // deleted. 00517 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent; 00518 OldParent = OldParent->getParentLoop()) { 00519 assert(OldParent && "new loop is not an ancestor of the original"); 00520 OldParent->removeBlockFromLoop(*BI); 00521 } 00522 } 00523 } 00524 00525 /// updateSubloopParents - Update the parent loop for all subloops directly 00526 /// nested within unloop. 00527 void UnloopUpdater::updateSubloopParents() { 00528 while (!Unloop->empty()) { 00529 Loop *Subloop = *std::prev(Unloop->end()); 00530 Unloop->removeChildLoop(std::prev(Unloop->end())); 00531 00532 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop"); 00533 if (Loop *Parent = SubloopParents[Subloop]) 00534 Parent->addChildLoop(Subloop); 00535 else 00536 LI->addTopLevelLoop(Subloop); 00537 } 00538 } 00539 00540 /// getNearestLoop - Return the nearest parent loop among this block's 00541 /// successors. If a successor is a subloop header, consider its parent to be 00542 /// the nearest parent of the subloop's exits. 00543 /// 00544 /// For subloop blocks, simply update SubloopParents and return NULL. 00545 Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) { 00546 00547 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and 00548 // is considered uninitialized. 00549 Loop *NearLoop = BBLoop; 00550 00551 Loop *Subloop = nullptr; 00552 if (NearLoop != Unloop && Unloop->contains(NearLoop)) { 00553 Subloop = NearLoop; 00554 // Find the subloop ancestor that is directly contained within Unloop. 00555 while (Subloop->getParentLoop() != Unloop) { 00556 Subloop = Subloop->getParentLoop(); 00557 assert(Subloop && "subloop is not an ancestor of the original loop"); 00558 } 00559 // Get the current nearest parent of the Subloop exits, initially Unloop. 00560 NearLoop = 00561 SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second; 00562 } 00563 00564 succ_iterator I = succ_begin(BB), E = succ_end(BB); 00565 if (I == E) { 00566 assert(!Subloop && "subloop blocks must have a successor"); 00567 NearLoop = nullptr; // unloop blocks may now exit the function. 00568 } 00569 for (; I != E; ++I) { 00570 if (*I == BB) 00571 continue; // self loops are uninteresting 00572 00573 Loop *L = LI->getLoopFor(*I); 00574 if (L == Unloop) { 00575 // This successor has not been processed. This path must lead to an 00576 // irreducible backedge. 00577 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB"); 00578 FoundIB = true; 00579 } 00580 if (L != Unloop && Unloop->contains(L)) { 00581 // Successor is in a subloop. 00582 if (Subloop) 00583 continue; // Branching within subloops. Ignore it. 00584 00585 // BB branches from the original into a subloop header. 00586 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops"); 00587 00588 // Get the current nearest parent of the Subloop's exits. 00589 L = SubloopParents[L]; 00590 // L could be Unloop if the only exit was an irreducible backedge. 00591 } 00592 if (L == Unloop) { 00593 continue; 00594 } 00595 // Handle critical edges from Unloop into a sibling loop. 00596 if (L && !L->contains(Unloop)) { 00597 L = L->getParentLoop(); 00598 } 00599 // Remember the nearest parent loop among successors or subloop exits. 00600 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L)) 00601 NearLoop = L; 00602 } 00603 if (Subloop) { 00604 SubloopParents[Subloop] = NearLoop; 00605 return BBLoop; 00606 } 00607 return NearLoop; 00608 } 00609 00610 //===----------------------------------------------------------------------===// 00611 // LoopInfo implementation 00612 // 00613 bool LoopInfo::runOnFunction(Function &) { 00614 releaseMemory(); 00615 LI.Analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree()); 00616 return false; 00617 } 00618 00619 /// updateUnloop - The last backedge has been removed from a loop--now the 00620 /// "unloop". Find a new parent for the blocks contained within unloop and 00621 /// update the loop tree. We don't necessarily have valid dominators at this 00622 /// point, but LoopInfo is still valid except for the removal of this loop. 00623 /// 00624 /// Note that Unloop may now be an empty loop. Calling Loop::getHeader without 00625 /// checking first is illegal. 00626 void LoopInfo::updateUnloop(Loop *Unloop) { 00627 00628 // First handle the special case of no parent loop to simplify the algorithm. 00629 if (!Unloop->getParentLoop()) { 00630 // Since BBLoop had no parent, Unloop blocks are no longer in a loop. 00631 for (Loop::block_iterator I = Unloop->block_begin(), 00632 E = Unloop->block_end(); I != E; ++I) { 00633 00634 // Don't reparent blocks in subloops. 00635 if (getLoopFor(*I) != Unloop) 00636 continue; 00637 00638 // Blocks no longer have a parent but are still referenced by Unloop until 00639 // the Unloop object is deleted. 00640 LI.changeLoopFor(*I, nullptr); 00641 } 00642 00643 // Remove the loop from the top-level LoopInfo object. 00644 for (LoopInfo::iterator I = LI.begin();; ++I) { 00645 assert(I != LI.end() && "Couldn't find loop"); 00646 if (*I == Unloop) { 00647 LI.removeLoop(I); 00648 break; 00649 } 00650 } 00651 00652 // Move all of the subloops to the top-level. 00653 while (!Unloop->empty()) 00654 LI.addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end()))); 00655 00656 return; 00657 } 00658 00659 // Update the parent loop for all blocks within the loop. Blocks within 00660 // subloops will not change parents. 00661 UnloopUpdater Updater(Unloop, this); 00662 Updater.updateBlockParents(); 00663 00664 // Remove blocks from former ancestor loops. 00665 Updater.removeBlocksFromAncestors(); 00666 00667 // Add direct subloops as children in their new parent loop. 00668 Updater.updateSubloopParents(); 00669 00670 // Remove unloop from its parent loop. 00671 Loop *ParentLoop = Unloop->getParentLoop(); 00672 for (Loop::iterator I = ParentLoop->begin();; ++I) { 00673 assert(I != ParentLoop->end() && "Couldn't find loop"); 00674 if (*I == Unloop) { 00675 ParentLoop->removeChildLoop(I); 00676 break; 00677 } 00678 } 00679 } 00680 00681 void LoopInfo::verifyAnalysis() const { 00682 // LoopInfo is a FunctionPass, but verifying every loop in the function 00683 // each time verifyAnalysis is called is very expensive. The 00684 // -verify-loop-info option can enable this. In order to perform some 00685 // checking by default, LoopPass has been taught to call verifyLoop 00686 // manually during loop pass sequences. 00687 00688 if (!VerifyLoopInfo) return; 00689 00690 DenseSet<const Loop*> Loops; 00691 for (iterator I = begin(), E = end(); I != E; ++I) { 00692 assert(!(*I)->getParentLoop() && "Top-level loop has a parent!"); 00693 (*I)->verifyLoopNest(&Loops); 00694 } 00695 00696 // Verify that blocks are mapped to valid loops. 00697 for (DenseMap<BasicBlock*, Loop*>::const_iterator I = LI.BBMap.begin(), 00698 E = LI.BBMap.end(); I != E; ++I) { 00699 assert(Loops.count(I->second) && "orphaned loop"); 00700 assert(I->second->contains(I->first) && "orphaned block"); 00701 } 00702 } 00703 00704 void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const { 00705 AU.setPreservesAll(); 00706 AU.addRequired<DominatorTreeWrapperPass>(); 00707 } 00708 00709 void LoopInfo::print(raw_ostream &OS, const Module*) const { 00710 LI.print(OS); 00711 } 00712 00713 //===----------------------------------------------------------------------===// 00714 // LoopBlocksDFS implementation 00715 // 00716 00717 /// Traverse the loop blocks and store the DFS result. 00718 /// Useful for clients that just want the final DFS result and don't need to 00719 /// visit blocks during the initial traversal. 00720 void LoopBlocksDFS::perform(LoopInfo *LI) { 00721 LoopBlocksTraversal Traversal(*this, LI); 00722 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(), 00723 POE = Traversal.end(); POI != POE; ++POI) ; 00724 }