Fix PR491 and testcase Transforms/DeadStoreElimination/2004-12-28-PartialStore.ll
[oota-llvm.git] / lib / Transforms / Scalar / DeadStoreElimination.cpp
1 //===- DeadStoreElimination.cpp - Dead Store Elimination ------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 #include "llvm/Transforms/Scalar.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/AliasSetTracker.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Transforms/Utils/Local.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/Statistic.h"
28 using namespace llvm;
29
30 namespace {
31   Statistic<> NumStores("dse", "Number of stores deleted");
32   Statistic<> NumOther ("dse", "Number of other instrs removed");
33
34   struct DSE : public FunctionPass {
35
36     virtual bool runOnFunction(Function &F) {
37       bool Changed = false;
38       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
39         Changed |= runOnBasicBlock(*I);
40       return Changed;
41     }
42     
43     bool runOnBasicBlock(BasicBlock &BB);
44     
45     void DeleteDeadInstructionChains(Instruction *I,
46                                      SetVector<Instruction*> &DeadInsts);
47
48     // getAnalysisUsage - We require post dominance frontiers (aka Control
49     // Dependence Graph)
50     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51       AU.setPreservesCFG();
52       AU.addRequired<TargetData>();
53       AU.addRequired<AliasAnalysis>();
54       AU.addPreserved<AliasAnalysis>();
55     }
56   };
57   RegisterOpt<DSE> X("dse", "Dead Store Elimination");
58 }
59
60 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
61
62 bool DSE::runOnBasicBlock(BasicBlock &BB) {
63   TargetData &TD = getAnalysis<TargetData>();
64   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
65   AliasSetTracker KillLocs(AA);
66
67   // If this block ends in a return, unwind, unreachable, and eventually
68   // tailcall, then all allocas are dead at its end.
69   if (BB.getTerminator()->getNumSuccessors() == 0) {
70     BasicBlock *Entry = BB.getParent()->begin();
71     for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
72       if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
73         unsigned Size = ~0U;
74         if (!AI->isArrayAllocation() &&
75             AI->getType()->getElementType()->isSized())
76           Size = TD.getTypeSize(AI->getType()->getElementType());
77         KillLocs.add(AI, Size);
78       }
79   }
80
81   // PotentiallyDeadInsts - Deleting dead stores from the program can make other
82   // instructions die if they were only used as operands to stores.  Keep track
83   // of the operands to stores so that we can try deleting them at the end of
84   // the traversal.
85   SetVector<Instruction*> PotentiallyDeadInsts;
86
87   bool MadeChange = false;
88   for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ) {
89     Instruction *I = --BBI;   // Keep moving iterator backwards
90     
91     // If this is a free instruction, it makes the free'd location dead!
92     if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
93       // Free instructions make any stores to the free'd location dead.
94       KillLocs.add(FI);
95       continue;
96     }
97
98     if (!isa<StoreInst>(I) || cast<StoreInst>(I)->isVolatile()) {
99       // If this is a non-store instruction, it makes everything referenced no
100       // longer killed.  Remove anything aliased from the alias set tracker.
101       KillLocs.remove(I);
102       continue;
103     }
104
105     // If this is a non-volatile store instruction, and if it is already in
106     // the stored location is already in the tracker, then this is a dead
107     // store.  We can just delete it here, but while we're at it, we also
108     // delete any trivially dead expression chains.
109     unsigned ValSize = TD.getTypeSize(I->getOperand(0)->getType());
110     Value *Ptr = I->getOperand(1);
111
112     if (AliasSet *AS = KillLocs.getAliasSetForPointerIfExists(Ptr, ValSize))
113       for (AliasSet::iterator ASI = AS->begin(), E = AS->end(); ASI != E; ++ASI)
114         if (ASI.getSize() >= ValSize &&  // Overwriting all of this store.
115             AA.alias(ASI.getPointer(), ASI.getSize(), Ptr, ValSize)
116                == AliasAnalysis::MustAlias) {
117           // If we found a must alias in the killed set, then this store really
118           // is dead.  Remember that the various operands of the store now have
119           // fewer users.  At the end we will see if we can delete any values
120           // that are dead as part of the store becoming dead.
121           if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(0)))
122             PotentiallyDeadInsts.insert(Op);
123           if (Instruction *Op = dyn_cast<Instruction>(Ptr))
124             PotentiallyDeadInsts.insert(Op);
125
126           // Delete it now.
127           ++BBI;                        // Don't invalidate iterator.
128           BB.getInstList().erase(I);    // Nuke the store!
129           ++NumStores;
130           MadeChange = true;
131           goto BigContinue;
132         }
133
134     // Otherwise, this is a non-dead store just add it to the set of dead
135     // locations.
136     KillLocs.add(cast<StoreInst>(I));
137   BigContinue:;
138   }
139
140   while (!PotentiallyDeadInsts.empty()) {
141     Instruction *I = PotentiallyDeadInsts.back();
142     PotentiallyDeadInsts.pop_back();
143     DeleteDeadInstructionChains(I, PotentiallyDeadInsts);
144   }
145   return MadeChange;
146 }
147
148 void DSE::DeleteDeadInstructionChains(Instruction *I,
149                                       SetVector<Instruction*> &DeadInsts) {
150   // Instruction must be dead.
151   if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
152
153   // Let the alias analysis know that we have nuked a value.
154   getAnalysis<AliasAnalysis>().deleteValue(I);
155
156   // See if this made any operands dead.  We do it this way in case the
157   // instruction uses the same operand twice.  We don't want to delete a
158   // value then reference it.
159   while (unsigned NumOps = I->getNumOperands()) {
160     Instruction *Op = dyn_cast<Instruction>(I->getOperand(NumOps-1));
161     I->op_erase(I->op_end()-1);         // Drop from the operand list.
162     
163     if (Op) DeadInsts.insert(Op);       // Attempt to nuke it later.
164   }
165   
166   I->getParent()->getInstList().erase(I);
167   ++NumOther;
168 }