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/Analysis/LoopPassManager.h" 23 #include "llvm/IR/Dominators.h" 24 #include "llvm/Transforms/Scalar.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 /// isLoopDead - Determined if a loop is dead. This assumes that we've already 33 /// checked for unique exit and exiting blocks, and that the code is in LCSSA 34 /// form. 35 bool LoopDeletionPass::isLoopDead(Loop *L, ScalarEvolution &SE, 36 SmallVectorImpl<BasicBlock *> &exitingBlocks, 37 SmallVectorImpl<BasicBlock *> &exitBlocks, 38 bool &Changed, BasicBlock *Preheader) { 39 BasicBlock *exitBlock = exitBlocks[0]; 40 41 // Make sure that all PHI entries coming from the loop are loop invariant. 42 // Because the code is in LCSSA form, any values used outside of the loop 43 // must pass through a PHI in the exit block, meaning that this check is 44 // sufficient to guarantee that no loop-variant values are used outside 45 // of the loop. 46 BasicBlock::iterator BI = exitBlock->begin(); 47 bool AllEntriesInvariant = true; 48 bool AllOutgoingValuesSame = true; 49 while (PHINode *P = dyn_cast<PHINode>(BI)) { 50 Value *incoming = P->getIncomingValueForBlock(exitingBlocks[0]); 51 52 // Make sure all exiting blocks produce the same incoming value for the exit 53 // block. If there are different incoming values for different exiting 54 // blocks, then it is impossible to statically determine which value should 55 // be used. 56 AllOutgoingValuesSame = 57 all_of(makeArrayRef(exitingBlocks).slice(1), [&](BasicBlock *BB) { 58 return incoming == P->getIncomingValueForBlock(BB); 59 }); 60 61 if (!AllOutgoingValuesSame) 62 break; 63 64 if (Instruction *I = dyn_cast<Instruction>(incoming)) 65 if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) { 66 AllEntriesInvariant = false; 67 break; 68 } 69 70 ++BI; 71 } 72 73 if (Changed) 74 SE.forgetLoopDispositions(L); 75 76 if (!AllEntriesInvariant || !AllOutgoingValuesSame) 77 return false; 78 79 // Make sure that no instructions in the block have potential side-effects. 80 // This includes instructions that could write to memory, and loads that are 81 // marked volatile. This could be made more aggressive by using aliasing 82 // information to identify readonly and readnone calls. 83 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 84 LI != LE; ++LI) { 85 for (Instruction &I : **LI) { 86 if (I.mayHaveSideEffects()) 87 return false; 88 } 89 } 90 91 return true; 92 } 93 94 /// Remove dead loops, by which we mean loops that do not impact the observable 95 /// behavior of the program other than finite running time. Note we do ensure 96 /// that this never remove a loop that might be infinite, as doing so could 97 /// change the halting/non-halting nature of a program. NOTE: This entire 98 /// process relies pretty heavily on LoopSimplify and LCSSA in order to make 99 /// various safety checks work. 100 bool LoopDeletionPass::runImpl(Loop *L, DominatorTree &DT, ScalarEvolution &SE, 101 LoopInfo &loopInfo) { 102 assert(L->isLCSSAForm(DT) && "Expected LCSSA!"); 103 104 // We can only remove the loop if there is a preheader that we can 105 // branch from after removing it. 106 BasicBlock *preheader = L->getLoopPreheader(); 107 if (!preheader) 108 return false; 109 110 // If LoopSimplify form is not available, stay out of trouble. 111 if (!L->hasDedicatedExits()) 112 return false; 113 114 // We can't remove loops that contain subloops. If the subloops were dead, 115 // they would already have been removed in earlier executions of this pass. 116 if (L->begin() != L->end()) 117 return false; 118 119 SmallVector<BasicBlock *, 4> exitingBlocks; 120 L->getExitingBlocks(exitingBlocks); 121 122 SmallVector<BasicBlock *, 4> exitBlocks; 123 L->getUniqueExitBlocks(exitBlocks); 124 125 // We require that the loop only have a single exit block. Otherwise, we'd 126 // be in the situation of needing to be able to solve statically which exit 127 // block will be branched to, or trying to preserve the branching logic in 128 // a loop invariant manner. 129 if (exitBlocks.size() != 1) 130 return false; 131 132 // Finally, we have to check that the loop really is dead. 133 bool Changed = false; 134 if (!isLoopDead(L, SE, exitingBlocks, exitBlocks, Changed, preheader)) 135 return Changed; 136 137 // Don't remove loops for which we can't solve the trip count. 138 // They could be infinite, in which case we'd be changing program behavior. 139 const SCEV *S = SE.getMaxBackedgeTakenCount(L); 140 if (isa<SCEVCouldNotCompute>(S)) 141 return Changed; 142 143 // Now that we know the removal is safe, remove the loop by changing the 144 // branch from the preheader to go to the single exit block. 145 BasicBlock *exitBlock = exitBlocks[0]; 146 147 // Because we're deleting a large chunk of code at once, the sequence in which 148 // we remove things is very important to avoid invalidation issues. Don't 149 // mess with this unless you have good reason and know what you're doing. 150 151 // Tell ScalarEvolution that the loop is deleted. Do this before 152 // deleting the loop so that ScalarEvolution can look at the loop 153 // to determine what it needs to clean up. 154 SE.forgetLoop(L); 155 156 // Connect the preheader directly to the exit block. 157 TerminatorInst *TI = preheader->getTerminator(); 158 TI->replaceUsesOfWith(L->getHeader(), exitBlock); 159 160 // Rewrite phis in the exit block to get their inputs from 161 // the preheader instead of the exiting block. 162 BasicBlock *exitingBlock = exitingBlocks[0]; 163 BasicBlock::iterator BI = exitBlock->begin(); 164 while (PHINode *P = dyn_cast<PHINode>(BI)) { 165 int j = P->getBasicBlockIndex(exitingBlock); 166 assert(j >= 0 && "Can't find exiting block in exit block's phi node!"); 167 P->setIncomingBlock(j, preheader); 168 for (unsigned i = 1; i < exitingBlocks.size(); ++i) 169 P->removeIncomingValue(exitingBlocks[i]); 170 ++BI; 171 } 172 173 // Update the dominator tree and remove the instructions and blocks that will 174 // be deleted from the reference counting scheme. 175 SmallVector<DomTreeNode*, 8> ChildNodes; 176 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 177 LI != LE; ++LI) { 178 // Move all of the block's children to be children of the preheader, which 179 // allows us to remove the domtree entry for the block. 180 ChildNodes.insert(ChildNodes.begin(), DT[*LI]->begin(), DT[*LI]->end()); 181 for (DomTreeNode *ChildNode : ChildNodes) { 182 DT.changeImmediateDominator(ChildNode, DT[preheader]); 183 } 184 185 ChildNodes.clear(); 186 DT.eraseNode(*LI); 187 188 // Remove the block from the reference counting scheme, so that we can 189 // delete it freely later. 190 (*LI)->dropAllReferences(); 191 } 192 193 // Erase the instructions and the blocks without having to worry 194 // about ordering because we already dropped the references. 195 // NOTE: This iteration is safe because erasing the block does not remove its 196 // entry from the loop's block list. We do that in the next section. 197 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 198 LI != LE; ++LI) 199 (*LI)->eraseFromParent(); 200 201 // Finally, the blocks from loopinfo. This has to happen late because 202 // otherwise our loop iterators won't work. 203 204 SmallPtrSet<BasicBlock *, 8> blocks; 205 blocks.insert(L->block_begin(), L->block_end()); 206 for (BasicBlock *BB : blocks) 207 loopInfo.removeBlock(BB); 208 209 // The last step is to update LoopInfo now that we've eliminated this loop. 210 loopInfo.markAsRemoved(L); 211 Changed = true; 212 213 ++NumDeleted; 214 215 return Changed; 216 } 217 218 PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM) { 219 auto &FAM = AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager(); 220 Function *F = L.getHeader()->getParent(); 221 222 auto &DT = *FAM.getCachedResult<DominatorTreeAnalysis>(*F); 223 auto &SE = *FAM.getCachedResult<ScalarEvolutionAnalysis>(*F); 224 auto &LI = *FAM.getCachedResult<LoopAnalysis>(*F); 225 226 bool Changed = runImpl(&L, DT, SE, LI); 227 if (!Changed) 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 &loopInfo = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 266 267 LoopDeletionPass Impl; 268 return Impl.runImpl(L, DT, SE, loopInfo); 269 } 270