1 //===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a trivial dead store elimination that only considers
11 // basic-block local redundant stores.
13 // FIXME: This should eventually be extended to be a post-dominator tree
14 // traversal. Doing so would be pretty trivial.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "dse"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Function.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/IntrinsicInst.h"
24 #include "llvm/Pass.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/Dominators.h"
29 #include "llvm/Analysis/MemoryBuiltins.h"
30 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Transforms/Utils/Local.h"
35 STATISTIC(NumFastStores, "Number of stores deleted");
36 STATISTIC(NumFastOther , "Number of other instrs removed");
39 struct DSE : public FunctionPass {
42 static char ID; // Pass identification, replacement for typeid
43 DSE() : FunctionPass(&ID) {}
45 virtual bool runOnFunction(Function &F) {
48 DominatorTree &DT = getAnalysis<DominatorTree>();
50 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
51 // Only check non-dead blocks. Dead blocks may have strange pointer
52 // cycles that will confuse alias analysis.
53 if (DT.isReachableFromEntry(I))
54 Changed |= runOnBasicBlock(*I);
58 bool runOnBasicBlock(BasicBlock &BB);
59 bool handleFreeWithNonTrivialDependency(const CallInst *F,
61 bool handleEndBlock(BasicBlock &BB);
62 bool RemoveUndeadPointers(Value *Ptr, uint64_t killPointerSize,
63 BasicBlock::iterator &BBI,
64 SmallPtrSet<Value*, 64> &deadPointers);
65 void DeleteDeadInstruction(Instruction *I,
66 SmallPtrSet<Value*, 64> *deadPointers = 0);
69 // getAnalysisUsage - We require post dominance frontiers (aka Control
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 AU.addRequired<DominatorTree>();
74 AU.addRequired<AliasAnalysis>();
75 AU.addRequired<MemoryDependenceAnalysis>();
76 AU.addPreserved<DominatorTree>();
77 AU.addPreserved<AliasAnalysis>();
78 AU.addPreserved<MemoryDependenceAnalysis>();
81 unsigned getPointerSize(Value *V) const;
86 static RegisterPass<DSE> X("dse", "Dead Store Elimination");
88 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
90 /// doesClobberMemory - Does this instruction clobber (write without reading)
92 static bool doesClobberMemory(Instruction *I) {
93 if (isa<StoreInst>(I))
95 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
96 switch (II->getIntrinsicID()) {
99 case Intrinsic::memset:
100 case Intrinsic::memmove:
101 case Intrinsic::memcpy:
102 case Intrinsic::init_trampoline:
103 case Intrinsic::lifetime_end:
110 /// isElidable - If the value of this instruction and the memory it writes to is
111 /// unused, may we delete this instrtction?
112 static bool isElidable(Instruction *I) {
113 assert(doesClobberMemory(I));
114 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
115 return II->getIntrinsicID() != Intrinsic::lifetime_end;
116 if (StoreInst *SI = dyn_cast<StoreInst>(I))
117 return !SI->isVolatile();
121 /// getPointerOperand - Return the pointer that is being clobbered.
122 static Value *getPointerOperand(Instruction *I) {
123 assert(doesClobberMemory(I));
124 if (StoreInst *SI = dyn_cast<StoreInst>(I))
125 return SI->getPointerOperand();
126 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
127 return MI->getArgOperand(0);
129 IntrinsicInst *II = cast<IntrinsicInst>(I);
130 switch (II->getIntrinsicID()) {
131 default: assert(false && "Unexpected intrinsic!");
132 case Intrinsic::init_trampoline:
133 return II->getArgOperand(0);
134 case Intrinsic::lifetime_end:
135 return II->getArgOperand(1);
139 /// getStoreSize - Return the length in bytes of the write by the clobbering
140 /// instruction. If variable or unknown, returns -1.
141 static unsigned getStoreSize(Instruction *I, const TargetData *TD) {
142 assert(doesClobberMemory(I));
143 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
145 return TD->getTypeStoreSize(SI->getOperand(0)->getType());
149 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
150 Len = MI->getLength();
152 IntrinsicInst *II = cast<IntrinsicInst>(I);
153 switch (II->getIntrinsicID()) {
154 default: assert(false && "Unexpected intrinsic!");
155 case Intrinsic::init_trampoline:
157 case Intrinsic::lifetime_end:
158 Len = II->getArgOperand(0);
162 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len))
163 if (!LenCI->isAllOnesValue())
164 return LenCI->getZExtValue();
168 /// isStoreAtLeastAsWideAs - Return true if the size of the store in I1 is
169 /// greater than or equal to the store in I2. This returns false if we don't
172 static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2,
173 const TargetData *TD) {
174 const Type *I1Ty = getPointerOperand(I1)->getType();
175 const Type *I2Ty = getPointerOperand(I2)->getType();
177 // Exactly the same type, must have exactly the same size.
178 if (I1Ty == I2Ty) return true;
180 int I1Size = getStoreSize(I1, TD);
181 int I2Size = getStoreSize(I2, TD);
183 return I1Size != -1 && I2Size != -1 && I1Size >= I2Size;
186 bool DSE::runOnBasicBlock(BasicBlock &BB) {
187 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
188 TD = getAnalysisIfAvailable<TargetData>();
190 bool MadeChange = false;
192 // Do a top-down walk on the BB.
193 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
194 Instruction *Inst = BBI++;
196 // If we find a store or a free, get its memory dependence.
197 if (!doesClobberMemory(Inst) && !isFreeCall(Inst))
200 MemDepResult InstDep = MD.getDependency(Inst);
202 // Ignore non-local stores.
203 // FIXME: cross-block DSE would be fun. :)
204 if (InstDep.isNonLocal()) continue;
206 // Handle frees whose dependencies are non-trivial.
207 if (const CallInst *F = isFreeCall(Inst)) {
208 MadeChange |= handleFreeWithNonTrivialDependency(F, InstDep);
212 // If not a definite must-alias dependency, ignore it.
213 if (!InstDep.isDef())
216 // If this is a store-store dependence, then the previous store is dead so
217 // long as this store is at least as big as it.
218 if (doesClobberMemory(InstDep.getInst())) {
219 Instruction *DepStore = InstDep.getInst();
220 if (isStoreAtLeastAsWideAs(Inst, DepStore, TD) &&
221 isElidable(DepStore)) {
222 // Delete the store and now-dead instructions that feed it.
223 DeleteDeadInstruction(DepStore);
227 // DeleteDeadInstruction can delete the current instruction in loop
230 if (BBI != BB.begin())
236 if (!isElidable(Inst))
239 // If we're storing the same value back to a pointer that we just
240 // loaded from, then the store can be removed.
241 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
242 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
243 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
244 SI->getOperand(0) == DepLoad) {
245 // DeleteDeadInstruction can delete the current instruction. Save BBI
246 // in case we need it.
247 WeakVH NextInst(BBI);
249 DeleteDeadInstruction(SI);
251 if (NextInst == 0) // Next instruction deleted.
253 else if (BBI != BB.begin()) // Revisit this instruction if possible.
262 // If this is a lifetime end marker, we can throw away the store.
263 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(InstDep.getInst())) {
264 if (II->getIntrinsicID() == Intrinsic::lifetime_end) {
265 // Delete the store and now-dead instructions that feed it.
266 // DeleteDeadInstruction can delete the current instruction. Save BBI
267 // in case we need it.
268 WeakVH NextInst(BBI);
270 DeleteDeadInstruction(Inst);
272 if (NextInst == 0) // Next instruction deleted.
274 else if (BBI != BB.begin()) // Revisit this instruction if possible.
283 // If this block ends in a return, unwind, or unreachable, all allocas are
284 // dead at its end, which means stores to them are also dead.
285 if (BB.getTerminator()->getNumSuccessors() == 0)
286 MadeChange |= handleEndBlock(BB);
291 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
292 /// dependency is a store to a field of that structure.
293 bool DSE::handleFreeWithNonTrivialDependency(const CallInst *F,
295 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
297 Instruction *Dependency = Dep.getInst();
298 if (!Dependency || !doesClobberMemory(Dependency) || !isElidable(Dependency))
301 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
303 // Check for aliasing.
304 if (AA.alias(F->getArgOperand(0), 1, DepPointer, 1) !=
305 AliasAnalysis::MustAlias)
308 // DCE instructions only used to calculate that store
309 DeleteDeadInstruction(Dependency);
314 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
315 /// function end block. Ex:
318 /// store i32 1, i32* %A
320 bool DSE::handleEndBlock(BasicBlock &BB) {
321 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
323 bool MadeChange = false;
325 // Pointers alloca'd in this function are dead in the end block
326 SmallPtrSet<Value*, 64> deadPointers;
328 // Find all of the alloca'd pointers in the entry block.
329 BasicBlock *Entry = BB.getParent()->begin();
330 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
331 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
332 deadPointers.insert(AI);
334 // Treat byval arguments the same, stores to them are dead at the end of the
336 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
337 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
338 if (AI->hasByValAttr())
339 deadPointers.insert(AI);
341 // Scan the basic block backwards
342 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
345 // If we find a store whose pointer is dead.
346 if (doesClobberMemory(BBI)) {
347 if (isElidable(BBI)) {
348 // See through pointer-to-pointer bitcasts
349 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
351 // Alloca'd pointers or byval arguments (which are functionally like
352 // alloca's) are valid candidates for removal.
353 if (deadPointers.count(pointerOperand)) {
354 // DCE instructions only used to calculate that store.
355 Instruction *Dead = BBI;
357 DeleteDeadInstruction(Dead, &deadPointers);
364 // Because a memcpy or memmove is also a load, we can't skip it if we
366 if (!isa<MemTransferInst>(BBI))
370 Value *killPointer = 0;
371 uint64_t killPointerSize = ~0UL;
373 // If we encounter a use of the pointer, it is no longer considered dead
374 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
375 // However, if this load is unused and not volatile, we can go ahead and
376 // remove it, and not have to worry about it making our pointer undead!
377 if (L->use_empty() && !L->isVolatile()) {
379 DeleteDeadInstruction(L, &deadPointers);
385 killPointer = L->getPointerOperand();
386 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
387 killPointer = V->getOperand(0);
388 } else if (isa<MemTransferInst>(BBI) &&
389 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
390 killPointer = cast<MemTransferInst>(BBI)->getSource();
391 killPointerSize = cast<ConstantInt>(
392 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
393 } else if (AllocaInst *A = dyn_cast<AllocaInst>(BBI)) {
394 deadPointers.erase(A);
396 // Dead alloca's can be DCE'd when we reach them
397 if (A->use_empty()) {
399 DeleteDeadInstruction(A, &deadPointers);
405 } else if (CallSite::get(BBI).getInstruction() != 0) {
406 // If this call does not access memory, it can't
407 // be undeadifying any of our pointers.
408 CallSite CS = CallSite::get(BBI);
409 if (AA.doesNotAccessMemory(CS))
415 // Remove any pointers made undead by the call from the dead set
416 std::vector<Value*> dead;
417 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
418 E = deadPointers.end(); I != E; ++I) {
419 // HACK: if we detect that our AA is imprecise, it's not
420 // worth it to scan the rest of the deadPointers set. Just
421 // assume that the AA will return ModRef for everything, and
422 // go ahead and bail.
423 if (modRef >= 16 && other == 0) {
424 deadPointers.clear();
428 // See if the call site touches it
429 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I,
432 if (A == AliasAnalysis::ModRef)
437 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
441 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
443 deadPointers.erase(*I);
446 } else if (isInstructionTriviallyDead(BBI)) {
447 // For any non-memory-affecting non-terminators, DCE them as we reach them
448 Instruction *Inst = BBI;
450 DeleteDeadInstruction(Inst, &deadPointers);
459 killPointer = killPointer->getUnderlyingObject();
461 // Deal with undead pointers
462 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
469 /// RemoveUndeadPointers - check for uses of a pointer that make it
470 /// undead when scanning for dead stores to alloca's.
471 bool DSE::RemoveUndeadPointers(Value *killPointer, uint64_t killPointerSize,
472 BasicBlock::iterator &BBI,
473 SmallPtrSet<Value*, 64> &deadPointers) {
474 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
476 // If the kill pointer can be easily reduced to an alloca,
477 // don't bother doing extraneous AA queries.
478 if (deadPointers.count(killPointer)) {
479 deadPointers.erase(killPointer);
483 // A global can't be in the dead pointer set.
484 if (isa<GlobalValue>(killPointer))
487 bool MadeChange = false;
489 SmallVector<Value*, 16> undead;
491 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
492 E = deadPointers.end(); I != E; ++I) {
493 // See if this pointer could alias it
494 AliasAnalysis::AliasResult A = AA.alias(*I, getPointerSize(*I),
495 killPointer, killPointerSize);
497 // If it must-alias and a store, we can delete it
498 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
499 StoreInst *S = cast<StoreInst>(BBI);
503 DeleteDeadInstruction(S, &deadPointers);
509 // Otherwise, it is undead
510 } else if (A != AliasAnalysis::NoAlias)
511 undead.push_back(*I);
514 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
516 deadPointers.erase(*I);
521 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
522 /// and zero out all the operands of this instruction. If any of them become
523 /// dead, delete them and the computation tree that feeds them.
525 /// If ValueSet is non-null, remove any deleted instructions from it as well.
527 void DSE::DeleteDeadInstruction(Instruction *I,
528 SmallPtrSet<Value*, 64> *ValueSet) {
529 SmallVector<Instruction*, 32> NowDeadInsts;
531 NowDeadInsts.push_back(I);
534 // Before we touch this instruction, remove it from memdep!
535 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
537 Instruction *DeadInst = NowDeadInsts.pop_back_val();
541 // This instruction is dead, zap it, in stages. Start by removing it from
542 // MemDep, which needs to know the operands and needs it to be in the
544 MDA.removeInstruction(DeadInst);
546 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
547 Value *Op = DeadInst->getOperand(op);
548 DeadInst->setOperand(op, 0);
550 // If this operand just became dead, add it to the NowDeadInsts list.
551 if (!Op->use_empty()) continue;
553 if (Instruction *OpI = dyn_cast<Instruction>(Op))
554 if (isInstructionTriviallyDead(OpI))
555 NowDeadInsts.push_back(OpI);
558 DeadInst->eraseFromParent();
560 if (ValueSet) ValueSet->erase(DeadInst);
561 } while (!NowDeadInsts.empty());
564 unsigned DSE::getPointerSize(Value *V) const {
566 if (AllocaInst *A = dyn_cast<AllocaInst>(V)) {
567 // Get size information for the alloca
568 if (ConstantInt *C = dyn_cast<ConstantInt>(A->getArraySize()))
569 return C->getZExtValue() * TD->getTypeAllocSize(A->getAllocatedType());
571 assert(isa<Argument>(V) && "Expected AllocaInst or Argument!");
572 const PointerType *PT = cast<PointerType>(V->getType());
573 return TD->getTypeAllocSize(PT->getElementType());