xref: /llvm-project/mlir/lib/Transforms/CSE.cpp (revision dea33c80d3666f1e8368ef1a3a09adf999e31723)
17669a259SRiver Riddle //===- CSE.cpp - Common Sub-expression Elimination ------------------------===//
27669a259SRiver Riddle //
330857107SMehdi Amini // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
456222a06SMehdi Amini // See https://llvm.org/LICENSE.txt for license information.
556222a06SMehdi Amini // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67669a259SRiver Riddle //
756222a06SMehdi Amini //===----------------------------------------------------------------------===//
87669a259SRiver Riddle //
97669a259SRiver Riddle // This transformation pass performs a simple common sub-expression elimination
101834ad4aSRiver Riddle // algorithm on operations within a region.
117669a259SRiver Riddle //
127669a259SRiver Riddle //===----------------------------------------------------------------------===//
137669a259SRiver Riddle 
14b9bdff49SMatthias Springer #include "mlir/Transforms/CSE.h"
1567d0d7acSMichele Scuttari 
1657818885SStephen Neuendorffer #include "mlir/IR/Dominance.h"
17b9bdff49SMatthias Springer #include "mlir/IR/PatternMatch.h"
1836d3efeaSRiver Riddle #include "mlir/Interfaces/SideEffectInterfaces.h"
1948ccae24SRiver Riddle #include "mlir/Pass/Pass.h"
20b9bdff49SMatthias Springer #include "mlir/Transforms/Passes.h"
217669a259SRiver Riddle #include "llvm/ADT/DenseMapInfo.h"
227669a259SRiver Riddle #include "llvm/ADT/Hashing.h"
237669a259SRiver Riddle #include "llvm/ADT/ScopedHashTable.h"
247669a259SRiver Riddle #include "llvm/Support/Allocator.h"
257669a259SRiver Riddle #include "llvm/Support/RecyclingAllocator.h"
267669a259SRiver Riddle #include <deque>
271834ad4aSRiver Riddle 
2867d0d7acSMichele Scuttari namespace mlir {
2967d0d7acSMichele Scuttari #define GEN_PASS_DEF_CSE
3067d0d7acSMichele Scuttari #include "mlir/Transforms/Passes.h.inc"
3167d0d7acSMichele Scuttari } // namespace mlir
3267d0d7acSMichele Scuttari 
337669a259SRiver Riddle using namespace mlir;
347669a259SRiver Riddle 
357669a259SRiver Riddle namespace {
3699b87c97SRiver Riddle struct SimpleOperationInfo : public llvm::DenseMapInfo<Operation *> {
getHashValue__anona17202b50111::SimpleOperationInfo3799b87c97SRiver Riddle   static unsigned getHashValue(const Operation *opC) {
380be5d1a9SMehdi Amini     return OperationEquivalence::computeHash(
390be5d1a9SMehdi Amini         const_cast<Operation *>(opC),
400be5d1a9SMehdi Amini         /*hashOperands=*/OperationEquivalence::directHashValue,
410be5d1a9SMehdi Amini         /*hashResults=*/OperationEquivalence::ignoreHashValue,
420be5d1a9SMehdi Amini         OperationEquivalence::IgnoreLocations);
437669a259SRiver Riddle   }
isEqual__anona17202b50111::SimpleOperationInfo4499b87c97SRiver Riddle   static bool isEqual(const Operation *lhsC, const Operation *rhsC) {
4599b87c97SRiver Riddle     auto *lhs = const_cast<Operation *>(lhsC);
4699b87c97SRiver Riddle     auto *rhs = const_cast<Operation *>(rhsC);
477669a259SRiver Riddle     if (lhs == rhs)
487669a259SRiver Riddle       return true;
497669a259SRiver Riddle     if (lhs == getTombstoneKey() || lhs == getEmptyKey() ||
507669a259SRiver Riddle         rhs == getTombstoneKey() || rhs == getEmptyKey())
517669a259SRiver Riddle       return false;
520be5d1a9SMehdi Amini     return OperationEquivalence::isEquivalentTo(
530be5d1a9SMehdi Amini         const_cast<Operation *>(lhsC), const_cast<Operation *>(rhsC),
540be5d1a9SMehdi Amini         OperationEquivalence::IgnoreLocations);
557669a259SRiver Riddle   }
567669a259SRiver Riddle };
57be0a7e9fSMehdi Amini } // namespace
58a250643eSChris Lattner 
59a250643eSChris Lattner namespace {
60a250643eSChris Lattner /// Simple common sub-expression elimination.
61b9bdff49SMatthias Springer class CSEDriver {
62b9bdff49SMatthias Springer public:
CSEDriver(RewriterBase & rewriter,DominanceInfo * domInfo)63b9bdff49SMatthias Springer   CSEDriver(RewriterBase &rewriter, DominanceInfo *domInfo)
64b9bdff49SMatthias Springer       : rewriter(rewriter), domInfo(domInfo) {}
65b9bdff49SMatthias Springer 
66b9bdff49SMatthias Springer   /// Simplify all operations within the given op.
67b9bdff49SMatthias Springer   void simplify(Operation *op, bool *changed = nullptr);
68b9bdff49SMatthias Springer 
getNumCSE() const69b9bdff49SMatthias Springer   int64_t getNumCSE() const { return numCSE; }
getNumDCE() const70b9bdff49SMatthias Springer   int64_t getNumDCE() const { return numDCE; }
71b9bdff49SMatthias Springer 
72b9bdff49SMatthias Springer private:
737669a259SRiver Riddle   /// Shared implementation of operation elimination and scoped map definitions.
747669a259SRiver Riddle   using AllocatorTy = llvm::RecyclingAllocator<
757669a259SRiver Riddle       llvm::BumpPtrAllocator,
7699b87c97SRiver Riddle       llvm::ScopedHashTableVal<Operation *, Operation *>>;
7799b87c97SRiver Riddle   using ScopedMapTy = llvm::ScopedHashTable<Operation *, Operation *,
787669a259SRiver Riddle                                             SimpleOperationInfo, AllocatorTy>;
797669a259SRiver Riddle 
8002da9643SValentin Clement   /// Cache holding MemoryEffects information between two operations. The first
8102da9643SValentin Clement   /// operation is stored has the key. The second operation is stored inside a
8202da9643SValentin Clement   /// pair in the value. The pair also hold the MemoryEffects between those
8302da9643SValentin Clement   /// two operations. If the MemoryEffects is nullptr then we assume there is
8402da9643SValentin Clement   /// no operation with MemoryEffects::Write between the two operations.
8502da9643SValentin Clement   using MemEffectsCache =
8602da9643SValentin Clement       DenseMap<Operation *, std::pair<Operation *, MemoryEffects::Effect *>>;
8702da9643SValentin Clement 
88a250643eSChris Lattner   /// Represents a single entry in the depth first traversal of a CFG.
89a250643eSChris Lattner   struct CFGStackNode {
CFGStackNode__anona17202b50211::CSEDriver::CFGStackNode90a250643eSChris Lattner     CFGStackNode(ScopedMapTy &knownValues, DominanceInfoNode *node)
91671e30a1SMehdi Amini         : scope(knownValues), node(node), childIterator(node->begin()) {}
92a250643eSChris Lattner 
93a250643eSChris Lattner     /// Scope for the known values.
94a250643eSChris Lattner     ScopedMapTy::ScopeTy scope;
95a250643eSChris Lattner 
96a250643eSChris Lattner     DominanceInfoNode *node;
973fa989d4SNicolai Hähnle     DominanceInfoNode::const_iterator childIterator;
98a250643eSChris Lattner 
99a250643eSChris Lattner     /// If this node has been fully processed yet or not.
100671e30a1SMehdi Amini     bool processed = false;
101a250643eSChris Lattner   };
1027669a259SRiver Riddle 
103b67cab4cSRiver Riddle   /// Attempt to eliminate a redundant operation. Returns success if the
104b67cab4cSRiver Riddle   /// operation was marked for removal, failure otherwise.
1059c61c76bSAndrew Young   LogicalResult simplifyOperation(ScopedMapTy &knownValues, Operation *op,
1069c61c76bSAndrew Young                                   bool hasSSADominance);
1071e344ce4SChris Lattner   void simplifyBlock(ScopedMapTy &knownValues, Block *bb, bool hasSSADominance);
1086134231aSChris Lattner   void simplifyRegion(ScopedMapTy &knownValues, Region &region);
109a250643eSChris Lattner 
11002da9643SValentin Clement   void replaceUsesAndDelete(ScopedMapTy &knownValues, Operation *op,
11102da9643SValentin Clement                             Operation *existing, bool hasSSADominance);
11202da9643SValentin Clement 
11302da9643SValentin Clement   /// Check if there is side-effecting operations other than the given effect
11402da9643SValentin Clement   /// between the two operations.
11502da9643SValentin Clement   bool hasOtherSideEffectingOpInBetween(Operation *fromOp, Operation *toOp);
11602da9643SValentin Clement 
117b9bdff49SMatthias Springer   /// A rewriter for modifying the IR.
118b9bdff49SMatthias Springer   RewriterBase &rewriter;
119b9bdff49SMatthias Springer 
120a250643eSChris Lattner   /// Operations marked as dead and to be erased.
12199b87c97SRiver Riddle   std::vector<Operation *> opsToErase;
1229979417dSFangrui Song   DominanceInfo *domInfo = nullptr;
12302da9643SValentin Clement   MemEffectsCache memEffectsCache;
124b9bdff49SMatthias Springer 
125b9bdff49SMatthias Springer   // Various statistics.
126b9bdff49SMatthias Springer   int64_t numCSE = 0;
127b9bdff49SMatthias Springer   int64_t numDCE = 0;
128a250643eSChris Lattner };
129be0a7e9fSMehdi Amini } // namespace
130a250643eSChris Lattner 
replaceUsesAndDelete(ScopedMapTy & knownValues,Operation * op,Operation * existing,bool hasSSADominance)131b9bdff49SMatthias Springer void CSEDriver::replaceUsesAndDelete(ScopedMapTy &knownValues, Operation *op,
132b9bdff49SMatthias Springer                                      Operation *existing,
133b9bdff49SMatthias Springer                                      bool hasSSADominance) {
1347669a259SRiver Riddle   // If we find one then replace all uses of the current operation with the
1359c61c76bSAndrew Young   // existing one and mark it for deletion. We can only replace an operand in
1369c61c76bSAndrew Young   // an operation if it has not been visited yet.
1379c61c76bSAndrew Young   if (hasSSADominance) {
1389c61c76bSAndrew Young     // If the region has SSA dominance, then we are guaranteed to have not
1399c61c76bSAndrew Young     // visited any use of the current operation.
140b9bdff49SMatthias Springer     if (auto *rewriteListener =
141b9bdff49SMatthias Springer             dyn_cast_if_present<RewriterBase::Listener>(rewriter.getListener()))
142b9bdff49SMatthias Springer       rewriteListener->notifyOperationReplaced(op, existing);
143b9bdff49SMatthias Springer     // Replace all uses, but do not remote the operation yet. This does not
144b9bdff49SMatthias Springer     // notify the listener because the original op is not erased.
145b9bdff49SMatthias Springer     rewriter.replaceAllUsesWith(op->getResults(), existing->getResults());
1467669a259SRiver Riddle     opsToErase.push_back(op);
1479c61c76bSAndrew Young   } else {
1489c61c76bSAndrew Young     // When the region does not have SSA dominance, we need to check if we
1499c61c76bSAndrew Young     // have visited a use before replacing any use.
150b9bdff49SMatthias Springer     auto wasVisited = [&](OpOperand &operand) {
1519c61c76bSAndrew Young       return !knownValues.count(operand.getOwner());
152b9bdff49SMatthias Springer     };
153b9bdff49SMatthias Springer     if (auto *rewriteListener =
154b9bdff49SMatthias Springer             dyn_cast_if_present<RewriterBase::Listener>(rewriter.getListener()))
155b9bdff49SMatthias Springer       for (Value v : op->getResults())
156b9bdff49SMatthias Springer         if (all_of(v.getUses(), wasVisited))
157b9bdff49SMatthias Springer           rewriteListener->notifyOperationReplaced(op, existing);
158b9bdff49SMatthias Springer 
159b9bdff49SMatthias Springer     // Replace all uses, but do not remote the operation yet. This does not
160b9bdff49SMatthias Springer     // notify the listener because the original op is not erased.
161b9bdff49SMatthias Springer     rewriter.replaceUsesWithIf(op->getResults(), existing->getResults(),
162b9bdff49SMatthias Springer                                wasVisited);
1639c61c76bSAndrew Young 
1649c61c76bSAndrew Young     // There may be some remaining uses of the operation.
1659c61c76bSAndrew Young     if (op->use_empty())
1669c61c76bSAndrew Young       opsToErase.push_back(op);
1679c61c76bSAndrew Young   }
1687669a259SRiver Riddle 
1697669a259SRiver Riddle   // If the existing operation has an unknown location and the current
1707669a259SRiver Riddle   // operation doesn't, then set the existing op's location to that of the
1717669a259SRiver Riddle   // current op.
1725550c821STres Popp   if (isa<UnknownLoc>(existing->getLoc()) && !isa<UnknownLoc>(op->getLoc()))
1737669a259SRiver Riddle     existing->setLoc(op->getLoc());
17402da9643SValentin Clement 
17502da9643SValentin Clement   ++numCSE;
1767669a259SRiver Riddle }
17733a64540SRiver Riddle 
hasOtherSideEffectingOpInBetween(Operation * fromOp,Operation * toOp)178b9bdff49SMatthias Springer bool CSEDriver::hasOtherSideEffectingOpInBetween(Operation *fromOp,
179b9bdff49SMatthias Springer                                                  Operation *toOp) {
18002da9643SValentin Clement   assert(fromOp->getBlock() == toOp->getBlock());
18102da9643SValentin Clement   assert(
18202da9643SValentin Clement       isa<MemoryEffectOpInterface>(fromOp) &&
18302da9643SValentin Clement       cast<MemoryEffectOpInterface>(fromOp).hasEffect<MemoryEffects::Read>() &&
18402da9643SValentin Clement       isa<MemoryEffectOpInterface>(toOp) &&
18502da9643SValentin Clement       cast<MemoryEffectOpInterface>(toOp).hasEffect<MemoryEffects::Read>());
18602da9643SValentin Clement   Operation *nextOp = fromOp->getNextNode();
18702da9643SValentin Clement   auto result =
18802da9643SValentin Clement       memEffectsCache.try_emplace(fromOp, std::make_pair(fromOp, nullptr));
18902da9643SValentin Clement   if (result.second) {
19002da9643SValentin Clement     auto memEffectsCachePair = result.first->second;
19102da9643SValentin Clement     if (memEffectsCachePair.second == nullptr) {
19202da9643SValentin Clement       // No MemoryEffects::Write has been detected until the cached operation.
19302da9643SValentin Clement       // Continue looking from the cached operation to toOp.
19402da9643SValentin Clement       nextOp = memEffectsCachePair.first;
19502da9643SValentin Clement     } else {
19602da9643SValentin Clement       // MemoryEffects::Write has been detected before so there is no need to
19702da9643SValentin Clement       // check further.
19802da9643SValentin Clement       return true;
19902da9643SValentin Clement     }
20002da9643SValentin Clement   }
20102da9643SValentin Clement   while (nextOp && nextOp != toOp) {
202*dea33c80STom Eccles     std::optional<SmallVector<MemoryEffects::EffectInstance>> effects =
203*dea33c80STom Eccles         getEffectsRecursively(nextOp);
204*dea33c80STom Eccles     if (!effects) {
20502da9643SValentin Clement       // TODO: Do we need to handle other effects generically?
20602da9643SValentin Clement       // If the operation does not implement the MemoryEffectOpInterface we
207*dea33c80STom Eccles       // conservatively assume it writes.
20802da9643SValentin Clement       result.first->second =
20902da9643SValentin Clement           std::make_pair(nextOp, MemoryEffects::Write::get());
21002da9643SValentin Clement       return true;
21102da9643SValentin Clement     }
212*dea33c80STom Eccles 
213*dea33c80STom Eccles     for (const MemoryEffects::EffectInstance &effect : *effects) {
214*dea33c80STom Eccles       if (isa<MemoryEffects::Write>(effect.getEffect())) {
215*dea33c80STom Eccles         result.first->second = {nextOp, MemoryEffects::Write::get()};
216*dea33c80STom Eccles         return true;
217*dea33c80STom Eccles       }
218*dea33c80STom Eccles     }
21902da9643SValentin Clement     nextOp = nextOp->getNextNode();
22002da9643SValentin Clement   }
22102da9643SValentin Clement   result.first->second = std::make_pair(toOp, nullptr);
22202da9643SValentin Clement   return false;
22302da9643SValentin Clement }
22402da9643SValentin Clement 
22502da9643SValentin Clement /// Attempt to eliminate a redundant operation.
simplifyOperation(ScopedMapTy & knownValues,Operation * op,bool hasSSADominance)226b9bdff49SMatthias Springer LogicalResult CSEDriver::simplifyOperation(ScopedMapTy &knownValues,
227b9bdff49SMatthias Springer                                            Operation *op,
228039b969bSMichele Scuttari                                            bool hasSSADominance) {
22902da9643SValentin Clement   // Don't simplify terminator operations.
23002da9643SValentin Clement   if (op->hasTrait<OpTrait::IsTerminator>())
23102da9643SValentin Clement     return failure();
23202da9643SValentin Clement 
23302da9643SValentin Clement   // If the operation is already trivially dead just add it to the erase list.
23402da9643SValentin Clement   if (isOpTriviallyDead(op)) {
23502da9643SValentin Clement     opsToErase.push_back(op);
23602da9643SValentin Clement     ++numDCE;
23702da9643SValentin Clement     return success();
23802da9643SValentin Clement   }
23902da9643SValentin Clement 
240aa4e54f2SMatthias Springer   // Don't simplify operations with regions that have multiple blocks.
241aa4e54f2SMatthias Springer   // TODO: We need additional tests to verify that we handle such IR correctly.
242aa4e54f2SMatthias Springer   if (!llvm::all_of(op->getRegions(), [](Region &r) {
243aa4e54f2SMatthias Springer         return r.getBlocks().empty() || llvm::hasSingleElement(r.getBlocks());
244aa4e54f2SMatthias Springer       }))
24502da9643SValentin Clement     return failure();
24602da9643SValentin Clement 
24702da9643SValentin Clement   // Some simple use case of operation with memory side-effect are dealt with
24802da9643SValentin Clement   // here. Operations with no side-effect are done after.
249fc367dfaSMahesh Ravishankar   if (!isMemoryEffectFree(op)) {
25002da9643SValentin Clement     auto memEffects = dyn_cast<MemoryEffectOpInterface>(op);
25102da9643SValentin Clement     // TODO: Only basic use case for operations with MemoryEffects::Read can be
25202da9643SValentin Clement     // eleminated now. More work needs to be done for more complicated patterns
25302da9643SValentin Clement     // and other side-effects.
25402da9643SValentin Clement     if (!memEffects || !memEffects.onlyHasEffect<MemoryEffects::Read>())
25502da9643SValentin Clement       return failure();
25602da9643SValentin Clement 
25702da9643SValentin Clement     // Look for an existing definition for the operation.
25802da9643SValentin Clement     if (auto *existing = knownValues.lookup(op)) {
25902da9643SValentin Clement       if (existing->getBlock() == op->getBlock() &&
26002da9643SValentin Clement           !hasOtherSideEffectingOpInBetween(existing, op)) {
26102da9643SValentin Clement         // The operation that can be deleted has been reach with no
26202da9643SValentin Clement         // side-effecting operations in between the existing operation and
26302da9643SValentin Clement         // this one so we can remove the duplicate.
26402da9643SValentin Clement         replaceUsesAndDelete(knownValues, op, existing, hasSSADominance);
26502da9643SValentin Clement         return success();
26602da9643SValentin Clement       }
26702da9643SValentin Clement     }
26802da9643SValentin Clement     knownValues.insert(op, op);
26902da9643SValentin Clement     return failure();
27002da9643SValentin Clement   }
27102da9643SValentin Clement 
27202da9643SValentin Clement   // Look for an existing definition for the operation.
27302da9643SValentin Clement   if (auto *existing = knownValues.lookup(op)) {
27402da9643SValentin Clement     replaceUsesAndDelete(knownValues, op, existing, hasSSADominance);
27533a64540SRiver Riddle     ++numCSE;
276b67cab4cSRiver Riddle     return success();
277c3424c3cSRiver Riddle   }
278c3424c3cSRiver Riddle 
2797669a259SRiver Riddle   // Otherwise, we add this operation to the known values map.
2807669a259SRiver Riddle   knownValues.insert(op, op);
281b67cab4cSRiver Riddle   return failure();
2827669a259SRiver Riddle }
2837669a259SRiver Riddle 
simplifyBlock(ScopedMapTy & knownValues,Block * bb,bool hasSSADominance)284b9bdff49SMatthias Springer void CSEDriver::simplifyBlock(ScopedMapTy &knownValues, Block *bb,
2851e344ce4SChris Lattner                               bool hasSSADominance) {
2861e344ce4SChris Lattner   for (auto &op : *bb) {
2871e344ce4SChris Lattner     // Most operations don't have regions, so fast path that case.
288242d5b2bSMahesh Ravishankar     if (op.getNumRegions() != 0) {
289242d5b2bSMahesh Ravishankar       // If this operation is isolated above, we can't process nested regions
290242d5b2bSMahesh Ravishankar       // with the given 'knownValues' map. This would cause the insertion of
291242d5b2bSMahesh Ravishankar       // implicit captures in explicit capture only regions.
2921e344ce4SChris Lattner       if (op.mightHaveTrait<OpTrait::IsIsolatedFromAbove>()) {
293b67cab4cSRiver Riddle         ScopedMapTy nestedKnownValues;
2946134231aSChris Lattner         for (auto &region : op.getRegions())
2956134231aSChris Lattner           simplifyRegion(nestedKnownValues, region);
296242d5b2bSMahesh Ravishankar       } else {
297b67cab4cSRiver Riddle         // Otherwise, process nested regions normally.
2986134231aSChris Lattner         for (auto &region : op.getRegions())
2996134231aSChris Lattner           simplifyRegion(knownValues, region);
300cdbfd484SRiver Riddle       }
301242d5b2bSMahesh Ravishankar     }
302242d5b2bSMahesh Ravishankar 
303242d5b2bSMahesh Ravishankar     // If the operation is simplified, we don't process any held regions.
304242d5b2bSMahesh Ravishankar     if (succeeded(simplifyOperation(knownValues, &op, hasSSADominance)))
305242d5b2bSMahesh Ravishankar       continue;
306242d5b2bSMahesh Ravishankar   }
30702da9643SValentin Clement   // Clear the MemoryEffects cache since its usage is by block only.
30802da9643SValentin Clement   memEffectsCache.clear();
309cdbfd484SRiver Riddle }
310cdbfd484SRiver Riddle 
simplifyRegion(ScopedMapTy & knownValues,Region & region)311b9bdff49SMatthias Springer void CSEDriver::simplifyRegion(ScopedMapTy &knownValues, Region &region) {
312276fae1bSAlex Zinenko   // If the region is empty there is nothing to do.
313276fae1bSAlex Zinenko   if (region.empty())
314cdbfd484SRiver Riddle     return;
315cdbfd484SRiver Riddle 
3169979417dSFangrui Song   bool hasSSADominance = domInfo->hasSSADominance(&region);
3176134231aSChris Lattner 
318276fae1bSAlex Zinenko   // If the region only contains one block, then simplify it directly.
319412ae15dSChris Lattner   if (region.hasOneBlock()) {
320c3424c3cSRiver Riddle     ScopedMapTy::ScopeTy scope(knownValues);
3211e344ce4SChris Lattner     simplifyBlock(knownValues, &region.front(), hasSSADominance);
322cdbfd484SRiver Riddle     return;
323c3424c3cSRiver Riddle   }
324cdbfd484SRiver Riddle 
32562828865SStephen Neuendorffer   // If the region does not have dominanceInfo, then skip it.
32662828865SStephen Neuendorffer   // TODO: Regions without SSA dominance should define a different
32762828865SStephen Neuendorffer   // traversal order which is appropriate and can be used here.
3289c61c76bSAndrew Young   if (!hasSSADominance)
32962828865SStephen Neuendorffer     return;
33062828865SStephen Neuendorffer 
3317669a259SRiver Riddle   // Note, deque is being used here because there was significant performance
3327669a259SRiver Riddle   // gains over vector when the container becomes very large due to the
3337669a259SRiver Riddle   // specific access patterns. If/when these performance issues are no
3347669a259SRiver Riddle   // longer a problem we can change this to vector. For more information see
3357669a259SRiver Riddle   // the llvm mailing list discussion on this:
3367669a259SRiver Riddle   // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
3377669a259SRiver Riddle   std::deque<std::unique_ptr<CFGStackNode>> stack;
3387669a259SRiver Riddle 
339276fae1bSAlex Zinenko   // Process the nodes of the dom tree for this region.
34079f53b0cSJacques Pienaar   stack.emplace_back(std::make_unique<CFGStackNode>(
3419979417dSFangrui Song       knownValues, domInfo->getRootNode(&region)));
3427669a259SRiver Riddle 
3437669a259SRiver Riddle   while (!stack.empty()) {
3447669a259SRiver Riddle     auto &currentNode = stack.back();
3457669a259SRiver Riddle 
3467669a259SRiver Riddle     // Check to see if we need to process this node.
3477669a259SRiver Riddle     if (!currentNode->processed) {
3487669a259SRiver Riddle       currentNode->processed = true;
3491e344ce4SChris Lattner       simplifyBlock(knownValues, currentNode->node->getBlock(),
3509c61c76bSAndrew Young                     hasSSADominance);
351a250643eSChris Lattner     }
352a250643eSChris Lattner 
3537669a259SRiver Riddle     // Otherwise, check to see if we need to process a child node.
354a250643eSChris Lattner     if (currentNode->childIterator != currentNode->node->end()) {
3557669a259SRiver Riddle       auto *childNode = *(currentNode->childIterator++);
3567669a259SRiver Riddle       stack.emplace_back(
35779f53b0cSJacques Pienaar           std::make_unique<CFGStackNode>(knownValues, childNode));
3587669a259SRiver Riddle     } else {
3597669a259SRiver Riddle       // Finally, if the node and all of its children have been processed
3607669a259SRiver Riddle       // then we delete the node.
3617669a259SRiver Riddle       stack.pop_back();
3627669a259SRiver Riddle     }
3637669a259SRiver Riddle   }
364cdbfd484SRiver Riddle }
365cdbfd484SRiver Riddle 
simplify(Operation * op,bool * changed)366b9bdff49SMatthias Springer void CSEDriver::simplify(Operation *op, bool *changed) {
367b9bdff49SMatthias Springer   /// Simplify all regions.
368b67cab4cSRiver Riddle   ScopedMapTy knownValues;
369b9bdff49SMatthias Springer   for (auto &region : op->getRegions())
3706134231aSChris Lattner     simplifyRegion(knownValues, region);
371485746f5SRiver Riddle 
372a250643eSChris Lattner   /// Erase any operations that were marked as dead during simplification.
373a250643eSChris Lattner   for (auto *op : opsToErase)
374b9bdff49SMatthias Springer     rewriter.eraseOp(op);
375b9bdff49SMatthias Springer   if (changed)
376b9bdff49SMatthias Springer     *changed = !opsToErase.empty();
377b9bdff49SMatthias Springer 
378b9bdff49SMatthias Springer   // Note: CSE does currently not remove ops with regions, so DominanceInfo
379b9bdff49SMatthias Springer   // does not have to be invalidated.
380b9bdff49SMatthias Springer }
381b9bdff49SMatthias Springer 
eliminateCommonSubExpressions(RewriterBase & rewriter,DominanceInfo & domInfo,Operation * op,bool * changed)382b9bdff49SMatthias Springer void mlir::eliminateCommonSubExpressions(RewriterBase &rewriter,
383b9bdff49SMatthias Springer                                          DominanceInfo &domInfo, Operation *op,
384b9bdff49SMatthias Springer                                          bool *changed) {
385b9bdff49SMatthias Springer   CSEDriver driver(rewriter, &domInfo);
386b9bdff49SMatthias Springer   driver.simplify(op, changed);
387b9bdff49SMatthias Springer }
388b9bdff49SMatthias Springer 
389b9bdff49SMatthias Springer namespace {
390b9bdff49SMatthias Springer /// CSE pass.
391b9bdff49SMatthias Springer struct CSE : public impl::CSEBase<CSE> {
392b9bdff49SMatthias Springer   void runOnOperation() override;
393b9bdff49SMatthias Springer };
394b9bdff49SMatthias Springer } // namespace
395b9bdff49SMatthias Springer 
runOnOperation()396b9bdff49SMatthias Springer void CSE::runOnOperation() {
397b9bdff49SMatthias Springer   // Simplify the IR.
398b9bdff49SMatthias Springer   IRRewriter rewriter(&getContext());
399b9bdff49SMatthias Springer   CSEDriver driver(rewriter, &getAnalysis<DominanceInfo>());
400b9bdff49SMatthias Springer   bool changed = false;
401b9bdff49SMatthias Springer   driver.simplify(getOperation(), &changed);
402b9bdff49SMatthias Springer 
403b9bdff49SMatthias Springer   // Set statistics.
404b9bdff49SMatthias Springer   numCSE = driver.getNumCSE();
405b9bdff49SMatthias Springer   numDCE = driver.getNumDCE();
406b9bdff49SMatthias Springer 
407b9bdff49SMatthias Springer   // If there was no change to the IR, we mark all analyses as preserved.
408b9bdff49SMatthias Springer   if (!changed)
409b9bdff49SMatthias Springer     return markAllAnalysesPreserved();
4101d87b62aSRiver Riddle 
4111d87b62aSRiver Riddle   // We currently don't remove region operations, so mark dominance as
4121d87b62aSRiver Riddle   // preserved.
4131d87b62aSRiver Riddle   markAnalysesPreserved<DominanceInfo, PostDominanceInfo>();
4147669a259SRiver Riddle }
415039b969bSMichele Scuttari 
createCSEPass()416039b969bSMichele Scuttari std::unique_ptr<Pass> mlir::createCSEPass() { return std::make_unique<CSE>(); }
417