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/SetVector.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Analysis/AliasAnalysis.h"
29 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Support/Compiler.h"
35 STATISTIC(NumFastStores, "Number of stores deleted");
36 STATISTIC(NumFastOther , "Number of other instrs removed");
39 struct VISIBILITY_HIDDEN DSE : public FunctionPass {
40 static char ID; // Pass identification, replacement for typeid
41 DSE() : FunctionPass((intptr_t)&ID) {}
43 virtual bool runOnFunction(Function &F) {
45 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
46 Changed |= runOnBasicBlock(*I);
50 bool runOnBasicBlock(BasicBlock &BB);
51 bool handleFreeWithNonTrivialDependency(FreeInst* F,
52 Instruction* dependency,
53 SetVector<Instruction*>& possiblyDead);
54 bool handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead);
55 bool RemoveUndeadPointers(Value* pointer, uint64_t killPointerSize,
56 BasicBlock::iterator& BBI,
57 SmallPtrSet<Value*, 64>& deadPointers,
58 SetVector<Instruction*>& possiblyDead);
59 void DeleteDeadInstructionChains(Instruction *I,
60 SetVector<Instruction*> &DeadInsts);
62 /// Find the base pointer that a pointer came from
63 /// Because this is used to find pointers that originate
64 /// from allocas, it is safe to ignore GEP indices, since
65 /// either the store will be in the alloca, and thus dead,
66 /// or beyond the end of the alloca, and thus undefined.
67 void TranslatePointerBitCasts(Value*& v, bool zeroGepsOnly = false) {
68 assert(isa<PointerType>(v->getType()) &&
69 "Translating a non-pointer type?");
71 if (BitCastInst* C = dyn_cast<BitCastInst>(v))
73 else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(v))
74 if (!zeroGepsOnly || G->hasAllZeroIndices()) {
84 // getAnalysisUsage - We require post dominance frontiers (aka Control
86 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88 AU.addRequired<TargetData>();
89 AU.addRequired<AliasAnalysis>();
90 AU.addRequired<MemoryDependenceAnalysis>();
91 AU.addPreserved<AliasAnalysis>();
92 AU.addPreserved<MemoryDependenceAnalysis>();
96 RegisterPass<DSE> X("dse", "Dead Store Elimination");
99 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
101 bool DSE::runOnBasicBlock(BasicBlock &BB) {
102 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
103 TargetData &TD = getAnalysis<TargetData>();
105 // Record the last-seen store to this pointer
106 DenseMap<Value*, StoreInst*> lastStore;
107 // Record instructions possibly made dead by deleting a store
108 SetVector<Instruction*> possiblyDead;
110 bool MadeChange = false;
112 // Do a top-down walk on the BB
113 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end();
115 // If we find a store or a free...
116 if (!isa<StoreInst>(BBI) && !isa<FreeInst>(BBI))
120 if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
121 if (!S->isVolatile())
122 pointer = S->getPointerOperand();
126 pointer = cast<FreeInst>(BBI)->getPointerOperand();
128 TranslatePointerBitCasts(pointer, true);
129 StoreInst*& last = lastStore[pointer];
130 bool deletedStore = false;
132 // ... to a pointer that has been stored to before...
134 Instruction* dep = MD.getDependency(BBI);
136 // ... and no other memory dependencies are between them....
137 while (dep != MemoryDependenceAnalysis::None &&
138 dep != MemoryDependenceAnalysis::NonLocal &&
139 isa<StoreInst>(dep)) {
141 TD.getTypeStoreSize(last->getOperand(0)->getType()) >
142 TD.getTypeStoreSize(BBI->getOperand(0)->getType())) {
143 dep = MD.getDependency(BBI, dep);
148 MD.removeInstruction(last);
150 // DCE instructions only used to calculate that store
151 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
152 possiblyDead.insert(D);
153 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(1)))
154 possiblyDead.insert(D);
156 last->eraseFromParent();
165 // Handle frees whose dependencies are non-trivial.
166 if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
168 MadeChange |= handleFreeWithNonTrivialDependency(F,
171 // No known stores after the free
174 // Update our most-recent-store map.
175 last = cast<StoreInst>(BBI);
179 // If this block ends in a return, unwind, unreachable, and eventually
180 // tailcall, then all allocas are dead at its end.
181 if (BB.getTerminator()->getNumSuccessors() == 0)
182 MadeChange |= handleEndBlock(BB, possiblyDead);
185 while (!possiblyDead.empty()) {
186 Instruction *I = possiblyDead.back();
187 possiblyDead.pop_back();
188 DeleteDeadInstructionChains(I, possiblyDead);
194 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
195 /// dependency is a store to a field of that structure
196 bool DSE::handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dep,
197 SetVector<Instruction*>& possiblyDead) {
198 TargetData &TD = getAnalysis<TargetData>();
199 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
200 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
202 if (dep == MemoryDependenceAnalysis::None ||
203 dep == MemoryDependenceAnalysis::NonLocal)
206 StoreInst* dependency = dyn_cast<StoreInst>(dep);
209 else if (dependency->isVolatile())
212 Value* depPointer = dependency->getPointerOperand();
213 const Type* depType = dependency->getOperand(0)->getType();
214 unsigned depPointerSize = TD.getTypeStoreSize(depType);
216 // Check for aliasing
217 AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0U,
218 depPointer, depPointerSize);
220 if (A == AliasAnalysis::MustAlias) {
222 MD.removeInstruction(dependency);
224 // DCE instructions only used to calculate that store
225 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
226 possiblyDead.insert(D);
227 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(1)))
228 possiblyDead.insert(D);
230 dependency->eraseFromParent();
238 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
239 /// function end block. Ex:
242 /// store i32 1, i32* %A
244 bool DSE::handleEndBlock(BasicBlock& BB,
245 SetVector<Instruction*>& possiblyDead) {
246 TargetData &TD = getAnalysis<TargetData>();
247 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
248 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
250 bool MadeChange = false;
252 // Pointers alloca'd in this function are dead in the end block
253 SmallPtrSet<Value*, 64> deadPointers;
255 // Find all of the alloca'd pointers in the entry block
256 BasicBlock *Entry = BB.getParent()->begin();
257 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
258 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
259 deadPointers.insert(AI);
260 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
261 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
262 if (AI->hasByValAttr())
263 deadPointers.insert(AI);
265 // Scan the basic block backwards
266 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
269 // If we find a store whose pointer is dead...
270 if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
271 if (!S->isVolatile()) {
272 Value* pointerOperand = S->getPointerOperand();
273 // See through pointer-to-pointer bitcasts
274 TranslatePointerBitCasts(pointerOperand);
276 // Alloca'd pointers or byval arguments (which are functionally like
277 // alloca's) are valid candidates for removal.
278 if (deadPointers.count(pointerOperand)) {
280 MD.removeInstruction(S);
282 // DCE instructions only used to calculate that store
283 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
284 possiblyDead.insert(D);
285 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
286 possiblyDead.insert(D);
289 S->eraseFromParent();
297 // We can also remove memcpy's to local variables at the end of a function
298 } else if (MemCpyInst* M = dyn_cast<MemCpyInst>(BBI)) {
299 Value* dest = M->getDest();
300 TranslatePointerBitCasts(dest);
302 if (deadPointers.count(dest)) {
303 MD.removeInstruction(M);
305 // DCE instructions only used to calculate that memcpy
306 if (Instruction* D = dyn_cast<Instruction>(M->getRawSource()))
307 possiblyDead.insert(D);
308 if (Instruction* D = dyn_cast<Instruction>(M->getLength()))
309 possiblyDead.insert(D);
310 if (Instruction* D = dyn_cast<Instruction>(M->getRawDest()))
311 possiblyDead.insert(D);
314 M->eraseFromParent();
321 // Because a memcpy is also a load, we can't skip it if we didn't remove it
324 Value* killPointer = 0;
325 uint64_t killPointerSize = ~0UL;
327 // If we encounter a use of the pointer, it is no longer considered dead
328 if (LoadInst* L = dyn_cast<LoadInst>(BBI)) {
329 // However, if this load is unused, we can go ahead and remove it, and
330 // not have to worry about it making our pointer undead!
331 if (L->use_empty()) {
332 MD.removeInstruction(L);
334 // DCE instructions only used to calculate that load
335 if (Instruction* D = dyn_cast<Instruction>(L->getPointerOperand()))
336 possiblyDead.insert(D);
339 L->eraseFromParent();
342 possiblyDead.remove(L);
347 killPointer = L->getPointerOperand();
348 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
349 killPointer = V->getOperand(0);
350 } else if (isa<MemCpyInst>(BBI) &&
351 isa<ConstantInt>(cast<MemCpyInst>(BBI)->getLength())) {
352 killPointer = cast<MemCpyInst>(BBI)->getSource();
353 killPointerSize = cast<ConstantInt>(
354 cast<MemCpyInst>(BBI)->getLength())->getZExtValue();
355 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
356 deadPointers.erase(A);
358 // Dead alloca's can be DCE'd when we reach them
359 if (A->use_empty()) {
360 MD.removeInstruction(A);
362 // DCE instructions only used to calculate that load
363 if (Instruction* D = dyn_cast<Instruction>(A->getArraySize()))
364 possiblyDead.insert(D);
367 A->eraseFromParent();
370 possiblyDead.remove(A);
374 } else if (CallSite::get(BBI).getInstruction() != 0) {
375 // If this call does not access memory, it can't
376 // be undeadifying any of our pointers.
377 CallSite CS = CallSite::get(BBI);
378 if (AA.doesNotAccessMemory(CS))
384 // Remove any pointers made undead by the call from the dead set
385 std::vector<Value*> dead;
386 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
387 E = deadPointers.end(); I != E; ++I) {
388 // HACK: if we detect that our AA is imprecise, it's not
389 // worth it to scan the rest of the deadPointers set. Just
390 // assume that the AA will return ModRef for everything, and
391 // go ahead and bail.
392 if (modRef >= 16 && other == 0) {
393 deadPointers.clear();
397 // Get size information for the alloca
398 unsigned pointerSize = ~0U;
399 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
400 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
401 pointerSize = C->getZExtValue() * \
402 TD.getABITypeSize(A->getAllocatedType());
404 const PointerType* PT = cast<PointerType>(
405 cast<Argument>(*I)->getType());
406 pointerSize = TD.getABITypeSize(PT->getElementType());
409 // See if the call site touches it
410 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
412 if (A == AliasAnalysis::ModRef)
417 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
421 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
423 deadPointers.erase(*I);
427 // For any non-memory-affecting non-terminators, DCE them as we reach them
428 Instruction *CI = BBI;
429 if (!CI->isTerminator() && CI->use_empty() && !isa<FreeInst>(CI)) {
431 // DCE instructions only used to calculate that load
432 for (Instruction::op_iterator OI = CI->op_begin(), OE = CI->op_end();
434 if (Instruction* D = dyn_cast<Instruction>(OI))
435 possiblyDead.insert(D);
438 CI->eraseFromParent();
441 possiblyDead.remove(CI);
450 TranslatePointerBitCasts(killPointer);
452 // Deal with undead pointers
453 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
454 deadPointers, possiblyDead);
460 /// RemoveUndeadPointers - check for uses of a pointer that make it
461 /// undead when scanning for dead stores to alloca's.
462 bool DSE::RemoveUndeadPointers(Value* killPointer, uint64_t killPointerSize,
463 BasicBlock::iterator& BBI,
464 SmallPtrSet<Value*, 64>& deadPointers,
465 SetVector<Instruction*>& possiblyDead) {
466 TargetData &TD = getAnalysis<TargetData>();
467 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
468 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
470 // If the kill pointer can be easily reduced to an alloca,
471 // don't bother doing extraneous AA queries
472 if (deadPointers.count(killPointer)) {
473 deadPointers.erase(killPointer);
475 } else if (isa<GlobalValue>(killPointer)) {
476 // A global can't be in the dead pointer set
480 bool MadeChange = false;
482 std::vector<Value*> undead;
484 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
485 E = deadPointers.end(); I != E; ++I) {
486 // Get size information for the alloca
487 unsigned pointerSize = ~0U;
488 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
489 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
490 pointerSize = C->getZExtValue() * \
491 TD.getABITypeSize(A->getAllocatedType());
493 const PointerType* PT = cast<PointerType>(
494 cast<Argument>(*I)->getType());
495 pointerSize = TD.getABITypeSize(PT->getElementType());
498 // See if this pointer could alias it
499 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
500 killPointer, killPointerSize);
502 // If it must-alias and a store, we can delete it
503 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
504 StoreInst* S = cast<StoreInst>(BBI);
507 MD.removeInstruction(S);
509 // DCE instructions only used to calculate that store
510 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
511 possiblyDead.insert(D);
512 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
513 possiblyDead.insert(D);
516 S->eraseFromParent();
522 // Otherwise, it is undead
523 } else if (A != AliasAnalysis::NoAlias)
524 undead.push_back(*I);
527 for (std::vector<Value*>::iterator I = undead.begin(), E = undead.end();
529 deadPointers.erase(*I);
534 /// DeleteDeadInstructionChains - takes an instruction and a setvector of
535 /// dead instructions. If I is dead, it is erased, and its operands are
536 /// checked for deadness. If they are dead, they are added to the dead
538 void DSE::DeleteDeadInstructionChains(Instruction *I,
539 SetVector<Instruction*> &DeadInsts) {
540 // Instruction must be dead.
541 if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
543 // Let the memory dependence know
544 getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
546 // See if this made any operands dead. We do it this way in case the
547 // instruction uses the same operand twice. We don't want to delete a
548 // value then reference it.
549 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
550 if (I->getOperand(i)->hasOneUse())
551 if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
552 DeadInsts.insert(Op); // Attempt to nuke it later.
554 I->setOperand(i, 0); // Drop from the operand list.
557 I->eraseFromParent();