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/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"
26 using namespace llvm;
27 
28 #define DEBUG_TYPE "loop-delete"
29 
30 STATISTIC(NumDeleted, "Number of loops deleted");
31 
32 /// Determines if a loop is dead.
33 ///
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
44   // of the loop.
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]);
50 
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
54     // be used.
55     AllOutgoingValuesSame =
56         all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) {
57           return incoming == P->getIncomingValueForBlock(BB);
58         });
59 
60     if (!AllOutgoingValuesSame)
61       break;
62 
63     if (Instruction *I = dyn_cast<Instruction>(incoming))
64       if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) {
65         AllEntriesInvariant = false;
66         break;
67       }
68 
69     ++BI;
70   }
71 
72   if (Changed)
73     SE.forgetLoopDispositions(L);
74 
75   if (!AllEntriesInvariant || !AllOutgoingValuesSame)
76     return false;
77 
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
80   // marked volatile.  This could be made more aggressive by using aliasing
81   // information to identify readonly and readnone calls.
82   for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
83        LI != LE; ++LI) {
84     for (Instruction &I : **LI) {
85       if (I.mayHaveSideEffects())
86         return false;
87     }
88   }
89 
90   return true;
91 }
92 
93 /// Remove a loop if it is dead.
94 ///
95 /// A loop is considered dead if it does not impact the observable behavior of
96 /// the program other than finite running time. This never removes a loop that
97 /// might be infinite, as doing so could change the halting/non-halting nature
98 /// of a program.
99 ///
100 /// This entire process relies pretty heavily on LoopSimplify form and LCSSA in
101 /// order to make various safety checks work.
102 ///
103 /// \returns true if the loop is deleted.
104 ///
105 /// This also sets the \p Changed output parameter to `true` if any changes
106 /// were made. This may mutate the loop even if it is unable to delete it due
107 /// to hoisting trivially loop invariant instructions out of the loop.
108 ///
109 /// This also updates the relevant analysis information in \p DT, \p SE, and \p
110 /// LI.
111 static bool deleteLoopIfDead(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
112                              LoopInfo &LI, bool &Changed) {
113   assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
114 
115   // We can only remove the loop if there is a preheader that we can
116   // branch from after removing it.
117   BasicBlock *Preheader = L->getLoopPreheader();
118   if (!Preheader)
119     return false;
120 
121   // If LoopSimplify form is not available, stay out of trouble.
122   if (!L->hasDedicatedExits())
123     return false;
124 
125   // We can't remove loops that contain subloops.  If the subloops were dead,
126   // they would already have been removed in earlier executions of this pass.
127   if (L->begin() != L->end())
128     return false;
129 
130   SmallVector<BasicBlock *, 4> ExitingBlocks;
131   L->getExitingBlocks(ExitingBlocks);
132 
133   // We require that the loop only have a single exit block.  Otherwise, we'd
134   // be in the situation of needing to be able to solve statically which exit
135   // block will be branched to, or trying to preserve the branching logic in
136   // a loop invariant manner.
137   BasicBlock *ExitBlock = L->getUniqueExitBlock();
138   if (!ExitBlock)
139     return false;
140 
141   // Finally, we have to check that the loop really is dead.
142   if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader))
143     return false;
144 
145   // Don't remove loops for which we can't solve the trip count.
146   // They could be infinite, in which case we'd be changing program behavior.
147   const SCEV *S = SE.getMaxBackedgeTakenCount(L);
148   if (isa<SCEVCouldNotCompute>(S))
149     return false;
150 
151   // Now that we know the removal is safe, remove the loop by changing the
152   // branch from the preheader to go to the single exit block.
153   //
154   // Because we're deleting a large chunk of code at once, the sequence in which
155   // we remove things is very important to avoid invalidation issues.
156 
157   // Tell ScalarEvolution that the loop is deleted. Do this before
158   // deleting the loop so that ScalarEvolution can look at the loop
159   // to determine what it needs to clean up.
160   SE.forgetLoop(L);
161 
162   // Connect the preheader directly to the exit block.
163   TerminatorInst *TI = Preheader->getTerminator();
164   TI->replaceUsesOfWith(L->getHeader(), ExitBlock);
165 
166   // Rewrite phis in the exit block to get their inputs from
167   // the preheader instead of the exiting block.
168   BasicBlock *ExitingBlock = ExitingBlocks[0];
169   BasicBlock::iterator BI = ExitBlock->begin();
170   while (PHINode *P = dyn_cast<PHINode>(BI)) {
171     int j = P->getBasicBlockIndex(ExitingBlock);
172     assert(j >= 0 && "Can't find exiting block in exit block's phi node!");
173     P->setIncomingBlock(j, Preheader);
174     for (unsigned i = 1; i < ExitingBlocks.size(); ++i)
175       P->removeIncomingValue(ExitingBlocks[i]);
176     ++BI;
177   }
178 
179   // Update the dominator tree and remove the instructions and blocks that will
180   // be deleted from the reference counting scheme.
181   SmallVector<DomTreeNode*, 8> ChildNodes;
182   for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
183        LI != LE; ++LI) {
184     // Move all of the block's children to be children of the Preheader, which
185     // allows us to remove the domtree entry for the block.
186     ChildNodes.insert(ChildNodes.begin(), DT[*LI]->begin(), DT[*LI]->end());
187     for (DomTreeNode *ChildNode : ChildNodes) {
188       DT.changeImmediateDominator(ChildNode, DT[Preheader]);
189     }
190 
191     ChildNodes.clear();
192     DT.eraseNode(*LI);
193 
194     // Remove the block from the reference counting scheme, so that we can
195     // delete it freely later.
196     (*LI)->dropAllReferences();
197   }
198 
199   // Erase the instructions and the blocks without having to worry
200   // about ordering because we already dropped the references.
201   // NOTE: This iteration is safe because erasing the block does not remove its
202   // entry from the loop's block list.  We do that in the next section.
203   for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
204        LI != LE; ++LI)
205     (*LI)->eraseFromParent();
206 
207   // Finally, the blocks from loopinfo.  This has to happen late because
208   // otherwise our loop iterators won't work.
209 
210   SmallPtrSet<BasicBlock *, 8> blocks;
211   blocks.insert(L->block_begin(), L->block_end());
212   for (BasicBlock *BB : blocks)
213     LI.removeBlock(BB);
214 
215   // The last step is to update LoopInfo now that we've eliminated this loop.
216   LI.markAsRemoved(L);
217   Changed = true;
218 
219   ++NumDeleted;
220 
221   return true;
222 }
223 
224 PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM,
225                                         LoopStandardAnalysisResults &AR,
226                                         LPMUpdater &Updater) {
227   bool Changed = false;
228 
229   if (deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, Changed)) {
230     assert(Changed && "Cannot delete a loop without changing something!");
231     // Need to update the LPM about this loop going away.
232     Updater.markLoopAsDeleted(L);
233   } else if (!Changed) {
234     return PreservedAnalyses::all();
235   }
236 
237   return getLoopPassPreservedAnalyses();
238 }
239 
240 namespace {
241 class LoopDeletionLegacyPass : public LoopPass {
242 public:
243   static char ID; // Pass ID, replacement for typeid
244   LoopDeletionLegacyPass() : LoopPass(ID) {
245     initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry());
246   }
247 
248   // Possibly eliminate loop L if it is dead.
249   bool runOnLoop(Loop *L, LPPassManager &) override;
250 
251   void getAnalysisUsage(AnalysisUsage &AU) const override {
252     getLoopAnalysisUsage(AU);
253   }
254 };
255 }
256 
257 char LoopDeletionLegacyPass::ID = 0;
258 INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion",
259                       "Delete dead loops", false, false)
260 INITIALIZE_PASS_DEPENDENCY(LoopPass)
261 INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion",
262                     "Delete dead loops", false, false)
263 
264 Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); }
265 
266 bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &) {
267   if (skipLoop(L))
268     return false;
269 
270   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
271   ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
272   LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
273 
274   bool Changed = false;
275   return deleteLoopIfDead(L, DT, SE, LI, Changed) || Changed;
276 }
277