LoopInfo.cpp 27 KB

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