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"
1049e37000SMatthias Springer #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h"
1149e37000SMatthias Springer #include "mlir/Dialect/MemRef/IR/MemRef.h"
1271bbb78bSMatthias Springer #include "mlir/Dialect/SCF/SCF.h"
1349e37000SMatthias Springer #include "mlir/Dialect/Tensor/IR/Tensor.h"
1449e37000SMatthias Springer #include "mlir/IR/Dialect.h"
1549e37000SMatthias Springer #include "mlir/IR/Operation.h"
1649e37000SMatthias Springer 
1749e37000SMatthias Springer using namespace mlir;
1849e37000SMatthias Springer using namespace mlir::bufferization;
1949e37000SMatthias Springer using namespace mlir::tensor;
2049e37000SMatthias Springer 
2149e37000SMatthias Springer namespace mlir {
2249e37000SMatthias Springer namespace tensor {
2349e37000SMatthias Springer namespace {
2449e37000SMatthias Springer 
2549e37000SMatthias Springer struct CastOpInterface
2649e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<CastOpInterface,
2749e37000SMatthias Springer                                                     tensor::CastOp> {
2849e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
299597b16aSMatthias Springer                               const AnalysisState &state) const {
3049e37000SMatthias Springer     return false;
3149e37000SMatthias Springer   }
3249e37000SMatthias Springer 
3349e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
349597b16aSMatthias Springer                                const AnalysisState &state) const {
3549e37000SMatthias Springer     return false;
3649e37000SMatthias Springer   }
3749e37000SMatthias Springer 
389597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
399597b16aSMatthias Springer                                             const AnalysisState &state) const {
40585a8a32SMatthias Springer     return {op->getResult(0)};
4149e37000SMatthias Springer   }
4249e37000SMatthias Springer 
4349e37000SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
449597b16aSMatthias Springer                                 const AnalysisState &state) const {
4549e37000SMatthias Springer     return BufferRelation::Equivalent;
4649e37000SMatthias Springer   }
4749e37000SMatthias Springer 
4849e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
499597b16aSMatthias Springer                           BufferizationState &state) const {
5049e37000SMatthias Springer     auto castOp = cast<tensor::CastOp>(op);
5149e37000SMatthias Springer 
5249e37000SMatthias Springer     // The result buffer still has the old (pre-cast) type.
5349e37000SMatthias Springer     FailureOr<Value> resultBuffer =
5449e37000SMatthias Springer         state.getBuffer(rewriter, castOp->getOpOperand(0) /*source*/);
5549e37000SMatthias Springer     if (failed(resultBuffer))
5649e37000SMatthias Springer       return failure();
5749e37000SMatthias Springer     auto sourceMemRefType = resultBuffer->getType().cast<BaseMemRefType>();
5849e37000SMatthias Springer     Attribute memorySpace = sourceMemRefType.getMemorySpace();
5949e37000SMatthias Springer     TensorType resultTensorType =
6049e37000SMatthias Springer         castOp.getResult().getType().cast<TensorType>();
6149e37000SMatthias Springer     MemRefLayoutAttrInterface layout;
6249e37000SMatthias Springer 
6349e37000SMatthias Springer     if (auto rankedMemRefType = sourceMemRefType.dyn_cast<MemRefType>())
6449e37000SMatthias Springer       if (resultTensorType.isa<RankedTensorType>())
6549e37000SMatthias Springer         layout = rankedMemRefType.getLayout();
6649e37000SMatthias Springer 
6749e37000SMatthias Springer     // Compute the new memref type.
6826852423SMatthias Springer     Type resultMemRefType = getMemRefType(resultTensorType, state.getOptions(),
6926852423SMatthias Springer                                           layout, memorySpace);
7049e37000SMatthias Springer 
7149e37000SMatthias Springer     // Replace the op with a memref.cast.
7249e37000SMatthias Springer     assert(memref::CastOp::areCastCompatible(resultBuffer->getType(),
7349e37000SMatthias Springer                                              resultMemRefType) &&
7449e37000SMatthias Springer            "CallOp::bufferize: cast incompatible");
7549e37000SMatthias Springer     replaceOpWithNewBufferizedOp<memref::CastOp>(rewriter, op, resultMemRefType,
7649e37000SMatthias Springer                                                  *resultBuffer);
7749e37000SMatthias Springer 
7849e37000SMatthias Springer     return success();
7949e37000SMatthias Springer   }
8049e37000SMatthias Springer };
8149e37000SMatthias Springer 
82e6f69161SMatthias Springer /// Bufferization of tensor.collapse_shape. Replace with memref.collapse_shape.
83e6f69161SMatthias Springer struct CollapseShapeOpInterface
84e6f69161SMatthias Springer     : public BufferizableOpInterface::ExternalModel<CollapseShapeOpInterface,
85e6f69161SMatthias Springer                                                     tensor::CollapseShapeOp> {
86e6f69161SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
879597b16aSMatthias Springer                               const AnalysisState &state) const {
88e6f69161SMatthias Springer     return false;
89e6f69161SMatthias Springer   }
90e6f69161SMatthias Springer 
91e6f69161SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
929597b16aSMatthias Springer                                const AnalysisState &state) const {
93e6f69161SMatthias Springer     return false;
94e6f69161SMatthias Springer   }
95e6f69161SMatthias Springer 
969597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
979597b16aSMatthias Springer                                             const AnalysisState &state) const {
98e6f69161SMatthias Springer     if (&opOperand == &op->getOpOperand(0) /*src*/)
99e6f69161SMatthias Springer       return {op->getOpResult(0)};
100e6f69161SMatthias Springer     return {};
101e6f69161SMatthias Springer   }
102e6f69161SMatthias Springer 
103e6f69161SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
1049597b16aSMatthias Springer                                 const AnalysisState &state) const {
105e6f69161SMatthias Springer     return BufferRelation::Equivalent;
106e6f69161SMatthias Springer   }
107e6f69161SMatthias Springer 
108e6f69161SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
1099597b16aSMatthias Springer                           BufferizationState &state) const {
110e6f69161SMatthias Springer     auto collapseShapeOp = cast<tensor::CollapseShapeOp>(op);
11151df6238SMatthias Springer     RankedTensorType tensorResultType = collapseShapeOp.getResultType();
112*d7a9bf91SMatthias Springer     OpOperand &srcOperand = collapseShapeOp->getOpOperand(0) /*src*/;
113*d7a9bf91SMatthias Springer     auto bufferType = state.getBufferType(srcOperand).cast<MemRefType>();
11451df6238SMatthias Springer 
11551df6238SMatthias Springer     if (tensorResultType.getRank() == 0) {
11651df6238SMatthias Springer       // 0-d collapses must go through a different op builder.
117*d7a9bf91SMatthias Springer       Value buffer = *state.getBuffer(rewriter, srcOperand);
11873c0333dSMatthias Springer       MemRefType resultType;
11973c0333dSMatthias Springer 
12073c0333dSMatthias Springer       if (bufferType.getLayout().isIdentity()) {
12173c0333dSMatthias Springer         // Standard layout: result type has no offset.
12251df6238SMatthias Springer         MemRefLayoutAttrInterface layout;
12373c0333dSMatthias Springer         resultType = MemRefType::get({}, tensorResultType.getElementType(),
12451df6238SMatthias Springer                                      layout, bufferType.getMemorySpace());
12573c0333dSMatthias Springer       } else {
12673c0333dSMatthias Springer         // Source memref has a layout map: result type has the same offset as
12773c0333dSMatthias Springer         // the source type.
12873c0333dSMatthias Springer         SmallVector<int64_t> strides;
12973c0333dSMatthias Springer         int64_t offset;
13073c0333dSMatthias Springer         if (failed(getStridesAndOffset(bufferType, strides, offset)))
13173c0333dSMatthias Springer           return failure();
13273c0333dSMatthias Springer         AffineMap resultLayout =
13373c0333dSMatthias Springer             makeStridedLinearLayoutMap({}, offset, op->getContext());
13473c0333dSMatthias Springer         resultType =
13573c0333dSMatthias Springer             MemRefType::get({}, tensorResultType.getElementType(), resultLayout,
13673c0333dSMatthias Springer                             bufferType.getMemorySpaceAsInt());
13773c0333dSMatthias Springer       }
13873c0333dSMatthias Springer 
139e6f69161SMatthias Springer       replaceOpWithNewBufferizedOp<memref::CollapseShapeOp>(
140e6f69161SMatthias Springer           rewriter, op, resultType, buffer, collapseShapeOp.reassociation());
141e6f69161SMatthias Springer       return success();
142e6f69161SMatthias Springer     }
14351df6238SMatthias Springer 
144*d7a9bf91SMatthias Springer     // If the dims are not collapsible (due to an incompatible source layout
145*d7a9bf91SMatthias Springer     // map), force an out-of-place bufferization, i.e., a buffer copy. This
146*d7a9bf91SMatthias Springer     // newly allocated buffer will have no layout map and thus be collapsible.
147*d7a9bf91SMatthias Springer     bool canBeCollapsed = memref::ExpandShapeOp::isGuaranteedCollapsible(
148*d7a9bf91SMatthias Springer         bufferType, collapseShapeOp.getReassociationIndices());
149*d7a9bf91SMatthias Springer     Optional<BufferizationState::ForceInPlacability> overrideInPlace =
150*d7a9bf91SMatthias Springer         canBeCollapsed
151*d7a9bf91SMatthias Springer             ? None
152*d7a9bf91SMatthias Springer             : Optional<BufferizationState::ForceInPlacability>(
153*d7a9bf91SMatthias Springer                   BufferizationState::ForceInPlacability::FORCE_OUT_OF_PLACE);
154*d7a9bf91SMatthias Springer     Value buffer = *state.getBuffer(rewriter, srcOperand, overrideInPlace);
155*d7a9bf91SMatthias Springer 
15651df6238SMatthias Springer     // Result type is inferred by the builder.
15751df6238SMatthias Springer     replaceOpWithNewBufferizedOp<memref::CollapseShapeOp>(
15851df6238SMatthias Springer         rewriter, op, buffer, collapseShapeOp.getReassociationIndices());
15951df6238SMatthias Springer     return success();
16051df6238SMatthias Springer   }
161e6f69161SMatthias Springer };
162e6f69161SMatthias Springer 
16349e37000SMatthias Springer /// Bufferization of tensor.dim. Replace with memref.dim.
16449e37000SMatthias Springer struct DimOpInterface
16549e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<DimOpInterface,
16649e37000SMatthias Springer                                                     tensor::DimOp> {
16749e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
1689597b16aSMatthias Springer                               const AnalysisState &state) const {
16949e37000SMatthias Springer     return true;
17049e37000SMatthias Springer   }
17149e37000SMatthias Springer 
17249e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
1739597b16aSMatthias Springer                                const AnalysisState &state) const {
17449e37000SMatthias Springer     return false;
17549e37000SMatthias Springer   }
17649e37000SMatthias Springer 
1779597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
1789597b16aSMatthias Springer                                             const AnalysisState &state) const {
179585a8a32SMatthias Springer     return {};
18049e37000SMatthias Springer   }
18149e37000SMatthias Springer 
18249e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
1839597b16aSMatthias Springer                           BufferizationState &state) const {
18449e37000SMatthias Springer     auto dimOp = cast<tensor::DimOp>(op);
18549e37000SMatthias Springer     Value v = *state.getBuffer(rewriter, dimOp->getOpOperand(0) /*source*/);
18649e37000SMatthias Springer     replaceOpWithNewBufferizedOp<memref::DimOp>(rewriter, op, v, dimOp.index());
18749e37000SMatthias Springer     return success();
18849e37000SMatthias Springer   }
18949e37000SMatthias Springer };
19049e37000SMatthias Springer 
191e6f69161SMatthias Springer /// Bufferization of tensor.expand_shape. Replace with memref.expand_shape.
192e6f69161SMatthias Springer struct ExpandShapeOpInterface
193e6f69161SMatthias Springer     : public BufferizableOpInterface::ExternalModel<ExpandShapeOpInterface,
194e6f69161SMatthias Springer                                                     tensor::ExpandShapeOp> {
195e6f69161SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
1969597b16aSMatthias Springer                               const AnalysisState &state) const {
197e6f69161SMatthias Springer     return false;
198e6f69161SMatthias Springer   }
199e6f69161SMatthias Springer 
200e6f69161SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
2019597b16aSMatthias Springer                                const AnalysisState &state) const {
202e6f69161SMatthias Springer     return false;
203e6f69161SMatthias Springer   }
204e6f69161SMatthias Springer 
2059597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
2069597b16aSMatthias Springer                                             const AnalysisState &state) const {
207e6f69161SMatthias Springer     if (&opOperand == &op->getOpOperand(0) /*src*/)
208e6f69161SMatthias Springer       return {op->getOpResult(0)};
209e6f69161SMatthias Springer     return {};
210e6f69161SMatthias Springer   }
211e6f69161SMatthias Springer 
212e6f69161SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
2139597b16aSMatthias Springer                                 const AnalysisState &state) const {
214e6f69161SMatthias Springer     return BufferRelation::Equivalent;
215e6f69161SMatthias Springer   }
216e6f69161SMatthias Springer 
217e6f69161SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
2189597b16aSMatthias Springer                           BufferizationState &state) const {
219e6f69161SMatthias Springer     auto expandShapeOp = cast<tensor::ExpandShapeOp>(op);
22051df6238SMatthias Springer     auto tensorResultType = expandShapeOp.getResultType();
221e6f69161SMatthias Springer     Value buffer =
222e6f69161SMatthias Springer         *state.getBuffer(rewriter, expandShapeOp->getOpOperand(0) /*src*/);
22351df6238SMatthias Springer 
22451df6238SMatthias Springer     // Memref result type is inferred by the builder based on reassociation
22551df6238SMatthias Springer     // indices and result shape.
226e6f69161SMatthias Springer     replaceOpWithNewBufferizedOp<memref::ExpandShapeOp>(
22751df6238SMatthias Springer         rewriter, op, tensorResultType.getShape(), buffer,
22851df6238SMatthias Springer         expandShapeOp.getReassociationIndices());
229e6f69161SMatthias Springer     return success();
230e6f69161SMatthias Springer   }
231e6f69161SMatthias Springer };
232e6f69161SMatthias Springer 
23349e37000SMatthias Springer /// Bufferization of tensor.extract_slice. Replace with memref.subview.
23449e37000SMatthias Springer struct ExtractSliceOpInterface
23549e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<ExtractSliceOpInterface,
23649e37000SMatthias Springer                                                     tensor::ExtractSliceOp> {
23749e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
2389597b16aSMatthias Springer                               const AnalysisState &state) const {
23949e37000SMatthias Springer     return false;
24049e37000SMatthias Springer   }
24149e37000SMatthias Springer 
24249e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
2439597b16aSMatthias Springer                                const AnalysisState &state) const {
24449e37000SMatthias Springer     return false;
24549e37000SMatthias Springer   }
24649e37000SMatthias Springer 
2479597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
2489597b16aSMatthias Springer                                             const AnalysisState &state) const {
249585a8a32SMatthias Springer     if (&opOperand == &op->getOpOperand(0) /*source*/)
250585a8a32SMatthias Springer       return {op->getOpResult(0)};
251585a8a32SMatthias Springer     return {};
25249e37000SMatthias Springer   }
25349e37000SMatthias Springer 
25449e37000SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
2559597b16aSMatthias Springer                                 const AnalysisState &state) const {
25649e37000SMatthias Springer     return BufferRelation::None;
25749e37000SMatthias Springer   }
25849e37000SMatthias Springer 
25949e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
2609597b16aSMatthias Springer                           BufferizationState &state) const {
26149e37000SMatthias Springer     auto extractSliceOp = cast<tensor::ExtractSliceOp>(op);
26249e37000SMatthias Springer     Location loc = extractSliceOp.getLoc();
263*d7a9bf91SMatthias Springer 
264*d7a9bf91SMatthias Springer     // Even if this op was decided to bufferize out-of-place, do not insert the
265*d7a9bf91SMatthias Springer     // buffer copy yet. This is done later in this function.
26649e37000SMatthias Springer     Value srcMemref =
26749e37000SMatthias Springer         *state.getBuffer(rewriter, extractSliceOp->getOpOperand(0) /*source*/,
268*d7a9bf91SMatthias Springer                          BufferizationState::ForceInPlacability::FORCE_INPLACE);
26949e37000SMatthias Springer     auto srcMemrefType = srcMemref.getType().cast<MemRefType>();
27049e37000SMatthias Springer     auto dstTensorType =
27149e37000SMatthias Springer         extractSliceOp.result().getType().cast<RankedTensorType>();
27249e37000SMatthias Springer 
27349e37000SMatthias Springer     // If not inplaceable, alloc.
2749597b16aSMatthias Springer     bool inplace =
2759597b16aSMatthias Springer         state.getAnalysisState().isInPlace(extractSliceOp->getOpOperand(0));
27649e37000SMatthias Springer     Value alloc;
27749e37000SMatthias Springer     if (!inplace) {
27849e37000SMatthias Springer       FailureOr<Value> allocOrFailure =
27905e0495fSMatthias Springer           state.createAlloc(rewriter, loc, extractSliceOp.result());
28049e37000SMatthias Springer       if (failed(allocOrFailure))
28149e37000SMatthias Springer         return failure();
28249e37000SMatthias Springer       alloc = *allocOrFailure;
28349e37000SMatthias Springer     }
28449e37000SMatthias Springer 
28549e37000SMatthias Springer     // Expand offsets, sizes and strides to the full rank to handle the
28649e37000SMatthias Springer     // rank-reducing case.
28749e37000SMatthias Springer     SmallVector<OpFoldResult> mixedOffsets = extractSliceOp.getMixedOffsets();
28849e37000SMatthias Springer     SmallVector<OpFoldResult> mixedSizes = extractSliceOp.getMixedSizes();
28949e37000SMatthias Springer     SmallVector<OpFoldResult> mixedStrides = extractSliceOp.getMixedStrides();
29049e37000SMatthias Springer     OffsetSizeAndStrideOpInterface::expandToRank(
29149e37000SMatthias Springer         srcMemref, mixedOffsets, mixedSizes, mixedStrides,
29249e37000SMatthias Springer         [&](Value target, int64_t dim) -> OpFoldResult {
29349e37000SMatthias Springer           auto shapedType = target.getType().cast<ShapedType>();
29449e37000SMatthias Springer           if (shapedType.isDynamicDim(dim))
29549e37000SMatthias Springer             return rewriter.create<memref::DimOp>(loc, target, dim).result();
29649e37000SMatthias Springer           return rewriter.getIndexAttr(shapedType.getDimSize(dim));
29749e37000SMatthias Springer         });
29849e37000SMatthias Springer     // Bufferize to subview.
29949e37000SMatthias Springer     auto subviewMemRefType = memref::SubViewOp::inferRankReducedResultType(
30049e37000SMatthias Springer                                  dstTensorType.getRank(), srcMemrefType,
30149e37000SMatthias Springer                                  mixedOffsets, mixedSizes, mixedStrides)
30249e37000SMatthias Springer                                  .cast<MemRefType>();
30349e37000SMatthias Springer     Value subView = rewriter.create<memref::SubViewOp>(
30449e37000SMatthias Springer         loc, subviewMemRefType, srcMemref, mixedOffsets, mixedSizes,
30549e37000SMatthias Springer         mixedStrides);
30649e37000SMatthias Springer 
30749e37000SMatthias Springer     // If not inplaceable, copy.
30849e37000SMatthias Springer     if (!inplace) {
30949e37000SMatthias Springer       // Do not copy if the copied data is never read.
3109597b16aSMatthias Springer       if (state.getAnalysisState().isValueRead(extractSliceOp.result()))
31149e37000SMatthias Springer         if (failed(createMemCpy(rewriter, extractSliceOp.getLoc(), subView,
31249e37000SMatthias Springer                                 alloc, state.getOptions())))
31349e37000SMatthias Springer           return failure();
31449e37000SMatthias Springer       subView = alloc;
31549e37000SMatthias Springer     }
31649e37000SMatthias Springer 
31749e37000SMatthias Springer     replaceOpWithBufferizedValues(rewriter, op, subView);
31849e37000SMatthias Springer     return success();
31949e37000SMatthias Springer   }
32049e37000SMatthias Springer };
32149e37000SMatthias Springer 
32249e37000SMatthias Springer /// Bufferization of tensor.extract. Replace with memref.load.
32349e37000SMatthias Springer struct ExtractOpInterface
32449e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<ExtractOpInterface,
32549e37000SMatthias Springer                                                     tensor::ExtractOp> {
32649e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
3279597b16aSMatthias Springer                               const AnalysisState &state) const {
32849e37000SMatthias Springer     return true;
32949e37000SMatthias Springer   }
33049e37000SMatthias Springer 
33149e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
3329597b16aSMatthias Springer                                const AnalysisState &state) const {
33349e37000SMatthias Springer     return false;
33449e37000SMatthias Springer   }
33549e37000SMatthias Springer 
3369597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
3379597b16aSMatthias Springer                                             const AnalysisState &state) const {
338585a8a32SMatthias Springer     return {};
33949e37000SMatthias Springer   }
34049e37000SMatthias Springer 
34149e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
3429597b16aSMatthias Springer                           BufferizationState &state) const {
34349e37000SMatthias Springer     auto extractOp = cast<tensor::ExtractOp>(op);
34449e37000SMatthias Springer     Value srcMemref =
34549e37000SMatthias Springer         *state.getBuffer(rewriter, extractOp->getOpOperand(0) /*tensor*/);
34649e37000SMatthias Springer     replaceOpWithNewBufferizedOp<memref::LoadOp>(rewriter, op, srcMemref,
34749e37000SMatthias Springer                                                  extractOp.indices());
34849e37000SMatthias Springer     return success();
34949e37000SMatthias Springer   }
35049e37000SMatthias Springer };
35149e37000SMatthias Springer 
352d581c94dSMatthias Springer // Implements backtracking to traverse indices of the output buffer while
353d581c94dSMatthias Springer // iterating over op.elements().
354d581c94dSMatthias Springer static void createStores(RewriterBase &rewriter, Location loc, int dim,
355d581c94dSMatthias Springer                          Value buffer, ArrayRef<int64_t> shape,
356d581c94dSMatthias Springer                          ArrayRef<Value> constants,
357d581c94dSMatthias Springer                          OperandRange::iterator &elementIt,
358d581c94dSMatthias Springer                          SmallVectorImpl<Value> &indices) {
359d581c94dSMatthias Springer   if (dim == static_cast<int>(shape.size()) - 1) {
360d581c94dSMatthias Springer     for (int i = 0; i < shape.back(); ++i) {
361d581c94dSMatthias Springer       indices.back() = constants[i];
362d581c94dSMatthias Springer       rewriter.create<memref::StoreOp>(loc, *elementIt, buffer, indices);
363d581c94dSMatthias Springer       ++elementIt;
364d581c94dSMatthias Springer     }
365d581c94dSMatthias Springer     return;
366d581c94dSMatthias Springer   }
367d581c94dSMatthias Springer   for (int i = 0; i < shape[dim]; ++i) {
368d581c94dSMatthias Springer     indices[dim] = constants[i];
369d581c94dSMatthias Springer     createStores(rewriter, loc, dim + 1, buffer, shape, constants, elementIt,
370d581c94dSMatthias Springer                  indices);
371d581c94dSMatthias Springer   }
372d581c94dSMatthias Springer }
373d581c94dSMatthias Springer 
374d581c94dSMatthias Springer /// Bufferization of tensor.from_elements.
375d581c94dSMatthias Springer struct FromElementsOpInterface
376d581c94dSMatthias Springer     : public BufferizableOpInterface::ExternalModel<FromElementsOpInterface,
377d581c94dSMatthias Springer                                                     tensor::FromElementsOp> {
378d581c94dSMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
3799597b16aSMatthias Springer                           BufferizationState &state) const {
380d581c94dSMatthias Springer     auto fromElementsOp = cast<tensor::FromElementsOp>(op);
381d581c94dSMatthias 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();
386d581c94dSMatthias Springer     FailureOr<Value> maybeBuffer =
3879e24f0f4SMatthias Springer         state.createAlloc(rewriter, loc, fromElementsOp.result());
388d581c94dSMatthias Springer     if (failed(maybeBuffer))
389d581c94dSMatthias Springer       return failure();
390d581c94dSMatthias Springer     Value buffer = *maybeBuffer;
391d581c94dSMatthias Springer 
392d581c94dSMatthias Springer     // Case: tensor<0xelem_type>.
393d581c94dSMatthias Springer     if (fromElementsOp.elements().empty()) {
394d581c94dSMatthias Springer       replaceOpWithBufferizedValues(rewriter, op, buffer);
395d581c94dSMatthias Springer       return success();
396d581c94dSMatthias Springer     }
397d581c94dSMatthias Springer 
398d581c94dSMatthias Springer     // Case: tensor<elem_type>.
399d581c94dSMatthias Springer     if (shape.empty()) {
400d581c94dSMatthias Springer       rewriter.create<memref::StoreOp>(loc, fromElementsOp.elements().front(),
401d581c94dSMatthias Springer                                        buffer);
402d581c94dSMatthias Springer       replaceOpWithBufferizedValues(rewriter, op, buffer);
403d581c94dSMatthias Springer       return success();
404d581c94dSMatthias Springer     }
405d581c94dSMatthias Springer 
406d581c94dSMatthias Springer     // Create constants for the range of possible indices [0, max{shape_i}).
407d581c94dSMatthias Springer     auto maxDim = *std::max_element(shape.begin(), shape.end());
408d581c94dSMatthias Springer     SmallVector<Value, 2> constants;
409d581c94dSMatthias Springer     constants.reserve(maxDim);
410d581c94dSMatthias Springer     for (int i = 0; i < maxDim; ++i)
411d581c94dSMatthias Springer       constants.push_back(rewriter.create<arith::ConstantIndexOp>(loc, i));
412d581c94dSMatthias Springer 
413d581c94dSMatthias Springer     // Traverse all `elements` and create `memref.store` ops.
414d581c94dSMatthias Springer     auto elementIt = fromElementsOp.elements().begin();
415d581c94dSMatthias Springer     SmallVector<Value, 2> indices(tensorType.getRank(), constants[0]);
416d581c94dSMatthias Springer     createStores(rewriter, loc, /*dim=*/0, buffer, shape, constants, elementIt,
417d581c94dSMatthias Springer                  indices);
418d581c94dSMatthias Springer 
419d581c94dSMatthias Springer     replaceOpWithBufferizedValues(rewriter, op, buffer);
420d581c94dSMatthias Springer     return success();
421d581c94dSMatthias Springer   }
422d581c94dSMatthias Springer };
423d581c94dSMatthias Springer 
42471bbb78bSMatthias Springer /// Bufferization of tensor.generate.
42571bbb78bSMatthias Springer struct GenerateOpInterface
42671bbb78bSMatthias Springer     : public BufferizableOpInterface::ExternalModel<GenerateOpInterface,
42771bbb78bSMatthias Springer                                                     tensor::GenerateOp> {
42871bbb78bSMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
4299597b16aSMatthias Springer                           BufferizationState &state) const {
43071bbb78bSMatthias Springer     auto generateOp = cast<tensor::GenerateOp>(op);
43171bbb78bSMatthias Springer 
43271bbb78bSMatthias Springer     // Allocate memory.
43371bbb78bSMatthias Springer     Location loc = op->getLoc();
43471bbb78bSMatthias Springer     MemRefType memrefType =
43571bbb78bSMatthias Springer         getContiguousMemRefType(generateOp.getType().cast<RankedTensorType>());
4369e24f0f4SMatthias Springer     FailureOr<Value> maybeResult =
4379e24f0f4SMatthias Springer         state.createAlloc(rewriter, loc, generateOp.result());
43871bbb78bSMatthias Springer     if (failed(maybeResult))
43971bbb78bSMatthias Springer       return failure();
44071bbb78bSMatthias Springer     Value result = *maybeResult;
44171bbb78bSMatthias Springer 
44271bbb78bSMatthias Springer     // Collect loop bounds.
44371bbb78bSMatthias Springer     int64_t rank = memrefType.getRank();
44471bbb78bSMatthias Springer     Value zero = rewriter.create<arith::ConstantIndexOp>(loc, 0);
44571bbb78bSMatthias Springer     Value one = rewriter.create<arith::ConstantIndexOp>(loc, 1);
44671bbb78bSMatthias Springer     SmallVector<Value, 4> lowerBounds(rank, zero);
44771bbb78bSMatthias Springer     SmallVector<Value, 4> steps(rank, one);
44871bbb78bSMatthias Springer     SmallVector<Value, 4> upperBounds;
44971bbb78bSMatthias Springer     int nextDynamicIndex = 0;
45071bbb78bSMatthias Springer     for (int i = 0; i < rank; i++) {
45171bbb78bSMatthias Springer       Value upperBound = memrefType.isDynamicDim(i)
45271bbb78bSMatthias Springer                              ? generateOp.dynamicExtents()[nextDynamicIndex++]
45371bbb78bSMatthias Springer                              : rewriter.create<arith::ConstantIndexOp>(
45471bbb78bSMatthias Springer                                    loc, memrefType.getDimSize(i));
45571bbb78bSMatthias Springer       upperBounds.push_back(upperBound);
45671bbb78bSMatthias Springer     }
45771bbb78bSMatthias Springer 
45871bbb78bSMatthias Springer     // Generate tensor elements with a parallel loop that stores into
45971bbb78bSMatthias Springer     // each element of the resulting memref. We use mergeBlockBefore to "move"
46071bbb78bSMatthias Springer     // this op's body into the scf.parallel's body.
46171bbb78bSMatthias Springer     auto parallel =
46271bbb78bSMatthias Springer         rewriter.create<scf::ParallelOp>(loc, lowerBounds, upperBounds, steps);
46371bbb78bSMatthias Springer     Block *parallelBody = parallel.getBody();
46471bbb78bSMatthias Springer     rewriter.mergeBlockBefore(generateOp.getBody(),
46571bbb78bSMatthias Springer                               parallelBody->getTerminator(),
46671bbb78bSMatthias Springer                               parallelBody->getArguments());
46771bbb78bSMatthias Springer     // Replace the inlined yield op with a store op. The scf.parallel's builder
46871bbb78bSMatthias Springer     // already populated an scf.yield at the end, so we don't need to worry
46971bbb78bSMatthias Springer     // about creating that.
47071bbb78bSMatthias Springer     Operation *elementYield = parallelBody->getTerminator()->getPrevNode();
47171bbb78bSMatthias Springer     rewriter.setInsertionPointAfter(elementYield);
47271bbb78bSMatthias Springer     rewriter.replaceOpWithNewOp<memref::StoreOp>(
47371bbb78bSMatthias Springer         elementYield, elementYield->getOperands()[0], result,
47471bbb78bSMatthias Springer         parallelBody->getArguments());
47571bbb78bSMatthias Springer 
47671bbb78bSMatthias Springer     replaceOpWithBufferizedValues(rewriter, op, result);
47771bbb78bSMatthias Springer     return success();
47871bbb78bSMatthias Springer   }
47971bbb78bSMatthias Springer };
48071bbb78bSMatthias Springer 
48149e37000SMatthias Springer /// Bufferization of tensor.insert. Replace with memref.store.
48249e37000SMatthias Springer struct InsertOpInterface
48349e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<InsertOpInterface,
48449e37000SMatthias Springer                                                     tensor::InsertOp> {
48549e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
4869597b16aSMatthias Springer                               const AnalysisState &state) const {
48749e37000SMatthias Springer     return true;
48849e37000SMatthias Springer   }
48949e37000SMatthias Springer 
49049e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
4919597b16aSMatthias Springer                                const AnalysisState &state) const {
49249e37000SMatthias Springer     return true;
49349e37000SMatthias Springer   }
49449e37000SMatthias Springer 
4959597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
4969597b16aSMatthias Springer                                             const AnalysisState &state) const {
49749e37000SMatthias Springer     assert(&opOperand == &op->getOpOperand(1) /*dest*/ &&
49849e37000SMatthias Springer            "expected dest OpOperand");
499585a8a32SMatthias Springer     return {op->getOpResult(0)};
50049e37000SMatthias Springer   }
50149e37000SMatthias Springer 
50249e37000SMatthias Springer   SmallVector<OpOperand *>
50349e37000SMatthias Springer   getAliasingOpOperand(Operation *op, OpResult opResult,
5049597b16aSMatthias Springer                        const AnalysisState &state) const {
50549e37000SMatthias Springer     return {&op->getOpOperand(1) /*dest*/};
50649e37000SMatthias Springer   }
50749e37000SMatthias Springer 
50849e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
5099597b16aSMatthias Springer                           BufferizationState &state) const {
51049e37000SMatthias Springer     auto insertOp = cast<tensor::InsertOp>(op);
51149e37000SMatthias Springer     FailureOr<Value> destMemref =
51249e37000SMatthias Springer         state.getBuffer(rewriter, insertOp->getOpOperand(1) /*dest*/);
51349e37000SMatthias Springer     if (failed(destMemref))
51449e37000SMatthias Springer       return failure();
51549e37000SMatthias Springer     rewriter.create<memref::StoreOp>(insertOp.getLoc(), insertOp.scalar(),
51649e37000SMatthias Springer                                      *destMemref, insertOp.indices());
51749e37000SMatthias Springer     replaceOpWithBufferizedValues(rewriter, op, *destMemref);
51849e37000SMatthias Springer     return success();
51949e37000SMatthias Springer   }
52049e37000SMatthias Springer 
52149e37000SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
5229597b16aSMatthias Springer                                 const AnalysisState &state) const {
52349e37000SMatthias Springer     return BufferRelation::Equivalent;
52449e37000SMatthias Springer   }
52549e37000SMatthias Springer };
52649e37000SMatthias Springer 
52749e37000SMatthias Springer /// Return true if the (ExtractSliceOp, InsertSliceOp) pair match (i.e.
52849e37000SMatthias Springer /// equivalent operand / result and same offset/sizes/strides specification).
52949e37000SMatthias Springer ///
53049e37000SMatthias Springer /// This is one particular type of relationship between ops on tensors that
53149e37000SMatthias Springer /// reduce to an equivalence on buffers. This should be generalized and
53249e37000SMatthias Springer /// exposed as interfaces on the proper types.
5339597b16aSMatthias Springer static bool areEquivalentExtractSliceOps(const AnalysisState &state,
53449e37000SMatthias Springer                                          ExtractSliceOp st, InsertSliceOp sti) {
53549e37000SMatthias Springer   if (!st || !sti)
53649e37000SMatthias Springer     return false;
53749e37000SMatthias Springer   if (sti != sti &&
53849e37000SMatthias Springer       !state.areEquivalentBufferizedValues(st.source(), sti.dest()))
53949e37000SMatthias Springer     return false;
54049e37000SMatthias Springer   if (!sameOffsetsSizesAndStrides(st, sti, isEqualConstantIntOrValue))
54149e37000SMatthias Springer     return false;
54249e37000SMatthias Springer   return true;
54349e37000SMatthias Springer }
54449e37000SMatthias Springer 
54549e37000SMatthias Springer /// Return true if `value` is originating from an ExtractSliceOp that matches
54649e37000SMatthias Springer /// the given InsertSliceOp.
5479597b16aSMatthias Springer static bool hasMatchingExtractSliceOp(const AnalysisState &state, Value value,
5489597b16aSMatthias Springer                                       InsertSliceOp insertOp) {
54949e37000SMatthias Springer   auto condition = [&](Value val) {
55049e37000SMatthias Springer     if (auto extractOp = val.getDefiningOp<ExtractSliceOp>())
55149e37000SMatthias Springer       if (areEquivalentExtractSliceOps(state, extractOp, insertOp))
55249e37000SMatthias Springer         return true;
55349e37000SMatthias Springer     return false;
55449e37000SMatthias Springer   };
55549e37000SMatthias Springer 
55649e37000SMatthias Springer   return llvm::all_of(state.findValueInReverseUseDefChain(value, condition),
55749e37000SMatthias Springer                       condition);
55849e37000SMatthias Springer }
55949e37000SMatthias Springer 
56049e37000SMatthias Springer /// Bufferization of tensor.insert_slice. Replace with a memory copy. Under
56149e37000SMatthias Springer /// certain circumstances, this op can also be a no-op.
56249e37000SMatthias Springer struct InsertSliceOpInterface
56349e37000SMatthias Springer     : public BufferizableOpInterface::ExternalModel<InsertSliceOpInterface,
56449e37000SMatthias Springer                                                     tensor::InsertSliceOp> {
56549e37000SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
5669597b16aSMatthias Springer                               const AnalysisState &state) const {
56749e37000SMatthias Springer     return true;
56849e37000SMatthias Springer   }
56949e37000SMatthias Springer 
57049e37000SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
5719597b16aSMatthias Springer                                const AnalysisState &state) const {
57249e37000SMatthias Springer     return &opOperand == &op->getOpOperand(1) /*dest*/;
57349e37000SMatthias Springer   }
57449e37000SMatthias Springer 
5759597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
5769597b16aSMatthias Springer                                             const AnalysisState &state) const {
577585a8a32SMatthias Springer     if (&opOperand == &op->getOpOperand(1) /*dest*/)
578585a8a32SMatthias Springer       return {op->getResult(0)};
579585a8a32SMatthias Springer     return {};
58049e37000SMatthias Springer   }
58149e37000SMatthias Springer 
58249e37000SMatthias Springer   BufferRelation bufferRelation(Operation *op, OpResult opResult,
5839597b16aSMatthias Springer                                 const AnalysisState &state) const {
58449e37000SMatthias Springer     return BufferRelation::Equivalent;
58549e37000SMatthias Springer   }
58649e37000SMatthias Springer 
58749e37000SMatthias Springer   bool isNotConflicting(Operation *op, OpOperand *uRead,
58849e37000SMatthias Springer                         OpOperand *uConflictingWrite,
5899597b16aSMatthias Springer                         const AnalysisState &state) const {
59049e37000SMatthias Springer     Operation *readingOp = uRead->getOwner();
59149e37000SMatthias Springer     Operation *conflictingWritingOp = uConflictingWrite->getOwner();
59249e37000SMatthias Springer 
59349e37000SMatthias Springer     // Special rules for matching ExtractSliceOp/InsertSliceOp pairs. If
59449e37000SMatthias Springer     // uRead is an InsertSliceOp...
59549e37000SMatthias Springer     if (auto insertSliceOp = dyn_cast<InsertSliceOp>(readingOp)) {
59649e37000SMatthias Springer       // As an example, consider the following IR.
59749e37000SMatthias Springer       //
59849e37000SMatthias Springer       // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] }
59949e37000SMatthias Springer       // %1 = linalg.fill %cst, %0 {inplace= [true] }
60049e37000SMatthias Springer       // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1]
60149e37000SMatthias Springer       //     {inplace= [true] }
60249e37000SMatthias Springer 
60349e37000SMatthias Springer       // TODO: Use insertSliceOp.getDestOpOperand etc. when available.
60449e37000SMatthias Springer       if (uRead == &insertSliceOp->getOpOperand(1) /*dest*/ &&
60549e37000SMatthias Springer           hasMatchingExtractSliceOp(state, uConflictingWrite->get(),
60649e37000SMatthias Springer                                     insertSliceOp))
60749e37000SMatthias Springer         // Case 1: The main insight is that InsertSliceOp reads only part of
60849e37000SMatthias Springer         // the destination tensor. The overwritten area is not read. If
60949e37000SMatthias Springer         // uConflictingWrite writes into exactly the memory location that is
61049e37000SMatthias Springer         // being read by uRead, this is not a conflict.
61149e37000SMatthias Springer         //
61249e37000SMatthias Springer         // In the above example:
61349e37000SMatthias Springer         // uRead             = OpOperand 1 (%t) of tensor.insert_slice
61449e37000SMatthias Springer         // uConflictingWrite = OpOperand 1 (%0) of linalg.fill
61549e37000SMatthias Springer         //
61649e37000SMatthias Springer         // The read of %t does not conflict with the write of the FillOp
61749e37000SMatthias Springer         // (same aliases!) because the area that the FillOp operates on is
61849e37000SMatthias Springer         // exactly the one that is *not* read via %t.
61949e37000SMatthias Springer         return true;
62049e37000SMatthias Springer 
62149e37000SMatthias Springer       if (uRead == &insertSliceOp->getOpOperand(0) /*source*/ &&
62249e37000SMatthias Springer           uConflictingWrite == &insertSliceOp->getOpOperand(1) /*dest*/ &&
62349e37000SMatthias Springer           hasMatchingExtractSliceOp(state, uRead->get(), insertSliceOp))
62449e37000SMatthias Springer         // Case 2: The read of the source tensor and the write to the dest
62549e37000SMatthias Springer         // tensor via an InsertSliceOp is not a conflict if the read is
62649e37000SMatthias Springer         // reading exactly that part of an equivalent tensor that the
62749e37000SMatthias Springer         // InsertSliceOp is writing.
62849e37000SMatthias Springer         //
62949e37000SMatthias Springer         // In the above example:
63049e37000SMatthias Springer         // uRead             = OpOperand 0 (%1) of tensor.insert_slice
63149e37000SMatthias Springer         // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice
63249e37000SMatthias Springer         return true;
63349e37000SMatthias Springer     }
63449e37000SMatthias Springer 
63549e37000SMatthias Springer     // If uConflictingWrite is an InsertSliceOp...
63649e37000SMatthias Springer     if (auto insertSliceOp = dyn_cast<InsertSliceOp>(conflictingWritingOp))
63749e37000SMatthias Springer       // As an example, consider the following IR.
63849e37000SMatthias Springer       //
63949e37000SMatthias Springer       // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] }
64049e37000SMatthias Springer       // %1 = linalg.fill %cst, %0 {inplace= [true] }
64149e37000SMatthias Springer       // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1]
64249e37000SMatthias Springer       //     {inplace= [true] }
64349e37000SMatthias Springer       // %3 = vector.transfer_read %1, %cst
64449e37000SMatthias Springer       //
64549e37000SMatthias Springer       // In the above example:
64649e37000SMatthias Springer       // uRead             = OpOperand 0 (%1) of vector.transfer_read
64749e37000SMatthias Springer       // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice
64849e37000SMatthias Springer       // lastWrite         = %1
64949e37000SMatthias Springer       //
65049e37000SMatthias Springer       // This is not a conflict because the InsertSliceOp overwrites the
65149e37000SMatthias Springer       // memory segment of %1 with the exact same data. (Effectively, there
65249e37000SMatthias Springer       // is no memory write here.)
65349e37000SMatthias Springer       if (uConflictingWrite == &insertSliceOp->getOpOperand(1) /*dest*/ &&
65449e37000SMatthias Springer           state.areEquivalentBufferizedValues(uRead->get(),
65549e37000SMatthias Springer                                               insertSliceOp.source()) &&
65649e37000SMatthias Springer           hasMatchingExtractSliceOp(state, insertSliceOp.source(),
65749e37000SMatthias Springer                                     insertSliceOp))
65849e37000SMatthias Springer         return true;
65949e37000SMatthias Springer 
66049e37000SMatthias Springer     return false;
66149e37000SMatthias Springer   }
66249e37000SMatthias Springer 
66349e37000SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
6649597b16aSMatthias Springer                           BufferizationState &state) const {
66549e37000SMatthias Springer     // insert_slice ops arise from tiling and bufferizing them out-of-place is
66649e37000SMatthias Springer     // generally a deal breaker. When used with loops, this ends up cloning the
66749e37000SMatthias Springer     // whole tensor on every single iteration and is a symptom of a
66849e37000SMatthias Springer     // catastrophically bad scheduling decision.
66949e37000SMatthias Springer     // TODO: be very loud about it or even consider failing the pass.
67049e37000SMatthias Springer     auto insertSliceOp = cast<tensor::InsertSliceOp>(op);
67149e37000SMatthias Springer     Location loc = insertSliceOp.getLoc();
67249e37000SMatthias Springer 
67349e37000SMatthias Springer     // When bufferizing out-of-place, `getResultBuffer` allocates.
67449e37000SMatthias Springer     FailureOr<Value> dstMemref =
67549e37000SMatthias Springer         state.getBuffer(rewriter, insertSliceOp->getOpOperand(1) /*dest*/);
67649e37000SMatthias Springer     if (failed(dstMemref))
67749e37000SMatthias Springer       return failure();
67849e37000SMatthias Springer 
67949e37000SMatthias Springer     // Expand offsets, sizes and strides to the full rank to handle the
68049e37000SMatthias Springer     // rank-reducing case.
68149e37000SMatthias Springer     SmallVector<OpFoldResult> mixedOffsets = insertSliceOp.getMixedOffsets();
68249e37000SMatthias Springer     SmallVector<OpFoldResult> mixedSizes = insertSliceOp.getMixedSizes();
68349e37000SMatthias Springer     SmallVector<OpFoldResult> mixedStrides = insertSliceOp.getMixedStrides();
68449e37000SMatthias Springer     OffsetSizeAndStrideOpInterface::expandToRank(
68549e37000SMatthias Springer         *dstMemref, mixedOffsets, mixedSizes, mixedStrides,
68649e37000SMatthias Springer         [&](Value target, int64_t dim) -> OpFoldResult {
68749e37000SMatthias Springer           auto shapedType = target.getType().cast<ShapedType>();
68849e37000SMatthias Springer           if (shapedType.isDynamicDim(dim))
68949e37000SMatthias Springer             return rewriter.create<memref::DimOp>(loc, target, dim).result();
69049e37000SMatthias Springer           return rewriter.getIndexAttr(shapedType.getDimSize(dim));
69149e37000SMatthias Springer         });
69249e37000SMatthias Springer     // Take a subview of the dst.
69349e37000SMatthias Springer     auto dstMemrefType = dstMemref->getType().cast<MemRefType>();
69449e37000SMatthias Springer     auto subviewMemRefType =
69549e37000SMatthias Springer         memref::SubViewOp::inferRankReducedResultType(
69649e37000SMatthias Springer             insertSliceOp.getSourceType().getRank(), dstMemrefType,
69749e37000SMatthias Springer             mixedOffsets, mixedSizes, mixedStrides)
69849e37000SMatthias Springer             .cast<MemRefType>();
69949e37000SMatthias Springer     Value subView = rewriter.create<memref::SubViewOp>(
70049e37000SMatthias Springer         loc, subviewMemRefType, *dstMemref, mixedOffsets, mixedSizes,
70149e37000SMatthias Springer         mixedStrides);
70249e37000SMatthias Springer 
70349e37000SMatthias Springer     // Copy tensor. If this tensor.insert_slice has a matching
70449e37000SMatthias Springer     // tensor.extract_slice, the copy operation will eventually fold away.
70549e37000SMatthias Springer     Value srcMemref =
70649e37000SMatthias Springer         *state.getBuffer(rewriter, insertSliceOp->getOpOperand(0) /*source*/);
70749e37000SMatthias Springer     if (failed(createMemCpy(rewriter, loc, srcMemref, subView,
70849e37000SMatthias Springer                             state.getOptions())))
70949e37000SMatthias Springer       return failure();
71049e37000SMatthias Springer 
71149e37000SMatthias Springer     replaceOpWithBufferizedValues(rewriter, op, *dstMemref);
71249e37000SMatthias Springer     return success();
71349e37000SMatthias Springer   }
71449e37000SMatthias Springer };
71549e37000SMatthias Springer 
716fc08d1c2SMatthias Springer /// Bufferization of tensor.rank. Replace with memref.rank.
717fc08d1c2SMatthias Springer struct RankOpInterface
718fc08d1c2SMatthias Springer     : public BufferizableOpInterface::ExternalModel<RankOpInterface,
719fc08d1c2SMatthias Springer                                                     tensor::RankOp> {
720fc08d1c2SMatthias Springer   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
7219597b16aSMatthias Springer                               const AnalysisState &state) const {
722fc08d1c2SMatthias Springer     return true;
723fc08d1c2SMatthias Springer   }
724fc08d1c2SMatthias Springer 
725fc08d1c2SMatthias Springer   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
7269597b16aSMatthias Springer                                const AnalysisState &state) const {
727fc08d1c2SMatthias Springer     return false;
728fc08d1c2SMatthias Springer   }
729fc08d1c2SMatthias Springer 
7309597b16aSMatthias Springer   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
7319597b16aSMatthias Springer                                             const AnalysisState &state) const {
732585a8a32SMatthias Springer     return {};
733fc08d1c2SMatthias Springer   }
734fc08d1c2SMatthias Springer 
735fc08d1c2SMatthias Springer   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
7369597b16aSMatthias Springer                           BufferizationState &state) const {
737fc08d1c2SMatthias Springer     auto rankOp = cast<tensor::RankOp>(op);
738fc08d1c2SMatthias Springer     Value v = *state.getBuffer(rewriter, rankOp->getOpOperand(0) /*source*/);
739fc08d1c2SMatthias Springer     replaceOpWithNewBufferizedOp<memref::RankOp>(rewriter, op, rankOp.getType(),
740fc08d1c2SMatthias Springer                                                  v);
741fc08d1c2SMatthias Springer     return success();
742fc08d1c2SMatthias Springer   }
743fc08d1c2SMatthias Springer };
744fc08d1c2SMatthias Springer 
74549e37000SMatthias Springer } // namespace
74649e37000SMatthias Springer } // namespace tensor
74749e37000SMatthias Springer } // namespace mlir
74849e37000SMatthias Springer 
74949e37000SMatthias Springer void mlir::tensor::registerBufferizableOpInterfaceExternalModels(
75049e37000SMatthias Springer     DialectRegistry &registry) {
75177eee579SRiver Riddle   registry.addExtension(+[](MLIRContext *ctx, tensor::TensorDialect *dialect) {
75277eee579SRiver Riddle     CastOp::attachInterface<CastOpInterface>(*ctx);
75377eee579SRiver Riddle     CollapseShapeOp::attachInterface<CollapseShapeOpInterface>(*ctx);
75477eee579SRiver Riddle     DimOp::attachInterface<DimOpInterface>(*ctx);
75577eee579SRiver Riddle     ExpandShapeOp::attachInterface<ExpandShapeOpInterface>(*ctx);
75677eee579SRiver Riddle     ExtractSliceOp::attachInterface<ExtractSliceOpInterface>(*ctx);
75777eee579SRiver Riddle     ExtractOp::attachInterface<ExtractOpInterface>(*ctx);
75877eee579SRiver Riddle     FromElementsOp::attachInterface<FromElementsOpInterface>(*ctx);
75977eee579SRiver Riddle     GenerateOp::attachInterface<GenerateOpInterface>(*ctx);
76077eee579SRiver Riddle     InsertOp::attachInterface<InsertOpInterface>(*ctx);
76177eee579SRiver Riddle     InsertSliceOp::attachInterface<InsertSliceOpInterface>(*ctx);
76277eee579SRiver Riddle     RankOp::attachInterface<RankOpInterface>(*ctx);
76377eee579SRiver Riddle   });
76449e37000SMatthias Springer }
765