MLIR 22.0.0git
ConversionUtils.cpp
Go to the documentation of this file.
1//===- ConversionUtils.cpp ------------------------------------------------===//
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// Utility functions for TOSA lowering
10//
11//===----------------------------------------------------------------------===//
12
15
16using namespace mlir;
17using namespace mlir::tosa;
18
20mlir::tosa::getNParallelLoopsAttrs(unsigned nParallelLoops) {
21 return SmallVector<utils::IteratorType>(nParallelLoops,
22 utils::IteratorType::parallel);
23}
24
27 SmallVector<Value> condensedValues;
28 for (auto value : values)
29 if (value)
30 condensedValues.push_back(value);
31 return condensedValues;
32}
33
35 Value max, OpBuilder &rewriter) {
36 Value minValue = arith::MinimumFOp::create(rewriter, loc, arg, max);
37 return arith::MaximumFOp::create(rewriter, loc, minValue, min);
38}
39
41 OpBuilder &rewriter, bool isUnsigned) {
42 if (isUnsigned) {
43 auto minOrArg = arith::MaxUIOp::create(rewriter, loc, min, arg);
44 return arith::MinUIOp::create(rewriter, loc, max, minOrArg);
45 }
46 auto minOrArg = arith::MaxSIOp::create(rewriter, loc, min, arg);
47 return arith::MinSIOp::create(rewriter, loc, max, minOrArg);
48}
49
50bool mlir::tosa::validIntegerRange(IntegerType ty, int64_t value) {
51 uint64_t bitwidth = ty.getIntOrFloatBitWidth();
52 if (ty.getSignedness() == IntegerType::Unsigned) {
53 uint64_t uvalue = value;
54 APInt intMin = APInt::getMinValue(bitwidth);
55 APInt intMax = APInt::getMaxValue(bitwidth);
56 return uvalue >= intMin.getZExtValue() && uvalue <= intMax.getZExtValue();
57 }
58
59 APInt intMin = APInt::getSignedMinValue(bitwidth);
60 APInt intMax = APInt::getSignedMaxValue(bitwidth);
61 return value >= intMin.getSExtValue() && value <= intMax.getSExtValue();
62}
63
64namespace {
65// Given two tensors of high and low ranks, derive the output shape
66// to reshape the lower rank to.
67// Examples:
68// If lower=[c], higher=[a, b, c], [c] reshaped into [1, 1, c].
69// If lower=[b, c], higher=[a, b, c], [b, c] reshaped into [1, b, c].
70// If lower=[a], higher=[a, a], [a] reshaped into [1, a].
71// If lower=[a], target=[a, b, a], [a] reshaped into [1, 1, a].
72// If lower=[], target=[a, b, c], [] reshaped into [1, 1, 1].
73LogicalResult
74computeReshapeOutput(ArrayRef<int64_t> higherRankShape,
75 ArrayRef<int64_t> lowerRankShape,
76 SmallVectorImpl<int64_t> &reshapeOutputShape) {
77 // Initialize new shapes with [1] * higherRank.
78 int64_t higherRank = higherRankShape.size();
79 int64_t lowerRank = lowerRankShape.size();
80 reshapeOutputShape.assign(higherRank, 1);
81
82 int64_t higherRankDim;
83 int64_t lowerRankDim;
84 const int64_t rankDiff = higherRank - lowerRank;
85
86 for (int64_t i = lowerRank - 1; i >= 0; i--) {
87 higherRankDim = higherRankShape[i + rankDiff];
88 lowerRankDim = lowerRankShape[i];
89
90 if (lowerRankDim != 1 && higherRankDim != 1 &&
91 lowerRankDim != higherRankDim)
92 return failure();
93
94 reshapeOutputShape[i + rankDiff] = lowerRankDim == 1 ? 1 : lowerRankDim;
95 }
96 return success();
97}
98} // namespace
99
101 Value &input1, Value &input2) {
102 ImplicitLocOpBuilder builder(loc, rewriter);
103 return EqualizeRanks(builder, input1, input2);
104}
105
107 Value &input1, Value &input2) {
108 auto input1Ty = llvm::dyn_cast<RankedTensorType>(input1.getType());
109 auto input2Ty = llvm::dyn_cast<RankedTensorType>(input2.getType());
110
111 if (!input1Ty || !input2Ty) {
112 return failure();
113 }
114
115 int64_t input1Rank = input1Ty.getRank();
116 int64_t input2Rank = input2Ty.getRank();
117
118 if (input1Rank == input2Rank)
119 return success();
120
121 Value higherTensorValue, lowerTensorValue;
122 if (input1Rank > input2Rank) {
123 higherTensorValue = input1;
124 lowerTensorValue = input2;
125 } else {
126 higherTensorValue = input2;
127 lowerTensorValue = input1;
128 }
129
130 ArrayRef<int64_t> higherRankShape =
131 llvm::cast<RankedTensorType>(higherTensorValue.getType()).getShape();
132 ArrayRef<int64_t> lowerRankShape =
133 llvm::cast<RankedTensorType>(lowerTensorValue.getType()).getShape();
134
135 SmallVector<int64_t, 4> reshapeOutputShape;
136
137 if (computeReshapeOutput(higherRankShape, lowerRankShape, reshapeOutputShape)
138 .failed())
139 return failure();
140
141 auto reshapeInputType =
142 llvm::cast<RankedTensorType>(lowerTensorValue.getType());
143 auto reshapeOutputType = RankedTensorType::get(
144 ArrayRef<int64_t>(reshapeOutputShape), reshapeInputType.getElementType());
145 auto reshapeOutputShapeValue = getTosaConstShape(builder, reshapeOutputShape);
146
147 auto reshapeLower = tosa::ReshapeOp::create(
148 builder, reshapeOutputType, lowerTensorValue, reshapeOutputShapeValue);
149
150 if (input1Rank > input2Rank) {
151 input1 = higherTensorValue;
152 input2 = reshapeLower.getResult();
153 } else {
154 input1 = reshapeLower.getResult();
155 input2 = higherTensorValue;
156 }
157
158 return success();
159}
160
163 auto attr = builder.getIndexTensorAttr(convertFromMlirShape(shape));
164 auto type = mlir::tosa::shapeType::get(builder.getContext(), shape.size());
165 mlir::Operation *mlirOp = tosa::ConstShapeOp::create(builder, type, attr);
166 return mlirOp->getResult(0);
167}
168
174
176 return to_vector(llvm::map_range(shape, [](int64_t dim) {
177 return ShapedType::isDynamic(dim) ? -1 : dim;
178 }));
179}
180
182 llvm::SmallVector<int64_t> &resultShape) {
183 if (!op) {
184 return false;
185 }
186 if (auto constOp = mlir::dyn_cast<tosa::ConstShapeOp>(op)) {
187 Attribute constOpAttr = constOp->getAttr("values");
188 DenseElementsAttr elementsAttr = cast<DenseElementsAttr>(constOpAttr);
189 for (int i = 0; i < elementsAttr.size(); i++) {
190 int64_t val = elementsAttr.getValues<int64_t>()[i];
191 resultShape.push_back(val);
192 }
193 return true;
194 }
195 // for undefined op, return false.
196 return false;
197}
198
199// returns a small vector of int64_t values that attr contains
202 if (attr.isSplat()) {
203 int64_t v = attr.getSplatValue<APInt>().getSExtValue();
204 return SmallVector<int64_t>(rank, v);
205 }
206
207 if (auto intArrayAttr = llvm::dyn_cast<DenseIntElementsAttr>(attr)) {
209 for (APInt val : intArrayAttr.getValues<APInt>()) {
210 vec.push_back(val.getSExtValue());
211 }
212 return vec;
213 }
214 return {};
215}
216
218 ShapedType indicesType, DenseIntElementsAttr indicesAttr) {
219 llvm::ArrayRef<int64_t> const indicesShape = indicesType.getShape();
220 const unsigned int indicesRank = indicesShape.size();
221 const unsigned int lastDimSize = indicesShape[indicesRank - 1];
222
223 // check each batch of indices from the flat indicesAttr values
224 // for duplicates
225 auto const indicesValues = indicesAttr.getValues<int32_t>();
226 assert(
227 (indicesValues.size() % lastDimSize == 0) &&
228 "Constant indices data length should be a multiple of indicesShape[-1]");
229
230 std::vector<uint64_t> indices(lastDimSize);
231 for (auto beg = indicesValues.begin(); beg < indicesValues.end();
232 beg += lastDimSize) {
233 std::copy(beg, beg + lastDimSize, indices.begin());
234 std::sort(indices.begin(), indices.end());
235 if (std::adjacent_find(indices.begin(), indices.end()) != indices.end()) {
236 // found duplicate values in indices in batch
237 return false;
238 }
239 }
240
241 return true;
242}
return success()
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
Attributes are known-constant values of operations.
Definition Attributes.h:25
DenseIntElementsAttr getIndexTensorAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:193
MLIRContext * getContext() const
Definition Builders.h:56
An attribute that represents a reference to a dense vector or tensor object.
auto getValues() const
Return the held element values as a range of the given type.
std::enable_if_t<!std::is_base_of< Attribute, T >::value||std::is_same< Attribute, T >::value, T > getSplatValue() const
Return the splat value for this attribute.
int64_t size() const
Returns the number of elements held by this attribute.
bool isSplat() const
Returns true if this attribute corresponds to a splat, i.e.
An attribute that represents a reference to a dense integer vector or tensor object.
ImplicitLocOpBuilder maintains a 'current location', allowing use of the create<> method without spec...
Definition Builders.h:630
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:207
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:407
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Value clampFloatHelper(Location loc, Value arg, Value min, Value max, OpBuilder &rewriter)
SmallVector< utils::IteratorType > getNParallelLoopsAttrs(unsigned nParallelLoops)
bool hasUniqueConstantScatterIndices(ShapedType indicesType, DenseIntElementsAttr indicesAttr)
SmallVector< Value > condenseValues(const SmallVector< Value > &values)
LogicalResult EqualizeRanks(PatternRewriter &rewriter, Location loc, Value &input1, Value &input2)
Common code to create the reshape op where necessary to make the rank of two values equal.
SmallVector< int64_t > convertFromIntAttr(const DenseElementsAttr &attr, const int rank)
bool validIntegerRange(IntegerType ty, int64_t value)
Value getTosaConstShape(ImplicitLocOpBuilder &builder, llvm::ArrayRef< int64_t > shape)
SmallVector< int64_t > convertFromMlirShape(ArrayRef< int64_t > shape)
Value clampIntHelper(Location loc, Value arg, Value min, Value max, OpBuilder &rewriter, bool isUnsigned)
bool getConstShapeValues(Operation *op, llvm::SmallVector< int64_t > &result_shape)
Include the generated interface declarations.