LoopInfo.cpp 41 KB

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