blob: a85cf7b28b54a28e524e346cbed2443885353865 [file] [log] [blame]
Owen Andersone3590582007-08-02 18:11:11 +00001//===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===//
Owen Anderson5e72db32007-07-11 00:46:18 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Owen Anderson5e72db32007-07-11 00:46:18 +00007//
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
Owen Anderson10e52ed2007-08-01 06:36:51 +000018#define DEBUG_TYPE "dse"
Owen Anderson5e72db32007-07-11 00:46:18 +000019#include "llvm/Transforms/Scalar.h"
Owen Anderson32c4a052007-07-12 21:41:30 +000020#include "llvm/Constants.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000021#include "llvm/Function.h"
22#include "llvm/Instructions.h"
Owen Anderson48d37802008-01-29 06:18:36 +000023#include "llvm/IntrinsicInst.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000024#include "llvm/Pass.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000025#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/Statistic.h"
Owen Andersonaa071722007-07-11 23:19:17 +000027#include "llvm/Analysis/AliasAnalysis.h"
Owen Anderson3f338972008-07-28 16:14:26 +000028#include "llvm/Analysis/Dominators.h"
Victor Hernandezf390e042009-10-27 20:05:49 +000029#include "llvm/Analysis/MemoryBuiltins.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000030#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Owen Andersonaa071722007-07-11 23:19:17 +000031#include "llvm/Target/TargetData.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000032#include "llvm/Transforms/Utils/Local.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000033using namespace llvm;
34
35STATISTIC(NumFastStores, "Number of stores deleted");
36STATISTIC(NumFastOther , "Number of other instrs removed");
37
38namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000039 struct DSE : public FunctionPass {
Dan Gohman67243a42009-07-24 18:13:53 +000040 TargetData *TD;
41
Owen Anderson5e72db32007-07-11 00:46:18 +000042 static char ID; // Pass identification, replacement for typeid
Dan Gohmana79db302008-09-04 17:05:41 +000043 DSE() : FunctionPass(&ID) {}
Owen Anderson5e72db32007-07-11 00:46:18 +000044
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 }
Chris Lattnerde04e112008-11-29 01:43:36 +000051
Owen Anderson5e72db32007-07-11 00:46:18 +000052 bool runOnBasicBlock(BasicBlock &BB);
Victor Hernandeze2971492009-10-24 04:23:03 +000053 bool handleFreeWithNonTrivialDependency(Instruction *F, MemDepResult Dep);
Chris Lattner1adb6752008-11-28 00:27:14 +000054 bool handleEndBlock(BasicBlock &BB);
Chris Lattner57e91ea2008-12-06 00:53:22 +000055 bool RemoveUndeadPointers(Value* Ptr, uint64_t killPointerSize,
Owen Anderson32c4a052007-07-12 21:41:30 +000056 BasicBlock::iterator& BBI,
Chris Lattner1adb6752008-11-28 00:27:14 +000057 SmallPtrSet<Value*, 64>& deadPointers);
58 void DeleteDeadInstruction(Instruction *I,
59 SmallPtrSet<Value*, 64> *deadPointers = 0);
60
Owen Anderson5e72db32007-07-11 00:46:18 +000061
62 // getAnalysisUsage - We require post dominance frontiers (aka Control
63 // Dependence Graph)
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65 AU.setPreservesCFG();
Owen Anderson3f338972008-07-28 16:14:26 +000066 AU.addRequired<DominatorTree>();
Owen Andersonaa071722007-07-11 23:19:17 +000067 AU.addRequired<AliasAnalysis>();
Owen Anderson5e72db32007-07-11 00:46:18 +000068 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson3f338972008-07-28 16:14:26 +000069 AU.addPreserved<DominatorTree>();
Owen Andersonaa071722007-07-11 23:19:17 +000070 AU.addPreserved<AliasAnalysis>();
Owen Anderson5e72db32007-07-11 00:46:18 +000071 AU.addPreserved<MemoryDependenceAnalysis>();
72 }
73 };
Owen Anderson5e72db32007-07-11 00:46:18 +000074}
75
Dan Gohmand78c4002008-05-13 00:00:25 +000076char DSE::ID = 0;
77static RegisterPass<DSE> X("dse", "Dead Store Elimination");
78
Owen Anderson10e52ed2007-08-01 06:36:51 +000079FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
Owen Anderson5e72db32007-07-11 00:46:18 +000080
Nick Lewycky90271472009-11-10 06:46:40 +000081/// doesClobberMemory - Does this instruction clobber (write without reading)
82/// some memory?
83static bool doesClobberMemory(Instruction *I) {
84 if (isa<StoreInst>(I))
85 return true;
86 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
87 switch (II->getIntrinsicID()) {
88 default: return false;
89 case Intrinsic::memset: case Intrinsic::memmove: case Intrinsic::memcpy:
90 case Intrinsic::lifetime_end: return true;
91 }
92 }
93 return false;
94}
95
96/// isElidable - If the memory this instruction and the memory it writes to is
97/// unused, may we delete this instrtction?
98static bool isElidable(Instruction *I) {
99 assert(doesClobberMemory(I));
100 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
101 return II->getIntrinsicID() != Intrinsic::lifetime_end;
102 if (StoreInst *SI = dyn_cast<StoreInst>(I))
103 return !SI->isVolatile();
104 return true;
105}
106
107/// getPointerOperand - Return the pointer that is being clobbered.
108static Value *getPointerOperand(Instruction *I) {
109 assert(doesClobberMemory(I));
110 if (StoreInst *SI = dyn_cast<StoreInst>(I))
111 return SI->getPointerOperand();
112 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
113 return MI->getOperand(1);
114 assert(cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::lifetime_end);
115 return cast<IntrinsicInst>(I)->getOperand(2);
116}
117
118/// getStoreSize - Return the length in bytes of the write by the clobbering
119/// instruction. If variable or unknown, returns -1.
120static unsigned getStoreSize(Instruction *I, const TargetData *TD) {
121 assert(doesClobberMemory(I));
122 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
123 if (!TD) return -1u;
124 const PointerType *PTy =
125 cast<PointerType>(SI->getPointerOperand()->getType());
126 return TD->getTypeStoreSize(PTy->getElementType());
127 }
128
129 Value *Len;
130 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
131 Len = MI->getLength();
132 } else {
133 IntrinsicInst *II = cast<IntrinsicInst>(I);
134 assert(II->getIntrinsicID() == Intrinsic::lifetime_end);
135 Len = II->getOperand(0);
136 }
137 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len))
138 if (!LenCI->isAllOnesValue())
139 return LenCI->getZExtValue();
140 return -1u;
141}
142
143/// isStoreAtLeastAsWideAs - Return true if the size of the store in I1 is
144/// greater than or equal to the store in I2. This returns false if we don't
145/// know.
Chris Lattnera0906272009-11-04 23:20:12 +0000146///
Nick Lewycky90271472009-11-10 06:46:40 +0000147static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2,
148 const TargetData *TD) {
149 const Type *I1Ty = getPointerOperand(I1)->getType();
150 const Type *I2Ty = getPointerOperand(I2)->getType();
Chris Lattnera0906272009-11-04 23:20:12 +0000151
152 // Exactly the same type, must have exactly the same size.
Nick Lewycky90271472009-11-10 06:46:40 +0000153 if (I1Ty == I2Ty) return true;
Chris Lattnera0906272009-11-04 23:20:12 +0000154
Nick Lewycky90271472009-11-10 06:46:40 +0000155 int I1Size = getStoreSize(I1, TD);
156 int I2Size = getStoreSize(I2, TD);
Chris Lattnera0906272009-11-04 23:20:12 +0000157
Nick Lewycky90271472009-11-10 06:46:40 +0000158 return I1Size != -1 && I2Size != -1 && I1Size >= I2Size;
Chris Lattnera0906272009-11-04 23:20:12 +0000159}
160
Owen Anderson10e52ed2007-08-01 06:36:51 +0000161bool DSE::runOnBasicBlock(BasicBlock &BB) {
Owen Anderson5e72db32007-07-11 00:46:18 +0000162 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Dan Gohman67243a42009-07-24 18:13:53 +0000163 TD = getAnalysisIfAvailable<TargetData>();
Owen Anderson2ed651a2007-11-01 05:29:16 +0000164
Owen Anderson5e72db32007-07-11 00:46:18 +0000165 bool MadeChange = false;
166
Chris Lattner49162672009-09-02 06:31:02 +0000167 // Do a top-down walk on the BB.
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000168 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
169 Instruction *Inst = BBI++;
170
Dan Gohman67243a42009-07-24 18:13:53 +0000171 // If we find a store or a free, get its memory dependence.
Nick Lewycky90271472009-11-10 06:46:40 +0000172 if (!doesClobberMemory(Inst) && !isFreeCall(Inst))
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000173 continue;
Chris Lattner5df5b4c2008-12-07 00:25:15 +0000174
Chris Lattner57e91ea2008-12-06 00:53:22 +0000175 MemDepResult InstDep = MD.getDependency(Inst);
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000176
Chris Lattner57e91ea2008-12-06 00:53:22 +0000177 // Ignore non-local stores.
178 // FIXME: cross-block DSE would be fun. :)
179 if (InstDep.isNonLocal()) continue;
180
181 // Handle frees whose dependencies are non-trivial.
Victor Hernandezde5ad422009-10-26 23:43:48 +0000182 if (isFreeCall(Inst)) {
Victor Hernandeze2971492009-10-24 04:23:03 +0000183 MadeChange |= handleFreeWithNonTrivialDependency(Inst, InstDep);
Chris Lattner57e91ea2008-12-06 00:53:22 +0000184 continue;
185 }
186
Chris Lattner57e91ea2008-12-06 00:53:22 +0000187 // If not a definite must-alias dependency, ignore it.
188 if (!InstDep.isDef())
189 continue;
190
191 // If this is a store-store dependence, then the previous store is dead so
192 // long as this store is at least as big as it.
Nick Lewycky90271472009-11-10 06:46:40 +0000193 if (doesClobberMemory(InstDep.getInst())) {
194 Instruction *DepStore = InstDep.getInst();
195 if (isStoreAtLeastAsWideAs(Inst, DepStore, TD) &&
196 isElidable(DepStore)) {
Chris Lattner1adb6752008-11-28 00:27:14 +0000197 // Delete the store and now-dead instructions that feed it.
Chris Lattner57e91ea2008-12-06 00:53:22 +0000198 DeleteDeadInstruction(DepStore);
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000199 NumFastStores++;
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000200 MadeChange = true;
Chris Lattner49162672009-09-02 06:31:02 +0000201
202 // DeleteDeadInstruction can delete the current instruction in loop
203 // cases, reset BBI.
204 BBI = Inst;
Chris Lattner8c5ff512008-11-29 20:29:04 +0000205 if (BBI != BB.begin())
Chris Lattnerf3f6a802008-11-28 22:50:08 +0000206 --BBI;
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000207 continue;
208 }
Nick Lewycky90271472009-11-10 06:46:40 +0000209 }
210
211 if (!isElidable(Inst))
212 continue;
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000213
Chris Lattner57e91ea2008-12-06 00:53:22 +0000214 // If we're storing the same value back to a pointer that we just
215 // loaded from, then the store can be removed.
Nick Lewycky90271472009-11-10 06:46:40 +0000216 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
217 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
218 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
219 SI->getOperand(0) == DepLoad) {
220 // DeleteDeadInstruction can delete the current instruction. Save BBI
221 // in case we need it.
222 WeakVH NextInst(BBI);
223
224 DeleteDeadInstruction(SI);
225
226 if (NextInst == 0) // Next instruction deleted.
227 BBI = BB.begin();
228 else if (BBI != BB.begin()) // Revisit this instruction if possible.
229 --BBI;
230 NumFastStores++;
231 MadeChange = true;
232 continue;
233 }
Chris Lattner0e3d6332008-12-05 21:04:20 +0000234 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000235 }
Owen Anderson2b2bd282009-10-28 07:05:35 +0000236
237 // If this is a lifetime end marker, we can throw away the store.
Nick Lewycky90271472009-11-10 06:46:40 +0000238 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(InstDep.getInst())) {
Owen Anderson2b2bd282009-10-28 07:05:35 +0000239 if (II->getIntrinsicID() == Intrinsic::lifetime_end) {
240 // Delete the store and now-dead instructions that feed it.
241 // DeleteDeadInstruction can delete the current instruction. Save BBI
242 // in case we need it.
243 WeakVH NextInst(BBI);
244
Nick Lewycky90271472009-11-10 06:46:40 +0000245 DeleteDeadInstruction(Inst);
Owen Anderson2b2bd282009-10-28 07:05:35 +0000246
247 if (NextInst == 0) // Next instruction deleted.
248 BBI = BB.begin();
249 else if (BBI != BB.begin()) // Revisit this instruction if possible.
250 --BBI;
251 NumFastStores++;
252 MadeChange = true;
253 continue;
254 }
255 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000256 }
257
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000258 // If this block ends in a return, unwind, or unreachable, all allocas are
259 // dead at its end, which means stores to them are also dead.
Owen Anderson32c4a052007-07-12 21:41:30 +0000260 if (BB.getTerminator()->getNumSuccessors() == 0)
Chris Lattner1adb6752008-11-28 00:27:14 +0000261 MadeChange |= handleEndBlock(BB);
Owen Anderson5e72db32007-07-11 00:46:18 +0000262
263 return MadeChange;
264}
265
Owen Andersonaa071722007-07-11 23:19:17 +0000266/// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
Chris Lattner1adb6752008-11-28 00:27:14 +0000267/// dependency is a store to a field of that structure.
Victor Hernandeze2971492009-10-24 04:23:03 +0000268bool DSE::handleFreeWithNonTrivialDependency(Instruction *F, MemDepResult Dep) {
Owen Andersonaa071722007-07-11 23:19:17 +0000269 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Owen Andersonaa071722007-07-11 23:19:17 +0000270
Nick Lewycky90271472009-11-10 06:46:40 +0000271 Instruction *Dependency = Dep.getInst();
272 if (!Dependency || !doesClobberMemory(Dependency) || !isElidable(Dependency))
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000273 return false;
Owen Andersond4451de2007-07-12 18:08:51 +0000274
Nick Lewycky90271472009-11-10 06:46:40 +0000275 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000276
Chris Lattner57e91ea2008-12-06 00:53:22 +0000277 // Check for aliasing.
Victor Hernandezde5ad422009-10-26 23:43:48 +0000278 if (AA.alias(F->getOperand(1), 1, DepPointer, 1) !=
Chris Lattner57e91ea2008-12-06 00:53:22 +0000279 AliasAnalysis::MustAlias)
Chris Lattner1adb6752008-11-28 00:27:14 +0000280 return false;
Owen Andersonaa071722007-07-11 23:19:17 +0000281
Chris Lattner1adb6752008-11-28 00:27:14 +0000282 // DCE instructions only used to calculate that store
Chris Lattner57e91ea2008-12-06 00:53:22 +0000283 DeleteDeadInstruction(Dependency);
Chris Lattner1adb6752008-11-28 00:27:14 +0000284 NumFastStores++;
285 return true;
Owen Andersonaa071722007-07-11 23:19:17 +0000286}
287
Owen Andersone3590582007-08-02 18:11:11 +0000288/// handleEndBlock - Remove dead stores to stack-allocated locations in the
Owen Anderson52aaabf2007-08-08 17:50:09 +0000289/// function end block. Ex:
290/// %A = alloca i32
291/// ...
292/// store i32 1, i32* %A
293/// ret void
Chris Lattner1adb6752008-11-28 00:27:14 +0000294bool DSE::handleEndBlock(BasicBlock &BB) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000295 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Owen Anderson32c4a052007-07-12 21:41:30 +0000296
297 bool MadeChange = false;
298
299 // Pointers alloca'd in this function are dead in the end block
Owen Anderson48d37802008-01-29 06:18:36 +0000300 SmallPtrSet<Value*, 64> deadPointers;
Owen Anderson32c4a052007-07-12 21:41:30 +0000301
Chris Lattner1adb6752008-11-28 00:27:14 +0000302 // Find all of the alloca'd pointers in the entry block.
Owen Anderson32c4a052007-07-12 21:41:30 +0000303 BasicBlock *Entry = BB.getParent()->begin();
304 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
305 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
306 deadPointers.insert(AI);
Chris Lattner1adb6752008-11-28 00:27:14 +0000307
308 // Treat byval arguments the same, stores to them are dead at the end of the
309 // function.
Owen Anderson48d37802008-01-29 06:18:36 +0000310 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
311 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
312 if (AI->hasByValAttr())
313 deadPointers.insert(AI);
Owen Anderson32c4a052007-07-12 21:41:30 +0000314
315 // Scan the basic block backwards
316 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
317 --BBI;
318
Chris Lattner1adb6752008-11-28 00:27:14 +0000319 // If we find a store whose pointer is dead.
Nick Lewycky90271472009-11-10 06:46:40 +0000320 if (doesClobberMemory(BBI)) {
321 if (isElidable(BBI)) {
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000322 // See through pointer-to-pointer bitcasts
Nick Lewycky90271472009-11-10 06:46:40 +0000323 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
Duncan Sandsd65a4da2008-10-01 15:25:41 +0000324
Owen Anderson6af19fd2008-01-25 10:10:33 +0000325 // Alloca'd pointers or byval arguments (which are functionally like
326 // alloca's) are valid candidates for removal.
Owen Anderson48d37802008-01-29 06:18:36 +0000327 if (deadPointers.count(pointerOperand)) {
Chris Lattner1adb6752008-11-28 00:27:14 +0000328 // DCE instructions only used to calculate that store.
Nick Lewycky90271472009-11-10 06:46:40 +0000329 Instruction *Dead = BBI;
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000330 BBI++;
Nick Lewycky90271472009-11-10 06:46:40 +0000331 DeleteDeadInstruction(Dead, &deadPointers);
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000332 NumFastStores++;
333 MadeChange = true;
Nick Lewycky90271472009-11-10 06:46:40 +0000334 continue;
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000335 }
Owen Anderson32c4a052007-07-12 21:41:30 +0000336 }
Owen Anderson52aaabf2007-08-08 17:50:09 +0000337
Nick Lewycky90271472009-11-10 06:46:40 +0000338 // Because a memcpy or memmove is also a load, we can't skip it if we
339 // didn't remove it.
340 if (!isa<MemTransferInst>(BBI))
Owen Anderson48d37802008-01-29 06:18:36 +0000341 continue;
Owen Anderson52aaabf2007-08-08 17:50:09 +0000342 }
343
344 Value* killPointer = 0;
Owen Andersona82c9932008-02-04 04:53:00 +0000345 uint64_t killPointerSize = ~0UL;
Owen Anderson32c4a052007-07-12 21:41:30 +0000346
347 // If we encounter a use of the pointer, it is no longer considered dead
Chris Lattner1adb6752008-11-28 00:27:14 +0000348 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
Nate Begeman53c5c622008-05-13 01:48:26 +0000349 // However, if this load is unused and not volatile, we can go ahead and
350 // remove it, and not have to worry about it making our pointer undead!
Dan Gohman8cb19d92008-04-28 19:51:27 +0000351 if (L->use_empty() && !L->isVolatile()) {
Owen Anderson4e4b1162008-01-30 01:24:47 +0000352 BBI++;
Chris Lattner1adb6752008-11-28 00:27:14 +0000353 DeleteDeadInstruction(L, &deadPointers);
Owen Anderson4e4b1162008-01-30 01:24:47 +0000354 NumFastOther++;
355 MadeChange = true;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000356 continue;
357 }
358
Owen Anderson32c4a052007-07-12 21:41:30 +0000359 killPointer = L->getPointerOperand();
Owen Anderson32c4a052007-07-12 21:41:30 +0000360 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
361 killPointer = V->getOperand(0);
Nick Lewycky90271472009-11-10 06:46:40 +0000362 } else if (isa<MemTransferInst>(BBI) &&
363 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
364 killPointer = cast<MemTransferInst>(BBI)->getSource();
Owen Andersona82c9932008-02-04 04:53:00 +0000365 killPointerSize = cast<ConstantInt>(
Nick Lewycky90271472009-11-10 06:46:40 +0000366 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
Owen Anderson32c4a052007-07-12 21:41:30 +0000367 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
368 deadPointers.erase(A);
Owen Anderson4e4b1162008-01-30 01:24:47 +0000369
370 // Dead alloca's can be DCE'd when we reach them
Nick Lewycky6b016702008-01-30 08:01:28 +0000371 if (A->use_empty()) {
Owen Anderson4e4b1162008-01-30 01:24:47 +0000372 BBI++;
Chris Lattner1adb6752008-11-28 00:27:14 +0000373 DeleteDeadInstruction(A, &deadPointers);
Owen Anderson4e4b1162008-01-30 01:24:47 +0000374 NumFastOther++;
375 MadeChange = true;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000376 }
377
Owen Anderson32c4a052007-07-12 21:41:30 +0000378 continue;
379 } else if (CallSite::get(BBI).getInstruction() != 0) {
Owen Anderson50df9682007-08-08 17:58:56 +0000380 // If this call does not access memory, it can't
381 // be undeadifying any of our pointers.
382 CallSite CS = CallSite::get(BBI);
Duncan Sands68b6f502007-12-01 07:51:45 +0000383 if (AA.doesNotAccessMemory(CS))
Owen Anderson50df9682007-08-08 17:58:56 +0000384 continue;
385
Owen Andersonddf4aee2007-08-08 18:38:28 +0000386 unsigned modRef = 0;
387 unsigned other = 0;
388
Owen Anderson32c4a052007-07-12 21:41:30 +0000389 // Remove any pointers made undead by the call from the dead set
Owen Anderson48d37802008-01-29 06:18:36 +0000390 std::vector<Value*> dead;
391 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
Owen Anderson32c4a052007-07-12 21:41:30 +0000392 E = deadPointers.end(); I != E; ++I) {
Owen Andersonddf4aee2007-08-08 18:38:28 +0000393 // HACK: if we detect that our AA is imprecise, it's not
394 // worth it to scan the rest of the deadPointers set. Just
395 // assume that the AA will return ModRef for everything, and
396 // go ahead and bail.
397 if (modRef >= 16 && other == 0) {
398 deadPointers.clear();
399 return MadeChange;
400 }
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000401
Owen Anderson32c4a052007-07-12 21:41:30 +0000402 // Get size information for the alloca
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000403 unsigned pointerSize = ~0U;
Dan Gohman67243a42009-07-24 18:13:53 +0000404 if (TD) {
405 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
406 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
407 pointerSize = C->getZExtValue() *
408 TD->getTypeAllocSize(A->getAllocatedType());
409 } else {
410 const PointerType* PT = cast<PointerType>(
411 cast<Argument>(*I)->getType());
412 pointerSize = TD->getTypeAllocSize(PT->getElementType());
413 }
Owen Anderson48d37802008-01-29 06:18:36 +0000414 }
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000415
Owen Anderson32c4a052007-07-12 21:41:30 +0000416 // See if the call site touches it
Owen Anderson50df9682007-08-08 17:58:56 +0000417 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
Owen Andersonddf4aee2007-08-08 18:38:28 +0000418
419 if (A == AliasAnalysis::ModRef)
420 modRef++;
421 else
422 other++;
423
Owen Anderson9c9ef212007-07-13 18:26:26 +0000424 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
Owen Anderson32c4a052007-07-12 21:41:30 +0000425 dead.push_back(*I);
426 }
427
Owen Anderson48d37802008-01-29 06:18:36 +0000428 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
Owen Anderson32c4a052007-07-12 21:41:30 +0000429 I != E; ++I)
Owen Anderson48d37802008-01-29 06:18:36 +0000430 deadPointers.erase(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000431
432 continue;
Chris Lattner1adb6752008-11-28 00:27:14 +0000433 } else if (isInstructionTriviallyDead(BBI)) {
Owen Anderson4e4b1162008-01-30 01:24:47 +0000434 // For any non-memory-affecting non-terminators, DCE them as we reach them
Chris Lattner1adb6752008-11-28 00:27:14 +0000435 Instruction *Inst = BBI;
436 BBI++;
437 DeleteDeadInstruction(Inst, &deadPointers);
438 NumFastOther++;
439 MadeChange = true;
440 continue;
Owen Anderson32c4a052007-07-12 21:41:30 +0000441 }
442
443 if (!killPointer)
444 continue;
Duncan Sandsd65a4da2008-10-01 15:25:41 +0000445
446 killPointer = killPointer->getUnderlyingObject();
447
Owen Anderson32c4a052007-07-12 21:41:30 +0000448 // Deal with undead pointers
Owen Andersona82c9932008-02-04 04:53:00 +0000449 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
Chris Lattner1adb6752008-11-28 00:27:14 +0000450 deadPointers);
Owen Anderson32c4a052007-07-12 21:41:30 +0000451 }
452
453 return MadeChange;
454}
455
Owen Andersonddf4aee2007-08-08 18:38:28 +0000456/// RemoveUndeadPointers - check for uses of a pointer that make it
457/// undead when scanning for dead stores to alloca's.
Owen Andersona82c9932008-02-04 04:53:00 +0000458bool DSE::RemoveUndeadPointers(Value* killPointer, uint64_t killPointerSize,
Chris Lattner1adb6752008-11-28 00:27:14 +0000459 BasicBlock::iterator &BBI,
460 SmallPtrSet<Value*, 64>& deadPointers) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000461 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Owen Anderson32c4a052007-07-12 21:41:30 +0000462
Owen Andersonddf4aee2007-08-08 18:38:28 +0000463 // If the kill pointer can be easily reduced to an alloca,
Chris Lattner1adb6752008-11-28 00:27:14 +0000464 // don't bother doing extraneous AA queries.
Owen Anderson48d37802008-01-29 06:18:36 +0000465 if (deadPointers.count(killPointer)) {
466 deadPointers.erase(killPointer);
Owen Andersonddf4aee2007-08-08 18:38:28 +0000467 return false;
468 }
469
Chris Lattner1adb6752008-11-28 00:27:14 +0000470 // A global can't be in the dead pointer set.
471 if (isa<GlobalValue>(killPointer))
472 return false;
473
Owen Anderson32c4a052007-07-12 21:41:30 +0000474 bool MadeChange = false;
475
Chris Lattner1adb6752008-11-28 00:27:14 +0000476 SmallVector<Value*, 16> undead;
Owen Anderson32c4a052007-07-12 21:41:30 +0000477
Owen Anderson48d37802008-01-29 06:18:36 +0000478 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
Owen Anderson32c4a052007-07-12 21:41:30 +0000479 E = deadPointers.end(); I != E; ++I) {
Chris Lattner1adb6752008-11-28 00:27:14 +0000480 // Get size information for the alloca.
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000481 unsigned pointerSize = ~0U;
Dan Gohman67243a42009-07-24 18:13:53 +0000482 if (TD) {
483 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
484 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
485 pointerSize = C->getZExtValue() *
486 TD->getTypeAllocSize(A->getAllocatedType());
487 } else {
488 const PointerType* PT = cast<PointerType>(cast<Argument>(*I)->getType());
489 pointerSize = TD->getTypeAllocSize(PT->getElementType());
490 }
Owen Anderson48d37802008-01-29 06:18:36 +0000491 }
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000492
Owen Anderson32c4a052007-07-12 21:41:30 +0000493 // See if this pointer could alias it
Owen Andersone3590582007-08-02 18:11:11 +0000494 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
Owen Andersona82c9932008-02-04 04:53:00 +0000495 killPointer, killPointerSize);
Owen Anderson32c4a052007-07-12 21:41:30 +0000496
497 // If it must-alias and a store, we can delete it
498 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
499 StoreInst* S = cast<StoreInst>(BBI);
500
501 // Remove it!
Owen Anderson32c4a052007-07-12 21:41:30 +0000502 BBI++;
Chris Lattner1adb6752008-11-28 00:27:14 +0000503 DeleteDeadInstruction(S, &deadPointers);
Owen Anderson32c4a052007-07-12 21:41:30 +0000504 NumFastStores++;
505 MadeChange = true;
506
507 continue;
508
509 // Otherwise, it is undead
Chris Lattner1adb6752008-11-28 00:27:14 +0000510 } else if (A != AliasAnalysis::NoAlias)
511 undead.push_back(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000512 }
513
Chris Lattner1adb6752008-11-28 00:27:14 +0000514 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
Owen Anderson32c4a052007-07-12 21:41:30 +0000515 I != E; ++I)
Owen Anderson48d37802008-01-29 06:18:36 +0000516 deadPointers.erase(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000517
518 return MadeChange;
519}
520
Chris Lattner1adb6752008-11-28 00:27:14 +0000521/// DeleteDeadInstruction - Delete this instruction. Before we do, go through
522/// and zero out all the operands of this instruction. If any of them become
523/// dead, delete them and the computation tree that feeds them.
524///
525/// If ValueSet is non-null, remove any deleted instructions from it as well.
526///
527void DSE::DeleteDeadInstruction(Instruction *I,
528 SmallPtrSet<Value*, 64> *ValueSet) {
529 SmallVector<Instruction*, 32> NowDeadInsts;
530
531 NowDeadInsts.push_back(I);
532 --NumFastOther;
Owen Anderson5e72db32007-07-11 00:46:18 +0000533
Chris Lattner1adb6752008-11-28 00:27:14 +0000534 // Before we touch this instruction, remove it from memdep!
535 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
536 while (!NowDeadInsts.empty()) {
537 Instruction *DeadInst = NowDeadInsts.back();
538 NowDeadInsts.pop_back();
Owen Andersonbf971aa2007-07-11 19:03:09 +0000539
Chris Lattner1adb6752008-11-28 00:27:14 +0000540 ++NumFastOther;
541
542 // This instruction is dead, zap it, in stages. Start by removing it from
543 // MemDep, which needs to know the operands and needs it to be in the
544 // function.
545 MDA.removeInstruction(DeadInst);
546
547 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
548 Value *Op = DeadInst->getOperand(op);
549 DeadInst->setOperand(op, 0);
550
551 // If this operand just became dead, add it to the NowDeadInsts list.
552 if (!Op->use_empty()) continue;
553
554 if (Instruction *OpI = dyn_cast<Instruction>(Op))
555 if (isInstructionTriviallyDead(OpI))
556 NowDeadInsts.push_back(OpI);
557 }
558
559 DeadInst->eraseFromParent();
560
561 if (ValueSet) ValueSet->erase(DeadInst);
Owen Anderson5e72db32007-07-11 00:46:18 +0000562 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000563}