1 //===- CSE.cpp - Common Sub-expression Elimination ------------------------===//
2 //
3 // Copyright 2019 The MLIR Authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //   http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 // =============================================================================
17 //
18 // This transformation pass performs a simple common sub-expression elimination
19 // algorithm on operations within a function.
20 //
21 //===----------------------------------------------------------------------===//
22 
23 #include "mlir/Analysis/Dominance.h"
24 #include "mlir/IR/Attributes.h"
25 #include "mlir/IR/Builders.h"
26 #include "mlir/IR/Function.h"
27 #include "mlir/Pass/Pass.h"
28 #include "mlir/Support/Functional.h"
29 #include "mlir/Transforms/Passes.h"
30 #include "mlir/Transforms/Utils.h"
31 #include "llvm/ADT/DenseMapInfo.h"
32 #include "llvm/ADT/Hashing.h"
33 #include "llvm/ADT/ScopedHashTable.h"
34 #include "llvm/Support/Allocator.h"
35 #include "llvm/Support/RecyclingAllocator.h"
36 #include <deque>
37 using namespace mlir;
38 
39 namespace {
40 // TODO(riverriddle) Handle commutative operations.
41 struct SimpleOperationInfo : public llvm::DenseMapInfo<Operation *> {
42   static unsigned getHashValue(const Operation *opC) {
43     auto *op = const_cast<Operation *>(opC);
44     // Hash the operations based upon their:
45     //   - Operation Name
46     //   - Attributes
47     //   - Result Types
48     //   - Operands
49     return hash_combine(
50         op->getName(), op->getAttrList().getDictionary(),
51         hash_combine_range(op->result_type_begin(), op->result_type_end()),
52         hash_combine_range(op->operand_begin(), op->operand_end()));
53   }
54   static bool isEqual(const Operation *lhsC, const Operation *rhsC) {
55     auto *lhs = const_cast<Operation *>(lhsC);
56     auto *rhs = const_cast<Operation *>(rhsC);
57     if (lhs == rhs)
58       return true;
59     if (lhs == getTombstoneKey() || lhs == getEmptyKey() ||
60         rhs == getTombstoneKey() || rhs == getEmptyKey())
61       return false;
62 
63     // Compare the operation name.
64     if (lhs->getName() != rhs->getName())
65       return false;
66     // Check operand and result type counts.
67     if (lhs->getNumOperands() != rhs->getNumOperands() ||
68         lhs->getNumResults() != rhs->getNumResults())
69       return false;
70     // Compare attributes.
71     if (lhs->getAttrList() != rhs->getAttrList())
72       return false;
73     // Compare operands.
74     if (!std::equal(lhs->operand_begin(), lhs->operand_end(),
75                     rhs->operand_begin()))
76       return false;
77     // Compare result types.
78     return std::equal(lhs->result_type_begin(), lhs->result_type_end(),
79                       rhs->result_type_begin());
80   }
81 };
82 } // end anonymous namespace
83 
84 namespace {
85 /// Simple common sub-expression elimination.
86 struct CSE : public OperationPass<CSE> {
87   CSE() = default;
88   CSE(const CSE &) {}
89 
90   /// Shared implementation of operation elimination and scoped map definitions.
91   using AllocatorTy = llvm::RecyclingAllocator<
92       llvm::BumpPtrAllocator,
93       llvm::ScopedHashTableVal<Operation *, Operation *>>;
94   using ScopedMapTy = llvm::ScopedHashTable<Operation *, Operation *,
95                                             SimpleOperationInfo, AllocatorTy>;
96 
97   /// Represents a single entry in the depth first traversal of a CFG.
98   struct CFGStackNode {
99     CFGStackNode(ScopedMapTy &knownValues, DominanceInfoNode *node)
100         : scope(knownValues), node(node), childIterator(node->begin()),
101           processed(false) {}
102 
103     /// Scope for the known values.
104     ScopedMapTy::ScopeTy scope;
105 
106     DominanceInfoNode *node;
107     DominanceInfoNode::iterator childIterator;
108 
109     /// If this node has been fully processed yet or not.
110     bool processed;
111   };
112 
113   /// Attempt to eliminate a redundant operation. Returns success if the
114   /// operation was marked for removal, failure otherwise.
115   LogicalResult simplifyOperation(ScopedMapTy &knownValues, Operation *op);
116 
117   void simplifyBlock(ScopedMapTy &knownValues, DominanceInfo &domInfo,
118                      Block *bb);
119   void simplifyRegion(ScopedMapTy &knownValues, DominanceInfo &domInfo,
120                       Region &region);
121 
122   void runOnOperation() override;
123 
124 private:
125   /// Operations marked as dead and to be erased.
126   std::vector<Operation *> opsToErase;
127 
128   /// Statistics for CSE.
129   Statistic numCSE{this, "num-cse'd", "Number of operations CSE'd"};
130   Statistic numDCE{this, "num-dce'd", "Number of operations trivially DCE'd"};
131 };
132 } // end anonymous namespace
133 
134 /// Attempt to eliminate a redundant operation.
135 LogicalResult CSE::simplifyOperation(ScopedMapTy &knownValues, Operation *op) {
136   // Don't simplify operations with nested blocks. We don't currently model
137   // equality comparisons correctly among other things. It is also unclear
138   // whether we would want to CSE such operations.
139   if (op->getNumRegions() != 0)
140     return failure();
141 
142   // TODO(riverriddle) We currently only eliminate non side-effecting
143   // operations.
144   if (!op->hasNoSideEffect())
145     return failure();
146 
147   // If the operation is already trivially dead just add it to the erase list.
148   if (op->use_empty()) {
149     opsToErase.push_back(op);
150     ++numDCE;
151     return success();
152   }
153 
154   // Look for an existing definition for the operation.
155   if (auto *existing = knownValues.lookup(op)) {
156     // If we find one then replace all uses of the current operation with the
157     // existing one and mark it for deletion.
158     op->replaceAllUsesWith(existing);
159     opsToErase.push_back(op);
160 
161     // If the existing operation has an unknown location and the current
162     // operation doesn't, then set the existing op's location to that of the
163     // current op.
164     if (existing->getLoc().isa<UnknownLoc>() &&
165         !op->getLoc().isa<UnknownLoc>()) {
166       existing->setLoc(op->getLoc());
167     }
168 
169     ++numCSE;
170     return success();
171   }
172 
173   // Otherwise, we add this operation to the known values map.
174   knownValues.insert(op, op);
175   return failure();
176 }
177 
178 void CSE::simplifyBlock(ScopedMapTy &knownValues, DominanceInfo &domInfo,
179                         Block *bb) {
180   for (auto &inst : *bb) {
181     // If the operation is simplified, we don't process any held regions.
182     if (succeeded(simplifyOperation(knownValues, &inst)))
183       continue;
184 
185     // If this operation is isolated above, we can't process nested regions with
186     // the given 'knownValues' map. This would cause the insertion of implicit
187     // captures in explicit capture only regions.
188     if (!inst.isRegistered() || inst.isKnownIsolatedFromAbove()) {
189       ScopedMapTy nestedKnownValues;
190       for (auto &region : inst.getRegions())
191         simplifyRegion(nestedKnownValues, domInfo, region);
192       continue;
193     }
194 
195     // Otherwise, process nested regions normally.
196     for (auto &region : inst.getRegions())
197       simplifyRegion(knownValues, domInfo, region);
198   }
199 }
200 
201 void CSE::simplifyRegion(ScopedMapTy &knownValues, DominanceInfo &domInfo,
202                          Region &region) {
203   // If the region is empty there is nothing to do.
204   if (region.empty())
205     return;
206 
207   // If the region only contains one block, then simplify it directly.
208   if (std::next(region.begin()) == region.end()) {
209     ScopedMapTy::ScopeTy scope(knownValues);
210     simplifyBlock(knownValues, domInfo, &region.front());
211     return;
212   }
213 
214   // Note, deque is being used here because there was significant performance
215   // gains over vector when the container becomes very large due to the
216   // specific access patterns. If/when these performance issues are no
217   // longer a problem we can change this to vector. For more information see
218   // the llvm mailing list discussion on this:
219   // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
220   std::deque<std::unique_ptr<CFGStackNode>> stack;
221 
222   // Process the nodes of the dom tree for this region.
223   stack.emplace_back(std::make_unique<CFGStackNode>(
224       knownValues, domInfo.getRootNode(&region)));
225 
226   while (!stack.empty()) {
227     auto &currentNode = stack.back();
228 
229     // Check to see if we need to process this node.
230     if (!currentNode->processed) {
231       currentNode->processed = true;
232       simplifyBlock(knownValues, domInfo, currentNode->node->getBlock());
233     }
234 
235     // Otherwise, check to see if we need to process a child node.
236     if (currentNode->childIterator != currentNode->node->end()) {
237       auto *childNode = *(currentNode->childIterator++);
238       stack.emplace_back(
239           std::make_unique<CFGStackNode>(knownValues, childNode));
240     } else {
241       // Finally, if the node and all of its children have been processed
242       // then we delete the node.
243       stack.pop_back();
244     }
245   }
246 }
247 
248 void CSE::runOnOperation() {
249   /// A scoped hash table of defining operations within a region.
250   ScopedMapTy knownValues;
251 
252   DominanceInfo &domInfo = getAnalysis<DominanceInfo>();
253   for (Region &region : getOperation()->getRegions())
254     simplifyRegion(knownValues, domInfo, region);
255 
256   // If no operations were erased, then we mark all analyses as preserved.
257   if (opsToErase.empty())
258     return markAllAnalysesPreserved();
259 
260   /// Erase any operations that were marked as dead during simplification.
261   for (auto *op : opsToErase)
262     op->erase();
263   opsToErase.clear();
264 
265   // We currently don't remove region operations, so mark dominance as
266   // preserved.
267   markAnalysesPreserved<DominanceInfo, PostDominanceInfo>();
268 }
269 
270 std::unique_ptr<Pass> mlir::createCSEPass() { return std::make_unique<CSE>(); }
271 
272 static PassRegistration<CSE> pass("cse", "Eliminate common sub-expressions");
273