LoopInfo.cpp 25 KB

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