LCOV - code coverage report
Current view: top level - lib/Analysis - LoopInfo.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 245 274 89.4 %
Date: 2018-05-20 00:06:23 Functions: 35 40 87.5 %
Legend: Lines: hit not hit

          Line data    Source code
       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      297711 :     VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
      51      297711 :                     cl::Hidden, cl::desc("Verify loop info (time consuming)"));
      52             : 
      53             : //===----------------------------------------------------------------------===//
      54             : // Loop implementation
      55             : //
      56             : 
      57     1511678 : bool Loop::isLoopInvariant(const Value *V) const {
      58             :   if (const Instruction *I = dyn_cast<Instruction>(V))
      59      676816 :     return !contains(I);
      60             :   return true; // All non-instructions are loop invariant
      61             : }
      62             : 
      63      839402 : bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
      64     2981374 :   return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
      65             : }
      66             : 
      67        6060 : bool Loop::makeLoopInvariant(Value *V, bool &Changed,
      68             :                              Instruction *InsertPt) const {
      69             :   if (Instruction *I = dyn_cast<Instruction>(V))
      70        5746 :     return makeLoopInvariant(I, Changed, InsertPt);
      71             :   return true; // All non-instructions are loop-invariant.
      72             : }
      73             : 
      74        7625 : bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
      75             :                              Instruction *InsertPt) const {
      76             :   // Test if the value is already loop-invariant.
      77        7625 :   if (isLoopInvariant(I))
      78             :     return true;
      79        7383 :   if (!isSafeToSpeculativelyExecute(I))
      80             :     return false;
      81        4893 :   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        4462 :   if (!InsertPt) {
      88        1090 :     BasicBlock *Preheader = getLoopPreheader();
      89             :     // Without a preheader, hoisting is not feasible.
      90        1090 :     if (!Preheader)
      91             :       return false;
      92             :     InsertPt = Preheader->getTerminator();
      93             :   }
      94             :   // Don't hoist instructions with loop-variant operands.
      95        9784 :   for (Value *Operand : I->operands())
      96        4811 :     if (!makeLoopInvariant(Operand, Changed, InsertPt))
      97             :       return false;
      98             : 
      99             :   // Hoist.
     100          81 :   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          81 :   Changed = true;
     109          81 :   return true;
     110             : }
     111             : 
     112         339 : 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         339 :   if (PI == pred_end(H))
     120             :     return nullptr; // dead loop
     121             :   Incoming = *PI++;
     122         339 :   if (PI != pred_end(H))
     123             :     return nullptr; // multiple backedges?
     124             : 
     125         331 :   if (contains(Incoming)) {
     126          57 :     if (contains(Backedge))
     127             :       return nullptr;
     128             :     std::swap(Incoming, Backedge);
     129         274 :   } else if (!contains(Backedge))
     130             :     return nullptr;
     131             : 
     132             :   // Loop over all of the PHI nodes, looking for a canonical indvar.
     133         485 :   for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
     134             :     PHINode *PN = cast<PHINode>(I);
     135             :     if (ConstantInt *CI =
     136         351 :             dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
     137         271 :       if (CI->isZero())
     138             :         if (Instruction *Inc =
     139         258 :                 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
     140         502 :           if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
     141             :             if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
     142         238 :               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           0 : static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
     150             :                                DominatorTree &DT) {
     151           0 :   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           0 :     if (I.getType()->isTokenTy())
     156           0 :       continue;
     157             : 
     158           0 :     for (const Use &U : I.uses()) {
     159           0 :       const Instruction *UI = cast<Instruction>(U.getUser());
     160           0 :       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           0 :       if (UserBB != &BB && !L.contains(UserBB) &&
     169           0 :           DT.isReachableFromEntry(UserBB))
     170             :         return false;
     171             :     }
     172             :   }
     173             :   return true;
     174             : }
     175             : 
     176           0 : 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           0 :   });
     181             : }
     182             : 
     183           0 : 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           0 :   return all_of(this->blocks(), [&](const BasicBlock *BB) {
     188           0 :     return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT);
     189           0 :   });
     190             : }
     191             : 
     192       63851 : 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       63851 :   return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
     196             : }
     197             : 
     198             : // Routines that reform the loop CFG and split edges often fail on indirectbr.
     199        4410 : bool Loop::isSafeToClone() const {
     200             :   // Return false if any loop blocks contain indirectbrs, or there are any calls
     201             :   // to noduplicate functions.
     202       62188 :   for (BasicBlock *BB : this->blocks()) {
     203       28892 :     if (isa<IndirectBrInst>(BB->getTerminator()))
     204             :       return false;
     205             : 
     206      396597 :     for (Instruction &I : *BB)
     207      367708 :       if (auto CS = CallSite(&I))
     208       59180 :         if (CS.cannotDuplicate())
     209           2 :           return false;
     210             :   }
     211             :   return true;
     212             : }
     213             : 
     214       51989 : MDNode *Loop::getLoopID() const {
     215             :   MDNode *LoopID = nullptr;
     216       51989 :   if (BasicBlock *Latch = getLoopLatch()) {
     217       51958 :     LoopID = Latch->getTerminator()->getMetadata(LLVMContext::MD_loop);
     218             :   } else {
     219             :     assert(!getLoopLatch() &&
     220             :            "The loop should have no single latch at this point");
     221             :     // Go through each predecessor of the loop header and check the
     222             :     // terminator for the metadata.
     223             :     BasicBlock *H = getHeader();
     224          31 :     for (BasicBlock *BB : this->blocks()) {
     225             :       TerminatorInst *TI = BB->getTerminator();
     226             :       MDNode *MD = nullptr;
     227             : 
     228             :       // Check if this terminator branches to the loop header.
     229          72 :       for (BasicBlock *Successor : TI->successors()) {
     230          57 :         if (Successor == H) {
     231          16 :           MD = TI->getMetadata(LLVMContext::MD_loop);
     232           0 :           break;
     233             :         }
     234             :       }
     235          15 :       if (!MD)
     236             :         return nullptr;
     237             : 
     238           0 :       if (!LoopID)
     239             :         LoopID = MD;
     240           0 :       else if (MD != LoopID)
     241             :         return nullptr;
     242             :     }
     243             :   }
     244       80662 :   if (!LoopID || LoopID->getNumOperands() == 0 ||
     245             :       LoopID->getOperand(0) != LoopID)
     246             :     return nullptr;
     247             :   return LoopID;
     248             : }
     249             : 
     250        4280 : void Loop::setLoopID(MDNode *LoopID) const {
     251             :   assert(LoopID && "Loop ID should not be null");
     252             :   assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
     253             :   assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
     254             : 
     255        4280 :   if (BasicBlock *Latch = getLoopLatch()) {
     256        4280 :     Latch->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
     257        4280 :     return;
     258             :   }
     259             : 
     260             :   assert(!getLoopLatch() &&
     261             :          "The loop should have no single latch at this point");
     262             :   BasicBlock *H = getHeader();
     263           0 :   for (BasicBlock *BB : this->blocks()) {
     264             :     TerminatorInst *TI = BB->getTerminator();
     265           0 :     for (BasicBlock *Successor : TI->successors()) {
     266           0 :       if (Successor == H)
     267           0 :         TI->setMetadata(LLVMContext::MD_loop, LoopID);
     268             :     }
     269             :   }
     270             : }
     271             : 
     272         189 : void Loop::setLoopAlreadyUnrolled() {
     273         189 :   MDNode *LoopID = getLoopID();
     274             :   // First remove any existing loop unrolling metadata.
     275             :   SmallVector<Metadata *, 4> MDs;
     276             :   // Reserve first location for self reference to the LoopID metadata node.
     277         189 :   MDs.push_back(nullptr);
     278             : 
     279         189 :   if (LoopID) {
     280          59 :     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
     281             :       bool IsUnrollMetadata = false;
     282             :       MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
     283             :       if (MD) {
     284             :         const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
     285          60 :         IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
     286             :       }
     287          32 :       if (!IsUnrollMetadata)
     288           8 :         MDs.push_back(LoopID->getOperand(i));
     289             :     }
     290             :   }
     291             : 
     292             :   // Add unroll(disable) metadata to disable future unrolling.
     293         189 :   LLVMContext &Context = getHeader()->getContext();
     294             :   SmallVector<Metadata *, 1> DisableOperands;
     295         189 :   DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
     296             :   MDNode *DisableNode = MDNode::get(Context, DisableOperands);
     297         189 :   MDs.push_back(DisableNode);
     298             : 
     299             :   MDNode *NewLoopID = MDNode::get(Context, MDs);
     300             :   // Set operand 0 to refer to the loop id itself.
     301         189 :   NewLoopID->replaceOperandWith(0, NewLoopID);
     302         189 :   setLoopID(NewLoopID);
     303         189 : }
     304             : 
     305        2554 : bool Loop::isAnnotatedParallel() const {
     306        2554 :   MDNode *DesiredLoopIdMetadata = getLoopID();
     307             : 
     308        2554 :   if (!DesiredLoopIdMetadata)
     309             :     return false;
     310             : 
     311             :   // The loop branch contains the parallel loop metadata. In order to ensure
     312             :   // that any parallel-loop-unaware optimization pass hasn't added loop-carried
     313             :   // dependencies (thus converted the loop back to a sequential loop), check
     314             :   // that all the memory instructions in the loop contain parallelism metadata
     315             :   // that point to the same unique "loop id metadata" the loop branch does.
     316        1418 :   for (BasicBlock *BB : this->blocks()) {
     317        8518 :     for (Instruction &I : *BB) {
     318        8460 :       if (!I.mayReadOrWriteMemory())
     319        7130 :         continue;
     320             : 
     321             :       // The memory instruction can refer to the loop identifier metadata
     322             :       // directly or indirectly through another list metadata (in case of
     323             :       // nested parallel loops). The loop identifier metadata refers to
     324             :       // itself so we can check both cases with the same routine.
     325             :       MDNode *LoopIdMD =
     326             :           I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
     327             : 
     328        1163 :       if (!LoopIdMD)
     329             :         return false;
     330             : 
     331             :       bool LoopIdMDFound = false;
     332          68 :       for (const MDOperand &MDOp : LoopIdMD->operands()) {
     333          52 :         if (MDOp == DesiredLoopIdMetadata) {
     334             :           LoopIdMDFound = true;
     335             :           break;
     336             :         }
     337             :       }
     338             : 
     339          46 :       if (!LoopIdMDFound)
     340             :         return false;
     341             :     }
     342             :   }
     343             :   return true;
     344             : }
     345             : 
     346        9642 : DebugLoc Loop::getStartLoc() const { return getLocRange().getStart(); }
     347             : 
     348        4821 : Loop::LocRange Loop::getLocRange() const {
     349             :   // If we have a debug location in the loop ID, then use it.
     350        4821 :   if (MDNode *LoopID = getLoopID()) {
     351        3743 :     DebugLoc Start;
     352             :     // We use the first DebugLoc in the header as the start location of the loop
     353             :     // and if there is a second DebugLoc in the header we use it as end location
     354             :     // of the loop.
     355        7504 :     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
     356             :       if (DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i))) {
     357        7227 :         if (!Start)
     358        7270 :           Start = DebugLoc(L);
     359             :         else
     360       14368 :           return LocRange(Start, DebugLoc(L));
     361             :       }
     362             :     }
     363             : 
     364         151 :     if (Start)
     365          86 :       return LocRange(Start);
     366             :   }
     367             : 
     368             :   // Try the pre-header first.
     369        1186 :   if (BasicBlock *PHeadBB = getLoopPreheader())
     370        1120 :     if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
     371         572 :       return LocRange(DL);
     372             : 
     373             :   // If we have no pre-header or there are no instructions with debug
     374             :   // info in it, try the header.
     375         900 :   if (BasicBlock *HeadBB = getHeader())
     376        1800 :     return LocRange(HeadBB->getTerminator()->getDebugLoc());
     377             : 
     378             :   return LocRange();
     379             : }
     380             : 
     381       93353 : bool Loop::hasDedicatedExits() const {
     382             :   // Each predecessor of each exit block of a normal loop is contained
     383             :   // within the loop.
     384             :   SmallVector<BasicBlock *, 4> ExitBlocks;
     385       93353 :   getExitBlocks(ExitBlocks);
     386      613797 :   for (BasicBlock *BB : ExitBlocks)
     387      904929 :     for (BasicBlock *Predecessor : predecessors(BB))
     388      384430 :       if (!contains(Predecessor))
     389          55 :         return false;
     390             :   // All the requirements are met.
     391             :   return true;
     392             : }
     393             : 
     394       25514 : void Loop::getUniqueExitBlocks(
     395             :     SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
     396             :   assert(hasDedicatedExits() &&
     397             :          "getUniqueExitBlocks assumes the loop has canonical form exits!");
     398             : 
     399             :   SmallVector<BasicBlock *, 32> SwitchExitBlocks;
     400      311380 :   for (BasicBlock *BB : this->blocks()) {
     401             :     SwitchExitBlocks.clear();
     402      387575 :     for (BasicBlock *Successor : successors(BB)) {
     403             :       // If block is inside the loop then it is not an exit block.
     404      244642 :       if (contains(Successor))
     405      182240 :         continue;
     406             : 
     407       62402 :       pred_iterator PI = pred_begin(Successor);
     408             :       BasicBlock *FirstPred = *PI;
     409             : 
     410             :       // If current basic block is this exit block's first predecessor
     411             :       // then only insert exit block in to the output ExitBlocks vector.
     412             :       // This ensures that same exit block is not inserted twice into
     413             :       // ExitBlocks vector.
     414       62402 :       if (BB != FirstPred)
     415        6153 :         continue;
     416             : 
     417             :       // If a terminator has more then two successors, for example SwitchInst,
     418             :       // then it is possible that there are multiple edges from current block
     419             :       // to one exit block.
     420      112110 :       if (succ_size(BB) <= 2) {
     421       55861 :         ExitBlocks.push_back(Successor);
     422       55861 :         continue;
     423             :       }
     424             : 
     425             :       // In case of multiple edges from current block to exit block, collect
     426             :       // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
     427             :       // duplicate edges.
     428         388 :       if (!is_contained(SwitchExitBlocks, Successor)) {
     429         245 :         SwitchExitBlocks.push_back(Successor);
     430         245 :         ExitBlocks.push_back(Successor);
     431             :       }
     432             :     }
     433             :   }
     434       25514 : }
     435             : 
     436        6478 : BasicBlock *Loop::getUniqueExitBlock() const {
     437             :   SmallVector<BasicBlock *, 8> UniqueExitBlocks;
     438        6478 :   getUniqueExitBlocks(UniqueExitBlocks);
     439        6478 :   if (UniqueExitBlocks.size() == 1)
     440        5326 :     return UniqueExitBlocks[0];
     441             :   return nullptr;
     442             : }
     443             : 
     444             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
     445             : LLVM_DUMP_METHOD void Loop::dump() const { print(dbgs()); }
     446             : 
     447             : LLVM_DUMP_METHOD void Loop::dumpVerbose() const {
     448             :   print(dbgs(), /*Depth=*/0, /*Verbose=*/true);
     449             : }
     450             : #endif
     451             : 
     452             : //===----------------------------------------------------------------------===//
     453             : // UnloopUpdater implementation
     454             : //
     455             : 
     456             : namespace {
     457             : /// Find the new parent loop for all blocks within the "unloop" whose last
     458             : /// backedges has just been removed.
     459          81 : class UnloopUpdater {
     460             :   Loop &Unloop;
     461             :   LoopInfo *LI;
     462             : 
     463             :   LoopBlocksDFS DFS;
     464             : 
     465             :   // Map unloop's immediate subloops to their nearest reachable parents. Nested
     466             :   // loops within these subloops will not change parents. However, an immediate
     467             :   // subloop's new parent will be the nearest loop reachable from either its own
     468             :   // exits *or* any of its nested loop's exits.
     469             :   DenseMap<Loop *, Loop *> SubloopParents;
     470             : 
     471             :   // Flag the presence of an irreducible backedge whose destination is a block
     472             :   // directly contained by the original unloop.
     473             :   bool FoundIB;
     474             : 
     475             : public:
     476             :   UnloopUpdater(Loop *UL, LoopInfo *LInfo)
     477         162 :       : Unloop(*UL), LI(LInfo), DFS(UL), FoundIB(false) {}
     478             : 
     479             :   void updateBlockParents();
     480             : 
     481             :   void removeBlocksFromAncestors();
     482             : 
     483             :   void updateSubloopParents();
     484             : 
     485             : protected:
     486             :   Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
     487             : };
     488             : } // end anonymous namespace
     489             : 
     490             : /// Update the parent loop for all blocks that are directly contained within the
     491             : /// original "unloop".
     492          81 : void UnloopUpdater::updateBlockParents() {
     493         162 :   if (Unloop.getNumBlocks()) {
     494             :     // Perform a post order CFG traversal of all blocks within this loop,
     495             :     // propagating the nearest loop from successors to predecessors.
     496          60 :     LoopBlocksTraversal Traversal(DFS, LI);
     497        1038 :     for (BasicBlock *POI : Traversal) {
     498             : 
     499         306 :       Loop *L = LI->getLoopFor(POI);
     500         306 :       Loop *NL = getNearestLoop(POI, L);
     501             : 
     502         306 :       if (NL != L) {
     503             :         // For reducible loops, NL is now an ancestor of Unloop.
     504             :         assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
     505             :                "uninitialized successor");
     506         239 :         LI->changeLoopFor(POI, NL);
     507             :       } else {
     508             :         // Or the current block is part of a subloop, in which case its parent
     509             :         // is unchanged.
     510             :         assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
     511             :       }
     512             :     }
     513             :   }
     514             :   // Each irreducible loop within the unloop induces a round of iteration using
     515             :   // the DFS result cached by Traversal.
     516          81 :   bool Changed = FoundIB;
     517          89 :   for (unsigned NIters = 0; Changed; ++NIters) {
     518             :     assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
     519             : 
     520             :     // Iterate over the postorder list of blocks, propagating the nearest loop
     521             :     // from successors to predecessors as before.
     522             :     Changed = false;
     523             :     for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
     524             :                                    POE = DFS.endPostorder();
     525          56 :          POI != POE; ++POI) {
     526             : 
     527          52 :       Loop *L = LI->getLoopFor(*POI);
     528          52 :       Loop *NL = getNearestLoop(*POI, L);
     529          52 :       if (NL != L) {
     530             :         assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
     531             :                "uninitialized successor");
     532           6 :         LI->changeLoopFor(*POI, NL);
     533             :         Changed = true;
     534             :       }
     535             :     }
     536             :   }
     537          81 : }
     538             : 
     539             : /// Remove unloop's blocks from all ancestors below their new parents.
     540          81 : void UnloopUpdater::removeBlocksFromAncestors() {
     541             :   // Remove all unloop's blocks (including those in nested subloops) from
     542             :   // ancestors below the new parent loop.
     543         387 :   for (Loop::block_iterator BI = Unloop.block_begin(), BE = Unloop.block_end();
     544         387 :        BI != BE; ++BI) {
     545         612 :     Loop *OuterParent = LI->getLoopFor(*BI);
     546         612 :     if (Unloop.contains(OuterParent)) {
     547         146 :       while (OuterParent->getParentLoop() != &Unloop)
     548           8 :         OuterParent = OuterParent->getParentLoop();
     549         122 :       OuterParent = SubloopParents[OuterParent];
     550             :     }
     551             :     // Remove blocks from former Ancestors except Unloop itself which will be
     552             :     // deleted.
     553         690 :     for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
     554             :          OldParent = OldParent->getParentLoop()) {
     555             :       assert(OldParent && "new loop is not an ancestor of the original");
     556          39 :       OldParent->removeBlockFromLoop(*BI);
     557             :     }
     558             :   }
     559          81 : }
     560             : 
     561             : /// Update the parent loop for all subloops directly nested within unloop.
     562          81 : void UnloopUpdater::updateSubloopParents() {
     563         237 :   while (!Unloop.empty()) {
     564          25 :     Loop *Subloop = *std::prev(Unloop.end());
     565             :     Unloop.removeChildLoop(std::prev(Unloop.end()));
     566             : 
     567             :     assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
     568          50 :     if (Loop *Parent = SubloopParents[Subloop])
     569          21 :       Parent->addChildLoop(Subloop);
     570             :     else
     571           4 :       LI->addTopLevelLoop(Subloop);
     572             :   }
     573          81 : }
     574             : 
     575             : /// Return the nearest parent loop among this block's successors. If a successor
     576             : /// is a subloop header, consider its parent to be the nearest parent of the
     577             : /// subloop's exits.
     578             : ///
     579             : /// For subloop blocks, simply update SubloopParents and return NULL.
     580         358 : Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
     581             : 
     582             :   // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
     583             :   // is considered uninitialized.
     584             :   Loop *NearLoop = BBLoop;
     585             : 
     586         358 :   Loop *Subloop = nullptr;
     587         465 :   if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
     588          61 :     Subloop = NearLoop;
     589             :     // Find the subloop ancestor that is directly contained within Unloop.
     590         146 :     while (Subloop->getParentLoop() != &Unloop) {
     591           8 :       Subloop = Subloop->getParentLoop();
     592             :       assert(Subloop && "subloop is not an ancestor of the original loop");
     593             :     }
     594             :     // Get the current nearest parent of the Subloop exits, initially Unloop.
     595         122 :     NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
     596             :   }
     597             : 
     598         358 :   succ_iterator I = succ_begin(BB), E = succ_end(BB);
     599         358 :   if (I == E) {
     600             :     assert(!Subloop && "subloop blocks must have a successor");
     601             :     NearLoop = nullptr; // unloop blocks may now exit the function.
     602             :   }
     603         906 :   for (; I != E; ++I) {
     604         548 :     if (*I == BB)
     605          92 :       continue; // self loops are uninteresting
     606             : 
     607        1070 :     Loop *L = LI->getLoopFor(*I);
     608         535 :     if (L == &Unloop) {
     609             :       // This successor has not been processed. This path must lead to an
     610             :       // irreducible backedge.
     611             :       assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
     612          10 :       FoundIB = true;
     613             :     }
     614        1060 :     if (L != &Unloop && Unloop.contains(L)) {
     615             :       // Successor is in a subloop.
     616          81 :       if (Subloop)
     617          56 :         continue; // Branching within subloops. Ignore it.
     618             : 
     619             :       // BB branches from the original into a subloop header.
     620             :       assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
     621             : 
     622             :       // Get the current nearest parent of the Subloop's exits.
     623          50 :       L = SubloopParents[L];
     624             :       // L could be Unloop if the only exit was an irreducible backedge.
     625             :     }
     626         479 :     if (L == &Unloop) {
     627          10 :       continue;
     628             :     }
     629             :     // Handle critical edges from Unloop into a sibling loop.
     630         812 :     if (L && !L->contains(&Unloop)) {
     631           4 :       L = L->getParentLoop();
     632             :     }
     633             :     // Remember the nearest parent loop among successors or subloop exits.
     634         636 :     if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
     635         395 :       NearLoop = L;
     636             :   }
     637         358 :   if (Subloop) {
     638         122 :     SubloopParents[Subloop] = NearLoop;
     639          61 :     return BBLoop;
     640             :   }
     641             :   return NearLoop;
     642             : }
     643             : 
     644         400 : LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); }
     645             : 
     646        1289 : bool LoopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
     647             :                           FunctionAnalysisManager::Invalidator &) {
     648             :   // Check whether the analysis, all analyses on functions, or the function's
     649             :   // CFG have been preserved.
     650             :   auto PAC = PA.getChecker<LoopAnalysis>();
     651        2040 :   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
     652        2040 :            PAC.preservedSet<CFGAnalyses>());
     653             : }
     654             : 
     655         474 : void LoopInfo::erase(Loop *Unloop) {
     656             :   assert(!Unloop->isInvalid() && "Loop has already been erased!");
     657             : 
     658             :   auto InvalidateOnExit = make_scope_exit([&]() { destroy(Unloop); });
     659             : 
     660             :   // First handle the special case of no parent loop to simplify the algorithm.
     661         948 :   if (!Unloop->getParentLoop()) {
     662             :     // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
     663        1754 :     for (Loop::block_iterator I = Unloop->block_begin(),
     664             :                               E = Unloop->block_end();
     665        2147 :          I != E; ++I) {
     666             : 
     667             :       // Don't reparent blocks in subloops.
     668        3508 :       if (getLoopFor(*I) != Unloop)
     669         172 :         continue;
     670             : 
     671             :       // Blocks no longer have a parent but are still referenced by Unloop until
     672             :       // the Unloop object is deleted.
     673        1582 :       changeLoopFor(*I, nullptr);
     674             :     }
     675             : 
     676             :     // Remove the loop from the top-level LoopInfo object.
     677             :     for (iterator I = begin();; ++I) {
     678             :       assert(I != end() && "Couldn't find loop");
     679         469 :       if (*I == Unloop) {
     680             :         removeLoop(I);
     681             :         break;
     682             :       }
     683             :     }
     684             : 
     685             :     // Move all of the subloops to the top-level.
     686         429 :     while (!Unloop->empty())
     687             :       addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
     688             : 
     689             :     return;
     690             :   }
     691             : 
     692             :   // Update the parent loop for all blocks within the loop. Blocks within
     693             :   // subloops will not change parents.
     694             :   UnloopUpdater Updater(Unloop, this);
     695          81 :   Updater.updateBlockParents();
     696             : 
     697             :   // Remove blocks from former ancestor loops.
     698          81 :   Updater.removeBlocksFromAncestors();
     699             : 
     700             :   // Add direct subloops as children in their new parent loop.
     701          81 :   Updater.updateSubloopParents();
     702             : 
     703             :   // Remove unloop from its parent loop.
     704             :   Loop *ParentLoop = Unloop->getParentLoop();
     705             :   for (Loop::iterator I = ParentLoop->begin();; ++I) {
     706             :     assert(I != ParentLoop->end() && "Couldn't find loop");
     707          90 :     if (*I == Unloop) {
     708             :       ParentLoop->removeChildLoop(I);
     709             :       break;
     710             :     }
     711             :   }
     712             : }
     713             : 
     714             : AnalysisKey LoopAnalysis::Key;
     715             : 
     716        1613 : LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
     717             :   // FIXME: Currently we create a LoopInfo from scratch for every function.
     718             :   // This may prove to be too wasteful due to deallocating and re-allocating
     719             :   // memory each time for the underlying map and vector datastructures. At some
     720             :   // point it may prove worthwhile to use a freelist and recycle LoopInfo
     721             :   // objects. I don't want to add that kind of complexity until the scope of
     722             :   // the problem is better understood.
     723             :   LoopInfo LI;
     724        1613 :   LI.analyze(AM.getResult<DominatorTreeAnalysis>(F));
     725        1613 :   return LI;
     726             : }
     727             : 
     728           1 : PreservedAnalyses LoopPrinterPass::run(Function &F,
     729             :                                        FunctionAnalysisManager &AM) {
     730           1 :   AM.getResult<LoopAnalysis>(F).print(OS);
     731           1 :   return PreservedAnalyses::all();
     732             : }
     733             : 
     734           4 : void llvm::printLoop(Loop &L, raw_ostream &OS, const std::string &Banner) {
     735             : 
     736           4 :   if (forcePrintModuleIR()) {
     737             :     // handling -print-module-scope
     738           1 :     OS << Banner << " (loop: ";
     739           1 :     L.getHeader()->printAsOperand(OS, false);
     740           1 :     OS << ")\n";
     741             : 
     742             :     // printing whole module
     743             :     OS << *L.getHeader()->getModule();
     744           1 :     return;
     745             :   }
     746             : 
     747             :   OS << Banner;
     748             : 
     749           3 :   auto *PreHeader = L.getLoopPreheader();
     750           3 :   if (PreHeader) {
     751           3 :     OS << "\n; Preheader:";
     752           3 :     PreHeader->print(OS);
     753           3 :     OS << "\n; Loop:";
     754             :   }
     755             : 
     756          11 :   for (auto *Block : L.blocks())
     757           4 :     if (Block)
     758           4 :       Block->print(OS);
     759             :     else
     760           0 :       OS << "Printing <null> block";
     761             : 
     762             :   SmallVector<BasicBlock *, 8> ExitBlocks;
     763           3 :   L.getExitBlocks(ExitBlocks);
     764           3 :   if (!ExitBlocks.empty()) {
     765           3 :     OS << "\n; Exit blocks";
     766           9 :     for (auto *Block : ExitBlocks)
     767           3 :       if (Block)
     768           3 :         Block->print(OS);
     769             :       else
     770           0 :         OS << "Printing <null> block";
     771             :   }
     772             : }
     773             : 
     774             : //===----------------------------------------------------------------------===//
     775             : // LoopInfo implementation
     776             : //
     777             : 
     778             : char LoopInfoWrapperPass::ID = 0;
     779       75359 : INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
     780             :                       true, true)
     781       75359 : INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
     782     4629186 : INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
     783             :                     true, true)
     784             : 
     785     1132565 : bool LoopInfoWrapperPass::runOnFunction(Function &) {
     786     1132565 :   releaseMemory();
     787     1132565 :   LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
     788     1132565 :   return false;
     789             : }
     790             : 
     791           0 : void LoopInfoWrapperPass::verifyAnalysis() const {
     792             :   // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
     793             :   // function each time verifyAnalysis is called is very expensive. The
     794             :   // -verify-loop-info option can enable this. In order to perform some
     795             :   // checking by default, LoopPass has been taught to call verifyLoop manually
     796             :   // during loop pass sequences.
     797           0 :   if (VerifyLoopInfo) {
     798           0 :     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
     799           0 :     LI.verify(DT);
     800             :   }
     801           0 : }
     802             : 
     803      106988 : void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
     804             :   AU.setPreservesAll();
     805             :   AU.addRequired<DominatorTreeWrapperPass>();
     806      106988 : }
     807             : 
     808           9 : void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
     809           9 :   LI.print(OS);
     810           9 : }
     811             : 
     812          66 : PreservedAnalyses LoopVerifierPass::run(Function &F,
     813             :                                         FunctionAnalysisManager &AM) {
     814             :   LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
     815             :   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
     816          66 :   LI.verify(DT);
     817          66 :   return PreservedAnalyses::all();
     818             : }
     819             : 
     820             : //===----------------------------------------------------------------------===//
     821             : // LoopBlocksDFS implementation
     822             : //
     823             : 
     824             : /// Traverse the loop blocks and store the DFS result.
     825             : /// Useful for clients that just want the final DFS result and don't need to
     826             : /// visit blocks during the initial traversal.
     827        6440 : void LoopBlocksDFS::perform(LoopInfo *LI) {
     828             :   LoopBlocksTraversal Traversal(*this, LI);
     829       26930 :   for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
     830             :                                         POE = Traversal.end();
     831       26930 :        POI != POE; ++POI)
     832             :     ;
     833      304151 : }

Generated by: LCOV version 1.13