LLVM API Documentation
00001 //===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the Dead Loop Deletion Pass. This pass is responsible 00011 // for eliminating loops with non-infinite computable trip counts that have no 00012 // side effects or volatile instructions, and do not contribute to the 00013 // computation of the function's return value. 00014 // 00015 //===----------------------------------------------------------------------===// 00016 00017 #include "llvm/Transforms/Scalar.h" 00018 #include "llvm/ADT/SmallVector.h" 00019 #include "llvm/ADT/Statistic.h" 00020 #include "llvm/Analysis/LoopPass.h" 00021 #include "llvm/Analysis/ScalarEvolution.h" 00022 #include "llvm/IR/Dominators.h" 00023 using namespace llvm; 00024 00025 #define DEBUG_TYPE "loop-delete" 00026 00027 STATISTIC(NumDeleted, "Number of loops deleted"); 00028 00029 namespace { 00030 class LoopDeletion : public LoopPass { 00031 public: 00032 static char ID; // Pass ID, replacement for typeid 00033 LoopDeletion() : LoopPass(ID) { 00034 initializeLoopDeletionPass(*PassRegistry::getPassRegistry()); 00035 } 00036 00037 // Possibly eliminate loop L if it is dead. 00038 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 00039 00040 void getAnalysisUsage(AnalysisUsage &AU) const override { 00041 AU.addRequired<DominatorTreeWrapperPass>(); 00042 AU.addRequired<LoopInfo>(); 00043 AU.addRequired<ScalarEvolution>(); 00044 AU.addRequiredID(LoopSimplifyID); 00045 AU.addRequiredID(LCSSAID); 00046 00047 AU.addPreserved<ScalarEvolution>(); 00048 AU.addPreserved<DominatorTreeWrapperPass>(); 00049 AU.addPreserved<LoopInfo>(); 00050 AU.addPreservedID(LoopSimplifyID); 00051 AU.addPreservedID(LCSSAID); 00052 } 00053 00054 private: 00055 bool isLoopDead(Loop *L, SmallVectorImpl<BasicBlock *> &exitingBlocks, 00056 SmallVectorImpl<BasicBlock *> &exitBlocks, 00057 bool &Changed, BasicBlock *Preheader); 00058 00059 }; 00060 } 00061 00062 char LoopDeletion::ID = 0; 00063 INITIALIZE_PASS_BEGIN(LoopDeletion, "loop-deletion", 00064 "Delete dead loops", false, false) 00065 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 00066 INITIALIZE_PASS_DEPENDENCY(LoopInfo) 00067 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 00068 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 00069 INITIALIZE_PASS_DEPENDENCY(LCSSA) 00070 INITIALIZE_PASS_END(LoopDeletion, "loop-deletion", 00071 "Delete dead loops", false, false) 00072 00073 Pass *llvm::createLoopDeletionPass() { 00074 return new LoopDeletion(); 00075 } 00076 00077 /// isLoopDead - Determined if a loop is dead. This assumes that we've already 00078 /// checked for unique exit and exiting blocks, and that the code is in LCSSA 00079 /// form. 00080 bool LoopDeletion::isLoopDead(Loop *L, 00081 SmallVectorImpl<BasicBlock *> &exitingBlocks, 00082 SmallVectorImpl<BasicBlock *> &exitBlocks, 00083 bool &Changed, BasicBlock *Preheader) { 00084 BasicBlock *exitBlock = exitBlocks[0]; 00085 00086 // Make sure that all PHI entries coming from the loop are loop invariant. 00087 // Because the code is in LCSSA form, any values used outside of the loop 00088 // must pass through a PHI in the exit block, meaning that this check is 00089 // sufficient to guarantee that no loop-variant values are used outside 00090 // of the loop. 00091 BasicBlock::iterator BI = exitBlock->begin(); 00092 while (PHINode *P = dyn_cast<PHINode>(BI)) { 00093 Value *incoming = P->getIncomingValueForBlock(exitingBlocks[0]); 00094 00095 // Make sure all exiting blocks produce the same incoming value for the exit 00096 // block. If there are different incoming values for different exiting 00097 // blocks, then it is impossible to statically determine which value should 00098 // be used. 00099 for (unsigned i = 1, e = exitingBlocks.size(); i < e; ++i) { 00100 if (incoming != P->getIncomingValueForBlock(exitingBlocks[i])) 00101 return false; 00102 } 00103 00104 if (Instruction *I = dyn_cast<Instruction>(incoming)) 00105 if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) 00106 return false; 00107 00108 ++BI; 00109 } 00110 00111 // Make sure that no instructions in the block have potential side-effects. 00112 // This includes instructions that could write to memory, and loads that are 00113 // marked volatile. This could be made more aggressive by using aliasing 00114 // information to identify readonly and readnone calls. 00115 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 00116 LI != LE; ++LI) { 00117 for (BasicBlock::iterator BI = (*LI)->begin(), BE = (*LI)->end(); 00118 BI != BE; ++BI) { 00119 if (BI->mayHaveSideEffects()) 00120 return false; 00121 } 00122 } 00123 00124 return true; 00125 } 00126 00127 /// runOnLoop - Remove dead loops, by which we mean loops that do not impact the 00128 /// observable behavior of the program other than finite running time. Note 00129 /// we do ensure that this never remove a loop that might be infinite, as doing 00130 /// so could change the halting/non-halting nature of a program. 00131 /// NOTE: This entire process relies pretty heavily on LoopSimplify and LCSSA 00132 /// in order to make various safety checks work. 00133 bool LoopDeletion::runOnLoop(Loop *L, LPPassManager &LPM) { 00134 if (skipOptnoneFunction(L)) 00135 return false; 00136 00137 // We can only remove the loop if there is a preheader that we can 00138 // branch from after removing it. 00139 BasicBlock *preheader = L->getLoopPreheader(); 00140 if (!preheader) 00141 return false; 00142 00143 // If LoopSimplify form is not available, stay out of trouble. 00144 if (!L->hasDedicatedExits()) 00145 return false; 00146 00147 // We can't remove loops that contain subloops. If the subloops were dead, 00148 // they would already have been removed in earlier executions of this pass. 00149 if (L->begin() != L->end()) 00150 return false; 00151 00152 SmallVector<BasicBlock*, 4> exitingBlocks; 00153 L->getExitingBlocks(exitingBlocks); 00154 00155 SmallVector<BasicBlock*, 4> exitBlocks; 00156 L->getUniqueExitBlocks(exitBlocks); 00157 00158 // We require that the loop only have a single exit block. Otherwise, we'd 00159 // be in the situation of needing to be able to solve statically which exit 00160 // block will be branched to, or trying to preserve the branching logic in 00161 // a loop invariant manner. 00162 if (exitBlocks.size() != 1) 00163 return false; 00164 00165 // Finally, we have to check that the loop really is dead. 00166 bool Changed = false; 00167 if (!isLoopDead(L, exitingBlocks, exitBlocks, Changed, preheader)) 00168 return Changed; 00169 00170 // Don't remove loops for which we can't solve the trip count. 00171 // They could be infinite, in which case we'd be changing program behavior. 00172 ScalarEvolution &SE = getAnalysis<ScalarEvolution>(); 00173 const SCEV *S = SE.getMaxBackedgeTakenCount(L); 00174 if (isa<SCEVCouldNotCompute>(S)) 00175 return Changed; 00176 00177 // Now that we know the removal is safe, remove the loop by changing the 00178 // branch from the preheader to go to the single exit block. 00179 BasicBlock *exitBlock = exitBlocks[0]; 00180 00181 // Because we're deleting a large chunk of code at once, the sequence in which 00182 // we remove things is very important to avoid invalidation issues. Don't 00183 // mess with this unless you have good reason and know what you're doing. 00184 00185 // Tell ScalarEvolution that the loop is deleted. Do this before 00186 // deleting the loop so that ScalarEvolution can look at the loop 00187 // to determine what it needs to clean up. 00188 SE.forgetLoop(L); 00189 00190 // Connect the preheader directly to the exit block. 00191 TerminatorInst *TI = preheader->getTerminator(); 00192 TI->replaceUsesOfWith(L->getHeader(), exitBlock); 00193 00194 // Rewrite phis in the exit block to get their inputs from 00195 // the preheader instead of the exiting block. 00196 BasicBlock *exitingBlock = exitingBlocks[0]; 00197 BasicBlock::iterator BI = exitBlock->begin(); 00198 while (PHINode *P = dyn_cast<PHINode>(BI)) { 00199 int j = P->getBasicBlockIndex(exitingBlock); 00200 assert(j >= 0 && "Can't find exiting block in exit block's phi node!"); 00201 P->setIncomingBlock(j, preheader); 00202 for (unsigned i = 1; i < exitingBlocks.size(); ++i) 00203 P->removeIncomingValue(exitingBlocks[i]); 00204 ++BI; 00205 } 00206 00207 // Update the dominator tree and remove the instructions and blocks that will 00208 // be deleted from the reference counting scheme. 00209 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 00210 SmallVector<DomTreeNode*, 8> ChildNodes; 00211 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 00212 LI != LE; ++LI) { 00213 // Move all of the block's children to be children of the preheader, which 00214 // allows us to remove the domtree entry for the block. 00215 ChildNodes.insert(ChildNodes.begin(), DT[*LI]->begin(), DT[*LI]->end()); 00216 for (SmallVectorImpl<DomTreeNode *>::iterator DI = ChildNodes.begin(), 00217 DE = ChildNodes.end(); DI != DE; ++DI) { 00218 DT.changeImmediateDominator(*DI, DT[preheader]); 00219 } 00220 00221 ChildNodes.clear(); 00222 DT.eraseNode(*LI); 00223 00224 // Remove the block from the reference counting scheme, so that we can 00225 // delete it freely later. 00226 (*LI)->dropAllReferences(); 00227 } 00228 00229 // Erase the instructions and the blocks without having to worry 00230 // about ordering because we already dropped the references. 00231 // NOTE: This iteration is safe because erasing the block does not remove its 00232 // entry from the loop's block list. We do that in the next section. 00233 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 00234 LI != LE; ++LI) 00235 (*LI)->eraseFromParent(); 00236 00237 // Finally, the blocks from loopinfo. This has to happen late because 00238 // otherwise our loop iterators won't work. 00239 LoopInfo &loopInfo = getAnalysis<LoopInfo>(); 00240 SmallPtrSet<BasicBlock*, 8> blocks; 00241 blocks.insert(L->block_begin(), L->block_end()); 00242 for (BasicBlock *BB : blocks) 00243 loopInfo.removeBlock(BB); 00244 00245 // The last step is to inform the loop pass manager that we've 00246 // eliminated this loop. 00247 LPM.deleteLoopFromQueue(L); 00248 Changed = true; 00249 00250 ++NumDeleted; 00251 00252 return Changed; 00253 }