1 //===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Dead Loop Deletion Pass. This pass is responsible
11 // for eliminating loops with non-infinite computable trip counts that have no
12 // side effects or volatile instructions, and do not contribute to the
13 // computation of the function's return value.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Scalar/LoopDeletion.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/GlobalsModRef.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Transforms/Scalar/LoopPassManager.h"
25 #include "llvm/Transforms/Utils/LoopUtils.h"
28 #define DEBUG_TYPE "loop-delete"
30 STATISTIC(NumDeleted, "Number of loops deleted");
32 /// Determines if a loop is dead.
34 /// This assumes that we've already checked for unique exit and exiting blocks,
35 /// and that the code is in LCSSA form.
36 static bool isLoopDead(Loop *L, ScalarEvolution &SE,
37 SmallVectorImpl<BasicBlock *> &ExitingBlocks,
38 BasicBlock *ExitBlock, bool &Changed,
39 BasicBlock *Preheader) {
40 // Make sure that all PHI entries coming from the loop are loop invariant.
41 // Because the code is in LCSSA form, any values used outside of the loop
42 // must pass through a PHI in the exit block, meaning that this check is
43 // sufficient to guarantee that no loop-variant values are used outside
45 BasicBlock::iterator BI = ExitBlock->begin();
46 bool AllEntriesInvariant = true;
47 bool AllOutgoingValuesSame = true;
48 while (PHINode *P = dyn_cast<PHINode>(BI)) {
49 Value *incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
51 // Make sure all exiting blocks produce the same incoming value for the exit
52 // block. If there are different incoming values for different exiting
53 // blocks, then it is impossible to statically determine which value should
55 AllOutgoingValuesSame =
56 all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) {
57 return incoming == P->getIncomingValueForBlock(BB);
60 if (!AllOutgoingValuesSame)
63 if (Instruction *I = dyn_cast<Instruction>(incoming))
64 if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) {
65 AllEntriesInvariant = false;
73 SE.forgetLoopDispositions(L);
75 if (!AllEntriesInvariant || !AllOutgoingValuesSame)
78 // Make sure that no instructions in the block have potential side-effects.
79 // This includes instructions that could write to memory, and loads that are
81 for (auto &I : L->blocks())
82 if (any_of(*I, [](Instruction &I) { return I.mayHaveSideEffects(); }))
87 /// Remove a loop if it is dead.
89 /// A loop is considered dead if it does not impact the observable behavior of
90 /// the program other than finite running time. This never removes a loop that
91 /// might be infinite, as doing so could change the halting/non-halting nature
94 /// This entire process relies pretty heavily on LoopSimplify form and LCSSA in
95 /// order to make various safety checks work.
97 /// \returns true if any changes were made. This may mutate the loop even if it
98 /// is unable to delete it due to hoisting trivially loop invariant
99 /// instructions out of the loop.
101 /// This also updates the relevant analysis information in \p DT, \p SE, and \p
102 /// LI. It also updates the loop PM if an updater struct is provided.
103 static bool deleteLoopIfDead(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
104 LoopInfo &LI, LPMUpdater *Updater = nullptr) {
105 assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
107 // We can only remove the loop if there is a preheader that we can
108 // branch from after removing it.
109 BasicBlock *Preheader = L->getLoopPreheader();
113 // If LoopSimplify form is not available, stay out of trouble.
114 if (!L->hasDedicatedExits())
117 // We can't remove loops that contain subloops. If the subloops were dead,
118 // they would already have been removed in earlier executions of this pass.
119 if (L->begin() != L->end())
122 SmallVector<BasicBlock *, 4> ExitingBlocks;
123 L->getExitingBlocks(ExitingBlocks);
125 // We require that the loop only have a single exit block. Otherwise, we'd
126 // be in the situation of needing to be able to solve statically which exit
127 // block will be branched to, or trying to preserve the branching logic in
128 // a loop invariant manner.
129 BasicBlock *ExitBlock = L->getUniqueExitBlock();
133 // Finally, we have to check that the loop really is dead.
134 bool Changed = false;
135 if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader))
138 // Don't remove loops for which we can't solve the trip count.
139 // They could be infinite, in which case we'd be changing program behavior.
140 const SCEV *S = SE.getMaxBackedgeTakenCount(L);
141 if (isa<SCEVCouldNotCompute>(S))
144 // Now that we know the removal is safe, remove the loop by changing the
145 // branch from the preheader to go to the single exit block.
147 // Because we're deleting a large chunk of code at once, the sequence in which
148 // we remove things is very important to avoid invalidation issues.
150 // If we have an LPM updater, tell it about the loop being removed.
152 Updater->markLoopAsDeleted(*L);
154 // Tell ScalarEvolution that the loop is deleted. Do this before
155 // deleting the loop so that ScalarEvolution can look at the loop
156 // to determine what it needs to clean up.
159 // Connect the preheader directly to the exit block.
160 TerminatorInst *TI = Preheader->getTerminator();
161 TI->replaceUsesOfWith(L->getHeader(), ExitBlock);
163 // Rewrite phis in the exit block to get their inputs from
164 // the preheader instead of the exiting block.
165 BasicBlock *ExitingBlock = ExitingBlocks[0];
166 BasicBlock::iterator BI = ExitBlock->begin();
167 while (PHINode *P = dyn_cast<PHINode>(BI)) {
168 int j = P->getBasicBlockIndex(ExitingBlock);
169 assert(j >= 0 && "Can't find exiting block in exit block's phi node!");
170 P->setIncomingBlock(j, Preheader);
171 for (unsigned i = 1; i < ExitingBlocks.size(); ++i)
172 P->removeIncomingValue(ExitingBlocks[i]);
176 // Update the dominator tree and remove the instructions and blocks that will
177 // be deleted from the reference counting scheme.
178 SmallVector<DomTreeNode*, 8> ChildNodes;
179 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
181 // Move all of the block's children to be children of the Preheader, which
182 // allows us to remove the domtree entry for the block.
183 ChildNodes.insert(ChildNodes.begin(), DT[*LI]->begin(), DT[*LI]->end());
184 for (DomTreeNode *ChildNode : ChildNodes) {
185 DT.changeImmediateDominator(ChildNode, DT[Preheader]);
191 // Remove the block from the reference counting scheme, so that we can
192 // delete it freely later.
193 (*LI)->dropAllReferences();
196 // Erase the instructions and the blocks without having to worry
197 // about ordering because we already dropped the references.
198 // NOTE: This iteration is safe because erasing the block does not remove its
199 // entry from the loop's block list. We do that in the next section.
200 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
202 (*LI)->eraseFromParent();
204 // Finally, the blocks from loopinfo. This has to happen late because
205 // otherwise our loop iterators won't work.
207 SmallPtrSet<BasicBlock *, 8> blocks;
208 blocks.insert(L->block_begin(), L->block_end());
209 for (BasicBlock *BB : blocks)
212 // The last step is to update LoopInfo now that we've eliminated this loop.
219 PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM,
220 LoopStandardAnalysisResults &AR,
221 LPMUpdater &Updater) {
222 if (!deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, &Updater))
223 return PreservedAnalyses::all();
225 return getLoopPassPreservedAnalyses();
229 class LoopDeletionLegacyPass : public LoopPass {
231 static char ID; // Pass ID, replacement for typeid
232 LoopDeletionLegacyPass() : LoopPass(ID) {
233 initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry());
236 // Possibly eliminate loop L if it is dead.
237 bool runOnLoop(Loop *L, LPPassManager &) override;
239 void getAnalysisUsage(AnalysisUsage &AU) const override {
240 getLoopAnalysisUsage(AU);
245 char LoopDeletionLegacyPass::ID = 0;
246 INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion",
247 "Delete dead loops", false, false)
248 INITIALIZE_PASS_DEPENDENCY(LoopPass)
249 INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion",
250 "Delete dead loops", false, false)
252 Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); }
254 bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &) {
258 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
259 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
260 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
262 return deleteLoopIfDead(L, DT, SE, LI);