Skip to content

Commit 1c69f42

Browse files
[mlir][Transforms][NFC] Turn in-place op modifications into RewriteActions
This commit simplifies the internal state of the dialect conversion. A separate field for the previous state of in-place op modifications is no longer needed. BEGIN_PUBLIC No public commit message needed for presubmit. END_PUBLIC
1 parent d228191 commit 1c69f42

File tree

2 files changed

+70
-75
lines changed

2 files changed

+70
-75
lines changed

mlir/include/mlir/Transforms/DialectConversion.h

+2-2
Original file line numberDiff line numberDiff line change
@@ -744,8 +744,8 @@ class ConversionPatternRewriter final : public PatternRewriter {
744744

745745
/// PatternRewriter hook for updating the given operation in-place.
746746
/// Note: These methods only track updates to the given operation itself,
747-
/// and not nested regions. Updates to regions will still require
748-
/// notification through other more specific hooks above.
747+
/// and not nested regions. Updates to regions will still require notification
748+
/// through other more specific hooks above.
749749
void startOpModification(Operation *op) override;
750750

751751
/// PatternRewriter hook for updating the given operation in-place.

mlir/lib/Transforms/Utils/DialectConversion.cpp

+68-73
Original file line numberDiff line numberDiff line change
@@ -154,14 +154,12 @@ namespace {
154154
struct RewriterState {
155155
RewriterState(unsigned numCreatedOps, unsigned numUnresolvedMaterializations,
156156
unsigned numReplacements, unsigned numArgReplacements,
157-
unsigned numRewrites, unsigned numIgnoredOperations,
158-
unsigned numRootUpdates)
157+
unsigned numRewrites, unsigned numIgnoredOperations)
159158
: numCreatedOps(numCreatedOps),
160159
numUnresolvedMaterializations(numUnresolvedMaterializations),
161160
numReplacements(numReplacements),
162161
numArgReplacements(numArgReplacements), numRewrites(numRewrites),
163-
numIgnoredOperations(numIgnoredOperations),
164-
numRootUpdates(numRootUpdates) {}
162+
numIgnoredOperations(numIgnoredOperations) {}
165163

166164
/// The current number of created operations.
167165
unsigned numCreatedOps;
@@ -180,44 +178,6 @@ struct RewriterState {
180178

181179
/// The current number of ignored operations.
182180
unsigned numIgnoredOperations;
183-
184-
/// The current number of operations that were updated in place.
185-
unsigned numRootUpdates;
186-
};
187-
188-
//===----------------------------------------------------------------------===//
189-
// OperationTransactionState
190-
191-
/// The state of an operation that was updated by a pattern in-place. This
192-
/// contains all of the necessary information to reconstruct an operation that
193-
/// was updated in place.
194-
class OperationTransactionState {
195-
public:
196-
OperationTransactionState() = default;
197-
OperationTransactionState(Operation *op)
198-
: op(op), loc(op->getLoc()), attrs(op->getAttrDictionary()),
199-
operands(op->operand_begin(), op->operand_end()),
200-
successors(op->successor_begin(), op->successor_end()) {}
201-
202-
/// Discard the transaction state and reset the state of the original
203-
/// operation.
204-
void resetOperation() const {
205-
op->setLoc(loc);
206-
op->setAttrs(attrs);
207-
op->setOperands(operands);
208-
for (const auto &it : llvm::enumerate(successors))
209-
op->setSuccessor(it.value(), it.index());
210-
}
211-
212-
/// Return the original operation of this state.
213-
Operation *getOperation() const { return op; }
214-
215-
private:
216-
Operation *op;
217-
LocationAttr loc;
218-
DictionaryAttr attrs;
219-
SmallVector<Value, 8> operands;
220-
SmallVector<Block *, 2> successors;
221181
};
222182

223183
//===----------------------------------------------------------------------===//
@@ -761,7 +721,8 @@ class IRRewrite {
761721
MoveBlock,
762722
SplitBlock,
763723
BlockTypeConversion,
764-
MoveOperation
724+
MoveOperation,
725+
ModifyOperation
765726
};
766727

767728
virtual ~IRRewrite() = default;
@@ -992,7 +953,7 @@ class OperationRewrite : public IRRewrite {
992953

993954
static bool classof(const IRRewrite *rewrite) {
994955
return rewrite->getKind() >= Kind::MoveOperation &&
995-
rewrite->getKind() <= Kind::MoveOperation;
956+
rewrite->getKind() <= Kind::ModifyOperation;
996957
}
997958

998959
protected:
@@ -1031,8 +992,50 @@ class MoveOperationRewrite : public OperationRewrite {
1031992
// this operation was the only operation in the region.
1032993
Operation *insertBeforeOp;
1033994
};
995+
996+
/// In-place modification of an op. This rewrite is immediately reflected in
997+
/// the IR. The previous state of the operation is stored in this object.
998+
class ModifyOperationRewrite : public OperationRewrite {
999+
public:
1000+
ModifyOperationRewrite(ConversionPatternRewriterImpl &rewriterImpl,
1001+
Operation *op)
1002+
: OperationRewrite(Kind::ModifyOperation, rewriterImpl, op),
1003+
loc(op->getLoc()), attrs(op->getAttrDictionary()),
1004+
operands(op->operand_begin(), op->operand_end()),
1005+
successors(op->successor_begin(), op->successor_end()) {}
1006+
1007+
static bool classof(const IRRewrite *rewrite) {
1008+
return rewrite->getKind() == Kind::ModifyOperation;
1009+
}
1010+
1011+
/// Discard the transaction state and reset the state of the original
1012+
/// operation.
1013+
void rollback() override {
1014+
op->setLoc(loc);
1015+
op->setAttrs(attrs);
1016+
op->setOperands(operands);
1017+
for (const auto &it : llvm::enumerate(successors))
1018+
op->setSuccessor(it.value(), it.index());
1019+
}
1020+
1021+
private:
1022+
LocationAttr loc;
1023+
DictionaryAttr attrs;
1024+
SmallVector<Value, 8> operands;
1025+
SmallVector<Block *, 2> successors;
1026+
};
10341027
} // namespace
10351028

1029+
/// Return "true" if there is an operation rewrite that matches the specified
1030+
/// rewrite type and operation among the given rewrites.
1031+
template <typename RewriteTy, typename R>
1032+
static bool hasRewrite(R &&rewrites, Operation *op) {
1033+
return any_of(std::move(rewrites), [&](auto &rewrite) {
1034+
auto *rewriteTy = dyn_cast<RewriteTy>(rewrite.get());
1035+
return rewriteTy && rewriteTy->getOperation() == op;
1036+
});
1037+
}
1038+
10361039
//===----------------------------------------------------------------------===//
10371040
// ConversionPatternRewriterImpl
10381041
//===----------------------------------------------------------------------===//
@@ -1184,9 +1187,6 @@ struct ConversionPatternRewriterImpl : public RewriterBase::Listener {
11841187
/// operation was ignored.
11851188
SetVector<Operation *> ignoredOps;
11861189

1187-
/// A transaction state for each of operations that were updated in-place.
1188-
SmallVector<OperationTransactionState, 4> rootUpdates;
1189-
11901190
/// A vector of indices into `replacements` of operations that were replaced
11911191
/// with values with different result types than the original operation, e.g.
11921192
/// 1->N conversion of some kind.
@@ -1238,10 +1238,6 @@ static void detachNestedAndErase(Operation *op) {
12381238
}
12391239

12401240
void ConversionPatternRewriterImpl::discardRewrites() {
1241-
// Reset any operations that were updated in place.
1242-
for (auto &state : rootUpdates)
1243-
state.resetOperation();
1244-
12451241
undoRewrites();
12461242

12471243
// Remove any newly created ops.
@@ -1316,15 +1312,10 @@ void ConversionPatternRewriterImpl::applyRewrites() {
13161312
RewriterState ConversionPatternRewriterImpl::getCurrentState() {
13171313
return RewriterState(createdOps.size(), unresolvedMaterializations.size(),
13181314
replacements.size(), argReplacements.size(),
1319-
rewrites.size(), ignoredOps.size(), rootUpdates.size());
1315+
rewrites.size(), ignoredOps.size());
13201316
}
13211317

13221318
void ConversionPatternRewriterImpl::resetState(RewriterState state) {
1323-
// Reset any operations that were updated in place.
1324-
for (unsigned i = state.numRootUpdates, e = rootUpdates.size(); i != e; ++i)
1325-
rootUpdates[i].resetOperation();
1326-
rootUpdates.resize(state.numRootUpdates);
1327-
13281319
// Reset any replaced arguments.
13291320
for (BlockArgument replacedArg :
13301321
llvm::drop_begin(argReplacements, state.numArgReplacements))
@@ -1750,7 +1741,7 @@ void ConversionPatternRewriter::startOpModification(Operation *op) {
17501741
#ifndef NDEBUG
17511742
impl->pendingRootUpdates.insert(op);
17521743
#endif
1753-
impl->rootUpdates.emplace_back(op);
1744+
impl->appendRewrite<ModifyOperationRewrite>(op);
17541745
}
17551746

17561747
void ConversionPatternRewriter::finalizeOpModification(Operation *op) {
@@ -1769,13 +1760,15 @@ void ConversionPatternRewriter::cancelOpModification(Operation *op) {
17691760
"operation did not have a pending in-place update");
17701761
#endif
17711762
// Erase the last update for this operation.
1772-
auto stateHasOp = [op](const auto &it) { return it.getOperation() == op; };
1773-
auto &rootUpdates = impl->rootUpdates;
1774-
auto it = llvm::find_if(llvm::reverse(rootUpdates), stateHasOp);
1775-
assert(it != rootUpdates.rend() && "no root update started on op");
1776-
(*it).resetOperation();
1777-
int updateIdx = std::prev(rootUpdates.rend()) - it;
1778-
rootUpdates.erase(rootUpdates.begin() + updateIdx);
1763+
auto it = llvm::find_if(
1764+
llvm::reverse(impl->rewrites), [&](std::unique_ptr<IRRewrite> &rewrite) {
1765+
auto *modifyRewrite = dyn_cast<ModifyOperationRewrite>(rewrite.get());
1766+
return modifyRewrite && modifyRewrite->getOperation() == op;
1767+
});
1768+
assert(it != impl->rewrites.rend() && "no root update started on op");
1769+
(*it)->rollback();
1770+
int updateIdx = std::prev(impl->rewrites.rend()) - it;
1771+
impl->rewrites.erase(impl->rewrites.begin() + updateIdx);
17791772
}
17801773

17811774
detail::ConversionPatternRewriterImpl &ConversionPatternRewriter::getImpl() {
@@ -2059,6 +2052,7 @@ OperationLegalizer::legalizeWithPattern(Operation *op,
20592052
// Functor that cleans up the rewriter state after a pattern failed to match.
20602053
RewriterState curState = rewriterImpl.getCurrentState();
20612054
auto onFailure = [&](const Pattern &pattern) {
2055+
assert(rewriterImpl.pendingRootUpdates.empty() && "dangling root updates");
20622056
LLVM_DEBUG({
20632057
logFailure(rewriterImpl.logger, "pattern failed to match");
20642058
if (rewriterImpl.notifyCallback) {
@@ -2076,6 +2070,7 @@ OperationLegalizer::legalizeWithPattern(Operation *op,
20762070
// Functor that performs additional legalization when a pattern is
20772071
// successfully applied.
20782072
auto onSuccess = [&](const Pattern &pattern) {
2073+
assert(rewriterImpl.pendingRootUpdates.empty() && "dangling root updates");
20792074
auto result = legalizePatternResult(op, pattern, rewriter, curState);
20802075
appliedPatterns.erase(&pattern);
20812076
if (failed(result))
@@ -2118,7 +2113,6 @@ OperationLegalizer::legalizePatternResult(Operation *op, const Pattern &pattern,
21182113

21192114
#ifndef NDEBUG
21202115
assert(impl.pendingRootUpdates.empty() && "dangling root updates");
2121-
#endif
21222116

21232117
// Check that the root was either replaced or updated in place.
21242118
auto replacedRoot = [&] {
@@ -2127,14 +2121,12 @@ OperationLegalizer::legalizePatternResult(Operation *op, const Pattern &pattern,
21272121
[op](auto &it) { return it.first == op; });
21282122
};
21292123
auto updatedRootInPlace = [&] {
2130-
return llvm::any_of(
2131-
llvm::drop_begin(impl.rootUpdates, curState.numRootUpdates),
2132-
[op](auto &state) { return state.getOperation() == op; });
2124+
return hasRewrite<ModifyOperationRewrite>(
2125+
llvm::drop_begin(impl.rewrites, curState.numRewrites), op);
21332126
};
2134-
(void)replacedRoot;
2135-
(void)updatedRootInPlace;
21362127
assert((replacedRoot() || updatedRootInPlace()) &&
21372128
"expected pattern to replace the root operation");
2129+
#endif // NDEBUG
21382130

21392131
// Legalize each of the actions registered during application.
21402132
RewriterState newState = impl.getCurrentState();
@@ -2221,8 +2213,11 @@ LogicalResult OperationLegalizer::legalizePatternCreatedOperations(
22212213
LogicalResult OperationLegalizer::legalizePatternRootUpdates(
22222214
ConversionPatternRewriter &rewriter, ConversionPatternRewriterImpl &impl,
22232215
RewriterState &state, RewriterState &newState) {
2224-
for (int i = state.numRootUpdates, e = newState.numRootUpdates; i != e; ++i) {
2225-
Operation *op = impl.rootUpdates[i].getOperation();
2216+
for (int i = state.numRewrites, e = newState.numRewrites; i != e; ++i) {
2217+
auto *rewrite = dyn_cast<ModifyOperationRewrite>(impl.rewrites[i].get());
2218+
if (!rewrite)
2219+
continue;
2220+
Operation *op = rewrite->getOperation();
22262221
if (failed(legalize(op, rewriter))) {
22272222
LLVM_DEBUG(logFailure(
22282223
impl.logger, "failed to legalize operation updated in-place '{0}'",

0 commit comments

Comments
 (0)