149e37000SMatthias Springer //===- BufferizableOpInterfaceImpl.cpp - Impl. of BufferizableOpInterface -===//
249e37000SMatthias Springer //
349e37000SMatthias Springer // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
449e37000SMatthias Springer // See https://llvm.org/LICENSE.txt for license information.
549e37000SMatthias Springer // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
649e37000SMatthias Springer //
749e37000SMatthias Springer //===----------------------------------------------------------------------===//
849e37000SMatthias Springer 
949e37000SMatthias Springer #include "mlir/Dialect/Tensor/Transforms/BufferizableOpInterfaceImpl.h"
10eda6f907SRiver Riddle #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
1149e37000SMatthias Springer #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h"
12b3ebe3beSMatthias Springer #include "mlir/Dialect/Bufferization/IR/Bufferization.h"
1349e37000SMatthias Springer #include "mlir/Dialect/MemRef/IR/MemRef.h"
148b68da2cSAlex Zinenko #include "mlir/Dialect/SCF/IR/SCF.h"
1549e37000SMatthias Springer #include "mlir/Dialect/Tensor/IR/Tensor.h"
1649e37000SMatthias Springer #include "mlir/IR/Dialect.h"
1749e37000SMatthias Springer #include "mlir/IR/Operation.h"
1849e37000SMatthias Springer 
1949e37000SMatthias Springer using namespace mlir;
2049e37000SMatthias Springer using namespace mlir::bufferization;
2149e37000SMatthias Springer using namespace mlir::tensor;
2249e37000SMatthias Springer 
2349e37000SMatthias Springer namespace mlir {
2449e37000SMatthias Springer namespace tensor {
2549e37000SMatthias Springer namespace {
2649e37000SMatthias Springer 
2749e37000SMatthias Springer struct CastOpInterface
2849e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<CastOpInterface,
2949e37000SMatthias Springer                                                     tensor::CastOp> {
3049e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
319597b16aSMatthias Springer                               const AnalysisState &state) const {
3249e37000SMatthias Springer     return false;
3349e37000SMatthias Springer   }
3449e37000SMatthias Springer 
3549e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
369597b16aSMatthias Springer                                const AnalysisState &state) const {
3749e37000SMatthias Springer     return false;
3849e37000SMatthias Springer   }
3949e37000SMatthias Springer 
409597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
419597b16aSMatthias Springer                                             const AnalysisState &state) const {
42585a8a32SMatthias Springer     return {op->getResult(0)};
4349e37000SMatthias Springer   }
4449e37000SMatthias Springer 
4549e37000SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
469597b16aSMatthias Springer                                 const AnalysisState &state) const {
4749e37000SMatthias Springer     return BufferRelation::Equivalent;
4849e37000SMatthias Springer   }
4949e37000SMatthias Springer 
5049e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
51b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
5249e37000SMatthias Springer     auto castOp = cast<tensor::CastOp>(op);
5349e37000SMatthias Springer 
5449e37000SMatthias Springer     // The result buffer still has the old (pre-cast) type.
555d50f51cSMatthias Springer     FailureOr<Value> resultBuffer =
565d50f51cSMatthias Springer         getBuffer(rewriter, castOp.getSource(), options);
575d50f51cSMatthias Springer     if (failed(resultBuffer))
585d50f51cSMatthias Springer       return failure();
595d50f51cSMatthias Springer     auto sourceMemRefType = resultBuffer->getType().cast<BaseMemRefType>();
6049e37000SMatthias Springer     TensorType resultTensorType =
6149e37000SMatthias Springer         castOp.getResult().getType().cast<TensorType>();
6249e37000SMatthias Springer     MemRefLayoutAttrInterface layout;
6349e37000SMatthias Springer 
6449e37000SMatthias Springer     if (auto rankedMemRefType = sourceMemRefType.dyn_cast<MemRefType>())
6549e37000SMatthias Springer       if (resultTensorType.isa<RankedTensorType>())
6649e37000SMatthias Springer         layout = rankedMemRefType.getLayout();
6749e37000SMatthias Springer 
6849e37000SMatthias Springer     // Compute the new memref type.
69b55d55ecSMatthias Springer     Type resultMemRefType =
70606f7c8fSMatthias Springer         getMemRefType(castOp.getResult(), options, layout,
71b06614e2SMatthias Springer                       sourceMemRefType.getMemorySpaceAsInt());
7249e37000SMatthias Springer 
7349e37000SMatthias Springer     // Replace the op with a memref.cast.
745d50f51cSMatthias Springer     assert(memref::CastOp::areCastCompatible(resultBuffer->getType(),
7549e37000SMatthias Springer                                              resultMemRefType) &&
7649e37000SMatthias Springer            "CallOp::bufferize: cast incompatible");
7749e37000SMatthias Springer     replaceOpWithNewBufferizedOp<memref::CastOp>(rewriter, op, resultMemRefType,
785d50f51cSMatthias Springer                                                  *resultBuffer);
7949e37000SMatthias Springer 
8049e37000SMatthias Springer     return success();
8149e37000SMatthias Springer   }
8249e37000SMatthias Springer };
8349e37000SMatthias Springer 
84e6f69161SMatthias Springer /// Bufferization of tensor.collapse_shape. Replace with memref.collapse_shape.
85e6f69161SMatthias Springer struct CollapseShapeOpInterface
86e6f69161SMatthias Springer     : public BufferizableOpInterface::ExternalModel<CollapseShapeOpInterface,
87e6f69161SMatthias Springer                                                     tensor::CollapseShapeOp> {
88e6f69161SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
899597b16aSMatthias Springer                               const AnalysisState &state) const {
90e6f69161SMatthias Springer     return false;
91e6f69161SMatthias Springer   }
92e6f69161SMatthias Springer 
93e6f69161SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
949597b16aSMatthias Springer                                const AnalysisState &state) const {
95e6f69161SMatthias Springer     return false;
96e6f69161SMatthias Springer   }
97e6f69161SMatthias Springer 
989597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
999597b16aSMatthias Springer                                             const AnalysisState &state) const {
100e6f69161SMatthias Springer     if (&opOperand == &op->getOpOperand(0) /*src*/)
101e6f69161SMatthias Springer       return {op->getOpResult(0)};
102e6f69161SMatthias Springer     return {};
103e6f69161SMatthias Springer   }
104e6f69161SMatthias Springer 
105e6f69161SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
1069597b16aSMatthias Springer                                 const AnalysisState &state) const {
107e6f69161SMatthias Springer     return BufferRelation::Equivalent;
108e6f69161SMatthias Springer   }
109e6f69161SMatthias Springer 
110e6f69161SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
111b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
112e6f69161SMatthias Springer     auto collapseShapeOp = cast<tensor::CollapseShapeOp>(op);
11351df6238SMatthias Springer     RankedTensorType tensorResultType = collapseShapeOp.getResultType();
1145d50f51cSMatthias Springer     FailureOr<Value> maybeBuffer =
1155d50f51cSMatthias Springer         getBuffer(rewriter, collapseShapeOp.getSrc(), options);
1165d50f51cSMatthias Springer     if (failed(maybeBuffer))
1175d50f51cSMatthias Springer       return failure();
1185d50f51cSMatthias Springer     Value buffer = *maybeBuffer;
119b3ebe3beSMatthias Springer     auto bufferType = buffer.getType().cast<MemRefType>();
12051df6238SMatthias Springer 
12151df6238SMatthias Springer     if (tensorResultType.getRank() == 0) {
12251df6238SMatthias Springer       // 0-d collapses must go through a different op builder.
12373c0333dSMatthias Springer       MemRefType resultType;
12473c0333dSMatthias Springer 
12573c0333dSMatthias Springer       if (bufferType.getLayout().isIdentity()) {
12673c0333dSMatthias Springer         // Standard layout: result type has no offset.
12751df6238SMatthias Springer         MemRefLayoutAttrInterface layout;
12873c0333dSMatthias Springer         resultType = MemRefType::get({}, tensorResultType.getElementType(),
12951df6238SMatthias Springer                                      layout, bufferType.getMemorySpace());
13073c0333dSMatthias Springer       } else {
13173c0333dSMatthias Springer         // Source memref has a layout map: result type has the same offset as
13273c0333dSMatthias Springer         // the source type.
13373c0333dSMatthias Springer         SmallVector<int64_t> strides;
13473c0333dSMatthias Springer         int64_t offset;
13573c0333dSMatthias Springer         if (failed(getStridesAndOffset(bufferType, strides, offset)))
13673c0333dSMatthias Springer           return failure();
13773c0333dSMatthias Springer         AffineMap resultLayout =
13873c0333dSMatthias Springer             makeStridedLinearLayoutMap({}, offset, op->getContext());
13973c0333dSMatthias Springer         resultType =
14073c0333dSMatthias Springer             MemRefType::get({}, tensorResultType.getElementType(), resultLayout,
14173c0333dSMatthias Springer                             bufferType.getMemorySpaceAsInt());
14273c0333dSMatthias Springer       }
14373c0333dSMatthias Springer 
144e6f69161SMatthias Springer       replaceOpWithNewBufferizedOp<memref::CollapseShapeOp>(
1458df54a6aSJacques Pienaar           rewriter, op, resultType, buffer, collapseShapeOp.getReassociation());
146e6f69161SMatthias Springer       return success();
147e6f69161SMatthias Springer     }
14851df6238SMatthias Springer 
149d7a9bf91SMatthias Springer     // If the dims are not collapsible (due to an incompatible source layout
150d7a9bf91SMatthias Springer     // map), force an out-of-place bufferization, i.e., a buffer copy. This
151d7a9bf91SMatthias Springer     // newly allocated buffer will have no layout map and thus be collapsible.
152a74e5a89SAdrian Kuegel     bool canBeCollapsed = memref::CollapseShapeOp::isGuaranteedCollapsible(
153d7a9bf91SMatthias Springer         bufferType, collapseShapeOp.getReassociationIndices());
154b3ebe3beSMatthias Springer     if (!canBeCollapsed) {
155b3ebe3beSMatthias Springer       // TODO: Create alloc_tensor ops during TensorCopyInsertion.
156b55d55ecSMatthias Springer       AnalysisState analysisState(options);
15745b995cdSMatthias Springer       FailureOr<Value> tensorAlloc = allocateTensorForShapedValue(
1588df54a6aSJacques Pienaar           rewriter, op->getLoc(), collapseShapeOp.getSrc(),
15945b995cdSMatthias Springer           analysisState.isTensorYielded(collapseShapeOp.getResult()), options);
16045b995cdSMatthias Springer       if (failed(tensorAlloc))
16145b995cdSMatthias Springer         return failure();
162b3ebe3beSMatthias Springer       auto memrefType =
163b3ebe3beSMatthias Springer           MemRefType::get(collapseShapeOp.getSrcType().getShape(),
164b3ebe3beSMatthias Springer                           collapseShapeOp.getSrcType().getElementType(),
165b3ebe3beSMatthias Springer                           AffineMap(), bufferType.getMemorySpaceAsInt());
166b3ebe3beSMatthias Springer       buffer = rewriter.create<bufferization::ToMemrefOp>(
16745b995cdSMatthias Springer           op->getLoc(), memrefType, *tensorAlloc);
168b3ebe3beSMatthias Springer     }
169d7a9bf91SMatthias Springer 
17051df6238SMatthias Springer     // Result type is inferred by the builder.
17151df6238SMatthias Springer     replaceOpWithNewBufferizedOp<memref::CollapseShapeOp>(
172b3ebe3beSMatthias Springer         rewriter, op, buffer, collapseShapeOp.getReassociationIndices());
17351df6238SMatthias Springer     return success();
17451df6238SMatthias Springer   }
175e6f69161SMatthias Springer };
176e6f69161SMatthias Springer 
17749e37000SMatthias Springer /// Bufferization of tensor.dim. Replace with memref.dim.
17849e37000SMatthias Springer struct DimOpInterface
17949e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<DimOpInterface,
18049e37000SMatthias Springer                                                     tensor::DimOp> {
18149e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
1829597b16aSMatthias Springer                               const AnalysisState &state) const {
18349e37000SMatthias Springer     return true;
18449e37000SMatthias Springer   }
18549e37000SMatthias Springer 
18649e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
1879597b16aSMatthias Springer                                const AnalysisState &state) const {
18849e37000SMatthias Springer     return false;
18949e37000SMatthias Springer   }
19049e37000SMatthias Springer 
1919597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
1929597b16aSMatthias Springer                                             const AnalysisState &state) const {
193585a8a32SMatthias Springer     return {};
19449e37000SMatthias Springer   }
19549e37000SMatthias Springer 
19649e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
197b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
19849e37000SMatthias Springer     auto dimOp = cast<tensor::DimOp>(op);
1995d50f51cSMatthias Springer     FailureOr<Value> v = getBuffer(rewriter, dimOp.getSource(), options);
2005d50f51cSMatthias Springer     if (failed(v))
2015d50f51cSMatthias Springer       return failure();
2025d50f51cSMatthias Springer     replaceOpWithNewBufferizedOp<memref::DimOp>(rewriter, op, *v,
203136d746eSJacques Pienaar                                                 dimOp.getIndex());
20449e37000SMatthias Springer     return success();
20549e37000SMatthias Springer   }
20649e37000SMatthias Springer };
20749e37000SMatthias Springer 
208e6f69161SMatthias Springer /// Bufferization of tensor.expand_shape. Replace with memref.expand_shape.
209e6f69161SMatthias Springer struct ExpandShapeOpInterface
210e6f69161SMatthias Springer     : public BufferizableOpInterface::ExternalModel<ExpandShapeOpInterface,
211e6f69161SMatthias Springer                                                     tensor::ExpandShapeOp> {
212e6f69161SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
2139597b16aSMatthias Springer                               const AnalysisState &state) const {
214e6f69161SMatthias Springer     return false;
215e6f69161SMatthias Springer   }
216e6f69161SMatthias Springer 
217e6f69161SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
2189597b16aSMatthias Springer                                const AnalysisState &state) const {
219e6f69161SMatthias Springer     return false;
220e6f69161SMatthias Springer   }
221e6f69161SMatthias Springer 
2229597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
2239597b16aSMatthias Springer                                             const AnalysisState &state) const {
224e6f69161SMatthias Springer     if (&opOperand == &op->getOpOperand(0) /*src*/)
225e6f69161SMatthias Springer       return {op->getOpResult(0)};
226e6f69161SMatthias Springer     return {};
227e6f69161SMatthias Springer   }
228e6f69161SMatthias Springer 
229e6f69161SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
2309597b16aSMatthias Springer                                 const AnalysisState &state) const {
231e6f69161SMatthias Springer     return BufferRelation::Equivalent;
232e6f69161SMatthias Springer   }
233e6f69161SMatthias Springer 
234e6f69161SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
235b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
236e6f69161SMatthias Springer     auto expandShapeOp = cast<tensor::ExpandShapeOp>(op);
23751df6238SMatthias Springer     auto tensorResultType = expandShapeOp.getResultType();
2385d50f51cSMatthias Springer     FailureOr<Value> buffer =
2395d50f51cSMatthias Springer         getBuffer(rewriter, expandShapeOp.getSrc(), options);
2405d50f51cSMatthias Springer     if (failed(buffer))
2415d50f51cSMatthias Springer       return failure();
24251df6238SMatthias Springer 
24351df6238SMatthias Springer     // Memref result type is inferred by the builder based on reassociation
24451df6238SMatthias Springer     // indices and result shape.
245e6f69161SMatthias Springer     replaceOpWithNewBufferizedOp<memref::ExpandShapeOp>(
2465d50f51cSMatthias Springer         rewriter, op, tensorResultType.getShape(), *buffer,
24751df6238SMatthias Springer         expandShapeOp.getReassociationIndices());
248e6f69161SMatthias Springer     return success();
249e6f69161SMatthias Springer   }
250e6f69161SMatthias Springer };
251e6f69161SMatthias Springer 
25249e37000SMatthias Springer /// Bufferization of tensor.extract_slice. Replace with memref.subview.
25349e37000SMatthias Springer struct ExtractSliceOpInterface
25449e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<ExtractSliceOpInterface,
25549e37000SMatthias Springer                                                     tensor::ExtractSliceOp> {
25649e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
2579597b16aSMatthias Springer                               const AnalysisState &state) const {
25849e37000SMatthias Springer     return false;
25949e37000SMatthias Springer   }
26049e37000SMatthias Springer 
26149e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
2629597b16aSMatthias Springer                                const AnalysisState &state) const {
26349e37000SMatthias Springer     return false;
26449e37000SMatthias Springer   }
26549e37000SMatthias Springer 
2669597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
2679597b16aSMatthias Springer                                             const AnalysisState &state) const {
268585a8a32SMatthias Springer     if (&opOperand == &op->getOpOperand(0) /*source*/)
269585a8a32SMatthias Springer       return {op->getOpResult(0)};
270585a8a32SMatthias Springer     return {};
27149e37000SMatthias Springer   }
27249e37000SMatthias Springer 
27349e37000SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
2749597b16aSMatthias Springer                                 const AnalysisState &state) const {
27549e37000SMatthias Springer     return BufferRelation::None;
27649e37000SMatthias Springer   }
27749e37000SMatthias Springer 
27849e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
279b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
28049e37000SMatthias Springer     auto extractSliceOp = cast<tensor::ExtractSliceOp>(op);
2816c3c5f80SMatthias Springer     SmallVector<OpFoldResult> mixedOffsets = extractSliceOp.getMixedOffsets();
2826c3c5f80SMatthias Springer     SmallVector<OpFoldResult> mixedSizes = extractSliceOp.getMixedSizes();
2836c3c5f80SMatthias Springer     SmallVector<OpFoldResult> mixedStrides = extractSliceOp.getMixedStrides();
28449e37000SMatthias Springer     Location loc = extractSliceOp.getLoc();
285d7a9bf91SMatthias Springer 
2866c3c5f80SMatthias Springer     // Get source buffer.
2875d50f51cSMatthias Springer     FailureOr<Value> srcMemref =
2885d50f51cSMatthias Springer         getBuffer(rewriter, extractSliceOp.getSource(), options);
2895d50f51cSMatthias Springer     if (failed(srcMemref))
2905d50f51cSMatthias Springer       return failure();
2915d50f51cSMatthias Springer     auto srcMemrefType = srcMemref->getType().cast<MemRefType>();
29249e37000SMatthias Springer 
2936c3c5f80SMatthias Springer     // Take a subview of the source buffer.
2946c3c5f80SMatthias Springer     auto subviewMemRefType =
2956c3c5f80SMatthias Springer         memref::SubViewOp::inferRankReducedResultType(
2966c3c5f80SMatthias Springer             extractSliceOp.getType().getShape(), srcMemrefType, mixedOffsets,
2976c3c5f80SMatthias Springer             mixedSizes, mixedStrides)
29849e37000SMatthias Springer             .cast<MemRefType>();
29949e37000SMatthias Springer     Value subView = rewriter.create<memref::SubViewOp>(
3005d50f51cSMatthias Springer         loc, subviewMemRefType, *srcMemref, mixedOffsets, mixedSizes,
30149e37000SMatthias Springer         mixedStrides);
30249e37000SMatthias Springer 
30349e37000SMatthias Springer     replaceOpWithBufferizedValues(rewriter, op, subView);
30449e37000SMatthias Springer     return success();
30549e37000SMatthias Springer   }
30649e37000SMatthias Springer };
30749e37000SMatthias Springer 
30849e37000SMatthias Springer /// Bufferization of tensor.extract. Replace with memref.load.
30949e37000SMatthias Springer struct ExtractOpInterface
31049e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<ExtractOpInterface,
31149e37000SMatthias Springer                                                     tensor::ExtractOp> {
31249e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
3139597b16aSMatthias Springer                               const AnalysisState &state) const {
31449e37000SMatthias Springer     return true;
31549e37000SMatthias Springer   }
31649e37000SMatthias Springer 
31749e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
3189597b16aSMatthias Springer                                const AnalysisState &state) const {
31949e37000SMatthias Springer     return false;
32049e37000SMatthias Springer   }
32149e37000SMatthias Springer 
3229597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
3239597b16aSMatthias Springer                                             const AnalysisState &state) const {
324585a8a32SMatthias Springer     return {};
32549e37000SMatthias Springer   }
32649e37000SMatthias Springer 
32749e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
328b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
32949e37000SMatthias Springer     auto extractOp = cast<tensor::ExtractOp>(op);
3305d50f51cSMatthias Springer     FailureOr<Value> srcMemref =
3315d50f51cSMatthias Springer         getBuffer(rewriter, extractOp.getTensor(), options);
3325d50f51cSMatthias Springer     if (failed(srcMemref))
3335d50f51cSMatthias Springer       return failure();
3345d50f51cSMatthias Springer     replaceOpWithNewBufferizedOp<memref::LoadOp>(rewriter, op, *srcMemref,
335136d746eSJacques Pienaar                                                  extractOp.getIndices());
33649e37000SMatthias Springer     return success();
33749e37000SMatthias Springer   }
33849e37000SMatthias Springer };
33949e37000SMatthias Springer 
340d581c94dSMatthias Springer // Implements backtracking to traverse indices of the output buffer while
341d581c94dSMatthias Springer // iterating over op.elements().
342d581c94dSMatthias Springer static void createStores(RewriterBase &rewriter, Location loc, int dim,
343d581c94dSMatthias Springer                          Value buffer, ArrayRef<int64_t> shape,
344d581c94dSMatthias Springer                          ArrayRef<Value> constants,
345d581c94dSMatthias Springer                          OperandRange::iterator &elementIt,
346d581c94dSMatthias Springer                          SmallVectorImpl<Value> &indices) {
347d581c94dSMatthias Springer   if (dim == static_cast<int>(shape.size()) - 1) {
348d581c94dSMatthias Springer     for (int i = 0; i < shape.back(); ++i) {
349d581c94dSMatthias Springer       indices.back() = constants[i];
350d581c94dSMatthias Springer       rewriter.create<memref::StoreOp>(loc, *elementIt, buffer, indices);
351d581c94dSMatthias Springer       ++elementIt;
352d581c94dSMatthias Springer     }
353d581c94dSMatthias Springer     return;
354d581c94dSMatthias Springer   }
355d581c94dSMatthias Springer   for (int i = 0; i < shape[dim]; ++i) {
356d581c94dSMatthias Springer     indices[dim] = constants[i];
357d581c94dSMatthias Springer     createStores(rewriter, loc, dim + 1, buffer, shape, constants, elementIt,
358d581c94dSMatthias Springer                  indices);
359d581c94dSMatthias Springer   }
360d581c94dSMatthias Springer }
361d581c94dSMatthias Springer 
362d581c94dSMatthias Springer /// Bufferization of tensor.from_elements.
363d581c94dSMatthias Springer struct FromElementsOpInterface
364d581c94dSMatthias Springer     : public BufferizableOpInterface::ExternalModel<FromElementsOpInterface,
365d581c94dSMatthias Springer                                                     tensor::FromElementsOp> {
366*664ffa46SMatthias Springer 
367*664ffa46SMatthias Springer   bool bufferizesToAllocation(Operation *op, OpResult opResult) const {
368*664ffa46SMatthias Springer     return true;
369*664ffa46SMatthias Springer   }
370*664ffa46SMatthias Springer 
371d581c94dSMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
372b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
373d581c94dSMatthias Springer     auto fromElementsOp = cast<tensor::FromElementsOp>(op);
374*664ffa46SMatthias Springer     // Should the buffer be deallocated?
375*664ffa46SMatthias Springer     bool dealloc = shouldDeallocateOpResult(
376*664ffa46SMatthias Springer         fromElementsOp.getResult().cast<OpResult>(), options);
377d581c94dSMatthias Springer 
378c0b0b6a0SMatthias Springer     // TODO: Implement memory space for this op.
379c0b0b6a0SMatthias Springer     if (options.defaultMemorySpace != static_cast<unsigned>(0))
380c0b0b6a0SMatthias Springer       return op->emitError("memory space not implemented yet");
381c0b0b6a0SMatthias Springer 
382d581c94dSMatthias Springer     // Allocate a buffer for the result.
383d581c94dSMatthias Springer     Location loc = op->getLoc();
384d581c94dSMatthias Springer     auto tensorType = fromElementsOp.getType().cast<RankedTensorType>();
385d581c94dSMatthias Springer     auto shape = tensorType.getShape();
386b3ebe3beSMatthias Springer     // TODO: Create alloc_tensor ops during TensorCopyInsertion.
387*664ffa46SMatthias Springer     FailureOr<Value> tensorAlloc =
388*664ffa46SMatthias Springer         allocateTensorForShapedValue(rewriter, loc, fromElementsOp.getResult(),
389*664ffa46SMatthias Springer                                      /*escape=*/!dealloc, options,
390b3ebe3beSMatthias Springer                                      /*copy=*/false);
39145b995cdSMatthias Springer     if (failed(tensorAlloc))
39245b995cdSMatthias Springer       return failure();
393b3ebe3beSMatthias Springer     auto memrefType =
394b3ebe3beSMatthias Springer         MemRefType::get(tensorType.getShape(), tensorType.getElementType());
395b3ebe3beSMatthias Springer     Value buffer = rewriter.create<bufferization::ToMemrefOp>(
39645b995cdSMatthias Springer         op->getLoc(), memrefType, *tensorAlloc);
397d581c94dSMatthias Springer 
398d581c94dSMatthias Springer     // Case: tensor<0xelem_type>.
3998df54a6aSJacques Pienaar     if (fromElementsOp.getElements().empty()) {
400d581c94dSMatthias Springer       replaceOpWithBufferizedValues(rewriter, op, buffer);
401d581c94dSMatthias Springer       return success();
402d581c94dSMatthias Springer     }
403d581c94dSMatthias Springer 
404d581c94dSMatthias Springer     // Case: tensor<elem_type>.
405d581c94dSMatthias Springer     if (shape.empty()) {
4068df54a6aSJacques Pienaar       rewriter.create<memref::StoreOp>(
4078df54a6aSJacques Pienaar           loc, fromElementsOp.getElements().front(), buffer);
408d581c94dSMatthias Springer       replaceOpWithBufferizedValues(rewriter, op, buffer);
409d581c94dSMatthias Springer       return success();
410d581c94dSMatthias Springer     }
411d581c94dSMatthias Springer 
412d581c94dSMatthias Springer     // Create constants for the range of possible indices [0, max{shape_i}).
413d581c94dSMatthias Springer     auto maxDim = *std::max_element(shape.begin(), shape.end());
414d581c94dSMatthias Springer     SmallVector<Value, 2> constants;
415d581c94dSMatthias Springer     constants.reserve(maxDim);
416d581c94dSMatthias Springer     for (int i = 0; i < maxDim; ++i)
417d581c94dSMatthias Springer       constants.push_back(rewriter.create<arith::ConstantIndexOp>(loc, i));
418d581c94dSMatthias Springer 
419d581c94dSMatthias Springer     // Traverse all `elements` and create `memref.store` ops.
4208df54a6aSJacques Pienaar     auto elementIt = fromElementsOp.getElements().begin();
421d581c94dSMatthias Springer     SmallVector<Value, 2> indices(tensorType.getRank(), constants[0]);
422d581c94dSMatthias Springer     createStores(rewriter, loc, /*dim=*/0, buffer, shape, constants, elementIt,
423d581c94dSMatthias Springer                  indices);
424d581c94dSMatthias Springer 
425d581c94dSMatthias Springer     replaceOpWithBufferizedValues(rewriter, op, buffer);
426*664ffa46SMatthias Springer 
427d581c94dSMatthias Springer     return success();
428d581c94dSMatthias Springer   }
429d581c94dSMatthias Springer };
430d581c94dSMatthias Springer 
43171bbb78bSMatthias Springer /// Bufferization of tensor.generate.
43271bbb78bSMatthias Springer struct GenerateOpInterface
43371bbb78bSMatthias Springer     : public BufferizableOpInterface::ExternalModel<GenerateOpInterface,
43471bbb78bSMatthias Springer                                                     tensor::GenerateOp> {
435*664ffa46SMatthias Springer 
436*664ffa46SMatthias Springer   bool bufferizesToAllocation(Operation *op, OpResult opResult) const {
437*664ffa46SMatthias Springer     return true;
438*664ffa46SMatthias Springer   }
439*664ffa46SMatthias Springer 
44071bbb78bSMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
441b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
44271bbb78bSMatthias Springer     auto generateOp = cast<tensor::GenerateOp>(op);
443*664ffa46SMatthias Springer     // Should the buffer be deallocated?
444*664ffa46SMatthias Springer     bool dealloc = shouldDeallocateOpResult(
445*664ffa46SMatthias Springer         generateOp.getResult().cast<OpResult>(), options);
446c0b0b6a0SMatthias Springer 
447c0b0b6a0SMatthias Springer     // TODO: Implement memory space for this op.
448c0b0b6a0SMatthias Springer     if (options.defaultMemorySpace != static_cast<unsigned>(0))
449c0b0b6a0SMatthias Springer       return op->emitError("memory space not implemented yet");
450c0b0b6a0SMatthias Springer 
451b3ebe3beSMatthias Springer     auto tensorType = generateOp.getType().cast<RankedTensorType>();
45271bbb78bSMatthias Springer     // Allocate memory.
45371bbb78bSMatthias Springer     Location loc = op->getLoc();
454b3ebe3beSMatthias Springer     // TODO: Create alloc_tensor ops during TensorCopyInsertion.
455*664ffa46SMatthias Springer     FailureOr<Value> tensorAlloc =
456*664ffa46SMatthias Springer         allocateTensorForShapedValue(rewriter, loc, generateOp.getResult(),
457*664ffa46SMatthias Springer                                      /*escape=*/!dealloc, options,
458b3ebe3beSMatthias Springer                                      /*copy=*/false);
45945b995cdSMatthias Springer     if (failed(tensorAlloc))
46045b995cdSMatthias Springer       return failure();
461b3ebe3beSMatthias Springer     auto memrefType =
462b3ebe3beSMatthias Springer         MemRefType::get(tensorType.getShape(), tensorType.getElementType());
463b3ebe3beSMatthias Springer     Value buffer = rewriter.create<bufferization::ToMemrefOp>(
46445b995cdSMatthias Springer         op->getLoc(), memrefType, *tensorAlloc);
46571bbb78bSMatthias Springer 
46671bbb78bSMatthias Springer     // Collect loop bounds.
46771bbb78bSMatthias Springer     int64_t rank = memrefType.getRank();
46871bbb78bSMatthias Springer     Value zero = rewriter.create<arith::ConstantIndexOp>(loc, 0);
46971bbb78bSMatthias Springer     Value one = rewriter.create<arith::ConstantIndexOp>(loc, 1);
47071bbb78bSMatthias Springer     SmallVector<Value, 4> lowerBounds(rank, zero);
47171bbb78bSMatthias Springer     SmallVector<Value, 4> steps(rank, one);
47271bbb78bSMatthias Springer     SmallVector<Value, 4> upperBounds;
47371bbb78bSMatthias Springer     int nextDynamicIndex = 0;
47471bbb78bSMatthias Springer     for (int i = 0; i < rank; i++) {
4758df54a6aSJacques Pienaar       Value upperBound =
4768df54a6aSJacques Pienaar           memrefType.isDynamicDim(i)
4778df54a6aSJacques Pienaar               ? generateOp.getDynamicExtents()[nextDynamicIndex++]
47871bbb78bSMatthias Springer               : rewriter.create<arith::ConstantIndexOp>(
47971bbb78bSMatthias Springer                     loc, memrefType.getDimSize(i));
48071bbb78bSMatthias Springer       upperBounds.push_back(upperBound);
48171bbb78bSMatthias Springer     }
48271bbb78bSMatthias Springer 
48371bbb78bSMatthias Springer     // Generate tensor elements with a parallel loop that stores into
48471bbb78bSMatthias Springer     // each element of the resulting memref. We use mergeBlockBefore to "move"
48571bbb78bSMatthias Springer     // this op's body into the scf.parallel's body.
48671bbb78bSMatthias Springer     auto parallel =
48771bbb78bSMatthias Springer         rewriter.create<scf::ParallelOp>(loc, lowerBounds, upperBounds, steps);
48871bbb78bSMatthias Springer     Block *parallelBody = parallel.getBody();
489eca86cb2SJacques Pienaar     rewriter.mergeBlockBefore(&generateOp.getBody().front(),
49071bbb78bSMatthias Springer                               parallelBody->getTerminator(),
49171bbb78bSMatthias Springer                               parallelBody->getArguments());
49271bbb78bSMatthias Springer     // Replace the inlined yield op with a store op. The scf.parallel's builder
49371bbb78bSMatthias Springer     // already populated an scf.yield at the end, so we don't need to worry
49471bbb78bSMatthias Springer     // about creating that.
49571bbb78bSMatthias Springer     Operation *elementYield = parallelBody->getTerminator()->getPrevNode();
49671bbb78bSMatthias Springer     rewriter.setInsertionPointAfter(elementYield);
49771bbb78bSMatthias Springer     rewriter.replaceOpWithNewOp<memref::StoreOp>(
498b3ebe3beSMatthias Springer         elementYield, elementYield->getOperands()[0], buffer,
49971bbb78bSMatthias Springer         parallelBody->getArguments());
50071bbb78bSMatthias Springer 
501b3ebe3beSMatthias Springer     replaceOpWithBufferizedValues(rewriter, op, buffer);
502*664ffa46SMatthias Springer 
50371bbb78bSMatthias Springer     return success();
50471bbb78bSMatthias Springer   }
50571bbb78bSMatthias Springer };
50671bbb78bSMatthias Springer 
50749e37000SMatthias Springer /// Bufferization of tensor.insert. Replace with memref.store.
50849e37000SMatthias Springer struct InsertOpInterface
50949e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<InsertOpInterface,
51049e37000SMatthias Springer                                                     tensor::InsertOp> {
51149e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
5129597b16aSMatthias Springer                               const AnalysisState &state) const {
51349e37000SMatthias Springer     return true;
51449e37000SMatthias Springer   }
51549e37000SMatthias Springer 
51649e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
5179597b16aSMatthias Springer                                const AnalysisState &state) const {
51849e37000SMatthias Springer     return true;
51949e37000SMatthias Springer   }
52049e37000SMatthias Springer 
5219597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
5229597b16aSMatthias Springer                                             const AnalysisState &state) const {
52349e37000SMatthias Springer     assert(&opOperand == &op->getOpOperand(1) /*dest*/ &&
52449e37000SMatthias Springer            "expected dest OpOperand");
525585a8a32SMatthias Springer     return {op->getOpResult(0)};
52649e37000SMatthias Springer   }
52749e37000SMatthias Springer 
52849e37000SMatthias Springer   SmallVector<OpOperand *>
52949e37000SMatthias Springer   getAliasingOpOperand(Operation *op, OpResult opResult,
5309597b16aSMatthias Springer                        const AnalysisState &state) const {
53149e37000SMatthias Springer     return {&op->getOpOperand(1) /*dest*/};
53249e37000SMatthias Springer   }
53349e37000SMatthias Springer 
53449e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
535b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
53649e37000SMatthias Springer     auto insertOp = cast<tensor::InsertOp>(op);
5375d50f51cSMatthias Springer     FailureOr<Value> destMemref =
5385d50f51cSMatthias Springer         getBuffer(rewriter, insertOp.getDest(), options);
5395d50f51cSMatthias Springer     if (failed(destMemref))
5405d50f51cSMatthias Springer       return failure();
5418df54a6aSJacques Pienaar     rewriter.create<memref::StoreOp>(insertOp.getLoc(), insertOp.getScalar(),
5425d50f51cSMatthias Springer                                      *destMemref, insertOp.getIndices());
5435d50f51cSMatthias Springer     replaceOpWithBufferizedValues(rewriter, op, *destMemref);
54449e37000SMatthias Springer     return success();
54549e37000SMatthias Springer   }
54649e37000SMatthias Springer 
54749e37000SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
5489597b16aSMatthias Springer                                 const AnalysisState &state) const {
54949e37000SMatthias Springer     return BufferRelation::Equivalent;
55049e37000SMatthias Springer   }
55149e37000SMatthias Springer };
55249e37000SMatthias Springer 
55349e37000SMatthias Springer /// Return true if the (ExtractSliceOp, InsertSliceOp) pair match (i.e.
55449e37000SMatthias Springer /// equivalent operand / result and same offset/sizes/strides specification).
55549e37000SMatthias Springer ///
55649e37000SMatthias Springer /// This is one particular type of relationship between ops on tensors that
55749e37000SMatthias Springer /// reduce to an equivalence on buffers. This should be generalized and
55849e37000SMatthias Springer /// exposed as interfaces on the proper types.
5599597b16aSMatthias Springer static bool areEquivalentExtractSliceOps(const AnalysisState &state,
56049e37000SMatthias Springer                                          ExtractSliceOp st, InsertSliceOp sti) {
56149e37000SMatthias Springer   if (!st || !sti)
56249e37000SMatthias Springer     return false;
56349e37000SMatthias Springer   if (sti != sti &&
5648df54a6aSJacques Pienaar       !state.areEquivalentBufferizedValues(st.getSource(), sti.getDest()))
56549e37000SMatthias Springer     return false;
56649e37000SMatthias Springer   if (!sameOffsetsSizesAndStrides(st, sti, isEqualConstantIntOrValue))
56749e37000SMatthias Springer     return false;
56849e37000SMatthias Springer   return true;
56949e37000SMatthias Springer }
57049e37000SMatthias Springer 
57149e37000SMatthias Springer /// Return true if `value` is originating from an ExtractSliceOp that matches
57249e37000SMatthias Springer /// the given InsertSliceOp.
5739597b16aSMatthias Springer static bool hasMatchingExtractSliceOp(const AnalysisState &state, Value value,
5749597b16aSMatthias Springer                                       InsertSliceOp insertOp) {
57549e37000SMatthias Springer   auto condition = [&](Value val) {
57649e37000SMatthias Springer     if (auto extractOp = val.getDefiningOp<ExtractSliceOp>())
57749e37000SMatthias Springer       if (areEquivalentExtractSliceOps(state, extractOp, insertOp))
57849e37000SMatthias Springer         return true;
57949e37000SMatthias Springer     return false;
58049e37000SMatthias Springer   };
58149e37000SMatthias Springer 
58249e37000SMatthias Springer   return llvm::all_of(state.findValueInReverseUseDefChain(value, condition),
58349e37000SMatthias Springer                       condition);
58449e37000SMatthias Springer }
58549e37000SMatthias Springer 
58649e37000SMatthias Springer /// Bufferization of tensor.insert_slice. Replace with a memory copy. Under
58749e37000SMatthias Springer /// certain circumstances, this op can also be a no-op.
58849e37000SMatthias Springer struct InsertSliceOpInterface
58949e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<InsertSliceOpInterface,
59049e37000SMatthias Springer                                                     tensor::InsertSliceOp> {
59149e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
5929597b16aSMatthias Springer                               const AnalysisState &state) const {
59349e37000SMatthias Springer     return true;
59449e37000SMatthias Springer   }
59549e37000SMatthias Springer 
59649e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
5979597b16aSMatthias Springer                                const AnalysisState &state) const {
59849e37000SMatthias Springer     return &opOperand == &op->getOpOperand(1) /*dest*/;
59949e37000SMatthias Springer   }
60049e37000SMatthias Springer 
6019597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
6029597b16aSMatthias Springer                                             const AnalysisState &state) const {
603585a8a32SMatthias Springer     if (&opOperand == &op->getOpOperand(1) /*dest*/)
604585a8a32SMatthias Springer       return {op->getResult(0)};
605585a8a32SMatthias Springer     return {};
60649e37000SMatthias Springer   }
60749e37000SMatthias Springer 
60849e37000SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
6099597b16aSMatthias Springer                                 const AnalysisState &state) const {
61049e37000SMatthias Springer     return BufferRelation::Equivalent;
61149e37000SMatthias Springer   }
61249e37000SMatthias Springer 
61349e37000SMatthias Springer   bool isNotConflicting(Operation *op, OpOperand *uRead,
61449e37000SMatthias Springer                         OpOperand *uConflictingWrite,
6159597b16aSMatthias Springer                         const AnalysisState &state) const {
61649e37000SMatthias Springer     Operation *readingOp = uRead->getOwner();
61749e37000SMatthias Springer     Operation *conflictingWritingOp = uConflictingWrite->getOwner();
61849e37000SMatthias Springer 
61949e37000SMatthias Springer     // Special rules for matching ExtractSliceOp/InsertSliceOp pairs. If
62049e37000SMatthias Springer     // uRead is an InsertSliceOp...
62149e37000SMatthias Springer     if (auto insertSliceOp = dyn_cast<InsertSliceOp>(readingOp)) {
62249e37000SMatthias Springer       // As an example, consider the following IR.
62349e37000SMatthias Springer       //
62449e37000SMatthias Springer       // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] }
62549e37000SMatthias Springer       // %1 = linalg.fill %cst, %0 {inplace= [true] }
62649e37000SMatthias Springer       // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1]
62749e37000SMatthias Springer       //     {inplace= [true] }
62849e37000SMatthias Springer 
62949e37000SMatthias Springer       // TODO: Use insertSliceOp.getDestOpOperand etc. when available.
63049e37000SMatthias Springer       if (uRead == &insertSliceOp->getOpOperand(1) /*dest*/ &&
63149e37000SMatthias Springer           hasMatchingExtractSliceOp(state, uConflictingWrite->get(),
63249e37000SMatthias Springer                                     insertSliceOp))
63349e37000SMatthias Springer         // Case 1: The main insight is that InsertSliceOp reads only part of
63449e37000SMatthias Springer         // the destination tensor. The overwritten area is not read. If
63549e37000SMatthias Springer         // uConflictingWrite writes into exactly the memory location that is
63649e37000SMatthias Springer         // being read by uRead, this is not a conflict.
63749e37000SMatthias Springer         //
63849e37000SMatthias Springer         // In the above example:
63949e37000SMatthias Springer         // uRead             = OpOperand 1 (%t) of tensor.insert_slice
64049e37000SMatthias Springer         // uConflictingWrite = OpOperand 1 (%0) of linalg.fill
64149e37000SMatthias Springer         //
64249e37000SMatthias Springer         // The read of %t does not conflict with the write of the FillOp
64349e37000SMatthias Springer         // (same aliases!) because the area that the FillOp operates on is
64449e37000SMatthias Springer         // exactly the one that is *not* read via %t.
64549e37000SMatthias Springer         return true;
64649e37000SMatthias Springer 
64749e37000SMatthias Springer       if (uRead == &insertSliceOp->getOpOperand(0) /*source*/ &&
64849e37000SMatthias Springer           uConflictingWrite == &insertSliceOp->getOpOperand(1) /*dest*/ &&
64949e37000SMatthias Springer           hasMatchingExtractSliceOp(state, uRead->get(), insertSliceOp))
65049e37000SMatthias Springer         // Case 2: The read of the source tensor and the write to the dest
65149e37000SMatthias Springer         // tensor via an InsertSliceOp is not a conflict if the read is
65249e37000SMatthias Springer         // reading exactly that part of an equivalent tensor that the
65349e37000SMatthias Springer         // InsertSliceOp is writing.
65449e37000SMatthias Springer         //
65549e37000SMatthias Springer         // In the above example:
65649e37000SMatthias Springer         // uRead             = OpOperand 0 (%1) of tensor.insert_slice
65749e37000SMatthias Springer         // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice
65849e37000SMatthias Springer         return true;
65949e37000SMatthias Springer     }
66049e37000SMatthias Springer 
66149e37000SMatthias Springer     // If uConflictingWrite is an InsertSliceOp...
66249e37000SMatthias Springer     if (auto insertSliceOp = dyn_cast<InsertSliceOp>(conflictingWritingOp))
66349e37000SMatthias Springer       // As an example, consider the following IR.
66449e37000SMatthias Springer       //
66549e37000SMatthias Springer       // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] }
66649e37000SMatthias Springer       // %1 = linalg.fill %cst, %0 {inplace= [true] }
66749e37000SMatthias Springer       // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1]
66849e37000SMatthias Springer       //     {inplace= [true] }
66949e37000SMatthias Springer       // %3 = vector.transfer_read %1, %cst
67049e37000SMatthias Springer       //
67149e37000SMatthias Springer       // In the above example:
67249e37000SMatthias Springer       // uRead             = OpOperand 0 (%1) of vector.transfer_read
67349e37000SMatthias Springer       // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice
67449e37000SMatthias Springer       // lastWrite         = %1
67549e37000SMatthias Springer       //
67649e37000SMatthias Springer       // This is not a conflict because the InsertSliceOp overwrites the
67749e37000SMatthias Springer       // memory segment of %1 with the exact same data. (Effectively, there
67849e37000SMatthias Springer       // is no memory write here.)
67949e37000SMatthias Springer       if (uConflictingWrite == &insertSliceOp->getOpOperand(1) /*dest*/ &&
68049e37000SMatthias Springer           state.areEquivalentBufferizedValues(uRead->get(),
6818df54a6aSJacques Pienaar                                               insertSliceOp.getSource()) &&
6828df54a6aSJacques Pienaar           hasMatchingExtractSliceOp(state, insertSliceOp.getSource(),
68349e37000SMatthias Springer                                     insertSliceOp))
68449e37000SMatthias Springer         return true;
68549e37000SMatthias Springer 
68649e37000SMatthias Springer     return false;
68749e37000SMatthias Springer   }
68849e37000SMatthias Springer 
68949e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
690b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
69149e37000SMatthias Springer     // insert_slice ops arise from tiling and bufferizing them out-of-place is
69249e37000SMatthias Springer     // generally a deal breaker. When used with loops, this ends up cloning the
69349e37000SMatthias Springer     // whole tensor on every single iteration and is a symptom of a
69449e37000SMatthias Springer     // catastrophically bad scheduling decision.
69549e37000SMatthias Springer     // TODO: be very loud about it or even consider failing the pass.
69649e37000SMatthias Springer     auto insertSliceOp = cast<tensor::InsertSliceOp>(op);
6976c3c5f80SMatthias Springer     SmallVector<OpFoldResult> mixedOffsets = insertSliceOp.getMixedOffsets();
6986c3c5f80SMatthias Springer     SmallVector<OpFoldResult> mixedSizes = insertSliceOp.getMixedSizes();
6996c3c5f80SMatthias Springer     SmallVector<OpFoldResult> mixedStrides = insertSliceOp.getMixedStrides();
70049e37000SMatthias Springer     Location loc = insertSliceOp.getLoc();
7016c3c5f80SMatthias Springer 
7026c3c5f80SMatthias Springer     // Get destination buffer.
7035d50f51cSMatthias Springer     FailureOr<Value> dstMemref =
7045d50f51cSMatthias Springer         getBuffer(rewriter, insertSliceOp.getDest(), options);
7055d50f51cSMatthias Springer     if (failed(dstMemref))
7065d50f51cSMatthias Springer       return failure();
70749e37000SMatthias Springer 
7086c3c5f80SMatthias Springer     // Take a subview of the destination buffer.
7095d50f51cSMatthias Springer     auto dstMemrefType = dstMemref->getType().cast<MemRefType>();
71049e37000SMatthias Springer     auto subviewMemRefType =
71149e37000SMatthias Springer         memref::SubViewOp::inferRankReducedResultType(
7126c3c5f80SMatthias Springer             insertSliceOp.getSourceType().getShape(), dstMemrefType,
71349e37000SMatthias Springer             mixedOffsets, mixedSizes, mixedStrides)
71449e37000SMatthias Springer             .cast<MemRefType>();
71549e37000SMatthias Springer     Value subView = rewriter.create<memref::SubViewOp>(
7165d50f51cSMatthias Springer         loc, subviewMemRefType, *dstMemref, mixedOffsets, mixedSizes,
71749e37000SMatthias Springer         mixedStrides);
71849e37000SMatthias Springer 
71949e37000SMatthias Springer     // Copy tensor. If this tensor.insert_slice has a matching
72049e37000SMatthias Springer     // tensor.extract_slice, the copy operation will eventually fold away.
7215d50f51cSMatthias Springer     FailureOr<Value> srcMemref =
7225d50f51cSMatthias Springer         getBuffer(rewriter, insertSliceOp.getSource(), options);
7235d50f51cSMatthias Springer     if (failed(srcMemref))
7245d50f51cSMatthias Springer       return failure();
7255d50f51cSMatthias Springer     if (failed(options.createMemCpy(rewriter, loc, *srcMemref, subView)))
72649e37000SMatthias Springer       return failure();
72749e37000SMatthias Springer 
7285d50f51cSMatthias Springer     replaceOpWithBufferizedValues(rewriter, op, *dstMemref);
72949e37000SMatthias Springer     return success();
73049e37000SMatthias Springer   }
73149e37000SMatthias Springer };
73249e37000SMatthias Springer 
733fc08d1c2SMatthias Springer /// Bufferization of tensor.rank. Replace with memref.rank.
734fc08d1c2SMatthias Springer struct RankOpInterface
735fc08d1c2SMatthias Springer     : public BufferizableOpInterface::ExternalModel<RankOpInterface,
736fc08d1c2SMatthias Springer                                                     tensor::RankOp> {
737fc08d1c2SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
7389597b16aSMatthias Springer                               const AnalysisState &state) const {
739fc08d1c2SMatthias Springer     return true;
740fc08d1c2SMatthias Springer   }
741fc08d1c2SMatthias Springer 
742fc08d1c2SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
7439597b16aSMatthias Springer                                const AnalysisState &state) const {
744fc08d1c2SMatthias Springer     return false;
745fc08d1c2SMatthias Springer   }
746fc08d1c2SMatthias Springer 
7479597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
7489597b16aSMatthias Springer                                             const AnalysisState &state) const {
749585a8a32SMatthias Springer     return {};
750fc08d1c2SMatthias Springer   }
751fc08d1c2SMatthias Springer 
752fc08d1c2SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
753b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
754fc08d1c2SMatthias Springer     auto rankOp = cast<tensor::RankOp>(op);
7555d50f51cSMatthias Springer     FailureOr<Value> v = getBuffer(rewriter, rankOp.getTensor(), options);
7565d50f51cSMatthias Springer     if (failed(v))
7575d50f51cSMatthias Springer       return failure();
758fc08d1c2SMatthias Springer     replaceOpWithNewBufferizedOp<memref::RankOp>(rewriter, op, rankOp.getType(),
7595d50f51cSMatthias Springer                                                  *v);
760fc08d1c2SMatthias Springer     return success();
761fc08d1c2SMatthias Springer   }
762fc08d1c2SMatthias Springer };
763fc08d1c2SMatthias Springer 
764e287d647SAshay Rane /// Bufferization of tensor.reshape. Replace with memref.reshape.
765e287d647SAshay Rane struct ReshapeOpInterface
766e287d647SAshay Rane     : public BufferizableOpInterface::ExternalModel<ReshapeOpInterface,
767e287d647SAshay Rane                                                     tensor::ReshapeOp> {
768e287d647SAshay Rane   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
769e287d647SAshay Rane                               const AnalysisState &state) const {
770e287d647SAshay Rane     if (&opOperand == &op->getOpOperand(1) /* shape */)
771e287d647SAshay Rane       return true;
772e287d647SAshay Rane     return false;
773e287d647SAshay Rane   }
774e287d647SAshay Rane 
775e287d647SAshay Rane   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
776e287d647SAshay Rane                                const AnalysisState &state) const {
777e287d647SAshay Rane     return false;
778e287d647SAshay Rane   }
779e287d647SAshay Rane 
780e287d647SAshay Rane   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
781e287d647SAshay Rane                                             const AnalysisState &state) const {
782e287d647SAshay Rane     return {op->getOpResult(0)};
783e287d647SAshay Rane   }
784e287d647SAshay Rane 
785e287d647SAshay Rane   BufferRelation bufferRelation(Operation *op, OpResult opResult,
786e287d647SAshay Rane                                 const AnalysisState &state) const {
787e287d647SAshay Rane     return BufferRelation::Equivalent;
788e287d647SAshay Rane   }
789e287d647SAshay Rane 
790e287d647SAshay Rane   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
791b55d55ecSMatthias Springer                           const BufferizationOptions &options) const {
792e287d647SAshay Rane     auto reshapeOp = cast<tensor::ReshapeOp>(op);
7935d50f51cSMatthias Springer     FailureOr<Value> srcBuffer =
7945d50f51cSMatthias Springer         getBuffer(rewriter, reshapeOp.getSource(), options);
7955d50f51cSMatthias Springer     FailureOr<Value> shapeBuffer =
7965d50f51cSMatthias Springer         getBuffer(rewriter, reshapeOp.getShape(), options);
7975d50f51cSMatthias Springer     if (failed(srcBuffer) || failed(shapeBuffer))
7985d50f51cSMatthias Springer       return failure();
799c0b0b6a0SMatthias Springer     auto resultMemRefType = getMemRefType(
800606f7c8fSMatthias Springer         reshapeOp.getResult(), options, /*layout=*/{},
801c0b0b6a0SMatthias Springer         srcBuffer->getType().cast<BaseMemRefType>().getMemorySpaceAsInt());
802e287d647SAshay Rane     replaceOpWithNewBufferizedOp<memref::ReshapeOp>(
8035d50f51cSMatthias Springer         rewriter, op, resultMemRefType, *srcBuffer, *shapeBuffer);
804e287d647SAshay Rane     return success();
805e287d647SAshay Rane   }
806e287d647SAshay Rane };
807e287d647SAshay Rane 
8087fbf55c9SNicolas Vasilache /// Return true if the (ExtractSliceOp, ParallelInsertSliceOp) pair match (i.e.
8097fbf55c9SNicolas Vasilache /// equivalent operand / result and same offset/sizes/strides specification).
8107fbf55c9SNicolas Vasilache static bool areEquivalentExtractSliceOps(const AnalysisState &state,
8117fbf55c9SNicolas Vasilache                                          ExtractSliceOp st,
8127fbf55c9SNicolas Vasilache                                          ParallelInsertSliceOp sti) {
8137fbf55c9SNicolas Vasilache   if (!st || !sti)
8147fbf55c9SNicolas Vasilache     return false;
8157fbf55c9SNicolas Vasilache   if (st != sti &&
8167fbf55c9SNicolas Vasilache       !state.areEquivalentBufferizedValues(st.getSource(), sti.getDest()))
8177fbf55c9SNicolas Vasilache     return false;
8187fbf55c9SNicolas Vasilache   if (!sameOffsetsSizesAndStrides(st, sti, isEqualConstantIntOrValue))
8197fbf55c9SNicolas Vasilache     return false;
8207fbf55c9SNicolas Vasilache   return true;
8217fbf55c9SNicolas Vasilache }
8227fbf55c9SNicolas Vasilache 
8237fbf55c9SNicolas Vasilache /// Return true if `value` is originating from an ExtractSliceOp that matches
8247fbf55c9SNicolas Vasilache /// the given InsertSliceOp.
8257fbf55c9SNicolas Vasilache static bool hasMatchingExtractSliceOp(const AnalysisState &state, Value value,
8267fbf55c9SNicolas Vasilache                                       ParallelInsertSliceOp insertOp) {
8277fbf55c9SNicolas Vasilache   auto condition = [&](Value val) {
8287fbf55c9SNicolas Vasilache     if (auto extractOp = val.getDefiningOp<ExtractSliceOp>())
8297fbf55c9SNicolas Vasilache       if (areEquivalentExtractSliceOps(state, extractOp, insertOp))
8307fbf55c9SNicolas Vasilache         return true;
8317fbf55c9SNicolas Vasilache     return false;
8327fbf55c9SNicolas Vasilache   };
8337fbf55c9SNicolas Vasilache 
8347fbf55c9SNicolas Vasilache   return llvm::all_of(state.findValueInReverseUseDefChain(value, condition),
8357fbf55c9SNicolas Vasilache                       condition);
8367fbf55c9SNicolas Vasilache }
8377fbf55c9SNicolas Vasilache 
8387fbf55c9SNicolas Vasilache /// Analysis of ParallelInsertSliceOp.
8397fbf55c9SNicolas Vasilache struct ParallelInsertSliceOpInterface
8407fbf55c9SNicolas Vasilache     : public BufferizableOpInterface::ExternalModel<
8417fbf55c9SNicolas Vasilache           ParallelInsertSliceOpInterface, ParallelInsertSliceOp> {
8427fbf55c9SNicolas Vasilache   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
8437fbf55c9SNicolas Vasilache                                             const AnalysisState &state) const {
8447fbf55c9SNicolas Vasilache     if (&opOperand != &op->getOpOperand(1) /*dest*/)
8457fbf55c9SNicolas Vasilache       return {};
8467fbf55c9SNicolas Vasilache 
8477fbf55c9SNicolas Vasilache     // ParallelInsertSliceOp itself has no results, query its tied op results.
8487fbf55c9SNicolas Vasilache     auto insertOp = cast<ParallelInsertSliceOp>(op);
8497fbf55c9SNicolas Vasilache     return {insertOp.getTiedOpResult()};
8507fbf55c9SNicolas Vasilache   }
8517fbf55c9SNicolas Vasilache 
8527fbf55c9SNicolas Vasilache   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
8537fbf55c9SNicolas Vasilache                               const AnalysisState &state) const {
8547fbf55c9SNicolas Vasilache     return true;
8557fbf55c9SNicolas Vasilache   }
8567fbf55c9SNicolas Vasilache 
8577fbf55c9SNicolas Vasilache   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
8587fbf55c9SNicolas Vasilache                                const AnalysisState &state) const {
8597fbf55c9SNicolas Vasilache     return &opOperand == &op->getOpOperand(1) /*dest*/;
8607fbf55c9SNicolas Vasilache   }
8617fbf55c9SNicolas Vasilache 
8627fbf55c9SNicolas Vasilache   BufferRelation bufferRelation(Operation *op, OpResult opResult,
8637fbf55c9SNicolas Vasilache                                 const AnalysisState &state) const {
8647fbf55c9SNicolas Vasilache     return BufferRelation::Equivalent;
8657fbf55c9SNicolas Vasilache   }
8667fbf55c9SNicolas Vasilache 
8677fbf55c9SNicolas Vasilache   LogicalResult resolveConflicts(Operation *op, RewriterBase &rewriter,
8687fbf55c9SNicolas Vasilache                                  const AnalysisState &state) const {
8697fbf55c9SNicolas Vasilache     // This interface method is overridden because we want to set a custom
8707fbf55c9SNicolas Vasilache     // insertion point for tensor copies. They should be inserted right before
8717fbf55c9SNicolas Vasilache     // the ForeachThreadOp. E.g.:
8727fbf55c9SNicolas Vasilache     //
8737fbf55c9SNicolas Vasilache     // %r0, %r1 = foreach_thead ... {
8747fbf55c9SNicolas Vasilache     //   ...
8757fbf55c9SNicolas Vasilache     //   perform_concurrently {
8767fbf55c9SNicolas Vasilache     //     parallel_insert_slice %a into %b ... {inplace = ["true", "true"]}
8777fbf55c9SNicolas Vasilache     //     parallel_insert_slice %c into %d ... {inplace = ["true", "false"]}
8787fbf55c9SNicolas Vasilache     //   }
8797fbf55c9SNicolas Vasilache     // }
8807fbf55c9SNicolas Vasilache     //
8817fbf55c9SNicolas Vasilache     // After TensorCopyInsertion:
8827fbf55c9SNicolas Vasilache     //
8837fbf55c9SNicolas Vasilache     // %copy = bufferization.alloc_tensor() copy(%d)
8847fbf55c9SNicolas Vasilache     // %r0, %r1 = foreach_thead ... {
8857fbf55c9SNicolas Vasilache     //   ...
8867fbf55c9SNicolas Vasilache     //   perform_concurrently {
8877fbf55c9SNicolas Vasilache     //     parallel_insert_slice %a into %b ...
8887fbf55c9SNicolas Vasilache     //     parallel_insert_slice %c into %copy ...
8897fbf55c9SNicolas Vasilache     //   }
8907fbf55c9SNicolas Vasilache     // }
8917fbf55c9SNicolas Vasilache 
8927fbf55c9SNicolas Vasilache     OpBuilder::InsertionGuard g(rewriter);
8937fbf55c9SNicolas Vasilache     auto parallelInsertSliceOp = cast<ParallelInsertSliceOp>(op);
8947fbf55c9SNicolas Vasilache     ParallelCombiningOpInterface parallelCombiningParent =
8957fbf55c9SNicolas Vasilache         parallelInsertSliceOp.getParallelCombiningParent();
8967fbf55c9SNicolas Vasilache     Operation *parallelIteratingOp = parallelCombiningParent->getParentOp();
8977fbf55c9SNicolas Vasilache 
8987fbf55c9SNicolas Vasilache     // Nothing to do if the destination tensor is inplace.
8997fbf55c9SNicolas Vasilache     assert(state.isInPlace(op->getOpOperand(0) /*src*/) &&
9007fbf55c9SNicolas Vasilache            "source is always in-place");
9017fbf55c9SNicolas Vasilache     if (state.isInPlace(op->getOpOperand(1) /*dest*/))
9027fbf55c9SNicolas Vasilache       return success();
9037fbf55c9SNicolas Vasilache 
9047fbf55c9SNicolas Vasilache     // Find corresponding OpResult.
9057fbf55c9SNicolas Vasilache     OpResult opResult = parallelInsertSliceOp.getTiedOpResult();
9067fbf55c9SNicolas Vasilache 
9077fbf55c9SNicolas Vasilache     // Insert tensor allocation right before the ForeachThreadOp.
9087fbf55c9SNicolas Vasilache     rewriter.setInsertionPoint(parallelIteratingOp);
9097fbf55c9SNicolas Vasilache     bool isYielded = state.isTensorYielded(opResult);
9107fbf55c9SNicolas Vasilache     FailureOr<Value> alloc = allocateTensorForShapedValue(
9117fbf55c9SNicolas Vasilache         rewriter, op->getLoc(), parallelInsertSliceOp.getDest(),
9127fbf55c9SNicolas Vasilache         /*escape=*/isYielded, state.getOptions());
9137fbf55c9SNicolas Vasilache     if (failed(alloc))
9147fbf55c9SNicolas Vasilache       return failure();
9157fbf55c9SNicolas Vasilache 
9167fbf55c9SNicolas Vasilache     // Update destination operand.
9177fbf55c9SNicolas Vasilache     rewriter.updateRootInPlace(parallelInsertSliceOp, [&]() {
9187fbf55c9SNicolas Vasilache       parallelInsertSliceOp.getDestMutable().assign(*alloc);
9197fbf55c9SNicolas Vasilache     });
9207fbf55c9SNicolas Vasilache 
9217fbf55c9SNicolas Vasilache     return success();
9227fbf55c9SNicolas Vasilache   }
9237fbf55c9SNicolas Vasilache 
9247fbf55c9SNicolas Vasilache   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
9257fbf55c9SNicolas Vasilache                           const BufferizationOptions &options) const {
9267fbf55c9SNicolas Vasilache     OpBuilder::InsertionGuard g(rewriter);
9277fbf55c9SNicolas Vasilache     auto parallelInsertSliceOp = cast<ParallelInsertSliceOp>(op);
9287fbf55c9SNicolas Vasilache     ParallelCombiningOpInterface parallelCombiningParent =
9297fbf55c9SNicolas Vasilache         parallelInsertSliceOp.getParallelCombiningParent();
9307fbf55c9SNicolas Vasilache     Operation *parallelIteratingOp = parallelCombiningParent->getParentOp();
9317fbf55c9SNicolas Vasilache 
9327fbf55c9SNicolas Vasilache     // Get destination buffer.
9337fbf55c9SNicolas Vasilache     FailureOr<Value> destBuffer =
9347fbf55c9SNicolas Vasilache         getBuffer(rewriter, parallelInsertSliceOp.getDest(), options);
9357fbf55c9SNicolas Vasilache     if (failed(destBuffer))
9367fbf55c9SNicolas Vasilache       return failure();
9377fbf55c9SNicolas Vasilache 
9387fbf55c9SNicolas Vasilache     // Bufferize the ParallelInsertSliceOp outside of `parallelCombiningParent`.
9397fbf55c9SNicolas Vasilache     rewriter.setInsertionPoint(parallelCombiningParent);
9407fbf55c9SNicolas Vasilache     FailureOr<Value> srcBuffer =
9417fbf55c9SNicolas Vasilache         getBuffer(rewriter, parallelInsertSliceOp.getSource(), options);
9427fbf55c9SNicolas Vasilache     if (failed(srcBuffer))
9437fbf55c9SNicolas Vasilache       return failure();
9446c3c5f80SMatthias Springer 
9456c3c5f80SMatthias Springer     // Take a subview of the destination buffer.
9466c3c5f80SMatthias Springer     auto destBufferType = destBuffer->getType().cast<MemRefType>();
9476c3c5f80SMatthias Springer     auto subviewMemRefType =
9486c3c5f80SMatthias Springer         memref::SubViewOp::inferRankReducedResultType(
9496c3c5f80SMatthias Springer             parallelInsertSliceOp.getSourceType().getShape(), destBufferType,
9506c3c5f80SMatthias Springer             parallelInsertSliceOp.getMixedOffsets(),
9516c3c5f80SMatthias Springer             parallelInsertSliceOp.getMixedSizes(),
9526c3c5f80SMatthias Springer             parallelInsertSliceOp.getMixedStrides())
9536c3c5f80SMatthias Springer             .cast<MemRefType>();
9547fbf55c9SNicolas Vasilache     Value subview = rewriter.create<memref::SubViewOp>(
9556c3c5f80SMatthias Springer         parallelInsertSliceOp.getLoc(), subviewMemRefType, *destBuffer,
9567fbf55c9SNicolas Vasilache         parallelInsertSliceOp.getMixedOffsets(),
9577fbf55c9SNicolas Vasilache         parallelInsertSliceOp.getMixedSizes(),
9587fbf55c9SNicolas Vasilache         parallelInsertSliceOp.getMixedStrides());
9596c3c5f80SMatthias Springer 
9607fbf55c9SNicolas Vasilache     // This memcpy will fold away if everything bufferizes in-place.
9617fbf55c9SNicolas Vasilache     if (failed(options.createMemCpy(rewriter, parallelInsertSliceOp.getLoc(),
9627fbf55c9SNicolas Vasilache                                     *srcBuffer, subview)))
9637fbf55c9SNicolas Vasilache       return failure();
9647fbf55c9SNicolas Vasilache 
9657fbf55c9SNicolas Vasilache     // Replace all uses of parallelIteratingOp (just the corresponding result).
9667fbf55c9SNicolas Vasilache     rewriter.setInsertionPointAfter(parallelIteratingOp);
9677fbf55c9SNicolas Vasilache     Value toTensorOp =
9687fbf55c9SNicolas Vasilache         rewriter.create<ToTensorOp>(parallelIteratingOp->getLoc(), *destBuffer);
9697fbf55c9SNicolas Vasilache     // PerformConcurrentlyOp can have multiple ParallelInsertSliceOps.
9707fbf55c9SNicolas Vasilache     SmallVector<OpOperand *> resultUses = llvm::to_vector(
9717fbf55c9SNicolas Vasilache         llvm::map_range(parallelInsertSliceOp.getTiedOpResult().getUses(),
9727fbf55c9SNicolas Vasilache                         [](OpOperand &use) { return &use; }));
9737fbf55c9SNicolas Vasilache     for (OpOperand *use : resultUses) {
9747fbf55c9SNicolas Vasilache       rewriter.updateRootInPlace(use->getOwner(),
9757fbf55c9SNicolas Vasilache                                  [&]() { use->set(toTensorOp); });
9767fbf55c9SNicolas Vasilache     }
9777fbf55c9SNicolas Vasilache     rewriter.eraseOp(op);
9787fbf55c9SNicolas Vasilache     return success();
9797fbf55c9SNicolas Vasilache   }
9807fbf55c9SNicolas Vasilache 
9817fbf55c9SNicolas Vasilache   // TODO: This is copied from TensorInterfaceImpl.cpp. Find a way to share
9827fbf55c9SNicolas Vasilache   // the code.
9837fbf55c9SNicolas Vasilache   bool isNotConflicting(Operation *op, OpOperand *uRead,
9847fbf55c9SNicolas Vasilache                         OpOperand *uConflictingWrite,
9857fbf55c9SNicolas Vasilache                         const AnalysisState &state) const {
9867fbf55c9SNicolas Vasilache     Operation *readingOp = uRead->getOwner();
9877fbf55c9SNicolas Vasilache     Operation *conflictingWritingOp = uConflictingWrite->getOwner();
9887fbf55c9SNicolas Vasilache 
9897fbf55c9SNicolas Vasilache     // Special rules for matching ExtractSliceOp/InsertSliceOp pairs. If
9907fbf55c9SNicolas Vasilache     // uRead is an InsertSliceOp...
9917fbf55c9SNicolas Vasilache     if (auto insertSliceOp = dyn_cast<ParallelInsertSliceOp>(readingOp)) {
9927fbf55c9SNicolas Vasilache       // As an example, consider the following IR.
9937fbf55c9SNicolas Vasilache       //
9947fbf55c9SNicolas Vasilache       // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] }
9957fbf55c9SNicolas Vasilache       // %1 = linalg.fill %cst, %0 {inplace= [true] }
9967fbf55c9SNicolas Vasilache       // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1]
9977fbf55c9SNicolas Vasilache       //     {inplace= [true] }
9987fbf55c9SNicolas Vasilache 
9997fbf55c9SNicolas Vasilache       // TODO: Use insertSliceOp.getDestOpOperand etc. when available.
10007fbf55c9SNicolas Vasilache       if (uRead == &insertSliceOp->getOpOperand(1) /*dest*/ &&
10017fbf55c9SNicolas Vasilache           hasMatchingExtractSliceOp(state, uConflictingWrite->get(),
10027fbf55c9SNicolas Vasilache                                     insertSliceOp))
10037fbf55c9SNicolas Vasilache         // Case 1: The main insight is that InsertSliceOp reads only part of
10047fbf55c9SNicolas Vasilache         // the destination tensor. The overwritten area is not read. If
10057fbf55c9SNicolas Vasilache         // uConflictingWrite writes into exactly the memory location that is
10067fbf55c9SNicolas Vasilache         // being read by uRead, this is not a conflict.
10077fbf55c9SNicolas Vasilache         //
10087fbf55c9SNicolas Vasilache         // In the above example:
10097fbf55c9SNicolas Vasilache         // uRead             = OpOperand 1 (%t) of tensor.insert_slice
10107fbf55c9SNicolas Vasilache         // uConflictingWrite = OpOperand 1 (%0) of linalg.fill
10117fbf55c9SNicolas Vasilache         //
10127fbf55c9SNicolas Vasilache         // The read of %t does not conflict with the write of the FillOp
10137fbf55c9SNicolas Vasilache         // (same aliases!) because the area that the FillOp operates on is
10147fbf55c9SNicolas Vasilache         // exactly the one that is *not* read via %t.
10157fbf55c9SNicolas Vasilache         return true;
10167fbf55c9SNicolas Vasilache 
10177fbf55c9SNicolas Vasilache       if (uRead == &insertSliceOp->getOpOperand(0) /*source*/ &&
10187fbf55c9SNicolas Vasilache           uConflictingWrite == &insertSliceOp->getOpOperand(1) /*dest*/ &&
10197fbf55c9SNicolas Vasilache           hasMatchingExtractSliceOp(state, uRead->get(), insertSliceOp))
10207fbf55c9SNicolas Vasilache         // Case 2: The read of the source tensor and the write to the dest
10217fbf55c9SNicolas Vasilache         // tensor via an InsertSliceOp is not a conflict if the read is
10227fbf55c9SNicolas Vasilache         // reading exactly that part of an equivalent tensor that the
10237fbf55c9SNicolas Vasilache         // InsertSliceOp is writing.
10247fbf55c9SNicolas Vasilache         //
10257fbf55c9SNicolas Vasilache         // In the above example:
10267fbf55c9SNicolas Vasilache         // uRead             = OpOperand 0 (%1) of tensor.insert_slice
10277fbf55c9SNicolas Vasilache         // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice
10287fbf55c9SNicolas Vasilache         return true;
10297fbf55c9SNicolas Vasilache     }
10307fbf55c9SNicolas Vasilache 
10317fbf55c9SNicolas Vasilache     // If uConflictingWrite is an InsertSliceOp...
10327fbf55c9SNicolas Vasilache     if (auto insertSliceOp =
10337fbf55c9SNicolas Vasilache             dyn_cast<ParallelInsertSliceOp>(conflictingWritingOp))
10347fbf55c9SNicolas Vasilache       // As an example, consider the following IR.
10357fbf55c9SNicolas Vasilache       //
10367fbf55c9SNicolas Vasilache       // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] }
10377fbf55c9SNicolas Vasilache       // %1 = linalg.fill %cst, %0 {inplace= [true] }
10387fbf55c9SNicolas Vasilache       // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1]
10397fbf55c9SNicolas Vasilache       //     {inplace= [true] }
10407fbf55c9SNicolas Vasilache       // %3 = vector.transfer_read %1, %cst
10417fbf55c9SNicolas Vasilache       //
10427fbf55c9SNicolas Vasilache       // In the above example:
10437fbf55c9SNicolas Vasilache       // uRead             = OpOperand 0 (%1) of vector.transfer_read
10447fbf55c9SNicolas Vasilache       // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice
10457fbf55c9SNicolas Vasilache       // lastWrite         = %1
10467fbf55c9SNicolas Vasilache       //
10477fbf55c9SNicolas Vasilache       // This is not a conflict because the InsertSliceOp overwrites the
10487fbf55c9SNicolas Vasilache       // memory segment of %1 with the exact same data. (Effectively, there
10497fbf55c9SNicolas Vasilache       // is no memory write here.)
10507fbf55c9SNicolas Vasilache       if (uConflictingWrite == &insertSliceOp->getOpOperand(1) /*dest*/ &&
10517fbf55c9SNicolas Vasilache           state.areEquivalentBufferizedValues(uRead->get(),
10527fbf55c9SNicolas Vasilache                                               insertSliceOp.getSource()) &&
10537fbf55c9SNicolas Vasilache           hasMatchingExtractSliceOp(state, insertSliceOp.getSource(),
10547fbf55c9SNicolas Vasilache                                     insertSliceOp))
10557fbf55c9SNicolas Vasilache         return true;
10567fbf55c9SNicolas Vasilache 
10577fbf55c9SNicolas Vasilache     return false;
10587fbf55c9SNicolas Vasilache   }
10597fbf55c9SNicolas Vasilache };
10607fbf55c9SNicolas Vasilache 
106149e37000SMatthias Springer } // namespace
106249e37000SMatthias Springer } // namespace tensor
106349e37000SMatthias Springer } // namespace mlir
106449e37000SMatthias Springer 
106549e37000SMatthias Springer void mlir::tensor::registerBufferizableOpInterfaceExternalModels(
106649e37000SMatthias Springer     DialectRegistry &registry) {
106777eee579SRiver Riddle   registry.addExtension(+[](MLIRContext *ctx, tensor::TensorDialect *dialect) {
106877eee579SRiver Riddle     CastOp::attachInterface<CastOpInterface>(*ctx);
106977eee579SRiver Riddle     CollapseShapeOp::attachInterface<CollapseShapeOpInterface>(*ctx);
107077eee579SRiver Riddle     DimOp::attachInterface<DimOpInterface>(*ctx);
107177eee579SRiver Riddle     ExpandShapeOp::attachInterface<ExpandShapeOpInterface>(*ctx);
107277eee579SRiver Riddle     ExtractSliceOp::attachInterface<ExtractSliceOpInterface>(*ctx);
107377eee579SRiver Riddle     ExtractOp::attachInterface<ExtractOpInterface>(*ctx);
107477eee579SRiver Riddle     FromElementsOp::attachInterface<FromElementsOpInterface>(*ctx);
107577eee579SRiver Riddle     GenerateOp::attachInterface<GenerateOpInterface>(*ctx);
107677eee579SRiver Riddle     InsertOp::attachInterface<InsertOpInterface>(*ctx);
107777eee579SRiver Riddle     InsertSliceOp::attachInterface<InsertSliceOpInterface>(*ctx);
10787fbf55c9SNicolas Vasilache     ParallelInsertSliceOp::attachInterface<ParallelInsertSliceOpInterface>(
10797fbf55c9SNicolas Vasilache         *ctx);
108077eee579SRiver Riddle     RankOp::attachInterface<RankOpInterface>(*ctx);
1081e287d647SAshay Rane     ReshapeOp::attachInterface<ReshapeOpInterface>(*ctx);
10825f5f71e7SMatthias Springer 
10835f5f71e7SMatthias Springer     // Load additional dialects of which ops may get created.
10845f5f71e7SMatthias Springer     ctx->loadDialect<arith::ArithmeticDialect, scf::SCFDialect>();
108577eee579SRiver Riddle   });
108649e37000SMatthias Springer }
1087