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