LLVM API Documentation
00001 //===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===// 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 a trivial dead store elimination that only considers 00011 // basic-block local redundant stores. 00012 // 00013 // FIXME: This should eventually be extended to be a post-dominator tree 00014 // traversal. Doing so would be pretty trivial. 00015 // 00016 //===----------------------------------------------------------------------===// 00017 00018 #define DEBUG_TYPE "dse" 00019 #include "llvm/Transforms/Scalar.h" 00020 #include "llvm/Constants.h" 00021 #include "llvm/Function.h" 00022 #include "llvm/Instructions.h" 00023 #include "llvm/IntrinsicInst.h" 00024 #include "llvm/Pass.h" 00025 #include "llvm/ADT/SmallPtrSet.h" 00026 #include "llvm/ADT/Statistic.h" 00027 #include "llvm/Analysis/AliasAnalysis.h" 00028 #include "llvm/Analysis/Dominators.h" 00029 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 00030 #include "llvm/Target/TargetData.h" 00031 #include "llvm/Transforms/Utils/Local.h" 00032 #include "llvm/Support/Compiler.h" 00033 using namespace llvm; 00034 00035 STATISTIC(NumFastStores, "Number of stores deleted"); 00036 STATISTIC(NumFastOther , "Number of other instrs removed"); 00037 00038 namespace { 00039 struct VISIBILITY_HIDDEN DSE : public FunctionPass { 00040 static char ID; // Pass identification, replacement for typeid 00041 DSE() : FunctionPass(&ID) {} 00042 00043 virtual bool runOnFunction(Function &F) { 00044 bool Changed = false; 00045 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) 00046 Changed |= runOnBasicBlock(*I); 00047 return Changed; 00048 } 00049 00050 bool runOnBasicBlock(BasicBlock &BB); 00051 bool handleFreeWithNonTrivialDependency(FreeInst *F, MemDepResult Dep); 00052 bool handleEndBlock(BasicBlock &BB); 00053 bool RemoveUndeadPointers(Value* Ptr, uint64_t killPointerSize, 00054 BasicBlock::iterator& BBI, 00055 SmallPtrSet<Value*, 64>& deadPointers); 00056 void DeleteDeadInstruction(Instruction *I, 00057 SmallPtrSet<Value*, 64> *deadPointers = 0); 00058 00059 00060 // getAnalysisUsage - We require post dominance frontiers (aka Control 00061 // Dependence Graph) 00062 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 00063 AU.setPreservesCFG(); 00064 AU.addRequired<DominatorTree>(); 00065 AU.addRequired<TargetData>(); 00066 AU.addRequired<AliasAnalysis>(); 00067 AU.addRequired<MemoryDependenceAnalysis>(); 00068 AU.addPreserved<DominatorTree>(); 00069 AU.addPreserved<AliasAnalysis>(); 00070 AU.addPreserved<MemoryDependenceAnalysis>(); 00071 } 00072 }; 00073 } 00074 00075 char DSE::ID = 0; 00076 static RegisterPass<DSE> X("dse", "Dead Store Elimination"); 00077 00078 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); } 00079 00080 bool DSE::runOnBasicBlock(BasicBlock &BB) { 00081 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>(); 00082 TargetData &TD = getAnalysis<TargetData>(); 00083 00084 bool MadeChange = false; 00085 00086 // Do a top-down walk on the BB 00087 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) { 00088 Instruction *Inst = BBI++; 00089 00090 // If we find a store or a free, get it's memory dependence. 00091 if (!isa<StoreInst>(Inst) && !isa<FreeInst>(Inst)) 00092 continue; 00093 00094 // Don't molest volatile stores or do queries that will return "clobber". 00095 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) 00096 if (SI->isVolatile()) 00097 continue; 00098 00099 MemDepResult InstDep = MD.getDependency(Inst); 00100 00101 // Ignore non-local stores. 00102 // FIXME: cross-block DSE would be fun. :) 00103 if (InstDep.isNonLocal()) continue; 00104 00105 // Handle frees whose dependencies are non-trivial. 00106 if (FreeInst *FI = dyn_cast<FreeInst>(Inst)) { 00107 MadeChange |= handleFreeWithNonTrivialDependency(FI, InstDep); 00108 continue; 00109 } 00110 00111 StoreInst *SI = cast<StoreInst>(Inst); 00112 00113 // If not a definite must-alias dependency, ignore it. 00114 if (!InstDep.isDef()) 00115 continue; 00116 00117 // If this is a store-store dependence, then the previous store is dead so 00118 // long as this store is at least as big as it. 00119 if (StoreInst *DepStore = dyn_cast<StoreInst>(InstDep.getInst())) 00120 if (TD.getTypeStoreSize(DepStore->getOperand(0)->getType()) <= 00121 TD.getTypeStoreSize(SI->getOperand(0)->getType())) { 00122 // Delete the store and now-dead instructions that feed it. 00123 DeleteDeadInstruction(DepStore); 00124 NumFastStores++; 00125 MadeChange = true; 00126 00127 if (BBI != BB.begin()) 00128 --BBI; 00129 continue; 00130 } 00131 00132 // If we're storing the same value back to a pointer that we just 00133 // loaded from, then the store can be removed. 00134 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) { 00135 if (SI->getPointerOperand() == DepLoad->getPointerOperand() && 00136 SI->getOperand(0) == DepLoad) { 00137 DeleteDeadInstruction(SI); 00138 if (BBI != BB.begin()) 00139 --BBI; 00140 NumFastStores++; 00141 MadeChange = true; 00142 continue; 00143 } 00144 } 00145 } 00146 00147 // If this block ends in a return, unwind, or unreachable, all allocas are 00148 // dead at its end, which means stores to them are also dead. 00149 if (BB.getTerminator()->getNumSuccessors() == 0) 00150 MadeChange |= handleEndBlock(BB); 00151 00152 return MadeChange; 00153 } 00154 00155 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose 00156 /// dependency is a store to a field of that structure. 00157 bool DSE::handleFreeWithNonTrivialDependency(FreeInst *F, MemDepResult Dep) { 00158 AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); 00159 00160 StoreInst *Dependency = dyn_cast_or_null<StoreInst>(Dep.getInst()); 00161 if (!Dependency || Dependency->isVolatile()) 00162 return false; 00163 00164 Value *DepPointer = Dependency->getPointerOperand()->getUnderlyingObject(); 00165 00166 // Check for aliasing. 00167 if (AA.alias(F->getPointerOperand(), 1, DepPointer, 1) != 00168 AliasAnalysis::MustAlias) 00169 return false; 00170 00171 // DCE instructions only used to calculate that store 00172 DeleteDeadInstruction(Dependency); 00173 NumFastStores++; 00174 return true; 00175 } 00176 00177 /// handleEndBlock - Remove dead stores to stack-allocated locations in the 00178 /// function end block. Ex: 00179 /// %A = alloca i32 00180 /// ... 00181 /// store i32 1, i32* %A 00182 /// ret void 00183 bool DSE::handleEndBlock(BasicBlock &BB) { 00184 TargetData &TD = getAnalysis<TargetData>(); 00185 AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); 00186 00187 bool MadeChange = false; 00188 00189 // Pointers alloca'd in this function are dead in the end block 00190 SmallPtrSet<Value*, 64> deadPointers; 00191 00192 // Find all of the alloca'd pointers in the entry block. 00193 BasicBlock *Entry = BB.getParent()->begin(); 00194 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I) 00195 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) 00196 deadPointers.insert(AI); 00197 00198 // Treat byval arguments the same, stores to them are dead at the end of the 00199 // function. 00200 for (Function::arg_iterator AI = BB.getParent()->arg_begin(), 00201 AE = BB.getParent()->arg_end(); AI != AE; ++AI) 00202 if (AI->hasByValAttr()) 00203 deadPointers.insert(AI); 00204 00205 // Scan the basic block backwards 00206 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){ 00207 --BBI; 00208 00209 // If we find a store whose pointer is dead. 00210 if (StoreInst* S = dyn_cast<StoreInst>(BBI)) { 00211 if (!S->isVolatile()) { 00212 // See through pointer-to-pointer bitcasts 00213 Value* pointerOperand = S->getPointerOperand()->getUnderlyingObject(); 00214 00215 // Alloca'd pointers or byval arguments (which are functionally like 00216 // alloca's) are valid candidates for removal. 00217 if (deadPointers.count(pointerOperand)) { 00218 // DCE instructions only used to calculate that store. 00219 BBI++; 00220 DeleteDeadInstruction(S, &deadPointers); 00221 NumFastStores++; 00222 MadeChange = true; 00223 } 00224 } 00225 00226 continue; 00227 } 00228 00229 // We can also remove memcpy's to local variables at the end of a function. 00230 if (MemCpyInst *M = dyn_cast<MemCpyInst>(BBI)) { 00231 Value *dest = M->getDest()->getUnderlyingObject(); 00232 00233 if (deadPointers.count(dest)) { 00234 BBI++; 00235 DeleteDeadInstruction(M, &deadPointers); 00236 NumFastOther++; 00237 MadeChange = true; 00238 continue; 00239 } 00240 00241 // Because a memcpy is also a load, we can't skip it if we didn't remove 00242 // it. 00243 } 00244 00245 Value* killPointer = 0; 00246 uint64_t killPointerSize = ~0UL; 00247 00248 // If we encounter a use of the pointer, it is no longer considered dead 00249 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) { 00250 // However, if this load is unused and not volatile, we can go ahead and 00251 // remove it, and not have to worry about it making our pointer undead! 00252 if (L->use_empty() && !L->isVolatile()) { 00253 BBI++; 00254 DeleteDeadInstruction(L, &deadPointers); 00255 NumFastOther++; 00256 MadeChange = true; 00257 continue; 00258 } 00259 00260 killPointer = L->getPointerOperand(); 00261 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) { 00262 killPointer = V->getOperand(0); 00263 } else if (isa<MemCpyInst>(BBI) && 00264 isa<ConstantInt>(cast<MemCpyInst>(BBI)->getLength())) { 00265 killPointer = cast<MemCpyInst>(BBI)->getSource(); 00266 killPointerSize = cast<ConstantInt>( 00267 cast<MemCpyInst>(BBI)->getLength())->getZExtValue(); 00268 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) { 00269 deadPointers.erase(A); 00270 00271 // Dead alloca's can be DCE'd when we reach them 00272 if (A->use_empty()) { 00273 BBI++; 00274 DeleteDeadInstruction(A, &deadPointers); 00275 NumFastOther++; 00276 MadeChange = true; 00277 } 00278 00279 continue; 00280 } else if (CallSite::get(BBI).getInstruction() != 0) { 00281 // If this call does not access memory, it can't 00282 // be undeadifying any of our pointers. 00283 CallSite CS = CallSite::get(BBI); 00284 if (AA.doesNotAccessMemory(CS)) 00285 continue; 00286 00287 unsigned modRef = 0; 00288 unsigned other = 0; 00289 00290 // Remove any pointers made undead by the call from the dead set 00291 std::vector<Value*> dead; 00292 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(), 00293 E = deadPointers.end(); I != E; ++I) { 00294 // HACK: if we detect that our AA is imprecise, it's not 00295 // worth it to scan the rest of the deadPointers set. Just 00296 // assume that the AA will return ModRef for everything, and 00297 // go ahead and bail. 00298 if (modRef >= 16 && other == 0) { 00299 deadPointers.clear(); 00300 return MadeChange; 00301 } 00302 00303 // Get size information for the alloca 00304 unsigned pointerSize = ~0U; 00305 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) { 00306 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize())) 00307 pointerSize = C->getZExtValue() * 00308 TD.getTypePaddedSize(A->getAllocatedType()); 00309 } else { 00310 const PointerType* PT = cast<PointerType>( 00311 cast<Argument>(*I)->getType()); 00312 pointerSize = TD.getTypePaddedSize(PT->getElementType()); 00313 } 00314 00315 // See if the call site touches it 00316 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize); 00317 00318 if (A == AliasAnalysis::ModRef) 00319 modRef++; 00320 else 00321 other++; 00322 00323 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref) 00324 dead.push_back(*I); 00325 } 00326 00327 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end(); 00328 I != E; ++I) 00329 deadPointers.erase(*I); 00330 00331 continue; 00332 } else if (isInstructionTriviallyDead(BBI)) { 00333 // For any non-memory-affecting non-terminators, DCE them as we reach them 00334 Instruction *Inst = BBI; 00335 BBI++; 00336 DeleteDeadInstruction(Inst, &deadPointers); 00337 NumFastOther++; 00338 MadeChange = true; 00339 continue; 00340 } 00341 00342 if (!killPointer) 00343 continue; 00344 00345 killPointer = killPointer->getUnderlyingObject(); 00346 00347 // Deal with undead pointers 00348 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI, 00349 deadPointers); 00350 } 00351 00352 return MadeChange; 00353 } 00354 00355 /// RemoveUndeadPointers - check for uses of a pointer that make it 00356 /// undead when scanning for dead stores to alloca's. 00357 bool DSE::RemoveUndeadPointers(Value* killPointer, uint64_t killPointerSize, 00358 BasicBlock::iterator &BBI, 00359 SmallPtrSet<Value*, 64>& deadPointers) { 00360 TargetData &TD = getAnalysis<TargetData>(); 00361 AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); 00362 00363 // If the kill pointer can be easily reduced to an alloca, 00364 // don't bother doing extraneous AA queries. 00365 if (deadPointers.count(killPointer)) { 00366 deadPointers.erase(killPointer); 00367 return false; 00368 } 00369 00370 // A global can't be in the dead pointer set. 00371 if (isa<GlobalValue>(killPointer)) 00372 return false; 00373 00374 bool MadeChange = false; 00375 00376 SmallVector<Value*, 16> undead; 00377 00378 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(), 00379 E = deadPointers.end(); I != E; ++I) { 00380 // Get size information for the alloca. 00381 unsigned pointerSize = ~0U; 00382 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) { 00383 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize())) 00384 pointerSize = C->getZExtValue() * 00385 TD.getTypePaddedSize(A->getAllocatedType()); 00386 } else { 00387 const PointerType* PT = cast<PointerType>(cast<Argument>(*I)->getType()); 00388 pointerSize = TD.getTypePaddedSize(PT->getElementType()); 00389 } 00390 00391 // See if this pointer could alias it 00392 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize, 00393 killPointer, killPointerSize); 00394 00395 // If it must-alias and a store, we can delete it 00396 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) { 00397 StoreInst* S = cast<StoreInst>(BBI); 00398 00399 // Remove it! 00400 BBI++; 00401 DeleteDeadInstruction(S, &deadPointers); 00402 NumFastStores++; 00403 MadeChange = true; 00404 00405 continue; 00406 00407 // Otherwise, it is undead 00408 } else if (A != AliasAnalysis::NoAlias) 00409 undead.push_back(*I); 00410 } 00411 00412 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end(); 00413 I != E; ++I) 00414 deadPointers.erase(*I); 00415 00416 return MadeChange; 00417 } 00418 00419 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through 00420 /// and zero out all the operands of this instruction. If any of them become 00421 /// dead, delete them and the computation tree that feeds them. 00422 /// 00423 /// If ValueSet is non-null, remove any deleted instructions from it as well. 00424 /// 00425 void DSE::DeleteDeadInstruction(Instruction *I, 00426 SmallPtrSet<Value*, 64> *ValueSet) { 00427 SmallVector<Instruction*, 32> NowDeadInsts; 00428 00429 NowDeadInsts.push_back(I); 00430 --NumFastOther; 00431 00432 // Before we touch this instruction, remove it from memdep! 00433 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>(); 00434 while (!NowDeadInsts.empty()) { 00435 Instruction *DeadInst = NowDeadInsts.back(); 00436 NowDeadInsts.pop_back(); 00437 00438 ++NumFastOther; 00439 00440 // This instruction is dead, zap it, in stages. Start by removing it from 00441 // MemDep, which needs to know the operands and needs it to be in the 00442 // function. 00443 MDA.removeInstruction(DeadInst); 00444 00445 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) { 00446 Value *Op = DeadInst->getOperand(op); 00447 DeadInst->setOperand(op, 0); 00448 00449 // If this operand just became dead, add it to the NowDeadInsts list. 00450 if (!Op->use_empty()) continue; 00451 00452 if (Instruction *OpI = dyn_cast<Instruction>(Op)) 00453 if (isInstructionTriviallyDead(OpI)) 00454 NowDeadInsts.push_back(OpI); 00455 } 00456 00457 DeadInst->eraseFromParent(); 00458 00459 if (ValueSet) ValueSet->erase(DeadInst); 00460 } 00461 }