blob: 7e5fbcb8014bc6a392d8b8fd8ca939a4f82d1f30 [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"
25#include "llvm/ADT/SetVector.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/Statistic.h"
Owen Andersonaa071722007-07-11 23:19:17 +000028#include "llvm/Analysis/AliasAnalysis.h"
Owen Anderson3f338972008-07-28 16:14:26 +000029#include "llvm/Analysis/Dominators.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"
33#include "llvm/Support/Compiler.h"
34using namespace llvm;
35
36STATISTIC(NumFastStores, "Number of stores deleted");
37STATISTIC(NumFastOther , "Number of other instrs removed");
38
39namespace {
Owen Anderson10e52ed2007-08-01 06:36:51 +000040 struct VISIBILITY_HIDDEN DSE : public FunctionPass {
Owen Anderson5e72db32007-07-11 00:46:18 +000041 static char ID; // Pass identification, replacement for typeid
Dan Gohmana79db302008-09-04 17:05:41 +000042 DSE() : FunctionPass(&ID) {}
Owen Anderson5e72db32007-07-11 00:46:18 +000043
44 virtual bool runOnFunction(Function &F) {
45 bool Changed = false;
46 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
47 Changed |= runOnBasicBlock(*I);
48 return Changed;
49 }
50
51 bool runOnBasicBlock(BasicBlock &BB);
Owen Andersone3590582007-08-02 18:11:11 +000052 bool handleFreeWithNonTrivialDependency(FreeInst* F,
53 Instruction* dependency,
54 SetVector<Instruction*>& possiblyDead);
Owen Anderson32c4a052007-07-12 21:41:30 +000055 bool handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead);
Owen Andersona82c9932008-02-04 04:53:00 +000056 bool RemoveUndeadPointers(Value* pointer, uint64_t killPointerSize,
Owen Anderson32c4a052007-07-12 21:41:30 +000057 BasicBlock::iterator& BBI,
Owen Anderson48d37802008-01-29 06:18:36 +000058 SmallPtrSet<Value*, 64>& deadPointers,
Owen Anderson32c4a052007-07-12 21:41:30 +000059 SetVector<Instruction*>& possiblyDead);
Owen Anderson5e72db32007-07-11 00:46:18 +000060 void DeleteDeadInstructionChains(Instruction *I,
61 SetVector<Instruction*> &DeadInsts);
Owen Anderson0aecf0e2007-08-08 04:52:29 +000062
Owen Andersonb17ab032007-08-08 06:06:02 +000063 /// Find the base pointer that a pointer came from
64 /// Because this is used to find pointers that originate
65 /// from allocas, it is safe to ignore GEP indices, since
66 /// either the store will be in the alloca, and thus dead,
67 /// or beyond the end of the alloca, and thus undefined.
Owen Anderson2ed651a2007-11-01 05:29:16 +000068 void TranslatePointerBitCasts(Value*& v, bool zeroGepsOnly = false) {
Owen Andersone3590582007-08-02 18:11:11 +000069 assert(isa<PointerType>(v->getType()) &&
70 "Translating a non-pointer type?");
Owen Anderson0aecf0e2007-08-08 04:52:29 +000071 while (true) {
Owen Anderson09f86992007-07-16 23:34:39 +000072 if (BitCastInst* C = dyn_cast<BitCastInst>(v))
73 v = C->getOperand(0);
74 else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(v))
Owen Anderson2ed651a2007-11-01 05:29:16 +000075 if (!zeroGepsOnly || G->hasAllZeroIndices()) {
76 v = G->getOperand(0);
77 } else {
78 break;
79 }
Owen Anderson0aecf0e2007-08-08 04:52:29 +000080 else
81 break;
82 }
Owen Anderson9c9ef212007-07-13 18:26:26 +000083 }
Owen Anderson5e72db32007-07-11 00:46:18 +000084
85 // getAnalysisUsage - We require post dominance frontiers (aka Control
86 // Dependence Graph)
87 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88 AU.setPreservesCFG();
Owen Anderson3f338972008-07-28 16:14:26 +000089 AU.addRequired<DominatorTree>();
Owen Andersonaa071722007-07-11 23:19:17 +000090 AU.addRequired<TargetData>();
91 AU.addRequired<AliasAnalysis>();
Owen Anderson5e72db32007-07-11 00:46:18 +000092 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson3f338972008-07-28 16:14:26 +000093 AU.addPreserved<DominatorTree>();
Owen Andersonaa071722007-07-11 23:19:17 +000094 AU.addPreserved<AliasAnalysis>();
Owen Anderson5e72db32007-07-11 00:46:18 +000095 AU.addPreserved<MemoryDependenceAnalysis>();
96 }
97 };
Owen Anderson5e72db32007-07-11 00:46:18 +000098}
99
Dan Gohmand78c4002008-05-13 00:00:25 +0000100char DSE::ID = 0;
101static RegisterPass<DSE> X("dse", "Dead Store Elimination");
102
Owen Anderson10e52ed2007-08-01 06:36:51 +0000103FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
Owen Anderson5e72db32007-07-11 00:46:18 +0000104
Owen Anderson10e52ed2007-08-01 06:36:51 +0000105bool DSE::runOnBasicBlock(BasicBlock &BB) {
Owen Anderson5e72db32007-07-11 00:46:18 +0000106 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Anderson2ed651a2007-11-01 05:29:16 +0000107 TargetData &TD = getAnalysis<TargetData>();
108
Owen Andersonbf971aa2007-07-11 19:03:09 +0000109 // Record the last-seen store to this pointer
Owen Anderson5e72db32007-07-11 00:46:18 +0000110 DenseMap<Value*, StoreInst*> lastStore;
Owen Andersonbf971aa2007-07-11 19:03:09 +0000111 // Record instructions possibly made dead by deleting a store
Owen Anderson5e72db32007-07-11 00:46:18 +0000112 SetVector<Instruction*> possiblyDead;
113
114 bool MadeChange = false;
115
116 // Do a top-down walk on the BB
Owen Andersone3590582007-08-02 18:11:11 +0000117 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end();
118 BBI != BBE; ++BBI) {
Owen Anderson14414702007-07-11 21:06:56 +0000119 // If we find a store or a free...
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000120 if (!isa<StoreInst>(BBI) && !isa<FreeInst>(BBI))
121 continue;
Owen Anderson9c9ef212007-07-13 18:26:26 +0000122
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000123 Value* pointer = 0;
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000124 if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
125 if (!S->isVolatile())
126 pointer = S->getPointerOperand();
127 else
128 continue;
129 } else
Owen Andersonb17ab032007-08-08 06:06:02 +0000130 pointer = cast<FreeInst>(BBI)->getPointerOperand();
Owen Anderson5e72db32007-07-11 00:46:18 +0000131
Owen Anderson2ed651a2007-11-01 05:29:16 +0000132 TranslatePointerBitCasts(pointer, true);
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000133 StoreInst*& last = lastStore[pointer];
134 bool deletedStore = false;
135
136 // ... to a pointer that has been stored to before...
137 if (last) {
Owen Anderson9b1cc8c2007-08-09 04:42:44 +0000138 Instruction* dep = MD.getDependency(BBI);
Owen Anderson5e72db32007-07-11 00:46:18 +0000139
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000140 // ... and no other memory dependencies are between them....
141 while (dep != MemoryDependenceAnalysis::None &&
142 dep != MemoryDependenceAnalysis::NonLocal &&
143 isa<StoreInst>(dep)) {
Owen Anderson2ed651a2007-11-01 05:29:16 +0000144 if (dep != last ||
Duncan Sands44b87212007-11-01 20:53:16 +0000145 TD.getTypeStoreSize(last->getOperand(0)->getType()) >
146 TD.getTypeStoreSize(BBI->getOperand(0)->getType())) {
Owen Anderson9b1cc8c2007-08-09 04:42:44 +0000147 dep = MD.getDependency(BBI, dep);
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000148 continue;
Owen Andersond4451de2007-07-12 18:08:51 +0000149 }
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000150
151 // Remove it!
152 MD.removeInstruction(last);
153
154 // DCE instructions only used to calculate that store
155 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
156 possiblyDead.insert(D);
157 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(1)))
158 possiblyDead.insert(D);
Owen Anderson4e4b1162008-01-30 01:24:47 +0000159
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000160 last->eraseFromParent();
161 NumFastStores++;
162 deletedStore = true;
163 MadeChange = true;
164
165 break;
Owen Anderson5e72db32007-07-11 00:46:18 +0000166 }
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000167 }
168
169 // Handle frees whose dependencies are non-trivial.
170 if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
171 if (!deletedStore)
172 MadeChange |= handleFreeWithNonTrivialDependency(F,
Owen Anderson9b1cc8c2007-08-09 04:42:44 +0000173 MD.getDependency(F),
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000174 possiblyDead);
175 // No known stores after the free
176 last = 0;
177 } else {
Owen Anderson3f338972008-07-28 16:14:26 +0000178 StoreInst* S = cast<StoreInst>(BBI);
179
180 // If we're storing the same value back to a pointer that we just
181 // loaded from, then the store can be removed;
182 if (LoadInst* L = dyn_cast<LoadInst>(S->getOperand(0))) {
183 Instruction* dep = MD.getDependency(S);
184 DominatorTree& DT = getAnalysis<DominatorTree>();
185
Owen Anderson813bf7a2008-07-28 20:52:42 +0000186 if (!S->isVolatile() && S->getParent() == L->getParent() &&
Owen Anderson3f338972008-07-28 16:14:26 +0000187 S->getPointerOperand() == L->getPointerOperand() &&
188 ( dep == MemoryDependenceAnalysis::None ||
189 dep == MemoryDependenceAnalysis::NonLocal ||
190 DT.dominates(dep, L))) {
191 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
192 possiblyDead.insert(D);
193 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
194 possiblyDead.insert(D);
195
196 // Avoid iterator invalidation.
197 BBI--;
198
199 MD.removeInstruction(S);
200 S->eraseFromParent();
201 NumFastStores++;
202 MadeChange = true;
203 } else
204 // Update our most-recent-store map.
205 last = S;
206 } else
207 // Update our most-recent-store map.
208 last = S;
Owen Anderson5e72db32007-07-11 00:46:18 +0000209 }
210 }
211
Owen Anderson32c4a052007-07-12 21:41:30 +0000212 // If this block ends in a return, unwind, unreachable, and eventually
213 // tailcall, then all allocas are dead at its end.
214 if (BB.getTerminator()->getNumSuccessors() == 0)
215 MadeChange |= handleEndBlock(BB, possiblyDead);
216
Owen Anderson5e72db32007-07-11 00:46:18 +0000217 // Do a trivial DCE
218 while (!possiblyDead.empty()) {
219 Instruction *I = possiblyDead.back();
220 possiblyDead.pop_back();
221 DeleteDeadInstructionChains(I, possiblyDead);
222 }
223
224 return MadeChange;
225}
226
Owen Andersonaa071722007-07-11 23:19:17 +0000227/// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
228/// dependency is a store to a field of that structure
Owen Anderson10e52ed2007-08-01 06:36:51 +0000229bool DSE::handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dep,
Owen Andersone3590582007-08-02 18:11:11 +0000230 SetVector<Instruction*>& possiblyDead) {
Owen Andersonaa071722007-07-11 23:19:17 +0000231 TargetData &TD = getAnalysis<TargetData>();
232 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
233 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
234
Owen Andersond4451de2007-07-12 18:08:51 +0000235 if (dep == MemoryDependenceAnalysis::None ||
236 dep == MemoryDependenceAnalysis::NonLocal)
237 return false;
238
239 StoreInst* dependency = dyn_cast<StoreInst>(dep);
240 if (!dependency)
241 return false;
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000242 else if (dependency->isVolatile())
243 return false;
Owen Andersond4451de2007-07-12 18:08:51 +0000244
Owen Andersonaa071722007-07-11 23:19:17 +0000245 Value* depPointer = dependency->getPointerOperand();
Owen Andersone3590582007-08-02 18:11:11 +0000246 const Type* depType = dependency->getOperand(0)->getType();
Duncan Sands44b87212007-11-01 20:53:16 +0000247 unsigned depPointerSize = TD.getTypeStoreSize(depType);
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000248
Owen Andersonaa071722007-07-11 23:19:17 +0000249 // Check for aliasing
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000250 AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0U,
Owen Andersonaa071722007-07-11 23:19:17 +0000251 depPointer, depPointerSize);
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000252
Owen Andersonaa071722007-07-11 23:19:17 +0000253 if (A == AliasAnalysis::MustAlias) {
254 // Remove it!
255 MD.removeInstruction(dependency);
Owen Andersonaa071722007-07-11 23:19:17 +0000256
257 // DCE instructions only used to calculate that store
258 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
259 possiblyDead.insert(D);
Owen Anderson9c9ef212007-07-13 18:26:26 +0000260 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(1)))
261 possiblyDead.insert(D);
Owen Andersonaa071722007-07-11 23:19:17 +0000262
263 dependency->eraseFromParent();
264 NumFastStores++;
265 return true;
266 }
267
268 return false;
269}
270
Owen Andersone3590582007-08-02 18:11:11 +0000271/// handleEndBlock - Remove dead stores to stack-allocated locations in the
Owen Anderson52aaabf2007-08-08 17:50:09 +0000272/// function end block. Ex:
273/// %A = alloca i32
274/// ...
275/// store i32 1, i32* %A
276/// ret void
Owen Andersone3590582007-08-02 18:11:11 +0000277bool DSE::handleEndBlock(BasicBlock& BB,
278 SetVector<Instruction*>& possiblyDead) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000279 TargetData &TD = getAnalysis<TargetData>();
280 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
281 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
282
283 bool MadeChange = false;
284
285 // Pointers alloca'd in this function are dead in the end block
Owen Anderson48d37802008-01-29 06:18:36 +0000286 SmallPtrSet<Value*, 64> deadPointers;
Owen Anderson32c4a052007-07-12 21:41:30 +0000287
288 // Find all of the alloca'd pointers in the entry block
289 BasicBlock *Entry = BB.getParent()->begin();
290 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
291 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
292 deadPointers.insert(AI);
Owen Anderson48d37802008-01-29 06:18:36 +0000293 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
294 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
295 if (AI->hasByValAttr())
296 deadPointers.insert(AI);
Owen Anderson32c4a052007-07-12 21:41:30 +0000297
298 // Scan the basic block backwards
299 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
300 --BBI;
301
Owen Anderson32c4a052007-07-12 21:41:30 +0000302 // If we find a store whose pointer is dead...
303 if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000304 if (!S->isVolatile()) {
305 Value* pointerOperand = S->getPointerOperand();
306 // See through pointer-to-pointer bitcasts
307 TranslatePointerBitCasts(pointerOperand);
Owen Anderson9c9ef212007-07-13 18:26:26 +0000308
Owen Anderson6af19fd2008-01-25 10:10:33 +0000309 // Alloca'd pointers or byval arguments (which are functionally like
310 // alloca's) are valid candidates for removal.
Owen Anderson48d37802008-01-29 06:18:36 +0000311 if (deadPointers.count(pointerOperand)) {
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000312 // Remove it!
313 MD.removeInstruction(S);
Owen Anderson32c4a052007-07-12 21:41:30 +0000314
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000315 // DCE instructions only used to calculate that store
316 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
317 possiblyDead.insert(D);
318 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
319 possiblyDead.insert(D);
Owen Anderson32c4a052007-07-12 21:41:30 +0000320
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000321 BBI++;
Owen Anderson3f338972008-07-28 16:14:26 +0000322 MD.removeInstruction(S);
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000323 S->eraseFromParent();
324 NumFastStores++;
325 MadeChange = true;
326 }
Owen Anderson32c4a052007-07-12 21:41:30 +0000327 }
Owen Anderson52aaabf2007-08-08 17:50:09 +0000328
329 continue;
Owen Anderson48d37802008-01-29 06:18:36 +0000330
331 // We can also remove memcpy's to local variables at the end of a function
332 } else if (MemCpyInst* M = dyn_cast<MemCpyInst>(BBI)) {
333 Value* dest = M->getDest();
334 TranslatePointerBitCasts(dest);
335
336 if (deadPointers.count(dest)) {
337 MD.removeInstruction(M);
338
339 // DCE instructions only used to calculate that memcpy
Owen Anderson4e4b1162008-01-30 01:24:47 +0000340 if (Instruction* D = dyn_cast<Instruction>(M->getRawSource()))
Owen Anderson48d37802008-01-29 06:18:36 +0000341 possiblyDead.insert(D);
342 if (Instruction* D = dyn_cast<Instruction>(M->getLength()))
343 possiblyDead.insert(D);
344 if (Instruction* D = dyn_cast<Instruction>(M->getRawDest()))
345 possiblyDead.insert(D);
346
347 BBI++;
348 M->eraseFromParent();
349 NumFastOther++;
350 MadeChange = true;
351
352 continue;
353 }
354
355 // Because a memcpy is also a load, we can't skip it if we didn't remove it
Owen Anderson52aaabf2007-08-08 17:50:09 +0000356 }
357
358 Value* killPointer = 0;
Owen Andersona82c9932008-02-04 04:53:00 +0000359 uint64_t killPointerSize = ~0UL;
Owen Anderson32c4a052007-07-12 21:41:30 +0000360
361 // If we encounter a use of the pointer, it is no longer considered dead
Owen Anderson52aaabf2007-08-08 17:50:09 +0000362 if (LoadInst* L = dyn_cast<LoadInst>(BBI)) {
Nate Begeman53c5c622008-05-13 01:48:26 +0000363 // However, if this load is unused and not volatile, we can go ahead and
364 // remove it, and not have to worry about it making our pointer undead!
Dan Gohman8cb19d92008-04-28 19:51:27 +0000365 if (L->use_empty() && !L->isVolatile()) {
Owen Anderson4e4b1162008-01-30 01:24:47 +0000366 MD.removeInstruction(L);
367
368 // DCE instructions only used to calculate that load
369 if (Instruction* D = dyn_cast<Instruction>(L->getPointerOperand()))
370 possiblyDead.insert(D);
371
372 BBI++;
373 L->eraseFromParent();
374 NumFastOther++;
375 MadeChange = true;
376 possiblyDead.remove(L);
377
378 continue;
379 }
380
Owen Anderson32c4a052007-07-12 21:41:30 +0000381 killPointer = L->getPointerOperand();
Owen Anderson32c4a052007-07-12 21:41:30 +0000382 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
383 killPointer = V->getOperand(0);
Owen Andersona82c9932008-02-04 04:53:00 +0000384 } else if (isa<MemCpyInst>(BBI) &&
385 isa<ConstantInt>(cast<MemCpyInst>(BBI)->getLength())) {
386 killPointer = cast<MemCpyInst>(BBI)->getSource();
387 killPointerSize = cast<ConstantInt>(
388 cast<MemCpyInst>(BBI)->getLength())->getZExtValue();
Owen Anderson32c4a052007-07-12 21:41:30 +0000389 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
390 deadPointers.erase(A);
Owen Anderson4e4b1162008-01-30 01:24:47 +0000391
392 // Dead alloca's can be DCE'd when we reach them
Nick Lewycky6b016702008-01-30 08:01:28 +0000393 if (A->use_empty()) {
Owen Anderson4e4b1162008-01-30 01:24:47 +0000394 MD.removeInstruction(A);
395
396 // DCE instructions only used to calculate that load
397 if (Instruction* D = dyn_cast<Instruction>(A->getArraySize()))
398 possiblyDead.insert(D);
399
400 BBI++;
401 A->eraseFromParent();
402 NumFastOther++;
403 MadeChange = true;
404 possiblyDead.remove(A);
405 }
406
Owen Anderson32c4a052007-07-12 21:41:30 +0000407 continue;
408 } else if (CallSite::get(BBI).getInstruction() != 0) {
Owen Anderson50df9682007-08-08 17:58:56 +0000409 // If this call does not access memory, it can't
410 // be undeadifying any of our pointers.
411 CallSite CS = CallSite::get(BBI);
Duncan Sands68b6f502007-12-01 07:51:45 +0000412 if (AA.doesNotAccessMemory(CS))
Owen Anderson50df9682007-08-08 17:58:56 +0000413 continue;
414
Owen Andersonddf4aee2007-08-08 18:38:28 +0000415 unsigned modRef = 0;
416 unsigned other = 0;
417
Owen Anderson32c4a052007-07-12 21:41:30 +0000418 // Remove any pointers made undead by the call from the dead set
Owen Anderson48d37802008-01-29 06:18:36 +0000419 std::vector<Value*> dead;
420 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
Owen Anderson32c4a052007-07-12 21:41:30 +0000421 E = deadPointers.end(); I != E; ++I) {
Owen Andersonddf4aee2007-08-08 18:38:28 +0000422 // HACK: if we detect that our AA is imprecise, it's not
423 // worth it to scan the rest of the deadPointers set. Just
424 // assume that the AA will return ModRef for everything, and
425 // go ahead and bail.
426 if (modRef >= 16 && other == 0) {
427 deadPointers.clear();
428 return MadeChange;
429 }
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000430
Owen Anderson32c4a052007-07-12 21:41:30 +0000431 // Get size information for the alloca
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000432 unsigned pointerSize = ~0U;
Owen Anderson48d37802008-01-29 06:18:36 +0000433 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
434 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
435 pointerSize = C->getZExtValue() * \
436 TD.getABITypeSize(A->getAllocatedType());
437 } else {
438 const PointerType* PT = cast<PointerType>(
439 cast<Argument>(*I)->getType());
440 pointerSize = TD.getABITypeSize(PT->getElementType());
441 }
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000442
Owen Anderson32c4a052007-07-12 21:41:30 +0000443 // See if the call site touches it
Owen Anderson50df9682007-08-08 17:58:56 +0000444 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
Owen Andersonddf4aee2007-08-08 18:38:28 +0000445
446 if (A == AliasAnalysis::ModRef)
447 modRef++;
448 else
449 other++;
450
Owen Anderson9c9ef212007-07-13 18:26:26 +0000451 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
Owen Anderson32c4a052007-07-12 21:41:30 +0000452 dead.push_back(*I);
453 }
454
Owen Anderson48d37802008-01-29 06:18:36 +0000455 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
Owen Anderson32c4a052007-07-12 21:41:30 +0000456 I != E; ++I)
Owen Anderson48d37802008-01-29 06:18:36 +0000457 deadPointers.erase(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000458
459 continue;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000460 } else {
461 // For any non-memory-affecting non-terminators, DCE them as we reach them
462 Instruction *CI = BBI;
Nick Lewycky625e89c2008-01-30 07:54:16 +0000463 if (!CI->isTerminator() && CI->use_empty() && !isa<FreeInst>(CI)) {
Owen Anderson4e4b1162008-01-30 01:24:47 +0000464
465 // DCE instructions only used to calculate that load
466 for (Instruction::op_iterator OI = CI->op_begin(), OE = CI->op_end();
467 OI != OE; ++OI)
468 if (Instruction* D = dyn_cast<Instruction>(OI))
469 possiblyDead.insert(D);
470
471 BBI++;
472 CI->eraseFromParent();
473 NumFastOther++;
474 MadeChange = true;
475 possiblyDead.remove(CI);
476
477 continue;
478 }
Owen Anderson32c4a052007-07-12 21:41:30 +0000479 }
480
481 if (!killPointer)
482 continue;
483
Owen Andersonddf4aee2007-08-08 18:38:28 +0000484 TranslatePointerBitCasts(killPointer);
485
Owen Anderson32c4a052007-07-12 21:41:30 +0000486 // Deal with undead pointers
Owen Andersona82c9932008-02-04 04:53:00 +0000487 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
Owen Anderson32c4a052007-07-12 21:41:30 +0000488 deadPointers, possiblyDead);
489 }
490
491 return MadeChange;
492}
493
Owen Andersonddf4aee2007-08-08 18:38:28 +0000494/// RemoveUndeadPointers - check for uses of a pointer that make it
495/// undead when scanning for dead stores to alloca's.
Owen Andersona82c9932008-02-04 04:53:00 +0000496bool DSE::RemoveUndeadPointers(Value* killPointer, uint64_t killPointerSize,
Owen Anderson32c4a052007-07-12 21:41:30 +0000497 BasicBlock::iterator& BBI,
Owen Anderson48d37802008-01-29 06:18:36 +0000498 SmallPtrSet<Value*, 64>& deadPointers,
Owen Anderson32c4a052007-07-12 21:41:30 +0000499 SetVector<Instruction*>& possiblyDead) {
500 TargetData &TD = getAnalysis<TargetData>();
501 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
502 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
503
Owen Andersonddf4aee2007-08-08 18:38:28 +0000504 // If the kill pointer can be easily reduced to an alloca,
505 // don't bother doing extraneous AA queries
Owen Anderson48d37802008-01-29 06:18:36 +0000506 if (deadPointers.count(killPointer)) {
507 deadPointers.erase(killPointer);
Owen Andersonddf4aee2007-08-08 18:38:28 +0000508 return false;
Owen Anderson68086282007-08-08 19:12:31 +0000509 } else if (isa<GlobalValue>(killPointer)) {
510 // A global can't be in the dead pointer set
511 return false;
Owen Andersonddf4aee2007-08-08 18:38:28 +0000512 }
513
Owen Anderson32c4a052007-07-12 21:41:30 +0000514 bool MadeChange = false;
515
Owen Anderson48d37802008-01-29 06:18:36 +0000516 std::vector<Value*> undead;
Owen Anderson32c4a052007-07-12 21:41:30 +0000517
Owen Anderson48d37802008-01-29 06:18:36 +0000518 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
Owen Anderson32c4a052007-07-12 21:41:30 +0000519 E = deadPointers.end(); I != E; ++I) {
520 // Get size information for the alloca
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000521 unsigned pointerSize = ~0U;
Owen Anderson48d37802008-01-29 06:18:36 +0000522 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
523 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
524 pointerSize = C->getZExtValue() * \
525 TD.getABITypeSize(A->getAllocatedType());
526 } else {
527 const PointerType* PT = cast<PointerType>(
528 cast<Argument>(*I)->getType());
529 pointerSize = TD.getABITypeSize(PT->getElementType());
530 }
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000531
Owen Anderson32c4a052007-07-12 21:41:30 +0000532 // See if this pointer could alias it
Owen Andersone3590582007-08-02 18:11:11 +0000533 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
Owen Andersona82c9932008-02-04 04:53:00 +0000534 killPointer, killPointerSize);
Owen Anderson32c4a052007-07-12 21:41:30 +0000535
536 // If it must-alias and a store, we can delete it
537 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
538 StoreInst* S = cast<StoreInst>(BBI);
539
540 // Remove it!
541 MD.removeInstruction(S);
542
543 // DCE instructions only used to calculate that store
544 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
545 possiblyDead.insert(D);
Owen Anderson9c9ef212007-07-13 18:26:26 +0000546 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
547 possiblyDead.insert(D);
Owen Anderson32c4a052007-07-12 21:41:30 +0000548
549 BBI++;
550 S->eraseFromParent();
551 NumFastStores++;
552 MadeChange = true;
553
554 continue;
555
556 // Otherwise, it is undead
557 } else if (A != AliasAnalysis::NoAlias)
558 undead.push_back(*I);
559 }
560
Owen Anderson48d37802008-01-29 06:18:36 +0000561 for (std::vector<Value*>::iterator I = undead.begin(), E = undead.end();
Owen Anderson32c4a052007-07-12 21:41:30 +0000562 I != E; ++I)
Owen Anderson48d37802008-01-29 06:18:36 +0000563 deadPointers.erase(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000564
565 return MadeChange;
566}
567
Owen Anderson52aaabf2007-08-08 17:50:09 +0000568/// DeleteDeadInstructionChains - takes an instruction and a setvector of
569/// dead instructions. If I is dead, it is erased, and its operands are
570/// checked for deadness. If they are dead, they are added to the dead
571/// setvector.
Owen Anderson10e52ed2007-08-01 06:36:51 +0000572void DSE::DeleteDeadInstructionChains(Instruction *I,
Owen Anderson5e72db32007-07-11 00:46:18 +0000573 SetVector<Instruction*> &DeadInsts) {
574 // Instruction must be dead.
575 if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
576
577 // Let the memory dependence know
578 getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
579
580 // See if this made any operands dead. We do it this way in case the
581 // instruction uses the same operand twice. We don't want to delete a
582 // value then reference it.
583 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Owen Andersonbf971aa2007-07-11 19:03:09 +0000584 if (I->getOperand(i)->hasOneUse())
585 if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
586 DeadInsts.insert(Op); // Attempt to nuke it later.
587
Owen Anderson5e72db32007-07-11 00:46:18 +0000588 I->setOperand(i, 0); // Drop from the operand list.
589 }
590
591 I->eraseFromParent();
592 ++NumFastOther;
593}