30#include "llvm/ADT/SetVector.h"
31#include "llvm/Support/LogicalResult.h"
32#include "llvm/Support/raw_ostream.h"
37#define GEN_PASS_DEF_XEGPUSGTOLANEDISTRIBUTE
38#include "mlir/Dialect/XeGPU/Transforms/Passes.h.inc"
44#define DEBUG_TYPE "xegpu-sg-to-lane-distribute"
45#define DBGS() (llvm::dbgs() << "[" DEBUG_TYPE "]: ")
50static Value castValueTo(ConversionPatternRewriter &rewriter,
53 if (v.getType() == expectedTy)
56 if (isa<VectorType>(v.getType()) &&
57 v.getType().getNumElements() == expectedTy.getNumElements())
58 return vector::ShapeCastOp::create(rewriter, v.getLoc(), expectedTy, v);
61 auto newOp = UnrealizedConversionCastOp::create(rewriter, v.getLoc(),
63 return newOp.getResult(0);
69static bool isValidSubgroupMultiReductionOp(vector::MultiDimReductionOp op) {
72 if (!resLayout || !resLayout.isForSubgroup())
75 if (op.getType().isIntOrFloat())
76 return op.getReductionDims().size() == 1;
77 VectorType resTy = dyn_cast<VectorType>(op.getType());
81 FailureOr<VectorType> resDistTypeOrFailure =
82 getDistVecTypeBasedOnLaneLayout(resLayout, resTy);
83 if (failed(resDistTypeOrFailure))
85 return op.getReductionDims().size() == 1;
91static bool isReductionLaneLocal(vector::MultiDimReductionOp op) {
93 assert(isValidSubgroupMultiReductionOp(op) &&
"Expecting a valid subgroup "
94 "MultiDimReductionOp");
97 assert(reductionDims.size() == 1 &&
98 "Expecting single reduction dimension for subgroup multi "
100 int64_t reductionDim = reductionDims[0];
102 assert(reductionDim <
static_cast<int64_t>(srcLaneLayout.size()) &&
103 "Expecting a source lane_layout covering the reduction dimension");
104 return srcLaneLayout[reductionDim] == 1;
110 VectorType distributedType) {
111 assert(originalType.getRank() == distributedType.getRank() &&
112 "original and distributed vector types must have the same rank");
114 for (
int64_t i = 0; i < originalType.getRank(); ++i) {
115 if (distributedType.getDimSize(i) != originalType.getDimSize(i))
116 distributedDims.push_back(i);
118 return distributedDims;
123struct SgToLaneCreateNdDesc
124 :
public OpConversionPattern<xegpu::CreateNdDescOp> {
125 using OpConversionPattern<xegpu::CreateNdDescOp>::OpConversionPattern;
128 matchAndRewrite(xegpu::CreateNdDescOp op, OpAdaptor adaptor,
129 ConversionPatternRewriter &rewriter)
const override {
130 xegpu::TensorDescType resultType = op.getType();
132 if (!resultType.getLayout())
135 auto newOp = xegpu::CreateNdDescOp::create(
136 rewriter, op.getLoc(),
TypeRange{resultType.dropLayouts()},
137 op.getOperands(), op.getProperties(),
138 op->getDiscardableAttrDictionary().getValue());
139 rewriter.replaceOp(op, newOp.getResult());
147struct SgToLaneLoadNd :
public OpConversionPattern<xegpu::LoadNdOp> {
148 using OpConversionPattern<xegpu::LoadNdOp>::OpConversionPattern;
151 matchAndRewrite(xegpu::LoadNdOp op, OpAdaptor adaptor,
152 ConversionPatternRewriter &rewriter)
const override {
153 xegpu::DistributeLayoutAttr layout = op.getAnchorLayout();
159 if (op.getTensorDescType().getLayout() != layout)
160 return rewriter.notifyMatchFailure(
161 op,
"conflicting layout attributes on tensor descriptor and anchor");
165 return rewriter.notifyMatchFailure(
166 op,
"xegpu::LoadNdOp require target attribute attached to "
167 "determine transpose "
169 auto supportedLaneResultTyOrFailure =
171 auto expectedLaneResultTyOrFailure =
173 if (failed(supportedLaneResultTyOrFailure))
174 return rewriter.notifyMatchFailure(
175 op,
"unable to compute the lane vector type for LoadNdOp");
176 if (failed(expectedLaneResultTyOrFailure))
177 return rewriter.notifyMatchFailure(
178 op,
"unable to compute expected lane vector type from lane layout");
179 auto newOp = xegpu::LoadNdOp::create(
180 rewriter, op.getLoc(), supportedLaneResultTyOrFailure.value(),
181 adaptor.getTensorDesc(), op.getMixedOffsets(), op.getPackedAttr(),
182 op.getTransposeAttr(), op.getL1HintAttr(), op.getL2HintAttr(),
183 op.getL3HintAttr(),
nullptr);
189 rewriter.replaceOp(op, castValueTo(rewriter, newOp.getResult(),
190 expectedLaneResultTyOrFailure.value()));
198struct SgToLaneStoreNd :
public OpConversionPattern<xegpu::StoreNdOp> {
199 using OpConversionPattern<xegpu::StoreNdOp>::OpConversionPattern;
202 matchAndRewrite(xegpu::StoreNdOp op, OpAdaptor adaptor,
203 ConversionPatternRewriter &rewriter)
const override {
204 xegpu::DistributeLayoutAttr layout = op.getAnchorLayout();
210 if (op.getTensorDescType().getLayout() != layout)
211 return rewriter.notifyMatchFailure(
212 op,
"conflicting layout attributes on tensor descriptor and anchor");
214 if (valueLayout != layout)
215 return rewriter.notifyMatchFailure(
216 op,
"conflicting layout attributes on value and anchor");
217 auto supportedLaneValueTyOrFailure =
219 if (failed(supportedLaneValueTyOrFailure))
220 return rewriter.notifyMatchFailure(
222 "unable to compute lane vector type for StoreNdOp value from tensor "
225 xegpu::StoreNdOp::create(
226 rewriter, op.getLoc(),
228 supportedLaneValueTyOrFailure.value()),
229 adaptor.getTensorDesc(), op.getMixedOffsets(), op.getL1HintAttr(),
230 op.getL2HintAttr(), op.getL3HintAttr(),
nullptr);
231 rewriter.eraseOp(op);
239struct SgToLaneDpas :
public OpConversionPattern<xegpu::DpasOp> {
240 using OpConversionPattern<xegpu::DpasOp>::OpConversionPattern;
243 matchAndRewrite(xegpu::DpasOp op, OpAdaptor adaptor,
244 ConversionPatternRewriter &rewriter)
const override {
246 auto layoutA = cast<xegpu::LayoutAttr>(op.getLayoutAAttr());
247 auto layoutB = cast<xegpu::LayoutAttr>(op.getLayoutBAttr());
248 auto layoutCd = cast<xegpu::LayoutAttr>(op.getLayoutCdAttr());
249 if (!layoutA || !layoutB || !layoutCd)
251 auto laneResultTyOrFailure =
253 auto laneATypeOrFailure =
255 auto laneBTypeOrFailure =
257 auto expectedLaneResultTyOrFailure =
259 if (failed(laneResultTyOrFailure) || failed(laneATypeOrFailure) ||
260 failed(laneBTypeOrFailure))
261 return rewriter.notifyMatchFailure(
262 op,
"failed to calculate supported lane vector types for DpasOp "
264 if (failed(expectedLaneResultTyOrFailure))
265 return rewriter.notifyMatchFailure(
266 op,
"unable to compute expected lane vector type for DpasOp from "
273 const auto *uArchInstruction =
274 dyn_cast<xegpu::uArch::SubgroupMatrixMultiplyAcc>(
275 uArch->getInstruction(
277 if (uArchInstruction) {
278 auto laneAType = laneATypeOrFailure.value();
279 auto laneBType = laneBTypeOrFailure.value();
281 unsigned aPackedBitWidth =
282 laneAType.getElementTypeBitWidth() * laneAType.getNumElements();
283 unsigned bPackedBitWidth =
284 laneBType.getElementTypeBitWidth() * laneBType.getNumElements();
285 unsigned expectedABitSize = uArchInstruction->getPackedFormatBitSizeA();
286 unsigned expectedBBitSize = uArchInstruction->getPackedFormatBitSizeB();
288 if (aPackedBitWidth % expectedABitSize != 0)
289 return rewriter.notifyMatchFailure(
291 "A operand packed bit width must be a multiple of uArch packed "
292 "format requirement");
293 if (bPackedBitWidth % expectedBBitSize != 0)
294 return rewriter.notifyMatchFailure(
296 "B operand packed bit width must be a multiple of uArch packed "
297 "format requirement");
301 auto newOp = xegpu::DpasOp::create(
302 rewriter, op->getLoc(), laneResultTyOrFailure.value(),
304 laneATypeOrFailure.value()),
306 laneBTypeOrFailure.value()),
308 laneResultTyOrFailure.value()),
312 rewriter.replaceOp(op, castValueTo(rewriter, newOp.getResult(),
313 expectedLaneResultTyOrFailure.value()));
320struct SgToLaneElementWise :
public ConversionPattern {
322 : ConversionPattern(MatchAnyOpTypeTag(), 1, ctx) {}
326 ConversionPatternRewriter &rewriter)
const override {
333 return rewriter.notifyMatchFailure(
334 op,
"operation result is not a vector type");
336 xegpu::DistributeLayoutAttr layout =
338 if (!layout || !layout.isForSubgroup())
339 return rewriter.notifyMatchFailure(
340 op,
"operation result does not have subgroup distribute layout");
342 auto laneShapeOrFailure =
345 if (failed(laneShapeOrFailure))
346 return rewriter.notifyMatchFailure(
347 op,
"unable to compute lane vector type from the layout");
349 VectorType newResultType = laneShapeOrFailure.value();
351 state.addOperands(operands);
352 state.addTypes(newResultType);
355 if (!isa<xegpu::DistributeLayoutAttr>(attr.getValue()))
356 state.addAttribute(attr.getName(), attr.getValue());
359 Operation *newOp = rewriter.create(state);
361 rewriter.replaceOp(op, newOp->
getResult(0));
373struct SgToLaneArithConstant :
public OpConversionPattern<arith::ConstantOp> {
374 using OpConversionPattern<arith::ConstantOp>::OpConversionPattern;
377 matchAndRewrite(arith::ConstantOp op, OpAdaptor adaptor,
378 ConversionPatternRewriter &rewriter)
const override {
379 auto resultType = dyn_cast<VectorType>(op.getType());
384 auto denseAttr = dyn_cast<DenseElementsAttr>(op.getValue());
386 return rewriter.notifyMatchFailure(
387 op,
"only dense vector constants are supported");
389 xegpu::DistributeLayoutAttr layout =
391 if (!layout || !layout.isForSubgroup())
392 return rewriter.notifyMatchFailure(
393 op,
"operation result does not have subgroup distribute layout");
395 auto laneShapeOrFailure =
398 if (failed(laneShapeOrFailure))
399 return rewriter.notifyMatchFailure(
400 op,
"unable to compute lane vector type from the layout");
402 VectorType newResultType = laneShapeOrFailure.value();
407 if (denseAttr.isSplat()) {
408 auto scalarValue = denseAttr.getSplatValue<
Attribute>();
411 arith::ConstantOp::create(rewriter, loc, newResultType, newDenseAttr);
412 rewriter.replaceOp(op, newOp.
getResult());
419 arith::ConstantOp::create(rewriter, loc, resultType, denseAttr);
421 Value laneId = gpu::LaneIdOp::create(rewriter, loc, rewriter.getIndexType(),
422 mlir::IntegerAttr());
423 auto maybeCoordsVec = layout.computeDistributedCoords(
424 rewriter, loc, laneId, resultType.getShape());
425 if (failed(maybeCoordsVec))
426 return rewriter.notifyMatchFailure(
427 op,
"failed to compute distributed coordinates from layout");
432 int64_t rank = newResultType.getRank();
438 for (
int64_t d = 0; d < rank; d++)
439 blockGridShape[d] = distShape[d] / laneData[d];
442 auto blockType = VectorType::get(laneData, newResultType.getElementType());
447 rewriter, loc, newResultType, rewriter.getZeroAttr(newResultType));
449 for (
auto [blockIdx, blockStart] : llvm::enumerate(coordsVec)) {
457 for (
int64_t d = 0; d < rank; d++)
459 rewriter, loc, blockStart[d],
461 blockElems.push_back(vector::ExtractOp::create(
462 rewriter, loc, fullConst.getResult(), pos));
469 vector::FromElementsOp::create(rewriter, loc, blockType, blockElems);
473 for (
int64_t d = 0; d < rank; d++)
474 offsets[d] = blockGridPos[d] * laneData[d];
475 result = vector::InsertStridedSliceOp::create(rewriter, loc, block,
476 result, offsets, strides);
479 rewriter.replaceOp(op,
result);
485struct SgToLanePrefetchNd :
public OpConversionPattern<xegpu::PrefetchNdOp> {
486 using OpConversionPattern<xegpu::PrefetchNdOp>::OpConversionPattern;
489 matchAndRewrite(xegpu::PrefetchNdOp op, OpAdaptor adaptor,
490 ConversionPatternRewriter &rewriter)
const override {
491 xegpu::DistributeLayoutAttr layout = op.getAnchorLayout();
496 xegpu::PrefetchNdOp::create(rewriter, op.getLoc(), adaptor.getTensorDesc(),
497 op.getMixedOffsets(), op.getL1HintAttr(),
498 op.getL2HintAttr(), op.getL3HintAttr(),
500 rewriter.eraseOp(op);
530struct SgToLaneLoadGather :
public OpConversionPattern<xegpu::LoadGatherOp> {
531 using OpConversionPattern<xegpu::LoadGatherOp>::OpConversionPattern;
534 matchAndRewrite(xegpu::LoadGatherOp op, OpAdaptor adaptor,
535 ConversionPatternRewriter &rewriter)
const override {
536 xegpu::DistributeLayoutAttr layout = op.getAnchorLayout();
540 VectorType origResultTy = op.getValueType();
545 int effectiveVecRank = 1;
546 ArrayRef<int64_t> shape = origResultTy.getShape();
548 shape.take_front(origResultTy.getRank() - effectiveVecRank),
549 [](int64_t d) { return d != 1; }))
550 return rewriter.notifyMatchFailure(
551 op,
"Only unit dimensions allowed for the leading "
552 "dimensions of the load vector!");
554 auto distResultTyOrFailure =
556 if (
failed(distResultTyOrFailure))
557 return rewriter.notifyMatchFailure(
558 op,
"unable to compute expected lane vector type from lane layout");
560 VectorType distResultTy = distResultTyOrFailure.value();
561 VectorType distResultTy1D = VectorType::get({distResultTy.getNumElements()},
562 distResultTy.getElementType());
565 Value distOffsets = adaptor.getOffsets();
566 auto distOffsetsTy = cast<VectorType>(distOffsets.
getType());
567 VectorType offsetsTy1D = VectorType::get({distOffsetsTy.getNumElements()},
568 distOffsetsTy.getElementType());
569 distOffsets = castValueTo(
572 Value distMask = adaptor.getMask();
573 auto distMaskTy = cast<VectorType>(distMask.
getType());
574 VectorType maskTy1D = VectorType::get({distMaskTy.getNumElements()},
575 distMaskTy.getElementType());
579 Value distSource = adaptor.getSource();
580 auto newOp = xegpu::LoadGatherOp::create(
581 rewriter, op.getLoc(), distResultTy1D, distSource, distOffsets,
582 distMask, op.getL1HintAttr(), op.getL2HintAttr(), op.getL3HintAttr(),
586 if (distResultTy1D != distResultTy)
589 rewriter.replaceOp(op,
result);
598struct SgToLaneVectorReduction
599 :
public OpConversionPattern<vector::ReductionOp> {
600 using OpConversionPattern<vector::ReductionOp>::OpConversionPattern;
603 matchAndRewrite(vector::ReductionOp op, OpAdaptor adaptor,
604 ConversionPatternRewriter &rewriter)
const override {
608 if (!layout || !layout.isForSubgroup())
611 VectorType srcVecType = op.getSourceVectorType();
613 if (srcVecType.getRank() != 1)
614 return rewriter.notifyMatchFailure(
615 op,
"Only rank 1 reductions can be distributed.");
617 if (layout.getRank() != srcVecType.getRank())
618 return rewriter.notifyMatchFailure(
619 op,
"Layout rank does not match vector rank.");
622 int64_t sgSize = layout.getEffectiveLaneLayoutAsInt()[0];
626 return rewriter.notifyMatchFailure(
627 op,
"xegpu::ReductionOp require target attribute attached to "
628 "determine subgroup size");
631 if (sgSize != uArch->getSubgroupSize() ||
632 srcVecType.getShape()[0] % sgSize != 0)
633 return rewriter.notifyMatchFailure(op,
634 "Invalid layout or reduction vector "
635 "dimension must match subgroup size.");
637 if (!op.getType().isIntOrFloat())
638 return rewriter.notifyMatchFailure(
639 op,
"Reduction distribution currently only supports floats and "
643 Value laneValVec = adaptor.getVector();
648 op.getKind(), sgSize, op.getFastmathAttr());
651 if (adaptor.getAcc())
653 rewriter, op.getLoc(), op.getKind(), fullReduce, adaptor.getAcc(),
654 op.getFastmathAttr());
656 rewriter.replaceOp(op, fullReduce);
665struct SgToLaneMultiDimReduction
666 :
public OpConversionPattern<vector::MultiDimReductionOp> {
667 using OpConversionPattern<vector::MultiDimReductionOp>::OpConversionPattern;
670 matchAndRewrite(vector::MultiDimReductionOp op, OpAdaptor adaptor,
671 ConversionPatternRewriter &rewriter)
const override {
673 ArrayRef<int64_t> reductionDims = op.getReductionDims();
674 assert(reductionDims.size() == 1 &&
675 "Expecting single reduction dimension for subgroup multi "
678 VectorType sourceType = op.getSourceVectorType();
679 int64_t rank = sourceType.getRank();
681 ArrayRef<int64_t> shape = sourceType.getShape();
682 if (llvm::any_of(shape.take_front(rank - 2),
683 [](int64_t d) { return d != 1; }))
684 return rewriter.notifyMatchFailure(
685 op,
"only unit leading dimensions are supported for "
686 "multi_reduction with rank > 2");
688 int64_t reductionDim = reductionDims[0];
689 int64_t reductionDimSize = sourceType.getShape()[reductionDim];
692 if (op.getType().isIntOrFloat()) {
695 adaptor.getSource(), op.getKind(),
696 reductionDimSize, op.getFastmathAttr());
698 if (adaptor.getAcc())
701 op.getFastmathAttr());
702 }
else if (reductionDimSize == 1) {
704 Value acc = adaptor.getAcc();
705 Value src = vector::ShapeCastOp::create(
706 rewriter, op.getLoc(), acc.
getType(), adaptor.getSource());
708 src, acc, op.getFastmathAttr());
709 }
else if (isReductionLaneLocal(op)) {
716 reductionDim, op.getLoc(), rewriter, op.getFastmathAttr());
721 reductionDim, reductionDimSize, op.getLoc(), rewriter,
722 op.getFastmathAttr());
724 rewriter.replaceOp(op,
result);
733 ConversionPatternRewriter &rewriter,
Location loc,
736 Value laneId = gpu::LaneIdOp::create(rewriter, loc, rewriter.getIndexType(),
737 mlir::IntegerAttr());
739 layout.computeDistributedCoords(rewriter, loc, laneId, payloadShape);
742 assert(maybeCoords.value().size() == 1 &&
743 "Expected one set of distributed offsets");
747 return llvm::map_to_vector(ofrVec, llvm::CastTo<Value>);
751struct SgToLaneLoadMatrix :
public OpConversionPattern<xegpu::LoadMatrixOp> {
752 using OpConversionPattern<xegpu::LoadMatrixOp>::OpConversionPattern;
755 matchAndRewrite(xegpu::LoadMatrixOp op, OpAdaptor adaptor,
756 ConversionPatternRewriter &rewriter)
const override {
757 auto layout = op.getLayoutAttr();
762 VectorType sgPayloadTy = dyn_cast<VectorType>(op.getResult().getType());
764 return rewriter.notifyMatchFailure(
765 op,
"the matrix op payload must be a vector type");
767 auto loc = op.getLoc();
768 auto offsets = op.getMixedOffsets();
770 return rewriter.notifyMatchFailure(op,
"the load op must have offsets");
772 FailureOr<VectorType> distPayloadTyOrFailure =
774 if (
failed(distPayloadTyOrFailure))
775 return rewriter.notifyMatchFailure(
776 op,
"Failed to distribute matrix op payload based on layout.");
778 SmallVector<Value> offsetsAsValues =
781 SmallVector<Value> newCoords = offsetsAsValues;
782 if (!op.getSubgroupBlockIoAttr()) {
783 newCoords = computeDistributedCoordsForMatrixOp(
784 rewriter, loc, layout, sgPayloadTy.getShape(), offsetsAsValues);
785 if (newCoords.empty())
786 return rewriter.notifyMatchFailure(
787 op,
"Failed to compute distributed coordinates.");
790 SmallVector<int64_t> newConstOffsets(op.getConstOffsets().size(),
791 ShapedType::kDynamic);
793 rewriter.getDenseI64ArrayAttr(newConstOffsets);
795 auto newOp = xegpu::LoadMatrixOp::create(
796 rewriter, loc, *distPayloadTyOrFailure, adaptor.getMemDesc(),
797 ValueRange(newCoords), newConstOffsetsAttr, op.getSubgroupBlockIoAttr(),
798 xegpu::DistributeLayoutAttr{});
799 rewriter.replaceOp(op, newOp.
getResult());
805struct SgToLaneVectorTranspose
806 :
public OpConversionPattern<vector::TransposeOp> {
807 using OpConversionPattern<vector::TransposeOp>::OpConversionPattern;
810 matchAndRewrite(vector::TransposeOp op, OpAdaptor adaptor,
811 ConversionPatternRewriter &rewriter)
const override {
812 xegpu::DistributeLayoutAttr sourceLayout =
814 xegpu::DistributeLayoutAttr resultLayout =
816 if (!sourceLayout || !resultLayout)
817 return rewriter.notifyMatchFailure(
818 op,
"the source or result vector of the transpose op lacks layout "
820 ArrayRef<int64_t> perm = op.getPermutation();
822 if (!resultLayout.isTransposeOf(sourceLayout, perm,
823 xegpu::LayoutKind::Lane))
824 return rewriter.notifyMatchFailure(
825 op,
"the source or result vector layouts must be transposes of "
827 FailureOr<VectorType> distributedResultTypeOrFailure =
829 if (
failed(distributedResultTypeOrFailure))
830 return rewriter.notifyMatchFailure(
831 op,
"Failed to distribute the result vector type in "
832 "vector::Transpose op");
833 auto newOp = vector::TransposeOp::create(rewriter, op.getLoc(),
834 adaptor.getVector(), perm);
835 rewriter.replaceOp(op, castValueTo(rewriter, newOp.
getResult(),
836 distributedResultTypeOrFailure.value()));
843struct SgToLaneVectorBitcast :
public OpConversionPattern<vector::BitCastOp> {
844 using OpConversionPattern<vector::BitCastOp>::OpConversionPattern;
847 matchAndRewrite(vector::BitCastOp op, OpAdaptor adaptor,
848 ConversionPatternRewriter &rewriter)
const override {
849 xegpu::DistributeLayoutAttr resultLayout =
852 return rewriter.notifyMatchFailure(
853 op,
"result vector of the bitcast op lacks layout attribute");
854 FailureOr<VectorType> distributedResultTypeOrFailure =
856 if (
failed(distributedResultTypeOrFailure))
857 return rewriter.notifyMatchFailure(
858 op,
"Failed to distribute the result vector type in "
859 "vector::BitCast op");
860 auto newOp = vector::BitCastOp::create(
861 rewriter, op.getLoc(), distributedResultTypeOrFailure.value(),
862 adaptor.getSource());
863 rewriter.replaceOp(op, newOp.
getResult());
906template <
typename OpType,
907 typename = std::enable_if_t<llvm::is_one_of<
908 OpType, vector::CreateMaskOp, vector::ConstantMaskOp>::value>>
909struct SgToLaneCreateMask :
public OpConversionPattern<OpType> {
910 using OpConversionPattern<OpType>::OpConversionPattern;
913 matchAndRewrite(OpType op,
typename OpType::Adaptor adaptor,
914 ConversionPatternRewriter &rewriter)
const override {
915 xegpu::DistributeLayoutAttr layout =
917 if (!layout || !layout.isForSubgroup())
918 return rewriter.notifyMatchFailure(
919 op,
"operation result does not have subgroup distribute layout");
921 VectorType origType = op.getType();
922 FailureOr<VectorType> distTypeOrFailure =
924 if (
failed(distTypeOrFailure))
925 return rewriter.notifyMatchFailure(
926 op,
"unable to compute lane vector type from the layout");
928 VectorType distType = distTypeOrFailure.value();
929 Location loc = op.getLoc();
932 SmallVector<Value> origBounds;
933 if constexpr (std::is_same_v<OpType, vector::CreateMaskOp>) {
934 origBounds.append(op.getOperands().begin(), op.getOperands().end());
936 auto dimSizes = op.getMaskDimSizesAttr().asArrayRef();
937 for (
auto dimSize : dimSizes)
938 origBounds.push_back(
942 ArrayRef<int64_t> origShape = origType.getShape();
945 Value laneId = gpu::LaneIdOp::create(rewriter, loc, rewriter.getIndexType(),
946 mlir::IntegerAttr());
947 auto maybeCoordsVec =
948 layout.computeDistributedCoords(rewriter, loc, laneId, origShape);
949 if (
failed(maybeCoordsVec))
950 return rewriter.notifyMatchFailure(
951 op,
"failed to compute distributed coordinates from layout");
953 SmallVector<SmallVector<Value>> laneDataCoords = maybeCoordsVec.value();
954 SmallVector<int64_t> laneData = layout.getEffectiveLaneDataAsInt();
955 ArrayRef<int64_t> distShape = distType.getShape();
956 int64_t rank = distType.getRank();
957 int64_t numElements = distType.getNumElements();
959 if (
static_cast<int64_t
>(laneData.size()) != rank ||
961 return rewriter.notifyMatchFailure(
962 op,
"lane_data does not tile the distributed vector");
965 assert(
static_cast<int64_t
>(laneDataCoords.size()) *
968 "number of coordinate sets must match number of lane_data blocks");
971 SmallVector<SmallVector<int64_t>> staticLaneDataOffsetsOrig =
972 layout.computeStaticDistributedCoords(0, origShape);
973 if (staticLaneDataOffsetsOrig.empty() ||
974 staticLaneDataOffsetsOrig.size() != laneDataCoords.size())
975 return rewriter.notifyMatchFailure(
976 op,
"static and dynamic coordinates disagree on the distribution "
979 SmallVector<int64_t> unitTile(rank, 1);
980 int64_t linearLaneDataIdx = 0;
985 SmallVector<SmallVector<int64_t>> staticElemOffset(
986 rank, SmallVector<int64_t>(numElements));
988 for (SmallVector<int64_t> laneDataOffsetDist :
989 StaticTileOffsetRange(distShape, laneData)) {
990 ArrayRef<int64_t> staticLaneDataOffsetOrig =
991 staticLaneDataOffsetsOrig[linearLaneDataIdx++];
993 for (SmallVector<int64_t> elemOffsetInLaneData :
994 StaticTileOffsetRange(laneData, unitTile)) {
996 SmallVector<int64_t> elementOffsetDist(rank);
997 for (int64_t d = 0; d < rank; d++)
998 elementOffsetDist[d] =
999 laneDataOffsetDist[d] + elemOffsetInLaneData[d];
1000 int64_t elemLinearizedIdxDist =
1001 linearize(elementOffsetDist, distStrides);
1002 for (int64_t d = 0; d < rank; d++)
1003 staticElemOffset[d][elemLinearizedIdxDist] =
1004 staticLaneDataOffsetOrig[d] + elemOffsetInLaneData[d];
1013 auto flatIndexType = VectorType::get(numElements, rewriter.getIndexType());
1015 for (int64_t d = 0; d < rank; d++) {
1017 if (constBound && *constBound >= origShape[d])
1020 Value materializedStaticOffset = arith::ConstantOp::create(
1021 rewriter, loc, rewriter.getIndexVectorAttr(staticElemOffset[d]));
1024 Value validDimExtent = arith::SubIOp::create(rewriter, loc, origBounds[d],
1025 laneDataCoords[0][d]);
1027 Value validDimExtentPerElement = vector::BroadcastOp::create(
1028 rewriter, loc, flatIndexType, validDimExtent);
1029 Value elementMaskInDim = arith::CmpIOp::create(
1030 rewriter, loc, arith::CmpIPredicate::slt, materializedStaticOffset,
1031 validDimExtentPerElement);
1034 inBounds = inBounds ? arith::AndIOp::create(rewriter, loc, inBounds,
1042 rewriter.replaceOp(op, arith::ConstantOp::create(
1043 rewriter, loc, distType,
1048 rewriter.createOrFold<vector::ShapeCastOp>(loc, distType, inBounds);
1049 rewriter.replaceOp(op, resMask);
1055struct SgToLaneStoreMatrix :
public OpConversionPattern<xegpu::StoreMatrixOp> {
1056 using OpConversionPattern<xegpu::StoreMatrixOp>::OpConversionPattern;
1059 matchAndRewrite(xegpu::StoreMatrixOp op, OpAdaptor adaptor,
1060 ConversionPatternRewriter &rewriter)
const override {
1061 auto layout = op.getLayoutAttr();
1066 VectorType sgPayloadTy = dyn_cast<VectorType>(op.getData().getType());
1068 return rewriter.notifyMatchFailure(
1069 op,
"the matrix op payload must be a vector type");
1071 auto loc = op.getLoc();
1072 auto offsets = op.getMixedOffsets();
1073 if (offsets.empty())
1074 return rewriter.notifyMatchFailure(op,
"the store op must have offsets");
1076 FailureOr<VectorType> distPayloadTyOrFailure =
1078 if (
failed(distPayloadTyOrFailure))
1079 return rewriter.notifyMatchFailure(
1080 op,
"Failed to distribute matrix op payload based on layout.");
1082 SmallVector<Value> offsetsAsValues =
1085 SmallVector<Value> newCoords = offsetsAsValues;
1086 if (!op.getSubgroupBlockIoAttr()) {
1087 newCoords = computeDistributedCoordsForMatrixOp(
1088 rewriter, loc, layout, sgPayloadTy.getShape(), offsetsAsValues);
1089 if (newCoords.empty())
1090 return rewriter.notifyMatchFailure(
1091 op,
"Failed to compute distributed coordinates.");
1094 SmallVector<int64_t> newConstOffsets(op.getConstOffsets().size(),
1095 ShapedType::kDynamic);
1097 rewriter.getDenseI64ArrayAttr(newConstOffsets);
1099 xegpu::StoreMatrixOp::create(
1102 distPayloadTyOrFailure.value()),
1103 adaptor.getMemDesc(),
ValueRange(newCoords), newConstOffsetsAttr,
1104 op.getSubgroupBlockIoAttr(), xegpu::DistributeLayoutAttr{});
1105 rewriter.eraseOp(op);
1136struct SgToLaneStoreScatter
1137 :
public OpConversionPattern<xegpu::StoreScatterOp> {
1138 using OpConversionPattern<xegpu::StoreScatterOp>::OpConversionPattern;
1141 matchAndRewrite(xegpu::StoreScatterOp op, OpAdaptor adaptor,
1142 ConversionPatternRewriter &rewriter)
const override {
1143 xegpu::DistributeLayoutAttr layout = op.getAnchorLayout();
1147 VectorType origValueTy = op.getValueType();
1152 int effectiveVecRank = 1;
1153 ArrayRef<int64_t> shape = origValueTy.getShape();
1154 if (llvm::any_of(shape.take_front(origValueTy.getRank() - effectiveVecRank),
1155 [](int64_t d) { return d != 1; }))
1156 return rewriter.notifyMatchFailure(
1157 op,
"Only unit dimensions allowed for the leading "
1158 "dimensions of the store vector!");
1160 auto distValueTyOrFailure =
1162 if (
failed(distValueTyOrFailure))
1163 return rewriter.notifyMatchFailure(
1164 op,
"unable to compute expected lane vector type from lane layout");
1166 VectorType distValueTy = distValueTyOrFailure.value();
1167 VectorType distValueTy1D = VectorType::get({distValueTy.getNumElements()},
1168 distValueTy.getElementType());
1170 Value distValue = adaptor.getValue();
1171 if (distValue.
getType() != distValueTy1D)
1176 Value distOffsets = adaptor.getOffsets();
1177 auto distOffsetsTy = cast<VectorType>(distOffsets.
getType());
1178 VectorType offsetsTy1D = VectorType::get({distOffsetsTy.getNumElements()},
1179 distOffsetsTy.getElementType());
1180 distOffsets = castValueTo(
1183 Value distMask = adaptor.getMask();
1184 auto distMaskTy = cast<VectorType>(distMask.
getType());
1185 VectorType maskTy1D = VectorType::get({distMaskTy.getNumElements()},
1186 distMaskTy.getElementType());
1190 Value distDest = adaptor.getDest();
1191 xegpu::StoreScatterOp::create(rewriter, op.getLoc(), distValue, distDest,
1192 distOffsets, distMask, op.getL1HintAttr(),
1193 op.getL2HintAttr(), op.getL3HintAttr(),
1196 rewriter.eraseOp(op);
1205struct SgToLaneVectorStep :
public OpConversionPattern<vector::StepOp> {
1206 using OpConversionPattern<vector::StepOp>::OpConversionPattern;
1209 matchAndRewrite(vector::StepOp op, OpAdaptor adaptor,
1210 ConversionPatternRewriter &rewriter)
const override {
1211 xegpu::DistributeLayoutAttr resultLayout =
1213 if (!resultLayout || !resultLayout.isForSubgroup())
1214 return rewriter.notifyMatchFailure(
1215 op,
"the result vector of the step op lacks subgroup layout");
1217 auto loc = op.getLoc();
1218 auto stepResultVecTy = op.getResult().getType();
1219 auto laneShapeOrFailure =
1221 if (
failed(laneShapeOrFailure))
1222 return rewriter.notifyMatchFailure(
1223 op,
"unable to compute lane vector type from the layout");
1224 VectorType newVecTy = laneShapeOrFailure.value();
1226 Value laneId = gpu::LaneIdOp::create(rewriter, loc, rewriter.getIndexType(),
1227 mlir::IntegerAttr());
1228 auto laneDataBlockCoords = resultLayout.computeDistributedCoords(
1229 rewriter, loc, laneId, stepResultVecTy.getShape());
1230 if (
failed(laneDataBlockCoords))
1231 return rewriter.notifyMatchFailure(
1232 op,
"failed to compute lane data block coordinates");
1234 auto laneDataBlockCoordsVec = laneDataBlockCoords.value();
1235 auto laneDataBlockLength = resultLayout.getEffectiveLaneDataAsInt()[0];
1236 assert(
static_cast<int64_t
>(laneDataBlockCoordsVec.size()) ==
1237 newVecTy.getNumElements() / laneDataBlockLength);
1238 SmallVector<Value> stepVals;
1246 for (
auto &laneDataBlockCoords : laneDataBlockCoordsVec) {
1247 auto laneDataBlockStartCoord = laneDataBlockCoords[0];
1248 stepVals.push_back(laneDataBlockStartCoord);
1249 for (
int i = 1; i < laneDataBlockLength; ++i) {
1251 stepVals.push_back(arith::AddIOp::create(
1252 rewriter, loc, laneDataBlockStartCoord, offset));
1255 assert(
static_cast<int64_t
>(stepVals.size()) == newVecTy.getNumElements() &&
1256 "Expecting the number of step values to match the number of "
1257 "elements in the vector");
1259 vector::FromElementsOp::create(rewriter, loc, newVecTy, stepVals);
1260 rewriter.replaceOp(op, stepOpVal);
1267struct SgToLaneVectorExtract :
public OpConversionPattern<vector::ExtractOp> {
1268 using OpConversionPattern<vector::ExtractOp>::OpConversionPattern;
1271 matchAndRewrite(vector::ExtractOp op, OpAdaptor adaptor,
1272 ConversionPatternRewriter &rewriter)
const override {
1274 auto resultType = dyn_cast<VectorType>(op.getType());
1276 return rewriter.notifyMatchFailure(op,
"scalar extract not supported");
1278 xegpu::DistributeLayoutAttr layout =
1280 if (!layout || !layout.isForSubgroup())
1285 auto laneLayout = layout.getEffectiveLaneLayoutAsInt();
1286 if (llvm::any_of(ArrayRef<int64_t>(laneLayout).drop_back(1),
1287 [](int64_t v) {
return v != 1; }))
1288 return rewriter.notifyMatchFailure(
1289 op,
"only innermost dimension distribution is supported for "
1292 auto newOp = vector::ExtractOp::create(
1293 rewriter, op.getLoc(), adaptor.getSource(), op.getMixedPosition());
1294 rewriter.replaceOp(op, newOp.
getResult());
1300struct SgToLaneVectorShapeCast
1301 :
public OpConversionPattern<vector::ShapeCastOp> {
1302 using OpConversionPattern<vector::ShapeCastOp>::OpConversionPattern;
1305 matchAndRewrite(vector::ShapeCastOp op, OpAdaptor adaptor,
1306 ConversionPatternRewriter &rewriter)
const override {
1307 xegpu::DistributeLayoutAttr resultLayout =
1309 if (!resultLayout || !resultLayout.isForSubgroup())
1310 return rewriter.notifyMatchFailure(
1311 op,
"the result vector of the shape_cast op lacks subgroup layout");
1314 resultLayout, op.getResultVectorType());
1315 if (
failed(resultDistTypeOrFailure))
1316 return rewriter.notifyMatchFailure(
1317 op,
"failed to get distributed vector type for result");
1319 Value source = adaptor.getSource();
1320 auto newShapeCast = vector::ShapeCastOp::create(
1321 rewriter, op.getLoc(), resultDistTypeOrFailure.value(), source);
1322 rewriter.replaceOp(op, newShapeCast);
1330struct SgToLaneVectorExtractStridedSlice
1331 :
public OpConversionPattern<vector::ExtractStridedSliceOp> {
1332 using OpConversionPattern<vector::ExtractStridedSliceOp>::OpConversionPattern;
1335 matchAndRewrite(vector::ExtractStridedSliceOp op, OpAdaptor adaptor,
1336 ConversionPatternRewriter &rewriter)
const override {
1337 xegpu::DistributeLayoutAttr resultLayout =
1339 if (!resultLayout || !resultLayout.isForSubgroup())
1342 VectorType resultType = op.getType();
1343 auto distResultTyOrFailure =
1345 if (
failed(distResultTyOrFailure))
1346 return rewriter.notifyMatchFailure(
1347 op,
"unable to compute distributed vector type from lane layout");
1348 VectorType distResultTy = *distResultTyOrFailure;
1350 SmallVector<int64_t> distributedDims =
1351 getDistributedDims(resultType, distResultTy);
1354 int64_t sourceRank = op.getSourceVectorType().getRank();
1355 SmallVector<Attribute> updatedSizes =
1356 llvm::map_to_vector(op.getSizes(), [](Attribute attr) { return attr; });
1357 SmallVector<Attribute> updatedOffsets = llvm::map_to_vector(
1358 op.getOffsets(), [](Attribute attr) { return attr; });
1359 SmallVector<Attribute> updatedStrides = llvm::map_to_vector(
1360 op.getStrides(), [](Attribute attr) { return attr; });
1361 for (int64_t i = op.getSizes().size(); i < sourceRank; ++i) {
1362 updatedSizes.push_back(
1363 rewriter.getI64IntegerAttr(op.getSourceVectorType().getDimSize(i)));
1364 updatedOffsets.push_back(rewriter.getI64IntegerAttr(0));
1365 updatedStrides.push_back(rewriter.getI64IntegerAttr(1));
1370 if (!distributedDims.empty()) {
1372 if (!sourceLayout || sourceLayout.getEffectiveLaneLayoutAsInt().empty())
1373 return rewriter.notifyMatchFailure(
1374 op,
"source of extract_strided_slice lacks distribution layout");
1375 SmallVector<int64_t> laneLayout =
1376 sourceLayout.getEffectiveLaneLayoutAsInt();
1377 SmallVector<int64_t> laneData = sourceLayout.getEffectiveLaneDataAsInt();
1378 ArrayRef<int64_t> sourceShape = op.getSourceVectorType().getShape();
1379 for (int64_t distDim : distributedDims) {
1380 int64_t lanes = laneLayout[distDim];
1381 if (lanes == 0 || sourceShape[distDim] % lanes != 0)
1382 return rewriter.notifyMatchFailure(
1383 op,
"source size along a distributed dim is not a multiple of "
1385 int64_t distrDimOffset =
1386 cast<IntegerAttr>(updatedOffsets[distDim]).getInt();
1387 if (distrDimOffset % (lanes * laneData[distDim]) != 0)
1388 return rewriter.notifyMatchFailure(
1389 op,
"offset along a distributed dim is not a multiple of its "
1391 updatedSizes[distDim] =
1392 rewriter.getI64IntegerAttr(distResultTy.getDimSize(distDim));
1393 updatedOffsets[distDim] =
1394 rewriter.getI64IntegerAttr(distrDimOffset / lanes);
1398 auto newOp = vector::ExtractStridedSliceOp::create(
1399 rewriter, op.getLoc(), distResultTy, adaptor.getSource(),
1400 ArrayAttr::get(rewriter.getContext(), updatedOffsets),
1401 ArrayAttr::get(rewriter.getContext(), updatedSizes),
1402 ArrayAttr::get(rewriter.getContext(), updatedStrides));
1403 rewriter.replaceOp(op, newOp.
getResult());
1465struct SgToLaneBroadcast :
public OpConversionPattern<vector::BroadcastOp> {
1466 using OpConversionPattern<vector::BroadcastOp>::OpConversionPattern;
1469 matchAndRewrite(vector::BroadcastOp op, OpAdaptor adaptor,
1470 ConversionPatternRewriter &rewriter)
const override {
1471 xegpu::DistributeLayoutAttr resultLayout =
1473 if (!resultLayout || !resultLayout.isForSubgroup())
1474 return rewriter.notifyMatchFailure(
1475 op,
"result does not have subgroup distribute layout");
1477 VectorType destType = op.getResultVectorType();
1478 VectorType sourceType = dyn_cast<VectorType>(op.getSourceType());
1480 xegpu::DistributeLayoutAttr sourceLayout =
1484 int64_t rankDiff = destType.getRank() - sourceType.getRank();
1487 if (!sourceLayout || !sourceLayout.isSliceOf(resultLayout))
1489 "broadcast source layout must be a slice of result layout");
1490 }
else if (rankDiff == 0) {
1492 auto broadcastUnitDimsSet = op.computeBroadcastedUnitDims();
1493 SmallVector<int64_t> broadcastUnitDims(broadcastUnitDimsSet.begin(),
1494 broadcastUnitDimsSet.end());
1495 assert(sourceLayout.isEqualTo(
1496 sourceLayout.setUnitDimData(broadcastUnitDims)) &&
1497 "The sg_data for unit dimensions should be set as 1");
1498 sourceLayout = sourceLayout.setUnitDimLayout(broadcastUnitDims);
1503 return rewriter.notifyMatchFailure(
1504 op,
"broadcast from scalar must not have a layout attribute");
1509 if (
failed(destDistType))
1510 return rewriter.notifyMatchFailure(
1511 op,
"failed to distribute the result vector type");
1513 Value source = adaptor.getSource();
1515 if (source.
getType() == destDistType.value()) {
1516 rewriter.replaceOp(op, source);
1520 auto newOp = vector::BroadcastOp::create(rewriter, op.getLoc(),
1521 destDistType.value(), source);
1522 rewriter.replaceOp(op, newOp);
1530struct SgToLaneVectorInsertStridedSlice
1531 :
public OpConversionPattern<vector::InsertStridedSliceOp> {
1532 using OpConversionPattern<vector::InsertStridedSliceOp>::OpConversionPattern;
1535 matchAndRewrite(vector::InsertStridedSliceOp op, OpAdaptor adaptor,
1536 ConversionPatternRewriter &rewriter)
const override {
1537 xegpu::DistributeLayoutAttr resultLayout =
1539 if (!resultLayout || !resultLayout.isForSubgroup())
1542 VectorType destType = op.getDestVectorType();
1543 auto distDestTyOrFailure =
1545 if (
failed(distDestTyOrFailure))
1546 return rewriter.notifyMatchFailure(
1547 op,
"unable to compute distributed vector type from lane layout");
1548 VectorType distDestTy = *distDestTyOrFailure;
1550 SmallVector<int64_t> destDistributedDims =
1551 getDistributedDims(destType, distDestTy);
1553 SmallVector<Attribute> updatedOffsets = llvm::map_to_vector(
1554 op.getOffsets(), [](Attribute attr) { return attr; });
1556 if (!destDistributedDims.empty()) {
1557 if (destDistributedDims.size() != 1)
1558 return rewriter.notifyMatchFailure(
1559 op,
"only single dimension distribution is supported");
1560 int64_t destDistDim = destDistributedDims[0];
1562 VectorType srcType = op.getSourceVectorType();
1564 int64_t sourceDistDim =
1565 destDistDim - (destType.getRank() - srcType.getRank());
1566 if (sourceDistDim < 0)
1567 return rewriter.notifyMatchFailure(
1568 op,
"distributed dimension must be in the last k dims of dest");
1572 if (!destLayout || !sourceLayout ||
1573 destLayout.getEffectiveLaneLayoutAsInt().empty() ||
1574 sourceLayout.getEffectiveLaneLayoutAsInt().empty())
1575 return rewriter.notifyMatchFailure(
1576 op,
"source or dest of insert_strided_slice lacks distribution "
1579 auto destLaneData = destLayout.getEffectiveLaneDataAsInt();
1580 auto sourceLaneData = sourceLayout.getEffectiveLaneDataAsInt();
1583 if ((destDistDim <
static_cast<int64_t
>(destLaneData.size()) &&
1584 destLaneData[destDistDim] != 1) ||
1585 (sourceDistDim <
static_cast<int64_t
>(sourceLaneData.size()) &&
1586 sourceLaneData[sourceDistDim] != 1))
1587 return rewriter.notifyMatchFailure(
1588 op,
"expecting unit lane data along the distributed dimension");
1592 auto destLaneLayout = destLayout.getEffectiveLaneLayoutAsInt();
1593 int64_t numLanesAlongDim =
1594 destDistDim < static_cast<int64_t>(destLaneLayout.size())
1595 ? destLaneLayout[destDistDim]
1598 int64_t srcDistrDimSize = srcType.getDimSize(sourceDistDim);
1599 if (srcDistrDimSize % numLanesAlongDim != 0)
1600 return rewriter.notifyMatchFailure(
1601 op,
"source distributed dim size is not a multiple of "
1602 "the number of lanes along that dimension");
1604 int64_t destDistrDimOffset =
1605 cast<IntegerAttr>(op.getOffsets()[destDistDim]).getInt();
1606 if (destDistrDimOffset % numLanesAlongDim != 0)
1607 return rewriter.notifyMatchFailure(
1608 op,
"offset along distributed dim is not a multiple of "
1609 "the number of lanes along that dimension");
1611 updatedOffsets[destDistDim] =
1612 rewriter.getI64IntegerAttr(destDistrDimOffset / numLanesAlongDim);
1615 auto newOp = vector::InsertStridedSliceOp::create(
1616 rewriter, op.getLoc(), distDestTy, adaptor.getValueToStore(),
1618 ArrayAttr::get(rewriter.getContext(), updatedOffsets), op.getStrides());
1619 rewriter.replaceOp(op, newOp.
getResult());
1626struct SgToLaneVectorInsert :
public OpConversionPattern<vector::InsertOp> {
1627 using OpConversionPattern<vector::InsertOp>::OpConversionPattern;
1630 matchAndRewrite(vector::InsertOp op, OpAdaptor adaptor,
1631 ConversionPatternRewriter &rewriter)
const override {
1633 auto valueType = dyn_cast<VectorType>(op.getValueToStoreType());
1635 return rewriter.notifyMatchFailure(op,
"scalar insert not supported");
1637 xegpu::DistributeLayoutAttr layout =
1639 if (!layout || !layout.isForSubgroup())
1644 auto laneLayout = layout.getEffectiveLaneLayoutAsInt();
1645 if (llvm::any_of(ArrayRef<int64_t>(laneLayout).drop_back(1),
1646 [](int64_t v) {
return v != 1; }))
1647 return rewriter.notifyMatchFailure(
1648 op,
"only innermost dimension distribution is supported for "
1651 auto newOp = vector::InsertOp::create(
1652 rewriter, op.getLoc(), adaptor.getValueToStore(), adaptor.getDest(),
1653 op.getMixedPosition());
1654 rewriter.replaceOp(op, newOp.
getResult());
1672static FailureOr<Value>
1673shuffleDataAsLaneLayoutChange(ConversionPatternRewriter &rewriter,
Location loc,
1676 VectorType srcTy = dyn_cast<VectorType>(src.
getType());
1677 if (!srcTy || srcTy.getRank() != 2)
1680 if (targetLaneNum <= 0 || currentLaneNum != targetLaneNum * 2)
1684 srcTy.getNumElements() * srcTy.getElementTypeBitWidth();
1685 if (vectorBitWidth % 32 != 0)
1697 Type shuffleElemTy = rewriter.getI32Type();
1698 int64_t numShuffles = vectorBitWidth / 32;
1699 VectorType shuffleBundleTy = VectorType::get({numShuffles}, shuffleElemTy);
1701 Value temp = arith::ConstantOp::create(
1704 IntegerAttr::get(shuffleElemTy, 0)));
1705 VectorType flatSrcTy =
1706 VectorType::get({srcTy.getNumElements()}, srcTy.getElementType());
1707 Value flatSrc = vector::ShapeCastOp::create(rewriter, loc, flatSrcTy, src);
1708 Value shuffleBundle =
1709 vector::BitCastOp::create(rewriter, loc, shuffleBundleTy, flatSrc);
1710 for (
int64_t i = 0; i < numShuffles; i++) {
1712 vector::ExtractOp::create(rewriter, loc, shuffleBundle, i);
1713 shuffleElem = gpu::ShuffleOp::create(rewriter, loc, shuffleElem, 0,
1714 targetLaneNum, gpu::ShuffleMode::UP)
1716 temp = vector::InsertOp::create(rewriter, loc, shuffleElem, temp, i);
1718 temp = vector::BitCastOp::create(rewriter, loc, flatSrcTy, temp);
1719 temp = vector::ShapeCastOp::create(rewriter, loc, srcTy, temp);
1724 Value res = vector::ShuffleOp::create(rewriter, loc, src, temp,
indices);
1735static FailureOr<Value> repackLaneData(ConversionPatternRewriter &rewriter,
1739 auto srcTy = dyn_cast<VectorType>(src.
getType());
1742 int64_t rank = srcTy.getRank();
1743 Type elemTy = srcTy.getElementType();
1744 int64_t k = srcTy.getShape()[repackDim];
1746 bool roundRobinToContig = inputData == 1 && targetData == k;
1747 bool contigToRoundRobin = inputData == k && targetData == 1;
1748 if (!roundRobinToContig && !contigToRoundRobin)
1753 xegpu::LaneShuffleMode mode = roundRobinToContig
1754 ? xegpu::LaneShuffleMode::Pack
1755 : xegpu::LaneShuffleMode::Unpack;
1756 VectorType runTy = VectorType::get({k}, elemTy);
1760 if (srcTy.getNumElements() == k) {
1763 xegpu::LaneShuffleOp::create(rewriter, loc, runTy, src, mode));
1764 Value flat = vector::ShapeCastOp::create(rewriter, loc, runTy, src);
1766 xegpu::LaneShuffleOp::create(rewriter, loc, runTy, flat, mode);
1767 return Value(vector::ShapeCastOp::create(rewriter, loc, srcTy, shuffled));
1772 if (repackDim == rank - 1) {
1776 Value result = arith::ConstantOp::create(rewriter, loc, srcTy,
1777 rewriter.getZeroAttr(srcTy));
1778 for (
int64_t i = 0; i < numRuns; ++i) {
1780 Value run = vector::ExtractOp::create(rewriter, loc, src, pos);
1782 xegpu::LaneShuffleOp::create(rewriter, loc, runTy, run, mode);
1783 result = vector::InsertOp::create(rewriter, loc, shuffled,
result, pos);
1793 for (
int64_t d = 0; d < rank; ++d)
1794 if (d != repackDim) {
1795 keptShape.push_back(srcTy.getShape()[d]);
1796 keptDims.push_back(d);
1801 sliceSizes[repackDim] = k;
1803 VectorType sliceTy = VectorType::get(sliceSizes, elemTy);
1804 Value result = arith::ConstantOp::create(rewriter, loc, srcTy,
1805 rewriter.getZeroAttr(srcTy));
1806 for (
int64_t i = 0; i < numRuns; ++i) {
1809 for (
auto [dim, coord] : llvm::zip_equal(keptDims, keptPos))
1810 offsets[dim] = coord;
1811 Value slice = vector::ExtractStridedSliceOp::create(
1812 rewriter, loc, src, offsets, sliceSizes, sliceStrides);
1813 Value run = vector::ShapeCastOp::create(rewriter, loc, runTy,
slice);
1815 xegpu::LaneShuffleOp::create(rewriter, loc, runTy, run, mode);
1816 Value repackedSlice =
1817 vector::ShapeCastOp::create(rewriter, loc, sliceTy, repacked);
1818 result = vector::InsertStridedSliceOp::create(
1819 rewriter, loc, repackedSlice,
result, offsets, sliceStrides);
1825struct SgToLaneConvertLayout
1826 :
public OpConversionPattern<xegpu::ConvertLayoutOp> {
1827 using OpConversionPattern<xegpu::ConvertLayoutOp>::OpConversionPattern;
1830 matchAndRewrite(xegpu::ConvertLayoutOp op, OpAdaptor adaptor,
1831 ConversionPatternRewriter &rewriter)
const override {
1832 auto inputLayout = op.getEffectiveInputLayout();
1833 auto targetLayout = op.getTargetLayoutAttr();
1834 Type valType = op.getResult().getType();
1837 rewriter.replaceOp(op, op.getSource());
1841 auto resShape = cast<VectorType>(valType).getShape();
1842 SmallVector<int64_t> resShapeVec(resShape.begin(), resShape.end());
1846 if (inputLayout.isCompatibleWith(targetLayout, resShapeVec,
1847 xegpu::LayoutKind::Lane)) {
1848 rewriter.replaceOp(op, adaptor.getSource());
1859 if (inputLayout.getEffectiveOrderAsInt() ==
1860 targetLayout.getEffectiveOrderAsInt() &&
1861 inputLayout.getRank() == 2 && targetLayout.getRank() == 2) {
1862 auto laneLayout = inputLayout.getEffectiveLaneLayoutAsInt();
1863 auto targetLaneLayout = targetLayout.getEffectiveLaneLayoutAsInt();
1864 auto laneData = inputLayout.getEffectiveLaneDataAsInt();
1865 auto targetLaneData = targetLayout.getEffectiveLaneDataAsInt();
1866 if (laneLayout.size() == 2 && targetLaneLayout.size() == 2 &&
1867 laneData == targetLaneData && laneLayout[1] == 1 &&
1868 targetLaneLayout[1] == 1 && laneLayout[0] > 1 &&
1869 laneLayout[0] != targetLaneLayout[0]) {
1870 FailureOr<Value> res = shuffleDataAsLaneLayoutChange(
1871 rewriter, op.getLoc(), adaptor.getSource(), laneLayout[0],
1872 targetLaneLayout[0]);
1873 if (succeeded(res)) {
1874 rewriter.replaceOp(op, *res);
1886 if (inputLayout.getEffectiveOrderAsInt() ==
1887 targetLayout.getEffectiveOrderAsInt() &&
1888 inputLayout.getEffectiveLaneLayoutAsInt() ==
1889 targetLayout.getEffectiveLaneLayoutAsInt()) {
1890 auto laneLayout = inputLayout.getEffectiveLaneLayoutAsInt();
1891 auto laneData = inputLayout.getEffectiveLaneDataAsInt();
1892 auto targetLaneData = targetLayout.getEffectiveLaneDataAsInt();
1895 int64_t rank = laneData.size();
1896 int64_t repackDim = -1;
1897 bool multipleChanged =
false;
1898 for (int64_t d = 0; d < rank; ++d)
1899 if (laneData[d] != targetLaneData[d]) {
1900 if (repackDim != -1)
1901 multipleChanged =
true;
1907 int64_t otherDim = repackDim == rank - 1 ? rank - 2 : rank - 1;
1908 bool laneLayoutOk = repackDim != -1 && laneLayout[repackDim] != 1 &&
1909 (rank < 2 || laneLayout[otherDim] == 1);
1913 if (repackDim != -1 && repackDim >= rank - 2 && !multipleChanged &&
1915 FailureOr<Value> res = repackLaneData(
1916 rewriter, op.getLoc(), adaptor.getSource(), repackDim,
1917 laneData[repackDim], targetLaneData[repackDim]);
1918 if (succeeded(res)) {
1919 rewriter.replaceOp(op, *res);
1925 return rewriter.notifyMatchFailure(
1926 op,
"lowering incompatible convert_layout not yet supported");
1934struct LaneFragmentPiece {
1935 SmallVector<int64_t> offsets;
1936 SmallVector<int64_t> sizes;
1939static LaneFragmentPiece getLaneFragmentPiece(
int64_t unit,
1945 for (
int64_t d = 0; d < rank; ++d)
1946 units[d] =
shape[d] / std::min(
shape[d], laneLayout[d] * laneData[d]);
1948 LaneFragmentPiece piece;
1949 for (
int64_t d = 0; d < rank; ++d) {
1950 piece.offsets.push_back(unitCoords[d] * laneData[d]);
1951 piece.sizes.push_back(laneData[d]);
1970struct SgToLaneConvertLayoutViaSLM
1971 :
public OpConversionPattern<xegpu::ConvertLayoutOp> {
1972 using OpConversionPattern<xegpu::ConvertLayoutOp>::OpConversionPattern;
1975 matchAndRewrite(xegpu::ConvertLayoutOp op, OpAdaptor adaptor,
1976 ConversionPatternRewriter &rewriter)
const override {
1977 xegpu::DistributeLayoutAttr inputLayout = op.getEffectiveInputLayout();
1978 xegpu::DistributeLayoutAttr targetLayout = op.getTargetLayoutAttr();
1979 if (!inputLayout || !targetLayout || !inputLayout.isForSubgroup() ||
1980 !targetLayout.isForSubgroup())
1981 return rewriter.notifyMatchFailure(op,
"both layouts must be lane level");
1983 auto valueTy = dyn_cast<VectorType>(op.getResult().getType());
1985 return rewriter.notifyMatchFailure(op,
"value type must be a vector");
1986 Type elemTy = valueTy.getElementType();
1990 return rewriter.notifyMatchFailure(
1991 op,
"element type must be a whole number of bytes");
1993 ArrayRef<int64_t> sgShape = valueTy.getShape();
1994 int64_t rank = sgShape.size();
1995 if (rank != inputLayout.getRank() || rank != targetLayout.getRank())
1996 return rewriter.notifyMatchFailure(
1997 op,
"both layouts must have the rank of the value");
1999 FailureOr<VectorType> distInputTy =
2001 FailureOr<VectorType> distTargetTy =
2004 return rewriter.notifyMatchFailure(
2005 op,
"value type must be distributable by both layouts");
2010 return rewriter.notifyMatchFailure(
2011 op,
"target attribute is required to determine the subgroup size");
2012 FailureOr<int64_t> numSubgroups =
2014 if (
failed(numSubgroups))
2015 return rewriter.notifyMatchFailure(
2016 op,
"the scratch holds one tile per subgroup, so @known_block_size "
2017 "must be attached to the kernel, with power-of-two dimensions "
2018 "covering at least one subgroup");
2020 Location loc = op.getLoc();
2023 SmallVector<int64_t> slmShape(sgShape);
2024 slmShape[0] *= *numSubgroups;
2027 auto slmTy = MemRefType::get({slmBytes}, rewriter.getI8Type(), {}, 3);
2028 Value slm = memref::AllocaOp::create(rewriter, loc, slmTy);
2029 Value memDesc = xegpu::CreateMemDescOp::create(
2031 xegpu::MemDescType::get(rewriter.getContext(), slmShape, elemTy,
2036 Value sgId = gpu::SubgroupIdOp::create(rewriter, loc,
2037 rewriter.getIndexType(),
nullptr);
2038 SmallVector<Value> base(rank);
2039 base[0] = arith::MulIOp::create(
2040 rewriter, loc, sgId,
2042 for (int64_t d = 1; d < rank; ++d)
2045 Value laneId = gpu::LaneIdOp::create(rewriter, loc, rewriter.getIndexType(),
2046 mlir::IntegerAttr());
2047 auto dynamicOffsets = rewriter.getDenseI64ArrayAttr(
2048 SmallVector<int64_t>(rank, ShapedType::kDynamic));
2051 auto withBase = [&](ArrayRef<Value> coords) {
2052 SmallVector<Value> offsets;
2053 for (
auto [coord,
b] : llvm::zip_equal(coords, base))
2054 offsets.push_back(arith::AddIOp::create(rewriter, loc, coord,
b));
2060 inputLayout.computeDistributedCoords(rewriter, loc, laneId, sgShape);
2062 return rewriter.notifyMatchFailure(
2063 op,
"failed to compute the input_layout coordinates");
2064 SmallVector<int64_t> inputLaneLayout =
2065 inputLayout.getEffectiveLaneLayoutAsInt();
2066 SmallVector<int64_t> inputLaneData =
2067 inputLayout.getEffectiveLaneDataAsInt();
2071 for (
auto [unit, coords] : llvm::enumerate(*storeCoords)) {
2072 LaneFragmentPiece piece =
2073 getLaneFragmentPiece(unit, sgShape, inputLaneLayout, inputLaneData);
2074 Value data = fragment;
2075 if (piece.sizes != SmallVector<int64_t>(distInputTy->getShape()))
2076 data = vector::ExtractStridedSliceOp::create(
2077 rewriter, loc, fragment, piece.offsets, piece.sizes,
2078 SmallVector<int64_t>(rank, 1));
2079 xegpu::StoreMatrixOp::create(rewriter, loc,
TypeRange{}, data, memDesc,
2080 ValueRange(withBase(coords)), dynamicOffsets,
2081 nullptr, xegpu::DistributeLayoutAttr{});
2087 xegpu::FenceOp::create(rewriter, loc, xegpu::MemorySpace::SLM,
2088 xegpu::FenceScope::Workgroup);
2092 targetLayout.computeDistributedCoords(rewriter, loc, laneId, sgShape);
2094 return rewriter.notifyMatchFailure(
2095 op,
"failed to compute the target_layout coordinates");
2096 SmallVector<int64_t> targetLaneLayout =
2097 targetLayout.getEffectiveLaneLayoutAsInt();
2098 SmallVector<int64_t> targetLaneData =
2099 targetLayout.getEffectiveLaneDataAsInt();
2101 if (loadCoords->size() > 1)
2102 result = arith::ConstantOp::create(rewriter, loc, *distTargetTy,
2103 rewriter.getZeroAttr(*distTargetTy));
2104 for (
auto [unit, coords] : llvm::enumerate(*loadCoords)) {
2105 LaneFragmentPiece piece =
2106 getLaneFragmentPiece(unit, sgShape, targetLaneLayout, targetLaneData);
2107 auto pieceTy = VectorType::get(piece.sizes, elemTy);
2108 Value loaded = xegpu::LoadMatrixOp::create(
2109 rewriter, loc, pieceTy, memDesc,
ValueRange(withBase(coords)),
2110 dynamicOffsets,
nullptr, xegpu::DistributeLayoutAttr{});
2115 result = vector::InsertStridedSliceOp::create(
2116 rewriter, loc, loaded,
result, piece.offsets,
2117 SmallVector<int64_t>(rank, 1));
2120 rewriter.replaceOp(op, castValueTo(rewriter,
2129static bool hasDefaultOrderAndUnitLaneData(xegpu::DistributeLayoutAttr layout) {
2130 if (layout.getRank() != 2)
2138struct ElementLaneRedistribution {
2140 VectorType valueType;
2142 VectorType distributedInput;
2143 VectorType distributedTarget;
2146 SmallVector<int64_t> inputLaneLayout;
2147 SmallVector<int64_t> targetLaneLayout;
2148 int64_t subgroupSize;
2157static FailureOr<ElementLaneRedistribution>
2158matchElementLaneRedistribution(xegpu::ConvertLayoutOp op,
2159 ConversionPatternRewriter &rewriter) {
2160 xegpu::DistributeLayoutAttr inputLayout = op.getEffectiveInputLayout();
2161 xegpu::DistributeLayoutAttr targetLayout = op.getTargetLayoutAttr();
2162 if (!hasDefaultOrderAndUnitLaneData(inputLayout) ||
2163 !hasDefaultOrderAndUnitLaneData(targetLayout))
2164 return rewriter.notifyMatchFailure(
2165 op,
"both layouts must be rank 2 with effective lane_data [1, 1] and "
2166 "effective order [1, 0]");
2168 auto valueType = dyn_cast<VectorType>(op.getResult().getType());
2170 return rewriter.notifyMatchFailure(op,
"value type must be a vector");
2172 FailureOr<VectorType> distributedInput =
2174 FailureOr<VectorType> distributedTarget =
2176 if (
failed(distributedInput) ||
failed(distributedTarget))
2177 return rewriter.notifyMatchFailure(
2178 op,
"value type must be distributable by both layouts");
2183 return rewriter.notifyMatchFailure(
2184 op,
"target attribute is required to determine the subgroup size");
2186 ElementLaneRedistribution redistribution;
2187 redistribution.valueType = valueType;
2188 redistribution.distributedInput = *distributedInput;
2189 redistribution.distributedTarget = *distributedTarget;
2190 redistribution.inputLaneLayout = inputLayout.getEffectiveLaneLayoutAsInt();
2191 redistribution.targetLaneLayout = targetLayout.getEffectiveLaneLayoutAsInt();
2192 redistribution.subgroupSize = uArch->getSubgroupSize();
2193 return redistribution;
2208static FailureOr<int64_t> getDistributedDimLaneStride(xegpu::SliceAttr
slice) {
2209 xegpu::SliceAttr flattened =
slice.flatten();
2210 auto parent = dyn_cast<xegpu::LayoutAttr>(flattened.getParent());
2216 if (parentLaneLayout.size() != parentOrder.size())
2220 std::optional<int64_t> distributedDim;
2221 for (
int64_t dim = 0, rank =
static_cast<int64_t>(parentLaneLayout.size());
2222 dim < rank; ++dim) {
2223 if (llvm::is_contained(slicedDims, dim) || parentLaneLayout[dim] == 1)
2227 distributedDim = dim;
2229 if (!distributedDim)
2233 for (
int64_t dim : parentOrder) {
2234 if (dim == *distributedDim)
2236 stride *= parentLaneLayout[dim];
2252struct SgToLaneConvertLayoutBroadcastExtract
2253 :
public OpConversionPattern<xegpu::ConvertLayoutOp> {
2254 using OpConversionPattern<xegpu::ConvertLayoutOp>::OpConversionPattern;
2257 matchAndRewrite(xegpu::ConvertLayoutOp op, OpAdaptor adaptor,
2258 ConversionPatternRewriter &rewriter)
const override {
2259 xegpu::DistributeLayoutAttr inputLayout = op.getEffectiveInputLayout();
2260 xegpu::DistributeLayoutAttr targetLayout = op.getTargetLayoutAttr();
2262 if (!isa<xegpu::SliceAttr>(inputLayout))
2263 return rewriter.notifyMatchFailure(op,
2264 "input_layout must be #xegpu.slice");
2265 if (!isa<xegpu::LayoutAttr>(targetLayout))
2266 return rewriter.notifyMatchFailure(op,
2267 "target_layout must be #xegpu.layout");
2269 FailureOr<ElementLaneRedistribution> redistribution =
2270 matchElementLaneRedistribution(op, rewriter);
2271 if (
failed(redistribution))
2274 if (redistribution->inputLaneLayout != SmallVector<int64_t>{1, 1})
2275 return rewriter.notifyMatchFailure(
2276 op,
"input_layout effective lane_layout must be [1, 1]");
2277 SmallVector<int64_t> targetLaneLayout = redistribution->targetLaneLayout;
2278 if (targetLaneLayout[0] <= 1 || targetLaneLayout[1] != 1)
2279 return rewriter.notifyMatchFailure(
2280 op,
"target_layout effective lane_layout must be [n, 1] with n > 1");
2281 if (redistribution->distributedInput != redistribution->valueType)
2282 return rewriter.notifyMatchFailure(
2283 op,
"distributed input_layout type must equal the value type");
2284 if (redistribution->distributedTarget.getShape() != ArrayRef<int64_t>{1, 1})
2285 return rewriter.notifyMatchFailure(
2286 op,
"distributed target_layout type must be vector<1x1>");
2287 if (targetLaneLayout[0] > redistribution->subgroupSize)
2288 return rewriter.notifyMatchFailure(
2289 op,
"target_layout effective lane_layout[0] must not exceed the "
2292 VectorType valueType = redistribution->valueType;
2293 Location loc = op.getLoc();
2296 redistribution->distributedInput);
2297 auto flatType = VectorType::get({valueType.getNumElements()},
2298 valueType.getElementType());
2299 Value flat = vector::ShapeCastOp::create(rewriter, loc, flatType, src);
2300 Value laneId = gpu::LaneIdOp::create(rewriter, loc, rewriter.getIndexType(),
2301 mlir::IntegerAttr());
2304 Value row = arith::RemUIOp::create(rewriter, loc, laneId, rowCount);
2305 Value element = vector::ExtractOp::create(rewriter, loc, flat,
2306 ArrayRef<OpFoldResult>{row});
2307 rewriter.replaceOpWithNewOp<vector::FromElementsOp>(
2308 op, redistribution->distributedTarget, element);
2354struct SgToLaneConvertLayoutPartialBroadcastExtractShuffle
2355 :
public OpConversionPattern<xegpu::ConvertLayoutOp> {
2356 using OpConversionPattern<xegpu::ConvertLayoutOp>::OpConversionPattern;
2359 matchAndRewrite(xegpu::ConvertLayoutOp op, OpAdaptor adaptor,
2360 ConversionPatternRewriter &rewriter)
const override {
2361 xegpu::DistributeLayoutAttr inputLayout = op.getEffectiveInputLayout();
2362 xegpu::DistributeLayoutAttr targetLayout = op.getTargetLayoutAttr();
2364 auto inputSlice = dyn_cast<xegpu::SliceAttr>(inputLayout);
2366 return rewriter.notifyMatchFailure(op,
2367 "input_layout must be #xegpu.slice");
2368 if (!isa<xegpu::LayoutAttr>(targetLayout))
2369 return rewriter.notifyMatchFailure(op,
2370 "target_layout must be #xegpu.layout");
2372 FailureOr<ElementLaneRedistribution> redistribution =
2373 matchElementLaneRedistribution(op, rewriter);
2374 if (
failed(redistribution))
2377 VectorType valueType = redistribution->valueType;
2378 Type elementType = valueType.getElementType();
2380 !llvm::is_contained({8u, 16u, 32u, 64u},
2382 return rewriter.notifyMatchFailure(
2383 op,
"element type must be an int or float of bit width 8, 16, 32 or "
2384 "64 to be carried by gpu.shuffle");
2386 if (redistribution->inputLaneLayout != SmallVector<int64_t>{1, 2})
2387 return rewriter.notifyMatchFailure(
2388 op,
"input_layout effective lane_layout must be [1, 2]");
2389 SmallVector<int64_t> targetLaneLayout = redistribution->targetLaneLayout;
2390 if (targetLaneLayout[0] <= 1 || targetLaneLayout[1] != 1)
2391 return rewriter.notifyMatchFailure(
2392 op,
"target_layout effective lane_layout must be [n, 1] with n > 1");
2393 if (redistribution->distributedInput.getShape() !=
2394 ArrayRef<int64_t>{valueType.getDimSize(0), 1})
2395 return rewriter.notifyMatchFailure(
2396 op,
"distributed input_layout type must be vector<shape[0]x1>");
2397 if (redistribution->distributedTarget.getShape() != ArrayRef<int64_t>{1, 2})
2398 return rewriter.notifyMatchFailure(
2399 op,
"distributed target_layout type must be vector<1x2>");
2401 FailureOr<int64_t> stride = getDistributedDimLaneStride(inputSlice);
2403 return rewriter.notifyMatchFailure(
2404 op,
"input_layout parent must have exactly one non-sliced dimension "
2405 "with lane_layout extent greater than one");
2408 if (*stride * redistribution->inputLaneLayout[1] !=
2409 redistribution->subgroupSize)
2410 return rewriter.notifyMatchFailure(
2411 op,
"input_layout distributed dimension lane stride times its extent "
2412 "must equal the subgroup size");
2416 if (*stride % targetLaneLayout[0] != 0)
2417 return rewriter.notifyMatchFailure(
2418 op,
"target_layout effective lane_layout[0] must divide the "
2419 "input_layout distributed dimension lane stride");
2421 Location loc = op.getLoc();
2424 redistribution->distributedInput);
2426 VectorType::get({redistribution->distributedInput.getNumElements()},
2427 valueType.getElementType());
2428 Value flat = vector::ShapeCastOp::create(rewriter, loc, flatType, src);
2429 Value laneId = gpu::LaneIdOp::create(rewriter, loc, rewriter.getIndexType(),
2430 mlir::IntegerAttr());
2433 Value row = arith::RemUIOp::create(rewriter, loc, laneId, rowCount);
2434 Value own = vector::ExtractOp::create(rewriter, loc, flat,
2435 ArrayRef<OpFoldResult>{row});
2437 Type i32Type = rewriter.getI32Type();
2439 redistribution->subgroupSize);
2440 Value rowI32 = arith::IndexCastOp::create(rewriter, loc, i32Type, row);
2443 Value otherOwner = arith::AddIOp::create(rewriter, loc, rowI32, strideI32);
2444 Value column0 = gpu::ShuffleOp::create(rewriter, loc, own, rowI32, width,
2445 gpu::ShuffleMode::IDX)
2446 .getShuffleResult();
2447 Value column1 = gpu::ShuffleOp::create(rewriter, loc, own, otherOwner,
2448 width, gpu::ShuffleMode::IDX)
2449 .getShuffleResult();
2450 rewriter.replaceOpWithNewOp<vector::FromElementsOp>(
2451 op, redistribution->distributedTarget,
ValueRange{column0, column1});
2466struct SgToLaneConvertLayoutDeinterleaveSelect
2467 :
public OpConversionPattern<xegpu::ConvertLayoutOp> {
2468 using OpConversionPattern<xegpu::ConvertLayoutOp>::OpConversionPattern;
2471 matchAndRewrite(xegpu::ConvertLayoutOp op, OpAdaptor adaptor,
2472 ConversionPatternRewriter &rewriter)
const override {
2473 xegpu::DistributeLayoutAttr inputLayout = op.getEffectiveInputLayout();
2474 xegpu::DistributeLayoutAttr targetLayout = op.getTargetLayoutAttr();
2476 if (!isa<xegpu::SliceAttr>(inputLayout))
2477 return rewriter.notifyMatchFailure(op,
2478 "input_layout must be #xegpu.slice");
2479 auto targetSlice = dyn_cast<xegpu::SliceAttr>(targetLayout);
2481 return rewriter.notifyMatchFailure(op,
2482 "target_layout must be #xegpu.slice");
2484 FailureOr<ElementLaneRedistribution> redistribution =
2485 matchElementLaneRedistribution(op, rewriter);
2486 if (
failed(redistribution))
2489 VectorType valueType = redistribution->valueType;
2490 if (redistribution->inputLaneLayout != SmallVector<int64_t>{1, 1})
2491 return rewriter.notifyMatchFailure(
2492 op,
"input_layout effective lane_layout must be [1, 1]");
2493 SmallVector<int64_t> targetLaneLayout = redistribution->targetLaneLayout;
2494 if (targetLaneLayout != SmallVector<int64_t>{1, 2})
2495 return rewriter.notifyMatchFailure(
2496 op,
"target_layout effective lane_layout must be [1, 2]");
2497 if (redistribution->distributedInput != valueType)
2498 return rewriter.notifyMatchFailure(
2499 op,
"distributed input_layout type must equal the value type");
2500 if (redistribution->distributedTarget.getShape() !=
2501 ArrayRef<int64_t>{valueType.getDimSize(0), 1})
2502 return rewriter.notifyMatchFailure(
2503 op,
"distributed target_layout type must be vector<shape[0]x1>");
2505 FailureOr<int64_t> stride = getDistributedDimLaneStride(targetSlice);
2507 return rewriter.notifyMatchFailure(
2508 op,
"target_layout parent must have exactly one non-sliced dimension "
2509 "with lane_layout extent greater than one");
2512 if (*stride * targetLaneLayout[1] != redistribution->subgroupSize)
2513 return rewriter.notifyMatchFailure(
2514 op,
"target_layout distributed dimension lane stride times its "
2515 "extent must equal the subgroup size");
2517 Location loc = op.getLoc();
2520 redistribution->distributedInput);
2521 auto flatType = VectorType::get({valueType.getNumElements()},
2522 valueType.getElementType());
2523 Value flat = vector::ShapeCastOp::create(rewriter, loc, flatType, src);
2524 auto deinterleaved = vector::DeinterleaveOp::create(rewriter, loc, flat);
2525 Value laneId = gpu::LaneIdOp::create(rewriter, loc, rewriter.getIndexType(),
2526 mlir::IntegerAttr());
2529 Value group = arith::DivUIOp::create(rewriter, loc, laneId, strideVal);
2530 Value isFirstGroup = arith::CmpIOp::create(
2531 rewriter, loc, arith::CmpIPredicate::eq, group, zero);
2532 Value selected = arith::SelectOp::create(rewriter, loc, isFirstGroup,
2533 deinterleaved.getResultEven(),
2534 deinterleaved.getResultOdd());
2535 rewriter.replaceOpWithNewOp<vector::ShapeCastOp>(
2536 op, redistribution->distributedTarget, selected);
2542struct SgToLaneVectorInterleave
2543 :
public OpConversionPattern<vector::InterleaveOp> {
2544 using OpConversionPattern<vector::InterleaveOp>::OpConversionPattern;
2547 matchAndRewrite(vector::InterleaveOp op, OpAdaptor adaptor,
2548 ConversionPatternRewriter &rewriter)
const override {
2550 auto newOp = vector::InterleaveOp::create(
2551 rewriter, op.getLoc(), adaptor.getLhs(), adaptor.getRhs());
2552 rewriter.replaceOp(op, newOp.
getResult());
2558struct SgToLaneVectorDeinterleave
2559 :
public OpConversionPattern<vector::DeinterleaveOp> {
2560 using OpConversionPattern<vector::DeinterleaveOp>::OpConversionPattern;
2563 matchAndRewrite(vector::DeinterleaveOp op, OpAdaptor adaptor,
2564 ConversionPatternRewriter &rewriter)
const override {
2566 auto newOp = vector::DeinterleaveOp::create(rewriter, op.getLoc(),
2567 adaptor.getSource());
2573struct SgToLaneDpasMx :
public OpConversionPattern<xegpu::DpasMxOp> {
2574 using OpConversionPattern<xegpu::DpasMxOp>::OpConversionPattern;
2577 matchAndRewrite(xegpu::DpasMxOp op, OpAdaptor adaptor,
2578 ConversionPatternRewriter &rewriter)
const override {
2583 if (!uArch->isSupportedInstruction(
2584 xegpu::uArch::InstructionKind::SubgroupScaledMatrixMultiplyAcc))
2585 return rewriter.notifyMatchFailure(
2586 op,
"target uArch does not support scaled subgroup mma");
2588 auto layoutA = cast<xegpu::LayoutAttr>(op.getLayoutAAttr());
2589 auto layoutB = cast<xegpu::LayoutAttr>(op.getLayoutBAttr());
2590 auto layoutCd = cast<xegpu::LayoutAttr>(op.getLayoutCdAttr());
2591 if (!layoutA || !layoutB || !layoutCd)
2592 return rewriter.notifyMatchFailure(
2593 op,
"missing required layout attributes for DpasMxOp distribution");
2596 auto expected1DTypeResult =
2598 auto expected1DTypeA =
2600 auto expected1DTypeB =
2603 VectorType expected1DTypeScaleA, expected1DTypeScaleB;
2604 if (op.getScaleA()) {
2605 auto layoutScaleA = cast<xegpu::LayoutAttr>(op.getLayoutAScaleAttr());
2607 cast<VectorType>(op.getScaleA().getType()), layoutScaleA);
2608 if (
failed(expected1DTypeScaleAOrFailure))
2609 return rewriter.notifyMatchFailure(
2610 op,
"failed to calculate expected 1D vector type for scale A");
2611 expected1DTypeScaleA = expected1DTypeScaleAOrFailure.value();
2613 if (op.getScaleB()) {
2614 auto layoutScaleB = cast<xegpu::LayoutAttr>(op.getLayoutBScaleAttr());
2616 cast<VectorType>(op.getScaleB().getType()), layoutScaleB);
2617 if (
failed(expected1DTypeScaleBOrFailure))
2618 return rewriter.notifyMatchFailure(
2619 op,
"failed to calculate expected 1D vector type for scale B");
2620 expected1DTypeScaleB = expected1DTypeScaleBOrFailure.value();
2623 auto expectedNDTypeResult =
2625 if (
failed(expected1DTypeResult) ||
failed(expected1DTypeA) ||
2627 return rewriter.notifyMatchFailure(
2629 "failed to calculate supported workitem 1D vector types for DpasOp "
2631 if (
failed(expectedNDTypeResult))
2632 return rewriter.notifyMatchFailure(
2633 op,
"unable to compute expected workitem vector type for DpasOp from "
2637 const auto *uArchInstruction = dyn_cast<
2639 xegpu::uArch::InstructionKind::SubgroupScaledMatrixMultiplyAcc));
2640 assert(uArchInstruction);
2641 auto wiAType = expected1DTypeA.value();
2642 auto wiBType = expected1DTypeB.value();
2644 unsigned aPackedBitWidth =
2645 wiAType.getElementTypeBitWidth() * wiAType.getNumElements();
2646 unsigned bPackedBitWidth =
2647 wiBType.getElementTypeBitWidth() * wiBType.getNumElements();
2648 if (aPackedBitWidth % uArchInstruction->getPackedFormatBitSizeA())
2649 return rewriter.notifyMatchFailure(
2650 op,
"A operand packed bit width must be a multiple of uArch packed "
2651 "format requirement");
2652 if (bPackedBitWidth % uArchInstruction->getPackedFormatBitSizeB())
2653 return rewriter.notifyMatchFailure(
2654 op,
"B operand packed bit width must be a multiple of uArch packed "
2655 "format requirement");
2657 auto newOp = xegpu::DpasMxOp::create(
2658 rewriter, op->getLoc(), expected1DTypeResult.value(),
2660 expected1DTypeA.value()),
2662 expected1DTypeB.value()),
2664 ? castValueTo(rewriter,
2666 expected1DTypeResult.value())
2670 ? castValueTo(rewriter,
2672 expected1DTypeScaleA)
2675 ? castValueTo(rewriter,
2677 expected1DTypeScaleB)
2683 rewriter.replaceOp(op, castValueTo(rewriter, newOp.
getResult(),
2684 expectedNDTypeResult.value()));
2689struct XeGPUSgToLaneDistributePass
2691 XeGPUSgToLaneDistributePass> {
2692 void runOnOperation()
override;
2697void XeGPUSgToLaneDistributePass::runOnOperation() {
2700 Operation *root = getOperation();
2702 signalPassFailure();
2707 llvm::SmallSetVector<UnrealizedConversionCastOp, 8> existingCasts;
2709 [&](UnrealizedConversionCastOp castOp) { existingCasts.insert(castOp); });
2715 TypeConverter typeConverter;
2719 auto materializeCast = [](OpBuilder &builder, Type type,
ValueRange inputs,
2720 Location loc) -> Value {
2721 return UnrealizedConversionCastOp::create(builder, loc, type, inputs)
2724 typeConverter.addSourceMaterialization(materializeCast);
2725 typeConverter.addTargetMaterialization(materializeCast);
2730 typeConverter, patterns,
target, root);
2731 target.addLegalOp<UnrealizedConversionCastOp>();
2736 ConversionConfig config;
2737 config.foldingMode = DialectConversionFoldingMode::AfterPatterns;
2739 applyPartialConversion(root,
target, std::move(patterns), config)))
2740 return signalPassFailure();
2751 typeConverter.addConversion([](
Type type) ->
Type {
return type; });
2753 typeConverter.addConversion([](TensorDescType type) ->
Type {
2754 if (type.getLayoutAttr()) {
2755 return type.dropLayouts();
2763 auto getSubShapeAndCount = [](VectorType vecTy,
2764 xegpu::DistributeLayoutAttr layout)
2767 if (failed(distTyOrFailure))
2774 std::move(loopArgTypes));
2782 target.addDynamicallyLegalOp<xegpu::CreateNdDescOp>(
2783 [&](xegpu::CreateNdDescOp op) {
return !op.getType().getLayoutAttr(); });
2785 target.addDynamicallyLegalDialect<xegpu::XeGPUDialect>([](
Operation *op) {
2786 if (isa<xegpu::ConvertLayoutOp>(op))
2788 auto anchorOp = dyn_cast<AnchorLayoutInterface>(op);
2791 return !anchorOp.getAnchorLayout();
2794 target.addDynamicallyLegalOp<arith::ConstantOp>(
2795 [=](arith::ConstantOp op) ->
bool {
2797 if (!isa<VectorType>(op.getResult().getType()))
2803 target.addDynamicallyLegalDialect<math::MathDialect, arith::ArithDialect>(
2804 [=](
Operation *op) -> std::optional<bool> {
2809 if (op->getNumResults() != 1)
2812 VectorType resultType =
2813 dyn_cast<VectorType>(op->getResult(0).getType());
2818 for (
Value operand : op->getOperands()) {
2819 VectorType operandType = dyn_cast<VectorType>(operand.getType());
2820 if (!operandType || operandType.getShape() != resultType.getShape()) {
2828 target.addDynamicallyLegalOp<vector::ReductionOp>(
2829 [=](vector::ReductionOp op) ->
bool {
2834 target.addDynamicallyLegalOp<vector::MultiDimReductionOp>(
2835 [=](vector::MultiDimReductionOp op) ->
bool {
2836 return !isValidSubgroupMultiReductionOp(op);
2838 target.addDynamicallyLegalOp<vector::CreateMaskOp, vector::ConstantMaskOp,
2839 vector::TransposeOp, vector::BitCastOp,
2840 vector::ShapeCastOp, vector::StepOp,
2841 vector::BroadcastOp>([=](
Operation *op) ->
bool {
2844 target.addDynamicallyLegalOp<vector::ExtractOp>(
2845 [=](vector::ExtractOp op) ->
bool {
2846 if (!isa<VectorType>(op.getType()))
2850 target.addDynamicallyLegalOp<vector::InsertOp>(
2851 [=](vector::InsertOp op) ->
bool {
2854 target.addDynamicallyLegalOp<vector::ExtractStridedSliceOp>(
2855 [=](vector::ExtractStridedSliceOp op) ->
bool {
2858 target.addDynamicallyLegalOp<vector::InsertStridedSliceOp>(
2859 [=](vector::InsertStridedSliceOp op) ->
bool {
2862 target.addDynamicallyLegalOp<vector::InterleaveOp, vector::DeinterleaveOp>(
2866 target.markUnknownOpDynamicallyLegal([](
Operation *op) {
return true; });
2868 .
add<SgToLaneCreateNdDesc, SgToLaneLoadNd, SgToLaneStoreNd, SgToLaneDpas,
2869 SgToLaneElementWise, SgToLaneArithConstant, SgToLanePrefetchNd,
2870 SgToLaneLoadGather, SgToLaneStoreScatter, SgToLaneVectorReduction,
2871 SgToLaneMultiDimReduction, SgToLaneVectorExtract,
2872 SgToLaneVectorInsert, SgToLaneVectorExtractStridedSlice,
2873 SgToLaneVectorInsertStridedSlice, SgToLaneLoadMatrix,
2874 SgToLaneStoreMatrix, SgToLaneConvertLayout, SgToLaneVectorTranspose,
2875 SgToLaneVectorBitcast, SgToLaneVectorStep, SgToLaneVectorShapeCast,
2876 SgToLaneBroadcast, SgToLaneCreateMask<vector::CreateMaskOp>,
2877 SgToLaneCreateMask<vector::ConstantMaskOp>,
2878 SgToLaneVectorDeinterleave, SgToLaneVectorInterleave, SgToLaneDpasMx,
2879 SgToLaneConvertLayoutBroadcastExtract,
2880 SgToLaneConvertLayoutPartialBroadcastExtractShuffle,
2881 SgToLaneConvertLayoutDeinterleaveSelect>(typeConverter,
2885 patterns.
add<SgToLaneConvertLayoutViaSLM>(typeConverter,
static SmallVector< Value > slice(OpBuilder &b, Location loc, Value value, VectorType nativeType)
Attributes are known-constant values of operations.
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.
Operation is the basic unit of execution within MLIR.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Location getLoc()
The source location the operation was defined or derived from.
Attribute getPropertiesAsAttribute()
Return the properties converted to an attribute.
OperationName getName()
The name of an operation is the key identifier for it.
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
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),...
result_range getResults()
unsigned getNumResults()
Return the number of results held by this operation.
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
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.
A range-style iterator that allows for iterating over the offsets of all potential tiles of size tile...
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...
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
This class provides an abstraction over the different types of ranges over Values.
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.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
static ConstantIntOp create(OpBuilder &builder, Location location, int64_t value, unsigned width)
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< int64_t > content)
bool hasElementwiseMappableTraits(Operation *op)
Together, Elementwise, Scalarizable, Vectorizable, and Tensorizable provide an easy way for scalar op...
void populateSCFStructuralTypeConversionsAndLegality(const TypeConverter &typeConverter, RewritePatternSet &patterns, ConversionTarget &target, PatternBenefit benefit=1)
Populates patterns for SCF structural type conversions and sets up the provided ConversionTarget with...
Value makeArithReduction(OpBuilder &b, Location loc, CombiningKind kind, Value v1, Value acc, arith::FastMathFlagsAttr fastmath=nullptr, Value mask=nullptr)
Returns the result value of reducing two scalar/vector values with the corresponding arith operation.
SmallVector< Value > getAsValues(OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > foldResults)
Convert foldResults into Values.
@ SubgroupMatrixMultiplyAcc
@ SubgroupScaledMatrixMultiplyAcc
const uArch * getUArch(llvm::StringRef archName)
void populateXeGPUSgToLaneDistributeTypeConversionAndLegality(TypeConverter &typeConverter, RewritePatternSet &patterns, ConversionTarget &target, Operation *topLevelOp)
Defines type conversions and legality for XeGPU subgroup to lane distribution and appends the require...
bool requirePacked(const DistributeLayoutAttr layout)
Helper function to check if the layout is packed.
void removeTemporaryLayoutAttrs(Operation *op)
Removes the temporary layout attributes for each OpOperand and OpResult of the given operation.
bool recoverTemporaryLayouts(Operation *rootOp)
Attach layout attributes to all vector-type operands of operations within the given operation's neste...
FailureOr< int64_t > getNumSubgroupsFromBlockSize(Operation *op, int64_t subgroupSize)
Returns the number of subgroups the kernel enclosing op runs, derived from the known_block_size of it...
FailureOr< VectorType > getDistVecTypeBasedOnLaneLayout(DistributeLayoutAttr layout, VectorType originalType)
Helper function to get distributed vector type for a source vector type according to the lane_layout.
bool requireTranspose(const DistributeLayoutAttr layout, const uArch::uArch *uArch)
Helper function to check if the layout requires a transpose effect.
DistributeLayoutAttr getDistributeLayoutAttr(const Value value)
Retrieves the DistributeLayoutAttr associated with a given Value, or nullptr if none is found.
DenseMap< Value, SmallVector< Type > > precomputeLoopBlockArgTypes(Operation *topLevelOp, SubShapeAndCountFn getSubShapeAndCount)
Pre-computes distributed VectorType mappings for every value carried through an SCF loop under topLev...
std::optional< std::string > getChipStr(Operation *op)
Retrieves the chip string from the XeVM target attribute of the parent GPU module operation.
void addVectorTypeConversion(TypeConverter &converter, SubShapeAndCountFn getSubShapeAndCount, DenseMap< Value, SmallVector< Type > > loopArgTypes)
Adds a context-aware VectorType conversion to converter (1:1 shape-changing or 1:N,...
Value lowerToVectorReductions(TypedValue< VectorType > src, TypedValue< VectorType > acc, vector::CombiningKind kind, int64_t reductionDim, Location loc, PatternRewriter &rewriter, arith::FastMathFlagsAttr fastmath=nullptr)
Given a src and an acc argumments from a vector::MultiDimReductionOp, lower to a set of vector::Reduc...
DistributeLayoutAttr getTemporaryLayout(const T &operandOrResult)
get and set distribute layout attribute for non-anchor operations (and offsets/masks of load/store op...
Value lowerCrossLaneReductionToShuffles(TypedValue< VectorType > src, TypedValue< VectorType > acc, vector::CombiningKind kind, int64_t reductionDim, int64_t reductionSize, Location loc, PatternRewriter &rewriter, arith::FastMathFlagsAttr fastmath=nullptr)
Lowers cross-lane reductions to shuffle operations on a 2D vector.
void populateXeGPUSgToLaneDistributeTypeConversions(TypeConverter &typeConverter, Operation *topLevelOp)
Define only the type conversions needed for XeGPU subgroup to lane distribution.
void cleanupUnrealizedConversionCasts(Operation *root, const llvm::SmallSetVector< UnrealizedConversionCastOp, 8 > &existingCasts)
Cleans up UnrealizedConversionCastOps inserted during SCF structural type conversion and/or XeGPU unr...
SmallVector< OpFoldResult > addWithRightAligned(OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > lhs, ArrayRef< OpFoldResult > rhs)
Generates element-wise addition ops of two arrays with automatic alignment.
FailureOr< VectorType > getDistributedVectorType(xegpu::TensorDescType tdescTy)
If tensor descriptor has a layout attribute it is used in SIMT mode.
Value subgroupReduction(Location loc, OpBuilder &builder, Value input, vector::CombiningKind kind, uint32_t size, arith::FastMathFlagsAttr fastmath=nullptr)
Given an input value representing per-lane data, this function returns the result after performing a ...
Include the generated interface declarations.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
SmallVector< int64_t > computeStrides(ArrayRef< int64_t > sizes)
SmallVector< int64_t > delinearize(int64_t linearIndex, ArrayRef< int64_t > strides)
Given the strides together with a linear index in the dimension space, return the vector-space offset...
int64_t computeProduct(ArrayRef< int64_t > basis)
Self-explicit.
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
OpFoldResult getAsOpFoldResult(Value val)
Given a value, try to extract a constant Attribute.
int64_t linearize(ArrayRef< int64_t > offsets, ArrayRef< int64_t > basis)
Return the linearized index of 'offsets' w.r.t.
std::optional< SmallVector< int64_t > > computeShapeRatio(ArrayRef< int64_t > shape, ArrayRef< int64_t > subShape)
Return the multi-dimensional integral ratio of subShape to the trailing dimensions of shape.
This represents an operation in an abstracted form, suitable for use with the builder APIs.