MLIR 24.0.0git
FoldTensorSubsetOps.cpp
Go to the documentation of this file.
1//===- FoldTensorSubsetOps.cpp - Fold tensor subset ops -------------------===//
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// Fold tensor subset ops with producer / consumers.
10//
11//===----------------------------------------------------------------------===//
12
21#include "mlir/IR/AffineMap.h"
24#include <type_traits>
26namespace mlir {
27namespace tensor {
28#define GEN_PASS_DEF_FOLDTENSORSUBSETOPSPASS
29#include "mlir/Dialect/Tensor/Transforms/Passes.h.inc"
30} // namespace tensor
31} // namespace mlir
32
33using namespace mlir;
34
35static Value getTensorOperand(vector::TransferReadOp op) {
36 return op.getBase();
39static Value getTensorOperand(tensor::InsertSliceOp op) {
40 return op.getSource();
41}
42
43//===----------------------------------------------------------------------===//
44// Patterns
45//===----------------------------------------------------------------------===//
47namespace {
48/// Merge extract_slice operation with load/transferRead operation.
49class TransferReadOfExtractSliceOpFolder final
50 : public vector::MaskableOpRewritePattern<vector::TransferReadOp> {
51public:
52 using MaskableOpRewritePattern::MaskableOpRewritePattern;
53
54 FailureOr<mlir::Value>
55 matchAndRewriteMaskableOp(vector::TransferReadOp readOp,
56 vector::MaskingOpInterface maskOp,
57 PatternRewriter &rewriter) const override;
58};
59
60/// Merge insert_slice operation with store/transferWriteOp operation.
61class InsertSliceOfTransferWriteOpFolder final
62 : public OpRewritePattern<tensor::InsertSliceOp> {
63public:
64 using OpRewritePattern<tensor::InsertSliceOp>::OpRewritePattern;
65
66 LogicalResult matchAndRewrite(tensor::InsertSliceOp insertSliceOp,
67 PatternRewriter &rewriter) const override;
68
69private:
70 static bool
71 doesTransferWriteCoverInsertSlice(vector::TransferWriteOp writeOp);
72};
73} // namespace
74
75template <typename XferOp, typename ExtractOrInsertOp>
77 RewriterBase &rewriter, XferOp xferOp,
78 ExtractOrInsertOp extractOrInsertSliceOp) {
79 if (xferOp.hasOutOfBoundsDim())
80 return rewriter.notifyMatchFailure(xferOp, "out of bounds transfer dim");
81 if (xferOp.getMask())
82 return rewriter.notifyMatchFailure(xferOp, "masked transfer");
83 if (!extractOrInsertSliceOp.hasUnitStride()) {
84 return rewriter.notifyMatchFailure(
85 xferOp, "non-1 stride insert/extract, requires keeping track of "
86 "strides, this may result in needing to insert "
87 "vector.insert_strided_slice/extract_strided_slice ops");
88 }
89 return success();
90}
91
92FailureOr<mlir::Value>
93TransferReadOfExtractSliceOpFolder::matchAndRewriteMaskableOp(
94 vector::TransferReadOp readOp, vector::MaskingOpInterface maskOp,
95 PatternRewriter &rewriter) const {
96 auto extractSliceOp =
97 getTensorOperand(readOp).getDefiningOp<tensor::ExtractSliceOp>();
98 if (!extractSliceOp)
99 return rewriter.notifyMatchFailure(readOp, "not an extract_slice");
100
101 LogicalResult preconditionResult =
103 extractSliceOp);
104 if (failed(preconditionResult))
105 return rewriter.notifyMatchFailure(readOp, "Failed preconditions");
106
107 SmallVector<Value> indices(readOp.getIndices().begin(),
108 readOp.getIndices().end());
109 SmallVector<Value> sourceIndices;
111 rewriter, readOp.getLoc(), extractSliceOp.getMixedOffsets(),
112 extractSliceOp.getMixedStrides(), extractSliceOp.getDroppedDims(),
113 indices, sourceIndices);
114
115 Operation *newOp = vector::TransferReadOp::create(
116 rewriter, readOp.getLoc(), readOp.getVectorType(),
117 extractSliceOp.getSource(), sourceIndices,
118 AffineMapAttr::get(expandDimsToRank(
119 readOp.getPermutationMap(), extractSliceOp.getSourceType().getRank(),
120 extractSliceOp.getDroppedDims())),
121 readOp.getPadding(),
122 /*mask=*/Value(), readOp.getInBoundsAttr());
123 if (maskOp)
124 newOp = mlir::vector::maskOperation(rewriter, newOp, maskOp.getMask(),
125 maskOp.getPassthru());
126 return newOp->getResults()[0];
127}
128
129LogicalResult InsertSliceOfTransferWriteOpFolder::matchAndRewrite(
130 tensor::InsertSliceOp insertSliceOp, PatternRewriter &rewriter) const {
131 auto writeOp = getTensorOperand(insertSliceOp)
132 .template getDefiningOp<vector::TransferWriteOp>();
133 if (!writeOp)
134 return rewriter.notifyMatchFailure(insertSliceOp, "not a transfer_write");
135
136 LogicalResult preconditionResult =
138 insertSliceOp);
139 if (failed(preconditionResult))
140 return preconditionResult;
141
142 if (!doesTransferWriteCoverInsertSlice(writeOp))
143 return rewriter.notifyMatchFailure(
144 insertSliceOp, "transfer_write does not cover insert_slice");
145
146 SmallVector<Value> indices(writeOp.getIndices().begin(),
147 writeOp.getIndices().end());
148 SmallVector<Value> sourceIndices;
150 rewriter, writeOp.getLoc(), insertSliceOp.getMixedOffsets(),
151 insertSliceOp.getMixedStrides(), insertSliceOp.getDroppedDims(), indices,
152 sourceIndices);
153
154 rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
155 insertSliceOp, writeOp.getValue(), insertSliceOp.getDest(), sourceIndices,
156 AffineMapAttr::get(expandDimsToRank(writeOp.getPermutationMap(),
157 insertSliceOp.getDestType().getRank(),
158 insertSliceOp.getDroppedDims())),
159 writeOp.getInBoundsAttr());
160
161 return success();
162}
163
164bool InsertSliceOfTransferWriteOpFolder::doesTransferWriteCoverInsertSlice(
165 vector::TransferWriteOp writeOp) {
166 if (writeOp.getShapedType().hasStaticShape())
167 return llvm::equal(writeOp.getVectorType().getShape(),
168 writeOp.getShapedType().getShape());
169
170 // TODO: Use ValueBoundsConstraintSet for dynamic shapes.
171
172 return false;
173}
174
175template <typename OpTy>
178
179 LogicalResult matchAndRewrite(OpTy insertSliceOp,
180 PatternRewriter &rewriter) const override {
181 auto sourceInsertSliceOp =
182 insertSliceOp.getSource()
183 .template getDefiningOp<tensor::InsertSliceOp>();
184 if (!sourceInsertSliceOp)
185 return failure();
186
187 int64_t srcDim = 0;
188 llvm::SmallBitVector droppedDims = insertSliceOp.getDroppedDims();
189 for (int64_t d = 0, e = insertSliceOp.getDestType().getRank(); d < e; ++d) {
190 if (droppedDims[d])
191 continue;
192 if (insertSliceOp.getMixedSizes()[d] !=
193 sourceInsertSliceOp.getMixedSizes()[srcDim++]) {
194 return rewriter.notifyMatchFailure(
195 sourceInsertSliceOp,
196 "requires matching sizes to fold, otherwise a copy is needed");
197 }
198 }
199
200 // If we are inside a ParallelCombining region, temporarily set the
201 // insertion point outside: only ops of ParallelCombiningOpInterface are
202 // allowed in there.
203 if (isa<mlir::ParallelCombiningOpInterface>(insertSliceOp.getOperation())) {
204 rewriter.setInsertionPoint(insertSliceOp->getParentOp());
205 }
206
207 SmallVector<OpFoldResult> newOffsets, newSizes, newStrides;
209 rewriter, insertSliceOp.getLoc(), insertSliceOp,
210 sourceInsertSliceOp, droppedDims, newOffsets, newSizes,
211 newStrides)))
212 return failure();
213
214 // Reset the insertion point.
215 rewriter.setInsertionPoint(insertSliceOp);
216 // Replace original op.
217 rewriter.replaceOpWithNewOp<OpTy>(
218 insertSliceOp, sourceInsertSliceOp.getSource(), insertSliceOp.getDest(),
219 newOffsets, newSizes, newStrides);
220 return success();
221 }
222};
223
225 : public OpRewritePattern<tensor::ExtractSliceOp> {
226 using Base::Base;
227
228 LogicalResult matchAndRewrite(tensor::ExtractSliceOp nextOp,
229 PatternRewriter &rewriter) const override {
230 auto prevOp = nextOp.getSource().getDefiningOp<tensor::ExtractSliceOp>();
231 if (!prevOp)
232 return failure();
233
234 SmallVector<OpFoldResult> newOffsets, newSizes, newStrides;
236 rewriter, nextOp.getLoc(), prevOp, nextOp, prevOp.getDroppedDims(),
237 newOffsets, newSizes, newStrides)))
238 return failure();
239
240 rewriter.replaceOpWithNewOp<tensor::ExtractSliceOp>(
241 nextOp, nextOp.getType(), prevOp.getSource(), newOffsets, newSizes,
242 newStrides);
243 return success();
244 }
245};
246
248 RewritePatternSet &patterns) {
249 patterns.add<TransferReadOfExtractSliceOpFolder,
250 InsertSliceOfTransferWriteOpFolder>(patterns.getContext());
251}
252
260
265
266//===----------------------------------------------------------------------===//
267// Pass registration
268//===----------------------------------------------------------------------===//
269
270namespace {
271
272struct FoldTensorSubsetOpsPass final
274 FoldTensorSubsetOpsPass> {
275 void runOnOperation() override;
276};
277
278} // namespace
279
280void FoldTensorSubsetOpsPass::runOnOperation() {
281 RewritePatternSet patterns(&getContext());
283 (void)applyPatternsGreedily(getOperation(), std::move(patterns));
284}
return success()
static Value getTensorOperand(vector::TransferReadOp op)
static LogicalResult preconditionsFoldExtractOrInsertWithTransferOp(RewriterBase &rewriter, XferOp xferOp, ExtractOrInsertOp extractOrInsertSliceOp)
b getContext())
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
result_range getResults()
Definition Operation.h:442
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
void resolveIndicesIntoOpWithOffsetsAndStrides(RewriterBase &rewriter, Location loc, ArrayRef< OpFoldResult > mixedSourceOffsets, ArrayRef< OpFoldResult > mixedSourceStrides, const llvm::SmallBitVector &rankReducedDims, ArrayRef< OpFoldResult > consumerIndices, SmallVectorImpl< Value > &resolvedIndices)
Given the 'consumerIndices' of a load/store operation operating on an op with offsets and strides,...
LogicalResult mergeOffsetsSizesAndStrides(OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > producerOffsets, ArrayRef< OpFoldResult > producerSizes, ArrayRef< OpFoldResult > producerStrides, const llvm::SmallBitVector &droppedProducerDims, ArrayRef< OpFoldResult > consumerOffsets, ArrayRef< OpFoldResult > consumerSizes, ArrayRef< OpFoldResult > consumerStrides, SmallVector< OpFoldResult > &combinedOffsets, SmallVector< OpFoldResult > &combinedSizes, SmallVector< OpFoldResult > &combinedStrides)
Fills the combinedOffsets, combinedSizes and combinedStrides to use when combining a producer slice i...
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
void populateMergeConsecutiveInsertExtractSlicePatterns(RewritePatternSet &patterns)
Collects patterns to merge consecutive tensor.insert_slice/extract_slice into one.
void populateFoldTensorSubsetOpPatterns(RewritePatternSet &patterns)
Appends patterns for folding tensor subset ops into consumer load/store ops into patterns.
void populateFoldTensorSubsetIntoVectorTransferPatterns(RewritePatternSet &patterns)
Appends patterns for folding tensor subset ops into vector transfer ops.
Operation * maskOperation(OpBuilder &builder, Operation *maskableOp, Value mask, Value passthru=Value())
Creates a vector.mask operation around a maskable operation.
Include the generated interface declarations.
AffineMap expandDimsToRank(AffineMap map, int64_t rank, const llvm::SmallBitVector &projectedDimensions)
Expand map to operate on rank dims while projecting out the dims in projectedDimensions.
LogicalResult applyPatternsGreedily(Region &region, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
LogicalResult matchAndRewrite(OpTy insertSliceOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tensor::ExtractSliceOp nextOp, PatternRewriter &rewriter) const override
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
OpRewritePattern Base
Type alias to allow derived classes to inherit constructors with using Base::Base;.
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
A pattern for ops that implement MaskableOpInterface and that might be masked (i.e.