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 if it does not impact the observable behavior of 132 /// the program other than finite running time. This never removes a loop that 133 /// might be infinite (unless it is never executed), as doing so could change 134 /// the halting/non-halting nature of a program. 135 /// 136 /// This entire process relies pretty heavily on LoopSimplify form and LCSSA in 137 /// order to make various safety checks work. 138 /// 139 /// \returns true if any changes were made. This may mutate the loop even if it 140 /// is unable to delete it due to hoisting trivially loop invariant 141 /// instructions out of the loop. 142 static LoopDeletionResult deleteLoopIfDead(Loop *L, DominatorTree &DT, 143 ScalarEvolution &SE, LoopInfo &LI, 144 MemorySSA *MSSA, 145 OptimizationRemarkEmitter &ORE) { 146 assert(L->isLCSSAForm(DT) && "Expected LCSSA!"); 147 148 // We can only remove the loop if there is a preheader that we can branch from 149 // after removing it. Also, if LoopSimplify form is not available, stay out 150 // of trouble. 151 BasicBlock *Preheader = L->getLoopPreheader(); 152 if (!Preheader || !L->hasDedicatedExits()) { 153 LLVM_DEBUG( 154 dbgs() 155 << "Deletion requires Loop with preheader and dedicated exits.\n"); 156 return LoopDeletionResult::Unmodified; 157 } 158 // We can't remove loops that contain subloops. If the subloops were dead, 159 // they would already have been removed in earlier executions of this pass. 160 if (L->begin() != L->end()) { 161 LLVM_DEBUG(dbgs() << "Loop contains subloops.\n"); 162 return LoopDeletionResult::Unmodified; 163 } 164 165 166 BasicBlock *ExitBlock = L->getUniqueExitBlock(); 167 168 if (ExitBlock && isLoopNeverExecuted(L)) { 169 LLVM_DEBUG(dbgs() << "Loop is proven to never execute, delete it!"); 170 // We need to forget the loop before setting the incoming values of the exit 171 // phis to undef, so we properly invalidate the SCEV expressions for those 172 // phis. 173 SE.forgetLoop(L); 174 // Set incoming value to undef for phi nodes in the exit block. 175 for (PHINode &P : ExitBlock->phis()) { 176 std::fill(P.incoming_values().begin(), P.incoming_values().end(), 177 UndefValue::get(P.getType())); 178 } 179 ORE.emit([&]() { 180 return OptimizationRemark(DEBUG_TYPE, "NeverExecutes", L->getStartLoc(), 181 L->getHeader()) 182 << "Loop deleted because it never executes"; 183 }); 184 deleteDeadLoop(L, &DT, &SE, &LI, MSSA); 185 ++NumDeleted; 186 return LoopDeletionResult::Deleted; 187 } 188 189 // The remaining checks below are for a loop being dead because all statements 190 // in the loop are invariant. 191 SmallVector<BasicBlock *, 4> ExitingBlocks; 192 L->getExitingBlocks(ExitingBlocks); 193 194 // We require that the loop has at most one exit block. Otherwise, we'd be in 195 // the situation of needing to be able to solve statically which exit block 196 // will be branched to, or trying to preserve the branching logic in a loop 197 // invariant manner. 198 if (!ExitBlock && !L->hasNoExitBlocks()) { 199 LLVM_DEBUG(dbgs() << "Deletion requires at most one exit block.\n"); 200 return LoopDeletionResult::Unmodified; 201 } 202 // Finally, we have to check that the loop really is dead. 203 bool Changed = false; 204 if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader)) { 205 LLVM_DEBUG(dbgs() << "Loop is not invariant, cannot delete.\n"); 206 return Changed ? LoopDeletionResult::Modified 207 : LoopDeletionResult::Unmodified; 208 } 209 210 // Don't remove loops for which we can't solve the trip count. 211 // They could be infinite, in which case we'd be changing program behavior. 212 const SCEV *S = SE.getConstantMaxBackedgeTakenCount(L); 213 if (isa<SCEVCouldNotCompute>(S)) { 214 LLVM_DEBUG(dbgs() << "Could not compute SCEV MaxBackedgeTakenCount.\n"); 215 return Changed ? LoopDeletionResult::Modified 216 : LoopDeletionResult::Unmodified; 217 } 218 219 LLVM_DEBUG(dbgs() << "Loop is invariant, delete it!"); 220 ORE.emit([&]() { 221 return OptimizationRemark(DEBUG_TYPE, "Invariant", L->getStartLoc(), 222 L->getHeader()) 223 << "Loop deleted because it is invariant"; 224 }); 225 deleteDeadLoop(L, &DT, &SE, &LI, MSSA); 226 ++NumDeleted; 227 228 return LoopDeletionResult::Deleted; 229 } 230 231 PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM, 232 LoopStandardAnalysisResults &AR, 233 LPMUpdater &Updater) { 234 235 LLVM_DEBUG(dbgs() << "Analyzing Loop for deletion: "); 236 LLVM_DEBUG(L.dump()); 237 std::string LoopName = std::string(L.getName()); 238 // For the new PM, we can't use OptimizationRemarkEmitter as an analysis 239 // pass. Function analyses need to be preserved across loop transformations 240 // but ORE cannot be preserved (see comment before the pass definition). 241 OptimizationRemarkEmitter ORE(L.getHeader()->getParent()); 242 auto Result = deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, AR.MSSA, ORE); 243 if (Result == LoopDeletionResult::Unmodified) 244 return PreservedAnalyses::all(); 245 246 if (Result == LoopDeletionResult::Deleted) 247 Updater.markLoopAsDeleted(L, LoopName); 248 249 auto PA = getLoopPassPreservedAnalyses(); 250 if (AR.MSSA) 251 PA.preserve<MemorySSAAnalysis>(); 252 return PA; 253 } 254 255 namespace { 256 class LoopDeletionLegacyPass : public LoopPass { 257 public: 258 static char ID; // Pass ID, replacement for typeid 259 LoopDeletionLegacyPass() : LoopPass(ID) { 260 initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry()); 261 } 262 263 // Possibly eliminate loop L if it is dead. 264 bool runOnLoop(Loop *L, LPPassManager &) override; 265 266 void getAnalysisUsage(AnalysisUsage &AU) const override { 267 AU.addPreserved<MemorySSAWrapperPass>(); 268 getLoopAnalysisUsage(AU); 269 } 270 }; 271 } 272 273 char LoopDeletionLegacyPass::ID = 0; 274 INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion", 275 "Delete dead loops", false, false) 276 INITIALIZE_PASS_DEPENDENCY(LoopPass) 277 INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion", 278 "Delete dead loops", false, false) 279 280 Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); } 281 282 bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) { 283 if (skipLoop(L)) 284 return false; 285 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 286 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 287 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 288 auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>(); 289 MemorySSA *MSSA = nullptr; 290 if (MSSAAnalysis) 291 MSSA = &MSSAAnalysis->getMSSA(); 292 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis 293 // pass. Function analyses need to be preserved across loop transformations 294 // but ORE cannot be preserved (see comment before the pass definition). 295 OptimizationRemarkEmitter ORE(L->getHeader()->getParent()); 296 297 LLVM_DEBUG(dbgs() << "Analyzing Loop for deletion: "); 298 LLVM_DEBUG(L->dump()); 299 300 LoopDeletionResult Result = deleteLoopIfDead(L, DT, SE, LI, MSSA, ORE); 301 302 if (Result == LoopDeletionResult::Deleted) 303 LPM.markLoopAsDeleted(*L); 304 305 return Result != LoopDeletionResult::Unmodified; 306 } 307