1//===- BufferizationOps.td - Bufferization op definitions ----------*- 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 BUFFERIZATION_OPS
10#define BUFFERIZATION_OPS
11
12include "mlir/Dialect/Bufferization/IR/AllocationOpInterface.td"
13include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.td"
14include "mlir/Dialect/Bufferization/IR/BufferizationBase.td"
15include "mlir/Interfaces/InferTypeOpInterface.td"
16include "mlir/Interfaces/SideEffectInterfaces.td"
17include "mlir/Interfaces/CopyOpInterface.td"
18
19class Bufferization_Op<string mnemonic, list<Trait> traits = []>
20    : Op<Bufferization_Dialect, mnemonic, traits>;
21
22//===----------------------------------------------------------------------===//
23// AllocTensorOp
24//===----------------------------------------------------------------------===//
25
26def Bufferization_AllocTensorOp : Bufferization_Op<"alloc_tensor",
27    [AttrSizedOperandSegments, BufferizableOpInterface,
28     DeclareOpInterfaceMethods<ReifyRankedShapedTypeOpInterface>]> {
29  let summary = "buffer allocation in tensor land";
30
31  let description = [{
32    `bufferization.alloc_tensor` materializes an uninitialized tensor with a
33    given shape (dynamic or static). It always bufferizes to a new buffer
34    allocation of the given shape. The optional `copy` operand specifies the
35    contents of the tensors. If no `copy` operand is specified, reading from the
36    result of an `alloc_tensor` op yields an undefined value.
37
38    If `copy` is specified, no dynamic sizes should be passed, since they are
39    the same as the dynamic sizes of the `copy` operand.
40
41    `alloc_tensor` is a helper op for bufferization. The operation is provided
42    as an anchor that marks the beginning of a new tensor SSA use-def chain. It
43    can be used to control in-place bufferization decisions during One-Shot
44    Bufferize: The bufferized result of a `bufferization.alloc_tensor` does not
45    alias with any other buffer, so it can be used to resolve read-after-write
46    conflicts that would have been introduced by the in-place bufferization of
47    another op.
48
49    The optional `memory_space` attribute specifies the memory space when
50    bufferizing this op. The memory space is inferred from `copy` if specified.
51    If neither `copy` nor `memory_space` is specified, the default memory space
52    is used during bufferization.
53
54    Both dense and sparse tensor types are supported. The result of a
55    `bufferization.alloc_tensor` is a tensor value that can be used like any
56    other tensor value. In practice, it is often used as the "out" operand of
57    another op. Sparse tensor allocations should always be used in a local
58    construction operation and never escape the function boundary directly.
59
60    Example:
61
62    ```mlir
63    %c = bufferization.alloc_tensor [%d1, %d2] : tensor<?x?xf32, #SparseMatrix>
64    %0 = linalg.matmul
65      ins(%a, %b: tensor<?x?xf32, #SparseMatrix>, tensor<?x?xf32, #SparseMatrix>)
66      outs(%c: tensor<?x?xf32, #SparseMatrix>) -> tensor<?x?xf32, #SparseMatrix>
67    return %0 : tensor<?x?xf32, #SparseMatrix>
68    ```
69  }];
70
71  let arguments = (ins Variadic<Index>:$dynamic_sizes,
72                       Optional<AnyTensor>:$copy,
73                       OptionalAttr<UI64Attr>:$memory_space);
74
75  let results = (outs AnyTensor:$result);
76
77  let extraClassDeclaration = [{
78    LogicalResult bufferize(RewriterBase &rewriter,
79                            const BufferizationOptions &options);
80
81    bool isMemoryWrite(OpResult opResult, const AnalysisState &state);
82
83    bool bufferizesToAllocation(OpResult opResult) { return true; }
84
85    FailureOr<unsigned> getMemorySpace(OpResult opResult) {
86      if (getMemorySpace().has_value())
87        return static_cast<unsigned>(*getMemorySpace());
88      return failure();
89    }
90
91    bool bufferizesToMemoryRead(OpOperand &opOperand,
92                                const AnalysisState &state);
93
94    bool bufferizesToMemoryWrite(OpOperand &opOperand,
95                                 const AnalysisState &state);
96
97    SmallVector<OpResult> getAliasingOpResult(
98        OpOperand &opOperand, const AnalysisState &state);
99
100    RankedTensorType getType() {
101      return getResult().getType().cast<RankedTensorType>();
102    }
103
104    // Return true if the size of the tensor is dynamic at `idx`
105    bool isDynamicDim(unsigned idx) {
106      return getType().isDynamicDim(idx);
107    }
108
109    // Return the argument position that contains the dynamic size of
110    // the tensor at dimension `idx`. Asserts that the shape is
111    // dynamic at that `idx`.
112    unsigned getIndexOfDynamicSize(unsigned idx) {
113      assert(!getCopy() && "no dim sizes specified when copying a tensor");
114      assert(isDynamicDim(idx) && "expected dynamic size");
115      ArrayRef<int64_t> shape = getType().getShape();
116      return std::count_if(
117          shape.begin(), shape.begin() + idx,
118          [&](int64_t size) { return ShapedType::isDynamic(size); });
119    }
120
121    // Return the Value of the dynamic size of the tensor at dimension
122    // `idx`. Asserts that the shape is dynamic at that `idx.
123    Value getDynamicSize(OpBuilder &b, unsigned idx);
124
125    // Assert that the size of the result tensor is static at `idx`
126    // and return the shape.
127    int64_t getStaticSize(unsigned idx) {
128      assert(!isDynamicDim(idx) && "expected static size");
129      return getType().getShape()[idx];
130    }
131  }];
132
133  let builders = [
134    // Build an op without `copy` or `memory_space`.
135    OpBuilder<(ins "RankedTensorType":$type, "ValueRange":$dynamicSizes)>,
136
137    // Build an op without `memory_space`.
138    OpBuilder<(ins "RankedTensorType":$type, "ValueRange":$dynamicSizes,
139                   "Value":$copy)>,
140  ];
141
142  let hasCanonicalizer = 1;
143  let hasCustomAssemblyFormat = 1;
144  let hasVerifier = 1;
145}
146
147//===----------------------------------------------------------------------===//
148// CloneOp
149//===----------------------------------------------------------------------===//
150
151def Bufferization_CloneOp : Bufferization_Op<"clone", [
152    CopyOpInterface,
153    DeclareOpInterfaceMethods<MemoryEffectsOpInterface>,
154    DeclareOpInterfaceMethods<AllocationOpInterface, ["buildDealloc", "buildClone"]>
155  ]> {
156  let builders = [
157    OpBuilder<(ins "Value":$value), [{
158      return build($_builder, $_state, value.getType(), value);
159    }]>];
160
161  let description = [{
162    Clones the data in the input view into an implicitly defined output view.
163
164    Usage:
165
166    ```mlir
167    %arg1 = bufferization.clone %arg0 : memref<?xf32> to memref<?xf32>
168    ```
169
170    Valid implementations of this operation may alias the input and output
171    views or create an actual copy. Mutating the source or result
172    of the clone operation after the clone operation thus leads to undefined
173    behavior.
174  }];
175
176  let arguments = (ins Arg<AnyRankedOrUnrankedMemRef, "", []>:$input);
177  let results = (outs Arg<AnyRankedOrUnrankedMemRef, "", []>:$output);
178
179  let extraClassDeclaration = [{
180    Value getSource() { return getInput(); }
181    Value getTarget() { return getOutput(); }
182  }];
183
184  let assemblyFormat = "$input attr-dict `:` type($input) `to` type($output)";
185
186  let hasFolder = 1;
187  let hasCanonicalizer = 1;
188}
189
190//===----------------------------------------------------------------------===//
191// DeallocTensorOp
192//===----------------------------------------------------------------------===//
193
194def Bufferization_DeallocTensorOp : Bufferization_Op<"dealloc_tensor",
195    [BufferizableOpInterface]> {
196  string summary = "Releases underlying sparse storage format of given tensor";
197  string description = [{
198    `bufferization.dealloc_tensor` is a buffer deallocation in tensor land. This
199    op can be used for manual buffer deallocation. Some bufferizations (such as
200    One-Shot Bufferize) take care of buffer deallocation, in which case this op
201    is usually not needed. Details can be found in the documentation of the
202    respective bufferization passes.
203
204    In case of a dense tensor, this op lowers to a `memref.dealloc` op during
205    bufferization.
206
207    In case of a sparse tensor, this op releases the underlying sparse storage
208    format for a tensor that materialized earlier through a `new` operation, a
209    `convert` operation with annotated destination tensor type (unless the
210    convert is folded away), or a `bufferization.alloc_tensor` operation. The
211    release operation should only be called once for any materialized tensor.
212    After this operation, any subsequent `memref` querying operation on the
213    tensor returns undefined results.
214
215    Example:
216
217    ```mlir
218    bufferization.dealloc_tensor %tensor : tensor<1024x1024xf64, #CSR>
219    ```
220  }];
221
222  let arguments = (ins AnyTensor:$tensor);
223  let results = (outs);
224  let assemblyFormat = "$tensor attr-dict `:` type($tensor)";
225
226  let extraClassDeclaration = [{
227    bool bufferizesToMemoryRead(OpOperand &opOperand,
228                                const AnalysisState &state) const {
229      return false;
230    }
231
232    bool bufferizesToMemoryWrite(OpOperand &opOperand,
233                                 const AnalysisState &state) const {
234      return false;
235    }
236
237    SmallVector<OpResult> getAliasingOpResult(
238        OpOperand &opOperand, const AnalysisState &state) const {
239      return {};
240    }
241
242    LogicalResult bufferize(RewriterBase &rewriter,
243                            const BufferizationOptions &options);
244  }];
245}
246
247//===----------------------------------------------------------------------===//
248// ToTensorOp
249//===----------------------------------------------------------------------===//
250
251def Bufferization_ToTensorOp : Bufferization_Op<"to_tensor", [
252    BufferizableOpInterface,
253    SameOperandsAndResultShape,
254    SameOperandsAndResultElementType,
255    TypesMatchWith<"result type matches tensor equivalent of 'memref'",
256                   "memref", "result",
257                   "memref::getTensorTypeFromMemRefType($_self)">
258  ]> {
259  let summary = "memref to tensor operation";
260  let description = [{
261    Create a tensor from a `memref`, making an independent copy of the element
262    data. The result value is a tensor whose shape and element type match the
263    memref operand.
264
265    The opposite of this op is `to_memref`. Together, these two ops are
266    useful for source/target materializations when doing type conversions
267    involving tensors and memrefs.
268
269    Example:
270
271    ```mlir
272    // Produces a value of tensor<4x?xf32> type.
273    %12 = bufferization.to_tensor %10 : memref<4x?xf32, #layout, memspace0>
274    ```
275
276    If tensor load is used in the bufferization steps, mutating the source
277    buffer after loading leads to undefined behavior.
278  }];
279
280  let arguments = (ins Arg<AnyRankedOrUnrankedMemRef,
281                       "the reference to load from", [MemRead]>:$memref);
282  let results = (outs AnyTensor:$result);
283
284  let builders = [
285    OpBuilder<(ins "Value":$memref), [{
286      $_state.addOperands(memref);
287      $_state.addTypes(memref::getTensorTypeFromMemRefType(memref.getType()));
288    }]>];
289
290  let extraClassDeclaration = [{
291    /// The result of a to_tensor is always a tensor.
292    TensorType getType() {
293      Type resultType = getResult().getType();
294      if (resultType.isa<TensorType>())
295        return resultType.cast<TensorType>();
296      return {};
297    }
298
299    //===------------------------------------------------------------------===//
300    // BufferizableOpInterface implementation
301    //===------------------------------------------------------------------===//
302
303    // ToTensorOp conceptually loads a tensor from a memory location. The
304    // One-Shot analysis has no information about the memref that is loaded from
305    // by ToTensorOp. We have to assume that the loaded tensor may after
306    // bufferization potentially alias with any other bufferized tensor. Since
307    // ToTensorOp and ToMemrefOp have no aliasing OpOperand/OpResult pairs, this
308    // cannot be encoded directly in the analysis. However, declaring ToTensorOp
309    // results as not writable enforces a buffer copy and has the same effect.
310
311    LogicalResult bufferize(RewriterBase &rewriter,
312                            const BufferizationOptions &options) const {
313      // to_tensor cannot be bufferized. However, other ops that are using
314      // to_tensor's result will eventually be bufferized. At that point, they
315      // will start using to_tensor's memref operand. Once all users of
316      // to_tensor are bufferized, the op will not have any users anymore and
317      // DCE away. In case of partial bufferization, to_memref(to_tensor(x))
318      // constructs may be left over. These are folded by the canonicalizer or
319      // FinalizingBufferize.
320      return success();
321    }
322
323    bool isWritable(Value value, const AnalysisState &state) const {
324      // It is unknown whether the memref operand is writable or not.
325      return false;
326    }
327  }];
328
329  let assemblyFormat = "$memref attr-dict `:` type($memref)";
330
331  let hasCanonicalizer = 1;
332  let hasFolder = 1;
333}
334
335
336//===----------------------------------------------------------------------===//
337// ToMemrefOp
338//===----------------------------------------------------------------------===//
339
340def Bufferization_ToMemrefOp : Bufferization_Op<"to_memref", [
341    BufferizableOpInterface,
342    SameOperandsAndResultShape,
343    SameOperandsAndResultElementType,
344    NoSideEffect,
345    TypesMatchWith<"type of 'tensor' is the tensor equivalent of 'memref'",
346                   "memref", "tensor",
347                   "memref::getTensorTypeFromMemRefType($_self)">
348  ]> {
349  let summary = "tensor to memref cast operation";
350  let description = [{
351    Casts a tensor to a memref.
352
353    ```mlir
354    // Result type is memref<4x?xf32, #map0, 42>
355    %12 = bufferization.to_memref %10 : memref<4x?xf32, #map0, 42>
356    ```
357
358    Note, that mutating the result of the `to_memref` operation leads to
359    undefined behavior.
360
361    This operation is a specialized variant of the built-in
362    `unrealized_conversion_cast` and is intended for use in the context of
363    gradual bufferization.
364  }];
365
366  let arguments = (ins AnyTensor:$tensor);
367  let results = (outs AnyRankedOrUnrankedMemRef:$memref);
368
369  let extraClassDeclaration = [{
370    //===------------------------------------------------------------------===//
371    // BufferizableOpInterface implementation
372    //===------------------------------------------------------------------===//
373
374    // Note: ToMemrefOp / ToTensorOp are temporary ops that are inserted at the
375    // bufferization boundary. When One-Shot bufferization is complete, there
376    // should be no such ops left over. If `allowUnknownOps` (or after running a
377    // partial bufferization pass), such ops may be part of the resulting IR,
378    // but such IR may no longer be analyzable by One-Shot analysis.
379
380    bool bufferizesToMemoryRead(OpOperand &opOperand,
381                                const AnalysisState &state) const {
382      // It is unknown whether the resulting memref will be read or not.
383      return true;
384    }
385
386    bool bufferizesToMemoryWrite(OpOperand &opOperand,
387                                 const AnalysisState &state) const {
388      // It is unknown whether the resulting MemRef will be written or not.
389      return true;
390    }
391
392    bool mustBufferizeInPlace(OpOperand &opOperand,
393                              const AnalysisState &state) const {
394      // ToMemrefOps always bufferize inplace.
395      return true;
396    }
397
398    SmallVector<OpResult> getAliasingOpResult(
399        OpOperand &opOperand, const AnalysisState &state) const {
400      return {};
401    }
402
403    LogicalResult bufferize(RewriterBase &rewriter,
404                            const BufferizationOptions &options);
405  }];
406
407  let assemblyFormat = "$tensor attr-dict `:` type($memref)";
408
409  let hasFolder = 1;
410  let hasCanonicalizer = 1;
411}
412
413#endif // BUFFERIZATION_OPS
414