blob: d05f57f0d029c586eacbc6fa3f60fb3b1fbfa5c7 [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);
Chris Lattner9d179d92010-11-30 01:28:33 +000061 bool HandleFree(CallInst *F);
Chris Lattner1adb6752008-11-28 00:27:14 +000062 bool handleEndBlock(BasicBlock &BB);
Dan Gohmanf372cf82010-10-19 22:54:46 +000063 bool RemoveUndeadPointers(Value *Ptr, uint64_t killPointerSize,
Nick Lewycky475d3d12010-01-03 04:39:07 +000064 BasicBlock::iterator &BBI,
65 SmallPtrSet<Value*, 64> &deadPointers);
Chris Lattner1adb6752008-11-28 00:27:14 +000066 void DeleteDeadInstruction(Instruction *I,
67 SmallPtrSet<Value*, 64> *deadPointers = 0);
68
Owen Anderson5e72db32007-07-11 00:46:18 +000069
70 // getAnalysisUsage - We require post dominance frontiers (aka Control
71 // Dependence Graph)
72 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 AU.setPreservesCFG();
Owen Anderson3f338972008-07-28 16:14:26 +000074 AU.addRequired<DominatorTree>();
Owen Andersonaa071722007-07-11 23:19:17 +000075 AU.addRequired<AliasAnalysis>();
Owen Anderson5e72db32007-07-11 00:46:18 +000076 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson3f338972008-07-28 16:14:26 +000077 AU.addPreserved<DominatorTree>();
Owen Anderson5e72db32007-07-11 00:46:18 +000078 AU.addPreserved<MemoryDependenceAnalysis>();
79 }
Nick Lewycky475d3d12010-01-03 04:39:07 +000080
Dan Gohmanf372cf82010-10-19 22:54:46 +000081 uint64_t getPointerSize(Value *V) const;
Owen Anderson5e72db32007-07-11 00:46:18 +000082 };
Owen Anderson5e72db32007-07-11 00:46:18 +000083}
84
Dan Gohmand78c4002008-05-13 00:00:25 +000085char DSE::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000086INITIALIZE_PASS_BEGIN(DSE, "dse", "Dead Store Elimination", false, false)
87INITIALIZE_PASS_DEPENDENCY(DominatorTree)
88INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
89INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
90INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000091
Owen Anderson10e52ed2007-08-01 06:36:51 +000092FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
Owen Anderson5e72db32007-07-11 00:46:18 +000093
Chris Lattner2227a8a2010-11-30 01:37:52 +000094/// hasMemoryWrite - Does this instruction write some memory? This only returns
95/// true for things that we can analyze with other helpers below.
96static bool hasMemoryWrite(Instruction *I) {
Nick Lewycky90271472009-11-10 06:46:40 +000097 if (isa<StoreInst>(I))
98 return true;
99 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
100 switch (II->getIntrinsicID()) {
Chris Lattner2764b4d2009-12-02 06:35:55 +0000101 default:
102 return false;
103 case Intrinsic::memset:
104 case Intrinsic::memmove:
105 case Intrinsic::memcpy:
106 case Intrinsic::init_trampoline:
107 case Intrinsic::lifetime_end:
108 return true;
Nick Lewycky90271472009-11-10 06:46:40 +0000109 }
110 }
111 return false;
112}
113
Chris Lattner58b779e2010-11-30 07:23:21 +0000114/// getLocForWrite - Return a Location stored to by the specified instruction.
115static AliasAnalysis::Location
116getLocForWrite(Instruction *Inst, AliasAnalysis &AA) {
117 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
118 return AA.getLocation(SI);
119
120 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Inst)) {
121 // memcpy/memmove/memset.
122 AliasAnalysis::Location Loc = AA.getLocationForDest(MI);
123 // If we don't have target data around, an unknown size in Location means
124 // that we should use the size of the pointee type. This isn't valid for
125 // memset/memcpy, which writes more than an i8.
126 if (Loc.Size == AliasAnalysis::UnknownSize && AA.getTargetData() == 0)
127 return AliasAnalysis::Location();
128 return Loc;
129 }
130
131 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
132 if (II == 0) return AliasAnalysis::Location();
133
134 switch (II->getIntrinsicID()) {
135 default: return AliasAnalysis::Location(); // Unhandled intrinsic.
136 case Intrinsic::init_trampoline:
137 // If we don't have target data around, an unknown size in Location means
138 // that we should use the size of the pointee type. This isn't valid for
139 // init.trampoline, which writes more than an i8.
140 if (AA.getTargetData() == 0) return AliasAnalysis::Location();
141
142 // FIXME: We don't know the size of the trampoline, so we can't really
143 // handle it here.
144 return AliasAnalysis::Location(II->getArgOperand(0));
145 case Intrinsic::lifetime_end: {
146 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
147 return AliasAnalysis::Location(II->getArgOperand(1), Len);
148 }
149 }
150}
151
Chris Lattner3590ef82010-11-30 05:30:45 +0000152/// isRemovable - If the value of this instruction and the memory it writes to
153/// is unused, may we delete this instruction?
154static bool isRemovable(Instruction *I) {
Chris Lattnerb63ba732010-11-30 19:12:10 +0000155 // Don't remove volatile stores.
Nick Lewycky90271472009-11-10 06:46:40 +0000156 if (StoreInst *SI = dyn_cast<StoreInst>(I))
157 return !SI->isVolatile();
Chris Lattnerb63ba732010-11-30 19:12:10 +0000158
159 IntrinsicInst *II = cast<IntrinsicInst>(I);
160 switch (II->getIntrinsicID()) {
161 default: assert(0 && "doesn't pass 'hasMemoryWrite' predicate");
162 case Intrinsic::lifetime_end:
163 // Never remove dead lifetime_end's, e.g. because it is followed by a
164 // free.
165 return false;
166 case Intrinsic::init_trampoline:
167 // Always safe to remove init_trampoline.
168 return true;
169
170 case Intrinsic::memset:
171 case Intrinsic::memmove:
172 case Intrinsic::memcpy:
173 // Don't remove volatile memory intrinsics.
174 return !cast<MemIntrinsic>(II)->isVolatile();
175 }
Nick Lewycky90271472009-11-10 06:46:40 +0000176}
177
Chris Lattner9d179d92010-11-30 01:28:33 +0000178/// getPointerOperand - Return the pointer that is being written to.
Nick Lewycky90271472009-11-10 06:46:40 +0000179static Value *getPointerOperand(Instruction *I) {
Chris Lattner2227a8a2010-11-30 01:37:52 +0000180 assert(hasMemoryWrite(I));
Nick Lewycky90271472009-11-10 06:46:40 +0000181 if (StoreInst *SI = dyn_cast<StoreInst>(I))
182 return SI->getPointerOperand();
183 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
Gabor Greif91f95892010-06-24 12:03:56 +0000184 return MI->getArgOperand(0);
185
186 IntrinsicInst *II = cast<IntrinsicInst>(I);
187 switch (II->getIntrinsicID()) {
Chris Lattner2764b4d2009-12-02 06:35:55 +0000188 default: assert(false && "Unexpected intrinsic!");
189 case Intrinsic::init_trampoline:
Gabor Greif91f95892010-06-24 12:03:56 +0000190 return II->getArgOperand(0);
Eric Christopher7258dcd2010-04-16 23:37:20 +0000191 case Intrinsic::lifetime_end:
Gabor Greif91f95892010-06-24 12:03:56 +0000192 return II->getArgOperand(1);
Duncan Sands1925d3a2009-11-10 13:49:50 +0000193 }
Nick Lewycky90271472009-11-10 06:46:40 +0000194}
195
Chris Lattner58b779e2010-11-30 07:23:21 +0000196/// isCompleteOverwrite - Return true if a store to the 'Later' location
197/// completely overwrites a store to the 'Earlier' location.
198static bool isCompleteOverwrite(const AliasAnalysis::Location &Later,
199 const AliasAnalysis::Location &Earlier,
200 AliasAnalysis &AA, const TargetData *TD) {
201 const Value *P1 = Later.Ptr->stripPointerCasts();
202 const Value *P2 = Earlier.Ptr->stripPointerCasts();
203
204 // Make sure that the start pointers are the same.
205 if (P1 != P2)
206 return false;
Nick Lewycky90271472009-11-10 06:46:40 +0000207
Chris Lattner58b779e2010-11-30 07:23:21 +0000208 // If we have no TargetData information around, then the size of the store is
209 // inferrable from the pointee type. If they are the same type, then we know
210 // that the store is safe.
211 if (TD == 0)
212 return Later.Ptr->getType() == Earlier.Ptr->getType();
213
214
215 // Make sure that the Later size is >= the Earlier size.
216 if (Later.Size < Earlier.Size)
217 return false;
218
219 return true;
Nick Lewycky90271472009-11-10 06:46:40 +0000220}
221
Owen Anderson10e52ed2007-08-01 06:36:51 +0000222bool DSE::runOnBasicBlock(BasicBlock &BB) {
Nick Lewycky475d3d12010-01-03 04:39:07 +0000223 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner3590ef82010-11-30 05:30:45 +0000224 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Dan Gohman67243a42009-07-24 18:13:53 +0000225 TD = getAnalysisIfAvailable<TargetData>();
Owen Anderson2ed651a2007-11-01 05:29:16 +0000226
Owen Anderson5e72db32007-07-11 00:46:18 +0000227 bool MadeChange = false;
228
Chris Lattner49162672009-09-02 06:31:02 +0000229 // Do a top-down walk on the BB.
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000230 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
231 Instruction *Inst = BBI++;
232
Chris Lattner9d179d92010-11-30 01:28:33 +0000233 // Handle 'free' calls specially.
234 if (CallInst *F = isFreeCall(Inst)) {
235 MadeChange |= HandleFree(F);
236 continue;
237 }
238
Chris Lattner2227a8a2010-11-30 01:37:52 +0000239 // If we find something that writes memory, get its memory dependence.
240 if (!hasMemoryWrite(Inst))
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000241 continue;
Chris Lattnerd4f10902010-11-30 00:01:19 +0000242
Chris Lattner57e91ea2008-12-06 00:53:22 +0000243 MemDepResult InstDep = MD.getDependency(Inst);
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000244
Chris Lattnerd4f10902010-11-30 00:01:19 +0000245 // Ignore non-local store liveness.
Chris Lattner57e91ea2008-12-06 00:53:22 +0000246 // FIXME: cross-block DSE would be fun. :)
Chris Lattner58b779e2010-11-30 07:23:21 +0000247 if (InstDep.isNonLocal() ||
248 // Ignore self dependence, which happens in the entry block of the
249 // function.
250 InstDep.getInst() == Inst)
251 continue;
Chris Lattner9d179d92010-11-30 01:28:33 +0000252
Chris Lattner57e91ea2008-12-06 00:53:22 +0000253 // If we're storing the same value back to a pointer that we just
254 // loaded from, then the store can be removed.
Nick Lewycky90271472009-11-10 06:46:40 +0000255 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
256 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
257 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
Chris Lattnerc3c754f2010-11-30 00:12:39 +0000258 SI->getOperand(0) == DepLoad && !SI->isVolatile()) {
Nick Lewycky90271472009-11-10 06:46:40 +0000259 // DeleteDeadInstruction can delete the current instruction. Save BBI
260 // in case we need it.
261 WeakVH NextInst(BBI);
262
263 DeleteDeadInstruction(SI);
264
265 if (NextInst == 0) // Next instruction deleted.
266 BBI = BB.begin();
267 else if (BBI != BB.begin()) // Revisit this instruction if possible.
268 --BBI;
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000269 ++NumFastStores;
Nick Lewycky90271472009-11-10 06:46:40 +0000270 MadeChange = true;
271 continue;
272 }
Chris Lattner0e3d6332008-12-05 21:04:20 +0000273 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000274 }
Chris Lattner3590ef82010-11-30 05:30:45 +0000275
Chris Lattner58b779e2010-11-30 07:23:21 +0000276 // Figure out what location is being stored to.
277 AliasAnalysis::Location Loc = getLocForWrite(Inst, AA);
278
279 // If we didn't get a useful location, fail.
280 if (Loc.Ptr == 0)
281 continue;
282
283 while (!InstDep.isNonLocal()) {
284 // Get the memory clobbered by the instruction we depend on. MemDep will
285 // skip any instructions that 'Loc' clearly doesn't interact with. If we
286 // end up depending on a may- or must-aliased load, then we can't optimize
287 // away the store and we bail out. However, if we depend on on something
288 // that overwrites the memory location we *can* potentially optimize it.
289 //
290 // Find out what memory location the dependant instruction stores.
291 Instruction *DepWrite = InstDep.getInst();
292 AliasAnalysis::Location DepLoc = getLocForWrite(DepWrite, AA);
293 // If we didn't get a useful location, or if it isn't a size, bail out.
294 if (DepLoc.Ptr == 0)
295 break;
296
297 // If we find a removable write that is completely obliterated by the
298 // store to 'Loc' then we can remove it.
299 if (isRemovable(DepWrite) && isCompleteOverwrite(Loc, DepLoc, AA, TD)) {
300 // Delete the store and now-dead instructions that feed it.
301 DeleteDeadInstruction(DepWrite);
302 ++NumFastStores;
303 MadeChange = true;
304
305 // DeleteDeadInstruction can delete the current instruction in loop
306 // cases, reset BBI.
307 BBI = Inst;
308 if (BBI != BB.begin())
309 --BBI;
310 break;
311 }
312
Chris Lattnerd4f10902010-11-30 00:01:19 +0000313 // If this is a may-aliased store that is clobbering the store value, we
314 // can keep searching past it for another must-aliased pointer that stores
315 // to the same location. For example, in:
316 // store -> P
317 // store -> Q
318 // store -> P
319 // we can remove the first store to P even though we don't know if P and Q
320 // alias.
Chris Lattner58b779e2010-11-30 07:23:21 +0000321 if (DepWrite == &BB.front()) break;
322
323 // Can't look past this instruction if it might read 'Loc'.
324 if (AA.getModRefInfo(DepWrite, Loc) & AliasAnalysis::Ref)
325 break;
Chris Lattner3590ef82010-11-30 05:30:45 +0000326
Chris Lattner58b779e2010-11-30 07:23:21 +0000327 InstDep = MD.getPointerDependencyFrom(Loc, false, DepWrite, &BB);
Owen Anderson2b2bd282009-10-28 07:05:35 +0000328 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000329 }
330
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000331 // If this block ends in a return, unwind, or unreachable, all allocas are
332 // dead at its end, which means stores to them are also dead.
Owen Anderson32c4a052007-07-12 21:41:30 +0000333 if (BB.getTerminator()->getNumSuccessors() == 0)
Chris Lattner1adb6752008-11-28 00:27:14 +0000334 MadeChange |= handleEndBlock(BB);
Owen Anderson5e72db32007-07-11 00:46:18 +0000335
336 return MadeChange;
337}
338
Chris Lattner9d179d92010-11-30 01:28:33 +0000339/// HandleFree - Handle frees of entire structures whose dependency is a store
340/// to a field of that structure.
341bool DSE::HandleFree(CallInst *F) {
Owen Andersonaa071722007-07-11 23:19:17 +0000342 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000343 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner9d179d92010-11-30 01:28:33 +0000344
345 MemDepResult Dep = MD.getDependency(F);
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000346 do {
Chris Lattner9d179d92010-11-30 01:28:33 +0000347 if (Dep.isNonLocal()) return false;
348
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000349 Instruction *Dependency = Dep.getInst();
Chris Lattner3590ef82010-11-30 05:30:45 +0000350 if (!hasMemoryWrite(Dependency) || !isRemovable(Dependency))
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000351 return false;
Owen Andersond4451de2007-07-12 18:08:51 +0000352
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000353 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000354
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000355 // Check for aliasing.
356 if (AA.alias(F->getArgOperand(0), 1, DepPointer, 1) !=
Chris Lattner9d179d92010-11-30 01:28:33 +0000357 AliasAnalysis::MustAlias)
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000358 return false;
Owen Andersonaa071722007-07-11 23:19:17 +0000359
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000360 // DCE instructions only used to calculate that store
361 DeleteDeadInstruction(Dependency);
362 ++NumFastStores;
363
364 // Inst's old Dependency is now deleted. Compute the next dependency,
365 // which may also be dead, as in
366 // s[0] = 0;
367 // s[1] = 0; // This has just been deleted.
368 // free(s);
Chris Lattner9d179d92010-11-30 01:28:33 +0000369 Dep = MD.getDependency(F);
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000370 } while (!Dep.isNonLocal());
Chris Lattner9d179d92010-11-30 01:28:33 +0000371
Chris Lattner1adb6752008-11-28 00:27:14 +0000372 return true;
Owen Andersonaa071722007-07-11 23:19:17 +0000373}
374
Owen Andersone3590582007-08-02 18:11:11 +0000375/// handleEndBlock - Remove dead stores to stack-allocated locations in the
Owen Anderson52aaabf2007-08-08 17:50:09 +0000376/// function end block. Ex:
377/// %A = alloca i32
378/// ...
379/// store i32 1, i32* %A
380/// ret void
Chris Lattner1adb6752008-11-28 00:27:14 +0000381bool DSE::handleEndBlock(BasicBlock &BB) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000382 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Owen Anderson32c4a052007-07-12 21:41:30 +0000383
384 bool MadeChange = false;
385
386 // Pointers alloca'd in this function are dead in the end block
Owen Anderson48d37802008-01-29 06:18:36 +0000387 SmallPtrSet<Value*, 64> deadPointers;
Owen Anderson32c4a052007-07-12 21:41:30 +0000388
Chris Lattner1adb6752008-11-28 00:27:14 +0000389 // Find all of the alloca'd pointers in the entry block.
Owen Anderson32c4a052007-07-12 21:41:30 +0000390 BasicBlock *Entry = BB.getParent()->begin();
391 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
392 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
393 deadPointers.insert(AI);
Chris Lattner1adb6752008-11-28 00:27:14 +0000394
395 // Treat byval arguments the same, stores to them are dead at the end of the
396 // function.
Owen Anderson48d37802008-01-29 06:18:36 +0000397 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
398 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
399 if (AI->hasByValAttr())
400 deadPointers.insert(AI);
Owen Anderson32c4a052007-07-12 21:41:30 +0000401
402 // Scan the basic block backwards
403 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
404 --BBI;
405
Chris Lattner1adb6752008-11-28 00:27:14 +0000406 // If we find a store whose pointer is dead.
Chris Lattner2227a8a2010-11-30 01:37:52 +0000407 if (hasMemoryWrite(BBI)) {
Chris Lattner3590ef82010-11-30 05:30:45 +0000408 if (isRemovable(BBI)) {
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000409 // See through pointer-to-pointer bitcasts
Nick Lewycky90271472009-11-10 06:46:40 +0000410 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
Duncan Sandsd65a4da2008-10-01 15:25:41 +0000411
Owen Anderson6af19fd2008-01-25 10:10:33 +0000412 // Alloca'd pointers or byval arguments (which are functionally like
413 // alloca's) are valid candidates for removal.
Owen Anderson48d37802008-01-29 06:18:36 +0000414 if (deadPointers.count(pointerOperand)) {
Chris Lattner1adb6752008-11-28 00:27:14 +0000415 // DCE instructions only used to calculate that store.
Nick Lewycky90271472009-11-10 06:46:40 +0000416 Instruction *Dead = BBI;
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000417 ++BBI;
Nick Lewycky90271472009-11-10 06:46:40 +0000418 DeleteDeadInstruction(Dead, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000419 ++NumFastStores;
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000420 MadeChange = true;
Nick Lewycky90271472009-11-10 06:46:40 +0000421 continue;
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000422 }
Owen Anderson32c4a052007-07-12 21:41:30 +0000423 }
Owen Anderson52aaabf2007-08-08 17:50:09 +0000424
Nick Lewycky90271472009-11-10 06:46:40 +0000425 // Because a memcpy or memmove is also a load, we can't skip it if we
426 // didn't remove it.
427 if (!isa<MemTransferInst>(BBI))
Owen Anderson48d37802008-01-29 06:18:36 +0000428 continue;
Owen Anderson52aaabf2007-08-08 17:50:09 +0000429 }
430
Nick Lewycky475d3d12010-01-03 04:39:07 +0000431 Value *killPointer = 0;
Dan Gohmanf372cf82010-10-19 22:54:46 +0000432 uint64_t killPointerSize = AliasAnalysis::UnknownSize;
Owen Anderson32c4a052007-07-12 21:41:30 +0000433
434 // If we encounter a use of the pointer, it is no longer considered dead
Chris Lattner1adb6752008-11-28 00:27:14 +0000435 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
Nate Begeman53c5c622008-05-13 01:48:26 +0000436 // However, if this load is unused and not volatile, we can go ahead and
437 // remove it, and not have to worry about it making our pointer undead!
Dan Gohman8cb19d92008-04-28 19:51:27 +0000438 if (L->use_empty() && !L->isVolatile()) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000439 ++BBI;
Chris Lattner1adb6752008-11-28 00:27:14 +0000440 DeleteDeadInstruction(L, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000441 ++NumFastOther;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000442 MadeChange = true;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000443 continue;
444 }
445
Owen Anderson32c4a052007-07-12 21:41:30 +0000446 killPointer = L->getPointerOperand();
Nick Lewycky475d3d12010-01-03 04:39:07 +0000447 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000448 killPointer = V->getOperand(0);
Nick Lewycky90271472009-11-10 06:46:40 +0000449 } else if (isa<MemTransferInst>(BBI) &&
450 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
451 killPointer = cast<MemTransferInst>(BBI)->getSource();
Owen Andersona82c9932008-02-04 04:53:00 +0000452 killPointerSize = cast<ConstantInt>(
Nick Lewycky90271472009-11-10 06:46:40 +0000453 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
Nick Lewycky475d3d12010-01-03 04:39:07 +0000454 } else if (AllocaInst *A = dyn_cast<AllocaInst>(BBI)) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000455 deadPointers.erase(A);
Owen Anderson4e4b1162008-01-30 01:24:47 +0000456
457 // Dead alloca's can be DCE'd when we reach them
Nick Lewycky6b016702008-01-30 08:01:28 +0000458 if (A->use_empty()) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000459 ++BBI;
Chris Lattner1adb6752008-11-28 00:27:14 +0000460 DeleteDeadInstruction(A, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000461 ++NumFastOther;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000462 MadeChange = true;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000463 }
464
Owen Anderson32c4a052007-07-12 21:41:30 +0000465 continue;
Gabor Greif0a970692010-07-28 14:28:18 +0000466 } else if (CallSite CS = cast<Value>(BBI)) {
Owen Anderson50df9682007-08-08 17:58:56 +0000467 // If this call does not access memory, it can't
468 // be undeadifying any of our pointers.
Duncan Sands68b6f502007-12-01 07:51:45 +0000469 if (AA.doesNotAccessMemory(CS))
Owen Anderson50df9682007-08-08 17:58:56 +0000470 continue;
471
Owen Andersonddf4aee2007-08-08 18:38:28 +0000472 unsigned modRef = 0;
473 unsigned other = 0;
474
Owen Anderson32c4a052007-07-12 21:41:30 +0000475 // Remove any pointers made undead by the call from the dead set
Owen Anderson48d37802008-01-29 06:18:36 +0000476 std::vector<Value*> dead;
477 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
Owen Anderson32c4a052007-07-12 21:41:30 +0000478 E = deadPointers.end(); I != E; ++I) {
Owen Andersonddf4aee2007-08-08 18:38:28 +0000479 // HACK: if we detect that our AA is imprecise, it's not
480 // worth it to scan the rest of the deadPointers set. Just
481 // assume that the AA will return ModRef for everything, and
482 // go ahead and bail.
483 if (modRef >= 16 && other == 0) {
484 deadPointers.clear();
485 return MadeChange;
486 }
Nick Lewycky475d3d12010-01-03 04:39:07 +0000487
Owen Anderson32c4a052007-07-12 21:41:30 +0000488 // See if the call site touches it
Nick Lewycky475d3d12010-01-03 04:39:07 +0000489 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I,
490 getPointerSize(*I));
Owen Andersonddf4aee2007-08-08 18:38:28 +0000491
492 if (A == AliasAnalysis::ModRef)
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000493 ++modRef;
Owen Andersonddf4aee2007-08-08 18:38:28 +0000494 else
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000495 ++other;
Owen Andersonddf4aee2007-08-08 18:38:28 +0000496
Owen Anderson9c9ef212007-07-13 18:26:26 +0000497 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
Owen Anderson32c4a052007-07-12 21:41:30 +0000498 dead.push_back(*I);
499 }
500
Owen Anderson48d37802008-01-29 06:18:36 +0000501 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
Owen Anderson32c4a052007-07-12 21:41:30 +0000502 I != E; ++I)
Owen Anderson48d37802008-01-29 06:18:36 +0000503 deadPointers.erase(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000504
505 continue;
Chris Lattner1adb6752008-11-28 00:27:14 +0000506 } else if (isInstructionTriviallyDead(BBI)) {
Owen Anderson4e4b1162008-01-30 01:24:47 +0000507 // For any non-memory-affecting non-terminators, DCE them as we reach them
Chris Lattner1adb6752008-11-28 00:27:14 +0000508 Instruction *Inst = BBI;
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000509 ++BBI;
Chris Lattner1adb6752008-11-28 00:27:14 +0000510 DeleteDeadInstruction(Inst, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000511 ++NumFastOther;
Chris Lattner1adb6752008-11-28 00:27:14 +0000512 MadeChange = true;
513 continue;
Owen Anderson32c4a052007-07-12 21:41:30 +0000514 }
515
516 if (!killPointer)
517 continue;
Duncan Sandsd65a4da2008-10-01 15:25:41 +0000518
519 killPointer = killPointer->getUnderlyingObject();
520
Owen Anderson32c4a052007-07-12 21:41:30 +0000521 // Deal with undead pointers
Owen Andersona82c9932008-02-04 04:53:00 +0000522 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
Chris Lattner1adb6752008-11-28 00:27:14 +0000523 deadPointers);
Owen Anderson32c4a052007-07-12 21:41:30 +0000524 }
525
526 return MadeChange;
527}
528
Owen Andersonddf4aee2007-08-08 18:38:28 +0000529/// RemoveUndeadPointers - check for uses of a pointer that make it
530/// undead when scanning for dead stores to alloca's.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000531bool DSE::RemoveUndeadPointers(Value *killPointer, uint64_t killPointerSize,
Chris Lattner1adb6752008-11-28 00:27:14 +0000532 BasicBlock::iterator &BBI,
Nick Lewycky475d3d12010-01-03 04:39:07 +0000533 SmallPtrSet<Value*, 64> &deadPointers) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000534 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Nick Lewycky475d3d12010-01-03 04:39:07 +0000535
Owen Andersonddf4aee2007-08-08 18:38:28 +0000536 // If the kill pointer can be easily reduced to an alloca,
Chris Lattner1adb6752008-11-28 00:27:14 +0000537 // don't bother doing extraneous AA queries.
Owen Anderson48d37802008-01-29 06:18:36 +0000538 if (deadPointers.count(killPointer)) {
539 deadPointers.erase(killPointer);
Owen Andersonddf4aee2007-08-08 18:38:28 +0000540 return false;
541 }
542
Chris Lattner1adb6752008-11-28 00:27:14 +0000543 // A global can't be in the dead pointer set.
544 if (isa<GlobalValue>(killPointer))
545 return false;
546
Owen Anderson32c4a052007-07-12 21:41:30 +0000547 bool MadeChange = false;
548
Chris Lattner1adb6752008-11-28 00:27:14 +0000549 SmallVector<Value*, 16> undead;
Nick Lewycky475d3d12010-01-03 04:39:07 +0000550
Owen Anderson48d37802008-01-29 06:18:36 +0000551 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
Nick Lewycky475d3d12010-01-03 04:39:07 +0000552 E = deadPointers.end(); I != E; ++I) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000553 // See if this pointer could alias it
Nick Lewycky475d3d12010-01-03 04:39:07 +0000554 AliasAnalysis::AliasResult A = AA.alias(*I, getPointerSize(*I),
Owen Andersona82c9932008-02-04 04:53:00 +0000555 killPointer, killPointerSize);
Owen Anderson32c4a052007-07-12 21:41:30 +0000556
557 // If it must-alias and a store, we can delete it
558 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
Nick Lewycky475d3d12010-01-03 04:39:07 +0000559 StoreInst *S = cast<StoreInst>(BBI);
Owen Anderson32c4a052007-07-12 21:41:30 +0000560
561 // Remove it!
Nick Lewycky475d3d12010-01-03 04:39:07 +0000562 ++BBI;
Chris Lattner1adb6752008-11-28 00:27:14 +0000563 DeleteDeadInstruction(S, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000564 ++NumFastStores;
Owen Anderson32c4a052007-07-12 21:41:30 +0000565 MadeChange = true;
566
567 continue;
568
569 // Otherwise, it is undead
Chris Lattner1adb6752008-11-28 00:27:14 +0000570 } else if (A != AliasAnalysis::NoAlias)
571 undead.push_back(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000572 }
573
Chris Lattner1adb6752008-11-28 00:27:14 +0000574 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
Owen Anderson32c4a052007-07-12 21:41:30 +0000575 I != E; ++I)
Owen Anderson48d37802008-01-29 06:18:36 +0000576 deadPointers.erase(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000577
578 return MadeChange;
579}
580
Chris Lattner1adb6752008-11-28 00:27:14 +0000581/// DeleteDeadInstruction - Delete this instruction. Before we do, go through
582/// and zero out all the operands of this instruction. If any of them become
583/// dead, delete them and the computation tree that feeds them.
584///
585/// If ValueSet is non-null, remove any deleted instructions from it as well.
586///
587void DSE::DeleteDeadInstruction(Instruction *I,
588 SmallPtrSet<Value*, 64> *ValueSet) {
589 SmallVector<Instruction*, 32> NowDeadInsts;
590
591 NowDeadInsts.push_back(I);
592 --NumFastOther;
Owen Anderson5e72db32007-07-11 00:46:18 +0000593
Chris Lattner1adb6752008-11-28 00:27:14 +0000594 // Before we touch this instruction, remove it from memdep!
595 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
Dan Gohman28943872010-01-05 16:27:25 +0000596 do {
597 Instruction *DeadInst = NowDeadInsts.pop_back_val();
Owen Andersonbf971aa2007-07-11 19:03:09 +0000598
Chris Lattner1adb6752008-11-28 00:27:14 +0000599 ++NumFastOther;
600
601 // This instruction is dead, zap it, in stages. Start by removing it from
602 // MemDep, which needs to know the operands and needs it to be in the
603 // function.
604 MDA.removeInstruction(DeadInst);
605
606 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
607 Value *Op = DeadInst->getOperand(op);
608 DeadInst->setOperand(op, 0);
609
610 // If this operand just became dead, add it to the NowDeadInsts list.
611 if (!Op->use_empty()) continue;
612
613 if (Instruction *OpI = dyn_cast<Instruction>(Op))
614 if (isInstructionTriviallyDead(OpI))
615 NowDeadInsts.push_back(OpI);
616 }
617
618 DeadInst->eraseFromParent();
619
620 if (ValueSet) ValueSet->erase(DeadInst);
Dan Gohman28943872010-01-05 16:27:25 +0000621 } while (!NowDeadInsts.empty());
Owen Anderson5e72db32007-07-11 00:46:18 +0000622}
Nick Lewycky475d3d12010-01-03 04:39:07 +0000623
Dan Gohmanf372cf82010-10-19 22:54:46 +0000624uint64_t DSE::getPointerSize(Value *V) const {
Nick Lewycky475d3d12010-01-03 04:39:07 +0000625 if (TD) {
626 if (AllocaInst *A = dyn_cast<AllocaInst>(V)) {
627 // Get size information for the alloca
628 if (ConstantInt *C = dyn_cast<ConstantInt>(A->getArraySize()))
629 return C->getZExtValue() * TD->getTypeAllocSize(A->getAllocatedType());
630 } else {
631 assert(isa<Argument>(V) && "Expected AllocaInst or Argument!");
632 const PointerType *PT = cast<PointerType>(V->getType());
633 return TD->getTypeAllocSize(PT->getElementType());
634 }
635 }
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000636 return AliasAnalysis::UnknownSize;
Nick Lewycky475d3d12010-01-03 04:39:07 +0000637}