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/IR/PatternMatch.h" 24 #include "llvm/Transforms/Scalar.h" 25 #include "llvm/Transforms/Scalar/LoopPassManager.h" 26 #include "llvm/Transforms/Utils/LoopUtils.h" 27 using namespace llvm; 28 29 #define DEBUG_TYPE "loop-delete" 30 31 STATISTIC(NumDeleted, "Number of loops deleted"); 32 33 /// This function deletes dead loops. The caller of this function needs to 34 /// guarantee that the loop is infact dead. Here we handle two kinds of dead 35 /// loop. The first kind (\p isLoopDead) is where only invariant values from 36 /// within the loop are used outside of it. The second kind (\p 37 /// isLoopNeverExecuted) is where the loop is provably never executed. We can 38 /// always remove never executed loops since they will not cause any difference 39 /// to program behaviour. 40 /// 41 /// This also updates the relevant analysis information in \p DT, \p SE, and \p 42 /// LI. It also updates the loop PM if an updater struct is provided. 43 // TODO: This function will be used by loop-simplifyCFG as well. So, move this 44 // to LoopUtils.cpp 45 static void deleteDeadLoop(Loop *L, DominatorTree &DT, ScalarEvolution &SE, 46 LoopInfo &LI, LPMUpdater *Updater = nullptr); 47 /// Determines if a loop is dead. 48 /// 49 /// This assumes that we've already checked for unique exit and exiting blocks, 50 /// and that the code is in LCSSA form. 51 static bool isLoopDead(Loop *L, ScalarEvolution &SE, 52 SmallVectorImpl<BasicBlock *> &ExitingBlocks, 53 BasicBlock *ExitBlock, bool &Changed, 54 BasicBlock *Preheader) { 55 // Make sure that all PHI entries coming from the loop are loop invariant. 56 // Because the code is in LCSSA form, any values used outside of the loop 57 // must pass through a PHI in the exit block, meaning that this check is 58 // sufficient to guarantee that no loop-variant values are used outside 59 // of the loop. 60 BasicBlock::iterator BI = ExitBlock->begin(); 61 bool AllEntriesInvariant = true; 62 bool AllOutgoingValuesSame = true; 63 while (PHINode *P = dyn_cast<PHINode>(BI)) { 64 Value *incoming = P->getIncomingValueForBlock(ExitingBlocks[0]); 65 66 // Make sure all exiting blocks produce the same incoming value for the exit 67 // block. If there are different incoming values for different exiting 68 // blocks, then it is impossible to statically determine which value should 69 // be used. 70 AllOutgoingValuesSame = 71 all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) { 72 return incoming == P->getIncomingValueForBlock(BB); 73 }); 74 75 if (!AllOutgoingValuesSame) 76 break; 77 78 if (Instruction *I = dyn_cast<Instruction>(incoming)) 79 if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) { 80 AllEntriesInvariant = false; 81 break; 82 } 83 84 ++BI; 85 } 86 87 if (Changed) 88 SE.forgetLoopDispositions(L); 89 90 if (!AllEntriesInvariant || !AllOutgoingValuesSame) 91 return false; 92 93 // Make sure that no instructions in the block have potential side-effects. 94 // This includes instructions that could write to memory, and loads that are 95 // marked volatile. 96 for (auto &I : L->blocks()) 97 if (any_of(*I, [](Instruction &I) { return I.mayHaveSideEffects(); })) 98 return false; 99 return true; 100 } 101 102 /// This function returns true if there is no viable path from the 103 /// entry block to the header of \p L. Right now, it only does 104 /// a local search to save compile time. 105 static bool isLoopNeverExecuted(Loop *L) { 106 using namespace PatternMatch; 107 108 auto *Preheader = L->getLoopPreheader(); 109 // TODO: We can relax this constraint, since we just need a loop 110 // predecessor. 111 assert(Preheader && "Needs preheader!"); 112 113 if (Preheader == &Preheader->getParent()->getEntryBlock()) 114 return false; 115 // All predecessors of the preheader should have a constant conditional 116 // branch, with the loop's preheader as not-taken. 117 for (auto *Pred: predecessors(Preheader)) { 118 BasicBlock *Taken, *NotTaken; 119 ConstantInt *Cond; 120 if (!match(Pred->getTerminator(), 121 m_Br(m_ConstantInt(Cond), Taken, NotTaken))) 122 return false; 123 if (!Cond->getZExtValue()) 124 std::swap(Taken, NotTaken); 125 if (Taken == Preheader) 126 return false; 127 } 128 assert(!pred_empty(Preheader) && 129 "Preheader should have predecessors at this point!"); 130 // All the predecessors have the loop preheader as not-taken target. 131 return true; 132 } 133 134 /// Remove a loop if it is dead. 135 /// 136 /// A loop is considered dead if it does not impact the observable behavior of 137 /// the program other than finite running time. This never removes a loop that 138 /// might be infinite (unless it is never executed), as doing so could change 139 /// the halting/non-halting nature of a program. 140 /// 141 /// This entire process relies pretty heavily on LoopSimplify form and LCSSA in 142 /// order to make various safety checks work. 143 /// 144 /// \returns true if any changes were made. This may mutate the loop even if it 145 /// is unable to delete it due to hoisting trivially loop invariant 146 /// instructions out of the loop. 147 static bool deleteLoopIfDead(Loop *L, DominatorTree &DT, ScalarEvolution &SE, 148 LoopInfo &LI, LPMUpdater *Updater = nullptr) { 149 assert(L->isLCSSAForm(DT) && "Expected LCSSA!"); 150 151 // We can only remove the loop if there is a preheader that we can 152 // branch from after removing it. 153 BasicBlock *Preheader = L->getLoopPreheader(); 154 if (!Preheader) 155 return false; 156 157 // If LoopSimplify form is not available, stay out of trouble. 158 if (!L->hasDedicatedExits()) 159 return false; 160 161 // We can't remove loops that contain subloops. If the subloops were dead, 162 // they would already have been removed in earlier executions of this pass. 163 if (L->begin() != L->end()) 164 return false; 165 166 167 BasicBlock *ExitBlock = L->getUniqueExitBlock(); 168 169 if (ExitBlock && isLoopNeverExecuted(L)) { 170 // Set incoming value to undef for phi nodes in the exit block. 171 BasicBlock::iterator BI = ExitBlock->begin(); 172 while (PHINode *P = dyn_cast<PHINode>(BI)) { 173 for (unsigned i = 0; i < P->getNumIncomingValues(); i++) 174 P->setIncomingValue(i, UndefValue::get(P->getType())); 175 BI++; 176 } 177 deleteDeadLoop(L, DT, SE, LI, Updater); 178 ++NumDeleted; 179 return true; 180 } 181 182 // The remaining checks below are for a loop being dead because all statements 183 // in the loop are invariant. 184 SmallVector<BasicBlock *, 4> ExitingBlocks; 185 L->getExitingBlocks(ExitingBlocks); 186 187 // We require that the loop only have a single exit block. Otherwise, we'd 188 // be in the situation of needing to be able to solve statically which exit 189 // block will be branched to, or trying to preserve the branching logic in 190 // a loop invariant manner. 191 if (!ExitBlock) 192 return false; 193 194 // Finally, we have to check that the loop really is dead. 195 bool Changed = false; 196 if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader)) 197 return Changed; 198 199 // Don't remove loops for which we can't solve the trip count. 200 // They could be infinite, in which case we'd be changing program behavior. 201 const SCEV *S = SE.getMaxBackedgeTakenCount(L); 202 if (isa<SCEVCouldNotCompute>(S)) 203 return Changed; 204 205 deleteDeadLoop(L, DT, SE, LI, Updater); 206 ++NumDeleted; 207 208 return true; 209 } 210 211 static void deleteDeadLoop(Loop *L, DominatorTree &DT, ScalarEvolution &SE, 212 LoopInfo &LI, LPMUpdater *Updater) { 213 assert(L->isLCSSAForm(DT) && "Expected LCSSA!"); 214 auto *Preheader = L->getLoopPreheader(); 215 assert(Preheader && "Preheader should exist!"); 216 217 // Now that we know the removal is safe, remove the loop by changing the 218 // branch from the preheader to go to the single exit block. 219 // 220 // Because we're deleting a large chunk of code at once, the sequence in which 221 // we remove things is very important to avoid invalidation issues. 222 223 // If we have an LPM updater, tell it about the loop being removed. 224 if (Updater) 225 Updater->markLoopAsDeleted(*L); 226 227 // Tell ScalarEvolution that the loop is deleted. Do this before 228 // deleting the loop so that ScalarEvolution can look at the loop 229 // to determine what it needs to clean up. 230 SE.forgetLoop(L); 231 232 auto *ExitBlock = L->getUniqueExitBlock(); 233 assert(ExitBlock && "Should have a unique exit block!"); 234 235 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!"); 236 237 // Connect the preheader directly to the exit block. 238 // Even when the loop is never executed, we cannot remove the edge from the 239 // source block to the exit block. Consider the case where the unexecuted loop 240 // branches back to an outer loop. If we deleted the loop and removed the edge 241 // coming to this inner loop, this will break the outer loop structure (by 242 // deleting the backedge of the outer loop). If the outer loop is indeed a 243 // non-loop, it will be deleted in a future iteration of loop deletion pass. 244 Preheader->getTerminator()->replaceUsesOfWith(L->getHeader(), ExitBlock); 245 246 // Rewrite phis in the exit block to get their inputs from the Preheader 247 // instead of the exiting block. 248 BasicBlock::iterator BI = ExitBlock->begin(); 249 while (PHINode *P = dyn_cast<PHINode>(BI)) { 250 // Set the zero'th element of Phi to be from the preheader and remove all 251 // other incoming values. Given the loop has dedicated exits, all other 252 // incoming values must be from the exiting blocks. 253 int PredIndex = 0; 254 P->setIncomingBlock(PredIndex, Preheader); 255 // Removes all incoming values from all other exiting blocks (including 256 // duplicate values from an exiting block). 257 // Nuke all entries except the zero'th entry which is the preheader entry. 258 // NOTE! We need to remove Incoming Values in the reverse order as done 259 // below, to keep the indices valid for deletion (removeIncomingValues 260 // updates getNumIncomingValues and shifts all values down into the operand 261 // being deleted). 262 for (unsigned i = 0, e = P->getNumIncomingValues() - 1; i != e; ++i) 263 P->removeIncomingValue(e-i, false); 264 265 assert((P->getNumIncomingValues() == 1 && 266 P->getIncomingBlock(PredIndex) == Preheader) && 267 "Should have exactly one value and that's from the preheader!"); 268 ++BI; 269 } 270 271 // Update the dominator tree and remove the instructions and blocks that will 272 // be deleted from the reference counting scheme. 273 SmallVector<DomTreeNode*, 8> ChildNodes; 274 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 275 LI != LE; ++LI) { 276 // Move all of the block's children to be children of the Preheader, which 277 // allows us to remove the domtree entry for the block. 278 ChildNodes.insert(ChildNodes.begin(), DT[*LI]->begin(), DT[*LI]->end()); 279 for (DomTreeNode *ChildNode : ChildNodes) { 280 DT.changeImmediateDominator(ChildNode, DT[Preheader]); 281 } 282 283 ChildNodes.clear(); 284 DT.eraseNode(*LI); 285 286 // Remove the block from the reference counting scheme, so that we can 287 // delete it freely later. 288 (*LI)->dropAllReferences(); 289 } 290 291 // Erase the instructions and the blocks without having to worry 292 // about ordering because we already dropped the references. 293 // NOTE: This iteration is safe because erasing the block does not remove its 294 // entry from the loop's block list. We do that in the next section. 295 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 296 LI != LE; ++LI) 297 (*LI)->eraseFromParent(); 298 299 // Finally, the blocks from loopinfo. This has to happen late because 300 // otherwise our loop iterators won't work. 301 302 SmallPtrSet<BasicBlock *, 8> blocks; 303 blocks.insert(L->block_begin(), L->block_end()); 304 for (BasicBlock *BB : blocks) 305 LI.removeBlock(BB); 306 307 // The last step is to update LoopInfo now that we've eliminated this loop. 308 LI.markAsRemoved(L); 309 } 310 311 PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM, 312 LoopStandardAnalysisResults &AR, 313 LPMUpdater &Updater) { 314 if (!deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, &Updater)) 315 return PreservedAnalyses::all(); 316 317 return getLoopPassPreservedAnalyses(); 318 } 319 320 namespace { 321 class LoopDeletionLegacyPass : public LoopPass { 322 public: 323 static char ID; // Pass ID, replacement for typeid 324 LoopDeletionLegacyPass() : LoopPass(ID) { 325 initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry()); 326 } 327 328 // Possibly eliminate loop L if it is dead. 329 bool runOnLoop(Loop *L, LPPassManager &) override; 330 331 void getAnalysisUsage(AnalysisUsage &AU) const override { 332 getLoopAnalysisUsage(AU); 333 } 334 }; 335 } 336 337 char LoopDeletionLegacyPass::ID = 0; 338 INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion", 339 "Delete dead loops", false, false) 340 INITIALIZE_PASS_DEPENDENCY(LoopPass) 341 INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion", 342 "Delete dead loops", false, false) 343 344 Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); } 345 346 bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &) { 347 if (skipLoop(L)) 348 return false; 349 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 350 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 351 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 352 353 return deleteLoopIfDead(L, DT, SE, LI); 354 } 355