1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the LoopInfo class that is used to identify natural loops 11 // and determine the loop depth of various nodes of the CFG. Note that the 12 // loops identified may actually be several natural loops that share the same 13 // header node... not just a single natural loop. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/Analysis/LoopInfo.h" 18 #include "llvm/ADT/DepthFirstIterator.h" 19 #include "llvm/ADT/ScopeExit.h" 20 #include "llvm/ADT/SmallPtrSet.h" 21 #include "llvm/Analysis/LoopInfoImpl.h" 22 #include "llvm/Analysis/LoopIterator.h" 23 #include "llvm/Analysis/ValueTracking.h" 24 #include "llvm/Config/llvm-config.h" 25 #include "llvm/IR/CFG.h" 26 #include "llvm/IR/Constants.h" 27 #include "llvm/IR/DebugLoc.h" 28 #include "llvm/IR/Dominators.h" 29 #include "llvm/IR/Instructions.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/IR/Metadata.h" 32 #include "llvm/IR/PassManager.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include <algorithm> 37 using namespace llvm; 38 39 // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops. 40 template class llvm::LoopBase<BasicBlock, Loop>; 41 template class llvm::LoopInfoBase<BasicBlock, Loop>; 42 43 // Always verify loopinfo if expensive checking is enabled. 44 #ifdef EXPENSIVE_CHECKS 45 bool llvm::VerifyLoopInfo = true; 46 #else 47 bool llvm::VerifyLoopInfo = false; 48 #endif 49 static cl::opt<bool, true> 50 VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo), 51 cl::Hidden, cl::desc("Verify loop info (time consuming)")); 52 53 //===----------------------------------------------------------------------===// 54 // Loop implementation 55 // 56 57 bool Loop::isLoopInvariant(const Value *V) const { 58 if (const Instruction *I = dyn_cast<Instruction>(V)) 59 return !contains(I); 60 return true; // All non-instructions are loop invariant 61 } 62 63 bool Loop::hasLoopInvariantOperands(const Instruction *I) const { 64 return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); }); 65 } 66 67 bool Loop::makeLoopInvariant(Value *V, bool &Changed, 68 Instruction *InsertPt) const { 69 if (Instruction *I = dyn_cast<Instruction>(V)) 70 return makeLoopInvariant(I, Changed, InsertPt); 71 return true; // All non-instructions are loop-invariant. 72 } 73 74 bool Loop::makeLoopInvariant(Instruction *I, bool &Changed, 75 Instruction *InsertPt) const { 76 // Test if the value is already loop-invariant. 77 if (isLoopInvariant(I)) 78 return true; 79 if (!isSafeToSpeculativelyExecute(I)) 80 return false; 81 if (I->mayReadFromMemory()) 82 return false; 83 // EH block instructions are immobile. 84 if (I->isEHPad()) 85 return false; 86 // Determine the insertion point, unless one was given. 87 if (!InsertPt) { 88 BasicBlock *Preheader = getLoopPreheader(); 89 // Without a preheader, hoisting is not feasible. 90 if (!Preheader) 91 return false; 92 InsertPt = Preheader->getTerminator(); 93 } 94 // Don't hoist instructions with loop-variant operands. 95 for (Value *Operand : I->operands()) 96 if (!makeLoopInvariant(Operand, Changed, InsertPt)) 97 return false; 98 99 // Hoist. 100 I->moveBefore(InsertPt); 101 102 // There is possibility of hoisting this instruction above some arbitrary 103 // condition. Any metadata defined on it can be control dependent on this 104 // condition. Conservatively strip it here so that we don't give any wrong 105 // information to the optimizer. 106 I->dropUnknownNonDebugMetadata(); 107 108 Changed = true; 109 return true; 110 } 111 112 PHINode *Loop::getCanonicalInductionVariable() const { 113 BasicBlock *H = getHeader(); 114 115 BasicBlock *Incoming = nullptr, *Backedge = nullptr; 116 pred_iterator PI = pred_begin(H); 117 assert(PI != pred_end(H) && "Loop must have at least one backedge!"); 118 Backedge = *PI++; 119 if (PI == pred_end(H)) 120 return nullptr; // dead loop 121 Incoming = *PI++; 122 if (PI != pred_end(H)) 123 return nullptr; // multiple backedges? 124 125 if (contains(Incoming)) { 126 if (contains(Backedge)) 127 return nullptr; 128 std::swap(Incoming, Backedge); 129 } else if (!contains(Backedge)) 130 return nullptr; 131 132 // Loop over all of the PHI nodes, looking for a canonical indvar. 133 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) { 134 PHINode *PN = cast<PHINode>(I); 135 if (ConstantInt *CI = 136 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming))) 137 if (CI->isZero()) 138 if (Instruction *Inc = 139 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge))) 140 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN) 141 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1))) 142 if (CI->isOne()) 143 return PN; 144 } 145 return nullptr; 146 } 147 148 // Check that 'BB' doesn't have any uses outside of the 'L' 149 static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB, 150 DominatorTree &DT) { 151 for (const Instruction &I : BB) { 152 // Tokens can't be used in PHI nodes and live-out tokens prevent loop 153 // optimizations, so for the purposes of considered LCSSA form, we 154 // can ignore them. 155 if (I.getType()->isTokenTy()) 156 continue; 157 158 for (const Use &U : I.uses()) { 159 const Instruction *UI = cast<Instruction>(U.getUser()); 160 const BasicBlock *UserBB = UI->getParent(); 161 if (const PHINode *P = dyn_cast<PHINode>(UI)) 162 UserBB = P->getIncomingBlock(U); 163 164 // Check the current block, as a fast-path, before checking whether 165 // the use is anywhere in the loop. Most values are used in the same 166 // block they are defined in. Also, blocks not reachable from the 167 // entry are special; uses in them don't need to go through PHIs. 168 if (UserBB != &BB && !L.contains(UserBB) && 169 DT.isReachableFromEntry(UserBB)) 170 return false; 171 } 172 } 173 return true; 174 } 175 176 bool Loop::isLCSSAForm(DominatorTree &DT) const { 177 // For each block we check that it doesn't have any uses outside of this loop. 178 return all_of(this->blocks(), [&](const BasicBlock *BB) { 179 return isBlockInLCSSAForm(*this, *BB, DT); 180 }); 181 } 182 183 bool Loop::isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const { 184 // For each block we check that it doesn't have any uses outside of its 185 // innermost loop. This process will transitively guarantee that the current 186 // loop and all of the nested loops are in LCSSA form. 187 return all_of(this->blocks(), [&](const BasicBlock *BB) { 188 return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT); 189 }); 190 } 191 192 bool Loop::isLoopSimplifyForm() const { 193 // Normal-form loops have a preheader, a single backedge, and all of their 194 // exits have all their predecessors inside the loop. 195 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits(); 196 } 197 198 // Routines that reform the loop CFG and split edges often fail on indirectbr. 199 bool Loop::isSafeToClone() const { 200 // Return false if any loop blocks contain indirectbrs, or there are any calls 201 // to noduplicate functions. 202 for (BasicBlock *BB : this->blocks()) { 203 if (isa<IndirectBrInst>(BB->getTerminator())) 204 return false; 205 206 for (Instruction &I : *BB) 207 if (auto CS = CallSite(&I)) 208 if (CS.cannotDuplicate()) 209 return false; 210 } 211 return true; 212 } 213 214 MDNode *Loop::getLoopID() const { 215 MDNode *LoopID = nullptr; 216 217 // Go through the latch blocks and check the terminator for the metadata. 218 SmallVector<BasicBlock *, 4> LatchesBlocks; 219 getLoopLatches(LatchesBlocks); 220 for (BasicBlock *BB : LatchesBlocks) { 221 TerminatorInst *TI = BB->getTerminator(); 222 MDNode *MD = TI->getMetadata(LLVMContext::MD_loop); 223 224 if (!MD) 225 return nullptr; 226 227 if (!LoopID) 228 LoopID = MD; 229 else if (MD != LoopID) 230 return nullptr; 231 } 232 if (!LoopID || LoopID->getNumOperands() == 0 || 233 LoopID->getOperand(0) != LoopID) 234 return nullptr; 235 return LoopID; 236 } 237 238 void Loop::setLoopID(MDNode *LoopID) const { 239 assert(LoopID && "Loop ID should not be null"); 240 assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand"); 241 assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself"); 242 243 if (BasicBlock *Latch = getLoopLatch()) { 244 Latch->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID); 245 return; 246 } 247 248 assert(!getLoopLatch() && 249 "The loop should have no single latch at this point"); 250 BasicBlock *H = getHeader(); 251 for (BasicBlock *BB : this->blocks()) { 252 TerminatorInst *TI = BB->getTerminator(); 253 for (BasicBlock *Successor : successors(TI)) { 254 if (Successor == H) 255 TI->setMetadata(LLVMContext::MD_loop, LoopID); 256 } 257 } 258 } 259 260 void Loop::setLoopAlreadyUnrolled() { 261 MDNode *LoopID = getLoopID(); 262 // First remove any existing loop unrolling metadata. 263 SmallVector<Metadata *, 4> MDs; 264 // Reserve first location for self reference to the LoopID metadata node. 265 MDs.push_back(nullptr); 266 267 if (LoopID) { 268 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 269 bool IsUnrollMetadata = false; 270 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 271 if (MD) { 272 const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 273 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); 274 } 275 if (!IsUnrollMetadata) 276 MDs.push_back(LoopID->getOperand(i)); 277 } 278 } 279 280 // Add unroll(disable) metadata to disable future unrolling. 281 LLVMContext &Context = getHeader()->getContext(); 282 SmallVector<Metadata *, 1> DisableOperands; 283 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); 284 MDNode *DisableNode = MDNode::get(Context, DisableOperands); 285 MDs.push_back(DisableNode); 286 287 MDNode *NewLoopID = MDNode::get(Context, MDs); 288 // Set operand 0 to refer to the loop id itself. 289 NewLoopID->replaceOperandWith(0, NewLoopID); 290 setLoopID(NewLoopID); 291 } 292 293 bool Loop::isAnnotatedParallel() const { 294 MDNode *DesiredLoopIdMetadata = getLoopID(); 295 296 if (!DesiredLoopIdMetadata) 297 return false; 298 299 // The loop branch contains the parallel loop metadata. In order to ensure 300 // that any parallel-loop-unaware optimization pass hasn't added loop-carried 301 // dependencies (thus converted the loop back to a sequential loop), check 302 // that all the memory instructions in the loop contain parallelism metadata 303 // that point to the same unique "loop id metadata" the loop branch does. 304 for (BasicBlock *BB : this->blocks()) { 305 for (Instruction &I : *BB) { 306 if (!I.mayReadOrWriteMemory()) 307 continue; 308 309 // The memory instruction can refer to the loop identifier metadata 310 // directly or indirectly through another list metadata (in case of 311 // nested parallel loops). The loop identifier metadata refers to 312 // itself so we can check both cases with the same routine. 313 MDNode *LoopIdMD = 314 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access); 315 316 if (!LoopIdMD) 317 return false; 318 319 bool LoopIdMDFound = false; 320 for (const MDOperand &MDOp : LoopIdMD->operands()) { 321 if (MDOp == DesiredLoopIdMetadata) { 322 LoopIdMDFound = true; 323 break; 324 } 325 } 326 327 if (!LoopIdMDFound) 328 return false; 329 } 330 } 331 return true; 332 } 333 334 DebugLoc Loop::getStartLoc() const { return getLocRange().getStart(); } 335 336 Loop::LocRange Loop::getLocRange() const { 337 // If we have a debug location in the loop ID, then use it. 338 if (MDNode *LoopID = getLoopID()) { 339 DebugLoc Start; 340 // We use the first DebugLoc in the header as the start location of the loop 341 // and if there is a second DebugLoc in the header we use it as end location 342 // of the loop. 343 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 344 if (DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i))) { 345 if (!Start) 346 Start = DebugLoc(L); 347 else 348 return LocRange(Start, DebugLoc(L)); 349 } 350 } 351 352 if (Start) 353 return LocRange(Start); 354 } 355 356 // Try the pre-header first. 357 if (BasicBlock *PHeadBB = getLoopPreheader()) 358 if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc()) 359 return LocRange(DL); 360 361 // If we have no pre-header or there are no instructions with debug 362 // info in it, try the header. 363 if (BasicBlock *HeadBB = getHeader()) 364 return LocRange(HeadBB->getTerminator()->getDebugLoc()); 365 366 return LocRange(); 367 } 368 369 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 370 LLVM_DUMP_METHOD void Loop::dump() const { print(dbgs()); } 371 372 LLVM_DUMP_METHOD void Loop::dumpVerbose() const { 373 print(dbgs(), /*Depth=*/0, /*Verbose=*/true); 374 } 375 #endif 376 377 //===----------------------------------------------------------------------===// 378 // UnloopUpdater implementation 379 // 380 381 namespace { 382 /// Find the new parent loop for all blocks within the "unloop" whose last 383 /// backedges has just been removed. 384 class UnloopUpdater { 385 Loop &Unloop; 386 LoopInfo *LI; 387 388 LoopBlocksDFS DFS; 389 390 // Map unloop's immediate subloops to their nearest reachable parents. Nested 391 // loops within these subloops will not change parents. However, an immediate 392 // subloop's new parent will be the nearest loop reachable from either its own 393 // exits *or* any of its nested loop's exits. 394 DenseMap<Loop *, Loop *> SubloopParents; 395 396 // Flag the presence of an irreducible backedge whose destination is a block 397 // directly contained by the original unloop. 398 bool FoundIB; 399 400 public: 401 UnloopUpdater(Loop *UL, LoopInfo *LInfo) 402 : Unloop(*UL), LI(LInfo), DFS(UL), FoundIB(false) {} 403 404 void updateBlockParents(); 405 406 void removeBlocksFromAncestors(); 407 408 void updateSubloopParents(); 409 410 protected: 411 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop); 412 }; 413 } // end anonymous namespace 414 415 /// Update the parent loop for all blocks that are directly contained within the 416 /// original "unloop". 417 void UnloopUpdater::updateBlockParents() { 418 if (Unloop.getNumBlocks()) { 419 // Perform a post order CFG traversal of all blocks within this loop, 420 // propagating the nearest loop from successors to predecessors. 421 LoopBlocksTraversal Traversal(DFS, LI); 422 for (BasicBlock *POI : Traversal) { 423 424 Loop *L = LI->getLoopFor(POI); 425 Loop *NL = getNearestLoop(POI, L); 426 427 if (NL != L) { 428 // For reducible loops, NL is now an ancestor of Unloop. 429 assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) && 430 "uninitialized successor"); 431 LI->changeLoopFor(POI, NL); 432 } else { 433 // Or the current block is part of a subloop, in which case its parent 434 // is unchanged. 435 assert((FoundIB || Unloop.contains(L)) && "uninitialized successor"); 436 } 437 } 438 } 439 // Each irreducible loop within the unloop induces a round of iteration using 440 // the DFS result cached by Traversal. 441 bool Changed = FoundIB; 442 for (unsigned NIters = 0; Changed; ++NIters) { 443 assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm"); 444 445 // Iterate over the postorder list of blocks, propagating the nearest loop 446 // from successors to predecessors as before. 447 Changed = false; 448 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(), 449 POE = DFS.endPostorder(); 450 POI != POE; ++POI) { 451 452 Loop *L = LI->getLoopFor(*POI); 453 Loop *NL = getNearestLoop(*POI, L); 454 if (NL != L) { 455 assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) && 456 "uninitialized successor"); 457 LI->changeLoopFor(*POI, NL); 458 Changed = true; 459 } 460 } 461 } 462 } 463 464 /// Remove unloop's blocks from all ancestors below their new parents. 465 void UnloopUpdater::removeBlocksFromAncestors() { 466 // Remove all unloop's blocks (including those in nested subloops) from 467 // ancestors below the new parent loop. 468 for (Loop::block_iterator BI = Unloop.block_begin(), BE = Unloop.block_end(); 469 BI != BE; ++BI) { 470 Loop *OuterParent = LI->getLoopFor(*BI); 471 if (Unloop.contains(OuterParent)) { 472 while (OuterParent->getParentLoop() != &Unloop) 473 OuterParent = OuterParent->getParentLoop(); 474 OuterParent = SubloopParents[OuterParent]; 475 } 476 // Remove blocks from former Ancestors except Unloop itself which will be 477 // deleted. 478 for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent; 479 OldParent = OldParent->getParentLoop()) { 480 assert(OldParent && "new loop is not an ancestor of the original"); 481 OldParent->removeBlockFromLoop(*BI); 482 } 483 } 484 } 485 486 /// Update the parent loop for all subloops directly nested within unloop. 487 void UnloopUpdater::updateSubloopParents() { 488 while (!Unloop.empty()) { 489 Loop *Subloop = *std::prev(Unloop.end()); 490 Unloop.removeChildLoop(std::prev(Unloop.end())); 491 492 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop"); 493 if (Loop *Parent = SubloopParents[Subloop]) 494 Parent->addChildLoop(Subloop); 495 else 496 LI->addTopLevelLoop(Subloop); 497 } 498 } 499 500 /// Return the nearest parent loop among this block's successors. If a successor 501 /// is a subloop header, consider its parent to be the nearest parent of the 502 /// subloop's exits. 503 /// 504 /// For subloop blocks, simply update SubloopParents and return NULL. 505 Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) { 506 507 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and 508 // is considered uninitialized. 509 Loop *NearLoop = BBLoop; 510 511 Loop *Subloop = nullptr; 512 if (NearLoop != &Unloop && Unloop.contains(NearLoop)) { 513 Subloop = NearLoop; 514 // Find the subloop ancestor that is directly contained within Unloop. 515 while (Subloop->getParentLoop() != &Unloop) { 516 Subloop = Subloop->getParentLoop(); 517 assert(Subloop && "subloop is not an ancestor of the original loop"); 518 } 519 // Get the current nearest parent of the Subloop exits, initially Unloop. 520 NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second; 521 } 522 523 succ_iterator I = succ_begin(BB), E = succ_end(BB); 524 if (I == E) { 525 assert(!Subloop && "subloop blocks must have a successor"); 526 NearLoop = nullptr; // unloop blocks may now exit the function. 527 } 528 for (; I != E; ++I) { 529 if (*I == BB) 530 continue; // self loops are uninteresting 531 532 Loop *L = LI->getLoopFor(*I); 533 if (L == &Unloop) { 534 // This successor has not been processed. This path must lead to an 535 // irreducible backedge. 536 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB"); 537 FoundIB = true; 538 } 539 if (L != &Unloop && Unloop.contains(L)) { 540 // Successor is in a subloop. 541 if (Subloop) 542 continue; // Branching within subloops. Ignore it. 543 544 // BB branches from the original into a subloop header. 545 assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops"); 546 547 // Get the current nearest parent of the Subloop's exits. 548 L = SubloopParents[L]; 549 // L could be Unloop if the only exit was an irreducible backedge. 550 } 551 if (L == &Unloop) { 552 continue; 553 } 554 // Handle critical edges from Unloop into a sibling loop. 555 if (L && !L->contains(&Unloop)) { 556 L = L->getParentLoop(); 557 } 558 // Remember the nearest parent loop among successors or subloop exits. 559 if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L)) 560 NearLoop = L; 561 } 562 if (Subloop) { 563 SubloopParents[Subloop] = NearLoop; 564 return BBLoop; 565 } 566 return NearLoop; 567 } 568 569 LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); } 570 571 bool LoopInfo::invalidate(Function &F, const PreservedAnalyses &PA, 572 FunctionAnalysisManager::Invalidator &) { 573 // Check whether the analysis, all analyses on functions, or the function's 574 // CFG have been preserved. 575 auto PAC = PA.getChecker<LoopAnalysis>(); 576 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() || 577 PAC.preservedSet<CFGAnalyses>()); 578 } 579 580 void LoopInfo::erase(Loop *Unloop) { 581 assert(!Unloop->isInvalid() && "Loop has already been erased!"); 582 583 auto InvalidateOnExit = make_scope_exit([&]() { destroy(Unloop); }); 584 585 // First handle the special case of no parent loop to simplify the algorithm. 586 if (!Unloop->getParentLoop()) { 587 // Since BBLoop had no parent, Unloop blocks are no longer in a loop. 588 for (Loop::block_iterator I = Unloop->block_begin(), 589 E = Unloop->block_end(); 590 I != E; ++I) { 591 592 // Don't reparent blocks in subloops. 593 if (getLoopFor(*I) != Unloop) 594 continue; 595 596 // Blocks no longer have a parent but are still referenced by Unloop until 597 // the Unloop object is deleted. 598 changeLoopFor(*I, nullptr); 599 } 600 601 // Remove the loop from the top-level LoopInfo object. 602 for (iterator I = begin();; ++I) { 603 assert(I != end() && "Couldn't find loop"); 604 if (*I == Unloop) { 605 removeLoop(I); 606 break; 607 } 608 } 609 610 // Move all of the subloops to the top-level. 611 while (!Unloop->empty()) 612 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end()))); 613 614 return; 615 } 616 617 // Update the parent loop for all blocks within the loop. Blocks within 618 // subloops will not change parents. 619 UnloopUpdater Updater(Unloop, this); 620 Updater.updateBlockParents(); 621 622 // Remove blocks from former ancestor loops. 623 Updater.removeBlocksFromAncestors(); 624 625 // Add direct subloops as children in their new parent loop. 626 Updater.updateSubloopParents(); 627 628 // Remove unloop from its parent loop. 629 Loop *ParentLoop = Unloop->getParentLoop(); 630 for (Loop::iterator I = ParentLoop->begin();; ++I) { 631 assert(I != ParentLoop->end() && "Couldn't find loop"); 632 if (*I == Unloop) { 633 ParentLoop->removeChildLoop(I); 634 break; 635 } 636 } 637 } 638 639 AnalysisKey LoopAnalysis::Key; 640 641 LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) { 642 // FIXME: Currently we create a LoopInfo from scratch for every function. 643 // This may prove to be too wasteful due to deallocating and re-allocating 644 // memory each time for the underlying map and vector datastructures. At some 645 // point it may prove worthwhile to use a freelist and recycle LoopInfo 646 // objects. I don't want to add that kind of complexity until the scope of 647 // the problem is better understood. 648 LoopInfo LI; 649 LI.analyze(AM.getResult<DominatorTreeAnalysis>(F)); 650 return LI; 651 } 652 653 PreservedAnalyses LoopPrinterPass::run(Function &F, 654 FunctionAnalysisManager &AM) { 655 AM.getResult<LoopAnalysis>(F).print(OS); 656 return PreservedAnalyses::all(); 657 } 658 659 void llvm::printLoop(Loop &L, raw_ostream &OS, const std::string &Banner) { 660 661 if (forcePrintModuleIR()) { 662 // handling -print-module-scope 663 OS << Banner << " (loop: "; 664 L.getHeader()->printAsOperand(OS, false); 665 OS << ")\n"; 666 667 // printing whole module 668 OS << *L.getHeader()->getModule(); 669 return; 670 } 671 672 OS << Banner; 673 674 auto *PreHeader = L.getLoopPreheader(); 675 if (PreHeader) { 676 OS << "\n; Preheader:"; 677 PreHeader->print(OS); 678 OS << "\n; Loop:"; 679 } 680 681 for (auto *Block : L.blocks()) 682 if (Block) 683 Block->print(OS); 684 else 685 OS << "Printing <null> block"; 686 687 SmallVector<BasicBlock *, 8> ExitBlocks; 688 L.getExitBlocks(ExitBlocks); 689 if (!ExitBlocks.empty()) { 690 OS << "\n; Exit blocks"; 691 for (auto *Block : ExitBlocks) 692 if (Block) 693 Block->print(OS); 694 else 695 OS << "Printing <null> block"; 696 } 697 } 698 699 //===----------------------------------------------------------------------===// 700 // LoopInfo implementation 701 // 702 703 char LoopInfoWrapperPass::ID = 0; 704 INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information", 705 true, true) 706 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 707 INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information", 708 true, true) 709 710 bool LoopInfoWrapperPass::runOnFunction(Function &) { 711 releaseMemory(); 712 LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree()); 713 return false; 714 } 715 716 void LoopInfoWrapperPass::verifyAnalysis() const { 717 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the 718 // function each time verifyAnalysis is called is very expensive. The 719 // -verify-loop-info option can enable this. In order to perform some 720 // checking by default, LoopPass has been taught to call verifyLoop manually 721 // during loop pass sequences. 722 if (VerifyLoopInfo) { 723 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 724 LI.verify(DT); 725 } 726 } 727 728 void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 729 AU.setPreservesAll(); 730 AU.addRequired<DominatorTreeWrapperPass>(); 731 } 732 733 void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const { 734 LI.print(OS); 735 } 736 737 PreservedAnalyses LoopVerifierPass::run(Function &F, 738 FunctionAnalysisManager &AM) { 739 LoopInfo &LI = AM.getResult<LoopAnalysis>(F); 740 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 741 LI.verify(DT); 742 return PreservedAnalyses::all(); 743 } 744 745 //===----------------------------------------------------------------------===// 746 // LoopBlocksDFS implementation 747 // 748 749 /// Traverse the loop blocks and store the DFS result. 750 /// Useful for clients that just want the final DFS result and don't need to 751 /// visit blocks during the initial traversal. 752 void LoopBlocksDFS::perform(LoopInfo *LI) { 753 LoopBlocksTraversal Traversal(*this, LI); 754 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(), 755 POE = Traversal.end(); 756 POI != POE; ++POI) 757 ; 758 } 759