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/Transforms/Scalar.h" 24 #include "llvm/Transforms/Scalar/LoopPassManager.h" 25 #include "llvm/Transforms/Utils/LoopUtils.h" 26 using namespace llvm; 27 28 #define DEBUG_TYPE "loop-delete" 29 30 STATISTIC(NumDeleted, "Number of loops deleted"); 31 32 /// Determines if a loop is dead. 33 /// 34 /// This assumes that we've already checked for unique exit and exiting blocks, 35 /// and that the code is in LCSSA form. 36 static bool isLoopDead(Loop *L, ScalarEvolution &SE, 37 SmallVectorImpl<BasicBlock *> &ExitingBlocks, 38 BasicBlock *ExitBlock, bool &Changed, 39 BasicBlock *Preheader) { 40 // Make sure that all PHI entries coming from the loop are loop invariant. 41 // Because the code is in LCSSA form, any values used outside of the loop 42 // must pass through a PHI in the exit block, meaning that this check is 43 // sufficient to guarantee that no loop-variant values are used outside 44 // of the loop. 45 BasicBlock::iterator BI = ExitBlock->begin(); 46 bool AllEntriesInvariant = true; 47 bool AllOutgoingValuesSame = true; 48 while (PHINode *P = dyn_cast<PHINode>(BI)) { 49 Value *incoming = P->getIncomingValueForBlock(ExitingBlocks[0]); 50 51 // Make sure all exiting blocks produce the same incoming value for the exit 52 // block. If there are different incoming values for different exiting 53 // blocks, then it is impossible to statically determine which value should 54 // be used. 55 AllOutgoingValuesSame = 56 all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) { 57 return incoming == P->getIncomingValueForBlock(BB); 58 }); 59 60 if (!AllOutgoingValuesSame) 61 break; 62 63 if (Instruction *I = dyn_cast<Instruction>(incoming)) 64 if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) { 65 AllEntriesInvariant = false; 66 break; 67 } 68 69 ++BI; 70 } 71 72 if (Changed) 73 SE.forgetLoopDispositions(L); 74 75 if (!AllEntriesInvariant || !AllOutgoingValuesSame) 76 return false; 77 78 // Make sure that no instructions in the block have potential side-effects. 79 // This includes instructions that could write to memory, and loads that are 80 // marked volatile. 81 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 82 LI != LE; ++LI) { 83 for (Instruction &I : **LI) { 84 if (I.mayHaveSideEffects()) 85 return false; 86 } 87 } 88 89 return true; 90 } 91 92 /// Remove a loop if it is dead. 93 /// 94 /// A loop is considered dead if it does not impact the observable behavior of 95 /// the program other than finite running time. This never removes a loop that 96 /// might be infinite, as doing so could change the halting/non-halting nature 97 /// of a program. 98 /// 99 /// This entire process relies pretty heavily on LoopSimplify form and LCSSA in 100 /// order to make various safety checks work. 101 /// 102 /// \returns true if any changes were made. This may mutate the loop even if it 103 /// is unable to delete it due to hoisting trivially loop invariant 104 /// instructions out of the loop. 105 /// 106 /// This also updates the relevant analysis information in \p DT, \p SE, and \p 107 /// LI. It also updates the loop PM if an updater struct is provided. 108 static bool deleteLoopIfDead(Loop *L, DominatorTree &DT, ScalarEvolution &SE, 109 LoopInfo &LI, LPMUpdater *Updater = nullptr) { 110 assert(L->isLCSSAForm(DT) && "Expected LCSSA!"); 111 112 // We can only remove the loop if there is a preheader that we can 113 // branch from after removing it. 114 BasicBlock *Preheader = L->getLoopPreheader(); 115 if (!Preheader) 116 return false; 117 118 // If LoopSimplify form is not available, stay out of trouble. 119 if (!L->hasDedicatedExits()) 120 return false; 121 122 // We can't remove loops that contain subloops. If the subloops were dead, 123 // they would already have been removed in earlier executions of this pass. 124 if (L->begin() != L->end()) 125 return false; 126 127 SmallVector<BasicBlock *, 4> ExitingBlocks; 128 L->getExitingBlocks(ExitingBlocks); 129 130 // We require that the loop only have a single exit block. Otherwise, we'd 131 // be in the situation of needing to be able to solve statically which exit 132 // block will be branched to, or trying to preserve the branching logic in 133 // a loop invariant manner. 134 BasicBlock *ExitBlock = L->getUniqueExitBlock(); 135 if (!ExitBlock) 136 return false; 137 138 // Finally, we have to check that the loop really is dead. 139 bool Changed = false; 140 if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader)) 141 return Changed; 142 143 // Don't remove loops for which we can't solve the trip count. 144 // They could be infinite, in which case we'd be changing program behavior. 145 const SCEV *S = SE.getMaxBackedgeTakenCount(L); 146 if (isa<SCEVCouldNotCompute>(S)) 147 return Changed; 148 149 // Now that we know the removal is safe, remove the loop by changing the 150 // branch from the preheader to go to the single exit block. 151 // 152 // Because we're deleting a large chunk of code at once, the sequence in which 153 // we remove things is very important to avoid invalidation issues. 154 155 // If we have an LPM updater, tell it about the loop being removed. 156 if (Updater) 157 Updater->markLoopAsDeleted(*L); 158 159 // Tell ScalarEvolution that the loop is deleted. Do this before 160 // deleting the loop so that ScalarEvolution can look at the loop 161 // to determine what it needs to clean up. 162 SE.forgetLoop(L); 163 164 // Connect the preheader directly to the exit block. 165 TerminatorInst *TI = Preheader->getTerminator(); 166 TI->replaceUsesOfWith(L->getHeader(), ExitBlock); 167 168 // Rewrite phis in the exit block to get their inputs from 169 // the preheader instead of the exiting block. 170 BasicBlock *ExitingBlock = ExitingBlocks[0]; 171 BasicBlock::iterator BI = ExitBlock->begin(); 172 while (PHINode *P = dyn_cast<PHINode>(BI)) { 173 int j = P->getBasicBlockIndex(ExitingBlock); 174 assert(j >= 0 && "Can't find exiting block in exit block's phi node!"); 175 P->setIncomingBlock(j, Preheader); 176 for (unsigned i = 1; i < ExitingBlocks.size(); ++i) 177 P->removeIncomingValue(ExitingBlocks[i]); 178 ++BI; 179 } 180 181 // Update the dominator tree and remove the instructions and blocks that will 182 // be deleted from the reference counting scheme. 183 SmallVector<DomTreeNode*, 8> ChildNodes; 184 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 185 LI != LE; ++LI) { 186 // Move all of the block's children to be children of the Preheader, which 187 // allows us to remove the domtree entry for the block. 188 ChildNodes.insert(ChildNodes.begin(), DT[*LI]->begin(), DT[*LI]->end()); 189 for (DomTreeNode *ChildNode : ChildNodes) { 190 DT.changeImmediateDominator(ChildNode, DT[Preheader]); 191 } 192 193 ChildNodes.clear(); 194 DT.eraseNode(*LI); 195 196 // Remove the block from the reference counting scheme, so that we can 197 // delete it freely later. 198 (*LI)->dropAllReferences(); 199 } 200 201 // Erase the instructions and the blocks without having to worry 202 // about ordering because we already dropped the references. 203 // NOTE: This iteration is safe because erasing the block does not remove its 204 // entry from the loop's block list. We do that in the next section. 205 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 206 LI != LE; ++LI) 207 (*LI)->eraseFromParent(); 208 209 // Finally, the blocks from loopinfo. This has to happen late because 210 // otherwise our loop iterators won't work. 211 212 SmallPtrSet<BasicBlock *, 8> blocks; 213 blocks.insert(L->block_begin(), L->block_end()); 214 for (BasicBlock *BB : blocks) 215 LI.removeBlock(BB); 216 217 // The last step is to update LoopInfo now that we've eliminated this loop. 218 LI.markAsRemoved(L); 219 ++NumDeleted; 220 221 return true; 222 } 223 224 PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM, 225 LoopStandardAnalysisResults &AR, 226 LPMUpdater &Updater) { 227 if (!deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, &Updater)) 228 return PreservedAnalyses::all(); 229 230 return getLoopPassPreservedAnalyses(); 231 } 232 233 namespace { 234 class LoopDeletionLegacyPass : public LoopPass { 235 public: 236 static char ID; // Pass ID, replacement for typeid 237 LoopDeletionLegacyPass() : LoopPass(ID) { 238 initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry()); 239 } 240 241 // Possibly eliminate loop L if it is dead. 242 bool runOnLoop(Loop *L, LPPassManager &) override; 243 244 void getAnalysisUsage(AnalysisUsage &AU) const override { 245 getLoopAnalysisUsage(AU); 246 } 247 }; 248 } 249 250 char LoopDeletionLegacyPass::ID = 0; 251 INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion", 252 "Delete dead loops", false, false) 253 INITIALIZE_PASS_DEPENDENCY(LoopPass) 254 INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion", 255 "Delete dead loops", false, false) 256 257 Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); } 258 259 bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &) { 260 if (skipLoop(L)) 261 return false; 262 263 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 264 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 265 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 266 267 return deleteLoopIfDead(L, DT, SE, LI); 268 } 269