1193323Sed//===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===// 2193323Sed// 3193323Sed// The LLVM Compiler Infrastructure 4193323Sed// 5193323Sed// This file is distributed under the University of Illinois Open Source 6193323Sed// License. See LICENSE.TXT for details. 7193323Sed// 8193323Sed//===----------------------------------------------------------------------===// 9193323Sed// 10193323Sed// This file implements the Dead Loop Deletion Pass. This pass is responsible 11193323Sed// for eliminating loops with non-infinite computable trip counts that have no 12193323Sed// side effects or volatile instructions, and do not contribute to the 13193323Sed// computation of the function's return value. 14193323Sed// 15193323Sed//===----------------------------------------------------------------------===// 16193323Sed 17193323Sed#define DEBUG_TYPE "loop-delete" 18193323Sed#include "llvm/Transforms/Scalar.h" 19249423Sdim#include "llvm/ADT/SmallVector.h" 20249423Sdim#include "llvm/ADT/Statistic.h" 21249423Sdim#include "llvm/Analysis/Dominators.h" 22193323Sed#include "llvm/Analysis/LoopPass.h" 23193323Sed#include "llvm/Analysis/ScalarEvolution.h" 24193323Sedusing namespace llvm; 25193323Sed 26193323SedSTATISTIC(NumDeleted, "Number of loops deleted"); 27193323Sed 28193323Sednamespace { 29198090Srdivacky class LoopDeletion : public LoopPass { 30193323Sed public: 31193323Sed static char ID; // Pass ID, replacement for typeid 32218893Sdim LoopDeletion() : LoopPass(ID) { 33218893Sdim initializeLoopDeletionPass(*PassRegistry::getPassRegistry()); 34218893Sdim } 35239462Sdim 36193323Sed // Possibly eliminate loop L if it is dead. 37249423Sdim bool runOnLoop(Loop *L, LPPassManager &LPM); 38239462Sdim 39249423Sdim virtual void getAnalysisUsage(AnalysisUsage &AU) const { 40193323Sed AU.addRequired<DominatorTree>(); 41193323Sed AU.addRequired<LoopInfo>(); 42212904Sdim AU.addRequired<ScalarEvolution>(); 43193323Sed AU.addRequiredID(LoopSimplifyID); 44193323Sed AU.addRequiredID(LCSSAID); 45239462Sdim 46193323Sed AU.addPreserved<ScalarEvolution>(); 47193323Sed AU.addPreserved<DominatorTree>(); 48193323Sed AU.addPreserved<LoopInfo>(); 49193323Sed AU.addPreservedID(LoopSimplifyID); 50193323Sed AU.addPreservedID(LCSSAID); 51193323Sed } 52249423Sdim 53249423Sdim private: 54263508Sdim bool isLoopDead(Loop *L, SmallVectorImpl<BasicBlock *> &exitingBlocks, 55263508Sdim SmallVectorImpl<BasicBlock *> &exitBlocks, 56249423Sdim bool &Changed, BasicBlock *Preheader); 57249423Sdim 58193323Sed }; 59193323Sed} 60239462Sdim 61193323Sedchar LoopDeletion::ID = 0; 62218893SdimINITIALIZE_PASS_BEGIN(LoopDeletion, "loop-deletion", 63218893Sdim "Delete dead loops", false, false) 64218893SdimINITIALIZE_PASS_DEPENDENCY(DominatorTree) 65218893SdimINITIALIZE_PASS_DEPENDENCY(LoopInfo) 66218893SdimINITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 67218893SdimINITIALIZE_PASS_DEPENDENCY(LoopSimplify) 68218893SdimINITIALIZE_PASS_DEPENDENCY(LCSSA) 69218893SdimINITIALIZE_PASS_END(LoopDeletion, "loop-deletion", 70218893Sdim "Delete dead loops", false, false) 71193323Sed 72249423SdimPass *llvm::createLoopDeletionPass() { 73193323Sed return new LoopDeletion(); 74193323Sed} 75193323Sed 76249423Sdim/// isLoopDead - Determined if a loop is dead. This assumes that we've already 77193323Sed/// checked for unique exit and exiting blocks, and that the code is in LCSSA 78193323Sed/// form. 79249423Sdimbool LoopDeletion::isLoopDead(Loop *L, 80263508Sdim SmallVectorImpl<BasicBlock *> &exitingBlocks, 81263508Sdim SmallVectorImpl<BasicBlock *> &exitBlocks, 82198090Srdivacky bool &Changed, BasicBlock *Preheader) { 83249423Sdim BasicBlock *exitBlock = exitBlocks[0]; 84239462Sdim 85193323Sed // Make sure that all PHI entries coming from the loop are loop invariant. 86193323Sed // Because the code is in LCSSA form, any values used outside of the loop 87193323Sed // must pass through a PHI in the exit block, meaning that this check is 88193323Sed // sufficient to guarantee that no loop-variant values are used outside 89193323Sed // of the loop. 90193323Sed BasicBlock::iterator BI = exitBlock->begin(); 91249423Sdim while (PHINode *P = dyn_cast<PHINode>(BI)) { 92249423Sdim Value *incoming = P->getIncomingValueForBlock(exitingBlocks[0]); 93219077Sdim 94219077Sdim // Make sure all exiting blocks produce the same incoming value for the exit 95219077Sdim // block. If there are different incoming values for different exiting 96219077Sdim // blocks, then it is impossible to statically determine which value should 97219077Sdim // be used. 98249423Sdim for (unsigned i = 1, e = exitingBlocks.size(); i < e; ++i) { 99219077Sdim if (incoming != P->getIncomingValueForBlock(exitingBlocks[i])) 100219077Sdim return false; 101219077Sdim } 102239462Sdim 103249423Sdim if (Instruction *I = dyn_cast<Instruction>(incoming)) 104198090Srdivacky if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) 105193323Sed return false; 106219077Sdim 107210299Sed ++BI; 108193323Sed } 109239462Sdim 110193323Sed // Make sure that no instructions in the block have potential side-effects. 111193323Sed // This includes instructions that could write to memory, and loads that are 112193323Sed // marked volatile. This could be made more aggressive by using aliasing 113193323Sed // information to identify readonly and readnone calls. 114193323Sed for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 115193323Sed LI != LE; ++LI) { 116193323Sed for (BasicBlock::iterator BI = (*LI)->begin(), BE = (*LI)->end(); 117193323Sed BI != BE; ++BI) { 118193323Sed if (BI->mayHaveSideEffects()) 119193323Sed return false; 120193323Sed } 121193323Sed } 122239462Sdim 123193323Sed return true; 124193323Sed} 125193323Sed 126193323Sed/// runOnLoop - Remove dead loops, by which we mean loops that do not impact the 127239462Sdim/// observable behavior of the program other than finite running time. Note 128193323Sed/// we do ensure that this never remove a loop that might be infinite, as doing 129193323Sed/// so could change the halting/non-halting nature of a program. 130193323Sed/// NOTE: This entire process relies pretty heavily on LoopSimplify and LCSSA 131193323Sed/// in order to make various safety checks work. 132249423Sdimbool LoopDeletion::runOnLoop(Loop *L, LPPassManager &LPM) { 133239462Sdim // We can only remove the loop if there is a preheader that we can 134193323Sed // branch from after removing it. 135249423Sdim BasicBlock *preheader = L->getLoopPreheader(); 136193323Sed if (!preheader) 137193323Sed return false; 138239462Sdim 139199481Srdivacky // If LoopSimplify form is not available, stay out of trouble. 140199481Srdivacky if (!L->hasDedicatedExits()) 141199481Srdivacky return false; 142199481Srdivacky 143193323Sed // We can't remove loops that contain subloops. If the subloops were dead, 144193323Sed // they would already have been removed in earlier executions of this pass. 145193323Sed if (L->begin() != L->end()) 146193323Sed return false; 147239462Sdim 148193323Sed SmallVector<BasicBlock*, 4> exitingBlocks; 149193323Sed L->getExitingBlocks(exitingBlocks); 150239462Sdim 151193323Sed SmallVector<BasicBlock*, 4> exitBlocks; 152193323Sed L->getUniqueExitBlocks(exitBlocks); 153239462Sdim 154193323Sed // We require that the loop only have a single exit block. Otherwise, we'd 155193323Sed // be in the situation of needing to be able to solve statically which exit 156193323Sed // block will be branched to, or trying to preserve the branching logic in 157193323Sed // a loop invariant manner. 158193323Sed if (exitBlocks.size() != 1) 159193323Sed return false; 160239462Sdim 161193323Sed // Finally, we have to check that the loop really is dead. 162198090Srdivacky bool Changed = false; 163249423Sdim if (!isLoopDead(L, exitingBlocks, exitBlocks, Changed, preheader)) 164198090Srdivacky return Changed; 165239462Sdim 166193323Sed // Don't remove loops for which we can't solve the trip count. 167193323Sed // They could be infinite, in which case we'd be changing program behavior. 168249423Sdim ScalarEvolution &SE = getAnalysis<ScalarEvolution>(); 169198892Srdivacky const SCEV *S = SE.getMaxBackedgeTakenCount(L); 170193323Sed if (isa<SCEVCouldNotCompute>(S)) 171198090Srdivacky return Changed; 172239462Sdim 173193323Sed // Now that we know the removal is safe, remove the loop by changing the 174239462Sdim // branch from the preheader to go to the single exit block. 175249423Sdim BasicBlock *exitBlock = exitBlocks[0]; 176239462Sdim 177193323Sed // Because we're deleting a large chunk of code at once, the sequence in which 178193323Sed // we remove things is very important to avoid invalidation issues. Don't 179193323Sed // mess with this unless you have good reason and know what you're doing. 180198090Srdivacky 181198090Srdivacky // Tell ScalarEvolution that the loop is deleted. Do this before 182198090Srdivacky // deleting the loop so that ScalarEvolution can look at the loop 183198090Srdivacky // to determine what it needs to clean up. 184198892Srdivacky SE.forgetLoop(L); 185198090Srdivacky 186193323Sed // Connect the preheader directly to the exit block. 187249423Sdim TerminatorInst *TI = preheader->getTerminator(); 188193323Sed TI->replaceUsesOfWith(L->getHeader(), exitBlock); 189193323Sed 190193323Sed // Rewrite phis in the exit block to get their inputs from 191193323Sed // the preheader instead of the exiting block. 192249423Sdim BasicBlock *exitingBlock = exitingBlocks[0]; 193193323Sed BasicBlock::iterator BI = exitBlock->begin(); 194249423Sdim while (PHINode *P = dyn_cast<PHINode>(BI)) { 195224145Sdim int j = P->getBasicBlockIndex(exitingBlock); 196224145Sdim assert(j >= 0 && "Can't find exiting block in exit block's phi node!"); 197224145Sdim P->setIncomingBlock(j, preheader); 198219077Sdim for (unsigned i = 1; i < exitingBlocks.size(); ++i) 199219077Sdim P->removeIncomingValue(exitingBlocks[i]); 200210299Sed ++BI; 201193323Sed } 202239462Sdim 203193323Sed // Update the dominator tree and remove the instructions and blocks that will 204193323Sed // be deleted from the reference counting scheme. 205249423Sdim DominatorTree &DT = getAnalysis<DominatorTree>(); 206218893Sdim SmallVector<DomTreeNode*, 8> ChildNodes; 207193323Sed for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 208193323Sed LI != LE; ++LI) { 209193323Sed // Move all of the block's children to be children of the preheader, which 210193323Sed // allows us to remove the domtree entry for the block. 211218893Sdim ChildNodes.insert(ChildNodes.begin(), DT[*LI]->begin(), DT[*LI]->end()); 212263508Sdim for (SmallVectorImpl<DomTreeNode *>::iterator DI = ChildNodes.begin(), 213193323Sed DE = ChildNodes.end(); DI != DE; ++DI) { 214193323Sed DT.changeImmediateDominator(*DI, DT[preheader]); 215193323Sed } 216239462Sdim 217193323Sed ChildNodes.clear(); 218193323Sed DT.eraseNode(*LI); 219193323Sed 220193323Sed // Remove the block from the reference counting scheme, so that we can 221193323Sed // delete it freely later. 222193323Sed (*LI)->dropAllReferences(); 223193323Sed } 224239462Sdim 225193323Sed // Erase the instructions and the blocks without having to worry 226193323Sed // about ordering because we already dropped the references. 227193323Sed // NOTE: This iteration is safe because erasing the block does not remove its 228193323Sed // entry from the loop's block list. We do that in the next section. 229193323Sed for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 230193323Sed LI != LE; ++LI) 231193323Sed (*LI)->eraseFromParent(); 232193323Sed 233193323Sed // Finally, the blocks from loopinfo. This has to happen late because 234193323Sed // otherwise our loop iterators won't work. 235249423Sdim LoopInfo &loopInfo = getAnalysis<LoopInfo>(); 236193323Sed SmallPtrSet<BasicBlock*, 8> blocks; 237193323Sed blocks.insert(L->block_begin(), L->block_end()); 238193323Sed for (SmallPtrSet<BasicBlock*,8>::iterator I = blocks.begin(), 239193323Sed E = blocks.end(); I != E; ++I) 240193323Sed loopInfo.removeBlock(*I); 241239462Sdim 242193323Sed // The last step is to inform the loop pass manager that we've 243193323Sed // eliminated this loop. 244193323Sed LPM.deleteLoopFromQueue(L); 245198090Srdivacky Changed = true; 246239462Sdim 247210299Sed ++NumDeleted; 248239462Sdim 249198090Srdivacky return Changed; 250193323Sed} 251