LoopInfo.cpp 26 KB

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