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) {
44 initializeDSEPass(*PassRegistry::getPassRegistry());
47 virtual bool runOnFunction(Function &F) {
50 DominatorTree &DT = getAnalysis<DominatorTree>();
52 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
53 // Only check non-dead blocks. Dead blocks may have strange pointer
54 // cycles that will confuse alias analysis.
55 if (DT.isReachableFromEntry(I))
56 Changed |= runOnBasicBlock(*I);
60 bool runOnBasicBlock(BasicBlock &BB);
61 bool HandleFree(CallInst *F);
62 bool handleEndBlock(BasicBlock &BB);
63 bool RemoveUndeadPointers(Value *Ptr, uint64_t killPointerSize,
64 BasicBlock::iterator &BBI,
65 SmallPtrSet<Value*, 64> &deadPointers);
66 void DeleteDeadInstruction(Instruction *I,
67 SmallPtrSet<Value*, 64> *deadPointers = 0);
70 // getAnalysisUsage - We require post dominance frontiers (aka Control
72 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
74 AU.addRequired<DominatorTree>();
75 AU.addRequired<AliasAnalysis>();
76 AU.addRequired<MemoryDependenceAnalysis>();
77 AU.addPreserved<DominatorTree>();
78 AU.addPreserved<MemoryDependenceAnalysis>();
81 uint64_t getPointerSize(Value *V) const;
86 INITIALIZE_PASS_BEGIN(DSE, "dse", "Dead Store Elimination", false, false)
87 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
88 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
89 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
90 INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false)
92 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
94 /// hasMemoryWrite - Does this instruction write some memory? This only returns
95 /// true for things that we can analyze with other helpers below.
96 static bool hasMemoryWrite(Instruction *I) {
97 if (isa<StoreInst>(I))
99 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
100 switch (II->getIntrinsicID()) {
103 case Intrinsic::memset:
104 case Intrinsic::memmove:
105 case Intrinsic::memcpy:
106 case Intrinsic::init_trampoline:
107 case Intrinsic::lifetime_end:
114 /// isRemovable - If the value of this instruction and the memory it writes to
115 /// is unused, may we delete this instruction?
116 static bool isRemovable(Instruction *I) {
117 assert(hasMemoryWrite(I));
118 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
119 return II->getIntrinsicID() != Intrinsic::lifetime_end;
120 if (StoreInst *SI = dyn_cast<StoreInst>(I))
121 return !SI->isVolatile();
125 /// getPointerOperand - Return the pointer that is being written to.
126 static Value *getPointerOperand(Instruction *I) {
127 assert(hasMemoryWrite(I));
128 if (StoreInst *SI = dyn_cast<StoreInst>(I))
129 return SI->getPointerOperand();
130 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
131 return MI->getArgOperand(0);
133 IntrinsicInst *II = cast<IntrinsicInst>(I);
134 switch (II->getIntrinsicID()) {
135 default: assert(false && "Unexpected intrinsic!");
136 case Intrinsic::init_trampoline:
137 return II->getArgOperand(0);
138 case Intrinsic::lifetime_end:
139 return II->getArgOperand(1);
143 /// getStoreSize - Return the length in bytes of the write by the clobbering
144 /// instruction. If variable or unknown, returns AliasAnalysis::UnknownSize.
145 static uint64_t getStoreSize(Instruction *I, const TargetData *TD) {
146 assert(hasMemoryWrite(I));
147 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
148 if (!TD) return AliasAnalysis::UnknownSize;
149 return TD->getTypeStoreSize(SI->getOperand(0)->getType());
153 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
154 Len = MI->getLength();
156 IntrinsicInst *II = cast<IntrinsicInst>(I);
157 switch (II->getIntrinsicID()) {
158 default: assert(false && "Unexpected intrinsic!");
159 case Intrinsic::init_trampoline:
160 return AliasAnalysis::UnknownSize;
161 case Intrinsic::lifetime_end:
162 Len = II->getArgOperand(0);
166 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len))
167 if (!LenCI->isAllOnesValue())
168 return LenCI->getZExtValue();
169 return AliasAnalysis::UnknownSize;
172 /// isStoreAtLeastAsWideAs - Return true if the size of the store in I1 is
173 /// greater than or equal to the store in I2. This returns false if we don't
176 static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2,
177 const TargetData *TD) {
178 const Type *I1Ty = getPointerOperand(I1)->getType();
179 const Type *I2Ty = getPointerOperand(I2)->getType();
181 // Exactly the same type, must have exactly the same size.
182 if (I1Ty == I2Ty) return true;
184 uint64_t I1Size = getStoreSize(I1, TD);
185 uint64_t I2Size = getStoreSize(I2, TD);
187 return I1Size != AliasAnalysis::UnknownSize &&
188 I2Size != AliasAnalysis::UnknownSize &&
193 bool DSE::runOnBasicBlock(BasicBlock &BB) {
194 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
195 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
196 TD = getAnalysisIfAvailable<TargetData>();
198 bool MadeChange = false;
200 // Do a top-down walk on the BB.
201 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
202 Instruction *Inst = BBI++;
204 // Handle 'free' calls specially.
205 if (CallInst *F = isFreeCall(Inst)) {
206 MadeChange |= HandleFree(F);
210 // If we find something that writes memory, get its memory dependence.
211 if (!hasMemoryWrite(Inst))
214 MemDepResult InstDep = MD.getDependency(Inst);
216 // Ignore non-local store liveness.
217 // FIXME: cross-block DSE would be fun. :)
218 if (InstDep.isNonLocal()) continue;
220 // If we're storing the same value back to a pointer that we just
221 // loaded from, then the store can be removed.
222 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
223 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
224 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
225 SI->getOperand(0) == DepLoad && !SI->isVolatile()) {
226 // DeleteDeadInstruction can delete the current instruction. Save BBI
227 // in case we need it.
228 WeakVH NextInst(BBI);
230 DeleteDeadInstruction(SI);
232 if (NextInst == 0) // Next instruction deleted.
234 else if (BBI != BB.begin()) // Revisit this instruction if possible.
243 if (!InstDep.isDef()) {
244 // If this is a may-aliased store that is clobbering the store value, we
245 // can keep searching past it for another must-aliased pointer that stores
246 // to the same location. For example, in:
250 // we can remove the first store to P even though we don't know if P and Q
252 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
253 AliasAnalysis::Location Loc = AA.getLocation(SI);
254 while (InstDep.isClobber() && InstDep.getInst() != &BB.front()) {
255 // Can't look past this instruction if it might read 'Loc'.
256 if (AA.getModRefInfo(InstDep.getInst(), Loc) & AliasAnalysis::Ref)
259 InstDep = MD.getPointerDependencyFrom(Loc, false,
260 InstDep.getInst(), &BB);
265 // If this is a store-store dependence, then the previous store is dead so
266 // long as this store is at least as big as it.
267 if (InstDep.isDef() && hasMemoryWrite(InstDep.getInst())) {
268 Instruction *DepStore = InstDep.getInst();
269 if (!isRemovable(DepStore) ||
270 !isStoreAtLeastAsWideAs(Inst, DepStore, TD))
273 // Delete the store and now-dead instructions that feed it.
274 DeleteDeadInstruction(DepStore);
278 // DeleteDeadInstruction can delete the current instruction in loop
281 if (BBI != BB.begin())
287 // If this block ends in a return, unwind, or unreachable, all allocas are
288 // dead at its end, which means stores to them are also dead.
289 if (BB.getTerminator()->getNumSuccessors() == 0)
290 MadeChange |= handleEndBlock(BB);
295 /// HandleFree - Handle frees of entire structures whose dependency is a store
296 /// to a field of that structure.
297 bool DSE::HandleFree(CallInst *F) {
298 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
299 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
301 MemDepResult Dep = MD.getDependency(F);
303 if (Dep.isNonLocal()) return false;
305 Instruction *Dependency = Dep.getInst();
306 if (!hasMemoryWrite(Dependency) || !isRemovable(Dependency))
309 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
311 // Check for aliasing.
312 if (AA.alias(F->getArgOperand(0), 1, DepPointer, 1) !=
313 AliasAnalysis::MustAlias)
316 // DCE instructions only used to calculate that store
317 DeleteDeadInstruction(Dependency);
320 // Inst's old Dependency is now deleted. Compute the next dependency,
321 // which may also be dead, as in
323 // s[1] = 0; // This has just been deleted.
325 Dep = MD.getDependency(F);
326 } while (!Dep.isNonLocal());
331 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
332 /// function end block. Ex:
335 /// store i32 1, i32* %A
337 bool DSE::handleEndBlock(BasicBlock &BB) {
338 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
340 bool MadeChange = false;
342 // Pointers alloca'd in this function are dead in the end block
343 SmallPtrSet<Value*, 64> deadPointers;
345 // Find all of the alloca'd pointers in the entry block.
346 BasicBlock *Entry = BB.getParent()->begin();
347 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
348 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
349 deadPointers.insert(AI);
351 // Treat byval arguments the same, stores to them are dead at the end of the
353 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
354 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
355 if (AI->hasByValAttr())
356 deadPointers.insert(AI);
358 // Scan the basic block backwards
359 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
362 // If we find a store whose pointer is dead.
363 if (hasMemoryWrite(BBI)) {
364 if (isRemovable(BBI)) {
365 // See through pointer-to-pointer bitcasts
366 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
368 // Alloca'd pointers or byval arguments (which are functionally like
369 // alloca's) are valid candidates for removal.
370 if (deadPointers.count(pointerOperand)) {
371 // DCE instructions only used to calculate that store.
372 Instruction *Dead = BBI;
374 DeleteDeadInstruction(Dead, &deadPointers);
381 // Because a memcpy or memmove is also a load, we can't skip it if we
383 if (!isa<MemTransferInst>(BBI))
387 Value *killPointer = 0;
388 uint64_t killPointerSize = AliasAnalysis::UnknownSize;
390 // If we encounter a use of the pointer, it is no longer considered dead
391 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
392 // However, if this load is unused and not volatile, we can go ahead and
393 // remove it, and not have to worry about it making our pointer undead!
394 if (L->use_empty() && !L->isVolatile()) {
396 DeleteDeadInstruction(L, &deadPointers);
402 killPointer = L->getPointerOperand();
403 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
404 killPointer = V->getOperand(0);
405 } else if (isa<MemTransferInst>(BBI) &&
406 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
407 killPointer = cast<MemTransferInst>(BBI)->getSource();
408 killPointerSize = cast<ConstantInt>(
409 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
410 } else if (AllocaInst *A = dyn_cast<AllocaInst>(BBI)) {
411 deadPointers.erase(A);
413 // Dead alloca's can be DCE'd when we reach them
414 if (A->use_empty()) {
416 DeleteDeadInstruction(A, &deadPointers);
422 } else if (CallSite CS = cast<Value>(BBI)) {
423 // If this call does not access memory, it can't
424 // be undeadifying any of our pointers.
425 if (AA.doesNotAccessMemory(CS))
431 // Remove any pointers made undead by the call from the dead set
432 std::vector<Value*> dead;
433 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
434 E = deadPointers.end(); I != E; ++I) {
435 // HACK: if we detect that our AA is imprecise, it's not
436 // worth it to scan the rest of the deadPointers set. Just
437 // assume that the AA will return ModRef for everything, and
438 // go ahead and bail.
439 if (modRef >= 16 && other == 0) {
440 deadPointers.clear();
444 // See if the call site touches it
445 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I,
448 if (A == AliasAnalysis::ModRef)
453 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
457 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
459 deadPointers.erase(*I);
462 } else if (isInstructionTriviallyDead(BBI)) {
463 // For any non-memory-affecting non-terminators, DCE them as we reach them
464 Instruction *Inst = BBI;
466 DeleteDeadInstruction(Inst, &deadPointers);
475 killPointer = killPointer->getUnderlyingObject();
477 // Deal with undead pointers
478 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
485 /// RemoveUndeadPointers - check for uses of a pointer that make it
486 /// undead when scanning for dead stores to alloca's.
487 bool DSE::RemoveUndeadPointers(Value *killPointer, uint64_t killPointerSize,
488 BasicBlock::iterator &BBI,
489 SmallPtrSet<Value*, 64> &deadPointers) {
490 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
492 // If the kill pointer can be easily reduced to an alloca,
493 // don't bother doing extraneous AA queries.
494 if (deadPointers.count(killPointer)) {
495 deadPointers.erase(killPointer);
499 // A global can't be in the dead pointer set.
500 if (isa<GlobalValue>(killPointer))
503 bool MadeChange = false;
505 SmallVector<Value*, 16> undead;
507 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
508 E = deadPointers.end(); I != E; ++I) {
509 // See if this pointer could alias it
510 AliasAnalysis::AliasResult A = AA.alias(*I, getPointerSize(*I),
511 killPointer, killPointerSize);
513 // If it must-alias and a store, we can delete it
514 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
515 StoreInst *S = cast<StoreInst>(BBI);
519 DeleteDeadInstruction(S, &deadPointers);
525 // Otherwise, it is undead
526 } else if (A != AliasAnalysis::NoAlias)
527 undead.push_back(*I);
530 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
532 deadPointers.erase(*I);
537 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
538 /// and zero out all the operands of this instruction. If any of them become
539 /// dead, delete them and the computation tree that feeds them.
541 /// If ValueSet is non-null, remove any deleted instructions from it as well.
543 void DSE::DeleteDeadInstruction(Instruction *I,
544 SmallPtrSet<Value*, 64> *ValueSet) {
545 SmallVector<Instruction*, 32> NowDeadInsts;
547 NowDeadInsts.push_back(I);
550 // Before we touch this instruction, remove it from memdep!
551 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
553 Instruction *DeadInst = NowDeadInsts.pop_back_val();
557 // This instruction is dead, zap it, in stages. Start by removing it from
558 // MemDep, which needs to know the operands and needs it to be in the
560 MDA.removeInstruction(DeadInst);
562 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
563 Value *Op = DeadInst->getOperand(op);
564 DeadInst->setOperand(op, 0);
566 // If this operand just became dead, add it to the NowDeadInsts list.
567 if (!Op->use_empty()) continue;
569 if (Instruction *OpI = dyn_cast<Instruction>(Op))
570 if (isInstructionTriviallyDead(OpI))
571 NowDeadInsts.push_back(OpI);
574 DeadInst->eraseFromParent();
576 if (ValueSet) ValueSet->erase(DeadInst);
577 } while (!NowDeadInsts.empty());
580 uint64_t DSE::getPointerSize(Value *V) const {
582 if (AllocaInst *A = dyn_cast<AllocaInst>(V)) {
583 // Get size information for the alloca
584 if (ConstantInt *C = dyn_cast<ConstantInt>(A->getArraySize()))
585 return C->getZExtValue() * TD->getTypeAllocSize(A->getAllocatedType());
587 assert(isa<Argument>(V) && "Expected AllocaInst or Argument!");
588 const PointerType *PT = cast<PointerType>(V->getType());
589 return TD->getTypeAllocSize(PT->getElementType());
592 return AliasAnalysis::UnknownSize;