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>();
77 static RegisterPass<DSE> X("dse", "Dead Store Elimination");
79 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
81 /// doesClobberMemory - Does this instruction clobber (write without reading)
83 static bool doesClobberMemory(Instruction *I) {
84 if (isa<StoreInst>(I))
86 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
87 switch (II->getIntrinsicID()) {
88 default: return false;
89 case Intrinsic::memset: case Intrinsic::memmove: case Intrinsic::memcpy:
90 case Intrinsic::init_trampoline: case Intrinsic::lifetime_end: return true;
96 /// isElidable - If the value of this instruction and the memory it writes to is
97 /// unused, may we delete this instrtction?
98 static bool isElidable(Instruction *I) {
99 assert(doesClobberMemory(I));
100 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
101 return II->getIntrinsicID() != Intrinsic::lifetime_end;
102 if (StoreInst *SI = dyn_cast<StoreInst>(I))
103 return !SI->isVolatile();
107 /// getPointerOperand - Return the pointer that is being clobbered.
108 static Value *getPointerOperand(Instruction *I) {
109 assert(doesClobberMemory(I));
110 if (StoreInst *SI = dyn_cast<StoreInst>(I))
111 return SI->getPointerOperand();
112 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
113 return MI->getOperand(1);
114 IntrinsicInst *II = cast<IntrinsicInst>(I);
115 switch (II->getIntrinsicID()) {
117 assert(false && "Unexpected intrinsic!");
118 case Intrinsic::init_trampoline:
119 return II->getOperand(1);
120 case Intrinsic::lifetime_end:
121 return II->getOperand(2);
125 /// getStoreSize - Return the length in bytes of the write by the clobbering
126 /// instruction. If variable or unknown, returns -1.
127 static unsigned getStoreSize(Instruction *I, const TargetData *TD) {
128 assert(doesClobberMemory(I));
129 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
131 return TD->getTypeStoreSize(SI->getOperand(0)->getType());
135 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
136 Len = MI->getLength();
138 IntrinsicInst *II = cast<IntrinsicInst>(I);
139 switch (II->getIntrinsicID()) {
141 assert(false && "Unexpected intrinsic!");
142 case Intrinsic::init_trampoline:
144 case Intrinsic::lifetime_end:
145 Len = II->getOperand(1);
149 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len))
150 if (!LenCI->isAllOnesValue())
151 return LenCI->getZExtValue();
155 /// isStoreAtLeastAsWideAs - Return true if the size of the store in I1 is
156 /// greater than or equal to the store in I2. This returns false if we don't
159 static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2,
160 const TargetData *TD) {
161 const Type *I1Ty = getPointerOperand(I1)->getType();
162 const Type *I2Ty = getPointerOperand(I2)->getType();
164 // Exactly the same type, must have exactly the same size.
165 if (I1Ty == I2Ty) return true;
167 int I1Size = getStoreSize(I1, TD);
168 int I2Size = getStoreSize(I2, TD);
170 return I1Size != -1 && I2Size != -1 && I1Size >= I2Size;
173 bool DSE::runOnBasicBlock(BasicBlock &BB) {
174 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
175 TD = getAnalysisIfAvailable<TargetData>();
177 bool MadeChange = false;
179 // Do a top-down walk on the BB.
180 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
181 Instruction *Inst = BBI++;
183 // If we find a store or a free, get its memory dependence.
184 if (!doesClobberMemory(Inst) && !isFreeCall(Inst))
187 MemDepResult InstDep = MD.getDependency(Inst);
189 // Ignore non-local stores.
190 // FIXME: cross-block DSE would be fun. :)
191 if (InstDep.isNonLocal()) continue;
193 // Handle frees whose dependencies are non-trivial.
194 if (isFreeCall(Inst)) {
195 MadeChange |= handleFreeWithNonTrivialDependency(Inst, InstDep);
199 // If not a definite must-alias dependency, ignore it.
200 if (!InstDep.isDef())
203 // If this is a store-store dependence, then the previous store is dead so
204 // long as this store is at least as big as it.
205 if (doesClobberMemory(InstDep.getInst())) {
206 Instruction *DepStore = InstDep.getInst();
207 if (isStoreAtLeastAsWideAs(Inst, DepStore, TD) &&
208 isElidable(DepStore)) {
209 // Delete the store and now-dead instructions that feed it.
210 DeleteDeadInstruction(DepStore);
214 // DeleteDeadInstruction can delete the current instruction in loop
217 if (BBI != BB.begin())
223 if (!isElidable(Inst))
226 // If we're storing the same value back to a pointer that we just
227 // loaded from, then the store can be removed.
228 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
229 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
230 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
231 SI->getOperand(0) == DepLoad) {
232 // DeleteDeadInstruction can delete the current instruction. Save BBI
233 // in case we need it.
234 WeakVH NextInst(BBI);
236 DeleteDeadInstruction(SI);
238 if (NextInst == 0) // Next instruction deleted.
240 else if (BBI != BB.begin()) // Revisit this instruction if possible.
249 // If this is a lifetime end marker, we can throw away the store.
250 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(InstDep.getInst())) {
251 if (II->getIntrinsicID() == Intrinsic::lifetime_end) {
252 // Delete the store and now-dead instructions that feed it.
253 // DeleteDeadInstruction can delete the current instruction. Save BBI
254 // in case we need it.
255 WeakVH NextInst(BBI);
257 DeleteDeadInstruction(Inst);
259 if (NextInst == 0) // Next instruction deleted.
261 else if (BBI != BB.begin()) // Revisit this instruction if possible.
270 // If this block ends in a return, unwind, or unreachable, all allocas are
271 // dead at its end, which means stores to them are also dead.
272 if (BB.getTerminator()->getNumSuccessors() == 0)
273 MadeChange |= handleEndBlock(BB);
278 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
279 /// dependency is a store to a field of that structure.
280 bool DSE::handleFreeWithNonTrivialDependency(Instruction *F, MemDepResult Dep) {
281 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
283 Instruction *Dependency = Dep.getInst();
284 if (!Dependency || !doesClobberMemory(Dependency) || !isElidable(Dependency))
287 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
289 // Check for aliasing.
290 if (AA.alias(F->getOperand(1), 1, DepPointer, 1) !=
291 AliasAnalysis::MustAlias)
294 // DCE instructions only used to calculate that store
295 DeleteDeadInstruction(Dependency);
300 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
301 /// function end block. Ex:
304 /// store i32 1, i32* %A
306 bool DSE::handleEndBlock(BasicBlock &BB) {
307 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
309 bool MadeChange = false;
311 // Pointers alloca'd in this function are dead in the end block
312 SmallPtrSet<Value*, 64> deadPointers;
314 // Find all of the alloca'd pointers in the entry block.
315 BasicBlock *Entry = BB.getParent()->begin();
316 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
317 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
318 deadPointers.insert(AI);
320 // Treat byval arguments the same, stores to them are dead at the end of the
322 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
323 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
324 if (AI->hasByValAttr())
325 deadPointers.insert(AI);
327 // Scan the basic block backwards
328 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
331 // If we find a store whose pointer is dead.
332 if (doesClobberMemory(BBI)) {
333 if (isElidable(BBI)) {
334 // See through pointer-to-pointer bitcasts
335 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
337 // Alloca'd pointers or byval arguments (which are functionally like
338 // alloca's) are valid candidates for removal.
339 if (deadPointers.count(pointerOperand)) {
340 // DCE instructions only used to calculate that store.
341 Instruction *Dead = BBI;
343 DeleteDeadInstruction(Dead, &deadPointers);
350 // Because a memcpy or memmove is also a load, we can't skip it if we
352 if (!isa<MemTransferInst>(BBI))
356 Value* killPointer = 0;
357 uint64_t killPointerSize = ~0UL;
359 // If we encounter a use of the pointer, it is no longer considered dead
360 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
361 // However, if this load is unused and not volatile, we can go ahead and
362 // remove it, and not have to worry about it making our pointer undead!
363 if (L->use_empty() && !L->isVolatile()) {
365 DeleteDeadInstruction(L, &deadPointers);
371 killPointer = L->getPointerOperand();
372 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
373 killPointer = V->getOperand(0);
374 } else if (isa<MemTransferInst>(BBI) &&
375 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
376 killPointer = cast<MemTransferInst>(BBI)->getSource();
377 killPointerSize = cast<ConstantInt>(
378 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
379 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
380 deadPointers.erase(A);
382 // Dead alloca's can be DCE'd when we reach them
383 if (A->use_empty()) {
385 DeleteDeadInstruction(A, &deadPointers);
391 } else if (CallSite::get(BBI).getInstruction() != 0) {
392 // If this call does not access memory, it can't
393 // be undeadifying any of our pointers.
394 CallSite CS = CallSite::get(BBI);
395 if (AA.doesNotAccessMemory(CS))
401 // Remove any pointers made undead by the call from the dead set
402 std::vector<Value*> dead;
403 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
404 E = deadPointers.end(); I != E; ++I) {
405 // HACK: if we detect that our AA is imprecise, it's not
406 // worth it to scan the rest of the deadPointers set. Just
407 // assume that the AA will return ModRef for everything, and
408 // go ahead and bail.
409 if (modRef >= 16 && other == 0) {
410 deadPointers.clear();
414 // Get size information for the alloca
415 unsigned pointerSize = ~0U;
417 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
418 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
419 pointerSize = C->getZExtValue() *
420 TD->getTypeAllocSize(A->getAllocatedType());
422 const PointerType* PT = cast<PointerType>(
423 cast<Argument>(*I)->getType());
424 pointerSize = TD->getTypeAllocSize(PT->getElementType());
428 // See if the call site touches it
429 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
431 if (A == AliasAnalysis::ModRef)
436 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
440 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
442 deadPointers.erase(*I);
445 } else if (isInstructionTriviallyDead(BBI)) {
446 // For any non-memory-affecting non-terminators, DCE them as we reach them
447 Instruction *Inst = BBI;
449 DeleteDeadInstruction(Inst, &deadPointers);
458 killPointer = killPointer->getUnderlyingObject();
460 // Deal with undead pointers
461 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
468 /// RemoveUndeadPointers - check for uses of a pointer that make it
469 /// undead when scanning for dead stores to alloca's.
470 bool DSE::RemoveUndeadPointers(Value* killPointer, uint64_t killPointerSize,
471 BasicBlock::iterator &BBI,
472 SmallPtrSet<Value*, 64>& deadPointers) {
473 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
475 // If the kill pointer can be easily reduced to an alloca,
476 // don't bother doing extraneous AA queries.
477 if (deadPointers.count(killPointer)) {
478 deadPointers.erase(killPointer);
482 // A global can't be in the dead pointer set.
483 if (isa<GlobalValue>(killPointer))
486 bool MadeChange = false;
488 SmallVector<Value*, 16> undead;
490 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
491 E = deadPointers.end(); I != E; ++I) {
492 // Get size information for the alloca.
493 unsigned pointerSize = ~0U;
495 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
496 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
497 pointerSize = C->getZExtValue() *
498 TD->getTypeAllocSize(A->getAllocatedType());
500 const PointerType* PT = cast<PointerType>(cast<Argument>(*I)->getType());
501 pointerSize = TD->getTypeAllocSize(PT->getElementType());
505 // See if this pointer could alias it
506 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
507 killPointer, killPointerSize);
509 // If it must-alias and a store, we can delete it
510 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
511 StoreInst* S = cast<StoreInst>(BBI);
515 DeleteDeadInstruction(S, &deadPointers);
521 // Otherwise, it is undead
522 } else if (A != AliasAnalysis::NoAlias)
523 undead.push_back(*I);
526 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
528 deadPointers.erase(*I);
533 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
534 /// and zero out all the operands of this instruction. If any of them become
535 /// dead, delete them and the computation tree that feeds them.
537 /// If ValueSet is non-null, remove any deleted instructions from it as well.
539 void DSE::DeleteDeadInstruction(Instruction *I,
540 SmallPtrSet<Value*, 64> *ValueSet) {
541 SmallVector<Instruction*, 32> NowDeadInsts;
543 NowDeadInsts.push_back(I);
546 // Before we touch this instruction, remove it from memdep!
547 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
548 while (!NowDeadInsts.empty()) {
549 Instruction *DeadInst = NowDeadInsts.back();
550 NowDeadInsts.pop_back();
554 // This instruction is dead, zap it, in stages. Start by removing it from
555 // MemDep, which needs to know the operands and needs it to be in the
557 MDA.removeInstruction(DeadInst);
559 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
560 Value *Op = DeadInst->getOperand(op);
561 DeadInst->setOperand(op, 0);
563 // If this operand just became dead, add it to the NowDeadInsts list.
564 if (!Op->use_empty()) continue;
566 if (Instruction *OpI = dyn_cast<Instruction>(Op))
567 if (isInstructionTriviallyDead(OpI))
568 NowDeadInsts.push_back(OpI);
571 DeadInst->eraseFromParent();
573 if (ValueSet) ValueSet->erase(DeadInst);