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 "llvm/ADT/DenseMapInfo.h"
19 #include "llvm/ADT/Hashing.h"
20 #include "llvm/ADT/ScopedHashTable.h"
21 #include "llvm/Support/Allocator.h"
22 #include "llvm/Support/RecyclingAllocator.h"
23 #include <deque>
24 
25 using namespace mlir;
26 
27 namespace {
28 struct SimpleOperationInfo : public llvm::DenseMapInfo<Operation *> {
29   static unsigned getHashValue(const Operation *opC) {
30     return OperationEquivalence::computeHash(
31         const_cast<Operation *>(opC),
32         /*hashOperands=*/OperationEquivalence::directHashValue,
33         /*hashResults=*/OperationEquivalence::ignoreHashValue,
34         OperationEquivalence::IgnoreLocations);
35   }
36   static bool isEqual(const Operation *lhsC, const Operation *rhsC) {
37     auto *lhs = const_cast<Operation *>(lhsC);
38     auto *rhs = const_cast<Operation *>(rhsC);
39     if (lhs == rhs)
40       return true;
41     if (lhs == getTombstoneKey() || lhs == getEmptyKey() ||
42         rhs == getTombstoneKey() || rhs == getEmptyKey())
43       return false;
44     return OperationEquivalence::isEquivalentTo(
45         const_cast<Operation *>(lhsC), const_cast<Operation *>(rhsC),
46         /*mapOperands=*/OperationEquivalence::exactValueMatch,
47         /*mapResults=*/OperationEquivalence::ignoreValueEquivalence,
48         OperationEquivalence::IgnoreLocations);
49   }
50 };
51 } // namespace
52 
53 namespace {
54 /// Simple common sub-expression elimination.
55 struct CSE : public CSEBase<CSE> {
56   /// Shared implementation of operation elimination and scoped map definitions.
57   using AllocatorTy = llvm::RecyclingAllocator<
58       llvm::BumpPtrAllocator,
59       llvm::ScopedHashTableVal<Operation *, Operation *>>;
60   using ScopedMapTy = llvm::ScopedHashTable<Operation *, Operation *,
61                                             SimpleOperationInfo, AllocatorTy>;
62 
63   /// Cache holding MemoryEffects information between two operations. The first
64   /// operation is stored has the key. The second operation is stored inside a
65   /// pair in the value. The pair also hold the MemoryEffects between those
66   /// two operations. If the MemoryEffects is nullptr then we assume there is
67   /// no operation with MemoryEffects::Write between the two operations.
68   using MemEffectsCache =
69       DenseMap<Operation *, std::pair<Operation *, MemoryEffects::Effect *>>;
70 
71   /// Represents a single entry in the depth first traversal of a CFG.
72   struct CFGStackNode {
73     CFGStackNode(ScopedMapTy &knownValues, DominanceInfoNode *node)
74         : scope(knownValues), node(node), childIterator(node->begin()) {}
75 
76     /// Scope for the known values.
77     ScopedMapTy::ScopeTy scope;
78 
79     DominanceInfoNode *node;
80     DominanceInfoNode::const_iterator childIterator;
81 
82     /// If this node has been fully processed yet or not.
83     bool processed = false;
84   };
85 
86   /// Attempt to eliminate a redundant operation. Returns success if the
87   /// operation was marked for removal, failure otherwise.
88   LogicalResult simplifyOperation(ScopedMapTy &knownValues, Operation *op,
89                                   bool hasSSADominance);
90   void simplifyBlock(ScopedMapTy &knownValues, Block *bb, bool hasSSADominance);
91   void simplifyRegion(ScopedMapTy &knownValues, Region &region);
92 
93   void runOnOperation() override;
94 
95 private:
96   void replaceUsesAndDelete(ScopedMapTy &knownValues, Operation *op,
97                             Operation *existing, bool hasSSADominance);
98 
99   /// Check if there is side-effecting operations other than the given effect
100   /// between the two operations.
101   bool hasOtherSideEffectingOpInBetween(Operation *fromOp, Operation *toOp);
102 
103   /// Operations marked as dead and to be erased.
104   std::vector<Operation *> opsToErase;
105   DominanceInfo *domInfo = nullptr;
106   MemEffectsCache memEffectsCache;
107 };
108 } // namespace
109 
110 void CSE::replaceUsesAndDelete(ScopedMapTy &knownValues, Operation *op,
111                                Operation *existing, bool hasSSADominance) {
112   // If we find one then replace all uses of the current operation with the
113   // existing one and mark it for deletion. We can only replace an operand in
114   // an operation if it has not been visited yet.
115   if (hasSSADominance) {
116     // If the region has SSA dominance, then we are guaranteed to have not
117     // visited any use of the current operation.
118     op->replaceAllUsesWith(existing);
119     opsToErase.push_back(op);
120   } else {
121     // When the region does not have SSA dominance, we need to check if we
122     // have visited a use before replacing any use.
123     for (auto it : llvm::zip(op->getResults(), existing->getResults())) {
124       std::get<0>(it).replaceUsesWithIf(
125           std::get<1>(it), [&](OpOperand &operand) {
126             return !knownValues.count(operand.getOwner());
127           });
128     }
129 
130     // There may be some remaining uses of the operation.
131     if (op->use_empty())
132       opsToErase.push_back(op);
133   }
134 
135   // If the existing operation has an unknown location and the current
136   // operation doesn't, then set the existing op's location to that of the
137   // current op.
138   if (existing->getLoc().isa<UnknownLoc>() && !op->getLoc().isa<UnknownLoc>())
139     existing->setLoc(op->getLoc());
140 
141   ++numCSE;
142 }
143 
144 bool CSE::hasOtherSideEffectingOpInBetween(Operation *fromOp, Operation *toOp) {
145   assert(fromOp->getBlock() == toOp->getBlock());
146   assert(
147       isa<MemoryEffectOpInterface>(fromOp) &&
148       cast<MemoryEffectOpInterface>(fromOp).hasEffect<MemoryEffects::Read>() &&
149       isa<MemoryEffectOpInterface>(toOp) &&
150       cast<MemoryEffectOpInterface>(toOp).hasEffect<MemoryEffects::Read>());
151   Operation *nextOp = fromOp->getNextNode();
152   auto result =
153       memEffectsCache.try_emplace(fromOp, std::make_pair(fromOp, nullptr));
154   if (result.second) {
155     auto memEffectsCachePair = result.first->second;
156     if (memEffectsCachePair.second == nullptr) {
157       // No MemoryEffects::Write has been detected until the cached operation.
158       // Continue looking from the cached operation to toOp.
159       nextOp = memEffectsCachePair.first;
160     } else {
161       // MemoryEffects::Write has been detected before so there is no need to
162       // check further.
163       return true;
164     }
165   }
166   while (nextOp && nextOp != toOp) {
167     auto nextOpMemEffects = dyn_cast<MemoryEffectOpInterface>(nextOp);
168     // TODO: Do we need to handle other effects generically?
169     // If the operation does not implement the MemoryEffectOpInterface we
170     // conservatively assumes it writes.
171     if ((nextOpMemEffects &&
172          nextOpMemEffects.hasEffect<MemoryEffects::Write>()) ||
173         !nextOpMemEffects) {
174       result.first->second =
175           std::make_pair(nextOp, MemoryEffects::Write::get());
176       return true;
177     }
178     nextOp = nextOp->getNextNode();
179   }
180   result.first->second = std::make_pair(toOp, nullptr);
181   return false;
182 }
183 
184 /// Attempt to eliminate a redundant operation.
185 LogicalResult CSE::simplifyOperation(ScopedMapTy &knownValues, Operation *op,
186                                      bool hasSSADominance) {
187   // Don't simplify terminator operations.
188   if (op->hasTrait<OpTrait::IsTerminator>())
189     return failure();
190 
191   // If the operation is already trivially dead just add it to the erase list.
192   if (isOpTriviallyDead(op)) {
193     opsToErase.push_back(op);
194     ++numDCE;
195     return success();
196   }
197 
198   // Don't simplify operations with nested blocks. We don't currently model
199   // equality comparisons correctly among other things. It is also unclear
200   // whether we would want to CSE such operations.
201   if (op->getNumRegions() != 0)
202     return failure();
203 
204   // Some simple use case of operation with memory side-effect are dealt with
205   // here. Operations with no side-effect are done after.
206   if (!MemoryEffectOpInterface::hasNoEffect(op)) {
207     auto memEffects = dyn_cast<MemoryEffectOpInterface>(op);
208     // TODO: Only basic use case for operations with MemoryEffects::Read can be
209     // eleminated now. More work needs to be done for more complicated patterns
210     // and other side-effects.
211     if (!memEffects || !memEffects.onlyHasEffect<MemoryEffects::Read>())
212       return failure();
213 
214     // Look for an existing definition for the operation.
215     if (auto *existing = knownValues.lookup(op)) {
216       if (existing->getBlock() == op->getBlock() &&
217           !hasOtherSideEffectingOpInBetween(existing, op)) {
218         // The operation that can be deleted has been reach with no
219         // side-effecting operations in between the existing operation and
220         // this one so we can remove the duplicate.
221         replaceUsesAndDelete(knownValues, op, existing, hasSSADominance);
222         return success();
223       }
224     }
225     knownValues.insert(op, op);
226     return failure();
227   }
228 
229   // Look for an existing definition for the operation.
230   if (auto *existing = knownValues.lookup(op)) {
231     replaceUsesAndDelete(knownValues, op, existing, hasSSADominance);
232     ++numCSE;
233     return success();
234   }
235 
236   // Otherwise, we add this operation to the known values map.
237   knownValues.insert(op, op);
238   return failure();
239 }
240 
241 void CSE::simplifyBlock(ScopedMapTy &knownValues, Block *bb,
242                         bool hasSSADominance) {
243   for (auto &op : *bb) {
244     // If the operation is simplified, we don't process any held regions.
245     if (succeeded(simplifyOperation(knownValues, &op, hasSSADominance)))
246       continue;
247 
248     // Most operations don't have regions, so fast path that case.
249     if (op.getNumRegions() == 0)
250       continue;
251 
252     // If this operation is isolated above, we can't process nested regions with
253     // the given 'knownValues' map. This would cause the insertion of implicit
254     // captures in explicit capture only regions.
255     if (op.mightHaveTrait<OpTrait::IsIsolatedFromAbove>()) {
256       ScopedMapTy nestedKnownValues;
257       for (auto &region : op.getRegions())
258         simplifyRegion(nestedKnownValues, region);
259       continue;
260     }
261 
262     // Otherwise, process nested regions normally.
263     for (auto &region : op.getRegions())
264       simplifyRegion(knownValues, region);
265   }
266   // Clear the MemoryEffects cache since its usage is by block only.
267   memEffectsCache.clear();
268 }
269 
270 void CSE::simplifyRegion(ScopedMapTy &knownValues, Region &region) {
271   // If the region is empty there is nothing to do.
272   if (region.empty())
273     return;
274 
275   bool hasSSADominance = domInfo->hasSSADominance(&region);
276 
277   // If the region only contains one block, then simplify it directly.
278   if (region.hasOneBlock()) {
279     ScopedMapTy::ScopeTy scope(knownValues);
280     simplifyBlock(knownValues, &region.front(), hasSSADominance);
281     return;
282   }
283 
284   // If the region does not have dominanceInfo, then skip it.
285   // TODO: Regions without SSA dominance should define a different
286   // traversal order which is appropriate and can be used here.
287   if (!hasSSADominance)
288     return;
289 
290   // Note, deque is being used here because there was significant performance
291   // gains over vector when the container becomes very large due to the
292   // specific access patterns. If/when these performance issues are no
293   // longer a problem we can change this to vector. For more information see
294   // the llvm mailing list discussion on this:
295   // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
296   std::deque<std::unique_ptr<CFGStackNode>> stack;
297 
298   // Process the nodes of the dom tree for this region.
299   stack.emplace_back(std::make_unique<CFGStackNode>(
300       knownValues, domInfo->getRootNode(&region)));
301 
302   while (!stack.empty()) {
303     auto &currentNode = stack.back();
304 
305     // Check to see if we need to process this node.
306     if (!currentNode->processed) {
307       currentNode->processed = true;
308       simplifyBlock(knownValues, currentNode->node->getBlock(),
309                     hasSSADominance);
310     }
311 
312     // Otherwise, check to see if we need to process a child node.
313     if (currentNode->childIterator != currentNode->node->end()) {
314       auto *childNode = *(currentNode->childIterator++);
315       stack.emplace_back(
316           std::make_unique<CFGStackNode>(knownValues, childNode));
317     } else {
318       // Finally, if the node and all of its children have been processed
319       // then we delete the node.
320       stack.pop_back();
321     }
322   }
323 }
324 
325 void CSE::runOnOperation() {
326   /// A scoped hash table of defining operations within a region.
327   ScopedMapTy knownValues;
328 
329   domInfo = &getAnalysis<DominanceInfo>();
330   Operation *rootOp = getOperation();
331 
332   for (auto &region : rootOp->getRegions())
333     simplifyRegion(knownValues, region);
334 
335   // If no operations were erased, then we mark all analyses as preserved.
336   if (opsToErase.empty())
337     return markAllAnalysesPreserved();
338 
339   /// Erase any operations that were marked as dead during simplification.
340   for (auto *op : opsToErase)
341     op->erase();
342   opsToErase.clear();
343 
344   // We currently don't remove region operations, so mark dominance as
345   // preserved.
346   markAnalysesPreserved<DominanceInfo, PostDominanceInfo>();
347   domInfo = nullptr;
348 }
349 
350 std::unique_ptr<Pass> mlir::createCSEPass() { return std::make_unique<CSE>(); }
351