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