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 function.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Analysis/Dominance.h"
15 #include "mlir/IR/Attributes.h"
16 #include "mlir/IR/Builders.h"
17 #include "mlir/IR/Function.h"
18 #include "mlir/Pass/Pass.h"
19 #include "mlir/Support/Functional.h"
20 #include "mlir/Transforms/Passes.h"
21 #include "mlir/Transforms/Utils.h"
22 #include "llvm/ADT/DenseMapInfo.h"
23 #include "llvm/ADT/Hashing.h"
24 #include "llvm/ADT/ScopedHashTable.h"
25 #include "llvm/Support/Allocator.h"
26 #include "llvm/Support/RecyclingAllocator.h"
27 #include <deque>
28 using namespace mlir;
29 
30 namespace {
31 // TODO(riverriddle) Handle commutative operations.
32 struct SimpleOperationInfo : public llvm::DenseMapInfo<Operation *> {
33   static unsigned getHashValue(const Operation *opC) {
34     auto *op = const_cast<Operation *>(opC);
35     // Hash the operations based upon their:
36     //   - Operation Name
37     //   - Attributes
38     //   - Result Types
39     //   - Operands
40     return llvm::hash_combine(
41         op->getName(), op->getAttrList().getDictionary(), op->getResultTypes(),
42         llvm::hash_combine_range(op->operand_begin(), op->operand_end()));
43   }
44   static bool isEqual(const Operation *lhsC, const Operation *rhsC) {
45     auto *lhs = const_cast<Operation *>(lhsC);
46     auto *rhs = const_cast<Operation *>(rhsC);
47     if (lhs == rhs)
48       return true;
49     if (lhs == getTombstoneKey() || lhs == getEmptyKey() ||
50         rhs == getTombstoneKey() || rhs == getEmptyKey())
51       return false;
52 
53     // Compare the operation name.
54     if (lhs->getName() != rhs->getName())
55       return false;
56     // Check operand and result type counts.
57     if (lhs->getNumOperands() != rhs->getNumOperands() ||
58         lhs->getNumResults() != rhs->getNumResults())
59       return false;
60     // Compare attributes.
61     if (lhs->getAttrList() != rhs->getAttrList())
62       return false;
63     // Compare operands.
64     if (!std::equal(lhs->operand_begin(), lhs->operand_end(),
65                     rhs->operand_begin()))
66       return false;
67     // Compare result types.
68     return std::equal(lhs->result_type_begin(), lhs->result_type_end(),
69                       rhs->result_type_begin());
70   }
71 };
72 } // end anonymous namespace
73 
74 namespace {
75 /// Simple common sub-expression elimination.
76 struct CSE : public OperationPass<CSE> {
77   CSE() = default;
78   CSE(const CSE &) {}
79 
80   /// Shared implementation of operation elimination and scoped map definitions.
81   using AllocatorTy = llvm::RecyclingAllocator<
82       llvm::BumpPtrAllocator,
83       llvm::ScopedHashTableVal<Operation *, Operation *>>;
84   using ScopedMapTy = llvm::ScopedHashTable<Operation *, Operation *,
85                                             SimpleOperationInfo, AllocatorTy>;
86 
87   /// Represents a single entry in the depth first traversal of a CFG.
88   struct CFGStackNode {
89     CFGStackNode(ScopedMapTy &knownValues, DominanceInfoNode *node)
90         : scope(knownValues), node(node), childIterator(node->begin()),
91           processed(false) {}
92 
93     /// Scope for the known values.
94     ScopedMapTy::ScopeTy scope;
95 
96     DominanceInfoNode *node;
97     DominanceInfoNode::iterator childIterator;
98 
99     /// If this node has been fully processed yet or not.
100     bool processed;
101   };
102 
103   /// Attempt to eliminate a redundant operation. Returns success if the
104   /// operation was marked for removal, failure otherwise.
105   LogicalResult simplifyOperation(ScopedMapTy &knownValues, Operation *op);
106 
107   void simplifyBlock(ScopedMapTy &knownValues, DominanceInfo &domInfo,
108                      Block *bb);
109   void simplifyRegion(ScopedMapTy &knownValues, DominanceInfo &domInfo,
110                       Region &region);
111 
112   void runOnOperation() override;
113 
114 private:
115   /// Operations marked as dead and to be erased.
116   std::vector<Operation *> opsToErase;
117 
118   /// Statistics for CSE.
119   Statistic numCSE{this, "num-cse'd", "Number of operations CSE'd"};
120   Statistic numDCE{this, "num-dce'd", "Number of operations trivially DCE'd"};
121 };
122 } // end anonymous namespace
123 
124 /// Attempt to eliminate a redundant operation.
125 LogicalResult CSE::simplifyOperation(ScopedMapTy &knownValues, Operation *op) {
126   // Don't simplify operations with nested blocks. We don't currently model
127   // equality comparisons correctly among other things. It is also unclear
128   // whether we would want to CSE such operations.
129   if (op->getNumRegions() != 0)
130     return failure();
131 
132   // TODO(riverriddle) We currently only eliminate non side-effecting
133   // operations.
134   if (!op->hasNoSideEffect())
135     return failure();
136 
137   // If the operation is already trivially dead just add it to the erase list.
138   if (op->use_empty()) {
139     opsToErase.push_back(op);
140     ++numDCE;
141     return success();
142   }
143 
144   // Look for an existing definition for the operation.
145   if (auto *existing = knownValues.lookup(op)) {
146     // If we find one then replace all uses of the current operation with the
147     // existing one and mark it for deletion.
148     op->replaceAllUsesWith(existing);
149     opsToErase.push_back(op);
150 
151     // If the existing operation has an unknown location and the current
152     // operation doesn't, then set the existing op's location to that of the
153     // current op.
154     if (existing->getLoc().isa<UnknownLoc>() &&
155         !op->getLoc().isa<UnknownLoc>()) {
156       existing->setLoc(op->getLoc());
157     }
158 
159     ++numCSE;
160     return success();
161   }
162 
163   // Otherwise, we add this operation to the known values map.
164   knownValues.insert(op, op);
165   return failure();
166 }
167 
168 void CSE::simplifyBlock(ScopedMapTy &knownValues, DominanceInfo &domInfo,
169                         Block *bb) {
170   for (auto &inst : *bb) {
171     // If the operation is simplified, we don't process any held regions.
172     if (succeeded(simplifyOperation(knownValues, &inst)))
173       continue;
174 
175     // If this operation is isolated above, we can't process nested regions with
176     // the given 'knownValues' map. This would cause the insertion of implicit
177     // captures in explicit capture only regions.
178     if (!inst.isRegistered() || inst.isKnownIsolatedFromAbove()) {
179       ScopedMapTy nestedKnownValues;
180       for (auto &region : inst.getRegions())
181         simplifyRegion(nestedKnownValues, domInfo, region);
182       continue;
183     }
184 
185     // Otherwise, process nested regions normally.
186     for (auto &region : inst.getRegions())
187       simplifyRegion(knownValues, domInfo, region);
188   }
189 }
190 
191 void CSE::simplifyRegion(ScopedMapTy &knownValues, DominanceInfo &domInfo,
192                          Region &region) {
193   // If the region is empty there is nothing to do.
194   if (region.empty())
195     return;
196 
197   // If the region only contains one block, then simplify it directly.
198   if (std::next(region.begin()) == region.end()) {
199     ScopedMapTy::ScopeTy scope(knownValues);
200     simplifyBlock(knownValues, domInfo, &region.front());
201     return;
202   }
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, domInfo, currentNode->node->getBlock());
223     }
224 
225     // Otherwise, check to see if we need to process a child node.
226     if (currentNode->childIterator != currentNode->node->end()) {
227       auto *childNode = *(currentNode->childIterator++);
228       stack.emplace_back(
229           std::make_unique<CFGStackNode>(knownValues, childNode));
230     } else {
231       // Finally, if the node and all of its children have been processed
232       // then we delete the node.
233       stack.pop_back();
234     }
235   }
236 }
237 
238 void CSE::runOnOperation() {
239   /// A scoped hash table of defining operations within a region.
240   ScopedMapTy knownValues;
241 
242   DominanceInfo &domInfo = getAnalysis<DominanceInfo>();
243   for (Region &region : getOperation()->getRegions())
244     simplifyRegion(knownValues, domInfo, region);
245 
246   // If no operations were erased, then we mark all analyses as preserved.
247   if (opsToErase.empty())
248     return markAllAnalysesPreserved();
249 
250   /// Erase any operations that were marked as dead during simplification.
251   for (auto *op : opsToErase)
252     op->erase();
253   opsToErase.clear();
254 
255   // We currently don't remove region operations, so mark dominance as
256   // preserved.
257   markAnalysesPreserved<DominanceInfo, PostDominanceInfo>();
258 }
259 
260 std::unique_ptr<Pass> mlir::createCSEPass() { return std::make_unique<CSE>(); }
261 
262 static PassRegistration<CSE> pass("cse", "Eliminate common sub-expressions");
263