MLIR 24.0.0git
Tensor.h
Go to the documentation of this file.
1//===- Tensor.h - Tensor dialect --------------------------------*- C++ -*-===//
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 MLIR_DIALECT_TENSOR_IR_TENSOR_H_
10#define MLIR_DIALECT_TENSOR_IR_TENSOR_H_
11
19
20namespace llvm {
21class SmallBitVector;
22} // namespace llvm
23
24//===----------------------------------------------------------------------===//
25// Tensor Dialect Helpers
26//===----------------------------------------------------------------------===//
27
28namespace mlir {
29
30/// Return the list of Range (i.e. offset, size, stride). Each Range
31/// entry contains either the dynamic value or a ConstantIndexOp constructed
32/// with `b` at location `loc`.
33SmallVector<Range, 8> getOrCreateRanges(OffsetSizeAndStrideOpInterface op,
34 OpBuilder &b, Location loc);
35
36} // namespace mlir
37
38//===----------------------------------------------------------------------===//
39// Tensor Dialect Operations
40//===----------------------------------------------------------------------===//
41
42#define GET_OP_CLASSES
43#include "mlir/Dialect/Tensor/IR/TensorOps.h.inc"
44
45//===----------------------------------------------------------------------===//
46// Tensor Dialect Helpers
47//===----------------------------------------------------------------------===//
48
49namespace mlir {
50namespace tensor {
51
52/// Returns true if `target` is a ranked tensor type that preserves static
53/// information available in the `source` ranked tensor type.
54bool preservesStaticInformation(Type source, Type target);
55
56/// Determines whether tensor::CastOp casts to a more dynamic version of the
57/// source tensor. This is useful to fold a tensor.cast into a consuming op and
58/// implement canonicalization patterns for ops in different dialects that may
59/// consume the results of tensor.cast operations. Such foldable tensor.cast
60/// operations are typically inserted as `extract_slice` ops and are
61/// canonicalized, to preserve the type compatibility of their uses.
62///
63/// Returns true when all conditions are met:
64/// 1. source and result are ranked tensors with same element type and rank.
65/// 2. the tensor type has more static information than the result
66///
67/// Example:
68/// ```mlir
69/// %1 = tensor.cast %0 : tensor<8x16xf32> to tensor<?x?xf32>
70/// %2 = consumer %1 ... : tensor<?x?xf32> ...
71/// ```
72///
73/// folds into:
74///
75/// ```mlir
76/// %2 = consumer %0 ... : tensor<8x16xf32> ...
77/// ```
78bool canFoldIntoConsumerOp(CastOp castOp);
79
80/// Determines whether the tensor::CastOp casts to a more static version of the
81/// source tensor. This is useful to fold into a producing op and implement
82/// canonicaliation patterns with the `tensor.cast` op as the root, but producer
83/// being from different dialects. Returns true when all conditions are met:
84/// 1. source and result and ranked tensors with same element type and rank.
85/// 2. the result type has more static information than the source.
86///
87/// Example:
88/// ```mlir
89/// %1 = producer ... : tensor<?x?xf32>
90/// %2 = tensor.cast %1 : tensor<?x?xf32> to tensor<8x16xf32>
91/// ```
92///
93/// can be canonicalized to :
94///
95/// ```mlir
96/// %2 = producer ... : tensor<8x16xf32>
97/// ```
98/// Not all ops might be canonicalizable this way, but for those that can be,
99/// this method provides a check that it is worth doing the canonicalization.
100bool canFoldIntoProducerOp(CastOp castOp);
101
102/// Return true if any of the operands of `op` is a CastOp that can be folded
103/// into its consumer, i.e. `op`. This is effectively a convenience wrapper for
104/// `canFoldIntoProducerOp`.
105bool hasFoldableTensorCastOperand(Operation *op);
106
107/// Assuming that `op` contains at least one operand that is a foldable CastOp
108/// (i.e. `hasFoldableTensorCastOperand` returns true), calculate the updated
109/// operands.
110SmallVector<Value>
111getUpdatedOperandsAfterCastOpFolding(DestinationStyleOpInterface op,
112 SmallVector<Type> &newResTy);
113
114/// Performs folding of any operand of `op` if it comes from a tensor::CastOp
115/// that can be folded.
116LogicalResult foldTensorCast(Operation *op);
117
118/// Return the dimension of the given tensor value.
119OpFoldResult getMixedSize(OpBuilder &builder, Location loc, Value value,
120 int64_t dim);
121
122/// Return the dimensions of the given tensor value.
123SmallVector<OpFoldResult> getMixedSizes(OpBuilder &builder, Location loc,
124 Value value);
125
126/// Infer a slice type for the given sizes and exact dropped-dimension mask. The
127/// result shape omits the sizes whose corresponding bits are set in
128/// `droppedDims`. The encoding of `sourceTensorType` is propagated to the
129/// inferred result type.
130RankedTensorType inferSliceType(RankedTensorType sourceTensorType,
131 ArrayRef<int64_t> staticSizes,
132 const llvm::SmallBitVector &droppedDims);
133/// SSA-valued sizes resolve to dynamic dimensions in the inferred type. Only
134/// static unit dimensions may be dropped from the source type to produce the
135/// result slice type.
136RankedTensorType inferSliceType(RankedTensorType sourceTensorType,
137 ArrayRef<OpFoldResult> sizes,
138 const llvm::SmallBitVector &droppedDims);
139
140/// Create a rank-reducing ExtractSliceOp @[0 .. 0] with strides [1 .. 1] and
141/// appropriate sizes (i.e. `tensor.getSizes()`) to reduce the rank of `tensor`
142/// to that of `targetType`.
143Value createCanonicalRankReducingExtractSliceOp(OpBuilder &b, Location loc,
144 Value tensor,
145 RankedTensorType targetType);
146
147/// Create a rank-reducing InsertSliceOp @[0 .. 0] with strides [1 .. 1] and
148/// appropriate sizes (i.e. `dest.getSizes()`). The result is a new tensor with
149/// rank increased to that of `dest`, obtained by inserting `tensor` into `dest`
150/// at the canonical [0 .. 0] position.
151Value createCanonicalRankReducingInsertSliceOp(OpBuilder &b, Location loc,
152 Value tensor, Value dest);
153
154/// This is a helper function for DestinationStyleOpInterface. If there is a
155/// destination operand for the given OpResult, return that operand. Otherwise,
156/// return an empty tensor (`tensor.empty`) with the shape of the OpResult.
157/// Dynamic dimensions are queried via ReifyRankedShapedTypeOpInterface.
158FailureOr<Value> getOrCreateDestination(OpBuilder &b, Location loc,
159 OpResult opResult);
160
161/// This is a helper function for DestinationStyleOpInterface. Get or create
162/// destinations for every tensor OpResult of the given op.
163LogicalResult getOrCreateDestinations(OpBuilder &b, Location loc, Operation *op,
164 SmallVector<Value> &result);
165
166/// Tests if types are the same when ignoring encoding on ranked tensors.
167bool isSameTypeWithoutEncoding(Type tp1, Type tp2);
168
169/// Function to control the folding of constant and extract slice.
170using ControlConstantExtractSliceFusionFn = std::function<bool(ExtractSliceOp)>;
171
172/// Patterns to fold the extract slice op with its constant operand.
174 RewritePatternSet &patterns,
175 const ControlConstantExtractSliceFusionFn &controlFn =
176 [](ExtractSliceOp op) {
177 // Disable by default because the folding can generate a large
178 // constant tensor, which would affect the compile time and storage.
179 return false;
180 });
181
182/// Patterns to fold extracts of a collapse_shaped tensor to an extract of the
183/// source tensor.
185
186} // namespace tensor
187} // namespace mlir
188
189#endif // MLIR_DIALECT_TENSOR_IR_TENSOR_H_
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
This class helps build Operations.
Definition Builders.h:210
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:229
LogicalResult foldTensorCast(Operation *op)
Performs folding of any operand of op if it comes from a tensor::CastOp that can be folded.
bool hasFoldableTensorCastOperand(Operation *op)
Return true if any of the operands of op is a CastOp that can be folded into its consumer,...
void populateFoldConstantExtractSlicePatterns(RewritePatternSet &patterns, const ControlConstantExtractSliceFusionFn &controlFn=[](ExtractSliceOp op) { return false;})
Patterns to fold the extract slice op with its constant operand.
bool canFoldIntoProducerOp(CastOp castOp)
Determines whether the tensor::CastOp casts to a more static version of the source tensor.
SmallVector< Value > getUpdatedOperandsAfterCastOpFolding(DestinationStyleOpInterface op, SmallVector< Type > &newResTy)
Assuming that op contains at least one operand that is a foldable CastOp (i.e.
bool canFoldIntoConsumerOp(CastOp castOp)
Determines whether tensor::CastOp casts to a more dynamic version of the source tensor.
Value createCanonicalRankReducingInsertSliceOp(OpBuilder &b, Location loc, Value tensor, Value dest)
Create a rank-reducing InsertSliceOp @[0 .
Value createCanonicalRankReducingExtractSliceOp(OpBuilder &b, Location loc, Value tensor, RankedTensorType targetType)
Create a rank-reducing ExtractSliceOp @[0 .
bool isSameTypeWithoutEncoding(Type tp1, Type tp2)
Tests if types are the same when ignoring encoding on ranked tensors.
RankedTensorType inferSliceType(RankedTensorType sourceTensorType, ArrayRef< int64_t > staticSizes, const llvm::SmallBitVector &droppedDims)
Infer a slice type for the given sizes and exact dropped-dimension mask.
OpFoldResult getMixedSize(OpBuilder &builder, Location loc, Value value, int64_t dim)
Return the dimension of the given tensor value.
Definition TensorOps.cpp:82
void populateFoldCollapseExtractPatterns(RewritePatternSet &patterns)
Patterns to fold extracts of a collapse_shaped tensor to an extract of the source tensor.
FailureOr< Value > getOrCreateDestination(OpBuilder &b, Location loc, OpResult opResult)
This is a helper function for DestinationStyleOpInterface.
bool preservesStaticInformation(Type source, Type target)
Returns true if target is a ranked tensor type that preserves static information available in the sou...
SmallVector< OpFoldResult > getMixedSizes(OpBuilder &builder, Location loc, Value value)
Return the dimensions of the given tensor value.
Definition TensorOps.cpp:91
LogicalResult getOrCreateDestinations(OpBuilder &b, Location loc, Operation *op, SmallVector< Value > &result)
This is a helper function for DestinationStyleOpInterface.
std::function< bool(ExtractSliceOp)> ControlConstantExtractSliceFusionFn
Function to control the folding of constant and extract slice.
Definition Tensor.h:170
Include the generated interface declarations.
SmallVector< Range, 8 > getOrCreateRanges(OffsetSizeAndStrideOpInterface op, OpBuilder &b, Location loc)
Return the list of Range (i.e.