32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/TypeSwitch.h"
34#include "llvm/Support/DebugLog.h"
36#define DEBUG_TYPE "vector-to-gpu"
39#define GEN_PASS_DEF_CONVERTVECTORTOGPU
40#include "mlir/Conversion/Passes.h.inc"
51template <
typename TransferOpType>
55 indices.append(xferOp.getIndices().begin(), xferOp.getIndices().end());
57 unsigned offsetsIdx = 0;
58 for (
auto expr : xferOp.getPermutationMap().getResults()) {
59 if (
auto dim = dyn_cast<AffineDimExpr>(expr)) {
62 dims.push_back(prevIdx);
65 rewriter, loc, d0 + offsetMap.
getResult(offsetsIdx++), dims);
75 auto infer = [&](MapList m) {
80 auto iteratorTypes =
contract.getIteratorTypes().getValue();
89 contract.getIndexingMapsArray() != infer({{m, k}, {k, n}, {m, n}}))
92 contract.getIndexingMapsArray() != infer({{m, k}, {n, k}, {m, n}}))
106 const unsigned nDim = permutationMap.
getNumDims();
107 if (0 == nDim || permutationMap.
getResults().empty())
126static std::optional<int64_t>
128 auto memrefType = dyn_cast<MemRefType>(type);
132 if (memrefType.getRank() < 2)
136 if (failed(memrefType.getStridesAndOffset(strides, offset)) ||
143 unsigned strideIndex = strides.size();
146 if (
auto cst = dyn_cast<AffineConstantExpr>(
result)) {
148 if (0 != cst.getValue())
153 auto dim = dyn_cast<AffineDimExpr>(
result);
157 strideIndex = std::min(strideIndex, dim.getPosition());
163 if (strideIndex + 1 >= strides.size())
166 const int64_t stride = strides[strideIndex];
167 if (stride == ShapedType::kDynamic)
174 if (readOp.getMask() || readOp.hasOutOfBoundsDim() ||
175 readOp.getVectorType().getRank() != 2)
183 if (readOp.getVectorType().getElementType().isInteger(8))
184 if (!readOp->hasOneUse() || (!isa<arith::ExtSIOp>(*readOp->user_begin()) &&
185 !isa<arith::ExtUIOp>(*readOp->user_begin())))
190 return llvm::is_contained(permutationMap.
getResults(), innerDim);
197 if (writeOp.getTransferRank() == 0)
200 if (writeOp.getMask() || writeOp.hasOutOfBoundsDim() ||
201 writeOp.getVectorType().getRank() != 2)
205 std::optional<int64_t> stride =
208 if (!stride.has_value() || stride.value() == 0)
214 return permutationMap.
getResult(1) == innerDim;
220 auto vecType = dyn_cast<VectorType>(constantOp.getType());
221 if (!vecType || vecType.getRank() != 2)
223 return isa<SplatElementsAttr>(constantOp.getValue());
228 return broadcastOp.getResultVectorType().getRank() == 2;
232template <
typename ExtOpTy>
234 auto transferReadOp =
235 extOp.getOperand().template getDefiningOp<vector::TransferReadOp>();
238 return llvm::all_of(extOp->getUsers(), llvm::IsaPred<vector::ContractionOp>);
246static std::optional<gpu::MMAElementwiseOp>
248 using MMAEwO = gpu::MMAElementwiseOp;
250 .Case([](arith::AddFOp) {
return MMAEwO::ADDF; })
251 .Case([](arith::AddIOp) {
return MMAEwO::ADDI; })
252 .Case([](arith::DivFOp) {
return MMAEwO::DIVF; })
253 .Case([](arith::DivSIOp) {
return MMAEwO::DIVS; })
254 .Case([](arith::DivUIOp) {
return MMAEwO::DIVU; })
255 .Case([](arith::ExtFOp) {
return MMAEwO::EXTF; })
256 .Case([](arith::MaximumFOp) {
return MMAEwO::MAXF; })
257 .Case([](arith::MinimumFOp) {
return MMAEwO::MINF; })
258 .Case([](arith::MulFOp) {
return MMAEwO::MULF; })
259 .Case([](arith::MulIOp) {
return MMAEwO::MULI; })
260 .Case([](arith::NegFOp) {
return MMAEwO::NEGATEF; })
261 .Case([](arith::SubFOp) {
return MMAEwO::SUBF; })
262 .Case([](arith::SubIOp) {
return MMAEwO::SUBI; })
263 .Case([](arith::TruncFOp) {
return MMAEwO::TRUNCF; })
264 .Default(std::nullopt);
277 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
279 if (failed(warpMatrixInfo))
283 if (failed(contractOp))
290 return (cast<VectorType>(op->getResult(0).getType()) ==
291 cast<VectorType>((*contractOp).getRhs().getType()));
293 return (cast<VectorType>(op->getResult(0).getType()) ==
294 cast<VectorType>((*contractOp).getAcc().getType()));
300 if (isa<scf::ForOp, scf::YieldOp>(op))
302 if (
auto transferRead = dyn_cast<vector::TransferReadOp>(op))
305 if (
auto transferWrite = dyn_cast<vector::TransferWriteOp>(op))
308 if (
auto extractStridedSlice = dyn_cast<vector::ExtractStridedSliceOp>(op))
311 if (
auto contract = dyn_cast<vector::ContractionOp>(op))
313 if (
auto constant = dyn_cast<arith::ConstantOp>(op))
315 if (
auto broadcast = dyn_cast<vector::BroadcastOp>(op))
317 if (
auto signedExtend = dyn_cast<arith::ExtSIOp>(op))
319 if (
auto unsignedExtend = dyn_cast<arith::ExtUIOp>(op))
321 if (
auto fpExtend = dyn_cast<arith::ExtFOp>(op))
323 if (
auto fpTrunc = dyn_cast<arith::TruncFOp>(op))
337 unsigned currentIndex = 0;
340 while (currentIndex != slice.size()) {
341 auto *currentOp = (slice)[currentIndex];
343 backwardSlice.clear();
346 assert(
result.succeeded() &&
"expected a backward slice");
348 slice.insert_range(backwardSlice);
351 forwardSlice.clear();
356 if (
auto forOp = dyn_cast<scf::ForOp>(currentOp)) {
357 for (
Value forOpResult : forOp.getResults())
364 slice.insert_range(forwardSlice);
375 return llvm::any_of(op->
getResultTypes(), llvm::IsaPred<VectorType>);
378 backwardSliceOptions.
filter = hasVectorDest;
384 forwardSliceOptions.
filter = hasVectorSrc;
388 if (!isa<vector::ContractionOp>(nestedOp) &&
391 if (opToConvert.contains(nestedOp))
398 if (llvm::any_of(dependentOps, [useNvGpu](
Operation *op) {
400 LDBG() <<
"cannot convert op: " << *op;
407 opToConvert.insert_range(dependentOps);
416struct PrepareContractToGPUMMA
420 LogicalResult matchAndRewrite(vector::ContractionOp op,
421 PatternRewriter &rewriter)
const override {
422 Location loc = op.getLoc();
423 Value
lhs = op.getLhs(),
rhs = op.getRhs(), res = op.getAcc();
426 using MapList = ArrayRef<ArrayRef<AffineExpr>>;
427 auto infer = [&](MapList m) {
432 static constexpr std::array<int64_t, 2> perm = {1, 0};
433 auto iteratorTypes = op.getIteratorTypes().getValue();
434 SmallVector<AffineMap, 4> maps = op.getIndexingMapsArray();
443 if (maps == infer({{m, k}, {k, n}, {m, n}}))
445 if (maps == infer({{m, k}, {n, k}, {m, n}})) {
446 rhs = vector::TransposeOp::create(rewriter, loc,
rhs, perm);
447 }
else if (maps == infer({{k, m}, {k, n}, {m, n}})) {
448 lhs = vector::TransposeOp::create(rewriter, loc,
lhs, perm);
449 }
else if (maps == infer({{k, m}, {n, k}, {m, n}})) {
450 rhs = vector::TransposeOp::create(rewriter, loc,
rhs, perm);
451 lhs = vector::TransposeOp::create(rewriter, loc,
lhs, perm);
452 }
else if (maps == infer({{m, k}, {k, n}, {n, m}})) {
454 rhs = vector::TransposeOp::create(rewriter, loc,
rhs, perm);
455 lhs = vector::TransposeOp::create(rewriter, loc,
lhs, perm);
456 }
else if (maps == infer({{m, k}, {n, k}, {n, m}})) {
458 rhs = vector::TransposeOp::create(rewriter, loc,
rhs, perm);
459 }
else if (maps == infer({{k, m}, {k, n}, {n, m}})) {
461 lhs = vector::TransposeOp::create(rewriter, loc,
lhs, perm);
462 }
else if (maps == infer({{k, m}, {n, k}, {n, m}})) {
471 op.getIteratorTypes());
480struct CombineTransferReadOpTranspose final
484 LogicalResult matchAndRewrite(vector::TransposeOp op,
485 PatternRewriter &rewriter)
const override {
487 Value source = op.getVector();
488 Type resultType = op.getType();
495 VectorType::get(cast<VectorType>(resultType).
getShape(),
496 cast<VectorType>(source.
getType()).getElementType());
499 auto transferReadOp = source.
getDefiningOp<vector::TransferReadOp>();
504 if (transferReadOp.getTransferRank() == 0)
507 if (transferReadOp.getMask() || transferReadOp.hasOutOfBoundsDim())
510 AffineMap permutationMap =
513 permutationMap.
compose(transferReadOp.getPermutationMap());
515 auto loc = op.getLoc();
516 Value
result = vector::TransferReadOp::create(
517 rewriter, loc, resultType, transferReadOp.getBase(),
518 transferReadOp.getIndices(), AffineMapAttr::get(newMap),
519 transferReadOp.getPadding(), transferReadOp.getMask(),
520 transferReadOp.getInBoundsAttr())
525 if (isa<arith::ExtSIOp>(extOp))
526 result = arith::ExtSIOp::create(rewriter, loc, op.getType(),
result)
528 else if (isa<arith::ExtUIOp>(extOp))
529 result = arith::ExtUIOp::create(rewriter, loc, op.getType(),
result)
534 arith::ExtFOp::Properties{})
559 auto contract = dyn_cast<vector::ContractionOp>(users);
577 assert(op.getTransferRank() > 0 &&
"unexpected 0-d transfer");
579 "expected convertible operation");
582 std::optional<int64_t> stride =
584 if (!stride.has_value()) {
585 LDBG() <<
"no stride";
595 Value mappingResult = op.getResult();
596 auto elType = op.getVectorType().getElementType();
598 if (op->hasOneUse()) {
599 auto *user = *op->user_begin();
601 if (isa<arith::ExtSIOp, arith::ExtUIOp>(user)) {
602 elType = IntegerType::get(
603 op.getContext(), cast<IntegerType>(elType).getWidth(),
604 isa<arith::ExtSIOp>(user) ? IntegerType::Signed
605 : IntegerType::Unsigned);
606 mappingResult = user->getResult(0);
611 Value load = gpu::SubgroupMmaLoadMatrixOp::create(
612 rewriter, op.getLoc(), type, op.getBase(), op.getIndices(),
614 isTranspose ? rewriter.
getUnitAttr() : UnitAttr());
615 valueMapping[mappingResult] =
load;
617 LDBG() <<
"transfer read to: " <<
load;
628 std::optional<int64_t> stride =
630 if (!stride.has_value()) {
631 LDBG() <<
"no stride";
635 auto it = valueMapping.find(op.getVector());
636 if (it == valueMapping.end()) {
637 LDBG() <<
"no mapping";
641 Value matrix = it->second;
642 auto store = gpu::SubgroupMmaStoreMatrixOp::create(
643 rewriter, op.getLoc(), matrix, op.getBase(), op.getIndices(),
647 LDBG() <<
"transfer write to: " << store;
649 LDBG() <<
"erase: " << op;
658 regInfo.elementsPerRegister};
659 Type elType = regInfo.registerLLVMType;
660 if (
auto vecType = dyn_cast<VectorType>(elType))
661 elType = vecType.getElementType();
662 return VectorType::get(
shape, elType);
672 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
674 if (failed(warpMatrixInfo)) {
675 LDBG() <<
"no warpMatrixInfo";
679 FailureOr<nvgpu::FragmentElementInfo> regInfo =
680 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
681 if (failed(regInfo)) {
682 LDBG() <<
"not mma sync reg info";
687 auto dense = dyn_cast<SplatElementsAttr>(op.getValue());
689 LDBG() <<
"not a splat";
694 rewriter, op.getLoc(), vectorType,
696 valueMapping[op.getResult()] =
result;
711 LDBG() <<
"Failed because the result of `vector.transfer_read` "
712 "is not a 2d operand";
721 auto exprM = dyn_cast<AffineDimExpr>(dM);
722 auto exprN = dyn_cast<AffineDimExpr>(dN);
724 if (!exprM || !exprN) {
725 LDBG() <<
"Failed because expressions are not affine dim "
726 "expressions, then transpose cannot be determined.";
730 return exprM.getPosition() > exprN.getPosition();
740 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
742 if (failed(warpMatrixInfo)) {
743 LDBG() <<
"no warpMatrixInfo";
747 FailureOr<nvgpu::FragmentElementInfo> regInfo =
748 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
749 if (failed(regInfo)) {
750 LDBG() <<
"not mma sync reg info";
755 if (failed(transpose)) {
756 LDBG() <<
"failed to determine the transpose";
758 op,
"Op should likely not be converted to a nvgpu.ldmatrix call.");
761 FailureOr<nvgpu::LdMatrixParams> params =
762 nvgpu::getLdMatrixParams(*warpMatrixInfo, *transpose);
764 if (failed(params)) {
765 LDBG() <<
"failed to convert vector.transfer_read to ldmatrix. "
766 <<
"Op should likely not be converted to a nvgpu.ldmatrix call.";
768 op,
"failed to convert vector.transfer_read to ldmatrix; this op "
769 "likely should not be converted to a nvgpu.ldmatrix call.");
773 auto laneId = gpu::LaneIdOp::create(rewriter, loc,
nullptr);
774 FailureOr<AffineMap> offsets =
775 nvgpu::getLaneIdToLdMatrixMatrixCoord(rewriter, loc, *params);
776 if (failed(offsets)) {
777 LDBG() <<
"no offsets";
787 nvgpu::LdMatrixOp newOp =
788 nvgpu::LdMatrixOp::create(rewriter, loc, vectorType, op.getBase(),
789 indices, *transpose, params->numTiles);
790 valueMapping[op] = newOp->getResult(0);
801 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
803 if (failed(warpMatrixInfo))
805 FailureOr<nvgpu::FragmentElementInfo> regInfo =
806 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
807 if (failed(regInfo)) {
809 op,
"Failed to deduce register fragment type during "
810 "conversion to distributed non-ldmatrix compatible load");
813 Value laneId = gpu::LaneIdOp::create(rewriter, loc,
nullptr);
816 Type loadedElType = regInfo->registerLLVMType;
819 Value fill = arith::ConstantOp::create(
820 rewriter, op.getLoc(), vectorType.getElementType(),
821 rewriter.
getZeroAttr(vectorType.getElementType()));
823 vector::BroadcastOp::create(rewriter, op.getLoc(), vectorType, fill);
825 bool isTransposeLoad = !op.getPermutationMap().isMinorIdentity();
829 if (!isTransposeLoad) {
830 if (!isa<VectorType>(loadedElType)) {
831 loadedElType = VectorType::get({1}, loadedElType);
834 for (
int i = 0; i < vectorType.getShape()[0]; i++) {
835 FailureOr<AffineMap> coords = nvgpu::getLaneIdAndValueIdToOperandCoord(
836 rewriter, op.getLoc(), *warpMatrixInfo);
840 Value logicalValueId = arith::ConstantOp::create(
842 rewriter.
getIndexAttr(i * regInfo->elementsPerRegister));
845 rewriter, op, *coords, {laneId, logicalValueId}, newIndices);
847 Value el = vector::LoadOp::create(rewriter, loc, loadedElType,
848 op.getBase(), newIndices);
849 result = vector::InsertOp::create(rewriter, loc, el,
result, i);
852 if (
auto vecType = dyn_cast<VectorType>(loadedElType)) {
853 loadedElType = vecType.getElementType();
855 for (
int i = 0; i < vectorType.getShape()[0]; i++) {
856 for (
unsigned innerIdx = 0; innerIdx < vectorType.getShape()[1];
859 Value logicalValueId = arith::ConstantOp::create(
861 rewriter.
getIndexAttr(i * regInfo->elementsPerRegister + innerIdx));
862 FailureOr<AffineMap> coords = nvgpu::getLaneIdAndValueIdToOperandCoord(
863 rewriter, op.getLoc(), *warpMatrixInfo);
869 rewriter, op, *coords, {laneId, logicalValueId}, newIndices);
870 Value el = memref::LoadOp::create(rewriter, op.getLoc(), loadedElType,
871 op.getBase(), newIndices);
872 result = vector::InsertOp::create(rewriter, op.getLoc(), el,
result,
878 valueMapping[op.getResult()] =
result;
885 dyn_cast_or_null<gpu::AddressSpaceAttr>(type.getMemorySpace());
886 return addressSpace &&
887 addressSpace.getValue() == gpu::GPUDialect::getWorkgroupAddressSpace();
899 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
901 if (failed(warpMatrixInfo))
904 bool isLdMatrixCompatible =
906 nvgpu::inferTileWidthInBits(*warpMatrixInfo) == 128;
908 VectorType vecTy = op.getVectorType();
909 int64_t bitWidth = vecTy.getElementType().getIntOrFloatBitWidth();
914 if (!op.getPermutationMap().isMinorIdentity() &&
915 (bitWidth != 16 || vecTy.getDimSize(1) < 8 ||
916 vecTy.getDimSize(0) * bitWidth < 128))
917 isLdMatrixCompatible =
false;
919 if (!isLdMatrixCompatible)
932 auto it = valueMapping.find(op.getVector());
933 if (it == valueMapping.end())
935 Value matrix = it->second;
937 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
939 if (failed(warpMatrixInfo))
941 FailureOr<nvgpu::FragmentElementInfo> regInfo =
942 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
947 Value laneId = gpu::LaneIdOp::create(rewriter, loc,
nullptr);
949 for (
unsigned i = 0; i < vectorType.getShape()[0]; i++) {
950 Value logicalValueId = arith::ConstantOp::create(
952 rewriter.
getIndexAttr(i * regInfo->elementsPerRegister));
953 FailureOr<AffineMap> coords = nvgpu::getLaneIdAndValueIdToOperandCoord(
954 rewriter, op.getLoc(), *warpMatrixInfo);
962 rewriter, op, *coords, {laneId, logicalValueId}, newIndices);
963 vector::StoreOp::create(rewriter, loc, el, op.getBase(), newIndices);
966 LDBG() <<
"erase: " << op;
973 for (
auto attr : arrayAttr)
974 results.push_back(cast<IntegerAttr>(attr).getInt());
979 vector::ExtractStridedSliceOp op,
986 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
988 if (failed(warpMatrixInfo))
991 FailureOr<nvgpu::FragmentElementInfo> mmaSyncFragmentInfo =
992 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
993 if (failed(mmaSyncFragmentInfo))
997 auto transferReadOp = op.getSource().getDefiningOp<vector::TransferReadOp>();
1002 if (failed(warpMatrixInfo))
1005 FailureOr<nvgpu::FragmentElementInfo> ldFragmentInfo =
1006 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
1007 if (failed(ldFragmentInfo))
1011 (mmaSyncFragmentInfo->elementsPerRegister ==
1012 ldFragmentInfo->elementsPerRegister) &&
1013 "Number of elements per register should be same for load and mma.sync");
1016 std::array<int64_t, 2> strides = {1,
1018 std::array<int64_t, 2> sliceShape = {
1019 mmaSyncFragmentInfo->numRegistersPerFragment,
1020 mmaSyncFragmentInfo->elementsPerRegister};
1021 auto it = valueMapping.find(transferReadOp);
1022 if (it == valueMapping.end())
1024 auto sourceVector = it->second;
1037 std::array<int64_t, 2> sliceOffset = {0, 0};
1039 if (offsets[0] && offsets[1])
1040 return op->emitError() <<
"Slicing fragments in 2D is not supported. ";
1042 sliceOffset[0] = (warpVectorShape[0] / offsets[0]);
1043 else if (offsets[1])
1044 sliceOffset[0] = (warpVectorShape[1] / offsets[1]);
1046 Value newOp = vector::ExtractStridedSliceOp::create(
1047 rewriter, loc, sourceVector, sliceOffset, sliceShape, strides);
1049 valueMapping[op] = newOp;
1059 auto itA = valueMapping.find(op.getLhs());
1060 auto itB = valueMapping.find(op.getRhs());
1061 auto itC = valueMapping.find(op.getAcc());
1062 if (itA == valueMapping.end() || itB == valueMapping.end() ||
1063 itC == valueMapping.end())
1065 Value opA = itA->second, opB = itB->second, opC = itC->second;
1066 Value matmul = gpu::SubgroupMmaComputeOp::create(rewriter, op.getLoc(),
1070 valueMapping[op.getResult()] = matmul;
1080 auto itA = valueMapping.find(op.getLhs());
1081 auto itB = valueMapping.find(op.getRhs());
1082 auto itC = valueMapping.find(op.getAcc());
1083 if (itA == valueMapping.end() || itB == valueMapping.end() ||
1084 itC == valueMapping.end())
1086 Value opA = itA->second, opB = itB->second, opC = itC->second;
1087 int64_t m = cast<VectorType>(op.getLhs().getType()).getShape()[0];
1088 int64_t n = cast<VectorType>(op.getRhs().getType()).getShape()[0];
1089 int64_t k = cast<VectorType>(op.getLhs().getType()).getShape()[1];
1090 Value matmul = nvgpu::MmaSyncOp::create(rewriter, op.getLoc(), opA, opB, opC,
1092 valueMapping[op.getResult()] = matmul;
1106 cast<SplatElementsAttr>(op.getValue()).getSplatValue<TypedAttr>();
1107 auto scalarConstant =
1108 arith::ConstantOp::create(rewriter, op.getLoc(), splat.getType(), splat);
1110 auto vecType = cast<VectorType>(op.getType());
1112 vecType.getShape(), vecType.getElementType(), llvm::StringRef(fragType));
1113 auto matrix = gpu::SubgroupMmaConstantMatrixOp::create(rewriter, op.getLoc(),
1114 type, scalarConstant);
1115 valueMapping[op.getResult()] = matrix;
1129 auto vecType = op.getResultVectorType();
1131 vecType.getShape(), vecType.getElementType(), llvm::StringRef(fragType));
1132 auto matrix = gpu::SubgroupMmaConstantMatrixOp::create(rewriter, op.getLoc(),
1133 type, op.getSource());
1134 valueMapping[op.getResult()] = matrix;
1148 auto operands = llvm::to_vector<4>(loop.getInitArgs());
1149 llvm::append_range(operands, newInitArgs);
1150 scf::ForOp newLoop =
1151 scf::ForOp::create(rewriter, loop.getLoc(), loop.getLowerBound(),
1152 loop.getUpperBound(), loop.getStep(), operands);
1155 newLoop.getRegion().getBlocks().splice(
1156 newLoop.getRegion().getBlocks().begin(), loop.getRegion().getBlocks());
1157 for (
Value operand : newInitArgs)
1158 newLoop.getBody()->addArgument(operand.getType(), operand.getLoc());
1160 for (
auto it : llvm::zip(loop.getResults(), newLoop.getResults().take_front(
1161 loop.getNumResults())))
1164 LDBG() <<
"newLoop now: " << newLoop;
1165 LDBG() <<
"stripped scf.for: " << loop;
1166 LDBG() <<
"erase: " << loop;
1179 for (
const auto &operand : llvm::enumerate(op.getInitArgs())) {
1180 auto it = valueMapping.find(operand.value());
1181 if (it == valueMapping.end()) {
1182 LDBG() <<
"no value mapping for: " << operand.value();
1185 argMapping.push_back(std::make_pair(
1186 operand.index(), op.getInitArgs().size() + newOperands.size()));
1187 newOperands.push_back(it->second);
1191 Block &loopBody = *newForOp.getBody();
1192 for (
auto mapping : argMapping) {
1193 valueMapping[newForOp.getResult(mapping.first)] =
1194 newForOp.getResult(mapping.second);
1196 newForOp.getNumInductionVars())] =
1197 loopBody.
getArgument(mapping.second + newForOp.getNumInductionVars());
1200 LDBG() <<
"scf.for to: " << newForOp;
1210 auto loop = cast<scf::ForOp>(op->getParentOp());
1211 auto yieldOperands = llvm::to_vector<4>(op.getOperands());
1212 for (
const auto &operand : llvm::enumerate(op.getOperands())) {
1213 auto it = valueMapping.find(operand.value());
1214 if (it == valueMapping.end())
1218 yieldOperands[operand.index()] = loop.getInitArgs()[operand.index()];
1219 yieldOperands.push_back(it->second);
1221 scf::YieldOp::create(rewriter, op.getLoc(), yieldOperands);
1223 LDBG() <<
"erase: " << op;
1231 gpu::MMAElementwiseOp opType,
1238 auto it = valueMapping.find(operand);
1239 if (it == valueMapping.end())
1241 matrixOperands.push_back(it->second);
1243 auto resultType = cast<gpu::MMAMatrixType>(matrixOperands[0].
getType());
1244 if (opType == gpu::MMAElementwiseOp::EXTF ||
1245 opType == gpu::MMAElementwiseOp::TRUNCF) {
1249 vectorType.getElementType(),
1250 resultType.getOperand());
1253 Value newOp = gpu::SubgroupMmaElementwiseOp::create(
1254 rewriter, op->
getLoc(), resultType, matrixOperands, opType);
1262 patterns.
add<PrepareContractToGPUMMA, CombineTransferReadOpTranspose>(
1267 patterns.
add<CombineTransferReadOpTranspose>(patterns.
getContext());
1275 auto globalRes = LogicalResult::success();
1277 LDBG() <<
"Process op: " << *op;
1279 auto res = LogicalResult::success();
1280 if (
auto transferRead = dyn_cast<vector::TransferReadOp>(op)) {
1282 }
else if (
auto transferWrite = dyn_cast<vector::TransferWriteOp>(op)) {
1284 }
else if (
auto contractOp = dyn_cast<vector::ContractionOp>(op)) {
1286 }
else if (
auto constantOp = dyn_cast<arith::ConstantOp>(op)) {
1288 }
else if (
auto broadcastOp = dyn_cast<vector::BroadcastOp>(op)) {
1290 }
else if (
auto forOp = dyn_cast<scf::ForOp>(op)) {
1292 }
else if (
auto yieldOp = dyn_cast<scf::YieldOp>(op)) {
1298 globalRes = failure();
1309 .Case([&](vector::TransferReadOp transferReadOp) {
1313 .Case([&](vector::TransferWriteOp transferWriteOp) {
1317 .Case([&](vector::ExtractStridedSliceOp extractStridedSliceOp) {
1321 .Case([&](vector::ContractionOp contractionOp) {
1325 .Case([&](scf::ForOp forOp) {
1328 .Case([&](scf::YieldOp yieldOp) {
1331 .Case([&](arith::ConstantOp constOp) {
1335 return op->
emitError() <<
"unhandled vector to mma type: " << *op;
1339 <<
"failed to convert op during vector-to-nvgpu conversion";
1347struct ConvertVectorToGPUPass
1348 :
public impl::ConvertVectorToGPUBase<ConvertVectorToGPUPass> {
1350 explicit ConvertVectorToGPUPass(
bool useNvGpu_) {
1351 useNvGpu.setValue(useNvGpu_);
1354 void runOnOperation()
override {
1358 return signalPassFailure();
1364 return signalPassFailure();
1374 return std::make_unique<ConvertVectorToGPUPass>(useNvGpu);
static void contract(RootOrderingGraph &graph, ArrayRef< Value > cycle, const DenseMap< Value, unsigned > &parentDepths, DenseMap< Value, Value > &actualSource, DenseMap< Value, Value > &actualTarget)
Contracts the specified cycle in the given graph in-place.
static Value broadcast(Location loc, Value toBroadcast, unsigned numElements, const TypeConverter &typeConverter, ConversionPatternRewriter &rewriter)
Broadcasts the value to vector with numElements number of elements.
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
static LogicalResult convertTransferWriteOp(RewriterBase &rewriter, vector::TransferWriteOp op, llvm::DenseMap< Value, Value > &valueMapping)
static LogicalResult convertForOp(RewriterBase &rewriter, scf::ForOp op, llvm::DenseMap< Value, Value > &valueMapping)
static std::optional< gpu::MMAElementwiseOp > convertElementwiseOpToMMA(Operation *op)
Return the MMA elementwise enum associated with op if it is supported.
static LogicalResult convertContractOp(RewriterBase &rewriter, vector::ContractionOp op, llvm::DenseMap< Value, Value > &valueMapping)
static bool fpTruncSupportsMMAMatrixType(arith::TruncFOp extOp)
static const char * inferFragType(Operation *op)
static LogicalResult convertContractOpToMmaSync(RewriterBase &rewriter, vector::ContractionOp op, llvm::DenseMap< Value, Value > &valueMapping)
static bool isSharedMemory(MemRefType type)
Return true if this is a shared memory memref type.
static VectorType getMmaSyncVectorOperandType(const nvgpu::FragmentElementInfo ®Info)
Returns the vector type which represents a matrix fragment.
static bool fpExtendSupportsMMAMatrixType(arith::ExtFOp extOp)
static bool supportsMMaMatrixType(Operation *op, bool useNvGpu)
static bool constantSupportsMMAMatrixType(arith::ConstantOp constantOp)
Return true if the constant is a splat to a 2D vector so that it can be converted to a MMA constant m...
static bool contractSupportsMMAMatrixType(vector::ContractionOp contract, bool useNvGpu)
static void populateFromInt64AttrArray(ArrayAttr arrayAttr, SmallVectorImpl< int64_t > &results)
static FailureOr< bool > isTransposed(vector::TransferReadOp op)
Check if the loaded matrix operand requires transposed.
static LogicalResult convertTransferReadOp(RewriterBase &rewriter, vector::TransferReadOp op, llvm::DenseMap< Value, Value > &valueMapping)
static bool integerExtendSupportsMMAMatrixType(ExtOpTy extOp)
Return true if this integer extend op can be folded into a contract op.
static LogicalResult convertTransferReadToLoads(RewriterBase &rewriter, vector::TransferReadOp op, llvm::DenseMap< Value, Value > &valueMapping)
Converts a vector.transfer_read operation directly to either a vector.load or a nvgpu....
static LogicalResult convertBroadcastOp(RewriterBase &rewriter, vector::BroadcastOp op, llvm::DenseMap< Value, Value > &valueMapping)
Convert a vector.broadcast from scalar to a SubgroupMmaConstantMatrix op.
static LogicalResult creatLdMatrixCompatibleLoads(RewriterBase &rewriter, vector::TransferReadOp op, llvm::DenseMap< Value, Value > &valueMapping)
static scf::ForOp replaceForOpWithNewSignature(RewriterBase &rewriter, scf::ForOp loop, ValueRange newInitArgs)
static bool transferWriteSupportsMMAMatrixType(vector::TransferWriteOp writeOp)
static LogicalResult convertElementwiseOp(RewriterBase &rewriter, Operation *op, gpu::MMAElementwiseOp opType, llvm::DenseMap< Value, Value > &valueMapping)
Convert an elementwise op to the equivalent elementwise op on MMA matrix.
static bool isFirstResultLastMapDimension(AffineMap permutationMap)
static bool transferReadSupportsMMAMatrixType(vector::TransferReadOp readOp)
static bool extractStridedSliceSupportsMMAMatrixType(vector::ExtractStridedSliceOp op)
Returns true if the extract strided slice op is supported with mma.sync path.
static LogicalResult convertConstantOpMmaSync(RewriterBase &rewriter, arith::ConstantOp op, llvm::DenseMap< Value, Value > &valueMapping)
Convert a 2D splat ConstantOp to a SubgroupMmaConstantMatrix op.
static bool elementwiseSupportsMMAMatrixType(Operation *op)
Return true if the op is supported as elementwise op on MMAMatrix type.
static LogicalResult convertConstantOp(RewriterBase &rewriter, arith::ConstantOp op, llvm::DenseMap< Value, Value > &valueMapping)
Convert a 2D splat ConstantOp to a SubgroupMmaConstantMatrix op.
static LogicalResult convertYieldOp(RewriterBase &rewriter, scf::YieldOp op, llvm::DenseMap< Value, Value > &valueMapping)
static SetVector< Operation * > getOpToConvert(mlir::Operation *op, bool useNvGpu)
static LogicalResult convertTransferWriteToStores(RewriterBase &rewriter, vector::TransferWriteOp op, llvm::DenseMap< Value, Value > &valueMapping)
static std::optional< int64_t > getStaticallyKnownRowStride(ShapedType type, AffineMap permutationMap)
static SetVector< Operation * > getSliceContract(Operation *op, const BackwardSliceOptions &backwardSliceOptions, const ForwardSliceOptions &forwardSliceOptions)
Return an unsorted slice handling scf.for region differently than getSlice.
static void getXferIndices(RewriterBase &rewriter, TransferOpType xferOp, AffineMap offsetMap, ArrayRef< Value > dimValues, SmallVector< Value, 4 > &indices)
For a vector TransferOpType xferOp, an empty indices vector, and an AffineMap representing offsets to...
static LogicalResult convertExtractStridedSlice(RewriterBase &rewriter, vector::ExtractStridedSliceOp op, llvm::DenseMap< Value, Value > &valueMapping)
static bool broadcastSupportsMMAMatrixType(vector::BroadcastOp broadcastOp)
Return true if this is a broadcast from scalar to a 2D vector.
static LogicalResult createNonLdMatrixLoads(RewriterBase &rewriter, vector::TransferReadOp op, llvm::DenseMap< Value, Value > &valueMapping)
Base type for affine expression.
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
MLIRContext * getContext() const
unsigned getNumDims() const
ArrayRef< AffineExpr > getResults() const
unsigned getNumResults() const
static SmallVector< AffineMap, 4 > inferFromExprList(ArrayRef< ArrayRef< AffineExpr > > exprsList, MLIRContext *context)
Returns a vector of AffineMaps; each with as many results as exprs.size(), as many dims as the larges...
AffineExpr getResult(unsigned idx) const
static AffineMap getPermutationMap(ArrayRef< unsigned > permutation, MLIRContext *context)
Returns an AffineMap representing a permutation.
AffineMap compose(AffineMap map) const
Returns the AffineMap resulting from composing this with map.
Attributes are known-constant values of operations.
This class represents an argument of a Block.
Block represents an ordered list of Operations.
BlockArgument getArgument(unsigned i)
IntegerAttr getIndexAttr(int64_t value)
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
TypedAttr getZeroAttr(Type type)
AffineExpr getAffineDimExpr(unsigned position)
MLIRContext * getContext() const
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
ArrayAttr getAffineMapArrayAttr(ArrayRef< AffineMap > values)
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
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.
RAII guard to reset the insertion point of the builder when destroyed.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Operation is the basic unit of execution within MLIR.
Value getOperand(unsigned idx)
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
bool hasOneUse()
Returns true if this operation has exactly one use.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Location getLoc()
The source location the operation was defined or derived from.
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
operand_type_range getOperandTypes()
result_type_range getResultTypes()
operand_range getOperands()
Returns an iterator on the underlying Value's.
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
user_range getUsers()
Returns a range of all users.
user_iterator user_begin()
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
unsigned getNumResults()
Return the number of results held by this operation.
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void eraseBlock(Block *block)
This method erases all operations in a block.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
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.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
MMAMatrix represents a matrix held by a subgroup for matrix-matrix multiply accumulate operations.
static MMAMatrixType get(ArrayRef< int64_t > shape, Type elementType, StringRef operand)
Get MMAMatrixType and verify construction Invariants.
AffineApplyOp makeComposedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Returns a composed AffineApplyOp by composing map and operands with other AffineApplyOps supplying th...
FailureOr< vector::ContractionOp > getUserContract(Operation *op)
Returns the first user of the op that is vector.contract.
FailureOr< WarpMatrixInfo > getWarpMatrixInfo(Operation *op)
If op is a vector.transfer_write, return the WarpMatrixInfo for the vector operand.
bool canLowerToWarpMatrixOperation(vector::TransferWriteOp op)
Returns the number of bits in a single tile row.
bool isReductionIterator(Attribute attr)
Returns true if attr has "reduction" iterator type semantics.
bool isParallelIterator(Attribute attr)
Returns true if attr has "parallel" iterator type semantics.
void populateVectorContractCanonicalizeMatmulToMMT(RewritePatternSet &patterns, std::function< LogicalResult(vector::ContractionOp)> constraint=[](vector::ContractionOp) { return success();}, PatternBenefit=1)
Canonicalization of a vector.contract a, b, c with row-major matmul semantics to a contraction with M...
Include the generated interface declarations.
void populatePrepareVectorToMMAPatterns(RewritePatternSet &patterns, bool useNvGpu=false)
Patterns to transform vector ops into a canonical form to convert to MMA matrix operations.
LogicalResult getBackwardSlice(Operation *op, SetVector< Operation * > *backwardSlice, const BackwardSliceOptions &options={})
Fills backwardSlice with the computed backward slice (i.e.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
LogicalResult applyPatternsGreedily(Region ®ion, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
llvm::SetVector< T, Vector, Set, N > SetVector
SliceOptions ForwardSliceOptions
LogicalResult convertVectorToNVVMCompatibleMMASync(RewriterBase &rewriter, Operation *rootOp)
Convert vector ops ops nested under rootOp to vector and GPU operaitons compatible with the nvvm....
llvm::TypeSwitch< T, ResultT > TypeSwitch
std::unique_ptr< Pass > createConvertVectorToGPUPass(bool useNvGpu=false)
Convert from vector to GPU ops.
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
LogicalResult convertVectorToMMAOps(RewriterBase &rewriter, Operation *rootOp)
Convert vector ops to MMA matrix operations nested under rootOp.
SetVector< Operation * > topologicalSort(const SetVector< Operation * > &toSort)
Sorts all operations in toSort topologically while also considering region semantics.
void getForwardSlice(Operation *op, SetVector< Operation * > *forwardSlice, const ForwardSliceOptions &options={})
Fills forwardSlice with the computed forward slice (i.e.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
This trait tags element-wise ops on vectors or tensors.