Get rid of static constructors for pass registration. Instead, every pass exposes...
[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       initializeDSEPass(*PassRegistry::getPassRegistry());
45     }
46
47     virtual bool runOnFunction(Function &F) {
48       bool Changed = false;
49       
50       DominatorTree &DT = getAnalysis<DominatorTree>();
51       
52       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
53         // Only check non-dead blocks.  Dead blocks may have strange pointer
54         // cycles that will confuse alias analysis.
55         if (DT.isReachableFromEntry(I))
56           Changed |= runOnBasicBlock(*I);
57       return Changed;
58     }
59     
60     bool runOnBasicBlock(BasicBlock &BB);
61     bool handleFreeWithNonTrivialDependency(const CallInst *F,
62                                             MemDepResult Dep);
63     bool handleEndBlock(BasicBlock &BB);
64     bool RemoveUndeadPointers(Value *Ptr, unsigned killPointerSize,
65                               BasicBlock::iterator &BBI,
66                               SmallPtrSet<Value*, 64> &deadPointers);
67     void DeleteDeadInstruction(Instruction *I,
68                                SmallPtrSet<Value*, 64> *deadPointers = 0);
69     
70
71     // getAnalysisUsage - We require post dominance frontiers (aka Control
72     // Dependence Graph)
73     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
74       AU.setPreservesCFG();
75       AU.addRequired<DominatorTree>();
76       AU.addRequired<AliasAnalysis>();
77       AU.addRequired<MemoryDependenceAnalysis>();
78       AU.addPreserved<DominatorTree>();
79       AU.addPreserved<MemoryDependenceAnalysis>();
80     }
81
82     unsigned getPointerSize(Value *V) const;
83   };
84 }
85
86 char DSE::ID = 0;
87 INITIALIZE_PASS_BEGIN(DSE, "dse", "Dead Store Elimination", false, false)
88 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
89 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
90 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
91 INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false)
92
93 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
94
95 /// doesClobberMemory - Does this instruction clobber (write without reading)
96 /// some memory?
97 static bool doesClobberMemory(Instruction *I) {
98   if (isa<StoreInst>(I))
99     return true;
100   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
101     switch (II->getIntrinsicID()) {
102     default:
103       return false;
104     case Intrinsic::memset:
105     case Intrinsic::memmove:
106     case Intrinsic::memcpy:
107     case Intrinsic::init_trampoline:
108     case Intrinsic::lifetime_end:
109       return true;
110     }
111   }
112   return false;
113 }
114
115 /// isElidable - If the value of this instruction and the memory it writes to is
116 /// unused, may we delete this instrtction?
117 static bool isElidable(Instruction *I) {
118   assert(doesClobberMemory(I));
119   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
120     return II->getIntrinsicID() != Intrinsic::lifetime_end;
121   if (StoreInst *SI = dyn_cast<StoreInst>(I))
122     return !SI->isVolatile();
123   return true;
124 }
125
126 /// getPointerOperand - Return the pointer that is being clobbered.
127 static Value *getPointerOperand(Instruction *I) {
128   assert(doesClobberMemory(I));
129   if (StoreInst *SI = dyn_cast<StoreInst>(I))
130     return SI->getPointerOperand();
131   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
132     return MI->getArgOperand(0);
133
134   IntrinsicInst *II = cast<IntrinsicInst>(I);
135   switch (II->getIntrinsicID()) {
136   default: assert(false && "Unexpected intrinsic!");
137   case Intrinsic::init_trampoline:
138     return II->getArgOperand(0);
139   case Intrinsic::lifetime_end:
140     return II->getArgOperand(1);
141   }
142 }
143
144 /// getStoreSize - Return the length in bytes of the write by the clobbering
145 /// instruction. If variable or unknown, returns -1.
146 static unsigned getStoreSize(Instruction *I, const TargetData *TD) {
147   assert(doesClobberMemory(I));
148   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
149     if (!TD) return -1u;
150     return TD->getTypeStoreSize(SI->getOperand(0)->getType());
151   }
152
153   Value *Len;
154   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
155     Len = MI->getLength();
156   } else {
157     IntrinsicInst *II = cast<IntrinsicInst>(I);
158     switch (II->getIntrinsicID()) {
159     default: assert(false && "Unexpected intrinsic!");
160     case Intrinsic::init_trampoline:
161       return -1u;
162     case Intrinsic::lifetime_end:
163       Len = II->getArgOperand(0);
164       break;
165     }
166   }
167   if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len))
168     if (!LenCI->isAllOnesValue())
169       return LenCI->getZExtValue();
170   return -1u;
171 }
172
173 /// isStoreAtLeastAsWideAs - Return true if the size of the store in I1 is
174 /// greater than or equal to the store in I2.  This returns false if we don't
175 /// know.
176 ///
177 static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2,
178                                    const TargetData *TD) {
179   const Type *I1Ty = getPointerOperand(I1)->getType();
180   const Type *I2Ty = getPointerOperand(I2)->getType();
181   
182   // Exactly the same type, must have exactly the same size.
183   if (I1Ty == I2Ty) return true;
184   
185   int I1Size = getStoreSize(I1, TD);
186   int I2Size = getStoreSize(I2, TD);
187   
188   return I1Size != -1 && I2Size != -1 && I1Size >= I2Size;
189 }
190
191 bool DSE::runOnBasicBlock(BasicBlock &BB) {
192   MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
193   TD = getAnalysisIfAvailable<TargetData>();
194
195   bool MadeChange = false;
196   
197   // Do a top-down walk on the BB.
198   for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
199     Instruction *Inst = BBI++;
200     
201     // If we find a store or a free, get its memory dependence.
202     if (!doesClobberMemory(Inst) && !isFreeCall(Inst))
203       continue;
204     
205     MemDepResult InstDep = MD.getDependency(Inst);
206     
207     // Ignore non-local stores.
208     // FIXME: cross-block DSE would be fun. :)
209     if (InstDep.isNonLocal()) continue;
210   
211     // Handle frees whose dependencies are non-trivial.
212     if (const CallInst *F = isFreeCall(Inst)) {
213       MadeChange |= handleFreeWithNonTrivialDependency(F, InstDep);
214       continue;
215     }
216     
217     // If not a definite must-alias dependency, ignore it.
218     if (!InstDep.isDef())
219       continue;
220     
221     // If this is a store-store dependence, then the previous store is dead so
222     // long as this store is at least as big as it.
223     if (doesClobberMemory(InstDep.getInst())) {
224       Instruction *DepStore = InstDep.getInst();
225       if (isStoreAtLeastAsWideAs(Inst, DepStore, TD) &&
226           isElidable(DepStore)) {
227         // Delete the store and now-dead instructions that feed it.
228         DeleteDeadInstruction(DepStore);
229         ++NumFastStores;
230         MadeChange = true;
231
232         // DeleteDeadInstruction can delete the current instruction in loop
233         // cases, reset BBI.
234         BBI = Inst;
235         if (BBI != BB.begin())
236           --BBI;
237         continue;
238       }
239     }
240     
241     if (!isElidable(Inst))
242       continue;
243     
244     // If we're storing the same value back to a pointer that we just
245     // loaded from, then the store can be removed.
246     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
247       if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
248         if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
249             SI->getOperand(0) == DepLoad) {
250           // DeleteDeadInstruction can delete the current instruction.  Save BBI
251           // in case we need it.
252           WeakVH NextInst(BBI);
253           
254           DeleteDeadInstruction(SI);
255           
256           if (NextInst == 0)  // Next instruction deleted.
257             BBI = BB.begin();
258           else if (BBI != BB.begin())  // Revisit this instruction if possible.
259             --BBI;
260           ++NumFastStores;
261           MadeChange = true;
262           continue;
263         }
264       }
265     }
266     
267     // If this is a lifetime end marker, we can throw away the store.
268     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(InstDep.getInst())) {
269       if (II->getIntrinsicID() == Intrinsic::lifetime_end) {
270         // Delete the store and now-dead instructions that feed it.
271         // DeleteDeadInstruction can delete the current instruction.  Save BBI
272         // in case we need it.
273         WeakVH NextInst(BBI);
274         
275         DeleteDeadInstruction(Inst);
276         
277         if (NextInst == 0)  // Next instruction deleted.
278           BBI = BB.begin();
279         else if (BBI != BB.begin())  // Revisit this instruction if possible.
280           --BBI;
281         ++NumFastStores;
282         MadeChange = true;
283         continue;
284       }
285     }
286   }
287   
288   // If this block ends in a return, unwind, or unreachable, all allocas are
289   // dead at its end, which means stores to them are also dead.
290   if (BB.getTerminator()->getNumSuccessors() == 0)
291     MadeChange |= handleEndBlock(BB);
292   
293   return MadeChange;
294 }
295
296 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
297 /// dependency is a store to a field of that structure.
298 bool DSE::handleFreeWithNonTrivialDependency(const CallInst *F,
299                                              MemDepResult Dep) {
300   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
301   
302   Instruction *Dependency = Dep.getInst();
303   if (!Dependency || !doesClobberMemory(Dependency) || !isElidable(Dependency))
304     return false;
305   
306   Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
307
308   // Check for aliasing.
309   if (AA.alias(F->getArgOperand(0), 1, DepPointer, 1) !=
310          AliasAnalysis::MustAlias)
311     return false;
312   
313   // DCE instructions only used to calculate that store
314   DeleteDeadInstruction(Dependency);
315   ++NumFastStores;
316   return true;
317 }
318
319 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
320 /// function end block.  Ex:
321 /// %A = alloca i32
322 /// ...
323 /// store i32 1, i32* %A
324 /// ret void
325 bool DSE::handleEndBlock(BasicBlock &BB) {
326   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
327   
328   bool MadeChange = false;
329   
330   // Pointers alloca'd in this function are dead in the end block
331   SmallPtrSet<Value*, 64> deadPointers;
332   
333   // Find all of the alloca'd pointers in the entry block.
334   BasicBlock *Entry = BB.getParent()->begin();
335   for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
336     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
337       deadPointers.insert(AI);
338   
339   // Treat byval arguments the same, stores to them are dead at the end of the
340   // function.
341   for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
342        AE = BB.getParent()->arg_end(); AI != AE; ++AI)
343     if (AI->hasByValAttr())
344       deadPointers.insert(AI);
345   
346   // Scan the basic block backwards
347   for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
348     --BBI;
349     
350     // If we find a store whose pointer is dead.
351     if (doesClobberMemory(BBI)) {
352       if (isElidable(BBI)) {
353         // See through pointer-to-pointer bitcasts
354         Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
355
356         // Alloca'd pointers or byval arguments (which are functionally like
357         // alloca's) are valid candidates for removal.
358         if (deadPointers.count(pointerOperand)) {
359           // DCE instructions only used to calculate that store.
360           Instruction *Dead = BBI;
361           ++BBI;
362           DeleteDeadInstruction(Dead, &deadPointers);
363           ++NumFastStores;
364           MadeChange = true;
365           continue;
366         }
367       }
368       
369       // Because a memcpy or memmove is also a load, we can't skip it if we
370       // didn't remove it.
371       if (!isa<MemTransferInst>(BBI))
372         continue;
373     }
374     
375     Value *killPointer = 0;
376     unsigned killPointerSize = AliasAnalysis::UnknownSize;
377     
378     // If we encounter a use of the pointer, it is no longer considered dead
379     if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
380       // However, if this load is unused and not volatile, we can go ahead and
381       // remove it, and not have to worry about it making our pointer undead!
382       if (L->use_empty() && !L->isVolatile()) {
383         ++BBI;
384         DeleteDeadInstruction(L, &deadPointers);
385         ++NumFastOther;
386         MadeChange = true;
387         continue;
388       }
389       
390       killPointer = L->getPointerOperand();
391     } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
392       killPointer = V->getOperand(0);
393     } else if (isa<MemTransferInst>(BBI) &&
394                isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
395       killPointer = cast<MemTransferInst>(BBI)->getSource();
396       killPointerSize = cast<ConstantInt>(
397                        cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
398     } else if (AllocaInst *A = dyn_cast<AllocaInst>(BBI)) {
399       deadPointers.erase(A);
400       
401       // Dead alloca's can be DCE'd when we reach them
402       if (A->use_empty()) {
403         ++BBI;
404         DeleteDeadInstruction(A, &deadPointers);
405         ++NumFastOther;
406         MadeChange = true;
407       }
408       
409       continue;
410     } else if (CallSite CS = cast<Value>(BBI)) {
411       // If this call does not access memory, it can't
412       // be undeadifying any of our pointers.
413       if (AA.doesNotAccessMemory(CS))
414         continue;
415       
416       unsigned modRef = 0;
417       unsigned other = 0;
418       
419       // Remove any pointers made undead by the call from the dead set
420       std::vector<Value*> dead;
421       for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
422            E = deadPointers.end(); I != E; ++I) {
423         // HACK: if we detect that our AA is imprecise, it's not
424         // worth it to scan the rest of the deadPointers set.  Just
425         // assume that the AA will return ModRef for everything, and
426         // go ahead and bail.
427         if (modRef >= 16 && other == 0) {
428           deadPointers.clear();
429           return MadeChange;
430         }
431         
432         // See if the call site touches it
433         AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I,
434                                                          getPointerSize(*I));
435         
436         if (A == AliasAnalysis::ModRef)
437           ++modRef;
438         else
439           ++other;
440         
441         if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
442           dead.push_back(*I);
443       }
444
445       for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
446            I != E; ++I)
447         deadPointers.erase(*I);
448       
449       continue;
450     } else if (isInstructionTriviallyDead(BBI)) {
451       // For any non-memory-affecting non-terminators, DCE them as we reach them
452       Instruction *Inst = BBI;
453       ++BBI;
454       DeleteDeadInstruction(Inst, &deadPointers);
455       ++NumFastOther;
456       MadeChange = true;
457       continue;
458     }
459     
460     if (!killPointer)
461       continue;
462
463     killPointer = killPointer->getUnderlyingObject();
464
465     // Deal with undead pointers
466     MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
467                                        deadPointers);
468   }
469   
470   return MadeChange;
471 }
472
473 /// RemoveUndeadPointers - check for uses of a pointer that make it
474 /// undead when scanning for dead stores to alloca's.
475 bool DSE::RemoveUndeadPointers(Value *killPointer, unsigned killPointerSize,
476                                BasicBlock::iterator &BBI,
477                                SmallPtrSet<Value*, 64> &deadPointers) {
478   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
479
480   // If the kill pointer can be easily reduced to an alloca,
481   // don't bother doing extraneous AA queries.
482   if (deadPointers.count(killPointer)) {
483     deadPointers.erase(killPointer);
484     return false;
485   }
486   
487   // A global can't be in the dead pointer set.
488   if (isa<GlobalValue>(killPointer))
489     return false;
490   
491   bool MadeChange = false;
492   
493   SmallVector<Value*, 16> undead;
494   
495   for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
496        E = deadPointers.end(); I != E; ++I) {
497     // See if this pointer could alias it
498     AliasAnalysis::AliasResult A = AA.alias(*I, getPointerSize(*I),
499                                             killPointer, killPointerSize);
500
501     // If it must-alias and a store, we can delete it
502     if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
503       StoreInst *S = cast<StoreInst>(BBI);
504
505       // Remove it!
506       ++BBI;
507       DeleteDeadInstruction(S, &deadPointers);
508       ++NumFastStores;
509       MadeChange = true;
510
511       continue;
512
513       // Otherwise, it is undead
514     } else if (A != AliasAnalysis::NoAlias)
515       undead.push_back(*I);
516   }
517
518   for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
519        I != E; ++I)
520       deadPointers.erase(*I);
521   
522   return MadeChange;
523 }
524
525 /// DeleteDeadInstruction - Delete this instruction.  Before we do, go through
526 /// and zero out all the operands of this instruction.  If any of them become
527 /// dead, delete them and the computation tree that feeds them.
528 ///
529 /// If ValueSet is non-null, remove any deleted instructions from it as well.
530 ///
531 void DSE::DeleteDeadInstruction(Instruction *I,
532                                 SmallPtrSet<Value*, 64> *ValueSet) {
533   SmallVector<Instruction*, 32> NowDeadInsts;
534   
535   NowDeadInsts.push_back(I);
536   --NumFastOther;
537
538   // Before we touch this instruction, remove it from memdep!
539   MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
540   do {
541     Instruction *DeadInst = NowDeadInsts.pop_back_val();
542     
543     ++NumFastOther;
544     
545     // This instruction is dead, zap it, in stages.  Start by removing it from
546     // MemDep, which needs to know the operands and needs it to be in the
547     // function.
548     MDA.removeInstruction(DeadInst);
549     
550     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
551       Value *Op = DeadInst->getOperand(op);
552       DeadInst->setOperand(op, 0);
553       
554       // If this operand just became dead, add it to the NowDeadInsts list.
555       if (!Op->use_empty()) continue;
556       
557       if (Instruction *OpI = dyn_cast<Instruction>(Op))
558         if (isInstructionTriviallyDead(OpI))
559           NowDeadInsts.push_back(OpI);
560     }
561     
562     DeadInst->eraseFromParent();
563     
564     if (ValueSet) ValueSet->erase(DeadInst);
565   } while (!NowDeadInsts.empty());
566 }
567
568 unsigned DSE::getPointerSize(Value *V) const {
569   if (TD) {
570     if (AllocaInst *A = dyn_cast<AllocaInst>(V)) {
571       // Get size information for the alloca
572       if (ConstantInt *C = dyn_cast<ConstantInt>(A->getArraySize()))
573         return C->getZExtValue() * TD->getTypeAllocSize(A->getAllocatedType());
574     } else {
575       assert(isa<Argument>(V) && "Expected AllocaInst or Argument!");
576       const PointerType *PT = cast<PointerType>(V->getType());
577       return TD->getTypeAllocSize(PT->getElementType());
578     }
579   }
580   return AliasAnalysis::UnknownSize;
581 }