25#include "llvm/ADT/STLExtras.h"
26#include "llvm/IR/IRBuilder.h"
27#include "llvm/IR/IntrinsicsNVPTX.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/raw_ostream.h"
44template <
typename AttrTy>
51 using EnumTy =
decltype(attr.getValue());
52 std::optional<EnumTy> value = NVVM::symbolizeEnum<EnumTy>(keyword);
54 return parser.
emitError(loc) <<
"unknown enum value '" << keyword <<
"'";
56 attr = AttrTy::get(parser.
getContext(), *value);
67std::optional<mlir::NVVM::MMATypes>
68MmaOp::inferOperandMMAType(
Type operandElType,
bool isAccumulator) {
70 VectorType::get(2, Float16Type::get(operandElType.
getContext()));
71 if (operandElType.
isF64())
72 return NVVM::MMATypes::f64;
73 if (operandElType.
isF16() || operandElType == half2Type)
74 return NVVM::MMATypes::f16;
75 if (operandElType.
isF32() && isAccumulator)
76 return NVVM::MMATypes::f32;
77 if (operandElType.
isF32() && !isAccumulator)
78 return NVVM::MMATypes::tf32;
79 if (llvm::isa<IntegerType>(operandElType)) {
81 return NVVM::MMATypes::s32;
85 if (
auto structType = llvm::dyn_cast<LLVM::LLVMStructType>(operandElType)) {
86 if (structType.getBody().empty())
88 return inferOperandMMAType(structType.getBody()[0], isAccumulator);
95 return (type == MMATypes::u4 || type == MMATypes::s4);
99 return (type == MMATypes::u8 || type == MMATypes::s8);
104 type == MMATypes::s32;
107MMATypes MmaOp::accumPtxType() {
108 std::optional<mlir::NVVM::MMATypes> val = inferOperandMMAType(
109 getODSOperands(2).getTypes().front(),
true);
110 assert(val.has_value() &&
"accumulator PTX type should always be inferrable");
114MMATypes MmaOp::resultPtxType() {
115 std::optional<mlir::NVVM::MMATypes> val =
116 inferOperandMMAType(getResult().
getType(),
true);
117 assert(val.has_value() &&
"result PTX type should always be inferrable");
121template <
typename AttrTy>
123 StringRef keyword, AttrTy value) {
124 printer << (isFirst ?
" " :
", ") << keyword <<
" = ";
129template <
typename AttrTy>
131 StringRef keyword, AttrTy value) {
132 printer << (isFirst ?
" " :
", ") << keyword <<
" = "
133 << NVVM::stringifyEnum(value.getValue());
139 printer << (isFirst ?
" " :
", ") << keyword;
143template <
typename AttrTy>
147 if (attributes.
get(name))
149 "duplicate property '" + name +
"'");
153 attributes.
append(name, value);
157template <
typename AttrTy>
161 if (attributes.
get(name))
163 "duplicate property '" + name +
"'");
167 attributes.
append(name, value);
172 return llvm::is_contained(
174 "shape",
"b1Op",
"intOverflowBehavior",
"layoutA",
"layoutB",
175 "multiplicandAPtxType",
"multiplicandBPtxType",
"orderedMetadata",
176 "kind",
"scaleVecSize",
"blockScaleFormat",
"operandSegmentSizes"},
188 if (!llvm::is_contained(allowedKeywords, keyword))
190 "unknown MMA property '" + keyword +
"'");
192 ParseResult parseResult =
success();
193 if (keyword ==
"shape")
196 else if (keyword ==
"b1_op")
199 else if (keyword ==
"int_overflow")
201 parser, attributes,
"intOverflowBehavior");
202 else if (keyword ==
"layout_a")
205 else if (keyword ==
"layout_b")
208 else if (keyword ==
"multiplicand_a_ptx_type")
210 parser, attributes,
"multiplicandAPtxType");
211 else if (keyword ==
"multiplicand_b_ptx_type")
213 parser, attributes,
"multiplicandBPtxType");
214 else if (keyword ==
"kind") {
215 if (llvm::is_contained(allowedKeywords,
"block_scale_format"))
217 parser, attributes,
"kind");
221 }
else if (keyword ==
"scale_vec_size")
223 parser, attributes,
"scaleVecSize");
224 else if (keyword ==
"block_scale_format")
226 parser, attributes,
"blockScaleFormat");
227 else if (keyword ==
"ordered_metadata") {
228 if (attributes.
get(
"orderedMetadata"))
230 "duplicate property 'orderedMetadata'");
234 "unknown MMA property '" + keyword +
"'");
236 if (failed(parseResult))
242 for (StringRef property : requiredProperties) {
243 if (!attributes.
get(property))
245 "missing required property '" + property +
"'");
255 "inherent property '" + attribute.getName().getValue() +
256 "' must be spelled directly in the operation syntax");
257 attributes.
append(attribute);
264 struct MMAOperandFragment {
265 StringRef operandName;
266 StringRef ptxTypeAttr;
267 SmallVector<Value, 4> regs;
268 explicit MMAOperandFragment(StringRef name, StringRef ptxTypeName)
269 : operandName(name), ptxTypeAttr(ptxTypeName) {}
272 std::array<MMAOperandFragment, 3> frags{
273 MMAOperandFragment(
"A", getMultiplicandAPtxTypeAttrName()),
274 MMAOperandFragment(
"B", getMultiplicandBPtxTypeAttrName()),
275 MMAOperandFragment(
"C",
"")};
277 mlir::NVVM::MmaOp::getOperandSegmentSizeAttr()};
279 for (
unsigned fragIdx = 0; fragIdx < frags.size(); fragIdx++) {
280 auto &frag = frags[fragIdx];
281 auto varOperandSpec = getODSOperandIndexAndLength(fragIdx);
282 for (
auto operandIdx = varOperandSpec.first;
283 operandIdx < varOperandSpec.first + varOperandSpec.second;
285 frag.regs.push_back(this->getOperand(operandIdx));
286 if (operandIdx == 0) {
287 regTypes.push_back(this->getOperand(operandIdx).
getType());
290 std::optional<MMATypes> inferredType = MmaOp::inferOperandMMAType(
291 regTypes.back(), fragIdx >= 2);
293 ignoreAttrNames.push_back(frag.ptxTypeAttr);
296 auto printMmaOperand = [&](
const MMAOperandFragment &frag) ->
void {
297 p <<
" " << frag.operandName;
303 for (
const auto &frag : frags) {
304 printMmaOperand(frag);
307 bool isFirstProperty =
true;
311 if (getIntOverflowBehaviorAttr())
313 getIntOverflowBehaviorAttr());
316 if (getMultiplicandAPtxTypeAttr() &&
317 !llvm::is_contained(ignoreAttrNames, getMultiplicandAPtxTypeAttrName()))
319 getMultiplicandAPtxTypeAttr());
320 if (getMultiplicandBPtxTypeAttr() &&
321 !llvm::is_contained(ignoreAttrNames, getMultiplicandBPtxTypeAttrName()))
323 getMultiplicandBPtxTypeAttr());
324 llvm::append_range(ignoreAttrNames,
326 getIntOverflowBehaviorAttrName(),
327 getLayoutAAttrName(),
328 getLayoutBAttrName(),
329 getMultiplicandAPtxTypeAttrName(),
330 getMultiplicandBPtxTypeAttrName()});
337 frags[1].regs[0].getType(),
338 frags[2].regs[0].getType()},
347 std::optional<MMAIntOverflow> intOverflow,
348 std::optional<std::array<MMATypes, 2>> multiplicandPtxTypes,
349 std::optional<std::array<MMALayout, 2>> multiplicandLayouts) {
351 assert(
shape.size() == 3 &&
"expected shape to have size 3 (m, n, k)");
356 result.addOperands(operandA);
357 result.addOperands(operandB);
358 result.addOperands(operandC);
360 if (multiplicandPtxTypes) {
361 result.addAttribute(
"multiplicandAPtxType",
362 MMATypesAttr::get(ctx, (*multiplicandPtxTypes)[0]));
363 result.addAttribute(
"multiplicandBPtxType",
364 MMATypesAttr::get(ctx, (*multiplicandPtxTypes)[1]));
366 if (
auto res = inferOperandMMAType(operandA[0].
getType(),
false))
367 result.addAttribute(
"multiplicandAPtxType", MMATypesAttr::get(ctx, *res));
368 if (
auto res = inferOperandMMAType(operandB[0].
getType(),
false))
369 result.addAttribute(
"multiplicandBPtxType", MMATypesAttr::get(ctx, *res));
372 if (multiplicandLayouts) {
373 result.addAttribute(
"layoutA",
374 MMALayoutAttr::get(ctx, (*multiplicandLayouts)[0]));
375 result.addAttribute(
"layoutB",
376 MMALayoutAttr::get(ctx, (*multiplicandLayouts)[1]));
378 result.addAttribute(
"layoutA", MMALayoutAttr::get(ctx, MMALayout::row));
379 result.addAttribute(
"layoutB", MMALayoutAttr::get(ctx, MMALayout::col));
382 if (intOverflow.has_value())
383 result.addAttribute(
"intOverflowBehavior",
384 MMAIntOverflowAttr::get(ctx, *intOverflow));
385 if (b1Op.has_value())
386 result.addAttribute(
"b1Op", MMAB1OpAttr::get(ctx, *b1Op));
388 result.addTypes(resultType);
390 MmaOp::getOperandSegmentSizeAttr(),
392 static_cast<int32_t>(operandB.size()),
393 static_cast<int32_t>(operandC.size())}));
402 struct MMAOperandFragment {
403 std::optional<MMATypes> elemtype;
404 SmallVector<OpAsmParser::UnresolvedOperand, 4> regs;
405 SmallVector<Type> regTypes;
409 std::array<MMAOperandFragment, 4> frags;
415 MMAOperandFragment &frag) -> LogicalResult {
434 {
"shape",
"b1_op",
"int_overflow",
"layout_a",
435 "layout_b",
"multiplicand_a_ptx_type",
436 "multiplicand_b_ptx_type"},
437 {
"shape",
"layoutA",
"layoutB"}))
449 if (operandTypes.size() != 3)
452 "expected one type for each operand segment but got " +
453 Twine(operandTypes.size()) +
" types");
454 for (
const auto &iter : llvm::enumerate(operandTypes)) {
455 auto &frag = frags[iter.index()];
456 frag.regTypes.resize(frag.regs.size(), iter.value());
460 frag.elemtype = inferOperandMMAType(frag.regTypes[0],
467 frags[3].elemtype = inferOperandMMAType(resultType,
true);
469 std::array<StringRef, 2> names{
"multiplicandAPtxType",
470 "multiplicandBPtxType"};
471 for (
unsigned idx = 0; idx < names.size(); idx++) {
472 const auto &frag = frags[idx];
473 std::optional<NamedAttribute> attr = namedAttributes.
getNamed(names[idx]);
474 if (!frag.elemtype.has_value() && !attr.has_value()) {
477 "attribute " + names[idx] +
478 " is not provided explicitly and cannot be inferred");
480 if (!attr.has_value())
482 names[idx], MMATypesAttr::get(parser.
getContext(), *frag.elemtype));
485 result.addTypes(resultType);
486 if (!namedAttributes.
empty())
487 result.addAttributes(namedAttributes);
488 result.addAttribute(MmaOp::getOperandSegmentSizeAttr(),
490 static_cast<int32_t>(frags[0].regs.size()),
491 static_cast<int32_t>(frags[1].regs.size()),
492 static_cast<int32_t>(frags[2].regs.size()),
497LogicalResult MmaOp::verify() {
499 auto f16Ty = Float16Type::get(context);
500 auto i32Ty = IntegerType::get(context, 32);
501 auto f16x2Ty = VectorType::get(2, f16Ty);
502 auto f32Ty = Float32Type::get(context);
503 auto f16x2x4StructTy = LLVM::LLVMStructType::getLiteral(
504 context, {f16x2Ty, f16x2Ty, f16x2Ty, f16x2Ty});
507 LLVM::LLVMStructType::getLiteral(context, {i32Ty, i32Ty, i32Ty, i32Ty});
510 auto f16x2x2StructTy =
511 LLVM::LLVMStructType::getLiteral(context, {f16x2Ty, f16x2Ty});
513 LLVM::LLVMStructType::getLiteral(context, {f32Ty, f32Ty, f32Ty, f32Ty});
515 LLVM::LLVMStructType::getLiteral(context, {i32Ty, i32Ty});
517 std::array<int64_t, 3> mmaShape{getShapeAttr().getM(), getShapeAttr().getN(),
518 getShapeAttr().getK()};
524 AllowedShapes allowedShapes;
525 AllowedTypes expectedA;
526 AllowedTypes expectedB;
527 AllowedTypes expectedC;
532 if (mmaShape[0] == 16) {
534 Type multiplicandFragType;
535 switch (*getMultiplicandAPtxType()) {
538 multiplicandFragType = i32Ty;
539 expectedResult.push_back(LLVM::LLVMStructType::getLiteral(
540 context, {f32Ty, f32Ty, f32Ty, f32Ty}));
544 multiplicandFragType = i32Ty;
545 expectedResult.push_back(LLVM::LLVMStructType::getLiteral(
546 context, {f32Ty, f32Ty, f32Ty, f32Ty}));
550 multiplicandFragType = f16x2Ty;
551 expectedResult.push_back(f16x2x2StructTy);
552 expectedResult.push_back(f32x4StructTy);
559 multiplicandFragType = i32Ty;
560 expectedResult.push_back(f16x2x2StructTy);
561 expectedResult.push_back(f32x4StructTy);
575 return emitError(
"invalid shape or multiplicand type: ")
576 << getMultiplicandAPtxType().value();
580 expectedResult.push_back(s32x4StructTy);
581 expectedC.emplace_back(4, i32Ty);
582 multiplicandFragType = i32Ty;
584 expectedC.emplace_back(2, f16x2Ty);
585 expectedC.emplace_back(4, f32Ty);
588 int64_t unitA = (mmaShape[0] / 8) * (mmaShape[2] / kFactor);
589 int64_t unitB = (mmaShape[1] / 8) * (mmaShape[2] / kFactor);
590 expectedA.emplace_back(unitA, multiplicandFragType);
591 expectedB.emplace_back(unitB, multiplicandFragType);
592 allowedShapes.push_back({16, 8, kFactor});
593 allowedShapes.push_back({16, 8, kFactor * 2});
595 if (resultPtxType() != accumPtxType())
596 return emitOpError(
"ctype does not match dtype");
600 if (mmaShape[0] == 8) {
601 if (*getMultiplicandAPtxType() == MMATypes::f16) {
602 expectedA.emplace_back(2, f16x2Ty);
603 expectedB.emplace_back(2, f16x2Ty);
604 expectedResult.push_back(f16x2x4StructTy);
605 expectedResult.push_back(f32x8StructTy);
606 expectedC.emplace_back(4, f16x2Ty);
607 expectedC.emplace_back(8, f32Ty);
608 allowedShapes.push_back({8, 8, 4});
610 if (*getMultiplicandAPtxType() == MMATypes::f64) {
611 Type f64Ty = Float64Type::get(context);
612 expectedA.emplace_back(1, f64Ty);
613 expectedB.emplace_back(1, f64Ty);
614 expectedC.emplace_back(2, f64Ty);
615 expectedResult.emplace_back(LLVM::LLVMStructType::getLiteral(
617 allowedShapes.push_back({8, 8, 4});
620 expectedA.push_back({i32Ty});
621 expectedB.push_back({i32Ty});
622 expectedC.push_back({i32Ty, i32Ty});
623 expectedResult.push_back(s32x2StructTy);
625 allowedShapes.push_back({8, 8, 32});
627 allowedShapes.push_back({8, 8, 16});
628 if (getMultiplicandAPtxType().value() == MMATypes::b1)
629 allowedShapes.push_back({8, 8, 128});
633 std::string errorMessage;
634 llvm::raw_string_ostream errorStream(errorMessage);
637 if (expectedA.empty() || expectedB.empty() || expectedC.empty() ||
638 !llvm::is_contained(allowedShapes, mmaShape)) {
639 errorStream <<
"unimplemented variant for MMA shape <";
640 llvm::interleaveComma(mmaShape, errorStream);
642 return emitOpError(errorMessage);
646 std::array<StringRef, 3> operandNames{
"A",
"B",
"C"};
647 for (
const auto &iter : llvm::enumerate(std::array<AllowedTypes, 3>{
648 std::move(expectedA), std::move(expectedB), std::move(expectedC)})) {
649 auto spec = this->getODSOperandIndexAndLength(iter.index());
651 operand_type_begin() + spec.first +
653 bool match = llvm::is_contained(iter.value(), operandTySeg);
656 errorStream <<
"Could not match types for the "
657 << operandNames[iter.index()]
658 <<
" operands; expected one of ";
659 for (
const auto &x : iter.value()) {
660 errorStream << x.size() <<
"x" << x[0] <<
" ";
662 errorStream <<
"but got ";
663 llvm::interleaveComma(operandTySeg, errorStream);
664 return emitOpError(errorMessage);
669 if (!llvm::any_of(expectedResult, [&](
Type expectedResultType) {
670 return expectedResultType == getResult().getType();
673 <<
"Could not match allowed types for the result; expected one of ";
674 llvm::interleaveComma(expectedResult, errorStream);
675 errorStream <<
" but got " << getResult().getType();
676 return emitOpError(errorMessage);
680 if (getMultiplicandAPtxType() == MMATypes::b1 && !getB1Op()) {
681 return emitOpError(
"op requires " + getB1OpAttrName().strref() +
689 if (!getIntOverflowBehavior())
690 return emitOpError(
"op requires " +
691 getIntOverflowBehaviorAttrName().strref() +
699 (mmaShape[0] == 8 && mmaShape[1] == 8 && mmaShape[2] == 4 &&
700 getMultiplicandAPtxType() == MMATypes::f16);
704 if (getLayoutA() != MMALayout::row || getLayoutB() != MMALayout::col) {
705 return emitOpError(
"requires layoutA = #nvvm.mma_layout<row> and "
706 "layoutB = #nvvm.mma_layout<col> for shape <")
707 << mmaShape[0] <<
", " << mmaShape[1] <<
", " << mmaShape[2]
708 <<
"> with element types " << *getMultiplicandAPtxType() <<
" and "
709 << *getMultiplicandBPtxType()
710 <<
". Only m8n8k4 with f16 supports other layouts.";
717MMATypes MmaSpOp::accumPtxType() {
718 std::optional<mlir::NVVM::MMATypes> val = MmaOp::inferOperandMMAType(
719 getODSOperands(2).getTypes().front(),
true);
720 assert(val.has_value() &&
"accumulator PTX type should always be inferrable");
724MMATypes MmaSpOp::resultPtxType() {
725 std::optional<mlir::NVVM::MMATypes> val =
726 MmaOp::inferOperandMMAType(getResult().
getType(),
true);
727 assert(val.has_value() &&
"result PTX type should always be inferrable");
733 llvm::IRBuilderBase &builder) {
734 auto thisOp = cast<NVVM::MmaSpOp>(op);
742 auto intId = MmaSpOp::getIntrinsicID(
743 thisOp.getShape().getM(), thisOp.getShape().getN(),
744 thisOp.getShape().getK(), thisOp.getIntOverflowBehavior(),
745 thisOp.getOrderedMetadata(), thisOp.getKind(),
746 *thisOp.getMultiplicandAPtxType(), *thisOp.getMultiplicandBPtxType(),
747 thisOp.accumPtxType(), thisOp.resultPtxType());
749 return {intId, args};
754 struct MMAOperandFragment {
755 StringRef operandName;
756 StringRef ptxTypeAttr;
757 SmallVector<Value, 4> regs;
758 explicit MMAOperandFragment(StringRef name, StringRef ptxTypeName)
759 : operandName(name), ptxTypeAttr(ptxTypeName) {}
762 std::array<MMAOperandFragment, 5> frags{
763 MMAOperandFragment(
"A", getMultiplicandAPtxTypeAttrName()),
764 MMAOperandFragment(
"B", getMultiplicandBPtxTypeAttrName()),
765 MMAOperandFragment(
"C",
""), MMAOperandFragment(
"sparseMetadata",
""),
766 MMAOperandFragment(
"selector",
"")};
768 mlir::NVVM::MmaSpOp::getOperandSegmentSizeAttr()};
771 for (
unsigned fragIdx = 0; fragIdx < 3; fragIdx++) {
772 auto &frag = frags[fragIdx];
773 auto varOperandSpec = getODSOperandIndexAndLength(fragIdx);
774 for (
auto operandIdx = varOperandSpec.first;
775 operandIdx < varOperandSpec.first + varOperandSpec.second;
777 frag.regs.push_back(this->getOperand(operandIdx));
778 if (operandIdx == varOperandSpec.first) {
779 regTypes.push_back(this->getOperand(operandIdx).
getType());
782 std::optional<MMATypes> inferredType = MmaOp::inferOperandMMAType(
783 regTypes.back(), fragIdx >= 2);
785 ignoreAttrNames.push_back(frag.ptxTypeAttr);
789 frags[3].regs.push_back(getSparseMetadata());
790 frags[4].regs.push_back(getSparsitySelector());
792 auto printMmaSpOperand = [&](
const MMAOperandFragment &frag) ->
void {
793 p <<
" " << frag.operandName;
799 for (
const auto &frag : frags)
800 printMmaSpOperand(frag);
802 bool isFirstProperty =
true;
804 if (getIntOverflowBehaviorAttr())
806 getIntOverflowBehaviorAttr());
807 if (getMultiplicandAPtxTypeAttr() &&
808 !llvm::is_contained(ignoreAttrNames, getMultiplicandAPtxTypeAttrName()))
810 getMultiplicandAPtxTypeAttr());
811 if (getMultiplicandBPtxTypeAttr() &&
812 !llvm::is_contained(ignoreAttrNames, getMultiplicandBPtxTypeAttrName()))
814 getMultiplicandBPtxTypeAttr());
815 if (getOrderedMetadata())
822 getMultiplicandAPtxTypeAttrName(),
823 getMultiplicandBPtxTypeAttrName(),
824 getOrderedMetadataAttrName(), getKindAttrName()});
829 for (
int i = 0; i < 3; ++i) {
834 p <<
") -> " << getResult().getType();
841 std::optional<MMAIntOverflow> intOverflow,
842 std::optional<std::array<MMATypes, 2>> multiplicandPtxTypes) {
844 assert(
shape.size() == 3 &&
"expected shape to have size 3 (m, n, k)");
849 result.addOperands(operandA);
850 result.addOperands(operandB);
851 result.addOperands(operandC);
852 result.addOperands(sparseMetadata);
853 result.addOperands(sparsitySelector);
855 if (multiplicandPtxTypes) {
856 result.addAttribute(
"multiplicandAPtxType",
857 MMATypesAttr::get(ctx, (*multiplicandPtxTypes)[0]));
858 result.addAttribute(
"multiplicandBPtxType",
859 MMATypesAttr::get(ctx, (*multiplicandPtxTypes)[1]));
861 if (
auto res = MmaOp::inferOperandMMAType(operandA[0].
getType(),
false))
862 result.addAttribute(
"multiplicandAPtxType", MMATypesAttr::get(ctx, *res));
863 if (
auto res = MmaOp::inferOperandMMAType(operandB[0].
getType(),
false))
864 result.addAttribute(
"multiplicandBPtxType", MMATypesAttr::get(ctx, *res));
867 if (intOverflow.has_value())
868 result.addAttribute(
"intOverflowBehavior",
869 MMAIntOverflowAttr::get(ctx, *intOverflow));
871 result.addTypes(resultType);
873 MmaSpOp::getOperandSegmentSizeAttr(),
875 static_cast<int32_t>(operandB.size()),
876 static_cast<int32_t>(operandC.size()), 1,
881 struct MMAOperandFragment {
882 std::optional<MMATypes> elemtype;
883 SmallVector<OpAsmParser::UnresolvedOperand, 4> regs;
884 SmallVector<Type> regTypes;
888 std::array<MMAOperandFragment, 6> frags;
893 auto parseMmaSpOperand = [&](StringRef operandName,
894 MMAOperandFragment &frag) -> LogicalResult {
905 if (parseMmaSpOperand(
"A", frags[0]).
failed())
907 if (parseMmaSpOperand(
"B", frags[1]).
failed())
909 if (parseMmaSpOperand(
"C", frags[2]).
failed())
911 if (parseMmaSpOperand(
"sparseMetadata", frags[3]).
failed())
913 if (parseMmaSpOperand(
"selector", frags[4]).
failed())
917 {
"shape",
"int_overflow",
"multiplicand_a_ptx_type",
918 "multiplicand_b_ptx_type",
"ordered_metadata",
933 if (operandTypes.size() != 3)
936 "expected one type for each operand segment but got " +
937 Twine(operandTypes.size()) +
" types");
938 for (
const auto &iter : llvm::enumerate(operandTypes)) {
939 auto &frag = frags[iter.index()];
940 frag.regTypes.resize(frag.regs.size(), iter.value());
945 MmaOp::inferOperandMMAType(frag.regTypes[0],
953 MmaOp::inferOperandMMAType(resultType,
true);
968 std::array<StringRef, 2> names{
"multiplicandAPtxType",
969 "multiplicandBPtxType"};
970 for (
unsigned idx = 0; idx < names.size(); idx++) {
971 const auto &frag = frags[idx];
972 std::optional<NamedAttribute> attr = namedAttributes.
getNamed(names[idx]);
973 if (!frag.elemtype.has_value() && !attr.has_value()) {
976 "attribute " + names[idx] +
977 " is not provided explicitly and cannot be inferred");
979 if (!attr.has_value())
981 names[idx], MMATypesAttr::get(parser.
getContext(), *frag.elemtype));
984 result.addTypes(resultType);
985 if (!namedAttributes.
empty())
986 result.addAttributes(namedAttributes);
987 result.addAttribute(MmaSpOp::getOperandSegmentSizeAttr(),
989 static_cast<int32_t>(frags[0].regs.size()),
990 static_cast<int32_t>(frags[1].regs.size()),
991 static_cast<int32_t>(frags[2].regs.size()),
998LogicalResult MmaSpOp::verify() {
1000 auto f16Ty = Float16Type::get(context);
1001 auto i32Ty = IntegerType::get(context, 32);
1002 auto f16x2Ty = VectorType::get(2, f16Ty);
1003 auto f32Ty = Float32Type::get(context);
1004 auto f16x2x4StructTy = LLVM::LLVMStructType::getLiteral(
1005 context, {f16x2Ty, f16x2Ty, f16x2Ty, f16x2Ty});
1007 auto s32x4StructTy =
1008 LLVM::LLVMStructType::getLiteral(context, {i32Ty, i32Ty, i32Ty, i32Ty});
1009 auto f32x8StructTy =
1011 auto f16x2x2StructTy =
1012 LLVM::LLVMStructType::getLiteral(context, {f16x2Ty, f16x2Ty});
1013 auto f32x4StructTy =
1014 LLVM::LLVMStructType::getLiteral(context, {f32Ty, f32Ty, f32Ty, f32Ty});
1015 auto s32x2StructTy =
1016 LLVM::LLVMStructType::getLiteral(context, {i32Ty, i32Ty});
1018 std::array<int64_t, 3> mmaShape{getShapeAttr().getM(), getShapeAttr().getN(),
1019 getShapeAttr().getK()};
1025 AllowedShapes allowedShapes;
1026 AllowedTypes expectedA;
1027 AllowedTypes expectedB;
1028 AllowedTypes expectedC;
1033 if (mmaShape[0] == 16) {
1035 Type multiplicandFragType;
1036 switch (*getMultiplicandAPtxType()) {
1037 case MMATypes::tf32:
1039 multiplicandFragType = i32Ty;
1040 expectedResult.push_back(LLVM::LLVMStructType::getLiteral(
1041 context, {f32Ty, f32Ty, f32Ty, f32Ty}));
1043 allowedShapes.push_back({16, 8, 8});
1044 allowedShapes.push_back({16, 8, 16});
1046 case MMATypes::bf16:
1048 multiplicandFragType = i32Ty;
1049 expectedResult.push_back(LLVM::LLVMStructType::getLiteral(
1050 context, {f32Ty, f32Ty, f32Ty, f32Ty}));
1052 allowedShapes.push_back({16, 8, 16});
1053 allowedShapes.push_back({16, 8, 32});
1057 multiplicandFragType = f16x2Ty;
1058 expectedResult.push_back(f16x2x2StructTy);
1059 expectedResult.push_back(f32x4StructTy);
1061 allowedShapes.push_back({16, 8, 16});
1062 allowedShapes.push_back({16, 8, 32});
1068 allowedShapes.push_back({16, 8, 64});
1069 allowedShapes.push_back({16, 8, 128});
1075 allowedShapes.push_back({16, 8, 32});
1076 allowedShapes.push_back({16, 8, 64});
1078 case MMATypes::e4m3:
1079 case MMATypes::e5m2:
1080 case MMATypes::e3m2:
1081 case MMATypes::e2m3:
1082 case MMATypes::e2m1:
1084 multiplicandFragType = i32Ty;
1085 expectedResult.push_back(f16x2x2StructTy);
1086 expectedResult.push_back(f32x4StructTy);
1088 allowedShapes.push_back({16, 8, 64});
1091 return emitError(
"invalid shape or multiplicand type: ")
1092 << getMultiplicandAPtxType().value();
1096 expectedResult.push_back(s32x4StructTy);
1097 expectedC.emplace_back(4, i32Ty);
1098 multiplicandFragType = i32Ty;
1099 }
else if (*getMultiplicandAPtxType() >= MMATypes::e4m3 &&
1100 *getMultiplicandAPtxType() <= MMATypes::e2m1) {
1102 expectedC.emplace_back(2, f16x2Ty);
1103 expectedC.emplace_back(4, f32Ty);
1105 expectedC.emplace_back(2, f16x2Ty);
1106 expectedC.emplace_back(4, f32Ty);
1111 int64_t unitA = (mmaShape[0] / 8) * (mmaShape[2] / kFactor) / 2;
1112 int64_t unitB = (mmaShape[1] / 8) * (mmaShape[2] / kFactor);
1113 expectedA.emplace_back(unitA, multiplicandFragType);
1114 expectedB.emplace_back(unitB, multiplicandFragType);
1116 if (resultPtxType() != accumPtxType())
1117 return emitOpError(
"ctype does not match dtype");
1121 if (mmaShape[0] == 8) {
1122 if (*getMultiplicandAPtxType() == MMATypes::f16) {
1123 expectedA.emplace_back(2, f16x2Ty);
1124 expectedB.emplace_back(2, f16x2Ty);
1125 expectedResult.push_back(f16x2x4StructTy);
1126 expectedResult.push_back(f32x8StructTy);
1127 expectedC.emplace_back(4, f16x2Ty);
1128 expectedC.emplace_back(8, f32Ty);
1129 allowedShapes.push_back({8, 8, 4});
1131 if (*getMultiplicandAPtxType() == MMATypes::f64) {
1132 Type f64Ty = Float64Type::get(context);
1133 expectedA.emplace_back(1, f64Ty);
1134 expectedB.emplace_back(1, f64Ty);
1135 expectedC.emplace_back(2, f64Ty);
1136 expectedResult.emplace_back(LLVM::LLVMStructType::getLiteral(
1138 allowedShapes.push_back({8, 8, 4});
1141 expectedA.push_back({i32Ty});
1142 expectedB.push_back({i32Ty});
1143 expectedC.push_back({i32Ty, i32Ty});
1144 expectedResult.push_back(s32x2StructTy);
1146 allowedShapes.push_back({8, 8, 32});
1148 allowedShapes.push_back({8, 8, 16});
1152 std::string errorMessage;
1153 llvm::raw_string_ostream errorStream(errorMessage);
1156 if (expectedA.empty() || expectedB.empty() || expectedC.empty() ||
1157 !llvm::is_contained(allowedShapes, mmaShape)) {
1158 errorStream <<
"unimplemented variant for MMA shape <";
1159 llvm::interleaveComma(mmaShape, errorStream);
1161 return emitOpError(errorMessage);
1165 std::array<StringRef, 3> operandNames{
"A",
"B",
"C"};
1166 for (
const auto &iter : llvm::enumerate(std::array<AllowedTypes, 3>{
1167 std::move(expectedA), std::move(expectedB), std::move(expectedC)})) {
1168 auto spec = this->getODSOperandIndexAndLength(iter.index());
1170 operand_type_begin() + spec.first +
1172 bool match = llvm::is_contained(iter.value(), operandTySeg);
1175 errorStream <<
"Could not match types for the "
1176 << operandNames[iter.index()]
1177 <<
" operands; expected one of ";
1178 for (
const auto &x : iter.value()) {
1179 errorStream << x.size() <<
"x" << x[0] <<
" ";
1181 errorStream <<
"but got ";
1182 llvm::interleaveComma(operandTySeg, errorStream);
1183 return emitOpError(errorMessage);
1188 if (!llvm::any_of(expectedResult, [&](
Type expectedResultType) {
1189 return expectedResultType == getResult().getType();
1192 <<
"Could not match allowed types for the result; expected one of ";
1193 llvm::interleaveComma(expectedResult, errorStream);
1194 errorStream <<
" but got " << getResult().getType();
1195 return emitOpError(errorMessage);
1202 if (!getIntOverflowBehavior())
1203 return emitOpError(
"op requires " +
1204 getIntOverflowBehaviorAttrName().strref() +
1209 if (!getSparseMetadata().
getType().isInteger(32)) {
1210 return emitOpError() <<
"sparse metadata must be i32 type";
1214 if (!getSparsitySelector().
getType().isInteger(32)) {
1215 return emitOpError() <<
"sparsity selector must be i32 type";
1227struct MMAOperandFragment {
1228 StringRef operandName;
1229 StringRef ptxTypeAttr;
1230 SmallVector<Value, 4> regs;
1231 explicit MMAOperandFragment(StringRef name, StringRef ptxTypeName)
1232 : operandName(name), ptxTypeAttr(ptxTypeName) {}
1239 p <<
" " << name <<
"[";
1258template <
typename Op>
1263 for (
unsigned fragIdx = 0; fragIdx < frags.size(); fragIdx++) {
1264 auto &frag = frags[fragIdx];
1265 auto varOperandSpec = op.getODSOperandIndexAndLength(fragIdx);
1266 for (
auto operandIdx = varOperandSpec.first;
1267 operandIdx < varOperandSpec.first + varOperandSpec.second;
1269 frag.regs.push_back(op.getOperand(operandIdx));
1270 if (fragIdx == 0 && operandIdx == varOperandSpec.first) {
1271 regTypes.push_back(op.getOperand(operandIdx).getType());
1275 regTypes.push_back(frag.regs[0].getType());
1277 std::optional<MMATypes> inferredType =
1278 MmaOp::inferOperandMMAType(regTypes.back(),
1281 ignoreAttrNames.push_back(frag.ptxTypeAttr);
1292 auto typeParser = [&]() {
1296 operandTypes.push_back(ty);
1302 if (operandTypes.size() != 3)
1304 "expected exactly 3 types");
1313 if (!attrs.
get(
"multiplicandAPtxType")) {
1314 if (
auto inferredType =
1315 MmaOp::inferOperandMMAType(operandTypes[0],
false)) {
1316 attrs.
set(
"multiplicandAPtxType", MMATypesAttr::get(ctx, *inferredType));
1319 if (!attrs.
get(
"multiplicandBPtxType")) {
1320 if (
auto inferredType =
1321 MmaOp::inferOperandMMAType(operandTypes[1],
false)) {
1322 attrs.
set(
"multiplicandBPtxType", MMATypesAttr::get(ctx, *inferredType));
1328template <
typename OpType>
1331 ScaleVecSize scaleVecSize,
1332 BlockScaleFormat blockScaleFormat,
1333 MMABlockScaleKind kind) {
1335 auto &properties =
result.getOrAddProperties<
typename OpType::Properties>();
1336 properties.setShape(
1338 properties.setScaleVecSize(ScaleVecSizeAttr::get(ctx, scaleVecSize));
1339 properties.setBlockScaleFormat(
1340 BlockScaleFormatAttr::get(ctx, blockScaleFormat));
1341 properties.setKind(MMABlockScaleKindAttr::get(ctx, kind));
1348 std::optional<std::array<MMATypes, 2>> multiplicandPtxTypes) {
1349 if (multiplicandPtxTypes) {
1350 result.addAttribute(
"multiplicandAPtxType",
1351 MMATypesAttr::get(ctx, (*multiplicandPtxTypes)[0]));
1352 result.addAttribute(
"multiplicandBPtxType",
1353 MMATypesAttr::get(ctx, (*multiplicandPtxTypes)[1]));
1355 if (
auto res = MmaOp::inferOperandMMAType(operandA[0].
getType(),
false))
1356 result.addAttribute(
"multiplicandAPtxType", MMATypesAttr::get(ctx, *res));
1357 if (
auto res = MmaOp::inferOperandMMAType(operandB[0].
getType(),
false))
1358 result.addAttribute(
"multiplicandBPtxType", MMATypesAttr::get(ctx, *res));
1363template <
typename OpTy>
1365 return *MmaOp::inferOperandMMAType(
1366 cast<LLVM::LLVMStructType>(op.getRes().getType()).getBody()[0],
1376 std::array<MMAOperandFragment, 3> frags{
1377 MMAOperandFragment(
"A", getMultiplicandAPtxTypeAttrName()),
1378 MMAOperandFragment(
"B", getMultiplicandBPtxTypeAttrName()),
1379 MMAOperandFragment(
"C",
"")};
1381 mlir::NVVM::MmaBlockScaleOp::getOperandSegmentSizeAttr()};
1386 for (
const auto &frag : frags)
1391 {getScaleAData(), getByteIdA(), getThreadIdA()});
1393 {getScaleBData(), getByteIdB(), getThreadIdB()});
1395 bool isFirstProperty =
true;
1397 if (getMultiplicandAPtxTypeAttr() &&
1398 !llvm::is_contained(ignoreAttrNames, getMultiplicandAPtxTypeAttrName()))
1400 getMultiplicandAPtxTypeAttr());
1401 if (getMultiplicandBPtxTypeAttr() &&
1402 !llvm::is_contained(ignoreAttrNames, getMultiplicandBPtxTypeAttrName()))
1404 getMultiplicandBPtxTypeAttr());
1406 getScaleVecSizeAttr());
1408 getBlockScaleFormatAttr());
1413 getMultiplicandBPtxTypeAttrName(),
1414 getScaleVecSizeAttrName(),
1415 getBlockScaleFormatAttrName(), getKindAttrName()});
1422 frags[1].regs[0].getType(),
1423 frags[2].regs[0].getType()},
1429ParseResult MmaBlockScaleOp::parse(
OpAsmParser &parser,
1431 struct LocalOperandFragment {
1432 std::optional<MMATypes> elemtype;
1433 SmallVector<OpAsmParser::UnresolvedOperand, 4> regs;
1437 std::array<LocalOperandFragment, 3> frags;
1453 {
"shape",
"multiplicand_a_ptx_type",
1454 "multiplicand_b_ptx_type",
"scale_vec_size",
1455 "block_scale_format",
"kind"},
1456 {
"shape",
"scaleVecSize",
"blockScaleFormat",
"kind"}))
1470 for (
const auto &[idx, frag] : llvm::enumerate(frags)) {
1471 frag.elemtype = MmaOp::inferOperandMMAType(operandTypes[idx],
1474 .resolveOperands(frag.regs, operandTypes[idx], parser.
getNameLoc(),
1484 .resolveOperands(scaleAOperands, scaleTypes, parser.
getNameLoc(),
1494 result.addAttributes(namedAttributes);
1498 result.addTypes(resultTypes);
1499 result.addAttribute(MmaBlockScaleOp::getOperandSegmentSizeAttr(),
1501 static_cast<int32_t>(frags[0].regs.size()),
1502 static_cast<int32_t>(frags[1].regs.size()),
1503 static_cast<int32_t>(frags[2].regs.size()),
1514void MmaBlockScaleOp::build(
1519 std::optional<std::array<MMATypes, 2>> multiplicandPtxTypes,
1520 ScaleVecSize scaleVecSize, BlockScaleFormat blockScaleFormat,
1521 MMABlockScaleKind kind) {
1522 assert(
shape.size() == 3 &&
"expected shape to have size 3 (m, n, k)");
1525 blockScaleFormat, kind);
1527 result.addOperands(operandA);
1528 result.addOperands(operandB);
1529 result.addOperands(operandC);
1531 {scaleAData, byteIdA, threadIdA, scaleBData, byteIdB, threadIdB});
1534 multiplicandPtxTypes);
1536 result.addTypes(resultType);
1537 result.addAttribute(MmaBlockScaleOp::getOperandSegmentSizeAttr(),
1539 static_cast<int32_t>(operandA.size()),
1540 static_cast<int32_t>(operandB.size()),
1541 static_cast<int32_t>(operandC.size()),
1553 auto curOp = cast<NVVM::MmaBlockScaleOp>(op);
1557 for (
Value operand : curOp.getOperandA())
1559 for (
Value operand : curOp.getOperandB())
1561 for (
Value operand : curOp.getOperandC())
1565 args.push_back(mt.
lookupValue(curOp.getScaleAData()));
1566 args.push_back(mt.
lookupValue(curOp.getByteIdA()));
1567 args.push_back(mt.
lookupValue(curOp.getThreadIdA()));
1568 args.push_back(mt.
lookupValue(curOp.getScaleBData()));
1569 args.push_back(mt.
lookupValue(curOp.getByteIdB()));
1570 args.push_back(mt.
lookupValue(curOp.getThreadIdB()));
1572 unsigned intId = MmaBlockScaleOp::getIntrinsicID(
1573 curOp.getShape().getM(), curOp.getShape().getN(), curOp.getShape().getK(),
1574 *curOp.getMultiplicandAPtxType(), *curOp.getMultiplicandBPtxType(),
1576 curOp.getBlockScaleFormat(), curOp.getKind());
1578 return {intId, args};
1581LogicalResult MmaBlockScaleOp::verify() {
1587 if (m == 16 && n == 8 && k == 64) {
1588 if (getMultiplicandAPtxType() != NVVM::MMATypes::e2m1 ||
1589 getMultiplicandBPtxType() != NVVM::MMATypes::e2m1)
1591 "unsupported MMATypes attribute for mma.m16n8k64.(mxf4nvf4|mxf4)");
1592 if (getKind() == NVVM::MMABlockScaleKind::MXF4) {
1593 if (getScaleVecSize() != NVVM::ScaleVecSize::X2)
1595 "unsupported ScaleVecSize attribute for mma.m16n8k64.mxf4");
1596 if (getBlockScaleFormat() != NVVM::BlockScaleFormat::UE8M0)
1598 "unsupported BlockScaleFormat attribute for mma.m16n8k64.mxf4");
1599 }
else if (getKind() == NVVM::MMABlockScaleKind::MXF4NVF4) {
1600 if (!((getScaleVecSize() == NVVM::ScaleVecSize::X2 &&
1601 getBlockScaleFormat() == NVVM::BlockScaleFormat::UE8M0) ||
1602 (getScaleVecSize() == NVVM::ScaleVecSize::X4 &&
1603 (getBlockScaleFormat() == NVVM::BlockScaleFormat::UE4M3 ||
1604 getBlockScaleFormat() == NVVM::BlockScaleFormat::UE8M0))))
1605 result = emitOpError(
"unsupported ScaleVecSize and BlockScaleFormat "
1606 "attributes for mma.m16n8k64.mxf4nvf4");
1608 result = emitOpError(
"unsupported Kind attribute for mma.m16n8k64");
1610 }
else if (m == 16 && n == 8 && k == 32) {
1611 if (!(getKind() == NVVM::MMABlockScaleKind::MXF8F6F4 &&
1612 getScaleVecSize() == NVVM::ScaleVecSize::X1 &&
1613 getBlockScaleFormat() == NVVM::BlockScaleFormat::UE8M0))
1615 emitOpError(
"unsupported Kind, ScaleVecSize and BlockScaleFormat "
1616 "attributes for mma.m16n8k32");
1618 result = emitOpError(
"unsupported Geom for mma with block scaling");
1629 std::array<MMAOperandFragment, 3> frags{
1630 MMAOperandFragment(
"A", getMultiplicandAPtxTypeAttrName()),
1631 MMAOperandFragment(
"B", getMultiplicandBPtxTypeAttrName()),
1632 MMAOperandFragment(
"C",
"")};
1634 mlir::NVVM::MmaSpBlockScaleOp::getOperandSegmentSizeAttr()};
1639 for (
const auto &frag : frags)
1648 {getScaleAData(), getByteIdA(), getThreadIdA()});
1650 {getScaleBData(), getByteIdB(), getThreadIdB()});
1652 bool isFirstProperty =
true;
1654 if (getMultiplicandAPtxTypeAttr() &&
1655 !llvm::is_contained(ignoreAttrNames, getMultiplicandAPtxTypeAttrName()))
1657 getMultiplicandAPtxTypeAttr());
1658 if (getMultiplicandBPtxTypeAttr() &&
1659 !llvm::is_contained(ignoreAttrNames, getMultiplicandBPtxTypeAttrName()))
1661 getMultiplicandBPtxTypeAttr());
1664 getScaleVecSizeAttr());
1666 getBlockScaleFormatAttr());
1671 getMultiplicandBPtxTypeAttrName(),
1672 getOrderedMetadataAttrName(),
1673 getScaleVecSizeAttrName(),
1674 getBlockScaleFormatAttrName(), getKindAttrName()});
1681 frags[1].regs[0].getType(),
1682 frags[2].regs[0].getType()},
1688ParseResult MmaSpBlockScaleOp::parse(
OpAsmParser &parser,
1690 struct LocalOperandFragment {
1691 std::optional<MMATypes> elemtype;
1692 SmallVector<OpAsmParser::UnresolvedOperand, 4> regs;
1696 std::array<LocalOperandFragment, 3> frags;
1719 {
"shape",
"multiplicand_a_ptx_type",
1720 "multiplicand_b_ptx_type",
"ordered_metadata",
1721 "scale_vec_size",
"block_scale_format",
"kind"},
1722 {
"shape",
"scaleVecSize",
"blockScaleFormat",
"kind"}))
1736 for (
const auto &[idx, frag] : llvm::enumerate(frags)) {
1737 frag.elemtype = MmaOp::inferOperandMMAType(operandTypes[idx],
1740 .resolveOperands(frag.regs, operandTypes[idx], parser.
getNameLoc(),
1749 .resolveOperands(metadataOperands, i32Type, parser.
getNameLoc(),
1762 .resolveOperands(scaleAOperands, scaleTypes, parser.
getNameLoc(),
1772 result.addAttributes(namedAttributes);
1777 if (!
result.attributes.get(
"orderedMetadata"))
1780 result.addTypes(resultTypes);
1781 result.addAttribute(MmaSpBlockScaleOp::getOperandSegmentSizeAttr(),
1783 static_cast<int32_t>(frags[0].regs.size()),
1784 static_cast<int32_t>(frags[1].regs.size()),
1785 static_cast<int32_t>(frags[2].regs.size()),
1798void MmaSpBlockScaleOp::build(
1804 std::optional<std::array<MMATypes, 2>> multiplicandPtxTypes,
1805 ScaleVecSize scaleVecSize, BlockScaleFormat blockScaleFormat,
1806 MMABlockScaleKind kind) {
1807 assert(
shape.size() == 3 &&
"expected shape to have size 3 (m, n, k)");
1810 builder,
result,
shape, scaleVecSize, blockScaleFormat, kind);
1813 result.addOperands(operandA);
1814 result.addOperands(operandB);
1815 result.addOperands(operandC);
1816 result.addOperands({sparseMetadata, sparsitySelector, scaleAData, byteIdA,
1817 threadIdA, scaleBData, byteIdB, threadIdB});
1820 multiplicandPtxTypes);
1822 result.addTypes(resultType);
1823 result.addAttribute(MmaSpBlockScaleOp::getOperandSegmentSizeAttr(),
1825 static_cast<int32_t>(operandA.size()),
1826 static_cast<int32_t>(operandB.size()),
1827 static_cast<int32_t>(operandC.size()),
1841 auto curOp = cast<NVVM::MmaSpBlockScaleOp>(op);
1845 for (
Value operand : curOp.getOperandA())
1847 for (
Value operand : curOp.getOperandB())
1849 for (
Value operand : curOp.getOperandC())
1853 args.push_back(mt.
lookupValue(curOp.getSparseMetadata()));
1854 args.push_back(mt.
lookupValue(curOp.getSparsitySelector()));
1857 args.push_back(mt.
lookupValue(curOp.getScaleAData()));
1858 args.push_back(mt.
lookupValue(curOp.getByteIdA()));
1859 args.push_back(mt.
lookupValue(curOp.getThreadIdA()));
1860 args.push_back(mt.
lookupValue(curOp.getScaleBData()));
1861 args.push_back(mt.
lookupValue(curOp.getByteIdB()));
1862 args.push_back(mt.
lookupValue(curOp.getThreadIdB()));
1864 unsigned intId = MmaSpBlockScaleOp::getIntrinsicID(
1865 curOp.getShape().getM(), curOp.getShape().getN(), curOp.getShape().getK(),
1866 *curOp.getMultiplicandAPtxType(), *curOp.getMultiplicandBPtxType(),
1868 curOp.getBlockScaleFormat(), curOp.getKind());
1870 return {intId, args};
1873LogicalResult MmaSpBlockScaleOp::verify() {
1875 if (!getOrderedMetadata()) {
1876 return emitOpError(
"'orderedMetadata' attribute is mandatory");
1884 if (m == 16 && n == 8 && k == 128) {
1885 if (getMultiplicandAPtxType() != NVVM::MMATypes::e2m1 ||
1886 getMultiplicandBPtxType() != NVVM::MMATypes::e2m1)
1888 "unsupported MMATypes attribute for mma.m16n8k128.(mxf4nvf4|mxf4)");
1889 if (getKind() == NVVM::MMABlockScaleKind::MXF4) {
1890 if (getScaleVecSize() != NVVM::ScaleVecSize::X2)
1892 "unsupported ScaleVecSize attribute for mma.m16n8k128.mxf4");
1893 if (getBlockScaleFormat() != NVVM::BlockScaleFormat::UE8M0)
1895 "unsupported BlockScaleFormat attribute for mma.m16n8k128.mxf4");
1896 }
else if (getKind() == NVVM::MMABlockScaleKind::MXF4NVF4) {
1897 if (!((getScaleVecSize() == NVVM::ScaleVecSize::X2 &&
1898 getBlockScaleFormat() == NVVM::BlockScaleFormat::UE8M0) ||
1899 (getScaleVecSize() == NVVM::ScaleVecSize::X4 &&
1900 (getBlockScaleFormat() == NVVM::BlockScaleFormat::UE4M3 ||
1901 getBlockScaleFormat() == NVVM::BlockScaleFormat::UE8M0))))
1902 result = emitOpError(
"unsupported ScaleVecSize and BlockScaleFormat "
1903 "attributes for mma.m16n8k128.mxf4nvf4");
1905 result = emitOpError(
"unsupported Kind attribute for mma.m16n8k128");
1907 }
else if (m == 16 && n == 8 && k == 64) {
1908 if (!(getKind() == NVVM::MMABlockScaleKind::MXF8F6F4 &&
1909 getScaleVecSize() == NVVM::ScaleVecSize::X1 &&
1910 getBlockScaleFormat() == NVVM::BlockScaleFormat::UE8M0))
1912 emitOpError(
"unsupported Kind, ScaleVecSize and BlockScaleFormat "
1913 "attributes for mma.m16n8k64");
1915 result = emitOpError(
"unsupported Geom for sparse mma with block scaling");
1921 NVVM::MMAFrag frag,
int nRow,
1924 unsigned numberElements = 0;
1927 Type f16x2 = VectorType::get(2, builder.getF16Type());
1928 if (type == NVVM::MMATypes::f16) {
1929 elementType = f16x2;
1930 if (frag == NVVM::MMAFrag::a || frag == NVVM::MMAFrag::b)
1934 }
else if (type == NVVM::MMATypes::f32) {
1935 elementType = builder.getF32Type();
1937 }
else if (type == NVVM::MMATypes::f64) {
1938 elementType = builder.getF64Type();
1939 if (frag == NVVM::MMAFrag::a || frag == NVVM::MMAFrag::b)
1943 }
else if (type == NVVM::MMATypes::tf32) {
1944 elementType = builder.getI32Type();
1946 }
else if (type == NVVM::MMATypes::s8 || type == NVVM::MMATypes::u8) {
1947 elementType = builder.getI32Type();
1948 int parallelSize = 0;
1949 if (frag == NVVM::MMAFrag::a)
1950 parallelSize = nRow;
1951 if (frag == NVVM::MMAFrag::b)
1952 parallelSize = nCol;
1955 if (parallelSize == 16)
1958 else if (parallelSize == 8)
1960 else if (parallelSize == 32)
1962 }
else if (type == NVVM::MMATypes::s32) {
1963 elementType = builder.getI32Type();
1966 assert(numberElements != 0 && elementType !=
nullptr);
1967 return std::make_pair(elementType, numberElements);
1970static std::pair<mlir::Type, unsigned>
1974 if (frag == NVVM::MMAFrag::a) {
1977 }
else if (frag == NVVM::MMAFrag::b) {
1984 assert(nRow && nCol);
1988LogicalResult NVVM::WMMALoadOp::verify() {
1989 unsigned addressSpace =
1990 llvm::cast<LLVM::LLVMPointerType>(getPtr().
getType()).getAddressSpace();
1991 if (addressSpace != 0 && addressSpace != NVVMMemorySpace::Global &&
1992 addressSpace != NVVMMemorySpace::Shared)
1993 return emitOpError(
"expected source pointer in memory "
1996 if (NVVM::WMMALoadOp::getIntrinsicID(
getM(),
getN(), getK(), getLayout(),
1997 getEltype(), getFrag()) == 0)
1998 return emitOpError() <<
"invalid attribute combination";
2003 if (typeInfo.first == f64Ty && typeInfo.second == 1) {
2005 return emitOpError(
"expected destination type to be f64");
2009 Type dstType = LLVM::LLVMStructType::getLiteral(
2012 return emitOpError(
"expected destination type is a structure of ")
2013 << typeInfo.second <<
" elements of type " << typeInfo.first;
2017LogicalResult NVVM::WMMAStoreOp::verify() {
2018 unsigned addressSpace =
2019 llvm::cast<LLVM::LLVMPointerType>(getPtr().
getType()).getAddressSpace();
2020 if (addressSpace != 0 && addressSpace != NVVMMemorySpace::Global &&
2021 addressSpace != NVVMMemorySpace::Shared)
2022 return emitOpError(
"expected operands to be a source pointer in memory "
2025 if (NVVM::WMMAStoreOp::getIntrinsicID(
getM(),
getN(), getK(), getLayout(),
2027 return emitOpError() <<
"invalid attribute combination";
2030 if (getArgs().size() != typeInfo.second)
2031 return emitOpError() <<
"expected " << typeInfo.second <<
" data operands";
2032 if (llvm::any_of(getArgs(), [&typeInfo](
Value operands) {
2033 return operands.
getType() != typeInfo.first;
2035 return emitOpError() <<
"expected data operands of type " << typeInfo.first;
2039LogicalResult NVVM::WMMAMmaOp::verify() {
2040 if (NVVM::WMMAMmaOp::getIntrinsicID(
getM(),
getN(), getK(), getLayoutA(),
2041 getLayoutB(), getEltypeA(),
2043 return emitOpError() <<
"invalid attribute combination";
2051 arguments.append(typeInfoA.second, typeInfoA.first);
2052 arguments.append(typeInfoB.second, typeInfoB.first);
2053 arguments.append(typeInfoC.second, typeInfoC.first);
2054 unsigned numArgs = arguments.size();
2055 if (getArgs().size() != numArgs)
2056 return emitOpError() <<
"expected " << numArgs <<
" arguments";
2057 for (
unsigned i = 0; i < numArgs; i++) {
2058 if (getArgs()[i].
getType() != arguments[i])
2059 return emitOpError() <<
"expected argument " << i <<
" to be of type "
2062 Type dstType = LLVM::LLVMStructType::getLiteral(
2065 return emitOpError(
"expected destination type is a structure of ")
2066 << typeInfoC.second <<
" elements of type " << typeInfoC.first;
2070LogicalResult NVVM::LdMatrixOp::verify() {
2072 if (m == 8 && n == 8) {
2073 if (num != 1 && num != 2 && num != 4) {
2074 return emitOpError(
"expected num attribute to be 1, 2 or 4 for 8x8 "
2077 if (getEltType() != LdStMatrixEltType::B16) {
2078 return emitOpError(
"expected element type to be b16 for 8x8 matrix");
2080 }
else if (m == 8 && n == 16) {
2081 if (num != 1 && num != 2 && num != 4) {
2082 return emitOpError(
"expected num attribute to be 1, 2 or 4 for 8x16 "
2085 if (getLayout() != MMALayout::row) {
2086 return emitOpError(
"expected layout to be row for 8x16 matrix");
2088 if (getEltType() != LdStMatrixEltType::B8X16_B4X16_P64 &&
2089 getEltType() != LdStMatrixEltType::B8X16_B6X16_P32 &&
2090 getEltType() != LdStMatrixEltType::S8_S4) {
2091 return emitOpError(
"expected element type to be b8x16.b4x16_p64, "
2092 "b8x16.b6x16_p32 or s8.s4 for 8x16 matrix");
2094 }
else if (m == 16 && n == 16) {
2095 if (num != 1 && num != 2) {
2096 return emitOpError(
"expected num attribute to be 1 or 2 for 16x16 "
2099 if (getLayout() != MMALayout::col) {
2100 return emitOpError(
"expected layout to be col for 16x16 matrix");
2102 if (getEltType() != LdStMatrixEltType::B8 &&
2103 getEltType() != LdStMatrixEltType::B8X16_B4X16_P64 &&
2104 getEltType() != LdStMatrixEltType::B8X16_B6X16_P32) {
2105 return emitOpError(
"expected element type to be b8, b8x16.b4x16_p64 or "
2106 "b8x16.b6x16_p32 for 16x16 matrix");
2109 return emitOpError(
"expected shape to be 8x8, 8x16 or 16x16");
2113 uint32_t numElements = (m == 16 && n == 16 ? num * 2 : num);
2114 if (numElements == 1 &&
getType() != i32)
2115 return emitOpError(
"expected destination type is i32");
2116 if (numElements == 2 || numElements == 4) {
2117 Type dstType = LLVM::LLVMStructType::getLiteral(
2120 return emitOpError(
"expected destination type is a structure of ")
2121 << numElements <<
" elements of type i32";
2127LogicalResult LdMatrixOp::inferReturnTypes(
2128 MLIRContext *context, std::optional<Location> location,
2130 uint32_t num = adaptor.getNum();
2131 uint32_t m = adaptor.getShape().getM();
2132 uint32_t n = adaptor.getShape().getN();
2133 uint32_t numElements = (m == 16 && n == 16) ? num * 2 : num;
2135 Type i32 = IntegerType::get(context, 32);
2136 if (numElements == 1)
2137 inferredReturnTypes.push_back(i32);
2139 inferredReturnTypes.push_back(LLVM::LLVMStructType::getLiteral(
2144LogicalResult NVVM::StMatrixOp::verify() {
2145 int numMatrix = getSources().size();
2146 if (numMatrix != 1 && numMatrix != 2 && numMatrix != 4)
2147 return emitOpError(
"expected num attribute to be 1, 2 or 4");
2150 if (m == 8 && n == 8) {
2151 if (getEltType() != NVVM::LdStMatrixEltType::B16) {
2152 return emitOpError(
"expected element type to be B16 for 8x8 matrix");
2154 }
else if (m == 16 && n == 8) {
2155 if (getEltType() != NVVM::LdStMatrixEltType::B8) {
2156 return emitOpError(
"expected element type to be B8 for 16x8 matrix");
2158 if (getLayout() != NVVM::MMALayout::col) {
2159 return emitOpError(
"expected layout to be col for 16x8 matrix");
2162 return emitOpError(
"expected shape to be 8x8 or 16x8");
2168LogicalResult NVVM::MovMatrixOp::verify() {
2170 if (m != 8 || n != 8)
2171 return emitOpError(
"expected shape to be 8x8");
2172 if (getLayout() != NVVM::MMALayout::col)
2173 return emitOpError(
"expected layout to be col");
2174 if (getEltType() != NVVM::LdStMatrixEltType::B16)
2175 return emitOpError(
"expected element type to be b16");
2185 llvm::IRBuilderBase &builder) {
2186 auto thisOp = cast<NVVM::MovMatrixOp>(op);
2187 return {llvm::Intrinsic::nvvm_movmatrix_sync_aligned_m8n8_trans_b16,
2191#define GET_OP_CLASSES
2192#include "mlir/Dialect/LLVMIR/NVVMMmaOps.cpp.inc"
static void addInferredMultiplicandTypes(MLIRContext *ctx, OperationState &result, ValueRange operandA, ValueRange operandB, std::optional< std::array< MMATypes, 2 > > multiplicandPtxTypes)
static void addBlockScaleProperties(OpBuilder &builder, OperationState &result, ArrayRef< int64_t > shape, ScaleVecSize scaleVecSize, BlockScaleFormat blockScaleFormat, MMABlockScaleKind kind)
static ParseResult parseEnumKeyword(OpAsmParser &parser, AttrTy &attr)
static void printMmaUnitProperty(OpAsmPrinter &printer, bool &isFirst, StringRef keyword)
static void printOperandList(OpAsmPrinter &p, StringRef name, ArrayRef< Value > operands)
static void printMmaProperty(OpAsmPrinter &printer, bool &isFirst, StringRef keyword, AttrTy value)
static bool isMmaPropertyName(StringRef name)
static void printMmaEnumProperty(OpAsmPrinter &printer, bool &isFirst, StringRef keyword, AttrTy value)
static ParseResult parseMmaProperties(OpAsmParser &parser, NamedAttrList &attributes, ArrayRef< StringRef > allowedKeywords, ArrayRef< StringRef > requiredProperties)
static void inferAndSetMultiplicandTypes(MLIRContext *ctx, NamedAttrList &attrs, const SmallVectorImpl< Type > &operandTypes)
static LogicalResult parseMmaOperand(OpAsmParser &parser, StringRef operandName, SmallVectorImpl< OpAsmParser::UnresolvedOperand > ®s)
static std::pair< mlir::Type, unsigned > inferMMATypeFromMNK(NVVM::MMATypes type, NVVM::MMAFrag frag, int m, int n, int k, MLIRContext *context)
static bool isInt8PtxType(MMATypes type)
static bool isInt4PtxType(MMATypes type)
static bool isIntegerPtxType(MMATypes type)
static MMATypes inferPtxTypeFromResult(OpTy op)
static LogicalResult parseMmaTypeSignature(OpAsmParser &parser, SmallVectorImpl< Type > &operandTypes)
static ParseResult parseMmaEnumPropertyValue(OpAsmParser &parser, NamedAttrList &attributes, StringRef name)
static ParseResult parseMmaPropertyValue(OpAsmParser &parser, NamedAttrList &attributes, StringRef name)
static void processOperandFragments(Op &op, std::array< MMAOperandFragment, 3 > &frags, SmallVectorImpl< Type > ®Types, SmallVectorImpl< StringRef > &ignoreAttrNames)
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
@ OptionalSquare
Square brackets supporting zero or more ops, or nothing.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
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.
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.
ParseResult parseKeywordOrString(std::string *result)
Parse a keyword or a quoted string.
virtual ParseResult parseCustomAttributeWithFallback(Attribute &result, Type type, function_ref< ParseResult(Attribute &result, Type type)> parseAttribute)=0
Parse a custom attribute with the provided callback, unless the next token is #, in which case the ge...
virtual ParseResult parseEqual()=0
Parse a = token.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseOptionalComma()=0
Parse a , token if present.
virtual ParseResult parseColon()=0
Parse a : token.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseArrow()=0
Parse a '->' token.
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an arrow followed by a type list.
ParseResult parseTypeList(SmallVectorImpl< Type > &result)
Parse a type list.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
void printArrowTypeList(TypeRange &&types)
void printStrippedAttrOrType(AttrOrType attrOrType)
Print the provided attribute in the context of an operation custom printer/parser: this will invoke d...
This class is a general helper class for creating context-global objects like types,...
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
IntegerType getIntegerType(unsigned width)
MLIRContext * getContext() const
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
Implementation class for module translation.
llvm::Value * lookupValue(Value value) const
Finds an LLVM IR value corresponding to the given MLIR value.
MLIRContext is the top-level object for a collection of MLIR operations.
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
std::optional< NamedAttribute > getNamed(StringRef name) const
Return the specified named attribute if present, std::nullopt otherwise.
Attribute get(StringAttr name) const
Return the specified attribute if present, null otherwise.
void append(StringRef name, Attribute attr)
Add an attribute with the specified name.
Attribute set(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
NamedAttribute represents a combination of a name and an Attribute value.
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
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 parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
void printOperands(OperandRange operands)
Print a comma separated range of operation operands out of line to avoid instantiating the range iter...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
This class helps build Operations.
This provides public APIs that all operations should have.
Operation is the basic unit of execution within MLIR.
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.
This class provides an abstraction over the different types of ranges over Values.
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.
std::pair< mlir::Type, unsigned > inferMMAType(mlir::NVVM::MMATypes type, mlir::NVVM::MMAFrag frag, int nRow, int nCol, mlir::MLIRContext *context)
Return the element type and number of elements associated with a wmma matrix of given chracteristics.
std::pair< llvm::Intrinsic::ID, llvm::SmallVector< llvm::Value * > > IDArgPair
A pair type of LLVM's Intrinsic ID and args (which are llvm values).
uint64_t getN(LevelType lt)
uint64_t getM(LevelType lt)
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
This represents an operation in an abstracted form, suitable for use with the builder APIs.