LoopInfo.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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/SmallPtrSet.h"
  19. #include "llvm/Analysis/LoopInfoImpl.h"
  20. #include "llvm/Analysis/LoopIterator.h"
  21. #include "llvm/Analysis/ValueTracking.h"
  22. #include "llvm/IR/CFG.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/Dominators.h"
  25. #include "llvm/IR/Instructions.h"
  26. #include "llvm/IR/LLVMContext.h"
  27. #include "llvm/IR/Metadata.h"
  28. #include "llvm/IR/PassManager.h"
  29. #include "llvm/Support/CommandLine.h"
  30. #include "llvm/Support/Debug.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include <algorithm>
  33. using namespace llvm;
  34. // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
  35. template class llvm::LoopBase<BasicBlock, Loop>;
  36. template class llvm::LoopInfoBase<BasicBlock, Loop>;
  37. // Always verify loopinfo if expensive checking is enabled.
  38. #ifdef XDEBUG
  39. static bool VerifyLoopInfo = true;
  40. #else
  41. static bool VerifyLoopInfo = false;
  42. #endif
  43. static cl::opt<bool,true>
  44. VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
  45. cl::desc("Verify loop info (time consuming)"));
  46. // Loop identifier metadata name.
  47. static const char *const LoopMDName = "llvm.loop";
  48. //===----------------------------------------------------------------------===//
  49. // Loop implementation
  50. //
  51. /// isLoopInvariant - Return true if the specified value is loop invariant
  52. ///
  53. bool Loop::isLoopInvariant(const Value *V) const {
  54. if (const Instruction *I = dyn_cast<Instruction>(V))
  55. return !contains(I);
  56. return true; // All non-instructions are loop invariant
  57. }
  58. /// hasLoopInvariantOperands - Return true if all the operands of the
  59. /// specified instruction are loop invariant.
  60. bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
  61. return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
  62. }
  63. /// makeLoopInvariant - If the given value is an instruciton inside of the
  64. /// loop and it can be hoisted, do so to make it trivially loop-invariant.
  65. /// Return true if the value after any hoisting is loop invariant. This
  66. /// function can be used as a slightly more aggressive replacement for
  67. /// isLoopInvariant.
  68. ///
  69. /// If InsertPt is specified, it is the point to hoist instructions to.
  70. /// If null, the terminator of the loop preheader is used.
  71. ///
  72. bool Loop::makeLoopInvariant(Value *V, bool &Changed,
  73. Instruction *InsertPt) const {
  74. if (Instruction *I = dyn_cast<Instruction>(V))
  75. return makeLoopInvariant(I, Changed, InsertPt);
  76. return true; // All non-instructions are loop-invariant.
  77. }
  78. /// makeLoopInvariant - If the given instruction is inside of the
  79. /// loop and it can be hoisted, do so to make it trivially loop-invariant.
  80. /// Return true if the instruction after any hoisting is loop invariant. This
  81. /// function can be used as a slightly more aggressive replacement for
  82. /// isLoopInvariant.
  83. ///
  84. /// If InsertPt is specified, it is the point to hoist instructions to.
  85. /// If null, the terminator of the loop preheader is used.
  86. ///
  87. bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
  88. Instruction *InsertPt) const {
  89. // Test if the value is already loop-invariant.
  90. if (isLoopInvariant(I))
  91. return true;
  92. if (!isSafeToSpeculativelyExecute(I))
  93. return false;
  94. if (I->mayReadFromMemory())
  95. return false;
  96. // The landingpad instruction is immobile.
  97. if (isa<LandingPadInst>(I))
  98. return false;
  99. // Determine the insertion point, unless one was given.
  100. if (!InsertPt) {
  101. BasicBlock *Preheader = getLoopPreheader();
  102. // Without a preheader, hoisting is not feasible.
  103. if (!Preheader)
  104. return false;
  105. InsertPt = Preheader->getTerminator();
  106. }
  107. // Don't hoist instructions with loop-variant operands.
  108. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  109. if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
  110. return false;
  111. // Hoist.
  112. I->moveBefore(InsertPt);
  113. Changed = true;
  114. return true;
  115. }
  116. /// getCanonicalInductionVariable - Check to see if the loop has a canonical
  117. /// induction variable: an integer recurrence that starts at 0 and increments
  118. /// by one each time through the loop. If so, return the phi node that
  119. /// corresponds to it.
  120. ///
  121. /// The IndVarSimplify pass transforms loops to have a canonical induction
  122. /// variable.
  123. ///
  124. PHINode *Loop::getCanonicalInductionVariable() const {
  125. BasicBlock *H = getHeader();
  126. BasicBlock *Incoming = nullptr, *Backedge = nullptr;
  127. pred_iterator PI = pred_begin(H);
  128. assert(PI != pred_end(H) &&
  129. "Loop must have at least one backedge!");
  130. Backedge = *PI++;
  131. if (PI == pred_end(H)) return nullptr; // dead loop
  132. Incoming = *PI++;
  133. if (PI != pred_end(H)) return nullptr; // multiple backedges?
  134. if (contains(Incoming)) {
  135. if (contains(Backedge))
  136. return nullptr;
  137. std::swap(Incoming, Backedge);
  138. } else if (!contains(Backedge))
  139. return nullptr;
  140. // Loop over all of the PHI nodes, looking for a canonical indvar.
  141. for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
  142. PHINode *PN = cast<PHINode>(I);
  143. if (ConstantInt *CI =
  144. dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
  145. if (CI->isNullValue())
  146. if (Instruction *Inc =
  147. dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
  148. if (Inc->getOpcode() == Instruction::Add &&
  149. Inc->getOperand(0) == PN)
  150. if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
  151. if (CI->equalsInt(1))
  152. return PN;
  153. }
  154. return nullptr;
  155. }
  156. /// isLCSSAForm - Return true if the Loop is in LCSSA form
  157. bool Loop::isLCSSAForm(DominatorTree &DT) const {
  158. for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
  159. BasicBlock *BB = *BI;
  160. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I)
  161. for (Use &U : I->uses()) {
  162. Instruction *UI = cast<Instruction>(U.getUser());
  163. BasicBlock *UserBB = UI->getParent();
  164. if (PHINode *P = dyn_cast<PHINode>(UI))
  165. UserBB = P->getIncomingBlock(U);
  166. // Check the current block, as a fast-path, before checking whether
  167. // the use is anywhere in the loop. Most values are used in the same
  168. // block they are defined in. Also, blocks not reachable from the
  169. // entry are special; uses in them don't need to go through PHIs.
  170. if (UserBB != BB &&
  171. !contains(UserBB) &&
  172. DT.isReachableFromEntry(UserBB))
  173. return false;
  174. }
  175. }
  176. return true;
  177. }
  178. /// isLoopSimplifyForm - Return true if the Loop is in the form that
  179. /// the LoopSimplify form transforms loops to, which is sometimes called
  180. /// normal form.
  181. bool Loop::isLoopSimplifyForm() const {
  182. // Normal-form loops have a preheader, a single backedge, and all of their
  183. // exits have all their predecessors inside the loop.
  184. return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
  185. }
  186. /// isSafeToClone - Return true if the loop body is safe to clone in practice.
  187. /// Routines that reform the loop CFG and split edges often fail on indirectbr.
  188. bool Loop::isSafeToClone() const {
  189. // Return false if any loop blocks contain indirectbrs, or there are any calls
  190. // to noduplicate functions.
  191. for (Loop::block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
  192. if (isa<IndirectBrInst>((*I)->getTerminator()))
  193. return false;
  194. if (const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator()))
  195. if (II->cannotDuplicate())
  196. return false;
  197. for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end(); BI != BE; ++BI) {
  198. if (const CallInst *CI = dyn_cast<CallInst>(BI)) {
  199. if (CI->cannotDuplicate())
  200. return false;
  201. }
  202. }
  203. }
  204. return true;
  205. }
  206. MDNode *Loop::getLoopID() const {
  207. MDNode *LoopID = nullptr;
  208. if (isLoopSimplifyForm()) {
  209. LoopID = getLoopLatch()->getTerminator()->getMetadata(LoopMDName);
  210. } else {
  211. // Go through each predecessor of the loop header and check the
  212. // terminator for the metadata.
  213. BasicBlock *H = getHeader();
  214. for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
  215. TerminatorInst *TI = (*I)->getTerminator();
  216. MDNode *MD = nullptr;
  217. // Check if this terminator branches to the loop header.
  218. for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
  219. if (TI->getSuccessor(i) == H) {
  220. MD = TI->getMetadata(LoopMDName);
  221. break;
  222. }
  223. }
  224. if (!MD)
  225. return nullptr;
  226. if (!LoopID)
  227. LoopID = MD;
  228. else if (MD != LoopID)
  229. return nullptr;
  230. }
  231. }
  232. if (!LoopID || LoopID->getNumOperands() == 0 ||
  233. LoopID->getOperand(0) != LoopID)
  234. return nullptr;
  235. return LoopID;
  236. }
  237. void Loop::setLoopID(MDNode *LoopID) const {
  238. assert(LoopID && "Loop ID should not be null");
  239. assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
  240. assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
  241. if (isLoopSimplifyForm()) {
  242. getLoopLatch()->getTerminator()->setMetadata(LoopMDName, LoopID);
  243. return;
  244. }
  245. BasicBlock *H = getHeader();
  246. for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
  247. TerminatorInst *TI = (*I)->getTerminator();
  248. for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
  249. if (TI->getSuccessor(i) == H)
  250. TI->setMetadata(LoopMDName, LoopID);
  251. }
  252. }
  253. }
  254. bool Loop::isAnnotatedParallel() const {
  255. MDNode *desiredLoopIdMetadata = getLoopID();
  256. if (!desiredLoopIdMetadata)
  257. return false;
  258. // The loop branch contains the parallel loop metadata. In order to ensure
  259. // that any parallel-loop-unaware optimization pass hasn't added loop-carried
  260. // dependencies (thus converted the loop back to a sequential loop), check
  261. // that all the memory instructions in the loop contain parallelism metadata
  262. // that point to the same unique "loop id metadata" the loop branch does.
  263. for (block_iterator BB = block_begin(), BE = block_end(); BB != BE; ++BB) {
  264. for (BasicBlock::iterator II = (*BB)->begin(), EE = (*BB)->end();
  265. II != EE; II++) {
  266. if (!II->mayReadOrWriteMemory())
  267. continue;
  268. // The memory instruction can refer to the loop identifier metadata
  269. // directly or indirectly through another list metadata (in case of
  270. // nested parallel loops). The loop identifier metadata refers to
  271. // itself so we can check both cases with the same routine.
  272. MDNode *loopIdMD =
  273. II->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
  274. if (!loopIdMD)
  275. return false;
  276. bool loopIdMDFound = false;
  277. for (unsigned i = 0, e = loopIdMD->getNumOperands(); i < e; ++i) {
  278. if (loopIdMD->getOperand(i) == desiredLoopIdMetadata) {
  279. loopIdMDFound = true;
  280. break;
  281. }
  282. }
  283. if (!loopIdMDFound)
  284. return false;
  285. }
  286. }
  287. return true;
  288. }
  289. /// hasDedicatedExits - Return true if no exit block for the loop
  290. /// has a predecessor that is outside the loop.
  291. bool Loop::hasDedicatedExits() const {
  292. // Each predecessor of each exit block of a normal loop is contained
  293. // within the loop.
  294. SmallVector<BasicBlock *, 4> ExitBlocks;
  295. getExitBlocks(ExitBlocks);
  296. for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
  297. for (pred_iterator PI = pred_begin(ExitBlocks[i]),
  298. PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
  299. if (!contains(*PI))
  300. return false;
  301. // All the requirements are met.
  302. return true;
  303. }
  304. /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
  305. /// These are the blocks _outside of the current loop_ which are branched to.
  306. /// This assumes that loop exits are in canonical form.
  307. ///
  308. void
  309. Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
  310. assert(hasDedicatedExits() &&
  311. "getUniqueExitBlocks assumes the loop has canonical form exits!");
  312. SmallVector<BasicBlock *, 32> switchExitBlocks;
  313. for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
  314. BasicBlock *current = *BI;
  315. switchExitBlocks.clear();
  316. for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
  317. // If block is inside the loop then it is not a exit block.
  318. if (contains(*I))
  319. continue;
  320. pred_iterator PI = pred_begin(*I);
  321. BasicBlock *firstPred = *PI;
  322. // If current basic block is this exit block's first predecessor
  323. // then only insert exit block in to the output ExitBlocks vector.
  324. // This ensures that same exit block is not inserted twice into
  325. // ExitBlocks vector.
  326. if (current != firstPred)
  327. continue;
  328. // If a terminator has more then two successors, for example SwitchInst,
  329. // then it is possible that there are multiple edges from current block
  330. // to one exit block.
  331. if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
  332. ExitBlocks.push_back(*I);
  333. continue;
  334. }
  335. // In case of multiple edges from current block to exit block, collect
  336. // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
  337. // duplicate edges.
  338. if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
  339. == switchExitBlocks.end()) {
  340. switchExitBlocks.push_back(*I);
  341. ExitBlocks.push_back(*I);
  342. }
  343. }
  344. }
  345. }
  346. /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
  347. /// block, return that block. Otherwise return null.
  348. BasicBlock *Loop::getUniqueExitBlock() const {
  349. SmallVector<BasicBlock *, 8> UniqueExitBlocks;
  350. getUniqueExitBlocks(UniqueExitBlocks);
  351. if (UniqueExitBlocks.size() == 1)
  352. return UniqueExitBlocks[0];
  353. return nullptr;
  354. }
  355. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  356. void Loop::dump() const {
  357. print(dbgs());
  358. }
  359. #endif
  360. //===----------------------------------------------------------------------===//
  361. // UnloopUpdater implementation
  362. //
  363. namespace {
  364. /// Find the new parent loop for all blocks within the "unloop" whose last
  365. /// backedges has just been removed.
  366. class UnloopUpdater {
  367. Loop *Unloop;
  368. LoopInfo *LI;
  369. LoopBlocksDFS DFS;
  370. // Map unloop's immediate subloops to their nearest reachable parents. Nested
  371. // loops within these subloops will not change parents. However, an immediate
  372. // subloop's new parent will be the nearest loop reachable from either its own
  373. // exits *or* any of its nested loop's exits.
  374. DenseMap<Loop*, Loop*> SubloopParents;
  375. // Flag the presence of an irreducible backedge whose destination is a block
  376. // directly contained by the original unloop.
  377. bool FoundIB;
  378. public:
  379. UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
  380. Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
  381. void updateBlockParents();
  382. void removeBlocksFromAncestors();
  383. void updateSubloopParents();
  384. protected:
  385. Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
  386. };
  387. } // end anonymous namespace
  388. /// updateBlockParents - Update the parent loop for all blocks that are directly
  389. /// contained within the original "unloop".
  390. void UnloopUpdater::updateBlockParents() {
  391. if (Unloop->getNumBlocks()) {
  392. // Perform a post order CFG traversal of all blocks within this loop,
  393. // propagating the nearest loop from sucessors to predecessors.
  394. LoopBlocksTraversal Traversal(DFS, LI);
  395. for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
  396. POE = Traversal.end(); POI != POE; ++POI) {
  397. Loop *L = LI->getLoopFor(*POI);
  398. Loop *NL = getNearestLoop(*POI, L);
  399. if (NL != L) {
  400. // For reducible loops, NL is now an ancestor of Unloop.
  401. assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
  402. "uninitialized successor");
  403. LI->changeLoopFor(*POI, NL);
  404. }
  405. else {
  406. // Or the current block is part of a subloop, in which case its parent
  407. // is unchanged.
  408. assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
  409. }
  410. }
  411. }
  412. // Each irreducible loop within the unloop induces a round of iteration using
  413. // the DFS result cached by Traversal.
  414. bool Changed = FoundIB;
  415. for (unsigned NIters = 0; Changed; ++NIters) {
  416. assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
  417. // Iterate over the postorder list of blocks, propagating the nearest loop
  418. // from successors to predecessors as before.
  419. Changed = false;
  420. for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
  421. POE = DFS.endPostorder(); POI != POE; ++POI) {
  422. Loop *L = LI->getLoopFor(*POI);
  423. Loop *NL = getNearestLoop(*POI, L);
  424. if (NL != L) {
  425. assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
  426. "uninitialized successor");
  427. LI->changeLoopFor(*POI, NL);
  428. Changed = true;
  429. }
  430. }
  431. }
  432. }
  433. /// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
  434. /// their new parents.
  435. void UnloopUpdater::removeBlocksFromAncestors() {
  436. // Remove all unloop's blocks (including those in nested subloops) from
  437. // ancestors below the new parent loop.
  438. for (Loop::block_iterator BI = Unloop->block_begin(),
  439. BE = Unloop->block_end(); BI != BE; ++BI) {
  440. Loop *OuterParent = LI->getLoopFor(*BI);
  441. if (Unloop->contains(OuterParent)) {
  442. while (OuterParent->getParentLoop() != Unloop)
  443. OuterParent = OuterParent->getParentLoop();
  444. OuterParent = SubloopParents[OuterParent];
  445. }
  446. // Remove blocks from former Ancestors except Unloop itself which will be
  447. // deleted.
  448. for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
  449. OldParent = OldParent->getParentLoop()) {
  450. assert(OldParent && "new loop is not an ancestor of the original");
  451. OldParent->removeBlockFromLoop(*BI);
  452. }
  453. }
  454. }
  455. /// updateSubloopParents - Update the parent loop for all subloops directly
  456. /// nested within unloop.
  457. void UnloopUpdater::updateSubloopParents() {
  458. while (!Unloop->empty()) {
  459. Loop *Subloop = *std::prev(Unloop->end());
  460. Unloop->removeChildLoop(std::prev(Unloop->end()));
  461. assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
  462. if (Loop *Parent = SubloopParents[Subloop])
  463. Parent->addChildLoop(Subloop);
  464. else
  465. LI->addTopLevelLoop(Subloop);
  466. }
  467. }
  468. /// getNearestLoop - Return the nearest parent loop among this block's
  469. /// successors. If a successor is a subloop header, consider its parent to be
  470. /// the nearest parent of the subloop's exits.
  471. ///
  472. /// For subloop blocks, simply update SubloopParents and return NULL.
  473. Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
  474. // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
  475. // is considered uninitialized.
  476. Loop *NearLoop = BBLoop;
  477. Loop *Subloop = nullptr;
  478. if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
  479. Subloop = NearLoop;
  480. // Find the subloop ancestor that is directly contained within Unloop.
  481. while (Subloop->getParentLoop() != Unloop) {
  482. Subloop = Subloop->getParentLoop();
  483. assert(Subloop && "subloop is not an ancestor of the original loop");
  484. }
  485. // Get the current nearest parent of the Subloop exits, initially Unloop.
  486. NearLoop =
  487. SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second;
  488. }
  489. succ_iterator I = succ_begin(BB), E = succ_end(BB);
  490. if (I == E) {
  491. assert(!Subloop && "subloop blocks must have a successor");
  492. NearLoop = nullptr; // unloop blocks may now exit the function.
  493. }
  494. for (; I != E; ++I) {
  495. if (*I == BB)
  496. continue; // self loops are uninteresting
  497. Loop *L = LI->getLoopFor(*I);
  498. if (L == Unloop) {
  499. // This successor has not been processed. This path must lead to an
  500. // irreducible backedge.
  501. assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
  502. FoundIB = true;
  503. }
  504. if (L != Unloop && Unloop->contains(L)) {
  505. // Successor is in a subloop.
  506. if (Subloop)
  507. continue; // Branching within subloops. Ignore it.
  508. // BB branches from the original into a subloop header.
  509. assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
  510. // Get the current nearest parent of the Subloop's exits.
  511. L = SubloopParents[L];
  512. // L could be Unloop if the only exit was an irreducible backedge.
  513. }
  514. if (L == Unloop) {
  515. continue;
  516. }
  517. // Handle critical edges from Unloop into a sibling loop.
  518. if (L && !L->contains(Unloop)) {
  519. L = L->getParentLoop();
  520. }
  521. // Remember the nearest parent loop among successors or subloop exits.
  522. if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
  523. NearLoop = L;
  524. }
  525. if (Subloop) {
  526. SubloopParents[Subloop] = NearLoop;
  527. return BBLoop;
  528. }
  529. return NearLoop;
  530. }
  531. /// updateUnloop - The last backedge has been removed from a loop--now the
  532. /// "unloop". Find a new parent for the blocks contained within unloop and
  533. /// update the loop tree. We don't necessarily have valid dominators at this
  534. /// point, but LoopInfo is still valid except for the removal of this loop.
  535. ///
  536. /// Note that Unloop may now be an empty loop. Calling Loop::getHeader without
  537. /// checking first is illegal.
  538. void LoopInfo::updateUnloop(Loop *Unloop) {
  539. // First handle the special case of no parent loop to simplify the algorithm.
  540. if (!Unloop->getParentLoop()) {
  541. // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
  542. for (Loop::block_iterator I = Unloop->block_begin(),
  543. E = Unloop->block_end();
  544. I != E; ++I) {
  545. // Don't reparent blocks in subloops.
  546. if (getLoopFor(*I) != Unloop)
  547. continue;
  548. // Blocks no longer have a parent but are still referenced by Unloop until
  549. // the Unloop object is deleted.
  550. changeLoopFor(*I, nullptr);
  551. }
  552. // Remove the loop from the top-level LoopInfo object.
  553. for (iterator I = begin();; ++I) {
  554. assert(I != end() && "Couldn't find loop");
  555. if (*I == Unloop) {
  556. removeLoop(I);
  557. break;
  558. }
  559. }
  560. // Move all of the subloops to the top-level.
  561. while (!Unloop->empty())
  562. addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
  563. return;
  564. }
  565. // Update the parent loop for all blocks within the loop. Blocks within
  566. // subloops will not change parents.
  567. UnloopUpdater Updater(Unloop, this);
  568. Updater.updateBlockParents();
  569. // Remove blocks from former ancestor loops.
  570. Updater.removeBlocksFromAncestors();
  571. // Add direct subloops as children in their new parent loop.
  572. Updater.updateSubloopParents();
  573. // Remove unloop from its parent loop.
  574. Loop *ParentLoop = Unloop->getParentLoop();
  575. for (Loop::iterator I = ParentLoop->begin();; ++I) {
  576. assert(I != ParentLoop->end() && "Couldn't find loop");
  577. if (*I == Unloop) {
  578. ParentLoop->removeChildLoop(I);
  579. break;
  580. }
  581. }
  582. }
  583. char LoopAnalysis::PassID;
  584. LoopInfo LoopAnalysis::run(Function &F, AnalysisManager<Function> *AM) {
  585. // FIXME: Currently we create a LoopInfo from scratch for every function.
  586. // This may prove to be too wasteful due to deallocating and re-allocating
  587. // memory each time for the underlying map and vector datastructures. At some
  588. // point it may prove worthwhile to use a freelist and recycle LoopInfo
  589. // objects. I don't want to add that kind of complexity until the scope of
  590. // the problem is better understood.
  591. LoopInfo LI;
  592. LI.Analyze(AM->getResult<DominatorTreeAnalysis>(F));
  593. return LI;
  594. }
  595. PreservedAnalyses LoopPrinterPass::run(Function &F,
  596. AnalysisManager<Function> *AM) {
  597. AM->getResult<LoopAnalysis>(F).print(OS);
  598. return PreservedAnalyses::all();
  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. LI.verify();
  622. }
  623. void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
  624. AU.setPreservesAll();
  625. AU.addRequired<DominatorTreeWrapperPass>();
  626. }
  627. void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
  628. LI.print(OS);
  629. }
  630. //===----------------------------------------------------------------------===//
  631. // LoopBlocksDFS implementation
  632. //
  633. /// Traverse the loop blocks and store the DFS result.
  634. /// Useful for clients that just want the final DFS result and don't need to
  635. /// visit blocks during the initial traversal.
  636. void LoopBlocksDFS::perform(LoopInfo *LI) {
  637. LoopBlocksTraversal Traversal(*this, LI);
  638. for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
  639. POE = Traversal.end(); POI != POE; ++POI) ;
  640. }