LoopDeletion.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. //===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===//
  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 implements the Dead Loop Deletion Pass. This pass is responsible
  10. // for eliminating loops with non-infinite computable trip counts that have no
  11. // side effects or volatile instructions, and do not contribute to the
  12. // computation of the function's return value.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Transforms/Scalar/LoopDeletion.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/Analysis/CFG.h"
  19. #include "llvm/Analysis/GlobalsModRef.h"
  20. #include "llvm/Analysis/InstructionSimplify.h"
  21. #include "llvm/Analysis/LoopIterator.h"
  22. #include "llvm/Analysis/LoopPass.h"
  23. #include "llvm/Analysis/MemorySSA.h"
  24. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  25. #include "llvm/IR/Dominators.h"
  26. #include "llvm/IR/PatternMatch.h"
  27. #include "llvm/InitializePasses.h"
  28. #include "llvm/Transforms/Scalar.h"
  29. #include "llvm/Transforms/Scalar/LoopPassManager.h"
  30. #include "llvm/Transforms/Utils/LoopUtils.h"
  31. using namespace llvm;
  32. #define DEBUG_TYPE "loop-delete"
  33. STATISTIC(NumDeleted, "Number of loops deleted");
  34. STATISTIC(NumBackedgesBroken,
  35. "Number of loops for which we managed to break the backedge");
  36. static cl::opt<bool> EnableSymbolicExecution(
  37. "loop-deletion-enable-symbolic-execution", cl::Hidden, cl::init(true),
  38. cl::desc("Break backedge through symbolic execution of 1st iteration "
  39. "attempting to prove that the backedge is never taken"));
  40. enum class LoopDeletionResult {
  41. Unmodified,
  42. Modified,
  43. Deleted,
  44. };
  45. static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B) {
  46. if (A == LoopDeletionResult::Deleted || B == LoopDeletionResult::Deleted)
  47. return LoopDeletionResult::Deleted;
  48. if (A == LoopDeletionResult::Modified || B == LoopDeletionResult::Modified)
  49. return LoopDeletionResult::Modified;
  50. return LoopDeletionResult::Unmodified;
  51. }
  52. /// Determines if a loop is dead.
  53. ///
  54. /// This assumes that we've already checked for unique exit and exiting blocks,
  55. /// and that the code is in LCSSA form.
  56. static bool isLoopDead(Loop *L, ScalarEvolution &SE,
  57. SmallVectorImpl<BasicBlock *> &ExitingBlocks,
  58. BasicBlock *ExitBlock, bool &Changed,
  59. BasicBlock *Preheader, LoopInfo &LI) {
  60. // Make sure that all PHI entries coming from the loop are loop invariant.
  61. // Because the code is in LCSSA form, any values used outside of the loop
  62. // must pass through a PHI in the exit block, meaning that this check is
  63. // sufficient to guarantee that no loop-variant values are used outside
  64. // of the loop.
  65. bool AllEntriesInvariant = true;
  66. bool AllOutgoingValuesSame = true;
  67. if (!L->hasNoExitBlocks()) {
  68. for (PHINode &P : ExitBlock->phis()) {
  69. Value *incoming = P.getIncomingValueForBlock(ExitingBlocks[0]);
  70. // Make sure all exiting blocks produce the same incoming value for the
  71. // block. If there are different incoming values for different exiting
  72. // blocks, then it is impossible to statically determine which value
  73. // should be used.
  74. AllOutgoingValuesSame =
  75. all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) {
  76. return incoming == P.getIncomingValueForBlock(BB);
  77. });
  78. if (!AllOutgoingValuesSame)
  79. break;
  80. if (Instruction *I = dyn_cast<Instruction>(incoming))
  81. if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) {
  82. AllEntriesInvariant = false;
  83. break;
  84. }
  85. }
  86. }
  87. if (Changed)
  88. SE.forgetLoopDispositions(L);
  89. if (!AllEntriesInvariant || !AllOutgoingValuesSame)
  90. return false;
  91. // Make sure that no instructions in the block have potential side-effects.
  92. // This includes instructions that could write to memory, and loads that are
  93. // marked volatile.
  94. for (auto &I : L->blocks())
  95. if (any_of(*I, [](Instruction &I) {
  96. return I.mayHaveSideEffects() && !I.isDroppable();
  97. }))
  98. return false;
  99. // The loop or any of its sub-loops looping infinitely is legal. The loop can
  100. // only be considered dead if either
  101. // a. the function is mustprogress.
  102. // b. all (sub-)loops are mustprogress or have a known trip-count.
  103. if (L->getHeader()->getParent()->mustProgress())
  104. return true;
  105. LoopBlocksRPO RPOT(L);
  106. RPOT.perform(&LI);
  107. // If the loop contains an irreducible cycle, it may loop infinitely.
  108. if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
  109. return false;
  110. SmallVector<Loop *, 8> WorkList;
  111. WorkList.push_back(L);
  112. while (!WorkList.empty()) {
  113. Loop *Current = WorkList.pop_back_val();
  114. if (hasMustProgress(Current))
  115. continue;
  116. const SCEV *S = SE.getConstantMaxBackedgeTakenCount(Current);
  117. if (isa<SCEVCouldNotCompute>(S)) {
  118. LLVM_DEBUG(
  119. dbgs() << "Could not compute SCEV MaxBackedgeTakenCount and was "
  120. "not required to make progress.\n");
  121. return false;
  122. }
  123. WorkList.append(Current->begin(), Current->end());
  124. }
  125. return true;
  126. }
  127. /// This function returns true if there is no viable path from the
  128. /// entry block to the header of \p L. Right now, it only does
  129. /// a local search to save compile time.
  130. static bool isLoopNeverExecuted(Loop *L) {
  131. using namespace PatternMatch;
  132. auto *Preheader = L->getLoopPreheader();
  133. // TODO: We can relax this constraint, since we just need a loop
  134. // predecessor.
  135. assert(Preheader && "Needs preheader!");
  136. if (Preheader->isEntryBlock())
  137. return false;
  138. // All predecessors of the preheader should have a constant conditional
  139. // branch, with the loop's preheader as not-taken.
  140. for (auto *Pred: predecessors(Preheader)) {
  141. BasicBlock *Taken, *NotTaken;
  142. ConstantInt *Cond;
  143. if (!match(Pred->getTerminator(),
  144. m_Br(m_ConstantInt(Cond), Taken, NotTaken)))
  145. return false;
  146. if (!Cond->getZExtValue())
  147. std::swap(Taken, NotTaken);
  148. if (Taken == Preheader)
  149. return false;
  150. }
  151. assert(!pred_empty(Preheader) &&
  152. "Preheader should have predecessors at this point!");
  153. // All the predecessors have the loop preheader as not-taken target.
  154. return true;
  155. }
  156. static Value *
  157. getValueOnFirstIteration(Value *V, DenseMap<Value *, Value *> &FirstIterValue,
  158. const SimplifyQuery &SQ) {
  159. // Quick hack: do not flood cache with non-instruction values.
  160. if (!isa<Instruction>(V))
  161. return V;
  162. // Do we already know cached result?
  163. auto Existing = FirstIterValue.find(V);
  164. if (Existing != FirstIterValue.end())
  165. return Existing->second;
  166. Value *FirstIterV = nullptr;
  167. if (auto *BO = dyn_cast<BinaryOperator>(V)) {
  168. Value *LHS =
  169. getValueOnFirstIteration(BO->getOperand(0), FirstIterValue, SQ);
  170. Value *RHS =
  171. getValueOnFirstIteration(BO->getOperand(1), FirstIterValue, SQ);
  172. FirstIterV = SimplifyBinOp(BO->getOpcode(), LHS, RHS, SQ);
  173. } else if (auto *Cmp = dyn_cast<ICmpInst>(V)) {
  174. Value *LHS =
  175. getValueOnFirstIteration(Cmp->getOperand(0), FirstIterValue, SQ);
  176. Value *RHS =
  177. getValueOnFirstIteration(Cmp->getOperand(1), FirstIterValue, SQ);
  178. FirstIterV = SimplifyICmpInst(Cmp->getPredicate(), LHS, RHS, SQ);
  179. } else if (auto *Select = dyn_cast<SelectInst>(V)) {
  180. Value *Cond =
  181. getValueOnFirstIteration(Select->getCondition(), FirstIterValue, SQ);
  182. if (auto *C = dyn_cast<ConstantInt>(Cond)) {
  183. auto *Selected = C->isAllOnesValue() ? Select->getTrueValue()
  184. : Select->getFalseValue();
  185. FirstIterV = getValueOnFirstIteration(Selected, FirstIterValue, SQ);
  186. }
  187. }
  188. if (!FirstIterV)
  189. FirstIterV = V;
  190. FirstIterValue[V] = FirstIterV;
  191. return FirstIterV;
  192. }
  193. // Try to prove that one of conditions that dominates the latch must exit on 1st
  194. // iteration.
  195. static bool canProveExitOnFirstIteration(Loop *L, DominatorTree &DT,
  196. LoopInfo &LI) {
  197. // Disabled by option.
  198. if (!EnableSymbolicExecution)
  199. return false;
  200. BasicBlock *Predecessor = L->getLoopPredecessor();
  201. BasicBlock *Latch = L->getLoopLatch();
  202. if (!Predecessor || !Latch)
  203. return false;
  204. LoopBlocksRPO RPOT(L);
  205. RPOT.perform(&LI);
  206. // For the optimization to be correct, we need RPOT to have a property that
  207. // each block is processed after all its predecessors, which may only be
  208. // violated for headers of the current loop and all nested loops. Irreducible
  209. // CFG provides multiple ways to break this assumption, so we do not want to
  210. // deal with it.
  211. if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
  212. return false;
  213. BasicBlock *Header = L->getHeader();
  214. // Blocks that are reachable on the 1st iteration.
  215. SmallPtrSet<BasicBlock *, 4> LiveBlocks;
  216. // Edges that are reachable on the 1st iteration.
  217. DenseSet<BasicBlockEdge> LiveEdges;
  218. LiveBlocks.insert(Header);
  219. SmallPtrSet<BasicBlock *, 4> Visited;
  220. auto MarkLiveEdge = [&](BasicBlock *From, BasicBlock *To) {
  221. assert(LiveBlocks.count(From) && "Must be live!");
  222. assert((LI.isLoopHeader(To) || !Visited.count(To)) &&
  223. "Only canonical backedges are allowed. Irreducible CFG?");
  224. assert((LiveBlocks.count(To) || !Visited.count(To)) &&
  225. "We already discarded this block as dead!");
  226. LiveBlocks.insert(To);
  227. LiveEdges.insert({ From, To });
  228. };
  229. auto MarkAllSuccessorsLive = [&](BasicBlock *BB) {
  230. for (auto *Succ : successors(BB))
  231. MarkLiveEdge(BB, Succ);
  232. };
  233. // Check if there is only one value coming from all live predecessor blocks.
  234. // Note that because we iterate in RPOT, we have already visited all its
  235. // (non-latch) predecessors.
  236. auto GetSoleInputOnFirstIteration = [&](PHINode & PN)->Value * {
  237. BasicBlock *BB = PN.getParent();
  238. bool HasLivePreds = false;
  239. (void)HasLivePreds;
  240. if (BB == Header)
  241. return PN.getIncomingValueForBlock(Predecessor);
  242. Value *OnlyInput = nullptr;
  243. for (auto *Pred : predecessors(BB))
  244. if (LiveEdges.count({ Pred, BB })) {
  245. HasLivePreds = true;
  246. Value *Incoming = PN.getIncomingValueForBlock(Pred);
  247. // Skip undefs. If they are present, we can assume they are equal to
  248. // the non-undef input.
  249. if (isa<UndefValue>(Incoming))
  250. continue;
  251. // Two inputs.
  252. if (OnlyInput && OnlyInput != Incoming)
  253. return nullptr;
  254. OnlyInput = Incoming;
  255. }
  256. assert(HasLivePreds && "No live predecessors?");
  257. // If all incoming live value were undefs, return undef.
  258. return OnlyInput ? OnlyInput : UndefValue::get(PN.getType());
  259. };
  260. DenseMap<Value *, Value *> FirstIterValue;
  261. // Use the following algorithm to prove we never take the latch on the 1st
  262. // iteration:
  263. // 1. Traverse in topological order, so that whenever we visit a block, all
  264. // its predecessors are already visited.
  265. // 2. If we can prove that the block may have only 1 predecessor on the 1st
  266. // iteration, map all its phis onto input from this predecessor.
  267. // 3a. If we can prove which successor of out block is taken on the 1st
  268. // iteration, mark this successor live.
  269. // 3b. If we cannot prove it, conservatively assume that all successors are
  270. // live.
  271. auto &DL = Header->getModule()->getDataLayout();
  272. const SimplifyQuery SQ(DL);
  273. for (auto *BB : RPOT) {
  274. Visited.insert(BB);
  275. // This block is not reachable on the 1st iterations.
  276. if (!LiveBlocks.count(BB))
  277. continue;
  278. // Skip inner loops.
  279. if (LI.getLoopFor(BB) != L) {
  280. MarkAllSuccessorsLive(BB);
  281. continue;
  282. }
  283. // If Phi has only one input from all live input blocks, use it.
  284. for (auto &PN : BB->phis()) {
  285. if (!PN.getType()->isIntegerTy())
  286. continue;
  287. auto *Incoming = GetSoleInputOnFirstIteration(PN);
  288. if (Incoming && DT.dominates(Incoming, BB->getTerminator())) {
  289. Value *FirstIterV =
  290. getValueOnFirstIteration(Incoming, FirstIterValue, SQ);
  291. FirstIterValue[&PN] = FirstIterV;
  292. }
  293. }
  294. using namespace PatternMatch;
  295. Value *Cond;
  296. BasicBlock *IfTrue, *IfFalse;
  297. auto *Term = BB->getTerminator();
  298. if (match(Term, m_Br(m_Value(Cond),
  299. m_BasicBlock(IfTrue), m_BasicBlock(IfFalse)))) {
  300. auto *ICmp = dyn_cast<ICmpInst>(Cond);
  301. if (!ICmp || !ICmp->getType()->isIntegerTy()) {
  302. MarkAllSuccessorsLive(BB);
  303. continue;
  304. }
  305. // Can we prove constant true or false for this condition?
  306. auto *KnownCondition = getValueOnFirstIteration(ICmp, FirstIterValue, SQ);
  307. if (KnownCondition == ICmp) {
  308. // Failed to simplify.
  309. MarkAllSuccessorsLive(BB);
  310. continue;
  311. }
  312. if (isa<UndefValue>(KnownCondition)) {
  313. // TODO: According to langref, branching by undef is undefined behavior.
  314. // It means that, theoretically, we should be able to just continue
  315. // without marking any successors as live. However, we are not certain
  316. // how correct our compiler is at handling such cases. So we are being
  317. // very conservative here.
  318. //
  319. // If there is a non-loop successor, always assume this branch leaves the
  320. // loop. Otherwise, arbitrarily take IfTrue.
  321. //
  322. // Once we are certain that branching by undef is handled correctly by
  323. // other transforms, we should not mark any successors live here.
  324. if (L->contains(IfTrue) && L->contains(IfFalse))
  325. MarkLiveEdge(BB, IfTrue);
  326. continue;
  327. }
  328. auto *ConstCondition = dyn_cast<ConstantInt>(KnownCondition);
  329. if (!ConstCondition) {
  330. // Non-constant condition, cannot analyze any further.
  331. MarkAllSuccessorsLive(BB);
  332. continue;
  333. }
  334. if (ConstCondition->isAllOnesValue())
  335. MarkLiveEdge(BB, IfTrue);
  336. else
  337. MarkLiveEdge(BB, IfFalse);
  338. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
  339. auto *SwitchValue = SI->getCondition();
  340. auto *SwitchValueOnFirstIter =
  341. getValueOnFirstIteration(SwitchValue, FirstIterValue, SQ);
  342. auto *ConstSwitchValue = dyn_cast<ConstantInt>(SwitchValueOnFirstIter);
  343. if (!ConstSwitchValue) {
  344. MarkAllSuccessorsLive(BB);
  345. continue;
  346. }
  347. auto CaseIterator = SI->findCaseValue(ConstSwitchValue);
  348. MarkLiveEdge(BB, CaseIterator->getCaseSuccessor());
  349. } else {
  350. MarkAllSuccessorsLive(BB);
  351. continue;
  352. }
  353. }
  354. // We can break the latch if it wasn't live.
  355. return !LiveEdges.count({ Latch, Header });
  356. }
  357. /// If we can prove the backedge is untaken, remove it. This destroys the
  358. /// loop, but leaves the (now trivially loop invariant) control flow and
  359. /// side effects (if any) in place.
  360. static LoopDeletionResult
  361. breakBackedgeIfNotTaken(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
  362. LoopInfo &LI, MemorySSA *MSSA,
  363. OptimizationRemarkEmitter &ORE) {
  364. assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
  365. if (!L->getLoopLatch())
  366. return LoopDeletionResult::Unmodified;
  367. auto *BTCMax = SE.getConstantMaxBackedgeTakenCount(L);
  368. if (!BTCMax->isZero()) {
  369. auto *BTC = SE.getBackedgeTakenCount(L);
  370. if (!BTC->isZero()) {
  371. if (!isa<SCEVCouldNotCompute>(BTC) && SE.isKnownNonZero(BTC))
  372. return LoopDeletionResult::Unmodified;
  373. if (!canProveExitOnFirstIteration(L, DT, LI))
  374. return LoopDeletionResult::Unmodified;
  375. }
  376. }
  377. ++NumBackedgesBroken;
  378. breakLoopBackedge(L, DT, SE, LI, MSSA);
  379. return LoopDeletionResult::Deleted;
  380. }
  381. /// Remove a loop if it is dead.
  382. ///
  383. /// A loop is considered dead either if it does not impact the observable
  384. /// behavior of the program other than finite running time, or if it is
  385. /// required to make progress by an attribute such as 'mustprogress' or
  386. /// 'llvm.loop.mustprogress' and does not make any. This may remove
  387. /// infinite loops that have been required to make progress.
  388. ///
  389. /// This entire process relies pretty heavily on LoopSimplify form and LCSSA in
  390. /// order to make various safety checks work.
  391. ///
  392. /// \returns true if any changes were made. This may mutate the loop even if it
  393. /// is unable to delete it due to hoisting trivially loop invariant
  394. /// instructions out of the loop.
  395. static LoopDeletionResult deleteLoopIfDead(Loop *L, DominatorTree &DT,
  396. ScalarEvolution &SE, LoopInfo &LI,
  397. MemorySSA *MSSA,
  398. OptimizationRemarkEmitter &ORE) {
  399. assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
  400. // We can only remove the loop if there is a preheader that we can branch from
  401. // after removing it. Also, if LoopSimplify form is not available, stay out
  402. // of trouble.
  403. BasicBlock *Preheader = L->getLoopPreheader();
  404. if (!Preheader || !L->hasDedicatedExits()) {
  405. LLVM_DEBUG(
  406. dbgs()
  407. << "Deletion requires Loop with preheader and dedicated exits.\n");
  408. return LoopDeletionResult::Unmodified;
  409. }
  410. BasicBlock *ExitBlock = L->getUniqueExitBlock();
  411. if (ExitBlock && isLoopNeverExecuted(L)) {
  412. LLVM_DEBUG(dbgs() << "Loop is proven to never execute, delete it!");
  413. // We need to forget the loop before setting the incoming values of the exit
  414. // phis to undef, so we properly invalidate the SCEV expressions for those
  415. // phis.
  416. SE.forgetLoop(L);
  417. // Set incoming value to undef for phi nodes in the exit block.
  418. for (PHINode &P : ExitBlock->phis()) {
  419. std::fill(P.incoming_values().begin(), P.incoming_values().end(),
  420. UndefValue::get(P.getType()));
  421. }
  422. ORE.emit([&]() {
  423. return OptimizationRemark(DEBUG_TYPE, "NeverExecutes", L->getStartLoc(),
  424. L->getHeader())
  425. << "Loop deleted because it never executes";
  426. });
  427. deleteDeadLoop(L, &DT, &SE, &LI, MSSA);
  428. ++NumDeleted;
  429. return LoopDeletionResult::Deleted;
  430. }
  431. // The remaining checks below are for a loop being dead because all statements
  432. // in the loop are invariant.
  433. SmallVector<BasicBlock *, 4> ExitingBlocks;
  434. L->getExitingBlocks(ExitingBlocks);
  435. // We require that the loop has at most one exit block. Otherwise, we'd be in
  436. // the situation of needing to be able to solve statically which exit block
  437. // will be branched to, or trying to preserve the branching logic in a loop
  438. // invariant manner.
  439. if (!ExitBlock && !L->hasNoExitBlocks()) {
  440. LLVM_DEBUG(dbgs() << "Deletion requires at most one exit block.\n");
  441. return LoopDeletionResult::Unmodified;
  442. }
  443. // Finally, we have to check that the loop really is dead.
  444. bool Changed = false;
  445. if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader, LI)) {
  446. LLVM_DEBUG(dbgs() << "Loop is not invariant, cannot delete.\n");
  447. return Changed ? LoopDeletionResult::Modified
  448. : LoopDeletionResult::Unmodified;
  449. }
  450. LLVM_DEBUG(dbgs() << "Loop is invariant, delete it!");
  451. ORE.emit([&]() {
  452. return OptimizationRemark(DEBUG_TYPE, "Invariant", L->getStartLoc(),
  453. L->getHeader())
  454. << "Loop deleted because it is invariant";
  455. });
  456. deleteDeadLoop(L, &DT, &SE, &LI, MSSA);
  457. ++NumDeleted;
  458. return LoopDeletionResult::Deleted;
  459. }
  460. PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM,
  461. LoopStandardAnalysisResults &AR,
  462. LPMUpdater &Updater) {
  463. LLVM_DEBUG(dbgs() << "Analyzing Loop for deletion: ");
  464. LLVM_DEBUG(L.dump());
  465. std::string LoopName = std::string(L.getName());
  466. // For the new PM, we can't use OptimizationRemarkEmitter as an analysis
  467. // pass. Function analyses need to be preserved across loop transformations
  468. // but ORE cannot be preserved (see comment before the pass definition).
  469. OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
  470. auto Result = deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, AR.MSSA, ORE);
  471. // If we can prove the backedge isn't taken, just break it and be done. This
  472. // leaves the loop structure in place which means it can handle dispatching
  473. // to the right exit based on whatever loop invariant structure remains.
  474. if (Result != LoopDeletionResult::Deleted)
  475. Result = merge(Result, breakBackedgeIfNotTaken(&L, AR.DT, AR.SE, AR.LI,
  476. AR.MSSA, ORE));
  477. if (Result == LoopDeletionResult::Unmodified)
  478. return PreservedAnalyses::all();
  479. if (Result == LoopDeletionResult::Deleted)
  480. Updater.markLoopAsDeleted(L, LoopName);
  481. auto PA = getLoopPassPreservedAnalyses();
  482. if (AR.MSSA)
  483. PA.preserve<MemorySSAAnalysis>();
  484. return PA;
  485. }
  486. namespace {
  487. class LoopDeletionLegacyPass : public LoopPass {
  488. public:
  489. static char ID; // Pass ID, replacement for typeid
  490. LoopDeletionLegacyPass() : LoopPass(ID) {
  491. initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry());
  492. }
  493. // Possibly eliminate loop L if it is dead.
  494. bool runOnLoop(Loop *L, LPPassManager &) override;
  495. void getAnalysisUsage(AnalysisUsage &AU) const override {
  496. AU.addPreserved<MemorySSAWrapperPass>();
  497. getLoopAnalysisUsage(AU);
  498. }
  499. };
  500. }
  501. char LoopDeletionLegacyPass::ID = 0;
  502. INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion",
  503. "Delete dead loops", false, false)
  504. INITIALIZE_PASS_DEPENDENCY(LoopPass)
  505. INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion",
  506. "Delete dead loops", false, false)
  507. Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); }
  508. bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
  509. if (skipLoop(L))
  510. return false;
  511. DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  512. ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  513. LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  514. auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>();
  515. MemorySSA *MSSA = nullptr;
  516. if (MSSAAnalysis)
  517. MSSA = &MSSAAnalysis->getMSSA();
  518. // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
  519. // pass. Function analyses need to be preserved across loop transformations
  520. // but ORE cannot be preserved (see comment before the pass definition).
  521. OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
  522. LLVM_DEBUG(dbgs() << "Analyzing Loop for deletion: ");
  523. LLVM_DEBUG(L->dump());
  524. LoopDeletionResult Result = deleteLoopIfDead(L, DT, SE, LI, MSSA, ORE);
  525. // If we can prove the backedge isn't taken, just break it and be done. This
  526. // leaves the loop structure in place which means it can handle dispatching
  527. // to the right exit based on whatever loop invariant structure remains.
  528. if (Result != LoopDeletionResult::Deleted)
  529. Result = merge(Result, breakBackedgeIfNotTaken(L, DT, SE, LI, MSSA, ORE));
  530. if (Result == LoopDeletionResult::Deleted)
  531. LPM.markLoopAsDeleted(*L);
  532. return Result != LoopDeletionResult::Unmodified;
  533. }