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/ADT/Hashing.h"
18 #include "llvm/ADT/ScopedHashTable.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/RecyclingAllocator.h"
27 #include "llvm/Target/TargetLibraryInfo.h"
28 #include "llvm/Transforms/Utils/Local.h"
32 STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
33 STATISTIC(NumCSE, "Number of instructions CSE'd");
34 STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
35 STATISTIC(NumCSECall, "Number of call instructions CSE'd");
36 STATISTIC(NumDSE, "Number of trivial dead stores removed");
38 static unsigned getHash(const void *V) {
39 return DenseMapInfo<const void*>::getHashValue(V);
42 //===----------------------------------------------------------------------===//
44 //===----------------------------------------------------------------------===//
47 /// SimpleValue - Instances of this struct represent available values in the
48 /// scoped hash table.
52 SimpleValue(Instruction *I) : Inst(I) {
53 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
56 bool isSentinel() const {
57 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
58 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
61 static bool canHandle(Instruction *Inst) {
62 // This can only handle non-void readnone functions.
63 if (CallInst *CI = dyn_cast<CallInst>(Inst))
64 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
65 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
66 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
67 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
68 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
69 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
75 // SimpleValue is POD.
76 template<> struct isPodLike<SimpleValue> {
77 static const bool value = true;
80 template<> struct DenseMapInfo<SimpleValue> {
81 static inline SimpleValue getEmptyKey() {
82 return DenseMapInfo<Instruction*>::getEmptyKey();
84 static inline SimpleValue getTombstoneKey() {
85 return DenseMapInfo<Instruction*>::getTombstoneKey();
87 static unsigned getHashValue(SimpleValue Val);
88 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
92 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
93 Instruction *Inst = Val.Inst;
94 // Hash in all of the operands as pointers.
95 if (BinaryOperator* BinOp = dyn_cast<BinaryOperator>(Inst)) {
96 Value *LHS = BinOp->getOperand(0);
97 Value *RHS = BinOp->getOperand(1);
98 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
101 if (isa<OverflowingBinaryOperator>(BinOp)) {
102 // Hash the overflow behavior
104 BinOp->hasNoSignedWrap() * OverflowingBinaryOperator::NoSignedWrap |
105 BinOp->hasNoUnsignedWrap() * OverflowingBinaryOperator::NoUnsignedWrap;
106 return hash_combine(BinOp->getOpcode(), Overflow, LHS, RHS);
109 return hash_combine(BinOp->getOpcode(), LHS, RHS);
112 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
113 Value *LHS = CI->getOperand(0);
114 Value *RHS = CI->getOperand(1);
115 CmpInst::Predicate Pred = CI->getPredicate();
116 if (Inst->getOperand(0) > Inst->getOperand(1)) {
118 Pred = CI->getSwappedPredicate();
120 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
123 if (CastInst *CI = dyn_cast<CastInst>(Inst))
124 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
126 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
127 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
128 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
130 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
131 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
133 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
135 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
136 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
137 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
138 isa<ShuffleVectorInst>(Inst)) && "Invalid/unknown instruction");
140 // Mix in the opcode.
141 return hash_combine(Inst->getOpcode(),
142 hash_combine_range(Inst->value_op_begin(),
143 Inst->value_op_end()));
146 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
147 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
149 if (LHS.isSentinel() || RHS.isSentinel())
152 if (LHSI->getOpcode() != RHSI->getOpcode()) return false;
153 if (LHSI->isIdenticalTo(RHSI)) return true;
155 // If we're not strictly identical, we still might be a commutable instruction
156 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
157 if (!LHSBinOp->isCommutative())
160 assert(isa<BinaryOperator>(RHSI)
161 && "same opcode, but different instruction type?");
162 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
164 // Check overflow attributes
165 if (isa<OverflowingBinaryOperator>(LHSBinOp)) {
166 assert(isa<OverflowingBinaryOperator>(RHSBinOp)
167 && "same opcode, but different operator type?");
168 if (LHSBinOp->hasNoUnsignedWrap() != RHSBinOp->hasNoUnsignedWrap() ||
169 LHSBinOp->hasNoSignedWrap() != RHSBinOp->hasNoSignedWrap())
174 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
175 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
177 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
178 assert(isa<CmpInst>(RHSI)
179 && "same opcode, but different instruction type?");
180 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
182 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
183 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
184 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
190 //===----------------------------------------------------------------------===//
192 //===----------------------------------------------------------------------===//
195 /// CallValue - Instances of this struct represent available call values in
196 /// the scoped hash table.
200 CallValue(Instruction *I) : Inst(I) {
201 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
204 bool isSentinel() const {
205 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
206 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
209 static bool canHandle(Instruction *Inst) {
210 // Don't value number anything that returns void.
211 if (Inst->getType()->isVoidTy())
214 CallInst *CI = dyn_cast<CallInst>(Inst);
215 if (CI == 0 || !CI->onlyReadsMemory())
224 template<> struct isPodLike<CallValue> {
225 static const bool value = true;
228 template<> struct DenseMapInfo<CallValue> {
229 static inline CallValue getEmptyKey() {
230 return DenseMapInfo<Instruction*>::getEmptyKey();
232 static inline CallValue getTombstoneKey() {
233 return DenseMapInfo<Instruction*>::getTombstoneKey();
235 static unsigned getHashValue(CallValue Val);
236 static bool isEqual(CallValue LHS, CallValue RHS);
239 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
240 Instruction *Inst = Val.Inst;
241 // Hash in all of the operands as pointers.
243 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i) {
244 assert(!Inst->getOperand(i)->getType()->isMetadataTy() &&
245 "Cannot value number calls with metadata operands");
246 Res ^= getHash(Inst->getOperand(i)) << (i & 0xF);
249 // Mix in the opcode.
250 return (Res << 1) ^ Inst->getOpcode();
253 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
254 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
255 if (LHS.isSentinel() || RHS.isSentinel())
257 return LHSI->isIdenticalTo(RHSI);
261 //===----------------------------------------------------------------------===//
263 //===----------------------------------------------------------------------===//
267 /// EarlyCSE - This pass does a simple depth-first walk over the dominator
268 /// tree, eliminating trivially redundant instructions and using instsimplify
269 /// to canonicalize things as it goes. It is intended to be fast and catch
270 /// obvious cases so that instcombine and other passes are more effective. It
271 /// is expected that a later pass of GVN will catch the interesting/hard
273 class EarlyCSE : public FunctionPass {
275 const DataLayout *TD;
276 const TargetLibraryInfo *TLI;
278 typedef RecyclingAllocator<BumpPtrAllocator,
279 ScopedHashTableVal<SimpleValue, Value*> > AllocatorTy;
280 typedef ScopedHashTable<SimpleValue, Value*, DenseMapInfo<SimpleValue>,
281 AllocatorTy> ScopedHTType;
283 /// AvailableValues - This scoped hash table contains the current values of
284 /// all of our simple scalar expressions. As we walk down the domtree, we
285 /// look to see if instructions are in this: if so, we replace them with what
286 /// we find, otherwise we insert them so that dominated values can succeed in
288 ScopedHTType *AvailableValues;
290 /// AvailableLoads - This scoped hash table contains the current values
291 /// of loads. This allows us to get efficient access to dominating loads when
292 /// we have a fully redundant load. In addition to the most recent load, we
293 /// keep track of a generation count of the read, which is compared against
294 /// the current generation count. The current generation count is
295 /// incremented after every possibly writing memory operation, which ensures
296 /// that we only CSE loads with other loads that have no intervening store.
297 typedef RecyclingAllocator<BumpPtrAllocator,
298 ScopedHashTableVal<Value*, std::pair<Value*, unsigned> > > LoadMapAllocator;
299 typedef ScopedHashTable<Value*, std::pair<Value*, unsigned>,
300 DenseMapInfo<Value*>, LoadMapAllocator> LoadHTType;
301 LoadHTType *AvailableLoads;
303 /// AvailableCalls - This scoped hash table contains the current values
304 /// of read-only call values. It uses the same generation count as loads.
305 typedef ScopedHashTable<CallValue, std::pair<Value*, unsigned> > CallHTType;
306 CallHTType *AvailableCalls;
308 /// CurrentGeneration - This is the current generation of the memory value.
309 unsigned CurrentGeneration;
312 explicit EarlyCSE() : FunctionPass(ID) {
313 initializeEarlyCSEPass(*PassRegistry::getPassRegistry());
316 bool runOnFunction(Function &F);
320 // NodeScope - almost a POD, but needs to call the constructors for the
321 // scoped hash tables so that a new scope gets pushed on. These are RAII so
322 // that the scope gets popped when the NodeScope is destroyed.
325 NodeScope(ScopedHTType *availableValues,
326 LoadHTType *availableLoads,
327 CallHTType *availableCalls) :
328 Scope(*availableValues),
329 LoadScope(*availableLoads),
330 CallScope(*availableCalls) {}
333 NodeScope(const NodeScope&) LLVM_DELETED_FUNCTION;
334 void operator=(const NodeScope&) LLVM_DELETED_FUNCTION;
336 ScopedHTType::ScopeTy Scope;
337 LoadHTType::ScopeTy LoadScope;
338 CallHTType::ScopeTy CallScope;
341 // StackNode - contains all the needed information to create a stack for
342 // doing a depth first tranversal of the tree. This includes scopes for
343 // values, loads, and calls as well as the generation. There is a child
344 // iterator so that the children do not need to be store spearately.
347 StackNode(ScopedHTType *availableValues,
348 LoadHTType *availableLoads,
349 CallHTType *availableCalls,
350 unsigned cg, DomTreeNode *n,
351 DomTreeNode::iterator child, DomTreeNode::iterator end) :
352 CurrentGeneration(cg), ChildGeneration(cg), Node(n),
353 ChildIter(child), EndIter(end),
354 Scopes(availableValues, availableLoads, availableCalls),
358 unsigned currentGeneration() { return CurrentGeneration; }
359 unsigned childGeneration() { return ChildGeneration; }
360 void childGeneration(unsigned generation) { ChildGeneration = generation; }
361 DomTreeNode *node() { return Node; }
362 DomTreeNode::iterator childIter() { return ChildIter; }
363 DomTreeNode *nextChild() {
364 DomTreeNode *child = *ChildIter;
368 DomTreeNode::iterator end() { return EndIter; }
369 bool isProcessed() { return Processed; }
370 void process() { Processed = true; }
373 StackNode(const StackNode&) LLVM_DELETED_FUNCTION;
374 void operator=(const StackNode&) LLVM_DELETED_FUNCTION;
377 unsigned CurrentGeneration;
378 unsigned ChildGeneration;
380 DomTreeNode::iterator ChildIter;
381 DomTreeNode::iterator EndIter;
386 bool processNode(DomTreeNode *Node);
388 // This transformation requires dominator postdominator info
389 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
390 AU.addRequired<DominatorTree>();
391 AU.addRequired<TargetLibraryInfo>();
392 AU.setPreservesCFG();
397 char EarlyCSE::ID = 0;
399 // createEarlyCSEPass - The public interface to this file.
400 FunctionPass *llvm::createEarlyCSEPass() {
401 return new EarlyCSE();
404 INITIALIZE_PASS_BEGIN(EarlyCSE, "early-cse", "Early CSE", false, false)
405 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
406 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
407 INITIALIZE_PASS_END(EarlyCSE, "early-cse", "Early CSE", false, false)
409 bool EarlyCSE::processNode(DomTreeNode *Node) {
410 BasicBlock *BB = Node->getBlock();
412 // If this block has a single predecessor, then the predecessor is the parent
413 // of the domtree node and all of the live out memory values are still current
414 // in this block. If this block has multiple predecessors, then they could
415 // have invalidated the live-out memory values of our parent value. For now,
416 // just be conservative and invalidate memory if this block has multiple
418 if (BB->getSinglePredecessor() == 0)
421 /// LastStore - Keep track of the last non-volatile store that we saw... for
422 /// as long as there in no instruction that reads memory. If we see a store
423 /// to the same location, we delete the dead store. This zaps trivial dead
424 /// stores which can occur in bitfield code among other things.
425 StoreInst *LastStore = 0;
427 bool Changed = false;
429 // See if any instructions in the block can be eliminated. If so, do it. If
430 // not, add them to AvailableValues.
431 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
432 Instruction *Inst = I++;
434 // Dead instructions should just be removed.
435 if (isInstructionTriviallyDead(Inst, TLI)) {
436 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
437 Inst->eraseFromParent();
443 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
444 // its simpler value.
445 if (Value *V = SimplifyInstruction(Inst, TD, TLI, DT)) {
446 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
447 Inst->replaceAllUsesWith(V);
448 Inst->eraseFromParent();
454 // If this is a simple instruction that we can value number, process it.
455 if (SimpleValue::canHandle(Inst)) {
456 // See if the instruction has an available value. If so, use it.
457 if (Value *V = AvailableValues->lookup(Inst)) {
458 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
459 Inst->replaceAllUsesWith(V);
460 Inst->eraseFromParent();
466 // Otherwise, just remember that this value is available.
467 AvailableValues->insert(Inst, Inst);
471 // If this is a non-volatile load, process it.
472 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
473 // Ignore volatile loads.
474 if (!LI->isSimple()) {
479 // If we have an available version of this load, and if it is the right
480 // generation, replace this instruction.
481 std::pair<Value*, unsigned> InVal =
482 AvailableLoads->lookup(Inst->getOperand(0));
483 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
484 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst << " to: "
485 << *InVal.first << '\n');
486 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
487 Inst->eraseFromParent();
493 // Otherwise, remember that we have this instruction.
494 AvailableLoads->insert(Inst->getOperand(0),
495 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
500 // If this instruction may read from memory, forget LastStore.
501 if (Inst->mayReadFromMemory())
504 // If this is a read-only call, process it.
505 if (CallValue::canHandle(Inst)) {
506 // If we have an available version of this call, and if it is the right
507 // generation, replace this instruction.
508 std::pair<Value*, unsigned> InVal = AvailableCalls->lookup(Inst);
509 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
510 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst << " to: "
511 << *InVal.first << '\n');
512 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
513 Inst->eraseFromParent();
519 // Otherwise, remember that we have this instruction.
520 AvailableCalls->insert(Inst,
521 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
525 // Okay, this isn't something we can CSE at all. Check to see if it is
526 // something that could modify memory. If so, our available memory values
527 // cannot be used so bump the generation count.
528 if (Inst->mayWriteToMemory()) {
531 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
532 // We do a trivial form of DSE if there are two stores to the same
533 // location with no intervening loads. Delete the earlier store.
535 LastStore->getPointerOperand() == SI->getPointerOperand()) {
536 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore << " due to: "
538 LastStore->eraseFromParent();
545 // Okay, we just invalidated anything we knew about loaded values. Try
546 // to salvage *something* by remembering that the stored value is a live
547 // version of the pointer. It is safe to forward from volatile stores
548 // to non-volatile loads, so we don't have to check for volatility of
550 AvailableLoads->insert(SI->getPointerOperand(),
551 std::pair<Value*, unsigned>(SI->getValueOperand(), CurrentGeneration));
553 // Remember that this was the last store we saw for DSE.
564 bool EarlyCSE::runOnFunction(Function &F) {
565 std::deque<StackNode *> nodesToProcess;
567 TD = getAnalysisIfAvailable<DataLayout>();
568 TLI = &getAnalysis<TargetLibraryInfo>();
569 DT = &getAnalysis<DominatorTree>();
571 // Tables that the pass uses when walking the domtree.
572 ScopedHTType AVTable;
573 AvailableValues = &AVTable;
574 LoadHTType LoadTable;
575 AvailableLoads = &LoadTable;
576 CallHTType CallTable;
577 AvailableCalls = &CallTable;
579 CurrentGeneration = 0;
580 bool Changed = false;
582 // Process the root node.
583 nodesToProcess.push_front(
584 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
585 CurrentGeneration, DT->getRootNode(),
586 DT->getRootNode()->begin(),
587 DT->getRootNode()->end()));
589 // Save the current generation.
590 unsigned LiveOutGeneration = CurrentGeneration;
592 // Process the stack.
593 while (!nodesToProcess.empty()) {
594 // Grab the first item off the stack. Set the current generation, remove
595 // the node from the stack, and process it.
596 StackNode *NodeToProcess = nodesToProcess.front();
598 // Initialize class members.
599 CurrentGeneration = NodeToProcess->currentGeneration();
601 // Check if the node needs to be processed.
602 if (!NodeToProcess->isProcessed()) {
604 Changed |= processNode(NodeToProcess->node());
605 NodeToProcess->childGeneration(CurrentGeneration);
606 NodeToProcess->process();
607 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
608 // Push the next child onto the stack.
609 DomTreeNode *child = NodeToProcess->nextChild();
610 nodesToProcess.push_front(
611 new StackNode(AvailableValues,
614 NodeToProcess->childGeneration(), child,
615 child->begin(), child->end()));
617 // It has been processed, and there are no more children to process,
618 // so delete it and pop it off the stack.
619 delete NodeToProcess;
620 nodesToProcess.pop_front();
622 } // while (!nodes...)
624 // Reset the current generation.
625 CurrentGeneration = LiveOutGeneration;