Treat lifetime begin/end markers as allocations/frees respectively for the
[oota-llvm.git] / lib / Transforms / Scalar / DeadStoreElimination.cpp
1 //===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a trivial dead store elimination that only considers
11 // basic-block local redundant stores.
12 //
13 // FIXME: This should eventually be extended to be a post-dominator tree
14 // traversal.  Doing so would be pretty trivial.
15 //
16 //===----------------------------------------------------------------------===//
17
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"
33 using namespace llvm;
34
35 STATISTIC(NumFastStores, "Number of stores deleted");
36 STATISTIC(NumFastOther , "Number of other instrs removed");
37
38 namespace {
39   struct DSE : public FunctionPass {
40     TargetData *TD;
41
42     static char ID; // Pass identification, replacement for typeid
43     DSE() : FunctionPass(&ID) {}
44
45     virtual bool runOnFunction(Function &F) {
46       bool Changed = false;
47       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
48         Changed |= runOnBasicBlock(*I);
49       return Changed;
50     }
51     
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);
60     
61
62     // getAnalysisUsage - We require post dominance frontiers (aka Control
63     // Dependence Graph)
64     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65       AU.setPreservesCFG();
66       AU.addRequired<DominatorTree>();
67       AU.addRequired<AliasAnalysis>();
68       AU.addRequired<MemoryDependenceAnalysis>();
69       AU.addPreserved<DominatorTree>();
70       AU.addPreserved<AliasAnalysis>();
71       AU.addPreserved<MemoryDependenceAnalysis>();
72     }
73   };
74 }
75
76 char DSE::ID = 0;
77 static RegisterPass<DSE> X("dse", "Dead Store Elimination");
78
79 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
80
81 bool DSE::runOnBasicBlock(BasicBlock &BB) {
82   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
83   TD = getAnalysisIfAvailable<TargetData>();
84
85   bool MadeChange = false;
86   
87   // Do a top-down walk on the BB.
88   for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
89     Instruction *Inst = BBI++;
90     
91     // If we find a store or a free, get its memory dependence.
92     if (!isa<StoreInst>(Inst) && !isFreeCall(Inst))
93       continue;
94     
95     // Don't molest volatile stores or do queries that will return "clobber".
96     if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
97       if (SI->isVolatile())
98         continue;
99
100     MemDepResult InstDep = MD.getDependency(Inst);
101     
102     // Ignore non-local stores.
103     // FIXME: cross-block DSE would be fun. :)
104     if (InstDep.isNonLocal()) continue;
105   
106     // Handle frees whose dependencies are non-trivial.
107     if (isFreeCall(Inst)) {
108       MadeChange |= handleFreeWithNonTrivialDependency(Inst, InstDep);
109       continue;
110     }
111     
112     StoreInst *SI = cast<StoreInst>(Inst);
113     
114     // If not a definite must-alias dependency, ignore it.
115     if (!InstDep.isDef())
116       continue;
117     
118     // If this is a store-store dependence, then the previous store is dead so
119     // long as this store is at least as big as it.
120     if (StoreInst *DepStore = dyn_cast<StoreInst>(InstDep.getInst()))
121       if (TD &&
122           TD->getTypeStoreSize(DepStore->getOperand(0)->getType()) <=
123           TD->getTypeStoreSize(SI->getOperand(0)->getType())) {
124         // Delete the store and now-dead instructions that feed it.
125         DeleteDeadInstruction(DepStore);
126         NumFastStores++;
127         MadeChange = true;
128
129         // DeleteDeadInstruction can delete the current instruction in loop
130         // cases, reset BBI.
131         BBI = Inst;
132         if (BBI != BB.begin())
133           --BBI;
134         continue;
135       }
136     
137     // If we're storing the same value back to a pointer that we just
138     // loaded from, then the store can be removed.
139     if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
140       if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
141           SI->getOperand(0) == DepLoad) {
142         // DeleteDeadInstruction can delete the current instruction.  Save BBI
143         // in case we need it.
144         WeakVH NextInst(BBI);
145         
146         DeleteDeadInstruction(SI);
147         
148         if (NextInst == 0)  // Next instruction deleted.
149           BBI = BB.begin();
150         else if (BBI != BB.begin())  // Revisit this instruction if possible.
151           --BBI;
152         NumFastStores++;
153         MadeChange = true;
154         continue;
155       }
156     }
157     
158     // If this is a lifetime end marker, we can throw away the store.
159     if (IntrinsicInst* II = dyn_cast<IntrinsicInst>(InstDep.getInst())) {
160       if (II->getIntrinsicID() == Intrinsic::lifetime_end) {
161         // Delete the store and now-dead instructions that feed it.
162         // DeleteDeadInstruction can delete the current instruction.  Save BBI
163         // in case we need it.
164         WeakVH NextInst(BBI);
165         
166         DeleteDeadInstruction(SI);
167         
168         if (NextInst == 0)  // Next instruction deleted.
169           BBI = BB.begin();
170         else if (BBI != BB.begin())  // Revisit this instruction if possible.
171           --BBI;
172         NumFastStores++;
173         MadeChange = true;
174         continue;
175       }
176     }
177   }
178   
179   // If this block ends in a return, unwind, or unreachable, all allocas are
180   // dead at its end, which means stores to them are also dead.
181   if (BB.getTerminator()->getNumSuccessors() == 0)
182     MadeChange |= handleEndBlock(BB);
183   
184   return MadeChange;
185 }
186
187 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
188 /// dependency is a store to a field of that structure.
189 bool DSE::handleFreeWithNonTrivialDependency(Instruction *F, MemDepResult Dep) {
190   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
191   
192   StoreInst *Dependency = dyn_cast_or_null<StoreInst>(Dep.getInst());
193   if (!Dependency || Dependency->isVolatile())
194     return false;
195   
196   Value *DepPointer = Dependency->getPointerOperand()->getUnderlyingObject();
197
198   // Check for aliasing.
199   if (AA.alias(F->getOperand(1), 1, DepPointer, 1) !=
200          AliasAnalysis::MustAlias)
201     return false;
202   
203   // DCE instructions only used to calculate that store
204   DeleteDeadInstruction(Dependency);
205   NumFastStores++;
206   return true;
207 }
208
209 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
210 /// function end block.  Ex:
211 /// %A = alloca i32
212 /// ...
213 /// store i32 1, i32* %A
214 /// ret void
215 bool DSE::handleEndBlock(BasicBlock &BB) {
216   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
217   
218   bool MadeChange = false;
219   
220   // Pointers alloca'd in this function are dead in the end block
221   SmallPtrSet<Value*, 64> deadPointers;
222   
223   // Find all of the alloca'd pointers in the entry block.
224   BasicBlock *Entry = BB.getParent()->begin();
225   for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
226     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
227       deadPointers.insert(AI);
228   
229   // Treat byval arguments the same, stores to them are dead at the end of the
230   // function.
231   for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
232        AE = BB.getParent()->arg_end(); AI != AE; ++AI)
233     if (AI->hasByValAttr())
234       deadPointers.insert(AI);
235   
236   // Scan the basic block backwards
237   for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
238     --BBI;
239     
240     // If we find a store whose pointer is dead.
241     if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
242       if (!S->isVolatile()) {
243         // See through pointer-to-pointer bitcasts
244         Value* pointerOperand = S->getPointerOperand()->getUnderlyingObject();
245
246         // Alloca'd pointers or byval arguments (which are functionally like
247         // alloca's) are valid candidates for removal.
248         if (deadPointers.count(pointerOperand)) {
249           // DCE instructions only used to calculate that store.
250           BBI++;
251           DeleteDeadInstruction(S, &deadPointers);
252           NumFastStores++;
253           MadeChange = true;
254         }
255       }
256       
257       continue;
258     }
259     
260     // We can also remove memcpy's to local variables at the end of a function.
261     if (MemCpyInst *M = dyn_cast<MemCpyInst>(BBI)) {
262       Value *dest = M->getDest()->getUnderlyingObject();
263
264       if (deadPointers.count(dest)) {
265         BBI++;
266         DeleteDeadInstruction(M, &deadPointers);
267         NumFastOther++;
268         MadeChange = true;
269         continue;
270       }
271       
272       // Because a memcpy is also a load, we can't skip it if we didn't remove
273       // it.
274     }
275     
276     Value* killPointer = 0;
277     uint64_t killPointerSize = ~0UL;
278     
279     // If we encounter a use of the pointer, it is no longer considered dead
280     if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
281       // However, if this load is unused and not volatile, we can go ahead and
282       // remove it, and not have to worry about it making our pointer undead!
283       if (L->use_empty() && !L->isVolatile()) {
284         BBI++;
285         DeleteDeadInstruction(L, &deadPointers);
286         NumFastOther++;
287         MadeChange = true;
288         continue;
289       }
290       
291       killPointer = L->getPointerOperand();
292     } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
293       killPointer = V->getOperand(0);
294     } else if (isa<MemCpyInst>(BBI) &&
295                isa<ConstantInt>(cast<MemCpyInst>(BBI)->getLength())) {
296       killPointer = cast<MemCpyInst>(BBI)->getSource();
297       killPointerSize = cast<ConstantInt>(
298                             cast<MemCpyInst>(BBI)->getLength())->getZExtValue();
299     } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
300       deadPointers.erase(A);
301       
302       // Dead alloca's can be DCE'd when we reach them
303       if (A->use_empty()) {
304         BBI++;
305         DeleteDeadInstruction(A, &deadPointers);
306         NumFastOther++;
307         MadeChange = true;
308       }
309       
310       continue;
311     } else if (CallSite::get(BBI).getInstruction() != 0) {
312       // If this call does not access memory, it can't
313       // be undeadifying any of our pointers.
314       CallSite CS = CallSite::get(BBI);
315       if (AA.doesNotAccessMemory(CS))
316         continue;
317       
318       unsigned modRef = 0;
319       unsigned other = 0;
320       
321       // Remove any pointers made undead by the call from the dead set
322       std::vector<Value*> dead;
323       for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
324            E = deadPointers.end(); I != E; ++I) {
325         // HACK: if we detect that our AA is imprecise, it's not
326         // worth it to scan the rest of the deadPointers set.  Just
327         // assume that the AA will return ModRef for everything, and
328         // go ahead and bail.
329         if (modRef >= 16 && other == 0) {
330           deadPointers.clear();
331           return MadeChange;
332         }
333
334         // Get size information for the alloca
335         unsigned pointerSize = ~0U;
336         if (TD) {
337           if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
338             if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
339               pointerSize = C->getZExtValue() *
340                             TD->getTypeAllocSize(A->getAllocatedType());
341           } else {
342             const PointerType* PT = cast<PointerType>(
343                                                    cast<Argument>(*I)->getType());
344             pointerSize = TD->getTypeAllocSize(PT->getElementType());
345           }
346         }
347
348         // See if the call site touches it
349         AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
350         
351         if (A == AliasAnalysis::ModRef)
352           modRef++;
353         else
354           other++;
355         
356         if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
357           dead.push_back(*I);
358       }
359
360       for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
361            I != E; ++I)
362         deadPointers.erase(*I);
363       
364       continue;
365     } else if (isInstructionTriviallyDead(BBI)) {
366       // For any non-memory-affecting non-terminators, DCE them as we reach them
367       Instruction *Inst = BBI;
368       BBI++;
369       DeleteDeadInstruction(Inst, &deadPointers);
370       NumFastOther++;
371       MadeChange = true;
372       continue;
373     }
374     
375     if (!killPointer)
376       continue;
377
378     killPointer = killPointer->getUnderlyingObject();
379
380     // Deal with undead pointers
381     MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
382                                        deadPointers);
383   }
384   
385   return MadeChange;
386 }
387
388 /// RemoveUndeadPointers - check for uses of a pointer that make it
389 /// undead when scanning for dead stores to alloca's.
390 bool DSE::RemoveUndeadPointers(Value* killPointer, uint64_t killPointerSize,
391                                BasicBlock::iterator &BBI,
392                                SmallPtrSet<Value*, 64>& deadPointers) {
393   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
394                                   
395   // If the kill pointer can be easily reduced to an alloca,
396   // don't bother doing extraneous AA queries.
397   if (deadPointers.count(killPointer)) {
398     deadPointers.erase(killPointer);
399     return false;
400   }
401   
402   // A global can't be in the dead pointer set.
403   if (isa<GlobalValue>(killPointer))
404     return false;
405   
406   bool MadeChange = false;
407   
408   SmallVector<Value*, 16> undead;
409     
410   for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
411       E = deadPointers.end(); I != E; ++I) {
412     // Get size information for the alloca.
413     unsigned pointerSize = ~0U;
414     if (TD) {
415       if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
416         if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
417           pointerSize = C->getZExtValue() *
418                         TD->getTypeAllocSize(A->getAllocatedType());
419       } else {
420         const PointerType* PT = cast<PointerType>(cast<Argument>(*I)->getType());
421         pointerSize = TD->getTypeAllocSize(PT->getElementType());
422       }
423     }
424
425     // See if this pointer could alias it
426     AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
427                                             killPointer, killPointerSize);
428
429     // If it must-alias and a store, we can delete it
430     if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
431       StoreInst* S = cast<StoreInst>(BBI);
432
433       // Remove it!
434       BBI++;
435       DeleteDeadInstruction(S, &deadPointers);
436       NumFastStores++;
437       MadeChange = true;
438
439       continue;
440
441       // Otherwise, it is undead
442     } else if (A != AliasAnalysis::NoAlias)
443       undead.push_back(*I);
444   }
445
446   for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
447        I != E; ++I)
448       deadPointers.erase(*I);
449   
450   return MadeChange;
451 }
452
453 /// DeleteDeadInstruction - Delete this instruction.  Before we do, go through
454 /// and zero out all the operands of this instruction.  If any of them become
455 /// dead, delete them and the computation tree that feeds them.
456 ///
457 /// If ValueSet is non-null, remove any deleted instructions from it as well.
458 ///
459 void DSE::DeleteDeadInstruction(Instruction *I,
460                                 SmallPtrSet<Value*, 64> *ValueSet) {
461   SmallVector<Instruction*, 32> NowDeadInsts;
462   
463   NowDeadInsts.push_back(I);
464   --NumFastOther;
465
466   // Before we touch this instruction, remove it from memdep!
467   MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
468   while (!NowDeadInsts.empty()) {
469     Instruction *DeadInst = NowDeadInsts.back();
470     NowDeadInsts.pop_back();
471     
472     ++NumFastOther;
473     
474     // This instruction is dead, zap it, in stages.  Start by removing it from
475     // MemDep, which needs to know the operands and needs it to be in the
476     // function.
477     MDA.removeInstruction(DeadInst);
478     
479     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
480       Value *Op = DeadInst->getOperand(op);
481       DeadInst->setOperand(op, 0);
482       
483       // If this operand just became dead, add it to the NowDeadInsts list.
484       if (!Op->use_empty()) continue;
485       
486       if (Instruction *OpI = dyn_cast<Instruction>(Op))
487         if (isInstructionTriviallyDead(OpI))
488           NowDeadInsts.push_back(OpI);
489     }
490     
491     DeadInst->eraseFromParent();
492     
493     if (ValueSet) ValueSet->erase(DeadInst);
494   }
495 }