MLIR 24.0.0git
ViewLikeInterface.h
Go to the documentation of this file.
1//===- ViewLikeInterface.h - View-like operations interface ---------------===//
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// This file implements the operation interface for view-like operations.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef MLIR_INTERFACES_VIEWLIKEINTERFACE_H_
14#define MLIR_INTERFACES_VIEWLIKEINTERFACE_H_
15
17#include "mlir/IR/Builders.h"
22#include "llvm/ADT/STLExtras.h"
23
24namespace mlir {
25
26class OffsetSizeAndStrideOpInterface;
27
28namespace detail {
29
30LogicalResult verifyOffsetSizeAndStrideOp(OffsetSizeAndStrideOpInterface op);
31
33 OffsetSizeAndStrideOpInterface a, OffsetSizeAndStrideOpInterface b,
34 llvm::function_ref<bool(OpFoldResult, OpFoldResult)> cmp);
35
36/// Helper method to compute the number of dynamic entries of `staticVals`,
37/// up to `idx`.
38unsigned getNumDynamicEntriesUpToIdx(ArrayRef<int64_t> staticVals,
39 unsigned idx);
40
41} // namespace detail
42} // namespace mlir
43
44/// Include the generated interface declarations.
45#include "mlir/Interfaces/ViewLikeInterface.h.inc"
46
47namespace mlir {
48
49/// Result for slice bounds verification;
51 /// If set to "true", the slice bounds verification was successful.
52 bool isValid;
53 /// An error message that can be printed during op verification.
54 std::string errorMessage;
55};
56
57/// Verify that the offsets/sizes/strides-style access into the given shape
58/// is in-bounds. Only static values are verified. If `generateErrorMessage`
59/// is set to "true", an error message is produced that can be printed by the
60/// op verifier.
63 ArrayRef<int64_t> staticSizes,
64 ArrayRef<int64_t> staticStrides,
65 bool generateErrorMessage = false);
68 ArrayRef<OpFoldResult> mixedSizes, ArrayRef<OpFoldResult> mixedStrides,
69 bool generateErrorMessage = false);
70
71/// Pattern to rewrite dynamic offsets/sizes/strides of view/slice-like ops as
72/// constant arguments. This pattern assumes that the op has a suitable builder
73/// that takes a result type, a "source" operand and mixed offsets, sizes and
74/// strides.
75///
76/// `OpType` is the type of op to which this pattern is applied. `ResultTypeFn`
77/// returns the new result type of the op, based on the new offsets, sizes and
78/// strides. `CastOpFunc` is used to generate a cast op if the result type of
79/// the op has changed.
80template <typename OpType, typename ResultTypeFn, typename CastOpFunc>
82 : public OpRewritePattern<OpType> {
83public:
85
86 LogicalResult matchAndRewrite(OpType op,
87 PatternRewriter &rewriter) const override {
88 SmallVector<OpFoldResult> mixedOffsets(op.getMixedOffsets());
89 SmallVector<OpFoldResult> mixedSizes(op.getMixedSizes());
90 SmallVector<OpFoldResult> mixedStrides(op.getMixedStrides());
91
92 // No constant operands were folded, just return;
93 if (failed(foldDynamicIndexList(mixedOffsets, /*onlyNonNegative=*/true)) &&
94 failed(foldDynamicIndexList(mixedSizes, /*onlyNonNegative=*/true)) &&
95 failed(foldDynamicIndexList(mixedStrides)))
96 return failure();
97
98 // Pattern does not apply if the produced op would not verify.
100 cast<ShapedType>(op.getSource().getType()).getShape(), mixedOffsets,
101 mixedSizes, mixedStrides);
102 if (!sliceResult.isValid)
103 return failure();
104
105 // Compute the new result type.
106 auto resultType =
107 ResultTypeFn()(op, mixedOffsets, mixedSizes, mixedStrides);
108 if (!resultType)
109 return failure();
110
111 // Create the new op in canonical form.
112 auto newOp =
113 OpType::create(rewriter, op.getLoc(), resultType, op.getSource(),
114 mixedOffsets, mixedSizes, mixedStrides);
115 CastOpFunc()(rewriter, op, newOp);
116
117 return success();
118 }
119};
120
121/// Printer hooks for custom directive in assemblyFormat.
122///
123/// custom<DynamicIndexList>($values, $integers)
124/// custom<DynamicIndexList>($values, $integers, type($values))
125///
126/// where `values` is of ODS type `Variadic<*>` and `integers` is of ODS type
127/// `I64ArrayAttr`. Print a list where each element is either:
128/// 1. the static integer value in `integers`, if it's not `kDynamic` or,
129/// 2. the next value in `values`, otherwise.
130///
131/// If `valueTypes` is provided, the corresponding type of each dynamic value is
132/// printed. Otherwise, the type is not printed. Each type must match the type
133/// of the corresponding value in `values`. `valueTypes` is redundant for
134/// printing as we can retrieve the types from the actual `values`. However,
135/// `valueTypes` is needed for parsing and we must keep the API symmetric for
136/// parsing and printing. The type for integer elements is `i64` by default and
137/// never printed.
138///
139/// Integer indices can also be scalable in the context of scalable vectors,
140/// denoted by square brackets (e.g., "[2, [4], 8]"). For each value in
141/// `integers`, the corresponding `bool` in `scalableFlags` encodes whether it's
142/// a scalable index. If `scalableFlags` is empty then assume that all indices
143/// are non-scalable.
144///
145/// Examples:
146///
147/// * Input: `integers = [kDynamic, 7, 42, kDynamic]`,
148/// `values = [%arg0, %arg42]` and
149/// `valueTypes = [index, index]`
150/// prints:
151/// `[%arg0 : index, 7, 42, %arg42 : i32]`
152///
153/// * Input: `integers = [kDynamic, 7, 42, kDynamic]`,
154/// `values = [%arg0, %arg42]` and
155/// `valueTypes = []`
156/// prints:
157/// `[%arg0, 7, 42, %arg42]`
158///
159/// * Input: `integers = [2, 4, 8]`,
160/// `values = []` and
161/// `scalableFlags = [false, true, false]`
162/// prints:
163/// `[2, [4], 8]`
164///
166 OpAsmPrinter &printer, Operation *op, OperandRange values,
167 ArrayRef<int64_t> integers, ArrayRef<bool> scalableFlags,
168 TypeRange valueTypes = TypeRange(),
171 OpAsmPrinter &printer, Operation *op, OperandRange values,
172 ArrayRef<int64_t> integers, TypeRange valueTypes = TypeRange(),
174 return printDynamicIndexList(printer, op, values, integers,
175 /*scalableFlags=*/{}, valueTypes, delimiter);
176}
177
178/// Parser hooks for custom directive in assemblyFormat.
179///
180/// custom<DynamicIndexList>($values, $integers)
181/// custom<DynamicIndexList>($values, $integers, type($values))
182///
183/// where `values` is of ODS type `Variadic<*>` and `integers` is of ODS
184/// type `I64ArrayAttr`. Parse a mixed list where each element is either a
185/// static integer or an SSA value. Fill `integers` with the integer ArrayAttr,
186/// where `kDynamic` encodes the position of SSA values. Add the parsed SSA
187/// values to `values` in-order.
188///
189/// If `valueTypes` is provided, fill it with the types corresponding to each
190/// value in `values`. Otherwise, the caller must handle the types and parsing
191/// will fail if the type of the value is found (e.g., `[%arg0 : index, 3, %arg1
192/// : index]`).
193///
194/// Integer indices can also be scalable in the context of scalable vectors,
195/// denoted by square brackets (e.g., "[2, [4], 8]"). For each value in
196/// `integers`, the corresponding `bool` in `scalableFlags` encodes whether it's
197/// a scalable index.
198///
199/// Examples:
200///
201/// * After parsing "[%arg0 : index, 7, 42, %arg42 : i32]":
202/// 1. `result` is filled with `[kDynamic, 7, 42, kDynamic]`
203/// 2. `values` is filled with "[%arg0, %arg1]".
204/// 3. `scalableFlags` is filled with `[false, true, false]`.
205///
206/// * After parsing `[2, [4], 8]`:
207/// 1. `result` is filled with `[2, 4, 8]`
208/// 2. `values` is empty.
209/// 3. `scalableFlags` is filled with `[false, true, false]`.
210///
211/// Overloads that do not return scalable flags reject scalable indices.
212///
213ParseResult parseDynamicIndexList(
214 OpAsmParser &parser,
215 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &values,
216 DenseI64ArrayAttr &integers, DenseBoolArrayAttr &scalableFlags,
217 SmallVectorImpl<Type> *valueTypes = nullptr,
219inline ParseResult parseDynamicIndexList(
220 OpAsmParser &parser,
222 DenseI64ArrayAttr &integers, SmallVectorImpl<Type> *valueTypes = nullptr,
224 DenseBoolArrayAttr scalableFlags;
225 if (failed(parseDynamicIndexList(parser, values, integers, scalableFlags,
226 valueTypes, delimiter)))
227 return failure();
228 if (llvm::is_contained(scalableFlags.asArrayRef(), true))
229 return parser.emitError(parser.getNameLoc())
230 << "scalable indices are not supported";
231 return success();
232}
233
234/// Verify that a the `values` has as many elements as the number of entries in
235/// `attr` for which `isDynamic` evaluates to true.
236LogicalResult verifyListOfOperandsOrIntegers(Operation *op, StringRef name,
237 unsigned expectedNumElements,
238 ArrayRef<int64_t> attr,
239 ValueRange values);
240
241namespace OpTrait {
242/// This trai indicates that pointer-like objects (such as memrefs) returned
243/// from this operation will never alias with each other. This provides a
244/// guarantee to optimization passes that accesses through different results
245/// of this operation can be safely reordered, as they will never reference
246/// overlapping memory locations.
247///
248/// Operations with this trait take multiple pointer-like operands
249/// and return the same operands with additional non-aliasing guarantees.
250/// If the access to the results of this operation aliases at runtime, the
251/// behavior of such access is undefined.
252template <typename ConcreteType>
254 : public TraitBase<ConcreteType, DistinctObjectsTrait> {};
255} // namespace OpTrait
256
257} // namespace mlir
258
259#endif // MLIR_INTERFACES_VIEWLIKEINTERFACE_H_
return success()
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
Delimiter
These are the supported delimiters around operand lists and region argument lists,...
@ Square
Square brackets surrounding zero or more operands.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
This trai indicates that pointer-like objects (such as memrefs) returned from this operation will nev...
Helper class for implementing traits.
Pattern to rewrite dynamic offsets/sizes/strides of view/slice-like ops as constant arguments.
LogicalResult matchAndRewrite(OpType op, PatternRewriter &rewriter) const override
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
AttrTypeReplacer.
bool sameOffsetsSizesAndStrides(OffsetSizeAndStrideOpInterface a, OffsetSizeAndStrideOpInterface b, llvm::function_ref< bool(OpFoldResult, OpFoldResult)> cmp)
unsigned getNumDynamicEntriesUpToIdx(ArrayRef< int64_t > staticVals, unsigned idx)
Helper method to compute the number of dynamic entries of staticVals, up to idx.
LogicalResult verifyOffsetSizeAndStrideOp(OffsetSizeAndStrideOpInterface op)
Include the generated interface declarations.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
ParseResult parseDynamicIndexList(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &values, DenseI64ArrayAttr &integers, DenseBoolArrayAttr &scalableFlags, SmallVectorImpl< Type > *valueTypes=nullptr, AsmParser::Delimiter delimiter=AsmParser::Delimiter::Square)
Parser hooks for custom directive in assemblyFormat.
SliceBoundsVerificationResult verifyInBoundsSlice(ArrayRef< int64_t > shape, ArrayRef< int64_t > staticOffsets, ArrayRef< int64_t > staticSizes, ArrayRef< int64_t > staticStrides, bool generateErrorMessage=false)
Verify that the offsets/sizes/strides-style access into the given shape is in-bounds.
detail::DenseArrayAttrImpl< bool > DenseBoolArrayAttr
LogicalResult verifyListOfOperandsOrIntegers(Operation *op, StringRef name, unsigned expectedNumElements, ArrayRef< int64_t > attr, ValueRange values)
Verify that a the values has as many elements as the number of entries in attr for which isDynamic ev...
void printDynamicIndexList(OpAsmPrinter &printer, Operation *op, OperandRange values, ArrayRef< int64_t > integers, ArrayRef< bool > scalableFlags, TypeRange valueTypes=TypeRange(), AsmParser::Delimiter delimiter=AsmParser::Delimiter::Square)
Printer hooks for custom directive in assemblyFormat.
LogicalResult foldDynamicIndexList(SmallVectorImpl< OpFoldResult > &ofrs, bool onlyNonNegative=false, bool onlyNonZero=false)
Returns "success" when any of the elements in ofrs is a constant value.
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Result for slice bounds verification;.
bool isValid
If set to "true", the slice bounds verification was successful.
std::string errorMessage
An error message that can be printed during op verification.