29#include "llvm/ADT/APFloat.h"
30#include "llvm/ADT/SmallVectorExtras.h"
31#include "llvm/ADT/TypeSwitch.h"
39#include "mlir/Dialect/Tosa/IR/TosaOpsDialect.cpp.inc"
46#include "mlir/Dialect/Tosa/IR/TosaEnums.cpp.inc"
47#include "mlir/Dialect/Tosa/IR/TosaInterfaces.cpp.inc"
50#include "mlir/Dialect/Tosa/IR/TosaDialectBytecode.cpp.inc"
55struct TosaInlinerInterface :
public DialectInlinerInterface {
56 using DialectInlinerInterface::DialectInlinerInterface;
64 IRMapping &map)
const final {
70 IRMapping &map)
const final {
71 return (isa<tosa::IfOp>(dest->getParentOp()) ||
72 isa<tosa::WhileOp>(dest->getParentOp()));
77struct TosaDialectBytecodeInterface :
public BytecodeDialectInterface {
78 TosaDialectBytecodeInterface(Dialect *dialect)
79 : BytecodeDialectInterface(dialect) {}
84 Attribute readAttribute(DialectBytecodeReader &reader)
const override {
88 LogicalResult writeAttribute(Attribute attr,
89 DialectBytecodeWriter &writer)
const override {
90 return ::writeAttribute(attr, writer);
96 Type readType(DialectBytecodeReader &reader)
const override {
100 LogicalResult writeType(Type type,
101 DialectBytecodeWriter &writer)
const override {
102 return ::writeType(type, writer);
105 void writeVersion(DialectBytecodeWriter &writer)
const final {
109 std::unique_ptr<DialectVersion>
110 readVersion(DialectBytecodeReader &reader)
const final {
112 reader.
emitError(
"Dialect does not support versioning");
116 LogicalResult upgradeFromVersion(Operation *topLevelOp,
117 const DialectVersion &version)
const final {
130 return {&getBodyGraph()};
139 return dim == -1 ? ShapedType::kDynamic : dim;
145 Type elementType = variableOp.getType();
148 return RankedTensorType::get(
shape, elementType);
155void TosaDialect::initialize() {
157#define GET_TYPEDEF_LIST
158#include "mlir/Dialect/Tosa/IR/TosaOpsTypesBase.cpp.inc"
162#include "mlir/Dialect/Tosa/IR/TosaOps.cpp.inc"
165#define GET_ATTRDEF_LIST
166#include "mlir/Dialect/Tosa/IR/TosaAttributes.cpp.inc"
168 addInterfaces<TosaDialectBytecodeInterface, TosaInlinerInterface>();
169 declarePromisedInterfaces<
170 shard::ShardingInterface, ClampOp, SigmoidOp, TanhOp, AddOp,
171 ArithmeticRightShiftOp, BitwiseAndOp, BitwiseOrOp, BitwiseXorOp, IntDivOp,
172 LogicalAndOp, LogicalLeftShiftOp, LogicalRightShiftOp, LogicalOrOp,
173 LogicalXorOp, MaximumOp, MinimumOp, MulOp, PowOp, SubOp, AbsOp,
174 BitwiseNotOp, CeilOp, ClzOp, ExpOp, FloorOp, LogOp, LogicalNotOp,
175 NegateOp, ReciprocalOp, RsqrtOp, SelectOp, EqualOp, GreaterOp,
176 GreaterEqualOp, MatMulOp>();
183 if (llvm::isa<shapeType>(type) && llvm::isa<DenseIntElementsAttr>(value)) {
184 return tosa::ConstShapeOp::create(builder, loc, type,
185 llvm::cast<DenseIntElementsAttr>(value));
187 if (llvm::isa<ElementsAttr>(value))
188 return tosa::ConstOp::create(builder, loc, type,
189 llvm::cast<ElementsAttr>(value));
199ParseResult getShapeAndElementType(
OpAsmParser &parser,
Type parsedType,
201 TypeAttr &typeAttr) {
202 if (
auto shapedType = dyn_cast<ShapedType>(parsedType)) {
203 if (!shapedType.hasRank())
205 <<
"expected ranked type";
207 auto elementType = shapedType.getElementType();
208 typeAttr = TypeAttr::get(elementType);
215 <<
"expected shaped type";
232 <<
"expected attribute";
234 if (
auto typedAttr = dyn_cast<TypedAttr>(initialValueAttr)) {
235 return getShapeAndElementType(parser, typedAttr.getType(), varShapeAttr,
239 <<
"expected Typed attr";
242 initialValueAttr =
nullptr;
246 <<
"expected type after colon";
248 return getShapeAndElementType(parser, parsedType, varShapeAttr, typeAttr);
253 TypeAttr typeAttr,
Attribute initialValueAttr) {
254 bool needsSpace =
false;
255 if (!dyn_cast_or_null<TypedAttr>(initialValueAttr)) {
258 Type elementType = typeAttr.getValue();
259 RankedTensorType tensorType =
261 auto tensorTypeAttr = TypeAttr::get(tensorType);
266 if (initialValueAttr) {
286 if (
auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(srcType))
296 Value valZp, StringRef name) {
301 mlir::isa<IntegerType>(eType) && mlir::isa<IntegerType>(eZpType);
305 if (!bothInts || !sameBitWidth) {
307 <<
"expected " << name <<
" and " << name
308 <<
"_zp to both be integer of the same bitwidth, but got " << eType
309 <<
" vs. " << eZpType;
316 Value src, int32_t val) {
319 const auto padConstType = mlir::RankedTensorType::get({1}, srcType);
320 const auto padConstEType = mlir::RankedTensorType::get({1}, srcElemType);
321 const auto padConstAttr{
322 llvm::isa<FloatType>(srcElemType)
327 return tosa::ConstOp::create(builder, loc, padConstType, padConstAttr);
331 if (
auto blockScaledTy = dyn_cast<tosa::BlockScaledType>(type))
333 if (dyn_cast<tosa::mxint8Type>(type))
342 const StringRef operandName,
343 const StringRef dimName) {
344 if (ShapedType::isDynamic(currDim)) {
347 }
else if (ShapedType::isStatic(newDim) && currDim != newDim) {
349 << dimName <<
" of " << operandName <<
" to match size " << currDim
350 <<
", got " << newDim;
357 auto printDim = [&](
int64_t dim) {
358 if (ShapedType::isDynamic(dim))
364 llvm::interleaveComma(
shape,
diag, printDim);
370 StringRef outputName =
"output") {
371 assert(outputType.hasRank() &&
"expected output type to be ranked");
377 diag << outputName <<
" shape ";
379 diag <<
" to be compatible with inferred shape ";
387 const int64_t stride,
const int64_t dilation,
const llvm::StringRef dimName,
388 const llvm::StringRef dimAxis,
const llvm::StringRef padBeforeName,
389 const llvm::StringRef padAfterName) {
390 if (inputSize == ShapedType::kDynamic || kernelSize == ShapedType::kDynamic)
395 const std::optional<int64_t> calculatedOutSizeMinusOne =
idivCheck(
396 inputSize - 1 + padBefore + padAfter - (kernelSize - 1) * dilation,
398 if (!calculatedOutSizeMinusOne.has_value())
400 << dimName <<
" - 1 + pad_" << padBeforeName <<
" + pad_"
401 << padAfterName <<
" - (kernel_" << dimName <<
" - 1) * dilation_"
402 << dimAxis <<
" to be wholly divisible by stride_" << dimAxis
403 <<
", got (" << inputSize <<
" - 1 + " << padBefore <<
" + "
404 << padAfter <<
" - (" << kernelSize <<
" - 1) * " << dilation
407 const int64_t calculatedOutSize = calculatedOutSizeMinusOne.value() + 1;
408 if (outputSize != ShapedType::kDynamic && calculatedOutSize != outputSize)
410 << dimName <<
" did not match expected: "
411 <<
"calculated=" << calculatedOutSize <<
", expected=" << outputSize;
419size_t mlir::tosa::mxint8Type::getDenseElementBitSize()
const {
return 8; }
422mlir::tosa::mxint8Type::convertToAttribute(
ArrayRef<char> rawData)
const {
423 assert(rawData.size() == 1 &&
"expected 1 byte for tosa.mxint8 element");
424 const auto intType = IntegerType::get(
getContext(), 8);
425 return intType.convertToAttribute(rawData);
428LogicalResult mlir::tosa::mxint8Type::convertFromAttribute(
430 const auto intAttr = dyn_cast<IntegerAttr>(attr);
433 const Type attrType = intAttr.getType();
436 return cast<IntegerType>(attrType).convertFromAttribute(attr,
result);
445 bool allowScaleValues) {
446 const auto tensorType = llvm::cast<ShapedType>(type);
447 const BlockScaledType elemType =
448 llvm::dyn_cast<BlockScaledType>(tensorType.getElementType());
452 if (!allowScaleValues && elemType.hasScaleValues()) {
455 <<
"block scaled tensor type with scale values is not allowed";
459 if (!tensorType.hasRank())
462 if (tensorType.getRank() == 0) {
464 emitError() <<
"block scaled tensor type must have rank greater than "
470 const uint32_t blockSize =
471 BlockShapeAttr::getBlockShapeValue(elemType.getBlockShape());
473 if (allowScaleValues && elemType.hasScaleValues() &&
474 tensorType.hasStaticShape()) {
475 const size_t numBlocks = tensorType.getNumElements() / blockSize;
476 if (elemType.getScaleValues().size() != numBlocks) {
478 emitError() <<
"block scaled tensor type with scale values must have "
479 "scale values for each block, expected "
480 << numBlocks <<
", got "
481 << elemType.getScaleValues().size();
486 const int64_t blockedDimension = tensorShape.back();
487 if (ShapedType::isDynamic(blockedDimension))
490 if (blockedDimension % blockSize != 0) {
492 emitError() <<
"last dimension of block scaled tensor type ("
493 << blockedDimension <<
") must be divisible by block size ("
509 type, [ctx] {
return emitError(UnknownLoc::get(ctx)); })) &&
511 return ": " + message;
520 const auto parseScaleValue = [&]() -> ParseResult {
527 if (floatValue < 0.0)
528 return parser.
emitError(loc,
"scale value must be non-negative, got ")
531 Type attrType = scaleType;
535 if (attrType != scaleType)
536 return parser.
emitError(loc,
"parsed attribute type ")
537 << attrType <<
" does not match expected scale type " << scaleType;
539 scaleValues.push_back(FloatAttr::get(attrType, floatValue));
548 llvm::interleaveComma(scaleValues, printer, [&](
Attribute scaleValue) {
553size_t mlir::tosa::BlockScaledType::getDenseElementBitSize()
const {
555 if (isa<tosa::mxint8Type>(valueType))
561mlir::tosa::BlockScaledType::convertToAttribute(
ArrayRef<char> rawData)
const {
565 assert(rawData.size() == 1 &&
"expected 1 byte for block_scaled element");
567 if (
const auto mxint8Value = dyn_cast<tosa::mxint8Type>(valueType))
568 return mxint8Value.convertToAttribute(rawData);
569 if (!isa<FloatType>(valueType))
574LogicalResult mlir::tosa::BlockScaledType::convertFromAttribute(
577 if (
const auto mxint8Value = dyn_cast<tosa::mxint8Type>(valueType))
578 return mxint8Value.convertFromAttribute(attr,
result);
580 const auto floatAttr = dyn_cast<FloatAttr>(attr);
581 if (!floatAttr || floatAttr.getType() != valueType)
592template <
typename A, std::enable_if_t<std::is_same_v<A, ArgMaxOp::Adaptor> ||
593 std::is_same_v<A, ArgMinOp::Adaptor>,
596 MLIRContext *context, ::std::optional<Location> location, A adaptor,
599 IntegerAttr axis = adaptor.getProperties().axis;
600 int32_t axisVal = axis.getValue().getSExtValue();
607 const auto inputRank = inputShape.
getRank();
609 outShape.reserve(inputRank - 1);
610 for (
int i = 0, s = inputRank; i < s; i++) {
625 const ShapedType resultType = llvm::cast<ShapedType>(op.getType());
627 if (
const auto resultETy = resultType.getElementType();
628 !resultETy.isIntOrIndex())
629 return op.emitOpError(
"result tensor is not of integer type");
631 const auto inputType = llvm::cast<ShapedType>(op.getInput().getType());
632 if (!inputType.hasRank())
636 const int64_t axis = op.getAxisAttr().getInt();
637 if (((axis < 0) || axis >= inputType.getRank()))
638 return op.emitOpError(
"specified axis is outside the rank of the tensor");
640 if (!resultType.hasRank())
646 expectedOutputShape.erase(expectedOutputShape.begin() + axis);
648 return op.emitOpError(
"expected output shape '")
649 << expectedOutputShape <<
"', got '" << outputShape <<
"'";
656 const auto inputType = llvm::dyn_cast<TensorType>(op.getInput().getType());
657 const auto weightType = llvm::dyn_cast<TensorType>(op.getWeight().getType());
659 auto inputEType = inputType.getElementType();
660 auto weightEType = weightType.getElementType();
662 llvm::cast<ShapedType>(op.getBias().getType()).getElementType();
664 llvm::cast<ShapedType>(op.getResult().getType()).getElementType();
665 bool biasIsFloat = llvm::isa<FloatType>(biasEType);
666 bool resultIsFloat = llvm::isa<FloatType>(resultEType);
668 if (
auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(inputEType))
671 if (
auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(weightEType))
674 if (
auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(biasEType))
677 if (
auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(resultEType))
680 if (biasIsFloat && resultIsFloat && (biasEType != resultEType)) {
684 "expect both bias and result to have same element type, got ")
685 << biasEType <<
" and " << resultEType;
689 const bool isInputBlockScaled = llvm::isa<BlockScaledType>(inputEType);
690 const bool isWeightBlockScaled = llvm::isa<BlockScaledType>(weightEType);
691 const bool isInputFloat = llvm::isa<FloatType>(inputEType);
692 const bool isWeightFloat = llvm::isa<FloatType>(weightEType);
694 const bool isInputBSorFloat = isInputBlockScaled || isInputFloat;
695 const bool isWeightBSorFloat = isWeightBlockScaled || isWeightFloat;
698 if (isInputBSorFloat != isWeightBSorFloat) {
700 "expect both input and weight to be float or not together, got ")
701 << inputEType <<
" and " << weightEType;
706 if (!isInputBlockScaled && inputEType != inputZpEType) {
707 return op.emitOpError(
"expect both input and its zero point are the same "
708 "element type, got ")
709 << inputEType <<
" and " << inputZpEType;
711 if (isInputBlockScaled && !llvm::isa<Float32Type>(inputZpEType)) {
712 return op.emitOpError(
713 "expect block scaled input to have fp32 zero point, got ")
714 << inputEType <<
" and " << inputZpEType;
718 if (!isWeightBlockScaled && weightEType != weightZpEType) {
719 return op.emitOpError(
"expect both weight and its zero point are the same "
720 "element type, got ")
721 << weightEType <<
" and " << weightZpEType;
723 if (isWeightBlockScaled && !llvm::isa<Float32Type>(weightZpEType)) {
724 return op.emitOpError(
725 "expect block scaled weight to have fp32 zero point, got ")
726 << weightEType <<
" and " << weightZpEType;
729 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
730 if (succeeded(maybeIZp) && op.verifyInputZeroPoint(*maybeIZp).failed())
733 FailureOr<int64_t> maybeWZp = op.getWeightZeroPoint();
734 if (succeeded(maybeWZp) && op.verifyWeightZeroPoint(*maybeWZp).failed())
740LogicalResult tosa::ConstOp::verify() {
742 auto attrType = llvm::dyn_cast<TensorType>(getValuesAttr().
getType());
743 auto outputType = llvm::dyn_cast<TensorType>(getOutput().
getType());
745 if (!attrType || !outputType) {
746 emitOpError(
"expected tensors for attr/result type");
750 const Type attrElemType = attrType.getElementType();
751 const Type resultElemType = outputType.getElementType();
754 llvm::dyn_cast<mlir::quant::QuantizedType>(resultElemType)) {
759 if (
auto attrBlockScaledType =
760 llvm::dyn_cast<mlir::tosa::BlockScaledType>(attrElemType)) {
761 if (!attrBlockScaledType.hasScaleValues())
763 "attribute block scaled type must have scale values");
765 const auto emitAttributeError = [&op]() {
766 return op.
emitOpError(
"attribute block scaled type is invalid: ");
772 const BlockScaledType resultBlockScaledType =
773 llvm::dyn_cast<mlir::tosa::BlockScaledType>(resultElemType);
774 if (!resultBlockScaledType)
776 "result type must be block scaled type if attribute is block "
779 if (attrBlockScaledType.getValueType() !=
780 resultBlockScaledType.getValueType() ||
781 attrBlockScaledType.getScaleType() !=
782 resultBlockScaledType.getScaleType() ||
783 attrBlockScaledType.getBlockShape() !=
784 resultBlockScaledType.getBlockShape())
786 "expected block scaled element type to be compatible "
787 "between attr and result, got ")
788 << attrBlockScaledType <<
" vs. " << resultBlockScaledType;
793 if (attrElemType != resultElemType)
794 return emitOpError(
"expected same attr/result element types");
807 if (llvm::any_of(padding, [](
int64_t p) {
return p < 0; }))
808 return op.emitOpError(
"expect all padding values to be >= 0, got ")
812 if (llvm::any_of(strides, [](
int64_t s) {
return s < 1; }))
813 return op.emitOpError(
"expect all stride values to be >= 1, got ")
817 if (llvm::any_of(dilations, [](
int64_t d) {
return d < 1; }))
818 return op.emitOpError(
"expect all dilation values to be >= 1, got ")
821 const RankedTensorType outputType =
822 llvm::dyn_cast<RankedTensorType>(op.getOutput().getType());
827 const RankedTensorType inputType =
828 llvm::dyn_cast<RankedTensorType>(op.getInput().getType());
829 const RankedTensorType weightType =
830 llvm::dyn_cast<RankedTensorType>(op.getWeight().getType());
832 if (inputType && weightType) {
834 if constexpr (std::is_same<T, tosa::Conv2DOp>::value) {
836 op, inputType.getDimSize(1), weightType.getDimSize(1),
837 outputType.getDimSize(1), padding[0], padding[1], strides[0],
838 dilations[0],
"height",
"y",
"top",
"bottom")))
842 op, inputType.getDimSize(2), weightType.getDimSize(2),
843 outputType.getDimSize(2), padding[2], padding[3], strides[1],
844 dilations[1],
"width",
"x",
"left",
"right")))
849 if constexpr (std::is_same<T, tosa::DepthwiseConv2DOp>::value) {
851 op, inputType.getDimSize(1), weightType.getDimSize(0),
852 outputType.getDimSize(1), padding[0], padding[1], strides[0],
853 dilations[0],
"height",
"y",
"top",
"bottom")))
857 op, inputType.getDimSize(2), weightType.getDimSize(1),
858 outputType.getDimSize(2), padding[2], padding[3], strides[1],
859 dilations[1],
"width",
"x",
"left",
"right")))
864 if constexpr (std::is_same<T, tosa::Conv3DOp>::value) {
866 op, inputType.getDimSize(1), weightType.getDimSize(1),
867 outputType.getDimSize(1), padding[0], padding[1], strides[0],
868 dilations[0],
"depth",
"d",
"front",
"back")))
872 op, inputType.getDimSize(2), weightType.getDimSize(2),
873 outputType.getDimSize(2), padding[2], padding[3], strides[1],
874 dilations[1],
"height",
"y",
"top",
"bottom")))
878 op, inputType.getDimSize(3), weightType.getDimSize(3),
879 outputType.getDimSize(3), padding[4], padding[5], strides[2],
880 dilations[2],
"width",
"x",
"left",
"right")))
885 const RankedTensorType biasType =
886 llvm::dyn_cast<RankedTensorType>(op.getBias().getType());
891 const int64_t biasChannels = biasType.getDimSize(0);
893 outputType.getDimSize(outputType.getRank() - 1);
894 if (biasChannels == ShapedType::kDynamic ||
895 outputChannels == ShapedType::kDynamic)
899 if (biasChannels != outputChannels && biasChannels != 1)
900 return op.emitOpError(
901 "bias channels expected to be equal to output channels (")
902 << outputChannels <<
") or 1, got " << biasChannels;
909 StringRef name1,
Type type2,
911 auto shapeType1 = dyn_cast<ShapedType>(type1);
912 auto shapeType2 = dyn_cast<ShapedType>(type2);
913 if (!shapeType1 || !shapeType2)
916 auto elemType1 = shapeType1.getElementType();
917 auto elemType2 = shapeType2.getElementType();
918 if (elemType1 != elemType2)
920 <<
"require same element type for " << name1 <<
" (" << elemType1
921 <<
") and " << name2 <<
" (" << elemType2 <<
")";
925 <<
"require same shapes for " << name1 <<
" (" << type1 <<
") and "
926 << name2 <<
" (" << type2 <<
")";
936 if (list1.size() != list2.size())
938 <<
"require same number of values in " << name1 <<
" ("
939 << list1.size() <<
") and " << name2 <<
" (" << list2.size() <<
")";
941 for (
auto [type1, type2] :
961 op->template getParentWithTrait<OpTrait::SymbolTable>();
968 const auto varOp = symTable.
lookup<tosa::VariableOp>(op.getName());
972 return op->emitOpError(
"'")
973 << op.getName() <<
"' has not been declared by 'tosa.variable'";
987 StringRef aName =
"input",
988 StringRef bName =
"output") {
989 auto aTType = llvm::dyn_cast<TensorType>(aType);
990 auto bTType = llvm::dyn_cast<TensorType>(bType);
992 op->
emitOpError(
"expect shaped tensor for") << aName <<
", got " << aType;
996 op->
emitOpError(
"expect shaped tensor for") << bName <<
", got" << bType;
999 auto aElementType = aTType.getElementType();
1000 auto bElementType = bTType.getElementType();
1002 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(aElementType);
1004 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(bElementType);
1005 if ((aElementType.isIntOrIndexOrFloat() || aQuantType) &&
1006 (bElementType.isIntOrIndexOrFloat() || bQuantType) &&
1007 aElementType != bElementType) {
1013 << aName <<
" and " << bName <<
" to have same element type, got "
1014 << aElementType <<
" and " << bElementType;
1020LogicalResult tosa::ArgMaxOp::verify() {
return argMaxMinVerify(*
this); }
1022LogicalResult tosa::ArgMinOp::verify() {
return argMaxMinVerify(*
this); }
1032 const bool hasKernel = kernel.size() > 0;
1033 const bool hasStrides = strides.size() > 0;
1034 const bool hasPad = padding.size() > 0;
1036 if (hasKernel && llvm::any_of(kernel, [](
int64_t s) {
return s < 1; }))
1037 return op->
emitOpError(
"expect all kernel values to be >= 1, got ")
1040 if (hasStrides && llvm::any_of(strides, [](
int64_t s) {
return s < 1; }))
1041 return op->
emitOpError(
"expect all stride values to be >= 1, got ")
1044 if (hasPad && llvm::any_of(padding, [](
int64_t p) {
return p < 0; }))
1045 return op->
emitOpError(
"expect all padding values to be >= 0, got ")
1048 if (hasKernel && hasPad) {
1050 const int64_t kernelX = kernel[1];
1051 const int64_t padLeft = padding[2];
1052 const int64_t padRight = padding[3];
1053 if (padRight >= kernelX || padLeft >= kernelX)
1054 return op->
emitOpError(
"expected left/right padding to be less than the "
1055 "width of the kernel, got pad_left=")
1056 << padLeft <<
", pad_right=" << padRight
1057 <<
", kernel_x=" << kernelX;
1059 const int64_t kernelY = kernel[0];
1060 const int64_t padTop = padding[0];
1061 const int64_t padBottom = padding[1];
1062 if (padTop >= kernelY || padBottom >= kernelY)
1063 return op->
emitOpError(
"expected top/bottom padding to be less than the "
1064 "height of the kernel, got pad_top=")
1065 << padTop <<
", pad_bottom=" << padBottom
1066 <<
", kernel_y=" << kernelY;
1069 const auto inputType = llvm::dyn_cast<RankedTensorType>(input.
getType());
1070 const auto outputType = llvm::dyn_cast<RankedTensorType>(output.
getType());
1071 if (!inputType || !outputType)
1074 if (hasKernel && hasStrides && hasPad) {
1075 const auto verifyOutputSize =
1079 const llvm::StringRef dimName,
const llvm::StringRef dimAxis,
1080 const llvm::StringRef padBeforeName,
1081 const llvm::StringRef padAfterName) -> LogicalResult {
1082 if (ShapedType::isDynamic(inputSize))
1085 const std::optional<int64_t> calculatedOutSizeMinusOne =
1086 idivCheck(inputSize + padBefore + padAfter - kernelSize, strideSize);
1087 if (!calculatedOutSizeMinusOne.has_value())
1089 << dimName <<
" + pad_" << padBeforeName <<
" + pad_"
1090 << padAfterName <<
" - kernel_" << dimAxis
1091 <<
" to be wholly divisible by stride_" << dimAxis <<
", got ("
1092 << inputSize <<
" + " << padBefore <<
" + " << padAfter <<
" - "
1093 << kernelSize <<
") / " << strideSize;
1095 const int64_t calculatedOutSize = calculatedOutSizeMinusOne.value() + 1;
1096 if (ShapedType::isStatic(outputSize) && calculatedOutSize != outputSize)
1098 << dimName <<
" did not match expected: " <<
"calculated="
1099 << calculatedOutSize <<
", expected=" << outputSize;
1104 if (failed(verifyOutputSize(inputType.getDimSize(1),
1105 outputType.getDimSize(1), kernel[0], strides[0],
1106 padding[0], padding[1],
"height",
"y",
"top",
1110 if (failed(verifyOutputSize(
1111 inputType.getDimSize(2), outputType.getDimSize(2), kernel[1],
1112 strides[1], padding[2], padding[3],
"width",
"x",
"left",
"right")))
1118template <
typename T>
1121 op.getPad(), op.getInput(), op.getOutput());
1124template <
typename T>
1128 const Type inputZpETy =
1130 const Type outputZpETy =
1133 auto accType = op.getAccType();
1134 if (llvm::isa<IntegerType>(inputETy) && !accType.isInteger(32))
1135 return op.emitOpError(
"accumulator type for integer tensor is not i32");
1137 if (inputETy.
isF16() && !(accType.isF16() || accType.isF32()))
1138 return op.emitOpError(
"accumulator type for f16 tensor is not f16/f32");
1140 if (inputETy.
isBF16() && !accType.isF32())
1141 return op.emitOpError(
"accumulator type for bf16 tensor is not f32");
1143 if (inputETy.
isF32() && !accType.isF32())
1144 return op.emitOpError(
"accumulator type for f32 tensor is not f32");
1146 if (inputETy != inputZpETy)
1147 return op.emitOpError(
"expect both input and its zero point are the same "
1148 "element type, got ")
1149 << inputETy <<
" and " << inputZpETy;
1151 if (resultETy != outputZpETy)
1152 return op.emitOpError(
"expect both output and its zero point are the same "
1153 "element type, got ")
1154 << resultETy <<
" and " << outputZpETy;
1156 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
1157 if (succeeded(maybeIZp) && op.verifyInputZeroPoint(*maybeIZp).failed())
1160 FailureOr<int64_t> maybeOZp = op.getOutputZeroPoint();
1161 if (succeeded(maybeOZp) && op.verifyOutputZeroPoint(*maybeOZp).failed())
1168struct AdaptivePoolingConstShapeValues {
1169 llvm::SmallVector<int64_t> kernel;
1170 llvm::SmallVector<int64_t> stride;
1171 llvm::SmallVector<int64_t> pad;
1175template <
typename T>
1177 std::is_same_v<T, tosa::AvgPool2dAdaptiveOp> ||
1178 std::is_same_v<T, tosa::MaxPool2dAdaptiveOp>;
1180template <
typename T,
1181 typename std::enable_if<IsSupportedAdaptivePoolConstShapeVerifyOp<T>,
1184 T op, AdaptivePoolingConstShapeValues &values) {
1190LogicalResult tosa::AvgPool2dOp::verify() {
1198LogicalResult tosa::AvgPool2dAdaptiveOp::verify() {
1199 AdaptivePoolingConstShapeValues values;
1208 values.pad, getInput(), getOutput())))
1217LogicalResult tosa::ClampOp::verify() {
1219 llvm::cast<ShapedType>(getInput().
getType()).getElementType();
1220 if (
auto quantType =
1221 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(inputETy)) {
1225 llvm::cast<ShapedType>(getOutput().
getType()).getElementType();
1226 if (
auto quantType =
1227 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(outputETy)) {
1230 if (inputETy != outputETy)
1231 return emitOpError(
"input/output element types are incompatible.");
1233 auto maxValAttr = getMaxValAttr();
1234 auto minValAttr = getMinValAttr();
1238 if (inputETy.
isInteger(dataTypeBitWidth)) {
1242 auto intMaxValAttr = mlir::dyn_cast<mlir::IntegerAttr>(maxValAttr);
1243 auto intMinValAttr = mlir::dyn_cast<mlir::IntegerAttr>(minValAttr);
1244 if (!intMaxValAttr || !intMinValAttr ||
1245 (intMaxValAttr.getType() != intMinValAttr.getType()) ||
1246 (intMaxValAttr.getType() != inputETy))
1247 return emitOpError(
"min/max attributes types are incompatible with "
1248 "input/output element types.");
1251 const bool isBoolean = inputETy.
isInteger(1);
1252 const APInt minVal = intMinValAttr.getValue();
1253 const APInt maxVal = intMaxValAttr.getValue();
1254 if ((isUnsigned || isBoolean) ? maxVal.ult(minVal) : maxVal.slt(minVal))
1255 return emitOpError(
"expected min_val <= max_val, got min_val=")
1256 << minValAttr <<
", max_val=" << maxValAttr;
1261 auto floatMaxValAttr = mlir::dyn_cast<mlir::FloatAttr>(maxValAttr);
1262 auto floatMinValAttr = mlir::dyn_cast<mlir::FloatAttr>(minValAttr);
1263 if (!floatMaxValAttr || !floatMinValAttr ||
1264 (floatMaxValAttr.getType() != floatMinValAttr.getType()) ||
1265 (floatMaxValAttr.getType() != inputETy))
1266 return emitOpError(
"min/max attributes types are incompatible with "
1267 "input/output element types.");
1269 const APFloat minVal = floatMinValAttr.getValue();
1270 const APFloat maxVal = floatMaxValAttr.getValue();
1271 if (minVal.isNaN() || maxVal.isNaN())
1272 return emitOpError(
"min/max attributes should not be 'NaN', got min_val=")
1273 << minValAttr <<
", max_val=" << maxValAttr;
1275 if (maxVal < minVal)
1276 return emitOpError(
"expected min_val <= max_val, got min_val=")
1277 << minValAttr <<
", max_val=" << maxValAttr;
1297 result.addOperands({input, weight, bias, zps.first, zps.second});
1298 result.addAttribute(
"pad", pad);
1299 result.addAttribute(
"stride", stride);
1300 result.addAttribute(
"dilation", dilation);
1301 result.addAttribute(
"acc_type", accType);
1302 Type finalOutputType = outputType;
1308 result.addTypes(finalOutputType);
1319 result.addOperands({input, weight, bias, zps.first, zps.second});
1320 result.addAttribute(
"out_pad", outpad);
1321 result.addAttribute(
"stride", stride);
1322 result.addAttribute(
"acc_type", accType);
1323 Type finalOutputType = outputType;
1329 result.addTypes(finalOutputType);
1336 result.addOperands({a,
b, zps.first, zps.second});
1338 Type finalOutputType{outputType};
1341 auto inputBits = eType.getIntOrFloatBitWidth();
1343 auto outputShapedType = llvm::dyn_cast<ShapedType>(outputType);
1344 assert(outputShapedType &&
"Output must be a shaped type");
1346 IntegerType accElementType;
1347 if (inputBits == 16)
1352 finalOutputType = outputShapedType.clone(accElementType);
1354 result.addTypes(finalOutputType);
1375 DenseArrayAttr kernel, DenseArrayAttr stride,
1376 DenseArrayAttr pad, TypeAttr accType) {
1381 if (
auto quantAttr =
1383 inputZp = quantAttr.getInputZp();
1384 outputZp = quantAttr.getOutputZp();
1386 const std::optional<Value> inputZpOp =
1391 "Failed to create input zero point tensor for quantized AVG_POOL2D op");
1393 const std::optional<Value> outputZpOp =
1396 (
void)
emitError(loc,
"Failed to create output zero point tensor for "
1397 "quantized AVG_POOL2D op");
1400 if (inputZpOp && outputZpOp) {
1401 result.addOperands({input, inputZpOp.value(), outputZpOp.value()});
1406 result.addOperands({input});
1408 result.addAttribute(
"kernel", kernel);
1409 result.addAttribute(
"stride", stride);
1410 result.addAttribute(
"pad", pad);
1411 result.addAttribute(
"acc_type", accType);
1412 result.types.push_back(outputType);
1425 if (
auto quantAttr =
1427 inputZp = quantAttr.getInputZp();
1428 outputZp = quantAttr.getOutputZp();
1430 const std::optional<Value> inputZpOp =
1434 "Failed to create input zero point tensor for quantized "
1435 "AVG_POOL2D_ADAPTIVE op");
1437 const std::optional<Value> outputZpOp =
1440 (
void)
emitError(loc,
"Failed to create output zero point tensor for "
1441 "quantized AVG_POOL2D_ADAPTIVE op");
1444 if (inputZpOp && outputZpOp) {
1449 result.addOperands({input, inputZpOp.value(), outputZpOp.value(),
1450 kernelShape, strideShape, padShape});
1455 result.addOperands({input});
1457 result.addAttribute(
"acc_type", accType);
1458 result.types.push_back(outputType);
1472 input1Zp = quantAttr.getInputZp();
1473 outputZp = quantAttr.getOutputZp();
1475 const std::optional<Value> input1ZpOp =
1479 loc,
"Failed to create input1 zero point for quantized NEGATE op");
1482 const std::optional<Value> outputZpOp =
1486 loc,
"Failed to create output zero point for quantized NEGATE op");
1489 if (input1ZpOp && outputZpOp) {
1490 result.addOperands({input, input1ZpOp.value(), outputZpOp.value()});
1495 result.addOperands({input});
1498 result.types.push_back(outputType);
1511 zp =
static_cast<int32_t
>(quantAttr.getInputZp());
1514 result.addOperands({input, paddings, padConstOp});
1515 result.types.push_back(outputType);
1519 StringRef name,
Type variableType,
1524 auto shapedType = dyn_cast<ShapedType>(variableType);
1526 (
void)
emitError(loc,
"variable type must be a shaped type");
1529 if (!shapedType.hasRank()) {
1530 (
void)
emitError(loc,
"variable type must be a ranked type");
1534 auto elementType = shapedType.getElementType();
1535 auto elementTypeAttr = TypeAttr::get(elementType);
1539 result.addAttribute(
"sym_name", nameAttr);
1540 result.addAttribute(
"var_shape", varShapeAttr);
1541 result.addAttribute(
"type", elementTypeAttr);
1542 result.addAttribute(
"initial_value", initialValue);
1555 if (ShapedType::isStatic(dim1) && ShapedType::isStatic(dim2) && dim1 != dim2)
1559 return ShapedType::isDynamic(dim1) ? dim2 : dim1;
1565 for (
int i = 0, e = operands.size(); i != e; ++i) {
1567 if (!
shape.hasRank()) {
1572 outRank = std::max<int64_t>(outRank,
shape.getRank());
1575 outShape.resize(outRank, 1);
1577 for (
int i = 0, e = operands.size(); i != e; ++i) {
1579 auto rankDiff = outShape.size() -
shape.getRank();
1581 for (
size_t i = 0, e =
shape.getRank(); i < e; ++i) {
1582 auto dim1 = outShape[i + rankDiff];
1583 auto dim2 =
shape.getDimSize(i);
1585 const FailureOr<int64_t> maybeResolvedDim =
1587 if (failed(maybeResolvedDim))
1589 const int64_t resolvedDim = *maybeResolvedDim;
1590 outShape[i + rankDiff] = resolvedDim;
1597LogicalResult tosa::ArgMaxOp::inferReturnTypeComponents(
1598 MLIRContext *context, ::std::optional<Location> location,
1599 ArgMaxOp::Adaptor adaptor,
1602 inferredReturnShapes);
1605LogicalResult tosa::ArgMinOp::inferReturnTypeComponents(
1606 MLIRContext *context, ::std::optional<Location> location,
1607 ArgMinOp::Adaptor adaptor,
1610 inferredReturnShapes);
1613LogicalResult tosa::RFFT2dOp::inferReturnTypeComponents(
1614 MLIRContext *context, ::std::optional<Location> location,
1615 RFFT2dOp::Adaptor adaptor,
1617 ShapeAdaptor inputShape(adaptor.getInputReal().getType());
1619 if (!inputShape.hasRank())
1623 outputShape.resize(3, ShapedType::kDynamic);
1624 outputShape[0] = inputShape.getDimSize(0);
1625 outputShape[1] = inputShape.getDimSize(1);
1626 int64_t inWidth = inputShape.getDimSize(2);
1630 if (inWidth != ShapedType::kDynamic)
1631 outputShape[2] = inWidth / 2 + 1;
1640 const llvm::StringRef dimName) {
1641 const bool isPowerOfTwo = (dimSize & (dimSize - 1)) == 0 && dimSize > 0;
1644 << dimName <<
" to be a power of two, got " << dimSize;
1649LogicalResult tosa::RFFT2dOp::verify() {
1650 const auto outputTypes = getResultTypes();
1652 return emitOpError(
"expected output shapes to match, got ") << outputTypes;
1654 const auto inputType =
1655 llvm::dyn_cast<RankedTensorType>(getInputReal().
getType());
1659 const int64_t height = inputType.getDimSize(1);
1660 if (ShapedType::isStatic(height) &&
1664 const int64_t width = inputType.getDimSize(2);
1665 if (ShapedType::isStatic(width) &&
1669 const auto outputType = llvm::dyn_cast<RankedTensorType>(outputTypes[0]);
1675 outputType.getShape().drop_back())))
1676 return emitOpError(
"expected batch and height dimensions of input/output "
1677 "to match, got input=")
1678 << inputType <<
" output=" << outputType;
1681 const int64_t outputWidth = outputType.getDimSize(2);
1682 if (ShapedType::isStatic(width) && ShapedType::isStatic(outputWidth) &&
1683 (outputWidth != (width / 2) + 1))
1685 "expected output width to be equal to input_width / 2 + 1, got ")
1691LogicalResult tosa::FFT2dOp::inferReturnTypeComponents(
1692 MLIRContext *context, ::std::optional<Location> location,
1693 FFT2dOp::Adaptor adaptor,
1695 inferredReturnShapes.push_back(
1697 inferredReturnShapes.push_back(
1702LogicalResult tosa::FFT2dOp::verify() {
1703 const auto inputRealType =
1704 llvm::dyn_cast<RankedTensorType>(getInputReal().
getType());
1705 const auto inputImagType =
1706 llvm::dyn_cast<RankedTensorType>(getInputImag().
getType());
1707 if (!inputRealType || !inputImagType)
1710 const auto trySelectStaticDim = [](
const int64_t a,
const int64_t b) {
1711 return ShapedType::isDynamic(a) ? a :
b;
1714 const int64_t height = trySelectStaticDim(inputRealType.getDimSize(1),
1715 inputImagType.getDimSize(1));
1716 if (ShapedType::isStatic(height) &&
1720 const int64_t width = trySelectStaticDim(inputRealType.getDimSize(2),
1721 inputImagType.getDimSize(2));
1722 if (ShapedType::isStatic(width) &&
1729LogicalResult tosa::ConcatOp::inferReturnTypeComponents(
1730 MLIRContext *context, ::std::optional<Location> location,
1731 ConcatOp::Adaptor adaptor,
1734 const Properties &prop = adaptor.getProperties();
1735 int32_t axis = prop.axis.getValue().getSExtValue();
1737 bool hasRankedInput =
false;
1738 for (
auto operand : adaptor.getOperands()) {
1740 if (!operandShape.hasRank())
1744 if (!hasRankedInput)
1745 outputShape.resize(operandShape.getRank(), ShapedType::kDynamic);
1748 for (
int i = 0, s = operandShape.getRank(); i < s; i++) {
1749 if (i == axis || operandShape.isDynamicDim(i))
1751 if (outputShape[i] == ShapedType::kDynamic)
1752 outputShape[i] = operandShape.getDimSize(i);
1753 if (outputShape[i] != operandShape.getDimSize(i))
1755 "Cannot concat tensors with different sizes"
1756 " on the non-axis dimension ",
1760 hasRankedInput =
true;
1763 if (adaptor.getInput1().empty())
1767 llvm::cast<TensorType>(adaptor.getInput1().getType()[0]).getElementType();
1768 if (!hasRankedInput) {
1775 for (
auto operand : adaptor.getOperands()) {
1780 if (!operandShape.hasRank() || operandShape.isDynamicDim(axis)) {
1781 concatDimSize = ShapedType::kDynamic;
1785 concatDimSize += operandShape.getDimSize(axis);
1788 outputShape[axis] = concatDimSize;
1794LogicalResult tosa::ConcatOp::verify() {
1796 auto outType = getOutput().getType();
1800 if (inputList.empty())
1801 return emitOpError(
"expect at least one input");
1803 if (!llvm::all_of(inputList, [&](
auto input) {
1805 *
this, input.getType(), outType));
1810 const int32_t axis = getAxis();
1812 for (
const auto &input : inputList) {
1813 const Type inputType = input.getType();
1815 if (currShape.hasRank()) {
1816 firstRankedInputShape = currShape;
1818 if (axis < 0 || axis >= firstRankedInputShape.
getRank())
1819 return emitOpError(
"expect axis to be within range 0 < axis < "
1820 "rank(input1[firstRankedTensorIdx]), got ")
1826 const auto allOperandsHasRank = [](
const Value input) {
1829 if (llvm::all_of(inputList, allOperandsHasRank)) {
1832 for (
const auto &[
index, input] : llvm::enumerate(inputList.drop_front())) {
1834 const int64_t inputRank = inputShape.getRank();
1835 const size_t operandNum =
index + 1;
1838 if (inputRank != firstInputRank)
1840 "expect all operands to have the same rank, but got ")
1841 << firstInputRank <<
" vs " << inputRank <<
" on operands 0 and "
1845 for (
int i = 0; i < inputRank; i++) {
1846 const int64_t inputDim = inputShape.getDimSize(i);
1848 if (i == axis || firstRankedInputShape.
isDynamicDim(i) ||
1849 inputShape.isDynamicDim(i))
1851 if (inputDim != firstInputDim)
1852 return emitOpError(
"expect all operand shapes to have the same sizes "
1853 "on non-axis dimensions, but got ")
1854 << inputDim <<
" vs " << firstInputDim <<
" at index " << i
1855 <<
" on operands 0 and " << operandNum;
1860 if (outputShape.hasRank() && outputShape.getRank() != firstInputRank)
1861 return emitOpError(
"expect output rank to match inputs rank, got ")
1862 << outputShape.getRank() <<
" vs " << firstInputRank;
1866 for (
const auto &input : inputList) {
1868 if (inputShape.isDynamicDim(axis)) {
1873 axisSum += inputShape.getDimSize(axis);
1876 if (axisSum >= 0 && outputShape.hasRank() &&
1877 !outputShape.isDynamicDim(axis) &&
1878 axisSum != outputShape.getDimSize(axis))
1879 return emitOpError(
"requires sum of axis dimensions of input1 "
1880 "equal to output axis dimension, got ")
1881 << axisSum <<
" and " << outputShape.getDimSize(axis);
1887LogicalResult tosa::EqualOp::inferReturnTypeComponents(
1888 MLIRContext *context, ::std::optional<Location> location,
1892 auto elementType = IntegerType::get(context, 1);
1905 if (l.size() != r.size() || l.size() != 1)
1915 if (!
shape.hasRank())
1916 return ShapedType::kDynamic;
1917 const int64_t inputAxis = axis - (outputRank -
shape.getRank());
1918 return inputAxis < 0 ? 1 :
shape.getDimSize(inputAxis);
1921static FailureOr<SmallVector<int64_t>>
1923 int64_t outputRank,
bool transposeB) {
1924 if (outputRank < 2 ||
1932 for (
int64_t axis = 0; axis < outputRank - 2; ++axis) {
1936 if (failed(resolvedDim))
1938 outputShape[axis] = *resolvedDim;
1944 outputShape[outputRank - 1] =
1959 inferredReturnShapes.emplace_back();
1966 if (ShapedType::isStatic(aChannels) && ShapedType::isStatic(bChannels) &&
1967 aChannels != bChannels)
1971 FailureOr<SmallVector<int64_t>> outputShape =
1973 if (failed(outputShape))
1976 inferredReturnShapes.emplace_back(*outputShape);
1980LogicalResult tosa::MatMulOp::inferReturnTypeComponents(
1981 MLIRContext *context, ::std::optional<Location> location,
1982 MatMulOp::Adaptor adaptor,
1987 inferredReturnShapes);
1990template <
typename T>
1992 Type bElementType) {
1993 const auto aQuantizedEType =
1994 llvm::dyn_cast<quant::UniformQuantizedType>(aElementType);
1995 const auto bQuantizedEType =
1996 llvm::dyn_cast<quant::UniformQuantizedType>(bElementType);
1998 if (aQuantizedEType || bQuantizedEType) {
1999 if (!aQuantizedEType || !bQuantizedEType) {
2000 return op.emitOpError(
"expect operands to be both quantized or both not "
2002 << aElementType <<
" and " << bElementType;
2005 auto aQuantWidth = aQuantizedEType.getStorageTypeIntegralWidth();
2006 auto bQuantWidth = bQuantizedEType.getStorageTypeIntegralWidth();
2007 if (aQuantWidth != bQuantWidth) {
2008 return op.emitOpError(
"expect quantized operands to have same widths, "
2010 << aQuantWidth <<
" and " << bQuantWidth;
2017template <
typename T>
2019 StringRef inputName,
2024 Type expectedElementType = inputStorageElementType;
2026 if (isa<BlockScaledType>(inputElementType))
2027 expectedElementType = Float32Type::get(op.getContext());
2029 if (expectedElementType == zpElementType)
2033 diag << inputName <<
" and " << zpName;
2034 if (isa<BlockScaledType>(inputElementType))
2035 diag <<
" have compatible element types, got " << inputElementType
2036 <<
" and " << zpElementType;
2038 diag <<
" have the same element type, got " << inputStorageElementType
2039 <<
" and " << zpElementType;
2047 batchShape.reserve(
shape.getRank() - 2);
2048 for (
int64_t i = 0, e =
shape.getRank() - 2; i < e; ++i)
2049 batchShape.push_back(
shape.getDimSize(i));
2053template <
typename T>
2057 const auto outputType = cast<ShapedType>(op.getResult().getType());
2060 : ShapedType::kDynamic;
2068 const int64_t minimumOutputRank =
2071 if (outputType.hasRank() && outputType.getRank() < minimumOutputRank)
2072 return op.emitOpError(
"expected output rank of at least ")
2073 << minimumOutputRank <<
", got " << outputType.getRank();
2075 const bool bothInputsRanked = aShape.
hasRank() && bShape.
hasRank();
2076 if (!bothInputsRanked && !outputType.hasRank())
2081 const int64_t expectedOutputRank =
2082 bothInputsRanked ? minimumOutputRank : outputType.getRank();
2083 FailureOr<SmallVector<int64_t>> expectedOutputShape =
2085 if (failed(expectedOutputShape)) {
2087 "expected batch dimensions of a and b to be broadcast compatible, "
2090 diag <<
"] and b=[";
2096 if (outputType.hasRank())
2098 op.getOperation(), outputType, *expectedOutputShape);
2102LogicalResult MatMulOp::verify() {
2114 FailureOr<int64_t> maybeAZp = getAZeroPoint();
2115 if (succeeded(maybeAZp) && verifyAZeroPoint(*maybeAZp).failed())
2118 FailureOr<int64_t> maybeBZp = getBZeroPoint();
2119 if (succeeded(maybeBZp) && verifyBZeroPoint(*maybeBZp).failed())
2125LogicalResult tosa::MatMulTOp::inferReturnTypeComponents(
2126 MLIRContext *context, ::std::optional<Location> location,
2127 MatMulTOp::Adaptor adaptor,
2132 inferredReturnShapes);
2135LogicalResult MatMulTOp::verify() {
2147 FailureOr<int64_t> maybeAZp = getAZeroPoint();
2148 if (succeeded(maybeAZp) && verifyAZeroPoint(*maybeAZp).failed())
2151 FailureOr<int64_t> maybeBZp = getBZeroPoint();
2152 if (succeeded(maybeBZp) && verifyBZeroPoint(*maybeBZp).failed())
2158LogicalResult tosa::MatmulTBlockScaledOp::inferReturnTypeComponents(
2159 MLIRContext *context, ::std::optional<Location> location,
2160 MatmulTBlockScaledOp::Adaptor adaptor,
2164 const auto aDataShape = cast<ShapedType>(adaptor.getAData().getType());
2165 if (aDataShape.hasRank()) {
2166 outShape[0] = aDataShape.getDimSize(0);
2167 outShape[1] = aDataShape.getDimSize(1);
2170 const auto aScaleShape = cast<ShapedType>(adaptor.getAScale().getType());
2171 if (aScaleShape.hasRank()) {
2172 outShape[0] = ShapedType::isDynamic(outShape[0]) ? aScaleShape.getDimSize(0)
2174 outShape[1] = ShapedType::isDynamic(outShape[1]) ? aScaleShape.getDimSize(1)
2179 const auto bDataShape = cast<ShapedType>(adaptor.getBData().getType());
2180 if (bDataShape.hasRank()) {
2181 const int64_t bDataBatchSize = bDataShape.getDimSize(0);
2182 if (bDataBatchSize != 1)
2184 ShapedType::isDynamic(outShape[0]) ? bDataBatchSize : outShape[0];
2185 outShape[2] = bDataShape.getDimSize(1);
2188 const auto bScaleShape = cast<ShapedType>(adaptor.getBScale().getType());
2189 if (bScaleShape.hasRank()) {
2190 const int64_t bScaleBatchSize = bScaleShape.getDimSize(0);
2191 if (bScaleBatchSize != 1)
2193 ShapedType::isDynamic(outShape[0]) ? bScaleBatchSize : outShape[0];
2194 outShape[2] = ShapedType::isDynamic(outShape[2]) ? bScaleShape.getDimSize(1)
2202LogicalResult MatmulTBlockScaledOp::verify() {
2204 const Type aDataType = getAData().getType();
2205 const Type bDataType = getBData().getType();
2211 int64_t N = ShapedType::kDynamic;
2212 int64_t D = ShapedType::kDynamic;
2213 int64_t H = ShapedType::kDynamic;
2216 int64_t multiplesOfC = ShapedType::kDynamic;
2228 "a_scale",
"batch")) ||
2230 "a_scale",
"height")))
2238 "b_data",
"batch")) ||
2240 "b_data",
"channels")))
2248 "b_scale",
"batch")) ||
2250 "b_scale",
"width")) ||
2258 if (ShapedType::isStatic(N) && ShapedType::isStatic(D) && N != D && D != 1)
2259 return emitOpError(
"expect B matrix batch size to be broadcast compatible "
2261 << D <<
" vs N=" << N;
2264 const uint32_t blockSize = BlockSizeAttr::getBlockSizeValue(
getBlockSize());
2265 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_32))
2266 return emitOpError(
"expect block size to be 32, got ") << blockSize;
2267 if (ShapedType::isStatic(C) && C % blockSize != 0)
2268 return emitOpError(
"expect C to be a multiple of block size, got C=")
2269 <<
C <<
", block_size=" << blockSize;
2272 if (ShapedType::isStatic(C) && ShapedType::isStatic(multiplesOfC) &&
2273 multiplesOfC != C / blockSize)
2275 "expect scale operands dimension 2 to equal C/block_size (")
2276 <<
C <<
"/" << blockSize <<
")" <<
", got " << multiplesOfC;
2279 N = ShapedType::isDynamic(N) ? D : N;
2281 const auto outputType = cast<ShapedType>(getResult().
getType());
2282 if (outputType.hasRank() &&
2287 opError <<
" to be compatible with expected output shape ";
2295LogicalResult tosa::PadOp::inferReturnTypeComponents(
2296 MLIRContext *context, ::std::optional<Location> location,
2297 PadOp::Adaptor adaptor,
2299 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2301 cast<tosa::shapeType>(adaptor.getPadding().getType()).getRank();
2306 if (!inputShape.hasRank()) {
2307 outputShape.resize(paddingRank / 2, ShapedType::kDynamic);
2316 outputShape.resize(inputShape.getRank(), ShapedType::kDynamic);
2321 outputShape.reserve(inputShape.getRank());
2322 for (
int i = 0, s = inputShape.getRank(); i < s; i++) {
2323 if (inputShape.isDynamicDim(i)) {
2324 outputShape.push_back(ShapedType::kDynamic);
2327 auto padFront = paddingValues[i * 2];
2328 auto padBack = paddingValues[i * 2 + 1];
2329 outputShape.push_back(inputShape.getDimSize(i) + padFront + padBack);
2336LogicalResult tosa::PadOp::verify() {
2343 if (
auto padConst = getPadConst()) {
2351 RankedTensorType inputType =
2352 llvm::dyn_cast<RankedTensorType>(getInput1().
getType());
2353 RankedTensorType outputType =
2354 llvm::dyn_cast<RankedTensorType>(getOutput().
getType());
2355 if (!inputType || !outputType)
2362 auto inputRank = inputType.getRank();
2363 auto paddingRank = cast<tosa::shapeType>(getPadding().
getType()).getRank();
2364 if (paddingRank != inputRank * 2)
2365 return emitOpError() <<
"padding tensor must have " << inputRank
2366 <<
" * 2 = " << inputRank * 2 <<
" elements, but got "
2372LogicalResult tosa::SliceOp::inferReturnTypeComponents(
2373 MLIRContext *context, ::std::optional<Location> location,
2374 SliceOp::Adaptor adaptor,
2383 auto rank = cast<tosa::shapeType>(adaptor.getSize().getType()).getRank();
2391 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2394 if (inputShape.hasRank()) {
2395 for (
size_t i = 0; i < size.size(); i++) {
2396 if (size[i] != 0 && size[i] >= -1 && start[i] >= 0 &&
2397 (ShapedType::isDynamic(inputShape.getDimSize(i)) ||
2398 start[i] < inputShape.getDimSize(i))) {
2400 if (ShapedType::isDynamic(inputShape.getDimSize(i))) {
2403 outputShape[i] = size[i];
2407 if (size[i] == -1) {
2408 outputShape[i] = inputShape.getDimSize(i) - start[i];
2409 }
else if (start[i] + size[i] <= inputShape.getDimSize(i)) {
2411 outputShape[i] = size[i];
2423LogicalResult tosa::SliceOp::verify() {
2424 const Value input = getInput1();
2425 const Value output = getOutput();
2431 const Value start = getStart();
2432 const Value size = getSize();
2436 if (inputShape.hasRank()) {
2437 const auto inputRank = inputShape.getRank();
2438 if (outputShape.hasRank() && inputRank != outputShape.getRank())
2440 "expect input1 and output to have the same ranks, got ")
2441 << inputRank <<
" and " << outputShape.getRank();
2443 const auto startShapeRank =
2444 llvm::cast<tosa::shapeType>(start.
getType()).getRank();
2445 if (inputRank != startShapeRank)
2446 return emitOpError(
"length of start is not equal to rank of input shape");
2448 const auto sizeShapeRank =
2449 llvm::cast<tosa::shapeType>(size.
getType()).getRank();
2450 if (inputRank != sizeShapeRank)
2451 return emitOpError(
"length of size is not equal to rank of input shape");
2457LogicalResult tosa::MulOp::inferReturnTypeComponents(
2458 MLIRContext *context, ::std::optional<Location> location,
2473LogicalResult tosa::MulOp::verify() {
2474 const Value output = getOutput();
2479 if (
auto resIntType = dyn_cast<IntegerType>(resElemType)) {
2480 IntegerType lhsIntType =
2482 IntegerType rhsIntType =
2484 if (!lhsIntType || !rhsIntType || lhsIntType != rhsIntType)
2485 return emitOpError(
"requires the same element type for all operands");
2490 if (lhsIntType.getWidth() > resIntType.getWidth())
2491 return emitOpError(
"invalid data type size for operands or result");
2496 for (
int i = 0; i < 2; ++i) {
2499 "requires the same element type for all operands and results");
2506 TypeRange operandTypes = getOperandTypes();
2507 ShapedType aType = cast<ShapedType>(operandTypes[0]);
2508 ShapedType bType = cast<ShapedType>(operandTypes[1]);
2510 const bool aHasRank = aType.hasRank();
2511 const bool bHasRank = bType.hasRank();
2513 bool hasExpectedOutputShape =
false;
2516 if (aHasRank && bHasRank) {
2517 const int64_t aRank = aType.getRank();
2518 const int64_t bRank = bType.getRank();
2520 return emitOpError(
"a and b operands don't have matching ranks, got ")
2521 << aRank <<
" and " << bRank;
2525 aType.getShape(), bType.getShape(), expectedOutputShape))
2526 return emitOpError(
"a and b operands don't have broadcast-compatible "
2528 << aType <<
" and " << bType;
2529 hasExpectedOutputShape =
true;
2532 ShapedType resultType = cast<ShapedType>(output.
getType());
2533 if (!resultType.hasRank())
2536 const int64_t resultRank = resultType.getRank();
2537 if (aHasRank && resultRank != aType.getRank())
2538 return emitOpError(
"result type has different rank than a, got ")
2539 << resultRank <<
" vs " << aType.getRank();
2540 if (bHasRank && resultRank != bType.getRank())
2541 return emitOpError(
"result type has different rank than b, got ")
2542 << resultRank <<
" vs " << bType.getRank();
2544 if (hasExpectedOutputShape &&
2546 expectedOutputShape)))
2552LogicalResult tosa::TableOp::inferReturnTypeComponents(
2553 MLIRContext *context, ::std::optional<Location> location,
2554 TableOp::Adaptor adaptor,
2556 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2558 if (!inputShape.hasRank()) {
2563 inferredReturnShapes.resize(1);
2564 inputShape.getDims(inferredReturnShapes[0]);
2568LogicalResult tosa::TableOp::verify() {
2569 const TensorType inputType = getInput1().getType();
2570 const TensorType outputType = getOutput().getType();
2579 auto inputDims = inputType.
getShape();
2580 auto outputDims = outputType.
getShape();
2581 for (
auto it : llvm::enumerate(llvm::zip(inputDims, outputDims))) {
2583 auto [inputDim, outputDim] = it.value();
2584 if (ShapedType::isStatic(outputDim) && outputDim != inputDim) {
2585 return emitOpError() <<
"dim(result, " << dim <<
") = " << outputDim
2586 <<
" doesn't match dim(input, " << dim
2587 <<
") = " << inputDim;
2600 llvm::map_to_vector(multiplesAttr.getValues<APInt>(),
2601 [](
const APInt &val) { return val.getSExtValue(); });
2605LogicalResult tosa::TileOp::inferReturnTypeComponents(
2606 MLIRContext *context, ::std::optional<Location> location,
2607 TileOp::Adaptor adaptor,
2614 cast<tosa::shapeType>(adaptor.getMultiples().getType()).getRank();
2621 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2623 if (!inputShape.hasRank()) {
2624 outputShape.resize(multiples.size(), ShapedType::kDynamic);
2625 inferredReturnShapes.push_back(
2629 if (
static_cast<size_t>(inputShape.getRank()) != multiples.size())
2633 outputShape.reserve(multiples.size());
2634 for (
int i = 0, s = inputShape.getRank(); i < s; i++) {
2635 if (multiples[i] == ShapedType::kDynamic) {
2636 outputShape.push_back(ShapedType::kDynamic);
2638 int64_t dim = inputShape.getDimSize(i);
2639 if (dim != ShapedType::kDynamic)
2640 dim *= multiples[i];
2641 outputShape.push_back(dim);
2649LogicalResult tosa::TileOp::verify() {
2655 ShapedType inputType = llvm::cast<ShapedType>(getInput1().
getType());
2656 ShapedType outputType = llvm::cast<ShapedType>(
getType());
2658 shapeType multiplesType =
2659 llvm::cast<tosa::shapeType>(getMultiples().
getType());
2661 auto multiplesRank = multiplesType.getRank();
2663 if (inputType.hasRank()) {
2664 if (inputType.getRank() != multiplesRank)
2665 return emitOpError(
"expect 'multiples' to have rank ")
2666 << inputType.getRank() <<
" but got " << multiplesRank <<
".";
2667 if (outputType.hasRank() &&
2671 }
else if (outputType.hasRank() && outputType.getRank() != multiplesRank)
2672 return emitOpError(
"expect 'multiples' array to have length ")
2673 << outputType.getRank() <<
" but got " << multiplesRank <<
".";
2676 if (getConstantMultiples(multiples).succeeded() &&
2677 llvm::any_of(multiples, [](
int64_t v) {
return v <= 0 && v != -1; }))
2679 "expect element of 'multiples' to be positive integer or -1.");
2685 if (l.size() != r.size() || l.size() != 1)
2690LogicalResult tosa::ReshapeOp::inferReturnTypeComponents(
2691 MLIRContext *context, ::std::optional<Location> location,
2692 ReshapeOp::Adaptor adaptor,
2694 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2699 auto rank = cast<tosa::shapeType>(adaptor.getShape().getType()).getRank();
2708 if (!inputShape.hasRank() || !inputShape.hasStaticShape()) {
2709 inferredReturnShapes.push_back(
2717 int64_t numElements = inputShape.getNumElements();
2719 for (
auto val : newShapeValue) {
2720 if (ShapedType::isStatic(val)) {
2726 for (
auto &val : newShapeValue) {
2727 if (ShapedType::isDynamic(val))
2728 val = numElements / staticMul;
2731 inferredReturnShapes.push_back(
2736llvm::LogicalResult tosa::ReshapeOp::verify() {
2742 TensorType inputType = getInput1().getType();
2747 return mlir::success();
2751 if (missingDims > 1)
2752 return emitOpError() <<
"expected at most one target dimension to be "
2755 const auto outputType = dyn_cast<RankedTensorType>(
getType());
2759 if ((
int64_t)shapeValues.size() != outputType.getRank())
2760 return emitOpError() <<
"new shape does not match result rank";
2762 for (
auto [newShapeDim, outputShapeDim] :
2763 zip(shapeValues, outputType.getShape())) {
2765 newShapeDim != ShapedType::kDynamic &&
2766 outputShapeDim != ShapedType::kDynamic && newShapeDim != outputShapeDim)
2767 return emitOpError() <<
"new shape is inconsistent with result shape";
2770 return emitOpError() <<
"new shape has invalid tensor dimension size "
2774 if (inputType.hasStaticShape()) {
2775 int64_t inputElementsNum = inputType.getNumElements();
2776 if (outputType.hasStaticShape()) {
2777 int64_t outputElementsNum = outputType.getNumElements();
2778 if (inputElementsNum != outputElementsNum) {
2779 return emitOpError() <<
"cannot reshape " << inputElementsNum
2780 <<
" elements into " << outputElementsNum;
2786 return (dim > 0) ?
acc * dim :
acc;
2788 bool isStaticNewShape =
2789 llvm::all_of(shapeValues, [](
int64_t s) {
return s > 0; });
2790 if ((isStaticNewShape && inputElementsNum != newShapeElementsNum) ||
2791 (!isStaticNewShape && newShapeElementsNum > inputElementsNum)) {
2792 return emitOpError() <<
"cannot reshape " << inputElementsNum
2793 <<
" elements into " << newShapeElementsNum;
2797 return mlir::success();
2800bool tosa::ReshapeBlockScaledOp::isCompatibleReturnTypes(
TypeRange l,
2802 if (l.size() != r.size() || l.size() < 1 || l.size() > 2)
2810LogicalResult tosa::ReshapeBlockScaledOp::inferReturnTypeComponents(
2811 MLIRContext *context, ::std::optional<Location> location,
2812 ReshapeBlockScaledOp::Adaptor adaptor,
2815 const auto numInputs = adaptor.getInput().size();
2816 ShapeAdaptor inputShape(adaptor.getInput()[0].getType());
2819 const auto newShape = adaptor.getNewValueShape();
2821 auto rank = cast<tosa::shapeType>(newShape.getType()).getRank();
2830 const uint32_t blockSize =
2831 BlockSizeAttr::getBlockSizeValue(adaptor.getBlockSize());
2834 if (numInputs == 2) {
2835 newScaleShapeValue.assign(newShapeValue.begin(), newShapeValue.end());
2836 if (!newScaleShapeValue.empty() &&
2837 ShapedType::isStatic(newScaleShapeValue.back()))
2838 newScaleShapeValue.back() /= blockSize;
2841 inferredReturnShapes.push_back(
2843 if (numInputs == 2) {
2845 for (
size_t idx = 0; idx < newShapeValue.size(); idx++) {
2846 if (ShapedType::isDynamic(newScaleShapeValue[idx])) {
2847 newScaleShapeValue[idx] = newShapeValue[idx];
2848 if (idx + 1 == newShapeValue.size())
2849 newScaleShapeValue[idx] /= blockSize;
2860llvm::LogicalResult tosa::ReshapeBlockScaledOp::verify() {
2864 if (inputList.size() == 0)
2865 return emitOpError(
"requires at least one input");
2867 if (inputList.size() > 2)
2868 return emitOpError(
"requires at most two inputs");
2870 if (inputList.size() != outputList.size())
2871 return emitOpError(
"requires number of results to match inputs");
2879 if (inputList.size() == 2 &&
2880 cast<tosa::shapeType>(getNewValueShape().
getType()).getRank() == 0)
2881 return emitOpError(
"requires new shape to have a rank greater than 0");
2883 const auto inputType = llvm::cast<ShapedType>(inputList[0].
getType());
2884 if (!inputType.hasRank())
2886 const uint32_t blockSize = BlockSizeAttr::getBlockSizeValue(
getBlockSize());
2888 if (inputList.size() == 2) {
2889 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_32))
2890 return emitOpError(
"expect block size to be 32, got ") << blockSize;
2891 if (llvm::any_of(inputList, [](
Value v) {
2892 const auto input = cast<ShapedType>(v.
getType());
2893 return input.hasRank() && input.getRank() == 0;
2896 "requires all input shapes have a rank greater than 0");
2897 if (llvm::any_of(outputList, [](
Value v) {
2898 const auto output = cast<ShapedType>(v.
getType());
2899 return output.hasRank() && output.getRank() == 0;
2902 "requires all result shapes have a rank greater than 0");
2910 const auto inputScaleType = llvm::cast<ShapedType>(inputList[1].
getType());
2911 if (inputScaleType.hasRank()) {
2912 if (inputType.getRank() != inputScaleType.getRank())
2913 return emitOpError(
"input shapes do not have same rank");
2916 for (
auto dimIdx = 0; dimIdx < inputType.getRank() - 1; dimIdx++) {
2917 const int64_t inputValueDim = inputType.getDimSize(dimIdx);
2918 const int64_t inputScaleDim = inputScaleType.getShape()[dimIdx];
2919 if (ShapedType::isStatic(inputValueDim) &&
2920 ShapedType::isStatic(inputScaleDim) &&
2921 inputValueDim != inputScaleDim)
2922 return emitOpError(
"input shapes for data and scale do not match on "
2929 inputType.getDimSize(inputType.getRank() - 1);
2930 if (ShapedType::isStatic(lastValueDim)) {
2931 if (lastValueDim % blockSize != 0)
2932 return emitOpError(
"expect last dimension of input_data (")
2933 << lastValueDim <<
") to be divisible by block_size ("
2934 << blockSize <<
")";
2937 inputScaleType.getDimSize(inputScaleType.getRank() - 1);
2939 if (ShapedType::isStatic(lastScaleDim) &&
2940 lastScaleDim != lastValueDim / blockSize)
2941 return emitOpError(
"expect last dimension of scale_data (")
2942 << lastScaleDim <<
") to be " << lastValueDim <<
"/"
2947 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_1))
2948 return emitOpError(
"expect block size to be 1, got ") << blockSize;
2956 return mlir::success();
2959 if (inputList.size() == 2) {
2960 const int64_t lastShapeDim = shapeValues.back();
2961 if (ShapedType::isStatic(lastShapeDim) && lastShapeDim % blockSize != 0)
2962 return emitOpError(
"expect last dimension of new shape (")
2963 << lastShapeDim <<
") to be divisible by block_size (" << blockSize
2967 const auto outputType = llvm::cast<ShapedType>(outputList[0].
getType());
2968 if (!outputType.hasRank())
2971 if (
static_cast<int64_t>(shapeValues.size()) != outputType.getRank())
2972 return emitOpError() <<
"result does not match new shape rank";
2974 for (
auto [newShapeDim, outputShapeDim] :
2975 zip(shapeValues, outputType.getShape())) {
2976 if (ShapedType::isStatic(newShapeDim) &&
2977 ShapedType::isStatic(outputShapeDim) && newShapeDim != outputShapeDim)
2978 return emitOpError() <<
"result shape is inconsistent with new shape";
2981 if (outputList.size() == 2) {
2985 scaleShapeValues.back() /= blockSize;
2987 const auto outputScaleType =
2988 llvm::cast<ShapedType>(outputList[1].
getType());
2989 if (outputScaleType.hasRank()) {
2990 if ((
int64_t)scaleShapeValues.size() != outputScaleType.getRank())
2991 return emitOpError() <<
"result scale does not match new shape rank";
2993 for (
auto [newScaleShapeDim, outputScaleShapeDim] :
2994 zip(scaleShapeValues, outputScaleType.getShape())) {
2995 if (ShapedType::isStatic(newScaleShapeDim) &&
2996 ShapedType::isStatic(outputScaleShapeDim) &&
2997 newScaleShapeDim != outputScaleShapeDim)
2998 return emitOpError()
2999 <<
"result scale shape is inconsistent with new shape";
3004 if (inputType.hasStaticShape()) {
3005 int64_t inputElementsNum = inputType.getNumElements();
3006 if (outputType.hasStaticShape()) {
3007 int64_t outputElementsNum = outputType.getNumElements();
3008 if (inputElementsNum != outputElementsNum) {
3009 return emitOpError() <<
"cannot reshape " << inputElementsNum
3010 <<
" elements into " << outputElementsNum;
3016 return (dim > 0) ?
acc * dim :
acc;
3018 bool isStaticNewShape =
3019 llvm::all_of(shapeValues, [](
int64_t s) {
return s > 0; });
3020 if ((isStaticNewShape && inputElementsNum != newShapeElementsNum) ||
3021 (!isStaticNewShape && newShapeElementsNum > inputElementsNum)) {
3022 return emitOpError() <<
"cannot reshape " << inputElementsNum
3023 <<
" elements into " << newShapeElementsNum;
3027 return mlir::success();
3034 ElementsAttr zpAttr;
3039 Type zpElemType = zpAttr.getElementType();
3041 if (llvm::isa<FloatType>(zpElemType)) {
3042 if (zpAttr.getValues<APFloat>()[0].isZero()) {
3049 if (llvm::isa<IntegerType>(zpElemType)) {
3051 return zpAttr.getValues<APInt>()[0].getSExtValue();
3052 return zpAttr.getValues<APInt>()[0].getZExtValue();
3059template <
typename T>
3061 const std::string &operand) {
3064 if (!zpElemType.
isInteger(8) && zp != 0) {
3066 std::string lower = operand;
3067 llvm::transform(lower, lower.begin(), ::tolower);
3068 return op.emitOpError()
3069 << lower <<
" zero point must be zero for non-int8 integer types";
3077 const std::string &operand) {
3078 bool isInputZp = (operand ==
"Input");
3080 bool tensorUnsigned =
3081 isInputZp ? op.getInputUnsigned() : op.getOutputUnsigned();
3082 StringRef tensorName = isInputZp ?
"input" :
"output";
3088 !(zpElemType.
isInteger(16) && tensorUnsigned)) {
3089 return op.emitOpError()
3090 <<
"expect " << tensorName <<
"_zp of 0, got " << zp;
3092 if (zpElemType.
isInteger(16) && tensorUnsigned && zp != 32768) {
3093 return op.emitOpError() <<
"expect " << tensorName
3094 <<
"_zp of 0 or 32768 for unsigned int16 "
3095 << tensorName <<
", got " << zp;
3102#define ZERO_POINT_HELPER(OP, OPERAND_NAME, SIGN_EXTEND) \
3103 FailureOr<int64_t> tosa::OP::get##OPERAND_NAME##ZeroPoint() { \
3104 return getZeroPoint(get##OPERAND_NAME##Zp(), SIGN_EXTEND); \
3106 LogicalResult tosa::OP::verify##OPERAND_NAME##ZeroPoint(int64_t zp) { \
3107 return verifyZeroPoint(*this, get##OPERAND_NAME##Zp(), zp, #OPERAND_NAME); \
3130#undef ZERO_POINT_HELPER
3132LogicalResult tosa::TransposeOp::inferReturnTypeComponents(
3133 MLIRContext *context, ::std::optional<Location> location,
3134 TransposeOp::Adaptor adaptor,
3136 ShapeAdaptor inputShape(adaptor.getInput1().getType());
3145 const auto inputRank = inputShape.
getRank();
3149 if (adaptor.getPerms().size() !=
static_cast<size_t>(inputRank)) {
3155 if (inputRank == 0) {
3161 bool allTheSame =
true;
3162 for (
int i = 1, s = inputRank; i < s; i++) {
3172 outputShape.resize(inputRank, inputShape.
getDimSize(0));
3177 outputShape.resize(inputRank, ShapedType::kDynamic);
3180 if (llvm::any_of(adaptor.getPerms(),
3181 [inputRank](
const auto i) { return i >= inputRank; }))
3184 outputShape.reserve(inputRank);
3185 for (
int i = 0, s = inputRank; i < s; i++) {
3186 outputShape[i] = inputShape.
getDimSize(adaptor.getPerms()[i]);
3193LogicalResult tosa::TransposeOp::verify() {
3205 if (inputShape.hasRank() &&
3206 constantPerms.size() !=
static_cast<size_t>(inputShape.getRank()))
3207 return emitOpError() <<
"expected perms attribute to have size "
3208 << inputShape.getRank()
3209 <<
" (input rank) but got size "
3210 << constantPerms.size();
3212 if (inputShape.hasRank() && outputShape.hasRank() &&
3213 inputShape.getRank() != outputShape.getRank())
3214 return emitOpError()
3215 <<
"expected input tensor rank to equal result tensor rank";
3217 if (outputShape.hasRank() &&
3218 constantPerms.size() !=
static_cast<size_t>(outputShape.getRank()))
3219 return emitOpError() <<
"expected perms attribute to have size "
3220 << outputShape.getRank()
3221 <<
" (output rank) but got size "
3222 << constantPerms.size();
3224 if (!llvm::all_of(constantPerms,
3225 [&constantPerms](int32_t s) {
3227 static_cast<size_t>(s) < constantPerms.size();
3230 constantPerms, [](int32_t v) ->
int64_t {
return v; })))
3231 return emitOpError() <<
"expected valid permutation indices";
3234 constantPerms.back() !=
static_cast<int32_t
>(constantPerms.size()) - 1) {
3235 return emitOpError() <<
"expected no-op permutation on innermost dimension "
3236 "for block scaled input";
3240 if (inputShape.hasStaticShape() && outputShape.hasStaticShape() &&
3241 inputShape.getNumElements() != outputShape.getNumElements())
3242 return emitOpError() <<
"expected input1 and output to have same numbers "
3244 << inputShape.getNumElements() <<
" and "
3245 << outputShape.getNumElements();
3249 if (inputShape.hasRank() && outputShape.hasRank()) {
3250 for (
auto i = 0; i < outputShape.getRank(); i++) {
3251 if (inputShape.isDynamicDim(constantPerms[i]) ||
3252 outputShape.isDynamicDim(i))
3255 if (inputShape.getDimSize(constantPerms[i]) != outputShape.getDimSize(i))
3256 return emitOpError()
3257 <<
"expected output tensor dim " << i <<
" to match "
3258 <<
"input dim " << constantPerms[i] <<
" with value of "
3259 << inputShape.getDimSize(constantPerms[i]);
3266LogicalResult TransposeOp::reifyResultShapes(
3269 const llvm::ArrayRef<int32_t> transposePerms = getPerms();
3271 Value input = getInput1();
3272 auto inputType = cast<TensorType>(input.
getType());
3274 SmallVector<OpFoldResult> returnedDims(inputType.getRank());
3275 for (
auto dim : transposePerms) {
3276 int32_t dimInInput = transposePerms[dim];
3277 if (inputType.isDynamicDim(dimInInput))
3279 tensor::DimOp::create(builder, getLoc(), input, dimInInput)
3283 builder.
getIndexAttr(inputType.getDimSize(dimInInput));
3286 reifiedReturnShapes.emplace_back(std::move(returnedDims));
3290LogicalResult tosa::GatherOp::inferReturnTypeComponents(
3291 MLIRContext *context, ::std::optional<Location> location,
3292 GatherOp::Adaptor adaptor,
3293 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3294 llvm::SmallVector<int64_t> outputShape;
3295 outputShape.resize(3, ShapedType::kDynamic);
3297 ShapeAdaptor valuesShape(adaptor.getValues().getType());
3298 if (valuesShape.hasRank()) {
3299 outputShape[0] = valuesShape.getDimSize(0);
3300 outputShape[2] = valuesShape.getDimSize(2);
3303 ShapeAdaptor indicesShape(adaptor.getIndices().getType());
3304 if (indicesShape.hasRank()) {
3305 if (outputShape[0] == ShapedType::kDynamic)
3306 outputShape[0] = indicesShape.getDimSize(0);
3307 if (outputShape[1] == ShapedType::kDynamic)
3308 outputShape[1] = indicesShape.getDimSize(1);
3311 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3315LogicalResult tosa::RowGatherOp::inferReturnTypeComponents(
3316 MLIRContext *context, ::std::optional<Location> location,
3317 RowGatherOp::Adaptor adaptor,
3318 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3319 llvm::SmallVector<int64_t> outputShape;
3320 outputShape.resize(3, ShapedType::kDynamic);
3322 const ShapeAdaptor valuesShape(adaptor.getValues().getType());
3323 if (valuesShape.hasRank()) {
3324 outputShape[0] = valuesShape.getDimSize(0);
3325 outputShape[2] = valuesShape.getDimSize(2);
3328 const ShapeAdaptor indicesShape(adaptor.getIndices().getType());
3329 if (indicesShape.hasRank()) {
3330 if (outputShape[0] == ShapedType::kDynamic)
3331 outputShape[0] = indicesShape.getDimSize(0);
3333 const FailureOr<int32_t> maybeRowCount =
3335 if (succeeded(maybeRowCount)) {
3336 const int64_t indicesW = indicesShape.getDimSize(1);
3337 if (ShapedType::isStatic(indicesW))
3338 outputShape[1] = indicesW * maybeRowCount.value();
3342 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3346LogicalResult tosa::RowGatherBlockScaledOp::inferReturnTypeComponents(
3347 MLIRContext *context, ::std::optional<Location> location,
3348 RowGatherBlockScaledOp::Adaptor adaptor,
3349 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3350 const auto values = adaptor.getValues();
3354 SmallVector<int64_t> dataShape(3, ShapedType::kDynamic);
3355 const ShapeAdaptor valuesShape(values.front().getType());
3356 if (valuesShape.hasRank()) {
3357 dataShape[0] = valuesShape.getDimSize(0);
3358 dataShape[2] = valuesShape.getDimSize(2);
3361 const ShapeAdaptor indicesShape(adaptor.getIndices().getType());
3362 if (indicesShape.hasRank()) {
3363 if (dataShape[0] == ShapedType::kDynamic)
3364 dataShape[0] = indicesShape.getDimSize(0);
3368 succeeded(rowCount) && rowCount.value() > 0) {
3369 const int64_t indicesW = indicesShape.getDimSize(1);
3370 if (ShapedType::isStatic(indicesW))
3371 dataShape[1] = indicesW * rowCount.value();
3375 inferredReturnShapes.push_back(ShapedTypeComponents(dataShape));
3376 if (values.size() == 1)
3379 SmallVector<int64_t> scaleShape = dataShape;
3380 const uint32_t blockSize =
3381 BlockSizeAttr::getBlockSizeValue(adaptor.getBlockSize());
3382 if (ShapedType::isStatic(dataShape[2]))
3383 scaleShape[2] = dataShape[2] / blockSize;
3385 inferredReturnShapes.push_back(ShapedTypeComponents(scaleShape));
3389LogicalResult tosa::GatherOp::verify() {
3396 const ShapeAdaptor valuesShape(getValues().
getType());
3398 const ShapeAdaptor outputShape(getOutput().
getType());
3400 int64_t n = ShapedType::kDynamic;
3401 int64_t w = ShapedType::kDynamic;
3402 int64_t c = ShapedType::kDynamic;
3404 if (valuesShape.hasRank()) {
3405 n = valuesShape.getDimSize(0);
3406 c = valuesShape.getDimSize(2);
3408 if (indicesShape.hasRank()) {
3409 const int64_t indicesN = indicesShape.getDimSize(0);
3410 w = indicesShape.getDimSize(1);
3411 if (n == ShapedType::kDynamic)
3413 else if (indicesN != ShapedType::kDynamic && n != indicesN)
3414 return emitOpError() <<
"requires indices dimension 0 to have size " << n
3415 <<
", got " << indicesN;
3417 if (outputShape.hasRank()) {
3418 const int64_t outputN = outputShape.getDimSize(0);
3419 const int64_t outputW = outputShape.getDimSize(1);
3420 const int64_t outputC = outputShape.getDimSize(2);
3421 if (n != ShapedType::kDynamic && outputN != ShapedType::kDynamic &&
3423 return emitOpError() <<
"requires output dimension 0 to have size " << n
3424 <<
", got " << outputN;
3426 if (w != ShapedType::kDynamic && outputW != ShapedType::kDynamic &&
3428 return emitOpError() <<
"requires output dimension 1 to have size " << w
3429 <<
", got " << outputW;
3430 if (c != ShapedType::kDynamic && outputC != ShapedType::kDynamic &&
3432 return emitOpError() <<
"requires output dimension 2 to have size " << c
3433 <<
", got " << outputC;
3438LogicalResult tosa::RowGatherOp::verify() {
3443 const FailureOr<int32_t> maybeRowCount =
3445 if (succeeded(maybeRowCount) && maybeRowCount.value() <= 0)
3446 return emitOpError() <<
"requires row_count to be > 0, got "
3447 << maybeRowCount.value();
3449 int64_t n = ShapedType::kDynamic;
3450 int64_t c = ShapedType::kDynamic;
3451 int64_t w = ShapedType::kDynamic;
3453 const ShapeAdaptor valuesShape(getValues().
getType());
3454 if (valuesShape.hasRank()) {
3455 n = valuesShape.getDimSize(0);
3456 c = valuesShape.getDimSize(2);
3460 if (indicesShape.hasRank()) {
3462 "indices",
"batch")))
3464 w = indicesShape.getDimSize(1);
3467 const ShapeAdaptor outputShape(getOutput().
getType());
3468 if (outputShape.hasRank()) {
3470 "output",
"batch")) ||
3472 "output",
"channels")))
3475 if (succeeded(maybeRowCount) && maybeRowCount.value() > 0 &&
3476 ShapedType::isStatic(w)) {
3477 const int64_t expectedOutputRows = w * maybeRowCount.value();
3478 if (ShapedType::isStatic(outputShape.getDimSize(1)) &&
3479 outputShape.getDimSize(1) != expectedOutputRows)
3480 return emitOpError()
3481 <<
"requires output dimension to be equal to "
3482 "indices[1]*row_count ("
3483 << expectedOutputRows <<
"), got " << outputShape.getDimSize(1);
3490LogicalResult tosa::RowGatherBlockScaledOp::verify() {
3491 const OperandRange values = getValues();
3492 const ResultRange output = getOutput();
3493 if (values.empty() || values.size() > 2)
3494 return emitOpError()
3495 <<
"expects values tensor list length to be 1 or 2, got "
3497 if (output.size() != values.size())
3498 return emitOpError()
3499 <<
"expects output tensor list length to match values tensor list "
3501 << output.size() <<
" results for " << values.size()
3502 <<
" input tensors";
3504 const uint32_t blockSize = BlockSizeAttr::getBlockSizeValue(
getBlockSize());
3505 if (values.size() == 1 && blockSize != 1)
3506 return emitOpError()
3507 <<
"requires block_size to be BLOCK_SIZE_1 when values tensor list "
3509 if (values.size() == 2 && blockSize == 1)
3510 return emitOpError()
3511 <<
"requires block_size to not be BLOCK_SIZE_1 when values tensor "
3515 output[0].
getType(),
"values[0]",
3520 "values[1]",
"output[1]")))
3524 succeeded(rowCount) && rowCount.value() <= 0)
3525 return emitOpError() <<
"requires row_count to be > 0, got "
3526 << rowCount.value();
3528 int64_t n = ShapedType::kDynamic;
3529 int64_t k = ShapedType::kDynamic;
3530 int64_t c = ShapedType::kDynamic;
3531 int64_t w = ShapedType::kDynamic;
3532 int64_t multiplesOfC = ShapedType::kDynamic;
3534 const ShapeAdaptor valuesDataShape(values[0].
getType());
3535 if (valuesDataShape.hasRank()) {
3536 n = valuesDataShape.getDimSize(0);
3537 k = valuesDataShape.getDimSize(1);
3538 c = valuesDataShape.getDimSize(2);
3541 if (ShapedType::isStatic(c) && c % blockSize != 0)
3542 return emitOpError() <<
"expects channels of values[0] (" << c
3543 <<
") to be divisible by block_size (" << blockSize
3547 if (indicesShape.hasRank()) {
3549 "indices",
"batch")))
3551 w = indicesShape.getDimSize(1);
3554 const ShapeAdaptor outputDataShape(output[0].
getType());
3555 if (outputDataShape.hasRank()) {
3557 "output[0]",
"batch")) ||
3559 "output[0]",
"channels")))
3563 succeeded(rowCount) && rowCount.value() > 0 &&
3564 ShapedType::isStatic(w)) {
3565 const int64_t expectedOutputRows = w * rowCount.value();
3566 if (ShapedType::isStatic(outputDataShape.getDimSize(1)) &&
3567 outputDataShape.getDimSize(1) != expectedOutputRows)
3568 return emitOpError() <<
"requires output[0] dimension 1 to have size "
3569 << expectedOutputRows <<
", got "
3570 << outputDataShape.getDimSize(1);
3574 if (values.size() == 2) {
3575 const ShapeAdaptor valuesScaleShape(values[1].
getType());
3576 if (valuesScaleShape.hasRank()) {
3578 "values[1]",
"batch")) ||
3580 "values[1]",
"rows")))
3582 multiplesOfC = valuesScaleShape.getDimSize(2);
3585 const ShapeAdaptor outputScaleShape(output[1].
getType());
3586 if (outputScaleShape.hasRank()) {
3588 "output[1]",
"batch")))
3592 succeeded(rowCount) && rowCount.value() > 0 &&
3593 ShapedType::isStatic(w)) {
3594 const int64_t expectedOutputRows = w * rowCount.value();
3595 if (ShapedType::isStatic(outputScaleShape.getDimSize(1)) &&
3596 outputScaleShape.getDimSize(1) != expectedOutputRows)
3597 return emitOpError() <<
"requires output[1] dimension 1 to have size "
3598 << expectedOutputRows <<
", got "
3599 << outputScaleShape.getDimSize(1);
3602 if (ShapedType::isDynamic(multiplesOfC))
3603 multiplesOfC = outputScaleShape.getDimSize(2);
3604 else if (ShapedType::isStatic(outputScaleShape.getDimSize(2)) &&
3605 multiplesOfC != outputScaleShape.getDimSize(2))
3606 return emitOpError()
3607 <<
"expected channels of output[1] to match size "
3608 << multiplesOfC <<
", got " << outputScaleShape.getDimSize(2);
3611 if (ShapedType::isStatic(c) && ShapedType::isStatic(multiplesOfC) &&
3612 multiplesOfC != c / blockSize)
3613 return emitOpError()
3614 <<
"expects channels of scale tensors to equal C/block_size (" << c
3615 <<
"/" << blockSize <<
"), got " << multiplesOfC;
3621LogicalResult tosa::ResizeOp::inferReturnTypeComponents(
3622 MLIRContext *context, ::std::optional<Location> location,
3623 ResizeOp::Adaptor adaptor,
3624 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3625 llvm::SmallVector<int64_t, 4> outputShape;
3626 outputShape.resize(4, ShapedType::kDynamic);
3628 ShapeAdaptor inputShape(adaptor.getInput().getType());
3629 if (!inputShape.hasRank())
3632 outputShape[0] = inputShape.getDimSize(0);
3633 outputShape[3] = inputShape.getDimSize(3);
3634 int64_t inputHeight = inputShape.getDimSize(1);
3635 int64_t inputWidth = inputShape.getDimSize(2);
3637 if ((inputHeight == ShapedType::kDynamic) ||
3638 (inputWidth == ShapedType::kDynamic))
3641 SmallVector<int64_t> scaleInt, offsetInt, borderInt;
3653 if (llvm::any_of(scaleInt, [](int64_t s) {
return s <= 0; }))
3657 const int64_t outputHeight =
3658 (((inputHeight - 1) * scaleInt[0] - offsetInt[0] + borderInt[0]) /
3662 const int64_t outputWidth =
3663 (((inputWidth - 1) * scaleInt[2] - offsetInt[1] + borderInt[1]) /
3667 if (outputHeight < 0 || outputWidth < 0) {
3670 "calculated output height and width must be non-negative, "
3672 outputHeight,
", width = ", outputWidth);
3675 outputShape[1] = outputHeight;
3676 outputShape[2] = outputWidth;
3677 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3681LogicalResult tosa::ResizeOp::verify() {
3684 if (isa<BlockScaledType>(inputElementType) &&
3685 getMode() != ResizeMode::NEAREST_NEIGHBOR)
3686 return emitOpError(
"requires NEAREST_NEIGHBOR mode for block scaled input");
3691LogicalResult tosa::ScatterOp::inferReturnTypeComponents(
3692 MLIRContext *context, ::std::optional<Location> location,
3693 ScatterOp::Adaptor adaptor,
3694 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3695 llvm::SmallVector<int64_t> outputShape;
3696 outputShape.resize(3, ShapedType::kDynamic);
3698 ShapeAdaptor valuesInShape(adaptor.getValuesIn().getType());
3699 if (valuesInShape.hasRank()) {
3700 outputShape[0] = valuesInShape.getDimSize(0);
3701 outputShape[1] = valuesInShape.getDimSize(1);
3702 outputShape[2] = valuesInShape.getDimSize(2);
3705 ShapeAdaptor indicesShape(adaptor.getIndices().getType());
3706 if (indicesShape.hasRank()) {
3707 if (outputShape[0] == ShapedType::kDynamic)
3708 outputShape[0] = indicesShape.getDimSize(0);
3711 ShapeAdaptor inputShape(adaptor.getInput().getType());
3712 if (inputShape.hasRank()) {
3713 if (outputShape[0] == ShapedType::kDynamic)
3714 outputShape[0] = inputShape.getDimSize(0);
3715 if (outputShape[2] == ShapedType::kDynamic)
3716 outputShape[2] = inputShape.getDimSize(2);
3719 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3723LogicalResult tosa::ScatterOp::verify() {
3733 const ShapeAdaptor valuesInShape(getValuesIn().
getType());
3735 const ShapeAdaptor inputShape(getInput().
getType());
3736 const ShapeAdaptor outputShape(getValuesOut().
getType());
3738 int64_t n = ShapedType::kDynamic;
3739 int64_t k = ShapedType::kDynamic;
3740 int64_t w = ShapedType::kDynamic;
3741 int64_t c = ShapedType::kDynamic;
3742 if (valuesInShape.hasRank()) {
3743 n = valuesInShape.getDimSize(0);
3744 k = valuesInShape.getDimSize(1);
3745 c = valuesInShape.getDimSize(2);
3747 if (indicesShape.hasRank()) {
3748 const int64_t indicesN = indicesShape.getDimSize(0);
3749 w = indicesShape.getDimSize(1);
3750 if (n == ShapedType::kDynamic)
3752 else if (indicesN != ShapedType::kDynamic && n != indicesN)
3753 return emitOpError() <<
"requires indices dimension 0 to have size " << n
3754 <<
", got " << indicesN;
3756 if (inputShape.hasRank()) {
3757 const int64_t inputN = inputShape.getDimSize(0);
3758 const int64_t inputW = inputShape.getDimSize(1);
3759 const int64_t inputC = inputShape.getDimSize(2);
3760 if (n == ShapedType::kDynamic)
3762 else if (inputN != ShapedType::kDynamic && n != inputN)
3763 return emitOpError() <<
"requires input dimension 0 to have size " << n
3764 <<
", got " << inputN;
3765 if (w == ShapedType::kDynamic)
3767 else if (inputW != ShapedType::kDynamic && w != inputW)
3768 return emitOpError() <<
"requires input dimension 1 to have size " << w
3769 <<
", got " << inputW;
3771 if (c == ShapedType::kDynamic)
3773 else if (inputC != ShapedType::kDynamic && c != inputC)
3774 return emitOpError() <<
"requires input dimension 2 to have size " << c
3775 <<
", got " << inputC;
3777 if (outputShape.hasRank()) {
3778 const int64_t outputN = outputShape.getDimSize(0);
3779 const int64_t outputK = outputShape.getDimSize(1);
3780 const int64_t outputC = outputShape.getDimSize(2);
3781 if (n != ShapedType::kDynamic && outputN != ShapedType::kDynamic &&
3783 return emitOpError() <<
"requires values_out dimension 0 to have size "
3784 << n <<
", got " << outputN;
3785 if (k == ShapedType::kDynamic)
3787 else if (outputK != ShapedType::kDynamic && k != outputK)
3788 return emitOpError() <<
"requires values_out dimension 1 to have size "
3789 << k <<
", got " << outputK;
3790 if (c != ShapedType::kDynamic && outputC != ShapedType::kDynamic &&
3792 return emitOpError() <<
"requires values_out dimension 2 to have size "
3793 << c <<
", got " << outputC;
3795 if (k != ShapedType::kDynamic && w != ShapedType::kDynamic && !(k >= w))
3796 return emitOpError() <<
"requires dimensions K >= W, got K=" << k
3805 int64_t axisVal = axis.getValue().getSExtValue();
3806 if (!operandShape.
hasRank() || operandShape.
getRank() <= axisVal) {
3812 operandShape.
getDims(outputShape);
3813 outputShape[axisVal] = 1;
3818#define COMPATIBLE_RETURN_TYPES(OP) \
3819 bool OP::isCompatibleReturnTypes(TypeRange l, TypeRange r) { \
3820 if (l.size() != r.size() || l.size() != 1) \
3822 if (getElementTypeOrSelf(l[0]) != getElementTypeOrSelf(r[0])) \
3824 return succeeded(verifyCompatibleShape(l[0], r[0])); \
3827#define REDUCE_SHAPE_INFER(OP) \
3828 LogicalResult OP::inferReturnTypeComponents( \
3829 MLIRContext *context, ::std::optional<Location> location, \
3830 OP::Adaptor adaptor, \
3831 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) { \
3833 llvm::cast<TensorType>(adaptor.getInput().getType()).getElementType(); \
3834 ShapeAdaptor inputShape(adaptor.getInput().getType()); \
3835 const Properties &prop = adaptor.getProperties(); \
3836 return ReduceInferReturnTypes(inputShape, inputType, prop.axis, \
3837 inferredReturnShapes); \
3839 COMPATIBLE_RETURN_TYPES(OP)
3847#undef REDUCE_SHAPE_INFER
3849#undef COMPATIBLE_RETURN_TYPES
3851template <
typename T>
3854 TensorType inputType = op.getInput().getType();
3855 TensorType outputType = op.getOutput().getType();
3856 int32_t reduceAxis = op.getAxis();
3858 if (reduceAxis < 0) {
3859 op.emitOpError(
"reduce axis must not be negative");
3863 int64_t inputRank = inputType.getRank();
3866 if (reduceAxis >= inputRank && (reduceAxis != 0 || inputRank != 0)) {
3867 op.emitOpError(
"expect input tensor rank (")
3868 << inputRank <<
") to be larger than reduce axis (" << reduceAxis
3874 int64_t outputRank = outputType.getRank();
3875 if (inputType.
hasRank() && outputRank != inputType.getRank()) {
3877 "expect output tensor rank to be equal to input tensor rank");
3880 if (reduceAxis >= outputRank && (reduceAxis != 0 || outputRank != 0)) {
3881 op.emitOpError(
"expect output tensor rank (")
3882 << outputRank <<
") to be larger than reduce axis (" << reduceAxis
3888 if (outputRank != 0) {
3889 auto outputShape = outputType.
getShape();
3890 if (!outputType.isDynamicDim(reduceAxis) &&
3891 outputShape[reduceAxis] != 1) {
3892 op.emitOpError(
"expect reduced dimension size to be 1, got ")
3893 << outputShape[reduceAxis];
3901LogicalResult tosa::ReduceAllOp::verify() {
return verifyReduceOp(*
this); }
3902LogicalResult tosa::ReduceAnyOp::verify() {
return verifyReduceOp(*
this); }
3903LogicalResult tosa::ReduceMaxOp::verify() {
return verifyReduceOp(*
this); }
3904LogicalResult tosa::ReduceMinOp::verify() {
return verifyReduceOp(*
this); }
3905LogicalResult tosa::ReduceProductOp::verify() {
return verifyReduceOp(*
this); }
3906LogicalResult tosa::ReduceSumOp::verify() {
return verifyReduceOp(*
this); }
3920#define NARY_SHAPE_INFER(OP) \
3921 LogicalResult OP::inferReturnTypeComponents( \
3922 MLIRContext *context, ::std::optional<Location> location, \
3923 ValueShapeRange operands, DictionaryAttr attributes, \
3924 PropertyRef properties, RegionRange regions, \
3925 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) { \
3926 return NAryInferReturnTypes(operands, inferredReturnShapes); \
3966#undef PRED_SHAPE_INFER
3968LogicalResult tosa::NegateOp::inferReturnTypeComponents(
3969 MLIRContext *context, ::std::optional<Location> location,
3970 NegateOp::Adaptor adaptor,
3972 ShapeAdaptor inputShape(adaptor.getInput1().getType());
3977LogicalResult tosa::NegateOp::verify() {
3979 const Type input1Type = getInput1().getType();
3980 const Type outputType = getOutput().getType();
3985 const SmallVector<Type, 2> types = {input1Type, outputType};
3987 return emitOpError() <<
"requires the same shape for input1 and output";
3990 const Type input1ZpEType =
3992 if (input1EType != input1ZpEType) {
3993 return emitOpError(
"expect both input1 and its zero point are the same "
3994 "element type, got ")
3995 << input1EType <<
" and " << input1ZpEType;
3998 const Type outputZpEType =
4000 if (outputEType != outputZpEType) {
4001 return emitOpError(
"expect both output and its zero point are the same "
4002 "element type, got ")
4003 << outputEType <<
" and " << outputZpEType;
4006 FailureOr<int64_t> maybeIZp = getInput1ZeroPoint();
4007 if (succeeded(maybeIZp) && verifyInput1ZeroPoint(*maybeIZp).failed())
4010 FailureOr<int64_t> maybeOZp = getOutputZeroPoint();
4011 if (succeeded(maybeOZp) && verifyOutputZeroPoint(*maybeOZp).failed())
4022 outputShape.resize(4, ShapedType::kDynamic);
4037 if (ShapedType::isStatic(height)) {
4038 int64_t padded = height + pad[0] + pad[1] - kernel[0];
4039 outputShape[1] = padded / stride[0] + 1;
4042 if (ShapedType::isStatic(width)) {
4043 int64_t padded = width + pad[2] + pad[3] - kernel[1];
4044 outputShape[2] = padded / stride[1] + 1;
4051template <
typename AdaptorT>
4057 if (ShapedType::isDynamic(current))
4058 current = candidate;
4067 : adaptor(adaptor) {}
4071 const ShapeAdaptor inputShape(adaptor.getInput().getType());
4079 outputShape[0] = outputBatch;
4080 inputSpatial[0] = inputHeight;
4081 inputSpatial[1] = inputWidth;
4086 const ShapeAdaptor weightShape(adaptor.getWeight().getType());
4094 outputShape[3] = outputChannels;
4095 weightSpatial[0] = kernelHeight;
4096 weightSpatial[1] = kernelWidth;
4105 padValues.assign(adaptor.getPad().begin(), adaptor.getPad().end());
4106 strideValues.assign(adaptor.getStride().begin(), adaptor.getStride().end());
4107 dilationValues.assign(adaptor.getDilation().begin(),
4108 adaptor.getDilation().end());
4113 Conv2DOp::Adaptor adaptor;
4121 : adaptor(adaptor) {}
4125 const ShapeAdaptor inputDataShape(adaptor.getInputData().getType());
4126 if (inputDataShape.
hasRank()) {
4131 outputShape[0] = outputBatch;
4132 inputSpatial[0] = inputHeight;
4133 inputSpatial[1] = inputWidth;
4136 const ShapeAdaptor inputScaleShape(adaptor.getInputScale().getType());
4137 if (!inputScaleShape.
hasRank())
4151 const ShapeAdaptor weightDataShape(adaptor.getWeightData().getType());
4152 if (weightDataShape.
hasRank()) {
4157 outputShape[3] = outputChannels;
4158 weightSpatial[0] = kernelHeight;
4159 weightSpatial[1] = kernelWidth;
4162 const ShapeAdaptor weightScaleShape(adaptor.getWeightScale().getType());
4163 if (!weightScaleShape.
hasRank())
4192 Conv2DBlockScaledOp::Adaptor adaptor;
4200 : adaptor(adaptor) {}
4204 const ShapeAdaptor inputShape(adaptor.getInput().getType());
4213 outputShape[0] = outputBatch;
4214 inputSpatial[0] = inputDepth;
4215 inputSpatial[1] = inputHeight;
4216 inputSpatial[2] = inputWidth;
4221 const ShapeAdaptor weightShape(adaptor.getWeight().getType());
4230 outputShape[4] = outputChannels;
4231 weightSpatial[0] = kernelDepth;
4232 weightSpatial[1] = kernelHeight;
4233 weightSpatial[2] = kernelWidth;
4242 padValues.assign(adaptor.getPad().begin(), adaptor.getPad().end());
4243 strideValues.assign(adaptor.getStride().begin(), adaptor.getStride().end());
4244 dilationValues.assign(adaptor.getDilation().begin(),
4245 adaptor.getDilation().end());
4250 Conv3DOp::Adaptor adaptor;
4253template <
typename AdaptorT>
4259 ShapedType::kDynamic);
4261 ShapedType::kDynamic);
4263 ShapedType::kDynamic);
4265 convShapeAdaptor.inferInputShape(outputShape, inputSpatial);
4266 convShapeAdaptor.inferWeightShape(outputShape, weightSpatial);
4268 const ShapeAdaptor biasShape = adaptor.getBias().getType();
4271 if (biasSize != 1) {
4272 const size_t outputChannelDim = convShapeAdaptor.getOutputRank() - 1;
4273 outputShape[outputChannelDim] =
4274 ShapedType::isDynamic(outputShape[outputChannelDim])
4276 : outputShape[outputChannelDim];
4283 if (failed(convShapeAdaptor.getSpatialParameters(padValues, strideValues,
4289 for (
int64_t dim = 0; dim < convShapeAdaptor.getNumSpatialDims(); ++dim) {
4290 if (!ShapedType::isStatic(inputSpatial[dim]) ||
4291 !ShapedType::isStatic(weightSpatial[dim]))
4294 inputSpatial[dim] + padValues[2 * dim] + padValues[2 * dim + 1];
4296 (weightSpatial[dim] - 1) * dilationValues[dim] + 1;
4297 const int64_t unstridedResult = inputSize - filterSize + 1;
4298 outputShape[dim + 1] = (unstridedResult - 1) / strideValues[dim] + 1;
4305LogicalResult Conv2DOp::inferReturnTypeComponents(
4306 MLIRContext *context, ::std::optional<Location> location,
4307 Conv2DOp::Adaptor adaptor,
4308 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4312LogicalResult Conv2DOp::verify() {
4318LogicalResult Conv2DBlockScaledOp::inferReturnTypeComponents(
4319 MLIRContext *context, ::std::optional<Location> location,
4320 Conv2DBlockScaledOp::Adaptor adaptor,
4321 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4325LogicalResult Conv2DBlockScaledOp::verify() {
4327 getWeightData().
getType(),
"input_data",
4330 getWeightScale().
getType(),
"input_scale",
4333 getOutput().
getType(),
"bias",
"output")))
4337 int64_t N = ShapedType::kDynamic;
4338 int64_t IH = ShapedType::kDynamic;
4339 int64_t IW = ShapedType::kDynamic;
4340 int64_t IC = ShapedType::kDynamic;
4341 int64_t multiplesOfIC = ShapedType::kDynamic;
4342 int64_t OC = ShapedType::kDynamic;
4343 int64_t KH = ShapedType::kDynamic;
4344 int64_t KW = ShapedType::kDynamic;
4346 const ShapeAdaptor inputDataShape(getInputData().
getType());
4347 if (inputDataShape.hasRank()) {
4348 N = inputDataShape.getDimSize(0);
4349 IH = inputDataShape.getDimSize(1);
4350 IW = inputDataShape.getDimSize(2);
4351 IC = inputDataShape.getDimSize(3);
4354 const ShapeAdaptor inputScaleShape(getInputScale().
getType());
4355 if (inputScaleShape.hasRank()) {
4357 "input_scale",
"batch size")) ||
4359 "input_scale",
"input height")) ||
4361 "input_scale",
"input width")))
4363 multiplesOfIC = inputScaleShape.getDimSize(3);
4366 const ShapeAdaptor weightDataShape(getWeightData().
getType());
4367 if (weightDataShape.hasRank()) {
4368 OC = weightDataShape.getDimSize(0);
4369 KH = weightDataShape.getDimSize(1);
4370 KW = weightDataShape.getDimSize(2);
4372 "weight_data",
"input channels")))
4376 const ShapeAdaptor weightScaleShape(getWeightScale().
getType());
4377 if (weightScaleShape.hasRank()) {
4379 "weight_scale",
"output channels")) ||
4381 "weight_scale",
"kernel height")) ||
4383 "weight_scale",
"kernel width")) ||
4385 weightScaleShape.getDimSize(3),
4386 "weight_scale",
"input channel blocks")))
4390 const uint32_t blockSize = BlockSizeAttr::getBlockSizeValue(
getBlockSize());
4391 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_32))
4392 return emitOpError(
"expect block size to be 32, got ") << blockSize;
4394 if (ShapedType::isStatic(IC) && IC % blockSize != 0)
4395 return emitOpError(
"expect IC to be a multiple of block size, got IC=")
4396 << IC <<
", block_size=" << blockSize;
4399 if (ShapedType::isStatic(IC) && ShapedType::isStatic(multiplesOfIC) &&
4400 multiplesOfIC != IC / blockSize)
4402 "expect scale operands dimension 2 to equal IC/block_size (")
4403 << IC <<
"/" << blockSize <<
")"
4404 <<
", got " << multiplesOfIC;
4407 SmallVector<int64_t> padValues;
4409 if (llvm::any_of(padValues, [](int64_t p) {
return p < 0; }))
4410 return emitOpError(
"expect all padding values to be >= 0, got ")
4414 SmallVector<int64_t> strideValues;
4416 if (llvm::any_of(strideValues, [](int64_t s) {
return s < 1; }))
4417 return emitOpError(
"expect all stride values to be >= 1, got ")
4421 SmallVector<int64_t> dilationValues;
4424 if (llvm::any_of(dilationValues, [](int64_t d) {
return d < 1; }))
4425 return emitOpError(
"expect all dilation values to be >= 1, got ")
4430 const ShapeAdaptor outputShape(getOutput().
getType());
4431 if (!padValues.empty() && !strideValues.empty() && !dilationValues.empty() &&
4432 outputShape.hasRank()) {
4434 padValues[0], padValues[1], strideValues[0],
4435 dilationValues[0],
"height",
"y",
"top",
4438 padValues[2], padValues[3], strideValues[1],
4439 dilationValues[1],
"width",
"x",
"left",
4445 const ShapeAdaptor biasShape(getBias().
getType());
4446 if (biasShape.hasRank() && outputShape.hasRank()) {
4447 const int64_t biasChannels = biasShape.getDimSize(0);
4448 const int64_t outputChannels =
4449 outputShape.getDimSize(outputShape.getRank() - 1);
4450 if (biasChannels == ShapedType::kDynamic ||
4451 outputChannels == ShapedType::kDynamic)
4455 if (biasChannels != outputChannels && biasChannels != 1)
4457 "bias channels expected to be equal to output channels (")
4458 << outputChannels <<
") or 1, got " << biasChannels;
4464LogicalResult Conv3DOp::inferReturnTypeComponents(
4465 MLIRContext *context, ::std::optional<Location> location,
4466 Conv3DOp::Adaptor adaptor,
4467 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4471LogicalResult Conv3DOp::verify() {
4477LogicalResult AvgPool2dOp::inferReturnTypeComponents(
4478 MLIRContext *context, ::std::optional<Location> location,
4479 AvgPool2dOp::Adaptor adaptor,
4480 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4481 ShapeAdaptor inputShape(adaptor.getInput().getType());
4482 const Properties &prop = adaptor.getProperties();
4484 inferredReturnShapes);
4487LogicalResult AvgPool2dAdaptiveOp::inferReturnTypeComponents(
4488 MLIRContext *context, ::std::optional<Location> location,
4489 AvgPool2dAdaptiveOp::Adaptor adaptor,
4490 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4491 ShapeAdaptor inputShape(adaptor.getInput().getType());
4493 llvm::SmallVector<int64_t> kernelValues;
4494 llvm::SmallVector<int64_t> strideValues;
4495 llvm::SmallVector<int64_t> padValues;
4502 padValues, inferredReturnShapes);
4505 llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamic);
4506 if (inputShape.hasRank()) {
4508 outputShape[0] = inputShape.getDimSize(0);
4509 outputShape[3] = inputShape.getDimSize(3);
4512 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4516LogicalResult MaxPool2dOp::inferReturnTypeComponents(
4517 MLIRContext *context, ::std::optional<Location> location,
4518 MaxPool2dOp::Adaptor adaptor,
4519 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4520 ShapeAdaptor inputShape(adaptor.getInput().getType());
4521 const Properties &prop = adaptor.getProperties();
4523 inferredReturnShapes);
4526LogicalResult MaxPool2dAdaptiveOp::inferReturnTypeComponents(
4527 MLIRContext *context, ::std::optional<Location> location,
4528 MaxPool2dAdaptiveOp::Adaptor adaptor,
4529 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4530 ShapeAdaptor inputShape(adaptor.getInput().getType());
4532 llvm::SmallVector<int64_t> kernelValues;
4533 llvm::SmallVector<int64_t> strideValues;
4534 llvm::SmallVector<int64_t> padValues;
4541 padValues, inferredReturnShapes);
4544 llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamic);
4545 if (inputShape.hasRank()) {
4546 outputShape[0] = inputShape.getDimSize(0);
4547 outputShape[3] = inputShape.getDimSize(3);
4549 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4553LogicalResult MaxPool2dOp::verify() {
4564LogicalResult MaxPool2dAdaptiveOp::verify() {
4569 AdaptivePoolingConstShapeValues values;
4573 values.pad, getInput(), getOutput())))
4579LogicalResult DepthwiseConv2DOp::inferReturnTypeComponents(
4580 MLIRContext *context, ::std::optional<Location> location,
4581 DepthwiseConv2DOp::Adaptor adaptor,
4582 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4583 llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamic);
4585 int64_t inputWidth = ShapedType::kDynamic;
4586 int64_t inputHeight = ShapedType::kDynamic;
4587 int64_t inputChannels = ShapedType::kDynamic;
4589 int64_t weightWidth = ShapedType::kDynamic;
4590 int64_t weightHeight = ShapedType::kDynamic;
4591 int64_t depthChannels = ShapedType::kDynamic;
4594 ShapeAdaptor inputShape(adaptor.getInput().getType());
4595 if (inputShape.hasRank()) {
4596 outputShape[0] = inputShape.getDimSize(0);
4597 inputHeight = inputShape.getDimSize(1);
4598 inputWidth = inputShape.getDimSize(2);
4599 inputChannels = inputShape.getDimSize(3);
4603 ShapeAdaptor weightShape(adaptor.getWeight().getType());
4604 if (weightShape.hasRank()) {
4605 weightHeight = weightShape.getDimSize(0);
4606 weightWidth = weightShape.getDimSize(1);
4607 inputChannels = ShapedType::isDynamic(inputChannels)
4608 ? weightShape.getDimSize(2)
4610 depthChannels = weightShape.getDimSize(3);
4615 if (ShapedType::isStatic(inputChannels) &&
4616 ShapedType::isStatic(depthChannels)) {
4617 outputShape[3] = inputChannels * depthChannels;
4621 ShapeAdaptor biasShape(adaptor.getBias().getType());
4622 if (biasShape.hasRank() && ShapedType::isDynamic(outputShape[3])) {
4623 int64_t bc = biasShape.getDimSize(0);
4624 if (bc != ShapedType::kDynamic && bc != 1)
4625 outputShape[3] = bc;
4628 llvm::ArrayRef<int64_t> dilation = adaptor.getDilation();
4629 llvm::ArrayRef<int64_t> padding = adaptor.getPad();
4630 llvm::ArrayRef<int64_t> stride = adaptor.getStride();
4632 if (ShapedType::isStatic(inputHeight) && ShapedType::isStatic(weightHeight)) {
4633 int64_t inputSize = inputHeight + padding[0] + padding[1];
4634 int64_t filterSize = (weightHeight - 1) * dilation[0] + 1;
4635 int64_t unstridedResult = inputSize - filterSize + 1;
4636 outputShape[1] = (unstridedResult - 1) / stride[0] + 1;
4639 if (ShapedType::isStatic(inputWidth) && ShapedType::isStatic(weightWidth)) {
4640 int64_t inputSize = inputWidth + padding[2] + padding[3];
4641 int64_t filterSize = (weightWidth - 1) * dilation[1] + 1;
4642 int64_t unstridedResult = inputSize - filterSize + 1;
4643 outputShape[2] = (unstridedResult - 1) / stride[1] + 1;
4646 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4650LogicalResult DepthwiseConv2DOp::verify() {
4656LogicalResult TransposeConv2DOp::inferReturnTypeComponents(
4657 MLIRContext *context, ::std::optional<Location> location,
4658 TransposeConv2DOp::Adaptor adaptor,
4659 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4660 llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamic);
4662 int64_t inputWidth = ShapedType::kDynamic;
4663 int64_t inputHeight = ShapedType::kDynamic;
4664 int64_t weightWidth = ShapedType::kDynamic;
4665 int64_t weightHeight = ShapedType::kDynamic;
4668 ShapeAdaptor inputShape(adaptor.getInput().getType());
4669 if (inputShape.hasRank()) {
4670 outputShape[0] = ShapedType::isDynamic(outputShape[0])
4671 ? inputShape.getDimSize(0)
4673 inputHeight = inputShape.getDimSize(1);
4674 inputWidth = inputShape.getDimSize(2);
4678 ShapeAdaptor weightShape(adaptor.getWeight().getType());
4679 if (weightShape.hasRank()) {
4680 outputShape[3] = ShapedType::isDynamic(outputShape[3])
4681 ? weightShape.getDimSize(0)
4683 weightHeight = weightShape.getDimSize(1);
4684 weightWidth = weightShape.getDimSize(2);
4688 ShapeAdaptor biasShape(adaptor.getBias().getType());
4689 if (biasShape.hasRank() && ShapedType::isDynamic(outputShape[3])) {
4690 int64_t bc = biasShape.getDimSize(0);
4691 if (bc != ShapedType::kDynamic && bc != 1)
4692 outputShape[3] = bc;
4695 llvm::ArrayRef<int64_t> padding = adaptor.getOutPad();
4696 llvm::ArrayRef<int64_t> stride = adaptor.getStride();
4698 if (ShapedType::isStatic(inputHeight) && ShapedType::isStatic(weightHeight)) {
4699 int64_t calculateSize =
4700 (inputHeight - 1) * stride[0] + padding[0] + padding[1] + weightHeight;
4702 ShapedType::isDynamic(outputShape[1]) ? calculateSize : outputShape[1];
4705 if (ShapedType::isStatic(inputWidth) && ShapedType::isStatic(weightWidth)) {
4706 int64_t calculateSize =
4707 (inputWidth - 1) * stride[1] + padding[2] + padding[3] + weightWidth;
4709 ShapedType::isDynamic(outputShape[2]) ? calculateSize : outputShape[2];
4712 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4716LogicalResult TransposeConv2DOp::verify() {
4720 const llvm::ArrayRef<int64_t> strides = getStride();
4721 const int64_t strideY = strides[0];
4722 const int64_t strideX = strides[1];
4724 if (strideY < 1 || strideX < 1)
4725 return emitOpError(
"expect all stride values to be >= 1, got [")
4728 const auto checkPadAgainstKernelDim =
4729 [
this](int64_t padValue, int64_t kernelDimSize, llvm::StringRef padName,
4730 llvm::StringRef kernelDimName) -> LogicalResult {
4731 if (padValue <= -kernelDimSize)
4732 return emitOpError(
"expected ")
4733 << padName <<
" > -" << kernelDimName <<
", but got: " << padName
4734 <<
"=" << padValue <<
" and " << kernelDimName <<
"="
4739 const llvm::ArrayRef<int64_t> padding = getOutPad();
4740 const int64_t outPadTop = padding[0];
4741 const int64_t outPadBottom = padding[1];
4742 const int64_t outPadLeft = padding[2];
4743 const int64_t outPadRight = padding[3];
4745 const auto weightType =
4746 llvm::dyn_cast<RankedTensorType>(getWeight().
getType());
4749 const int64_t kernelHeight = weightType.getDimSize(1);
4750 if (ShapedType::isStatic(kernelHeight)) {
4751 if (
failed(checkPadAgainstKernelDim(outPadTop, kernelHeight,
4752 "out_pad_top",
"KH")))
4755 if (
failed(checkPadAgainstKernelDim(outPadBottom, kernelHeight,
4756 "out_pad_bottom",
"KH")))
4760 const int64_t kernelWidth = weightType.getDimSize(2);
4761 if (ShapedType::isStatic(kernelWidth)) {
4762 if (
failed(checkPadAgainstKernelDim(outPadLeft, kernelWidth,
4763 "out_pad_left",
"KW")))
4766 if (
failed(checkPadAgainstKernelDim(outPadRight, kernelWidth,
4767 "out_pad_right",
"KW")))
4773 const auto outputType =
4774 llvm::dyn_cast<RankedTensorType>(getOutput().
getType());
4778 const auto inputType = llvm::dyn_cast<RankedTensorType>(getInput().
getType());
4779 if (inputType && weightType) {
4780 const int64_t inputHeight = inputType.getDimSize(1);
4781 const int64_t kernelHeight = weightType.getDimSize(1);
4782 const int64_t outputHeight = outputType.getDimSize(1);
4784 if (ShapedType::isStatic(inputHeight) &&
4785 ShapedType::isStatic(outputHeight)) {
4787 (inputHeight - 1) * strideY + outPadTop + outPadBottom + kernelHeight)
4789 "dimension mismatch: expected OH == (IH - 1) * stride_y "
4790 "+ out_pad_top + out_pad_bottom + KH, but got ")
4791 << outputHeight <<
" != (" << inputHeight <<
" - 1) * "
4792 << strideY <<
" + " << outPadTop <<
" + " << outPadBottom
4793 <<
" + " << kernelHeight;
4796 const int64_t inputWidth = inputType.getDimSize(2);
4797 const int64_t kernelWidth = weightType.getDimSize(2);
4798 const int64_t outputWidth = outputType.getDimSize(2);
4800 if (ShapedType::isStatic(inputWidth) && ShapedType::isStatic(outputWidth)) {
4802 (inputWidth - 1) * strideX + outPadLeft + outPadRight + kernelWidth)
4804 "dimension mismatch: expected OW == (IW - 1) * stride_x "
4805 "+ out_pad_left + out_pad_right + KW, but got ")
4806 << outputWidth <<
" != (" << inputWidth <<
" - 1) * " << strideX
4807 <<
" + " << outPadLeft <<
" + " << outPadRight <<
" + "
4812 const auto biasType = llvm::dyn_cast<RankedTensorType>(getBias().
getType());
4817 const int64_t biasChannels = biasType.getDimSize(0);
4820 if (biasChannels == ShapedType::kDynamic)
4823 const int64_t outputChannels = outputType.getDimSize(3);
4824 if (!ShapedType::isDynamic(outputChannels) &&
4825 biasChannels != outputChannels && biasChannels != 1)
4827 "bias channels expected to be equal to output channels (")
4828 << outputChannels <<
") or 1, got " << biasChannels;
4833LogicalResult RescaleOp::verify() {
4834 const auto inputType = llvm::cast<ShapedType>(getInput().
getType());
4835 auto inputElementType =
4837 if (!mlir::isa<IntegerType>(inputElementType)) {
4838 emitOpError(
"expect input to have integer element type, got ")
4839 << inputElementType;
4843 const auto outputType = llvm::cast<ShapedType>(getOutput().
getType());
4844 auto outputElementType =
4846 if (!mlir::isa<IntegerType>(outputElementType)) {
4847 emitOpError(
"expect output to have integer element type, got ")
4848 << outputElementType;
4860 const auto multiplierType = llvm::cast<ShapedType>(getMultiplier().
getType());
4862 if (getScale32() && !multiplierType.getElementType().isInteger(32)) {
4863 emitOpError(
"expect i32 element type for multiplier for scale32=true, got ")
4864 << multiplierType.getElementType();
4869 if (!getScale32() && !multiplierType.getElementType().isInteger(16)) {
4871 "expect i16 element type for multiplier for scale32=false, got ")
4872 << multiplierType.getElementType();
4876 if (!inputType.hasRank())
4882 int64_t numChannels = 1;
4883 if (getPerChannel()) {
4884 if (inputType.getRank() < 1) {
4885 emitOpError(
"requires input to be at least rank 1 when per_channel is "
4886 "true, but got rank ")
4887 << inputType.getRank();
4890 numChannels = inputType.getDimSize(inputType.getRank() - 1);
4893 if (outputType.hasRank()) {
4895 getOperation(), outputType, inputType.getShape())))
4899 if (multiplierType.hasRank()) {
4900 ArrayRef<int64_t> multiplierShape = multiplierType.getShape();
4902 if (multiplierShape[0] != ShapedType::kDynamic &&
4903 multiplierShape[0] != numChannels) {
4904 emitOpError(
"expect shape of { ")
4905 << numChannels <<
" } for multiplier input, got { "
4906 << multiplierShape[0] <<
" }";
4911 const auto shiftType = llvm::cast<ShapedType>(getShift().
getType());
4912 if (shiftType.hasRank()) {
4913 ArrayRef<int64_t> shiftShape = shiftType.getShape();
4915 if (shiftShape[0] != ShapedType::kDynamic && shiftShape[0] != numChannels) {
4916 emitOpError(
"expect shape of { ")
4917 << numChannels <<
" } for shift input, got { " << shiftShape[0]
4926LogicalResult RescaleOp::inferReturnTypeComponents(
4927 MLIRContext *context, ::std::optional<Location> location,
4928 RescaleOp::Adaptor adaptor,
4929 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4930 ShapeAdaptor inputShape(adaptor.getInput().getType());
4931 inferredReturnShapes.push_back(ShapedTypeComponents(inputShape));
4935LogicalResult CastOp::verify() {
4936 const ShapedType inputType = llvm::cast<ShapedType>(getInput().
getType());
4937 const ShapedType outputType = llvm::cast<ShapedType>(
getType());
4938 const Type inputElementType = inputType.getElementType();
4939 const Type outputElementType = outputType.getElementType();
4941 const bool inputIsBlockScaled = llvm::isa<BlockScaledType>(inputElementType);
4942 const bool outputIsBlockScaled =
4943 llvm::isa<BlockScaledType>(outputElementType);
4945 const bool isUnsigned = this->getInputUnsigned();
4950 return emitOpError()
4951 <<
"attribute input_unsigned requires integer type inputs. Got: "
4954 if (!inputIsBlockScaled && !outputIsBlockScaled)
4957 if (inputIsBlockScaled && outputIsBlockScaled)
4958 return emitOpError()
4959 <<
"requires exactly one of input or output to have block scaled "
4962 const Type scalarElementType =
4963 inputIsBlockScaled ? outputElementType : inputElementType;
4964 if (!llvm::isa<FloatType>(scalarElementType))
4965 return emitOpError()
4966 <<
"requires non-block-scaled element type to be floating-point "
4967 "when casting to or from block scaled element type, got "
4968 << scalarElementType;
4973LogicalResult CastFromBlockScaledOp::inferReturnTypeComponents(
4974 MLIRContext *context, ::std::optional<Location> location,
4975 CastFromBlockScaledOp::Adaptor adaptor,
4976 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4977 const ShapeAdaptor inputShape(adaptor.getInputData().getType());
4978 inferredReturnShapes.push_back(ShapedTypeComponents(inputShape));
4982LogicalResult CastFromBlockScaledOp::verify() {
4983 const Type inputDataType = getInputData().getType();
4984 const Type outputDataType = getResult().getType();
4986 return emitOpError() <<
"require compatible shapes for input_data ("
4987 << inputDataType <<
") and " <<
"output_data ("
4988 << outputDataType <<
")";
4990 const ShapeAdaptor inputDataShape = ShapeAdaptor(inputDataType);
4992 if (inputDataShape.
hasRank()) {
4993 const unsigned int blockSize =
4995 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_32))
4996 return emitOpError(
"expect block size to be 32, got ") << blockSize;
4997 const int64_t inputDataLastDim =
4999 if (inputDataLastDim % blockSize != 0)
5000 return emitOpError() <<
"expect last dimension of input_data ("
5002 <<
") to be divisible by block_size (" << blockSize
5005 const Type inputScaleType = getInputScale().getType();
5006 const ShapeAdaptor inputScaleShape = ShapeAdaptor(inputScaleType);
5008 if (inputScaleShape.
hasRank()) {
5009 SmallVector<int64_t> inputDataDims, inputScaleDims;
5010 inputDataShape.
getDims(inputDataDims);
5011 inputScaleShape.
getDims(inputScaleDims);
5013 if (inputDataDims.size() != inputScaleDims.size() ||
5015 ArrayRef<int64_t>(inputDataDims).drop_back(1),
5016 ArrayRef<int64_t>(inputScaleDims).drop_back(1))))
5017 return emitOpError()
5018 <<
"require compatible shapes for input_data (" << inputDataType
5019 <<
") and " <<
"input_scale (" << inputScaleType
5020 <<
") except for the last dimension";
5022 const SmallVector<int64_t, 2> dimsToCheck{inputDataLastDim / blockSize,
5023 inputScaleDims.back()};
5024 if (ShapedType::isStatic(inputDataLastDim) &&
5026 return emitOpError()
5027 <<
"expect last dimension of input_scale ("
5028 << inputScaleDims.back()
5029 <<
") to be equal to last dimension of input_data / block_size ("
5030 << inputDataDims.back() / blockSize <<
")";
5037LogicalResult CastToBlockScaledOp::inferReturnTypeComponents(
5038 MLIRContext *context, ::std::optional<Location> location,
5039 CastToBlockScaledOp::Adaptor adaptor,
5040 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
5041 const ShapeAdaptor inputShape(adaptor.getInputData().getType());
5042 inferredReturnShapes.push_back(ShapedTypeComponents(inputShape));
5043 if (!inputShape.hasRank())
5047 SmallVector<int64_t> outputScaleShape;
5048 inputShape.getDims(outputScaleShape);
5049 const int64_t lastDimLoc = inputShape.getRank() - 1;
5050 const int64_t lastDimSize = inputShape.getDimSize(lastDimLoc);
5051 if (ShapedType::isStatic(lastDimSize)) {
5052 const unsigned int blockSize =
5053 BlockSizeAttr::getBlockSizeValue(adaptor.getBlockSize());
5054 outputScaleShape[lastDimLoc] = lastDimSize / blockSize;
5056 inferredReturnShapes.push_back(ShapedTypeComponents(outputScaleShape));
5060LogicalResult CastToBlockScaledOp::verify() {
5061 const Type inputDataType = getInputData().getType();
5062 const Type outputDataType = getResult(0).getType();
5064 return emitOpError() <<
"require compatible shapes for input_data ("
5065 << inputDataType <<
") and " <<
"output_data ("
5066 << outputDataType <<
")";
5068 const unsigned int blockSize =
5070 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_32))
5071 return emitOpError(
"expect block size to be 32, got ") << blockSize;
5072 const ShapeAdaptor inputDataShape = ShapeAdaptor(inputDataType);
5073 if (inputDataShape.
hasRank()) {
5074 const int64_t inputDataLastDim =
5076 if (ShapedType::isStatic(inputDataLastDim) &&
5077 inputDataLastDim % blockSize != 0)
5078 return emitOpError() <<
"expect last dimension of input_data ("
5080 <<
") to be divisible by block_size (" << blockSize
5084 const ShapeAdaptor outputDataShape = ShapeAdaptor(outputDataType);
5085 const Type outputScaleType = getResult(1).getType();
5086 const ShapeAdaptor outputScaleShape = ShapeAdaptor(outputScaleType);
5088 SmallVector<int64_t> outputDataDims, outputScaleDims;
5089 outputDataShape.
getDims(outputDataDims);
5090 outputScaleShape.
getDims(outputScaleDims);
5092 if (outputDataDims.size() != outputScaleDims.size() ||
5094 ArrayRef<int64_t>(outputDataDims).drop_back(1),
5095 ArrayRef<int64_t>(outputScaleDims).drop_back(1))))
5096 return emitOpError() <<
"require compatible shapes for output_data ("
5097 << outputDataType <<
") and " <<
"output_scale ("
5099 <<
") except for the last dimension";
5101 const int64_t outputDataLastDim = outputDataDims.back();
5102 const SmallVector<int64_t, 2> dimsToCheck{outputDataLastDim / blockSize,
5103 outputScaleDims.back()};
5104 if (ShapedType::isStatic(outputDataLastDim) &&
5106 return emitOpError()
5107 <<
"expect last dimension of output_scale ("
5108 << outputScaleDims.back()
5109 <<
") to be equal to last dimension of output_data / block_size ("
5110 << outputDataDims.back() / blockSize <<
")";
5116LogicalResult IfOp::inferReturnTypeComponents(
5117 MLIRContext *context, ::std::optional<Location> location,
5118 IfOp::Adaptor adaptor,
5119 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
5120 llvm::SmallVector<tosa::YieldOp> yieldOps;
5121 for (Region *region : adaptor.getRegions()) {
5122 for (
auto &block : *region)
5123 if (
auto returnOp = dyn_cast<tosa::YieldOp>(block.getTerminator()))
5124 yieldOps.push_back(returnOp);
5127 if (yieldOps.empty())
5131 llvm::SmallVector<ValueKnowledge> resultKnowledge;
5132 resultKnowledge.reserve(yieldOps.front().getNumOperands());
5133 for (
auto operand : yieldOps.front().getOperands()) {
5134 resultKnowledge.push_back(
5138 for (
auto yieldOp : yieldOps) {
5139 if (resultKnowledge.size() != yieldOp.getNumOperands())
5142 for (
const auto &it : llvm::enumerate(yieldOp.getOperands())) {
5143 int32_t index = it.index();
5145 resultKnowledge[index],
5149 resultKnowledge[index] = meet;
5153 for (
const ValueKnowledge &
result : resultKnowledge) {
5154 inferredReturnShapes.push_back(
result.getShapedTypeComponents());
5160LogicalResult WhileOp::inferReturnTypeComponents(
5161 MLIRContext *context, ::std::optional<Location> location,
5162 WhileOp::Adaptor adaptor,
5163 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
5164 llvm::SmallVector<tosa::YieldOp> yieldOps;
5165 for (
auto &block : adaptor.getBodyGraph())
5166 if (
auto returnOp = dyn_cast<tosa::YieldOp>(block.getTerminator()))
5167 yieldOps.push_back(returnOp);
5171 if (yieldOps.empty())
5175 llvm::SmallVector<ValueKnowledge> resultKnowledge;
5176 resultKnowledge.reserve(yieldOps.front().getNumOperands());
5177 for (
auto operand : yieldOps.front().getOperands()) {
5178 resultKnowledge.push_back(
5182 for (
auto yieldOp : yieldOps) {
5183 if (resultKnowledge.size() != yieldOp.getNumOperands())
5186 for (
const auto &it : llvm::enumerate(yieldOp.getOperands())) {
5187 int32_t index = it.index();
5189 resultKnowledge[index],
5191 resultKnowledge[index] = meet;
5196 for (
const ValueKnowledge &
result : resultKnowledge) {
5197 inferredReturnShapes.push_back(
result.getShapedTypeComponents());
5206 StringRef prefix =
"") {
5207 assert(blocksArgs.size() == initializers.size() &&
5208 "expected same length of arguments and initializers");
5209 if (initializers.empty())
5212 parser << prefix <<
'(';
5213 llvm::interleaveComma(
5214 llvm::zip(blocksArgs, initializers), parser,
5215 [&](
auto it) { parser << std::get<0>(it) <<
" = " << std::get<1>(it); });
5220ParseResult IfOp::parse(OpAsmParser &parser, OperationState &
result) {
5222 result.regions.reserve(2);
5223 Region *thenRegion =
result.addRegion();
5224 Region *elseRegion =
result.addRegion();
5226 OpAsmParser::UnresolvedOperand cond;
5231 SmallVector<OpAsmParser::Argument, 4> regionArgs;
5232 SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
5235 OptionalParseResult listResult =
5243 "expected type for condition operand");
5249 "expected type for condition operand");
5257 FunctionType functionType;
5261 <<
"expected list of types for block arguments "
5262 <<
"followed by arrow type and list of return types";
5264 result.addTypes(functionType.getResults());
5266 if (functionType.getNumInputs() != operands.size()) {
5268 <<
"expected as many input types as operands " <<
"(expected "
5269 << operands.size() <<
" got " << functionType.getNumInputs()
5300void IfOp::print(OpAsmPrinter &p) {
5301 p <<
" " << getCondition();
5304 getInputList(),
" ");
5306 p << getCondition().getType();
5308 if (!getInputList().empty()) {
5310 llvm::interleaveComma(getInputList().getTypes(), p);
5319 auto &elseRegion = getElseGraph();
5320 if (!elseRegion.
empty()) {
5328LogicalResult IfOp::verify() {
5330 "'then_graph' arguments", getInputList(),
5336 "'else_graph' arguments", getInputList(),
5342 if (getThenGraph().front().mightHaveTerminator()) {
5344 dyn_cast<tosa::YieldOp>(getThenGraph().front().getTerminator());
5346 *
this, thenYield.getInputs(),
"'then_graph' results",
5347 getOutputList(),
"'output_list'")
5353 if (getElseGraph().front().mightHaveTerminator()) {
5355 dyn_cast<tosa::YieldOp>(getElseGraph().front().getTerminator());
5357 *
this, elseYield.getInputs(),
"'else_graph' results",
5358 getOutputList(),
"'output_list'")
5363 auto condType = getCondition().getType();
5365 return emitOpError() <<
"'condition' must be a size 1 tensor, got "
5371LogicalResult WhileOp::verify() {
5373 getOutputList(),
"'output_list'")
5378 "'cond_graph' arguments", getInputList(),
5384 "'body_graph' arguments", getInputList(),
5389 if (getBodyGraph().front().mightHaveTerminator()) {
5391 dyn_cast<tosa::YieldOp>(getBodyGraph().front().getTerminator());
5393 "'body_graph' results",
5394 getInputList(),
"'input_list'")
5401 if (!getCondGraph().front().mightHaveTerminator())
5405 dyn_cast<tosa::YieldOp>(getCondGraph().front().getTerminator());
5409 if (condYield.getInputs().size() != 1)
5410 return emitOpError() <<
"require 'cond_graph' only have one result";
5412 auto condOutType = condYield.getInputs()[0].getType();
5414 return emitOpError() <<
"'cond_graph' result must be a size 1 tensor, got "
5418 return emitOpError() <<
"'cond_graph' result must be a boolean tensor, got "
5424LogicalResult ReverseOp::verify() {
5425 TensorType inputType = getInput1().getType();
5426 int32_t reverseAxis = getAxis();
5428 if (reverseAxis < 0)
5429 return emitOpError(
"expected non-negative reverse axis");
5431 int64_t inputRank = inputType.getRank();
5434 if (reverseAxis >= inputRank && (reverseAxis != 0 || inputRank != 0))
5435 return emitOpError(
"expect input tensor rank (")
5436 << inputRank <<
") to be larger than reverse axis (" << reverseAxis
5443LogicalResult tosa::SelectOp::verify() {
5454 auto predicateType = llvm::dyn_cast<ShapedType>(getPred().
getType());
5455 if (!predicateType) {
5456 return emitOpError(
"expect shaped tensor for input1, got ")
5457 << getInput1().getType();
5459 auto predicateElementType = predicateType.getElementType();
5460 if (!predicateElementType.isInteger(1)) {
5461 return emitOpError(
"expect element type of bool for input1, got ")
5462 << predicateElementType;
5468LogicalResult tosa::VariableReadOp::verify() {
5476LogicalResult tosa::VariableWriteOp::verify() {
5485ParseResult WhileOp::parse(OpAsmParser &parser, OperationState &
result) {
5486 SmallVector<OpAsmParser::Argument, 4> regionArgs;
5487 SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
5488 Region *cond =
result.addRegion();
5489 Region *body =
result.addRegion();
5491 OptionalParseResult listResult =
5496 FunctionType functionType;
5501 result.addTypes(functionType.getResults());
5503 if (functionType.getNumInputs() != operands.size()) {
5505 <<
"expected as many input types as operands " <<
"(expected "
5506 << operands.size() <<
" got " << functionType.getNumInputs() <<
")";
5516 for (
size_t i = 0, e = regionArgs.size(); i != e; ++i)
5517 regionArgs[i].type = functionType.getInput(i);
5519 return failure(parser.
parseRegion(*cond, regionArgs) ||
5524void WhileOp::print(OpAsmPrinter &parser) {
5526 getInputList(),
" ");
5529 getResults().getTypes());
5535 (*this)->getDiscardableAttrDictionary().getValue());
5544 auto zpType = mlir::RankedTensorType::get({1}, srcElemType);
5545 if (llvm::isa<FloatType>(srcElemType)) {
5547 zpType, builder.
getFloatAttr(srcElemType,
static_cast<double>(zp)));
5548 return tosa::ConstOp::create(builder, loc, zpType, zpAttr);
5550 if (llvm::isa<IntegerType>(srcElemType)) {
5553 return tosa::ConstOp::create(builder, loc, zpType, zpAttr);
5555 llvm::errs() <<
"zero point is not allowed for unsupported data types\n";
5556 return std::nullopt;
5564 return mlir::isa<tosa::shapeType>(t);
5571 return emitError() <<
"invalid rank (must be >= 0): " << rank;
5577 if (mlir::isa<::mlir::tosa::shapeType>(v.getType())) {
5578 Operation *definingOp = v.getDefiningOp();
5580 return op->
emitOpError(
"shape operand is not compile time resolvable");
5593 auto getRank = [](
const Type type) {
5594 return mlir::cast<mlir::tosa::shapeType>(type).getRank();
5600 for (
auto type : operandTypes) {
5601 if (getRank(type) != rank) {
5602 return op->
emitOpError(
"operands don't have matching ranks");
5605 for (
auto type : resultTypes) {
5606 if (getRank(type) != rank) {
5607 return op->
emitOpError(
"result shape has different rank than operands");
5617LogicalResult tosa::ConstShapeOp::verify() {
5619 auto valuesRank = getValues().getType().getRank();
5620 if (valuesRank != 1)
5621 return emitOpError(
"expect elements in attribute values with rank 1");
5623 auto count = getValues().getNumElements();
5624 auto rank = (cast<tosa::shapeType>(getResult().
getType())).getRank();
5625 if (count != rank && (count != 1 || rank != 0)) {
5626 return emitOpError(
"expect number of elements in attribute values (")
5627 << count <<
") to be equal to the rank (" << rank
5628 <<
") for the result shape type";
5633LogicalResult tosa::DimOp::verify() {
5634 const tosa::shapeType outShapeType =
5635 cast<tosa::shapeType>(getResult().
getType());
5636 if (outShapeType.getRank() != 1)
5637 return emitOpError(
"expect output shape type to contain one element, got ")
5642 const int64_t inputRank = inputType.getRank();
5643 const int64_t axis = getAxisAttr().getInt();
5644 if (axis < 0 || axis >= inputRank)
5645 return emitOpError(
"expect axis to be in the range [0, ")
5646 << inputRank <<
"), got " << axis;
5651LogicalResult tosa::ConcatShapeOp::verify() {
5652 const tosa::shapeType outShapeType =
5653 cast<tosa::shapeType>(getResult().
getType());
5654 const int64_t outputRank = outShapeType.getRank();
5657 if (inputList.size() == 0)
5658 return emitOpError(
"requires at least one input shape");
5660 if (llvm::any_of(inputList, [](Value v) {
5661 return cast<tosa::shapeType>(v.
getType()).getRank() == 0;
5663 return emitOpError(
"requires all inputs shapes have a rank greater than 0");
5665 const int64_t inputsRank =
5666 llvm::accumulate(inputList, 0, [](int64_t acc,
const Value &input) {
5667 const tosa::shapeType inShapeType =
5668 cast<tosa::shapeType>(input.
getType());
5669 return acc + inShapeType.getRank();
5671 if (outputRank != inputsRank)
5672 return emitOpError(
"requires output shape rank to be equal to the sum of "
5673 "the input shape ranks (")
5674 << inputsRank <<
"), got " << outputRank;
5679LogicalResult tosa::SliceShapeOp::verify() {
5680 std::optional<int32_t> start;
5681 DenseIntElementsAttr startAttr;
5683 start = startAttr.getValues<int32_t>()[0];
5684 if (start && start.value() < 0)
5685 return emitOpError(
"expected non-negative start index, got ")
5688 std::optional<int32_t> size;
5689 DenseIntElementsAttr sizeAttr;
5691 size = sizeAttr.getValues<int32_t>()[0];
5692 if (size && size.value() <= 0)
5693 return emitOpError(
"expected positive size, got ") << size.value();
5698 const tosa::shapeType outShapeType =
5699 cast<tosa::shapeType>(getResult().
getType());
5700 const int64_t outputRank = outShapeType.getRank();
5701 if (outputRank != size)
5703 "expected output type size to be equal to size attribute, got ")
5704 << outputRank <<
" vs " << size.value();
5709 const tosa::shapeType inShapeType =
5710 cast<tosa::shapeType>(getInput().
getType());
5711 const int64_t inputRank = inShapeType.getRank();
5712 const int64_t sliceSize = start.value() + size.value();
5713 if (sliceSize > inputRank)
5714 return emitOpError(
"expected start + size to be less than or equal to "
5715 "input shape rank (")
5716 << inputRank <<
"), got " << sliceSize;
5725#define GET_ATTRDEF_CLASSES
5726#include "mlir/Dialect/Tosa/IR/TosaAttributes.cpp.inc"
5731#define GET_TYPEDEF_CLASSES
5732#include "mlir/Dialect/Tosa/IR/TosaOpsTypesBase.cpp.inc"
5753 printer << keyword <<
'(';
5775#define GET_OP_CLASSES
5776#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.
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)
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.
constexpr int64_t kInferableDimSize
Represents a dimension in the shape of a tensor that can be inferred based on the other provided dime...
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)