1//===-- BufferizableOpInterface.td - Bufferizable Ops ------*- tablegen -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef BUFFERIZABLE_OP_INTERFACE
10#define BUFFERIZABLE_OP_INTERFACE
11
12include "mlir/IR/OpBase.td"
13
14def BufferizableOpInterface : OpInterface<"BufferizableOpInterface"> {
15  let description = [{
16    An op interface for One-Shot Bufferize. Ops that implement this interface
17    interface can be analyzed and bufferized using One-Shot Bufferize.
18
19    Note: All "bufferizesTo*" and "getAliasing*" interface methods must be
20    implemented conservatively. If it is not statically known whether an
21    OpOperand/OpResult bufferizes in a certain way (e.g., to a memory write),
22    the worst case must be assumed (e.g., that it does). Similarly,
23    "getAliasing*" interface methods may always return additional OpOperands or
24    OpResults, but must not miss an OpOperand or OpResult that could potentially
25    alias at runtime.
26  }];
27  let cppNamespace = "::mlir::bufferization";
28  let methods = [
29      InterfaceMethod<
30        /*desc=*/[{
31          Return `true` if the given OpResult may bufferize to a new buffer
32          allocation. If it is statically unknown if the given OpResult
33          bufferizes to a buffer allocation, `true` should be returned.
34        }],
35        /*retType=*/"bool",
36        /*methodName=*/"bufferizesToAllocation",
37        /*args=*/(ins "OpResult":$opResult),
38        /*methodBody=*/"",
39        /*defaultImplementation=*/"return false;"
40      >,
41      InterfaceMethod<
42        /*desc=*/[{
43          Return `true` if the given OpOperand bufferizes to a memory read. This
44          method will never be called on OpOperands that do not have a tensor
45          type.
46
47          Note: It is always safe to consider an OpOperand as a memory read,
48          even if it does actually not read; however, this can introduce
49          unnecessary out-of-place bufferization decisions. One-Shot Analysis
50          considers OpOperands of unknown ops (that do not implement this
51          interface) as reading OpOperands.
52        }],
53        /*retType=*/"bool",
54        /*methodName=*/"bufferizesToMemoryRead",
55        /*args=*/(ins "OpOperand &":$opOperand,
56                      "const AnalysisState &":$state),
57        /*methodBody=*/"",
58        /*defaultImplementation=*/[{
59          // Does not have to be implemented for ops without tensor OpOperands.
60          llvm_unreachable("bufferizesToMemoryRead not implemented");
61         }]
62      >,
63      InterfaceMethod<
64        /*desc=*/[{
65          Return `true` if the given OpOperand bufferizes to a memory write.
66
67          This method will never be called on OpOperands that do not have a
68          tensor type.
69
70          This method will never be called on OpOperands that do not have an
71          aliasing OpResult. Intuitively, it does not make sense for an
72          OpOperand to bufferize to a memory write without returning an aliasing
73          tensor, because the write would have no visible effect outside of the
74          op.
75
76          Note: It is always safe to consider an OpOperand as a memory write,
77          even if it does actually not write; however, this can introduce
78          unnecessary out-of-place bufferization decisions. One-Shot Analysis
79          considers OpOperands of unknown ops (that do not implement this
80          interface) as writing OpOperands.
81        }],
82        /*retType=*/"bool",
83        /*methodName=*/"bufferizesToMemoryWrite",
84        /*args=*/(ins "OpOperand &":$opOperand,
85                      "const AnalysisState &":$state),
86        /*methodBody=*/"",
87        /*defaultImplementation=*/[{
88          // Does not have to be implemented for ops without tensor OpOperands.
89          // Does not have to be implemented for OpOperands that do not have an
90          // aliasing OpResult.
91          llvm_unreachable("bufferizesToMemoryWrite not implemented");
92         }]
93      >,
94      InterfaceMethod<
95          /*desc=*/[{
96            Return `true` if the given OpResult is a memory write. This is the
97            case if in the following cases:
98
99            * The corresponding aliasing OpOperand bufferizes to a memory write.
100            * Or: There is no corresponding aliasing OpOperand.
101
102            If the OpResult has multiple aliasing OpOperands, this method
103            returns `true` if at least one of them bufferizes to a memory write.
104          }],
105          /*retType=*/"bool",
106          /*methodName=*/"isMemoryWrite",
107          /*args=*/(ins "OpResult":$opResult,
108                        "const AnalysisState &":$state),
109          /*methodBody=*/"",
110          /*defaultImplementation=*/[{
111            auto bufferizableOp =
112                cast<BufferizableOpInterface>($_op.getOperation());
113            SmallVector<OpOperand*> opOperands =
114              bufferizableOp.getAliasingOpOperand(opResult, state);
115            if (opOperands.empty())
116              return true;
117            return llvm::any_of(
118                opOperands,
119                [&](OpOperand *operand) {
120                  return bufferizableOp.bufferizesToMemoryWrite(*operand,
121                                                                state);
122                });
123          }]
124      >,
125      InterfaceMethod<
126        /*desc=*/[{
127          Return `true` if the given OpOperand must bufferize in-place. Alias
128          sets and inplace attributes will be set up accordingly before making
129          any other bufferization decisions. This method will never be called on
130          OpOperands that do not have a tensor type.
131        }],
132        /*retType=*/"bool",
133        /*methodName=*/"mustBufferizeInPlace",
134        /*args=*/(ins "OpOperand &":$opOperand,
135                      "const AnalysisState &":$state),
136        /*methodBody=*/"",
137        /*defaultImplementation=*/[{
138          return false;
139        }]
140      >,
141      InterfaceMethod<
142        /*desc=*/[{
143          Return the OpResult that aliases with a given OpOperand when
144          bufferized in-place. This method will never be called on OpOperands
145          that do not have a tensor type.
146        }],
147        /*retType=*/"SmallVector<OpResult>",
148        /*methodName=*/"getAliasingOpResult",
149        /*args=*/(ins "OpOperand &":$opOperand,
150                      "const AnalysisState &":$state),
151        /*methodBody=*/"",
152        /*defaultImplementation=*/[{
153          // Does not have to be implemented for ops without tensor OpOperands.
154          llvm_unreachable("getAliasingOpResult not implemented");
155        }]
156      >,
157      InterfaceMethod<
158        /*desc=*/[{
159          Return the OpOperands that alias with a given OpResult when
160          bufferized in-place. This method will never be called on OpResults
161          that do not have a tensor type.
162
163          By default, this method is the inverse of `getAliasingOpResult`. Ops
164          with a region that yield values may want to override this method to
165          return the OpOperands that are yielded by the terminator.
166
167          Note: This method can return multiple OpOperands, indicating that the
168          given OpResult may at runtime alias with any of the OpOperands. This
169          is useful for branches and for ops such as `arith.select`.
170        }],
171        /*retType=*/"SmallVector<OpOperand *>",
172        /*methodName=*/"getAliasingOpOperand",
173        /*args=*/(ins "OpResult":$opResult,
174                      "const AnalysisState &":$state),
175        /*methodBody=*/"",
176        /*defaultImplementation=*/[{
177          assert(opResult.getType().isa<TensorType>() &&
178                 "expected OpResult with tensor type");
179          SmallVector<OpOperand *> result;
180          auto bufferizableOp =
181              cast<BufferizableOpInterface>($_op.getOperation());
182          for (OpOperand &opOperand : $_op.getOperation()->getOpOperands()) {
183            if (!opOperand.get().getType().isa<TensorType>())
184              continue;
185            SmallVector<OpResult> aliasingOpResults =
186                bufferizableOp.getAliasingOpResult(opOperand, state);
187            if (llvm::is_contained(aliasingOpResults, opResult))
188              result.push_back(&opOperand);
189          }
190          return result;
191        }]
192      >,
193      InterfaceMethod<
194        /*desc=*/[{
195          Return the buffer relation between the given OpResult and its aliasing
196          OpOperands when bufferized in-place. Most OpOperands have an
197          "equivalence" relation. This method will never be called on OpResults
198          that do not have a tensor type. It will also never be called on
199          OpResults that do not have at least one aliasing OpOperand.
200
201          TODO: Support other relations such as "OpOperand is included in
202          OpResult".
203        }],
204        /*retType=*/"BufferRelation",
205        /*methodName=*/"bufferRelation",
206        /*args=*/(ins "OpResult":$opResult,
207                      "const AnalysisState &":$state),
208        /*methodBody=*/"",
209        /*defaultImplementation=*/[{
210          // Does not have to be implemented for ops without tensor OpResults
211          // that have an aliasing OpOperand.
212          llvm_unreachable("bufferRelation not implemented");
213        }]
214      >,
215      InterfaceMethod<
216        /*desc=*/[{
217          Resolve all inplacability conflicts by inserting explicit
218          `bufferization.alloc_tensor` ops. Examples of inplacability conflicts
219          are read-after-write conflicts or writes into non-writable buffers.
220
221          This method should rewrite the IR in such a way that for each tensor
222          OpOperand t, buffer(t) can be directly used when during bufferization.
223          The bufferization does no longer have to care about inplacability
224          conflicts.
225
226          This method can query analysis information from the given analysis
227          state.
228        }],
229        /*retType=*/"LogicalResult",
230        /*methodName=*/"resolveConflicts",
231        /*args=*/(ins "RewriterBase &":$rewriter,
232                      "const AnalysisState &":$state),
233        /*methodBody=*/"",
234        /*defaultImplementation=*/[{
235          auto bufferizableOp =
236              cast<BufferizableOpInterface>($_op.getOperation());
237          return bufferizableOp.resolveTensorOpOperandConflicts(
238              rewriter, state);
239        }]
240      >,
241      InterfaceMethod<
242        /*desc=*/[{
243          Bufferize this op, i.e., rewrite it into a memref-based equivalent.
244          Buffers of tensor SSA values can be retrieved via `getBuffer`.
245          Uses of tensor results of the existing tensor op can be replaced with
246          `replaceOpWithBufferizedValues` or `replaceOpWithNewBufferizedOp`.
247          These two functions automatically handle the tensor-to-memref type
248          conversion.
249
250          The implementation of this method must be consistent with the
251          remaining methods, in particular `getAliasingOpOperand`. I.e., a
252          tensor result `r` may only be replaced with:
253          a) A buffer that aliases one of buffers in getAliasingOpOperand(r).
254          b) Or: A newly allocated buffer.
255
256          This method will never be called on ops that do not have at least one
257          tensor operand/result.
258
259          The return value of this method indicates whether there was an error
260          while bufferizing this op (such as failing to create a new buffer
261          allocation op). The bufferization driver immediately stops bufferizing
262          the input IR and returns `failure` in that case. If this op is
263          expected to survive bufferization, `success` should be returned
264          (together with `allow-unknown-ops` enabled).
265        }],
266        /*retType=*/"LogicalResult",
267        /*methodName=*/"bufferize",
268        /*args=*/(ins "RewriterBase &":$rewriter,
269                      "const BufferizationOptions &":$options),
270        /*methodBody=*/"",
271        /*defaultImplementation=*/[{
272          llvm_unreachable("bufferize not implemented");
273          return failure();
274        }]
275      >,
276      InterfaceMethod<
277        /*desc=*/[{
278          Return `true` if the given Value can be written to in-place. Value is
279          either an OpResult of this operation or a BlockArgument of a block of
280          this operation.
281
282          Most OpResult buffers can be written to, but some ops such as
283          ConstantOp may bufferize to non-writable (read-only) memory locations.
284          Therefore, by default, this method returns `true` for OpResults. This
285          method will never be called on OpResults that do not have a tensor
286          type.
287
288          Whether a BlockArgument can be written to or not depends on the
289          operation. This method conservatively returns `false`. This method
290          will never be called on BlockArguments that do not have a tensor type.
291        }],
292        /*retType=*/"bool",
293        /*methodName=*/"isWritable",
294        /*args=*/(ins "Value":$value,
295                      "const AnalysisState &":$state),
296        /*methodBody=*/"",
297        /*defaultImplementation=*/[{
298          return value.isa<OpResult>();
299        }]
300      >,
301      InterfaceMethod<
302        /*desc=*/[{
303          Return `true` if the `uRead` and `uWrite` do not constitute a RaW
304          conflict. If they are conflicting or if it is unknown whether they are
305          conflicting, return `false`. This method will never be called with
306          OpOperands that do not have a tensor type. At least one of the two
307          given OpOperands belongs to this operation.
308
309          This method can be implemented to specify custom RaW analysis rules.
310          If this method returns `true` the given OpOperands are not considered
311          to be conflicting and do not force out-of-place bufferization. (There
312          may still be other conflicts that do.)
313        }],
314        /*retType=*/"bool",
315        /*methodName=*/"isNotConflicting",
316        /*args=*/(ins "OpOperand *":$uRead,
317                      "OpOperand *":$uWrite,
318                      "const AnalysisState &":$state),
319        /*methodBody=*/"",
320        /*defaultImplementation=*/[{
321          return false;
322        }]
323      >,
324      InterfaceMethod<
325        /*desc=*/[{
326          Return `failure` if this op does not pass the analysis. This method
327          is run during One-Shot Bufferize (after all post-analysis steps). If
328          the op does not pass the analysis, bufferization is aborted.
329
330          This method can be used to check expected invariants and limitations
331          of the current bufferization implementation.
332        }],
333        /*retType=*/"LogicalResult",
334        /*methodName=*/"verifyAnalysis",
335        /*args=*/(ins "const AnalysisState &":$state),
336        /*methodBody=*/"",
337        /*defaultImplementation=*/[{
338          return success();
339        }]
340      >,
341      InterfaceMethod<
342        /*desc=*/[{
343          Return the bufferized type of the given tensor block argument. The
344          block argument is guaranteed to belong to a block of this op.
345        }],
346        /*retType=*/"FailureOr<BaseMemRefType>",
347        /*methodName=*/"getBufferType",
348        /*args=*/(ins "BlockArgument":$bbArg,
349                      "const BufferizationOptions &":$options),
350        /*methodBody=*/"",
351        /*defaultImplementation=*/[{
352          assert(bbArg.getOwner()->getParentOp() == $_op &&
353                 "bbArg must belong to this op");
354          assert(bbArg.getType().isa<TensorType>() &&
355                 "expected tensor type");
356          return bufferization::getMemRefType(bbArg, options);
357        }]
358      >,
359      InterfaceMethod<
360        /*desc=*/[{
361          Return the memory space of the given tensor OpResult if specified on
362          this op. If not specified, return `failure`.
363
364          This method will never be called with OpResults that do not bufferize
365          to a memory allocation.
366        }],
367        /*retType=*/"FailureOr<unsigned>",
368        /*methodName=*/"getMemorySpace",
369        /*args=*/(ins "OpResult":$opResult),
370        /*methodBody=*/"",
371        /*defaultImplementation=*/[{
372          assert(cast<BufferizableOpInterface>($_op.getOperation())
373                     .bufferizesToAllocation(opResult)
374                 && "expected allocation");
375          return failure();
376        }]
377      >,
378  ];
379
380  let extraClassDeclaration = [{
381    /// Resolve out-of-place tensor OpOperands with explicit allocations in the
382    /// form of `bufferization.alloc_tensor` ops.
383    LogicalResult resolveTensorOpOperandConflicts(
384        RewriterBase &rewriter, const AnalysisState &state);
385
386    /// Return `true` if the given OpOperand creates an alias but does neither
387    /// read nor write. This implies that `bufferizesToMemoryRead` and
388    /// `bufferizesToMemoryWrite` must return `false`. This method will never
389    /// be called on OpOperands that do not have a tensor type.
390    ///
391    /// Examples of such ops are `tensor.extract_slice` and `tensor.cast`.
392    bool bufferizesToAliasOnly(OpOperand &opOperand,
393                               const AnalysisState &state) {
394      auto bufferizableOp =
395          cast<BufferizableOpInterface>(getOperation());
396      return !bufferizableOp.bufferizesToMemoryRead(opOperand, state)
397          && !bufferizableOp.bufferizesToMemoryWrite(opOperand, state)
398          && !bufferizableOp.getAliasingOpResult(opOperand, state).empty();
399    }
400  }];
401}
402
403#endif  // BUFFERIZABLE_OP_INTERFACE
404