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