MLIR 24.0.0git
TosaOps.cpp
Go to the documentation of this file.
1//===- TosaOps.cpp - MLIR Dialect for TOSA --------------------------------===//
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// \file
10// This file implements the TOSA Specification:
11// https://www.mlplatform.org/tosa/tosa_spec.html
12//
13//===----------------------------------------------------------------------===//
14
25#include "mlir/IR/Matchers.h"
29#include "llvm/ADT/APFloat.h"
30#include "llvm/ADT/SmallVectorExtras.h"
31
32#include <numeric>
33#include <type_traits>
34
35using namespace mlir;
36using namespace mlir::tosa;
37
38#include "mlir/Dialect/Tosa/IR/TosaOpsDialect.cpp.inc"
40
41//===----------------------------------------------------------------------===//
42// Tosa dialect interface includes.
43//===----------------------------------------------------------------------===//
44
45#include "mlir/Dialect/Tosa/IR/TosaDialectBytecode.cpp.inc"
46#include "mlir/Dialect/Tosa/IR/TosaEnums.cpp.inc"
47#include "mlir/Dialect/Tosa/IR/TosaInterfaces.cpp.inc"
48
49namespace {
50//===----------------------------------------------------------------------===//
51// Dialect Function Inliner Interface.
52//===----------------------------------------------------------------------===//
53struct TosaInlinerInterface : public DialectInlinerInterface {
54 using DialectInlinerInterface::DialectInlinerInterface;
55
56 //===--------------------------------------------------------------------===//
57 // Analysis Hooks.
58 //===--------------------------------------------------------------------===//
59
60 /// All operations can be inlined by default.
61 bool isLegalToInline(Operation *op, Region *region, bool wouldBeCloned,
62 IRMapping &map) const final {
63 return true;
64 }
65
66 /// All regions with If and While parent operators can be inlined.
67 bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
68 IRMapping &map) const final {
69 return (isa<tosa::IfOp>(dest->getParentOp()) ||
70 isa<tosa::WhileOp>(dest->getParentOp()));
71 }
72};
73
74/// This class implements the bytecode interface for the Tosa dialect.
75struct TosaDialectBytecodeInterface : public BytecodeDialectInterface {
76 TosaDialectBytecodeInterface(Dialect *dialect)
77 : BytecodeDialectInterface(dialect) {}
78
79 //===--------------------------------------------------------------------===//
80 // Attributes
81
82 Attribute readAttribute(DialectBytecodeReader &reader) const override {
83 return ::readAttribute(getContext(), reader);
84 }
85
86 LogicalResult writeAttribute(Attribute attr,
87 DialectBytecodeWriter &writer) const override {
88 return ::writeAttribute(attr, writer);
89 }
90
91 //===--------------------------------------------------------------------===//
92 // Types
93
94 Type readType(DialectBytecodeReader &reader) const override {
95 return ::readType(getContext(), reader);
96 }
97
98 LogicalResult writeType(Type type,
99 DialectBytecodeWriter &writer) const override {
100 return ::writeType(type, writer);
101 }
102
103 void writeVersion(DialectBytecodeWriter &writer) const final {
104 // TODO: Populate.
105 }
106
107 std::unique_ptr<DialectVersion>
108 readVersion(DialectBytecodeReader &reader) const final {
109 // TODO: Populate
110 reader.emitError("Dialect does not support versioning");
111 return nullptr;
112 }
113
114 LogicalResult upgradeFromVersion(Operation *topLevelOp,
115 const DialectVersion &version) const final {
116 return success();
117 }
118};
119} // namespace
120
121//===----------------------------------------------------------------------===//
122// TOSA control flow support.
123//===----------------------------------------------------------------------===//
124
125/// Returns the while loop body.
126SmallVector<Region *> tosa::WhileOp::getLoopRegions() {
127 return {&getBodyGraph()};
128}
129
130//===----------------------------------------------------------------------===//
131// TOSA variable operator support.
132//===----------------------------------------------------------------------===//
133
135 return map_to_vector(shape, [](int64_t dim) {
136 return dim == -1 ? ShapedType::kDynamic : dim;
137 });
138}
139
140// returns type of variable op
141RankedTensorType mlir::tosa::getVariableType(tosa::VariableOp variableOp) {
142 Type elementType = variableOp.getType();
143 DenseIntElementsAttr varShapeAttr = variableOp.getVarShape();
144 auto shape = convertToMlirShape(to_vector(varShapeAttr.getValues<int64_t>()));
145 return RankedTensorType::get(shape, elementType);
146}
147
148//===----------------------------------------------------------------------===//
149// Tosa dialect initialization.
150//===----------------------------------------------------------------------===//
151
152void TosaDialect::initialize() {
153 addInterfaces<TosaDialectBytecodeInterface, TosaInlinerInterface>();
154 declarePromisedInterfaces<
155 shard::ShardingInterface, ClampOp, SigmoidOp, TanhOp, AddOp,
156 ArithmeticRightShiftOp, BitwiseAndOp, BitwiseOrOp, BitwiseXorOp, IntDivOp,
157 LogicalAndOp, LogicalLeftShiftOp, LogicalRightShiftOp, LogicalOrOp,
158 LogicalXorOp, MaximumOp, MinimumOp, MulOp, PowOp, SubOp, AbsOp,
159 BitwiseNotOp, CeilOp, ClzOp, ExpOp, FloorOp, LogOp, LogicalNotOp,
160 NegateOp, ReciprocalOp, RsqrtOp, SelectOp, EqualOp, GreaterOp,
161 GreaterEqualOp, MatMulOp>();
162}
163
164Operation *TosaDialect::materializeConstant(OpBuilder &builder, Attribute value,
165 Type type, Location loc) {
166 // Tosa dialect constants only support ElementsAttr unlike standard dialect
167 // constant which supports all attributes.
168 if (llvm::isa<shapeType>(type) && llvm::isa<DenseIntElementsAttr>(value)) {
169 return tosa::ConstShapeOp::create(builder, loc, type,
170 llvm::cast<DenseIntElementsAttr>(value));
171 }
172 if (llvm::isa<ElementsAttr>(value))
173 return tosa::ConstOp::create(builder, loc, type,
174 llvm::cast<ElementsAttr>(value));
175 return nullptr;
176}
177
178//===----------------------------------------------------------------------===//
179// Parsers and printers
180//===----------------------------------------------------------------------===//
181
182namespace {
183
184ParseResult getShapeAndElementType(OpAsmParser &parser, Type parsedType,
185 DenseElementsAttr &varShapeAttr,
186 TypeAttr &typeAttr) {
187 if (auto shapedType = dyn_cast<ShapedType>(parsedType)) {
188 if (!shapedType.hasRank())
189 return parser.emitError(parser.getCurrentLocation())
190 << "expected ranked type";
191
192 auto elementType = shapedType.getElementType();
193 typeAttr = TypeAttr::get(elementType);
194 ArrayRef<int64_t> shape = shapedType.getShape();
195 Builder builder(parser.getContext());
196 varShapeAttr = builder.getIndexTensorAttr(convertFromMlirShape(shape));
197 return success();
198 }
199 return parser.emitError(parser.getCurrentLocation())
200 << "expected shaped type";
201}
202
203} // namespace
204
205// parses the optional initial value or type for a tosa variable
206// with initial value:
207// tosa.variable @name = dense<0.0> : tensor<1x8xf32>
208//
209// without initial value:
210// tosa.variable @name : tensor<1x8xf32>
212 OpAsmParser &parser, DenseElementsAttr &varShapeAttr, TypeAttr &typeAttr,
213 Attribute &initialValueAttr) {
214 if (succeeded(parser.parseOptionalEqual())) {
215 if (failed(parser.parseAttribute(initialValueAttr))) {
216 return parser.emitError(parser.getCurrentLocation())
217 << "expected attribute";
218 }
219 if (auto typedAttr = dyn_cast<TypedAttr>(initialValueAttr)) {
220 return getShapeAndElementType(parser, typedAttr.getType(), varShapeAttr,
221 typeAttr);
222 }
223 return parser.emitError(parser.getCurrentLocation())
224 << "expected Typed attr";
225 }
226
227 initialValueAttr = nullptr;
228 Type parsedType;
229 if (failed(parser.parseColonType(parsedType))) {
230 return parser.emitError(parser.getCurrentLocation())
231 << "expected type after colon";
232 }
233 return getShapeAndElementType(parser, parsedType, varShapeAttr, typeAttr);
234}
235
237 OpAsmPrinter &p, Operation *op, DenseElementsAttr varShapeAttr,
238 TypeAttr typeAttr, Attribute initialValueAttr) {
239 bool needsSpace = false;
240 if (!dyn_cast_or_null<TypedAttr>(initialValueAttr)) {
241 auto shape =
242 convertToMlirShape(to_vector(varShapeAttr.getValues<int64_t>()));
243 Type elementType = typeAttr.getValue();
244 RankedTensorType tensorType =
245 RankedTensorType::get(ArrayRef<int64_t>(shape), elementType);
246 auto tensorTypeAttr = TypeAttr::get(tensorType);
247 p << ": ";
248 p.printAttribute(tensorTypeAttr);
249 needsSpace = true; // subsequent attr value needs a space separator
250 }
251 if (initialValueAttr) {
252 if (needsSpace)
253 p << ' ';
254 p << "= ";
255 p.printAttribute(initialValueAttr);
256 }
257}
258
259//===----------------------------------------------------------------------===//
260// Tosa utilities.
261//===----------------------------------------------------------------------===//
262
263static std::optional<int64_t> idivCheck(const int64_t lhs, const int64_t rhs) {
264 if (lhs % rhs != 0)
265 return std::nullopt;
266 return lhs / rhs;
267}
268
270 auto srcType = getElementTypeOrSelf(type);
271 if (auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(srcType))
272 srcType = getStorageElementTypeFromQuantized(quantType);
273 return srcType;
274}
275
279
280static LogicalResult verifyRescaleValueAndZpTypes(Operation *op, Value val,
281 Value valZp, StringRef name) {
283 Type eZpType = getStorageElementTypeOrSelf(valZp.getType());
284
285 bool bothInts =
286 mlir::isa<IntegerType>(eType) && mlir::isa<IntegerType>(eZpType);
287 bool sameBitWidth =
288 (eType.getIntOrFloatBitWidth() == eZpType.getIntOrFloatBitWidth());
289
290 if (!bothInts || !sameBitWidth) {
291 return op->emitOpError()
292 << "expected " << name << " and " << name
293 << "_zp to both be integer of the same bitwidth, but got " << eType
294 << " vs. " << eZpType;
295 }
296 return success();
297}
298
299// Create a pad-const const tensor with value of `val` of required data-type
301 Value src, int32_t val) {
302 const auto srcType = getElementTypeOrSelf(src);
303 const auto srcElemType = getStorageElementTypeOrSelf(src);
304 const auto padConstType = mlir::RankedTensorType::get({1}, srcType);
305 const auto padConstEType = mlir::RankedTensorType::get({1}, srcElemType);
306 const auto padConstAttr{
307 llvm::isa<FloatType>(srcElemType)
308 ? DenseElementsAttr::get(padConstEType,
309 builder.getFloatAttr(srcElemType, val))
310 : DenseElementsAttr::get(padConstEType,
311 builder.getIntegerAttr(srcElemType, val))};
312 return tosa::ConstOp::create(builder, loc, padConstType, padConstAttr);
313}
314
316 if (auto blockScaledTy = dyn_cast<tosa::BlockScaledType>(type))
317 return getBitWidth(blockScaledTy.getValueType());
318 if (isa<MXI8Type, tosa::mxint8Type>(type))
319 return 8;
320 return type.getIntOrFloatBitWidth();
321}
322
323// Update dim size if current dim is dynamic, otherwise raise an error if sizes
324// do not match
325LogicalResult tryUpdateDimOrFailure(Operation *op, int64_t &currDim,
326 const int64_t newDim,
327 const StringRef operandName,
328 const StringRef dimName) {
329 if (ShapedType::isDynamic(currDim)) {
330 currDim = newDim;
331 return success();
332 } else if (ShapedType::isStatic(newDim) && currDim != newDim) {
333 return op->emitOpError("expected ")
334 << dimName << " of " << operandName << " to match size " << currDim
335 << ", got " << newDim;
336 }
337 return success();
338}
339
342 auto printDim = [&](int64_t dim) {
343 if (ShapedType::isDynamic(dim))
344 diag << "?";
345 else
346 diag << dim;
347 };
348
349 llvm::interleaveComma(shape, diag, printDim);
350}
351
352static LogicalResult
354 ArrayRef<int64_t> expectedShape,
355 StringRef outputName = "output") {
356 assert(outputType.hasRank() && "expected output type to be ranked");
357
358 if (succeeded(verifyCompatibleShape(outputType.getShape(), expectedShape)))
359 return success();
360
361 InFlightDiagnostic diag = op->emitOpError("expected ");
362 diag << outputName << " shape ";
363 printShapeToDiagnostic(diag, outputType.getShape());
364 diag << " to be compatible with inferred shape ";
365 printShapeToDiagnostic(diag, expectedShape);
366 return diag;
367}
368
370 Operation *op, const int64_t inputSize, const int64_t kernelSize,
371 const int64_t outputSize, const int64_t padBefore, const int64_t padAfter,
372 const int64_t stride, const int64_t dilation, const llvm::StringRef dimName,
373 const llvm::StringRef dimAxis, const llvm::StringRef padBeforeName,
374 const llvm::StringRef padAfterName) {
375 if (inputSize == ShapedType::kDynamic || kernelSize == ShapedType::kDynamic)
376 return success();
377
378 // ERROR_IF: O != idiv_check(I - 1 + pa + pb - (K - 1) * d, s) + 1
379
380 const std::optional<int64_t> calculatedOutSizeMinusOne = idivCheck(
381 inputSize - 1 + padBefore + padAfter - (kernelSize - 1) * dilation,
382 stride);
383 if (!calculatedOutSizeMinusOne.has_value())
384 return op->emitOpError("expected input_")
385 << dimName << " - 1 + pad_" << padBeforeName << " + pad_"
386 << padAfterName << " - (kernel_" << dimName << " - 1) * dilation_"
387 << dimAxis << " to be wholly divisible by stride_" << dimAxis
388 << ", got (" << inputSize << " - 1 + " << padBefore << " + "
389 << padAfter << " - (" << kernelSize << " - 1) * " << dilation
390 << ") / " << stride;
391
392 const int64_t calculatedOutSize = calculatedOutSizeMinusOne.value() + 1;
393 if (outputSize != ShapedType::kDynamic && calculatedOutSize != outputSize)
394 return op->emitOpError("calculated output ")
395 << dimName << " did not match expected: "
396 << "calculated=" << calculatedOutSize << ", expected=" << outputSize;
397
398 return success();
399}
400
401//===----------------------------------------------------------------------===//
402// mxint8Type DenseElementTypeInterface implementation.
403//===----------------------------------------------------------------------===//
404size_t mlir::tosa::mxint8Type::getDenseElementBitSize() const { return 8; }
405
407mlir::tosa::mxint8Type::convertToAttribute(ArrayRef<char> rawData) const {
408 assert(rawData.size() == 1 && "expected 1 byte for tosa.mxint8 element");
409 const auto intType = IntegerType::get(getContext(), 8);
410 return intType.convertToAttribute(rawData);
411}
412
413LogicalResult mlir::tosa::mxint8Type::convertFromAttribute(
415 const auto intAttr = dyn_cast<IntegerAttr>(attr);
416 if (!intAttr)
417 return failure();
418 const Type attrType = intAttr.getType();
419 if (!attrType.isSignlessInteger(8))
420 return failure();
421 return cast<IntegerType>(attrType).convertFromAttribute(attr, result);
422}
423
424//===----------------------------------------------------------------------===//
425// TOSA block scaling utilities.
426//===----------------------------------------------------------------------===//
427
430 bool allowScaleValues) {
431 if (!llvm::isa<ShapedType>(type)) {
432 if (emitError)
433 emitError() << "non tensor type " << type << " is not allowed";
434 return failure();
435 }
436
437 const auto tensorType = llvm::cast<ShapedType>(type);
438 const BlockScaledType elemType =
439 llvm::dyn_cast<BlockScaledType>(tensorType.getElementType());
440 if (!elemType)
441 return success();
442
443 if (!allowScaleValues && elemType.hasScaleValues()) {
444 if (emitError)
445 emitError()
446 << "block scaled tensor type with scale values is not allowed";
447 return failure();
448 }
449
450 if (!tensorType.hasRank())
451 return success();
452
453 if (tensorType.getRank() == 0) {
454 if (emitError)
455 emitError() << "block scaled tensor type must have rank greater than "
456 "zero";
457 return failure();
458 }
459
460 const ArrayRef<int64_t> tensorShape = tensorType.getShape();
461 const uint32_t blockSize =
462 BlockShapeAttr::getBlockShapeValue(elemType.getBlockShape());
463
464 if (allowScaleValues && elemType.hasScaleValues() &&
465 tensorType.hasStaticShape()) {
466 const size_t numBlocks = tensorType.getNumElements() / blockSize;
467 if (elemType.getScaleValues().size() != numBlocks) {
468 if (emitError)
469 emitError() << "block scaled tensor type with scale values must have "
470 "scale values for each block, expected "
471 << numBlocks << ", got "
472 << elemType.getScaleValues().size();
473 return failure();
474 }
475 }
476
477 const int64_t blockedDimension = tensorShape.back();
478 if (ShapedType::isDynamic(blockedDimension))
479 return success();
480
481 if (blockedDimension % blockSize != 0) {
482 if (emitError)
483 emitError() << "last dimension of block scaled tensor type ("
484 << blockedDimension << ") must be divisible by block size ("
485 << blockSize << ")";
486
487 return failure();
488 }
489
490 return success();
491}
492
494 MLIRContext *ctx = type.getContext();
495 std::string message;
497 ctx, [&](Diagnostic &diag) { message = diag.str(); });
498
500 type, [ctx] { return emitError(UnknownLoc::get(ctx)); })) &&
501 !message.empty()) {
502 return ": " + message;
503 }
504
505 return "";
506}
507
508static ParseResult parseScaleValues(AsmParser &parser,
509 SmallVector<Attribute> &scaleValues,
510 Type scaleType) {
511 const auto parseScaleValue = [&]() -> ParseResult {
512 const SMLoc loc = parser.getCurrentLocation();
513
514 double floatValue;
515 if (parser.parseFloat(floatValue))
516 return failure();
517
518 if (floatValue < 0.0)
519 return parser.emitError(loc, "scale value must be non-negative, got ")
520 << floatValue;
521
522 Type attrType = scaleType;
523 if (succeeded(parser.parseOptionalColon()) && parser.parseType(attrType))
524 return failure();
525
526 if (attrType != scaleType)
527 return parser.emitError(loc, "parsed attribute type ")
528 << attrType << " does not match expected scale type " << scaleType;
529
530 scaleValues.push_back(FloatAttr::get(attrType, floatValue));
531 return success();
532 };
533
534 return parser.parseCommaSeparatedList(parseScaleValue);
535}
536
537static void printScaleValues(AsmPrinter &printer,
538 ArrayRef<Attribute> scaleValues, Type) {
539 llvm::interleaveComma(scaleValues, printer, [&](Attribute scaleValue) {
540 printer.printAttributeWithoutType(scaleValue);
541 });
542}
543
544size_t mlir::tosa::BlockScaledType::getDenseElementBitSize() const {
545 const Type valueType = getValueType();
546 if (isa<MXI8Type, tosa::mxint8Type>(valueType))
547 return 8;
548 return valueType.getIntOrFloatBitWidth();
549}
550
552mlir::tosa::BlockScaledType::convertToAttribute(ArrayRef<char> rawData) const {
553 // Block scaled values are stored as a single byte. This is because possible
554 // value data types are either 8-bit or sub-byte. Sub-byte types are aligned
555 // to 8-bits.
556 assert(rawData.size() == 1 && "expected 1 byte for block_scaled element");
557 const Type valueType = getValueType();
558 if (const auto mxi8Value = dyn_cast<MXI8Type>(valueType))
559 return mxi8Value.convertToAttribute(rawData);
560 if (const auto mxint8Value = dyn_cast<tosa::mxint8Type>(valueType))
561 return mxint8Value.convertToAttribute(rawData);
562 if (!isa<FloatType>(valueType))
563 return {};
564 return mlir::detail::convertFloatTypeToAttribute(valueType, rawData);
565}
566
567LogicalResult mlir::tosa::BlockScaledType::convertFromAttribute(
569 const Type valueType = getValueType();
570 if (const auto mxi8Value = dyn_cast<MXI8Type>(valueType))
571 return mxi8Value.convertFromAttribute(attr, result);
572 if (const auto mxint8Value = dyn_cast<tosa::mxint8Type>(valueType))
573 return mxint8Value.convertFromAttribute(attr, result);
574
575 const auto floatAttr = dyn_cast<FloatAttr>(attr);
576 if (!floatAttr || floatAttr.getType() != valueType)
577 return failure();
578 // const APFloat value = floatAttr.getValue();
579 return mlir::detail::convertFloatTypeFromAttribute(valueType, floatAttr,
580 result);
581}
582
583//===----------------------------------------------------------------------===//
584// TOSA Operator shape inference
585//===----------------------------------------------------------------------===//
586
587template <typename A, std::enable_if_t<std::is_same_v<A, ArgMaxOp::Adaptor> ||
588 std::is_same_v<A, ArgMinOp::Adaptor>,
589 int> = 0>
591 MLIRContext *context, ::std::optional<Location> location, A adaptor,
592 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
593 ShapeAdaptor inputShape(adaptor.getInput().getType());
594 IntegerAttr axis = adaptor.getProperties().axis;
595 int32_t axisVal = axis.getValue().getSExtValue();
596
597 if (!inputShape.hasRank()) {
598 inferredReturnShapes.push_back(ShapedTypeComponents());
599 return success();
600 }
601
602 const auto inputRank = inputShape.getRank();
603 SmallVector<int64_t> outShape;
604 outShape.reserve(inputRank - 1);
605 for (int i = 0, s = inputRank; i < s; i++) {
606 if (i == axisVal)
607 continue;
608 outShape.push_back(inputShape.getDimSize(i));
609 }
610
611 inferredReturnShapes.push_back(ShapedTypeComponents(outShape));
612 return success();
613}
614
615//===----------------------------------------------------------------------===//
616// TOSA Operator Verifiers.
617//===----------------------------------------------------------------------===//
618template <typename T>
619LogicalResult argMaxMinVerify(T op) {
620 const ShapedType resultType = llvm::cast<ShapedType>(op.getType());
621
622 if (const auto resultETy = resultType.getElementType();
623 !resultETy.isIntOrIndex())
624 return op.emitOpError("result tensor is not of integer type");
625
626 const auto inputType = llvm::cast<ShapedType>(op.getInput().getType());
627 if (!inputType.hasRank())
628 return success();
629
630 // Ensure axis is within the tensor rank
631 const int64_t axis = op.getAxisAttr().getInt();
632 if (((axis < 0) || axis >= inputType.getRank()))
633 return op.emitOpError("specified axis is outside the rank of the tensor");
634
635 if (!resultType.hasRank())
636 return success();
637
638 const ArrayRef<int64_t> inputShape = inputType.getShape();
639 const ArrayRef<int64_t> outputShape = resultType.getShape();
640 llvm::SmallVector<int64_t> expectedOutputShape(inputShape);
641 expectedOutputShape.erase(expectedOutputShape.begin() + axis);
642 if (failed(verifyCompatibleShape(expectedOutputShape, outputShape)))
643 return op.emitOpError("expected output shape '")
644 << expectedOutputShape << "', got '" << outputShape << "'";
645
646 return success();
647}
648
649template <typename T>
650static LogicalResult verifyConvOp(T op) {
651 const auto inputType = llvm::dyn_cast<TensorType>(op.getInput().getType());
652 const auto weightType = llvm::dyn_cast<TensorType>(op.getWeight().getType());
653
654 auto inputEType = inputType.getElementType();
655 auto weightEType = weightType.getElementType();
656 auto biasEType =
657 llvm::cast<ShapedType>(op.getBias().getType()).getElementType();
658 auto resultEType =
659 llvm::cast<ShapedType>(op.getResult().getType()).getElementType();
660 bool biasIsFloat = llvm::isa<FloatType>(biasEType);
661 bool resultIsFloat = llvm::isa<FloatType>(resultEType);
662
663 if (auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(inputEType))
664 inputEType = getStorageElementTypeFromQuantized(quantType);
665
666 if (auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(weightEType))
667 weightEType = getStorageElementTypeFromQuantized(quantType);
668
669 if (auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(biasEType))
670 biasEType = getStorageElementTypeFromQuantized(quantType);
671
672 if (auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(resultEType))
673 resultEType = getStorageElementTypeFromQuantized(quantType);
674
675 if (biasIsFloat && resultIsFloat && (biasEType != resultEType)) {
676 // for now, only enforce bias element type == result element type for
677 // float types.
678 op.emitOpError(
679 "expect both bias and result to have same element type, got ")
680 << biasEType << " and " << resultEType;
681 return failure();
682 }
683
684 const bool isInputBlockScaled = llvm::isa<BlockScaledType>(inputEType);
685 const bool isWeightBlockScaled = llvm::isa<BlockScaledType>(weightEType);
686 const bool isInputFloat = llvm::isa<FloatType>(inputEType);
687 const bool isWeightFloat = llvm::isa<FloatType>(weightEType);
688
689 const bool isInputBSorFloat = isInputBlockScaled || isInputFloat;
690 const bool isWeightBSorFloat = isWeightBlockScaled || isWeightFloat;
691
692 // Either both must be float or both non-float.
693 if (isInputBSorFloat != isWeightBSorFloat) {
694 op.emitOpError(
695 "expect both input and weight to be float or not together, got ")
696 << inputEType << " and " << weightEType;
697 return failure();
698 }
699
700 auto inputZpEType = getStorageElementTypeOrSelf(op.getInputZp().getType());
701 if (!isInputBlockScaled && inputEType != inputZpEType) {
702 return op.emitOpError("expect both input and its zero point are the same "
703 "element type, got ")
704 << inputEType << " and " << inputZpEType;
705 }
706 if (isInputBlockScaled && !llvm::isa<Float32Type>(inputZpEType)) {
707 return op.emitOpError(
708 "expect block scaled input to have fp32 zero point, got ")
709 << inputEType << " and " << inputZpEType;
710 }
711
712 auto weightZpEType = getStorageElementTypeOrSelf(op.getWeightZp().getType());
713 if (!isWeightBlockScaled && weightEType != weightZpEType) {
714 return op.emitOpError("expect both weight and its zero point are the same "
715 "element type, got ")
716 << weightEType << " and " << weightZpEType;
717 }
718 if (isWeightBlockScaled && !llvm::isa<Float32Type>(weightZpEType)) {
719 return op.emitOpError(
720 "expect block scaled weight to have fp32 zero point, got ")
721 << weightEType << " and " << weightZpEType;
722 }
723
724 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
725 if (succeeded(maybeIZp) && op.verifyInputZeroPoint(*maybeIZp).failed())
726 return failure();
727
728 FailureOr<int64_t> maybeWZp = op.getWeightZeroPoint();
729 if (succeeded(maybeWZp) && op.verifyWeightZeroPoint(*maybeWZp).failed())
730 return failure();
731
732 return success();
733}
734
735LogicalResult tosa::ConstOp::verify() {
736 Operation &op = *getOperation();
737 auto attrType = llvm::dyn_cast<TensorType>(getValuesAttr().getType());
738 auto outputType = llvm::dyn_cast<TensorType>(getOutput().getType());
739
740 if (!attrType || !outputType) {
741 emitOpError("expected tensors for attr/result type");
742 return failure();
743 }
744
745 const Type attrElemType = attrType.getElementType();
746 const Type resultElemType = outputType.getElementType();
747
748 if (auto result =
749 llvm::dyn_cast<mlir::quant::QuantizedType>(resultElemType)) {
750 if (getStorageElementTypeFromQuantized(result) == attrElemType)
751 return success();
752 }
753
754 if (auto attrBlockScaledType =
755 llvm::dyn_cast<mlir::tosa::BlockScaledType>(attrElemType)) {
756 if (!attrBlockScaledType.hasScaleValues())
757 return op.emitOpError(
758 "attribute block scaled type must have scale values");
759
760 const auto emitAttributeError = [&op]() {
761 return op.emitOpError("attribute block scaled type is invalid: ");
762 };
763
764 if (failed(verifyBlockScaledTensorType(attrType, emitAttributeError, true)))
765 return failure();
766
767 const BlockScaledType resultBlockScaledType =
768 llvm::dyn_cast<mlir::tosa::BlockScaledType>(resultElemType);
769 if (!resultBlockScaledType)
770 return op.emitOpError(
771 "result type must be block scaled type if attribute is block "
772 "scaled type");
773
774 if (attrBlockScaledType.getValueType() !=
775 resultBlockScaledType.getValueType() ||
776 attrBlockScaledType.getScaleType() !=
777 resultBlockScaledType.getScaleType() ||
778 attrBlockScaledType.getBlockShape() !=
779 resultBlockScaledType.getBlockShape())
780 return op.emitOpError(
781 "expected block scaled element type to be compatible "
782 "between attr and result, got ")
783 << attrBlockScaledType << " vs. " << resultBlockScaledType;
784
785 return success();
786 }
787
788 if (attrElemType != resultElemType)
789 return emitOpError("expected same attr/result element types");
790
791 return success();
792}
793
794//===----------------------------------------------------------------------===//
795// ERROR_IF functions.
796// ERROR_IF is a predicate that must set an error if the condition holds.
797//===----------------------------------------------------------------------===//
798
799template <typename T>
800static LogicalResult verifyConvOpErrorIf(T op) {
801 llvm::ArrayRef<int64_t> padding = op.getPad();
802 if (llvm::any_of(padding, [](int64_t p) { return p < 0; }))
803 return op.emitOpError("expect all padding values to be >= 0, got ")
804 << padding;
805
806 llvm::ArrayRef<int64_t> strides = op.getStride();
807 if (llvm::any_of(strides, [](int64_t s) { return s < 1; }))
808 return op.emitOpError("expect all stride values to be >= 1, got ")
809 << strides;
810
811 llvm::ArrayRef<int64_t> dilations = op.getDilation();
812 if (llvm::any_of(dilations, [](int64_t d) { return d < 1; }))
813 return op.emitOpError("expect all dilation values to be >= 1, got ")
814 << dilations;
815
816 const RankedTensorType outputType =
817 llvm::dyn_cast<RankedTensorType>(op.getOutput().getType());
818 if (!outputType)
819 // Skip following checks if output is not ranked
820 return success();
821
822 const RankedTensorType inputType =
823 llvm::dyn_cast<RankedTensorType>(op.getInput().getType());
824 const RankedTensorType weightType =
825 llvm::dyn_cast<RankedTensorType>(op.getWeight().getType());
826
827 if (inputType && weightType) {
828 // input = [_,IH,IW,_], weight = [_,KH,KW,_], output = [_,OH,OW,_]
829 if constexpr (std::is_same<T, tosa::Conv2DOp>::value) {
830 if (failed(verifyConvOutputSize(
831 op, inputType.getDimSize(1), weightType.getDimSize(1),
832 outputType.getDimSize(1), padding[0], padding[1], strides[0],
833 dilations[0], "height", "y", "top", "bottom")))
834 return failure();
835
836 if (failed(verifyConvOutputSize(
837 op, inputType.getDimSize(2), weightType.getDimSize(2),
838 outputType.getDimSize(2), padding[2], padding[3], strides[1],
839 dilations[1], "width", "x", "left", "right")))
840 return failure();
841 }
842
843 // input = [_,IH,IW,_], weight = [KH,KW,_,_], output = [_,OH,OW,_]
844 if constexpr (std::is_same<T, tosa::DepthwiseConv2DOp>::value) {
845 if (failed(verifyConvOutputSize(
846 op, inputType.getDimSize(1), weightType.getDimSize(0),
847 outputType.getDimSize(1), padding[0], padding[1], strides[0],
848 dilations[0], "height", "y", "top", "bottom")))
849 return failure();
850
851 if (failed(verifyConvOutputSize(
852 op, inputType.getDimSize(2), weightType.getDimSize(1),
853 outputType.getDimSize(2), padding[2], padding[3], strides[1],
854 dilations[1], "width", "x", "left", "right")))
855 return failure();
856 }
857
858 // input = [_,ID,IH,IW,_], weight = [_,KD,KH,KW,_], output = [_,OD,OH,OW,_]
859 if constexpr (std::is_same<T, tosa::Conv3DOp>::value) {
860 if (failed(verifyConvOutputSize(
861 op, inputType.getDimSize(1), weightType.getDimSize(1),
862 outputType.getDimSize(1), padding[0], padding[1], strides[0],
863 dilations[0], "depth", "d", "front", "back")))
864 return failure();
865
866 if (failed(verifyConvOutputSize(
867 op, inputType.getDimSize(2), weightType.getDimSize(2),
868 outputType.getDimSize(2), padding[2], padding[3], strides[1],
869 dilations[1], "height", "y", "top", "bottom")))
870 return failure();
871
872 if (failed(verifyConvOutputSize(
873 op, inputType.getDimSize(3), weightType.getDimSize(3),
874 outputType.getDimSize(3), padding[4], padding[5], strides[2],
875 dilations[2], "width", "x", "left", "right")))
876 return failure();
877 }
878 }
879
880 const RankedTensorType biasType =
881 llvm::dyn_cast<RankedTensorType>(op.getBias().getType());
882 if (!biasType)
883 // Skip following checks if bias is not ranked
884 return success();
885
886 const int64_t biasChannels = biasType.getDimSize(0);
887 const int64_t outputChannels =
888 outputType.getDimSize(outputType.getRank() - 1);
889 if (biasChannels == ShapedType::kDynamic ||
890 outputChannels == ShapedType::kDynamic)
891 // Skip following checks if biasChannels or outputChannels is dynamic dim
892 return success();
893
894 if (biasChannels != outputChannels && biasChannels != 1)
895 return op.emitOpError(
896 "bias channels expected to be equal to output channels (")
897 << outputChannels << ") or 1, got " << biasChannels;
898
899 return success();
900}
901
902// Verify whether same type and shape of the given two types.
903static LogicalResult errorIfTypeOrShapeMismatch(Operation *op, Type type1,
904 StringRef name1, Type type2,
905 StringRef name2) {
906 auto shapeType1 = dyn_cast<ShapedType>(type1);
907 auto shapeType2 = dyn_cast<ShapedType>(type2);
908 if (!shapeType1 || !shapeType2)
909 return failure();
910
911 auto elemType1 = shapeType1.getElementType();
912 auto elemType2 = shapeType2.getElementType();
913 if (elemType1 != elemType2)
914 return op->emitOpError()
915 << "require same element type for " << name1 << " (" << elemType1
916 << ") and " << name2 << " (" << elemType2 << ")";
917
918 if (failed(verifyCompatibleShape(type1, type2)))
919 return op->emitOpError()
920 << "require same shapes for " << name1 << " (" << type1 << ") and "
921 << name2 << " (" << type2 << ")";
922
923 return success();
924}
925
926// Verify whether same length, type, and shape of the given two tensor lists.
927static LogicalResult errorIfTypeOrShapeMismatch(Operation *op, ValueRange list1,
928 StringRef name1,
929 ValueRange list2,
930 StringRef name2) {
931 if (list1.size() != list2.size())
932 return op->emitOpError()
933 << "require same number of values in " << name1 << " ("
934 << list1.size() << ") and " << name2 << " (" << list2.size() << ")";
935
936 for (auto [type1, type2] :
937 llvm::zip_equal(list1.getTypes(), list2.getTypes())) {
938 if (errorIfTypeOrShapeMismatch(op, type1, name1, type2, name2).failed())
939 return failure();
940 }
941
942 return success();
943}
944
945static inline LogicalResult errorIfShapeNotSizeOne(Operation *op, Type type) {
946 ShapeAdaptor shapeAdaptor(type);
947 if (!shapeAdaptor.hasRank() || !shapeAdaptor.hasStaticShape())
948 return success();
949
950 return shapeAdaptor.getNumElements() == 1 ? success() : failure();
951}
952
953template <typename T>
954static LogicalResult verifyVariableOpErrorIf(T op, Type type, StringRef name) {
955 Operation *symTableOp =
956 op->template getParentWithTrait<OpTrait::SymbolTable>();
957 if (!symTableOp)
958 // If the operation is not the scope of a symbol table, we cannot
959 // verify it against it's declaration.
960 return success();
961
962 SymbolTable symTable(symTableOp);
963 const auto varOp = symTable.lookup<tosa::VariableOp>(op.getName());
964
965 // Verify prior declaration
966 if (!varOp)
967 return op->emitOpError("'")
968 << op.getName() << "' has not been declared by 'tosa.variable'";
969
970 // Verify type and shape
971 auto variableType = getVariableType(varOp);
972 if (errorIfTypeOrShapeMismatch(op, type, name, variableType,
973 "the input tensor")
974 .failed())
975 return failure();
976 return success();
977}
978
979// verify that inType and outType have same element types
980static LogicalResult verifySameElementTypes(Operation *op, Type aType,
981 Type bType,
982 StringRef aName = "input",
983 StringRef bName = "output") {
984 auto aTType = llvm::dyn_cast<TensorType>(aType);
985 auto bTType = llvm::dyn_cast<TensorType>(bType);
986 if (!aTType) {
987 op->emitOpError("expect shaped tensor for") << aName << ", got " << aType;
988 return failure();
989 }
990 if (!bTType) {
991 op->emitOpError("expect shaped tensor for") << bName << ", got" << bType;
992 return failure();
993 }
994 auto aElementType = aTType.getElementType();
995 auto bElementType = bTType.getElementType();
996 auto aQuantType =
997 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(aElementType);
998 auto bQuantType =
999 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(bElementType);
1000 if ((aElementType.isIntOrIndexOrFloat() || aQuantType) &&
1001 (bElementType.isIntOrIndexOrFloat() || bQuantType) &&
1002 aElementType != bElementType) {
1003 // only check if both element types are int/index/float/UniformQuantized
1004 // eg, not sure how to check quant::QuantizedType
1005 // this happens in test_conv2d_q_grouped_convolution in
1006 // tfl-to-tosa-pipeline.mlir
1007 op->emitOpError("expect ")
1008 << aName << " and " << bName << " to have same element type, got "
1009 << aElementType << " and " << bElementType;
1010 return failure();
1011 }
1012 return success();
1013}
1014
1015LogicalResult tosa::ArgMaxOp::verify() { return argMaxMinVerify(*this); }
1016
1017LogicalResult tosa::ArgMinOp::verify() { return argMaxMinVerify(*this); }
1018
1019static LogicalResult verifyPoolingOpImpl(Operation *op,
1020 ArrayRef<int64_t> kernel,
1021 ArrayRef<int64_t> strides,
1022 ArrayRef<int64_t> padding, Value input,
1023 Value output) {
1024 if (failed(verifySameElementTypes(op, input.getType(), output.getType())))
1025 return failure();
1026
1027 const bool hasKernel = kernel.size() > 0;
1028 const bool hasStrides = strides.size() > 0;
1029 const bool hasPad = padding.size() > 0;
1030
1031 if (hasKernel && llvm::any_of(kernel, [](int64_t s) { return s < 1; }))
1032 return op->emitOpError("expect all kernel values to be >= 1, got ")
1033 << kernel;
1034
1035 if (hasStrides && llvm::any_of(strides, [](int64_t s) { return s < 1; }))
1036 return op->emitOpError("expect all stride values to be >= 1, got ")
1037 << strides;
1038
1039 if (hasPad && llvm::any_of(padding, [](int64_t p) { return p < 0; }))
1040 return op->emitOpError("expect all padding values to be >= 0, got ")
1041 << padding;
1042
1043 if (hasKernel && hasPad) {
1044 // Padding must be less than kernel size to avoid a divide-by-zero
1045 const int64_t kernelX = kernel[1];
1046 const int64_t padLeft = padding[2];
1047 const int64_t padRight = padding[3];
1048 if (padRight >= kernelX || padLeft >= kernelX)
1049 return op->emitOpError("expected left/right padding to be less than the "
1050 "width of the kernel, got pad_left=")
1051 << padLeft << ", pad_right=" << padRight
1052 << ", kernel_x=" << kernelX;
1053
1054 const int64_t kernelY = kernel[0];
1055 const int64_t padTop = padding[0];
1056 const int64_t padBottom = padding[1];
1057 if (padTop >= kernelY || padBottom >= kernelY)
1058 return op->emitOpError("expected top/bottom padding to be less than the "
1059 "height of the kernel, got pad_top=")
1060 << padTop << ", pad_bottom=" << padBottom
1061 << ", kernel_y=" << kernelY;
1062 }
1063
1064 const auto inputType = llvm::dyn_cast<RankedTensorType>(input.getType());
1065 const auto outputType = llvm::dyn_cast<RankedTensorType>(output.getType());
1066 if (!inputType || !outputType)
1067 return success();
1068
1069 if (hasKernel && hasStrides && hasPad) {
1070 const auto verifyOutputSize =
1071 [op](const int64_t inputSize, const int64_t outputSize,
1072 const int64_t kernelSize, const int64_t strideSize,
1073 const int64_t padBefore, const int64_t padAfter,
1074 const llvm::StringRef dimName, const llvm::StringRef dimAxis,
1075 const llvm::StringRef padBeforeName,
1076 const llvm::StringRef padAfterName) -> LogicalResult {
1077 if (ShapedType::isDynamic(inputSize))
1078 return success();
1079
1080 const std::optional<int64_t> calculatedOutSizeMinusOne =
1081 idivCheck(inputSize + padBefore + padAfter - kernelSize, strideSize);
1082 if (!calculatedOutSizeMinusOne.has_value())
1083 return op->emitOpError("expected input_")
1084 << dimName << " + pad_" << padBeforeName << " + pad_"
1085 << padAfterName << " - kernel_" << dimAxis
1086 << " to be wholly divisible by stride_" << dimAxis << ", got ("
1087 << inputSize << " + " << padBefore << " + " << padAfter << " - "
1088 << kernelSize << ") / " << strideSize;
1089
1090 const int64_t calculatedOutSize = calculatedOutSizeMinusOne.value() + 1;
1091 if (ShapedType::isStatic(outputSize) && calculatedOutSize != outputSize)
1092 return op->emitOpError("calculated output ")
1093 << dimName << " did not match expected: " << "calculated="
1094 << calculatedOutSize << ", expected=" << outputSize;
1095
1096 return success();
1097 };
1098
1099 if (failed(verifyOutputSize(inputType.getDimSize(1),
1100 outputType.getDimSize(1), kernel[0], strides[0],
1101 padding[0], padding[1], "height", "y", "top",
1102 "bottom")))
1103 return failure();
1104
1105 if (failed(verifyOutputSize(
1106 inputType.getDimSize(2), outputType.getDimSize(2), kernel[1],
1107 strides[1], padding[2], padding[3], "width", "x", "left", "right")))
1108 return failure();
1109 }
1110 return success();
1111}
1112
1113template <typename T>
1114static LogicalResult verifyPoolingOp(T op) {
1115 return verifyPoolingOpImpl(op.getOperation(), op.getKernel(), op.getStride(),
1116 op.getPad(), op.getInput(), op.getOutput());
1117}
1118
1119template <typename T>
1120static LogicalResult verifyAvgPoolCommonTypeAndZpChecks(T op) {
1121 const Type inputETy = getStorageElementTypeOrSelf(op.getInput().getType());
1122 const Type resultETy = getStorageElementTypeOrSelf(op.getOutput().getType());
1123 const Type inputZpETy =
1124 getStorageElementTypeOrSelf(op.getInputZp().getType());
1125 const Type outputZpETy =
1126 getStorageElementTypeOrSelf(op.getOutputZp().getType());
1127
1128 auto accType = op.getAccType();
1129 if (llvm::isa<IntegerType>(inputETy) && !accType.isInteger(32))
1130 return op.emitOpError("accumulator type for integer tensor is not i32");
1131
1132 if (inputETy.isF16() && !(accType.isF16() || accType.isF32()))
1133 return op.emitOpError("accumulator type for f16 tensor is not f16/f32");
1134
1135 if (inputETy.isBF16() && !accType.isF32())
1136 return op.emitOpError("accumulator type for bf16 tensor is not f32");
1137
1138 if (inputETy.isF32() && !accType.isF32())
1139 return op.emitOpError("accumulator type for f32 tensor is not f32");
1140
1141 if (inputETy != inputZpETy)
1142 return op.emitOpError("expect both input and its zero point are the same "
1143 "element type, got ")
1144 << inputETy << " and " << inputZpETy;
1145
1146 if (resultETy != outputZpETy)
1147 return op.emitOpError("expect both output and its zero point are the same "
1148 "element type, got ")
1149 << resultETy << " and " << outputZpETy;
1150
1151 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
1152 if (succeeded(maybeIZp) && op.verifyInputZeroPoint(*maybeIZp).failed())
1153 return failure();
1154
1155 FailureOr<int64_t> maybeOZp = op.getOutputZeroPoint();
1156 if (succeeded(maybeOZp) && op.verifyOutputZeroPoint(*maybeOZp).failed())
1157 return failure();
1158
1159 return success();
1160}
1161
1162namespace {
1163struct AdaptivePoolingConstShapeValues {
1164 llvm::SmallVector<int64_t> kernel;
1165 llvm::SmallVector<int64_t> stride;
1166 llvm::SmallVector<int64_t> pad;
1167};
1168} // namespace
1169
1170template <typename T>
1172 std::is_same_v<T, tosa::AvgPool2dAdaptiveOp> ||
1173 std::is_same_v<T, tosa::MaxPool2dAdaptiveOp>;
1174
1175template <typename T,
1176 typename std::enable_if<IsSupportedAdaptivePoolConstShapeVerifyOp<T>,
1177 int>::type = 0>
1179 T op, AdaptivePoolingConstShapeValues &values) {
1180 tosa::getConstShapeValues(op.getKernel().getDefiningOp(), values.kernel);
1181 tosa::getConstShapeValues(op.getStride().getDefiningOp(), values.stride);
1182 tosa::getConstShapeValues(op.getPad().getDefiningOp(), values.pad);
1183}
1184
1185LogicalResult tosa::AvgPool2dOp::verify() {
1186 if (failed(verifyPoolingOp(*this)))
1187 return failure();
1189 return failure();
1190 return success();
1191}
1192
1193LogicalResult tosa::AvgPool2dAdaptiveOp::verify() {
1194 AdaptivePoolingConstShapeValues values;
1196
1197 // If pad/stride/kernel are not constant, this is okay, we just can't check
1198 // their values. extractAdaptivePoolingConstShapeOperands will return an empty
1199 // list for each non CTC input. verifyPoolingOpImpl will need to handle values
1200 // not being present, and return success if they cannot be checked.
1201
1202 if (failed(verifyPoolingOpImpl(getOperation(), values.kernel, values.stride,
1203 values.pad, getInput(), getOutput())))
1204 return failure();
1205
1207 return failure();
1208
1209 return success();
1210}
1211
1212LogicalResult tosa::ClampOp::verify() {
1213 mlir::Type inputETy =
1214 llvm::cast<ShapedType>(getInput().getType()).getElementType();
1215 if (auto quantType =
1216 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(inputETy)) {
1217 inputETy = getStorageElementTypeFromQuantized(quantType);
1218 }
1219 mlir::Type outputETy =
1220 llvm::cast<ShapedType>(getOutput().getType()).getElementType();
1221 if (auto quantType =
1222 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(outputETy)) {
1223 outputETy = getStorageElementTypeFromQuantized(quantType);
1224 }
1225 if (inputETy != outputETy)
1226 return emitOpError("input/output element types are incompatible.");
1227
1228 auto maxValAttr = getMaxValAttr();
1229 auto minValAttr = getMinValAttr();
1230
1231 unsigned dataTypeBitWidth = inputETy.getIntOrFloatBitWidth();
1232
1233 if (inputETy.isInteger(dataTypeBitWidth)) {
1234 // if input datatype is integer, check that the min_val/max_val attributes
1235 // are integer attributes, and that their type is the same as the input's
1236 // datatype
1237 auto intMaxValAttr = mlir::dyn_cast<mlir::IntegerAttr>(maxValAttr);
1238 auto intMinValAttr = mlir::dyn_cast<mlir::IntegerAttr>(minValAttr);
1239 if (!intMaxValAttr || !intMinValAttr ||
1240 (intMaxValAttr.getType() != intMinValAttr.getType()) ||
1241 (intMaxValAttr.getType() != inputETy))
1242 return emitOpError("min/max attributes types are incompatible with "
1243 "input/output element types.");
1244
1245 const bool isUnsigned = inputETy.isUnsignedInteger();
1246 const bool isBoolean = inputETy.isInteger(1);
1247 const APInt minVal = intMinValAttr.getValue();
1248 const APInt maxVal = intMaxValAttr.getValue();
1249 if ((isUnsigned || isBoolean) ? maxVal.ult(minVal) : maxVal.slt(minVal))
1250 return emitOpError("expected min_val <= max_val, got min_val=")
1251 << minValAttr << ", max_val=" << maxValAttr;
1252 } else {
1253 // otherwise, input datatype is float, check that the min_val/max_val
1254 // attributes share the same type and that their type is the same as the
1255 // input's datatype
1256 auto floatMaxValAttr = mlir::dyn_cast<mlir::FloatAttr>(maxValAttr);
1257 auto floatMinValAttr = mlir::dyn_cast<mlir::FloatAttr>(minValAttr);
1258 if (!floatMaxValAttr || !floatMinValAttr ||
1259 (floatMaxValAttr.getType() != floatMinValAttr.getType()) ||
1260 (floatMaxValAttr.getType() != inputETy))
1261 return emitOpError("min/max attributes types are incompatible with "
1262 "input/output element types.");
1263
1264 const APFloat minVal = floatMinValAttr.getValue();
1265 const APFloat maxVal = floatMaxValAttr.getValue();
1266 if (minVal.isNaN() || maxVal.isNaN())
1267 return emitOpError("min/max attributes should not be 'NaN', got min_val=")
1268 << minValAttr << ", max_val=" << maxValAttr;
1269
1270 if (maxVal < minVal)
1271 return emitOpError("expected min_val <= max_val, got min_val=")
1272 << minValAttr << ", max_val=" << maxValAttr;
1273 }
1274
1275 return success();
1276}
1277
1278//===----------------------------------------------------------------------===//
1279// TOSA Operator Quantization Builders.
1280//===----------------------------------------------------------------------===//
1281
1282/// This builder is called on all convolution operators except TransposeConv,
1283/// which has specialized output shape semantics. The builder also defines the
1284/// bitwidth of the output given the bit width of the input & weight content.
1286 Type outputType, Value input, Value weight,
1287 Value bias, DenseI64ArrayAttr pad,
1288 DenseI64ArrayAttr stride,
1289 DenseI64ArrayAttr dilation,
1290 TypeAttr accType) {
1291 auto zps = createZPsAsConst(builder, input, weight);
1292 result.addOperands({input, weight, bias, zps.first, zps.second});
1293 result.addAttribute("pad", pad);
1294 result.addAttribute("stride", stride);
1295 result.addAttribute("dilation", dilation);
1296 result.addAttribute("acc_type", accType);
1297 Type finalOutputType = outputType;
1298 auto quantAttr = buildConvOpQuantizationAttr(builder, input, weight);
1299 if (quantAttr) {
1300 finalOutputType =
1301 buildConvOpResultTypeInfo(builder, outputType, input, weight);
1302 }
1303 result.addTypes(finalOutputType);
1304}
1305
1306/// Handles tosa.transpose_conv2d which has outpad and output shape
1307/// attributes.
1308static void
1310 Type outputType, Value input, Value weight,
1311 Value bias, DenseI64ArrayAttr outpad,
1312 DenseI64ArrayAttr stride, TypeAttr accType) {
1313 auto zps = createZPsAsConst(builder, input, weight);
1314 result.addOperands({input, weight, bias, zps.first, zps.second});
1315 result.addAttribute("out_pad", outpad);
1316 result.addAttribute("stride", stride);
1317 result.addAttribute("acc_type", accType);
1318 Type finalOutputType = outputType;
1319 auto quantAttr = buildConvOpQuantizationAttr(builder, input, weight);
1320 if (quantAttr) {
1321 finalOutputType =
1322 buildConvOpResultTypeInfo(builder, outputType, input, weight);
1323 }
1324 result.addTypes(finalOutputType);
1325}
1326
1329 Type outputType, Value a, Value b) {
1330 const std::pair<Value, Value> zps = createZPsAsConst(builder, a, b);
1331 result.addOperands({a, b, zps.first, zps.second});
1332
1333 Type finalOutputType{outputType};
1334 if (buildMatMulOpQuantizationAttr(builder, a, b)) {
1335 auto eType = getStorageElementTypeOrSelf(a.getType());
1336 auto inputBits = eType.getIntOrFloatBitWidth();
1337
1338 auto outputShapedType = llvm::dyn_cast<ShapedType>(outputType);
1339 assert(outputShapedType && "Output must be a shaped type");
1340
1341 IntegerType accElementType;
1342 if (inputBits == 16)
1343 accElementType = builder.getIntegerType(48);
1344 else
1345 accElementType = builder.getI32Type();
1346
1347 finalOutputType = outputShapedType.clone(accElementType);
1348 }
1349 result.addTypes(finalOutputType);
1350}
1351
1353 OperationState &result, Type outputType,
1354 Value a, Value b) {
1355 buildMatMulLikeOpWithQuantInfo(builder, result, outputType, a, b);
1356}
1357
1359 OperationState &result, Type outputType,
1360 Value a, Value b) {
1361 buildMatMulLikeOpWithQuantInfo(builder, result, outputType, a, b);
1362}
1363
1364/// Both the tosa.avg_pool2d and unary ops use the same
1365/// UnaryOpQuantizationAttr but avg_pool operator has its own builder as it
1366/// has additional parameters not part of the unary ops.
1367static void
1369 Type outputType, Value input,
1370 DenseArrayAttr kernel, DenseArrayAttr stride,
1371 DenseArrayAttr pad, TypeAttr accType) {
1372 const Location loc{result.location};
1373 int64_t inputZp{0};
1374 int64_t outputZp{0};
1375
1376 if (auto quantAttr =
1377 buildUnaryOpQuantizationAttr(builder, input, outputType)) {
1378 inputZp = quantAttr.getInputZp();
1379 outputZp = quantAttr.getOutputZp();
1380 }
1381 const std::optional<Value> inputZpOp =
1382 createZeroPointTensor(builder, loc, input.getType(), inputZp);
1383 if (!inputZpOp) {
1384 (void)emitError(
1385 loc,
1386 "Failed to create input zero point tensor for quantized AVG_POOL2D op");
1387 }
1388 const std::optional<Value> outputZpOp =
1389 createZeroPointTensor(builder, loc, outputType, outputZp);
1390 if (!outputZpOp) {
1391 (void)emitError(loc, "Failed to create output zero point tensor for "
1392 "quantized AVG_POOL2D op");
1393 }
1394
1395 if (inputZpOp && outputZpOp) {
1396 result.addOperands({input, inputZpOp.value(), outputZpOp.value()});
1397 } else {
1398 // failed to create one or more zero points above: just add input as
1399 // operands this will trigger error in building the op because of missing
1400 // zero points
1401 result.addOperands({input});
1402 }
1403 result.addAttribute("kernel", kernel);
1404 result.addAttribute("stride", stride);
1405 result.addAttribute("pad", pad);
1406 result.addAttribute("acc_type", accType);
1407 result.types.push_back(outputType);
1408}
1409
1410/// This builder mirrors avg_pool2d quant-info handling and materializes
1411/// kernel/stride/pad as const_shape operands for avg_pool2d_adaptive.
1413 OpBuilder &builder, OperationState &result, Type outputType, Value input,
1415 TypeAttr accType) {
1416 const Location loc{result.location};
1417 int64_t inputZp{0};
1418 int64_t outputZp{0};
1419
1420 if (auto quantAttr =
1421 buildUnaryOpQuantizationAttr(builder, input, outputType)) {
1422 inputZp = quantAttr.getInputZp();
1423 outputZp = quantAttr.getOutputZp();
1424 }
1425 const std::optional<Value> inputZpOp =
1426 createZeroPointTensor(builder, loc, input.getType(), inputZp);
1427 if (!inputZpOp) {
1428 (void)emitError(loc,
1429 "Failed to create input zero point tensor for quantized "
1430 "AVG_POOL2D_ADAPTIVE op");
1431 }
1432 const std::optional<Value> outputZpOp =
1433 createZeroPointTensor(builder, loc, outputType, outputZp);
1434 if (!outputZpOp) {
1435 (void)emitError(loc, "Failed to create output zero point tensor for "
1436 "quantized AVG_POOL2D_ADAPTIVE op");
1437 }
1438
1439 if (inputZpOp && outputZpOp) {
1440 ImplicitLocOpBuilder b(loc, builder);
1441 Value kernelShape = getTosaConstShape(b, kernel.asArrayRef());
1442 Value strideShape = getTosaConstShape(b, stride.asArrayRef());
1443 Value padShape = getTosaConstShape(b, pad.asArrayRef());
1444 result.addOperands({input, inputZpOp.value(), outputZpOp.value(),
1445 kernelShape, strideShape, padShape});
1446 } else {
1447 // Failed to create one or more zero points above: just add input as
1448 // operands. This will trigger error in building the op because of missing
1449 // operands.
1450 result.addOperands({input});
1451 }
1452 result.addAttribute("acc_type", accType);
1453 result.types.push_back(outputType);
1454}
1455
1456/// This builder is called on single-parameter negate operator
1457/// to construct input and output zero points based on their
1458/// types.
1460 OperationState &result, Type outputType,
1461 Value input) {
1462 const Location loc{result.location};
1463 int64_t input1Zp{0};
1464 int64_t outputZp{0};
1465 auto quantAttr = buildUnaryOpQuantizationAttr(builder, input, outputType);
1466 if (quantAttr) {
1467 input1Zp = quantAttr.getInputZp();
1468 outputZp = quantAttr.getOutputZp();
1469 }
1470 const std::optional<Value> input1ZpOp =
1471 createZeroPointTensor(builder, loc, input.getType(), input1Zp);
1472 if (!input1ZpOp) {
1473 (void)emitError(
1474 loc, "Failed to create input1 zero point for quantized NEGATE op");
1475 }
1476
1477 const std::optional<Value> outputZpOp =
1478 createZeroPointTensor(builder, loc, input.getType(), outputZp);
1479 if (!outputZpOp) {
1480 (void)emitError(
1481 loc, "Failed to create output zero point for quantized NEGATE op");
1482 }
1483
1484 if (input1ZpOp && outputZpOp) {
1485 result.addOperands({input, input1ZpOp.value(), outputZpOp.value()});
1486 } else {
1487 // failed to create one or more zero points above: just add input as
1488 // operands. This will trigger error in building the op because of
1489 // missing zero points
1490 result.addOperands({input});
1491 }
1492
1493 result.types.push_back(outputType);
1494}
1495
1496/// This builder is called on TOSA pad operator that needs to create its own
1497/// OptionalAttr quantization_attr parameter to scale the padding values
1498/// correctly. No pad_const is interpreted as zero-padding.
1500 Type outputType, Value input,
1501 Value paddings) {
1502 const Location loc{result.location};
1503 int32_t zp{0};
1504 const auto quantAttr = buildPadOpQuantizationAttr(builder, input);
1505 if (quantAttr) {
1506 zp = static_cast<int32_t>(quantAttr.getInputZp());
1507 }
1508 const auto padConstOp{createPadConstTensor(builder, loc, input, zp)};
1509 result.addOperands({input, paddings, padConstOp});
1510 result.types.push_back(outputType);
1511}
1512
1514 StringRef name, Type variableType,
1515 Attribute initialValue) {
1516 const Location loc{result.location};
1517 auto nameAttr = builder.getStringAttr(name);
1518
1519 auto shapedType = dyn_cast<ShapedType>(variableType);
1520 if (!shapedType) {
1521 (void)emitError(loc, "variable type must be a shaped type");
1522 return;
1523 }
1524 if (!shapedType.hasRank()) {
1525 (void)emitError(loc, "variable type must be a ranked type");
1526 return;
1527 }
1528
1529 auto elementType = shapedType.getElementType();
1530 auto elementTypeAttr = TypeAttr::get(elementType);
1531 ArrayRef<int64_t> shape = shapedType.getShape();
1532 auto varShapeAttr = builder.getIndexTensorAttr(convertFromMlirShape(shape));
1533
1534 result.addAttribute("sym_name", nameAttr);
1535 result.addAttribute("var_shape", varShapeAttr);
1536 result.addAttribute("type", elementTypeAttr);
1537 result.addAttribute("initial_value", initialValue);
1538}
1539
1540//===----------------------------------------------------------------------===//
1541// TOSA Operator Return Type Inference.
1542//===----------------------------------------------------------------------===//
1543static FailureOr<int64_t> resolveBroadcastDim(const int64_t dim1,
1544 const int64_t dim2) {
1545 if (dim1 == 1)
1546 return dim2;
1547 if (dim2 == 1)
1548 return dim1;
1549
1550 if (ShapedType::isStatic(dim1) && ShapedType::isStatic(dim2) && dim1 != dim2)
1551 return failure();
1552
1553 // Prefer static dimension over dynamic
1554 return ShapedType::isDynamic(dim1) ? dim2 : dim1;
1555}
1556
1557static LogicalResult resolveBroadcastShape(const ValueShapeRange &operands,
1558 SmallVector<int64_t> &outShape) {
1559 int64_t outRank = 0;
1560 for (int i = 0, e = operands.size(); i != e; ++i) {
1561 auto shape = operands.getShape(i);
1562 if (!shape.hasRank()) {
1563 // TODO(jennik): Update function to have better case handling for
1564 // invalid operands and for ranked tensors.
1565 return failure();
1566 }
1567 outRank = std::max<int64_t>(outRank, shape.getRank());
1568 }
1569
1570 outShape.resize(outRank, 1);
1571
1572 for (int i = 0, e = operands.size(); i != e; ++i) {
1573 auto shape = operands.getShape(i);
1574 auto rankDiff = outShape.size() - shape.getRank();
1575
1576 for (size_t i = 0, e = shape.getRank(); i < e; ++i) {
1577 auto dim1 = outShape[i + rankDiff];
1578 auto dim2 = shape.getDimSize(i);
1579
1580 const FailureOr<int64_t> maybeResolvedDim =
1581 resolveBroadcastDim(dim1, dim2);
1582 if (failed(maybeResolvedDim))
1583 return failure();
1584 const int64_t resolvedDim = *maybeResolvedDim;
1585 outShape[i + rankDiff] = resolvedDim;
1586 }
1587 }
1588
1589 return success();
1590}
1591
1592LogicalResult tosa::ArgMaxOp::inferReturnTypeComponents(
1593 MLIRContext *context, ::std::optional<Location> location,
1594 ArgMaxOp::Adaptor adaptor,
1595 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1596 return inferArgMaxMinReturnTypeComponents(context, location, adaptor,
1597 inferredReturnShapes);
1598}
1599
1600LogicalResult tosa::ArgMinOp::inferReturnTypeComponents(
1601 MLIRContext *context, ::std::optional<Location> location,
1602 ArgMinOp::Adaptor adaptor,
1603 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1604 return inferArgMaxMinReturnTypeComponents(context, location, adaptor,
1605 inferredReturnShapes);
1606}
1607
1608LogicalResult tosa::RFFT2dOp::inferReturnTypeComponents(
1609 MLIRContext *context, ::std::optional<Location> location,
1610 RFFT2dOp::Adaptor adaptor,
1611 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1612 ShapeAdaptor inputShape(adaptor.getInputReal().getType());
1613
1614 if (!inputShape.hasRank())
1615 return failure();
1616
1617 llvm::SmallVector<int64_t> outputShape;
1618 outputShape.resize(3, ShapedType::kDynamic);
1619 outputShape[0] = inputShape.getDimSize(0);
1620 outputShape[1] = inputShape.getDimSize(1);
1621 int64_t inWidth = inputShape.getDimSize(2);
1622
1623 // Note that we can support this calculation symbolically
1624 // in the future e.g. [x, y, z] -> [x, y, z / 2 + 1]
1625 if (inWidth != ShapedType::kDynamic)
1626 outputShape[2] = inWidth / 2 + 1;
1627
1628 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1629 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1630
1631 return success();
1632}
1633
1634static LogicalResult verifyDimIsPowerOfTwo(Operation *op, const int64_t dimSize,
1635 const llvm::StringRef dimName) {
1636 const bool isPowerOfTwo = (dimSize & (dimSize - 1)) == 0 && dimSize > 0;
1637 if (!isPowerOfTwo)
1638 return op->emitOpError("expected ")
1639 << dimName << " to be a power of two, got " << dimSize;
1640
1641 return success();
1642}
1643
1644LogicalResult tosa::RFFT2dOp::verify() {
1645 const auto outputTypes = getResultTypes();
1646 if (failed(verifyCompatibleShapes(outputTypes)))
1647 return emitOpError("expected output shapes to match, got ") << outputTypes;
1648
1649 const auto inputType =
1650 llvm::dyn_cast<RankedTensorType>(getInputReal().getType());
1651 if (!inputType)
1652 return success();
1653
1654 const int64_t height = inputType.getDimSize(1);
1655 if (ShapedType::isStatic(height) &&
1656 failed(verifyDimIsPowerOfTwo(*this, height, "height")))
1657 return failure();
1658
1659 const int64_t width = inputType.getDimSize(2);
1660 if (ShapedType::isStatic(width) &&
1661 failed(verifyDimIsPowerOfTwo(*this, width, "width")))
1662 return failure();
1663
1664 const auto outputType = llvm::dyn_cast<RankedTensorType>(outputTypes[0]);
1665 if (!outputType)
1666 return success();
1667
1668 // Batch and height input/output dimensions should match
1669 if (failed(verifyCompatibleShape(inputType.getShape().drop_back(),
1670 outputType.getShape().drop_back())))
1671 return emitOpError("expected batch and height dimensions of input/output "
1672 "to match, got input=")
1673 << inputType << " output=" << outputType;
1674
1675 // Output width dimension expected to be input_width / 2 + 1
1676 const int64_t outputWidth = outputType.getDimSize(2);
1677 if (ShapedType::isStatic(width) && ShapedType::isStatic(outputWidth) &&
1678 (outputWidth != (width / 2) + 1))
1679 return emitOpError(
1680 "expected output width to be equal to input_width / 2 + 1, got ")
1681 << outputWidth;
1682
1683 return success();
1684}
1685
1686LogicalResult tosa::FFT2dOp::inferReturnTypeComponents(
1687 MLIRContext *context, ::std::optional<Location> location,
1688 FFT2dOp::Adaptor adaptor,
1689 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1690 inferredReturnShapes.push_back(
1691 ShapedTypeComponents(ShapeAdaptor(adaptor.getInputReal().getType())));
1692 inferredReturnShapes.push_back(
1693 ShapedTypeComponents(ShapeAdaptor(adaptor.getInputImag().getType())));
1694 return success();
1695}
1696
1697LogicalResult tosa::FFT2dOp::verify() {
1698 const auto inputRealType =
1699 llvm::dyn_cast<RankedTensorType>(getInputReal().getType());
1700 const auto inputImagType =
1701 llvm::dyn_cast<RankedTensorType>(getInputImag().getType());
1702 if (!inputRealType || !inputImagType)
1703 return success();
1704
1705 const auto trySelectStaticDim = [](const int64_t a, const int64_t b) {
1706 return ShapedType::isDynamic(a) ? a : b;
1707 };
1708
1709 const int64_t height = trySelectStaticDim(inputRealType.getDimSize(1),
1710 inputImagType.getDimSize(1));
1711 if (ShapedType::isStatic(height) &&
1712 failed(verifyDimIsPowerOfTwo(*this, height, "height")))
1713 return failure();
1714
1715 const int64_t width = trySelectStaticDim(inputRealType.getDimSize(2),
1716 inputImagType.getDimSize(2));
1717 if (ShapedType::isStatic(width) &&
1718 failed(verifyDimIsPowerOfTwo(*this, width, "width")))
1719 return failure();
1720
1721 return success();
1722}
1723
1724LogicalResult tosa::ConcatOp::inferReturnTypeComponents(
1725 MLIRContext *context, ::std::optional<Location> location,
1726 ConcatOp::Adaptor adaptor,
1727 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1728 // Infer all dimension sizes by reducing based on inputs.
1729 const Properties &prop = adaptor.getProperties();
1730 int32_t axis = prop.axis.getValue().getSExtValue();
1731 llvm::SmallVector<int64_t> outputShape;
1732 bool hasRankedInput = false;
1733 for (auto operand : adaptor.getOperands()) {
1734 ShapeAdaptor operandShape(operand.getType());
1735 if (!operandShape.hasRank())
1736 continue;
1737
1738 // Copy the Operand's rank.
1739 if (!hasRankedInput)
1740 outputShape.resize(operandShape.getRank(), ShapedType::kDynamic);
1741
1742 // Copy shapes until the dim is non-dynamic.
1743 for (int i = 0, s = operandShape.getRank(); i < s; i++) {
1744 if (i == axis || operandShape.isDynamicDim(i))
1745 continue;
1746 if (outputShape[i] == ShapedType::kDynamic)
1747 outputShape[i] = operandShape.getDimSize(i);
1748 if (outputShape[i] != operandShape.getDimSize(i))
1749 return emitOptionalError(location,
1750 "Cannot concat tensors with different sizes"
1751 " on the non-axis dimension ",
1752 i);
1753 }
1754
1755 hasRankedInput = true;
1756 }
1757
1758 if (adaptor.getInput1().empty())
1759 return failure();
1760
1761 Type inputType =
1762 llvm::cast<TensorType>(adaptor.getInput1().getType()[0]).getElementType();
1763 if (!hasRankedInput) {
1764 inferredReturnShapes.push_back(ShapedTypeComponents(inputType));
1765 return success();
1766 }
1767
1768 // Determine the dimension size along the concatenation axis.
1769 int64_t concatDimSize = 0;
1770 for (auto operand : adaptor.getOperands()) {
1771 ShapeAdaptor operandShape(operand.getType());
1772
1773 // We need to know the length of the concatenation axis of all inputs to
1774 // determine the dimension size of the output shape.
1775 if (!operandShape.hasRank() || operandShape.isDynamicDim(axis)) {
1776 concatDimSize = ShapedType::kDynamic;
1777 break;
1778 }
1779
1780 concatDimSize += operandShape.getDimSize(axis);
1781 }
1782
1783 outputShape[axis] = concatDimSize;
1784
1785 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape, inputType));
1786 return success();
1787}
1788
1789LogicalResult tosa::ConcatOp::verify() {
1790 // check that each input has same element type as output
1791 auto outType = getOutput().getType();
1792 const Operation::operand_range inputList = getInput1();
1793
1794 // Check there is at least one input
1795 if (inputList.empty())
1796 return emitOpError("expect at least one input");
1797
1798 if (!llvm::all_of(inputList, [&](auto input) {
1799 return succeeded(verifySameElementTypes(
1800 *this, /* inType = */ input.getType(), outType));
1801 })) {
1802 return failure();
1803 }
1804
1805 const int32_t axis = getAxis();
1806 ShapeAdaptor firstRankedInputShape = nullptr;
1807 for (const auto &input : inputList) {
1808 const Type inputType = input.getType();
1809 ShapeAdaptor currShape(inputType);
1810 if (currShape.hasRank()) {
1811 firstRankedInputShape = currShape;
1812 // Check axis is in expected range
1813 if (axis < 0 || axis >= firstRankedInputShape.getRank())
1814 return emitOpError("expect axis to be within range 0 < axis < "
1815 "rank(input1[firstRankedTensorIdx]), got ")
1816 << axis;
1817 break;
1818 }
1819 }
1820
1821 const auto allOperandsHasRank = [](const Value input) {
1822 return ShapeAdaptor(input.getType()).hasRank();
1823 };
1824 if (llvm::all_of(inputList, allOperandsHasRank)) {
1825 const int64_t firstInputRank = firstRankedInputShape.getRank();
1826
1827 for (const auto &[index, input] : llvm::enumerate(inputList.drop_front())) {
1828 const ShapeAdaptor inputShape(input.getType());
1829 const int64_t inputRank = inputShape.getRank();
1830 const size_t operandNum = index + 1;
1831
1832 // Check that each operand has the same rank
1833 if (inputRank != firstInputRank)
1834 return emitOpError(
1835 "expect all operands to have the same rank, but got ")
1836 << firstInputRank << " vs " << inputRank << " on operands 0 and "
1837 << operandNum;
1838
1839 // Check non-axis dims match
1840 for (int i = 0; i < inputRank; i++) {
1841 const int64_t inputDim = inputShape.getDimSize(i);
1842 const int64_t firstInputDim = firstRankedInputShape.getDimSize(i);
1843 if (i == axis || firstRankedInputShape.isDynamicDim(i) ||
1844 inputShape.isDynamicDim(i))
1845 continue;
1846 if (inputDim != firstInputDim)
1847 return emitOpError("expect all operand shapes to have the same sizes "
1848 "on non-axis dimensions, but got ")
1849 << inputDim << " vs " << firstInputDim << " at index " << i
1850 << " on operands 0 and " << operandNum;
1851 }
1852 }
1853
1854 const ShapeAdaptor outputShape(outType);
1855 if (outputShape.hasRank() && outputShape.getRank() != firstInputRank)
1856 return emitOpError("expect output rank to match inputs rank, got ")
1857 << outputShape.getRank() << " vs " << firstInputRank;
1858
1859 // ERROR_IF(axis_sum != shape[axis]);
1860 int64_t axisSum = 0;
1861 for (const auto &input : inputList) {
1862 const ShapeAdaptor inputShape(input.getType());
1863 if (inputShape.isDynamicDim(axis)) {
1864 // make axisSum negative to indicate invalid value
1865 axisSum = -1;
1866 break;
1867 }
1868 axisSum += inputShape.getDimSize(axis);
1869 }
1870
1871 if (axisSum >= 0 && outputShape.hasRank() &&
1872 !outputShape.isDynamicDim(axis) &&
1873 axisSum != outputShape.getDimSize(axis))
1874 return emitOpError("requires sum of axis dimensions of input1 "
1875 "equal to output axis dimension, got ")
1876 << axisSum << " and " << outputShape.getDimSize(axis);
1877 }
1878
1879 return success();
1880}
1881
1882LogicalResult tosa::EqualOp::inferReturnTypeComponents(
1883 MLIRContext *context, ::std::optional<Location> location,
1884 ValueShapeRange operands, DictionaryAttr attributes, PropertyRef properties,
1885 RegionRange regions,
1886 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1887 auto elementType = IntegerType::get(context, /*width=*/1);
1888
1890 if (resolveBroadcastShape(operands, outShape).failed()) {
1891 inferredReturnShapes.push_back(ShapedTypeComponents(elementType));
1892 return success();
1893 }
1894
1895 inferredReturnShapes.push_back(ShapedTypeComponents(outShape, elementType));
1896 return success();
1897}
1898
1899bool tosa::EqualOp::isCompatibleReturnTypes(TypeRange l, TypeRange r) {
1900 if (l.size() != r.size() || l.size() != 1)
1901 return false;
1902 return succeeded(verifyCompatibleShape(l[0], r[0]));
1903}
1904
1905// MATMUL batch shapes are right aligned and may have different ranks. Missing
1906// leading dimensions are treated as one, while an unranked input remains
1907// unknown because it may contain any number of batch dimensions.
1909 int64_t axis) {
1910 if (!shape.hasRank())
1911 return ShapedType::kDynamic;
1912 const int64_t inputAxis = axis - (outputRank - shape.getRank());
1913 return inputAxis < 0 ? 1 : shape.getDimSize(inputAxis);
1914}
1915
1916static FailureOr<SmallVector<int64_t>>
1918 int64_t outputRank, bool transposeB) {
1919 if (outputRank < 2 ||
1920 (aShape.hasRank() &&
1921 (aShape.getRank() < 2 || aShape.getRank() > outputRank)) ||
1922 (bShape.hasRank() &&
1923 (bShape.getRank() < 2 || bShape.getRank() > outputRank)))
1924 return failure();
1925
1926 SmallVector<int64_t> outputShape(outputRank, ShapedType::kDynamic);
1927 for (int64_t axis = 0; axis < outputRank - 2; ++axis) {
1928 const int64_t aDim = getMatMulBatchDim(aShape, outputRank, axis);
1929 const int64_t bDim = getMatMulBatchDim(bShape, outputRank, axis);
1930 FailureOr<int64_t> resolvedDim = resolveBroadcastDim(aDim, bDim);
1931 if (failed(resolvedDim))
1932 return failure();
1933 outputShape[axis] = *resolvedDim;
1934 }
1935
1936 if (aShape.hasRank())
1937 outputShape[outputRank - 2] = aShape.getDimSize(aShape.getRank() - 2);
1938 if (bShape.hasRank())
1939 outputShape[outputRank - 1] =
1940 bShape.getDimSize(bShape.getRank() - (transposeB ? 2 : 1));
1941 return outputShape;
1942}
1943
1945 const ShapeAdaptor &aShape, const ShapeAdaptor &bShape, bool transposeB,
1946 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1947 if ((aShape.hasRank() && aShape.getRank() < 2) ||
1948 (bShape.hasRank() && bShape.getRank() < 2))
1949 return failure();
1950
1951 // An unranked input can have an arbitrary batch prefix, so the output rank
1952 // cannot yet be inferred.
1953 if (!aShape.hasRank() || !bShape.hasRank()) {
1954 inferredReturnShapes.emplace_back();
1955 return success();
1956 }
1957
1958 const int64_t aChannels = aShape.getDimSize(aShape.getRank() - 1);
1959 const int64_t bChannels =
1960 bShape.getDimSize(bShape.getRank() - (transposeB ? 1 : 2));
1961 if (ShapedType::isStatic(aChannels) && ShapedType::isStatic(bChannels) &&
1962 aChannels != bChannels)
1963 return failure();
1964
1965 const int64_t outputRank = std::max(aShape.getRank(), bShape.getRank());
1966 FailureOr<SmallVector<int64_t>> outputShape =
1967 resolveMatMulOutputShape(aShape, bShape, outputRank, transposeB);
1968 if (failed(outputShape))
1969 return failure();
1970
1971 inferredReturnShapes.emplace_back(*outputShape);
1972 return success();
1973}
1974
1975LogicalResult tosa::MatMulOp::inferReturnTypeComponents(
1976 MLIRContext *context, ::std::optional<Location> location,
1977 MatMulOp::Adaptor adaptor,
1978 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1979 return inferMatMulReturnTypeComponents(ShapeAdaptor(adaptor.getA().getType()),
1980 ShapeAdaptor(adaptor.getB().getType()),
1981 /*transposeB=*/false,
1982 inferredReturnShapes);
1983}
1984
1985template <typename T>
1986static LogicalResult verifyMatMulQuantizedOperandsType(T op, Type aElementType,
1987 Type bElementType) {
1988 const auto aQuantizedEType =
1989 llvm::dyn_cast<quant::UniformQuantizedType>(aElementType);
1990 const auto bQuantizedEType =
1991 llvm::dyn_cast<quant::UniformQuantizedType>(bElementType);
1992
1993 if (aQuantizedEType || bQuantizedEType) {
1994 if (!aQuantizedEType || !bQuantizedEType) {
1995 return op.emitOpError("expect operands to be both quantized or both not "
1996 "quantized, got ")
1997 << aElementType << " and " << bElementType;
1998 }
1999 // both a and b have quantized element types
2000 auto aQuantWidth = aQuantizedEType.getStorageTypeIntegralWidth();
2001 auto bQuantWidth = bQuantizedEType.getStorageTypeIntegralWidth();
2002 if (aQuantWidth != bQuantWidth) {
2003 return op.emitOpError("expect quantized operands to have same widths, "
2004 "got ")
2005 << aQuantWidth << " and " << bQuantWidth;
2006 }
2007 }
2008
2009 return success();
2010}
2011
2012template <typename T>
2013static LogicalResult verifyMatMulZeroPointType(T op, Value input, Value zp,
2014 StringRef inputName,
2015 StringRef zpName) {
2016 const Type inputElementType = getElementTypeOrSelf(input.getType());
2017 const Type inputStorageElementType = getStorageElementTypeOrSelf(input);
2018 const Type zpElementType = getStorageElementTypeOrSelf(zp);
2019 Type expectedElementType = inputStorageElementType;
2020
2021 if (isa<BlockScaledType>(inputElementType))
2022 expectedElementType = Float32Type::get(op.getContext());
2023
2024 if (expectedElementType == zpElementType)
2025 return success();
2026
2027 InFlightDiagnostic diag = op.emitOpError("expect input ");
2028 diag << inputName << " and " << zpName;
2029 if (isa<BlockScaledType>(inputElementType))
2030 diag << " have compatible element types, got " << inputElementType
2031 << " and " << zpElementType;
2032 else
2033 diag << " have the same element type, got " << inputStorageElementType
2034 << " and " << zpElementType;
2035 return diag;
2036}
2037
2039 SmallVector<int64_t> batchShape;
2040 if (!shape.hasRank() || shape.getRank() < 2)
2041 return batchShape;
2042 batchShape.reserve(shape.getRank() - 2);
2043 for (int64_t i = 0, e = shape.getRank() - 2; i < e; ++i)
2044 batchShape.push_back(shape.getDimSize(i));
2045 return batchShape;
2046}
2047
2048template <typename T>
2049static LogicalResult verifyMatMulShapes(T op, bool transposeB) {
2050 const ShapeAdaptor aShape(op.getA().getType());
2051 const ShapeAdaptor bShape(op.getB().getType());
2052 const auto outputType = cast<ShapedType>(op.getResult().getType());
2053
2054 int64_t channels = aShape.hasRank() ? aShape.getDimSize(aShape.getRank() - 1)
2055 : ShapedType::kDynamic;
2056 if (bShape.hasRank() &&
2057 failed(tryUpdateDimOrFailure(
2058 op, channels,
2059 bShape.getDimSize(bShape.getRank() - (transposeB ? 1 : 2)), "b",
2060 "channels")))
2061 return failure();
2062
2063 const int64_t minimumOutputRank =
2064 std::max(aShape.hasRank() ? aShape.getRank() : 2,
2065 bShape.hasRank() ? bShape.getRank() : 2);
2066 if (outputType.hasRank() && outputType.getRank() < minimumOutputRank)
2067 return op.emitOpError("expected output rank of at least ")
2068 << minimumOutputRank << ", got " << outputType.getRank();
2069
2070 const bool bothInputsRanked = aShape.hasRank() && bShape.hasRank();
2071 if (!bothInputsRanked && !outputType.hasRank())
2072 return success();
2073
2074 // When an input is unranked, use the declared output rank to validate every
2075 // result dimension constrained by the ranked input.
2076 const int64_t expectedOutputRank =
2077 bothInputsRanked ? minimumOutputRank : outputType.getRank();
2078 FailureOr<SmallVector<int64_t>> expectedOutputShape =
2079 resolveMatMulOutputShape(aShape, bShape, expectedOutputRank, transposeB);
2080 if (failed(expectedOutputShape)) {
2081 InFlightDiagnostic diag = op.emitOpError(
2082 "expected batch dimensions of a and b to be broadcast compatible, "
2083 "got a=[");
2085 diag << "] and b=[";
2087 diag << "]";
2088 return diag;
2089 }
2090
2091 if (outputType.hasRank())
2093 op.getOperation(), outputType, *expectedOutputShape);
2094 return success();
2095}
2096
2097LogicalResult MatMulOp::verify() {
2098 const Type aElementType = getElementTypeOrSelf(getA());
2099 const Type bElementType = getElementTypeOrSelf(getB());
2100
2101 if (failed(
2102 verifyMatMulQuantizedOperandsType(*this, aElementType, bElementType)))
2103 return failure();
2104
2105 if (failed(verifyMatMulZeroPointType(*this, getA(), getAZp(), "a", "a_zp")) ||
2106 failed(verifyMatMulZeroPointType(*this, getB(), getBZp(), "b", "b_zp")))
2107 return failure();
2108
2109 FailureOr<int64_t> maybeAZp = getAZeroPoint();
2110 if (succeeded(maybeAZp) && verifyAZeroPoint(*maybeAZp).failed())
2111 return failure();
2112
2113 FailureOr<int64_t> maybeBZp = getBZeroPoint();
2114 if (succeeded(maybeBZp) && verifyBZeroPoint(*maybeBZp).failed())
2115 return failure();
2116
2117 return verifyMatMulShapes(*this, /*transposeB=*/false);
2118}
2119
2120LogicalResult tosa::MatMulTOp::inferReturnTypeComponents(
2121 MLIRContext *context, ::std::optional<Location> location,
2122 MatMulTOp::Adaptor adaptor,
2123 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2124 return inferMatMulReturnTypeComponents(ShapeAdaptor(adaptor.getA().getType()),
2125 ShapeAdaptor(adaptor.getB().getType()),
2126 /*transposeB=*/true,
2127 inferredReturnShapes);
2128}
2129
2130LogicalResult MatMulTOp::verify() {
2131 const Type aElementType = getElementTypeOrSelf(getA());
2132 const Type bElementType = getElementTypeOrSelf(getB());
2133
2134 if (failed(
2135 verifyMatMulQuantizedOperandsType(*this, aElementType, bElementType)))
2136 return failure();
2137
2138 if (failed(verifyMatMulZeroPointType(*this, getA(), getAZp(), "a", "a_zp")) ||
2139 failed(verifyMatMulZeroPointType(*this, getB(), getBZp(), "b", "b_zp")))
2140 return failure();
2141
2142 FailureOr<int64_t> maybeAZp = getAZeroPoint();
2143 if (succeeded(maybeAZp) && verifyAZeroPoint(*maybeAZp).failed())
2144 return failure();
2145
2146 FailureOr<int64_t> maybeBZp = getBZeroPoint();
2147 if (succeeded(maybeBZp) && verifyBZeroPoint(*maybeBZp).failed())
2148 return failure();
2149
2150 return verifyMatMulShapes(*this, /*transposeB=*/true);
2151}
2152
2153LogicalResult tosa::MatmulTBlockScaledOp::inferReturnTypeComponents(
2154 MLIRContext *context, ::std::optional<Location> location,
2155 MatmulTBlockScaledOp::Adaptor adaptor,
2156 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2157 SmallVector<int64_t, 3> outShape(3, ShapedType::kDynamic);
2158
2159 const auto aDataShape = cast<ShapedType>(adaptor.getAData().getType());
2160 if (aDataShape.hasRank()) {
2161 outShape[0] = aDataShape.getDimSize(0);
2162 outShape[1] = aDataShape.getDimSize(1);
2163 }
2164
2165 const auto aScaleShape = cast<ShapedType>(adaptor.getAScale().getType());
2166 if (aScaleShape.hasRank()) {
2167 outShape[0] = ShapedType::isDynamic(outShape[0]) ? aScaleShape.getDimSize(0)
2168 : outShape[0];
2169 outShape[1] = ShapedType::isDynamic(outShape[1]) ? aScaleShape.getDimSize(1)
2170 : outShape[1];
2171 }
2172
2173 // If B batch size is 1, it is broadcast across A's batch size
2174 const auto bDataShape = cast<ShapedType>(adaptor.getBData().getType());
2175 if (bDataShape.hasRank()) {
2176 const int64_t bDataBatchSize = bDataShape.getDimSize(0);
2177 if (bDataBatchSize != 1)
2178 outShape[0] =
2179 ShapedType::isDynamic(outShape[0]) ? bDataBatchSize : outShape[0];
2180 outShape[2] = bDataShape.getDimSize(1);
2181 }
2182
2183 const auto bScaleShape = cast<ShapedType>(adaptor.getBScale().getType());
2184 if (bScaleShape.hasRank()) {
2185 const int64_t bScaleBatchSize = bScaleShape.getDimSize(0);
2186 if (bScaleBatchSize != 1)
2187 outShape[0] =
2188 ShapedType::isDynamic(outShape[0]) ? bScaleBatchSize : outShape[0];
2189 outShape[2] = ShapedType::isDynamic(outShape[2]) ? bScaleShape.getDimSize(1)
2190 : outShape[2];
2191 }
2192
2193 inferredReturnShapes.push_back(ShapedTypeComponents(outShape));
2194 return success();
2195}
2196
2197LogicalResult MatmulTBlockScaledOp::verify() {
2198 // Verify same input data types
2199 const Type aDataType = getAData().getType();
2200 const Type bDataType = getBData().getType();
2201 if (failed(verifySameElementTypes(*this, aDataType, bDataType, "A_data",
2202 "B_data")))
2203 return failure();
2204
2205 // Verify input shape compatibility
2206 int64_t N = ShapedType::kDynamic;
2207 int64_t D = ShapedType::kDynamic;
2208 int64_t H = ShapedType::kDynamic;
2209 int64_t W = ShapedType::kDynamic;
2210 int64_t C = ShapedType::kDynamic;
2211 int64_t multiplesOfC = ShapedType::kDynamic;
2212
2213 const ShapeAdaptor aDataShape = ShapeAdaptor(aDataType);
2214 if (aDataShape.hasRank()) {
2215 N = aDataShape.getDimSize(0);
2216 H = aDataShape.getDimSize(1);
2217 C = aDataShape.getDimSize(2);
2218 }
2219
2220 const ShapeAdaptor aScaleShape = ShapeAdaptor(getAScale().getType());
2221 if (aScaleShape.hasRank()) {
2222 if (failed(tryUpdateDimOrFailure(*this, N, aScaleShape.getDimSize(0),
2223 "a_scale", "batch")) ||
2224 failed(tryUpdateDimOrFailure(*this, H, aScaleShape.getDimSize(1),
2225 "a_scale", "height")))
2226 return failure();
2227 multiplesOfC = aScaleShape.getDimSize(2);
2228 }
2229
2230 const ShapeAdaptor bDataShape = ShapeAdaptor(bDataType);
2231 if (bDataShape.hasRank()) {
2232 if (failed(tryUpdateDimOrFailure(*this, D, bDataShape.getDimSize(0),
2233 "b_data", "batch")) ||
2234 failed(tryUpdateDimOrFailure(*this, C, bDataShape.getDimSize(2),
2235 "b_data", "channels")))
2236 return failure();
2237 W = bDataShape.getDimSize(1);
2238 }
2239
2240 const ShapeAdaptor bScaleShape = ShapeAdaptor(getBScale().getType());
2241 if (bScaleShape.hasRank()) {
2242 if (failed(tryUpdateDimOrFailure(*this, D, bScaleShape.getDimSize(0),
2243 "b_scale", "batch")) ||
2244 failed(tryUpdateDimOrFailure(*this, W, bScaleShape.getDimSize(1),
2245 "b_scale", "width")) ||
2246 failed(tryUpdateDimOrFailure(*this, multiplesOfC,
2247 bScaleShape.getDimSize(2), "b_scale",
2248 "C/block_size")))
2249 return failure();
2250 }
2251
2252 // Verify batch size is broadcast compatible
2253 if (ShapedType::isStatic(N) && ShapedType::isStatic(D) && N != D && D != 1)
2254 return emitOpError("expect B matrix batch size to be broadcast compatible "
2255 "with A, got D=")
2256 << D << " vs N=" << N;
2257
2258 // Verify C is a multiple of block size
2259 const uint32_t blockSize = BlockSizeAttr::getBlockSizeValue(getBlockSize());
2260 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_32))
2261 return emitOpError("expect block size to be 32, got ") << blockSize;
2262 if (ShapedType::isStatic(C) && C % blockSize != 0)
2263 return emitOpError("expect C to be a multiple of block size, got C=")
2264 << C << ", block_size=" << blockSize;
2265
2266 // Verify multiplesOfC is C / block size
2267 if (ShapedType::isStatic(C) && ShapedType::isStatic(multiplesOfC) &&
2268 multiplesOfC != C / blockSize)
2269 return emitOpError(
2270 "expect scale operands dimension 2 to equal C/block_size (")
2271 << C << "/" << blockSize << ")" << ", got " << multiplesOfC;
2272
2273 // Verify output shape
2274 N = ShapedType::isDynamic(N) ? D : N;
2275 const SmallVector<int64_t, 3> expectedOutputShape = {N, H, W};
2276 const auto outputType = cast<ShapedType>(getResult().getType());
2277 if (outputType.hasRank() &&
2278 failed(
2279 verifyCompatibleShape(outputType.getShape(), expectedOutputShape))) {
2280 InFlightDiagnostic opError = emitOpError("expected output shape ");
2281 printShapeToDiagnostic(opError, outputType.getShape());
2282 opError << " to be compatible with expected output shape ";
2283 printShapeToDiagnostic(opError, expectedOutputShape);
2284 return opError;
2285 }
2286
2287 return success();
2288}
2289
2290LogicalResult tosa::PadOp::inferReturnTypeComponents(
2291 MLIRContext *context, ::std::optional<Location> location,
2292 PadOp::Adaptor adaptor,
2293 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2294 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2295 auto paddingRank =
2296 cast<tosa::shapeType>(adaptor.getPadding().getType()).getRank();
2297 SmallVector<int64_t> outputShape;
2298
2299 // If the input rank is unknown, we can infer the output rank using the
2300 // padding shape's rank divided by 2.
2301 if (!inputShape.hasRank()) {
2302 outputShape.resize(paddingRank / 2, ShapedType::kDynamic);
2303 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
2304 return success();
2305 }
2306
2307 SmallVector<int64_t> paddingValues;
2308 // If the paddings value is not a constant, all dimensions must be dynamic.
2309 if (!tosa::getConstShapeValues(adaptor.getPadding().getDefiningOp(),
2310 paddingValues)) {
2311 outputShape.resize(inputShape.getRank(), ShapedType::kDynamic);
2312 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
2313 return success();
2314 }
2315
2316 outputShape.reserve(inputShape.getRank());
2317 for (int i = 0, s = inputShape.getRank(); i < s; i++) {
2318 if (inputShape.isDynamicDim(i)) {
2319 outputShape.push_back(ShapedType::kDynamic);
2320 continue;
2321 }
2322 auto padFront = paddingValues[i * 2];
2323 auto padBack = paddingValues[i * 2 + 1];
2324 outputShape.push_back(inputShape.getDimSize(i) + padFront + padBack);
2325 }
2326
2327 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
2328 return success();
2329}
2330
2331LogicalResult tosa::PadOp::verify() {
2332 if (verifySameElementTypes(*this, /* inType = */ getInput1().getType(),
2333 /* outType = */ getOutput().getType())
2334 .failed()) {
2335 return failure();
2336 }
2337
2338 if (auto padConst = getPadConst()) {
2339 if (verifySameElementTypes(*this, /* inType = */ padConst.getType(),
2340 /* outType = */ getOutput().getType())
2341 .failed()) {
2342 return failure();
2343 }
2344 }
2345
2346 RankedTensorType inputType =
2347 llvm::dyn_cast<RankedTensorType>(getInput1().getType());
2348 RankedTensorType outputType =
2349 llvm::dyn_cast<RankedTensorType>(getOutput().getType());
2350 if (!inputType || !outputType)
2351 return success();
2352
2353 if (failed(verifyRanksMatch(getOperation(), inputType, outputType, "input",
2354 "output")))
2355 return failure();
2356
2357 auto inputRank = inputType.getRank();
2358 auto paddingRank = cast<tosa::shapeType>(getPadding().getType()).getRank();
2359 if (paddingRank != inputRank * 2)
2360 return emitOpError() << "padding tensor must have " << inputRank
2361 << " * 2 = " << inputRank * 2 << " elements, but got "
2362 << paddingRank;
2363
2364 return success();
2365}
2366
2367LogicalResult tosa::SliceOp::inferReturnTypeComponents(
2368 MLIRContext *context, ::std::optional<Location> location,
2369 SliceOp::Adaptor adaptor,
2370 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2371
2372 Type inputType = getElementTypeOrSelf(adaptor.getInput1().getType());
2375
2376 if (!tosa::getConstShapeValues(adaptor.getStart().getDefiningOp(), start) ||
2377 !tosa::getConstShapeValues(adaptor.getSize().getDefiningOp(), size)) {
2378 auto rank = cast<tosa::shapeType>(adaptor.getSize().getType()).getRank();
2379 SmallVector<int64_t> fallback(rank, ShapedType::kDynamic);
2380 inferredReturnShapes.push_back(ShapedTypeComponents(fallback, inputType));
2381 return success();
2382 }
2383
2384 // if size[i] is -1, all remaining elements in dimension i are included
2385 // in the slice, similar to TF.
2386 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2387 // initialize outputShape to all unknown
2388 SmallVector<int64_t> outputShape(size.size(), ShapedType::kDynamic);
2389 if (inputShape.hasRank()) {
2390 for (size_t i = 0; i < size.size(); i++) {
2391 if (size[i] != 0 && size[i] >= -1 && start[i] >= 0 &&
2392 (ShapedType::isDynamic(inputShape.getDimSize(i)) ||
2393 start[i] < inputShape.getDimSize(i))) {
2394 // size[i] is not 0 and not < -1, and start[i] is in valid range
2395 if (ShapedType::isDynamic(inputShape.getDimSize(i))) {
2396 // input shape has unknown dim[i] - only valid if size[i] > 0
2397 if (size[i] > 0) {
2398 outputShape[i] = size[i];
2399 }
2400 } else {
2401 // input shape has known dim[i]
2402 if (size[i] == -1) {
2403 outputShape[i] = inputShape.getDimSize(i) - start[i];
2404 } else if (start[i] + size[i] <= inputShape.getDimSize(i)) {
2405 // start[i] + size[i] is within bound of input shape's dim[i]
2406 outputShape[i] = size[i];
2407 }
2408 }
2409 }
2410 }
2411 } else {
2412 outputShape = convertToMlirShape(size);
2413 }
2414 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
2415 return success();
2416}
2417
2418LogicalResult tosa::SliceOp::verify() {
2419 const Value input = getInput1();
2420 const Value output = getOutput();
2421 if (verifySameElementTypes(*this, /* inType = */ input.getType(),
2422 /* outType = */ output.getType())
2423 .failed())
2424 return failure();
2425
2426 const Value start = getStart();
2427 const Value size = getSize();
2428 const ShapeAdaptor inputShape(input.getType());
2429 const ShapeAdaptor outputShape(output.getType());
2430
2431 if (inputShape.hasRank()) {
2432 const auto inputRank = inputShape.getRank();
2433 if (outputShape.hasRank() && inputRank != outputShape.getRank())
2434 return emitOpError(
2435 "expect input1 and output to have the same ranks, got ")
2436 << inputRank << " and " << outputShape.getRank();
2437
2438 const auto startShapeRank =
2439 llvm::cast<tosa::shapeType>(start.getType()).getRank();
2440 if (inputRank != startShapeRank)
2441 return emitOpError("length of start is not equal to rank of input shape");
2442
2443 const auto sizeShapeRank =
2444 llvm::cast<tosa::shapeType>(size.getType()).getRank();
2445 if (inputRank != sizeShapeRank)
2446 return emitOpError("length of size is not equal to rank of input shape");
2447 }
2448
2449 return success();
2450}
2451
2452LogicalResult tosa::MulOp::inferReturnTypeComponents(
2453 MLIRContext *context, ::std::optional<Location> location,
2454 ValueShapeRange operands, DictionaryAttr attributes, PropertyRef properties,
2455 RegionRange regions,
2456 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2457 // mul op's output shape only depend on input1 and input2, not on shift
2458 ValueShapeRange twoInputs = operands.drop_back();
2460 if (resolveBroadcastShape(twoInputs, outShape).failed()) {
2461 inferredReturnShapes.push_back(ShapedTypeComponents());
2462 } else {
2463 inferredReturnShapes.push_back(ShapedTypeComponents(outShape));
2464 }
2465 return success();
2466}
2467
2468LogicalResult tosa::MulOp::verify() {
2469 const Value output = getOutput();
2470 auto resElemType = getElementTypeOrSelf(output);
2471
2472 // Verify if the element type among operands and result match tosa
2473 // specification.
2474 if (auto resIntType = dyn_cast<IntegerType>(resElemType)) {
2475 IntegerType lhsIntType =
2476 dyn_cast<IntegerType>(getElementTypeOrSelf(getInput1()));
2477 IntegerType rhsIntType =
2478 dyn_cast<IntegerType>(getElementTypeOrSelf(getInput2()));
2479 if (!lhsIntType || !rhsIntType || lhsIntType != rhsIntType)
2480 return emitOpError("requires the same element type for all operands");
2481
2482 // Though the spec requires the element type of result to be i32, a more
2483 // relaxed way is provided at dialect level for easier cooperating with
2484 // other dialects.
2485 if (lhsIntType.getWidth() > resIntType.getWidth())
2486 return emitOpError("invalid data type size for operands or result");
2487
2488 } else {
2489 // For other supported type, the spec requires requires the same element
2490 // type for all operands (excludes `shift` operand) and results.
2491 for (int i = 0; i < 2; ++i) {
2492 if (getElementTypeOrSelf(getOperand(i)) != resElemType)
2493 return emitOpError(
2494 "requires the same element type for all operands and results");
2495 }
2496 }
2497
2498 // Verify the op has same ranks for all main operands (excludes extra operands
2499 // such as shift of mul op, so this is the only difference with the built-in
2500 // `SameOperandsAndResultRank` trait) and results types, if known.
2501 TypeRange operandTypes = getOperandTypes();
2502 ShapedType aType = cast<ShapedType>(operandTypes[0]);
2503 ShapedType bType = cast<ShapedType>(operandTypes[1]);
2504
2505 const bool aHasRank = aType.hasRank();
2506 const bool bHasRank = bType.hasRank();
2507
2508 bool hasExpectedOutputShape = false;
2509 SmallVector<int64_t> expectedOutputShape;
2510
2511 if (aHasRank && bHasRank) {
2512 const int64_t aRank = aType.getRank();
2513 const int64_t bRank = bType.getRank();
2514 if (aRank != bRank)
2515 return emitOpError("a and b operands don't have matching ranks, got ")
2516 << aRank << " and " << bRank;
2517
2518 // check for broadcast compatible shapes
2520 aType.getShape(), bType.getShape(), expectedOutputShape))
2521 return emitOpError("a and b operands don't have broadcast-compatible "
2522 "shapes, got ")
2523 << aType << " and " << bType;
2524 hasExpectedOutputShape = true;
2525 }
2526
2527 ShapedType resultType = cast<ShapedType>(output.getType());
2528 if (!resultType.hasRank())
2529 return success();
2530
2531 const int64_t resultRank = resultType.getRank();
2532 if (aHasRank && resultRank != aType.getRank())
2533 return emitOpError("result type has different rank than a, got ")
2534 << resultRank << " vs " << aType.getRank();
2535 if (bHasRank && resultRank != bType.getRank())
2536 return emitOpError("result type has different rank than b, got ")
2537 << resultRank << " vs " << bType.getRank();
2538
2539 if (hasExpectedOutputShape &&
2540 failed(verifyOutputShapeCompatibleWithExpected(getOperation(), resultType,
2541 expectedOutputShape)))
2542 return failure();
2543
2544 return success();
2545}
2546
2547LogicalResult tosa::TableOp::inferReturnTypeComponents(
2548 MLIRContext *context, ::std::optional<Location> location,
2549 TableOp::Adaptor adaptor,
2550 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2551 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2552
2553 if (!inputShape.hasRank()) {
2554 inferredReturnShapes.push_back(ShapedTypeComponents());
2555 return success();
2556 }
2557
2558 inferredReturnShapes.resize(1);
2559 inputShape.getDims(inferredReturnShapes[0]);
2560 return success();
2561}
2562
2563LogicalResult tosa::TableOp::verify() {
2564 const TensorType inputType = getInput1().getType();
2565 const TensorType outputType = getOutput().getType();
2566
2567 if (!inputType.hasRank() || !outputType.hasRank())
2568 return success();
2569
2570 if (failed(verifyRanksMatch(getOperation(), inputType, outputType, "input",
2571 "result")))
2572 return failure();
2573
2574 auto inputDims = inputType.getShape();
2575 auto outputDims = outputType.getShape();
2576 for (auto it : llvm::enumerate(llvm::zip(inputDims, outputDims))) {
2577 int64_t dim = it.index();
2578 auto [inputDim, outputDim] = it.value();
2579 if (ShapedType::isStatic(outputDim) && outputDim != inputDim) {
2580 return emitOpError() << "dim(result, " << dim << ") = " << outputDim
2581 << " doesn't match dim(input, " << dim
2582 << ") = " << inputDim;
2583 }
2584 }
2585 return success();
2586}
2587
2588LogicalResult
2589tosa::TileOp::getConstantMultiples(SmallVector<int64_t> &multiples) {
2590 // Multiples must be constants.
2591 DenseIntElementsAttr multiplesAttr;
2592 if (!matchPattern(getMultiples(), m_Constant(&multiplesAttr)))
2593 return failure();
2594 multiples =
2595 llvm::map_to_vector(multiplesAttr.getValues<APInt>(),
2596 [](const APInt &val) { return val.getSExtValue(); });
2597 return success();
2598}
2599
2600LogicalResult tosa::TileOp::inferReturnTypeComponents(
2601 MLIRContext *context, ::std::optional<Location> location,
2602 TileOp::Adaptor adaptor,
2603 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2604 Type inputType = getElementTypeOrSelf(adaptor.getInput1().getType());
2605 SmallVector<int64_t> multiples;
2606 if (!tosa::getConstShapeValues(adaptor.getMultiples().getDefiningOp(),
2607 multiples)) {
2608 auto rank =
2609 cast<tosa::shapeType>(adaptor.getMultiples().getType()).getRank();
2610 SmallVector<int64_t> fallback(rank, ShapedType::kDynamic);
2611 inferredReturnShapes.push_back(ShapedTypeComponents(fallback, inputType));
2612 return success();
2613 }
2614 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2615 SmallVector<int64_t> outputShape;
2616 if (!inputShape.hasRank()) {
2617 outputShape.resize(multiples.size(), ShapedType::kDynamic);
2618 inferredReturnShapes.push_back(
2619 ShapedTypeComponents(outputShape, inputType));
2620 return success();
2621 }
2622 if (static_cast<size_t>(inputShape.getRank()) != multiples.size())
2623 return failure();
2624
2625 // Any non dynamic dimension can be multiplied to a known size.
2626 outputShape.reserve(multiples.size());
2627 for (int i = 0, s = inputShape.getRank(); i < s; i++) {
2628 // Conservatively infer a dynamic dimension for non-positive multiples.
2629 // Leave their validation to tosa-validate.
2630 if (multiples[i] <= 0) {
2631 outputShape.push_back(ShapedType::kDynamic);
2632 } else {
2633 int64_t dim = inputShape.getDimSize(i);
2634 if (dim != ShapedType::kDynamic)
2635 dim *= multiples[i];
2636 outputShape.push_back(dim);
2637 }
2638 }
2639
2640 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape, inputType));
2641 return success();
2642}
2643
2644LogicalResult tosa::TileOp::verify() {
2645 if (verifySameElementTypes(*this, /* intype = */ getInput1().getType(),
2646 /* outType = */ getOutput().getType())
2647 .failed()) {
2648 return failure();
2649 }
2650 ShapedType inputType = llvm::cast<ShapedType>(getInput1().getType());
2651 ShapedType outputType = llvm::cast<ShapedType>(getType());
2652
2653 shapeType multiplesType =
2654 llvm::cast<tosa::shapeType>(getMultiples().getType());
2655
2656 auto multiplesRank = multiplesType.getRank();
2657
2658 if (inputType.hasRank()) {
2659 if (inputType.getRank() != multiplesRank)
2660 return emitOpError("expect 'multiples' to have rank ")
2661 << inputType.getRank() << " but got " << multiplesRank << ".";
2662 if (outputType.hasRank() &&
2663 failed(verifyRanksMatch(getOperation(), inputType, outputType, "input",
2664 "output")))
2665 return failure();
2666 } else if (outputType.hasRank() && outputType.getRank() != multiplesRank)
2667 return emitOpError("expect 'multiples' array to have length ")
2668 << outputType.getRank() << " but got " << multiplesRank << ".";
2669
2670 return success();
2671}
2672
2673bool tosa::ReshapeOp::isCompatibleReturnTypes(TypeRange l, TypeRange r) {
2674 if (l.size() != r.size() || l.size() != 1)
2675 return false;
2676 return getElementTypeOrSelf(l[0]) == getElementTypeOrSelf(r[0]);
2677}
2678
2679LogicalResult tosa::ReshapeOp::inferReturnTypeComponents(
2680 MLIRContext *context, ::std::optional<Location> location,
2681 ReshapeOp::Adaptor adaptor,
2682 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2683 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2684 Type inputType = getElementTypeOrSelf(adaptor.getInput1().getType());
2685 llvm::SmallVector<int64_t> newShapeValue;
2686 // A shape that is not a compile-time constant, or that contains a dimension
2687 // which cannot describe a TOSA tensor (a negative value other than the
2688 // inferable -1, or zero), cannot be used to infer the result type. Fall back
2689 // to dynamic dimensions and let tosa-validate diagnose the shape. Such a
2690 // dimension must not reach RankedTensorType::get().
2691 if (!tosa::getConstShapeValues(adaptor.getShape().getDefiningOp(),
2692 newShapeValue) ||
2693 llvm::any_of(newShapeValue, [](int64_t dim) {
2694 return dim == 0 || dim < kInferableDimSize;
2695 })) {
2696 auto rank = cast<tosa::shapeType>(adaptor.getShape().getType()).getRank();
2697 SmallVector<int64_t> fallback(rank, ShapedType::kDynamic);
2698 inferredReturnShapes.push_back(ShapedTypeComponents(fallback, inputType));
2699 return success();
2700 }
2701
2702 newShapeValue = convertToMlirShape(newShapeValue);
2703
2704 // We cannot infer from the total number of elements so we must take the
2705 // shape attribute as exact.
2706 if (!inputShape.hasRank() || !inputShape.hasStaticShape()) {
2707 inferredReturnShapes.push_back(
2708 ShapedTypeComponents(newShapeValue, inputType));
2709 return success();
2710 }
2711
2712 // Determine the number of elements covered by the slice of all static
2713 // dimensions. This allows us to infer the length of the remaining dynamic
2714 // dimension.
2715 int64_t numElements = inputShape.getNumElements();
2716 int64_t staticMul = 1;
2717 for (auto val : newShapeValue) {
2718 if (ShapedType::isStatic(val)) {
2719 staticMul *= val;
2720 }
2721 }
2722
2723 // Determine the length of the dynamic dimension.
2724 for (auto &val : newShapeValue) {
2725 if (ShapedType::isDynamic(val))
2726 val = numElements / staticMul;
2727 }
2728
2729 inferredReturnShapes.push_back(
2730 ShapedTypeComponents(newShapeValue, inputType));
2731 return success();
2732}
2733
2734llvm::LogicalResult tosa::ReshapeOp::verify() {
2735 TensorType outputType = getOutput().getType();
2736 if (verifySameElementTypes(*this, /* inType = */ getInput1().getType(),
2737 outputType)
2738 .failed()) {
2739 return failure();
2740 }
2741
2742 // The rank of the shape operand is encoded in its type (`!tosa.shape<N>`),
2743 // so it can be compared without inspecting the constant values.
2744 if (auto rankedOutputType = dyn_cast<RankedTensorType>(outputType)) {
2745 if (cast<tosa::shapeType>(getShape().getType()).getRank() !=
2746 rankedOutputType.getRank())
2747 return emitOpError() << "new shape does not match result rank";
2748 }
2749
2750 const TensorType inputType = getInput1().getType();
2751 if (inputType.hasStaticShape() && outputType.hasStaticShape()) {
2752 const int64_t inputElementsNum = inputType.getNumElements();
2753 const int64_t outputElementsNum = outputType.getNumElements();
2754 if (inputElementsNum != outputElementsNum)
2755 return emitOpError() << "cannot reshape " << inputElementsNum
2756 << " elements into " << outputElementsNum;
2757 }
2758
2759 return mlir::success();
2760}
2761
2762bool tosa::ReshapeBlockScaledOp::isCompatibleReturnTypes(TypeRange l,
2763 TypeRange r) {
2764 if (l.size() != r.size() || l.size() < 1 || l.size() > 2)
2765 return false;
2766 bool ok = (getElementTypeOrSelf(l[0]) == getElementTypeOrSelf(r[0]));
2767 if (l.size() == 2)
2768 ok = ok && (getElementTypeOrSelf(l[1]) == getElementTypeOrSelf(r[1]));
2769 return ok;
2770}
2771
2772LogicalResult tosa::ReshapeBlockScaledOp::inferReturnTypeComponents(
2773 MLIRContext *context, ::std::optional<Location> location,
2774 ReshapeBlockScaledOp::Adaptor adaptor,
2775 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2776
2777 const auto numInputs = adaptor.getInput().size();
2778 ShapeAdaptor inputShape(adaptor.getInput()[0].getType());
2779 Type inputType = getElementTypeOrSelf(adaptor.getInput()[0].getType());
2780 llvm::SmallVector<int64_t> newShapeValue;
2781 const auto newShape = adaptor.getNewValueShape();
2782 if (!tosa::getConstShapeValues(newShape.getDefiningOp(), newShapeValue)) {
2783 auto rank = cast<tosa::shapeType>(newShape.getType()).getRank();
2784 SmallVector<int64_t> fallback(rank, ShapedType::kDynamic);
2785 inferredReturnShapes.push_back(ShapedTypeComponents(fallback, inputType));
2786 if (numInputs == 2)
2787 inferredReturnShapes.push_back(ShapedTypeComponents(
2788 fallback, getElementTypeOrSelf(adaptor.getInput()[1].getType())));
2789 return success();
2790 }
2791
2792 const uint32_t blockSize =
2793 BlockSizeAttr::getBlockSizeValue(adaptor.getBlockSize());
2794
2795 llvm::SmallVector<int64_t> newScaleShapeValue;
2796 if (numInputs == 2) {
2797 newScaleShapeValue.assign(newShapeValue.begin(), newShapeValue.end());
2798 if (!newScaleShapeValue.empty() &&
2799 ShapedType::isStatic(newScaleShapeValue.back()))
2800 newScaleShapeValue.back() /= blockSize;
2801 }
2802
2803 inferredReturnShapes.push_back(
2804 ShapedTypeComponents(newShapeValue, inputType));
2805 if (numInputs == 2) {
2806 // Fix up scale shape - with special case for last dimension
2807 for (size_t idx = 0; idx < newShapeValue.size(); idx++) {
2808 if (ShapedType::isDynamic(newScaleShapeValue[idx])) {
2809 newScaleShapeValue[idx] = newShapeValue[idx];
2810 if (idx + 1 == newShapeValue.size())
2811 newScaleShapeValue[idx] /= blockSize;
2812 }
2813 }
2814
2815 inferredReturnShapes.push_back(ShapedTypeComponents(
2816 newScaleShapeValue,
2817 getElementTypeOrSelf(adaptor.getInput()[1].getType())));
2818 }
2819 return success();
2820}
2821
2822llvm::LogicalResult tosa::ReshapeBlockScaledOp::verify() {
2823 const Operation::operand_range inputList = getInput();
2824 const Operation::result_range outputList = getResults();
2825
2826 if (inputList.size() == 0)
2827 return emitOpError("requires at least one input");
2828
2829 if (inputList.size() > 2)
2830 return emitOpError("requires at most two inputs");
2831
2832 if (inputList.size() != outputList.size())
2833 return emitOpError("requires number of results to match inputs");
2834
2835 if (verifySameElementTypes(*this, /* inType = */ inputList[0].getType(),
2836 /* outType = */ outputList[0].getType())
2837 .failed()) {
2838 return failure();
2839 }
2840
2841 if (inputList.size() == 2 &&
2842 cast<tosa::shapeType>(getNewValueShape().getType()).getRank() == 0)
2843 return emitOpError("requires new shape to have a rank greater than 0");
2844
2845 const auto inputType = llvm::cast<ShapedType>(inputList[0].getType());
2846 if (!inputType.hasRank())
2847 return success();
2848 const uint32_t blockSize = BlockSizeAttr::getBlockSizeValue(getBlockSize());
2849
2850 if (inputList.size() == 2) {
2851 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_32))
2852 return emitOpError("expect block size to be 32, got ") << blockSize;
2853 if (llvm::any_of(inputList, [](Value v) {
2854 const auto input = cast<ShapedType>(v.getType());
2855 return input.hasRank() && input.getRank() == 0;
2856 }))
2857 return emitOpError(
2858 "requires all input shapes have a rank greater than 0");
2859 if (llvm::any_of(outputList, [](Value v) {
2860 const auto output = cast<ShapedType>(v.getType());
2861 return output.hasRank() && output.getRank() == 0;
2862 }))
2863 return emitOpError(
2864 "requires all result shapes have a rank greater than 0");
2865
2866 if (verifySameElementTypes(*this, /* inType = */ inputList[1].getType(),
2867 /* outType = */ outputList[1].getType())
2868 .failed()) {
2869 return failure();
2870 }
2871
2872 const auto inputScaleType = llvm::cast<ShapedType>(inputList[1].getType());
2873 if (inputScaleType.hasRank()) {
2874 if (inputType.getRank() != inputScaleType.getRank())
2875 return emitOpError("input shapes do not have same rank");
2876
2877 // Check all but the last dimension that the input shape dimensions match
2878 for (auto dimIdx = 0; dimIdx < inputType.getRank() - 1; dimIdx++) {
2879 const int64_t inputValueDim = inputType.getDimSize(dimIdx);
2880 const int64_t inputScaleDim = inputScaleType.getShape()[dimIdx];
2881 if (ShapedType::isStatic(inputValueDim) &&
2882 ShapedType::isStatic(inputScaleDim) &&
2883 inputValueDim != inputScaleDim)
2884 return emitOpError("input shapes for data and scale do not match on "
2885 "dimension ")
2886 << dimIdx;
2887 }
2888
2889 // Verify last dimension of input is a multiple of block size
2890 const int64_t lastValueDim =
2891 inputType.getDimSize(inputType.getRank() - 1);
2892 if (ShapedType::isStatic(lastValueDim)) {
2893 if (lastValueDim % blockSize != 0)
2894 return emitOpError("expect last dimension of input_data (")
2895 << lastValueDim << ") to be divisible by block_size ("
2896 << blockSize << ")";
2897
2898 const int64_t lastScaleDim =
2899 inputScaleType.getDimSize(inputScaleType.getRank() - 1);
2900 // Verify last dimension of scale is lastValueDim / block size
2901 if (ShapedType::isStatic(lastScaleDim) &&
2902 lastScaleDim != lastValueDim / blockSize)
2903 return emitOpError("expect last dimension of scale_data (")
2904 << lastScaleDim << ") to be " << lastValueDim << "/"
2905 << blockSize;
2906 }
2907 }
2908 } else {
2909 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_1))
2910 return emitOpError("expect block size to be 1, got ") << blockSize;
2911 }
2912
2913 // Get the new value shape dimension values.
2914 SmallVector<int64_t> shapeValues;
2915 if (!tosa::getConstShapeValues(getNewValueShape().getDefiningOp(),
2916 shapeValues)) {
2917 // skip following checks if shape is not constant
2918 return mlir::success();
2919 }
2920
2921 if (inputList.size() == 2) {
2922 const int64_t lastShapeDim = shapeValues.back();
2923 if (ShapedType::isStatic(lastShapeDim) && lastShapeDim % blockSize != 0)
2924 return emitOpError("expect last dimension of new shape (")
2925 << lastShapeDim << ") to be divisible by block_size (" << blockSize
2926 << ")";
2927 }
2928
2929 const auto outputType = llvm::cast<ShapedType>(outputList[0].getType());
2930 if (!outputType.hasRank())
2931 return success();
2932
2933 if (static_cast<int64_t>(shapeValues.size()) != outputType.getRank())
2934 return emitOpError() << "result does not match new shape rank";
2935
2936 for (auto [newShapeDim, outputShapeDim] :
2937 zip(shapeValues, outputType.getShape())) {
2938 if (ShapedType::isStatic(newShapeDim) &&
2939 ShapedType::isStatic(outputShapeDim) && newShapeDim != outputShapeDim)
2940 return emitOpError() << "result shape is inconsistent with new shape";
2941 }
2942
2943 if (outputList.size() == 2) {
2944 // Set up scale shape from new shape given
2945 SmallVector<int64_t> scaleShapeValues(shapeValues.begin(),
2946 shapeValues.end());
2947 scaleShapeValues.back() /= blockSize;
2948
2949 const auto outputScaleType =
2950 llvm::cast<ShapedType>(outputList[1].getType());
2951 if (outputScaleType.hasRank()) {
2952 if ((int64_t)scaleShapeValues.size() != outputScaleType.getRank())
2953 return emitOpError() << "result scale does not match new shape rank";
2954
2955 for (auto [newScaleShapeDim, outputScaleShapeDim] :
2956 zip(scaleShapeValues, outputScaleType.getShape())) {
2957 if (ShapedType::isStatic(newScaleShapeDim) &&
2958 ShapedType::isStatic(outputScaleShapeDim) &&
2959 newScaleShapeDim != outputScaleShapeDim)
2960 return emitOpError()
2961 << "result scale shape is inconsistent with new shape";
2962 }
2963 }
2964 }
2965
2966 if (inputType.hasStaticShape()) {
2967 int64_t inputElementsNum = inputType.getNumElements();
2968 if (outputType.hasStaticShape()) {
2969 int64_t outputElementsNum = outputType.getNumElements();
2970 if (inputElementsNum != outputElementsNum) {
2971 return emitOpError() << "cannot reshape " << inputElementsNum
2972 << " elements into " << outputElementsNum;
2973 }
2974 }
2975
2976 int64_t newShapeElementsNum =
2977 llvm::accumulate(shapeValues, int64_t(1), [](int64_t acc, int64_t dim) {
2978 return (dim > 0) ? acc * dim : acc;
2979 });
2980 bool isStaticNewShape =
2981 llvm::all_of(shapeValues, [](int64_t s) { return s > 0; });
2982 if ((isStaticNewShape && inputElementsNum != newShapeElementsNum) ||
2983 (!isStaticNewShape && newShapeElementsNum > inputElementsNum)) {
2984 return emitOpError() << "cannot reshape " << inputElementsNum
2985 << " elements into " << newShapeElementsNum;
2986 }
2987 }
2988
2989 return mlir::success();
2990}
2991
2992// return failure if val is not a constant
2993// set zp to -1 if val is non-zero float or val is not integer nor float
2994// otherwise set zp to val's constant value
2995static FailureOr<int64_t> getZeroPoint(Value val, bool signExtend) {
2996 ElementsAttr zpAttr;
2997 if (!matchPattern(val, m_Constant(&zpAttr))) {
2998 return failure();
2999 }
3000
3001 Type zpElemType = zpAttr.getElementType();
3002
3003 if (llvm::isa<FloatType>(zpElemType)) {
3004 if (zpAttr.getValues<APFloat>()[0].isZero()) {
3005 return 0;
3006 }
3007 // return non-zero value to trigger error check
3008 return -1;
3009 }
3010
3011 if (llvm::isa<IntegerType>(zpElemType)) {
3012 if (signExtend)
3013 return zpAttr.getValues<APInt>()[0].getSExtValue();
3014 return zpAttr.getValues<APInt>()[0].getZExtValue();
3015 }
3016
3017 // return non-zero value to trigger error check
3018 return -1;
3019}
3020
3021template <typename T>
3022static LogicalResult verifyZeroPoint(T op, Value val, const int64_t &zp,
3023 const std::string &operand) {
3024 Type zpElemType = getElementTypeOrSelf(val);
3025
3026 if (!zpElemType.isInteger(8) && zp != 0) {
3027 // convert operand to lower case for error message
3028 std::string lower = operand;
3029 llvm::transform(lower, lower.begin(), ::tolower);
3030 return op.emitOpError()
3031 << lower << " zero point must be zero for non-int8 integer types";
3032 }
3033
3034 return success();
3035}
3036
3037static LogicalResult verifyZeroPoint(tosa::RescaleOp op, Value zpVal,
3038 const int64_t &zp,
3039 const std::string &operand) {
3040 bool isInputZp = (operand == "Input");
3041
3042 bool tensorUnsigned =
3043 isInputZp ? op.getInputUnsigned() : op.getOutputUnsigned();
3044 StringRef tensorName = isInputZp ? "input" : "output";
3045
3046 Type zpElemType = getElementTypeOrSelf(zpVal);
3047
3048 if (zp != 0) {
3049 if (!zpElemType.isInteger(8) &&
3050 !(zpElemType.isInteger(16) && tensorUnsigned)) {
3051 return op.emitOpError()
3052 << "expect " << tensorName << "_zp of 0, got " << zp;
3053 }
3054 if (zpElemType.isInteger(16) && tensorUnsigned && zp != 32768) {
3055 return op.emitOpError() << "expect " << tensorName
3056 << "_zp of 0 or 32768 for unsigned int16 "
3057 << tensorName << ", got " << zp;
3058 }
3059 }
3060
3061 return success();
3062}
3063
3064#define ZERO_POINT_HELPER(OP, OPERAND_NAME, SIGN_EXTEND) \
3065 FailureOr<int64_t> tosa::OP::get##OPERAND_NAME##ZeroPoint() { \
3066 return getZeroPoint(get##OPERAND_NAME##Zp(), SIGN_EXTEND); \
3067 } \
3068 LogicalResult tosa::OP::verify##OPERAND_NAME##ZeroPoint(int64_t zp) { \
3069 return verifyZeroPoint(*this, get##OPERAND_NAME##Zp(), zp, #OPERAND_NAME); \
3070 }
3071
3072ZERO_POINT_HELPER(Conv2DOp, Input, true)
3073ZERO_POINT_HELPER(Conv2DOp, Weight, true)
3074ZERO_POINT_HELPER(Conv3DOp, Input, true)
3075ZERO_POINT_HELPER(Conv3DOp, Weight, true)
3076ZERO_POINT_HELPER(DepthwiseConv2DOp, Input, true)
3077ZERO_POINT_HELPER(DepthwiseConv2DOp, Weight, true)
3078ZERO_POINT_HELPER(TransposeConv2DOp, Input, true)
3079ZERO_POINT_HELPER(TransposeConv2DOp, Weight, true)
3080ZERO_POINT_HELPER(AvgPool2dOp, Input, true)
3081ZERO_POINT_HELPER(AvgPool2dOp, Output, true)
3082ZERO_POINT_HELPER(AvgPool2dAdaptiveOp, Input, true)
3083ZERO_POINT_HELPER(AvgPool2dAdaptiveOp, Output, true)
3084ZERO_POINT_HELPER(MatMulOp, A, true)
3085ZERO_POINT_HELPER(MatMulOp, B, true)
3086ZERO_POINT_HELPER(MatMulTOp, A, true)
3087ZERO_POINT_HELPER(MatMulTOp, B, true)
3088ZERO_POINT_HELPER(NegateOp, Input1, true)
3089ZERO_POINT_HELPER(NegateOp, Output, true)
3090ZERO_POINT_HELPER(RescaleOp, Input, !getInputUnsigned())
3091ZERO_POINT_HELPER(RescaleOp, Output, !getOutputUnsigned())
3092#undef ZERO_POINT_HELPER
3093
3094LogicalResult tosa::TransposeOp::inferReturnTypeComponents(
3095 MLIRContext *context, ::std::optional<Location> location,
3096 TransposeOp::Adaptor adaptor,
3097 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3098 ShapeAdaptor inputShape(adaptor.getInput1().getType());
3099
3100 // If input rank and permutation length is unknown, the output rank is
3101 // unknown.
3102 if (!inputShape.hasRank()) {
3103 inferredReturnShapes.push_back(ShapedTypeComponents());
3104 return success();
3105 }
3106
3107 const auto inputRank = inputShape.getRank();
3108
3109 // This would imply the number of permutations does not match the rank of
3110 // the input which is illegal.
3111 if (adaptor.getPerms().size() != static_cast<size_t>(inputRank)) {
3112 return failure();
3113 }
3114
3115 SmallVector<int64_t> outputShape;
3116 // Rank-0 means no permutations matter.
3117 if (inputRank == 0) {
3118 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3119 return success();
3120 }
3121
3122 // Check whether the input dimensions are all the same.
3123 bool allTheSame = true;
3124 for (int i = 1, s = inputRank; i < s; i++) {
3125 if (inputShape.getDimSize(0) != inputShape.getDimSize(i)) {
3126 allTheSame = false;
3127 break;
3128 }
3129 }
3130
3131 // If all of the input dimensions are the same we don't care about the
3132 // permutation.
3133 if (allTheSame) {
3134 outputShape.resize(inputRank, inputShape.getDimSize(0));
3135 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3136 return success();
3137 }
3138
3139 outputShape.resize(inputRank, ShapedType::kDynamic);
3140
3141 // Constant permutation values must be within the input rank.
3142 if (llvm::any_of(adaptor.getPerms(),
3143 [inputRank](const auto i) { return i >= inputRank; }))
3144 return failure();
3145
3146 outputShape.reserve(inputRank);
3147 for (int i = 0, s = inputRank; i < s; i++) {
3148 outputShape[i] = inputShape.getDimSize(adaptor.getPerms()[i]);
3149 }
3150
3151 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3152 return success();
3153}
3154
3155LogicalResult tosa::TransposeOp::verify() {
3156 if (verifySameElementTypes(*this, /* inType = */ getInput1().getType(),
3157 /* outType = */ getOutput().getType())
3158 .failed()) {
3159 return failure();
3160 }
3161
3162 const ShapeAdaptor inputShape(getInput1().getType());
3163 const ShapeAdaptor outputShape(getOutput().getType());
3164
3165 const llvm::ArrayRef<int32_t> constantPerms = getPerms();
3166
3167 if (inputShape.hasRank() &&
3168 constantPerms.size() != static_cast<size_t>(inputShape.getRank()))
3169 return emitOpError() << "expected perms attribute to have size "
3170 << inputShape.getRank()
3171 << " (input rank) but got size "
3172 << constantPerms.size();
3173
3174 if (inputShape.hasRank() && outputShape.hasRank() &&
3175 inputShape.getRank() != outputShape.getRank())
3176 return emitOpError()
3177 << "expected input tensor rank to equal result tensor rank";
3178
3179 if (outputShape.hasRank() &&
3180 constantPerms.size() != static_cast<size_t>(outputShape.getRank()))
3181 return emitOpError() << "expected perms attribute to have size "
3182 << outputShape.getRank()
3183 << " (output rank) but got size "
3184 << constantPerms.size();
3185
3186 if (!llvm::all_of(constantPerms,
3187 [&constantPerms](int32_t s) {
3188 return s >= 0 &&
3189 static_cast<size_t>(s) < constantPerms.size();
3190 }) ||
3191 !isPermutationVector(llvm::map_to_vector(
3192 constantPerms, [](int32_t v) -> int64_t { return v; })))
3193 return emitOpError() << "expected valid permutation indices";
3194
3195 if (isa<BlockScaledType>(getInput1().getType().getElementType()) &&
3196 constantPerms.back() != static_cast<int32_t>(constantPerms.size()) - 1) {
3197 return emitOpError() << "expected no-op permutation on innermost dimension "
3198 "for block scaled input";
3199 }
3200
3201 // ERROR_IF(tensor_size(shape1) != tensor_size(shape))
3202 if (inputShape.hasStaticShape() && outputShape.hasStaticShape() &&
3203 inputShape.getNumElements() != outputShape.getNumElements())
3204 return emitOpError() << "expected input1 and output to have same numbers "
3205 "of elements, got "
3206 << inputShape.getNumElements() << " and "
3207 << outputShape.getNumElements();
3208
3209 // Verify that the types of the input and output tensors are properly
3210 // permuted.
3211 if (inputShape.hasRank() && outputShape.hasRank()) {
3212 for (auto i = 0; i < outputShape.getRank(); i++) {
3213 if (inputShape.isDynamicDim(constantPerms[i]) ||
3214 outputShape.isDynamicDim(i))
3215 continue;
3216
3217 if (inputShape.getDimSize(constantPerms[i]) != outputShape.getDimSize(i))
3218 return emitOpError()
3219 << "expected output tensor dim " << i << " to match "
3220 << "input dim " << constantPerms[i] << " with value of "
3221 << inputShape.getDimSize(constantPerms[i]);
3222 }
3223 }
3224
3225 return success();
3226}
3227
3228LogicalResult TransposeOp::reifyResultShapes(
3229 OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) {
3230
3231 const llvm::ArrayRef<int32_t> transposePerms = getPerms();
3232
3233 Value input = getInput1();
3234 auto inputType = cast<TensorType>(input.getType());
3235
3236 SmallVector<OpFoldResult> returnedDims(inputType.getRank());
3237 for (auto dim : transposePerms) {
3238 int32_t dimInInput = transposePerms[dim];
3239 if (inputType.isDynamicDim(dimInInput))
3240 returnedDims[dim] =
3241 tensor::DimOp::create(builder, getLoc(), input, dimInInput)
3242 .getResult();
3243 else
3244 returnedDims[dim] =
3245 builder.getIndexAttr(inputType.getDimSize(dimInInput));
3246 }
3247
3248 reifiedReturnShapes.emplace_back(std::move(returnedDims));
3249 return success();
3250}
3251
3252LogicalResult tosa::GatherOp::inferReturnTypeComponents(
3253 MLIRContext *context, ::std::optional<Location> location,
3254 GatherOp::Adaptor adaptor,
3255 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3256 llvm::SmallVector<int64_t> outputShape;
3257 outputShape.resize(3, ShapedType::kDynamic);
3258
3259 ShapeAdaptor valuesShape(adaptor.getValues().getType());
3260 if (valuesShape.hasRank()) {
3261 outputShape[0] = valuesShape.getDimSize(0);
3262 outputShape[2] = valuesShape.getDimSize(2);
3263 }
3264
3265 ShapeAdaptor indicesShape(adaptor.getIndices().getType());
3266 if (indicesShape.hasRank()) {
3267 if (outputShape[0] == ShapedType::kDynamic)
3268 outputShape[0] = indicesShape.getDimSize(0);
3269 if (outputShape[1] == ShapedType::kDynamic)
3270 outputShape[1] = indicesShape.getDimSize(1);
3271 }
3272
3273 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3274 return success();
3275}
3276
3277LogicalResult tosa::RowGatherOp::inferReturnTypeComponents(
3278 MLIRContext *context, ::std::optional<Location> location,
3279 RowGatherOp::Adaptor adaptor,
3280 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3281 llvm::SmallVector<int64_t> outputShape;
3282 outputShape.resize(3, ShapedType::kDynamic);
3283
3284 const ShapeAdaptor valuesShape(adaptor.getValues().getType());
3285 if (valuesShape.hasRank()) {
3286 outputShape[0] = valuesShape.getDimSize(0);
3287 outputShape[2] = valuesShape.getDimSize(2);
3288 }
3289
3290 const ShapeAdaptor indicesShape(adaptor.getIndices().getType());
3291 if (indicesShape.hasRank()) {
3292 if (outputShape[0] == ShapedType::kDynamic)
3293 outputShape[0] = indicesShape.getDimSize(0);
3294
3295 const FailureOr<int32_t> maybeRowCount =
3296 getConstantScalarIntValue<int32_t>(adaptor.getRowCount());
3297 if (succeeded(maybeRowCount)) {
3298 const int64_t indicesW = indicesShape.getDimSize(1);
3299 if (ShapedType::isStatic(indicesW))
3300 outputShape[1] = indicesW * maybeRowCount.value();
3301 }
3302 }
3303
3304 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3305 return success();
3306}
3307
3308LogicalResult tosa::RowGatherBlockScaledOp::inferReturnTypeComponents(
3309 MLIRContext *context, ::std::optional<Location> location,
3310 RowGatherBlockScaledOp::Adaptor adaptor,
3311 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3312 const auto values = adaptor.getValues();
3313 if (values.empty())
3314 return failure();
3315
3316 SmallVector<int64_t> dataShape(3, ShapedType::kDynamic);
3317 const ShapeAdaptor valuesShape(values.front().getType());
3318 if (valuesShape.hasRank()) {
3319 dataShape[0] = valuesShape.getDimSize(0);
3320 dataShape[2] = valuesShape.getDimSize(2);
3321 }
3322
3323 const ShapeAdaptor indicesShape(adaptor.getIndices().getType());
3324 if (indicesShape.hasRank()) {
3325 if (dataShape[0] == ShapedType::kDynamic)
3326 dataShape[0] = indicesShape.getDimSize(0);
3327
3328 if (auto rowCount =
3329 getConstantScalarIntValue<int32_t>(adaptor.getRowCount());
3330 succeeded(rowCount) && rowCount.value() > 0) {
3331 const int64_t indicesW = indicesShape.getDimSize(1);
3332 if (ShapedType::isStatic(indicesW))
3333 dataShape[1] = indicesW * rowCount.value();
3334 }
3335 }
3336
3337 inferredReturnShapes.push_back(ShapedTypeComponents(dataShape));
3338 if (values.size() == 1)
3339 return success();
3340
3341 SmallVector<int64_t> scaleShape = dataShape;
3342 const uint32_t blockSize =
3343 BlockSizeAttr::getBlockSizeValue(adaptor.getBlockSize());
3344 if (ShapedType::isStatic(dataShape[2]))
3345 scaleShape[2] = dataShape[2] / blockSize;
3346
3347 inferredReturnShapes.push_back(ShapedTypeComponents(scaleShape));
3348 return success();
3349}
3350
3351LogicalResult tosa::GatherOp::verify() {
3352 if (verifySameElementTypes(*this, /* inType = */ getValues().getType(),
3353 /* outType = */ getOutput().getType())
3354 .failed()) {
3355 return failure();
3356 }
3357
3358 const ShapeAdaptor valuesShape(getValues().getType());
3359 const ShapeAdaptor indicesShape(getIndices().getType());
3360 const ShapeAdaptor outputShape(getOutput().getType());
3361
3362 int64_t n = ShapedType::kDynamic;
3363 int64_t w = ShapedType::kDynamic;
3364 int64_t c = ShapedType::kDynamic;
3365
3366 if (valuesShape.hasRank()) {
3367 n = valuesShape.getDimSize(0);
3368 c = valuesShape.getDimSize(2);
3369 }
3370 if (indicesShape.hasRank()) {
3371 const int64_t indicesN = indicesShape.getDimSize(0);
3372 w = indicesShape.getDimSize(1);
3373 if (n == ShapedType::kDynamic)
3374 n = indicesN;
3375 else if (indicesN != ShapedType::kDynamic && n != indicesN)
3376 return emitOpError() << "requires indices dimension 0 to have size " << n
3377 << ", got " << indicesN;
3378 }
3379 if (outputShape.hasRank()) {
3380 const int64_t outputN = outputShape.getDimSize(0);
3381 const int64_t outputW = outputShape.getDimSize(1);
3382 const int64_t outputC = outputShape.getDimSize(2);
3383 if (n != ShapedType::kDynamic && outputN != ShapedType::kDynamic &&
3384 n != outputN)
3385 return emitOpError() << "requires output dimension 0 to have size " << n
3386 << ", got " << outputN;
3387
3388 if (w != ShapedType::kDynamic && outputW != ShapedType::kDynamic &&
3389 w != outputW)
3390 return emitOpError() << "requires output dimension 1 to have size " << w
3391 << ", got " << outputW;
3392 if (c != ShapedType::kDynamic && outputC != ShapedType::kDynamic &&
3393 c != outputC)
3394 return emitOpError() << "requires output dimension 2 to have size " << c
3395 << ", got " << outputC;
3396 }
3397 return success();
3398}
3399
3400LogicalResult tosa::RowGatherOp::verify() {
3401 if (failed(verifySameElementTypes(*this, /* inType = */ getValues().getType(),
3402 /* outType = */ getOutput().getType())))
3403 return failure();
3404
3405 const FailureOr<int32_t> maybeRowCount =
3407 if (succeeded(maybeRowCount) && maybeRowCount.value() <= 0)
3408 return emitOpError() << "requires row_count to be > 0, got "
3409 << maybeRowCount.value();
3410
3411 int64_t n = ShapedType::kDynamic;
3412 int64_t c = ShapedType::kDynamic;
3413 int64_t w = ShapedType::kDynamic;
3414
3415 const ShapeAdaptor valuesShape(getValues().getType());
3416 if (valuesShape.hasRank()) {
3417 n = valuesShape.getDimSize(0);
3418 c = valuesShape.getDimSize(2);
3419 }
3420
3421 const ShapeAdaptor indicesShape(getIndices().getType());
3422 if (indicesShape.hasRank()) {
3423 if (failed(tryUpdateDimOrFailure(*this, n, indicesShape.getDimSize(0),
3424 "indices", "batch")))
3425 return failure();
3426 w = indicesShape.getDimSize(1);
3427 }
3428
3429 const ShapeAdaptor outputShape(getOutput().getType());
3430 if (outputShape.hasRank()) {
3431 if (failed(tryUpdateDimOrFailure(*this, n, outputShape.getDimSize(0),
3432 "output", "batch")) ||
3433 failed(tryUpdateDimOrFailure(*this, c, outputShape.getDimSize(2),
3434 "output", "channels")))
3435 return failure();
3436
3437 if (succeeded(maybeRowCount) && maybeRowCount.value() > 0 &&
3438 ShapedType::isStatic(w)) {
3439 const int64_t expectedOutputRows = w * maybeRowCount.value();
3440 if (ShapedType::isStatic(outputShape.getDimSize(1)) &&
3441 outputShape.getDimSize(1) != expectedOutputRows)
3442 return emitOpError()
3443 << "requires output dimension to be equal to "
3444 "indices[1]*row_count ("
3445 << expectedOutputRows << "), got " << outputShape.getDimSize(1);
3446 }
3447 }
3448
3449 return success();
3450}
3451
3452LogicalResult tosa::RowGatherBlockScaledOp::verify() {
3453 const OperandRange values = getValues();
3454 const ResultRange output = getOutput();
3455 if (values.empty() || values.size() > 2)
3456 return emitOpError()
3457 << "expects values tensor list length to be 1 or 2, got "
3458 << values.size();
3459 if (output.size() != values.size())
3460 return emitOpError()
3461 << "expects output tensor list length to match values tensor list "
3462 "length, got "
3463 << output.size() << " results for " << values.size()
3464 << " input tensors";
3465
3466 const uint32_t blockSize = BlockSizeAttr::getBlockSizeValue(getBlockSize());
3467 if (values.size() == 1 && blockSize != 1)
3468 return emitOpError()
3469 << "requires block_size to be BLOCK_SIZE_1 when values tensor list "
3470 "length is 1";
3471 if (values.size() == 2 && blockSize == 1)
3472 return emitOpError()
3473 << "requires block_size to not be BLOCK_SIZE_1 when values tensor "
3474 "list length is 2";
3475
3476 if (failed(verifySameElementTypes(*this, values[0].getType(),
3477 output[0].getType(), "values[0]",
3478 "output[0]")))
3479 return failure();
3480 if (values.size() == 2 && failed(verifySameElementTypes(
3481 *this, values[1].getType(), output[1].getType(),
3482 "values[1]", "output[1]")))
3483 return failure();
3484
3485 if (auto rowCount = getConstantScalarIntValue<int32_t>(getRowCount());
3486 succeeded(rowCount) && rowCount.value() <= 0)
3487 return emitOpError() << "requires row_count to be > 0, got "
3488 << rowCount.value();
3489
3490 int64_t n = ShapedType::kDynamic;
3491 int64_t k = ShapedType::kDynamic;
3492 int64_t c = ShapedType::kDynamic;
3493 int64_t w = ShapedType::kDynamic;
3494 int64_t multiplesOfC = ShapedType::kDynamic;
3495
3496 const ShapeAdaptor valuesDataShape(values[0].getType());
3497 if (valuesDataShape.hasRank()) {
3498 n = valuesDataShape.getDimSize(0);
3499 k = valuesDataShape.getDimSize(1);
3500 c = valuesDataShape.getDimSize(2);
3501 }
3502
3503 if (ShapedType::isStatic(c) && c % blockSize != 0)
3504 return emitOpError() << "expects channels of values[0] (" << c
3505 << ") to be divisible by block_size (" << blockSize
3506 << ")";
3507
3508 const ShapeAdaptor indicesShape(getIndices().getType());
3509 if (indicesShape.hasRank()) {
3510 if (failed(tryUpdateDimOrFailure(*this, n, indicesShape.getDimSize(0),
3511 "indices", "batch")))
3512 return failure();
3513 w = indicesShape.getDimSize(1);
3514 }
3515
3516 const ShapeAdaptor outputDataShape(output[0].getType());
3517 if (outputDataShape.hasRank()) {
3518 if (failed(tryUpdateDimOrFailure(*this, n, outputDataShape.getDimSize(0),
3519 "output[0]", "batch")) ||
3520 failed(tryUpdateDimOrFailure(*this, c, outputDataShape.getDimSize(2),
3521 "output[0]", "channels")))
3522 return failure();
3523
3524 if (auto rowCount = getConstantScalarIntValue<int32_t>(getRowCount());
3525 succeeded(rowCount) && rowCount.value() > 0 &&
3526 ShapedType::isStatic(w)) {
3527 const int64_t expectedOutputRows = w * rowCount.value();
3528 if (ShapedType::isStatic(outputDataShape.getDimSize(1)) &&
3529 outputDataShape.getDimSize(1) != expectedOutputRows)
3530 return emitOpError() << "requires output[0] dimension 1 to have size "
3531 << expectedOutputRows << ", got "
3532 << outputDataShape.getDimSize(1);
3533 }
3534 }
3535
3536 if (values.size() == 2) {
3537 const ShapeAdaptor valuesScaleShape(values[1].getType());
3538 if (valuesScaleShape.hasRank()) {
3539 if (failed(tryUpdateDimOrFailure(*this, n, valuesScaleShape.getDimSize(0),
3540 "values[1]", "batch")) ||
3541 failed(tryUpdateDimOrFailure(*this, k, valuesScaleShape.getDimSize(1),
3542 "values[1]", "rows")))
3543 return failure();
3544 multiplesOfC = valuesScaleShape.getDimSize(2);
3545 }
3546
3547 const ShapeAdaptor outputScaleShape(output[1].getType());
3548 if (outputScaleShape.hasRank()) {
3549 if (failed(tryUpdateDimOrFailure(*this, n, outputScaleShape.getDimSize(0),
3550 "output[1]", "batch")))
3551 return failure();
3552
3553 if (auto rowCount = getConstantScalarIntValue<int32_t>(getRowCount());
3554 succeeded(rowCount) && rowCount.value() > 0 &&
3555 ShapedType::isStatic(w)) {
3556 const int64_t expectedOutputRows = w * rowCount.value();
3557 if (ShapedType::isStatic(outputScaleShape.getDimSize(1)) &&
3558 outputScaleShape.getDimSize(1) != expectedOutputRows)
3559 return emitOpError() << "requires output[1] dimension 1 to have size "
3560 << expectedOutputRows << ", got "
3561 << outputScaleShape.getDimSize(1);
3562 }
3563
3564 if (ShapedType::isDynamic(multiplesOfC))
3565 multiplesOfC = outputScaleShape.getDimSize(2);
3566 else if (ShapedType::isStatic(outputScaleShape.getDimSize(2)) &&
3567 multiplesOfC != outputScaleShape.getDimSize(2))
3568 return emitOpError()
3569 << "expected channels of output[1] to match size "
3570 << multiplesOfC << ", got " << outputScaleShape.getDimSize(2);
3571 }
3572
3573 if (ShapedType::isStatic(c) && ShapedType::isStatic(multiplesOfC) &&
3574 multiplesOfC != c / blockSize)
3575 return emitOpError()
3576 << "expects channels of scale tensors to equal C/block_size (" << c
3577 << "/" << blockSize << "), got " << multiplesOfC;
3578 }
3579
3580 return success();
3581}
3582
3583LogicalResult tosa::ResizeOp::inferReturnTypeComponents(
3584 MLIRContext *context, ::std::optional<Location> location,
3585 ResizeOp::Adaptor adaptor,
3586 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3587 llvm::SmallVector<int64_t, 4> outputShape;
3588 outputShape.resize(4, ShapedType::kDynamic);
3589
3590 ShapeAdaptor inputShape(adaptor.getInput().getType());
3591 if (!inputShape.hasRank())
3592 return failure();
3593
3594 outputShape[0] = inputShape.getDimSize(0);
3595 outputShape[3] = inputShape.getDimSize(3);
3596 int64_t inputHeight = inputShape.getDimSize(1);
3597 int64_t inputWidth = inputShape.getDimSize(2);
3598
3599 if ((inputHeight == ShapedType::kDynamic) ||
3600 (inputWidth == ShapedType::kDynamic))
3601 return failure();
3602
3603 SmallVector<int64_t> scaleInt, offsetInt, borderInt;
3604 if (!tosa::getConstShapeValues(adaptor.getScale().getDefiningOp(),
3605 scaleInt) ||
3606 !tosa::getConstShapeValues(adaptor.getOffset().getDefiningOp(),
3607 offsetInt) ||
3608 !tosa::getConstShapeValues(adaptor.getBorder().getDefiningOp(),
3609 borderInt)) {
3610 return failure();
3611 }
3612
3613 // Non-positive scale values are invalid, so the output shape cannot be
3614 // inferred here. They are reported by the ERROR_IF check in tosa-validate.
3615 if (llvm::any_of(scaleInt, [](int64_t s) { return s <= 0; }))
3616 return failure();
3617
3618 // Compute the output shape based on attributes: scale, offset, and border.
3619 const int64_t outputHeight =
3620 (((inputHeight - 1) * scaleInt[0] - offsetInt[0] + borderInt[0]) /
3621 scaleInt[1]) +
3622 1;
3623
3624 const int64_t outputWidth =
3625 (((inputWidth - 1) * scaleInt[2] - offsetInt[1] + borderInt[1]) /
3626 scaleInt[3]) +
3627 1;
3628
3629 if (outputHeight < 0 || outputWidth < 0) {
3630 return emitOptionalError(
3631 location,
3632 "calculated output height and width must be non-negative, "
3633 "got height = ",
3634 outputHeight, ", width = ", outputWidth);
3635 }
3636
3637 outputShape[1] = outputHeight;
3638 outputShape[2] = outputWidth;
3639 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3640 return success();
3641}
3642
3643LogicalResult tosa::ResizeOp::verify() {
3644 const Type inputElementType = getElementTypeOrSelf(getInput().getType());
3645
3646 if (isa<BlockScaledType>(inputElementType) &&
3647 getMode() != ResizeMode::NEAREST_NEIGHBOR)
3648 return emitOpError("requires NEAREST_NEIGHBOR mode for block scaled input");
3649
3650 return success();
3651}
3652
3653LogicalResult tosa::ScatterOp::inferReturnTypeComponents(
3654 MLIRContext *context, ::std::optional<Location> location,
3655 ScatterOp::Adaptor adaptor,
3656 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3657 llvm::SmallVector<int64_t> outputShape;
3658 outputShape.resize(3, ShapedType::kDynamic);
3659
3660 ShapeAdaptor valuesInShape(adaptor.getValuesIn().getType());
3661 if (valuesInShape.hasRank()) {
3662 outputShape[0] = valuesInShape.getDimSize(0);
3663 outputShape[1] = valuesInShape.getDimSize(1);
3664 outputShape[2] = valuesInShape.getDimSize(2);
3665 }
3666
3667 ShapeAdaptor indicesShape(adaptor.getIndices().getType());
3668 if (indicesShape.hasRank()) {
3669 if (outputShape[0] == ShapedType::kDynamic)
3670 outputShape[0] = indicesShape.getDimSize(0);
3671 }
3672
3673 ShapeAdaptor inputShape(adaptor.getInput().getType());
3674 if (inputShape.hasRank()) {
3675 if (outputShape[0] == ShapedType::kDynamic)
3676 outputShape[0] = inputShape.getDimSize(0);
3677 if (outputShape[2] == ShapedType::kDynamic)
3678 outputShape[2] = inputShape.getDimSize(2);
3679 }
3680
3681 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3682 return success();
3683}
3684
3685LogicalResult tosa::ScatterOp::verify() {
3686 if (verifySameElementTypes(*this, /* inType = */ getValuesIn().getType(),
3687 /* outType = */ getValuesOut().getType())
3688 .failed() ||
3689 verifySameElementTypes(*this, /* inType = */ getInput().getType(),
3690 /* outType = */ getValuesOut().getType())
3691 .failed()) {
3692 return failure();
3693 }
3694
3695 const ShapeAdaptor valuesInShape(getValuesIn().getType());
3696 const ShapeAdaptor indicesShape(getIndices().getType());
3697 const ShapeAdaptor inputShape(getInput().getType());
3698 const ShapeAdaptor outputShape(getValuesOut().getType());
3699
3700 int64_t n = ShapedType::kDynamic;
3701 int64_t k = ShapedType::kDynamic;
3702 int64_t w = ShapedType::kDynamic;
3703 int64_t c = ShapedType::kDynamic;
3704 if (valuesInShape.hasRank()) {
3705 n = valuesInShape.getDimSize(0);
3706 k = valuesInShape.getDimSize(1);
3707 c = valuesInShape.getDimSize(2);
3708 }
3709 if (indicesShape.hasRank()) {
3710 const int64_t indicesN = indicesShape.getDimSize(0);
3711 w = indicesShape.getDimSize(1);
3712 if (n == ShapedType::kDynamic)
3713 n = indicesN;
3714 else if (indicesN != ShapedType::kDynamic && n != indicesN)
3715 return emitOpError() << "requires indices dimension 0 to have size " << n
3716 << ", got " << indicesN;
3717 }
3718 if (inputShape.hasRank()) {
3719 const int64_t inputN = inputShape.getDimSize(0);
3720 const int64_t inputW = inputShape.getDimSize(1);
3721 const int64_t inputC = inputShape.getDimSize(2);
3722 if (n == ShapedType::kDynamic)
3723 n = inputN;
3724 else if (inputN != ShapedType::kDynamic && n != inputN)
3725 return emitOpError() << "requires input dimension 0 to have size " << n
3726 << ", got " << inputN;
3727 if (w == ShapedType::kDynamic)
3728 w = inputW;
3729 else if (inputW != ShapedType::kDynamic && w != inputW)
3730 return emitOpError() << "requires input dimension 1 to have size " << w
3731 << ", got " << inputW;
3732
3733 if (c == ShapedType::kDynamic)
3734 c = inputC;
3735 else if (inputC != ShapedType::kDynamic && c != inputC)
3736 return emitOpError() << "requires input dimension 2 to have size " << c
3737 << ", got " << inputC;
3738 }
3739 if (outputShape.hasRank()) {
3740 const int64_t outputN = outputShape.getDimSize(0);
3741 const int64_t outputK = outputShape.getDimSize(1);
3742 const int64_t outputC = outputShape.getDimSize(2);
3743 if (n != ShapedType::kDynamic && outputN != ShapedType::kDynamic &&
3744 n != outputN)
3745 return emitOpError() << "requires values_out dimension 0 to have size "
3746 << n << ", got " << outputN;
3747 if (k == ShapedType::kDynamic)
3748 k = outputK;
3749 else if (outputK != ShapedType::kDynamic && k != outputK)
3750 return emitOpError() << "requires values_out dimension 1 to have size "
3751 << k << ", got " << outputK;
3752 if (c != ShapedType::kDynamic && outputC != ShapedType::kDynamic &&
3753 c != outputC)
3754 return emitOpError() << "requires values_out dimension 2 to have size "
3755 << c << ", got " << outputC;
3756 }
3757 if (k != ShapedType::kDynamic && w != ShapedType::kDynamic && !(k >= w))
3758 return emitOpError() << "requires dimensions K >= W, got K=" << k
3759 << " and W=" << w;
3760
3761 return success();
3762}
3763
3764static LogicalResult ReduceInferReturnTypes(
3765 ShapeAdaptor operandShape, Type inputType, IntegerAttr axis,
3766 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3767 int64_t axisVal = axis.getValue().getSExtValue();
3768 if (!operandShape.hasRank() || operandShape.getRank() <= axisVal) {
3769 inferredReturnShapes.push_back(ShapedTypeComponents(inputType));
3770 return success();
3771 }
3772
3773 SmallVector<int64_t> outputShape;
3774 operandShape.getDims(outputShape);
3775 outputShape[axisVal] = 1;
3776 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape, inputType));
3777 return success();
3778}
3779
3780#define COMPATIBLE_RETURN_TYPES(OP) \
3781 bool OP::isCompatibleReturnTypes(TypeRange l, TypeRange r) { \
3782 if (l.size() != r.size() || l.size() != 1) \
3783 return false; \
3784 if (getElementTypeOrSelf(l[0]) != getElementTypeOrSelf(r[0])) \
3785 return false; \
3786 return succeeded(verifyCompatibleShape(l[0], r[0])); \
3787 }
3788
3789#define REDUCE_SHAPE_INFER(OP) \
3790 LogicalResult OP::inferReturnTypeComponents( \
3791 MLIRContext *context, ::std::optional<Location> location, \
3792 OP::Adaptor adaptor, \
3793 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) { \
3794 Type inputType = \
3795 llvm::cast<TensorType>(adaptor.getInput().getType()).getElementType(); \
3796 ShapeAdaptor inputShape(adaptor.getInput().getType()); \
3797 const Properties &prop = adaptor.getProperties(); \
3798 return ReduceInferReturnTypes(inputShape, inputType, prop.axis, \
3799 inferredReturnShapes); \
3800 } \
3801 COMPATIBLE_RETURN_TYPES(OP)
3802
3803REDUCE_SHAPE_INFER(tosa::ReduceAllOp)
3804REDUCE_SHAPE_INFER(tosa::ReduceAnyOp)
3805REDUCE_SHAPE_INFER(tosa::ReduceMaxOp)
3806REDUCE_SHAPE_INFER(tosa::ReduceMinOp)
3807REDUCE_SHAPE_INFER(tosa::ReduceProductOp)
3808REDUCE_SHAPE_INFER(tosa::ReduceSumOp)
3809#undef REDUCE_SHAPE_INFER
3810COMPATIBLE_RETURN_TYPES(tosa::ConcatOp)
3811#undef COMPATIBLE_RETURN_TYPES
3812
3813template <typename T>
3814static LogicalResult verifyReduceOp(T op) {
3815 // All TOSA reduce Ops have input, output and axis.
3816 TensorType inputType = op.getInput().getType();
3817 TensorType outputType = op.getOutput().getType();
3818 int32_t reduceAxis = op.getAxis();
3819
3820 if (reduceAxis < 0) {
3821 op.emitOpError("reduce axis must not be negative");
3822 return failure();
3823 }
3824 if (inputType.hasRank()) {
3825 int64_t inputRank = inputType.getRank();
3826 // We allow for a special case where the input/output shape has rank 0 and
3827 // axis is also 0.
3828 if (reduceAxis >= inputRank && (reduceAxis != 0 || inputRank != 0)) {
3829 op.emitOpError("expect input tensor rank (")
3830 << inputRank << ") to be larger than reduce axis (" << reduceAxis
3831 << ")";
3832 return failure();
3833 }
3834 }
3835 if (outputType.hasRank()) {
3836 int64_t outputRank = outputType.getRank();
3837 if (inputType.hasRank() && outputRank != inputType.getRank()) {
3838 op.emitOpError(
3839 "expect output tensor rank to be equal to input tensor rank");
3840 return failure();
3841 }
3842 if (reduceAxis >= outputRank && (reduceAxis != 0 || outputRank != 0)) {
3843 op.emitOpError("expect output tensor rank (")
3844 << outputRank << ") to be larger than reduce axis (" << reduceAxis
3845 << ")";
3846 return failure();
3847 }
3848 // We can only verify the reduced dimension size to be 1 if this is not
3849 // the special case of output rank == 0.
3850 if (outputRank != 0) {
3851 auto outputShape = outputType.getShape();
3852 if (!outputType.isDynamicDim(reduceAxis) &&
3853 outputShape[reduceAxis] != 1) {
3854 op.emitOpError("expect reduced dimension size to be 1, got ")
3855 << outputShape[reduceAxis];
3856 return failure();
3857 }
3858 }
3859 }
3860 return success();
3861}
3862
3863LogicalResult tosa::ReduceAllOp::verify() { return verifyReduceOp(*this); }
3864LogicalResult tosa::ReduceAnyOp::verify() { return verifyReduceOp(*this); }
3865LogicalResult tosa::ReduceMaxOp::verify() { return verifyReduceOp(*this); }
3866LogicalResult tosa::ReduceMinOp::verify() { return verifyReduceOp(*this); }
3867LogicalResult tosa::ReduceProductOp::verify() { return verifyReduceOp(*this); }
3868LogicalResult tosa::ReduceSumOp::verify() { return verifyReduceOp(*this); }
3869
3870static LogicalResult NAryInferReturnTypes(
3871 const ValueShapeRange &operands,
3872 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3874 if (resolveBroadcastShape(operands, outShape).failed()) {
3875 inferredReturnShapes.push_back(ShapedTypeComponents());
3876 } else {
3877 inferredReturnShapes.push_back(ShapedTypeComponents(outShape));
3878 }
3879 return success();
3880}
3881
3882#define NARY_SHAPE_INFER(OP) \
3883 LogicalResult OP::inferReturnTypeComponents( \
3884 MLIRContext *context, ::std::optional<Location> location, \
3885 ValueShapeRange operands, DictionaryAttr attributes, \
3886 PropertyRef properties, RegionRange regions, \
3887 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) { \
3888 return NAryInferReturnTypes(operands, inferredReturnShapes); \
3889 }
3890
3891NARY_SHAPE_INFER(tosa::AbsOp)
3892NARY_SHAPE_INFER(tosa::AddOp)
3893NARY_SHAPE_INFER(tosa::ArithmeticRightShiftOp)
3894NARY_SHAPE_INFER(tosa::BitwiseAndOp)
3895NARY_SHAPE_INFER(tosa::BitwiseOrOp)
3896NARY_SHAPE_INFER(tosa::BitwiseXorOp)
3897NARY_SHAPE_INFER(tosa::BitwiseNotOp)
3898NARY_SHAPE_INFER(tosa::CastOp)
3899NARY_SHAPE_INFER(tosa::CeilOp)
3900NARY_SHAPE_INFER(tosa::ClampOp)
3901NARY_SHAPE_INFER(tosa::ClzOp)
3902NARY_SHAPE_INFER(tosa::CosOp)
3903NARY_SHAPE_INFER(tosa::ExpOp)
3904NARY_SHAPE_INFER(tosa::FloorOp)
3905NARY_SHAPE_INFER(tosa::GreaterEqualOp)
3906NARY_SHAPE_INFER(tosa::GreaterOp)
3907NARY_SHAPE_INFER(tosa::IdentityOp)
3908NARY_SHAPE_INFER(tosa::IntDivOp)
3909NARY_SHAPE_INFER(tosa::LogOp)
3910NARY_SHAPE_INFER(tosa::LogicalAndOp)
3911NARY_SHAPE_INFER(tosa::LogicalLeftShiftOp)
3912NARY_SHAPE_INFER(tosa::LogicalNotOp)
3913NARY_SHAPE_INFER(tosa::LogicalOrOp)
3914NARY_SHAPE_INFER(tosa::LogicalRightShiftOp)
3915NARY_SHAPE_INFER(tosa::LogicalXorOp)
3916NARY_SHAPE_INFER(tosa::MaximumOp)
3917NARY_SHAPE_INFER(tosa::MinimumOp)
3918NARY_SHAPE_INFER(tosa::PowOp)
3919NARY_SHAPE_INFER(tosa::ReciprocalOp)
3920NARY_SHAPE_INFER(tosa::ReverseOp)
3921NARY_SHAPE_INFER(tosa::RsqrtOp)
3922NARY_SHAPE_INFER(tosa::SinOp)
3923NARY_SHAPE_INFER(tosa::SelectOp)
3924NARY_SHAPE_INFER(tosa::SubOp)
3925NARY_SHAPE_INFER(tosa::TanhOp)
3926NARY_SHAPE_INFER(tosa::ErfOp)
3927NARY_SHAPE_INFER(tosa::SigmoidOp)
3928#undef PRED_SHAPE_INFER
3929
3930LogicalResult tosa::NegateOp::inferReturnTypeComponents(
3931 MLIRContext *context, ::std::optional<Location> location,
3932 NegateOp::Adaptor adaptor,
3933 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3934 ShapeAdaptor inputShape(adaptor.getInput1().getType());
3935 inferredReturnShapes.push_back(ShapedTypeComponents(inputShape));
3936 return success();
3937}
3938
3939LogicalResult tosa::NegateOp::verify() {
3940 // Verify same element type
3941 const Type input1Type = getInput1().getType();
3942 const Type outputType = getOutput().getType();
3943 if (verifySameElementTypes(*this, input1Type, outputType).failed())
3944 return failure();
3945
3946 // Verify same shape
3947 const SmallVector<Type, 2> types = {input1Type, outputType};
3948 if (failed(verifyCompatibleShapes(types)))
3949 return emitOpError() << "requires the same shape for input1 and output";
3950
3951 const Type input1EType = getStorageElementTypeOrSelf(getInput1().getType());
3952 const Type input1ZpEType =
3953 getStorageElementTypeOrSelf(getInput1Zp().getType());
3954 if (input1EType != input1ZpEType) {
3955 return emitOpError("expect both input1 and its zero point are the same "
3956 "element type, got ")
3957 << input1EType << " and " << input1ZpEType;
3958 }
3959 const Type outputEType = getStorageElementTypeOrSelf(getOutput().getType());
3960 const Type outputZpEType =
3961 getStorageElementTypeOrSelf(getOutputZp().getType());
3962 if (outputEType != outputZpEType) {
3963 return emitOpError("expect both output and its zero point are the same "
3964 "element type, got ")
3965 << outputEType << " and " << outputZpEType;
3966 }
3967
3968 FailureOr<int64_t> maybeIZp = getInput1ZeroPoint();
3969 if (succeeded(maybeIZp) && verifyInput1ZeroPoint(*maybeIZp).failed())
3970 return failure();
3971
3972 FailureOr<int64_t> maybeOZp = getOutputZeroPoint();
3973 if (succeeded(maybeOZp) && verifyOutputZeroPoint(*maybeOZp).failed())
3974 return failure();
3975
3976 return success();
3977}
3978
3979static LogicalResult poolingInferReturnTypes(
3980 ShapeAdaptor inputShape, ArrayRef<int64_t> kernel, ArrayRef<int64_t> stride,
3982 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3983 llvm::SmallVector<int64_t> outputShape;
3984 outputShape.resize(4, ShapedType::kDynamic);
3985
3986 // We only know the rank if the input type is unranked.
3987 if (!inputShape.hasRank()) {
3988 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3989 return success();
3990 }
3991
3992 // Batch and number of channels are identical for pooling layer.
3993 outputShape[0] = inputShape.getDimSize(0);
3994 outputShape[3] = inputShape.getDimSize(3);
3995
3996 int64_t height = inputShape.getDimSize(1);
3997 int64_t width = inputShape.getDimSize(2);
3998
3999 if (ShapedType::isStatic(height)) {
4000 int64_t padded = height + pad[0] + pad[1] - kernel[0];
4001 outputShape[1] = padded / stride[0] + 1;
4002 }
4003
4004 if (ShapedType::isStatic(width)) {
4005 int64_t padded = width + pad[2] + pad[3] - kernel[1];
4006 outputShape[2] = padded / stride[1] + 1;
4007 }
4008
4009 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4010 return success();
4011}
4012
4013template <typename AdaptorT>
4015
4017protected:
4018 static void updateIfDynamic(int64_t &current, int64_t candidate) {
4019 if (ShapedType::isDynamic(current))
4020 current = candidate;
4021 }
4022};
4023
4024template <>
4025class ConvInferShapeAdaptor<Conv2DOp::Adaptor>
4026 : public ConvInferShapeAdaptorBase {
4027public:
4028 explicit ConvInferShapeAdaptor(Conv2DOp::Adaptor adaptor)
4029 : adaptor(adaptor) {}
4030
4032 SmallVectorImpl<int64_t> &inputSpatial) {
4033 const ShapeAdaptor inputShape(adaptor.getInput().getType());
4034 if (!inputShape.hasRank())
4035 return;
4036
4037 const int64_t outputBatch = inputShape.getDimSize(0);
4038 const int64_t inputHeight = inputShape.getDimSize(1);
4039 const int64_t inputWidth = inputShape.getDimSize(2);
4040
4041 outputShape[0] = outputBatch;
4042 inputSpatial[0] = inputHeight;
4043 inputSpatial[1] = inputWidth;
4044 }
4045
4047 SmallVectorImpl<int64_t> &weightSpatial) {
4048 const ShapeAdaptor weightShape(adaptor.getWeight().getType());
4049 if (!weightShape.hasRank())
4050 return;
4051
4052 const int64_t outputChannels = weightShape.getDimSize(0);
4053 const int64_t kernelHeight = weightShape.getDimSize(1);
4054 const int64_t kernelWidth = weightShape.getDimSize(2);
4055
4056 outputShape[3] = outputChannels;
4057 weightSpatial[0] = kernelHeight;
4058 weightSpatial[1] = kernelWidth;
4059 }
4060
4061 int64_t getNumSpatialDims() const { return 2; }
4062 int64_t getOutputRank() const { return 4; }
4063
4065 SmallVector<int64_t> &strideValues,
4066 SmallVector<int64_t> &dilationValues) {
4067 padValues.assign(adaptor.getPad().begin(), adaptor.getPad().end());
4068 strideValues.assign(adaptor.getStride().begin(), adaptor.getStride().end());
4069 dilationValues.assign(adaptor.getDilation().begin(),
4070 adaptor.getDilation().end());
4071 return success();
4072 }
4073
4074private:
4075 Conv2DOp::Adaptor adaptor;
4076};
4077
4078template <>
4079class ConvInferShapeAdaptor<Conv2DBlockScaledOp::Adaptor>
4080 : public ConvInferShapeAdaptorBase {
4081public:
4082 explicit ConvInferShapeAdaptor(Conv2DBlockScaledOp::Adaptor adaptor)
4083 : adaptor(adaptor) {}
4084
4086 SmallVectorImpl<int64_t> &inputSpatial) {
4087 const ShapeAdaptor inputDataShape(adaptor.getInputData().getType());
4088 if (inputDataShape.hasRank()) {
4089 const int64_t outputBatch = inputDataShape.getDimSize(0);
4090 const int64_t inputHeight = inputDataShape.getDimSize(1);
4091 const int64_t inputWidth = inputDataShape.getDimSize(2);
4092
4093 outputShape[0] = outputBatch;
4094 inputSpatial[0] = inputHeight;
4095 inputSpatial[1] = inputWidth;
4096 }
4097
4098 const ShapeAdaptor inputScaleShape(adaptor.getInputScale().getType());
4099 if (!inputScaleShape.hasRank())
4100 return;
4101
4102 const int64_t scaleBatch = inputScaleShape.getDimSize(0);
4103 const int64_t scaleHeight = inputScaleShape.getDimSize(1);
4104 const int64_t scaleWidth = inputScaleShape.getDimSize(2);
4105
4106 updateIfDynamic(outputShape[0], scaleBatch);
4107 updateIfDynamic(inputSpatial[0], scaleHeight);
4108 updateIfDynamic(inputSpatial[1], scaleWidth);
4109 }
4110
4112 SmallVectorImpl<int64_t> &weightSpatial) {
4113 const ShapeAdaptor weightDataShape(adaptor.getWeightData().getType());
4114 if (weightDataShape.hasRank()) {
4115 const int64_t outputChannels = weightDataShape.getDimSize(0);
4116 const int64_t kernelHeight = weightDataShape.getDimSize(1);
4117 const int64_t kernelWidth = weightDataShape.getDimSize(2);
4118
4119 outputShape[3] = outputChannels;
4120 weightSpatial[0] = kernelHeight;
4121 weightSpatial[1] = kernelWidth;
4122 }
4123
4124 const ShapeAdaptor weightScaleShape(adaptor.getWeightScale().getType());
4125 if (!weightScaleShape.hasRank())
4126 return;
4127
4128 const int64_t scaleOutputChannels = weightScaleShape.getDimSize(0);
4129 const int64_t scaleKernelHeight = weightScaleShape.getDimSize(1);
4130 const int64_t scaleKernelWidth = weightScaleShape.getDimSize(2);
4131
4132 updateIfDynamic(outputShape[3], scaleOutputChannels);
4133 updateIfDynamic(weightSpatial[0], scaleKernelHeight);
4134 updateIfDynamic(weightSpatial[1], scaleKernelWidth);
4135 }
4136
4137 int64_t getNumSpatialDims() const { return 2; }
4138 int64_t getOutputRank() const { return 4; }
4139
4141 SmallVector<int64_t> &strideValues,
4142 SmallVector<int64_t> &dilationValues) {
4143 if (!tosa::getConstShapeValues(adaptor.getPad().getDefiningOp(),
4144 padValues) ||
4145 !tosa::getConstShapeValues(adaptor.getStride().getDefiningOp(),
4146 strideValues) ||
4147 !tosa::getConstShapeValues(adaptor.getDilation().getDefiningOp(),
4148 dilationValues))
4149 return failure();
4150 return success();
4151 }
4152
4153private:
4154 Conv2DBlockScaledOp::Adaptor adaptor;
4155};
4156
4157template <>
4158class ConvInferShapeAdaptor<Conv3DOp::Adaptor>
4159 : public ConvInferShapeAdaptorBase {
4160public:
4161 explicit ConvInferShapeAdaptor(Conv3DOp::Adaptor adaptor)
4162 : adaptor(adaptor) {}
4163
4165 SmallVectorImpl<int64_t> &inputSpatial) {
4166 const ShapeAdaptor inputShape(adaptor.getInput().getType());
4167 if (!inputShape.hasRank())
4168 return;
4169
4170 const int64_t outputBatch = inputShape.getDimSize(0);
4171 const int64_t inputDepth = inputShape.getDimSize(1);
4172 const int64_t inputHeight = inputShape.getDimSize(2);
4173 const int64_t inputWidth = inputShape.getDimSize(3);
4174
4175 outputShape[0] = outputBatch;
4176 inputSpatial[0] = inputDepth;
4177 inputSpatial[1] = inputHeight;
4178 inputSpatial[2] = inputWidth;
4179 }
4180
4182 SmallVectorImpl<int64_t> &weightSpatial) {
4183 const ShapeAdaptor weightShape(adaptor.getWeight().getType());
4184 if (!weightShape.hasRank())
4185 return;
4186
4187 const int64_t outputChannels = weightShape.getDimSize(0);
4188 const int64_t kernelDepth = weightShape.getDimSize(1);
4189 const int64_t kernelHeight = weightShape.getDimSize(2);
4190 const int64_t kernelWidth = weightShape.getDimSize(3);
4191
4192 outputShape[4] = outputChannels;
4193 weightSpatial[0] = kernelDepth;
4194 weightSpatial[1] = kernelHeight;
4195 weightSpatial[2] = kernelWidth;
4196 }
4197
4198 int64_t getNumSpatialDims() const { return 3; }
4199 int64_t getOutputRank() const { return 5; }
4200
4202 SmallVector<int64_t> &strideValues,
4203 SmallVector<int64_t> &dilationValues) {
4204 padValues.assign(adaptor.getPad().begin(), adaptor.getPad().end());
4205 strideValues.assign(adaptor.getStride().begin(), adaptor.getStride().end());
4206 dilationValues.assign(adaptor.getDilation().begin(),
4207 adaptor.getDilation().end());
4208 return success();
4209 }
4210
4211private:
4212 Conv3DOp::Adaptor adaptor;
4213};
4214
4215template <typename AdaptorT>
4217 AdaptorT adaptor,
4218 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4219 ConvInferShapeAdaptor<AdaptorT> convShapeAdaptor(adaptor);
4220 llvm::SmallVector<int64_t> outputShape(convShapeAdaptor.getOutputRank(),
4221 ShapedType::kDynamic);
4222 llvm::SmallVector<int64_t> inputSpatial(convShapeAdaptor.getNumSpatialDims(),
4223 ShapedType::kDynamic);
4224 llvm::SmallVector<int64_t> weightSpatial(convShapeAdaptor.getNumSpatialDims(),
4225 ShapedType::kDynamic);
4226
4227 convShapeAdaptor.inferInputShape(outputShape, inputSpatial);
4228 convShapeAdaptor.inferWeightShape(outputShape, weightSpatial);
4229
4230 const ShapeAdaptor biasShape = adaptor.getBias().getType();
4231 if (biasShape.hasRank()) {
4232 const int64_t biasSize = biasShape.getDimSize(0);
4233 if (biasSize != 1) {
4234 const size_t outputChannelDim = convShapeAdaptor.getOutputRank() - 1;
4235 outputShape[outputChannelDim] =
4236 ShapedType::isDynamic(outputShape[outputChannelDim])
4237 ? biasSize
4238 : outputShape[outputChannelDim];
4239 }
4240 }
4241
4242 SmallVector<int64_t> padValues;
4243 SmallVector<int64_t> strideValues;
4244 SmallVector<int64_t> dilationValues;
4245 if (failed(convShapeAdaptor.getSpatialParameters(padValues, strideValues,
4246 dilationValues))) {
4247 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4248 return success();
4249 }
4250
4251 for (int64_t dim = 0; dim < convShapeAdaptor.getNumSpatialDims(); ++dim) {
4252 if (!ShapedType::isStatic(inputSpatial[dim]) ||
4253 !ShapedType::isStatic(weightSpatial[dim]))
4254 continue;
4255 const int64_t inputSize =
4256 inputSpatial[dim] + padValues[2 * dim] + padValues[2 * dim + 1];
4257 const int64_t filterSize =
4258 (weightSpatial[dim] - 1) * dilationValues[dim] + 1;
4259 const int64_t unstridedResult = inputSize - filterSize + 1;
4260 outputShape[dim + 1] = (unstridedResult - 1) / strideValues[dim] + 1;
4261 }
4262
4263 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4264 return success();
4265}
4266
4267LogicalResult Conv2DOp::inferReturnTypeComponents(
4268 MLIRContext *context, ::std::optional<Location> location,
4269 Conv2DOp::Adaptor adaptor,
4270 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4271 return inferConvReturnTypeComponents(adaptor, inferredReturnShapes);
4272}
4273
4274LogicalResult Conv2DOp::verify() {
4275 if (verifyConvOp(*this).failed() || verifyConvOpErrorIf(*this).failed())
4276 return failure();
4277 return success();
4278}
4279
4280LogicalResult Conv2DBlockScaledOp::inferReturnTypeComponents(
4281 MLIRContext *context, ::std::optional<Location> location,
4282 Conv2DBlockScaledOp::Adaptor adaptor,
4283 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4284 return inferConvReturnTypeComponents(adaptor, inferredReturnShapes);
4285}
4286
4287LogicalResult Conv2DBlockScaledOp::verify() {
4288 if (failed(verifySameElementTypes(*this, getInputData().getType(),
4289 getWeightData().getType(), "input_data",
4290 "weight_data")) ||
4291 failed(verifySameElementTypes(*this, getInputScale().getType(),
4292 getWeightScale().getType(), "input_scale",
4293 "weight_scale")) ||
4294 failed(verifySameElementTypes(*this, getBias().getType(),
4295 getOutput().getType(), "bias", "output")))
4296 return failure();
4297
4298 // Verify input shape compatibility
4299 int64_t N = ShapedType::kDynamic;
4300 int64_t IH = ShapedType::kDynamic;
4301 int64_t IW = ShapedType::kDynamic;
4302 int64_t IC = ShapedType::kDynamic;
4303 int64_t multiplesOfIC = ShapedType::kDynamic;
4304 int64_t OC = ShapedType::kDynamic;
4305 int64_t KH = ShapedType::kDynamic;
4306 int64_t KW = ShapedType::kDynamic;
4307
4308 const ShapeAdaptor inputDataShape(getInputData().getType());
4309 if (inputDataShape.hasRank()) {
4310 N = inputDataShape.getDimSize(0);
4311 IH = inputDataShape.getDimSize(1);
4312 IW = inputDataShape.getDimSize(2);
4313 IC = inputDataShape.getDimSize(3);
4314 }
4315
4316 const ShapeAdaptor inputScaleShape(getInputScale().getType());
4317 if (inputScaleShape.hasRank()) {
4318 if (failed(tryUpdateDimOrFailure(*this, N, inputScaleShape.getDimSize(0),
4319 "input_scale", "batch size")) ||
4320 failed(tryUpdateDimOrFailure(*this, IH, inputScaleShape.getDimSize(1),
4321 "input_scale", "input height")) ||
4322 failed(tryUpdateDimOrFailure(*this, IW, inputScaleShape.getDimSize(2),
4323 "input_scale", "input width")))
4324 return failure();
4325 multiplesOfIC = inputScaleShape.getDimSize(3);
4326 }
4327
4328 const ShapeAdaptor weightDataShape(getWeightData().getType());
4329 if (weightDataShape.hasRank()) {
4330 OC = weightDataShape.getDimSize(0);
4331 KH = weightDataShape.getDimSize(1);
4332 KW = weightDataShape.getDimSize(2);
4333 if (failed(tryUpdateDimOrFailure(*this, IC, weightDataShape.getDimSize(3),
4334 "weight_data", "input channels")))
4335 return failure();
4336 }
4337
4338 const ShapeAdaptor weightScaleShape(getWeightScale().getType());
4339 if (weightScaleShape.hasRank()) {
4340 if (failed(tryUpdateDimOrFailure(*this, OC, weightScaleShape.getDimSize(0),
4341 "weight_scale", "output channels")) ||
4342 failed(tryUpdateDimOrFailure(*this, KH, weightScaleShape.getDimSize(1),
4343 "weight_scale", "kernel height")) ||
4344 failed(tryUpdateDimOrFailure(*this, KW, weightScaleShape.getDimSize(2),
4345 "weight_scale", "kernel width")) ||
4346 failed(tryUpdateDimOrFailure(*this, multiplesOfIC,
4347 weightScaleShape.getDimSize(3),
4348 "weight_scale", "input channel blocks")))
4349 return failure();
4350 }
4351
4352 const uint32_t blockSize = BlockSizeAttr::getBlockSizeValue(getBlockSize());
4353 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_32))
4354 return emitOpError("expect block size to be 32, got ") << blockSize;
4355 // Verify IC is a multiple of block size
4356 if (ShapedType::isStatic(IC) && IC % blockSize != 0)
4357 return emitOpError("expect IC to be a multiple of block size, got IC=")
4358 << IC << ", block_size=" << blockSize;
4359
4360 // Verify multiplesOfIC is IC / block size
4361 if (ShapedType::isStatic(IC) && ShapedType::isStatic(multiplesOfIC) &&
4362 multiplesOfIC != IC / blockSize)
4363 return emitOpError(
4364 "expect scale operands dimension 2 to equal IC/block_size (")
4365 << IC << "/" << blockSize << ")"
4366 << ", got " << multiplesOfIC;
4367
4368 // Verify pad/stride/dilation values
4369 SmallVector<int64_t> padValues;
4370 if (tosa::getConstShapeValues(getPad().getDefiningOp(), padValues)) {
4371 if (llvm::any_of(padValues, [](int64_t p) { return p < 0; }))
4372 return emitOpError("expect all padding values to be >= 0, got ")
4373 << padValues;
4374 }
4375
4376 SmallVector<int64_t> strideValues;
4377 if (tosa::getConstShapeValues(getStride().getDefiningOp(), strideValues)) {
4378 if (llvm::any_of(strideValues, [](int64_t s) { return s < 1; }))
4379 return emitOpError("expect all stride values to be >= 1, got ")
4380 << strideValues;
4381 }
4382
4383 SmallVector<int64_t> dilationValues;
4384 if (tosa::getConstShapeValues(getDilation().getDefiningOp(),
4385 dilationValues)) {
4386 if (llvm::any_of(dilationValues, [](int64_t d) { return d < 1; }))
4387 return emitOpError("expect all dilation values to be >= 1, got ")
4388 << dilationValues;
4389 }
4390
4391 // Verify output shape compatibility
4392 const ShapeAdaptor outputShape(getOutput().getType());
4393 if (!padValues.empty() && !strideValues.empty() && !dilationValues.empty() &&
4394 outputShape.hasRank()) {
4395 if (failed(verifyConvOutputSize(*this, IH, KH, outputShape.getDimSize(1),
4396 padValues[0], padValues[1], strideValues[0],
4397 dilationValues[0], "height", "y", "top",
4398 "bottom")) ||
4399 failed(verifyConvOutputSize(*this, IW, KW, outputShape.getDimSize(2),
4400 padValues[2], padValues[3], strideValues[1],
4401 dilationValues[1], "width", "x", "left",
4402 "right")))
4403 return failure();
4404 }
4405
4406 // Verify bias
4407 const ShapeAdaptor biasShape(getBias().getType());
4408 if (biasShape.hasRank() && outputShape.hasRank()) {
4409 const int64_t biasChannels = biasShape.getDimSize(0);
4410 const int64_t outputChannels =
4411 outputShape.getDimSize(outputShape.getRank() - 1);
4412 if (biasChannels == ShapedType::kDynamic ||
4413 outputChannels == ShapedType::kDynamic)
4414 // Skip following checks if biasChannels or outputChannels is dynamic dim
4415 return success();
4416
4417 if (biasChannels != outputChannels && biasChannels != 1)
4418 return emitOpError(
4419 "bias channels expected to be equal to output channels (")
4420 << outputChannels << ") or 1, got " << biasChannels;
4421 }
4422
4423 return success();
4424}
4425
4426LogicalResult Conv3DOp::inferReturnTypeComponents(
4427 MLIRContext *context, ::std::optional<Location> location,
4428 Conv3DOp::Adaptor adaptor,
4429 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4430 return inferConvReturnTypeComponents(adaptor, inferredReturnShapes);
4431}
4432
4433LogicalResult Conv3DOp::verify() {
4434 if (verifyConvOp(*this).failed() || verifyConvOpErrorIf(*this).failed())
4435 return failure();
4436 return success();
4437}
4438
4439LogicalResult AvgPool2dOp::inferReturnTypeComponents(
4440 MLIRContext *context, ::std::optional<Location> location,
4441 AvgPool2dOp::Adaptor adaptor,
4442 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4443 ShapeAdaptor inputShape(adaptor.getInput().getType());
4444 const Properties &prop = adaptor.getProperties();
4445 return poolingInferReturnTypes(inputShape, prop.kernel, prop.stride, prop.pad,
4446 inferredReturnShapes);
4447}
4448
4449LogicalResult AvgPool2dAdaptiveOp::inferReturnTypeComponents(
4450 MLIRContext *context, ::std::optional<Location> location,
4451 AvgPool2dAdaptiveOp::Adaptor adaptor,
4452 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4453 ShapeAdaptor inputShape(adaptor.getInput().getType());
4454
4455 llvm::SmallVector<int64_t> kernelValues;
4456 llvm::SmallVector<int64_t> strideValues;
4457 llvm::SmallVector<int64_t> padValues;
4458 if (tosa::getConstShapeValues(adaptor.getKernel().getDefiningOp(),
4459 kernelValues) &&
4460 tosa::getConstShapeValues(adaptor.getStride().getDefiningOp(),
4461 strideValues) &&
4462 tosa::getConstShapeValues(adaptor.getPad().getDefiningOp(), padValues)) {
4463 return poolingInferReturnTypes(inputShape, kernelValues, strideValues,
4464 padValues, inferredReturnShapes);
4465 }
4466
4467 llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamic);
4468 if (inputShape.hasRank()) {
4469 // Keep N & C as pooling only changes H & W.
4470 outputShape[0] = inputShape.getDimSize(0);
4471 outputShape[3] = inputShape.getDimSize(3);
4472 }
4473
4474 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4475 return success();
4476}
4477
4478LogicalResult MaxPool2dOp::inferReturnTypeComponents(
4479 MLIRContext *context, ::std::optional<Location> location,
4480 MaxPool2dOp::Adaptor adaptor,
4481 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4482 ShapeAdaptor inputShape(adaptor.getInput().getType());
4483 const Properties &prop = adaptor.getProperties();
4484 return poolingInferReturnTypes(inputShape, prop.kernel, prop.stride, prop.pad,
4485 inferredReturnShapes);
4486}
4487
4488LogicalResult MaxPool2dAdaptiveOp::inferReturnTypeComponents(
4489 MLIRContext *context, ::std::optional<Location> location,
4490 MaxPool2dAdaptiveOp::Adaptor adaptor,
4491 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4492 ShapeAdaptor inputShape(adaptor.getInput().getType());
4493
4494 llvm::SmallVector<int64_t> kernelValues;
4495 llvm::SmallVector<int64_t> strideValues;
4496 llvm::SmallVector<int64_t> padValues;
4497 if (tosa::getConstShapeValues(adaptor.getKernel().getDefiningOp(),
4498 kernelValues) &&
4499 tosa::getConstShapeValues(adaptor.getStride().getDefiningOp(),
4500 strideValues) &&
4501 tosa::getConstShapeValues(adaptor.getPad().getDefiningOp(), padValues)) {
4502 return poolingInferReturnTypes(inputShape, kernelValues, strideValues,
4503 padValues, inferredReturnShapes);
4504 }
4505
4506 llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamic);
4507 if (inputShape.hasRank()) {
4508 outputShape[0] = inputShape.getDimSize(0);
4509 outputShape[3] = inputShape.getDimSize(3);
4510 }
4511 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4512 return success();
4513}
4514
4515LogicalResult MaxPool2dOp::verify() {
4516 if (failed(verifySameElementTypes(*this, /* intype = */ getInput().getType(),
4517 /* outType = */ getOutput().getType())))
4518 return failure();
4519
4520 if (failed(verifyPoolingOp(*this)))
4521 return failure();
4522
4523 return success();
4524}
4525
4526LogicalResult MaxPool2dAdaptiveOp::verify() {
4527 if (failed(verifySameElementTypes(*this, /* intype = */ getInput().getType(),
4528 /* outType = */ getOutput().getType())))
4529 return failure();
4530
4531 AdaptivePoolingConstShapeValues values;
4533
4534 if (failed(verifyPoolingOpImpl(getOperation(), values.kernel, values.stride,
4535 values.pad, getInput(), getOutput())))
4536 return failure();
4537
4538 return success();
4539}
4540
4541LogicalResult DepthwiseConv2DOp::inferReturnTypeComponents(
4542 MLIRContext *context, ::std::optional<Location> location,
4543 DepthwiseConv2DOp::Adaptor adaptor,
4544 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4545 llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamic);
4546
4547 int64_t inputWidth = ShapedType::kDynamic;
4548 int64_t inputHeight = ShapedType::kDynamic;
4549 int64_t inputChannels = ShapedType::kDynamic;
4550
4551 int64_t weightWidth = ShapedType::kDynamic;
4552 int64_t weightHeight = ShapedType::kDynamic;
4553 int64_t depthChannels = ShapedType::kDynamic;
4554
4555 // Input shape describes input width/height and batch.
4556 ShapeAdaptor inputShape(adaptor.getInput().getType());
4557 if (inputShape.hasRank()) {
4558 outputShape[0] = inputShape.getDimSize(0);
4559 inputHeight = inputShape.getDimSize(1);
4560 inputWidth = inputShape.getDimSize(2);
4561 inputChannels = inputShape.getDimSize(3);
4562 }
4563
4564 // Weight shapes describes the filter width/height and the output channels.
4565 ShapeAdaptor weightShape(adaptor.getWeight().getType());
4566 if (weightShape.hasRank()) {
4567 weightHeight = weightShape.getDimSize(0);
4568 weightWidth = weightShape.getDimSize(1);
4569 inputChannels = ShapedType::isDynamic(inputChannels)
4570 ? weightShape.getDimSize(2)
4571 : inputChannels;
4572 depthChannels = weightShape.getDimSize(3);
4573 }
4574
4575 // If both inputChannels and depthChannels are available we can determine
4576 // the output channels.
4577 if (ShapedType::isStatic(inputChannels) &&
4578 ShapedType::isStatic(depthChannels)) {
4579 outputShape[3] = inputChannels * depthChannels;
4580 }
4581
4582 // Bias shape can describe the output channels.
4583 ShapeAdaptor biasShape(adaptor.getBias().getType());
4584 if (biasShape.hasRank() && ShapedType::isDynamic(outputShape[3])) {
4585 int64_t bc = biasShape.getDimSize(0);
4586 if (bc != ShapedType::kDynamic && bc != 1)
4587 outputShape[3] = bc;
4588 }
4589
4590 llvm::ArrayRef<int64_t> dilation = adaptor.getDilation();
4591 llvm::ArrayRef<int64_t> padding = adaptor.getPad();
4592 llvm::ArrayRef<int64_t> stride = adaptor.getStride();
4593
4594 if (ShapedType::isStatic(inputHeight) && ShapedType::isStatic(weightHeight)) {
4595 int64_t inputSize = inputHeight + padding[0] + padding[1];
4596 int64_t filterSize = (weightHeight - 1) * dilation[0] + 1;
4597 int64_t unstridedResult = inputSize - filterSize + 1;
4598 outputShape[1] = (unstridedResult - 1) / stride[0] + 1;
4599 }
4600
4601 if (ShapedType::isStatic(inputWidth) && ShapedType::isStatic(weightWidth)) {
4602 int64_t inputSize = inputWidth + padding[2] + padding[3];
4603 int64_t filterSize = (weightWidth - 1) * dilation[1] + 1;
4604 int64_t unstridedResult = inputSize - filterSize + 1;
4605 outputShape[2] = (unstridedResult - 1) / stride[1] + 1;
4606 }
4607
4608 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4609 return success();
4610}
4611
4612LogicalResult DepthwiseConv2DOp::verify() {
4613 if (verifyConvOp(*this).failed() || verifyConvOpErrorIf(*this).failed())
4614 return failure();
4615 return success();
4616}
4617
4618LogicalResult TransposeConv2DOp::inferReturnTypeComponents(
4619 MLIRContext *context, ::std::optional<Location> location,
4620 TransposeConv2DOp::Adaptor adaptor,
4621 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4622 llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamic);
4623
4624 int64_t inputWidth = ShapedType::kDynamic;
4625 int64_t inputHeight = ShapedType::kDynamic;
4626 int64_t weightWidth = ShapedType::kDynamic;
4627 int64_t weightHeight = ShapedType::kDynamic;
4628
4629 // Input shape describes input width/height and batch.
4630 ShapeAdaptor inputShape(adaptor.getInput().getType());
4631 if (inputShape.hasRank()) {
4632 outputShape[0] = ShapedType::isDynamic(outputShape[0])
4633 ? inputShape.getDimSize(0)
4634 : outputShape[0];
4635 inputHeight = inputShape.getDimSize(1);
4636 inputWidth = inputShape.getDimSize(2);
4637 }
4638
4639 // Weight shapes describes the filter width/height and the output channels.
4640 ShapeAdaptor weightShape(adaptor.getWeight().getType());
4641 if (weightShape.hasRank()) {
4642 outputShape[3] = ShapedType::isDynamic(outputShape[3])
4643 ? weightShape.getDimSize(0)
4644 : outputShape[3];
4645 weightHeight = weightShape.getDimSize(1);
4646 weightWidth = weightShape.getDimSize(2);
4647 }
4648
4649 // Bias shape can describe the output channels.
4650 ShapeAdaptor biasShape(adaptor.getBias().getType());
4651 if (biasShape.hasRank() && ShapedType::isDynamic(outputShape[3])) {
4652 int64_t bc = biasShape.getDimSize(0);
4653 if (bc != ShapedType::kDynamic && bc != 1)
4654 outputShape[3] = bc;
4655 }
4656
4657 llvm::ArrayRef<int64_t> padding = adaptor.getOutPad();
4658 llvm::ArrayRef<int64_t> stride = adaptor.getStride();
4659
4660 if (ShapedType::isStatic(inputHeight) && ShapedType::isStatic(weightHeight)) {
4661 int64_t calculateSize =
4662 (inputHeight - 1) * stride[0] + padding[0] + padding[1] + weightHeight;
4663 outputShape[1] =
4664 ShapedType::isDynamic(outputShape[1]) ? calculateSize : outputShape[1];
4665 }
4666
4667 if (ShapedType::isStatic(inputWidth) && ShapedType::isStatic(weightWidth)) {
4668 int64_t calculateSize =
4669 (inputWidth - 1) * stride[1] + padding[2] + padding[3] + weightWidth;
4670 outputShape[2] =
4671 ShapedType::isDynamic(outputShape[2]) ? calculateSize : outputShape[2];
4672 }
4673
4674 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4675 return success();
4676}
4677
4678LogicalResult TransposeConv2DOp::verify() {
4679 if (verifyConvOp(*this).failed())
4680 return failure();
4681
4682 const llvm::ArrayRef<int64_t> strides = getStride();
4683 const int64_t strideY = strides[0];
4684 const int64_t strideX = strides[1];
4685
4686 if (strideY < 1 || strideX < 1)
4687 return emitOpError("expect all stride values to be >= 1, got [")
4688 << strides << "]";
4689
4690 const auto checkPadAgainstKernelDim =
4691 [this](int64_t padValue, int64_t kernelDimSize, llvm::StringRef padName,
4692 llvm::StringRef kernelDimName) -> LogicalResult {
4693 if (padValue <= -kernelDimSize)
4694 return emitOpError("expected ")
4695 << padName << " > -" << kernelDimName << ", but got: " << padName
4696 << "=" << padValue << " and " << kernelDimName << "="
4697 << kernelDimSize;
4698 return success();
4699 };
4700
4701 const llvm::ArrayRef<int64_t> padding = getOutPad();
4702 const int64_t outPadTop = padding[0];
4703 const int64_t outPadBottom = padding[1];
4704 const int64_t outPadLeft = padding[2];
4705 const int64_t outPadRight = padding[3];
4706
4707 const auto weightType =
4708 llvm::dyn_cast<RankedTensorType>(getWeight().getType());
4709
4710 if (weightType) {
4711 const int64_t kernelHeight = weightType.getDimSize(1);
4712 if (ShapedType::isStatic(kernelHeight)) {
4713 if (failed(checkPadAgainstKernelDim(outPadTop, kernelHeight,
4714 "out_pad_top", "KH")))
4715 return failure();
4716
4717 if (failed(checkPadAgainstKernelDim(outPadBottom, kernelHeight,
4718 "out_pad_bottom", "KH")))
4719 return failure();
4720 }
4721
4722 const int64_t kernelWidth = weightType.getDimSize(2);
4723 if (ShapedType::isStatic(kernelWidth)) {
4724 if (failed(checkPadAgainstKernelDim(outPadLeft, kernelWidth,
4725 "out_pad_left", "KW")))
4726 return failure();
4727
4728 if (failed(checkPadAgainstKernelDim(outPadRight, kernelWidth,
4729 "out_pad_right", "KW")))
4730 return failure();
4731 }
4732 }
4733
4734 // Rest of the checks depend on the output type being a RankedTensorType
4735 const auto outputType =
4736 llvm::dyn_cast<RankedTensorType>(getOutput().getType());
4737 if (!outputType)
4738 return success();
4739
4740 const auto inputType = llvm::dyn_cast<RankedTensorType>(getInput().getType());
4741 if (inputType && weightType) {
4742 const int64_t inputHeight = inputType.getDimSize(1);
4743 const int64_t kernelHeight = weightType.getDimSize(1);
4744 const int64_t outputHeight = outputType.getDimSize(1);
4745
4746 if (ShapedType::isStatic(inputHeight) &&
4747 ShapedType::isStatic(outputHeight)) {
4748 if (outputHeight !=
4749 (inputHeight - 1) * strideY + outPadTop + outPadBottom + kernelHeight)
4750 return emitOpError(
4751 "dimension mismatch: expected OH == (IH - 1) * stride_y "
4752 "+ out_pad_top + out_pad_bottom + KH, but got ")
4753 << outputHeight << " != (" << inputHeight << " - 1) * "
4754 << strideY << " + " << outPadTop << " + " << outPadBottom
4755 << " + " << kernelHeight;
4756 }
4757
4758 const int64_t inputWidth = inputType.getDimSize(2);
4759 const int64_t kernelWidth = weightType.getDimSize(2);
4760 const int64_t outputWidth = outputType.getDimSize(2);
4761
4762 if (ShapedType::isStatic(inputWidth) && ShapedType::isStatic(outputWidth)) {
4763 if (outputWidth !=
4764 (inputWidth - 1) * strideX + outPadLeft + outPadRight + kernelWidth)
4765 return emitOpError(
4766 "dimension mismatch: expected OW == (IW - 1) * stride_x "
4767 "+ out_pad_left + out_pad_right + KW, but got ")
4768 << outputWidth << " != (" << inputWidth << " - 1) * " << strideX
4769 << " + " << outPadLeft << " + " << outPadRight << " + "
4770 << kernelWidth;
4771 }
4772 }
4773
4774 const auto biasType = llvm::dyn_cast<RankedTensorType>(getBias().getType());
4775
4776 if (!biasType)
4777 return success();
4778
4779 const int64_t biasChannels = biasType.getDimSize(0);
4780
4781 // Skip further checks if bias is dynamic
4782 if (biasChannels == ShapedType::kDynamic)
4783 return success();
4784
4785 const int64_t outputChannels = outputType.getDimSize(3);
4786 if (!ShapedType::isDynamic(outputChannels) &&
4787 biasChannels != outputChannels && biasChannels != 1)
4788 return emitOpError(
4789 "bias channels expected to be equal to output channels (")
4790 << outputChannels << ") or 1, got " << biasChannels;
4791
4792 return success();
4793}
4794
4795void RescaleOp::build(OpBuilder &builder, OperationState &state, Type output,
4796 Value input, Value multiplier, Value shift, Value inputZp,
4797 Value outputZp, bool scale32, RoundingMode roundingMode,
4798 bool perChannel) {
4799 build(builder, state, output, input, multiplier, shift, inputZp, outputZp,
4800 scale32, roundingMode, perChannel,
4801 getStorageElementTypeOrSelf(input).isUnsignedInteger(),
4802 getStorageElementTypeOrSelf(output).isUnsignedInteger());
4803}
4804
4805void RescaleOp::build(OpBuilder &builder, OperationState &state, Type output,
4806 Value input, Value multiplier, Value shift, Value inputZp,
4807 Value outputZp, BoolAttr scale32,
4808 RoundingModeAttr roundingMode, BoolAttr perChannel) {
4809 build(builder, state, output, input, multiplier, shift, inputZp, outputZp,
4810 scale32.getValue(), roundingMode.getValue(), perChannel.getValue());
4811}
4812
4813LogicalResult RescaleOp::verify() {
4814 const auto inputType = llvm::cast<ShapedType>(getInput().getType());
4815 auto inputElementType =
4816 getStorageElementTypeOrSelf(inputType.getElementType());
4817 if (!mlir::isa<IntegerType>(inputElementType)) {
4818 emitOpError("expect input to have integer element type, got ")
4819 << inputElementType;
4820 return failure();
4821 }
4822
4823 const auto outputType = llvm::cast<ShapedType>(getOutput().getType());
4824 auto outputElementType =
4825 getStorageElementTypeOrSelf(outputType.getElementType());
4826 if (!mlir::isa<IntegerType>(outputElementType)) {
4827 emitOpError("expect output to have integer element type, got ")
4828 << outputElementType;
4829 return failure();
4830 }
4831
4832 if (inputElementType.isUnsignedInteger() && !getInputUnsigned())
4833 return emitOpError("requires input_unsigned to be true for unsigned input "
4834 "type, got ")
4835 << inputElementType;
4836
4837 if (outputElementType.isUnsignedInteger() && !getOutputUnsigned())
4838 return emitOpError(
4839 "requires output_unsigned to be true for unsigned output "
4840 "type, got ")
4841 << outputElementType;
4842
4843 if (verifyRescaleValueAndZpTypes(*this, getInput(), getInputZp(), "input")
4844 .failed())
4845 return failure();
4846
4847 if (verifyRescaleValueAndZpTypes(*this, getOutput(), getOutputZp(), "output")
4848 .failed())
4849 return failure();
4850
4851 const auto multiplierType = llvm::cast<ShapedType>(getMultiplier().getType());
4852 // multiplier element type must be i32 for scale32 = true
4853 if (getScale32() && !multiplierType.getElementType().isInteger(32)) {
4854 emitOpError("expect i32 element type for multiplier for scale32=true, got ")
4855 << multiplierType.getElementType();
4856 return failure();
4857 }
4858
4859 // multiplier element type must be i16 for scale32 = false
4860 if (!getScale32() && !multiplierType.getElementType().isInteger(16)) {
4861 emitOpError(
4862 "expect i16 element type for multiplier for scale32=false, got ")
4863 << multiplierType.getElementType();
4864 return failure();
4865 }
4866
4867 if (!inputType.hasRank())
4868 return success();
4869
4870 // multiplier/shift must have shape = {numChannels},
4871 // where numChannel is 1 if per_channel = false
4872 // otherwise numChannel is dimension in input shape's last axis
4873 int64_t numChannels = 1;
4874 if (getPerChannel()) {
4875 if (inputType.getRank() < 1) {
4876 emitOpError("requires input to be at least rank 1 when per_channel is "
4877 "true, but got rank ")
4878 << inputType.getRank();
4879 return failure();
4880 }
4881 numChannels = inputType.getDimSize(inputType.getRank() - 1);
4882 }
4883
4884 if (outputType.hasRank()) {
4886 getOperation(), outputType, inputType.getShape())))
4887 return failure();
4888 }
4889
4890 if (multiplierType.hasRank()) {
4891 ArrayRef<int64_t> multiplierShape = multiplierType.getShape();
4892 // multiplier input has rank 1 by dialect definition
4893 if (multiplierShape[0] != ShapedType::kDynamic &&
4894 multiplierShape[0] != numChannels) {
4895 emitOpError("expect shape of { ")
4896 << numChannels << " } for multiplier input, got { "
4897 << multiplierShape[0] << " }";
4898 return failure();
4899 }
4900 }
4901
4902 const auto shiftType = llvm::cast<ShapedType>(getShift().getType());
4903 if (shiftType.hasRank()) {
4904 ArrayRef<int64_t> shiftShape = shiftType.getShape();
4905 // shift input has rank 1 by dialect definition
4906 if (shiftShape[0] != ShapedType::kDynamic && shiftShape[0] != numChannels) {
4907 emitOpError("expect shape of { ")
4908 << numChannels << " } for shift input, got { " << shiftShape[0]
4909 << " }";
4910 return failure();
4911 }
4912 }
4913
4914 return success();
4915}
4916
4917LogicalResult RescaleOp::inferReturnTypeComponents(
4918 MLIRContext *context, ::std::optional<Location> location,
4919 RescaleOp::Adaptor adaptor,
4920 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4921 ShapeAdaptor inputShape(adaptor.getInput().getType());
4922 inferredReturnShapes.push_back(ShapedTypeComponents(inputShape));
4923 return success();
4924}
4925
4926void CastOp::build(OpBuilder &builder, OperationState &state, Type output,
4927 Value input) {
4928 const Type inputType = getStorageElementTypeOrSelf(input);
4929 build(builder, state, output, input,
4930 inputType.isUnsignedInteger() && !inputType.isInteger(1));
4931}
4932
4933void CastOp::build(OpBuilder &builder, OperationState &state, Type output,
4934 Value input, bool inputUnsigned) {
4935 build(builder, state, output, input, builder.getBoolAttr(inputUnsigned));
4936}
4937
4938LogicalResult CastOp::verify() {
4939 const ShapedType inputType = llvm::cast<ShapedType>(getInput().getType());
4940 const ShapedType outputType = llvm::cast<ShapedType>(getType());
4941 const Type inputElementType = inputType.getElementType();
4942 const Type outputElementType = outputType.getElementType();
4943
4944 const bool inputIsBlockScaled = llvm::isa<BlockScaledType>(inputElementType);
4945 const bool outputIsBlockScaled =
4946 llvm::isa<BlockScaledType>(outputElementType);
4947
4948 const bool isUnsigned = this->getInputUnsigned();
4949 const Type inputDataType = getStorageElementTypeOrSelf(inputType);
4950 const bool isBoolType = inputDataType.isInteger(1);
4951
4952 if (isUnsigned)
4953 if (!inputDataType.isInteger() || isBoolType)
4954 return emitOpError()
4955 << "attribute input_unsigned requires integer type inputs. Got: "
4956 << inputDataType;
4957
4958 if (inputDataType.isUnsignedInteger() && !isBoolType && !isUnsigned)
4959 return emitOpError("requires input_unsigned to be true for unsigned input "
4960 "type, got ")
4961 << inputDataType;
4962
4963 if (!inputIsBlockScaled && !outputIsBlockScaled)
4964 return success();
4965
4966 if (inputIsBlockScaled && outputIsBlockScaled)
4967 return emitOpError()
4968 << "requires exactly one of input or output to have block scaled "
4969 "element type";
4970
4971 const Type scalarElementType =
4972 inputIsBlockScaled ? outputElementType : inputElementType;
4973 if (!llvm::isa<FloatType>(scalarElementType))
4974 return emitOpError()
4975 << "requires non-block-scaled element type to be floating-point "
4976 "when casting to or from block scaled element type, got "
4977 << scalarElementType;
4978
4979 return success();
4980}
4981
4982LogicalResult CastFromBlockScaledOp::inferReturnTypeComponents(
4983 MLIRContext *context, ::std::optional<Location> location,
4984 CastFromBlockScaledOp::Adaptor adaptor,
4985 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4986 const ShapeAdaptor inputShape(adaptor.getInputData().getType());
4987 inferredReturnShapes.push_back(ShapedTypeComponents(inputShape));
4988 return success();
4989}
4990
4991LogicalResult CastFromBlockScaledOp::verify() {
4992 const Type inputDataType = getInputData().getType();
4993 const Type outputDataType = getResult().getType();
4994 if (failed(verifyCompatibleShape(inputDataType, outputDataType)))
4995 return emitOpError() << "require compatible shapes for input_data ("
4996 << inputDataType << ") and " << "output_data ("
4997 << outputDataType << ")";
4998
4999 const ShapeAdaptor inputDataShape = ShapeAdaptor(inputDataType);
5000
5001 if (inputDataShape.hasRank()) {
5002 const unsigned int blockSize =
5003 BlockSizeAttr::getBlockSizeValue(getBlockSize());
5004 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_32))
5005 return emitOpError("expect block size to be 32, got ") << blockSize;
5006 const int64_t inputDataLastDim =
5007 inputDataShape.getDimSize(inputDataShape.getRank() - 1);
5008 if (inputDataLastDim % blockSize != 0)
5009 return emitOpError() << "expect last dimension of input_data ("
5010 << inputDataLastDim
5011 << ") to be divisible by block_size (" << blockSize
5012 << ")";
5013
5014 const Type inputScaleType = getInputScale().getType();
5015 const ShapeAdaptor inputScaleShape = ShapeAdaptor(inputScaleType);
5016
5017 if (inputScaleShape.hasRank()) {
5018 SmallVector<int64_t> inputDataDims, inputScaleDims;
5019 inputDataShape.getDims(inputDataDims);
5020 inputScaleShape.getDims(inputScaleDims);
5021
5022 if (inputDataDims.size() != inputScaleDims.size() ||
5024 ArrayRef<int64_t>(inputDataDims).drop_back(1),
5025 ArrayRef<int64_t>(inputScaleDims).drop_back(1))))
5026 return emitOpError()
5027 << "require compatible shapes for input_data (" << inputDataType
5028 << ") and " << "input_scale (" << inputScaleType
5029 << ") except for the last dimension";
5030
5031 const SmallVector<int64_t, 2> dimsToCheck{inputDataLastDim / blockSize,
5032 inputScaleDims.back()};
5033 if (ShapedType::isStatic(inputDataLastDim) &&
5034 failed(verifyCompatibleDims(dimsToCheck)))
5035 return emitOpError()
5036 << "expect last dimension of input_scale ("
5037 << inputScaleDims.back()
5038 << ") to be equal to last dimension of input_data / block_size ("
5039 << inputDataDims.back() / blockSize << ")";
5040 }
5041 }
5042
5043 return success();
5044}
5045
5046LogicalResult CastToBlockScaledOp::inferReturnTypeComponents(
5047 MLIRContext *context, ::std::optional<Location> location,
5048 CastToBlockScaledOp::Adaptor adaptor,
5049 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
5050 const ShapeAdaptor inputShape(adaptor.getInputData().getType());
5051 inferredReturnShapes.push_back(ShapedTypeComponents(inputShape));
5052 if (!inputShape.hasRank())
5053 return success();
5054
5055 // Calculate output_scale shape if ranked input provided
5056 SmallVector<int64_t> outputScaleShape;
5057 inputShape.getDims(outputScaleShape);
5058 const int64_t lastDimLoc = inputShape.getRank() - 1;
5059 const int64_t lastDimSize = inputShape.getDimSize(lastDimLoc);
5060 if (ShapedType::isStatic(lastDimSize)) {
5061 const unsigned int blockSize =
5062 BlockSizeAttr::getBlockSizeValue(adaptor.getBlockSize());
5063 outputScaleShape[lastDimLoc] = lastDimSize / blockSize;
5064 }
5065 inferredReturnShapes.push_back(ShapedTypeComponents(outputScaleShape));
5066 return success();
5067}
5068
5069LogicalResult CastToBlockScaledOp::verify() {
5070 const Type inputDataType = getInputData().getType();
5071 const Type outputDataType = getResult(0).getType();
5072 if (failed(verifyCompatibleShape(inputDataType, outputDataType)))
5073 return emitOpError() << "require compatible shapes for input_data ("
5074 << inputDataType << ") and " << "output_data ("
5075 << outputDataType << ")";
5076
5077 const unsigned int blockSize =
5078 BlockSizeAttr::getBlockSizeValue(getBlockSize());
5079 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_32))
5080 return emitOpError("expect block size to be 32, got ") << blockSize;
5081 const ShapeAdaptor inputDataShape = ShapeAdaptor(inputDataType);
5082 if (inputDataShape.hasRank()) {
5083 const int64_t inputDataLastDim =
5084 inputDataShape.getDimSize(inputDataShape.getRank() - 1);
5085 if (ShapedType::isStatic(inputDataLastDim) &&
5086 inputDataLastDim % blockSize != 0)
5087 return emitOpError() << "expect last dimension of input_data ("
5088 << inputDataLastDim
5089 << ") to be divisible by block_size (" << blockSize
5090 << ")";
5091 }
5092
5093 const ShapeAdaptor outputDataShape = ShapeAdaptor(outputDataType);
5094 const Type outputScaleType = getResult(1).getType();
5095 const ShapeAdaptor outputScaleShape = ShapeAdaptor(outputScaleType);
5096 if (outputDataShape.hasRank() && outputScaleShape.hasRank()) {
5097 SmallVector<int64_t> outputDataDims, outputScaleDims;
5098 outputDataShape.getDims(outputDataDims);
5099 outputScaleShape.getDims(outputScaleDims);
5100
5101 if (outputDataDims.size() != outputScaleDims.size() ||
5103 ArrayRef<int64_t>(outputDataDims).drop_back(1),
5104 ArrayRef<int64_t>(outputScaleDims).drop_back(1))))
5105 return emitOpError() << "require compatible shapes for output_data ("
5106 << outputDataType << ") and " << "output_scale ("
5107 << outputScaleType
5108 << ") except for the last dimension";
5109
5110 const int64_t outputDataLastDim = outputDataDims.back();
5111 const SmallVector<int64_t, 2> dimsToCheck{outputDataLastDim / blockSize,
5112 outputScaleDims.back()};
5113 if (ShapedType::isStatic(outputDataLastDim) &&
5114 failed(verifyCompatibleDims(dimsToCheck)))
5115 return emitOpError()
5116 << "expect last dimension of output_scale ("
5117 << outputScaleDims.back()
5118 << ") to be equal to last dimension of output_data / block_size ("
5119 << outputDataDims.back() / blockSize << ")";
5120 }
5121
5122 return success();
5123}
5124
5125LogicalResult IfOp::inferReturnTypeComponents(
5126 MLIRContext *context, ::std::optional<Location> location,
5127 IfOp::Adaptor adaptor,
5128 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
5129 llvm::SmallVector<tosa::YieldOp> yieldOps;
5130 for (Region *region : adaptor.getRegions()) {
5131 for (auto &block : *region)
5132 if (auto returnOp = dyn_cast<tosa::YieldOp>(block.getTerminator()))
5133 yieldOps.push_back(returnOp);
5134 }
5135
5136 if (yieldOps.empty())
5137 return failure();
5138
5139 // Get the initial type information for the yield op.
5140 llvm::SmallVector<ValueKnowledge> resultKnowledge;
5141 resultKnowledge.reserve(yieldOps.front().getNumOperands());
5142 for (auto operand : yieldOps.front().getOperands()) {
5143 resultKnowledge.push_back(
5144 ValueKnowledge::getKnowledgeFromType(operand.getType()));
5145 }
5146
5147 for (auto yieldOp : yieldOps) {
5148 if (resultKnowledge.size() != yieldOp.getNumOperands())
5149 return failure();
5150
5151 for (const auto &it : llvm::enumerate(yieldOp.getOperands())) {
5152 int32_t index = it.index();
5153 auto meet = ValueKnowledge::meet(
5154 resultKnowledge[index],
5155 ValueKnowledge::getKnowledgeFromType(it.value().getType()));
5156 if (!meet)
5157 continue;
5158 resultKnowledge[index] = meet;
5159 }
5160 }
5161
5162 for (const ValueKnowledge &result : resultKnowledge) {
5163 inferredReturnShapes.push_back(result.getShapedTypeComponents());
5164 }
5165
5166 return success();
5167}
5168
5169LogicalResult WhileOp::inferReturnTypeComponents(
5170 MLIRContext *context, ::std::optional<Location> location,
5171 WhileOp::Adaptor adaptor,
5172 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
5173 llvm::SmallVector<tosa::YieldOp> yieldOps;
5174 for (auto &block : adaptor.getBodyGraph())
5175 if (auto returnOp = dyn_cast<tosa::YieldOp>(block.getTerminator()))
5176 yieldOps.push_back(returnOp);
5177
5178 // TOSA's while must have a tosa.yield as its terminator. If not found this
5179 // tosa.while is invalid.
5180 if (yieldOps.empty())
5181 return failure();
5182
5183 // Get the initial type information from the operand types.
5184 llvm::SmallVector<ValueKnowledge> resultKnowledge;
5185 resultKnowledge.reserve(yieldOps.front().getNumOperands());
5186 for (auto operand : yieldOps.front().getOperands()) {
5187 resultKnowledge.push_back(
5188 ValueKnowledge::getKnowledgeFromType(operand.getType()));
5189 }
5190
5191 for (auto yieldOp : yieldOps) {
5192 if (resultKnowledge.size() != yieldOp.getNumOperands())
5193 return failure();
5194
5195 for (const auto &it : llvm::enumerate(yieldOp.getOperands())) {
5196 int32_t index = it.index();
5197 if (auto meet = ValueKnowledge::meet(
5198 resultKnowledge[index],
5199 ValueKnowledge::getKnowledgeFromType(it.value().getType()))) {
5200 resultKnowledge[index] = meet;
5201 }
5202 }
5203 }
5204
5205 for (const ValueKnowledge &result : resultKnowledge) {
5206 inferredReturnShapes.push_back(result.getShapedTypeComponents());
5207 }
5208
5209 return success();
5210}
5211
5213 Block::BlockArgListType blocksArgs,
5214 ValueRange initializers,
5215 StringRef prefix = "") {
5216 assert(blocksArgs.size() == initializers.size() &&
5217 "expected same length of arguments and initializers");
5218 if (initializers.empty())
5219 return;
5220
5221 parser << prefix << '(';
5222 llvm::interleaveComma(
5223 llvm::zip(blocksArgs, initializers), parser,
5224 [&](auto it) { parser << std::get<0>(it) << " = " << std::get<1>(it); });
5225 parser << ")";
5226}
5227
5228// parse and print of IfOp refer to the implementation of SCF dialect.
5229ParseResult IfOp::parse(OpAsmParser &parser, OperationState &result) {
5230 // Create the regions for 'then'.
5231 result.regions.reserve(2);
5232 Region *thenRegion = result.addRegion();
5233 Region *elseRegion = result.addRegion();
5234
5235 OpAsmParser::UnresolvedOperand cond;
5236
5237 if (parser.parseOperand(cond))
5238 return failure();
5239
5240 SmallVector<OpAsmParser::Argument, 4> regionArgs;
5241 SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
5242
5243 // Parse the optional block arguments
5244 OptionalParseResult listResult =
5245 parser.parseOptionalAssignmentList(regionArgs, operands);
5246 if (listResult.has_value() && failed(listResult.value()))
5247 return failure();
5248
5249 // Parse a colon.
5250 if (failed(parser.parseColon()))
5251 return parser.emitError(parser.getCurrentLocation(),
5252 "expected type for condition operand");
5253
5254 // Parse the type of the condition operand
5255 Type condType;
5256 if (failed(parser.parseType(condType)))
5257 return parser.emitError(parser.getCurrentLocation(),
5258 "expected type for condition operand");
5259
5260 // Resolve operand with provided type
5261 if (failed(parser.resolveOperand(cond, condType, result.operands)))
5262 return failure();
5263
5264 // Parse optional block arg types
5265 if (listResult.has_value()) {
5266 FunctionType functionType;
5267
5268 if (failed(parser.parseType(functionType)))
5269 return parser.emitError(parser.getCurrentLocation())
5270 << "expected list of types for block arguments "
5271 << "followed by arrow type and list of return types";
5272
5273 result.addTypes(functionType.getResults());
5274
5275 if (functionType.getNumInputs() != operands.size()) {
5276 return parser.emitError(parser.getCurrentLocation())
5277 << "expected as many input types as operands " << "(expected "
5278 << operands.size() << " got " << functionType.getNumInputs()
5279 << ")";
5280 }
5281
5282 // Resolve input operands.
5283 if (failed(parser.resolveOperands(operands, functionType.getInputs(),
5284 parser.getCurrentLocation(),
5285 result.operands)))
5286 return failure();
5287 } else {
5288 // Parse optional results type list.
5289 if (parser.parseOptionalArrowTypeList(result.types))
5290 return failure();
5291 }
5292
5293 // Parse the 'then' region.
5294 if (parser.parseRegion(*thenRegion, /*arguments=*/{}, /*argTypes=*/{}))
5295 return failure();
5296
5297 // If we find an 'else' keyword then parse the 'else' region.
5298 if (!parser.parseOptionalKeyword("else")) {
5299 if (parser.parseRegion(*elseRegion, /*arguments=*/{}, /*argTypes=*/{}))
5300 return failure();
5301 }
5302
5303 // Parse the optional attribute list.
5304 if (parser.parseOptionalAttrDict(result.attributes))
5305 return failure();
5306 return success();
5307}
5308
5309void IfOp::print(OpAsmPrinter &p) {
5310 p << " " << getCondition();
5311
5312 printInitializationList(p, getThenGraph().front().getArguments(),
5313 getInputList(), " ");
5314 p << " : ";
5315 p << getCondition().getType();
5316
5317 if (!getInputList().empty()) {
5318 p << " (";
5319 llvm::interleaveComma(getInputList().getTypes(), p);
5320 p << ")";
5321 }
5322 p.printArrowTypeList(getResultTypes());
5323 p << " ";
5324
5325 p.printRegion(getThenGraph());
5326
5327 // Print the 'else' regions if it exists and has a block.
5328 auto &elseRegion = getElseGraph();
5329 if (!elseRegion.empty()) {
5330 p << " else ";
5331 p.printRegion(elseRegion);
5332 }
5333
5334 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
5335}
5336
5337LogicalResult IfOp::verify() {
5338 if (errorIfTypeOrShapeMismatch(*this, getThenGraph().front().getArguments(),
5339 "'then_graph' arguments", getInputList(),
5340 "'input_list'")
5341 .failed())
5342 return failure();
5343
5344 if (errorIfTypeOrShapeMismatch(*this, getElseGraph().front().getArguments(),
5345 "'else_graph' arguments", getInputList(),
5346 "'input_list'")
5347 .failed())
5348 return failure();
5349
5350 // MLIR will verify the absence of the terminator for us if otherwise.
5351 if (getThenGraph().front().mightHaveTerminator()) {
5352 auto thenYield =
5353 dyn_cast<tosa::YieldOp>(getThenGraph().front().getTerminator());
5354 if (thenYield && errorIfTypeOrShapeMismatch(
5355 *this, thenYield.getInputs(), "'then_graph' results",
5356 getOutputList(), "'output_list'")
5357 .failed())
5358 return failure();
5359 }
5360
5361 // MLIR will verify the absence of the terminator for us if otherwise.
5362 if (getElseGraph().front().mightHaveTerminator()) {
5363 auto elseYield =
5364 dyn_cast<tosa::YieldOp>(getElseGraph().front().getTerminator());
5365 if (elseYield && errorIfTypeOrShapeMismatch(
5366 *this, elseYield.getInputs(), "'else_graph' results",
5367 getOutputList(), "'output_list'")
5368 .failed())
5369 return failure();
5370 }
5371
5372 auto condType = getCondition().getType();
5373 if (errorIfShapeNotSizeOne(*this, condType).failed())
5374 return emitOpError() << "'condition' must be a size 1 tensor, got "
5375 << condType;
5376
5377 return success();
5378}
5379
5380LogicalResult WhileOp::verify() {
5381 if (errorIfTypeOrShapeMismatch(*this, getInputList(), "'input_list'",
5382 getOutputList(), "'output_list'")
5383 .failed())
5384 return failure();
5385
5386 if (errorIfTypeOrShapeMismatch(*this, getCondGraph().front().getArguments(),
5387 "'cond_graph' arguments", getInputList(),
5388 "'input_list'")
5389 .failed())
5390 return failure();
5391
5392 if (errorIfTypeOrShapeMismatch(*this, getBodyGraph().front().getArguments(),
5393 "'body_graph' arguments", getInputList(),
5394 "'input_list'")
5395 .failed())
5396 return failure();
5397
5398 if (getBodyGraph().front().mightHaveTerminator()) {
5399 auto bodyYield =
5400 dyn_cast<tosa::YieldOp>(getBodyGraph().front().getTerminator());
5401 if (bodyYield && errorIfTypeOrShapeMismatch(*this, bodyYield.getInputs(),
5402 "'body_graph' results",
5403 getInputList(), "'input_list'")
5404 .failed())
5405 return failure();
5406 }
5407
5408 // Condition block output must be a single element tensor with a single bool
5409 // value.
5410 if (!getCondGraph().front().mightHaveTerminator())
5411 return success();
5412
5413 auto condYield =
5414 dyn_cast<tosa::YieldOp>(getCondGraph().front().getTerminator());
5415 if (!condYield)
5416 return success();
5417
5418 if (condYield.getInputs().size() != 1)
5419 return emitOpError() << "require 'cond_graph' only have one result";
5420
5421 auto condOutType = condYield.getInputs()[0].getType();
5422 if (errorIfShapeNotSizeOne(*this, condOutType).failed())
5423 return emitOpError() << "'cond_graph' result must be a size 1 tensor, got "
5424 << condOutType;
5425
5426 if (!getElementTypeOrSelf(condOutType).isInteger(1))
5427 return emitOpError() << "'cond_graph' result must be a boolean tensor, got "
5428 << condOutType;
5429
5430 return success();
5431}
5432
5433LogicalResult ReverseOp::verify() {
5434 TensorType inputType = getInput1().getType();
5435 int32_t reverseAxis = getAxis();
5436
5437 if (reverseAxis < 0)
5438 return emitOpError("expected non-negative reverse axis");
5439 if (inputType.hasRank()) {
5440 int64_t inputRank = inputType.getRank();
5441 // We allow for a special case where the input/output shape has rank 0 and
5442 // axis is also 0.
5443 if (reverseAxis >= inputRank && (reverseAxis != 0 || inputRank != 0))
5444 return emitOpError("expect input tensor rank (")
5445 << inputRank << ") to be larger than reverse axis (" << reverseAxis
5446 << ")";
5447 }
5448
5449 return success();
5450}
5451
5452LogicalResult tosa::SelectOp::verify() {
5453 // verify input2 and input3 have same element type as output
5454 if (verifySameElementTypes(*this, /* inType = */ getOnTrue().getType(),
5455 /* outType = */ getOutput().getType())
5456 .failed() ||
5457 verifySameElementTypes(*this, /* inType = */ getOnFalse().getType(),
5458 /* outType = */ getOutput().getType())
5459 .failed()) {
5460 return failure();
5461 }
5462 // verify input1 has element type of bool
5463 auto predicateType = llvm::dyn_cast<ShapedType>(getPred().getType());
5464 if (!predicateType) {
5465 return emitOpError("expect shaped tensor for input1, got ")
5466 << getInput1().getType();
5467 }
5468 auto predicateElementType = predicateType.getElementType();
5469 if (!predicateElementType.isInteger(1)) {
5470 return emitOpError("expect element type of bool for input1, got ")
5471 << predicateElementType;
5472 }
5473
5474 return success();
5475}
5476
5477LogicalResult tosa::VariableReadOp::verify() {
5478 if (verifyVariableOpErrorIf(*this, getOutput1().getType(), "'output1'")
5479 .failed())
5480 return failure();
5481
5482 return success();
5483}
5484
5485LogicalResult tosa::VariableWriteOp::verify() {
5486 if (verifyVariableOpErrorIf(*this, getInput1().getType(), "'input1'")
5487 .failed())
5488 return failure();
5489
5490 return success();
5491}
5492
5493// parse and print of WhileOp refer to the implementation of SCF dialect.
5494ParseResult WhileOp::parse(OpAsmParser &parser, OperationState &result) {
5495 SmallVector<OpAsmParser::Argument, 4> regionArgs;
5496 SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
5497 Region *cond = result.addRegion();
5498 Region *body = result.addRegion();
5499
5500 OptionalParseResult listResult =
5501 parser.parseOptionalAssignmentList(regionArgs, operands);
5502 if (listResult.has_value() && failed(listResult.value()))
5503 return failure();
5504
5505 FunctionType functionType;
5506 SMLoc typeLoc = parser.getCurrentLocation();
5507 if (failed(parser.parseColonType(functionType)))
5508 return failure();
5509
5510 result.addTypes(functionType.getResults());
5511
5512 if (functionType.getNumInputs() != operands.size()) {
5513 return parser.emitError(typeLoc)
5514 << "expected as many input types as operands " << "(expected "
5515 << operands.size() << " got " << functionType.getNumInputs() << ")";
5516 }
5517
5518 // Resolve input operands.
5519 if (failed(parser.resolveOperands(operands, functionType.getInputs(),
5520 parser.getCurrentLocation(),
5521 result.operands)))
5522 return failure();
5523
5524 // Propagate the types into the region arguments.
5525 for (size_t i = 0, e = regionArgs.size(); i != e; ++i)
5526 regionArgs[i].type = functionType.getInput(i);
5527
5528 return failure(parser.parseRegion(*cond, regionArgs) ||
5529 parser.parseKeyword("do") || parser.parseRegion(*body) ||
5530 parser.parseOptionalAttrDictWithKeyword(result.attributes));
5531}
5532
5533void WhileOp::print(OpAsmPrinter &parser) {
5534 printInitializationList(parser, getCondGraph().front().getArguments(),
5535 getInputList(), " ");
5536 parser << " : ";
5537 parser.printFunctionalType(getInputList().getTypes(),
5538 getResults().getTypes());
5539 parser << ' ';
5540 parser.printRegion(getCondGraph(), /*printEntryBlockArgs=*/false);
5541 parser << " do ";
5542 parser.printRegion(getBodyGraph());
5544 (*this)->getDiscardableAttrDictionary().getValue());
5545}
5546
5547// Create a rank-1 const tensor for zero point of the source tensor.
5548std::optional<Value> mlir::tosa::createZeroPointTensor(OpBuilder &builder,
5549 Location loc,
5550 Type srcElemType,
5551 int64_t zp) {
5552 srcElemType = getStorageElementTypeOrSelf(srcElemType);
5553 auto zpType = mlir::RankedTensorType::get({1}, srcElemType);
5554 if (llvm::isa<FloatType>(srcElemType)) {
5555 auto zpAttr = DenseElementsAttr::get(
5556 zpType, builder.getFloatAttr(srcElemType, static_cast<double>(zp)));
5557 return tosa::ConstOp::create(builder, loc, zpType, zpAttr);
5558 }
5559 if (llvm::isa<IntegerType>(srcElemType)) {
5560 auto zpAttr =
5561 DenseElementsAttr::get(zpType, builder.getIntegerAttr(srcElemType, zp));
5562 return tosa::ConstOp::create(builder, loc, zpType, zpAttr);
5563 }
5564 llvm::errs() << "zero point is not allowed for unsupported data types\n";
5565 return std::nullopt;
5566}
5567
5568//===----------------------------------------------------------------------===//
5569// TOSA Shape and Shape Operators Helper functions.
5570//===----------------------------------------------------------------------===//
5571
5573 return mlir::isa<tosa::shapeType>(t);
5574}
5575
5576LogicalResult
5577mlir::tosa::shapeType::verify(function_ref<InFlightDiagnostic()> emitError,
5578 int rank) {
5579 if (rank < 0)
5580 return emitError() << "invalid rank (must be >= 0): " << rank;
5581 return success();
5582}
5583
5585 for (auto v : op->getOperands()) {
5586 if (mlir::isa<::mlir::tosa::shapeType>(v.getType())) {
5587 Operation *definingOp = v.getDefiningOp();
5588 if (!definingOp || !definingOp->hasTrait<TosaShapeOperator>()) {
5589 return op->emitOpError("shape operand is not compile time resolvable");
5590 }
5591 }
5592 }
5593 return success();
5594}
5595
5596LogicalResult
5598 if (failed(OpTrait::impl::verifyAtLeastNOperands(op, 1)))
5599 return failure();
5600
5601 // delegate function that returns rank of shape type
5602 auto getRank = [](const Type type) {
5603 return mlir::cast<mlir::tosa::shapeType>(type).getRank();
5604 };
5605 auto operandTypes = op->getOperandTypes();
5606 auto resultTypes = op->getResultTypes();
5607
5608 auto rank = getRank(*op->getOperandTypes().begin());
5609 for (auto type : operandTypes) {
5610 if (getRank(type) != rank) {
5611 return op->emitOpError("operands don't have matching ranks");
5612 }
5613 }
5614 for (auto type : resultTypes) {
5615 if (getRank(type) != rank) {
5616 return op->emitOpError("result shape has different rank than operands");
5617 }
5618 }
5619 return success();
5620}
5621
5622//===----------------------------------------------------------------------===//
5623// TOSA Shape Operators verify functions.
5624//===----------------------------------------------------------------------===//
5625
5626LogicalResult tosa::ConstShapeOp::verify() {
5627 // check one dimensional rank
5628 auto valuesRank = getValues().getType().getRank();
5629 if (valuesRank != 1)
5630 return emitOpError("expect elements in attribute values with rank 1");
5631 // check that number of elements in values attr equal to rank of result shape
5632 auto count = getValues().getNumElements();
5633 auto rank = (cast<tosa::shapeType>(getResult().getType())).getRank();
5634 if (count != rank && (count != 1 || rank != 0)) {
5635 return emitOpError("expect number of elements in attribute values (")
5636 << count << ") to be equal to the rank (" << rank
5637 << ") for the result shape type";
5638 }
5639 return success();
5640}
5641
5642LogicalResult tosa::DimOp::verify() {
5643 const tosa::shapeType outShapeType =
5644 cast<tosa::shapeType>(getResult().getType());
5645 if (outShapeType.getRank() != 1)
5646 return emitOpError("expect output shape type to contain one element, got ")
5647 << outShapeType;
5648
5649 const ShapeAdaptor inputType(getInput1().getType());
5650 if (inputType.hasRank()) {
5651 const int64_t inputRank = inputType.getRank();
5652 const int64_t axis = getAxisAttr().getInt();
5653 if (axis < 0 || axis >= inputRank)
5654 return emitOpError("expect axis to be in the range [0, ")
5655 << inputRank << "), got " << axis;
5656 }
5657 return success();
5658}
5659
5660LogicalResult tosa::ConcatShapeOp::verify() {
5661 const tosa::shapeType outShapeType =
5662 cast<tosa::shapeType>(getResult().getType());
5663 const int64_t outputRank = outShapeType.getRank();
5664 const Operation::operand_range inputList = getInput();
5665
5666 if (inputList.size() == 0)
5667 return emitOpError("requires at least one input shape");
5668
5669 if (llvm::any_of(inputList, [](Value v) {
5670 return cast<tosa::shapeType>(v.getType()).getRank() == 0;
5671 }))
5672 return emitOpError("requires all inputs shapes have a rank greater than 0");
5673
5674 const int64_t inputsRank =
5675 llvm::accumulate(inputList, 0, [](int64_t acc, const Value &input) {
5676 const tosa::shapeType inShapeType =
5677 cast<tosa::shapeType>(input.getType());
5678 return acc + inShapeType.getRank();
5679 });
5680 if (outputRank != inputsRank)
5681 return emitOpError("requires output shape rank to be equal to the sum of "
5682 "the input shape ranks (")
5683 << inputsRank << "), got " << outputRank;
5684
5685 return success();
5686}
5687
5688LogicalResult tosa::SliceShapeOp::verify() {
5689 std::optional<int32_t> start;
5690 DenseIntElementsAttr startAttr;
5691 if (matchPattern(getStart(), m_Constant(&startAttr)))
5692 start = startAttr.getValues<int32_t>()[0];
5693 if (start && start.value() < 0)
5694 return emitOpError("expected non-negative start index, got ")
5695 << start.value();
5696
5697 std::optional<int32_t> size;
5698 DenseIntElementsAttr sizeAttr;
5699 if (matchPattern(getSize(), m_Constant(&sizeAttr)))
5700 size = sizeAttr.getValues<int32_t>()[0];
5701 if (size && size.value() <= 0)
5702 return emitOpError("expected positive size, got ") << size.value();
5703
5704 if (!size)
5705 return success();
5706
5707 const tosa::shapeType outShapeType =
5708 cast<tosa::shapeType>(getResult().getType());
5709 const int64_t outputRank = outShapeType.getRank();
5710 if (outputRank != size)
5711 return emitOpError(
5712 "expected output type size to be equal to size attribute, got ")
5713 << outputRank << " vs " << size.value();
5714
5715 if (!start)
5716 return success();
5717
5718 const tosa::shapeType inShapeType =
5719 cast<tosa::shapeType>(getInput().getType());
5720 const int64_t inputRank = inShapeType.getRank();
5721 const int64_t sliceSize = start.value() + size.value();
5722 if (sliceSize > inputRank)
5723 return emitOpError("expected start + size to be less than or equal to "
5724 "input shape rank (")
5725 << inputRank << "), got " << sliceSize;
5726
5727 return success();
5728}
5729
5730//===----------------------------------------------------------------------===//
5731// TOSA Attribute Definitions.
5732//===----------------------------------------------------------------------===//
5733
5734#define GET_ATTRDEF_CLASSES
5735#include "mlir/Dialect/Tosa/IR/TosaAttributes.cpp.inc"
5736
5737//===----------------------------------------------------------------------===//
5738// TOSA Type Definitions.
5739//===----------------------------------------------------------------------===//
5740#define GET_TYPEDEF_CLASSES
5741#include "mlir/Dialect/Tosa/IR/TosaOpsTypesBase.cpp.inc"
5742
5743//===----------------------------------------------------------------------===//
5744// TOSA Operator Definitions.
5745//===----------------------------------------------------------------------===//
5746
5747static ParseResult parseOptionalBoolClause(OpAsmParser &parser,
5748 StringRef keyword,
5749 BoolAttr &result) {
5750 if (failed(parser.parseOptionalKeyword(keyword)))
5751 return success();
5752 if (parser.parseLParen() || parser.parseAttribute(result) ||
5753 parser.parseRParen())
5754 return failure();
5755 return success();
5756}
5757
5758static void printOptionalBoolClause(OpAsmPrinter &printer, StringRef keyword,
5759 BoolAttr attr) {
5760 if (!attr)
5761 return;
5762 printer << keyword << '(';
5763 printer.printAttribute(attr);
5764 printer << ')';
5765}
5766
5767static ParseResult parseLocalBound(OpAsmParser &parser, BoolAttr &result) {
5768 return parseOptionalBoolClause(parser, "local_bound", result);
5769}
5770
5771static void printLocalBound(OpAsmPrinter &printer, Operation *, BoolAttr attr) {
5772 printOptionalBoolClause(printer, "local_bound", attr);
5773}
5774
5775static ParseResult parseInputUnsigned(OpAsmParser &parser, BoolAttr &result) {
5776 return parseOptionalBoolClause(parser, "input_unsigned", result);
5777}
5778
5780 BoolAttr attr) {
5781 printOptionalBoolClause(printer, "input_unsigned", attr);
5782}
5783
5784#define GET_OP_CLASSES
5785#include "mlir/Dialect/Tosa/IR/TosaOps.cpp.inc"
return success()
static void printInitializationList(OpAsmPrinter &p, Block::BlockArgListType blocksArgs, ValueRange initializers, StringRef prefix="")
Prints the initialization list in the form of <prefix>(inner = outer, inner2 = outer2,...
Definition SCF.cpp:500
true
Given two iterators into the same block, return "true" if a is before `b.
static bool isLegalToInline(InlinerInterface &interface, Region *src, Region *insertRegion, bool shouldCloneInlinedRegion, IRMapping &valueMapping)
Utility to check that all of the operations within 'src' can be inlined.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
b getContext())
static Type getValueType(Attribute attr)
Definition SPIRVOps.cpp:846
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
Definition SPIRVOps.cpp:230
static LogicalResult verifyMatMulShapes(T op, bool transposeB)
Definition TosaOps.cpp:2049
static ParseResult parseOptionalBoolClause(OpAsmParser &parser, StringRef keyword, BoolAttr &result)
Definition TosaOps.cpp:5747
static void printShapeToDiagnostic(InFlightDiagnostic &diag, ArrayRef< int64_t > shape)
Definition TosaOps.cpp:340
static void buildMatMulOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value a, Value b)
Definition TosaOps.cpp:1352
static LogicalResult verifySameElementTypes(Operation *op, Type aType, Type bType, StringRef aName="input", StringRef bName="output")
Definition TosaOps.cpp:980
static ParseResult parseLocalBound(OpAsmParser &parser, BoolAttr &result)
Definition TosaOps.cpp:5767
LogicalResult inferConvReturnTypeComponents(AdaptorT adaptor, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
Definition TosaOps.cpp:4216
static int64_t getMatMulBatchDim(const ShapeAdaptor &shape, int64_t outputRank, int64_t axis)
Definition TosaOps.cpp:1908
static SmallVector< int64_t > convertToMlirShape(ArrayRef< int64_t > shape)
Definition TosaOps.cpp:134
static LogicalResult ReduceInferReturnTypes(ShapeAdaptor operandShape, Type inputType, IntegerAttr axis, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
Definition TosaOps.cpp:3764
static void printScaleValues(AsmPrinter &printer, ArrayRef< Attribute > scaleValues, Type)
Definition TosaOps.cpp:537
static void buildAvgPool2dAdaptiveOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value input, DenseI64ArrayAttr kernel, DenseI64ArrayAttr stride, DenseI64ArrayAttr pad, TypeAttr accType)
This builder mirrors avg_pool2d quant-info handling and materializes kernel/stride/pad as const_shape...
Definition TosaOps.cpp:1412
static LogicalResult verifyRescaleValueAndZpTypes(Operation *op, Value val, Value valZp, StringRef name)
Definition TosaOps.cpp:280
static void printOptionalBoolClause(OpAsmPrinter &printer, StringRef keyword, BoolAttr attr)
Definition TosaOps.cpp:5758
static LogicalResult errorIfShapeNotSizeOne(Operation *op, Type type)
Definition TosaOps.cpp:945
static void printLocalBound(OpAsmPrinter &printer, Operation *, BoolAttr attr)
Definition TosaOps.cpp:5771
LogicalResult argMaxMinVerify(T op)
Definition TosaOps.cpp:619
static LogicalResult verifyMatMulZeroPointType(T op, Value input, Value zp, StringRef inputName, StringRef zpName)
Definition TosaOps.cpp:2013
static ParseResult parseScaleValues(AsmParser &parser, SmallVector< Attribute > &scaleValues, Type scaleType)
Definition TosaOps.cpp:508
static ParseResult parseInputUnsigned(OpAsmParser &parser, BoolAttr &result)
Definition TosaOps.cpp:5775
#define REDUCE_SHAPE_INFER(OP)
Definition TosaOps.cpp:3789
static LogicalResult verifyConvOp(T op)
Definition TosaOps.cpp:650
static LogicalResult verifyAvgPoolCommonTypeAndZpChecks(T op)
Definition TosaOps.cpp:1120
static LogicalResult verifyVariableOpErrorIf(T op, Type type, StringRef name)
Definition TosaOps.cpp:954
static LogicalResult poolingInferReturnTypes(ShapeAdaptor inputShape, ArrayRef< int64_t > kernel, ArrayRef< int64_t > stride, ArrayRef< int64_t > pad, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
Definition TosaOps.cpp:3979
static void buildPadOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value input, Value paddings)
This builder is called on TOSA pad operator that needs to create its own OptionalAttr quantization_at...
Definition TosaOps.cpp:1499
static LogicalResult verifyPoolingOpImpl(Operation *op, ArrayRef< int64_t > kernel, ArrayRef< int64_t > strides, ArrayRef< int64_t > padding, Value input, Value output)
Definition TosaOps.cpp:1019
static std::optional< int64_t > idivCheck(const int64_t lhs, const int64_t rhs)
Definition TosaOps.cpp:263
static void buildVariableOp(OpBuilder &builder, OperationState &result, StringRef name, Type variableType, Attribute initialValue)
Definition TosaOps.cpp:1513
static void buildMatMulLikeOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value a, Value b)
Definition TosaOps.cpp:1327
LogicalResult verifyConvOutputSize(Operation *op, const int64_t inputSize, const int64_t kernelSize, const int64_t outputSize, const int64_t padBefore, const int64_t padAfter, const int64_t stride, const int64_t dilation, const llvm::StringRef dimName, const llvm::StringRef dimAxis, const llvm::StringRef padBeforeName, const llvm::StringRef padAfterName)
Definition TosaOps.cpp:369
static LogicalResult verifyReduceOp(T op)
Definition TosaOps.cpp:3814
#define NARY_SHAPE_INFER(OP)
Definition TosaOps.cpp:3882
#define ZERO_POINT_HELPER(OP, OPERAND_NAME, SIGN_EXTEND)
Definition TosaOps.cpp:3064
static void buildTransConvOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value input, Value weight, Value bias, DenseI64ArrayAttr outpad, DenseI64ArrayAttr stride, TypeAttr accType)
Handles tosa.transpose_conv2d which has outpad and output shape attributes.
Definition TosaOps.cpp:1309
LogicalResult inferArgMaxMinReturnTypeComponents(MLIRContext *context, ::std::optional< Location > location, A adaptor, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
Definition TosaOps.cpp:590
static void extractAdaptivePoolingConstShapeOperands(T op, AdaptivePoolingConstShapeValues &values)
Definition TosaOps.cpp:1178
static LogicalResult verifyConvOpErrorIf(T op)
Definition TosaOps.cpp:800
static FailureOr< int64_t > getZeroPoint(Value val, bool signExtend)
Definition TosaOps.cpp:2995
static constexpr bool IsSupportedAdaptivePoolConstShapeVerifyOp
Definition TosaOps.cpp:1171
LogicalResult tryUpdateDimOrFailure(Operation *op, int64_t &currDim, const int64_t newDim, const StringRef operandName, const StringRef dimName)
Definition TosaOps.cpp:325
static LogicalResult NAryInferReturnTypes(const ValueShapeRange &operands, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
Definition TosaOps.cpp:3870
#define COMPATIBLE_RETURN_TYPES(OP)
Definition TosaOps.cpp:3780
static LogicalResult resolveBroadcastShape(const ValueShapeRange &operands, SmallVector< int64_t > &outShape)
Definition TosaOps.cpp:1557
static LogicalResult verifyMatMulQuantizedOperandsType(T op, Type aElementType, Type bElementType)
Definition TosaOps.cpp:1986
static LogicalResult verifyOutputShapeCompatibleWithExpected(Operation *op, ShapedType outputType, ArrayRef< int64_t > expectedShape, StringRef outputName="output")
Definition TosaOps.cpp:353
static void printInputUnsigned(OpAsmPrinter &printer, Operation *, BoolAttr attr)
Definition TosaOps.cpp:5779
static void buildNegateOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value input)
This builder is called on single-parameter negate operator to construct input and output zero points ...
Definition TosaOps.cpp:1459
static void buildConvOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value input, Value weight, Value bias, DenseI64ArrayAttr pad, DenseI64ArrayAttr stride, DenseI64ArrayAttr dilation, TypeAttr accType)
This builder is called on all convolution operators except TransposeConv, which has specialized outpu...
Definition TosaOps.cpp:1285
static SmallVector< int64_t > getMatMulBatchShape(const ShapeAdaptor &shape)
Definition TosaOps.cpp:2038
static void buildAvgPool2dOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value input, DenseArrayAttr kernel, DenseArrayAttr stride, DenseArrayAttr pad, TypeAttr accType)
Both the tosa.avg_pool2d and unary ops use the same UnaryOpQuantizationAttr but avg_pool operator has...
Definition TosaOps.cpp:1368
static LogicalResult errorIfTypeOrShapeMismatch(Operation *op, Type type1, StringRef name1, Type type2, StringRef name2)
Definition TosaOps.cpp:903
static LogicalResult inferMatMulReturnTypeComponents(const ShapeAdaptor &aShape, const ShapeAdaptor &bShape, bool transposeB, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
Definition TosaOps.cpp:1944
static void buildMatMulTOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value a, Value b)
Definition TosaOps.cpp:1358
static FailureOr< SmallVector< int64_t > > resolveMatMulOutputShape(const ShapeAdaptor &aShape, const ShapeAdaptor &bShape, int64_t outputRank, bool transposeB)
Definition TosaOps.cpp:1917
static FailureOr< int64_t > resolveBroadcastDim(const int64_t dim1, const int64_t dim2)
Definition TosaOps.cpp:1543
static LogicalResult verifyZeroPoint(T op, Value val, const int64_t &zp, const std::string &operand)
Definition TosaOps.cpp:3022
static LogicalResult verifyPoolingOp(T op)
Definition TosaOps.cpp:1114
static LogicalResult verifyDimIsPowerOfTwo(Operation *op, const int64_t dimSize, const llvm::StringRef dimName)
Definition TosaOps.cpp:1634
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition Traits.cpp:117
static void updateIfDynamic(int64_t &current, int64_t candidate)
Definition TosaOps.cpp:4018
void inferWeightShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &weightSpatial)
Definition TosaOps.cpp:4111
LogicalResult getSpatialParameters(SmallVector< int64_t > &padValues, SmallVector< int64_t > &strideValues, SmallVector< int64_t > &dilationValues)
Definition TosaOps.cpp:4140
void inferInputShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &inputSpatial)
Definition TosaOps.cpp:4085
ConvInferShapeAdaptor(Conv2DBlockScaledOp::Adaptor adaptor)
Definition TosaOps.cpp:4082
void inferInputShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &inputSpatial)
Definition TosaOps.cpp:4031
void inferWeightShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &weightSpatial)
Definition TosaOps.cpp:4046
ConvInferShapeAdaptor(Conv2DOp::Adaptor adaptor)
Definition TosaOps.cpp:4028
LogicalResult getSpatialParameters(SmallVector< int64_t > &padValues, SmallVector< int64_t > &strideValues, SmallVector< int64_t > &dilationValues)
Definition TosaOps.cpp:4064
void inferWeightShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &weightSpatial)
Definition TosaOps.cpp:4181
ConvInferShapeAdaptor(Conv3DOp::Adaptor adaptor)
Definition TosaOps.cpp:4161
void inferInputShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &inputSpatial)
Definition TosaOps.cpp:4164
LogicalResult getSpatialParameters(SmallVector< int64_t > &padValues, SmallVector< int64_t > &strideValues, SmallVector< int64_t > &dilationValues)
Definition TosaOps.cpp:4201
This base class exposes generic asm parser hooks, usable across the various derived parsers.
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseOptionalEqual()=0
Parse a = token if present.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
MLIRContext * getContext() const
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseOptionalColon()=0
Parse a : token if present.
virtual ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result)=0
Parse a named dictionary into 'result' if the attributes keyword is present.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseColon()=0
Parse a : token.
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseOptionalArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an optional arrow followed by a type list.
virtual ParseResult parseFloat(double &result)=0
Parse a floating point value from the stream.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
This base class exposes generic asm printer hooks, usable across the various derived printers.
virtual void printAttributeWithoutType(Attribute attr)
Print the given attribute without its type.
virtual void printAttribute(Attribute attr)
void printArrowTypeList(TypeRange &&types)
Attributes are known-constant values of operations.
Definition Attributes.h:25
MutableArrayRef< BlockArgument > BlockArgListType
Definition Block.h:110
Special case of IntegerAttr to represent boolean integers, i.e., signless i1 integers.
bool getValue() const
Return the boolean value of this attribute.
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
FloatAttr getFloatAttr(Type type, double value)
Definition Builders.cpp:263
IntegerType getI32Type()
Definition Builders.cpp:71
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:75
BoolAttr getBoolAttr(bool value)
Definition Builders.cpp:108
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
DenseIntElementsAttr getIndexTensorAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:201
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.
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
An attribute that represents a reference to a dense integer vector or tensor object.
This class contains all of the information necessary to report a diagnostic to the DiagnosticEngine.
virtual InFlightDiagnostic emitError(const Twine &msg={}) const =0
Emit an error to the reader.
ImplicitLocOpBuilder maintains a 'current location', allowing use of the create<> method without spec...
Definition Builders.h:632
This class represents a diagnostic that is inflight and set to be reported.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual OptionalParseResult parseOptionalAssignmentList(SmallVectorImpl< Argument > &lhs, SmallVectorImpl< UnresolvedOperand > &rhs)=0
virtual ParseResult parseRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDictWithKeyword(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary prefixed with 'attribute...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
void printFunctionalType(Operation *op)
Print the complete type of an operation in functional form.
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
This class helps build Operations.
Definition Builders.h:210
This class indicates that op operates on tosa shape types.
Definition TosaOps.h:73
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
ResultRange result_range
Support result iteration.
Definition Operation.h:437
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
OperandRange operand_range
Definition Operation.h:398
operand_type_range getOperandTypes()
Definition Operation.h:424
result_type_range getResultTypes()
Definition Operation.h:455
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
ParseResult value() const
Access the internal ParseResult value.
bool has_value() const
Returns true if we contain a valid ParseResult value.
Type-safe wrapper around a void* for passing properties, including the properties structs of operatio...
This class provides an abstraction over the different types of ranges over Regions.
Definition Region.h:363
bool empty()
Definition Region.h:60
This diagnostic handler is a simple RAII class that registers and erases a diagnostic handler on a gi...
Adaptor class to abstract the differences between whether value is from a ShapedType or ShapedTypeCom...
bool isDynamicDim(int index) const
Returns whether the index'th dimension is dynamic.
int64_t getDimSize(int index) const
Returns the size of the index'th dimension.
int64_t getRank() const
Returns the rank of the shape.
bool hasStaticShape() const
Returns whether the shape is fully static.
int64_t getNumElements() const
Returns the number of elements in the shape.
void getDims(SmallVectorImpl< int64_t > &res) const
Populates the dimensions from shape referenced.
bool hasRank() const
Returns whether the shape has a rank.
ShapedTypeComponents that represents the components of a ShapedType.
This class allows for representing and managing the symbol table used by operations with the 'SymbolT...
Definition SymbolTable.h:25
Operation * lookup(StringRef name) const
Look up a symbol with the specified name, returning null if no such name exists.
Tensor types represent multi-dimensional arrays, and have two variants: RankedTensorType and Unranked...
ArrayRef< int64_t > getShape() const
Returns the shape of this tensor type.
bool hasRank() const
Returns if this type is ranked, i.e. it has a known number of dimensions.
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
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
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
type_range getTypes() const
Range of values and shapes (corresponding effectively to Shapes dialect's ValueShape type concept).
ShapeAdaptor getShape(int index) const
Returns the shape of index'th operand.
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
LogicalResult verifyAtLeastNOperands(Operation *op, unsigned numOperands)
LogicalResult verifyTosaShapeOperatorWithSameRanks(Operation *op)
Definition TosaOps.cpp:5597
LogicalResult verifyTosaResolvableShapeOperands(Operation *op)
Definition TosaOps.cpp:5584
bool getBroadcastedShape(ArrayRef< int64_t > shape1, ArrayRef< int64_t > shape2, SmallVectorImpl< int64_t > &resultShape)
Returns true and sets resultShape to the broadcasted shape from the two given shapes if they are broa...
Definition Traits.cpp:59
LogicalResult convertFloatTypeFromAttribute(Type type, Attribute attr, llvm::SmallVectorImpl< char > &result)
Float type implementation of DenseElementTypeInterface::convertFromAttribute.
Attribute convertFloatTypeToAttribute(Type type, llvm::ArrayRef< char > rawData)
Float type implementation of DenseElementTypeInterface::convertToAttribute.
Operation::operand_range getIndices(Operation *op)
Get the indices that the given load/store operation is operating on.
Definition Utils.cpp:18
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
SmallVector< unsigned > getBlockSize(AffineMap dimToLvl)
Given the dimToLvl map, returns the block sizes in a vector.
ConvOpQuantizationAttr buildConvOpQuantizationAttr(OpBuilder &builder, Value input, Value weight)
Method to build ConvOpQuantizationAttr, called from ConvOpQuantInfoBuilder/TransConvOpQuantInfoBuilde...
Type getStorageElementTypeOrSelf(Type type)
Definition TosaOps.cpp:269
RankedTensorType getVariableType(VariableOp variableOp)
Type buildConvOpResultTypeInfo(OpBuilder &builder, Type outputType, Value input, Value weight)
construct ConvOp output type with correct bitwidth based on input/weight width.
ParseResult parseVariableOpTypeOrInitialValue(OpAsmParser &parser, DenseElementsAttr &varShapeAttr, TypeAttr &typeAttr, Attribute &initialValueAttr)
Definition TosaOps.cpp:211
PadOpQuantizationAttr buildPadOpQuantizationAttr(OpBuilder &builder, Value input)
Builds PadOpQuantizationAttr, called from PadOpQuantInfoBuilder: inputZp: input zeropoint.
std::pair< Value, Value > createZPsAsConst(OpBuilder &builder, Value input, Value weight)
void printVariableOpTypeOrInitialValue(OpAsmPrinter &p, Operation *op, DenseElementsAttr varShapeAttr, TypeAttr typeAttr, Attribute initialValueAttr)
Definition TosaOps.cpp:236
FailureOr< T > getConstantScalarIntValue(Value val)
Value getTosaConstShape(ImplicitLocOpBuilder &builder, llvm::ArrayRef< int64_t > shape)
MatMulOpQuantizationAttr buildMatMulOpQuantizationAttr(OpBuilder &builder, Value a, Value b)
Builds MatMulOpQuantizationAttr, called from MatMulOpQuantInfoBuilder: aZp: input a zeropoint bZp: in...
unsigned getBitWidth(Type type)
Definition TosaOps.cpp:315
std::optional< Value > createZeroPointTensor(OpBuilder &builder, Location loc, Type srcElemType, int64_t zp=0)
Definition TosaOps.cpp:5548
bool isa_tosa_shape_type(mlir::Type t)
Definition TosaOps.cpp:5572
SmallVector< int64_t > convertFromMlirShape(ArrayRef< int64_t > shape)
UnaryOpQuantizationAttr buildUnaryOpQuantizationAttr(OpBuilder &builder, Value input, Type outputRawType)
Builds UnaryOpQuantizationAttr UnaryOpQuantInfoBuilder: inputZp: input zeropoint outputZp: output zer...
Type getStorageElementTypeFromQuantized(quant::QuantizedType quantizedType)
Value createPadConstTensor(OpBuilder &builder, Location loc, Value src, int32_t val=0)
Definition TosaOps.cpp:300
LogicalResult verifyBlockScaledTensorType(mlir::Type type, llvm::function_ref< mlir::InFlightDiagnostic()> emitError=nullptr, bool allowScaleValues=false)
Definition TosaOps.cpp:428
std::string getTosaTensorTypeErrorMessage(mlir::Type type)
Definition TosaOps.cpp:493
bool getConstShapeValues(Operation *op, llvm::SmallVector< int64_t > &result_shape)
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
LogicalResult verifyCompatibleShapes(TypeRange types1, TypeRange types2)
Returns success if the given two arrays have the same number of elements and each pair wise entries h...
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
LogicalResult emitOptionalError(std::optional< Location > loc, Args &&...args)
Overloads of the above emission functions that take an optionally null location.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
SmallVector< SmallVector< OpFoldResult > > ReifiedRankedShapedTypeDims
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
LogicalResult verifyCompatibleDims(ArrayRef< int64_t > dims)
Dimensions are compatible if all non-dynamic dims are equal.
LogicalResult verifyRanksMatch(Operation *op, ShapedType lhs, ShapedType rhs, StringRef lhsName, StringRef rhsName)
Verify that two shaped types have matching ranks.
LogicalResult verifyCompatibleShape(ArrayRef< int64_t > shape1, ArrayRef< int64_t > shape2)
Returns success if the given two shapes are compatible.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
bool isPermutationVector(ArrayRef< int64_t > interchange)
Method to check if an interchange vector is a permutation.
This represents an operation in an abstracted form, suitable for use with the builder APIs.
static ValueKnowledge meet(const ValueKnowledge &lhs, const ValueKnowledge &rhs)
Definition ShapeUtils.h:136
static ValueKnowledge getKnowledgeFromType(Type type)
Definition ShapeUtils.h:45