1 //===- CSE.cpp - Common Sub-expression Elimination ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This transformation pass performs a simple common sub-expression elimination
10 // algorithm on operations within a region.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PassDetail.h"
15 #include "mlir/IR/Dominance.h"
16 #include "mlir/Pass/Pass.h"
17 #include "mlir/Transforms/Passes.h"
18 #include "mlir/Transforms/Utils.h"
19 #include "llvm/ADT/DenseMapInfo.h"
20 #include "llvm/ADT/Hashing.h"
21 #include "llvm/ADT/ScopedHashTable.h"
22 #include "llvm/Support/Allocator.h"
23 #include "llvm/Support/RecyclingAllocator.h"
24 #include <deque>
25 
26 using namespace mlir;
27 
28 namespace {
29 struct SimpleOperationInfo : public llvm::DenseMapInfo<Operation *> {
getHashValue__anonb1da1e3c0111::SimpleOperationInfo30   static unsigned getHashValue(const Operation *opC) {
31     return OperationEquivalence::computeHash(const_cast<Operation *>(opC));
32   }
isEqual__anonb1da1e3c0111::SimpleOperationInfo33   static bool isEqual(const Operation *lhsC, const Operation *rhsC) {
34     auto *lhs = const_cast<Operation *>(lhsC);
35     auto *rhs = const_cast<Operation *>(rhsC);
36     if (lhs == rhs)
37       return true;
38     if (lhs == getTombstoneKey() || lhs == getEmptyKey() ||
39         rhs == getTombstoneKey() || rhs == getEmptyKey())
40       return false;
41     return OperationEquivalence::isEquivalentTo(const_cast<Operation *>(lhsC),
42                                                 const_cast<Operation *>(rhsC));
43   }
44 };
45 } // end anonymous namespace
46 
47 namespace {
48 /// Simple common sub-expression elimination.
49 struct CSE : public CSEBase<CSE> {
50   /// Shared implementation of operation elimination and scoped map definitions.
51   using AllocatorTy = llvm::RecyclingAllocator<
52       llvm::BumpPtrAllocator,
53       llvm::ScopedHashTableVal<Operation *, Operation *>>;
54   using ScopedMapTy = llvm::ScopedHashTable<Operation *, Operation *,
55                                             SimpleOperationInfo, AllocatorTy>;
56 
57   /// Represents a single entry in the depth first traversal of a CFG.
58   struct CFGStackNode {
CFGStackNode__anonb1da1e3c0211::CSE::CFGStackNode59     CFGStackNode(ScopedMapTy &knownValues, DominanceInfoNode *node)
60         : scope(knownValues), node(node), childIterator(node->begin()),
61           processed(false) {}
62 
63     /// Scope for the known values.
64     ScopedMapTy::ScopeTy scope;
65 
66     DominanceInfoNode *node;
67     DominanceInfoNode::const_iterator childIterator;
68 
69     /// If this node has been fully processed yet or not.
70     bool processed;
71   };
72 
73   /// Attempt to eliminate a redundant operation. Returns success if the
74   /// operation was marked for removal, failure otherwise.
75   LogicalResult simplifyOperation(ScopedMapTy &knownValues, Operation *op,
76                                   bool hasSSADominance);
77   void simplifyBlock(ScopedMapTy &knownValues, Block *bb, bool hasSSADominance);
78   void simplifyRegion(ScopedMapTy &knownValues, Region &region);
79 
80   void runOnOperation() override;
81 
82 private:
83   /// Operations marked as dead and to be erased.
84   std::vector<Operation *> opsToErase;
85   DominanceInfo *domInfo = nullptr;
86 };
87 } // end anonymous namespace
88 
89 /// Attempt to eliminate a redundant operation.
simplifyOperation(ScopedMapTy & knownValues,Operation * op,bool hasSSADominance)90 LogicalResult CSE::simplifyOperation(ScopedMapTy &knownValues, Operation *op,
91                                      bool hasSSADominance) {
92   // Don't simplify terminator operations.
93   if (op->hasTrait<OpTrait::IsTerminator>())
94     return failure();
95 
96   // If the operation is already trivially dead just add it to the erase list.
97   if (isOpTriviallyDead(op)) {
98     opsToErase.push_back(op);
99     ++numDCE;
100     return success();
101   }
102 
103   // Don't simplify operations with nested blocks. We don't currently model
104   // equality comparisons correctly among other things. It is also unclear
105   // whether we would want to CSE such operations.
106   if (op->getNumRegions() != 0)
107     return failure();
108 
109   // TODO: We currently only eliminate non side-effecting
110   // operations.
111   if (!MemoryEffectOpInterface::hasNoEffect(op))
112     return failure();
113 
114   // Look for an existing definition for the operation.
115   if (auto *existing = knownValues.lookup(op)) {
116 
117     // If we find one then replace all uses of the current operation with the
118     // existing one and mark it for deletion. We can only replace an operand in
119     // an operation if it has not been visited yet.
120     if (hasSSADominance) {
121       // If the region has SSA dominance, then we are guaranteed to have not
122       // visited any use of the current operation.
123       op->replaceAllUsesWith(existing);
124       opsToErase.push_back(op);
125     } else {
126       // When the region does not have SSA dominance, we need to check if we
127       // have visited a use before replacing any use.
128       for (auto it : llvm::zip(op->getResults(), existing->getResults())) {
129         std::get<0>(it).replaceUsesWithIf(
130             std::get<1>(it), [&](OpOperand &operand) {
131               return !knownValues.count(operand.getOwner());
132             });
133       }
134 
135       // There may be some remaining uses of the operation.
136       if (op->use_empty())
137         opsToErase.push_back(op);
138     }
139 
140     // If the existing operation has an unknown location and the current
141     // operation doesn't, then set the existing op's location to that of the
142     // current op.
143     if (existing->getLoc().isa<UnknownLoc>() &&
144         !op->getLoc().isa<UnknownLoc>()) {
145       existing->setLoc(op->getLoc());
146     }
147 
148     ++numCSE;
149     return success();
150   }
151 
152   // Otherwise, we add this operation to the known values map.
153   knownValues.insert(op, op);
154   return failure();
155 }
156 
simplifyBlock(ScopedMapTy & knownValues,Block * bb,bool hasSSADominance)157 void CSE::simplifyBlock(ScopedMapTy &knownValues, Block *bb,
158                         bool hasSSADominance) {
159   for (auto &op : *bb) {
160     // If the operation is simplified, we don't process any held regions.
161     if (succeeded(simplifyOperation(knownValues, &op, hasSSADominance)))
162       continue;
163 
164     // Most operations don't have regions, so fast path that case.
165     if (op.getNumRegions() == 0)
166       continue;
167 
168     // If this operation is isolated above, we can't process nested regions with
169     // the given 'knownValues' map. This would cause the insertion of implicit
170     // captures in explicit capture only regions.
171     if (op.mightHaveTrait<OpTrait::IsIsolatedFromAbove>()) {
172       ScopedMapTy nestedKnownValues;
173       for (auto &region : op.getRegions())
174         simplifyRegion(nestedKnownValues, region);
175       continue;
176     }
177 
178     // Otherwise, process nested regions normally.
179     for (auto &region : op.getRegions())
180       simplifyRegion(knownValues, region);
181   }
182 }
183 
simplifyRegion(ScopedMapTy & knownValues,Region & region)184 void CSE::simplifyRegion(ScopedMapTy &knownValues, Region &region) {
185   // If the region is empty there is nothing to do.
186   if (region.empty())
187     return;
188 
189   bool hasSSADominance = domInfo->hasSSADominance(&region);
190 
191   // If the region only contains one block, then simplify it directly.
192   if (region.hasOneBlock()) {
193     ScopedMapTy::ScopeTy scope(knownValues);
194     simplifyBlock(knownValues, &region.front(), hasSSADominance);
195     return;
196   }
197 
198   // If the region does not have dominanceInfo, then skip it.
199   // TODO: Regions without SSA dominance should define a different
200   // traversal order which is appropriate and can be used here.
201   if (!hasSSADominance)
202     return;
203 
204   // Note, deque is being used here because there was significant performance
205   // gains over vector when the container becomes very large due to the
206   // specific access patterns. If/when these performance issues are no
207   // longer a problem we can change this to vector. For more information see
208   // the llvm mailing list discussion on this:
209   // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
210   std::deque<std::unique_ptr<CFGStackNode>> stack;
211 
212   // Process the nodes of the dom tree for this region.
213   stack.emplace_back(std::make_unique<CFGStackNode>(
214       knownValues, domInfo->getRootNode(&region)));
215 
216   while (!stack.empty()) {
217     auto &currentNode = stack.back();
218 
219     // Check to see if we need to process this node.
220     if (!currentNode->processed) {
221       currentNode->processed = true;
222       simplifyBlock(knownValues, currentNode->node->getBlock(),
223                     hasSSADominance);
224     }
225 
226     // Otherwise, check to see if we need to process a child node.
227     if (currentNode->childIterator != currentNode->node->end()) {
228       auto *childNode = *(currentNode->childIterator++);
229       stack.emplace_back(
230           std::make_unique<CFGStackNode>(knownValues, childNode));
231     } else {
232       // Finally, if the node and all of its children have been processed
233       // then we delete the node.
234       stack.pop_back();
235     }
236   }
237 }
238 
runOnOperation()239 void CSE::runOnOperation() {
240   /// A scoped hash table of defining operations within a region.
241   ScopedMapTy knownValues;
242 
243   domInfo = &getAnalysis<DominanceInfo>();
244   Operation *rootOp = getOperation();
245 
246   for (auto &region : rootOp->getRegions())
247     simplifyRegion(knownValues, region);
248 
249   // If no operations were erased, then we mark all analyses as preserved.
250   if (opsToErase.empty())
251     return markAllAnalysesPreserved();
252 
253   /// Erase any operations that were marked as dead during simplification.
254   for (auto *op : opsToErase)
255     op->erase();
256   opsToErase.clear();
257 
258   // We currently don't remove region operations, so mark dominance as
259   // preserved.
260   markAnalysesPreserved<DominanceInfo, PostDominanceInfo>();
261   domInfo = nullptr;
262 }
263 
createCSEPass()264 std::unique_ptr<Pass> mlir::createCSEPass() { return std::make_unique<CSE>(); }
265