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();
116 else if (FreeInst* F = dyn_cast<FreeInst>(BBI))
117 pointer = F->getPointerOperand();
119 assert(pointer && "Not a free or a store?");
121 StoreInst*& last = lastStore[pointer];
122 bool deletedStore = false;
124 // ... to a pointer that has been stored to before...
126 Instruction* dep = MD.getDependency(BBI);
128 // ... and no other memory dependencies are between them....
129 while (dep != MemoryDependenceAnalysis::None &&
130 dep != MemoryDependenceAnalysis::NonLocal &&
131 isa<StoreInst>(dep)) {
133 dep = MD.getDependency(BBI, dep);
138 MD.removeInstruction(last);
140 // DCE instructions only used to calculate that store
141 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
142 possiblyDead.insert(D);
143 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(1)))
144 possiblyDead.insert(D);
146 last->eraseFromParent();
155 // Handle frees whose dependencies are non-trivial.
156 if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
158 MadeChange |= handleFreeWithNonTrivialDependency(F,
161 // No known stores after the free
164 // Update our most-recent-store map.
165 last = cast<StoreInst>(BBI);
169 // If this block ends in a return, unwind, unreachable, and eventually
170 // tailcall, then all allocas are dead at its end.
171 if (BB.getTerminator()->getNumSuccessors() == 0)
172 MadeChange |= handleEndBlock(BB, possiblyDead);
175 while (!possiblyDead.empty()) {
176 Instruction *I = possiblyDead.back();
177 possiblyDead.pop_back();
178 DeleteDeadInstructionChains(I, possiblyDead);
184 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
185 /// dependency is a store to a field of that structure
186 bool DSE::handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dep,
187 SetVector<Instruction*>& possiblyDead) {
188 TargetData &TD = getAnalysis<TargetData>();
189 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
190 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
192 if (dep == MemoryDependenceAnalysis::None ||
193 dep == MemoryDependenceAnalysis::NonLocal)
196 StoreInst* dependency = dyn_cast<StoreInst>(dep);
200 Value* depPointer = dependency->getPointerOperand();
201 const Type* depType = dependency->getOperand(0)->getType();
202 unsigned depPointerSize = TD.getTypeSize(depType);
204 // Check for aliasing
205 AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0UL,
206 depPointer, depPointerSize);
208 if (A == AliasAnalysis::MustAlias) {
210 MD.removeInstruction(dependency);
212 // DCE instructions only used to calculate that store
213 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
214 possiblyDead.insert(D);
215 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(1)))
216 possiblyDead.insert(D);
218 dependency->eraseFromParent();
226 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
227 /// function end block
228 bool DSE::handleEndBlock(BasicBlock& BB,
229 SetVector<Instruction*>& possiblyDead) {
230 TargetData &TD = getAnalysis<TargetData>();
231 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
232 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
234 bool MadeChange = false;
236 // Pointers alloca'd in this function are dead in the end block
237 SmallPtrSet<AllocaInst*, 4> deadPointers;
239 // Find all of the alloca'd pointers in the entry block
240 BasicBlock *Entry = BB.getParent()->begin();
241 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
242 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
243 deadPointers.insert(AI);
245 // Scan the basic block backwards
246 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
249 if (deadPointers.empty())
252 Value* killPointer = 0;
253 unsigned killPointerSize = 0;
255 // If we find a store whose pointer is dead...
256 if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
257 Value* pointerOperand = S->getPointerOperand();
258 // See through pointer-to-pointer bitcasts
259 TranslatePointerBitCasts(pointerOperand);
261 if (deadPointers.count(pointerOperand)){
263 MD.removeInstruction(S);
265 // DCE instructions only used to calculate that store
266 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
267 possiblyDead.insert(D);
268 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
269 possiblyDead.insert(D);
272 S->eraseFromParent();
277 // If we encounter a use of the pointer, it is no longer considered dead
278 } else if (LoadInst* L = dyn_cast<LoadInst>(BBI)) {
279 killPointer = L->getPointerOperand();
280 killPointerSize = TD.getTypeSize(L->getType());
281 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
282 killPointer = V->getOperand(0);
283 killPointerSize = TD.getTypeSize(V->getType());
284 } else if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
285 killPointer = F->getPointerOperand();
286 killPointerSize = ~0UL;
287 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
288 deadPointers.erase(A);
290 } else if (CallSite::get(BBI).getInstruction() != 0) {
291 // Remove any pointers made undead by the call from the dead set
292 std::vector<Instruction*> dead;
293 for (SmallPtrSet<AllocaInst*, 4>::iterator I = deadPointers.begin(),
294 E = deadPointers.end(); I != E; ++I) {
295 // Get size information for the alloca
296 unsigned pointerSize = ~0UL;
297 if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
298 pointerSize = C->getZExtValue() * \
299 TD.getTypeSize((*I)->getAllocatedType());
301 // See if the call site touches it
302 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CallSite::get(BBI),
304 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
308 for (std::vector<Instruction*>::iterator I = dead.begin(), E = dead.end();
310 deadPointers.erase(*I);
318 // Deal with undead pointers
319 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
320 deadPointers, possiblyDead);
326 bool DSE::RemoveUndeadPointers(Value* killPointer, unsigned killPointerSize,
327 BasicBlock::iterator& BBI,
328 SmallPtrSet<AllocaInst*, 4>& deadPointers,
329 SetVector<Instruction*>& possiblyDead) {
330 TargetData &TD = getAnalysis<TargetData>();
331 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
332 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
334 bool MadeChange = false;
336 std::vector<Instruction*> undead;
338 for (SmallPtrSet<AllocaInst*, 4>::iterator I = deadPointers.begin(),
339 E = deadPointers.end(); I != E; ++I) {
340 // Get size information for the alloca
341 unsigned pointerSize = ~0UL;
342 if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
343 pointerSize = C->getZExtValue() * \
344 TD.getTypeSize((*I)->getAllocatedType());
346 // See if this pointer could alias it
347 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
348 killPointer, killPointerSize);
350 // If it must-alias and a store, we can delete it
351 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
352 StoreInst* S = cast<StoreInst>(BBI);
355 MD.removeInstruction(S);
357 // DCE instructions only used to calculate that store
358 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
359 possiblyDead.insert(D);
360 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
361 possiblyDead.insert(D);
364 S->eraseFromParent();
370 // Otherwise, it is undead
371 } else if (A != AliasAnalysis::NoAlias)
372 undead.push_back(*I);
375 for (std::vector<Instruction*>::iterator I = undead.begin(), E = undead.end();
377 deadPointers.erase(*I);
382 void DSE::DeleteDeadInstructionChains(Instruction *I,
383 SetVector<Instruction*> &DeadInsts) {
384 // Instruction must be dead.
385 if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
387 // Let the memory dependence know
388 getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
390 // See if this made any operands dead. We do it this way in case the
391 // instruction uses the same operand twice. We don't want to delete a
392 // value then reference it.
393 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
394 if (I->getOperand(i)->hasOneUse())
395 if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
396 DeadInsts.insert(Op); // Attempt to nuke it later.
398 I->setOperand(i, 0); // Drop from the operand list.
401 I->eraseFromParent();