blob: e1d89cb910931feaa954146041356dc0320a7a65 [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
Owen Anderson6c18d1a2010-10-19 17:21:58 +000043 DSE() : FunctionPass(ID) {
44 initializeDSEPass(*PassRegistry::getPassRegistry());
45 }
Owen Anderson5e72db32007-07-11 00:46:18 +000046
47 virtual bool runOnFunction(Function &F) {
48 bool Changed = false;
Chris Lattnerc053cbb2010-02-11 05:11:54 +000049
50 DominatorTree &DT = getAnalysis<DominatorTree>();
51
Owen Anderson5e72db32007-07-11 00:46:18 +000052 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
Chris Lattnerc053cbb2010-02-11 05:11:54 +000053 // 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);
Owen Anderson5e72db32007-07-11 00:46:18 +000057 return Changed;
58 }
Chris Lattnerde04e112008-11-29 01:43:36 +000059
Owen Anderson5e72db32007-07-11 00:46:18 +000060 bool runOnBasicBlock(BasicBlock &BB);
Gabor Greif07e92842010-06-25 07:40:32 +000061 bool handleFreeWithNonTrivialDependency(const CallInst *F,
Dan Gohmand4b7fff2010-11-12 02:19:17 +000062 Instruction *Inst,
Gabor Greif07e92842010-06-25 07:40:32 +000063 MemDepResult Dep);
Chris Lattner1adb6752008-11-28 00:27:14 +000064 bool handleEndBlock(BasicBlock &BB);
Dan Gohmanf372cf82010-10-19 22:54:46 +000065 bool RemoveUndeadPointers(Value *Ptr, uint64_t killPointerSize,
Nick Lewycky475d3d12010-01-03 04:39:07 +000066 BasicBlock::iterator &BBI,
67 SmallPtrSet<Value*, 64> &deadPointers);
Chris Lattner1adb6752008-11-28 00:27:14 +000068 void DeleteDeadInstruction(Instruction *I,
69 SmallPtrSet<Value*, 64> *deadPointers = 0);
70
Owen Anderson5e72db32007-07-11 00:46:18 +000071
72 // getAnalysisUsage - We require post dominance frontiers (aka Control
73 // Dependence Graph)
74 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.setPreservesCFG();
Owen Anderson3f338972008-07-28 16:14:26 +000076 AU.addRequired<DominatorTree>();
Owen Andersonaa071722007-07-11 23:19:17 +000077 AU.addRequired<AliasAnalysis>();
Owen Anderson5e72db32007-07-11 00:46:18 +000078 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson3f338972008-07-28 16:14:26 +000079 AU.addPreserved<DominatorTree>();
Owen Anderson5e72db32007-07-11 00:46:18 +000080 AU.addPreserved<MemoryDependenceAnalysis>();
81 }
Nick Lewycky475d3d12010-01-03 04:39:07 +000082
Dan Gohmanf372cf82010-10-19 22:54:46 +000083 uint64_t getPointerSize(Value *V) const;
Owen Anderson5e72db32007-07-11 00:46:18 +000084 };
Owen Anderson5e72db32007-07-11 00:46:18 +000085}
86
Dan Gohmand78c4002008-05-13 00:00:25 +000087char DSE::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000088INITIALIZE_PASS_BEGIN(DSE, "dse", "Dead Store Elimination", false, false)
89INITIALIZE_PASS_DEPENDENCY(DominatorTree)
90INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
91INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
92INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000093
Owen Anderson10e52ed2007-08-01 06:36:51 +000094FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
Owen Anderson5e72db32007-07-11 00:46:18 +000095
Nick Lewycky90271472009-11-10 06:46:40 +000096/// doesClobberMemory - Does this instruction clobber (write without reading)
97/// some memory?
98static bool doesClobberMemory(Instruction *I) {
99 if (isa<StoreInst>(I))
100 return true;
101 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
102 switch (II->getIntrinsicID()) {
Chris Lattner2764b4d2009-12-02 06:35:55 +0000103 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;
Nick Lewycky90271472009-11-10 06:46:40 +0000111 }
112 }
113 return false;
114}
115
Duncan Sands1925d3a2009-11-10 13:49:50 +0000116/// isElidable - If the value of this instruction and the memory it writes to is
Nick Lewycky90271472009-11-10 06:46:40 +0000117/// unused, may we delete this instrtction?
118static 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.
128static 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))
Gabor Greif91f95892010-06-24 12:03:56 +0000133 return MI->getArgOperand(0);
134
135 IntrinsicInst *II = cast<IntrinsicInst>(I);
136 switch (II->getIntrinsicID()) {
Chris Lattner2764b4d2009-12-02 06:35:55 +0000137 default: assert(false && "Unexpected intrinsic!");
138 case Intrinsic::init_trampoline:
Gabor Greif91f95892010-06-24 12:03:56 +0000139 return II->getArgOperand(0);
Eric Christopher7258dcd2010-04-16 23:37:20 +0000140 case Intrinsic::lifetime_end:
Gabor Greif91f95892010-06-24 12:03:56 +0000141 return II->getArgOperand(1);
Duncan Sands1925d3a2009-11-10 13:49:50 +0000142 }
Nick Lewycky90271472009-11-10 06:46:40 +0000143}
144
145/// getStoreSize - Return the length in bytes of the write by the clobbering
Dan Gohmanf372cf82010-10-19 22:54:46 +0000146/// instruction. If variable or unknown, returns AliasAnalysis::UnknownSize.
147static uint64_t getStoreSize(Instruction *I, const TargetData *TD) {
Nick Lewycky90271472009-11-10 06:46:40 +0000148 assert(doesClobberMemory(I));
149 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Dan Gohmanf372cf82010-10-19 22:54:46 +0000150 if (!TD) return AliasAnalysis::UnknownSize;
Nick Lewycky5b3def92009-11-10 07:00:43 +0000151 return TD->getTypeStoreSize(SI->getOperand(0)->getType());
Nick Lewycky90271472009-11-10 06:46:40 +0000152 }
153
154 Value *Len;
155 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
156 Len = MI->getLength();
157 } else {
Gabor Greif91f95892010-06-24 12:03:56 +0000158 IntrinsicInst *II = cast<IntrinsicInst>(I);
159 switch (II->getIntrinsicID()) {
Chris Lattner2764b4d2009-12-02 06:35:55 +0000160 default: assert(false && "Unexpected intrinsic!");
161 case Intrinsic::init_trampoline:
Dan Gohmanf372cf82010-10-19 22:54:46 +0000162 return AliasAnalysis::UnknownSize;
Chris Lattner2764b4d2009-12-02 06:35:55 +0000163 case Intrinsic::lifetime_end:
Gabor Greif91f95892010-06-24 12:03:56 +0000164 Len = II->getArgOperand(0);
Chris Lattner2764b4d2009-12-02 06:35:55 +0000165 break;
Duncan Sands1925d3a2009-11-10 13:49:50 +0000166 }
Nick Lewycky90271472009-11-10 06:46:40 +0000167 }
168 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len))
169 if (!LenCI->isAllOnesValue())
170 return LenCI->getZExtValue();
Dan Gohmanf372cf82010-10-19 22:54:46 +0000171 return AliasAnalysis::UnknownSize;
Nick Lewycky90271472009-11-10 06:46:40 +0000172}
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.
Chris Lattnera0906272009-11-04 23:20:12 +0000177///
Nick Lewycky90271472009-11-10 06:46:40 +0000178static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2,
179 const TargetData *TD) {
180 const Type *I1Ty = getPointerOperand(I1)->getType();
181 const Type *I2Ty = getPointerOperand(I2)->getType();
Chris Lattnera0906272009-11-04 23:20:12 +0000182
183 // Exactly the same type, must have exactly the same size.
Nick Lewycky90271472009-11-10 06:46:40 +0000184 if (I1Ty == I2Ty) return true;
Chris Lattnera0906272009-11-04 23:20:12 +0000185
Dan Gohmanf372cf82010-10-19 22:54:46 +0000186 uint64_t I1Size = getStoreSize(I1, TD);
187 uint64_t I2Size = getStoreSize(I2, TD);
Chris Lattnera0906272009-11-04 23:20:12 +0000188
Dan Gohmanf372cf82010-10-19 22:54:46 +0000189 return I1Size != AliasAnalysis::UnknownSize &&
190 I2Size != AliasAnalysis::UnknownSize &&
191 I1Size >= I2Size;
Chris Lattnera0906272009-11-04 23:20:12 +0000192}
193
Owen Anderson10e52ed2007-08-01 06:36:51 +0000194bool DSE::runOnBasicBlock(BasicBlock &BB) {
Nick Lewycky475d3d12010-01-03 04:39:07 +0000195 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
Dan Gohman67243a42009-07-24 18:13:53 +0000196 TD = getAnalysisIfAvailable<TargetData>();
Owen Anderson2ed651a2007-11-01 05:29:16 +0000197
Owen Anderson5e72db32007-07-11 00:46:18 +0000198 bool MadeChange = false;
199
Chris Lattner49162672009-09-02 06:31:02 +0000200 // Do a top-down walk on the BB.
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000201 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
202 Instruction *Inst = BBI++;
203
Dan Gohman67243a42009-07-24 18:13:53 +0000204 // If we find a store or a free, get its memory dependence.
Nick Lewycky90271472009-11-10 06:46:40 +0000205 if (!doesClobberMemory(Inst) && !isFreeCall(Inst))
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000206 continue;
Chris Lattnerd4f10902010-11-30 00:01:19 +0000207
Chris Lattner57e91ea2008-12-06 00:53:22 +0000208 MemDepResult InstDep = MD.getDependency(Inst);
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000209
Chris Lattnerd4f10902010-11-30 00:01:19 +0000210 // Ignore non-local store liveness.
Chris Lattner57e91ea2008-12-06 00:53:22 +0000211 // FIXME: cross-block DSE would be fun. :)
212 if (InstDep.isNonLocal()) continue;
213
214 // Handle frees whose dependencies are non-trivial.
Gabor Greif07e92842010-06-25 07:40:32 +0000215 if (const CallInst *F = isFreeCall(Inst)) {
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000216 MadeChange |= handleFreeWithNonTrivialDependency(F, Inst, InstDep);
Chris Lattner57e91ea2008-12-06 00:53:22 +0000217 continue;
218 }
Chris Lattner49162672009-09-02 06:31:02 +0000219
Chris Lattner57e91ea2008-12-06 00:53:22 +0000220 // If we're storing the same value back to a pointer that we just
221 // loaded from, then the store can be removed.
Nick Lewycky90271472009-11-10 06:46:40 +0000222 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
223 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
224 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
225 SI->getOperand(0) == DepLoad) {
226 // DeleteDeadInstruction can delete the current instruction. Save BBI
227 // in case we need it.
228 WeakVH NextInst(BBI);
229
230 DeleteDeadInstruction(SI);
231
232 if (NextInst == 0) // Next instruction deleted.
233 BBI = BB.begin();
234 else if (BBI != BB.begin()) // Revisit this instruction if possible.
235 --BBI;
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000236 ++NumFastStores;
Nick Lewycky90271472009-11-10 06:46:40 +0000237 MadeChange = true;
238 continue;
239 }
Chris Lattner0e3d6332008-12-05 21:04:20 +0000240 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000241 }
Chris Lattnerd4f10902010-11-30 00:01:19 +0000242
243 if (!InstDep.isDef()) {
244 // If this is a may-aliased store that is clobbering the store value, we
245 // can keep searching past it for another must-aliased pointer that stores
246 // to the same location. For example, in:
247 // store -> P
248 // store -> Q
249 // store -> P
250 // we can remove the first store to P even though we don't know if P and Q
251 // alias.
252 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
253 AliasAnalysis::Location Loc =
254 getAnalysis<AliasAnalysis>().getLocation(SI);
255 while (InstDep.isClobber() && isa<StoreInst>(InstDep.getInst()) &&
256 InstDep.getInst() != &BB.front())
257 InstDep = MD.getPointerDependencyFrom(Loc, false, InstDep.getInst(),
258 &BB);
259 }
260 }
Owen Anderson2b2bd282009-10-28 07:05:35 +0000261
Chris Lattnerd4f10902010-11-30 00:01:19 +0000262 // If this is a store-store dependence, then the previous store is dead so
263 // long as this store is at least as big as it.
264 if (InstDep.isDef() && doesClobberMemory(InstDep.getInst())) {
265 Instruction *DepStore = InstDep.getInst();
266 if (isStoreAtLeastAsWideAs(Inst, DepStore, TD) && isElidable(DepStore)) {
Owen Anderson2b2bd282009-10-28 07:05:35 +0000267 // Delete the store and now-dead instructions that feed it.
Chris Lattnerd4f10902010-11-30 00:01:19 +0000268 DeleteDeadInstruction(DepStore);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000269 ++NumFastStores;
Owen Anderson2b2bd282009-10-28 07:05:35 +0000270 MadeChange = true;
Chris Lattnerd4f10902010-11-30 00:01:19 +0000271
272 // DeleteDeadInstruction can delete the current instruction in loop
273 // cases, reset BBI.
274 BBI = Inst;
275 if (BBI != BB.begin())
276 --BBI;
Owen Anderson2b2bd282009-10-28 07:05:35 +0000277 continue;
278 }
279 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000280 }
281
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000282 // If this block ends in a return, unwind, or unreachable, all allocas are
283 // dead at its end, which means stores to them are also dead.
Owen Anderson32c4a052007-07-12 21:41:30 +0000284 if (BB.getTerminator()->getNumSuccessors() == 0)
Chris Lattner1adb6752008-11-28 00:27:14 +0000285 MadeChange |= handleEndBlock(BB);
Owen Anderson5e72db32007-07-11 00:46:18 +0000286
287 return MadeChange;
288}
289
Owen Andersonaa071722007-07-11 23:19:17 +0000290/// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
Chris Lattner1adb6752008-11-28 00:27:14 +0000291/// dependency is a store to a field of that structure.
Gabor Greif07e92842010-06-25 07:40:32 +0000292bool DSE::handleFreeWithNonTrivialDependency(const CallInst *F,
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000293 Instruction *Inst,
Gabor Greif07e92842010-06-25 07:40:32 +0000294 MemDepResult Dep) {
Owen Andersonaa071722007-07-11 23:19:17 +0000295 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000296 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Andersonaa071722007-07-11 23:19:17 +0000297
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000298 do {
299 Instruction *Dependency = Dep.getInst();
300 if (!Dependency || !doesClobberMemory(Dependency) || !isElidable(Dependency))
301 return false;
Owen Andersond4451de2007-07-12 18:08:51 +0000302
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000303 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000304
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000305 // Check for aliasing.
306 if (AA.alias(F->getArgOperand(0), 1, DepPointer, 1) !=
307 AliasAnalysis::MustAlias)
308 return false;
Owen Andersonaa071722007-07-11 23:19:17 +0000309
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000310 // DCE instructions only used to calculate that store
311 DeleteDeadInstruction(Dependency);
312 ++NumFastStores;
313
314 // Inst's old Dependency is now deleted. Compute the next dependency,
315 // which may also be dead, as in
316 // s[0] = 0;
317 // s[1] = 0; // This has just been deleted.
318 // free(s);
319 Dep = MD.getDependency(Inst);
320 } while (!Dep.isNonLocal());
Chris Lattner1adb6752008-11-28 00:27:14 +0000321 return true;
Owen Andersonaa071722007-07-11 23:19:17 +0000322}
323
Owen Andersone3590582007-08-02 18:11:11 +0000324/// handleEndBlock - Remove dead stores to stack-allocated locations in the
Owen Anderson52aaabf2007-08-08 17:50:09 +0000325/// function end block. Ex:
326/// %A = alloca i32
327/// ...
328/// store i32 1, i32* %A
329/// ret void
Chris Lattner1adb6752008-11-28 00:27:14 +0000330bool DSE::handleEndBlock(BasicBlock &BB) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000331 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Owen Anderson32c4a052007-07-12 21:41:30 +0000332
333 bool MadeChange = false;
334
335 // Pointers alloca'd in this function are dead in the end block
Owen Anderson48d37802008-01-29 06:18:36 +0000336 SmallPtrSet<Value*, 64> deadPointers;
Owen Anderson32c4a052007-07-12 21:41:30 +0000337
Chris Lattner1adb6752008-11-28 00:27:14 +0000338 // Find all of the alloca'd pointers in the entry block.
Owen Anderson32c4a052007-07-12 21:41:30 +0000339 BasicBlock *Entry = BB.getParent()->begin();
340 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
341 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
342 deadPointers.insert(AI);
Chris Lattner1adb6752008-11-28 00:27:14 +0000343
344 // Treat byval arguments the same, stores to them are dead at the end of the
345 // function.
Owen Anderson48d37802008-01-29 06:18:36 +0000346 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
347 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
348 if (AI->hasByValAttr())
349 deadPointers.insert(AI);
Owen Anderson32c4a052007-07-12 21:41:30 +0000350
351 // Scan the basic block backwards
352 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
353 --BBI;
354
Chris Lattner1adb6752008-11-28 00:27:14 +0000355 // If we find a store whose pointer is dead.
Nick Lewycky90271472009-11-10 06:46:40 +0000356 if (doesClobberMemory(BBI)) {
357 if (isElidable(BBI)) {
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000358 // See through pointer-to-pointer bitcasts
Nick Lewycky90271472009-11-10 06:46:40 +0000359 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
Duncan Sandsd65a4da2008-10-01 15:25:41 +0000360
Owen Anderson6af19fd2008-01-25 10:10:33 +0000361 // Alloca'd pointers or byval arguments (which are functionally like
362 // alloca's) are valid candidates for removal.
Owen Anderson48d37802008-01-29 06:18:36 +0000363 if (deadPointers.count(pointerOperand)) {
Chris Lattner1adb6752008-11-28 00:27:14 +0000364 // DCE instructions only used to calculate that store.
Nick Lewycky90271472009-11-10 06:46:40 +0000365 Instruction *Dead = BBI;
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000366 ++BBI;
Nick Lewycky90271472009-11-10 06:46:40 +0000367 DeleteDeadInstruction(Dead, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000368 ++NumFastStores;
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000369 MadeChange = true;
Nick Lewycky90271472009-11-10 06:46:40 +0000370 continue;
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000371 }
Owen Anderson32c4a052007-07-12 21:41:30 +0000372 }
Owen Anderson52aaabf2007-08-08 17:50:09 +0000373
Nick Lewycky90271472009-11-10 06:46:40 +0000374 // Because a memcpy or memmove is also a load, we can't skip it if we
375 // didn't remove it.
376 if (!isa<MemTransferInst>(BBI))
Owen Anderson48d37802008-01-29 06:18:36 +0000377 continue;
Owen Anderson52aaabf2007-08-08 17:50:09 +0000378 }
379
Nick Lewycky475d3d12010-01-03 04:39:07 +0000380 Value *killPointer = 0;
Dan Gohmanf372cf82010-10-19 22:54:46 +0000381 uint64_t killPointerSize = AliasAnalysis::UnknownSize;
Owen Anderson32c4a052007-07-12 21:41:30 +0000382
383 // If we encounter a use of the pointer, it is no longer considered dead
Chris Lattner1adb6752008-11-28 00:27:14 +0000384 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
Nate Begeman53c5c622008-05-13 01:48:26 +0000385 // However, if this load is unused and not volatile, we can go ahead and
386 // remove it, and not have to worry about it making our pointer undead!
Dan Gohman8cb19d92008-04-28 19:51:27 +0000387 if (L->use_empty() && !L->isVolatile()) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000388 ++BBI;
Chris Lattner1adb6752008-11-28 00:27:14 +0000389 DeleteDeadInstruction(L, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000390 ++NumFastOther;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000391 MadeChange = true;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000392 continue;
393 }
394
Owen Anderson32c4a052007-07-12 21:41:30 +0000395 killPointer = L->getPointerOperand();
Nick Lewycky475d3d12010-01-03 04:39:07 +0000396 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000397 killPointer = V->getOperand(0);
Nick Lewycky90271472009-11-10 06:46:40 +0000398 } else if (isa<MemTransferInst>(BBI) &&
399 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
400 killPointer = cast<MemTransferInst>(BBI)->getSource();
Owen Andersona82c9932008-02-04 04:53:00 +0000401 killPointerSize = cast<ConstantInt>(
Nick Lewycky90271472009-11-10 06:46:40 +0000402 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
Nick Lewycky475d3d12010-01-03 04:39:07 +0000403 } else if (AllocaInst *A = dyn_cast<AllocaInst>(BBI)) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000404 deadPointers.erase(A);
Owen Anderson4e4b1162008-01-30 01:24:47 +0000405
406 // Dead alloca's can be DCE'd when we reach them
Nick Lewycky6b016702008-01-30 08:01:28 +0000407 if (A->use_empty()) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000408 ++BBI;
Chris Lattner1adb6752008-11-28 00:27:14 +0000409 DeleteDeadInstruction(A, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000410 ++NumFastOther;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000411 MadeChange = true;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000412 }
413
Owen Anderson32c4a052007-07-12 21:41:30 +0000414 continue;
Gabor Greif0a970692010-07-28 14:28:18 +0000415 } else if (CallSite CS = cast<Value>(BBI)) {
Owen Anderson50df9682007-08-08 17:58:56 +0000416 // If this call does not access memory, it can't
417 // be undeadifying any of our pointers.
Duncan Sands68b6f502007-12-01 07:51:45 +0000418 if (AA.doesNotAccessMemory(CS))
Owen Anderson50df9682007-08-08 17:58:56 +0000419 continue;
420
Owen Andersonddf4aee2007-08-08 18:38:28 +0000421 unsigned modRef = 0;
422 unsigned other = 0;
423
Owen Anderson32c4a052007-07-12 21:41:30 +0000424 // Remove any pointers made undead by the call from the dead set
Owen Anderson48d37802008-01-29 06:18:36 +0000425 std::vector<Value*> dead;
426 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
Owen Anderson32c4a052007-07-12 21:41:30 +0000427 E = deadPointers.end(); I != E; ++I) {
Owen Andersonddf4aee2007-08-08 18:38:28 +0000428 // HACK: if we detect that our AA is imprecise, it's not
429 // worth it to scan the rest of the deadPointers set. Just
430 // assume that the AA will return ModRef for everything, and
431 // go ahead and bail.
432 if (modRef >= 16 && other == 0) {
433 deadPointers.clear();
434 return MadeChange;
435 }
Nick Lewycky475d3d12010-01-03 04:39:07 +0000436
Owen Anderson32c4a052007-07-12 21:41:30 +0000437 // See if the call site touches it
Nick Lewycky475d3d12010-01-03 04:39:07 +0000438 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I,
439 getPointerSize(*I));
Owen Andersonddf4aee2007-08-08 18:38:28 +0000440
441 if (A == AliasAnalysis::ModRef)
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000442 ++modRef;
Owen Andersonddf4aee2007-08-08 18:38:28 +0000443 else
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000444 ++other;
Owen Andersonddf4aee2007-08-08 18:38:28 +0000445
Owen Anderson9c9ef212007-07-13 18:26:26 +0000446 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
Owen Anderson32c4a052007-07-12 21:41:30 +0000447 dead.push_back(*I);
448 }
449
Owen Anderson48d37802008-01-29 06:18:36 +0000450 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
Owen Anderson32c4a052007-07-12 21:41:30 +0000451 I != E; ++I)
Owen Anderson48d37802008-01-29 06:18:36 +0000452 deadPointers.erase(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000453
454 continue;
Chris Lattner1adb6752008-11-28 00:27:14 +0000455 } else if (isInstructionTriviallyDead(BBI)) {
Owen Anderson4e4b1162008-01-30 01:24:47 +0000456 // For any non-memory-affecting non-terminators, DCE them as we reach them
Chris Lattner1adb6752008-11-28 00:27:14 +0000457 Instruction *Inst = BBI;
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000458 ++BBI;
Chris Lattner1adb6752008-11-28 00:27:14 +0000459 DeleteDeadInstruction(Inst, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000460 ++NumFastOther;
Chris Lattner1adb6752008-11-28 00:27:14 +0000461 MadeChange = true;
462 continue;
Owen Anderson32c4a052007-07-12 21:41:30 +0000463 }
464
465 if (!killPointer)
466 continue;
Duncan Sandsd65a4da2008-10-01 15:25:41 +0000467
468 killPointer = killPointer->getUnderlyingObject();
469
Owen Anderson32c4a052007-07-12 21:41:30 +0000470 // Deal with undead pointers
Owen Andersona82c9932008-02-04 04:53:00 +0000471 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
Chris Lattner1adb6752008-11-28 00:27:14 +0000472 deadPointers);
Owen Anderson32c4a052007-07-12 21:41:30 +0000473 }
474
475 return MadeChange;
476}
477
Owen Andersonddf4aee2007-08-08 18:38:28 +0000478/// RemoveUndeadPointers - check for uses of a pointer that make it
479/// undead when scanning for dead stores to alloca's.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000480bool DSE::RemoveUndeadPointers(Value *killPointer, uint64_t killPointerSize,
Chris Lattner1adb6752008-11-28 00:27:14 +0000481 BasicBlock::iterator &BBI,
Nick Lewycky475d3d12010-01-03 04:39:07 +0000482 SmallPtrSet<Value*, 64> &deadPointers) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000483 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Nick Lewycky475d3d12010-01-03 04:39:07 +0000484
Owen Andersonddf4aee2007-08-08 18:38:28 +0000485 // If the kill pointer can be easily reduced to an alloca,
Chris Lattner1adb6752008-11-28 00:27:14 +0000486 // don't bother doing extraneous AA queries.
Owen Anderson48d37802008-01-29 06:18:36 +0000487 if (deadPointers.count(killPointer)) {
488 deadPointers.erase(killPointer);
Owen Andersonddf4aee2007-08-08 18:38:28 +0000489 return false;
490 }
491
Chris Lattner1adb6752008-11-28 00:27:14 +0000492 // A global can't be in the dead pointer set.
493 if (isa<GlobalValue>(killPointer))
494 return false;
495
Owen Anderson32c4a052007-07-12 21:41:30 +0000496 bool MadeChange = false;
497
Chris Lattner1adb6752008-11-28 00:27:14 +0000498 SmallVector<Value*, 16> undead;
Nick Lewycky475d3d12010-01-03 04:39:07 +0000499
Owen Anderson48d37802008-01-29 06:18:36 +0000500 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
Nick Lewycky475d3d12010-01-03 04:39:07 +0000501 E = deadPointers.end(); I != E; ++I) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000502 // See if this pointer could alias it
Nick Lewycky475d3d12010-01-03 04:39:07 +0000503 AliasAnalysis::AliasResult A = AA.alias(*I, getPointerSize(*I),
Owen Andersona82c9932008-02-04 04:53:00 +0000504 killPointer, killPointerSize);
Owen Anderson32c4a052007-07-12 21:41:30 +0000505
506 // If it must-alias and a store, we can delete it
507 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
Nick Lewycky475d3d12010-01-03 04:39:07 +0000508 StoreInst *S = cast<StoreInst>(BBI);
Owen Anderson32c4a052007-07-12 21:41:30 +0000509
510 // Remove it!
Nick Lewycky475d3d12010-01-03 04:39:07 +0000511 ++BBI;
Chris Lattner1adb6752008-11-28 00:27:14 +0000512 DeleteDeadInstruction(S, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000513 ++NumFastStores;
Owen Anderson32c4a052007-07-12 21:41:30 +0000514 MadeChange = true;
515
516 continue;
517
518 // Otherwise, it is undead
Chris Lattner1adb6752008-11-28 00:27:14 +0000519 } else if (A != AliasAnalysis::NoAlias)
520 undead.push_back(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000521 }
522
Chris Lattner1adb6752008-11-28 00:27:14 +0000523 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
Owen Anderson32c4a052007-07-12 21:41:30 +0000524 I != E; ++I)
Owen Anderson48d37802008-01-29 06:18:36 +0000525 deadPointers.erase(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000526
527 return MadeChange;
528}
529
Chris Lattner1adb6752008-11-28 00:27:14 +0000530/// DeleteDeadInstruction - Delete this instruction. Before we do, go through
531/// and zero out all the operands of this instruction. If any of them become
532/// dead, delete them and the computation tree that feeds them.
533///
534/// If ValueSet is non-null, remove any deleted instructions from it as well.
535///
536void DSE::DeleteDeadInstruction(Instruction *I,
537 SmallPtrSet<Value*, 64> *ValueSet) {
538 SmallVector<Instruction*, 32> NowDeadInsts;
539
540 NowDeadInsts.push_back(I);
541 --NumFastOther;
Owen Anderson5e72db32007-07-11 00:46:18 +0000542
Chris Lattner1adb6752008-11-28 00:27:14 +0000543 // Before we touch this instruction, remove it from memdep!
544 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
Dan Gohman28943872010-01-05 16:27:25 +0000545 do {
546 Instruction *DeadInst = NowDeadInsts.pop_back_val();
Owen Andersonbf971aa2007-07-11 19:03:09 +0000547
Chris Lattner1adb6752008-11-28 00:27:14 +0000548 ++NumFastOther;
549
550 // This instruction is dead, zap it, in stages. Start by removing it from
551 // MemDep, which needs to know the operands and needs it to be in the
552 // function.
553 MDA.removeInstruction(DeadInst);
554
555 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
556 Value *Op = DeadInst->getOperand(op);
557 DeadInst->setOperand(op, 0);
558
559 // If this operand just became dead, add it to the NowDeadInsts list.
560 if (!Op->use_empty()) continue;
561
562 if (Instruction *OpI = dyn_cast<Instruction>(Op))
563 if (isInstructionTriviallyDead(OpI))
564 NowDeadInsts.push_back(OpI);
565 }
566
567 DeadInst->eraseFromParent();
568
569 if (ValueSet) ValueSet->erase(DeadInst);
Dan Gohman28943872010-01-05 16:27:25 +0000570 } while (!NowDeadInsts.empty());
Owen Anderson5e72db32007-07-11 00:46:18 +0000571}
Nick Lewycky475d3d12010-01-03 04:39:07 +0000572
Dan Gohmanf372cf82010-10-19 22:54:46 +0000573uint64_t DSE::getPointerSize(Value *V) const {
Nick Lewycky475d3d12010-01-03 04:39:07 +0000574 if (TD) {
575 if (AllocaInst *A = dyn_cast<AllocaInst>(V)) {
576 // Get size information for the alloca
577 if (ConstantInt *C = dyn_cast<ConstantInt>(A->getArraySize()))
578 return C->getZExtValue() * TD->getTypeAllocSize(A->getAllocatedType());
579 } else {
580 assert(isa<Argument>(V) && "Expected AllocaInst or Argument!");
581 const PointerType *PT = cast<PointerType>(V->getType());
582 return TD->getTypeAllocSize(PT->getElementType());
583 }
584 }
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000585 return AliasAnalysis::UnknownSize;
Nick Lewycky475d3d12010-01-03 04:39:07 +0000586}