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