1 //===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs a simple dominator tree walk that eliminates trivially
11 // redundant instructions.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "early-cse"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Analysis/Dominators.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetLibraryInfo.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/RecyclingAllocator.h"
26 #include "llvm/ADT/ScopedHashTable.h"
27 #include "llvm/ADT/Statistic.h"
30 STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
31 STATISTIC(NumCSE, "Number of instructions CSE'd");
32 STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
33 STATISTIC(NumCSECall, "Number of call instructions CSE'd");
34 STATISTIC(NumDSE, "Number of trivial dead stores removed");
36 static unsigned getHash(const void *V) {
37 return DenseMapInfo<const void*>::getHashValue(V);
40 //===----------------------------------------------------------------------===//
42 //===----------------------------------------------------------------------===//
45 /// SimpleValue - Instances of this struct represent available values in the
46 /// scoped hash table.
50 SimpleValue(Instruction *I) : Inst(I) {
51 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
54 bool isSentinel() const {
55 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
56 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
59 static bool canHandle(Instruction *Inst) {
60 // This can only handle non-void readnone functions.
61 if (CallInst *CI = dyn_cast<CallInst>(Inst))
62 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
63 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
64 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
65 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
66 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
67 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
73 // SimpleValue is POD.
74 template<> struct isPodLike<SimpleValue> {
75 static const bool value = true;
78 template<> struct DenseMapInfo<SimpleValue> {
79 static inline SimpleValue getEmptyKey() {
80 return DenseMapInfo<Instruction*>::getEmptyKey();
82 static inline SimpleValue getTombstoneKey() {
83 return DenseMapInfo<Instruction*>::getTombstoneKey();
85 static unsigned getHashValue(SimpleValue Val);
86 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
90 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
91 Instruction *Inst = Val.Inst;
93 // Hash in all of the operands as pointers.
95 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
96 Res ^= getHash(Inst->getOperand(i)) << (i & 0xF);
98 if (CastInst *CI = dyn_cast<CastInst>(Inst))
99 Res ^= getHash(CI->getType());
100 else if (CmpInst *CI = dyn_cast<CmpInst>(Inst))
101 Res ^= CI->getPredicate();
102 else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst)) {
103 for (ExtractValueInst::idx_iterator I = EVI->idx_begin(),
104 E = EVI->idx_end(); I != E; ++I)
106 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst)) {
107 for (InsertValueInst::idx_iterator I = IVI->idx_begin(),
108 E = IVI->idx_end(); I != E; ++I)
111 // nothing extra to hash in.
112 assert((isa<CallInst>(Inst) ||
113 isa<BinaryOperator>(Inst) || isa<GetElementPtrInst>(Inst) ||
114 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
115 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst)) &&
116 "Invalid/unknown instruction");
119 // Mix in the opcode.
120 return (Res << 1) ^ Inst->getOpcode();
123 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
124 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
126 if (LHS.isSentinel() || RHS.isSentinel())
129 if (LHSI->getOpcode() != RHSI->getOpcode()) return false;
130 return LHSI->isIdenticalTo(RHSI);
133 //===----------------------------------------------------------------------===//
135 //===----------------------------------------------------------------------===//
138 /// CallValue - Instances of this struct represent available call values in
139 /// the scoped hash table.
143 CallValue(Instruction *I) : Inst(I) {
144 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
147 bool isSentinel() const {
148 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
149 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
152 static bool canHandle(Instruction *Inst) {
153 // Don't value number anything that returns void.
154 if (Inst->getType()->isVoidTy())
157 CallInst *CI = dyn_cast<CallInst>(Inst);
158 if (CI == 0 || !CI->onlyReadsMemory())
167 template<> struct isPodLike<CallValue> {
168 static const bool value = true;
171 template<> struct DenseMapInfo<CallValue> {
172 static inline CallValue getEmptyKey() {
173 return DenseMapInfo<Instruction*>::getEmptyKey();
175 static inline CallValue getTombstoneKey() {
176 return DenseMapInfo<Instruction*>::getTombstoneKey();
178 static unsigned getHashValue(CallValue Val);
179 static bool isEqual(CallValue LHS, CallValue RHS);
182 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
183 Instruction *Inst = Val.Inst;
184 // Hash in all of the operands as pointers.
186 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i) {
187 assert(!Inst->getOperand(i)->getType()->isMetadataTy() &&
188 "Cannot value number calls with metadata operands");
189 Res ^= getHash(Inst->getOperand(i)) << (i & 0xF);
192 // Mix in the opcode.
193 return (Res << 1) ^ Inst->getOpcode();
196 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
197 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
198 if (LHS.isSentinel() || RHS.isSentinel())
200 return LHSI->isIdenticalTo(RHSI);
204 //===----------------------------------------------------------------------===//
206 //===----------------------------------------------------------------------===//
210 /// EarlyCSE - This pass does a simple depth-first walk over the dominator
211 /// tree, eliminating trivially redundant instructions and using instsimplify
212 /// to canonicalize things as it goes. It is intended to be fast and catch
213 /// obvious cases so that instcombine and other passes are more effective. It
214 /// is expected that a later pass of GVN will catch the interesting/hard
216 class EarlyCSE : public FunctionPass {
218 const TargetData *TD;
219 const TargetLibraryInfo *TLI;
221 typedef RecyclingAllocator<BumpPtrAllocator,
222 ScopedHashTableVal<SimpleValue, Value*> > AllocatorTy;
223 typedef ScopedHashTable<SimpleValue, Value*, DenseMapInfo<SimpleValue>,
224 AllocatorTy> ScopedHTType;
226 /// AvailableValues - This scoped hash table contains the current values of
227 /// all of our simple scalar expressions. As we walk down the domtree, we
228 /// look to see if instructions are in this: if so, we replace them with what
229 /// we find, otherwise we insert them so that dominated values can succeed in
231 ScopedHTType *AvailableValues;
233 /// AvailableLoads - This scoped hash table contains the current values
234 /// of loads. This allows us to get efficient access to dominating loads when
235 /// we have a fully redundant load. In addition to the most recent load, we
236 /// keep track of a generation count of the read, which is compared against
237 /// the current generation count. The current generation count is
238 /// incremented after every possibly writing memory operation, which ensures
239 /// that we only CSE loads with other loads that have no intervening store.
240 typedef RecyclingAllocator<BumpPtrAllocator,
241 ScopedHashTableVal<Value*, std::pair<Value*, unsigned> > > LoadMapAllocator;
242 typedef ScopedHashTable<Value*, std::pair<Value*, unsigned>,
243 DenseMapInfo<Value*>, LoadMapAllocator> LoadHTType;
244 LoadHTType *AvailableLoads;
246 /// AvailableCalls - This scoped hash table contains the current values
247 /// of read-only call values. It uses the same generation count as loads.
248 typedef ScopedHashTable<CallValue, std::pair<Value*, unsigned> > CallHTType;
249 CallHTType *AvailableCalls;
251 /// CurrentGeneration - This is the current generation of the memory value.
252 unsigned CurrentGeneration;
255 explicit EarlyCSE() : FunctionPass(ID) {
256 initializeEarlyCSEPass(*PassRegistry::getPassRegistry());
259 bool runOnFunction(Function &F);
263 bool processNode(DomTreeNode *Node);
265 // This transformation requires dominator postdominator info
266 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
267 AU.addRequired<DominatorTree>();
268 AU.addRequired<TargetLibraryInfo>();
269 AU.setPreservesCFG();
274 char EarlyCSE::ID = 0;
276 // createEarlyCSEPass - The public interface to this file.
277 FunctionPass *llvm::createEarlyCSEPass() {
278 return new EarlyCSE();
281 INITIALIZE_PASS_BEGIN(EarlyCSE, "early-cse", "Early CSE", false, false)
282 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
283 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
284 INITIALIZE_PASS_END(EarlyCSE, "early-cse", "Early CSE", false, false)
286 bool EarlyCSE::processNode(DomTreeNode *Node) {
287 // Define a scope in the scoped hash table. When we are done processing this
288 // domtree node and recurse back up to our parent domtree node, this will pop
289 // off all the values we install.
290 ScopedHTType::ScopeTy Scope(*AvailableValues);
292 // Define a scope for the load values so that anything we add will get
293 // popped when we recurse back up to our parent domtree node.
294 LoadHTType::ScopeTy LoadScope(*AvailableLoads);
296 // Define a scope for the call values so that anything we add will get
297 // popped when we recurse back up to our parent domtree node.
298 CallHTType::ScopeTy CallScope(*AvailableCalls);
300 BasicBlock *BB = Node->getBlock();
302 // If this block has a single predecessor, then the predecessor is the parent
303 // of the domtree node and all of the live out memory values are still current
304 // in this block. If this block has multiple predecessors, then they could
305 // have invalidated the live-out memory values of our parent value. For now,
306 // just be conservative and invalidate memory if this block has multiple
308 if (BB->getSinglePredecessor() == 0)
311 /// LastStore - Keep track of the last non-volatile store that we saw... for
312 /// as long as there in no instruction that reads memory. If we see a store
313 /// to the same location, we delete the dead store. This zaps trivial dead
314 /// stores which can occur in bitfield code among other things.
315 StoreInst *LastStore = 0;
317 bool Changed = false;
319 // See if any instructions in the block can be eliminated. If so, do it. If
320 // not, add them to AvailableValues.
321 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
322 Instruction *Inst = I++;
324 // Dead instructions should just be removed.
325 if (isInstructionTriviallyDead(Inst)) {
326 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
327 Inst->eraseFromParent();
333 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
334 // its simpler value.
335 if (Value *V = SimplifyInstruction(Inst, TD, TLI, DT)) {
336 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
337 Inst->replaceAllUsesWith(V);
338 Inst->eraseFromParent();
344 // If this is a simple instruction that we can value number, process it.
345 if (SimpleValue::canHandle(Inst)) {
346 // See if the instruction has an available value. If so, use it.
347 if (Value *V = AvailableValues->lookup(Inst)) {
348 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
349 Inst->replaceAllUsesWith(V);
350 Inst->eraseFromParent();
356 // Otherwise, just remember that this value is available.
357 AvailableValues->insert(Inst, Inst);
361 // If this is a non-volatile load, process it.
362 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
363 // Ignore volatile loads.
364 if (!LI->isSimple()) {
369 // If we have an available version of this load, and if it is the right
370 // generation, replace this instruction.
371 std::pair<Value*, unsigned> InVal =
372 AvailableLoads->lookup(Inst->getOperand(0));
373 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
374 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst << " to: "
375 << *InVal.first << '\n');
376 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
377 Inst->eraseFromParent();
383 // Otherwise, remember that we have this instruction.
384 AvailableLoads->insert(Inst->getOperand(0),
385 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
390 // If this instruction may read from memory, forget LastStore.
391 if (Inst->mayReadFromMemory())
394 // If this is a read-only call, process it.
395 if (CallValue::canHandle(Inst)) {
396 // If we have an available version of this call, and if it is the right
397 // generation, replace this instruction.
398 std::pair<Value*, unsigned> InVal = AvailableCalls->lookup(Inst);
399 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
400 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst << " to: "
401 << *InVal.first << '\n');
402 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
403 Inst->eraseFromParent();
409 // Otherwise, remember that we have this instruction.
410 AvailableCalls->insert(Inst,
411 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
415 // Okay, this isn't something we can CSE at all. Check to see if it is
416 // something that could modify memory. If so, our available memory values
417 // cannot be used so bump the generation count.
418 if (Inst->mayWriteToMemory()) {
421 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
422 // We do a trivial form of DSE if there are two stores to the same
423 // location with no intervening loads. Delete the earlier store.
425 LastStore->getPointerOperand() == SI->getPointerOperand()) {
426 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore << " due to: "
428 LastStore->eraseFromParent();
435 // Okay, we just invalidated anything we knew about loaded values. Try
436 // to salvage *something* by remembering that the stored value is a live
437 // version of the pointer. It is safe to forward from volatile stores
438 // to non-volatile loads, so we don't have to check for volatility of
440 AvailableLoads->insert(SI->getPointerOperand(),
441 std::pair<Value*, unsigned>(SI->getValueOperand(), CurrentGeneration));
443 // Remember that this was the last store we saw for DSE.
450 unsigned LiveOutGeneration = CurrentGeneration;
451 for (DomTreeNode::iterator I = Node->begin(), E = Node->end(); I != E; ++I) {
452 Changed |= processNode(*I);
453 // Pop any generation changes off the stack from the recursive walk.
454 CurrentGeneration = LiveOutGeneration;
460 bool EarlyCSE::runOnFunction(Function &F) {
461 TD = getAnalysisIfAvailable<TargetData>();
462 TLI = &getAnalysis<TargetLibraryInfo>();
463 DT = &getAnalysis<DominatorTree>();
465 // Tables that the pass uses when walking the domtree.
466 ScopedHTType AVTable;
467 AvailableValues = &AVTable;
468 LoadHTType LoadTable;
469 AvailableLoads = &LoadTable;
470 CallHTType CallTable;
471 AvailableCalls = &CallTable;
473 CurrentGeneration = 0;
474 return processNode(DT->getRootNode());