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()) {
90 case Intrinsic::memset:
91 case Intrinsic::memmove:
92 case Intrinsic::memcpy:
93 case Intrinsic::init_trampoline:
94 case Intrinsic::lifetime_end:
101 /// isElidable - If the value of this instruction and the memory it writes to is
102 /// unused, may we delete this instrtction?
103 static bool isElidable(Instruction *I) {
104 assert(doesClobberMemory(I));
105 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
106 return II->getIntrinsicID() != Intrinsic::lifetime_end;
107 if (StoreInst *SI = dyn_cast<StoreInst>(I))
108 return !SI->isVolatile();
112 /// getPointerOperand - Return the pointer that is being clobbered.
113 static Value *getPointerOperand(Instruction *I) {
114 assert(doesClobberMemory(I));
115 if (StoreInst *SI = dyn_cast<StoreInst>(I))
116 return SI->getPointerOperand();
117 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
118 return MI->getOperand(1);
120 switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
121 default: assert(false && "Unexpected intrinsic!");
122 case Intrinsic::init_trampoline:
123 return I->getOperand(1);
124 case Intrinsic::lifetime_end:
125 return I->getOperand(2);
129 /// getStoreSize - Return the length in bytes of the write by the clobbering
130 /// instruction. If variable or unknown, returns -1.
131 static unsigned getStoreSize(Instruction *I, const TargetData *TD) {
132 assert(doesClobberMemory(I));
133 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
135 return TD->getTypeStoreSize(SI->getOperand(0)->getType());
139 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
140 Len = MI->getLength();
142 switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
143 default: assert(false && "Unexpected intrinsic!");
144 case Intrinsic::init_trampoline:
146 case Intrinsic::lifetime_end:
147 Len = I->getOperand(1);
151 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len))
152 if (!LenCI->isAllOnesValue())
153 return LenCI->getZExtValue();
157 /// isStoreAtLeastAsWideAs - Return true if the size of the store in I1 is
158 /// greater than or equal to the store in I2. This returns false if we don't
161 static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2,
162 const TargetData *TD) {
163 const Type *I1Ty = getPointerOperand(I1)->getType();
164 const Type *I2Ty = getPointerOperand(I2)->getType();
166 // Exactly the same type, must have exactly the same size.
167 if (I1Ty == I2Ty) return true;
169 int I1Size = getStoreSize(I1, TD);
170 int I2Size = getStoreSize(I2, TD);
172 return I1Size != -1 && I2Size != -1 && I1Size >= I2Size;
175 bool DSE::runOnBasicBlock(BasicBlock &BB) {
176 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
177 TD = getAnalysisIfAvailable<TargetData>();
179 bool MadeChange = false;
181 // Do a top-down walk on the BB.
182 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
183 Instruction *Inst = BBI++;
185 // If we find a store or a free, get its memory dependence.
186 if (!doesClobberMemory(Inst) && !isFreeCall(Inst))
189 MemDepResult InstDep = MD.getDependency(Inst);
191 // Ignore non-local stores.
192 // FIXME: cross-block DSE would be fun. :)
193 if (InstDep.isNonLocal()) continue;
195 // Handle frees whose dependencies are non-trivial.
196 if (isFreeCall(Inst)) {
197 MadeChange |= handleFreeWithNonTrivialDependency(Inst, InstDep);
201 // If not a definite must-alias dependency, ignore it.
202 if (!InstDep.isDef())
205 // If this is a store-store dependence, then the previous store is dead so
206 // long as this store is at least as big as it.
207 if (doesClobberMemory(InstDep.getInst())) {
208 Instruction *DepStore = InstDep.getInst();
209 if (isStoreAtLeastAsWideAs(Inst, DepStore, TD) &&
210 isElidable(DepStore)) {
211 // Delete the store and now-dead instructions that feed it.
212 DeleteDeadInstruction(DepStore);
216 // DeleteDeadInstruction can delete the current instruction in loop
219 if (BBI != BB.begin())
225 if (!isElidable(Inst))
228 // If we're storing the same value back to a pointer that we just
229 // loaded from, then the store can be removed.
230 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
231 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
232 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
233 SI->getOperand(0) == DepLoad) {
234 // DeleteDeadInstruction can delete the current instruction. Save BBI
235 // in case we need it.
236 WeakVH NextInst(BBI);
238 DeleteDeadInstruction(SI);
240 if (NextInst == 0) // Next instruction deleted.
242 else if (BBI != BB.begin()) // Revisit this instruction if possible.
251 // If this is a lifetime end marker, we can throw away the store.
252 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(InstDep.getInst())) {
253 if (II->getIntrinsicID() == Intrinsic::lifetime_end) {
254 // Delete the store and now-dead instructions that feed it.
255 // DeleteDeadInstruction can delete the current instruction. Save BBI
256 // in case we need it.
257 WeakVH NextInst(BBI);
259 DeleteDeadInstruction(Inst);
261 if (NextInst == 0) // Next instruction deleted.
263 else if (BBI != BB.begin()) // Revisit this instruction if possible.
272 // If this block ends in a return, unwind, or unreachable, all allocas are
273 // dead at its end, which means stores to them are also dead.
274 if (BB.getTerminator()->getNumSuccessors() == 0)
275 MadeChange |= handleEndBlock(BB);
280 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
281 /// dependency is a store to a field of that structure.
282 bool DSE::handleFreeWithNonTrivialDependency(Instruction *F, MemDepResult Dep) {
283 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
285 Instruction *Dependency = Dep.getInst();
286 if (!Dependency || !doesClobberMemory(Dependency) || !isElidable(Dependency))
289 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
291 // Check for aliasing.
292 if (AA.alias(F->getOperand(1), 1, DepPointer, 1) !=
293 AliasAnalysis::MustAlias)
296 // DCE instructions only used to calculate that store
297 DeleteDeadInstruction(Dependency);
302 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
303 /// function end block. Ex:
306 /// store i32 1, i32* %A
308 bool DSE::handleEndBlock(BasicBlock &BB) {
309 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
311 bool MadeChange = false;
313 // Pointers alloca'd in this function are dead in the end block
314 SmallPtrSet<Value*, 64> deadPointers;
316 // Find all of the alloca'd pointers in the entry block.
317 BasicBlock *Entry = BB.getParent()->begin();
318 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
319 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
320 deadPointers.insert(AI);
322 // Treat byval arguments the same, stores to them are dead at the end of the
324 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
325 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
326 if (AI->hasByValAttr())
327 deadPointers.insert(AI);
329 // Scan the basic block backwards
330 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
333 // If we find a store whose pointer is dead.
334 if (doesClobberMemory(BBI)) {
335 if (isElidable(BBI)) {
336 // See through pointer-to-pointer bitcasts
337 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
339 // Alloca'd pointers or byval arguments (which are functionally like
340 // alloca's) are valid candidates for removal.
341 if (deadPointers.count(pointerOperand)) {
342 // DCE instructions only used to calculate that store.
343 Instruction *Dead = BBI;
345 DeleteDeadInstruction(Dead, &deadPointers);
352 // Because a memcpy or memmove is also a load, we can't skip it if we
354 if (!isa<MemTransferInst>(BBI))
358 Value* killPointer = 0;
359 uint64_t killPointerSize = ~0UL;
361 // If we encounter a use of the pointer, it is no longer considered dead
362 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
363 // However, if this load is unused and not volatile, we can go ahead and
364 // remove it, and not have to worry about it making our pointer undead!
365 if (L->use_empty() && !L->isVolatile()) {
367 DeleteDeadInstruction(L, &deadPointers);
373 killPointer = L->getPointerOperand();
374 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
375 killPointer = V->getOperand(0);
376 } else if (isa<MemTransferInst>(BBI) &&
377 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
378 killPointer = cast<MemTransferInst>(BBI)->getSource();
379 killPointerSize = cast<ConstantInt>(
380 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
381 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
382 deadPointers.erase(A);
384 // Dead alloca's can be DCE'd when we reach them
385 if (A->use_empty()) {
387 DeleteDeadInstruction(A, &deadPointers);
393 } else if (CallSite::get(BBI).getInstruction() != 0) {
394 // If this call does not access memory, it can't
395 // be undeadifying any of our pointers.
396 CallSite CS = CallSite::get(BBI);
397 if (AA.doesNotAccessMemory(CS))
403 // Remove any pointers made undead by the call from the dead set
404 std::vector<Value*> dead;
405 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
406 E = deadPointers.end(); I != E; ++I) {
407 // HACK: if we detect that our AA is imprecise, it's not
408 // worth it to scan the rest of the deadPointers set. Just
409 // assume that the AA will return ModRef for everything, and
410 // go ahead and bail.
411 if (modRef >= 16 && other == 0) {
412 deadPointers.clear();
416 // Get size information for the alloca
417 unsigned pointerSize = ~0U;
419 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
420 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
421 pointerSize = C->getZExtValue() *
422 TD->getTypeAllocSize(A->getAllocatedType());
424 const PointerType* PT = cast<PointerType>(
425 cast<Argument>(*I)->getType());
426 pointerSize = TD->getTypeAllocSize(PT->getElementType());
430 // See if the call site touches it
431 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
433 if (A == AliasAnalysis::ModRef)
438 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
442 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
444 deadPointers.erase(*I);
447 } else if (isInstructionTriviallyDead(BBI)) {
448 // For any non-memory-affecting non-terminators, DCE them as we reach them
449 Instruction *Inst = BBI;
451 DeleteDeadInstruction(Inst, &deadPointers);
460 killPointer = killPointer->getUnderlyingObject();
462 // Deal with undead pointers
463 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
470 /// RemoveUndeadPointers - check for uses of a pointer that make it
471 /// undead when scanning for dead stores to alloca's.
472 bool DSE::RemoveUndeadPointers(Value* killPointer, uint64_t killPointerSize,
473 BasicBlock::iterator &BBI,
474 SmallPtrSet<Value*, 64>& deadPointers) {
475 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
477 // If the kill pointer can be easily reduced to an alloca,
478 // don't bother doing extraneous AA queries.
479 if (deadPointers.count(killPointer)) {
480 deadPointers.erase(killPointer);
484 // A global can't be in the dead pointer set.
485 if (isa<GlobalValue>(killPointer))
488 bool MadeChange = false;
490 SmallVector<Value*, 16> undead;
492 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
493 E = deadPointers.end(); I != E; ++I) {
494 // Get size information for the alloca.
495 unsigned pointerSize = ~0U;
497 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
498 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
499 pointerSize = C->getZExtValue() *
500 TD->getTypeAllocSize(A->getAllocatedType());
502 const PointerType* PT = cast<PointerType>(cast<Argument>(*I)->getType());
503 pointerSize = TD->getTypeAllocSize(PT->getElementType());
507 // See if this pointer could alias it
508 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
509 killPointer, killPointerSize);
511 // If it must-alias and a store, we can delete it
512 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
513 StoreInst* S = cast<StoreInst>(BBI);
517 DeleteDeadInstruction(S, &deadPointers);
523 // Otherwise, it is undead
524 } else if (A != AliasAnalysis::NoAlias)
525 undead.push_back(*I);
528 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
530 deadPointers.erase(*I);
535 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
536 /// and zero out all the operands of this instruction. If any of them become
537 /// dead, delete them and the computation tree that feeds them.
539 /// If ValueSet is non-null, remove any deleted instructions from it as well.
541 void DSE::DeleteDeadInstruction(Instruction *I,
542 SmallPtrSet<Value*, 64> *ValueSet) {
543 SmallVector<Instruction*, 32> NowDeadInsts;
545 NowDeadInsts.push_back(I);
548 // Before we touch this instruction, remove it from memdep!
549 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
550 while (!NowDeadInsts.empty()) {
551 Instruction *DeadInst = NowDeadInsts.back();
552 NowDeadInsts.pop_back();
556 // This instruction is dead, zap it, in stages. Start by removing it from
557 // MemDep, which needs to know the operands and needs it to be in the
559 MDA.removeInstruction(DeadInst);
561 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
562 Value *Op = DeadInst->getOperand(op);
563 DeadInst->setOperand(op, 0);
565 // If this operand just became dead, add it to the NowDeadInsts list.
566 if (!Op->use_empty()) continue;
568 if (Instruction *OpI = dyn_cast<Instruction>(Op))
569 if (isInstructionTriviallyDead(OpI))
570 NowDeadInsts.push_back(OpI);
573 DeadInst->eraseFromParent();
575 if (ValueSet) ValueSet->erase(DeadInst);