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) {
47 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
48 Changed |= runOnBasicBlock(*I);
52 bool runOnBasicBlock(BasicBlock &BB);
53 bool handleFreeWithNonTrivialDependency(Instruction *F, MemDepResult Dep);
54 bool handleEndBlock(BasicBlock &BB);
55 bool RemoveUndeadPointers(Value *Ptr, uint64_t killPointerSize,
56 BasicBlock::iterator &BBI,
57 SmallPtrSet<Value*, 64> &deadPointers);
58 void DeleteDeadInstruction(Instruction *I,
59 SmallPtrSet<Value*, 64> *deadPointers = 0);
62 // getAnalysisUsage - We require post dominance frontiers (aka Control
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66 AU.addRequired<DominatorTree>();
67 AU.addRequired<AliasAnalysis>();
68 AU.addRequired<MemoryDependenceAnalysis>();
69 AU.addPreserved<DominatorTree>();
70 AU.addPreserved<AliasAnalysis>();
71 AU.addPreserved<MemoryDependenceAnalysis>();
74 unsigned getPointerSize(Value *V) const;
79 static RegisterPass<DSE> X("dse", "Dead Store Elimination");
81 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
83 /// doesClobberMemory - Does this instruction clobber (write without reading)
85 static bool doesClobberMemory(Instruction *I) {
86 if (isa<StoreInst>(I))
88 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
89 switch (II->getIntrinsicID()) {
92 case Intrinsic::memset:
93 case Intrinsic::memmove:
94 case Intrinsic::memcpy:
95 case Intrinsic::init_trampoline:
96 case Intrinsic::lifetime_end:
103 /// isElidable - If the value of this instruction and the memory it writes to is
104 /// unused, may we delete this instrtction?
105 static bool isElidable(Instruction *I) {
106 assert(doesClobberMemory(I));
107 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
108 return II->getIntrinsicID() != Intrinsic::lifetime_end;
109 if (StoreInst *SI = dyn_cast<StoreInst>(I))
110 return !SI->isVolatile();
114 /// getPointerOperand - Return the pointer that is being clobbered.
115 static Value *getPointerOperand(Instruction *I) {
116 assert(doesClobberMemory(I));
117 if (StoreInst *SI = dyn_cast<StoreInst>(I))
118 return SI->getPointerOperand();
119 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
120 return MI->getOperand(1);
122 switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
123 default: assert(false && "Unexpected intrinsic!");
124 case Intrinsic::init_trampoline:
125 return I->getOperand(1);
126 case Intrinsic::lifetime_end:
127 return I->getOperand(2);
131 /// getStoreSize - Return the length in bytes of the write by the clobbering
132 /// instruction. If variable or unknown, returns -1.
133 static unsigned getStoreSize(Instruction *I, const TargetData *TD) {
134 assert(doesClobberMemory(I));
135 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
137 return TD->getTypeStoreSize(SI->getOperand(0)->getType());
141 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
142 Len = MI->getLength();
144 switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
145 default: assert(false && "Unexpected intrinsic!");
146 case Intrinsic::init_trampoline:
148 case Intrinsic::lifetime_end:
149 Len = I->getOperand(1);
153 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len))
154 if (!LenCI->isAllOnesValue())
155 return LenCI->getZExtValue();
159 /// isStoreAtLeastAsWideAs - Return true if the size of the store in I1 is
160 /// greater than or equal to the store in I2. This returns false if we don't
163 static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2,
164 const TargetData *TD) {
165 const Type *I1Ty = getPointerOperand(I1)->getType();
166 const Type *I2Ty = getPointerOperand(I2)->getType();
168 // Exactly the same type, must have exactly the same size.
169 if (I1Ty == I2Ty) return true;
171 int I1Size = getStoreSize(I1, TD);
172 int I2Size = getStoreSize(I2, TD);
174 return I1Size != -1 && I2Size != -1 && I1Size >= I2Size;
177 bool DSE::runOnBasicBlock(BasicBlock &BB) {
178 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
179 TD = getAnalysisIfAvailable<TargetData>();
181 bool MadeChange = false;
183 // Do a top-down walk on the BB.
184 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
185 Instruction *Inst = BBI++;
187 // If we find a store or a free, get its memory dependence.
188 if (!doesClobberMemory(Inst) && !isFreeCall(Inst))
191 MemDepResult InstDep = MD.getDependency(Inst);
193 // Ignore non-local stores.
194 // FIXME: cross-block DSE would be fun. :)
195 if (InstDep.isNonLocal()) continue;
197 // Handle frees whose dependencies are non-trivial.
198 if (isFreeCall(Inst)) {
199 MadeChange |= handleFreeWithNonTrivialDependency(Inst, InstDep);
203 // If not a definite must-alias dependency, ignore it.
204 if (!InstDep.isDef())
207 // If this is a store-store dependence, then the previous store is dead so
208 // long as this store is at least as big as it.
209 if (doesClobberMemory(InstDep.getInst())) {
210 Instruction *DepStore = InstDep.getInst();
211 if (isStoreAtLeastAsWideAs(Inst, DepStore, TD) &&
212 isElidable(DepStore)) {
213 // Delete the store and now-dead instructions that feed it.
214 DeleteDeadInstruction(DepStore);
218 // DeleteDeadInstruction can delete the current instruction in loop
221 if (BBI != BB.begin())
227 if (!isElidable(Inst))
230 // If we're storing the same value back to a pointer that we just
231 // loaded from, then the store can be removed.
232 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
233 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
234 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
235 SI->getOperand(0) == DepLoad) {
236 // DeleteDeadInstruction can delete the current instruction. Save BBI
237 // in case we need it.
238 WeakVH NextInst(BBI);
240 DeleteDeadInstruction(SI);
242 if (NextInst == 0) // Next instruction deleted.
244 else if (BBI != BB.begin()) // Revisit this instruction if possible.
253 // If this is a lifetime end marker, we can throw away the store.
254 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(InstDep.getInst())) {
255 if (II->getIntrinsicID() == Intrinsic::lifetime_end) {
256 // Delete the store and now-dead instructions that feed it.
257 // DeleteDeadInstruction can delete the current instruction. Save BBI
258 // in case we need it.
259 WeakVH NextInst(BBI);
261 DeleteDeadInstruction(Inst);
263 if (NextInst == 0) // Next instruction deleted.
265 else if (BBI != BB.begin()) // Revisit this instruction if possible.
274 // If this block ends in a return, unwind, or unreachable, all allocas are
275 // dead at its end, which means stores to them are also dead.
276 if (BB.getTerminator()->getNumSuccessors() == 0)
277 MadeChange |= handleEndBlock(BB);
282 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
283 /// dependency is a store to a field of that structure.
284 bool DSE::handleFreeWithNonTrivialDependency(Instruction *F, MemDepResult Dep) {
285 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
287 Instruction *Dependency = Dep.getInst();
288 if (!Dependency || !doesClobberMemory(Dependency) || !isElidable(Dependency))
291 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
293 // Check for aliasing.
294 if (AA.alias(F->getOperand(1), 1, DepPointer, 1) !=
295 AliasAnalysis::MustAlias)
298 // DCE instructions only used to calculate that store
299 DeleteDeadInstruction(Dependency);
304 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
305 /// function end block. Ex:
308 /// store i32 1, i32* %A
310 bool DSE::handleEndBlock(BasicBlock &BB) {
311 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
313 bool MadeChange = false;
315 // Pointers alloca'd in this function are dead in the end block
316 SmallPtrSet<Value*, 64> deadPointers;
318 // Find all of the alloca'd pointers in the entry block.
319 BasicBlock *Entry = BB.getParent()->begin();
320 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
321 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
322 deadPointers.insert(AI);
324 // Treat byval arguments the same, stores to them are dead at the end of the
326 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
327 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
328 if (AI->hasByValAttr())
329 deadPointers.insert(AI);
331 // Scan the basic block backwards
332 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
335 // If we find a store whose pointer is dead.
336 if (doesClobberMemory(BBI)) {
337 if (isElidable(BBI)) {
338 // See through pointer-to-pointer bitcasts
339 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
341 // Alloca'd pointers or byval arguments (which are functionally like
342 // alloca's) are valid candidates for removal.
343 if (deadPointers.count(pointerOperand)) {
344 // DCE instructions only used to calculate that store.
345 Instruction *Dead = BBI;
347 DeleteDeadInstruction(Dead, &deadPointers);
354 // Because a memcpy or memmove is also a load, we can't skip it if we
356 if (!isa<MemTransferInst>(BBI))
360 Value *killPointer = 0;
361 uint64_t killPointerSize = ~0UL;
363 // If we encounter a use of the pointer, it is no longer considered dead
364 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
365 // However, if this load is unused and not volatile, we can go ahead and
366 // remove it, and not have to worry about it making our pointer undead!
367 if (L->use_empty() && !L->isVolatile()) {
369 DeleteDeadInstruction(L, &deadPointers);
375 killPointer = L->getPointerOperand();
376 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
377 killPointer = V->getOperand(0);
378 } else if (isa<MemTransferInst>(BBI) &&
379 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
380 killPointer = cast<MemTransferInst>(BBI)->getSource();
381 killPointerSize = cast<ConstantInt>(
382 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
383 } else if (AllocaInst *A = dyn_cast<AllocaInst>(BBI)) {
384 deadPointers.erase(A);
386 // Dead alloca's can be DCE'd when we reach them
387 if (A->use_empty()) {
389 DeleteDeadInstruction(A, &deadPointers);
395 } else if (CallSite::get(BBI).getInstruction() != 0) {
396 // If this call does not access memory, it can't
397 // be undeadifying any of our pointers.
398 CallSite CS = CallSite::get(BBI);
399 if (AA.doesNotAccessMemory(CS))
405 // Remove any pointers made undead by the call from the dead set
406 std::vector<Value*> dead;
407 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
408 E = deadPointers.end(); I != E; ++I) {
409 // HACK: if we detect that our AA is imprecise, it's not
410 // worth it to scan the rest of the deadPointers set. Just
411 // assume that the AA will return ModRef for everything, and
412 // go ahead and bail.
413 if (modRef >= 16 && other == 0) {
414 deadPointers.clear();
418 // See if the call site touches it
419 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I,
422 if (A == AliasAnalysis::ModRef)
427 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
431 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
433 deadPointers.erase(*I);
436 } else if (isInstructionTriviallyDead(BBI)) {
437 // For any non-memory-affecting non-terminators, DCE them as we reach them
438 Instruction *Inst = BBI;
440 DeleteDeadInstruction(Inst, &deadPointers);
449 killPointer = killPointer->getUnderlyingObject();
451 // Deal with undead pointers
452 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
459 /// RemoveUndeadPointers - check for uses of a pointer that make it
460 /// undead when scanning for dead stores to alloca's.
461 bool DSE::RemoveUndeadPointers(Value *killPointer, uint64_t killPointerSize,
462 BasicBlock::iterator &BBI,
463 SmallPtrSet<Value*, 64> &deadPointers) {
464 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
466 // If the kill pointer can be easily reduced to an alloca,
467 // don't bother doing extraneous AA queries.
468 if (deadPointers.count(killPointer)) {
469 deadPointers.erase(killPointer);
473 // A global can't be in the dead pointer set.
474 if (isa<GlobalValue>(killPointer))
477 bool MadeChange = false;
479 SmallVector<Value*, 16> undead;
481 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
482 E = deadPointers.end(); I != E; ++I) {
483 // See if this pointer could alias it
484 AliasAnalysis::AliasResult A = AA.alias(*I, getPointerSize(*I),
485 killPointer, killPointerSize);
487 // If it must-alias and a store, we can delete it
488 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
489 StoreInst *S = cast<StoreInst>(BBI);
493 DeleteDeadInstruction(S, &deadPointers);
499 // Otherwise, it is undead
500 } else if (A != AliasAnalysis::NoAlias)
501 undead.push_back(*I);
504 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
506 deadPointers.erase(*I);
511 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
512 /// and zero out all the operands of this instruction. If any of them become
513 /// dead, delete them and the computation tree that feeds them.
515 /// If ValueSet is non-null, remove any deleted instructions from it as well.
517 void DSE::DeleteDeadInstruction(Instruction *I,
518 SmallPtrSet<Value*, 64> *ValueSet) {
519 SmallVector<Instruction*, 32> NowDeadInsts;
521 NowDeadInsts.push_back(I);
524 // Before we touch this instruction, remove it from memdep!
525 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
527 Instruction *DeadInst = NowDeadInsts.pop_back_val();
531 // This instruction is dead, zap it, in stages. Start by removing it from
532 // MemDep, which needs to know the operands and needs it to be in the
534 MDA.removeInstruction(DeadInst);
536 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
537 Value *Op = DeadInst->getOperand(op);
538 DeadInst->setOperand(op, 0);
540 // If this operand just became dead, add it to the NowDeadInsts list.
541 if (!Op->use_empty()) continue;
543 if (Instruction *OpI = dyn_cast<Instruction>(Op))
544 if (isInstructionTriviallyDead(OpI))
545 NowDeadInsts.push_back(OpI);
548 DeadInst->eraseFromParent();
550 if (ValueSet) ValueSet->erase(DeadInst);
551 } while (!NowDeadInsts.empty());
554 unsigned DSE::getPointerSize(Value *V) const {
556 if (AllocaInst *A = dyn_cast<AllocaInst>(V)) {
557 // Get size information for the alloca
558 if (ConstantInt *C = dyn_cast<ConstantInt>(A->getArraySize()))
559 return C->getZExtValue() * TD->getTypeAllocSize(A->getAllocatedType());
561 assert(isa<Argument>(V) && "Expected AllocaInst or Argument!");
562 const PointerType *PT = cast<PointerType>(V->getType());
563 return TD->getTypeAllocSize(PT->getElementType());