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