MLIR 24.0.0git
TosaToLinalgNamed.cpp
Go to the documentation of this file.
1//===- TosaToLinalgNamed.cpp - Lowering Tosa to Linalg Named Ops ----------===//
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// These rewriters lower from the Tosa to the Linalg named ops.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TosaToLinalgUtils.h"
24#include "mlir/IR/Matchers.h"
27#include "llvm/ADT/SmallVectorExtras.h"
28#include "llvm/ADT/TypeSwitch.h"
29
30#include <optional>
31#include <type_traits>
32
33using namespace mlir;
34using namespace mlir::tosa;
35
36// Return the linalg.elementwise kind that is semantically equivalent to the
37// given TOSA elementwise op for the provided element type, or std::nullopt if
38// the op has no direct linalg.elementwise counterpart. Only ops whose TOSA
39// lowering maps to a single linalg.elementwise function are handled; the more
40// involved lowerings (e.g. quantized negate, mul with shift, casts) are left to
41// the generic TosaToLinalg conversion.
42static std::optional<linalg::ElementwiseKind>
44 using linalg::ElementwiseKind;
45 const bool isFloat = isa<FloatType>(elementTy);
46 const bool isSignlessInt = elementTy.isSignlessInteger();
47 const bool isBoolean = elementTy.isInteger(1);
48
49 // Unary ops. linalg.elementwise only defines these on floating point types.
50 if (isFloat) {
51 if (isa<tosa::AbsOp>(op))
52 return ElementwiseKind::abs;
53 if (isa<tosa::CeilOp>(op))
54 return ElementwiseKind::ceil;
55 if (isa<tosa::FloorOp>(op))
56 return ElementwiseKind::floor;
57 if (isa<tosa::ExpOp>(op))
58 return ElementwiseKind::exp;
59 if (isa<tosa::LogOp>(op))
60 return ElementwiseKind::log;
61 if (isa<tosa::RsqrtOp>(op))
62 return ElementwiseKind::rsqrt;
63 if (isa<tosa::SinOp>(op))
64 return ElementwiseKind::sin;
65 if (isa<tosa::CosOp>(op))
66 return ElementwiseKind::cos;
67 if (isa<tosa::TanhOp>(op))
68 return ElementwiseKind::tanh;
69 if (isa<tosa::ErfOp>(op))
70 return ElementwiseKind::erf;
71 if (isa<tosa::ReciprocalOp>(op))
72 return ElementwiseKind::reciprocal;
73 if (isa<tosa::PowOp>(op))
74 return ElementwiseKind::powf;
75 }
76
77 // Binary ops defined on both floating point and (non-boolean) integers.
78 if (isFloat || (isSignlessInt && !isBoolean)) {
79 if (isa<tosa::AddOp>(op))
80 return ElementwiseKind::add;
81 if (isa<tosa::SubOp>(op))
82 return ElementwiseKind::sub;
83 }
84
85 // Signed integer division.
86 if (isSignlessInt && !isBoolean && isa<tosa::IntDivOp>(op))
87 return ElementwiseKind::div;
88
89 // Multiply maps to a plain elementwise multiply only when no rescaling shift
90 // is requested (the shift must be a constant zero) and the inputs already
91 // share the result element type. The shifted/rescaled integer variant is left
92 // to the generic conversion.
93 if (auto mulOp = dyn_cast<tosa::MulOp>(op)) {
94 DenseElementsAttr shiftAttr;
95 const bool zeroShift =
96 matchPattern(mulOp.getShift(), m_Constant(&shiftAttr)) &&
97 shiftAttr.getValues<APInt>()[0].isZero();
98 const bool matchingTypes =
99 cast<ShapedType>(mulOp.getInput1().getType()).getElementType() ==
100 elementTy &&
101 cast<ShapedType>(mulOp.getInput2().getType()).getElementType() ==
102 elementTy;
103 if ((isFloat || (isSignlessInt && !isBoolean)) && zeroShift &&
104 matchingTypes)
105 return ElementwiseKind::mul;
106 }
107
108 // Negate maps to floating-point negation only when the zero points are zero.
109 // The quantized integer variant is left to the generic conversion.
110 if (auto negateOp = dyn_cast<tosa::NegateOp>(op)) {
111 if (isFloat) {
112 FailureOr<int64_t> inZp = negateOp.getInput1ZeroPoint();
113 FailureOr<int64_t> outZp = negateOp.getOutputZeroPoint();
114 if (succeeded(inZp) && succeeded(outZp) && *inZp == 0 && *outZp == 0)
115 return ElementwiseKind::negf;
116 }
117 }
118
119 // Maximum/minimum. The NaN "IGNORE" mode requires an additional compare and
120 // select that linalg.elementwise cannot express, so only the default
121 // "PROPAGATE" mode is handled for floating point types.
122 auto nanModeIsPropagate = [](auto tosaOp) {
123 return tosaOp.getNanMode() == NanPropagationMode::PROPAGATE;
124 };
125 if (isFloat || (isSignlessInt && !isBoolean)) {
126 if (auto maxOp = dyn_cast<tosa::MaximumOp>(op)) {
127 if (!isFloat || nanModeIsPropagate(maxOp))
128 return ElementwiseKind::max_signed;
129 }
130 if (auto minOp = dyn_cast<tosa::MinimumOp>(op)) {
131 if (!isFloat || nanModeIsPropagate(minOp))
132 return ElementwiseKind::min_signed;
133 }
134 }
135
136 // Select (ternary) for valid element types.
137 if ((isFloat || isSignlessInt || isBoolean) && isa<tosa::SelectOp>(op))
138 return ElementwiseKind::select;
139
140 return std::nullopt;
141}
142
143std::optional<linalg::ElementwiseKind>
145 if (op->getNumResults() != 1)
146 return std::nullopt;
147
148 // Make sure all operands and result have static sizes
149 for (Value operand : op->getOperands()) {
150 auto operandTy = dyn_cast<RankedTensorType>(operand.getType());
151 if (!operandTy || !operandTy.hasStaticShape())
152 return std::nullopt;
153 }
154 auto resultTy = dyn_cast<RankedTensorType>(op->getResult(0).getType());
155 if (!resultTy || !resultTy.hasStaticShape())
156 return std::nullopt;
157
158 return getElementwiseKind(op, resultTy.getElementType());
159}
160
162 OpFoldResult paddingValue, OpBuilder &rewriter) {
163 // Input should be padded only if necessary.
164 if (llvm::all_of(pad, [](int64_t p) { return p == 0; }))
165 return input;
166
167 ShapedType inputTy = cast<ShapedType>(input.getType());
168 Type inputETy = inputTy.getElementType();
169 auto inputShape = inputTy.getShape();
170
171 assert((inputShape.size() * 2) == pad.size());
172
173 SmallVector<int64_t, 4> paddedShape;
176 for (size_t i : llvm::seq(inputShape.size())) {
177 auto lowPad = pad[i * 2];
178 auto highPad = pad[i * 2 + 1];
179 if (ShapedType::isDynamic(inputShape[i]))
180 paddedShape.push_back(inputShape[i]);
181 else
182 paddedShape.push_back(inputShape[i] + highPad + lowPad);
183 lowIndices.push_back(rewriter.getIndexAttr(lowPad));
184 highIndices.push_back(rewriter.getIndexAttr(highPad));
185 }
186
187 Value padValue = dyn_cast<Value>(paddingValue);
188 if (!padValue) {
189 auto padAttr = cast<TypedAttr>(cast<Attribute>(paddingValue));
190 padValue = arith::ConstantOp::create(rewriter, loc, padAttr);
191 }
192
193 return tensor::PadOp::create(rewriter, loc,
194 RankedTensorType::get(paddedShape, inputETy),
195 input, lowIndices, highIndices, padValue);
196}
197
198static mlir::Value
200 Value conv, Value result,
201 ArrayRef<AffineMap> indexingMaps) {
202 ShapedType resultTy = cast<ShapedType>(conv.getType());
203 return linalg::GenericOp::create(
204 rewriter, loc, resultTy, ValueRange({bias, conv}), result,
205 indexingMaps, getNParallelLoopsAttrs(resultTy.getRank()),
206 [](OpBuilder &builder, Location loc, ValueRange args) {
207 Value biasVal = args[0];
208 Type resType = args[1].getType();
209 if (resType != biasVal.getType()) {
210 biasVal =
211 arith::ExtSIOp::create(builder, loc, resType, biasVal);
212 }
213 Value added =
214 arith::AddIOp::create(builder, loc, biasVal, args[1]);
215 linalg::YieldOp::create(builder, loc, added);
216 })
217 .getResult(0);
218}
219
220// Construct the affine map that a linalg generic would use to broadcast the
221// source tensor into the shape of the result tensor.
223 Value result) {
224 ShapedType resultTy = cast<ShapedType>(result.getType());
225 ShapedType sourceTy = cast<ShapedType>(source.getType());
226 const int64_t resultRank = resultTy.getRank();
227 const int64_t sourceRank = sourceTy.getRank();
228
229 // The source tensor is broadcast to all the outer dimensions of the
230 // result tensor.
231 SmallVector<AffineExpr> sourceDims;
232 // In the case of a rank one source tensor with a single element TOSA
233 // specifies that the value be broadcast meaning we need an edge case for a
234 // constant map.
235 assert(sourceTy.hasStaticShape() &&
236 "Dynamic broadcasting shapes not supported!");
237 if (sourceRank == 1 && sourceTy.getDimSize(0) == 1) {
238 sourceDims.push_back(rewriter.getAffineConstantExpr(0));
239 } else {
240 for (auto dim : llvm::seq<int64_t>(0, sourceRank)) {
241 auto expr = rewriter.getAffineDimExpr(dim + resultRank - sourceRank);
242 sourceDims.push_back(expr);
243 }
244 }
245
246 return AffineMap::get(/*dimCount=*/resultRank,
247 /*symbolCount=*/0, sourceDims, rewriter.getContext());
248}
249
250// Broadcast the source value to all the outer dimensions of the result value.
251// If required, the element type is expanded using an arith.extsi or arith.extf
252// operation as appropriate.
254 Location loc, Value source,
255 Value result) {
256 ShapedType resultTy = cast<ShapedType>(result.getType());
257 const int64_t resultRank = resultTy.getRank();
258 // Creating maps for the input and output of the broacast-like generic op.
259 SmallVector<AffineMap, 2> indexingMaps;
260 indexingMaps.push_back(getBroadcastingMap(rewriter, source, result));
261 indexingMaps.push_back(rewriter.getMultiDimIdentityMap(resultRank));
262
263 // Build the broadcast-like operation as a linalg.generic.
264 return linalg::GenericOp::create(
265 rewriter, loc, resultTy, ValueRange({source}), result,
266 indexingMaps, getNParallelLoopsAttrs(resultTy.getRank()),
267 [&resultTy](OpBuilder &builder, Location loc, ValueRange args) {
268 Value biasVal = args[0];
269 Type resType = args[1].getType();
270 if (resType != biasVal.getType()) {
271 biasVal =
272 resultTy.getElementType().isFloat()
273 ? arith::ExtFOp::create(
274 builder, loc, TypeRange{resType},
275 ValueRange{biasVal}, arith::ExtFOp::Properties{})
276 .getResult()
277 : arith::ExtSIOp::create(builder, loc, resType,
278 biasVal)
279 .getResult();
280 }
281 linalg::YieldOp::create(builder, loc, biasVal);
282 })
283 .getResult(0);
284}
285
287 ImplicitLocOpBuilder &builder) {
288 return arith::ConstantIndexOp::create(builder, attr);
289}
290
291// Calculating the output width/height using the formula:
292// H = ((IH+pad_top+pad_bottom-(dilation_y*(KH-1)+1))/stride_y)+1
293// W = ((IW+pad_left+pad_right-(dilation_x*(KW-1)+1))/stride_x)+1
294
296 int64_t padBeforeAttr,
297 int64_t padAfterAttr, Value kernelDim,
298 int64_t strideAttr,
299 int64_t dilationAttr,
300 OpBuilder &rewriter) {
301 ImplicitLocOpBuilder builder(loc, rewriter);
302 auto one = arith::ConstantOp::create(rewriter, loc,
303 IntegerAttr::get(inputDim.getType(), 1));
304 Value padBefore = reifyConstantDim(padBeforeAttr, builder);
305 Value paddedBefore = arith::AddIOp::create(builder, inputDim, padBefore);
306 Value padAfter = reifyConstantDim(padAfterAttr, builder);
307 Value paddedAfter = arith::AddIOp::create(builder, paddedBefore, padAfter);
308
309 Value subOne = arith::SubIOp::create(builder, kernelDim, one);
310 Value dilation = reifyConstantDim(dilationAttr, builder);
311 Value dilated = arith::MulIOp::create(builder, dilation, subOne);
312 Value addOne = arith::AddIOp::create(builder, dilated, one);
313
314 Value subtract = arith::SubIOp::create(builder, paddedAfter, addOne);
315 Value stride = reifyConstantDim(strideAttr, builder);
316 Value divide = arith::DivUIOp::create(builder, subtract, stride);
317 return arith::AddIOp::create(builder, divide, one);
318}
319
320// Creates a vector of the dynamic output dims for Conv2D and Depthwise_Conv2D
322 Location loc, Value input, Value weight, ShapedType resultTy,
323 ArrayRef<int64_t> padAttr, ArrayRef<int64_t> strideAttr,
324 ArrayRef<int64_t> dilationAttr, ArrayRef<int64_t> inputSizeDims,
325 ArrayRef<int64_t> kernelSizeDims, OpBuilder &rewriter) {
326 ShapedType inputTy = cast<ShapedType>(input.getType());
327 int64_t inputRank = inputTy.getRank();
328
329 SmallVector<Value> dynDims;
330 dynDims.resize(resultTy.getRank());
331
332 for (uint32_t i = 0, s = inputSizeDims.size(); i < s; ++i) {
333 int64_t inputDim = inputSizeDims[i];
334 int64_t kernelDim = kernelSizeDims[i];
335 if (resultTy.isDynamicDim(inputDim)) {
336 auto padTop = padAttr[i * 2];
337 auto padBottom = padAttr[i * 2 + 1];
338 auto stride = strideAttr[i];
339 auto dilation = dilationAttr[i];
340 Value initDynDim = tensor::DimOp::create(rewriter, loc, input, inputDim);
341 Value kernelDynDim =
342 tensor::DimOp::create(rewriter, loc, weight, kernelDim);
343 // H = F(IH, pad_top, pad_bottom, dilation_y, KH, stride_y)
344 dynDims[inputDim] =
345 getConvOrPoolOutputDim(loc, initDynDim, padTop, padBottom,
346 kernelDynDim, stride, dilation, rewriter);
347 }
348 }
349
350 // Get the batch/channels dimensions.
351 for (int i = 0; i < inputRank; i++) {
352 if (resultTy.isDynamicDim(i) && !dynDims[i])
353 dynDims[i] = tensor::DimOp::create(rewriter, loc, input, i);
354 }
355
356 SmallVector<Value> filteredDims = condenseValues(dynDims);
357 return filteredDims;
358}
359
360// Creates a map to collapse the last dimension of the Depthwise convolution op
361// due to a shape mismatch
363 int64_t outputRank, SmallVector<ReassociationExprs, 4> &reassociationMap,
364 OpBuilder &rewriter) {
365 reassociationMap.resize(outputRank);
366 for (int i = 0; i < outputRank; i++) {
367 reassociationMap[i].push_back(rewriter.getAffineDimExpr(i));
368 }
369 reassociationMap[outputRank - 1].push_back(
370 rewriter.getAffineDimExpr(outputRank));
371}
372
374 Location loc, Value zeroPoint,
375 StringRef message) {
376 Type zeroPointType = zeroPoint.getType();
377 if (zeroPointType.isSignlessInteger(8))
378 return;
379
380 Value zero = arith::ConstantOp::create(rewriter, loc,
381 rewriter.getZeroAttr(zeroPointType));
382 Value isZero;
383 if (isa<FloatType>(zeroPointType)) {
384 isZero = arith::CmpFOp::create(rewriter, loc, arith::CmpFPredicate::OEQ,
385 zeroPoint, zero);
386 } else {
387 isZero = arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::eq,
388 zeroPoint, zero);
389 }
390 cf::AssertOp::create(rewriter, loc, isZero, rewriter.getStringAttr(message));
391}
392
393namespace {
394template <typename TosaConvOp, typename LinalgConvOp, typename LinalgConvQOp>
395class ConvConverter : public OpConversionPattern<TosaConvOp> {
396public:
397 using OpConversionPattern<TosaConvOp>::OpConversionPattern;
398 LogicalResult
399 matchAndRewrite(TosaConvOp op, typename TosaConvOp::Adaptor adaptor,
400 ConversionPatternRewriter &rewriter) const final {
401 Location loc = op->getLoc();
402 Value input = op->getOperand(0);
403 Value weight = op->getOperand(1);
404 Value bias = op->getOperand(2);
405
406 ShapedType inputTy = cast<ShapedType>(input.getType());
407 ShapedType weightTy = cast<ShapedType>(weight.getType());
408 ShapedType biasTy = cast<ShapedType>(bias.getType());
409 ShapedType resultTy = cast<ShapedType>(op->getResult(0).getType());
410
411 Type inputETy = inputTy.getElementType();
412
413 DenseI64ArrayAttr padAttr = op.getPadAttr();
414 DenseI64ArrayAttr strideTosaAttr = op.getStrideAttr();
415 DenseI64ArrayAttr dilationTosaAttr = op.getDilationAttr();
416
417 Type accETy = getAccumulationType(op.getAccType());
418 Type accTy = RankedTensorType::get(resultTy.getShape(), accETy);
419
420 // Get and verify zero points.
421 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
422 FailureOr<int64_t> maybeWZp = op.getWeightZeroPoint();
423
424 bool isInputZpConstant = succeeded(maybeIZp);
425 bool isWeightZpConstant = succeeded(maybeWZp);
426
427 Value nonConstantInputZpScalar;
428 Value nonConstantWeightZpScalar;
429
430 if (isInputZpConstant) {
431 const int64_t inputZpConstant = *maybeIZp;
432 if (op.verifyInputZeroPoint(inputZpConstant).failed())
433 return rewriter.notifyMatchFailure(
434 op, "input zero point must be zero for non-int8 integer types");
435 } else {
436 Value index0 = arith::ConstantIndexOp::create(rewriter, loc, 0);
437 nonConstantInputZpScalar = tensor::ExtractOp::create(
438 rewriter, loc, adaptor.getInputZp(), ValueRange{index0});
440 rewriter, loc, nonConstantInputZpScalar,
441 "tosa.conv input zero point must be zero for non-int8 types");
442 }
443
444 if (isWeightZpConstant) {
445 const int64_t weightZpConstant = *maybeWZp;
446 if (op.verifyWeightZeroPoint(weightZpConstant).failed())
447 return rewriter.notifyMatchFailure(
448 op, "weight zero point must be zero for non-int8 integer types");
449 } else {
450 Value index0 = arith::ConstantIndexOp::create(rewriter, loc, 0);
451 nonConstantWeightZpScalar = tensor::ExtractOp::create(
452 rewriter, loc, adaptor.getWeightZp(), ValueRange{index0});
454 rewriter, loc, nonConstantWeightZpScalar,
455 "tosa.conv weight zero point must be zero for non-int8 types");
456 }
457
458 // Use the quantized op if either zero point is:
459 // - Constant and non-zero, or
460 // - Non-constant and of type i8.
461 bool useConvQOp =
462 (isInputZpConstant && *maybeIZp != 0) ||
463 (isWeightZpConstant && *maybeWZp != 0) ||
464 (!isInputZpConstant &&
465 nonConstantInputZpScalar.getType().isSignlessInteger(8)) ||
466 (!isWeightZpConstant &&
467 nonConstantWeightZpScalar.getType().isSignlessInteger(8));
468
469 if (!weightTy.hasStaticShape() || !biasTy.hasStaticShape())
470 return rewriter.notifyMatchFailure(
471 op, "tosa.conv ops require static shapes for weight and bias");
472
473 if (inputETy.isUnsignedInteger())
474 return rewriter.notifyMatchFailure(
475 op, "tosa.conv ops does not support unsigned integer input");
476
477 llvm::SmallVector<int64_t> inputSizeDims;
478 llvm::SmallVector<int64_t> kernelSizeDims;
479 for (int i = 1; i < resultTy.getRank() - 1; i++) {
480 inputSizeDims.push_back(i);
481 kernelSizeDims.push_back(i);
482 }
483
484 SmallVector<Value> filteredDims = inferDynamicDimsForConv(
485 loc, input, weight, resultTy, padAttr.asArrayRef(),
486 strideTosaAttr.asArrayRef(), dilationTosaAttr.asArrayRef(),
487 inputSizeDims, kernelSizeDims, rewriter);
488
489 auto weightShape = weightTy.getShape();
490
491 // Apply padding as necessary.
492 llvm::SmallVector<int64_t> pad;
493 pad.resize(2, 0);
494 llvm::append_range(pad, padAttr.asArrayRef());
495 pad.resize(pad.size() + 2, 0);
496
497 if (isInputZpConstant) {
498 const int64_t inputZpConstant = *maybeIZp;
499 TypedAttr padValue = rewriter.getZeroAttr(inputETy);
500 if (inputZpConstant != 0)
501 padValue = rewriter.getIntegerAttr(inputETy, inputZpConstant);
502 input = applyPad(loc, input, pad, padValue, rewriter);
503 } else {
504 // The non-constant input zero point already has the input's element type,
505 // so it can be used directly as the padding value.
506 input = applyPad(loc, input, pad, nonConstantInputZpScalar, rewriter);
507 }
508
509 if (4 == inputTy.getRank()) {
510 // For 2D convolutions, we need to check if the target convolution op
511 // wants a HWCF kernel layout.
512 bool wantHwcf =
513 useConvQOp ? std::is_same_v<LinalgConvQOp, linalg::Conv2DNhwcHwcfQOp>
514 : std::is_same_v<LinalgConvOp, linalg::Conv2DNhwcHwcfOp>;
515 if (wantHwcf) {
516 // Transpose the kernel to match dimension ordering of the linalg
517 // convolution operation.
518 // TODO(suderman): See if this can be efficiently folded - check whether
519 // the input is used anywhere else, if not fold the constant.
520 SmallVector<int32_t> weightPerm;
521 for (int i = 1; i < resultTy.getRank(); i++)
522 weightPerm.push_back(i);
523 weightPerm.push_back(0);
524
525 SmallVector<int64_t> newWeightShape;
526 for (auto dim : weightPerm)
527 newWeightShape.push_back(weightShape[dim]);
528 auto weightPermAttr = rewriter.getDenseI32ArrayAttr(weightPerm);
529 Type newWeightTy =
530 RankedTensorType::get(newWeightShape, weightTy.getElementType());
531 weight = tosa::TransposeOp::create(rewriter, loc, newWeightTy, weight,
532 weightPermAttr);
533 }
534 }
535
536 // For Conv3D transpose the kernel to match dimension ordering of the linalg
537 // convolution operation. Conv2D has a 1-1 mapping in linalg so better to
538 // map directly and then transpose later if desired.
539 if (5 == inputTy.getRank()) {
540 // TODO(suderman): See if this can be efficiently folded - check whether
541 // the input is used anywhere else, if not fold the constant.
542 SmallVector<int32_t> weightPerm;
543 for (int i = 1; i < resultTy.getRank(); i++)
544 weightPerm.push_back(i);
545 weightPerm.push_back(0);
546
547 SmallVector<int64_t> newWeightShape;
548 for (auto dim : weightPerm)
549 newWeightShape.push_back(weightShape[dim]);
550 auto weightPermAttr = rewriter.getDenseI32ArrayAttr(weightPerm);
551 Type newWeightTy =
552 RankedTensorType::get(newWeightShape, weightTy.getElementType());
553 weight = tosa::TransposeOp::create(rewriter, loc, newWeightTy, weight,
554 weightPermAttr);
555 }
556
557 // Extract the attributes for convolution.
558 ArrayRef<int64_t> stride = strideTosaAttr;
559 ArrayRef<int64_t> dilation = dilationTosaAttr;
560
561 // Create the convolution op.
562 auto strideAttr = rewriter.getI64TensorAttr(stride);
563 auto dilationAttr = rewriter.getI64TensorAttr(dilation);
564
565 Value biasEmptyTensor = tensor::EmptyOp::create(
566 rewriter, loc, resultTy.getShape(), accETy, filteredDims);
567
568 Value broadcastBias =
569 linalgBroadcastAndMaybeExt(rewriter, loc, bias, biasEmptyTensor);
570
571 if (useConvQOp) {
572 auto getQConvZpAsI32 = [&](FailureOr<int64_t> maybeZp,
573 Value nonConstantZpScalar) -> Value {
574 if (succeeded(maybeZp))
575 return arith::ConstantOp::create(
576 rewriter, loc, rewriter.getI32IntegerAttr(*maybeZp));
577 assert(nonConstantZpScalar &&
578 "expected a scalar for a non-constant zero point");
579 if (nonConstantZpScalar.getType().isSignlessInteger(8))
580 return arith::ExtSIOp::create(rewriter, loc, rewriter.getI32Type(),
581 nonConstantZpScalar);
582 // Non-int8 non-constant zero points were asserted to be zero above.
583 return arith::ConstantOp::create(rewriter, loc,
584 rewriter.getI32IntegerAttr(0));
585 };
586
587 Value iZpVal = getQConvZpAsI32(maybeIZp, nonConstantInputZpScalar);
588 Value kZpVal = getQConvZpAsI32(maybeWZp, nonConstantWeightZpScalar);
589
590 Value conv = LinalgConvQOp::create(
591 rewriter, loc, resultTy,
592 ValueRange{input, weight, iZpVal, kZpVal},
593 ValueRange{broadcastBias}, strideAttr, dilationAttr)
594 ->getResult(0);
595
596 rewriter.replaceOp(op, conv);
597 return success();
598 }
599
600 Value conv = LinalgConvOp::create(
601 rewriter, loc, accTy, ValueRange{input, weight},
602 ValueRange{broadcastBias}, strideAttr, dilationAttr)
603 ->getResult(0);
604
605 // We may need to truncate back to the result type if the accumulator was
606 // wider than the result.
607 if (resultTy != accTy)
608 conv = tosa::CastOp::create(rewriter, loc, resultTy, conv);
609
610 rewriter.replaceOp(op, conv);
611 return success();
612 }
613};
614
615class DepthwiseConvConverter
616 : public OpConversionPattern<tosa::DepthwiseConv2DOp> {
617public:
618 using OpConversionPattern<tosa::DepthwiseConv2DOp>::OpConversionPattern;
619 LogicalResult
620 matchAndRewrite(tosa::DepthwiseConv2DOp op, OpAdaptor adaptor,
621 ConversionPatternRewriter &rewriter) const final {
622 Location loc = op->getLoc();
623 Value input = op->getOperand(0);
624 Value weight = op->getOperand(1);
625 Value bias = op->getOperand(2);
626
627 ShapedType inputTy = cast<ShapedType>(input.getType());
628 ShapedType weightTy = cast<ShapedType>(weight.getType());
629 ShapedType biasTy = cast<ShapedType>(bias.getType());
630 ShapedType resultTy = cast<ShapedType>(op->getResult(0).getType());
631 int64_t resultRank = resultTy.getRank();
632
633 Type inputETy = inputTy.getElementType();
634 Type resultETy = resultTy.getElementType();
635
636 auto padAttr = op.getPadAttr();
637 auto strideTosaAttr = op.getStrideAttr();
638 auto dilationTosaAttr = op.getDilationAttr();
639
640 Type accETy = getAccumulationType(op.getAccType());
641
642 if (!weightTy.hasStaticShape() || !biasTy.hasStaticShape())
643 return rewriter.notifyMatchFailure(
644 op, "tosa.depthwise_conv ops require static shapes");
645
646 // Compute output dynamic dims
647 SmallVector<Value> filteredDims = inferDynamicDimsForConv(
648 loc, input, weight, resultTy, padAttr.asArrayRef(),
649 strideTosaAttr.asArrayRef(), dilationTosaAttr.asArrayRef(),
650 /*inputSizeDims=*/{1, 2},
651 /*kernelSizeDims=*/{0, 1}, rewriter);
652
653 // Get and verify zero points.
654
655 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
656 FailureOr<int64_t> maybeWZp = op.getWeightZeroPoint();
657 if (failed(maybeIZp))
658 return rewriter.notifyMatchFailure(
659 op, "input zero point cannot be statically determined");
660 if (failed(maybeWZp))
661 return rewriter.notifyMatchFailure(
662 op, "weight zero point cannot be statically determined");
663
664 const int64_t inputZpVal = *maybeIZp;
665 const int64_t weightZpVal = *maybeWZp;
666
667 if (op.verifyInputZeroPoint(inputZpVal).failed())
668 return rewriter.notifyMatchFailure(
669 op, "input zero point must be zero for non-int8 integer types");
670
671 if (op.verifyWeightZeroPoint(weightZpVal).failed())
672 return rewriter.notifyMatchFailure(
673 op, "weight zero point must be zero for non-int8 integer types");
674
675 bool hasNullZps = (inputZpVal == 0) && (weightZpVal == 0);
676 auto weightShape = weightTy.getShape();
677 auto resultShape = resultTy.getShape();
678
679 // Apply padding as necessary.
680 TypedAttr zeroAttr = rewriter.getZeroAttr(inputETy);
681 if (!hasNullZps) {
682 int64_t intMin =
683 APInt::getSignedMinValue(inputETy.getIntOrFloatBitWidth())
684 .getSExtValue();
685 int64_t intMax =
686 APInt::getSignedMaxValue(inputETy.getIntOrFloatBitWidth())
687 .getSExtValue();
688
689 if (inputZpVal < intMin || inputZpVal > intMax)
690 return rewriter.notifyMatchFailure(
691 op, "tosa.depthwise_conv op quantization has zp outside of input "
692 "range");
693
694 zeroAttr = rewriter.getIntegerAttr(inputETy, inputZpVal);
695 }
696
697 llvm::SmallVector<int64_t> pad;
698 pad.resize(2, 0);
699 llvm::append_range(pad, padAttr.asArrayRef());
700 pad.resize(pad.size() + 2, 0);
701
702 input = applyPad(loc, input, pad, zeroAttr, rewriter);
703
704 // Extract the attributes for convolution.
705 ArrayRef<int64_t> stride = strideTosaAttr;
706 ArrayRef<int64_t> dilation = dilationTosaAttr;
707
708 // Create the convolution op.
709 auto strideAttr = rewriter.getI64TensorAttr(stride);
710 auto dilationAttr = rewriter.getI64TensorAttr(dilation);
711 ShapedType linalgConvTy =
712 RankedTensorType::get({resultShape[0], resultShape[1], resultShape[2],
713 weightShape[2], weightShape[3]},
714 accETy);
715
716 auto resultZeroAttr = rewriter.getZeroAttr(accETy);
717 Value emptyTensor = tensor::EmptyOp::create(
718 rewriter, loc, linalgConvTy.getShape(), accETy, filteredDims);
719 Value zero = arith::ConstantOp::create(rewriter, loc, resultZeroAttr);
720 Value zeroTensor = linalg::FillOp::create(rewriter, loc, ValueRange{zero},
721 ValueRange{emptyTensor})
722 .result();
723
724 Value biasEmptyTensor = tensor::EmptyOp::create(
725 rewriter, loc, resultTy.getShape(), resultETy, filteredDims);
726
727 // Broadcast the initial value to the output tensor before convolving.
728 SmallVector<AffineMap, 4> indexingMaps;
729 indexingMaps.push_back(getBroadcastingMap(rewriter, bias, biasEmptyTensor));
730 indexingMaps.push_back(rewriter.getMultiDimIdentityMap(resultRank));
731 indexingMaps.push_back(rewriter.getMultiDimIdentityMap(resultRank));
732
733 if (hasNullZps) {
734 Value conv = linalg::DepthwiseConv2DNhwcHwcmOp::create(
735 rewriter, loc, linalgConvTy, ValueRange{input, weight},
736 ValueRange{zeroTensor}, strideAttr, dilationAttr)
737 .getResult(0);
738
739 // We may need to truncate back to the result type if the accumulator was
740 // wider than the result.
741 if (accETy != resultETy)
742 conv = tosa::CastOp::create(
743 rewriter, loc,
744 RankedTensorType::get(cast<ShapedType>(conv.getType()).getShape(),
745 resultETy),
746 conv);
747
748 SmallVector<ReassociationExprs, 4> reassociationMap;
749 createDepthwiseConvCollapseMap(resultRank, reassociationMap, rewriter);
750 Value convReshape = tensor::CollapseShapeOp::create(
751 rewriter, loc, resultTy, conv, reassociationMap);
752
753 Value result =
754 linalg::GenericOp::create(
755 rewriter, loc, resultTy, ValueRange({bias, convReshape}),
756 biasEmptyTensor, indexingMaps, getNParallelLoopsAttrs(resultRank),
757 [&](OpBuilder &nestedBuilder, Location nestedLoc,
758 ValueRange args) {
759 Value added;
760 if (llvm::isa<FloatType>(inputETy))
761 added = arith::AddFOp::create(nestedBuilder, loc, args[0],
762 args[1]);
763 else
764 added = arith::AddIOp::create(nestedBuilder, loc, args[0],
765 args[1]);
766 linalg::YieldOp::create(nestedBuilder, nestedLoc, added);
767 })
768 .getResult(0);
769 rewriter.replaceOp(op, result);
770 } else {
771 IntegerAttr iZp = rewriter.getI32IntegerAttr(inputZpVal);
772 IntegerAttr wZp = rewriter.getI32IntegerAttr(weightZpVal);
773 auto iZpVal = arith::ConstantOp::create(rewriter, loc, iZp);
774 auto kZpVal = arith::ConstantOp::create(rewriter, loc, wZp);
775 Value conv = linalg::DepthwiseConv2DNhwcHwcmQOp::create(
776 rewriter, loc, linalgConvTy,
777 ValueRange{input, weight, iZpVal, kZpVal},
778 ValueRange{zeroTensor}, strideAttr, dilationAttr)
779 .getResult(0);
780 SmallVector<ReassociationExprs, 4> reassociationMap;
781 createDepthwiseConvCollapseMap(resultRank, reassociationMap, rewriter);
782 Value convReshape = tensor::CollapseShapeOp::create(
783 rewriter, loc, resultTy, conv, reassociationMap);
785 rewriter, loc, bias, convReshape, biasEmptyTensor, indexingMaps);
786 rewriter.replaceOp(op, result);
787 }
788 return success();
789 }
790};
791
792// Lower TOSA elementwise ops that have a direct linalg.elementwise named op
793// counterpart. Unlike linalg.generic, linalg.elementwise dispatches on a single
794// function kind and infers the body, so the conversion is a handful of checks
795// (kind, ranks, static shapes) followed by construction of the indexing maps
796// and the named op.
797template <typename TosaOp>
798class ElementwiseConverter : public OpConversionPattern<TosaOp> {
799public:
800 using OpConversionPattern<TosaOp>::OpConversionPattern;
801 using typename OpConversionPattern<TosaOp>::OpAdaptor;
802
803 LogicalResult
804 matchAndRewrite(TosaOp op, OpAdaptor adaptor,
805 ConversionPatternRewriter &rewriter) const final {
806 std::optional<linalg::ElementwiseKind> kind =
808 if (!kind)
809 return rewriter.notifyMatchFailure(
810 op, "op has no linalg.elementwise counterpart");
811
812 Location loc = op.getLoc();
813 auto resultTy = cast<RankedTensorType>(op.getType());
814 const int64_t rank = resultTy.getRank();
815
816 const unsigned arity =
817 llvm::to_underlying(linalg::getArityGroupAndKind(*kind).arityGroup);
818
819 // Trailing metadata operands (e.g. MulOp's shift, NegateOp's zero points)
820 // are not forwarded to linalg.elementwise.
821 ValueRange inputs = adaptor.getOperands().take_front(arity);
822
823 // Build one indexing map per input, broadcasting static size-1 dimensions,
824 // followed by the identity map for the output.
825 SmallVector<AffineMap> indexingMaps;
826 for (Value operand : inputs) {
827 ArrayRef<int64_t> shape = cast<ShapedType>(operand.getType()).getShape();
828 SmallVector<AffineExpr> exprs;
829 for (const auto &dim : llvm::enumerate(shape)) {
830 bool requiresBroadcast =
831 dim.value() == 1 && resultTy.getDimSize(dim.index()) != 1;
832 exprs.push_back(requiresBroadcast
833 ? rewriter.getAffineConstantExpr(0)
834 : rewriter.getAffineDimExpr(dim.index()));
835 }
836 indexingMaps.push_back(AffineMap::get(rank, /*symbolCount=*/0, exprs,
837 rewriter.getContext()));
838 }
839 indexingMaps.push_back(rewriter.getMultiDimIdentityMap(rank));
840
841 // Shapes are guaranteed static by isConvertibleToLinalgElementwise.
842 Value emptyTensor = tensor::EmptyOp::create(
843 rewriter, loc, resultTy.getShape(), resultTy.getElementType());
844
845 rewriter.replaceOpWithNewOp<linalg::ElementwiseOp>(
846 op, inputs, ValueRange{emptyTensor}, *kind,
847 rewriter.getAffineMapArrayAttr(indexingMaps));
848 return success();
849 }
850};
851
853getMatMulBatchCollapseReassociation(int64_t rank) {
854 SmallVector<ReassociationIndices> reassociation(3);
855 for (int64_t dim = 0; dim < rank - 2; ++dim)
856 reassociation[0].push_back(dim);
857 reassociation[1].push_back(rank - 2);
858 reassociation[2].push_back(rank - 1);
859 return reassociation;
860}
861
862class MatMulConverter : public OpConversionPattern<tosa::MatMulOp> {
863public:
864 using OpConversionPattern<tosa::MatMulOp>::OpConversionPattern;
865 LogicalResult
866 matchAndRewrite(tosa::MatMulOp op, OpAdaptor adaptor,
867 ConversionPatternRewriter &rewriter) const final {
868 Location loc = op.getLoc();
869 auto aType = dyn_cast<RankedTensorType>(adaptor.getA().getType());
870 auto bType = dyn_cast<RankedTensorType>(adaptor.getB().getType());
871 auto outputType = dyn_cast<RankedTensorType>(op.getType());
872 if (!aType || !bType || !outputType)
873 return rewriter.notifyMatchFailure(op, "only supports ranked tensors");
874
875 auto accType =
876 outputType.clone(getAccumulationType(outputType.getElementType()));
877
878 FailureOr<int64_t> maybeAZp = op.getAZeroPoint();
879 FailureOr<int64_t> maybeBZp = op.getBZeroPoint();
880 if (failed(maybeAZp))
881 return rewriter.notifyMatchFailure(
882 op, "input A zero point cannot be statically determined");
883 if (failed(maybeBZp))
884 return rewriter.notifyMatchFailure(
885 op, "input B zero point cannot be statically determined");
886
887 const int64_t aZpVal = *maybeAZp;
888 const int64_t bZpVal = *maybeBZp;
889
890 if (op.verifyAZeroPoint(aZpVal).failed())
891 return rewriter.notifyMatchFailure(
892 op, "input A zero point must be zero for non-int8 integer types");
893
894 if (op.verifyBZeroPoint(bZpVal).failed())
895 return rewriter.notifyMatchFailure(
896 op, "input B zero point must be zero for non-int8 integer types");
897
898 const int64_t outputRank = outputType.getRank();
899 auto [a, b, zeroTensor] =
900 prepareMatMulOperands(rewriter, loc, adaptor.getA(), adaptor.getB(),
901 accType, /*transposeB=*/false);
902
903 Value aZp, bZp;
904 const bool hasNonzeroZeroPoint = aZpVal != 0 || bZpVal != 0;
905 if (hasNonzeroZeroPoint) {
906 aZp = arith::ConstantOp::create(rewriter, loc,
907 rewriter.getI32IntegerAttr(aZpVal));
908 bZp = arith::ConstantOp::create(rewriter, loc,
909 rewriter.getI32IntegerAttr(bZpVal));
910 }
911
912 Value result;
913 if (outputRank == 2) {
914 if (!hasNonzeroZeroPoint) {
915 result =
916 linalg::MatmulOp::create(rewriter, loc, TypeRange{accType},
917 ValueRange{a, b}, ValueRange{zeroTensor})
918 .getResult(0);
919 } else {
920 result = linalg::QuantizedMatmulOp::create(
921 rewriter, loc, TypeRange{accType},
922 ValueRange{a, b, aZp, bZp}, ValueRange{zeroTensor})
923 .getResult(0);
924 }
925 } else if (outputRank == 3) {
926 if (!hasNonzeroZeroPoint) {
927 result = linalg::BatchMatmulOp::create(
928 rewriter, loc, TypeRange{accType}, ValueRange{a, b},
929 ValueRange{zeroTensor})
930 .getResult(0);
931 } else {
932 result = linalg::QuantizedBatchMatmulOp::create(
933 rewriter, loc, TypeRange{accType},
934 ValueRange{a, b, aZp, bZp}, ValueRange{zeroTensor})
935 .getResult(0);
936 }
937 } else {
938 SmallVector<ReassociationIndices> reassociation =
939 getMatMulBatchCollapseReassociation(outputRank);
940 auto collapse = [&](Value value) {
941 auto type = cast<RankedTensorType>(value.getType());
942 auto collapsedType =
943 tensor::CollapseShapeOp::inferCollapsedType(type, reassociation);
944 return tensor::CollapseShapeOp::create(rewriter, loc, collapsedType,
945 value, reassociation);
946 };
947
948 Value collapsedA = collapse(a);
949 Value collapsedB = collapse(b);
950 Value collapsedInit = collapse(zeroTensor);
951 auto collapsedOutputType =
952 cast<RankedTensorType>(collapsedInit.getType());
953 Value collapsedResult;
954
955 if (!hasNonzeroZeroPoint) {
956 collapsedResult =
957 linalg::BatchMatmulOp::create(
958 rewriter, loc, TypeRange{collapsedOutputType},
959 ValueRange{collapsedA, collapsedB}, ValueRange{collapsedInit})
960 .getResult(0);
961 } else {
962 collapsedResult = linalg::QuantizedBatchMatmulOp::create(
963 rewriter, loc, TypeRange{collapsedOutputType},
964 ValueRange{collapsedA, collapsedB, aZp, bZp},
965 ValueRange{collapsedInit})
966 .getResult(0);
967 }
968
969 result = tensor::ExpandShapeOp::create(
970 rewriter, loc, accType, collapsedResult, reassociation,
971 tensor::getMixedSizes(rewriter, loc, zeroTensor));
972 }
973
974 result = truncateToOutputType(rewriter, loc, result, outputType);
975 rewriter.replaceOp(op, result);
976 return success();
977 }
978};
979
980class MatMulTConverter : public OpConversionPattern<tosa::MatMulTOp> {
981public:
982 using OpConversionPattern<tosa::MatMulTOp>::OpConversionPattern;
983 LogicalResult
984 matchAndRewrite(tosa::MatMulTOp op, OpAdaptor adaptor,
985 ConversionPatternRewriter &rewriter) const final {
986 Location loc = op.getLoc();
987 auto aType = dyn_cast<RankedTensorType>(adaptor.getA().getType());
988 auto bType = dyn_cast<RankedTensorType>(adaptor.getB().getType());
989 auto outputType = dyn_cast<RankedTensorType>(op.getType());
990 if (!aType || !bType || !outputType)
991 return rewriter.notifyMatchFailure(op, "only supports ranked tensors");
992
993 auto accType =
994 outputType.clone(getAccumulationType(outputType.getElementType()));
995
996 FailureOr<int64_t> maybeAZp = op.getAZeroPoint();
997 FailureOr<int64_t> maybeBZp = op.getBZeroPoint();
998 if (failed(maybeAZp))
999 return rewriter.notifyMatchFailure(
1000 op, "input A zero point cannot be statically determined");
1001 if (failed(maybeBZp))
1002 return rewriter.notifyMatchFailure(
1003 op, "input B zero point cannot be statically determined");
1004
1005 const int64_t aZpVal = *maybeAZp;
1006 const int64_t bZpVal = *maybeBZp;
1007
1008 if (aZpVal != 0 || bZpVal != 0)
1009 return rewriter.notifyMatchFailure(
1010 op, "nonzero zero points require the generic MATMUL_T lowering");
1011
1012 const int64_t outputRank = outputType.getRank();
1013 auto [a, b, zeroTensor] =
1014 prepareMatMulOperands(rewriter, loc, adaptor.getA(), adaptor.getB(),
1015 accType, /*transposeB=*/true);
1016
1017 Value result;
1018 if (outputRank == 2) {
1020 rewriter, loc, TypeRange{accType}, ValueRange{a, b},
1021 ValueRange{zeroTensor})
1022 .getResult(0);
1023 } else if (outputRank == 3) {
1025 rewriter, loc, TypeRange{accType}, ValueRange{a, b},
1026 ValueRange{zeroTensor})
1027 .getResult(0);
1028 } else {
1029 SmallVector<ReassociationIndices> reassociation =
1030 getMatMulBatchCollapseReassociation(outputRank);
1031 auto collapse = [&](Value value) {
1032 auto type = cast<RankedTensorType>(value.getType());
1033 auto collapsedType =
1034 tensor::CollapseShapeOp::inferCollapsedType(type, reassociation);
1035 return tensor::CollapseShapeOp::create(rewriter, loc, collapsedType,
1036 value, reassociation);
1037 };
1038
1039 Value collapsedA = collapse(a);
1040 Value collapsedB = collapse(b);
1041 Value collapsedInit = collapse(zeroTensor);
1042 auto collapsedOutputType =
1043 cast<RankedTensorType>(collapsedInit.getType());
1044
1045 Value collapsedResult =
1047 rewriter, loc, TypeRange{collapsedOutputType},
1048 ValueRange{collapsedA, collapsedB}, ValueRange{collapsedInit})
1049 .getResult(0);
1050
1051 result = tensor::ExpandShapeOp::create(
1052 rewriter, loc, accType, collapsedResult, reassociation,
1053 tensor::getMixedSizes(rewriter, loc, zeroTensor));
1054 }
1055
1056 result = truncateToOutputType(rewriter, loc, result, outputType);
1057 rewriter.replaceOp(op, result);
1058 return success();
1059 }
1060};
1061
1062class MaxPool2dConverter : public OpConversionPattern<tosa::MaxPool2dOp> {
1063public:
1064 MaxPool2dConverter(const TypeConverter &typeConverter, MLIRContext *context,
1065 bool allowNonFinites)
1066 : OpConversionPattern(typeConverter, context),
1067 allowNonFinites(allowNonFinites) {}
1068
1069 // Compute the dynamic output sizes of the maxpool operation.
1070 static SmallVector<Value>
1071 computeDynamicOutputSizes(tosa::MaxPool2dOp op, OpAdaptor adaptor,
1072 ConversionPatternRewriter &rewriter) {
1073 TensorType resultTy = op.getType();
1074 Location loc = op.getLoc();
1075
1076 Value input = adaptor.getInput();
1077 ArrayRef<int64_t> kernel = op.getKernel();
1078 ArrayRef<int64_t> pad = op.getPad();
1079 ArrayRef<int64_t> stride = op.getStride();
1080
1081 SmallVector<Value> dynamicDims;
1082
1083 // Batch dimension
1084 if (resultTy.isDynamicDim(0))
1085 dynamicDims.push_back(tensor::DimOp::create(rewriter, loc, input, 0));
1086
1087 // Height/width dimensions
1088 for (int64_t dim : {1, 2}) {
1089 if (!resultTy.isDynamicDim(dim))
1090 continue;
1091
1092 // Index into the attribute arrays
1093 int64_t index = dim - 1;
1094
1095 // Input height/width
1096 Value ihw = tensor::DimOp::create(rewriter, loc, input, dim);
1097
1098 // Kernel height/width
1099 Value khw = arith::ConstantIndexOp::create(rewriter, loc, kernel[index]);
1100
1101 // Output height/width
1102 Value ohw = getConvOrPoolOutputDim(loc, ihw, pad[index * 2],
1103 pad[index * 2 + 1], khw, stride[index],
1104 /*dilationAttr=*/1, rewriter);
1105 dynamicDims.push_back(ohw);
1106 }
1107
1108 // Channel dimension
1109 if (resultTy.isDynamicDim(3))
1110 dynamicDims.push_back(tensor::DimOp::create(rewriter, loc, input, 3));
1111
1112 return dynamicDims;
1113 }
1114
1115 LogicalResult
1116 matchAndRewrite(tosa::MaxPool2dOp op, OpAdaptor adaptor,
1117 ConversionPatternRewriter &rewriter) const final {
1118 Location loc = op.getLoc();
1119 Value input = adaptor.getInput();
1120 ShapedType inputTy = cast<ShapedType>(input.getType());
1121
1122 bool isUnsigned = op.getType().getElementType().isUnsignedInteger();
1123 ShapedType resultTy =
1124 getTypeConverter()->convertType<ShapedType>(op.getType());
1125 if (!resultTy)
1126 return rewriter.notifyMatchFailure(op, "failed to convert type");
1127 Type resultETy = inputTy.getElementType();
1128 NanPropagationMode nanMode = op.getNanMode();
1129
1130 SmallVector<Value> dynamicDims =
1131 computeDynamicOutputSizes(op, adaptor, rewriter);
1132
1133 // Determine what the initial value needs to be for the max pool op.
1134 TypedAttr initialAttr;
1135 if (resultETy.isF32() || resultETy.isBF16() || resultETy.isF16()) {
1136 const llvm::fltSemantics &semantics =
1137 cast<FloatType>(resultETy).getFloatSemantics();
1138 if (llvm::APFloat::semanticsHasNaN(semantics))
1139 initialAttr = rewriter.getFloatAttr(
1140 resultETy,
1141 nanMode == NanPropagationMode::IGNORE
1142 ? APFloat::getNaN(semantics)
1143 : getFloatMinMaxIdentity(semantics,
1144 /*negative=*/true, allowNonFinites));
1145 }
1146
1147 else if (isUnsigned)
1148 initialAttr = rewriter.getIntegerAttr(
1149 resultETy, APInt::getZero(resultETy.getIntOrFloatBitWidth()));
1150 else if (isa<IntegerType>(resultETy))
1151 initialAttr = rewriter.getIntegerAttr(
1152 resultETy,
1153 APInt::getSignedMinValue(resultETy.getIntOrFloatBitWidth()));
1154
1155 if (!initialAttr)
1156 return rewriter.notifyMatchFailure(
1157 op, "Unsupported initial value for tosa.maxpool_2d op");
1158
1159 // Apply padding as necessary.
1160 llvm::SmallVector<int64_t> pad;
1161 pad.resize(2, 0);
1162 llvm::append_range(pad, op.getPad());
1163 pad.resize(pad.size() + 2, 0);
1164
1165 // The initial value doubles as the padding value. This is safe for every
1166 // seed above because the verifier rejects a pad as wide as the kernel on
1167 // any side, so no window consists purely of padding.
1168 Value paddedInput = applyPad(loc, input, pad, initialAttr, rewriter);
1169
1170 Value initialValue = arith::ConstantOp::create(rewriter, loc, initialAttr);
1171
1172 ArrayRef<int64_t> kernel = op.getKernel();
1173 ArrayRef<int64_t> stride = op.getStride();
1174
1175 Attribute strideAttr = rewriter.getI64VectorAttr(stride);
1176 Attribute dilationAttr = rewriter.getI64VectorAttr({1, 1});
1177
1178 // Create the linalg op that performs pooling.
1179 Value emptyTensor =
1180 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(),
1181 resultTy.getElementType(), dynamicDims);
1182
1183 Value filledEmptyTensor =
1184 linalg::FillOp::create(rewriter, loc, initialValue, emptyTensor)
1185 .result();
1186
1187 Value fakeWindowDims =
1188 tensor::EmptyOp::create(rewriter, loc, kernel, resultETy);
1189
1190 if (isUnsigned) {
1191 rewriter.replaceOpWithNewOp<linalg::PoolingNhwcMaxUnsignedOp>(
1192 op, ArrayRef<Type>{resultTy}, ValueRange{paddedInput, fakeWindowDims},
1193 filledEmptyTensor, strideAttr, dilationAttr);
1194 return llvm::success();
1195 }
1196
1197 auto resultOp = linalg::PoolingNhwcMaxOp::create(
1198 rewriter, op->getLoc(), ArrayRef<Type>{resultTy},
1199 ValueRange{paddedInput, fakeWindowDims}, filledEmptyTensor, strideAttr,
1200 dilationAttr);
1201
1202 rewriter.replaceOp(op, resultOp);
1203
1204 // NaN propagation has no meaning for non floating point types.
1205 if (!isa<FloatType>(getElementTypeOrSelf(inputTy)))
1206 return success();
1207
1208 // "PROPAGATE" mode matches the behaviour of the LinAlg named op, so no
1209 // compare and select materialization is required.
1210 //
1211 // In the case of "IGNORE" we need to insert a compare and select. Since
1212 // we've already produced a named op we will just take its body and modify
1213 // it to include the appropriate checks. A NaN accumulator represents a
1214 // window with no finite values yet. The first finite input replaces it;
1215 // input NaNs are ignored. An all-NaN window therefore remains NaN.
1216 if (nanMode == NanPropagationMode::IGNORE) {
1217 auto genericOp = linalg::GenericOp::create(
1218 rewriter, loc, resultOp.getType(0), resultOp.getInputs(),
1219 resultOp.getOutputs(), resultOp.getIndexingMapsArray(),
1220 resultOp.getIteratorTypesArray(),
1221 [&](OpBuilder &opBuilder, Location loc, ValueRange blockArgs) {
1222 IRMapping map;
1223 auto oldBlock = resultOp.getRegion().begin();
1224 auto oldArgs = oldBlock->getArguments();
1225 auto &oldMaxOp = *resultOp.getBlock()->begin();
1226 map.map(oldArgs, blockArgs);
1227 auto *newOp = opBuilder.clone(oldMaxOp, map);
1228 Value inputIsNaN =
1229 arith::CmpFOp::create(opBuilder, loc, arith::CmpFPredicate::UNO,
1230 blockArgs.front(), blockArgs.front());
1231 Value accumulatorIsNaN =
1232 arith::CmpFOp::create(opBuilder, loc, arith::CmpFPredicate::UNO,
1233 blockArgs.back(), blockArgs.back());
1234 Value finiteMaximum =
1235 arith::SelectOp::create(opBuilder, loc, accumulatorIsNaN,
1236 blockArgs.front(), newOp->getResult(0));
1237 Value result = arith::SelectOp::create(
1238 opBuilder, loc, inputIsNaN, blockArgs.back(), finiteMaximum);
1239 linalg::YieldOp::create(opBuilder, loc, result);
1240 });
1241 rewriter.replaceOp(resultOp, genericOp);
1242 }
1243
1244 return success();
1245 }
1246
1247private:
1248 bool allowNonFinites;
1249};
1250
1251class AvgPool2dConverter : public OpRewritePattern<tosa::AvgPool2dOp> {
1252public:
1253 using OpRewritePattern<tosa::AvgPool2dOp>::OpRewritePattern;
1254
1255 LogicalResult matchAndRewrite(tosa::AvgPool2dOp op,
1256 PatternRewriter &rewriter) const final {
1257 Location loc = op.getLoc();
1258 Value input = op.getInput();
1259 ShapedType inputTy = cast<ShapedType>(input.getType());
1260 Type inElementTy = inputTy.getElementType();
1261
1262 ShapedType resultTy = cast<ShapedType>(op.getType());
1263 Type resultETy = cast<ShapedType>(op.getType()).getElementType();
1264
1265 Type accETy = op.getAccType();
1266 ShapedType accTy = resultTy.clone(accETy);
1267
1268 auto dynamicDimsOr =
1269 checkHasDynamicBatchDims(rewriter, op, {input, op.getOutput()});
1270 if (!dynamicDimsOr.has_value())
1271 return failure();
1272 SmallVector<Value> dynamicDims = *dynamicDimsOr;
1273
1274 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
1275 FailureOr<int64_t> maybeOZp = op.getOutputZeroPoint();
1276 if (failed(maybeIZp))
1277 return rewriter.notifyMatchFailure(
1278 op, "input zero point could not be statically determined");
1279 if (failed(maybeOZp))
1280 return rewriter.notifyMatchFailure(
1281 op, "output zero point could not be statically determined");
1282
1283 const int64_t inputZpVal = *maybeIZp;
1284 const int64_t outputZpVal = *maybeOZp;
1285
1286 // Apply padding as necessary.
1287 llvm::SmallVector<int64_t> pad;
1288 pad.resize(2, 0);
1289 llvm::append_range(pad, op.getPad());
1290 pad.resize(pad.size() + 2, 0);
1291 TypedAttr padAttr = rewriter.getZeroAttr(inElementTy);
1292 // Unsupported element type
1293 if (!padAttr)
1294 return failure();
1295 Value paddedInput = applyPad(loc, input, pad, padAttr, rewriter);
1296
1297 auto initialAttr = rewriter.getZeroAttr(accETy);
1298 Value initialValue = arith::ConstantOp::create(rewriter, loc, initialAttr);
1299
1300 ArrayRef<int64_t> kernel = op.getKernel();
1301 ArrayRef<int64_t> stride = op.getStride();
1302
1303 Attribute strideAttr = rewriter.getI64VectorAttr(stride);
1304 Attribute dilationAttr = rewriter.getI64VectorAttr({1, 1});
1305
1306 // Create the linalg op that performs pooling.
1307 Value poolEmptyTensor = tensor::EmptyOp::create(
1308 rewriter, loc, accTy.getShape(), accETy, dynamicDims);
1309
1310 Value filledEmptyTensor =
1311 linalg::FillOp::create(rewriter, loc, ValueRange{initialValue},
1312 ValueRange{poolEmptyTensor})
1313 .result();
1314
1315 Value fakeWindowDims =
1316 tensor::EmptyOp::create(rewriter, loc, kernel, accETy);
1317
1318 // Sum across the pooled region.
1319 Value poolingOp = linalg::PoolingNhwcSumOp::create(
1320 rewriter, loc, ArrayRef<Type>{accTy},
1321 ValueRange{paddedInput, fakeWindowDims},
1322 filledEmptyTensor, strideAttr, dilationAttr)
1323 .getResult(0);
1324
1325 // Normalize the summed value by the number of elements grouped in each
1326 // pool.
1327 Value iH = tensor::DimOp::create(rewriter, loc, poolingOp, 1);
1328 Value iW = tensor::DimOp::create(rewriter, loc, poolingOp, 2);
1329
1330 auto one = arith::ConstantIndexOp::create(rewriter, loc, 1);
1331 iH = arith::SubIOp::create(rewriter, loc, iH, one);
1332 iW = arith::SubIOp::create(rewriter, loc, iW, one);
1333
1334 Value genericEmptyTensor = tensor::EmptyOp::create(
1335 rewriter, loc, resultTy.getShape(), resultETy, dynamicDims);
1336
1337 auto affineMap = rewriter.getMultiDimIdentityMap(resultTy.getRank());
1338 auto genericOp = linalg::GenericOp::create(
1339 rewriter, loc, ArrayRef<Type>({resultTy}), ValueRange{poolingOp},
1340 ValueRange{genericEmptyTensor},
1341 ArrayRef<AffineMap>({affineMap, affineMap}),
1342 getNParallelLoopsAttrs(resultTy.getRank()),
1343 [&](OpBuilder &b, Location loc, ValueRange args) {
1344 auto zero = arith::ConstantIndexOp::create(rewriter, loc, 0);
1345
1346 // Determines what the portion of valid input is covered by the
1347 // kernel.
1348 auto padFn = [&](Value valid, Value pos, int64_t pad) -> Value {
1349 if (pad == 0)
1350 return valid;
1351
1352 auto padVal = arith::ConstantIndexOp::create(rewriter, loc, pad);
1353 Value dpos = arith::SubIOp::create(rewriter, loc, pos, padVal);
1354
1355 Value offset = arith::MinSIOp::create(rewriter, loc, dpos, zero);
1356 return arith::AddIOp::create(rewriter, loc, valid, offset)
1357 ->getResult(0);
1358 };
1359
1360 auto coverageFn = [&](int64_t i, Value isize) -> Value {
1361 Value strideVal =
1362 arith::ConstantIndexOp::create(rewriter, loc, stride[i - 1]);
1363 Value val =
1364 arith::ConstantIndexOp::create(rewriter, loc, kernel[i - 1]);
1365
1366 // Find the position relative to the input tensor's ends.
1367 Value left = linalg::IndexOp::create(rewriter, loc, i);
1368 Value right = arith::SubIOp::create(rewriter, loc, isize, left);
1369 left = arith::MulIOp::create(rewriter, loc, left, strideVal);
1370 right = arith::MulIOp::create(rewriter, loc, right, strideVal);
1371
1372 // Determine how much padding was included.
1373 val = padFn(val, left, pad[i * 2]);
1374 val = padFn(val, right, pad[i * 2 + 1]);
1375 return arith::MaxSIOp::create(rewriter, loc, one, val);
1376 };
1377
1378 // Compute the indices from either end.
1379 Value kH3 = coverageFn(1, iH);
1380 Value kW3 = coverageFn(2, iW);
1381
1382 // Compute the total number of elements and normalize.
1383 auto count = arith::IndexCastOp::create(
1384 rewriter, loc, rewriter.getI32Type(),
1385 arith::MulIOp::create(rewriter, loc, kH3, kW3));
1386
1387 // Divide by the number of summed values. For floats this is just
1388 // a div however for quantized values input normalization had
1389 // to be applied.
1390 Value poolVal = args[0];
1391 if (isa<FloatType>(accETy)) {
1392 auto countF = arith::SIToFPOp::create(rewriter, loc, accETy, count);
1393 poolVal = arith::DivFOp::create(rewriter, loc, poolVal, countF)
1394 ->getResult(0);
1395 if (accETy.getIntOrFloatBitWidth() >
1396 resultETy.getIntOrFloatBitWidth())
1397 poolVal =
1398 arith::TruncFOp::create(rewriter, loc, resultETy, poolVal);
1399 } else {
1400
1401 // If we have quantization information we need to apply an offset
1402 // for the input zp value.
1403 if (inputZpVal != 0) {
1404 auto inputZp = arith::ConstantOp::create(
1405 rewriter, loc, b.getIntegerAttr(accETy, inputZpVal));
1406 Value offset =
1407 arith::MulIOp::create(rewriter, loc, accETy, count, inputZp);
1408 poolVal =
1409 arith::SubIOp::create(rewriter, loc, accETy, poolVal, offset);
1410 }
1411
1412 // Compute: k = 32 - count_leading_zeros(value - 1)
1413 Value one32 = arith::ConstantOp::create(
1414 rewriter, loc, rewriter.getI32IntegerAttr(1));
1415 Value thirtyTwo32 = arith::ConstantOp::create(
1416 rewriter, loc, rewriter.getI32IntegerAttr(32));
1417
1418 Value countSubOne =
1419 arith::SubIOp::create(rewriter, loc, count, one32);
1420 Value leadingZeros =
1421 math::CountLeadingZerosOp::create(rewriter, loc, countSubOne);
1422 Value k =
1423 arith::SubIOp::create(rewriter, loc, thirtyTwo32, leadingZeros);
1424
1425 // Compute: numerator = ((1 << 30) + 1) << k
1426 Value k64 =
1427 arith::ExtUIOp::create(rewriter, loc, rewriter.getI64Type(), k);
1428 Value thirtyShiftPlusOne = arith::ConstantOp::create(
1429 rewriter, loc, rewriter.getI64IntegerAttr((1 << 30) + 1));
1430 Value numerator =
1431 arith::ShLIOp::create(rewriter, loc, thirtyShiftPlusOne, k64);
1432
1433 // Compute: scale.multiplier = numerator / value;
1434 Value count64 = arith::ExtUIOp::create(
1435 rewriter, loc, rewriter.getI64Type(), count);
1436 Value multiplier =
1437 arith::DivUIOp::create(rewriter, loc, numerator, count64);
1438 multiplier = arith::TruncIOp::create(
1439 rewriter, loc, rewriter.getI32Type(), multiplier);
1440
1441 // Compute: scale.shift = 30 + k
1442 Value k8 =
1443 arith::TruncIOp::create(rewriter, loc, rewriter.getI8Type(), k);
1444 Value thirty8 = arith::ConstantOp::create(
1445 rewriter, loc, rewriter.getI8IntegerAttr(30));
1446 Value shift = arith::AddIOp::create(rewriter, loc, k8, thirty8);
1447
1448 auto roundingAttr = RoundingModeAttr::get(
1449 rewriter.getContext(), RoundingMode::SINGLE_ROUND);
1450
1451 auto scaled = tosa::ApplyScaleOp::create(
1452 rewriter, loc, rewriter.getI32Type(), poolVal,
1453 multiplier, shift, roundingAttr)
1454 .getResult();
1455
1456 // If we have quantization information we need to apply output
1457 // zeropoint.
1458 if (outputZpVal != 0) {
1459 auto outputZp = arith::ConstantOp::create(
1460 rewriter, loc,
1461 b.getIntegerAttr(scaled.getType(), outputZpVal));
1462 scaled = arith::AddIOp::create(rewriter, loc, scaled, outputZp)
1463 .getResult();
1464 }
1465
1466 // Apply Clip.
1467 int64_t outBitwidth = resultETy.getIntOrFloatBitWidth();
1468
1470 rewriter, loc, accETy,
1471 APInt::getSignedMinValue(outBitwidth).getSExtValue());
1473 rewriter, loc, accETy,
1474 APInt::getSignedMaxValue(outBitwidth).getSExtValue());
1475 auto clamp = clampIntHelper(loc, scaled, min, max, rewriter,
1476 /*isUnsigned=*/false);
1477
1478 poolVal = clamp;
1479 // Convert type.
1480 if (resultETy != clamp.getType()) {
1481 poolVal =
1482 arith::TruncIOp::create(rewriter, loc, resultETy, poolVal);
1483 }
1484 }
1485
1486 linalg::YieldOp::create(rewriter, loc, poolVal);
1487 });
1488
1489 rewriter.replaceOp(op, genericOp.getResult(0));
1490 return success();
1491 }
1492};
1493
1494class TransposeConverter : public OpRewritePattern<tosa::TransposeOp> {
1495public:
1496 using OpRewritePattern<tosa::TransposeOp>::OpRewritePattern;
1497
1498 LogicalResult matchAndRewrite(tosa::TransposeOp op,
1499 PatternRewriter &rewriter) const final {
1500 const llvm::ArrayRef<int32_t> constantPerms = op.getPerms();
1501
1502 Location loc = op.getLoc();
1503 // The verifier should have made sure we have a valid TOSA permutation
1504 // tensor. isPermutationVector doesn't actually check the TOSA perms we
1505 // expect.
1506 SmallVector<OpFoldResult> inputSizes =
1507 tensor::getMixedSizes(rewriter, loc, op.getInput1());
1508 auto permutedSizes =
1509 applyTOSAPermutation<OpFoldResult>(inputSizes, constantPerms);
1510
1511 auto permutedInit =
1512 tensor::EmptyOp::create(rewriter, loc, permutedSizes,
1513 op.getInput1().getType().getElementType());
1514 rewriter.replaceOpWithNewOp<linalg::TransposeOp>(
1515 op, op.getInput1(), permutedInit,
1516 llvm::map_to_vector(constantPerms,
1517 [](int32_t v) -> int64_t { return v; }));
1518 return success();
1519 }
1520};
1521} // namespace
1522
1524 const TypeConverter &converter, RewritePatternSet *patterns,
1525 const TosaToLinalgNamedOptions &options) {
1526 if (options.preferConv2DKernelLayoutHWCF) {
1527 patterns->add<ConvConverter<tosa::Conv2DOp, linalg::Conv2DNhwcHwcfOp,
1528 linalg::Conv2DNhwcHwcfQOp>>(
1529 patterns->getContext());
1530 } else {
1531 patterns->add<ConvConverter<tosa::Conv2DOp, linalg::Conv2DNhwcFhwcOp,
1532 linalg::Conv2DNhwcFhwcQOp>>(
1533 patterns->getContext());
1534 }
1535 patterns->add<
1536 // clang-format off
1537 ConvConverter<tosa::Conv3DOp, linalg::Conv3DNdhwcDhwcfOp, linalg::Conv3DNdhwcDhwcfQOp>,
1538 DepthwiseConvConverter,
1539 MatMulConverter,
1540 MatMulTConverter,
1541 AvgPool2dConverter,
1542 TransposeConverter
1543 >(patterns->getContext());
1544
1545 patterns->add<
1546 ElementwiseConverter<tosa::AbsOp>,
1547 ElementwiseConverter<tosa::CeilOp>,
1548 ElementwiseConverter<tosa::FloorOp>,
1549 ElementwiseConverter<tosa::ExpOp>,
1550 ElementwiseConverter<tosa::LogOp>,
1551 ElementwiseConverter<tosa::RsqrtOp>,
1552 ElementwiseConverter<tosa::SinOp>,
1553 ElementwiseConverter<tosa::CosOp>,
1554 ElementwiseConverter<tosa::TanhOp>,
1555 ElementwiseConverter<tosa::ErfOp>,
1556 ElementwiseConverter<tosa::ReciprocalOp>,
1557 ElementwiseConverter<tosa::PowOp>,
1558 ElementwiseConverter<tosa::AddOp>,
1559 ElementwiseConverter<tosa::SubOp>,
1560 ElementwiseConverter<tosa::IntDivOp>,
1561 ElementwiseConverter<tosa::MulOp>,
1562 ElementwiseConverter<tosa::NegateOp>,
1563 ElementwiseConverter<tosa::MaximumOp>,
1564 ElementwiseConverter<tosa::MinimumOp>,
1565 ElementwiseConverter<tosa::SelectOp>
1566 >(patterns->getContext());
1567
1568 patterns->add<
1569 MaxPool2dConverter
1570 >(converter, patterns->getContext(), options.allowNonFinites);
1571 // clang-format on
1572}
return success()
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
memberIdxs push_back(ArrayAttr::get(parser.getContext(), values))
static llvm::ManagedStatic< PassManagerOptions > options
static Value clamp(ImplicitLocOpBuilder &builder, Value value, Value lowerBound, Value upperBound)
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
static AffineMap getBroadcastingMap(PatternRewriter &rewriter, Value source, Value result)
static void createDepthwiseConvCollapseMap(int64_t outputRank, SmallVector< ReassociationExprs, 4 > &reassociationMap, OpBuilder &rewriter)
static mlir::Value linalgIntBroadcastExtSIAdd(PatternRewriter &rewriter, Location loc, Value bias, Value conv, Value result, ArrayRef< AffineMap > indexingMaps)
static mlir::Value getConvOrPoolOutputDim(Location loc, Value inputDim, int64_t padBeforeAttr, int64_t padAfterAttr, Value kernelDim, int64_t strideAttr, int64_t dilationAttr, OpBuilder &rewriter)
static void createZeroPointAssertionIfNonI8(PatternRewriter &rewriter, Location loc, Value zeroPoint, StringRef message)
static mlir::Value linalgBroadcastAndMaybeExt(PatternRewriter &rewriter, Location loc, Value source, Value result)
static mlir::Value reifyConstantDim(int64_t attr, ImplicitLocOpBuilder &builder)
static SmallVector< Value > inferDynamicDimsForConv(Location loc, Value input, Value weight, ShapedType resultTy, ArrayRef< int64_t > padAttr, ArrayRef< int64_t > strideAttr, ArrayRef< int64_t > dilationAttr, ArrayRef< int64_t > inputSizeDims, ArrayRef< int64_t > kernelSizeDims, OpBuilder &rewriter)
static std::optional< linalg::ElementwiseKind > getElementwiseKind(Operation *op, Type elementTy)
static mlir::Value applyPad(Location loc, Value input, ArrayRef< int64_t > pad, OpFoldResult paddingValue, OpBuilder &rewriter)
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
AffineMap getMultiDimIdentityMap(unsigned rank)
Definition Builders.cpp:396
AffineExpr getAffineConstantExpr(int64_t constant)
Definition Builders.cpp:381
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:333
AffineExpr getAffineDimExpr(unsigned position)
Definition Builders.cpp:373
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.
ImplicitLocOpBuilder maintains a 'current location', allowing use of the create<> method without spec...
Definition Builders.h:632
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
This class represents a single result from folding an operation.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
Definition Types.cpp:66
bool isF32() const
Definition Types.cpp:40
bool isUnsignedInteger() const
Return true if this is an unsigned integer type (with the specified width).
Definition Types.cpp:90
bool isInteger() const
Return true if this is an integer type (with the specified width).
Definition Types.cpp:58
bool isF16() const
Definition Types.cpp:38
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
bool isBF16() const
Definition Types.cpp:37
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
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
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:453
static ConstantIntOp create(OpBuilder &builder, Location location, int64_t value, unsigned width)
Definition ArithOps.cpp:352
static BatchMatmulTransposeBOp create(OpBuilder &builder, Location location, ValueRange inputs, ValueRange outputs, ArrayRef< NamedAttribute > attributes={})
static MatmulTransposeBOp create(OpBuilder &builder, Location location, ValueRange inputs, ValueRange outputs, ArrayRef< NamedAttribute > attributes={})
ArityGroupAndKind getArityGroupAndKind(ElementwiseKind kind)
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
SmallVector< OpFoldResult > getMixedSizes(OpBuilder &builder, Location loc, Value value)
Return the dimensions of the given tensor value.
Definition TensorOps.cpp:92
SmallVector< T > applyTOSAPermutation(ArrayRef< T > input, ArrayRef< int32_t > perms)
SmallVector< utils::IteratorType > getNParallelLoopsAttrs(unsigned nParallelLoops)
SmallVector< Value > condenseValues(const SmallVector< Value > &values)
std::optional< SmallVector< Value > > checkHasDynamicBatchDims(PatternRewriter &rewriter, Op op, ArrayRef< Value > params)
Value truncateToOutputType(PatternRewriter &rewriter, Location loc, Value input, RankedTensorType targetType)
Truncate an FP32 tensor to BF16 without changing shape or encoding.
MatMulTOperands prepareMatMulOperands(PatternRewriter &rewriter, Location loc, Value a, Value b, RankedTensorType outputType, bool transposeB)
Broadcast the batch dimensions of the ranked operands and create a zero-filled result tensor for eith...
APFloat getFloatMinMaxIdentity(const llvm::fltSemantics &semantics, bool negative, bool allowNonFinites)
Type getAccumulationType(Type requestedType)
Value clampIntHelper(Location loc, Value arg, Value min, Value max, OpBuilder &rewriter, bool isUnsigned)
void populateTosaToLinalgNamedConversionPatterns(const TypeConverter &converter, RewritePatternSet *patterns, const TosaToLinalgNamedOptions &options)
Populates conversion passes from TOSA dialect to Linalg named operations.
std::optional< linalg::ElementwiseKind > isConvertibleToLinalgElementwise(Operation *op)
Returns the linalg.elementwise kind that the TosaToLinalgNamed conversion lowers op to,...
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
ElementwiseArityGroup arityGroup
Definition Linalg.h:147