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 
16 #include "llvm/Transforms/Scalar/LoopDeletion.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/GlobalsModRef.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/MemorySSA.h"
22 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/PatternMatch.h"
25 #include "llvm/InitializePasses.h"
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/Transforms/Scalar/LoopPassManager.h"
28 #include "llvm/Transforms/Utils/LoopUtils.h"
29 using namespace llvm;
30 
31 #define DEBUG_TYPE "loop-delete"
32 
33 STATISTIC(NumDeleted, "Number of loops deleted");
34 
35 enum class LoopDeletionResult {
36   Unmodified,
37   Modified,
38   Deleted,
39 };
40 
41 /// Determines if a loop is dead.
42 ///
43 /// This assumes that we've already checked for unique exit and exiting blocks,
44 /// and that the code is in LCSSA form.
45 static bool isLoopDead(Loop *L, ScalarEvolution &SE,
46                        SmallVectorImpl<BasicBlock *> &ExitingBlocks,
47                        BasicBlock *ExitBlock, bool &Changed,
48                        BasicBlock *Preheader) {
49   // Make sure that all PHI entries coming from the loop are loop invariant.
50   // Because the code is in LCSSA form, any values used outside of the loop
51   // must pass through a PHI in the exit block, meaning that this check is
52   // sufficient to guarantee that no loop-variant values are used outside
53   // of the loop.
54   bool AllEntriesInvariant = true;
55   bool AllOutgoingValuesSame = true;
56   if (!L->hasNoExitBlocks()) {
57     for (PHINode &P : ExitBlock->phis()) {
58       Value *incoming = P.getIncomingValueForBlock(ExitingBlocks[0]);
59 
60       // Make sure all exiting blocks produce the same incoming value for the
61       // block. If there are different incoming values for different exiting
62       // blocks, then it is impossible to statically determine which value
63       // should be used.
64       AllOutgoingValuesSame =
65           all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) {
66             return incoming == P.getIncomingValueForBlock(BB);
67           });
68 
69       if (!AllOutgoingValuesSame)
70         break;
71 
72       if (Instruction *I = dyn_cast<Instruction>(incoming))
73         if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) {
74           AllEntriesInvariant = false;
75           break;
76         }
77     }
78   }
79 
80   if (Changed)
81     SE.forgetLoopDispositions(L);
82 
83   if (!AllEntriesInvariant || !AllOutgoingValuesSame)
84     return false;
85 
86   // Make sure that no instructions in the block have potential side-effects.
87   // This includes instructions that could write to memory, and loads that are
88   // marked volatile.
89   for (auto &I : L->blocks())
90     if (any_of(*I, [](Instruction &I) {
91           return I.mayHaveSideEffects() && !I.isDroppable();
92         }))
93       return false;
94   return true;
95 }
96 
97 /// This function returns true if there is no viable path from the
98 /// entry block to the header of \p L. Right now, it only does
99 /// a local search to save compile time.
100 static bool isLoopNeverExecuted(Loop *L) {
101   using namespace PatternMatch;
102 
103   auto *Preheader = L->getLoopPreheader();
104   // TODO: We can relax this constraint, since we just need a loop
105   // predecessor.
106   assert(Preheader && "Needs preheader!");
107 
108   if (Preheader == &Preheader->getParent()->getEntryBlock())
109     return false;
110   // All predecessors of the preheader should have a constant conditional
111   // branch, with the loop's preheader as not-taken.
112   for (auto *Pred: predecessors(Preheader)) {
113     BasicBlock *Taken, *NotTaken;
114     ConstantInt *Cond;
115     if (!match(Pred->getTerminator(),
116                m_Br(m_ConstantInt(Cond), Taken, NotTaken)))
117       return false;
118     if (!Cond->getZExtValue())
119       std::swap(Taken, NotTaken);
120     if (Taken == Preheader)
121       return false;
122   }
123   assert(!pred_empty(Preheader) &&
124          "Preheader should have predecessors at this point!");
125   // All the predecessors have the loop preheader as not-taken target.
126   return true;
127 }
128 
129 /// Remove a loop if it is dead.
130 ///
131 /// A loop is considered dead either if it does not impact the observable
132 /// behavior of the program other than finite running time, or if it is
133 /// required to make progress by an attribute such as 'mustprogress' or
134 /// 'llvm.loop.mustprogress' and does not make any. This may remove
135 /// infinite loops that have been required to make progress.
136 ///
137 /// This entire process relies pretty heavily on LoopSimplify form and LCSSA in
138 /// order to make various safety checks work.
139 ///
140 /// \returns true if any changes were made. This may mutate the loop even if it
141 /// is unable to delete it due to hoisting trivially loop invariant
142 /// instructions out of the loop.
143 static LoopDeletionResult deleteLoopIfDead(Loop *L, DominatorTree &DT,
144                                            ScalarEvolution &SE, LoopInfo &LI,
145                                            MemorySSA *MSSA,
146                                            OptimizationRemarkEmitter &ORE) {
147   assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
148 
149   // We can only remove the loop if there is a preheader that we can branch from
150   // after removing it. Also, if LoopSimplify form is not available, stay out
151   // of trouble.
152   BasicBlock *Preheader = L->getLoopPreheader();
153   if (!Preheader || !L->hasDedicatedExits()) {
154     LLVM_DEBUG(
155         dbgs()
156         << "Deletion requires Loop with preheader and dedicated exits.\n");
157     return LoopDeletionResult::Unmodified;
158   }
159 
160   BasicBlock *ExitBlock = L->getUniqueExitBlock();
161 
162   if (ExitBlock && isLoopNeverExecuted(L)) {
163     LLVM_DEBUG(dbgs() << "Loop is proven to never execute, delete it!");
164     // We need to forget the loop before setting the incoming values of the exit
165     // phis to undef, so we properly invalidate the SCEV expressions for those
166     // phis.
167     SE.forgetLoop(L);
168     // Set incoming value to undef for phi nodes in the exit block.
169     for (PHINode &P : ExitBlock->phis()) {
170       std::fill(P.incoming_values().begin(), P.incoming_values().end(),
171                 UndefValue::get(P.getType()));
172     }
173     ORE.emit([&]() {
174       return OptimizationRemark(DEBUG_TYPE, "NeverExecutes", L->getStartLoc(),
175                                 L->getHeader())
176              << "Loop deleted because it never executes";
177     });
178     deleteDeadLoop(L, &DT, &SE, &LI, MSSA);
179     ++NumDeleted;
180     return LoopDeletionResult::Deleted;
181   }
182 
183   // The remaining checks below are for a loop being dead because all statements
184   // in the loop are invariant.
185   SmallVector<BasicBlock *, 4> ExitingBlocks;
186   L->getExitingBlocks(ExitingBlocks);
187 
188   // We require that the loop has at most one exit block. Otherwise, we'd be in
189   // the situation of needing to be able to solve statically which exit block
190   // will be branched to, or trying to preserve the branching logic in a loop
191   // invariant manner.
192   if (!ExitBlock && !L->hasNoExitBlocks()) {
193     LLVM_DEBUG(dbgs() << "Deletion requires at most one exit block.\n");
194     return LoopDeletionResult::Unmodified;
195   }
196   // Finally, we have to check that the loop really is dead.
197   bool Changed = false;
198   if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader)) {
199     LLVM_DEBUG(dbgs() << "Loop is not invariant, cannot delete.\n");
200     return Changed ? LoopDeletionResult::Modified
201                    : LoopDeletionResult::Unmodified;
202   }
203 
204   // Don't remove loops for which we can't solve the trip count unless the loop
205   // was required to make progress but has been determined to be dead.
206   const SCEV *S = SE.getConstantMaxBackedgeTakenCount(L);
207   if (isa<SCEVCouldNotCompute>(S) &&
208       !L->getHeader()->getParent()->mustProgress() && !hasMustProgress(L)) {
209     LLVM_DEBUG(dbgs() << "Could not compute SCEV MaxBackedgeTakenCount and was "
210                          "not required to make progress.\n");
211     return Changed ? LoopDeletionResult::Modified
212                    : LoopDeletionResult::Unmodified;
213   }
214 
215   LLVM_DEBUG(dbgs() << "Loop is invariant, delete it!");
216   ORE.emit([&]() {
217     return OptimizationRemark(DEBUG_TYPE, "Invariant", L->getStartLoc(),
218                               L->getHeader())
219            << "Loop deleted because it is invariant";
220   });
221   deleteDeadLoop(L, &DT, &SE, &LI, MSSA);
222   ++NumDeleted;
223 
224   return LoopDeletionResult::Deleted;
225 }
226 
227 PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM,
228                                         LoopStandardAnalysisResults &AR,
229                                         LPMUpdater &Updater) {
230 
231   LLVM_DEBUG(dbgs() << "Analyzing Loop for deletion: ");
232   LLVM_DEBUG(L.dump());
233   std::string LoopName = std::string(L.getName());
234   // For the new PM, we can't use OptimizationRemarkEmitter as an analysis
235   // pass. Function analyses need to be preserved across loop transformations
236   // but ORE cannot be preserved (see comment before the pass definition).
237   OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
238   auto Result = deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, AR.MSSA, ORE);
239   if (Result == LoopDeletionResult::Unmodified)
240     return PreservedAnalyses::all();
241 
242   if (Result == LoopDeletionResult::Deleted)
243     Updater.markLoopAsDeleted(L, LoopName);
244 
245   auto PA = getLoopPassPreservedAnalyses();
246   if (AR.MSSA)
247     PA.preserve<MemorySSAAnalysis>();
248   return PA;
249 }
250 
251 namespace {
252 class LoopDeletionLegacyPass : public LoopPass {
253 public:
254   static char ID; // Pass ID, replacement for typeid
255   LoopDeletionLegacyPass() : LoopPass(ID) {
256     initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry());
257   }
258 
259   // Possibly eliminate loop L if it is dead.
260   bool runOnLoop(Loop *L, LPPassManager &) override;
261 
262   void getAnalysisUsage(AnalysisUsage &AU) const override {
263     AU.addPreserved<MemorySSAWrapperPass>();
264     getLoopAnalysisUsage(AU);
265   }
266 };
267 }
268 
269 char LoopDeletionLegacyPass::ID = 0;
270 INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion",
271                       "Delete dead loops", false, false)
272 INITIALIZE_PASS_DEPENDENCY(LoopPass)
273 INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion",
274                     "Delete dead loops", false, false)
275 
276 Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); }
277 
278 bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
279   if (skipLoop(L))
280     return false;
281   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
282   ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
283   LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
284   auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>();
285   MemorySSA *MSSA = nullptr;
286   if (MSSAAnalysis)
287     MSSA = &MSSAAnalysis->getMSSA();
288   // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
289   // pass.  Function analyses need to be preserved across loop transformations
290   // but ORE cannot be preserved (see comment before the pass definition).
291   OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
292 
293   LLVM_DEBUG(dbgs() << "Analyzing Loop for deletion: ");
294   LLVM_DEBUG(L->dump());
295 
296   LoopDeletionResult Result = deleteLoopIfDead(L, DT, SE, LI, MSSA, ORE);
297 
298   if (Result == LoopDeletionResult::Deleted)
299     LPM.markLoopAsDeleted(*L);
300 
301   return Result != LoopDeletionResult::Unmodified;
302 }
303