MLIR 23.0.0git
CSE.cpp
Go to the documentation of this file.
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 file implements common sub-expression elimination as a library utility.
10// The matching CSE pass is a thin wrapper over the APIs declared here.
11//
12//===----------------------------------------------------------------------===//
13
14#include "mlir/Transforms/CSE.h"
15
16#include "mlir/IR/Dominance.h"
19#include "llvm/ADT/DenseMapInfo.h"
20#include "llvm/ADT/ScopedHashTable.h"
21#include "llvm/Support/Allocator.h"
22#include "llvm/Support/RecyclingAllocator.h"
23#include <deque>
24
25using namespace mlir;
26
27namespace {
28struct SimpleOperationInfo : public llvm::DenseMapInfo<Operation *> {
29 static unsigned getHashValue(const Operation *opC) {
31 const_cast<Operation *>(opC),
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 == getEmptyKey() || rhs == getEmptyKey())
42 return false;
44 const_cast<Operation *>(lhsC), const_cast<Operation *>(rhsC),
46 }
47};
48} // namespace
49
50namespace {
51/// Simple common sub-expression elimination.
52class CSEDriver {
53public:
54 CSEDriver(RewriterBase &rewriter, DominanceInfo *domInfo)
55 : rewriter(rewriter), domInfo(domInfo) {}
56
57 /// Simplify all operations within the given op.
58 void simplify(Operation *op, bool *changed = nullptr);
59
60 /// Simplify operations within the given region.
61 void simplify(Region &region, bool *changed = nullptr);
62
63 int64_t getNumCSE() const { return numCSE; }
64 int64_t getNumDCE() const { return numDCE; }
65
66private:
67 /// Shared implementation of operation elimination and scoped map definitions.
68 using AllocatorTy = llvm::RecyclingAllocator<
69 llvm::BumpPtrAllocator,
70 llvm::ScopedHashTableVal<Operation *, Operation *>>;
71 using ScopedMapTy = llvm::ScopedHashTable<Operation *, Operation *,
72 SimpleOperationInfo, AllocatorTy>;
73
74 /// Cache holding MemoryEffects information between two operations. The first
75 /// operation is stored has the key. The second operation is stored inside a
76 /// pair in the value. The pair also hold the MemoryEffects between those
77 /// two operations. If the MemoryEffects is nullptr then we assume there is
78 /// no operation with MemoryEffects::Write between the two operations.
79 using MemEffectsCache =
81
82 /// Represents a single entry in the depth first traversal of a CFG.
83 struct CFGStackNode {
84 CFGStackNode(ScopedMapTy &knownValues, DominanceInfoNode *node)
85 : scope(knownValues), node(node), childIterator(node->begin()) {}
86
87 /// Scope for the known values.
88 ScopedMapTy::ScopeTy scope;
89
91 DominanceInfoNode::const_iterator childIterator;
92
93 /// If this node has been fully processed yet or not.
94 bool processed = false;
95 };
96
97 /// Attempt to eliminate a redundant operation. Returns success if the
98 /// operation was marked for removal, failure otherwise.
99 LogicalResult simplifyOperation(ScopedMapTy &knownValues, Operation *op,
100 bool hasSSADominance);
101 void simplifyBlock(ScopedMapTy &knownValues, Block *bb, bool hasSSADominance);
102 void simplifyRegion(ScopedMapTy &knownValues, Region &region);
103
104 /// Erase all operations queued for deletion by the simplification routines.
105 void eraseDeadOps(bool *changed);
106
107 void replaceUsesAndDelete(ScopedMapTy &knownValues, Operation *op,
108 Operation *existing, bool hasSSADominance);
109
110 /// Check if there is side-effecting operations other than the given effect
111 /// between the two operations.
112 bool hasOtherSideEffectingOpInBetween(Operation *fromOp, Operation *toOp);
113
114 /// A rewriter for modifying the IR.
115 RewriterBase &rewriter;
116
117 /// Operations marked as dead and to be erased.
118 std::vector<Operation *> opsToErase;
119 DominanceInfo *domInfo = nullptr;
120 MemEffectsCache memEffectsCache;
121
122 // Various statistics.
123 int64_t numCSE = 0;
124 int64_t numDCE = 0;
125};
126} // namespace
127
128void CSEDriver::replaceUsesAndDelete(ScopedMapTy &knownValues, Operation *op,
129 Operation *existing,
130 bool hasSSADominance) {
131 // If we find one then replace all uses of the current operation with the
132 // existing one and mark it for deletion. We can only replace an operand in
133 // an operation if it has not been visited yet.
134 if (hasSSADominance) {
135 // If the region has SSA dominance, then we are guaranteed to have not
136 // visited any use of the current operation.
137 // Replace all uses, but do not remove the operation yet.
138 rewriter.replaceAllOpUsesWith(op, existing->getResults());
139 opsToErase.push_back(op);
140 } else {
141 // When the region does not have SSA dominance, we need to check if we
142 // have visited a use before replacing any use.
143 auto wasVisited = [&](OpOperand &operand) {
144 return !knownValues.count(operand.getOwner());
145 };
146 if (auto *rewriteListener =
147 dyn_cast_if_present<RewriterBase::Listener>(rewriter.getListener()))
148 for (Value v : op->getResults())
149 if (all_of(v.getUses(), wasVisited))
150 rewriteListener->notifyOperationReplaced(op, existing);
151
152 // Replace all uses, but do not remove the operation yet. This does not
153 // notify the listener because the original op is not erased.
154 rewriter.replaceUsesWithIf(op->getResults(), existing->getResults(),
155 wasVisited);
156
157 // There may be some remaining uses of the operation.
158 if (op->use_empty())
159 opsToErase.push_back(op);
160 }
161
162 // If the existing operation has an unknown location and the current
163 // operation doesn't, then set the existing op's location to that of the
164 // current op.
165 if (isa<UnknownLoc>(existing->getLoc()) && !isa<UnknownLoc>(op->getLoc()))
166 existing->setLoc(op->getLoc());
167
168 ++numCSE;
169}
170
171bool CSEDriver::hasOtherSideEffectingOpInBetween(Operation *fromOp,
172 Operation *toOp) {
173 assert(fromOp->getBlock() == toOp->getBlock());
174 assert(hasEffect<MemoryEffects::Read>(fromOp) &&
175 "expected read effect on fromOp");
176 assert(hasEffect<MemoryEffects::Read>(toOp) &&
177 "expected read effect on toOp");
178
179 // Collect the read effects of fromOp. A write can only block CSE if it
180 // can conflict with one of these reads.
181 SmallVector<MemoryEffects::EffectInstance> readEffects;
182 if (auto memOp = dyn_cast<MemoryEffectOpInterface>(fromOp)) {
183 SmallVector<MemoryEffects::EffectInstance> fromEffects;
184 memOp.getEffects(fromEffects);
185 for (MemoryEffects::EffectInstance &e : fromEffects)
186 if (isa<MemoryEffects::Read>(e.getEffect()))
187 readEffects.push_back(e);
188 }
189
190 Operation *nextOp = fromOp->getNextNode();
191 auto result =
192 memEffectsCache.try_emplace(fromOp, std::make_pair(fromOp, nullptr));
193 if (!result.second) {
194 auto memEffectsCachePair = result.first->second;
195 if (memEffectsCachePair.second == nullptr) {
196 // No MemoryEffects::Write has been detected until the cached operation.
197 // Continue looking from the cached operation to toOp.
198 nextOp = memEffectsCachePair.first;
199 } else {
200 // MemoryEffects::Write has been detected before so there is no need to
201 // check further.
202 return true;
203 }
204 }
205 while (nextOp && nextOp != toOp) {
206 std::optional<SmallVector<MemoryEffects::EffectInstance>> effects =
207 getEffectsRecursively(nextOp);
208 if (!effects) {
209 // TODO: Do we need to handle other effects generically?
210 // If the operation does not implement the MemoryEffectOpInterface we
211 // conservatively assume it writes.
212 result.first->second =
213 std::make_pair(nextOp, MemoryEffects::Write::get());
214 return true;
215 }
216
217 for (const MemoryEffects::EffectInstance &effect : *effects) {
218 if (isa<MemoryEffects::Write>(effect.getEffect())) {
219 // A write on a resource disjoint from all read resources cannot
220 // conflict with the reads being CSE'd.
221 SideEffects::Resource *writeResource = effect.getResource();
222 bool canConflict =
223 llvm::any_of(readEffects, [&](const auto &readEffect) {
224 SideEffects::Resource *readResource = readEffect.getResource();
225 if (writeResource->isDisjointFrom(readResource))
226 return false;
227 // A pointer-based access to an addressable resource cannot
228 // conflict with a non-addressable resource.
229 if (readEffect.getValue() && !writeResource->isAddressable())
230 return false;
231 if (effect.getValue() && !readResource->isAddressable())
232 return false;
233 return true;
234 });
235 if (canConflict) {
236 result.first->second = {nextOp, MemoryEffects::Write::get()};
237 return true;
238 }
239 }
240 }
241 nextOp = nextOp->getNextNode();
242 }
243 result.first->second = std::make_pair(toOp, nullptr);
244 return false;
245}
246
247/// Attempt to eliminate a redundant operation.
248LogicalResult CSEDriver::simplifyOperation(ScopedMapTy &knownValues,
249 Operation *op,
250 bool hasSSADominance) {
251 // Don't simplify terminator operations.
252 if (op->hasTrait<OpTrait::IsTerminator>())
253 return failure();
254
255 // Don't simplify operations with regions that have multiple blocks.
256 // TODO: We need additional tests to verify that we handle such IR correctly.
257 if (!llvm::all_of(op->getRegions(),
258 [](Region &r) { return r.empty() || r.hasOneBlock(); }))
259 return failure();
260
261 // Some simple use case of operation with memory side-effect are dealt with
262 // here. Operations with no side-effect are done after.
263 if (!isMemoryEffectFree(op)) {
264 // TODO: Only basic use case for operations with MemoryEffects::Read can be
265 // eleminated now. More work needs to be done for more complicated patterns
266 // and other side-effects.
268 return failure();
269
270 // Look for an existing definition for the operation.
271 if (auto *existing = knownValues.lookup(op)) {
272 if (existing->getBlock() == op->getBlock() &&
273 !hasOtherSideEffectingOpInBetween(existing, op)) {
274 // The operation that can be deleted has been reach with no
275 // side-effecting operations in between the existing operation and
276 // this one so we can remove the duplicate.
277 replaceUsesAndDelete(knownValues, op, existing, hasSSADominance);
278 return success();
279 }
280 }
281 knownValues.insert(op, op);
282 return failure();
283 }
284
285 // Look for an existing definition for the operation.
286 if (auto *existing = knownValues.lookup(op)) {
287 replaceUsesAndDelete(knownValues, op, existing, hasSSADominance);
288 return success();
289 }
290
291 // Otherwise, we add this operation to the known values map.
292 knownValues.insert(op, op);
293 return failure();
294}
295
296void CSEDriver::simplifyBlock(ScopedMapTy &knownValues, Block *bb,
297 bool hasSSADominance) {
298 for (auto &op : llvm::make_early_inc_range(*bb)) {
299 // If the operation is already trivially dead just add it to the erase list.
300 // This also avoids calling `simplifyRegion` on dead region ops
301 // unnecessarily.
302 if (isOpTriviallyDead(&op)) {
303 opsToErase.push_back(&op);
304 ++numDCE;
305 continue;
306 }
307
308 // Most operations don't have regions, so fast path that case.
309 if (op.getNumRegions() != 0) {
310 // If this operation is isolated above, we can't process nested regions
311 // with the given 'knownValues' map. This would cause the insertion of
312 // implicit captures in explicit capture only regions.
313 if (op.mightHaveTrait<OpTrait::IsIsolatedFromAbove>()) {
314 ScopedMapTy nestedKnownValues;
315 for (auto &region : op.getRegions())
316 simplifyRegion(nestedKnownValues, region);
317 } else {
318 // Otherwise, process nested regions normally.
319 for (auto &region : op.getRegions())
320 simplifyRegion(knownValues, region);
321 }
322 }
323
324 // If the operation is simplified, we don't process any held regions.
325 if (succeeded(simplifyOperation(knownValues, &op, hasSSADominance)))
326 continue;
327 }
328 // Clear the MemoryEffects cache since its usage is by block only.
329 memEffectsCache.clear();
330}
331
332void CSEDriver::simplifyRegion(ScopedMapTy &knownValues, Region &region) {
333 // If the region is empty there is nothing to do.
334 if (region.empty())
335 return;
336
337 bool hasSSADominance = domInfo->hasSSADominance(&region);
338
339 // If the region only contains one block, then simplify it directly.
340 if (region.hasOneBlock()) {
341 ScopedMapTy::ScopeTy scope(knownValues);
342 simplifyBlock(knownValues, &region.front(), hasSSADominance);
343 return;
344 }
345
346 // If the region does not have dominanceInfo, then skip it.
347 // TODO: Regions without SSA dominance should define a different
348 // traversal order which is appropriate and can be used here.
349 if (!hasSSADominance)
350 return;
351
352 // Note, deque is being used here because there was significant performance
353 // gains over vector when the container becomes very large due to the
354 // specific access patterns. If/when these performance issues are no
355 // longer a problem we can change this to vector. For more information see
356 // the llvm mailing list discussion on this:
357 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
358 std::deque<std::unique_ptr<CFGStackNode>> stack;
359
360 // Process the nodes of the dom tree for this region.
361 stack.emplace_back(std::make_unique<CFGStackNode>(
362 knownValues, domInfo->getRootNode(&region)));
363
364 while (!stack.empty()) {
365 auto &currentNode = stack.back();
366
367 // Check to see if we need to process this node.
368 if (!currentNode->processed) {
369 currentNode->processed = true;
370 simplifyBlock(knownValues, currentNode->node->getBlock(),
371 hasSSADominance);
372 }
373
374 // Otherwise, check to see if we need to process a child node.
375 if (currentNode->childIterator != currentNode->node->end()) {
376 auto *childNode = *(currentNode->childIterator++);
377 stack.emplace_back(
378 std::make_unique<CFGStackNode>(knownValues, childNode));
379 } else {
380 // Finally, if the node and all of its children have been processed
381 // then we delete the node.
382 stack.pop_back();
383 }
384 }
385}
386
387void CSEDriver::eraseDeadOps(bool *changed) {
388 // Erase any operations that were marked as dead during simplification, and
389 // remove their associated dominator trees.
390 for (auto *op : opsToErase) {
391 for (Region &region : op->getRegions())
392 domInfo->invalidate(&region);
393 rewriter.eraseOp(op);
394 }
395 if (changed)
396 *changed = !opsToErase.empty();
397 opsToErase.clear();
398
399 // Note: CSE does currently not remove ops with regions, so DominanceInfo
400 // does not have to be invalidated.
401}
402
403void CSEDriver::simplify(Operation *op, bool *changed) {
404 // Simplify all regions.
405 ScopedMapTy knownValues;
406 for (auto &region : op->getRegions())
407 simplifyRegion(knownValues, region);
408 eraseDeadOps(changed);
409}
410
411void CSEDriver::simplify(Region &region, bool *changed) {
412 ScopedMapTy knownValues;
413 simplifyRegion(knownValues, region);
414 eraseDeadOps(changed);
415}
416
418 DominanceInfo &domInfo, Operation *op,
419 bool *changed, int64_t *numCSE,
420 int64_t *numDCE) {
421 CSEDriver driver(rewriter, &domInfo);
422 driver.simplify(op, changed);
423 if (numCSE)
424 *numCSE = driver.getNumCSE();
425 if (numDCE)
426 *numDCE = driver.getNumDCE();
427}
428
430 DominanceInfo &domInfo, Region &region,
431 bool *changed) {
432 CSEDriver driver(rewriter, &domInfo);
433 driver.simplify(region, changed);
434}
return success()
lhs
template bool mlir::hasEffect< MemoryEffects::Read >(Operation *)
template bool mlir::hasSingleEffect< MemoryEffects::Read >(Operation *)
A class for computing basic dominance information.
Definition Dominance.h:143
Listener * getListener() const
Returns the current listener of this builder, or nullptr if this builder doesn't have a listener.
Definition Builders.h:322
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
void setLoc(Location loc)
Set the source location the operation was defined or derived from.
Definition Operation.h:243
bool use_empty()
Returns true if this operation has no uses.
Definition Operation.h:877
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:774
bool mightHaveTrait()
Returns true if the operation might have the provided trait.
Definition Operation.h:782
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
unsigned getNumRegions()
Returns the number of regions held by this operation.
Definition Operation.h:699
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition Operation.h:702
result_range getResults()
Definition Operation.h:440
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & front()
Definition Region.h:65
bool empty()
Definition Region.h:60
bool hasOneBlock()
Return true if this region has exactly one block.
Definition Region.h:68
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
virtual void replaceUsesWithIf(Value from, Value to, function_ref< bool(OpOperand &)> functor, bool *allUsesReplaced=nullptr)
Find uses of from and replace them with to if the functor returns true.
void replaceAllOpUsesWith(Operation *from, ValueRange to)
Find uses of from and replace them with to.
virtual bool isAddressable() const
Returns true if this resource is addressable (effects on it can alias pointer-based memory).
bool isDisjointFrom(const Resource *other) const
Returns true if this resource is disjoint from another.
DominanceInfoNode * getRootNode(Region *region)
Get the root dominance node of the given region.
Definition Dominance.h:77
bool hasSSADominance(Block *block) const
Return true if operations in the specified block are known to obey SSA dominance requirements.
Definition Dominance.h:95
void invalidate()
Invalidate dominance info.
Definition Dominance.cpp:37
SideEffects::EffectInstance< Effect > EffectInstance
Include the generated interface declarations.
void eliminateCommonSubExpressions(RewriterBase &rewriter, DominanceInfo &domInfo, Operation *op, bool *changed=nullptr, int64_t *numCSE=nullptr, int64_t *numDCE=nullptr)
Eliminate common subexpressions within the given operation.
Definition CSE.cpp:417
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
llvm::DomTreeNodeBase< Block > DominanceInfoNode
Definition Dominance.h:30
bool isOpTriviallyDead(Operation *op)
Return true if the given operation is unused, and has no side effects on memory that prevent erasing.
std::optional< llvm::SmallVector< MemoryEffects::EffectInstance > > getEffectsRecursively(Operation *rootOp)
Returns the side effects of an operation.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:120
static llvm::hash_code ignoreHashValue(Value)
Helper that can be used with computeHash above to ignore operation operands/result mapping.
static bool isEquivalentTo(Operation *lhs, Operation *rhs, function_ref< LogicalResult(Value, Value)> checkEquivalent, function_ref< void(Value, Value)> markEquivalent=nullptr, Flags flags=Flags::None, function_ref< LogicalResult(ValueRange, ValueRange)> checkCommutativeEquivalent=nullptr)
Compare two operations (including their regions) and return if they are equivalent.
static llvm::hash_code directHashValue(Value v)
Helper that can be used with computeHash to compute the hash value of operands/results directly.
static llvm::hash_code computeHash(Operation *op, function_ref< llvm::hash_code(Value)> hashOperands=[](Value v) { return hash_value(v);}, function_ref< llvm::hash_code(Value)> hashResults=[](Value v) { return hash_value(v);}, Flags flags=Flags::None)
Compute a hash for the given operation.