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/EarlyCSE.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/Analysis/TargetTransformInfo.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/RecyclingAllocator.h"
30 #include "llvm/Analysis/TargetLibraryInfo.h"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/Transforms/Utils/Local.h"
35 using namespace llvm::PatternMatch;
37 #define DEBUG_TYPE "early-cse"
39 STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
40 STATISTIC(NumCSE, "Number of instructions CSE'd");
41 STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
42 STATISTIC(NumCSECall, "Number of call instructions CSE'd");
43 STATISTIC(NumDSE, "Number of trivial dead stores removed");
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
50 /// \brief Struct representing the available values in the scoped hash table.
54 SimpleValue(Instruction *I) : Inst(I) {
55 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
58 bool isSentinel() const {
59 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
60 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
63 static bool canHandle(Instruction *Inst) {
64 // This can only handle non-void readnone functions.
65 if (CallInst *CI = dyn_cast<CallInst>(Inst))
66 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
67 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
68 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
69 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
70 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
71 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
77 template <> struct DenseMapInfo<SimpleValue> {
78 static inline SimpleValue getEmptyKey() {
79 return DenseMapInfo<Instruction *>::getEmptyKey();
81 static inline SimpleValue getTombstoneKey() {
82 return DenseMapInfo<Instruction *>::getTombstoneKey();
84 static unsigned getHashValue(SimpleValue Val);
85 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
89 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
90 Instruction *Inst = Val.Inst;
91 // Hash in all of the operands as pointers.
92 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
93 Value *LHS = BinOp->getOperand(0);
94 Value *RHS = BinOp->getOperand(1);
95 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
98 if (isa<OverflowingBinaryOperator>(BinOp)) {
99 // Hash the overflow behavior
101 BinOp->hasNoSignedWrap() * OverflowingBinaryOperator::NoSignedWrap |
102 BinOp->hasNoUnsignedWrap() *
103 OverflowingBinaryOperator::NoUnsignedWrap;
104 return hash_combine(BinOp->getOpcode(), Overflow, LHS, RHS);
107 return hash_combine(BinOp->getOpcode(), LHS, RHS);
110 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
111 Value *LHS = CI->getOperand(0);
112 Value *RHS = CI->getOperand(1);
113 CmpInst::Predicate Pred = CI->getPredicate();
114 if (Inst->getOperand(0) > Inst->getOperand(1)) {
116 Pred = CI->getSwappedPredicate();
118 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
121 if (CastInst *CI = dyn_cast<CastInst>(Inst))
122 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
124 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
125 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
126 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
128 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
129 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
131 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
133 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
134 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
135 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
136 isa<ShuffleVectorInst>(Inst)) &&
137 "Invalid/unknown instruction");
139 // Mix in the opcode.
142 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
145 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
146 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
148 if (LHS.isSentinel() || RHS.isSentinel())
151 if (LHSI->getOpcode() != RHSI->getOpcode())
153 if (LHSI->isIdenticalTo(RHSI))
156 // If we're not strictly identical, we still might be a commutable instruction
157 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
158 if (!LHSBinOp->isCommutative())
161 assert(isa<BinaryOperator>(RHSI) &&
162 "same opcode, but different instruction type?");
163 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
165 // Check overflow attributes
166 if (isa<OverflowingBinaryOperator>(LHSBinOp)) {
167 assert(isa<OverflowingBinaryOperator>(RHSBinOp) &&
168 "same opcode, but different operator type?");
169 if (LHSBinOp->hasNoUnsignedWrap() != RHSBinOp->hasNoUnsignedWrap() ||
170 LHSBinOp->hasNoSignedWrap() != RHSBinOp->hasNoSignedWrap())
175 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
176 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
178 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
179 assert(isa<CmpInst>(RHSI) &&
180 "same opcode, but different instruction type?");
181 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
183 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
184 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
185 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
191 //===----------------------------------------------------------------------===//
193 //===----------------------------------------------------------------------===//
196 /// \brief Struct representing the available call values in the scoped hash
201 CallValue(Instruction *I) : Inst(I) {
202 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
205 bool isSentinel() const {
206 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
207 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
210 static bool canHandle(Instruction *Inst) {
211 // Don't value number anything that returns void.
212 if (Inst->getType()->isVoidTy())
215 CallInst *CI = dyn_cast<CallInst>(Inst);
216 if (!CI || !CI->onlyReadsMemory())
224 template <> struct DenseMapInfo<CallValue> {
225 static inline CallValue getEmptyKey() {
226 return DenseMapInfo<Instruction *>::getEmptyKey();
228 static inline CallValue getTombstoneKey() {
229 return DenseMapInfo<Instruction *>::getTombstoneKey();
231 static unsigned getHashValue(CallValue Val);
232 static bool isEqual(CallValue LHS, CallValue RHS);
236 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
237 Instruction *Inst = Val.Inst;
238 // Hash all of the operands as pointers and mix in the opcode.
241 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
244 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
245 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
246 if (LHS.isSentinel() || RHS.isSentinel())
248 return LHSI->isIdenticalTo(RHSI);
251 //===----------------------------------------------------------------------===//
252 // EarlyCSE implementation
253 //===----------------------------------------------------------------------===//
256 /// \brief A simple and fast domtree-based CSE pass.
258 /// This pass does a simple depth-first walk over the dominator tree,
259 /// eliminating trivially redundant instructions and using instsimplify to
260 /// canonicalize things as it goes. It is intended to be fast and catch obvious
261 /// cases so that instcombine and other passes are more effective. It is
262 /// expected that a later pass of GVN will catch the interesting/hard cases.
266 const DataLayout *DL;
267 const TargetLibraryInfo &TLI;
268 const TargetTransformInfo &TTI;
271 typedef RecyclingAllocator<
272 BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy;
273 typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
274 AllocatorTy> ScopedHTType;
276 /// \brief A scoped hash table of the current values of all of our simple
277 /// scalar expressions.
279 /// As we walk down the domtree, we look to see if instructions are in this:
280 /// if so, we replace them with what we find, otherwise we insert them so
281 /// that dominated values can succeed in their lookup.
282 ScopedHTType AvailableValues;
284 /// \brief A scoped hash table of the current values of loads.
286 /// This allows us to get efficient access to dominating loads when we have
287 /// a fully redundant load. In addition to the most recent load, we keep
288 /// track of a generation count of the read, which is compared against the
289 /// current generation count. The current generation count is incremented
290 /// after every possibly writing memory operation, which ensures that we only
291 /// CSE loads with other loads that have no intervening store.
292 typedef RecyclingAllocator<
294 ScopedHashTableVal<Value *, std::pair<Value *, unsigned>>>
296 typedef ScopedHashTable<Value *, std::pair<Value *, unsigned>,
297 DenseMapInfo<Value *>, LoadMapAllocator> LoadHTType;
298 LoadHTType AvailableLoads;
300 /// \brief A scoped hash table of the current values of read-only call
303 /// It uses the same generation count as loads.
304 typedef ScopedHashTable<CallValue, std::pair<Value *, unsigned>> CallHTType;
305 CallHTType AvailableCalls;
307 /// \brief This is the current generation of the memory value.
308 unsigned CurrentGeneration;
310 /// \brief Set up the EarlyCSE runner for a particular function.
311 EarlyCSE(Function &F, const DataLayout *DL, const TargetLibraryInfo &TLI,
312 const TargetTransformInfo &TTI, DominatorTree &DT,
314 : F(F), DL(DL), TLI(TLI), TTI(TTI), DT(DT), AC(AC), CurrentGeneration(0) {
320 // Almost a POD, but needs to call the constructors for the scoped hash
321 // tables so that a new scope gets pushed on. These are RAII so that the
322 // scope gets popped when the NodeScope is destroyed.
325 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
326 CallHTType &AvailableCalls)
327 : Scope(AvailableValues), LoadScope(AvailableLoads),
328 CallScope(AvailableCalls) {}
331 NodeScope(const NodeScope &) LLVM_DELETED_FUNCTION;
332 void operator=(const NodeScope &) LLVM_DELETED_FUNCTION;
334 ScopedHTType::ScopeTy Scope;
335 LoadHTType::ScopeTy LoadScope;
336 CallHTType::ScopeTy CallScope;
339 // Contains all the needed information to create a stack for doing a depth
340 // first tranversal of the tree. This includes scopes for values, loads, and
341 // calls as well as the generation. There is a child iterator so that the
342 // children do not need to be store spearately.
345 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
346 CallHTType &AvailableCalls, unsigned cg, DomTreeNode *n,
347 DomTreeNode::iterator child, DomTreeNode::iterator end)
348 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
349 EndIter(end), Scopes(AvailableValues, AvailableLoads, AvailableCalls),
353 unsigned currentGeneration() { return CurrentGeneration; }
354 unsigned childGeneration() { return ChildGeneration; }
355 void childGeneration(unsigned generation) { ChildGeneration = generation; }
356 DomTreeNode *node() { return Node; }
357 DomTreeNode::iterator childIter() { return ChildIter; }
358 DomTreeNode *nextChild() {
359 DomTreeNode *child = *ChildIter;
363 DomTreeNode::iterator end() { return EndIter; }
364 bool isProcessed() { return Processed; }
365 void process() { Processed = true; }
368 StackNode(const StackNode &) LLVM_DELETED_FUNCTION;
369 void operator=(const StackNode &) LLVM_DELETED_FUNCTION;
372 unsigned CurrentGeneration;
373 unsigned ChildGeneration;
375 DomTreeNode::iterator ChildIter;
376 DomTreeNode::iterator EndIter;
381 /// \brief Wrapper class to handle memory instructions, including loads,
382 /// stores and intrinsic loads and stores defined by the target.
383 class ParseMemoryInst {
385 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
386 : Load(false), Store(false), Vol(false), MayReadFromMemory(false),
387 MayWriteToMemory(false), MatchingId(-1), Ptr(nullptr) {
388 MayReadFromMemory = Inst->mayReadFromMemory();
389 MayWriteToMemory = Inst->mayWriteToMemory();
390 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
391 MemIntrinsicInfo Info;
392 if (!TTI.getTgtMemIntrinsic(II, Info))
394 if (Info.NumMemRefs == 1) {
395 Store = Info.WriteMem;
397 MatchingId = Info.MatchingId;
398 MayReadFromMemory = Info.ReadMem;
399 MayWriteToMemory = Info.WriteMem;
403 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
405 Vol = !LI->isSimple();
406 Ptr = LI->getPointerOperand();
407 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
409 Vol = !SI->isSimple();
410 Ptr = SI->getPointerOperand();
413 bool isLoad() { return Load; }
414 bool isStore() { return Store; }
415 bool isVolatile() { return Vol; }
416 bool isMatchingMemLoc(const ParseMemoryInst &Inst) {
417 return Ptr == Inst.Ptr && MatchingId == Inst.MatchingId;
419 bool isValid() { return Ptr != nullptr; }
420 int getMatchingId() { return MatchingId; }
421 Value *getPtr() { return Ptr; }
422 bool mayReadFromMemory() { return MayReadFromMemory; }
423 bool mayWriteToMemory() { return MayWriteToMemory; }
429 bool MayReadFromMemory;
430 bool MayWriteToMemory;
431 // For regular (non-intrinsic) loads/stores, this is set to -1. For
432 // intrinsic loads/stores, the id is retrieved from the corresponding
433 // field in the MemIntrinsicInfo structure. That field contains
434 // non-negative values only.
439 bool processNode(DomTreeNode *Node);
441 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
442 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
444 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
445 return SI->getValueOperand();
446 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
447 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
453 bool EarlyCSE::processNode(DomTreeNode *Node) {
454 BasicBlock *BB = Node->getBlock();
456 // If this block has a single predecessor, then the predecessor is the parent
457 // of the domtree node and all of the live out memory values are still current
458 // in this block. If this block has multiple predecessors, then they could
459 // have invalidated the live-out memory values of our parent value. For now,
460 // just be conservative and invalidate memory if this block has multiple
462 if (!BB->getSinglePredecessor())
465 /// LastStore - Keep track of the last non-volatile store that we saw... for
466 /// as long as there in no instruction that reads memory. If we see a store
467 /// to the same location, we delete the dead store. This zaps trivial dead
468 /// stores which can occur in bitfield code among other things.
469 Instruction *LastStore = nullptr;
471 bool Changed = false;
473 // See if any instructions in the block can be eliminated. If so, do it. If
474 // not, add them to AvailableValues.
475 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
476 Instruction *Inst = I++;
478 // Dead instructions should just be removed.
479 if (isInstructionTriviallyDead(Inst, &TLI)) {
480 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
481 Inst->eraseFromParent();
487 // Skip assume intrinsics, they don't really have side effects (although
488 // they're marked as such to ensure preservation of control dependencies),
489 // and this pass will not disturb any of the assumption's control
491 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
492 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
496 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
497 // its simpler value.
498 if (Value *V = SimplifyInstruction(Inst, DL, &TLI, &DT, &AC)) {
499 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
500 Inst->replaceAllUsesWith(V);
501 Inst->eraseFromParent();
507 // If this is a simple instruction that we can value number, process it.
508 if (SimpleValue::canHandle(Inst)) {
509 // See if the instruction has an available value. If so, use it.
510 if (Value *V = AvailableValues.lookup(Inst)) {
511 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
512 Inst->replaceAllUsesWith(V);
513 Inst->eraseFromParent();
519 // Otherwise, just remember that this value is available.
520 AvailableValues.insert(Inst, Inst);
524 ParseMemoryInst MemInst(Inst, TTI);
525 // If this is a non-volatile load, process it.
526 if (MemInst.isValid() && MemInst.isLoad()) {
527 // Ignore volatile loads.
528 if (MemInst.isVolatile()) {
530 // Don't CSE across synchronization boundaries.
531 if (Inst->mayWriteToMemory())
536 // If we have an available version of this load, and if it is the right
537 // generation, replace this instruction.
538 std::pair<Value *, unsigned> InVal =
539 AvailableLoads.lookup(MemInst.getPtr());
540 if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
541 Value *Op = getOrCreateResult(InVal.first, Inst->getType());
543 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
544 << " to: " << *InVal.first << '\n');
545 if (!Inst->use_empty())
546 Inst->replaceAllUsesWith(Op);
547 Inst->eraseFromParent();
554 // Otherwise, remember that we have this instruction.
555 AvailableLoads.insert(MemInst.getPtr(), std::pair<Value *, unsigned>(
556 Inst, CurrentGeneration));
561 // If this instruction may read from memory, forget LastStore.
562 // Load/store intrinsics will indicate both a read and a write to
563 // memory. The target may override this (e.g. so that a store intrinsic
564 // does not read from memory, and thus will be treated the same as a
565 // regular store for commoning purposes).
566 if (Inst->mayReadFromMemory() &&
567 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
570 // If this is a read-only call, process it.
571 if (CallValue::canHandle(Inst)) {
572 // If we have an available version of this call, and if it is the right
573 // generation, replace this instruction.
574 std::pair<Value *, unsigned> InVal = AvailableCalls.lookup(Inst);
575 if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
576 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
577 << " to: " << *InVal.first << '\n');
578 if (!Inst->use_empty())
579 Inst->replaceAllUsesWith(InVal.first);
580 Inst->eraseFromParent();
586 // Otherwise, remember that we have this instruction.
587 AvailableCalls.insert(
588 Inst, std::pair<Value *, unsigned>(Inst, CurrentGeneration));
592 // Okay, this isn't something we can CSE at all. Check to see if it is
593 // something that could modify memory. If so, our available memory values
594 // cannot be used so bump the generation count.
595 if (Inst->mayWriteToMemory()) {
598 if (MemInst.isValid() && MemInst.isStore()) {
599 // We do a trivial form of DSE if there are two stores to the same
600 // location with no intervening loads. Delete the earlier store.
602 ParseMemoryInst LastStoreMemInst(LastStore, TTI);
603 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
604 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
605 << " due to: " << *Inst << '\n');
606 LastStore->eraseFromParent();
611 // fallthrough - we can exploit information about this store
614 // Okay, we just invalidated anything we knew about loaded values. Try
615 // to salvage *something* by remembering that the stored value is a live
616 // version of the pointer. It is safe to forward from volatile stores
617 // to non-volatile loads, so we don't have to check for volatility of
619 AvailableLoads.insert(MemInst.getPtr(), std::pair<Value *, unsigned>(
620 Inst, CurrentGeneration));
622 // Remember that this was the last store we saw for DSE.
623 if (!MemInst.isVolatile())
632 bool EarlyCSE::run() {
633 // Note, deque is being used here because there is significant performance
634 // gains over vector when the container becomes very large due to the
635 // specific access patterns. For more information see the mailing list
636 // discussion on this:
637 // http://lists.cs.uiuc.edu/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
638 std::deque<StackNode *> nodesToProcess;
640 bool Changed = false;
642 // Process the root node.
643 nodesToProcess.push_back(new StackNode(
644 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration,
645 DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end()));
647 // Save the current generation.
648 unsigned LiveOutGeneration = CurrentGeneration;
650 // Process the stack.
651 while (!nodesToProcess.empty()) {
652 // Grab the first item off the stack. Set the current generation, remove
653 // the node from the stack, and process it.
654 StackNode *NodeToProcess = nodesToProcess.back();
656 // Initialize class members.
657 CurrentGeneration = NodeToProcess->currentGeneration();
659 // Check if the node needs to be processed.
660 if (!NodeToProcess->isProcessed()) {
662 Changed |= processNode(NodeToProcess->node());
663 NodeToProcess->childGeneration(CurrentGeneration);
664 NodeToProcess->process();
665 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
666 // Push the next child onto the stack.
667 DomTreeNode *child = NodeToProcess->nextChild();
668 nodesToProcess.push_back(
669 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
670 NodeToProcess->childGeneration(), child, child->begin(),
673 // It has been processed, and there are no more children to process,
674 // so delete it and pop it off the stack.
675 delete NodeToProcess;
676 nodesToProcess.pop_back();
678 } // while (!nodes...)
680 // Reset the current generation.
681 CurrentGeneration = LiveOutGeneration;
686 PreservedAnalyses EarlyCSEPass::run(Function &F,
687 AnalysisManager<Function> *AM) {
688 const DataLayout *DL = F.getParent()->getDataLayout();
690 auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
691 auto &TTI = AM->getResult<TargetIRAnalysis>(F);
692 auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
693 auto &AC = AM->getResult<AssumptionAnalysis>(F);
695 EarlyCSE CSE(F, DL, TLI, TTI, DT, AC);
698 return PreservedAnalyses::all();
700 // CSE preserves the dominator tree because it doesn't mutate the CFG.
701 // FIXME: Bundle this with other CFG-preservation.
702 PreservedAnalyses PA;
703 PA.preserve<DominatorTreeAnalysis>();
708 /// \brief A simple and fast domtree-based CSE pass.
710 /// This pass does a simple depth-first walk over the dominator tree,
711 /// eliminating trivially redundant instructions and using instsimplify to
712 /// canonicalize things as it goes. It is intended to be fast and catch obvious
713 /// cases so that instcombine and other passes are more effective. It is
714 /// expected that a later pass of GVN will catch the interesting/hard cases.
715 class EarlyCSELegacyPass : public FunctionPass {
719 EarlyCSELegacyPass() : FunctionPass(ID) {
720 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
723 bool runOnFunction(Function &F) override {
724 if (skipOptnoneFunction(F))
727 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
728 auto *DL = DLP ? &DLP->getDataLayout() : nullptr;
729 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
730 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
731 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
732 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
734 EarlyCSE CSE(F, DL, TLI, TTI, DT, AC);
739 void getAnalysisUsage(AnalysisUsage &AU) const override {
740 AU.addRequired<AssumptionCacheTracker>();
741 AU.addRequired<DominatorTreeWrapperPass>();
742 AU.addRequired<TargetLibraryInfoWrapperPass>();
743 AU.addRequired<TargetTransformInfoWrapperPass>();
744 AU.setPreservesCFG();
749 char EarlyCSELegacyPass::ID = 0;
751 FunctionPass *llvm::createEarlyCSEPass() { return new EarlyCSELegacyPass(); }
753 INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
755 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
756 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
757 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
758 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
759 INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)