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 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/ADT/Hashing.h"
17 #include "llvm/ADT/ScopedHashTable.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/AssumptionCache.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/PatternMatch.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/RecyclingAllocator.h"
29 #include "llvm/Analysis/TargetLibraryInfo.h"
30 #include "llvm/Transforms/Utils/Local.h"
33 using namespace llvm::PatternMatch;
35 #define DEBUG_TYPE "early-cse"
37 STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
38 STATISTIC(NumCSE, "Number of instructions CSE'd");
39 STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
40 STATISTIC(NumCSECall, "Number of call instructions CSE'd");
41 STATISTIC(NumDSE, "Number of trivial dead stores removed");
43 static unsigned getHash(const void *V) {
44 return DenseMapInfo<const void*>::getHashValue(V);
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
52 /// \brief Struct representing the available values in the scoped hash table.
56 SimpleValue(Instruction *I) : Inst(I) {
57 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
60 bool isSentinel() const {
61 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
62 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
65 static bool canHandle(Instruction *Inst) {
66 // This can only handle non-void readnone functions.
67 if (CallInst *CI = dyn_cast<CallInst>(Inst))
68 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
69 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
70 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
71 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
72 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
73 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
79 template <> struct DenseMapInfo<SimpleValue> {
80 static inline SimpleValue getEmptyKey() {
81 return DenseMapInfo<Instruction *>::getEmptyKey();
83 static inline SimpleValue getTombstoneKey() {
84 return DenseMapInfo<Instruction *>::getTombstoneKey();
86 static unsigned getHashValue(SimpleValue Val);
87 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
91 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
92 Instruction *Inst = Val.Inst;
93 // Hash in all of the operands as pointers.
94 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
95 Value *LHS = BinOp->getOperand(0);
96 Value *RHS = BinOp->getOperand(1);
97 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
100 if (isa<OverflowingBinaryOperator>(BinOp)) {
101 // Hash the overflow behavior
103 BinOp->hasNoSignedWrap() * OverflowingBinaryOperator::NoSignedWrap |
104 BinOp->hasNoUnsignedWrap() *
105 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)) &&
139 "Invalid/unknown instruction");
141 // Mix in the opcode.
144 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
147 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
148 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
150 if (LHS.isSentinel() || RHS.isSentinel())
153 if (LHSI->getOpcode() != RHSI->getOpcode())
155 if (LHSI->isIdenticalTo(RHSI))
158 // If we're not strictly identical, we still might be a commutable instruction
159 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
160 if (!LHSBinOp->isCommutative())
163 assert(isa<BinaryOperator>(RHSI) &&
164 "same opcode, but different instruction type?");
165 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
167 // Check overflow attributes
168 if (isa<OverflowingBinaryOperator>(LHSBinOp)) {
169 assert(isa<OverflowingBinaryOperator>(RHSBinOp) &&
170 "same opcode, but different operator type?");
171 if (LHSBinOp->hasNoUnsignedWrap() != RHSBinOp->hasNoUnsignedWrap() ||
172 LHSBinOp->hasNoSignedWrap() != RHSBinOp->hasNoSignedWrap())
177 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
178 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
180 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
181 assert(isa<CmpInst>(RHSI) &&
182 "same opcode, but different instruction type?");
183 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
185 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
186 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
187 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
193 //===----------------------------------------------------------------------===//
195 //===----------------------------------------------------------------------===//
198 /// \brief Struct representing the available call values in the scoped hash
203 CallValue(Instruction *I) : Inst(I) {
204 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
207 bool isSentinel() const {
208 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
209 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
212 static bool canHandle(Instruction *Inst) {
213 // Don't value number anything that returns void.
214 if (Inst->getType()->isVoidTy())
217 CallInst *CI = dyn_cast<CallInst>(Inst);
218 if (!CI || !CI->onlyReadsMemory())
226 template <> struct DenseMapInfo<CallValue> {
227 static inline CallValue getEmptyKey() {
228 return DenseMapInfo<Instruction *>::getEmptyKey();
230 static inline CallValue getTombstoneKey() {
231 return DenseMapInfo<Instruction *>::getTombstoneKey();
233 static unsigned getHashValue(CallValue Val);
234 static bool isEqual(CallValue LHS, CallValue RHS);
238 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
239 Instruction *Inst = Val.Inst;
240 // Hash in all of the operands as pointers.
242 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i) {
243 assert(!Inst->getOperand(i)->getType()->isMetadataTy() &&
244 "Cannot value number calls with metadata operands");
245 Res ^= getHash(Inst->getOperand(i)) << (i & 0xF);
248 // Mix in the opcode.
249 return (Res << 1) ^ Inst->getOpcode();
252 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
253 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
254 if (LHS.isSentinel() || RHS.isSentinel())
256 return LHSI->isIdenticalTo(RHSI);
259 //===----------------------------------------------------------------------===//
261 //===----------------------------------------------------------------------===//
265 /// \brief A simple and fast domtree-based CSE pass.
267 /// This pass does a simple depth-first walk over the dominator tree,
268 /// eliminating trivially redundant instructions and using instsimplify to
269 /// canonicalize things as it goes. It is intended to be fast and catch obvious
270 /// cases so that instcombine and other passes are more effective. It is
271 /// expected that a later pass of GVN will catch the interesting/hard cases.
272 class EarlyCSE : public FunctionPass {
274 const DataLayout *DL;
275 const TargetLibraryInfo *TLI;
278 typedef RecyclingAllocator<
279 BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy;
280 typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
281 AllocatorTy> ScopedHTType;
283 /// \brief A scoped hash table of the current values of all of our simple
284 /// scalar expressions.
286 /// As we walk down the domtree, we look to see if instructions are in this:
287 /// if so, we replace them with what we find, otherwise we insert them so
288 /// that dominated values can succeed in their lookup.
289 ScopedHTType *AvailableValues;
291 /// \brief A scoped hash table of the current values of loads.
293 /// This allows us to get efficient access to dominating loads when we have
294 /// a fully redundant load. In addition to the most recent load, we keep
295 /// track of a generation count of the read, which is compared against the
296 /// current generation count. The current generation count is incremented
297 /// after every possibly writing memory operation, which ensures that we only
298 /// CSE loads with other loads that have no intervening store.
299 typedef RecyclingAllocator<
301 ScopedHashTableVal<Value *, std::pair<Value *, unsigned>>>
303 typedef ScopedHashTable<Value *, std::pair<Value *, unsigned>,
304 DenseMapInfo<Value *>, LoadMapAllocator> LoadHTType;
305 LoadHTType *AvailableLoads;
307 /// \brief A scoped hash table of the current values of read-only call
310 /// It uses the same generation count as loads.
311 typedef ScopedHashTable<CallValue, std::pair<Value *, unsigned>> CallHTType;
312 CallHTType *AvailableCalls;
314 /// \brief This is the current generation of the memory value.
315 unsigned CurrentGeneration;
318 explicit EarlyCSE() : FunctionPass(ID) {
319 initializeEarlyCSEPass(*PassRegistry::getPassRegistry());
322 bool runOnFunction(Function &F) override;
325 // Almost a POD, but needs to call the constructors for the scoped hash
326 // tables so that a new scope gets pushed on. These are RAII so that the
327 // scope gets popped when the NodeScope is destroyed.
330 NodeScope(ScopedHTType *availableValues, LoadHTType *availableLoads,
331 CallHTType *availableCalls)
332 : Scope(*availableValues), LoadScope(*availableLoads),
333 CallScope(*availableCalls) {}
336 NodeScope(const NodeScope &) LLVM_DELETED_FUNCTION;
337 void operator=(const NodeScope &) LLVM_DELETED_FUNCTION;
339 ScopedHTType::ScopeTy Scope;
340 LoadHTType::ScopeTy LoadScope;
341 CallHTType::ScopeTy CallScope;
344 // Contains all the needed information to create a stack for doing a depth
345 // first tranversal of the tree. This includes scopes for values, loads, and
346 // calls as well as the generation. There is a child iterator so that the
347 // children do not need to be store spearately.
350 StackNode(ScopedHTType *availableValues, LoadHTType *availableLoads,
351 CallHTType *availableCalls, unsigned cg, DomTreeNode *n,
352 DomTreeNode::iterator child, DomTreeNode::iterator end)
353 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
354 EndIter(end), 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 void getAnalysisUsage(AnalysisUsage &AU) const override {
389 AU.addRequired<AssumptionCacheTracker>();
390 AU.addRequired<DominatorTreeWrapperPass>();
391 AU.addRequired<TargetLibraryInfoWrapperPass>();
392 AU.setPreservesCFG();
397 char EarlyCSE::ID = 0;
399 FunctionPass *llvm::createEarlyCSEPass() { return new EarlyCSE(); }
401 INITIALIZE_PASS_BEGIN(EarlyCSE, "early-cse", "Early CSE", false, false)
402 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
403 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
404 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
405 INITIALIZE_PASS_END(EarlyCSE, "early-cse", "Early CSE", false, false)
407 bool EarlyCSE::processNode(DomTreeNode *Node) {
408 BasicBlock *BB = Node->getBlock();
410 // If this block has a single predecessor, then the predecessor is the parent
411 // of the domtree node and all of the live out memory values are still current
412 // in this block. If this block has multiple predecessors, then they could
413 // have invalidated the live-out memory values of our parent value. For now,
414 // just be conservative and invalidate memory if this block has multiple
416 if (!BB->getSinglePredecessor())
419 /// LastStore - Keep track of the last non-volatile store that we saw... for
420 /// as long as there in no instruction that reads memory. If we see a store
421 /// to the same location, we delete the dead store. This zaps trivial dead
422 /// stores which can occur in bitfield code among other things.
423 StoreInst *LastStore = nullptr;
425 bool Changed = false;
427 // See if any instructions in the block can be eliminated. If so, do it. If
428 // not, add them to AvailableValues.
429 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
430 Instruction *Inst = I++;
432 // Dead instructions should just be removed.
433 if (isInstructionTriviallyDead(Inst, TLI)) {
434 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
435 Inst->eraseFromParent();
441 // Skip assume intrinsics, they don't really have side effects (although
442 // they're marked as such to ensure preservation of control dependencies),
443 // and this pass will not disturb any of the assumption's control
445 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
446 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
450 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
451 // its simpler value.
452 if (Value *V = SimplifyInstruction(Inst, DL, TLI, DT, AC)) {
453 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
454 Inst->replaceAllUsesWith(V);
455 Inst->eraseFromParent();
461 // If this is a simple instruction that we can value number, process it.
462 if (SimpleValue::canHandle(Inst)) {
463 // See if the instruction has an available value. If so, use it.
464 if (Value *V = AvailableValues->lookup(Inst)) {
465 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
466 Inst->replaceAllUsesWith(V);
467 Inst->eraseFromParent();
473 // Otherwise, just remember that this value is available.
474 AvailableValues->insert(Inst, Inst);
478 // If this is a non-volatile load, process it.
479 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
480 // Ignore volatile loads.
481 if (!LI->isSimple()) {
486 // If we have an available version of this load, and if it is the right
487 // generation, replace this instruction.
488 std::pair<Value *, unsigned> InVal =
489 AvailableLoads->lookup(Inst->getOperand(0));
490 if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
491 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
492 << " to: " << *InVal.first << '\n');
493 if (!Inst->use_empty())
494 Inst->replaceAllUsesWith(InVal.first);
495 Inst->eraseFromParent();
501 // Otherwise, remember that we have this instruction.
502 AvailableLoads->insert(Inst->getOperand(0), std::pair<Value *, unsigned>(
503 Inst, CurrentGeneration));
508 // If this instruction may read from memory, forget LastStore.
509 if (Inst->mayReadFromMemory())
512 // If this is a read-only call, process it.
513 if (CallValue::canHandle(Inst)) {
514 // If we have an available version of this call, and if it is the right
515 // generation, replace this instruction.
516 std::pair<Value *, unsigned> InVal = AvailableCalls->lookup(Inst);
517 if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
518 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
519 << " to: " << *InVal.first << '\n');
520 if (!Inst->use_empty())
521 Inst->replaceAllUsesWith(InVal.first);
522 Inst->eraseFromParent();
528 // Otherwise, remember that we have this instruction.
529 AvailableCalls->insert(
530 Inst, std::pair<Value *, unsigned>(Inst, CurrentGeneration));
534 // Okay, this isn't something we can CSE at all. Check to see if it is
535 // something that could modify memory. If so, our available memory values
536 // cannot be used so bump the generation count.
537 if (Inst->mayWriteToMemory()) {
540 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
541 // We do a trivial form of DSE if there are two stores to the same
542 // location with no intervening loads. Delete the earlier store.
544 LastStore->getPointerOperand() == SI->getPointerOperand()) {
545 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
546 << " due to: " << *Inst << '\n');
547 LastStore->eraseFromParent();
551 // fallthrough - we can exploit information about this store
554 // Okay, we just invalidated anything we knew about loaded values. Try
555 // to salvage *something* by remembering that the stored value is a live
556 // version of the pointer. It is safe to forward from volatile stores
557 // to non-volatile loads, so we don't have to check for volatility of
559 AvailableLoads->insert(SI->getPointerOperand(),
560 std::pair<Value *, unsigned>(
561 SI->getValueOperand(), CurrentGeneration));
563 // Remember that this was the last store we saw for DSE.
573 bool EarlyCSE::runOnFunction(Function &F) {
574 if (skipOptnoneFunction(F))
577 // Note, deque is being used here because there is significant performance
578 // gains over vector when the container becomes very large due to the
579 // specific access patterns. For more information see the mailing list
580 // discussion on this:
581 // http://lists.cs.uiuc.edu/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
582 std::deque<StackNode *> nodesToProcess;
584 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
585 DL = DLP ? &DLP->getDataLayout() : nullptr;
586 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
587 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
588 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
590 // Tables that the pass uses when walking the domtree.
591 ScopedHTType AVTable;
592 AvailableValues = &AVTable;
593 LoadHTType LoadTable;
594 AvailableLoads = &LoadTable;
595 CallHTType CallTable;
596 AvailableCalls = &CallTable;
598 CurrentGeneration = 0;
599 bool Changed = false;
601 // Process the root node.
602 nodesToProcess.push_back(new StackNode(
603 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration,
604 DT->getRootNode(), DT->getRootNode()->begin(), DT->getRootNode()->end()));
606 // Save the current generation.
607 unsigned LiveOutGeneration = CurrentGeneration;
609 // Process the stack.
610 while (!nodesToProcess.empty()) {
611 // Grab the first item off the stack. Set the current generation, remove
612 // the node from the stack, and process it.
613 StackNode *NodeToProcess = nodesToProcess.back();
615 // Initialize class members.
616 CurrentGeneration = NodeToProcess->currentGeneration();
618 // Check if the node needs to be processed.
619 if (!NodeToProcess->isProcessed()) {
621 Changed |= processNode(NodeToProcess->node());
622 NodeToProcess->childGeneration(CurrentGeneration);
623 NodeToProcess->process();
624 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
625 // Push the next child onto the stack.
626 DomTreeNode *child = NodeToProcess->nextChild();
627 nodesToProcess.push_back(
628 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
629 NodeToProcess->childGeneration(), child, child->begin(),
632 // It has been processed, and there are no more children to process,
633 // so delete it and pop it off the stack.
634 delete NodeToProcess;
635 nodesToProcess.pop_back();
637 } // while (!nodes...)
639 // Reset the current generation.
640 CurrentGeneration = LiveOutGeneration;