Add support for eliminating memcpy's at the end of functions. Also fix some errors...
[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/SetVector.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Analysis/AliasAnalysis.h"
29 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Support/Compiler.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 VISIBILITY_HIDDEN DSE : public FunctionPass {
40     static char ID; // Pass identification, replacement for typeid
41     DSE() : FunctionPass((intptr_t)&ID) {}
42
43     virtual bool runOnFunction(Function &F) {
44       bool Changed = false;
45       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
46         Changed |= runOnBasicBlock(*I);
47       return Changed;
48     }
49
50     bool runOnBasicBlock(BasicBlock &BB);
51     bool handleFreeWithNonTrivialDependency(FreeInst* F,
52                                             Instruction* dependency,
53                                         SetVector<Instruction*>& possiblyDead);
54     bool handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead);
55     bool RemoveUndeadPointers(Value* pointer,
56                               BasicBlock::iterator& BBI,
57                               SmallPtrSet<Value*, 64>& deadPointers, 
58                               SetVector<Instruction*>& possiblyDead);
59     void DeleteDeadInstructionChains(Instruction *I,
60                                      SetVector<Instruction*> &DeadInsts);
61     
62     /// Find the base pointer that a pointer came from
63     /// Because this is used to find pointers that originate
64     /// from allocas, it is safe to ignore GEP indices, since
65     /// either the store will be in the alloca, and thus dead,
66     /// or beyond the end of the alloca, and thus undefined.
67     void TranslatePointerBitCasts(Value*& v, bool zeroGepsOnly = false) {
68       assert(isa<PointerType>(v->getType()) &&
69              "Translating a non-pointer type?");
70       while (true) {
71         if (BitCastInst* C = dyn_cast<BitCastInst>(v))
72           v = C->getOperand(0);
73         else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(v))
74           if (!zeroGepsOnly || G->hasAllZeroIndices()) {
75             v = G->getOperand(0);
76           } else {
77             break;
78           }
79         else
80           break;
81       }
82     }
83
84     // getAnalysisUsage - We require post dominance frontiers (aka Control
85     // Dependence Graph)
86     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
87       AU.setPreservesCFG();
88       AU.addRequired<TargetData>();
89       AU.addRequired<AliasAnalysis>();
90       AU.addRequired<MemoryDependenceAnalysis>();
91       AU.addPreserved<AliasAnalysis>();
92       AU.addPreserved<MemoryDependenceAnalysis>();
93     }
94   };
95   char DSE::ID = 0;
96   RegisterPass<DSE> X("dse", "Dead Store Elimination");
97 }
98
99 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
100
101 bool DSE::runOnBasicBlock(BasicBlock &BB) {
102   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
103   TargetData &TD = getAnalysis<TargetData>();  
104
105   // Record the last-seen store to this pointer
106   DenseMap<Value*, StoreInst*> lastStore;
107   // Record instructions possibly made dead by deleting a store
108   SetVector<Instruction*> possiblyDead;
109   
110   bool MadeChange = false;
111   
112   // Do a top-down walk on the BB
113   for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end();
114        BBI != BBE; ++BBI) {
115     // If we find a store or a free...
116     if (!isa<StoreInst>(BBI) && !isa<FreeInst>(BBI))
117       continue;
118       
119     Value* pointer = 0;
120     if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
121       if (!S->isVolatile())
122         pointer = S->getPointerOperand();
123       else
124         continue;
125     } else
126       pointer = cast<FreeInst>(BBI)->getPointerOperand();
127       
128     TranslatePointerBitCasts(pointer, true);
129     StoreInst*& last = lastStore[pointer];
130     bool deletedStore = false;
131       
132     // ... to a pointer that has been stored to before...
133     if (last) {
134       Instruction* dep = MD.getDependency(BBI);
135         
136       // ... and no other memory dependencies are between them....
137       while (dep != MemoryDependenceAnalysis::None &&
138              dep != MemoryDependenceAnalysis::NonLocal &&
139              isa<StoreInst>(dep)) {
140         if (dep != last ||
141              TD.getTypeStoreSize(last->getOperand(0)->getType()) >
142              TD.getTypeStoreSize(BBI->getOperand(0)->getType())) {
143           dep = MD.getDependency(BBI, dep);
144           continue;
145         }
146         
147         // Remove it!
148         MD.removeInstruction(last);
149           
150         // DCE instructions only used to calculate that store
151         if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
152           possiblyDead.insert(D);
153         if (Instruction* D = dyn_cast<Instruction>(last->getOperand(1)))
154           possiblyDead.insert(D);
155           
156         last->eraseFromParent();
157         NumFastStores++;
158         deletedStore = true;
159         MadeChange = true;
160           
161         break;
162       }
163     }
164     
165     // Handle frees whose dependencies are non-trivial.
166     if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
167       if (!deletedStore)
168         MadeChange |= handleFreeWithNonTrivialDependency(F,
169                                                          MD.getDependency(F),
170                                                          possiblyDead);
171       // No known stores after the free
172       last = 0;
173     } else {
174       // Update our most-recent-store map.
175       last = cast<StoreInst>(BBI);
176     }
177   }
178   
179   // If this block ends in a return, unwind, unreachable, and eventually
180   // tailcall, then all allocas are dead at its end.
181   if (BB.getTerminator()->getNumSuccessors() == 0)
182     MadeChange |= handleEndBlock(BB, possiblyDead);
183   
184   // Do a trivial DCE
185   while (!possiblyDead.empty()) {
186     Instruction *I = possiblyDead.back();
187     possiblyDead.pop_back();
188     DeleteDeadInstructionChains(I, possiblyDead);
189   }
190   
191   return MadeChange;
192 }
193
194 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
195 /// dependency is a store to a field of that structure
196 bool DSE::handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dep,
197                                        SetVector<Instruction*>& possiblyDead) {
198   TargetData &TD = getAnalysis<TargetData>();
199   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
200   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
201   
202   if (dep == MemoryDependenceAnalysis::None ||
203       dep == MemoryDependenceAnalysis::NonLocal)
204     return false;
205   
206   StoreInst* dependency = dyn_cast<StoreInst>(dep);
207   if (!dependency)
208     return false;
209   else if (dependency->isVolatile())
210     return false;
211   
212   Value* depPointer = dependency->getPointerOperand();
213   const Type* depType = dependency->getOperand(0)->getType();
214   unsigned depPointerSize = TD.getTypeStoreSize(depType);
215
216   // Check for aliasing
217   AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0U,
218                                           depPointer, depPointerSize);
219
220   if (A == AliasAnalysis::MustAlias) {
221     // Remove it!
222     MD.removeInstruction(dependency);
223
224     // DCE instructions only used to calculate that store
225     if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
226       possiblyDead.insert(D);
227     if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(1)))
228       possiblyDead.insert(D);
229
230     dependency->eraseFromParent();
231     NumFastStores++;
232     return true;
233   }
234   
235   return false;
236 }
237
238 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
239 /// function end block.  Ex:
240 /// %A = alloca i32
241 /// ...
242 /// store i32 1, i32* %A
243 /// ret void
244 bool DSE::handleEndBlock(BasicBlock& BB,
245                          SetVector<Instruction*>& possiblyDead) {
246   TargetData &TD = getAnalysis<TargetData>();
247   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
248   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
249   
250   bool MadeChange = false;
251   
252   // Pointers alloca'd in this function are dead in the end block
253   SmallPtrSet<Value*, 64> deadPointers;
254   
255   // Find all of the alloca'd pointers in the entry block
256   BasicBlock *Entry = BB.getParent()->begin();
257   for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
258     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
259       deadPointers.insert(AI);
260   for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
261        AE = BB.getParent()->arg_end(); AI != AE; ++AI)
262     if (AI->hasByValAttr())
263       deadPointers.insert(AI);
264   
265   // Scan the basic block backwards
266   for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
267     --BBI;
268     
269     // If we find a store whose pointer is dead...
270     if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
271       if (!S->isVolatile()) {
272         Value* pointerOperand = S->getPointerOperand();
273         // See through pointer-to-pointer bitcasts
274         TranslatePointerBitCasts(pointerOperand);
275       
276         // Alloca'd pointers or byval arguments (which are functionally like
277         // alloca's) are valid candidates for removal.
278         if (deadPointers.count(pointerOperand)) {
279           // Remove it!
280           MD.removeInstruction(S);
281         
282           // DCE instructions only used to calculate that store
283           if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
284             possiblyDead.insert(D);
285           if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
286             possiblyDead.insert(D);
287         
288           BBI++;
289           S->eraseFromParent();
290           NumFastStores++;
291           MadeChange = true;
292         }
293       }
294       
295       continue;
296     
297     // We can also remove memcpy's to local variables at the end of a function
298     } else if (MemCpyInst* M = dyn_cast<MemCpyInst>(BBI)) {
299       Value* dest = M->getDest();
300       TranslatePointerBitCasts(dest);
301       
302       if (deadPointers.count(dest)) {
303         MD.removeInstruction(M);
304         
305         // DCE instructions only used to calculate that memcpy
306         if (Instruction* D = dyn_cast<Instruction>(M->getSource()))
307           possiblyDead.insert(D);
308         if (Instruction* D = dyn_cast<Instruction>(M->getLength()))
309           possiblyDead.insert(D);
310         if (Instruction* D = dyn_cast<Instruction>(M->getRawDest()))
311           possiblyDead.insert(D);
312         
313         BBI++;
314         M->eraseFromParent();
315         NumFastOther++;
316         MadeChange = true;
317         
318         continue;
319       }
320       
321       // Because a memcpy is also a load, we can't skip it if we didn't remove it
322     }
323     
324     Value* killPointer = 0;
325     
326     // If we encounter a use of the pointer, it is no longer considered dead
327     if (LoadInst* L = dyn_cast<LoadInst>(BBI)) {
328       killPointer = L->getPointerOperand();
329     } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
330       killPointer = V->getOperand(0);
331     } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
332       deadPointers.erase(A);
333       continue;
334     } else if (CallSite::get(BBI).getInstruction() != 0) {
335       // If this call does not access memory, it can't
336       // be undeadifying any of our pointers.
337       CallSite CS = CallSite::get(BBI);
338       if (AA.doesNotAccessMemory(CS))
339         continue;
340       
341       unsigned modRef = 0;
342       unsigned other = 0;
343       
344       // Remove any pointers made undead by the call from the dead set
345       std::vector<Value*> dead;
346       for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
347            E = deadPointers.end(); I != E; ++I) {
348         // HACK: if we detect that our AA is imprecise, it's not
349         // worth it to scan the rest of the deadPointers set.  Just
350         // assume that the AA will return ModRef for everything, and
351         // go ahead and bail.
352         if (modRef >= 16 && other == 0) {
353           deadPointers.clear();
354           return MadeChange;
355         }
356
357         // Get size information for the alloca
358         unsigned pointerSize = ~0U;
359         if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
360           if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
361             pointerSize = C->getZExtValue() * \
362                           TD.getABITypeSize(A->getAllocatedType());
363         } else {
364           const PointerType* PT = cast<PointerType>(
365                                                  cast<Argument>(*I)->getType());
366           pointerSize = TD.getABITypeSize(PT->getElementType());
367         }
368
369         // See if the call site touches it
370         AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
371         
372         if (A == AliasAnalysis::ModRef)
373           modRef++;
374         else
375           other++;
376         
377         if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
378           dead.push_back(*I);
379       }
380
381       for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
382            I != E; ++I)
383         deadPointers.erase(*I);
384       
385       continue;
386     }
387     
388     if (!killPointer)
389       continue;
390     
391     TranslatePointerBitCasts(killPointer);
392     
393     // Deal with undead pointers
394     MadeChange |= RemoveUndeadPointers(killPointer, BBI,
395                                        deadPointers, possiblyDead);
396   }
397   
398   return MadeChange;
399 }
400
401 /// RemoveUndeadPointers - check for uses of a pointer that make it
402 /// undead when scanning for dead stores to alloca's.
403 bool DSE::RemoveUndeadPointers(Value* killPointer,
404                                 BasicBlock::iterator& BBI,
405                                 SmallPtrSet<Value*, 64>& deadPointers, 
406                                 SetVector<Instruction*>& possiblyDead) {
407   TargetData &TD = getAnalysis<TargetData>();
408   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
409   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
410                                   
411   // If the kill pointer can be easily reduced to an alloca,
412   // don't bother doing extraneous AA queries
413   if (deadPointers.count(killPointer)) {
414     deadPointers.erase(killPointer);
415     return false;
416   } else if (isa<GlobalValue>(killPointer)) {
417     // A global can't be in the dead pointer set
418     return false;
419   }
420   
421   bool MadeChange = false;
422   
423   std::vector<Value*> undead;
424     
425   for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
426       E = deadPointers.end(); I != E; ++I) {
427     // Get size information for the alloca
428     unsigned pointerSize = ~0U;
429     if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
430       if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
431         pointerSize = C->getZExtValue() * \
432                       TD.getABITypeSize(A->getAllocatedType());
433     } else {
434       const PointerType* PT = cast<PointerType>(
435                                                 cast<Argument>(*I)->getType());
436       pointerSize = TD.getABITypeSize(PT->getElementType());
437     }
438
439     // See if this pointer could alias it
440     AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
441                                             killPointer, ~0U);
442
443     // If it must-alias and a store, we can delete it
444     if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
445       StoreInst* S = cast<StoreInst>(BBI);
446
447       // Remove it!
448       MD.removeInstruction(S);
449
450       // DCE instructions only used to calculate that store
451       if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
452         possiblyDead.insert(D);
453       if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
454         possiblyDead.insert(D);
455
456       BBI++;
457       S->eraseFromParent();
458       NumFastStores++;
459       MadeChange = true;
460
461       continue;
462
463       // Otherwise, it is undead
464       } else if (A != AliasAnalysis::NoAlias)
465         undead.push_back(*I);
466   }
467
468   for (std::vector<Value*>::iterator I = undead.begin(), E = undead.end();
469        I != E; ++I)
470       deadPointers.erase(*I);
471   
472   return MadeChange;
473 }
474
475 /// DeleteDeadInstructionChains - takes an instruction and a setvector of
476 /// dead instructions.  If I is dead, it is erased, and its operands are
477 /// checked for deadness.  If they are dead, they are added to the dead
478 /// setvector.
479 void DSE::DeleteDeadInstructionChains(Instruction *I,
480                                       SetVector<Instruction*> &DeadInsts) {
481   // Instruction must be dead.
482   if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
483
484   // Let the memory dependence know
485   getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
486
487   // See if this made any operands dead.  We do it this way in case the
488   // instruction uses the same operand twice.  We don't want to delete a
489   // value then reference it.
490   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
491     if (I->getOperand(i)->hasOneUse())
492       if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
493         DeadInsts.insert(Op);      // Attempt to nuke it later.
494     
495     I->setOperand(i, 0);         // Drop from the operand list.
496   }
497
498   I->eraseFromParent();
499   ++NumFastOther;
500 }