LoopInfo.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  1. //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the LoopInfo class that is used to identify natural loops
  10. // and determine the loop depth of various nodes of the CFG. Note that the
  11. // loops identified may actually be several natural loops that share the same
  12. // header node... not just a single natural loop.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Analysis/LoopInfo.h"
  16. #include "llvm/ADT/ScopeExit.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/Analysis/IVDescriptors.h"
  19. #include "llvm/Analysis/LoopInfoImpl.h"
  20. #include "llvm/Analysis/LoopIterator.h"
  21. #include "llvm/Analysis/LoopNestAnalysis.h"
  22. #include "llvm/Analysis/MemorySSA.h"
  23. #include "llvm/Analysis/MemorySSAUpdater.h"
  24. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  25. #include "llvm/Analysis/ValueTracking.h"
  26. #include "llvm/Config/llvm-config.h"
  27. #include "llvm/IR/CFG.h"
  28. #include "llvm/IR/Constants.h"
  29. #include "llvm/IR/DebugLoc.h"
  30. #include "llvm/IR/Dominators.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/LLVMContext.h"
  33. #include "llvm/IR/Metadata.h"
  34. #include "llvm/IR/PassManager.h"
  35. #include "llvm/IR/PrintPasses.h"
  36. #include "llvm/InitializePasses.h"
  37. #include "llvm/Support/CommandLine.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. using namespace llvm;
  40. // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
  41. template class llvm::LoopBase<BasicBlock, Loop>;
  42. template class llvm::LoopInfoBase<BasicBlock, Loop>;
  43. // Always verify loopinfo if expensive checking is enabled.
  44. #ifdef EXPENSIVE_CHECKS
  45. bool llvm::VerifyLoopInfo = true;
  46. #else
  47. bool llvm::VerifyLoopInfo = false;
  48. #endif
  49. static cl::opt<bool, true>
  50. VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
  51. cl::Hidden, cl::desc("Verify loop info (time consuming)"));
  52. //===----------------------------------------------------------------------===//
  53. // Loop implementation
  54. //
  55. bool Loop::isLoopInvariant(const Value *V) const {
  56. if (const Instruction *I = dyn_cast<Instruction>(V))
  57. return !contains(I);
  58. return true; // All non-instructions are loop invariant
  59. }
  60. bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
  61. return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
  62. }
  63. bool Loop::makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt,
  64. MemorySSAUpdater *MSSAU,
  65. ScalarEvolution *SE) const {
  66. if (Instruction *I = dyn_cast<Instruction>(V))
  67. return makeLoopInvariant(I, Changed, InsertPt, MSSAU, SE);
  68. return true; // All non-instructions are loop-invariant.
  69. }
  70. bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
  71. Instruction *InsertPt, MemorySSAUpdater *MSSAU,
  72. ScalarEvolution *SE) const {
  73. // Test if the value is already loop-invariant.
  74. if (isLoopInvariant(I))
  75. return true;
  76. if (!isSafeToSpeculativelyExecute(I))
  77. return false;
  78. if (I->mayReadFromMemory())
  79. return false;
  80. // EH block instructions are immobile.
  81. if (I->isEHPad())
  82. return false;
  83. // Determine the insertion point, unless one was given.
  84. if (!InsertPt) {
  85. BasicBlock *Preheader = getLoopPreheader();
  86. // Without a preheader, hoisting is not feasible.
  87. if (!Preheader)
  88. return false;
  89. InsertPt = Preheader->getTerminator();
  90. }
  91. // Don't hoist instructions with loop-variant operands.
  92. for (Value *Operand : I->operands())
  93. if (!makeLoopInvariant(Operand, Changed, InsertPt, MSSAU, SE))
  94. return false;
  95. // Hoist.
  96. I->moveBefore(InsertPt);
  97. if (MSSAU)
  98. if (auto *MUD = MSSAU->getMemorySSA()->getMemoryAccess(I))
  99. MSSAU->moveToPlace(MUD, InsertPt->getParent(),
  100. MemorySSA::BeforeTerminator);
  101. // There is possibility of hoisting this instruction above some arbitrary
  102. // condition. Any metadata defined on it can be control dependent on this
  103. // condition. Conservatively strip it here so that we don't give any wrong
  104. // information to the optimizer.
  105. I->dropUnknownNonDebugMetadata();
  106. if (SE)
  107. SE->forgetBlockAndLoopDispositions(I);
  108. Changed = true;
  109. return true;
  110. }
  111. bool Loop::getIncomingAndBackEdge(BasicBlock *&Incoming,
  112. BasicBlock *&Backedge) const {
  113. BasicBlock *H = getHeader();
  114. Incoming = nullptr;
  115. Backedge = nullptr;
  116. pred_iterator PI = pred_begin(H);
  117. assert(PI != pred_end(H) && "Loop must have at least one backedge!");
  118. Backedge = *PI++;
  119. if (PI == pred_end(H))
  120. return false; // dead loop
  121. Incoming = *PI++;
  122. if (PI != pred_end(H))
  123. return false; // multiple backedges?
  124. if (contains(Incoming)) {
  125. if (contains(Backedge))
  126. return false;
  127. std::swap(Incoming, Backedge);
  128. } else if (!contains(Backedge))
  129. return false;
  130. assert(Incoming && Backedge && "expected non-null incoming and backedges");
  131. return true;
  132. }
  133. PHINode *Loop::getCanonicalInductionVariable() const {
  134. BasicBlock *H = getHeader();
  135. BasicBlock *Incoming = nullptr, *Backedge = nullptr;
  136. if (!getIncomingAndBackEdge(Incoming, Backedge))
  137. return nullptr;
  138. // Loop over all of the PHI nodes, looking for a canonical indvar.
  139. for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
  140. PHINode *PN = cast<PHINode>(I);
  141. if (ConstantInt *CI =
  142. dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
  143. if (CI->isZero())
  144. if (Instruction *Inc =
  145. dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
  146. if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
  147. if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
  148. if (CI->isOne())
  149. return PN;
  150. }
  151. return nullptr;
  152. }
  153. /// Get the latch condition instruction.
  154. ICmpInst *Loop::getLatchCmpInst() const {
  155. if (BasicBlock *Latch = getLoopLatch())
  156. if (BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator()))
  157. if (BI->isConditional())
  158. return dyn_cast<ICmpInst>(BI->getCondition());
  159. return nullptr;
  160. }
  161. /// Return the final value of the loop induction variable if found.
  162. static Value *findFinalIVValue(const Loop &L, const PHINode &IndVar,
  163. const Instruction &StepInst) {
  164. ICmpInst *LatchCmpInst = L.getLatchCmpInst();
  165. if (!LatchCmpInst)
  166. return nullptr;
  167. Value *Op0 = LatchCmpInst->getOperand(0);
  168. Value *Op1 = LatchCmpInst->getOperand(1);
  169. if (Op0 == &IndVar || Op0 == &StepInst)
  170. return Op1;
  171. if (Op1 == &IndVar || Op1 == &StepInst)
  172. return Op0;
  173. return nullptr;
  174. }
  175. std::optional<Loop::LoopBounds>
  176. Loop::LoopBounds::getBounds(const Loop &L, PHINode &IndVar,
  177. ScalarEvolution &SE) {
  178. InductionDescriptor IndDesc;
  179. if (!InductionDescriptor::isInductionPHI(&IndVar, &L, &SE, IndDesc))
  180. return std::nullopt;
  181. Value *InitialIVValue = IndDesc.getStartValue();
  182. Instruction *StepInst = IndDesc.getInductionBinOp();
  183. if (!InitialIVValue || !StepInst)
  184. return std::nullopt;
  185. const SCEV *Step = IndDesc.getStep();
  186. Value *StepInstOp1 = StepInst->getOperand(1);
  187. Value *StepInstOp0 = StepInst->getOperand(0);
  188. Value *StepValue = nullptr;
  189. if (SE.getSCEV(StepInstOp1) == Step)
  190. StepValue = StepInstOp1;
  191. else if (SE.getSCEV(StepInstOp0) == Step)
  192. StepValue = StepInstOp0;
  193. Value *FinalIVValue = findFinalIVValue(L, IndVar, *StepInst);
  194. if (!FinalIVValue)
  195. return std::nullopt;
  196. return LoopBounds(L, *InitialIVValue, *StepInst, StepValue, *FinalIVValue,
  197. SE);
  198. }
  199. using Direction = Loop::LoopBounds::Direction;
  200. ICmpInst::Predicate Loop::LoopBounds::getCanonicalPredicate() const {
  201. BasicBlock *Latch = L.getLoopLatch();
  202. assert(Latch && "Expecting valid latch");
  203. BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator());
  204. assert(BI && BI->isConditional() && "Expecting conditional latch branch");
  205. ICmpInst *LatchCmpInst = dyn_cast<ICmpInst>(BI->getCondition());
  206. assert(LatchCmpInst &&
  207. "Expecting the latch compare instruction to be a CmpInst");
  208. // Need to inverse the predicate when first successor is not the loop
  209. // header
  210. ICmpInst::Predicate Pred = (BI->getSuccessor(0) == L.getHeader())
  211. ? LatchCmpInst->getPredicate()
  212. : LatchCmpInst->getInversePredicate();
  213. if (LatchCmpInst->getOperand(0) == &getFinalIVValue())
  214. Pred = ICmpInst::getSwappedPredicate(Pred);
  215. // Need to flip strictness of the predicate when the latch compare instruction
  216. // is not using StepInst
  217. if (LatchCmpInst->getOperand(0) == &getStepInst() ||
  218. LatchCmpInst->getOperand(1) == &getStepInst())
  219. return Pred;
  220. // Cannot flip strictness of NE and EQ
  221. if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
  222. return ICmpInst::getFlippedStrictnessPredicate(Pred);
  223. Direction D = getDirection();
  224. if (D == Direction::Increasing)
  225. return ICmpInst::ICMP_SLT;
  226. if (D == Direction::Decreasing)
  227. return ICmpInst::ICMP_SGT;
  228. // If cannot determine the direction, then unable to find the canonical
  229. // predicate
  230. return ICmpInst::BAD_ICMP_PREDICATE;
  231. }
  232. Direction Loop::LoopBounds::getDirection() const {
  233. if (const SCEVAddRecExpr *StepAddRecExpr =
  234. dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&getStepInst())))
  235. if (const SCEV *StepRecur = StepAddRecExpr->getStepRecurrence(SE)) {
  236. if (SE.isKnownPositive(StepRecur))
  237. return Direction::Increasing;
  238. if (SE.isKnownNegative(StepRecur))
  239. return Direction::Decreasing;
  240. }
  241. return Direction::Unknown;
  242. }
  243. std::optional<Loop::LoopBounds> Loop::getBounds(ScalarEvolution &SE) const {
  244. if (PHINode *IndVar = getInductionVariable(SE))
  245. return LoopBounds::getBounds(*this, *IndVar, SE);
  246. return std::nullopt;
  247. }
  248. PHINode *Loop::getInductionVariable(ScalarEvolution &SE) const {
  249. if (!isLoopSimplifyForm())
  250. return nullptr;
  251. BasicBlock *Header = getHeader();
  252. assert(Header && "Expected a valid loop header");
  253. ICmpInst *CmpInst = getLatchCmpInst();
  254. if (!CmpInst)
  255. return nullptr;
  256. Value *LatchCmpOp0 = CmpInst->getOperand(0);
  257. Value *LatchCmpOp1 = CmpInst->getOperand(1);
  258. for (PHINode &IndVar : Header->phis()) {
  259. InductionDescriptor IndDesc;
  260. if (!InductionDescriptor::isInductionPHI(&IndVar, this, &SE, IndDesc))
  261. continue;
  262. BasicBlock *Latch = getLoopLatch();
  263. Value *StepInst = IndVar.getIncomingValueForBlock(Latch);
  264. // case 1:
  265. // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
  266. // StepInst = IndVar + step
  267. // cmp = StepInst < FinalValue
  268. if (StepInst == LatchCmpOp0 || StepInst == LatchCmpOp1)
  269. return &IndVar;
  270. // case 2:
  271. // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
  272. // StepInst = IndVar + step
  273. // cmp = IndVar < FinalValue
  274. if (&IndVar == LatchCmpOp0 || &IndVar == LatchCmpOp1)
  275. return &IndVar;
  276. }
  277. return nullptr;
  278. }
  279. bool Loop::getInductionDescriptor(ScalarEvolution &SE,
  280. InductionDescriptor &IndDesc) const {
  281. if (PHINode *IndVar = getInductionVariable(SE))
  282. return InductionDescriptor::isInductionPHI(IndVar, this, &SE, IndDesc);
  283. return false;
  284. }
  285. bool Loop::isAuxiliaryInductionVariable(PHINode &AuxIndVar,
  286. ScalarEvolution &SE) const {
  287. // Located in the loop header
  288. BasicBlock *Header = getHeader();
  289. if (AuxIndVar.getParent() != Header)
  290. return false;
  291. // No uses outside of the loop
  292. for (User *U : AuxIndVar.users())
  293. if (const Instruction *I = dyn_cast<Instruction>(U))
  294. if (!contains(I))
  295. return false;
  296. InductionDescriptor IndDesc;
  297. if (!InductionDescriptor::isInductionPHI(&AuxIndVar, this, &SE, IndDesc))
  298. return false;
  299. // The step instruction opcode should be add or sub.
  300. if (IndDesc.getInductionOpcode() != Instruction::Add &&
  301. IndDesc.getInductionOpcode() != Instruction::Sub)
  302. return false;
  303. // Incremented by a loop invariant step for each loop iteration
  304. return SE.isLoopInvariant(IndDesc.getStep(), this);
  305. }
  306. BranchInst *Loop::getLoopGuardBranch() const {
  307. if (!isLoopSimplifyForm())
  308. return nullptr;
  309. BasicBlock *Preheader = getLoopPreheader();
  310. assert(Preheader && getLoopLatch() &&
  311. "Expecting a loop with valid preheader and latch");
  312. // Loop should be in rotate form.
  313. if (!isRotatedForm())
  314. return nullptr;
  315. // Disallow loops with more than one unique exit block, as we do not verify
  316. // that GuardOtherSucc post dominates all exit blocks.
  317. BasicBlock *ExitFromLatch = getUniqueExitBlock();
  318. if (!ExitFromLatch)
  319. return nullptr;
  320. BasicBlock *GuardBB = Preheader->getUniquePredecessor();
  321. if (!GuardBB)
  322. return nullptr;
  323. assert(GuardBB->getTerminator() && "Expecting valid guard terminator");
  324. BranchInst *GuardBI = dyn_cast<BranchInst>(GuardBB->getTerminator());
  325. if (!GuardBI || GuardBI->isUnconditional())
  326. return nullptr;
  327. BasicBlock *GuardOtherSucc = (GuardBI->getSuccessor(0) == Preheader)
  328. ? GuardBI->getSuccessor(1)
  329. : GuardBI->getSuccessor(0);
  330. // Check if ExitFromLatch (or any BasicBlock which is an empty unique
  331. // successor of ExitFromLatch) is equal to GuardOtherSucc. If
  332. // skipEmptyBlockUntil returns GuardOtherSucc, then the guard branch for the
  333. // loop is GuardBI (return GuardBI), otherwise return nullptr.
  334. if (&LoopNest::skipEmptyBlockUntil(ExitFromLatch, GuardOtherSucc,
  335. /*CheckUniquePred=*/true) ==
  336. GuardOtherSucc)
  337. return GuardBI;
  338. else
  339. return nullptr;
  340. }
  341. bool Loop::isCanonical(ScalarEvolution &SE) const {
  342. InductionDescriptor IndDesc;
  343. if (!getInductionDescriptor(SE, IndDesc))
  344. return false;
  345. ConstantInt *Init = dyn_cast_or_null<ConstantInt>(IndDesc.getStartValue());
  346. if (!Init || !Init->isZero())
  347. return false;
  348. if (IndDesc.getInductionOpcode() != Instruction::Add)
  349. return false;
  350. ConstantInt *Step = IndDesc.getConstIntStepValue();
  351. if (!Step || !Step->isOne())
  352. return false;
  353. return true;
  354. }
  355. // Check that 'BB' doesn't have any uses outside of the 'L'
  356. static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
  357. const DominatorTree &DT, bool IgnoreTokens) {
  358. for (const Instruction &I : BB) {
  359. // Tokens can't be used in PHI nodes and live-out tokens prevent loop
  360. // optimizations, so for the purposes of considered LCSSA form, we
  361. // can ignore them.
  362. if (IgnoreTokens && I.getType()->isTokenTy())
  363. continue;
  364. for (const Use &U : I.uses()) {
  365. const Instruction *UI = cast<Instruction>(U.getUser());
  366. const BasicBlock *UserBB = UI->getParent();
  367. // For practical purposes, we consider that the use in a PHI
  368. // occurs in the respective predecessor block. For more info,
  369. // see the `phi` doc in LangRef and the LCSSA doc.
  370. if (const PHINode *P = dyn_cast<PHINode>(UI))
  371. UserBB = P->getIncomingBlock(U);
  372. // Check the current block, as a fast-path, before checking whether
  373. // the use is anywhere in the loop. Most values are used in the same
  374. // block they are defined in. Also, blocks not reachable from the
  375. // entry are special; uses in them don't need to go through PHIs.
  376. if (UserBB != &BB && !L.contains(UserBB) &&
  377. DT.isReachableFromEntry(UserBB))
  378. return false;
  379. }
  380. }
  381. return true;
  382. }
  383. bool Loop::isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens) const {
  384. // For each block we check that it doesn't have any uses outside of this loop.
  385. return all_of(this->blocks(), [&](const BasicBlock *BB) {
  386. return isBlockInLCSSAForm(*this, *BB, DT, IgnoreTokens);
  387. });
  388. }
  389. bool Loop::isRecursivelyLCSSAForm(const DominatorTree &DT, const LoopInfo &LI,
  390. bool IgnoreTokens) const {
  391. // For each block we check that it doesn't have any uses outside of its
  392. // innermost loop. This process will transitively guarantee that the current
  393. // loop and all of the nested loops are in LCSSA form.
  394. return all_of(this->blocks(), [&](const BasicBlock *BB) {
  395. return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT, IgnoreTokens);
  396. });
  397. }
  398. bool Loop::isLoopSimplifyForm() const {
  399. // Normal-form loops have a preheader, a single backedge, and all of their
  400. // exits have all their predecessors inside the loop.
  401. return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
  402. }
  403. // Routines that reform the loop CFG and split edges often fail on indirectbr.
  404. bool Loop::isSafeToClone() const {
  405. // Return false if any loop blocks contain indirectbrs, or there are any calls
  406. // to noduplicate functions.
  407. for (BasicBlock *BB : this->blocks()) {
  408. if (isa<IndirectBrInst>(BB->getTerminator()))
  409. return false;
  410. for (Instruction &I : *BB)
  411. if (auto *CB = dyn_cast<CallBase>(&I))
  412. if (CB->cannotDuplicate())
  413. return false;
  414. }
  415. return true;
  416. }
  417. MDNode *Loop::getLoopID() const {
  418. MDNode *LoopID = nullptr;
  419. // Go through the latch blocks and check the terminator for the metadata.
  420. SmallVector<BasicBlock *, 4> LatchesBlocks;
  421. getLoopLatches(LatchesBlocks);
  422. for (BasicBlock *BB : LatchesBlocks) {
  423. Instruction *TI = BB->getTerminator();
  424. MDNode *MD = TI->getMetadata(LLVMContext::MD_loop);
  425. if (!MD)
  426. return nullptr;
  427. if (!LoopID)
  428. LoopID = MD;
  429. else if (MD != LoopID)
  430. return nullptr;
  431. }
  432. if (!LoopID || LoopID->getNumOperands() == 0 ||
  433. LoopID->getOperand(0) != LoopID)
  434. return nullptr;
  435. return LoopID;
  436. }
  437. void Loop::setLoopID(MDNode *LoopID) const {
  438. assert((!LoopID || LoopID->getNumOperands() > 0) &&
  439. "Loop ID needs at least one operand");
  440. assert((!LoopID || LoopID->getOperand(0) == LoopID) &&
  441. "Loop ID should refer to itself");
  442. SmallVector<BasicBlock *, 4> LoopLatches;
  443. getLoopLatches(LoopLatches);
  444. for (BasicBlock *BB : LoopLatches)
  445. BB->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
  446. }
  447. void Loop::setLoopAlreadyUnrolled() {
  448. LLVMContext &Context = getHeader()->getContext();
  449. MDNode *DisableUnrollMD =
  450. MDNode::get(Context, MDString::get(Context, "llvm.loop.unroll.disable"));
  451. MDNode *LoopID = getLoopID();
  452. MDNode *NewLoopID = makePostTransformationMetadata(
  453. Context, LoopID, {"llvm.loop.unroll."}, {DisableUnrollMD});
  454. setLoopID(NewLoopID);
  455. }
  456. void Loop::setLoopMustProgress() {
  457. LLVMContext &Context = getHeader()->getContext();
  458. MDNode *MustProgress = findOptionMDForLoop(this, "llvm.loop.mustprogress");
  459. if (MustProgress)
  460. return;
  461. MDNode *MustProgressMD =
  462. MDNode::get(Context, MDString::get(Context, "llvm.loop.mustprogress"));
  463. MDNode *LoopID = getLoopID();
  464. MDNode *NewLoopID =
  465. makePostTransformationMetadata(Context, LoopID, {}, {MustProgressMD});
  466. setLoopID(NewLoopID);
  467. }
  468. bool Loop::isAnnotatedParallel() const {
  469. MDNode *DesiredLoopIdMetadata = getLoopID();
  470. if (!DesiredLoopIdMetadata)
  471. return false;
  472. MDNode *ParallelAccesses =
  473. findOptionMDForLoop(this, "llvm.loop.parallel_accesses");
  474. SmallPtrSet<MDNode *, 4>
  475. ParallelAccessGroups; // For scalable 'contains' check.
  476. if (ParallelAccesses) {
  477. for (const MDOperand &MD : drop_begin(ParallelAccesses->operands())) {
  478. MDNode *AccGroup = cast<MDNode>(MD.get());
  479. assert(isValidAsAccessGroup(AccGroup) &&
  480. "List item must be an access group");
  481. ParallelAccessGroups.insert(AccGroup);
  482. }
  483. }
  484. // The loop branch contains the parallel loop metadata. In order to ensure
  485. // that any parallel-loop-unaware optimization pass hasn't added loop-carried
  486. // dependencies (thus converted the loop back to a sequential loop), check
  487. // that all the memory instructions in the loop belong to an access group that
  488. // is parallel to this loop.
  489. for (BasicBlock *BB : this->blocks()) {
  490. for (Instruction &I : *BB) {
  491. if (!I.mayReadOrWriteMemory())
  492. continue;
  493. if (MDNode *AccessGroup = I.getMetadata(LLVMContext::MD_access_group)) {
  494. auto ContainsAccessGroup = [&ParallelAccessGroups](MDNode *AG) -> bool {
  495. if (AG->getNumOperands() == 0) {
  496. assert(isValidAsAccessGroup(AG) && "Item must be an access group");
  497. return ParallelAccessGroups.count(AG);
  498. }
  499. for (const MDOperand &AccessListItem : AG->operands()) {
  500. MDNode *AccGroup = cast<MDNode>(AccessListItem.get());
  501. assert(isValidAsAccessGroup(AccGroup) &&
  502. "List item must be an access group");
  503. if (ParallelAccessGroups.count(AccGroup))
  504. return true;
  505. }
  506. return false;
  507. };
  508. if (ContainsAccessGroup(AccessGroup))
  509. continue;
  510. }
  511. // The memory instruction can refer to the loop identifier metadata
  512. // directly or indirectly through another list metadata (in case of
  513. // nested parallel loops). The loop identifier metadata refers to
  514. // itself so we can check both cases with the same routine.
  515. MDNode *LoopIdMD =
  516. I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
  517. if (!LoopIdMD)
  518. return false;
  519. if (!llvm::is_contained(LoopIdMD->operands(), DesiredLoopIdMetadata))
  520. return false;
  521. }
  522. }
  523. return true;
  524. }
  525. DebugLoc Loop::getStartLoc() const { return getLocRange().getStart(); }
  526. Loop::LocRange Loop::getLocRange() const {
  527. // If we have a debug location in the loop ID, then use it.
  528. if (MDNode *LoopID = getLoopID()) {
  529. DebugLoc Start;
  530. // We use the first DebugLoc in the header as the start location of the loop
  531. // and if there is a second DebugLoc in the header we use it as end location
  532. // of the loop.
  533. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  534. if (DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i))) {
  535. if (!Start)
  536. Start = DebugLoc(L);
  537. else
  538. return LocRange(Start, DebugLoc(L));
  539. }
  540. }
  541. if (Start)
  542. return LocRange(Start);
  543. }
  544. // Try the pre-header first.
  545. if (BasicBlock *PHeadBB = getLoopPreheader())
  546. if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
  547. return LocRange(DL);
  548. // If we have no pre-header or there are no instructions with debug
  549. // info in it, try the header.
  550. if (BasicBlock *HeadBB = getHeader())
  551. return LocRange(HeadBB->getTerminator()->getDebugLoc());
  552. return LocRange();
  553. }
  554. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  555. LLVM_DUMP_METHOD void Loop::dump() const { print(dbgs()); }
  556. LLVM_DUMP_METHOD void Loop::dumpVerbose() const {
  557. print(dbgs(), /*Verbose=*/true);
  558. }
  559. #endif
  560. //===----------------------------------------------------------------------===//
  561. // UnloopUpdater implementation
  562. //
  563. namespace {
  564. /// Find the new parent loop for all blocks within the "unloop" whose last
  565. /// backedges has just been removed.
  566. class UnloopUpdater {
  567. Loop &Unloop;
  568. LoopInfo *LI;
  569. LoopBlocksDFS DFS;
  570. // Map unloop's immediate subloops to their nearest reachable parents. Nested
  571. // loops within these subloops will not change parents. However, an immediate
  572. // subloop's new parent will be the nearest loop reachable from either its own
  573. // exits *or* any of its nested loop's exits.
  574. DenseMap<Loop *, Loop *> SubloopParents;
  575. // Flag the presence of an irreducible backedge whose destination is a block
  576. // directly contained by the original unloop.
  577. bool FoundIB = false;
  578. public:
  579. UnloopUpdater(Loop *UL, LoopInfo *LInfo) : Unloop(*UL), LI(LInfo), DFS(UL) {}
  580. void updateBlockParents();
  581. void removeBlocksFromAncestors();
  582. void updateSubloopParents();
  583. protected:
  584. Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
  585. };
  586. } // end anonymous namespace
  587. /// Update the parent loop for all blocks that are directly contained within the
  588. /// original "unloop".
  589. void UnloopUpdater::updateBlockParents() {
  590. if (Unloop.getNumBlocks()) {
  591. // Perform a post order CFG traversal of all blocks within this loop,
  592. // propagating the nearest loop from successors to predecessors.
  593. LoopBlocksTraversal Traversal(DFS, LI);
  594. for (BasicBlock *POI : Traversal) {
  595. Loop *L = LI->getLoopFor(POI);
  596. Loop *NL = getNearestLoop(POI, L);
  597. if (NL != L) {
  598. // For reducible loops, NL is now an ancestor of Unloop.
  599. assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
  600. "uninitialized successor");
  601. LI->changeLoopFor(POI, NL);
  602. } else {
  603. // Or the current block is part of a subloop, in which case its parent
  604. // is unchanged.
  605. assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
  606. }
  607. }
  608. }
  609. // Each irreducible loop within the unloop induces a round of iteration using
  610. // the DFS result cached by Traversal.
  611. bool Changed = FoundIB;
  612. for (unsigned NIters = 0; Changed; ++NIters) {
  613. assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
  614. (void) NIters;
  615. // Iterate over the postorder list of blocks, propagating the nearest loop
  616. // from successors to predecessors as before.
  617. Changed = false;
  618. for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
  619. POE = DFS.endPostorder();
  620. POI != POE; ++POI) {
  621. Loop *L = LI->getLoopFor(*POI);
  622. Loop *NL = getNearestLoop(*POI, L);
  623. if (NL != L) {
  624. assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
  625. "uninitialized successor");
  626. LI->changeLoopFor(*POI, NL);
  627. Changed = true;
  628. }
  629. }
  630. }
  631. }
  632. /// Remove unloop's blocks from all ancestors below their new parents.
  633. void UnloopUpdater::removeBlocksFromAncestors() {
  634. // Remove all unloop's blocks (including those in nested subloops) from
  635. // ancestors below the new parent loop.
  636. for (BasicBlock *BB : Unloop.blocks()) {
  637. Loop *OuterParent = LI->getLoopFor(BB);
  638. if (Unloop.contains(OuterParent)) {
  639. while (OuterParent->getParentLoop() != &Unloop)
  640. OuterParent = OuterParent->getParentLoop();
  641. OuterParent = SubloopParents[OuterParent];
  642. }
  643. // Remove blocks from former Ancestors except Unloop itself which will be
  644. // deleted.
  645. for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
  646. OldParent = OldParent->getParentLoop()) {
  647. assert(OldParent && "new loop is not an ancestor of the original");
  648. OldParent->removeBlockFromLoop(BB);
  649. }
  650. }
  651. }
  652. /// Update the parent loop for all subloops directly nested within unloop.
  653. void UnloopUpdater::updateSubloopParents() {
  654. while (!Unloop.isInnermost()) {
  655. Loop *Subloop = *std::prev(Unloop.end());
  656. Unloop.removeChildLoop(std::prev(Unloop.end()));
  657. assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
  658. if (Loop *Parent = SubloopParents[Subloop])
  659. Parent->addChildLoop(Subloop);
  660. else
  661. LI->addTopLevelLoop(Subloop);
  662. }
  663. }
  664. /// Return the nearest parent loop among this block's successors. If a successor
  665. /// is a subloop header, consider its parent to be the nearest parent of the
  666. /// subloop's exits.
  667. ///
  668. /// For subloop blocks, simply update SubloopParents and return NULL.
  669. Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
  670. // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
  671. // is considered uninitialized.
  672. Loop *NearLoop = BBLoop;
  673. Loop *Subloop = nullptr;
  674. if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
  675. Subloop = NearLoop;
  676. // Find the subloop ancestor that is directly contained within Unloop.
  677. while (Subloop->getParentLoop() != &Unloop) {
  678. Subloop = Subloop->getParentLoop();
  679. assert(Subloop && "subloop is not an ancestor of the original loop");
  680. }
  681. // Get the current nearest parent of the Subloop exits, initially Unloop.
  682. NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
  683. }
  684. succ_iterator I = succ_begin(BB), E = succ_end(BB);
  685. if (I == E) {
  686. assert(!Subloop && "subloop blocks must have a successor");
  687. NearLoop = nullptr; // unloop blocks may now exit the function.
  688. }
  689. for (; I != E; ++I) {
  690. if (*I == BB)
  691. continue; // self loops are uninteresting
  692. Loop *L = LI->getLoopFor(*I);
  693. if (L == &Unloop) {
  694. // This successor has not been processed. This path must lead to an
  695. // irreducible backedge.
  696. assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
  697. FoundIB = true;
  698. }
  699. if (L != &Unloop && Unloop.contains(L)) {
  700. // Successor is in a subloop.
  701. if (Subloop)
  702. continue; // Branching within subloops. Ignore it.
  703. // BB branches from the original into a subloop header.
  704. assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
  705. // Get the current nearest parent of the Subloop's exits.
  706. L = SubloopParents[L];
  707. // L could be Unloop if the only exit was an irreducible backedge.
  708. }
  709. if (L == &Unloop) {
  710. continue;
  711. }
  712. // Handle critical edges from Unloop into a sibling loop.
  713. if (L && !L->contains(&Unloop)) {
  714. L = L->getParentLoop();
  715. }
  716. // Remember the nearest parent loop among successors or subloop exits.
  717. if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
  718. NearLoop = L;
  719. }
  720. if (Subloop) {
  721. SubloopParents[Subloop] = NearLoop;
  722. return BBLoop;
  723. }
  724. return NearLoop;
  725. }
  726. LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); }
  727. bool LoopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
  728. FunctionAnalysisManager::Invalidator &) {
  729. // Check whether the analysis, all analyses on functions, or the function's
  730. // CFG have been preserved.
  731. auto PAC = PA.getChecker<LoopAnalysis>();
  732. return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
  733. PAC.preservedSet<CFGAnalyses>());
  734. }
  735. void LoopInfo::erase(Loop *Unloop) {
  736. assert(!Unloop->isInvalid() && "Loop has already been erased!");
  737. auto InvalidateOnExit = make_scope_exit([&]() { destroy(Unloop); });
  738. // First handle the special case of no parent loop to simplify the algorithm.
  739. if (Unloop->isOutermost()) {
  740. // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
  741. for (BasicBlock *BB : Unloop->blocks()) {
  742. // Don't reparent blocks in subloops.
  743. if (getLoopFor(BB) != Unloop)
  744. continue;
  745. // Blocks no longer have a parent but are still referenced by Unloop until
  746. // the Unloop object is deleted.
  747. changeLoopFor(BB, nullptr);
  748. }
  749. // Remove the loop from the top-level LoopInfo object.
  750. for (iterator I = begin();; ++I) {
  751. assert(I != end() && "Couldn't find loop");
  752. if (*I == Unloop) {
  753. removeLoop(I);
  754. break;
  755. }
  756. }
  757. // Move all of the subloops to the top-level.
  758. while (!Unloop->isInnermost())
  759. addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
  760. return;
  761. }
  762. // Update the parent loop for all blocks within the loop. Blocks within
  763. // subloops will not change parents.
  764. UnloopUpdater Updater(Unloop, this);
  765. Updater.updateBlockParents();
  766. // Remove blocks from former ancestor loops.
  767. Updater.removeBlocksFromAncestors();
  768. // Add direct subloops as children in their new parent loop.
  769. Updater.updateSubloopParents();
  770. // Remove unloop from its parent loop.
  771. Loop *ParentLoop = Unloop->getParentLoop();
  772. for (Loop::iterator I = ParentLoop->begin();; ++I) {
  773. assert(I != ParentLoop->end() && "Couldn't find loop");
  774. if (*I == Unloop) {
  775. ParentLoop->removeChildLoop(I);
  776. break;
  777. }
  778. }
  779. }
  780. bool
  781. LoopInfo::wouldBeOutOfLoopUseRequiringLCSSA(const Value *V,
  782. const BasicBlock *ExitBB) const {
  783. if (V->getType()->isTokenTy())
  784. // We can't form PHIs of token type, so the definition of LCSSA excludes
  785. // values of that type.
  786. return false;
  787. const Instruction *I = dyn_cast<Instruction>(V);
  788. if (!I)
  789. return false;
  790. const Loop *L = getLoopFor(I->getParent());
  791. if (!L)
  792. return false;
  793. if (L->contains(ExitBB))
  794. // Could be an exit bb of a subloop and contained in defining loop
  795. return false;
  796. // We found a (new) out-of-loop use location, for a value defined in-loop.
  797. // (Note that because of LCSSA, we don't have to account for values defined
  798. // in sibling loops. Such values will have LCSSA phis of their own in the
  799. // common parent loop.)
  800. return true;
  801. }
  802. AnalysisKey LoopAnalysis::Key;
  803. LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
  804. // FIXME: Currently we create a LoopInfo from scratch for every function.
  805. // This may prove to be too wasteful due to deallocating and re-allocating
  806. // memory each time for the underlying map and vector datastructures. At some
  807. // point it may prove worthwhile to use a freelist and recycle LoopInfo
  808. // objects. I don't want to add that kind of complexity until the scope of
  809. // the problem is better understood.
  810. LoopInfo LI;
  811. LI.analyze(AM.getResult<DominatorTreeAnalysis>(F));
  812. return LI;
  813. }
  814. PreservedAnalyses LoopPrinterPass::run(Function &F,
  815. FunctionAnalysisManager &AM) {
  816. AM.getResult<LoopAnalysis>(F).print(OS);
  817. return PreservedAnalyses::all();
  818. }
  819. void llvm::printLoop(Loop &L, raw_ostream &OS, const std::string &Banner) {
  820. if (forcePrintModuleIR()) {
  821. // handling -print-module-scope
  822. OS << Banner << " (loop: ";
  823. L.getHeader()->printAsOperand(OS, false);
  824. OS << ")\n";
  825. // printing whole module
  826. OS << *L.getHeader()->getModule();
  827. return;
  828. }
  829. OS << Banner;
  830. auto *PreHeader = L.getLoopPreheader();
  831. if (PreHeader) {
  832. OS << "\n; Preheader:";
  833. PreHeader->print(OS);
  834. OS << "\n; Loop:";
  835. }
  836. for (auto *Block : L.blocks())
  837. if (Block)
  838. Block->print(OS);
  839. else
  840. OS << "Printing <null> block";
  841. SmallVector<BasicBlock *, 8> ExitBlocks;
  842. L.getExitBlocks(ExitBlocks);
  843. if (!ExitBlocks.empty()) {
  844. OS << "\n; Exit blocks";
  845. for (auto *Block : ExitBlocks)
  846. if (Block)
  847. Block->print(OS);
  848. else
  849. OS << "Printing <null> block";
  850. }
  851. }
  852. MDNode *llvm::findOptionMDForLoopID(MDNode *LoopID, StringRef Name) {
  853. // No loop metadata node, no loop properties.
  854. if (!LoopID)
  855. return nullptr;
  856. // First operand should refer to the metadata node itself, for legacy reasons.
  857. assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
  858. assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
  859. // Iterate over the metdata node operands and look for MDString metadata.
  860. for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
  861. MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
  862. if (!MD || MD->getNumOperands() < 1)
  863. continue;
  864. MDString *S = dyn_cast<MDString>(MD->getOperand(0));
  865. if (!S)
  866. continue;
  867. // Return the operand node if MDString holds expected metadata.
  868. if (Name.equals(S->getString()))
  869. return MD;
  870. }
  871. // Loop property not found.
  872. return nullptr;
  873. }
  874. MDNode *llvm::findOptionMDForLoop(const Loop *TheLoop, StringRef Name) {
  875. return findOptionMDForLoopID(TheLoop->getLoopID(), Name);
  876. }
  877. /// Find string metadata for loop
  878. ///
  879. /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
  880. /// operand or null otherwise. If the string metadata is not found return
  881. /// Optional's not-a-value.
  882. std::optional<const MDOperand *>
  883. llvm::findStringMetadataForLoop(const Loop *TheLoop, StringRef Name) {
  884. MDNode *MD = findOptionMDForLoop(TheLoop, Name);
  885. if (!MD)
  886. return std::nullopt;
  887. switch (MD->getNumOperands()) {
  888. case 1:
  889. return nullptr;
  890. case 2:
  891. return &MD->getOperand(1);
  892. default:
  893. llvm_unreachable("loop metadata has 0 or 1 operand");
  894. }
  895. }
  896. std::optional<bool> llvm::getOptionalBoolLoopAttribute(const Loop *TheLoop,
  897. StringRef Name) {
  898. MDNode *MD = findOptionMDForLoop(TheLoop, Name);
  899. if (!MD)
  900. return std::nullopt;
  901. switch (MD->getNumOperands()) {
  902. case 1:
  903. // When the value is absent it is interpreted as 'attribute set'.
  904. return true;
  905. case 2:
  906. if (ConstantInt *IntMD =
  907. mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get()))
  908. return IntMD->getZExtValue();
  909. return true;
  910. }
  911. llvm_unreachable("unexpected number of options");
  912. }
  913. bool llvm::getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
  914. return getOptionalBoolLoopAttribute(TheLoop, Name).value_or(false);
  915. }
  916. std::optional<int> llvm::getOptionalIntLoopAttribute(const Loop *TheLoop,
  917. StringRef Name) {
  918. const MDOperand *AttrMD =
  919. findStringMetadataForLoop(TheLoop, Name).value_or(nullptr);
  920. if (!AttrMD)
  921. return std::nullopt;
  922. ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
  923. if (!IntMD)
  924. return std::nullopt;
  925. return IntMD->getSExtValue();
  926. }
  927. int llvm::getIntLoopAttribute(const Loop *TheLoop, StringRef Name,
  928. int Default) {
  929. return getOptionalIntLoopAttribute(TheLoop, Name).value_or(Default);
  930. }
  931. bool llvm::isFinite(const Loop *L) {
  932. return L->getHeader()->getParent()->willReturn();
  933. }
  934. static const char *LLVMLoopMustProgress = "llvm.loop.mustprogress";
  935. bool llvm::hasMustProgress(const Loop *L) {
  936. return getBooleanLoopAttribute(L, LLVMLoopMustProgress);
  937. }
  938. bool llvm::isMustProgress(const Loop *L) {
  939. return L->getHeader()->getParent()->mustProgress() || hasMustProgress(L);
  940. }
  941. bool llvm::isValidAsAccessGroup(MDNode *Node) {
  942. return Node->getNumOperands() == 0 && Node->isDistinct();
  943. }
  944. MDNode *llvm::makePostTransformationMetadata(LLVMContext &Context,
  945. MDNode *OrigLoopID,
  946. ArrayRef<StringRef> RemovePrefixes,
  947. ArrayRef<MDNode *> AddAttrs) {
  948. // First remove any existing loop metadata related to this transformation.
  949. SmallVector<Metadata *, 4> MDs;
  950. // Reserve first location for self reference to the LoopID metadata node.
  951. MDs.push_back(nullptr);
  952. // Remove metadata for the transformation that has been applied or that became
  953. // outdated.
  954. if (OrigLoopID) {
  955. for (unsigned i = 1, ie = OrigLoopID->getNumOperands(); i < ie; ++i) {
  956. bool IsVectorMetadata = false;
  957. Metadata *Op = OrigLoopID->getOperand(i);
  958. if (MDNode *MD = dyn_cast<MDNode>(Op)) {
  959. const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
  960. if (S)
  961. IsVectorMetadata =
  962. llvm::any_of(RemovePrefixes, [S](StringRef Prefix) -> bool {
  963. return S->getString().startswith(Prefix);
  964. });
  965. }
  966. if (!IsVectorMetadata)
  967. MDs.push_back(Op);
  968. }
  969. }
  970. // Add metadata to avoid reapplying a transformation, such as
  971. // llvm.loop.unroll.disable and llvm.loop.isvectorized.
  972. MDs.append(AddAttrs.begin(), AddAttrs.end());
  973. MDNode *NewLoopID = MDNode::getDistinct(Context, MDs);
  974. // Replace the temporary node with a self-reference.
  975. NewLoopID->replaceOperandWith(0, NewLoopID);
  976. return NewLoopID;
  977. }
  978. //===----------------------------------------------------------------------===//
  979. // LoopInfo implementation
  980. //
  981. LoopInfoWrapperPass::LoopInfoWrapperPass() : FunctionPass(ID) {
  982. initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
  983. }
  984. char LoopInfoWrapperPass::ID = 0;
  985. INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
  986. true, true)
  987. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  988. INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
  989. true, true)
  990. bool LoopInfoWrapperPass::runOnFunction(Function &) {
  991. releaseMemory();
  992. LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
  993. return false;
  994. }
  995. void LoopInfoWrapperPass::verifyAnalysis() const {
  996. // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
  997. // function each time verifyAnalysis is called is very expensive. The
  998. // -verify-loop-info option can enable this. In order to perform some
  999. // checking by default, LoopPass has been taught to call verifyLoop manually
  1000. // during loop pass sequences.
  1001. if (VerifyLoopInfo) {
  1002. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1003. LI.verify(DT);
  1004. }
  1005. }
  1006. void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
  1007. AU.setPreservesAll();
  1008. AU.addRequiredTransitive<DominatorTreeWrapperPass>();
  1009. }
  1010. void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
  1011. LI.print(OS);
  1012. }
  1013. PreservedAnalyses LoopVerifierPass::run(Function &F,
  1014. FunctionAnalysisManager &AM) {
  1015. LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
  1016. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  1017. LI.verify(DT);
  1018. return PreservedAnalyses::all();
  1019. }
  1020. //===----------------------------------------------------------------------===//
  1021. // LoopBlocksDFS implementation
  1022. //
  1023. /// Traverse the loop blocks and store the DFS result.
  1024. /// Useful for clients that just want the final DFS result and don't need to
  1025. /// visit blocks during the initial traversal.
  1026. void LoopBlocksDFS::perform(LoopInfo *LI) {
  1027. LoopBlocksTraversal Traversal(*this, LI);
  1028. for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
  1029. POE = Traversal.end();
  1030. POI != POE; ++POI)
  1031. ;
  1032. }