1 //===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file 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.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/Transforms/Scalar.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/Analysis/ScalarEvolution.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/Transforms/Utils/LoopUtils.h"
25 using namespace llvm;
26 
27 #define DEBUG_TYPE "loop-delete"
28 
29 STATISTIC(NumDeleted, "Number of loops deleted");
30 
31 namespace {
32   class LoopDeletion : public LoopPass {
33   public:
34     static char ID; // Pass ID, replacement for typeid
35     LoopDeletion() : LoopPass(ID) {
36       initializeLoopDeletionPass(*PassRegistry::getPassRegistry());
37     }
38 
39     // Possibly eliminate loop L if it is dead.
40     bool runOnLoop(Loop *L, LPPassManager &) override;
41 
42     void getAnalysisUsage(AnalysisUsage &AU) const override {
43       getLoopAnalysisUsage(AU);
44     }
45 
46   private:
47     bool isLoopDead(Loop *L, ScalarEvolution &SE,
48                     SmallVectorImpl<BasicBlock *> &exitingBlocks,
49                     SmallVectorImpl<BasicBlock *> &exitBlocks, bool &Changed,
50                     BasicBlock *Preheader);
51   };
52 }
53 
54 char LoopDeletion::ID = 0;
55 INITIALIZE_PASS_BEGIN(LoopDeletion, "loop-deletion",
56                 "Delete dead loops", false, false)
57 INITIALIZE_PASS_DEPENDENCY(LoopPass)
58 INITIALIZE_PASS_END(LoopDeletion, "loop-deletion",
59                 "Delete dead loops", false, false)
60 
61 Pass *llvm::createLoopDeletionPass() {
62   return new LoopDeletion();
63 }
64 
65 /// isLoopDead - Determined if a loop is dead.  This assumes that we've already
66 /// checked for unique exit and exiting blocks, and that the code is in LCSSA
67 /// form.
68 bool LoopDeletion::isLoopDead(Loop *L, ScalarEvolution &SE,
69                               SmallVectorImpl<BasicBlock *> &exitingBlocks,
70                               SmallVectorImpl<BasicBlock *> &exitBlocks,
71                               bool &Changed, BasicBlock *Preheader) {
72   BasicBlock *exitBlock = exitBlocks[0];
73 
74   // Make sure that all PHI entries coming from the loop are loop invariant.
75   // Because the code is in LCSSA form, any values used outside of the loop
76   // must pass through a PHI in the exit block, meaning that this check is
77   // sufficient to guarantee that no loop-variant values are used outside
78   // of the loop.
79   BasicBlock::iterator BI = exitBlock->begin();
80   bool AllEntriesInvariant = true;
81   bool AllOutgoingValuesSame = true;
82   while (PHINode *P = dyn_cast<PHINode>(BI)) {
83     Value *incoming = P->getIncomingValueForBlock(exitingBlocks[0]);
84 
85     // Make sure all exiting blocks produce the same incoming value for the exit
86     // block.  If there are different incoming values for different exiting
87     // blocks, then it is impossible to statically determine which value should
88     // be used.
89     AllOutgoingValuesSame =
90         all_of(makeArrayRef(exitingBlocks).slice(1), [&](BasicBlock *BB) {
91           return incoming == P->getIncomingValueForBlock(BB);
92         });
93 
94     if (!AllOutgoingValuesSame)
95       break;
96 
97     if (Instruction *I = dyn_cast<Instruction>(incoming))
98       if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) {
99         AllEntriesInvariant = false;
100         break;
101       }
102 
103     ++BI;
104   }
105 
106   if (Changed)
107     SE.forgetLoopDispositions(L);
108 
109   if (!AllEntriesInvariant || !AllOutgoingValuesSame)
110     return false;
111 
112   // Make sure that no instructions in the block have potential side-effects.
113   // This includes instructions that could write to memory, and loads that are
114   // marked volatile.  This could be made more aggressive by using aliasing
115   // information to identify readonly and readnone calls.
116   for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
117        LI != LE; ++LI) {
118     for (BasicBlock::iterator BI = (*LI)->begin(), BE = (*LI)->end();
119          BI != BE; ++BI) {
120       if (BI->mayHaveSideEffects())
121         return false;
122     }
123   }
124 
125   return true;
126 }
127 
128 /// runOnLoop - Remove dead loops, by which we mean loops that do not impact the
129 /// observable behavior of the program other than finite running time.  Note
130 /// we do ensure that this never remove a loop that might be infinite, as doing
131 /// so could change the halting/non-halting nature of a program.
132 /// NOTE: This entire process relies pretty heavily on LoopSimplify and LCSSA
133 /// in order to make various safety checks work.
134 bool LoopDeletion::runOnLoop(Loop *L, LPPassManager &) {
135   if (skipLoop(L))
136     return false;
137 
138   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
139   assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
140 
141   // We can only remove the loop if there is a preheader that we can
142   // branch from after removing it.
143   BasicBlock *preheader = L->getLoopPreheader();
144   if (!preheader)
145     return false;
146 
147   // If LoopSimplify form is not available, stay out of trouble.
148   if (!L->hasDedicatedExits())
149     return false;
150 
151   // We can't remove loops that contain subloops.  If the subloops were dead,
152   // they would already have been removed in earlier executions of this pass.
153   if (L->begin() != L->end())
154     return false;
155 
156   SmallVector<BasicBlock*, 4> exitingBlocks;
157   L->getExitingBlocks(exitingBlocks);
158 
159   SmallVector<BasicBlock*, 4> exitBlocks;
160   L->getUniqueExitBlocks(exitBlocks);
161 
162   // We require that the loop only have a single exit block.  Otherwise, we'd
163   // be in the situation of needing to be able to solve statically which exit
164   // block will be branched to, or trying to preserve the branching logic in
165   // a loop invariant manner.
166   if (exitBlocks.size() != 1)
167     return false;
168 
169   ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
170 
171   // Finally, we have to check that the loop really is dead.
172   bool Changed = false;
173   if (!isLoopDead(L, SE, exitingBlocks, exitBlocks, Changed, preheader))
174     return Changed;
175 
176   // Don't remove loops for which we can't solve the trip count.
177   // They could be infinite, in which case we'd be changing program behavior.
178   const SCEV *S = SE.getMaxBackedgeTakenCount(L);
179   if (isa<SCEVCouldNotCompute>(S))
180     return Changed;
181 
182   // Now that we know the removal is safe, remove the loop by changing the
183   // branch from the preheader to go to the single exit block.
184   BasicBlock *exitBlock = exitBlocks[0];
185 
186   // Because we're deleting a large chunk of code at once, the sequence in which
187   // we remove things is very important to avoid invalidation issues.  Don't
188   // mess with this unless you have good reason and know what you're doing.
189 
190   // Tell ScalarEvolution that the loop is deleted. Do this before
191   // deleting the loop so that ScalarEvolution can look at the loop
192   // to determine what it needs to clean up.
193   SE.forgetLoop(L);
194 
195   // Connect the preheader directly to the exit block.
196   TerminatorInst *TI = preheader->getTerminator();
197   TI->replaceUsesOfWith(L->getHeader(), exitBlock);
198 
199   // Rewrite phis in the exit block to get their inputs from
200   // the preheader instead of the exiting block.
201   BasicBlock *exitingBlock = exitingBlocks[0];
202   BasicBlock::iterator BI = exitBlock->begin();
203   while (PHINode *P = dyn_cast<PHINode>(BI)) {
204     int j = P->getBasicBlockIndex(exitingBlock);
205     assert(j >= 0 && "Can't find exiting block in exit block's phi node!");
206     P->setIncomingBlock(j, preheader);
207     for (unsigned i = 1; i < exitingBlocks.size(); ++i)
208       P->removeIncomingValue(exitingBlocks[i]);
209     ++BI;
210   }
211 
212   // Update the dominator tree and remove the instructions and blocks that will
213   // be deleted from the reference counting scheme.
214   SmallVector<DomTreeNode*, 8> ChildNodes;
215   for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
216        LI != LE; ++LI) {
217     // Move all of the block's children to be children of the preheader, which
218     // allows us to remove the domtree entry for the block.
219     ChildNodes.insert(ChildNodes.begin(), DT[*LI]->begin(), DT[*LI]->end());
220     for (SmallVectorImpl<DomTreeNode *>::iterator DI = ChildNodes.begin(),
221          DE = ChildNodes.end(); DI != DE; ++DI) {
222       DT.changeImmediateDominator(*DI, DT[preheader]);
223     }
224 
225     ChildNodes.clear();
226     DT.eraseNode(*LI);
227 
228     // Remove the block from the reference counting scheme, so that we can
229     // delete it freely later.
230     (*LI)->dropAllReferences();
231   }
232 
233   // Erase the instructions and the blocks without having to worry
234   // about ordering because we already dropped the references.
235   // NOTE: This iteration is safe because erasing the block does not remove its
236   // entry from the loop's block list.  We do that in the next section.
237   for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
238        LI != LE; ++LI)
239     (*LI)->eraseFromParent();
240 
241   // Finally, the blocks from loopinfo.  This has to happen late because
242   // otherwise our loop iterators won't work.
243   LoopInfo &loopInfo = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
244   SmallPtrSet<BasicBlock*, 8> blocks;
245   blocks.insert(L->block_begin(), L->block_end());
246   for (BasicBlock *BB : blocks)
247     loopInfo.removeBlock(BB);
248 
249   // The last step is to update LoopInfo now that we've eliminated this loop.
250   loopInfo.markAsRemoved(L);
251   Changed = true;
252 
253   ++NumDeleted;
254 
255   return Changed;
256 }
257