29#include "llvm/ADT/APFloat.h"
30#include "llvm/ADT/SmallVectorExtras.h"
38#include "mlir/Dialect/Tosa/IR/TosaOpsDialect.cpp.inc"
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"
53struct TosaInlinerInterface :
public DialectInlinerInterface {
54 using DialectInlinerInterface::DialectInlinerInterface;
62 IRMapping &map)
const final {
68 IRMapping &map)
const final {
69 return (isa<tosa::IfOp>(dest->getParentOp()) ||
70 isa<tosa::WhileOp>(dest->getParentOp()));
75struct TosaDialectBytecodeInterface :
public BytecodeDialectInterface {
76 TosaDialectBytecodeInterface(Dialect *dialect)
77 : BytecodeDialectInterface(dialect) {}
82 Attribute readAttribute(DialectBytecodeReader &reader)
const override {
86 LogicalResult writeAttribute(Attribute attr,
87 DialectBytecodeWriter &writer)
const override {
88 return ::writeAttribute(attr, writer);
94 Type readType(DialectBytecodeReader &reader)
const override {
98 LogicalResult writeType(Type type,
99 DialectBytecodeWriter &writer)
const override {
100 return ::writeType(type, writer);
103 void writeVersion(DialectBytecodeWriter &writer)
const final {
107 std::unique_ptr<DialectVersion>
108 readVersion(DialectBytecodeReader &reader)
const final {
110 reader.
emitError(
"Dialect does not support versioning");
114 LogicalResult upgradeFromVersion(Operation *topLevelOp,
115 const DialectVersion &version)
const final {
127 return {&getBodyGraph()};
136 return dim == -1 ? ShapedType::kDynamic : dim;
142 Type elementType = variableOp.getType();
145 return RankedTensorType::get(
shape, elementType);
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>();
168 if (llvm::isa<shapeType>(type) && llvm::isa<DenseIntElementsAttr>(value)) {
169 return tosa::ConstShapeOp::create(builder, loc, type,
170 llvm::cast<DenseIntElementsAttr>(value));
172 if (llvm::isa<ElementsAttr>(value))
173 return tosa::ConstOp::create(builder, loc, type,
174 llvm::cast<ElementsAttr>(value));
184ParseResult getShapeAndElementType(
OpAsmParser &parser,
Type parsedType,
186 TypeAttr &typeAttr) {
187 if (
auto shapedType = dyn_cast<ShapedType>(parsedType)) {
188 if (!shapedType.hasRank())
190 <<
"expected ranked type";
192 auto elementType = shapedType.getElementType();
193 typeAttr = TypeAttr::get(elementType);
200 <<
"expected shaped type";
217 <<
"expected attribute";
219 if (
auto typedAttr = dyn_cast<TypedAttr>(initialValueAttr)) {
220 return getShapeAndElementType(parser, typedAttr.getType(), varShapeAttr,
224 <<
"expected Typed attr";
227 initialValueAttr =
nullptr;
231 <<
"expected type after colon";
233 return getShapeAndElementType(parser, parsedType, varShapeAttr, typeAttr);
238 TypeAttr typeAttr,
Attribute initialValueAttr) {
239 bool needsSpace =
false;
240 if (!dyn_cast_or_null<TypedAttr>(initialValueAttr)) {
243 Type elementType = typeAttr.getValue();
244 RankedTensorType tensorType =
246 auto tensorTypeAttr = TypeAttr::get(tensorType);
251 if (initialValueAttr) {
271 if (
auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(srcType))
281 Value valZp, StringRef name) {
286 mlir::isa<IntegerType>(eType) && mlir::isa<IntegerType>(eZpType);
290 if (!bothInts || !sameBitWidth) {
292 <<
"expected " << name <<
" and " << name
293 <<
"_zp to both be integer of the same bitwidth, but got " << eType
294 <<
" vs. " << eZpType;
301 Value src, int32_t val) {
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)
312 return tosa::ConstOp::create(builder, loc, padConstType, padConstAttr);
316 if (
auto blockScaledTy = dyn_cast<tosa::BlockScaledType>(type))
318 if (isa<MXI8Type, tosa::mxint8Type>(type))
327 const StringRef operandName,
328 const StringRef dimName) {
329 if (ShapedType::isDynamic(currDim)) {
332 }
else if (ShapedType::isStatic(newDim) && currDim != newDim) {
334 << dimName <<
" of " << operandName <<
" to match size " << currDim
335 <<
", got " << newDim;
342 auto printDim = [&](
int64_t dim) {
343 if (ShapedType::isDynamic(dim))
349 llvm::interleaveComma(
shape,
diag, printDim);
355 StringRef outputName =
"output") {
356 assert(outputType.hasRank() &&
"expected output type to be ranked");
362 diag << outputName <<
" shape ";
364 diag <<
" to be compatible with inferred shape ";
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)
380 const std::optional<int64_t> calculatedOutSizeMinusOne =
idivCheck(
381 inputSize - 1 + padBefore + padAfter - (kernelSize - 1) * dilation,
383 if (!calculatedOutSizeMinusOne.has_value())
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
392 const int64_t calculatedOutSize = calculatedOutSizeMinusOne.value() + 1;
393 if (outputSize != ShapedType::kDynamic && calculatedOutSize != outputSize)
395 << dimName <<
" did not match expected: "
396 <<
"calculated=" << calculatedOutSize <<
", expected=" << outputSize;
404size_t mlir::tosa::mxint8Type::getDenseElementBitSize()
const {
return 8; }
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);
413LogicalResult mlir::tosa::mxint8Type::convertFromAttribute(
415 const auto intAttr = dyn_cast<IntegerAttr>(attr);
418 const Type attrType = intAttr.getType();
421 return cast<IntegerType>(attrType).convertFromAttribute(attr,
result);
430 bool allowScaleValues) {
431 if (!llvm::isa<ShapedType>(type)) {
433 emitError() <<
"non tensor type " << type <<
" is not allowed";
437 const auto tensorType = llvm::cast<ShapedType>(type);
438 const BlockScaledType elemType =
439 llvm::dyn_cast<BlockScaledType>(tensorType.getElementType());
443 if (!allowScaleValues && elemType.hasScaleValues()) {
446 <<
"block scaled tensor type with scale values is not allowed";
450 if (!tensorType.hasRank())
453 if (tensorType.getRank() == 0) {
455 emitError() <<
"block scaled tensor type must have rank greater than "
461 const uint32_t blockSize =
462 BlockShapeAttr::getBlockShapeValue(elemType.getBlockShape());
464 if (allowScaleValues && elemType.hasScaleValues() &&
465 tensorType.hasStaticShape()) {
466 const size_t numBlocks = tensorType.getNumElements() / blockSize;
467 if (elemType.getScaleValues().size() != numBlocks) {
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();
477 const int64_t blockedDimension = tensorShape.back();
478 if (ShapedType::isDynamic(blockedDimension))
481 if (blockedDimension % blockSize != 0) {
483 emitError() <<
"last dimension of block scaled tensor type ("
484 << blockedDimension <<
") must be divisible by block size ("
500 type, [ctx] {
return emitError(UnknownLoc::get(ctx)); })) &&
502 return ": " + message;
511 const auto parseScaleValue = [&]() -> ParseResult {
518 if (floatValue < 0.0)
519 return parser.
emitError(loc,
"scale value must be non-negative, got ")
522 Type attrType = scaleType;
526 if (attrType != scaleType)
527 return parser.
emitError(loc,
"parsed attribute type ")
528 << attrType <<
" does not match expected scale type " << scaleType;
530 scaleValues.push_back(FloatAttr::get(attrType, floatValue));
539 llvm::interleaveComma(scaleValues, printer, [&](
Attribute scaleValue) {
544size_t mlir::tosa::BlockScaledType::getDenseElementBitSize()
const {
546 if (isa<MXI8Type, tosa::mxint8Type>(valueType))
552mlir::tosa::BlockScaledType::convertToAttribute(
ArrayRef<char> rawData)
const {
556 assert(rawData.size() == 1 &&
"expected 1 byte for block_scaled element");
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))
567LogicalResult mlir::tosa::BlockScaledType::convertFromAttribute(
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);
575 const auto floatAttr = dyn_cast<FloatAttr>(attr);
576 if (!floatAttr || floatAttr.getType() != valueType)
587template <
typename A, std::enable_if_t<std::is_same_v<A, ArgMaxOp::Adaptor> ||
588 std::is_same_v<A, ArgMinOp::Adaptor>,
591 MLIRContext *context, ::std::optional<Location> location, A adaptor,
594 IntegerAttr axis = adaptor.getProperties().axis;
595 int32_t axisVal = axis.getValue().getSExtValue();
602 const auto inputRank = inputShape.
getRank();
604 outShape.reserve(inputRank - 1);
605 for (
int i = 0, s = inputRank; i < s; i++) {
620 const ShapedType resultType = llvm::cast<ShapedType>(op.getType());
622 if (
const auto resultETy = resultType.getElementType();
623 !resultETy.isIntOrIndex())
624 return op.emitOpError(
"result tensor is not of integer type");
626 const auto inputType = llvm::cast<ShapedType>(op.getInput().getType());
627 if (!inputType.hasRank())
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");
635 if (!resultType.hasRank())
641 expectedOutputShape.erase(expectedOutputShape.begin() + axis);
643 return op.emitOpError(
"expected output shape '")
644 << expectedOutputShape <<
"', got '" << outputShape <<
"'";
651 const auto inputType = llvm::dyn_cast<TensorType>(op.getInput().getType());
652 const auto weightType = llvm::dyn_cast<TensorType>(op.getWeight().getType());
654 auto inputEType = inputType.getElementType();
655 auto weightEType = weightType.getElementType();
657 llvm::cast<ShapedType>(op.getBias().getType()).getElementType();
659 llvm::cast<ShapedType>(op.getResult().getType()).getElementType();
660 bool biasIsFloat = llvm::isa<FloatType>(biasEType);
661 bool resultIsFloat = llvm::isa<FloatType>(resultEType);
663 if (
auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(inputEType))
666 if (
auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(weightEType))
669 if (
auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(biasEType))
672 if (
auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(resultEType))
675 if (biasIsFloat && resultIsFloat && (biasEType != resultEType)) {
679 "expect both bias and result to have same element type, got ")
680 << biasEType <<
" and " << resultEType;
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);
689 const bool isInputBSorFloat = isInputBlockScaled || isInputFloat;
690 const bool isWeightBSorFloat = isWeightBlockScaled || isWeightFloat;
693 if (isInputBSorFloat != isWeightBSorFloat) {
695 "expect both input and weight to be float or not together, got ")
696 << inputEType <<
" and " << weightEType;
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;
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;
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;
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;
724 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
725 if (succeeded(maybeIZp) && op.verifyInputZeroPoint(*maybeIZp).failed())
728 FailureOr<int64_t> maybeWZp = op.getWeightZeroPoint();
729 if (succeeded(maybeWZp) && op.verifyWeightZeroPoint(*maybeWZp).failed())
735LogicalResult tosa::ConstOp::verify() {
737 auto attrType = llvm::dyn_cast<TensorType>(getValuesAttr().
getType());
738 auto outputType = llvm::dyn_cast<TensorType>(getOutput().
getType());
740 if (!attrType || !outputType) {
741 emitOpError(
"expected tensors for attr/result type");
745 const Type attrElemType = attrType.getElementType();
746 const Type resultElemType = outputType.getElementType();
749 llvm::dyn_cast<mlir::quant::QuantizedType>(resultElemType)) {
754 if (
auto attrBlockScaledType =
755 llvm::dyn_cast<mlir::tosa::BlockScaledType>(attrElemType)) {
756 if (!attrBlockScaledType.hasScaleValues())
758 "attribute block scaled type must have scale values");
760 const auto emitAttributeError = [&op]() {
761 return op.
emitOpError(
"attribute block scaled type is invalid: ");
767 const BlockScaledType resultBlockScaledType =
768 llvm::dyn_cast<mlir::tosa::BlockScaledType>(resultElemType);
769 if (!resultBlockScaledType)
771 "result type must be block scaled type if attribute is block "
774 if (attrBlockScaledType.getValueType() !=
775 resultBlockScaledType.getValueType() ||
776 attrBlockScaledType.getScaleType() !=
777 resultBlockScaledType.getScaleType() ||
778 attrBlockScaledType.getBlockShape() !=
779 resultBlockScaledType.getBlockShape())
781 "expected block scaled element type to be compatible "
782 "between attr and result, got ")
783 << attrBlockScaledType <<
" vs. " << resultBlockScaledType;
788 if (attrElemType != resultElemType)
789 return emitOpError(
"expected same attr/result element types");
802 if (llvm::any_of(padding, [](
int64_t p) {
return p < 0; }))
803 return op.emitOpError(
"expect all padding values to be >= 0, got ")
807 if (llvm::any_of(strides, [](
int64_t s) {
return s < 1; }))
808 return op.emitOpError(
"expect all stride values to be >= 1, got ")
812 if (llvm::any_of(dilations, [](
int64_t d) {
return d < 1; }))
813 return op.emitOpError(
"expect all dilation values to be >= 1, got ")
816 const RankedTensorType outputType =
817 llvm::dyn_cast<RankedTensorType>(op.getOutput().getType());
822 const RankedTensorType inputType =
823 llvm::dyn_cast<RankedTensorType>(op.getInput().getType());
824 const RankedTensorType weightType =
825 llvm::dyn_cast<RankedTensorType>(op.getWeight().getType());
827 if (inputType && weightType) {
829 if constexpr (std::is_same<T, tosa::Conv2DOp>::value) {
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")))
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")))
844 if constexpr (std::is_same<T, tosa::DepthwiseConv2DOp>::value) {
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")))
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")))
859 if constexpr (std::is_same<T, tosa::Conv3DOp>::value) {
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")))
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")))
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")))
880 const RankedTensorType biasType =
881 llvm::dyn_cast<RankedTensorType>(op.getBias().getType());
886 const int64_t biasChannels = biasType.getDimSize(0);
888 outputType.getDimSize(outputType.getRank() - 1);
889 if (biasChannels == ShapedType::kDynamic ||
890 outputChannels == ShapedType::kDynamic)
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;
904 StringRef name1,
Type type2,
906 auto shapeType1 = dyn_cast<ShapedType>(type1);
907 auto shapeType2 = dyn_cast<ShapedType>(type2);
908 if (!shapeType1 || !shapeType2)
911 auto elemType1 = shapeType1.getElementType();
912 auto elemType2 = shapeType2.getElementType();
913 if (elemType1 != elemType2)
915 <<
"require same element type for " << name1 <<
" (" << elemType1
916 <<
") and " << name2 <<
" (" << elemType2 <<
")";
920 <<
"require same shapes for " << name1 <<
" (" << type1 <<
") and "
921 << name2 <<
" (" << type2 <<
")";
931 if (list1.size() != list2.size())
933 <<
"require same number of values in " << name1 <<
" ("
934 << list1.size() <<
") and " << name2 <<
" (" << list2.size() <<
")";
936 for (
auto [type1, type2] :
956 op->template getParentWithTrait<OpTrait::SymbolTable>();
963 const auto varOp = symTable.
lookup<tosa::VariableOp>(op.getName());
967 return op->emitOpError(
"'")
968 << op.getName() <<
"' has not been declared by 'tosa.variable'";
982 StringRef aName =
"input",
983 StringRef bName =
"output") {
984 auto aTType = llvm::dyn_cast<TensorType>(aType);
985 auto bTType = llvm::dyn_cast<TensorType>(bType);
987 op->
emitOpError(
"expect shaped tensor for") << aName <<
", got " << aType;
991 op->
emitOpError(
"expect shaped tensor for") << bName <<
", got" << bType;
994 auto aElementType = aTType.getElementType();
995 auto bElementType = bTType.getElementType();
997 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(aElementType);
999 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(bElementType);
1000 if ((aElementType.isIntOrIndexOrFloat() || aQuantType) &&
1001 (bElementType.isIntOrIndexOrFloat() || bQuantType) &&
1002 aElementType != bElementType) {
1008 << aName <<
" and " << bName <<
" to have same element type, got "
1009 << aElementType <<
" and " << bElementType;
1015LogicalResult tosa::ArgMaxOp::verify() {
return argMaxMinVerify(*
this); }
1017LogicalResult tosa::ArgMinOp::verify() {
return argMaxMinVerify(*
this); }
1027 const bool hasKernel = kernel.size() > 0;
1028 const bool hasStrides = strides.size() > 0;
1029 const bool hasPad = padding.size() > 0;
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 ")
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 ")
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 ")
1043 if (hasKernel && hasPad) {
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;
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;
1064 const auto inputType = llvm::dyn_cast<RankedTensorType>(input.
getType());
1065 const auto outputType = llvm::dyn_cast<RankedTensorType>(output.
getType());
1066 if (!inputType || !outputType)
1069 if (hasKernel && hasStrides && hasPad) {
1070 const auto verifyOutputSize =
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))
1080 const std::optional<int64_t> calculatedOutSizeMinusOne =
1081 idivCheck(inputSize + padBefore + padAfter - kernelSize, strideSize);
1082 if (!calculatedOutSizeMinusOne.has_value())
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;
1090 const int64_t calculatedOutSize = calculatedOutSizeMinusOne.value() + 1;
1091 if (ShapedType::isStatic(outputSize) && calculatedOutSize != outputSize)
1093 << dimName <<
" did not match expected: " <<
"calculated="
1094 << calculatedOutSize <<
", expected=" << outputSize;
1099 if (failed(verifyOutputSize(inputType.getDimSize(1),
1100 outputType.getDimSize(1), kernel[0], strides[0],
1101 padding[0], padding[1],
"height",
"y",
"top",
1105 if (failed(verifyOutputSize(
1106 inputType.getDimSize(2), outputType.getDimSize(2), kernel[1],
1107 strides[1], padding[2], padding[3],
"width",
"x",
"left",
"right")))
1113template <
typename T>
1116 op.getPad(), op.getInput(), op.getOutput());
1119template <
typename T>
1123 const Type inputZpETy =
1125 const Type outputZpETy =
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");
1132 if (inputETy.
isF16() && !(accType.isF16() || accType.isF32()))
1133 return op.emitOpError(
"accumulator type for f16 tensor is not f16/f32");
1135 if (inputETy.
isBF16() && !accType.isF32())
1136 return op.emitOpError(
"accumulator type for bf16 tensor is not f32");
1138 if (inputETy.
isF32() && !accType.isF32())
1139 return op.emitOpError(
"accumulator type for f32 tensor is not f32");
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;
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;
1151 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
1152 if (succeeded(maybeIZp) && op.verifyInputZeroPoint(*maybeIZp).failed())
1155 FailureOr<int64_t> maybeOZp = op.getOutputZeroPoint();
1156 if (succeeded(maybeOZp) && op.verifyOutputZeroPoint(*maybeOZp).failed())
1163struct AdaptivePoolingConstShapeValues {
1164 llvm::SmallVector<int64_t> kernel;
1165 llvm::SmallVector<int64_t> stride;
1166 llvm::SmallVector<int64_t> pad;
1170template <
typename T>
1172 std::is_same_v<T, tosa::AvgPool2dAdaptiveOp> ||
1173 std::is_same_v<T, tosa::MaxPool2dAdaptiveOp>;
1175template <
typename T,
1176 typename std::enable_if<IsSupportedAdaptivePoolConstShapeVerifyOp<T>,
1179 T op, AdaptivePoolingConstShapeValues &values) {
1185LogicalResult tosa::AvgPool2dOp::verify() {
1193LogicalResult tosa::AvgPool2dAdaptiveOp::verify() {
1194 AdaptivePoolingConstShapeValues values;
1203 values.pad, getInput(), getOutput())))
1212LogicalResult tosa::ClampOp::verify() {
1214 llvm::cast<ShapedType>(getInput().
getType()).getElementType();
1215 if (
auto quantType =
1216 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(inputETy)) {
1220 llvm::cast<ShapedType>(getOutput().
getType()).getElementType();
1221 if (
auto quantType =
1222 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(outputETy)) {
1225 if (inputETy != outputETy)
1226 return emitOpError(
"input/output element types are incompatible.");
1228 auto maxValAttr = getMaxValAttr();
1229 auto minValAttr = getMinValAttr();
1233 if (inputETy.
isInteger(dataTypeBitWidth)) {
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.");
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;
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.");
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;
1270 if (maxVal < minVal)
1271 return emitOpError(
"expected min_val <= max_val, got min_val=")
1272 << minValAttr <<
", max_val=" << maxValAttr;
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;
1303 result.addTypes(finalOutputType);
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;
1324 result.addTypes(finalOutputType);
1331 result.addOperands({a,
b, zps.first, zps.second});
1333 Type finalOutputType{outputType};
1336 auto inputBits = eType.getIntOrFloatBitWidth();
1338 auto outputShapedType = llvm::dyn_cast<ShapedType>(outputType);
1339 assert(outputShapedType &&
"Output must be a shaped type");
1341 IntegerType accElementType;
1342 if (inputBits == 16)
1347 finalOutputType = outputShapedType.clone(accElementType);
1349 result.addTypes(finalOutputType);
1370 DenseArrayAttr kernel, DenseArrayAttr stride,
1371 DenseArrayAttr pad, TypeAttr accType) {
1376 if (
auto quantAttr =
1378 inputZp = quantAttr.getInputZp();
1379 outputZp = quantAttr.getOutputZp();
1381 const std::optional<Value> inputZpOp =
1386 "Failed to create input zero point tensor for quantized AVG_POOL2D op");
1388 const std::optional<Value> outputZpOp =
1391 (
void)
emitError(loc,
"Failed to create output zero point tensor for "
1392 "quantized AVG_POOL2D op");
1395 if (inputZpOp && outputZpOp) {
1396 result.addOperands({input, inputZpOp.value(), outputZpOp.value()});
1401 result.addOperands({input});
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);
1420 if (
auto quantAttr =
1422 inputZp = quantAttr.getInputZp();
1423 outputZp = quantAttr.getOutputZp();
1425 const std::optional<Value> inputZpOp =
1429 "Failed to create input zero point tensor for quantized "
1430 "AVG_POOL2D_ADAPTIVE op");
1432 const std::optional<Value> outputZpOp =
1435 (
void)
emitError(loc,
"Failed to create output zero point tensor for "
1436 "quantized AVG_POOL2D_ADAPTIVE op");
1439 if (inputZpOp && outputZpOp) {
1444 result.addOperands({input, inputZpOp.value(), outputZpOp.value(),
1445 kernelShape, strideShape, padShape});
1450 result.addOperands({input});
1452 result.addAttribute(
"acc_type", accType);
1453 result.types.push_back(outputType);
1467 input1Zp = quantAttr.getInputZp();
1468 outputZp = quantAttr.getOutputZp();
1470 const std::optional<Value> input1ZpOp =
1474 loc,
"Failed to create input1 zero point for quantized NEGATE op");
1477 const std::optional<Value> outputZpOp =
1481 loc,
"Failed to create output zero point for quantized NEGATE op");
1484 if (input1ZpOp && outputZpOp) {
1485 result.addOperands({input, input1ZpOp.value(), outputZpOp.value()});
1490 result.addOperands({input});
1493 result.types.push_back(outputType);
1506 zp =
static_cast<int32_t
>(quantAttr.getInputZp());
1509 result.addOperands({input, paddings, padConstOp});
1510 result.types.push_back(outputType);
1514 StringRef name,
Type variableType,
1519 auto shapedType = dyn_cast<ShapedType>(variableType);
1521 (
void)
emitError(loc,
"variable type must be a shaped type");
1524 if (!shapedType.hasRank()) {
1525 (
void)
emitError(loc,
"variable type must be a ranked type");
1529 auto elementType = shapedType.getElementType();
1530 auto elementTypeAttr = TypeAttr::get(elementType);
1534 result.addAttribute(
"sym_name", nameAttr);
1535 result.addAttribute(
"var_shape", varShapeAttr);
1536 result.addAttribute(
"type", elementTypeAttr);
1537 result.addAttribute(
"initial_value", initialValue);
1550 if (ShapedType::isStatic(dim1) && ShapedType::isStatic(dim2) && dim1 != dim2)
1554 return ShapedType::isDynamic(dim1) ? dim2 : dim1;
1560 for (
int i = 0, e = operands.size(); i != e; ++i) {
1562 if (!
shape.hasRank()) {
1567 outRank = std::max<int64_t>(outRank,
shape.getRank());
1570 outShape.resize(outRank, 1);
1572 for (
int i = 0, e = operands.size(); i != e; ++i) {
1574 auto rankDiff = outShape.size() -
shape.getRank();
1576 for (
size_t i = 0, e =
shape.getRank(); i < e; ++i) {
1577 auto dim1 = outShape[i + rankDiff];
1578 auto dim2 =
shape.getDimSize(i);
1580 const FailureOr<int64_t> maybeResolvedDim =
1582 if (failed(maybeResolvedDim))
1584 const int64_t resolvedDim = *maybeResolvedDim;
1585 outShape[i + rankDiff] = resolvedDim;
1592LogicalResult tosa::ArgMaxOp::inferReturnTypeComponents(
1593 MLIRContext *context, ::std::optional<Location> location,
1594 ArgMaxOp::Adaptor adaptor,
1597 inferredReturnShapes);
1600LogicalResult tosa::ArgMinOp::inferReturnTypeComponents(
1601 MLIRContext *context, ::std::optional<Location> location,
1602 ArgMinOp::Adaptor adaptor,
1605 inferredReturnShapes);
1608LogicalResult tosa::RFFT2dOp::inferReturnTypeComponents(
1609 MLIRContext *context, ::std::optional<Location> location,
1610 RFFT2dOp::Adaptor adaptor,
1612 ShapeAdaptor inputShape(adaptor.getInputReal().getType());
1614 if (!inputShape.hasRank())
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);
1625 if (inWidth != ShapedType::kDynamic)
1626 outputShape[2] = inWidth / 2 + 1;
1635 const llvm::StringRef dimName) {
1636 const bool isPowerOfTwo = (dimSize & (dimSize - 1)) == 0 && dimSize > 0;
1639 << dimName <<
" to be a power of two, got " << dimSize;
1644LogicalResult tosa::RFFT2dOp::verify() {
1645 const auto outputTypes = getResultTypes();
1647 return emitOpError(
"expected output shapes to match, got ") << outputTypes;
1649 const auto inputType =
1650 llvm::dyn_cast<RankedTensorType>(getInputReal().
getType());
1654 const int64_t height = inputType.getDimSize(1);
1655 if (ShapedType::isStatic(height) &&
1659 const int64_t width = inputType.getDimSize(2);
1660 if (ShapedType::isStatic(width) &&
1664 const auto outputType = llvm::dyn_cast<RankedTensorType>(outputTypes[0]);
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;
1676 const int64_t outputWidth = outputType.getDimSize(2);
1677 if (ShapedType::isStatic(width) && ShapedType::isStatic(outputWidth) &&
1678 (outputWidth != (width / 2) + 1))
1680 "expected output width to be equal to input_width / 2 + 1, got ")
1686LogicalResult tosa::FFT2dOp::inferReturnTypeComponents(
1687 MLIRContext *context, ::std::optional<Location> location,
1688 FFT2dOp::Adaptor adaptor,
1690 inferredReturnShapes.push_back(
1692 inferredReturnShapes.push_back(
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)
1705 const auto trySelectStaticDim = [](
const int64_t a,
const int64_t b) {
1706 return ShapedType::isDynamic(a) ? a :
b;
1709 const int64_t height = trySelectStaticDim(inputRealType.getDimSize(1),
1710 inputImagType.getDimSize(1));
1711 if (ShapedType::isStatic(height) &&
1715 const int64_t width = trySelectStaticDim(inputRealType.getDimSize(2),
1716 inputImagType.getDimSize(2));
1717 if (ShapedType::isStatic(width) &&
1724LogicalResult tosa::ConcatOp::inferReturnTypeComponents(
1725 MLIRContext *context, ::std::optional<Location> location,
1726 ConcatOp::Adaptor adaptor,
1729 const Properties &prop = adaptor.getProperties();
1730 int32_t axis = prop.axis.getValue().getSExtValue();
1732 bool hasRankedInput =
false;
1733 for (
auto operand : adaptor.getOperands()) {
1735 if (!operandShape.hasRank())
1739 if (!hasRankedInput)
1740 outputShape.resize(operandShape.getRank(), ShapedType::kDynamic);
1743 for (
int i = 0, s = operandShape.getRank(); i < s; i++) {
1744 if (i == axis || operandShape.isDynamicDim(i))
1746 if (outputShape[i] == ShapedType::kDynamic)
1747 outputShape[i] = operandShape.getDimSize(i);
1748 if (outputShape[i] != operandShape.getDimSize(i))
1750 "Cannot concat tensors with different sizes"
1751 " on the non-axis dimension ",
1755 hasRankedInput =
true;
1758 if (adaptor.getInput1().empty())
1762 llvm::cast<TensorType>(adaptor.getInput1().getType()[0]).getElementType();
1763 if (!hasRankedInput) {
1770 for (
auto operand : adaptor.getOperands()) {
1775 if (!operandShape.hasRank() || operandShape.isDynamicDim(axis)) {
1776 concatDimSize = ShapedType::kDynamic;
1780 concatDimSize += operandShape.getDimSize(axis);
1783 outputShape[axis] = concatDimSize;
1789LogicalResult tosa::ConcatOp::verify() {
1791 auto outType = getOutput().getType();
1795 if (inputList.empty())
1796 return emitOpError(
"expect at least one input");
1798 if (!llvm::all_of(inputList, [&](
auto input) {
1800 *
this, input.getType(), outType));
1805 const int32_t axis = getAxis();
1807 for (
const auto &input : inputList) {
1808 const Type inputType = input.getType();
1810 if (currShape.hasRank()) {
1811 firstRankedInputShape = currShape;
1813 if (axis < 0 || axis >= firstRankedInputShape.
getRank())
1814 return emitOpError(
"expect axis to be within range 0 < axis < "
1815 "rank(input1[firstRankedTensorIdx]), got ")
1821 const auto allOperandsHasRank = [](
const Value input) {
1824 if (llvm::all_of(inputList, allOperandsHasRank)) {
1827 for (
const auto &[
index, input] : llvm::enumerate(inputList.drop_front())) {
1829 const int64_t inputRank = inputShape.getRank();
1830 const size_t operandNum =
index + 1;
1833 if (inputRank != firstInputRank)
1835 "expect all operands to have the same rank, but got ")
1836 << firstInputRank <<
" vs " << inputRank <<
" on operands 0 and "
1840 for (
int i = 0; i < inputRank; i++) {
1841 const int64_t inputDim = inputShape.getDimSize(i);
1843 if (i == axis || firstRankedInputShape.
isDynamicDim(i) ||
1844 inputShape.isDynamicDim(i))
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;
1855 if (outputShape.hasRank() && outputShape.getRank() != firstInputRank)
1856 return emitOpError(
"expect output rank to match inputs rank, got ")
1857 << outputShape.getRank() <<
" vs " << firstInputRank;
1861 for (
const auto &input : inputList) {
1863 if (inputShape.isDynamicDim(axis)) {
1868 axisSum += inputShape.getDimSize(axis);
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);
1882LogicalResult tosa::EqualOp::inferReturnTypeComponents(
1883 MLIRContext *context, ::std::optional<Location> location,
1887 auto elementType = IntegerType::get(context, 1);
1900 if (l.size() != r.size() || l.size() != 1)
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);
1916static FailureOr<SmallVector<int64_t>>
1918 int64_t outputRank,
bool transposeB) {
1919 if (outputRank < 2 ||
1927 for (
int64_t axis = 0; axis < outputRank - 2; ++axis) {
1931 if (failed(resolvedDim))
1933 outputShape[axis] = *resolvedDim;
1939 outputShape[outputRank - 1] =
1954 inferredReturnShapes.emplace_back();
1961 if (ShapedType::isStatic(aChannels) && ShapedType::isStatic(bChannels) &&
1962 aChannels != bChannels)
1966 FailureOr<SmallVector<int64_t>> outputShape =
1968 if (failed(outputShape))
1971 inferredReturnShapes.emplace_back(*outputShape);
1975LogicalResult tosa::MatMulOp::inferReturnTypeComponents(
1976 MLIRContext *context, ::std::optional<Location> location,
1977 MatMulOp::Adaptor adaptor,
1982 inferredReturnShapes);
1985template <
typename T>
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);
1993 if (aQuantizedEType || bQuantizedEType) {
1994 if (!aQuantizedEType || !bQuantizedEType) {
1995 return op.emitOpError(
"expect operands to be both quantized or both not "
1997 << aElementType <<
" and " << bElementType;
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, "
2005 << aQuantWidth <<
" and " << bQuantWidth;
2012template <
typename T>
2014 StringRef inputName,
2019 Type expectedElementType = inputStorageElementType;
2021 if (isa<BlockScaledType>(inputElementType))
2022 expectedElementType = Float32Type::get(op.getContext());
2024 if (expectedElementType == zpElementType)
2028 diag << inputName <<
" and " << zpName;
2029 if (isa<BlockScaledType>(inputElementType))
2030 diag <<
" have compatible element types, got " << inputElementType
2031 <<
" and " << zpElementType;
2033 diag <<
" have the same element type, got " << inputStorageElementType
2034 <<
" and " << zpElementType;
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));
2048template <
typename T>
2052 const auto outputType = cast<ShapedType>(op.getResult().getType());
2055 : ShapedType::kDynamic;
2063 const int64_t minimumOutputRank =
2066 if (outputType.hasRank() && outputType.getRank() < minimumOutputRank)
2067 return op.emitOpError(
"expected output rank of at least ")
2068 << minimumOutputRank <<
", got " << outputType.getRank();
2070 const bool bothInputsRanked = aShape.
hasRank() && bShape.
hasRank();
2071 if (!bothInputsRanked && !outputType.hasRank())
2076 const int64_t expectedOutputRank =
2077 bothInputsRanked ? minimumOutputRank : outputType.getRank();
2078 FailureOr<SmallVector<int64_t>> expectedOutputShape =
2080 if (failed(expectedOutputShape)) {
2082 "expected batch dimensions of a and b to be broadcast compatible, "
2085 diag <<
"] and b=[";
2091 if (outputType.hasRank())
2093 op.getOperation(), outputType, *expectedOutputShape);
2097LogicalResult MatMulOp::verify() {
2109 FailureOr<int64_t> maybeAZp = getAZeroPoint();
2110 if (succeeded(maybeAZp) && verifyAZeroPoint(*maybeAZp).failed())
2113 FailureOr<int64_t> maybeBZp = getBZeroPoint();
2114 if (succeeded(maybeBZp) && verifyBZeroPoint(*maybeBZp).failed())
2120LogicalResult tosa::MatMulTOp::inferReturnTypeComponents(
2121 MLIRContext *context, ::std::optional<Location> location,
2122 MatMulTOp::Adaptor adaptor,
2127 inferredReturnShapes);
2130LogicalResult MatMulTOp::verify() {
2142 FailureOr<int64_t> maybeAZp = getAZeroPoint();
2143 if (succeeded(maybeAZp) && verifyAZeroPoint(*maybeAZp).failed())
2146 FailureOr<int64_t> maybeBZp = getBZeroPoint();
2147 if (succeeded(maybeBZp) && verifyBZeroPoint(*maybeBZp).failed())
2153LogicalResult tosa::MatmulTBlockScaledOp::inferReturnTypeComponents(
2154 MLIRContext *context, ::std::optional<Location> location,
2155 MatmulTBlockScaledOp::Adaptor adaptor,
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);
2165 const auto aScaleShape = cast<ShapedType>(adaptor.getAScale().getType());
2166 if (aScaleShape.hasRank()) {
2167 outShape[0] = ShapedType::isDynamic(outShape[0]) ? aScaleShape.getDimSize(0)
2169 outShape[1] = ShapedType::isDynamic(outShape[1]) ? aScaleShape.getDimSize(1)
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)
2179 ShapedType::isDynamic(outShape[0]) ? bDataBatchSize : outShape[0];
2180 outShape[2] = bDataShape.getDimSize(1);
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)
2188 ShapedType::isDynamic(outShape[0]) ? bScaleBatchSize : outShape[0];
2189 outShape[2] = ShapedType::isDynamic(outShape[2]) ? bScaleShape.getDimSize(1)
2197LogicalResult MatmulTBlockScaledOp::verify() {
2199 const Type aDataType = getAData().getType();
2200 const Type bDataType = getBData().getType();
2206 int64_t N = ShapedType::kDynamic;
2207 int64_t D = ShapedType::kDynamic;
2208 int64_t H = ShapedType::kDynamic;
2211 int64_t multiplesOfC = ShapedType::kDynamic;
2223 "a_scale",
"batch")) ||
2225 "a_scale",
"height")))
2233 "b_data",
"batch")) ||
2235 "b_data",
"channels")))
2243 "b_scale",
"batch")) ||
2245 "b_scale",
"width")) ||
2253 if (ShapedType::isStatic(N) && ShapedType::isStatic(D) && N != D && D != 1)
2254 return emitOpError(
"expect B matrix batch size to be broadcast compatible "
2256 << D <<
" vs N=" << N;
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;
2267 if (ShapedType::isStatic(C) && ShapedType::isStatic(multiplesOfC) &&
2268 multiplesOfC != C / blockSize)
2270 "expect scale operands dimension 2 to equal C/block_size (")
2271 <<
C <<
"/" << blockSize <<
")" <<
", got " << multiplesOfC;
2274 N = ShapedType::isDynamic(N) ? D : N;
2276 const auto outputType = cast<ShapedType>(getResult().
getType());
2277 if (outputType.hasRank() &&
2282 opError <<
" to be compatible with expected output shape ";
2290LogicalResult tosa::PadOp::inferReturnTypeComponents(
2291 MLIRContext *context, ::std::optional<Location> location,
2292 PadOp::Adaptor adaptor,
2294 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2296 cast<tosa::shapeType>(adaptor.getPadding().getType()).getRank();
2301 if (!inputShape.hasRank()) {
2302 outputShape.resize(paddingRank / 2, ShapedType::kDynamic);
2311 outputShape.resize(inputShape.getRank(), ShapedType::kDynamic);
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);
2322 auto padFront = paddingValues[i * 2];
2323 auto padBack = paddingValues[i * 2 + 1];
2324 outputShape.push_back(inputShape.getDimSize(i) + padFront + padBack);
2331LogicalResult tosa::PadOp::verify() {
2338 if (
auto padConst = getPadConst()) {
2346 RankedTensorType inputType =
2347 llvm::dyn_cast<RankedTensorType>(getInput1().
getType());
2348 RankedTensorType outputType =
2349 llvm::dyn_cast<RankedTensorType>(getOutput().
getType());
2350 if (!inputType || !outputType)
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 "
2367LogicalResult tosa::SliceOp::inferReturnTypeComponents(
2368 MLIRContext *context, ::std::optional<Location> location,
2369 SliceOp::Adaptor adaptor,
2378 auto rank = cast<tosa::shapeType>(adaptor.getSize().getType()).getRank();
2386 ShapeAdaptor inputShape(adaptor.getInput1().getType());
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))) {
2395 if (ShapedType::isDynamic(inputShape.getDimSize(i))) {
2398 outputShape[i] = size[i];
2402 if (size[i] == -1) {
2403 outputShape[i] = inputShape.getDimSize(i) - start[i];
2404 }
else if (start[i] + size[i] <= inputShape.getDimSize(i)) {
2406 outputShape[i] = size[i];
2418LogicalResult tosa::SliceOp::verify() {
2419 const Value input = getInput1();
2420 const Value output = getOutput();
2426 const Value start = getStart();
2427 const Value size = getSize();
2431 if (inputShape.hasRank()) {
2432 const auto inputRank = inputShape.getRank();
2433 if (outputShape.hasRank() && inputRank != outputShape.getRank())
2435 "expect input1 and output to have the same ranks, got ")
2436 << inputRank <<
" and " << outputShape.getRank();
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");
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");
2452LogicalResult tosa::MulOp::inferReturnTypeComponents(
2453 MLIRContext *context, ::std::optional<Location> location,
2468LogicalResult tosa::MulOp::verify() {
2469 const Value output = getOutput();
2474 if (
auto resIntType = dyn_cast<IntegerType>(resElemType)) {
2475 IntegerType lhsIntType =
2477 IntegerType rhsIntType =
2479 if (!lhsIntType || !rhsIntType || lhsIntType != rhsIntType)
2480 return emitOpError(
"requires the same element type for all operands");
2485 if (lhsIntType.getWidth() > resIntType.getWidth())
2486 return emitOpError(
"invalid data type size for operands or result");
2491 for (
int i = 0; i < 2; ++i) {
2494 "requires the same element type for all operands and results");
2501 TypeRange operandTypes = getOperandTypes();
2502 ShapedType aType = cast<ShapedType>(operandTypes[0]);
2503 ShapedType bType = cast<ShapedType>(operandTypes[1]);
2505 const bool aHasRank = aType.hasRank();
2506 const bool bHasRank = bType.hasRank();
2508 bool hasExpectedOutputShape =
false;
2511 if (aHasRank && bHasRank) {
2512 const int64_t aRank = aType.getRank();
2513 const int64_t bRank = bType.getRank();
2515 return emitOpError(
"a and b operands don't have matching ranks, got ")
2516 << aRank <<
" and " << bRank;
2520 aType.getShape(), bType.getShape(), expectedOutputShape))
2521 return emitOpError(
"a and b operands don't have broadcast-compatible "
2523 << aType <<
" and " << bType;
2524 hasExpectedOutputShape =
true;
2527 ShapedType resultType = cast<ShapedType>(output.
getType());
2528 if (!resultType.hasRank())
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();
2539 if (hasExpectedOutputShape &&
2541 expectedOutputShape)))
2547LogicalResult tosa::TableOp::inferReturnTypeComponents(
2548 MLIRContext *context, ::std::optional<Location> location,
2549 TableOp::Adaptor adaptor,
2551 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2553 if (!inputShape.hasRank()) {
2558 inferredReturnShapes.resize(1);
2559 inputShape.getDims(inferredReturnShapes[0]);
2563LogicalResult tosa::TableOp::verify() {
2564 const TensorType inputType = getInput1().getType();
2565 const TensorType outputType = getOutput().getType();
2574 auto inputDims = inputType.
getShape();
2575 auto outputDims = outputType.
getShape();
2576 for (
auto it : llvm::enumerate(llvm::zip(inputDims, outputDims))) {
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;
2595 llvm::map_to_vector(multiplesAttr.getValues<APInt>(),
2596 [](
const APInt &val) { return val.getSExtValue(); });
2600LogicalResult tosa::TileOp::inferReturnTypeComponents(
2601 MLIRContext *context, ::std::optional<Location> location,
2602 TileOp::Adaptor adaptor,
2609 cast<tosa::shapeType>(adaptor.getMultiples().getType()).getRank();
2614 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2616 if (!inputShape.hasRank()) {
2617 outputShape.resize(multiples.size(), ShapedType::kDynamic);
2618 inferredReturnShapes.push_back(
2622 if (
static_cast<size_t>(inputShape.getRank()) != multiples.size())
2626 outputShape.reserve(multiples.size());
2627 for (
int i = 0, s = inputShape.getRank(); i < s; i++) {
2630 if (multiples[i] <= 0) {
2631 outputShape.push_back(ShapedType::kDynamic);
2633 int64_t dim = inputShape.getDimSize(i);
2634 if (dim != ShapedType::kDynamic)
2635 dim *= multiples[i];
2636 outputShape.push_back(dim);
2644LogicalResult tosa::TileOp::verify() {
2650 ShapedType inputType = llvm::cast<ShapedType>(getInput1().
getType());
2651 ShapedType outputType = llvm::cast<ShapedType>(
getType());
2653 shapeType multiplesType =
2654 llvm::cast<tosa::shapeType>(getMultiples().
getType());
2656 auto multiplesRank = multiplesType.getRank();
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() &&
2666 }
else if (outputType.hasRank() && outputType.getRank() != multiplesRank)
2667 return emitOpError(
"expect 'multiples' array to have length ")
2668 << outputType.getRank() <<
" but got " << multiplesRank <<
".";
2674 if (l.size() != r.size() || l.size() != 1)
2679LogicalResult tosa::ReshapeOp::inferReturnTypeComponents(
2680 MLIRContext *context, ::std::optional<Location> location,
2681 ReshapeOp::Adaptor adaptor,
2683 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2693 llvm::any_of(newShapeValue, [](
int64_t dim) {
2694 return dim == 0 || dim < kInferableDimSize;
2696 auto rank = cast<tosa::shapeType>(adaptor.getShape().getType()).getRank();
2706 if (!inputShape.hasRank() || !inputShape.hasStaticShape()) {
2707 inferredReturnShapes.push_back(
2715 int64_t numElements = inputShape.getNumElements();
2717 for (
auto val : newShapeValue) {
2718 if (ShapedType::isStatic(val)) {
2724 for (
auto &val : newShapeValue) {
2725 if (ShapedType::isDynamic(val))
2726 val = numElements / staticMul;
2729 inferredReturnShapes.push_back(
2734llvm::LogicalResult tosa::ReshapeOp::verify() {
2735 TensorType outputType = getOutput().getType();
2744 if (
auto rankedOutputType = dyn_cast<RankedTensorType>(outputType)) {
2746 rankedOutputType.getRank())
2747 return emitOpError() <<
"new shape does not match result rank";
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;
2759 return mlir::success();
2762bool tosa::ReshapeBlockScaledOp::isCompatibleReturnTypes(
TypeRange l,
2764 if (l.size() != r.size() || l.size() < 1 || l.size() > 2)
2772LogicalResult tosa::ReshapeBlockScaledOp::inferReturnTypeComponents(
2773 MLIRContext *context, ::std::optional<Location> location,
2774 ReshapeBlockScaledOp::Adaptor adaptor,
2777 const auto numInputs = adaptor.getInput().size();
2778 ShapeAdaptor inputShape(adaptor.getInput()[0].getType());
2781 const auto newShape = adaptor.getNewValueShape();
2783 auto rank = cast<tosa::shapeType>(newShape.getType()).getRank();
2792 const uint32_t blockSize =
2793 BlockSizeAttr::getBlockSizeValue(adaptor.getBlockSize());
2796 if (numInputs == 2) {
2797 newScaleShapeValue.assign(newShapeValue.begin(), newShapeValue.end());
2798 if (!newScaleShapeValue.empty() &&
2799 ShapedType::isStatic(newScaleShapeValue.back()))
2800 newScaleShapeValue.back() /= blockSize;
2803 inferredReturnShapes.push_back(
2805 if (numInputs == 2) {
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;
2822llvm::LogicalResult tosa::ReshapeBlockScaledOp::verify() {
2826 if (inputList.size() == 0)
2827 return emitOpError(
"requires at least one input");
2829 if (inputList.size() > 2)
2830 return emitOpError(
"requires at most two inputs");
2832 if (inputList.size() != outputList.size())
2833 return emitOpError(
"requires number of results to match inputs");
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");
2845 const auto inputType = llvm::cast<ShapedType>(inputList[0].
getType());
2846 if (!inputType.hasRank())
2848 const uint32_t blockSize = BlockSizeAttr::getBlockSizeValue(
getBlockSize());
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;
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;
2864 "requires all result shapes have a rank greater than 0");
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");
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 "
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 <<
")";
2899 inputScaleType.getDimSize(inputScaleType.getRank() - 1);
2901 if (ShapedType::isStatic(lastScaleDim) &&
2902 lastScaleDim != lastValueDim / blockSize)
2903 return emitOpError(
"expect last dimension of scale_data (")
2904 << lastScaleDim <<
") to be " << lastValueDim <<
"/"
2909 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_1))
2910 return emitOpError(
"expect block size to be 1, got ") << blockSize;
2918 return mlir::success();
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
2929 const auto outputType = llvm::cast<ShapedType>(outputList[0].
getType());
2933 if (
static_cast<int64_t>(shapeValues.size()) != outputType.getRank())
2934 return emitOpError() <<
"result does not match new shape rank";
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";
2943 if (outputList.size() == 2) {
2947 scaleShapeValues.back() /= blockSize;
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";
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";
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;
2978 return (dim > 0) ?
acc * dim :
acc;
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;
2989 return mlir::success();
2996 ElementsAttr zpAttr;
3001 Type zpElemType = zpAttr.getElementType();
3003 if (llvm::isa<FloatType>(zpElemType)) {
3004 if (zpAttr.getValues<APFloat>()[0].isZero()) {
3011 if (llvm::isa<IntegerType>(zpElemType)) {
3013 return zpAttr.getValues<APInt>()[0].getSExtValue();
3014 return zpAttr.getValues<APInt>()[0].getZExtValue();
3021template <
typename T>
3023 const std::string &operand) {
3026 if (!zpElemType.
isInteger(8) && zp != 0) {
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";
3039 const std::string &operand) {
3040 bool isInputZp = (operand ==
"Input");
3042 bool tensorUnsigned =
3043 isInputZp ? op.getInputUnsigned() : op.getOutputUnsigned();
3044 StringRef tensorName = isInputZp ?
"input" :
"output";
3050 !(zpElemType.
isInteger(16) && tensorUnsigned)) {
3051 return op.emitOpError()
3052 <<
"expect " << tensorName <<
"_zp of 0, got " << zp;
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;
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); \
3068 LogicalResult tosa::OP::verify##OPERAND_NAME##ZeroPoint(int64_t zp) { \
3069 return verifyZeroPoint(*this, get##OPERAND_NAME##Zp(), zp, #OPERAND_NAME); \
3092#undef ZERO_POINT_HELPER
3094LogicalResult tosa::TransposeOp::inferReturnTypeComponents(
3095 MLIRContext *context, ::std::optional<Location> location,
3096 TransposeOp::Adaptor adaptor,
3098 ShapeAdaptor inputShape(adaptor.getInput1().getType());
3107 const auto inputRank = inputShape.
getRank();
3111 if (adaptor.getPerms().size() !=
static_cast<size_t>(inputRank)) {
3117 if (inputRank == 0) {
3123 bool allTheSame =
true;
3124 for (
int i = 1, s = inputRank; i < s; i++) {
3134 outputShape.resize(inputRank, inputShape.
getDimSize(0));
3139 outputShape.resize(inputRank, ShapedType::kDynamic);
3142 if (llvm::any_of(adaptor.getPerms(),
3143 [inputRank](
const auto i) { return i >= inputRank; }))
3146 outputShape.reserve(inputRank);
3147 for (
int i = 0, s = inputRank; i < s; i++) {
3148 outputShape[i] = inputShape.
getDimSize(adaptor.getPerms()[i]);
3155LogicalResult tosa::TransposeOp::verify() {
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();
3174 if (inputShape.hasRank() && outputShape.hasRank() &&
3175 inputShape.getRank() != outputShape.getRank())
3176 return emitOpError()
3177 <<
"expected input tensor rank to equal result tensor rank";
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();
3186 if (!llvm::all_of(constantPerms,
3187 [&constantPerms](int32_t s) {
3189 static_cast<size_t>(s) < constantPerms.size();
3192 constantPerms, [](int32_t v) ->
int64_t {
return v; })))
3193 return emitOpError() <<
"expected valid permutation indices";
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";
3202 if (inputShape.hasStaticShape() && outputShape.hasStaticShape() &&
3203 inputShape.getNumElements() != outputShape.getNumElements())
3204 return emitOpError() <<
"expected input1 and output to have same numbers "
3206 << inputShape.getNumElements() <<
" and "
3207 << outputShape.getNumElements();
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))
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]);
3228LogicalResult TransposeOp::reifyResultShapes(
3231 const llvm::ArrayRef<int32_t> transposePerms = getPerms();
3233 Value input = getInput1();
3234 auto inputType = cast<TensorType>(input.
getType());
3236 SmallVector<OpFoldResult> returnedDims(inputType.getRank());
3237 for (
auto dim : transposePerms) {
3238 int32_t dimInInput = transposePerms[dim];
3239 if (inputType.isDynamicDim(dimInInput))
3241 tensor::DimOp::create(builder, getLoc(), input, dimInInput)
3245 builder.
getIndexAttr(inputType.getDimSize(dimInInput));
3248 reifiedReturnShapes.emplace_back(std::move(returnedDims));
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);
3259 ShapeAdaptor valuesShape(adaptor.getValues().getType());
3260 if (valuesShape.hasRank()) {
3261 outputShape[0] = valuesShape.getDimSize(0);
3262 outputShape[2] = valuesShape.getDimSize(2);
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);
3273 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
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);
3284 const ShapeAdaptor valuesShape(adaptor.getValues().getType());
3285 if (valuesShape.hasRank()) {
3286 outputShape[0] = valuesShape.getDimSize(0);
3287 outputShape[2] = valuesShape.getDimSize(2);
3290 const ShapeAdaptor indicesShape(adaptor.getIndices().getType());
3291 if (indicesShape.hasRank()) {
3292 if (outputShape[0] == ShapedType::kDynamic)
3293 outputShape[0] = indicesShape.getDimSize(0);
3295 const FailureOr<int32_t> maybeRowCount =
3297 if (succeeded(maybeRowCount)) {
3298 const int64_t indicesW = indicesShape.getDimSize(1);
3299 if (ShapedType::isStatic(indicesW))
3300 outputShape[1] = indicesW * maybeRowCount.value();
3304 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
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();
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);
3323 const ShapeAdaptor indicesShape(adaptor.getIndices().getType());
3324 if (indicesShape.hasRank()) {
3325 if (dataShape[0] == ShapedType::kDynamic)
3326 dataShape[0] = indicesShape.getDimSize(0);
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();
3337 inferredReturnShapes.push_back(ShapedTypeComponents(dataShape));
3338 if (values.size() == 1)
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;
3347 inferredReturnShapes.push_back(ShapedTypeComponents(scaleShape));
3351LogicalResult tosa::GatherOp::verify() {
3358 const ShapeAdaptor valuesShape(getValues().
getType());
3360 const ShapeAdaptor outputShape(getOutput().
getType());
3362 int64_t n = ShapedType::kDynamic;
3363 int64_t w = ShapedType::kDynamic;
3364 int64_t c = ShapedType::kDynamic;
3366 if (valuesShape.hasRank()) {
3367 n = valuesShape.getDimSize(0);
3368 c = valuesShape.getDimSize(2);
3370 if (indicesShape.hasRank()) {
3371 const int64_t indicesN = indicesShape.getDimSize(0);
3372 w = indicesShape.getDimSize(1);
3373 if (n == ShapedType::kDynamic)
3375 else if (indicesN != ShapedType::kDynamic && n != indicesN)
3376 return emitOpError() <<
"requires indices dimension 0 to have size " << n
3377 <<
", got " << indicesN;
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 &&
3385 return emitOpError() <<
"requires output dimension 0 to have size " << n
3386 <<
", got " << outputN;
3388 if (w != ShapedType::kDynamic && outputW != ShapedType::kDynamic &&
3390 return emitOpError() <<
"requires output dimension 1 to have size " << w
3391 <<
", got " << outputW;
3392 if (c != ShapedType::kDynamic && outputC != ShapedType::kDynamic &&
3394 return emitOpError() <<
"requires output dimension 2 to have size " << c
3395 <<
", got " << outputC;
3400LogicalResult tosa::RowGatherOp::verify() {
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();
3411 int64_t n = ShapedType::kDynamic;
3412 int64_t c = ShapedType::kDynamic;
3413 int64_t w = ShapedType::kDynamic;
3415 const ShapeAdaptor valuesShape(getValues().
getType());
3416 if (valuesShape.hasRank()) {
3417 n = valuesShape.getDimSize(0);
3418 c = valuesShape.getDimSize(2);
3422 if (indicesShape.hasRank()) {
3424 "indices",
"batch")))
3426 w = indicesShape.getDimSize(1);
3429 const ShapeAdaptor outputShape(getOutput().
getType());
3430 if (outputShape.hasRank()) {
3432 "output",
"batch")) ||
3434 "output",
"channels")))
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);
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 "
3459 if (output.size() != values.size())
3460 return emitOpError()
3461 <<
"expects output tensor list length to match values tensor list "
3463 << output.size() <<
" results for " << values.size()
3464 <<
" input tensors";
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 "
3471 if (values.size() == 2 && blockSize == 1)
3472 return emitOpError()
3473 <<
"requires block_size to not be BLOCK_SIZE_1 when values tensor "
3477 output[0].
getType(),
"values[0]",
3482 "values[1]",
"output[1]")))
3486 succeeded(rowCount) && rowCount.value() <= 0)
3487 return emitOpError() <<
"requires row_count to be > 0, got "
3488 << rowCount.value();
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;
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);
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
3509 if (indicesShape.hasRank()) {
3511 "indices",
"batch")))
3513 w = indicesShape.getDimSize(1);
3516 const ShapeAdaptor outputDataShape(output[0].
getType());
3517 if (outputDataShape.hasRank()) {
3519 "output[0]",
"batch")) ||
3521 "output[0]",
"channels")))
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);
3536 if (values.size() == 2) {
3537 const ShapeAdaptor valuesScaleShape(values[1].
getType());
3538 if (valuesScaleShape.hasRank()) {
3540 "values[1]",
"batch")) ||
3542 "values[1]",
"rows")))
3544 multiplesOfC = valuesScaleShape.getDimSize(2);
3547 const ShapeAdaptor outputScaleShape(output[1].
getType());
3548 if (outputScaleShape.hasRank()) {
3550 "output[1]",
"batch")))
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);
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);
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;
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);
3590 ShapeAdaptor inputShape(adaptor.getInput().getType());
3591 if (!inputShape.hasRank())
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);
3599 if ((inputHeight == ShapedType::kDynamic) ||
3600 (inputWidth == ShapedType::kDynamic))
3603 SmallVector<int64_t> scaleInt, offsetInt, borderInt;
3615 if (llvm::any_of(scaleInt, [](int64_t s) {
return s <= 0; }))
3619 const int64_t outputHeight =
3620 (((inputHeight - 1) * scaleInt[0] - offsetInt[0] + borderInt[0]) /
3624 const int64_t outputWidth =
3625 (((inputWidth - 1) * scaleInt[2] - offsetInt[1] + borderInt[1]) /
3629 if (outputHeight < 0 || outputWidth < 0) {
3632 "calculated output height and width must be non-negative, "
3634 outputHeight,
", width = ", outputWidth);
3637 outputShape[1] = outputHeight;
3638 outputShape[2] = outputWidth;
3639 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3643LogicalResult tosa::ResizeOp::verify() {
3646 if (isa<BlockScaledType>(inputElementType) &&
3647 getMode() != ResizeMode::NEAREST_NEIGHBOR)
3648 return emitOpError(
"requires NEAREST_NEIGHBOR mode for block scaled input");
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);
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);
3667 ShapeAdaptor indicesShape(adaptor.getIndices().getType());
3668 if (indicesShape.hasRank()) {
3669 if (outputShape[0] == ShapedType::kDynamic)
3670 outputShape[0] = indicesShape.getDimSize(0);
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);
3681 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3685LogicalResult tosa::ScatterOp::verify() {
3695 const ShapeAdaptor valuesInShape(getValuesIn().
getType());
3697 const ShapeAdaptor inputShape(getInput().
getType());
3698 const ShapeAdaptor outputShape(getValuesOut().
getType());
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);
3709 if (indicesShape.hasRank()) {
3710 const int64_t indicesN = indicesShape.getDimSize(0);
3711 w = indicesShape.getDimSize(1);
3712 if (n == ShapedType::kDynamic)
3714 else if (indicesN != ShapedType::kDynamic && n != indicesN)
3715 return emitOpError() <<
"requires indices dimension 0 to have size " << n
3716 <<
", got " << indicesN;
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)
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)
3729 else if (inputW != ShapedType::kDynamic && w != inputW)
3730 return emitOpError() <<
"requires input dimension 1 to have size " << w
3731 <<
", got " << inputW;
3733 if (c == ShapedType::kDynamic)
3735 else if (inputC != ShapedType::kDynamic && c != inputC)
3736 return emitOpError() <<
"requires input dimension 2 to have size " << c
3737 <<
", got " << inputC;
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 &&
3745 return emitOpError() <<
"requires values_out dimension 0 to have size "
3746 << n <<
", got " << outputN;
3747 if (k == ShapedType::kDynamic)
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 &&
3754 return emitOpError() <<
"requires values_out dimension 2 to have size "
3755 << c <<
", got " << outputC;
3757 if (k != ShapedType::kDynamic && w != ShapedType::kDynamic && !(k >= w))
3758 return emitOpError() <<
"requires dimensions K >= W, got K=" << k
3767 int64_t axisVal = axis.getValue().getSExtValue();
3768 if (!operandShape.
hasRank() || operandShape.
getRank() <= axisVal) {
3774 operandShape.
getDims(outputShape);
3775 outputShape[axisVal] = 1;
3780#define COMPATIBLE_RETURN_TYPES(OP) \
3781 bool OP::isCompatibleReturnTypes(TypeRange l, TypeRange r) { \
3782 if (l.size() != r.size() || l.size() != 1) \
3784 if (getElementTypeOrSelf(l[0]) != getElementTypeOrSelf(r[0])) \
3786 return succeeded(verifyCompatibleShape(l[0], r[0])); \
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) { \
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); \
3801 COMPATIBLE_RETURN_TYPES(OP)
3809#undef REDUCE_SHAPE_INFER
3811#undef COMPATIBLE_RETURN_TYPES
3813template <
typename T>
3816 TensorType inputType = op.getInput().getType();
3817 TensorType outputType = op.getOutput().getType();
3818 int32_t reduceAxis = op.getAxis();
3820 if (reduceAxis < 0) {
3821 op.emitOpError(
"reduce axis must not be negative");
3825 int64_t inputRank = inputType.getRank();
3828 if (reduceAxis >= inputRank && (reduceAxis != 0 || inputRank != 0)) {
3829 op.emitOpError(
"expect input tensor rank (")
3830 << inputRank <<
") to be larger than reduce axis (" << reduceAxis
3836 int64_t outputRank = outputType.getRank();
3837 if (inputType.
hasRank() && outputRank != inputType.getRank()) {
3839 "expect output tensor rank to be equal to input tensor rank");
3842 if (reduceAxis >= outputRank && (reduceAxis != 0 || outputRank != 0)) {
3843 op.emitOpError(
"expect output tensor rank (")
3844 << outputRank <<
") to be larger than reduce axis (" << reduceAxis
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];
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); }
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); \
3928#undef PRED_SHAPE_INFER
3930LogicalResult tosa::NegateOp::inferReturnTypeComponents(
3931 MLIRContext *context, ::std::optional<Location> location,
3932 NegateOp::Adaptor adaptor,
3934 ShapeAdaptor inputShape(adaptor.getInput1().getType());
3939LogicalResult tosa::NegateOp::verify() {
3941 const Type input1Type = getInput1().getType();
3942 const Type outputType = getOutput().getType();
3947 const SmallVector<Type, 2> types = {input1Type, outputType};
3949 return emitOpError() <<
"requires the same shape for input1 and output";
3952 const Type input1ZpEType =
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;
3960 const Type outputZpEType =
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;
3968 FailureOr<int64_t> maybeIZp = getInput1ZeroPoint();
3969 if (succeeded(maybeIZp) && verifyInput1ZeroPoint(*maybeIZp).failed())
3972 FailureOr<int64_t> maybeOZp = getOutputZeroPoint();
3973 if (succeeded(maybeOZp) && verifyOutputZeroPoint(*maybeOZp).failed())
3984 outputShape.resize(4, ShapedType::kDynamic);
3999 if (ShapedType::isStatic(height)) {
4000 int64_t padded = height + pad[0] + pad[1] - kernel[0];
4001 outputShape[1] = padded / stride[0] + 1;
4004 if (ShapedType::isStatic(width)) {
4005 int64_t padded = width + pad[2] + pad[3] - kernel[1];
4006 outputShape[2] = padded / stride[1] + 1;
4013template <
typename AdaptorT>
4019 if (ShapedType::isDynamic(current))
4020 current = candidate;
4029 : adaptor(adaptor) {}
4033 const ShapeAdaptor inputShape(adaptor.getInput().getType());
4041 outputShape[0] = outputBatch;
4042 inputSpatial[0] = inputHeight;
4043 inputSpatial[1] = inputWidth;
4048 const ShapeAdaptor weightShape(adaptor.getWeight().getType());
4056 outputShape[3] = outputChannels;
4057 weightSpatial[0] = kernelHeight;
4058 weightSpatial[1] = kernelWidth;
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());
4075 Conv2DOp::Adaptor adaptor;
4083 : adaptor(adaptor) {}
4087 const ShapeAdaptor inputDataShape(adaptor.getInputData().getType());
4088 if (inputDataShape.
hasRank()) {
4093 outputShape[0] = outputBatch;
4094 inputSpatial[0] = inputHeight;
4095 inputSpatial[1] = inputWidth;
4098 const ShapeAdaptor inputScaleShape(adaptor.getInputScale().getType());
4099 if (!inputScaleShape.
hasRank())
4113 const ShapeAdaptor weightDataShape(adaptor.getWeightData().getType());
4114 if (weightDataShape.
hasRank()) {
4119 outputShape[3] = outputChannels;
4120 weightSpatial[0] = kernelHeight;
4121 weightSpatial[1] = kernelWidth;
4124 const ShapeAdaptor weightScaleShape(adaptor.getWeightScale().getType());
4125 if (!weightScaleShape.
hasRank())
4154 Conv2DBlockScaledOp::Adaptor adaptor;
4162 : adaptor(adaptor) {}
4166 const ShapeAdaptor inputShape(adaptor.getInput().getType());
4175 outputShape[0] = outputBatch;
4176 inputSpatial[0] = inputDepth;
4177 inputSpatial[1] = inputHeight;
4178 inputSpatial[2] = inputWidth;
4183 const ShapeAdaptor weightShape(adaptor.getWeight().getType());
4192 outputShape[4] = outputChannels;
4193 weightSpatial[0] = kernelDepth;
4194 weightSpatial[1] = kernelHeight;
4195 weightSpatial[2] = kernelWidth;
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());
4212 Conv3DOp::Adaptor adaptor;
4215template <
typename AdaptorT>
4221 ShapedType::kDynamic);
4223 ShapedType::kDynamic);
4225 ShapedType::kDynamic);
4227 convShapeAdaptor.inferInputShape(outputShape, inputSpatial);
4228 convShapeAdaptor.inferWeightShape(outputShape, weightSpatial);
4230 const ShapeAdaptor biasShape = adaptor.getBias().getType();
4233 if (biasSize != 1) {
4234 const size_t outputChannelDim = convShapeAdaptor.getOutputRank() - 1;
4235 outputShape[outputChannelDim] =
4236 ShapedType::isDynamic(outputShape[outputChannelDim])
4238 : outputShape[outputChannelDim];
4245 if (failed(convShapeAdaptor.getSpatialParameters(padValues, strideValues,
4251 for (
int64_t dim = 0; dim < convShapeAdaptor.getNumSpatialDims(); ++dim) {
4252 if (!ShapedType::isStatic(inputSpatial[dim]) ||
4253 !ShapedType::isStatic(weightSpatial[dim]))
4256 inputSpatial[dim] + padValues[2 * dim] + padValues[2 * dim + 1];
4258 (weightSpatial[dim] - 1) * dilationValues[dim] + 1;
4259 const int64_t unstridedResult = inputSize - filterSize + 1;
4260 outputShape[dim + 1] = (unstridedResult - 1) / strideValues[dim] + 1;
4267LogicalResult Conv2DOp::inferReturnTypeComponents(
4268 MLIRContext *context, ::std::optional<Location> location,
4269 Conv2DOp::Adaptor adaptor,
4270 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4274LogicalResult Conv2DOp::verify() {
4280LogicalResult Conv2DBlockScaledOp::inferReturnTypeComponents(
4281 MLIRContext *context, ::std::optional<Location> location,
4282 Conv2DBlockScaledOp::Adaptor adaptor,
4283 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4287LogicalResult Conv2DBlockScaledOp::verify() {
4289 getWeightData().
getType(),
"input_data",
4292 getWeightScale().
getType(),
"input_scale",
4295 getOutput().
getType(),
"bias",
"output")))
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;
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);
4316 const ShapeAdaptor inputScaleShape(getInputScale().
getType());
4317 if (inputScaleShape.hasRank()) {
4319 "input_scale",
"batch size")) ||
4321 "input_scale",
"input height")) ||
4323 "input_scale",
"input width")))
4325 multiplesOfIC = inputScaleShape.getDimSize(3);
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);
4334 "weight_data",
"input channels")))
4338 const ShapeAdaptor weightScaleShape(getWeightScale().
getType());
4339 if (weightScaleShape.hasRank()) {
4341 "weight_scale",
"output channels")) ||
4343 "weight_scale",
"kernel height")) ||
4345 "weight_scale",
"kernel width")) ||
4347 weightScaleShape.getDimSize(3),
4348 "weight_scale",
"input channel blocks")))
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;
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;
4361 if (ShapedType::isStatic(IC) && ShapedType::isStatic(multiplesOfIC) &&
4362 multiplesOfIC != IC / blockSize)
4364 "expect scale operands dimension 2 to equal IC/block_size (")
4365 << IC <<
"/" << blockSize <<
")"
4366 <<
", got " << multiplesOfIC;
4369 SmallVector<int64_t> padValues;
4371 if (llvm::any_of(padValues, [](int64_t p) {
return p < 0; }))
4372 return emitOpError(
"expect all padding values to be >= 0, got ")
4376 SmallVector<int64_t> strideValues;
4378 if (llvm::any_of(strideValues, [](int64_t s) {
return s < 1; }))
4379 return emitOpError(
"expect all stride values to be >= 1, got ")
4383 SmallVector<int64_t> dilationValues;
4386 if (llvm::any_of(dilationValues, [](int64_t d) {
return d < 1; }))
4387 return emitOpError(
"expect all dilation values to be >= 1, got ")
4392 const ShapeAdaptor outputShape(getOutput().
getType());
4393 if (!padValues.empty() && !strideValues.empty() && !dilationValues.empty() &&
4394 outputShape.hasRank()) {
4396 padValues[0], padValues[1], strideValues[0],
4397 dilationValues[0],
"height",
"y",
"top",
4400 padValues[2], padValues[3], strideValues[1],
4401 dilationValues[1],
"width",
"x",
"left",
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)
4417 if (biasChannels != outputChannels && biasChannels != 1)
4419 "bias channels expected to be equal to output channels (")
4420 << outputChannels <<
") or 1, got " << biasChannels;
4426LogicalResult Conv3DOp::inferReturnTypeComponents(
4427 MLIRContext *context, ::std::optional<Location> location,
4428 Conv3DOp::Adaptor adaptor,
4429 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4433LogicalResult Conv3DOp::verify() {
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();
4446 inferredReturnShapes);
4449LogicalResult AvgPool2dAdaptiveOp::inferReturnTypeComponents(
4450 MLIRContext *context, ::std::optional<Location> location,
4451 AvgPool2dAdaptiveOp::Adaptor adaptor,
4452 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4453 ShapeAdaptor inputShape(adaptor.getInput().getType());
4455 llvm::SmallVector<int64_t> kernelValues;
4456 llvm::SmallVector<int64_t> strideValues;
4457 llvm::SmallVector<int64_t> padValues;
4464 padValues, inferredReturnShapes);
4467 llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamic);
4468 if (inputShape.hasRank()) {
4470 outputShape[0] = inputShape.getDimSize(0);
4471 outputShape[3] = inputShape.getDimSize(3);
4474 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
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();
4485 inferredReturnShapes);
4488LogicalResult MaxPool2dAdaptiveOp::inferReturnTypeComponents(
4489 MLIRContext *context, ::std::optional<Location> location,
4490 MaxPool2dAdaptiveOp::Adaptor adaptor,
4491 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4492 ShapeAdaptor inputShape(adaptor.getInput().getType());
4494 llvm::SmallVector<int64_t> kernelValues;
4495 llvm::SmallVector<int64_t> strideValues;
4496 llvm::SmallVector<int64_t> padValues;
4503 padValues, inferredReturnShapes);
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);
4511 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4515LogicalResult MaxPool2dOp::verify() {
4526LogicalResult MaxPool2dAdaptiveOp::verify() {
4531 AdaptivePoolingConstShapeValues values;
4535 values.pad, getInput(), getOutput())))
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);
4547 int64_t inputWidth = ShapedType::kDynamic;
4548 int64_t inputHeight = ShapedType::kDynamic;
4549 int64_t inputChannels = ShapedType::kDynamic;
4551 int64_t weightWidth = ShapedType::kDynamic;
4552 int64_t weightHeight = ShapedType::kDynamic;
4553 int64_t depthChannels = ShapedType::kDynamic;
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);
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)
4572 depthChannels = weightShape.getDimSize(3);
4577 if (ShapedType::isStatic(inputChannels) &&
4578 ShapedType::isStatic(depthChannels)) {
4579 outputShape[3] = inputChannels * depthChannels;
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;
4590 llvm::ArrayRef<int64_t> dilation = adaptor.getDilation();
4591 llvm::ArrayRef<int64_t> padding = adaptor.getPad();
4592 llvm::ArrayRef<int64_t> stride = adaptor.getStride();
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;
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;
4608 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4612LogicalResult DepthwiseConv2DOp::verify() {
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);
4624 int64_t inputWidth = ShapedType::kDynamic;
4625 int64_t inputHeight = ShapedType::kDynamic;
4626 int64_t weightWidth = ShapedType::kDynamic;
4627 int64_t weightHeight = ShapedType::kDynamic;
4630 ShapeAdaptor inputShape(adaptor.getInput().getType());
4631 if (inputShape.hasRank()) {
4632 outputShape[0] = ShapedType::isDynamic(outputShape[0])
4633 ? inputShape.getDimSize(0)
4635 inputHeight = inputShape.getDimSize(1);
4636 inputWidth = inputShape.getDimSize(2);
4640 ShapeAdaptor weightShape(adaptor.getWeight().getType());
4641 if (weightShape.hasRank()) {
4642 outputShape[3] = ShapedType::isDynamic(outputShape[3])
4643 ? weightShape.getDimSize(0)
4645 weightHeight = weightShape.getDimSize(1);
4646 weightWidth = weightShape.getDimSize(2);
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;
4657 llvm::ArrayRef<int64_t> padding = adaptor.getOutPad();
4658 llvm::ArrayRef<int64_t> stride = adaptor.getStride();
4660 if (ShapedType::isStatic(inputHeight) && ShapedType::isStatic(weightHeight)) {
4661 int64_t calculateSize =
4662 (inputHeight - 1) * stride[0] + padding[0] + padding[1] + weightHeight;
4664 ShapedType::isDynamic(outputShape[1]) ? calculateSize : outputShape[1];
4667 if (ShapedType::isStatic(inputWidth) && ShapedType::isStatic(weightWidth)) {
4668 int64_t calculateSize =
4669 (inputWidth - 1) * stride[1] + padding[2] + padding[3] + weightWidth;
4671 ShapedType::isDynamic(outputShape[2]) ? calculateSize : outputShape[2];
4674 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4678LogicalResult TransposeConv2DOp::verify() {
4682 const llvm::ArrayRef<int64_t> strides = getStride();
4683 const int64_t strideY = strides[0];
4684 const int64_t strideX = strides[1];
4686 if (strideY < 1 || strideX < 1)
4687 return emitOpError(
"expect all stride values to be >= 1, got [")
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 <<
"="
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];
4707 const auto weightType =
4708 llvm::dyn_cast<RankedTensorType>(getWeight().
getType());
4711 const int64_t kernelHeight = weightType.getDimSize(1);
4712 if (ShapedType::isStatic(kernelHeight)) {
4713 if (
failed(checkPadAgainstKernelDim(outPadTop, kernelHeight,
4714 "out_pad_top",
"KH")))
4717 if (
failed(checkPadAgainstKernelDim(outPadBottom, kernelHeight,
4718 "out_pad_bottom",
"KH")))
4722 const int64_t kernelWidth = weightType.getDimSize(2);
4723 if (ShapedType::isStatic(kernelWidth)) {
4724 if (
failed(checkPadAgainstKernelDim(outPadLeft, kernelWidth,
4725 "out_pad_left",
"KW")))
4728 if (
failed(checkPadAgainstKernelDim(outPadRight, kernelWidth,
4729 "out_pad_right",
"KW")))
4735 const auto outputType =
4736 llvm::dyn_cast<RankedTensorType>(getOutput().
getType());
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);
4746 if (ShapedType::isStatic(inputHeight) &&
4747 ShapedType::isStatic(outputHeight)) {
4749 (inputHeight - 1) * strideY + outPadTop + outPadBottom + kernelHeight)
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;
4758 const int64_t inputWidth = inputType.getDimSize(2);
4759 const int64_t kernelWidth = weightType.getDimSize(2);
4760 const int64_t outputWidth = outputType.getDimSize(2);
4762 if (ShapedType::isStatic(inputWidth) && ShapedType::isStatic(outputWidth)) {
4764 (inputWidth - 1) * strideX + outPadLeft + outPadRight + kernelWidth)
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 <<
" + "
4774 const auto biasType = llvm::dyn_cast<RankedTensorType>(getBias().
getType());
4779 const int64_t biasChannels = biasType.getDimSize(0);
4782 if (biasChannels == ShapedType::kDynamic)
4785 const int64_t outputChannels = outputType.getDimSize(3);
4786 if (!ShapedType::isDynamic(outputChannels) &&
4787 biasChannels != outputChannels && biasChannels != 1)
4789 "bias channels expected to be equal to output channels (")
4790 << outputChannels <<
") or 1, got " << biasChannels;
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,
4799 build(builder, state, output, input, multiplier, shift, inputZp, outputZp,
4800 scale32, roundingMode, perChannel,
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,
4813LogicalResult RescaleOp::verify() {
4814 const auto inputType = llvm::cast<ShapedType>(getInput().
getType());
4815 auto inputElementType =
4817 if (!mlir::isa<IntegerType>(inputElementType)) {
4818 emitOpError(
"expect input to have integer element type, got ")
4819 << inputElementType;
4823 const auto outputType = llvm::cast<ShapedType>(getOutput().
getType());
4824 auto outputElementType =
4826 if (!mlir::isa<IntegerType>(outputElementType)) {
4827 emitOpError(
"expect output to have integer element type, got ")
4828 << outputElementType;
4833 return emitOpError(
"requires input_unsigned to be true for unsigned input "
4835 << inputElementType;
4837 if (outputElementType.isUnsignedInteger() && !getOutputUnsigned())
4839 "requires output_unsigned to be true for unsigned output "
4841 << outputElementType;
4851 const auto multiplierType = llvm::cast<ShapedType>(getMultiplier().
getType());
4853 if (getScale32() && !multiplierType.getElementType().isInteger(32)) {
4854 emitOpError(
"expect i32 element type for multiplier for scale32=true, got ")
4855 << multiplierType.getElementType();
4860 if (!getScale32() && !multiplierType.getElementType().isInteger(16)) {
4862 "expect i16 element type for multiplier for scale32=false, got ")
4863 << multiplierType.getElementType();
4867 if (!inputType.hasRank())
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();
4881 numChannels = inputType.getDimSize(inputType.getRank() - 1);
4884 if (outputType.hasRank()) {
4886 getOperation(), outputType, inputType.getShape())))
4890 if (multiplierType.hasRank()) {
4891 ArrayRef<int64_t> multiplierShape = multiplierType.getShape();
4893 if (multiplierShape[0] != ShapedType::kDynamic &&
4894 multiplierShape[0] != numChannels) {
4895 emitOpError(
"expect shape of { ")
4896 << numChannels <<
" } for multiplier input, got { "
4897 << multiplierShape[0] <<
" }";
4902 const auto shiftType = llvm::cast<ShapedType>(getShift().
getType());
4903 if (shiftType.hasRank()) {
4904 ArrayRef<int64_t> shiftShape = shiftType.getShape();
4906 if (shiftShape[0] != ShapedType::kDynamic && shiftShape[0] != numChannels) {
4907 emitOpError(
"expect shape of { ")
4908 << numChannels <<
" } for shift input, got { " << shiftShape[0]
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));
4926void CastOp::build(OpBuilder &builder, OperationState &state, Type output,
4929 build(builder, state, output, input,
4933void CastOp::build(OpBuilder &builder, OperationState &state, Type output,
4934 Value input,
bool inputUnsigned) {
4935 build(builder, state, output, input, builder.
getBoolAttr(inputUnsigned));
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();
4944 const bool inputIsBlockScaled = llvm::isa<BlockScaledType>(inputElementType);
4945 const bool outputIsBlockScaled =
4946 llvm::isa<BlockScaledType>(outputElementType);
4948 const bool isUnsigned = this->getInputUnsigned();
4950 const bool isBoolType = inputDataType.
isInteger(1);
4953 if (!inputDataType.
isInteger() || isBoolType)
4954 return emitOpError()
4955 <<
"attribute input_unsigned requires integer type inputs. Got: "
4959 return emitOpError(
"requires input_unsigned to be true for unsigned input "
4963 if (!inputIsBlockScaled && !outputIsBlockScaled)
4966 if (inputIsBlockScaled && outputIsBlockScaled)
4967 return emitOpError()
4968 <<
"requires exactly one of input or output to have block scaled "
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;
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));
4991LogicalResult CastFromBlockScaledOp::verify() {
4992 const Type inputDataType = getInputData().getType();
4993 const Type outputDataType = getResult().getType();
4995 return emitOpError() <<
"require compatible shapes for input_data ("
4996 << inputDataType <<
") and " <<
"output_data ("
4997 << outputDataType <<
")";
4999 const ShapeAdaptor inputDataShape = ShapeAdaptor(inputDataType);
5001 if (inputDataShape.
hasRank()) {
5002 const unsigned int blockSize =
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 =
5008 if (inputDataLastDim % blockSize != 0)
5009 return emitOpError() <<
"expect last dimension of input_data ("
5011 <<
") to be divisible by block_size (" << blockSize
5014 const Type inputScaleType = getInputScale().getType();
5015 const ShapeAdaptor inputScaleShape = ShapeAdaptor(inputScaleType);
5017 if (inputScaleShape.
hasRank()) {
5018 SmallVector<int64_t> inputDataDims, inputScaleDims;
5019 inputDataShape.
getDims(inputDataDims);
5020 inputScaleShape.
getDims(inputScaleDims);
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";
5031 const SmallVector<int64_t, 2> dimsToCheck{inputDataLastDim / blockSize,
5032 inputScaleDims.back()};
5033 if (ShapedType::isStatic(inputDataLastDim) &&
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 <<
")";
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())
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;
5065 inferredReturnShapes.push_back(ShapedTypeComponents(outputScaleShape));
5069LogicalResult CastToBlockScaledOp::verify() {
5070 const Type inputDataType = getInputData().getType();
5071 const Type outputDataType = getResult(0).getType();
5073 return emitOpError() <<
"require compatible shapes for input_data ("
5074 << inputDataType <<
") and " <<
"output_data ("
5075 << outputDataType <<
")";
5077 const unsigned int blockSize =
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 =
5085 if (ShapedType::isStatic(inputDataLastDim) &&
5086 inputDataLastDim % blockSize != 0)
5087 return emitOpError() <<
"expect last dimension of input_data ("
5089 <<
") to be divisible by block_size (" << blockSize
5093 const ShapeAdaptor outputDataShape = ShapeAdaptor(outputDataType);
5094 const Type outputScaleType = getResult(1).getType();
5095 const ShapeAdaptor outputScaleShape = ShapeAdaptor(outputScaleType);
5097 SmallVector<int64_t> outputDataDims, outputScaleDims;
5098 outputDataShape.
getDims(outputDataDims);
5099 outputScaleShape.
getDims(outputScaleDims);
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 ("
5108 <<
") except for the last dimension";
5110 const int64_t outputDataLastDim = outputDataDims.back();
5111 const SmallVector<int64_t, 2> dimsToCheck{outputDataLastDim / blockSize,
5112 outputScaleDims.back()};
5113 if (ShapedType::isStatic(outputDataLastDim) &&
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 <<
")";
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);
5136 if (yieldOps.empty())
5140 llvm::SmallVector<ValueKnowledge> resultKnowledge;
5141 resultKnowledge.reserve(yieldOps.front().getNumOperands());
5142 for (
auto operand : yieldOps.front().getOperands()) {
5143 resultKnowledge.push_back(
5147 for (
auto yieldOp : yieldOps) {
5148 if (resultKnowledge.size() != yieldOp.getNumOperands())
5151 for (
const auto &it : llvm::enumerate(yieldOp.getOperands())) {
5152 int32_t index = it.index();
5154 resultKnowledge[index],
5158 resultKnowledge[index] = meet;
5162 for (
const ValueKnowledge &
result : resultKnowledge) {
5163 inferredReturnShapes.push_back(
result.getShapedTypeComponents());
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);
5180 if (yieldOps.empty())
5184 llvm::SmallVector<ValueKnowledge> resultKnowledge;
5185 resultKnowledge.reserve(yieldOps.front().getNumOperands());
5186 for (
auto operand : yieldOps.front().getOperands()) {
5187 resultKnowledge.push_back(
5191 for (
auto yieldOp : yieldOps) {
5192 if (resultKnowledge.size() != yieldOp.getNumOperands())
5195 for (
const auto &it : llvm::enumerate(yieldOp.getOperands())) {
5196 int32_t index = it.index();
5198 resultKnowledge[index],
5200 resultKnowledge[index] = meet;
5205 for (
const ValueKnowledge &
result : resultKnowledge) {
5206 inferredReturnShapes.push_back(
result.getShapedTypeComponents());
5215 StringRef prefix =
"") {
5216 assert(blocksArgs.size() == initializers.size() &&
5217 "expected same length of arguments and initializers");
5218 if (initializers.empty())
5221 parser << prefix <<
'(';
5222 llvm::interleaveComma(
5223 llvm::zip(blocksArgs, initializers), parser,
5224 [&](
auto it) { parser << std::get<0>(it) <<
" = " << std::get<1>(it); });
5229ParseResult IfOp::parse(OpAsmParser &parser, OperationState &
result) {
5231 result.regions.reserve(2);
5232 Region *thenRegion =
result.addRegion();
5233 Region *elseRegion =
result.addRegion();
5235 OpAsmParser::UnresolvedOperand cond;
5240 SmallVector<OpAsmParser::Argument, 4> regionArgs;
5241 SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
5244 OptionalParseResult listResult =
5252 "expected type for condition operand");
5258 "expected type for condition operand");
5266 FunctionType functionType;
5270 <<
"expected list of types for block arguments "
5271 <<
"followed by arrow type and list of return types";
5273 result.addTypes(functionType.getResults());
5275 if (functionType.getNumInputs() != operands.size()) {
5277 <<
"expected as many input types as operands " <<
"(expected "
5278 << operands.size() <<
" got " << functionType.getNumInputs()
5309void IfOp::print(OpAsmPrinter &p) {
5310 p <<
" " << getCondition();
5313 getInputList(),
" ");
5315 p << getCondition().getType();
5317 if (!getInputList().empty()) {
5319 llvm::interleaveComma(getInputList().getTypes(), p);
5328 auto &elseRegion = getElseGraph();
5329 if (!elseRegion.
empty()) {
5337LogicalResult IfOp::verify() {
5339 "'then_graph' arguments", getInputList(),
5345 "'else_graph' arguments", getInputList(),
5351 if (getThenGraph().front().mightHaveTerminator()) {
5353 dyn_cast<tosa::YieldOp>(getThenGraph().front().getTerminator());
5355 *
this, thenYield.getInputs(),
"'then_graph' results",
5356 getOutputList(),
"'output_list'")
5362 if (getElseGraph().front().mightHaveTerminator()) {
5364 dyn_cast<tosa::YieldOp>(getElseGraph().front().getTerminator());
5366 *
this, elseYield.getInputs(),
"'else_graph' results",
5367 getOutputList(),
"'output_list'")
5372 auto condType = getCondition().getType();
5374 return emitOpError() <<
"'condition' must be a size 1 tensor, got "
5380LogicalResult WhileOp::verify() {
5382 getOutputList(),
"'output_list'")
5387 "'cond_graph' arguments", getInputList(),
5393 "'body_graph' arguments", getInputList(),
5398 if (getBodyGraph().front().mightHaveTerminator()) {
5400 dyn_cast<tosa::YieldOp>(getBodyGraph().front().getTerminator());
5402 "'body_graph' results",
5403 getInputList(),
"'input_list'")
5410 if (!getCondGraph().front().mightHaveTerminator())
5414 dyn_cast<tosa::YieldOp>(getCondGraph().front().getTerminator());
5418 if (condYield.getInputs().size() != 1)
5419 return emitOpError() <<
"require 'cond_graph' only have one result";
5421 auto condOutType = condYield.getInputs()[0].getType();
5423 return emitOpError() <<
"'cond_graph' result must be a size 1 tensor, got "
5427 return emitOpError() <<
"'cond_graph' result must be a boolean tensor, got "
5433LogicalResult ReverseOp::verify() {
5434 TensorType inputType = getInput1().getType();
5435 int32_t reverseAxis = getAxis();
5437 if (reverseAxis < 0)
5438 return emitOpError(
"expected non-negative reverse axis");
5440 int64_t inputRank = inputType.getRank();
5443 if (reverseAxis >= inputRank && (reverseAxis != 0 || inputRank != 0))
5444 return emitOpError(
"expect input tensor rank (")
5445 << inputRank <<
") to be larger than reverse axis (" << reverseAxis
5452LogicalResult tosa::SelectOp::verify() {
5463 auto predicateType = llvm::dyn_cast<ShapedType>(getPred().
getType());
5464 if (!predicateType) {
5465 return emitOpError(
"expect shaped tensor for input1, got ")
5466 << getInput1().getType();
5468 auto predicateElementType = predicateType.getElementType();
5469 if (!predicateElementType.isInteger(1)) {
5470 return emitOpError(
"expect element type of bool for input1, got ")
5471 << predicateElementType;
5477LogicalResult tosa::VariableReadOp::verify() {
5485LogicalResult tosa::VariableWriteOp::verify() {
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();
5500 OptionalParseResult listResult =
5505 FunctionType functionType;
5510 result.addTypes(functionType.getResults());
5512 if (functionType.getNumInputs() != operands.size()) {
5514 <<
"expected as many input types as operands " <<
"(expected "
5515 << operands.size() <<
" got " << functionType.getNumInputs() <<
")";
5525 for (
size_t i = 0, e = regionArgs.size(); i != e; ++i)
5526 regionArgs[i].type = functionType.getInput(i);
5528 return failure(parser.
parseRegion(*cond, regionArgs) ||
5533void WhileOp::print(OpAsmPrinter &parser) {
5535 getInputList(),
" ");
5538 getResults().getTypes());
5544 (*this)->getDiscardableAttrDictionary().getValue());
5553 auto zpType = mlir::RankedTensorType::get({1}, srcElemType);
5554 if (llvm::isa<FloatType>(srcElemType)) {
5556 zpType, builder.
getFloatAttr(srcElemType,
static_cast<double>(zp)));
5557 return tosa::ConstOp::create(builder, loc, zpType, zpAttr);
5559 if (llvm::isa<IntegerType>(srcElemType)) {
5562 return tosa::ConstOp::create(builder, loc, zpType, zpAttr);
5564 llvm::errs() <<
"zero point is not allowed for unsupported data types\n";
5565 return std::nullopt;
5573 return mlir::isa<tosa::shapeType>(t);
5580 return emitError() <<
"invalid rank (must be >= 0): " << rank;
5586 if (mlir::isa<::mlir::tosa::shapeType>(v.getType())) {
5587 Operation *definingOp = v.getDefiningOp();
5589 return op->
emitOpError(
"shape operand is not compile time resolvable");
5602 auto getRank = [](
const Type type) {
5603 return mlir::cast<mlir::tosa::shapeType>(type).getRank();
5609 for (
auto type : operandTypes) {
5610 if (getRank(type) != rank) {
5611 return op->
emitOpError(
"operands don't have matching ranks");
5614 for (
auto type : resultTypes) {
5615 if (getRank(type) != rank) {
5616 return op->
emitOpError(
"result shape has different rank than operands");
5626LogicalResult tosa::ConstShapeOp::verify() {
5628 auto valuesRank = getValues().getType().getRank();
5629 if (valuesRank != 1)
5630 return emitOpError(
"expect elements in attribute values with rank 1");
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";
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 ")
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;
5660LogicalResult tosa::ConcatShapeOp::verify() {
5661 const tosa::shapeType outShapeType =
5662 cast<tosa::shapeType>(getResult().
getType());
5663 const int64_t outputRank = outShapeType.getRank();
5666 if (inputList.size() == 0)
5667 return emitOpError(
"requires at least one input shape");
5669 if (llvm::any_of(inputList, [](Value v) {
5670 return cast<tosa::shapeType>(v.
getType()).getRank() == 0;
5672 return emitOpError(
"requires all inputs shapes have a rank greater than 0");
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();
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;
5688LogicalResult tosa::SliceShapeOp::verify() {
5689 std::optional<int32_t> start;
5690 DenseIntElementsAttr startAttr;
5692 start = startAttr.getValues<int32_t>()[0];
5693 if (start && start.value() < 0)
5694 return emitOpError(
"expected non-negative start index, got ")
5697 std::optional<int32_t> size;
5698 DenseIntElementsAttr sizeAttr;
5700 size = sizeAttr.getValues<int32_t>()[0];
5701 if (size && size.value() <= 0)
5702 return emitOpError(
"expected positive size, got ") << size.value();
5707 const tosa::shapeType outShapeType =
5708 cast<tosa::shapeType>(getResult().
getType());
5709 const int64_t outputRank = outShapeType.getRank();
5710 if (outputRank != size)
5712 "expected output type size to be equal to size attribute, got ")
5713 << outputRank <<
" vs " << size.value();
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;
5734#define GET_ATTRDEF_CLASSES
5735#include "mlir/Dialect/Tosa/IR/TosaAttributes.cpp.inc"
5740#define GET_TYPEDEF_CLASSES
5741#include "mlir/Dialect/Tosa/IR/TosaOpsTypesBase.cpp.inc"
5762 printer << keyword <<
'(';
5784#define GET_OP_CLASSES
5785#include "mlir/Dialect/Tosa/IR/TosaOps.cpp.inc"
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,...
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.
static Type getValueType(Attribute attr)
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,...
static LogicalResult verifyMatMulShapes(T op, bool transposeB)
static ParseResult parseOptionalBoolClause(OpAsmParser &parser, StringRef keyword, BoolAttr &result)
static void printShapeToDiagnostic(InFlightDiagnostic &diag, ArrayRef< int64_t > shape)
static void buildMatMulOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value a, Value b)
static LogicalResult verifySameElementTypes(Operation *op, Type aType, Type bType, StringRef aName="input", StringRef bName="output")
static ParseResult parseLocalBound(OpAsmParser &parser, BoolAttr &result)
LogicalResult inferConvReturnTypeComponents(AdaptorT adaptor, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
static int64_t getMatMulBatchDim(const ShapeAdaptor &shape, int64_t outputRank, int64_t axis)
static SmallVector< int64_t > convertToMlirShape(ArrayRef< int64_t > shape)
static LogicalResult ReduceInferReturnTypes(ShapeAdaptor operandShape, Type inputType, IntegerAttr axis, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
static void printScaleValues(AsmPrinter &printer, ArrayRef< Attribute > scaleValues, Type)
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...
static LogicalResult verifyRescaleValueAndZpTypes(Operation *op, Value val, Value valZp, StringRef name)
static void printOptionalBoolClause(OpAsmPrinter &printer, StringRef keyword, BoolAttr attr)
static LogicalResult errorIfShapeNotSizeOne(Operation *op, Type type)
static void printLocalBound(OpAsmPrinter &printer, Operation *, BoolAttr attr)
LogicalResult argMaxMinVerify(T op)
static LogicalResult verifyMatMulZeroPointType(T op, Value input, Value zp, StringRef inputName, StringRef zpName)
static ParseResult parseScaleValues(AsmParser &parser, SmallVector< Attribute > &scaleValues, Type scaleType)
static ParseResult parseInputUnsigned(OpAsmParser &parser, BoolAttr &result)
#define REDUCE_SHAPE_INFER(OP)
static LogicalResult verifyConvOp(T op)
static LogicalResult verifyAvgPoolCommonTypeAndZpChecks(T op)
static LogicalResult verifyVariableOpErrorIf(T op, Type type, StringRef name)
static LogicalResult poolingInferReturnTypes(ShapeAdaptor inputShape, ArrayRef< int64_t > kernel, ArrayRef< int64_t > stride, ArrayRef< int64_t > pad, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
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...
static LogicalResult verifyPoolingOpImpl(Operation *op, ArrayRef< int64_t > kernel, ArrayRef< int64_t > strides, ArrayRef< int64_t > padding, Value input, Value output)
static std::optional< int64_t > idivCheck(const int64_t lhs, const int64_t rhs)
static void buildVariableOp(OpBuilder &builder, OperationState &result, StringRef name, Type variableType, Attribute initialValue)
static void buildMatMulLikeOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value a, Value b)
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)
static LogicalResult verifyReduceOp(T op)
#define NARY_SHAPE_INFER(OP)
#define ZERO_POINT_HELPER(OP, OPERAND_NAME, SIGN_EXTEND)
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.
LogicalResult inferArgMaxMinReturnTypeComponents(MLIRContext *context, ::std::optional< Location > location, A adaptor, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
static void extractAdaptivePoolingConstShapeOperands(T op, AdaptivePoolingConstShapeValues &values)
static LogicalResult verifyConvOpErrorIf(T op)
static FailureOr< int64_t > getZeroPoint(Value val, bool signExtend)
static constexpr bool IsSupportedAdaptivePoolConstShapeVerifyOp
LogicalResult tryUpdateDimOrFailure(Operation *op, int64_t &currDim, const int64_t newDim, const StringRef operandName, const StringRef dimName)
static LogicalResult NAryInferReturnTypes(const ValueShapeRange &operands, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
#define COMPATIBLE_RETURN_TYPES(OP)
static LogicalResult resolveBroadcastShape(const ValueShapeRange &operands, SmallVector< int64_t > &outShape)
static LogicalResult verifyMatMulQuantizedOperandsType(T op, Type aElementType, Type bElementType)
static LogicalResult verifyOutputShapeCompatibleWithExpected(Operation *op, ShapedType outputType, ArrayRef< int64_t > expectedShape, StringRef outputName="output")
static void printInputUnsigned(OpAsmPrinter &printer, Operation *, BoolAttr attr)
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 ...
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...
static SmallVector< int64_t > getMatMulBatchShape(const ShapeAdaptor &shape)
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...
static LogicalResult errorIfTypeOrShapeMismatch(Operation *op, Type type1, StringRef name1, Type type2, StringRef name2)
static LogicalResult inferMatMulReturnTypeComponents(const ShapeAdaptor &aShape, const ShapeAdaptor &bShape, bool transposeB, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
static void buildMatMulTOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value a, Value b)
static FailureOr< SmallVector< int64_t > > resolveMatMulOutputShape(const ShapeAdaptor &aShape, const ShapeAdaptor &bShape, int64_t outputRank, bool transposeB)
static FailureOr< int64_t > resolveBroadcastDim(const int64_t dim1, const int64_t dim2)
static LogicalResult verifyZeroPoint(T op, Value val, const int64_t &zp, const std::string &operand)
static LogicalResult verifyPoolingOp(T op)
static LogicalResult verifyDimIsPowerOfTwo(Operation *op, const int64_t dimSize, const llvm::StringRef dimName)
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
static void updateIfDynamic(int64_t ¤t, int64_t candidate)
void inferWeightShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &weightSpatial)
LogicalResult getSpatialParameters(SmallVector< int64_t > &padValues, SmallVector< int64_t > &strideValues, SmallVector< int64_t > &dilationValues)
void inferInputShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &inputSpatial)
ConvInferShapeAdaptor(Conv2DBlockScaledOp::Adaptor adaptor)
int64_t getOutputRank() const
int64_t getNumSpatialDims() const
void inferInputShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &inputSpatial)
void inferWeightShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &weightSpatial)
ConvInferShapeAdaptor(Conv2DOp::Adaptor adaptor)
int64_t getNumSpatialDims() const
int64_t getOutputRank() const
LogicalResult getSpatialParameters(SmallVector< int64_t > &padValues, SmallVector< int64_t > &strideValues, SmallVector< int64_t > &dilationValues)
int64_t getNumSpatialDims() const
void inferWeightShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &weightSpatial)
int64_t getOutputRank() const
ConvInferShapeAdaptor(Conv3DOp::Adaptor adaptor)
void inferInputShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &inputSpatial)
LogicalResult getSpatialParameters(SmallVector< int64_t > &padValues, SmallVector< int64_t > &strideValues, SmallVector< int64_t > &dilationValues)
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.
MutableArrayRef< BlockArgument > BlockArgListType
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,...
IntegerAttr getIndexAttr(int64_t value)
IntegerAttr getIntegerAttr(Type type, int64_t value)
FloatAttr getFloatAttr(Type type, double value)
IntegerType getIntegerType(unsigned width)
BoolAttr getBoolAttr(bool value)
StringAttr getStringAttr(const Twine &bytes)
DenseIntElementsAttr getIndexTensorAttr(ArrayRef< int64_t > values)
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...
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...
MLIRContext is the top-level object for a collection of MLIR operations.
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 ®ion, 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.
This class indicates that op operates on tosa shape types.
Operation is the basic unit of execution within MLIR.
ResultRange result_range
Support result iteration.
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
OperandRange operand_range
operand_type_range getOperandTypes()
result_type_range getResultTypes()
operand_range getOperands()
Returns an iterator on the underlying Value's.
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.
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...
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.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
bool isUnsignedInteger() const
Return true if this is an unsigned integer type (with the specified width).
bool isInteger() const
Return true if this is an integer type (with the specified width).
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
This class provides an abstraction over the different types of ranges over Values.
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...
Type getType() const
Return the type of this value.
ArrayRef< T > asArrayRef() const
LogicalResult verifyAtLeastNOperands(Operation *op, unsigned numOperands)
LogicalResult verifyTosaShapeOperatorWithSameRanks(Operation *op)
LogicalResult verifyTosaResolvableShapeOperands(Operation *op)
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...
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.
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)
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)
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)
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)
std::optional< Value > createZeroPointTensor(OpBuilder &builder, Location loc, Type srcElemType, int64_t zp=0)
bool isa_tosa_shape_type(mlir::Type t)
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)
LogicalResult verifyBlockScaledTensorType(mlir::Type type, llvm::function_ref< mlir::InFlightDiagnostic()> emitError=nullptr, bool allowScaleValues=false)
std::string getTosaTensorTypeErrorMessage(mlir::Type type)
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.
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.
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.
llvm::function_ref< Fn > function_ref
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)
static ValueKnowledge getKnowledgeFromType(Type type)