blob: 7794953e43214bfdbb4a27747e15df66b735ed7c [file] [log] [blame]
Owen Anderson5e72db32007-07-11 00:46:18 +00001//===- DeadStoreElimination.cpp - Dead Store Elimination ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Owen Andersonbf971aa2007-07-11 19:03:09 +00005// This file was developed by Owen Anderson and is distributed under
Owen Anderson5e72db32007-07-11 00:46:18 +00006// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a trivial dead store elimination that only considers
11// basic-block local redundant stores.
12//
13// FIXME: This should eventually be extended to be a post-dominator tree
14// traversal. Doing so would be pretty trivial.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "fdse"
19#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"
23#include "llvm/Pass.h"
24#include "llvm/ADT/SetVector.h"
25#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 Anderson5e72db32007-07-11 00:46:18 +000028#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Owen Andersonaa071722007-07-11 23:19:17 +000029#include "llvm/Target/TargetData.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000030#include "llvm/Transforms/Utils/Local.h"
31#include "llvm/Support/Compiler.h"
32using namespace llvm;
33
34STATISTIC(NumFastStores, "Number of stores deleted");
35STATISTIC(NumFastOther , "Number of other instrs removed");
36
37namespace {
38 struct VISIBILITY_HIDDEN FDSE : public FunctionPass {
39 static char ID; // Pass identification, replacement for typeid
40 FDSE() : FunctionPass((intptr_t)&ID) {}
41
42 virtual bool runOnFunction(Function &F) {
43 bool Changed = false;
44 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
45 Changed |= runOnBasicBlock(*I);
46 return Changed;
47 }
48
49 bool runOnBasicBlock(BasicBlock &BB);
Owen Andersond4451de2007-07-12 18:08:51 +000050 bool handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dependency,
Owen Andersonaa071722007-07-11 23:19:17 +000051 SetVector<Instruction*>& possiblyDead);
Owen Anderson32c4a052007-07-12 21:41:30 +000052 bool handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead);
53 bool RemoveUndeadPointers(Value* pointer, unsigned pointerSize,
54 BasicBlock::iterator& BBI,
55 SmallPtrSet<AllocaInst*, 4>& deadPointers,
56 SetVector<Instruction*>& possiblyDead);
Owen Anderson5e72db32007-07-11 00:46:18 +000057 void DeleteDeadInstructionChains(Instruction *I,
58 SetVector<Instruction*> &DeadInsts);
59
60 // getAnalysisUsage - We require post dominance frontiers (aka Control
61 // Dependence Graph)
62 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
63 AU.setPreservesCFG();
Owen Andersonaa071722007-07-11 23:19:17 +000064 AU.addRequired<TargetData>();
65 AU.addRequired<AliasAnalysis>();
Owen Anderson5e72db32007-07-11 00:46:18 +000066 AU.addRequired<MemoryDependenceAnalysis>();
Owen Andersonaa071722007-07-11 23:19:17 +000067 AU.addPreserved<AliasAnalysis>();
Owen Anderson5e72db32007-07-11 00:46:18 +000068 AU.addPreserved<MemoryDependenceAnalysis>();
69 }
70 };
71 char FDSE::ID = 0;
72 RegisterPass<FDSE> X("fdse", "Fast Dead Store Elimination");
73}
74
75FunctionPass *llvm::createFastDeadStoreEliminationPass() { return new FDSE(); }
76
77bool FDSE::runOnBasicBlock(BasicBlock &BB) {
78 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
79
Owen Andersonbf971aa2007-07-11 19:03:09 +000080 // Record the last-seen store to this pointer
Owen Anderson5e72db32007-07-11 00:46:18 +000081 DenseMap<Value*, StoreInst*> lastStore;
Owen Andersonbf971aa2007-07-11 19:03:09 +000082 // Record instructions possibly made dead by deleting a store
Owen Anderson5e72db32007-07-11 00:46:18 +000083 SetVector<Instruction*> possiblyDead;
84
85 bool MadeChange = false;
86
87 // Do a top-down walk on the BB
88 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ++BBI) {
Owen Anderson14414702007-07-11 21:06:56 +000089 // If we find a store or a free...
Owen Andersone7201442007-07-11 20:38:34 +000090 if (isa<StoreInst>(BBI) || isa<FreeInst>(BBI)) {
91 Value* pointer = 0;
92 if (StoreInst* S = dyn_cast<StoreInst>(BBI))
93 pointer = S->getPointerOperand();
94 else if (FreeInst* F = dyn_cast<FreeInst>(BBI))
95 pointer = F->getPointerOperand();
96 assert(pointer && "Not a free or a store?");
97
98 StoreInst*& last = lastStore[pointer];
Owen Andersond4451de2007-07-12 18:08:51 +000099 bool deletedStore = false;
Owen Anderson5e72db32007-07-11 00:46:18 +0000100
101 // ... to a pointer that has been stored to before...
Owen Andersonbf971aa2007-07-11 19:03:09 +0000102 if (last) {
Owen Anderson5e72db32007-07-11 00:46:18 +0000103
104 // ... and no other memory dependencies are between them....
Owen Andersone7201442007-07-11 20:38:34 +0000105 if (MD.getDependency(BBI) == last) {
106
Owen Anderson5e72db32007-07-11 00:46:18 +0000107 // Remove it!
108 MD.removeInstruction(last);
109
110 // DCE instructions only used to calculate that store
111 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
112 possiblyDead.insert(D);
113
114 last->eraseFromParent();
115 NumFastStores++;
Owen Andersond4451de2007-07-12 18:08:51 +0000116 deletedStore = true;
Owen Anderson5e72db32007-07-11 00:46:18 +0000117 MadeChange = true;
Owen Andersond4451de2007-07-12 18:08:51 +0000118 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000119 }
120
Owen Andersond4451de2007-07-12 18:08:51 +0000121 // Handle frees whose dependencies are non-trivial
122 if (FreeInst* F = dyn_cast<FreeInst>(BBI))
123 if (!deletedStore)
124 MadeChange |= handleFreeWithNonTrivialDependency(F, MD.getDependency(F),
125 possiblyDead);
126
Owen Anderson5e72db32007-07-11 00:46:18 +0000127 // Update our most-recent-store map
Owen Andersone7201442007-07-11 20:38:34 +0000128 if (StoreInst* S = dyn_cast<StoreInst>(BBI))
129 last = S;
130 else
131 last = 0;
Owen Anderson5e72db32007-07-11 00:46:18 +0000132 }
133 }
134
Owen Anderson32c4a052007-07-12 21:41:30 +0000135 // If this block ends in a return, unwind, unreachable, and eventually
136 // tailcall, then all allocas are dead at its end.
137 if (BB.getTerminator()->getNumSuccessors() == 0)
138 MadeChange |= handleEndBlock(BB, possiblyDead);
139
Owen Anderson5e72db32007-07-11 00:46:18 +0000140 // Do a trivial DCE
141 while (!possiblyDead.empty()) {
142 Instruction *I = possiblyDead.back();
143 possiblyDead.pop_back();
144 DeleteDeadInstructionChains(I, possiblyDead);
145 }
146
147 return MadeChange;
148}
149
Owen Andersonaa071722007-07-11 23:19:17 +0000150/// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
151/// dependency is a store to a field of that structure
Owen Andersond4451de2007-07-12 18:08:51 +0000152bool FDSE::handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dep,
Owen Andersonaa071722007-07-11 23:19:17 +0000153 SetVector<Instruction*>& possiblyDead) {
154 TargetData &TD = getAnalysis<TargetData>();
155 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
156 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
157
Owen Andersond4451de2007-07-12 18:08:51 +0000158 if (dep == MemoryDependenceAnalysis::None ||
159 dep == MemoryDependenceAnalysis::NonLocal)
160 return false;
161
162 StoreInst* dependency = dyn_cast<StoreInst>(dep);
163 if (!dependency)
164 return false;
165
Owen Andersonaa071722007-07-11 23:19:17 +0000166 Value* depPointer = dependency->getPointerOperand();
167 unsigned depPointerSize = TD.getTypeSize(dependency->getOperand(0)->getType());
168
169 // Check for aliasing
170 AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0UL,
171 depPointer, depPointerSize);
172
173 if (A == AliasAnalysis::MustAlias) {
174 // Remove it!
175 MD.removeInstruction(dependency);
Owen Andersonaa071722007-07-11 23:19:17 +0000176
177 // DCE instructions only used to calculate that store
178 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
179 possiblyDead.insert(D);
180
181 dependency->eraseFromParent();
182 NumFastStores++;
183 return true;
184 }
185
186 return false;
187}
188
Owen Anderson32c4a052007-07-12 21:41:30 +0000189/// handleEndBlock - Remove dead stores to stack-allocated locations in the function
190/// end block
191bool FDSE::handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead) {
192 TargetData &TD = getAnalysis<TargetData>();
193 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
194 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
195
196 bool MadeChange = false;
197
198 // Pointers alloca'd in this function are dead in the end block
199 SmallPtrSet<AllocaInst*, 4> deadPointers;
200
201 // Find all of the alloca'd pointers in the entry block
202 BasicBlock *Entry = BB.getParent()->begin();
203 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
204 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
205 deadPointers.insert(AI);
206
207 // Scan the basic block backwards
208 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
209 --BBI;
210
211 if (deadPointers.empty())
212 break;
213
214 Value* killPointer = 0;
215 unsigned killPointerSize = 0;
216
217 // If we find a store whose pointer is dead...
218 if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
219 if (deadPointers.count(S->getPointerOperand())){
220 // Remove it!
221 MD.removeInstruction(S);
222
223 // DCE instructions only used to calculate that store
224 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
225 possiblyDead.insert(D);
226
227 BBI++;
228 S->eraseFromParent();
229 NumFastStores++;
230 MadeChange = true;
231
232 // If we can't trivially delete this store, consider it undead
233 } else {
234 killPointer = S->getPointerOperand();
235 killPointerSize = TD.getTypeSize(S->getOperand(0)->getType());
236 }
237
238 // If we encounter a use of the pointer, it is no longer considered dead
239 } else if (LoadInst* L = dyn_cast<LoadInst>(BBI)) {
240 killPointer = L->getPointerOperand();
241 killPointerSize = TD.getTypeSize(L->getType());
242 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
243 killPointer = V->getOperand(0);
244 killPointerSize = TD.getTypeSize(V->getType());
245 } else if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
246 killPointer = F->getPointerOperand();
247 killPointerSize = ~0UL;
248 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
249 deadPointers.erase(A);
250 continue;
251 } else if (CallSite::get(BBI).getInstruction() != 0) {
252 // Remove any pointers made undead by the call from the dead set
253 std::vector<Instruction*> dead;
254 for (SmallPtrSet<AllocaInst*, 4>::iterator I = deadPointers.begin(),
255 E = deadPointers.end(); I != E; ++I) {
256 // Get size information for the alloca
257 unsigned pointerSize = ~0UL;
258 if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
259 pointerSize = C->getZExtValue() * TD.getTypeSize((*I)->getAllocatedType());
260
261 // See if the call site touches it
262 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CallSite::get(BBI),
263 *I, pointerSize);
264 if (A != AliasAnalysis::NoModRef)
265 dead.push_back(*I);
266 }
267
268 for (std::vector<Instruction*>::iterator I = dead.begin(), E = dead.end();
269 I != E; ++I)
270 deadPointers.erase(*I);
271
272 continue;
273 }
274
275 if (!killPointer)
276 continue;
277
278 // Deal with undead pointers
279 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
280 deadPointers, possiblyDead);
281 }
282
283 return MadeChange;
284}
285
286bool FDSE::RemoveUndeadPointers(Value* killPointer, unsigned killPointerSize,
287 BasicBlock::iterator& BBI,
288 SmallPtrSet<AllocaInst*, 4>& deadPointers,
289 SetVector<Instruction*>& possiblyDead) {
290 TargetData &TD = getAnalysis<TargetData>();
291 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
292 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
293
294 bool MadeChange = false;
295
296 std::vector<Instruction*> undead;
297
298 for (SmallPtrSet<AllocaInst*, 4>::iterator I = deadPointers.begin(),
299 E = deadPointers.end(); I != E; ++I) {
300 // Get size information for the alloca
301 unsigned pointerSize = ~0UL;
302 if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
303 pointerSize = C->getZExtValue() * TD.getTypeSize((*I)->getAllocatedType());
304
305 // See if this pointer could alias it
306 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize, killPointer, killPointerSize);
307
308 // If it must-alias and a store, we can delete it
309 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
310 StoreInst* S = cast<StoreInst>(BBI);
311
312 // Remove it!
313 MD.removeInstruction(S);
314
315 // DCE instructions only used to calculate that store
316 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
317 possiblyDead.insert(D);
318
319 BBI++;
320 S->eraseFromParent();
321 NumFastStores++;
322 MadeChange = true;
323
324 continue;
325
326 // Otherwise, it is undead
327 } else if (A != AliasAnalysis::NoAlias)
328 undead.push_back(*I);
329 }
330
331 for (std::vector<Instruction*>::iterator I = undead.begin(), E = undead.end();
332 I != E; ++I)
333 deadPointers.erase(*I);
334
335 return MadeChange;
336}
337
Owen Anderson5e72db32007-07-11 00:46:18 +0000338void FDSE::DeleteDeadInstructionChains(Instruction *I,
339 SetVector<Instruction*> &DeadInsts) {
340 // Instruction must be dead.
341 if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
342
343 // Let the memory dependence know
344 getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
345
346 // See if this made any operands dead. We do it this way in case the
347 // instruction uses the same operand twice. We don't want to delete a
348 // value then reference it.
349 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Owen Andersonbf971aa2007-07-11 19:03:09 +0000350 if (I->getOperand(i)->hasOneUse())
351 if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
352 DeadInsts.insert(Op); // Attempt to nuke it later.
353
Owen Anderson5e72db32007-07-11 00:46:18 +0000354 I->setOperand(i, 0); // Drop from the operand list.
355 }
356
357 I->eraseFromParent();
358 ++NumFastOther;
359}