blob: 557cd6d2b53ef81a3e3c3ce6eae12c855cc10a57 [file] [log] [blame]
Chris Lattner12be9362011-01-02 21:47:05 +00001//===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs a simple dominator tree walk that eliminates trivially
11// redundant instructions.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "early-cse"
16#include "llvm/Transforms/Scalar.h"
Chris Lattner91139cc2011-01-02 23:19:45 +000017#include "llvm/Instructions.h"
Chris Lattner12be9362011-01-02 21:47:05 +000018#include "llvm/Pass.h"
Chris Lattnercc9eab22011-01-02 23:04:14 +000019#include "llvm/Analysis/Dominators.h"
20#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnercc9eab22011-01-02 23:04:14 +000021#include "llvm/Target/TargetData.h"
22#include "llvm/Transforms/Utils/Local.h"
Chris Lattner91139cc2011-01-02 23:19:45 +000023#include "llvm/Support/Debug.h"
Chris Lattner82dcd5e2011-01-03 01:42:46 +000024#include "llvm/Support/RecyclingAllocator.h"
Chris Lattnercc9eab22011-01-02 23:04:14 +000025#include "llvm/ADT/ScopedHashTable.h"
Chris Lattner91139cc2011-01-02 23:19:45 +000026#include "llvm/ADT/Statistic.h"
Chris Lattner12be9362011-01-02 21:47:05 +000027using namespace llvm;
28
Chris Lattner91139cc2011-01-02 23:19:45 +000029STATISTIC(NumSimplify, "Number of insts simplified or DCE'd");
Chris Lattner8e7f0d72011-01-03 03:18:43 +000030STATISTIC(NumCSE, "Number of insts CSE'd");
31STATISTIC(NumCSEMem, "Number of load and call insts CSE'd");
32
33static unsigned getHash(const void *V) {
34 return DenseMapInfo<const void*>::getHashValue(V);
35}
Chris Lattner91139cc2011-01-02 23:19:45 +000036
Chris Lattnerf1974592011-01-03 02:20:48 +000037//===----------------------------------------------------------------------===//
38// SimpleValue
39//===----------------------------------------------------------------------===//
40
Chris Lattner12be9362011-01-02 21:47:05 +000041namespace {
Chris Lattnerf1974592011-01-03 02:20:48 +000042 /// SimpleValue - Instances of this struct represent available values in the
Chris Lattnercc9eab22011-01-02 23:04:14 +000043 /// scoped hash table.
Chris Lattnerf1974592011-01-03 02:20:48 +000044 struct SimpleValue {
Chris Lattnercc9eab22011-01-02 23:04:14 +000045 Instruction *Inst;
46
47 bool isSentinel() const {
48 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
49 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
50 }
51
52 static bool canHandle(Instruction *Inst) {
Chris Lattner91139cc2011-01-02 23:19:45 +000053 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
54 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
55 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
56 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
57 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
Chris Lattnercc9eab22011-01-02 23:04:14 +000058 }
59
Chris Lattnerf1974592011-01-03 02:20:48 +000060 static SimpleValue get(Instruction *I) {
61 SimpleValue X; X.Inst = I;
Chris Lattnercc9eab22011-01-02 23:04:14 +000062 assert((X.isSentinel() || canHandle(I)) && "Inst can't be handled!");
63 return X;
64 }
65 };
66}
67
68namespace llvm {
Chris Lattnerf1974592011-01-03 02:20:48 +000069// SimpleValue is POD.
70template<> struct isPodLike<SimpleValue> {
Chris Lattnercc9eab22011-01-02 23:04:14 +000071 static const bool value = true;
72};
73
Chris Lattnerf1974592011-01-03 02:20:48 +000074template<> struct DenseMapInfo<SimpleValue> {
75 static inline SimpleValue getEmptyKey() {
76 return SimpleValue::get(DenseMapInfo<Instruction*>::getEmptyKey());
Chris Lattnercc9eab22011-01-02 23:04:14 +000077 }
Chris Lattnerf1974592011-01-03 02:20:48 +000078 static inline SimpleValue getTombstoneKey() {
79 return SimpleValue::get(DenseMapInfo<Instruction*>::getTombstoneKey());
Chris Lattnercc9eab22011-01-02 23:04:14 +000080 }
Chris Lattnerf1974592011-01-03 02:20:48 +000081 static unsigned getHashValue(SimpleValue Val);
82 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
Chris Lattnercc9eab22011-01-02 23:04:14 +000083};
84}
85
Chris Lattnerf1974592011-01-03 02:20:48 +000086unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
Chris Lattnercc9eab22011-01-02 23:04:14 +000087 Instruction *Inst = Val.Inst;
Chris Lattnercc9eab22011-01-02 23:04:14 +000088
Chris Lattnerd957c712011-01-03 01:10:08 +000089 // Hash in all of the operands as pointers.
90 unsigned Res = 0;
91 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
92 Res ^= getHash(Inst->getOperand(i)) << i;
93
94 if (CastInst *CI = dyn_cast<CastInst>(Inst))
95 Res ^= getHash(CI->getType());
96 else if (CmpInst *CI = dyn_cast<CmpInst>(Inst))
97 Res ^= CI->getPredicate();
98 else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst)) {
99 for (ExtractValueInst::idx_iterator I = EVI->idx_begin(),
100 E = EVI->idx_end(); I != E; ++I)
101 Res ^= *I;
102 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst)) {
103 for (InsertValueInst::idx_iterator I = IVI->idx_begin(),
104 E = IVI->idx_end(); I != E; ++I)
105 Res ^= *I;
106 } else {
107 // nothing extra to hash in.
108 assert((isa<BinaryOperator>(Inst) || isa<GetElementPtrInst>(Inst) ||
109 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
110 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst)) &&
111 "Invalid/unknown instruction");
112 }
113
114 // Mix in the opcode.
Chris Lattnercc9eab22011-01-02 23:04:14 +0000115 return (Res << 1) ^ Inst->getOpcode();
116}
117
Chris Lattnerf1974592011-01-03 02:20:48 +0000118bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
Chris Lattnercc9eab22011-01-02 23:04:14 +0000119 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
120
121 if (LHS.isSentinel() || RHS.isSentinel())
122 return LHSI == RHSI;
123
124 if (LHSI->getOpcode() != RHSI->getOpcode()) return false;
125 return LHSI->isIdenticalTo(RHSI);
126}
127
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000128//===----------------------------------------------------------------------===//
129// MemoryValue
130//===----------------------------------------------------------------------===//
131
132namespace {
133 /// MemoryValue - Instances of this struct represent available load and call
134 /// values in the scoped hash table.
135 struct MemoryValue {
136 Instruction *Inst;
137
138 bool isSentinel() const {
139 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
140 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
141 }
142
143 static bool canHandle(Instruction *Inst) {
144 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
145 return !LI->isVolatile();
146 if (CallInst *CI = dyn_cast<CallInst>(Inst))
147 return CI->onlyReadsMemory();
148 return false;
149 }
150
151 static MemoryValue get(Instruction *I) {
152 MemoryValue X; X.Inst = I;
153 assert((X.isSentinel() || canHandle(I)) && "Inst can't be handled!");
154 return X;
155 }
156 };
157}
158
159namespace llvm {
160 // MemoryValue is POD.
161 template<> struct isPodLike<MemoryValue> {
162 static const bool value = true;
163 };
164
165 template<> struct DenseMapInfo<MemoryValue> {
166 static inline MemoryValue getEmptyKey() {
167 return MemoryValue::get(DenseMapInfo<Instruction*>::getEmptyKey());
168 }
169 static inline MemoryValue getTombstoneKey() {
170 return MemoryValue::get(DenseMapInfo<Instruction*>::getTombstoneKey());
171 }
172 static unsigned getHashValue(MemoryValue Val);
173 static bool isEqual(MemoryValue LHS, MemoryValue RHS);
174 };
175}
176unsigned DenseMapInfo<MemoryValue>::getHashValue(MemoryValue Val) {
177 Instruction *Inst = Val.Inst;
178 // Hash in all of the operands as pointers.
179 unsigned Res = 0;
180 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
181 Res ^= getHash(Inst->getOperand(i)) << i;
182 // Mix in the opcode.
183 return (Res << 1) ^ Inst->getOpcode();
184}
185
186bool DenseMapInfo<MemoryValue>::isEqual(MemoryValue LHS, MemoryValue RHS) {
187 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
188
189 if (LHS.isSentinel() || RHS.isSentinel())
190 return LHSI == RHSI;
191
192 if (LHSI->getOpcode() != RHSI->getOpcode()) return false;
193 return LHSI->isIdenticalTo(RHSI);
194}
195
Chris Lattnercc9eab22011-01-02 23:04:14 +0000196
Chris Lattnerf1974592011-01-03 02:20:48 +0000197//===----------------------------------------------------------------------===//
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000198// EarlyCSE pass.
Chris Lattnerf1974592011-01-03 02:20:48 +0000199//===----------------------------------------------------------------------===//
200
Chris Lattnercc9eab22011-01-02 23:04:14 +0000201namespace {
202
Chris Lattner12be9362011-01-02 21:47:05 +0000203/// EarlyCSE - This pass does a simple depth-first walk over the dominator
204/// tree, eliminating trivially redundant instructions and using instsimplify
205/// to canonicalize things as it goes. It is intended to be fast and catch
206/// obvious cases so that instcombine and other passes are more effective. It
207/// is expected that a later pass of GVN will catch the interesting/hard
208/// cases.
209class EarlyCSE : public FunctionPass {
210public:
Chris Lattnercc9eab22011-01-02 23:04:14 +0000211 const TargetData *TD;
212 DominatorTree *DT;
Chris Lattner82dcd5e2011-01-03 01:42:46 +0000213 typedef RecyclingAllocator<BumpPtrAllocator,
Chris Lattnerf1974592011-01-03 02:20:48 +0000214 ScopedHashTableVal<SimpleValue, Value*> > AllocatorTy;
215 typedef ScopedHashTable<SimpleValue, Value*, DenseMapInfo<SimpleValue>,
Chris Lattner82dcd5e2011-01-03 01:42:46 +0000216 AllocatorTy> ScopedHTType;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000217
Chris Lattnerf1974592011-01-03 02:20:48 +0000218 /// AvailableValues - This scoped hash table contains the current values of
219 /// all of our simple scalar expressions. As we walk down the domtree, we
220 /// look to see if instructions are in this: if so, we replace them with what
221 /// we find, otherwise we insert them so that dominated values can succeed in
222 /// their lookup.
223 ScopedHTType *AvailableValues;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000224
225 typedef ScopedHashTable<MemoryValue, std::pair<Value*, unsigned> > MemHTType;
226 /// AvailableMemValues - This scoped hash table contains the current values of
227 /// loads and other read-only memory values. This allows us to get efficient
228 /// access to dominating loads we we find a fully redundant load. In addition
229 /// to the most recent load, we keep track of a generation count of the read,
230 /// which is compared against the current generation count. The current
231 /// generation count is incremented after every possibly writing memory
232 /// operation, which ensures that we only CSE loads with other loads that have
233 /// no intervening store.
234 MemHTType *AvailableMemValues;
235
236 /// CurrentGeneration - This is the current generation of the memory value.
237 unsigned CurrentGeneration;
238
Chris Lattner12be9362011-01-02 21:47:05 +0000239 static char ID;
Chris Lattnerf1974592011-01-03 02:20:48 +0000240 explicit EarlyCSE() : FunctionPass(ID) {
Chris Lattner12be9362011-01-02 21:47:05 +0000241 initializeEarlyCSEPass(*PassRegistry::getPassRegistry());
242 }
243
244 bool runOnFunction(Function &F);
245
246private:
Chris Lattnercc9eab22011-01-02 23:04:14 +0000247
248 bool processNode(DomTreeNode *Node);
249
Chris Lattner12be9362011-01-02 21:47:05 +0000250 // This transformation requires dominator postdominator info
251 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
252 AU.addRequired<DominatorTree>();
253 AU.setPreservesCFG();
254 }
255};
256}
257
258char EarlyCSE::ID = 0;
259
260// createEarlyCSEPass - The public interface to this file.
261FunctionPass *llvm::createEarlyCSEPass() {
262 return new EarlyCSE();
263}
264
265INITIALIZE_PASS_BEGIN(EarlyCSE, "early-cse", "Early CSE", false, false)
266INITIALIZE_PASS_DEPENDENCY(DominatorTree)
267INITIALIZE_PASS_END(EarlyCSE, "early-cse", "Early CSE", false, false)
268
Chris Lattnercc9eab22011-01-02 23:04:14 +0000269bool EarlyCSE::processNode(DomTreeNode *Node) {
Chris Lattnerf1974592011-01-03 02:20:48 +0000270 // Define a scope in the scoped hash table. When we are done processing this
271 // domtree node and recurse back up to our parent domtree node, this will pop
272 // off all the values we install.
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000273 ScopedHTType::ScopeTy Scope(*AvailableValues);
274
275 // Define a scope for the memory values so that anything we add will get
276 // popped when we recurse back up to our parent domtree node.
277 MemHTType::ScopeTy MemScope(*AvailableMemValues);
Chris Lattnercc9eab22011-01-02 23:04:14 +0000278
279 BasicBlock *BB = Node->getBlock();
280
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000281 // If this block has a single predecessor, then the predecessor is the parent
282 // of the domtree node and all of the live out memory values are still current
283 // in this block. If this block has multiple predecessors, then they could
284 // have invalidated the live-out memory values of our parent value. For now,
285 // just be conservative and invalidate memory if this block has multiple
286 // predecessors.
287 if (BB->getSinglePredecessor() == 0)
288 ++CurrentGeneration;
289
Chris Lattnercc9eab22011-01-02 23:04:14 +0000290 bool Changed = false;
291
292 // See if any instructions in the block can be eliminated. If so, do it. If
293 // not, add them to AvailableValues.
294 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
295 Instruction *Inst = I++;
296
297 // Dead instructions should just be removed.
298 if (isInstructionTriviallyDead(Inst)) {
Chris Lattner91139cc2011-01-02 23:19:45 +0000299 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Chris Lattnercc9eab22011-01-02 23:04:14 +0000300 Inst->eraseFromParent();
301 Changed = true;
Chris Lattner91139cc2011-01-02 23:19:45 +0000302 ++NumSimplify;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000303 continue;
304 }
305
306 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
307 // its simpler value.
308 if (Value *V = SimplifyInstruction(Inst, TD, DT)) {
Chris Lattner91139cc2011-01-02 23:19:45 +0000309 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
Chris Lattnercc9eab22011-01-02 23:04:14 +0000310 Inst->replaceAllUsesWith(V);
311 Inst->eraseFromParent();
312 Changed = true;
Chris Lattner91139cc2011-01-02 23:19:45 +0000313 ++NumSimplify;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000314 continue;
315 }
316
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000317 // If this is a simple instruction that we can value number, process it.
318 if (SimpleValue::canHandle(Inst)) {
319 // See if the instruction has an available value. If so, use it.
320 if (Value *V = AvailableValues->lookup(SimpleValue::get(Inst))) {
321 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
322 Inst->replaceAllUsesWith(V);
323 Inst->eraseFromParent();
324 Changed = true;
325 ++NumCSE;
326 continue;
327 }
328
329 // Otherwise, just remember that this value is available.
330 AvailableValues->insert(SimpleValue::get(Inst), Inst);
Chris Lattnercc9eab22011-01-02 23:04:14 +0000331 continue;
332 }
333
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000334 // If this is a read-only memory value, process it.
335 if (MemoryValue::canHandle(Inst)) {
336 // If we have an available version of this value, and if it is the right
337 // generation, replace this instruction.
338 std::pair<Value*, unsigned> InVal =
339 AvailableMemValues->lookup(MemoryValue::get(Inst));
340 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
341 DEBUG(dbgs() << "EarlyCSE CSE MEM: " << *Inst << " to: "
342 << *InVal.first << '\n');
343 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
344 Inst->eraseFromParent();
345 Changed = true;
346 ++NumCSEMem;
347 continue;
348 }
349
350 // Otherwise, remember that we have this instruction.
351 AvailableMemValues->insert(MemoryValue::get(Inst),
352 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
353 continue;
354 }
355
356 // Okay, this isn't something we can CSE at all. Check to see if it is
357 // something that could modify memory. If so, our available memory values
358 // cannot be used so bump the generation count.
359 if (Inst->mayWriteToMemory())
360 ++CurrentGeneration;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000361 }
362
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000363 unsigned LiveOutGeneration = CurrentGeneration;
364 for (DomTreeNode::iterator I = Node->begin(), E = Node->end(); I != E; ++I) {
Chris Lattnercc9eab22011-01-02 23:04:14 +0000365 Changed |= processNode(*I);
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000366 // Pop any generation changes off the stack from the recursive walk.
367 CurrentGeneration = LiveOutGeneration;
368 }
Chris Lattnercc9eab22011-01-02 23:04:14 +0000369 return Changed;
Chris Lattner12be9362011-01-02 21:47:05 +0000370}
Chris Lattnercc9eab22011-01-02 23:04:14 +0000371
372
373bool EarlyCSE::runOnFunction(Function &F) {
374 TD = getAnalysisIfAvailable<TargetData>();
375 DT = &getAnalysis<DominatorTree>();
Chris Lattner82dcd5e2011-01-03 01:42:46 +0000376 ScopedHTType AVTable;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000377 AvailableValues = &AVTable;
Chris Lattnerf1974592011-01-03 02:20:48 +0000378
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000379 MemHTType MemTable;
380 AvailableMemValues = &MemTable;
381
382 CurrentGeneration = 0;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000383 return processNode(DT->getRootNode());
384}