MLIR 24.0.0git
BufferizableOpInterfaceImpl.cpp
Go to the documentation of this file.
1//===- BufferizableOpInterfaceImpl.cpp - Impl. of BufferizableOpInterface -===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
14#include "mlir/IR/Dialect.h"
15#include "mlir/IR/Operation.h"
16
17using namespace mlir;
18using namespace mlir::bufferization;
19
20namespace mlir {
21namespace bufferization {
22namespace {
23
24struct AllocTensorOpInterface
25 : public BufferizableOpInterface::ExternalModel<AllocTensorOpInterface,
26 AllocTensorOp> {
27 bool bufferizesToAllocation(Operation *op, Value value) const { return true; }
28
29 bool resultBufferizesToMemoryWrite(Operation *op, OpResult opResult,
30 const AnalysisState &state) const {
31 // AllocTensorOps do not write unless they have a `copy` value.
32 return static_cast<bool>(cast<AllocTensorOp>(op).getCopy());
33 }
34
35 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
36 const AnalysisState &state) const {
37 assert(&opOperand == &cast<AllocTensorOp>(op).getCopyMutable()[0] &&
38 "expected copy operand");
39 return true;
40 }
41
42 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
43 const AnalysisState &state) const {
44 assert(&opOperand == &cast<AllocTensorOp>(op).getCopyMutable()[0] &&
45 "expected copy operand");
46 return false;
47 }
48
49 AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
50 const AnalysisState &state) const {
51 // This is a new allocation. It does not alias with any other buffer.
52 return {};
53 }
54
55 FailureOr<BufferLikeType>
56 getBufferType(Operation *op, Value value, const BufferizationOptions &options,
57 const BufferizationState &state,
58 SmallVector<Value> &invocationStack) const {
59 auto allocTensorOp = cast<AllocTensorOp>(op);
60 assert(value == allocTensorOp.getResult() && "invalid value");
61
62 FailureOr<BufferLikeType> copyBufferType;
63 if (allocTensorOp.getCopy()) {
64 copyBufferType = bufferization::getBufferType(
65 allocTensorOp.getCopy(), options, state, invocationStack);
66 if (failed(copyBufferType))
67 return failure();
68 }
69
70 // Compute memory space of this allocation.
71 Attribute memorySpace;
72 if (allocTensorOp.getMemorySpace().has_value()) {
73 memorySpace = *allocTensorOp.getMemorySpace();
74 } else if (allocTensorOp.getCopy()) {
75 // A buffer that is not a memref has no memory space to inherit.
76 if (auto copyMemRefType = dyn_cast<BaseMemRefType>(*copyBufferType))
77 memorySpace = copyMemRefType.getMemorySpace();
78 } else if (auto ms = options.defaultMemorySpaceFn(
79 cast<TensorLikeType>(allocTensorOp.getType()))) {
80 memorySpace = *ms;
81 } else {
82 return op->emitError("could not infer memory space");
83 }
84
85 // A copy has the shape of the memref it copies, so the sizes `bufferize`
86 // reads from that memref are the copy's dynamic sizes.
87 if (allocTensorOp.getCopy())
88 if (auto copyMemRefType = dyn_cast<MemRefType>(*copyBufferType))
89 return cast<BufferLikeType>(MemRefType::get(
90 copyMemRefType.getShape(), copyMemRefType.getElementType(),
91 MemRefLayoutAttrInterface{}, memorySpace));
92 // Any other result's buffer type is the options' choice.
93 if (auto tensorType = dyn_cast<RankedTensorType>(allocTensorOp.getType()))
94 return cast<BufferLikeType>(
95 getMemRefTypeWithStaticIdentityLayout(tensorType, memorySpace));
96 return options.unknownTypeConverterFn(allocTensorOp.getType(), memorySpace,
97 options);
98 }
99
100 LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
101 const BufferizationOptions &options,
102 BufferizationState &state) const {
103 auto allocTensorOp = cast<AllocTensorOp>(op);
104 OpBuilder::InsertionGuard g(rewriter);
105 Location loc = allocTensorOp.getLoc();
106
107 // Nothing to do for dead AllocTensorOps.
108 if (op->getUses().empty()) {
109 rewriter.eraseOp(op);
110 return success();
111 }
112
113 // Get "copy" buffer.
114 Value copyBuffer;
115 if (allocTensorOp.getCopy()) {
116 FailureOr<Value> maybeCopyBuffer = bufferization::getBuffer(
117 rewriter, allocTensorOp.getCopy(), options, state);
118 if (failed(maybeCopyBuffer))
119 return failure();
120 copyBuffer = *maybeCopyBuffer;
121 }
122
123 // Create memory allocation.
124 auto allocType =
125 bufferization::getBufferType(allocTensorOp.getResult(), options, state);
126 if (failed(allocType))
127 return failure();
128 // TODO: The allocation hook takes a MemRefType; a buffer type that is not
129 // a memref is diagnosed rather than allocated.
130 auto memRefType = dyn_cast<MemRefType>(*allocType);
131 if (!memRefType)
132 return op->emitError() << "allocating a buffer of type " << *allocType
133 << " is not supported";
134 SmallVector<Value> dynamicDims = allocTensorOp.getDynamicSizes();
135 // populateDynamicDimSizes supports no buffer type other than a memref.
136 if (allocTensorOp.getCopy() && isa<MemRefType>(copyBuffer.getType())) {
137 assert(dynamicDims.empty() && "expected either `copy` or `dynamicDims`");
138 populateDynamicDimSizes(rewriter, loc, copyBuffer, dynamicDims);
139 }
140 // TODO: A result that is not a ranked tensor takes no sizes (verifier), so
141 // a buffer type with a dynamic dimension is diagnosed rather than
142 // allocated unless the op copies a value.
143 if (memRefType.getNumDynamicDims() != dynamicDims.size())
144 return op->emitError()
145 << "allocating " << memRefType
146 << " needs a size for each dynamic dimension, which the op "
147 "takes only for a ranked tensor result";
148 FailureOr<Value> alloc = options.allocationFn(
149 rewriter, loc, memRefType, dynamicDims, options.bufferAlignment);
150 if (failed(alloc))
151 return failure();
152
153 // Create memory copy (if any).
154 if (allocTensorOp.getCopy()) {
155 if (failed(options.memCpyFn(rewriter, loc, copyBuffer, *alloc)))
156 return failure();
157 }
158
159 // Replace op.
160 replaceOpWithBufferizedValues(rewriter, op, *alloc);
161
162 return success();
163 }
164};
165
166struct DeallocTensorOpInterface
167 : public BufferizableOpInterface::ExternalModel<DeallocTensorOpInterface,
168 DeallocTensorOp> {
169 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
170 const AnalysisState &state) const {
171 return false;
172 }
173
174 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
175 const AnalysisState &state) const {
176 return false;
177 }
178
179 AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
180 const AnalysisState &state) const {
181 return {};
182 }
183
184 LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
185 const BufferizationOptions &options,
186 BufferizationState &state) const {
187 auto deallocTensorOp = cast<DeallocTensorOp>(op);
188 FailureOr<Value> buffer = bufferization::getBuffer(
189 rewriter, deallocTensorOp.getTensor(), options, state);
190 if (failed(buffer))
191 return failure();
192 memref::DeallocOp::create(rewriter, deallocTensorOp.getLoc(), *buffer);
193 rewriter.eraseOp(op);
194 return success();
195 }
196};
197
198struct MaterializeInDestinationOpInterface
199 : public BufferizableOpInterface::ExternalModel<
200 MaterializeInDestinationOpInterface, MaterializeInDestinationOp> {
201 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
202 const AnalysisState &state) const {
203 return opOperand == cast<MaterializeInDestinationOp>(op).getSourceMutable();
204 }
205
206 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
207 const AnalysisState &state) const {
208 auto materializeOp = cast<MaterializeInDestinationOp>(op);
209 if (opOperand == materializeOp.getDestMutable()) {
210 assert(isa<TensorType>(materializeOp.getDest().getType()) &&
211 "expected tensor type");
212 return true;
213 }
214 return false;
215 }
216
217 bool mustBufferizeInPlace(Operation *op, OpOperand &opOperand,
218 const AnalysisState &state) const {
219 // The source is only read and not written, so it always bufferizes in-place
220 // by default. The destination is written and is forced to bufferize
221 // in-place (if it is a tensor).
222 return true;
223 }
224
225 AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
226 const AnalysisState &state) const {
227 auto materializeOp = cast<MaterializeInDestinationOp>(op);
228 if (opOperand == materializeOp.getDestMutable()) {
229 assert(isa<TensorType>(materializeOp.getDest().getType()) &&
230 "expected tensor type");
231 return {{op->getResult(0), BufferRelation::Equivalent}};
232 }
233 return {};
234 }
235
236 LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
237 const BufferizationOptions &options,
238 BufferizationState &state) const {
239 auto materializeOp = cast<MaterializeInDestinationOp>(op);
240 bool tensorDest = isa<TensorType>(materializeOp.getDest().getType());
241 Value buffer;
242 if (tensorDest) {
243 FailureOr<Value> maybeBuffer = bufferization::getBuffer(
244 rewriter, materializeOp.getDest(), options, state);
245 if (failed(maybeBuffer))
246 return failure();
247 buffer = *maybeBuffer;
248 } else {
249 assert(isa<BaseMemRefType>(materializeOp.getDest().getType()) &&
250 "expected memref type");
251 buffer = materializeOp.getDest();
252 }
253 auto srcBuffer = bufferization::getBuffer(
254 rewriter, materializeOp.getSource(), options, state);
255 if (failed(srcBuffer))
256 return failure();
257 if (failed(options.memCpyFn(rewriter, materializeOp.getLoc(), *srcBuffer,
258 buffer)))
259 return failure();
260 replaceOpWithBufferizedValues(
261 rewriter, op, tensorDest ? ValueRange(buffer) : ValueRange());
262 return success();
263 }
264
265 bool bufferizesToElementwiseAccess(Operation *op, const AnalysisState &state,
266 ArrayRef<OpOperand *> opOperands) const {
267 // As elements are copied from the "source" buffer to the "dest" buffer,
268 // already copied elements are not read a second time.
269 return true;
270 }
271
272 bool isWritable(Operation *op, Value value,
273 const AnalysisState &state) const {
274 auto materializeOp = cast<MaterializeInDestinationOp>(op);
275 return isa<TensorType>(materializeOp.getDest().getType())
276 ? true
277 : materializeOp.getWritable();
278 }
279};
280
281// Note: ToBufferOp / ToTensorOp are temporary ops that are inserted at the
282// bufferization boundary. When One-Shot bufferization is complete, there should
283// be no such ops left over. If `allowUnknownOps` (or after running a partial
284// bufferization pass), such ops may be part of the resulting IR, but such IR
285// may no longer be analyzable by One-Shot analysis.
286
287struct ToTensorOpInterface
288 : public BufferizableOpInterface::ExternalModel<ToTensorOpInterface,
289 ToTensorOp> {
290 bool isWritable(Operation *op, Value value,
291 const AnalysisState &state) const {
292 return cast<ToTensorOp>(op).getWritable();
293 }
294
295 FailureOr<BufferLikeType>
296 getBufferType(Operation *op, Value value, const BufferizationOptions &options,
297 const BufferizationState &state,
298 SmallVector<Value> &invocationStack) const {
299 return cast<ToTensorOp>(op).getBuffer().getType();
300 }
301
302 LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
303 const BufferizationOptions &options,
304 BufferizationState &state) const {
305 // to_tensor/to_buffer pairs fold away after bufferization.
306 return success();
307 }
308};
309
310struct ToBufferOpInterface
311 : public BufferizableOpInterface::ExternalModel<ToBufferOpInterface,
312 ToBufferOp> {
313 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
314 const AnalysisState &state) const {
315 // It is unknown whether the resulting memref will be read or not.
316 return true;
317 }
318
319 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
320 const AnalysisState &state) const {
321 return !cast<ToBufferOp>(op).getReadOnly();
322 }
323
324 AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
325 const AnalysisState &state) const {
326 return {};
327 }
328
329 LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
330 const BufferizationOptions &options,
331 BufferizationState &state) const {
332 // Fold to_buffer(to_tensor(x)) to x. Insert a cast if necessary.
333 (void)foldToBufferToTensorPair(rewriter, cast<ToBufferOp>(op), options);
334 // Note: The return value of `bufferize` indicates whether there was an
335 // error or not. (And not whether the pattern matched or not.)
336 return success();
337 }
338};
339
340} // namespace
341} // namespace bufferization
342} // namespace mlir
343
345 DialectRegistry &registry) {
346 registry.addExtension(+[](MLIRContext *ctx, BufferizationDialect *dialect) {
347 AllocTensorOp::attachInterface<AllocTensorOpInterface>(*ctx);
348 DeallocTensorOp::attachInterface<DeallocTensorOpInterface>(*ctx);
349 MaterializeInDestinationOp::attachInterface<
350 MaterializeInDestinationOpInterface>(*ctx);
351 ToBufferOp::attachInterface<ToBufferOpInterface>(*ctx);
352 ToTensorOp::attachInterface<ToTensorOpInterface>(*ctx);
353 });
354}
return success()
true
Given two iterators into the same block, return "true" if a is before `b.
static llvm::ManagedStatic< PassManagerOptions > options
static RankedTensorType getBufferType(const SparseTensorType &stt, bool needTmpCOO)
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
use_range getUses()
Returns a range of all uses, which is useful for iterating over all uses.
Definition Operation.h:900
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
Type getType() const
Return the type of this value.
Definition Value.h:105
LogicalResult foldToBufferToTensorPair(RewriterBase &rewriter, ToBufferOp toBuffer, const BufferizationOptions &options)
Try to fold to_buffer(to_tensor(x)).
void registerBufferizableOpInterfaceExternalModels(DialectRegistry &registry)
void populateDynamicDimSizes(OpBuilder &b, Location loc, Value shapedValue, SmallVector< Value > &dynamicDims)
Populate dynamicDims with tensor::DimOp / memref::DimOp results for all dynamic dimensions of the giv...
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.