1 //===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Owen Anderson and is distributed under
6 // the University of Illinois Open Source 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/Pass.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Support/Compiler.h"
34 STATISTIC(NumFastStores, "Number of stores deleted");
35 STATISTIC(NumFastOther , "Number of other instrs removed");
38 struct VISIBILITY_HIDDEN DSE : public FunctionPass {
39 static char ID; // Pass identification, replacement for typeid
40 DSE() : FunctionPass((intptr_t)&ID) {}
42 virtual bool runOnFunction(Function &F) {
44 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
45 Changed |= runOnBasicBlock(*I);
49 bool runOnBasicBlock(BasicBlock &BB);
50 bool handleFreeWithNonTrivialDependency(FreeInst* F,
51 Instruction* dependency,
52 SetVector<Instruction*>& possiblyDead);
53 bool handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead);
54 bool RemoveUndeadPointers(Value* pointer, unsigned pointerSize,
55 BasicBlock::iterator& BBI,
56 SmallPtrSet<AllocaInst*, 4>& deadPointers,
57 SetVector<Instruction*>& possiblyDead);
58 void DeleteDeadInstructionChains(Instruction *I,
59 SetVector<Instruction*> &DeadInsts);
61 /// Find the base pointer that a pointer came from
62 /// Because this is used to find pointers that originate
63 /// from allocas, it is safe to ignore GEP indices, since
64 /// either the store will be in the alloca, and thus dead,
65 /// or beyond the end of the alloca, and thus undefined.
66 void TranslatePointerBitCasts(Value*& v) {
67 assert(isa<PointerType>(v->getType()) &&
68 "Translating a non-pointer type?");
70 if (BitCastInst* C = dyn_cast<BitCastInst>(v))
72 else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(v))
79 // getAnalysisUsage - We require post dominance frontiers (aka Control
81 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
83 AU.addRequired<TargetData>();
84 AU.addRequired<AliasAnalysis>();
85 AU.addRequired<MemoryDependenceAnalysis>();
86 AU.addPreserved<AliasAnalysis>();
87 AU.addPreserved<MemoryDependenceAnalysis>();
91 RegisterPass<DSE> X("dse", "Dead Store Elimination");
94 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
96 bool DSE::runOnBasicBlock(BasicBlock &BB) {
97 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
99 // Record the last-seen store to this pointer
100 DenseMap<Value*, StoreInst*> lastStore;
101 // Record instructions possibly made dead by deleting a store
102 SetVector<Instruction*> possiblyDead;
104 bool MadeChange = false;
106 // Do a top-down walk on the BB
107 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end();
109 // If we find a store or a free...
110 if (!isa<StoreInst>(BBI) && !isa<FreeInst>(BBI))
114 if (StoreInst* S = dyn_cast<StoreInst>(BBI))
115 pointer = S->getPointerOperand();
117 pointer = cast<FreeInst>(BBI)->getPointerOperand();
119 StoreInst*& last = lastStore[pointer];
120 bool deletedStore = false;
122 // ... to a pointer that has been stored to before...
124 Instruction* dep = MD.getDependency(BBI);
126 // ... and no other memory dependencies are between them....
127 while (dep != MemoryDependenceAnalysis::None &&
128 dep != MemoryDependenceAnalysis::NonLocal &&
129 isa<StoreInst>(dep)) {
131 dep = MD.getDependency(BBI, dep);
136 MD.removeInstruction(last);
138 // DCE instructions only used to calculate that store
139 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
140 possiblyDead.insert(D);
141 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(1)))
142 possiblyDead.insert(D);
144 last->eraseFromParent();
153 // Handle frees whose dependencies are non-trivial.
154 if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
156 MadeChange |= handleFreeWithNonTrivialDependency(F,
159 // No known stores after the free
162 // Update our most-recent-store map.
163 last = cast<StoreInst>(BBI);
167 // If this block ends in a return, unwind, unreachable, and eventually
168 // tailcall, then all allocas are dead at its end.
169 if (BB.getTerminator()->getNumSuccessors() == 0)
170 MadeChange |= handleEndBlock(BB, possiblyDead);
173 while (!possiblyDead.empty()) {
174 Instruction *I = possiblyDead.back();
175 possiblyDead.pop_back();
176 DeleteDeadInstructionChains(I, possiblyDead);
182 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
183 /// dependency is a store to a field of that structure
184 bool DSE::handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dep,
185 SetVector<Instruction*>& possiblyDead) {
186 TargetData &TD = getAnalysis<TargetData>();
187 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
188 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
190 if (dep == MemoryDependenceAnalysis::None ||
191 dep == MemoryDependenceAnalysis::NonLocal)
194 StoreInst* dependency = dyn_cast<StoreInst>(dep);
198 Value* depPointer = dependency->getPointerOperand();
199 const Type* depType = dependency->getOperand(0)->getType();
200 unsigned depPointerSize = TD.getTypeSize(depType);
202 // Check for aliasing
203 AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0UL,
204 depPointer, depPointerSize);
206 if (A == AliasAnalysis::MustAlias) {
208 MD.removeInstruction(dependency);
210 // DCE instructions only used to calculate that store
211 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
212 possiblyDead.insert(D);
213 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(1)))
214 possiblyDead.insert(D);
216 dependency->eraseFromParent();
224 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
225 /// function end block
226 bool DSE::handleEndBlock(BasicBlock& BB,
227 SetVector<Instruction*>& possiblyDead) {
228 TargetData &TD = getAnalysis<TargetData>();
229 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
230 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
232 bool MadeChange = false;
234 // Pointers alloca'd in this function are dead in the end block
235 SmallPtrSet<AllocaInst*, 4> deadPointers;
237 // Find all of the alloca'd pointers in the entry block
238 BasicBlock *Entry = BB.getParent()->begin();
239 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
240 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
241 deadPointers.insert(AI);
243 // Scan the basic block backwards
244 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
247 if (deadPointers.empty())
250 Value* killPointer = 0;
251 unsigned killPointerSize = 0;
253 // If we find a store whose pointer is dead...
254 if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
255 Value* pointerOperand = S->getPointerOperand();
256 // See through pointer-to-pointer bitcasts
257 TranslatePointerBitCasts(pointerOperand);
259 if (deadPointers.count(pointerOperand)){
261 MD.removeInstruction(S);
263 // DCE instructions only used to calculate that store
264 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
265 possiblyDead.insert(D);
266 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
267 possiblyDead.insert(D);
270 S->eraseFromParent();
275 // If we encounter a use of the pointer, it is no longer considered dead
276 } else if (LoadInst* L = dyn_cast<LoadInst>(BBI)) {
277 killPointer = L->getPointerOperand();
278 killPointerSize = TD.getTypeSize(L->getType());
279 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
280 killPointer = V->getOperand(0);
281 killPointerSize = TD.getTypeSize(V->getType());
282 } else if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
283 killPointer = F->getPointerOperand();
284 killPointerSize = ~0UL;
285 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
286 deadPointers.erase(A);
288 } else if (CallSite::get(BBI).getInstruction() != 0) {
289 // Remove any pointers made undead by the call from the dead set
290 std::vector<Instruction*> dead;
291 for (SmallPtrSet<AllocaInst*, 4>::iterator I = deadPointers.begin(),
292 E = deadPointers.end(); I != E; ++I) {
293 // Get size information for the alloca
294 unsigned pointerSize = ~0UL;
295 if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
296 pointerSize = C->getZExtValue() * \
297 TD.getTypeSize((*I)->getAllocatedType());
299 // See if the call site touches it
300 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CallSite::get(BBI),
302 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
306 for (std::vector<Instruction*>::iterator I = dead.begin(), E = dead.end();
308 deadPointers.erase(*I);
316 // Deal with undead pointers
317 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
318 deadPointers, possiblyDead);
324 bool DSE::RemoveUndeadPointers(Value* killPointer, unsigned killPointerSize,
325 BasicBlock::iterator& BBI,
326 SmallPtrSet<AllocaInst*, 4>& deadPointers,
327 SetVector<Instruction*>& possiblyDead) {
328 TargetData &TD = getAnalysis<TargetData>();
329 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
330 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
332 bool MadeChange = false;
334 std::vector<Instruction*> undead;
336 for (SmallPtrSet<AllocaInst*, 4>::iterator I = deadPointers.begin(),
337 E = deadPointers.end(); I != E; ++I) {
338 // Get size information for the alloca
339 unsigned pointerSize = ~0UL;
340 if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
341 pointerSize = C->getZExtValue() * \
342 TD.getTypeSize((*I)->getAllocatedType());
344 // See if this pointer could alias it
345 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
346 killPointer, killPointerSize);
348 // If it must-alias and a store, we can delete it
349 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
350 StoreInst* S = cast<StoreInst>(BBI);
353 MD.removeInstruction(S);
355 // DCE instructions only used to calculate that store
356 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
357 possiblyDead.insert(D);
358 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
359 possiblyDead.insert(D);
362 S->eraseFromParent();
368 // Otherwise, it is undead
369 } else if (A != AliasAnalysis::NoAlias)
370 undead.push_back(*I);
373 for (std::vector<Instruction*>::iterator I = undead.begin(), E = undead.end();
375 deadPointers.erase(*I);
380 void DSE::DeleteDeadInstructionChains(Instruction *I,
381 SetVector<Instruction*> &DeadInsts) {
382 // Instruction must be dead.
383 if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
385 // Let the memory dependence know
386 getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
388 // See if this made any operands dead. We do it this way in case the
389 // instruction uses the same operand twice. We don't want to delete a
390 // value then reference it.
391 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
392 if (I->getOperand(i)->hasOneUse())
393 if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
394 DeadInsts.insert(Op); // Attempt to nuke it later.
396 I->setOperand(i, 0); // Drop from the operand list.
399 I->eraseFromParent();