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 terminator operations.
127   if (op->isKnownTerminator())
128     return failure();
129 
130   // If the operation is already trivially dead just add it to the erase list.
131   if (isOpTriviallyDead(op)) {
132     opsToErase.push_back(op);
133     ++numDCE;
134     return success();
135   }
136 
137   // Don't simplify operations with nested blocks. We don't currently model
138   // equality comparisons correctly among other things. It is also unclear
139   // whether we would want to CSE such operations.
140   if (op->getNumRegions() != 0)
141     return failure();
142 
143   // TODO(riverriddle) We currently only eliminate non side-effecting
144   // operations.
145   if (!MemoryEffectOpInterface::hasNoEffect(op))
146     return failure();
147 
148   // Look for an existing definition for the operation.
149   if (auto *existing = knownValues.lookup(op)) {
150     // If we find one then replace all uses of the current operation with the
151     // existing one and mark it for deletion.
152     op->replaceAllUsesWith(existing);
153     opsToErase.push_back(op);
154 
155     // If the existing operation has an unknown location and the current
156     // operation doesn't, then set the existing op's location to that of the
157     // current op.
158     if (existing->getLoc().isa<UnknownLoc>() &&
159         !op->getLoc().isa<UnknownLoc>()) {
160       existing->setLoc(op->getLoc());
161     }
162 
163     ++numCSE;
164     return success();
165   }
166 
167   // Otherwise, we add this operation to the known values map.
168   knownValues.insert(op, op);
169   return failure();
170 }
171 
172 void CSE::simplifyBlock(ScopedMapTy &knownValues, DominanceInfo &domInfo,
173                         Block *bb) {
174   for (auto &inst : *bb) {
175     // If the operation is simplified, we don't process any held regions.
176     if (succeeded(simplifyOperation(knownValues, &inst)))
177       continue;
178 
179     // If this operation is isolated above, we can't process nested regions with
180     // the given 'knownValues' map. This would cause the insertion of implicit
181     // captures in explicit capture only regions.
182     if (!inst.isRegistered() || inst.isKnownIsolatedFromAbove()) {
183       ScopedMapTy nestedKnownValues;
184       for (auto &region : inst.getRegions())
185         simplifyRegion(nestedKnownValues, domInfo, region);
186       continue;
187     }
188 
189     // Otherwise, process nested regions normally.
190     for (auto &region : inst.getRegions())
191       simplifyRegion(knownValues, domInfo, region);
192   }
193 }
194 
195 void CSE::simplifyRegion(ScopedMapTy &knownValues, DominanceInfo &domInfo,
196                          Region &region) {
197   // If the region is empty there is nothing to do.
198   if (region.empty())
199     return;
200 
201   // If the region only contains one block, then simplify it directly.
202   if (std::next(region.begin()) == region.end()) {
203     ScopedMapTy::ScopeTy scope(knownValues);
204     simplifyBlock(knownValues, domInfo, &region.front());
205     return;
206   }
207 
208   // Note, deque is being used here because there was significant performance
209   // gains over vector when the container becomes very large due to the
210   // specific access patterns. If/when these performance issues are no
211   // longer a problem we can change this to vector. For more information see
212   // the llvm mailing list discussion on this:
213   // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
214   std::deque<std::unique_ptr<CFGStackNode>> stack;
215 
216   // Process the nodes of the dom tree for this region.
217   stack.emplace_back(std::make_unique<CFGStackNode>(
218       knownValues, domInfo.getRootNode(&region)));
219 
220   while (!stack.empty()) {
221     auto &currentNode = stack.back();
222 
223     // Check to see if we need to process this node.
224     if (!currentNode->processed) {
225       currentNode->processed = true;
226       simplifyBlock(knownValues, domInfo, currentNode->node->getBlock());
227     }
228 
229     // Otherwise, check to see if we need to process a child node.
230     if (currentNode->childIterator != currentNode->node->end()) {
231       auto *childNode = *(currentNode->childIterator++);
232       stack.emplace_back(
233           std::make_unique<CFGStackNode>(knownValues, childNode));
234     } else {
235       // Finally, if the node and all of its children have been processed
236       // then we delete the node.
237       stack.pop_back();
238     }
239   }
240 }
241 
242 void CSE::runOnOperation() {
243   /// A scoped hash table of defining operations within a region.
244   ScopedMapTy knownValues;
245 
246   DominanceInfo &domInfo = getAnalysis<DominanceInfo>();
247   for (Region &region : getOperation()->getRegions())
248     simplifyRegion(knownValues, domInfo, region);
249 
250   // If no operations were erased, then we mark all analyses as preserved.
251   if (opsToErase.empty())
252     return markAllAnalysesPreserved();
253 
254   /// Erase any operations that were marked as dead during simplification.
255   for (auto *op : opsToErase)
256     op->erase();
257   opsToErase.clear();
258 
259   // We currently don't remove region operations, so mark dominance as
260   // preserved.
261   markAnalysesPreserved<DominanceInfo, PostDominanceInfo>();
262 }
263 
264 std::unique_ptr<Pass> mlir::createCSEPass() { return std::make_unique<CSE>(); }
265 
266 static PassRegistration<CSE> pass("cse", "Eliminate common sub-expressions");
267