32#include "llvm/ADT/DenseSet.h"
33#include "llvm/ADT/PostOrderIterator.h"
34#include "llvm/ADT/SetVector.h"
35#include "llvm/Support/FormatVariadic.h"
45 out.reserve(attrs.size());
47 for (
auto attr : attrs) {
48 if (
auto dist = dyn_cast<xegpu::DistributeLayoutAttr>(attr.getValue())) {
49 auto newLayout = dist.dropSgLayoutAndData();
51 out.emplace_back(attr.getName(), newLayout);
63 out.reserve(attrs.size());
65 for (
auto attr : attrs) {
66 if (
auto dist = dyn_cast<xegpu::DistributeLayoutAttr>(attr.getValue())) {
67 auto newLayout = dist.dropInstData();
69 out.emplace_back(attr.getName(), newLayout);
80 if (
auto dist = dyn_cast<xegpu::DistributeLayoutAttr>(attr))
81 attr = dist.dropInstData();
89 auto it = targets.find(region);
90 if (it == targets.end())
93 if (!visitedRegions.contains(
target))
103 regions.push_back(®ion);
104 auto regionOp = dyn_cast<RegionBranchOpInterface>(op);
111 for (
Region *region : regions) {
113 regionOp.getSuccessorRegions(*region, successors);
115 if (successor.isOperation())
116 exits.insert(region);
117 else if (successor.getSuccessor() != region)
118 targets[region].insert(successor.getSuccessor());
123 while (visitedRegions.size() < regions.size()) {
129 auto findFirst = [&](
auto pred) ->
Region * {
130 for (
Region *region : regions)
131 if (!visitedRegions.contains(region) && pred(region))
136 return isReady(region, targets, visitedRegions);
140 findFirst([&](
Region *region) {
return exits.contains(region); });
142 chosen = findFirst([](
Region *) {
return true; });
143 visitedRegions.insert(chosen);
145 return visitedRegions.takeVector();
154 llvm::ReversePostOrderTraversal<Region *> rpot(®ion);
156 for (
Block *block : llvm::reverse(blocks)) {
157 for (
Operation &op : llvm::reverse(*block)) {
158 auto walkNestedRegions = [&]() {
163 auto terminator = dyn_cast<RegionBranchTerminatorOpInterface>(&op);
164 if (terminator && isa<RegionBranchOpInterface>(op.getParentOp())) {
166 }
else if (
auto regionOp = dyn_cast<RegionBranchOpInterface>(&op)) {
170 unsigned numRegionArgs = 0;
171 for (
Region ®ion : op.getRegions())
187 root->
walk([&](FunctionOpInterface funcOp) {
188 if (!funcOp.isExternal())
194 xegpu::DistributeLayoutAttr layout =
nullptr;
215 if (
auto constant = dyn_cast<arith::ConstantOp>(op)) {
216 auto value = dyn_cast<DenseElementsAttr>(constant.getValue());
217 return value && value.isSplat();
219 if (isa<vector::StepOp, vector::CreateMaskOp>(op))
221 if (
auto broadcast = dyn_cast<vector::BroadcastOp>(op))
222 return !isa<VectorType>(
broadcast.getSource().getType());
234 while (!worklist.empty()) {
235 auto [op, expanded] = worklist.pop_back_val();
240 if (!visited.insert(op).second)
245 worklist.emplace_back(op,
true);
246 for (
Value operand : op->getOperands()) {
247 if (!isa<VectorType>(operand.getType()))
249 Operation *producer = operand.getDefiningOp();
252 if (!visited.contains(producer))
253 worklist.emplace_back(producer,
false);
280 return mapping.
lookup(value);
288 if (op->
getNumResults() > 1 && !isa<vector::DeinterleaveOp>(op))
299 if (
auto tdescTy = dyn_cast<xegpu::TensorDescType>(resultType);
300 tdescTy && !tdescTy.getLayoutAttr())
305 if (isa<VectorType>(resultType) || isa<vector::MultiDimReductionOp>(op))
308 if (isa<vector::DeinterleaveOp>(op))
312 xegpu::DistributeLayoutAttr operandLayout =
314 if (isa<VectorType>(opr.get().getType()) && operandLayout)
320 RegionBranchTerminatorOpInterface terminator,
322 auto regionOp = dyn_cast<RegionBranchOpInterface>(terminator->getParentOp());
326 regionOp.getSuccessorOperandInputMapping(mapping,
328 for (
const auto &[successorOperand, successorInputs] : mapping) {
332 xegpu::DistributeLayoutAttr layout;
333 for (
auto arg : llvm::make_isa_range<BlockArgument>(successorInputs))
334 if ((layout = getLayoutOfValue(arg)))
338 for (
Value input : successorInputs)
339 if (isa<OpResult>(input))
340 layout = getLayoutOfValue(input);
341 setOperandLayout(*successorOperand, layout);
350 SetOperandLayoutFnTy setOperandLayout,
351 SetTDescArgLayoutFnTy setTDescArgLayout) {
357 for (
Region ®ion : regionOp->getRegions()) {
362 ValueRange successorInputs = regionOp.getSuccessorInputs(regionSuccessor);
363 for (
auto [inputIdx, regionArg] : llvm::enumerate(successorInputs)) {
364 auto layout = getLayoutOfValue(regionArg);
369 if (
auto tdescTy = dyn_cast<xegpu::TensorDescType>(regionArg.getType());
370 tdescTy && !tdescTy.getLayoutAttr())
371 setTDescArgLayout(cast<BlockArgument>(regionArg), layout);
376 regionOp.getPredecessorValues(regionSuccessor, inputIdx, predValues);
377 for (
Value predVal : predValues) {
379 for (
OpOperand &operand : regionOp->getOpOperands()) {
380 if (operand.get() == predVal)
381 setOperandLayout(operand, layout);
416 void visitTerminator(RegionBranchTerminatorOpInterface terminator)
override {
421 void visitRegionOp(RegionBranchOpInterface regionOp)
override {
423 for (OpResult
result : regionOp->getResults()) {
428 if (
auto tdescTy = dyn_cast<xegpu::TensorDescType>(
result.getType());
429 tdescTy && !tdescTy.getLayoutAttr())
436 void visitRegularOp(Operation *op)
override {
437 if (!isa<xegpu::AnchorLayoutInterface>(op))
445 LayoutRecovery recovery;
450template <
typename T,
typename>
452 Operation *owner = operandOrResult.getOwner();
471 if (isa<DistributeLayoutAttr>(namedAttr.getValue()))
472 attrsToRemove.push_back(namedAttr.getName());
474 for (
auto attrName : attrsToRemove)
483 if (isa<xegpu::DistributeLayoutAttr>(namedAttr.getValue()))
484 attrsToRemove.push_back(namedAttr.getName());
486 for (
auto attrName : attrsToRemove)
495 auto toI32Attr = [&](
auto range) {
499 return xegpu::LayoutAttr::get(context,
nullptr,
500 nullptr, toI32Attr(instData),
501 toI32Attr(laneLayout), toI32Attr(laneData),
508 return !llvm::any_of(llvm::seq<int>(0, dataShape.size()), [&](
int dim) {
509 return dataShape[dim] % (laneLayout[dim] * laneData[dim]) != 0;
513static xegpu::LayoutAttr
517 auto toI32Attr = [&](
auto range) {
521 return xegpu::LayoutAttr::get(context,
nullptr,
523 nullptr, toI32Attr(laneLayout),
524 toI32Attr(laneData), orderAttr);
527static xegpu::LayoutAttr
532 auto toI32Attr = [&](
auto range) {
536 return xegpu::LayoutAttr::get(
537 context, sgLayout.empty() ?
nullptr : toI32Attr(sgLayout),
538 sgData.empty() ?
nullptr : toI32Attr(sgData),
539 instData.empty() ?
nullptr : toI32Attr(instData),
540 laneLayout.empty() ?
nullptr : toI32Attr(laneLayout),
541 laneData.empty() ?
nullptr : toI32Attr(laneData), orderAttr);
550 for (
int dim = 0; dim < (int)sgLayout.size(); ++dim) {
552 sgData[dim] = wgTileShape[dim];
554 sgData[dim] = wgTileShape[dim] / sgLayout[dim];
563xegpu::DistributeLayoutAttr
569 size_t dimDiff = resShape.size() - srcShape.size();
570 auto bcastSourceLayout = resLayout;
573 for (
size_t i = dimDiff; i < resShape.size(); i++) {
574 if ((srcShape[i - dimDiff] == 1) && (resShape[i] != 1))
575 bcastDims.push_back(i);
580 if (!bcastDims.empty())
581 bcastSourceLayout = bcastSourceLayout.setUnitDimData(bcastDims);
586 bool isOuterDimDiffUnitDims = llvm::all_of(
587 resShape.take_front(dimDiff), [&](
int64_t dim) { return dim == 1; });
588 if (dimDiff && bcastDims.size() == dimDiff && isOuterDimDiffUnitDims) {
591 sliceDims.assign(bcastDims.begin(), bcastDims.end());
595 llvm::append_range(sliceDims, llvm::seq<int64_t>(0, dimDiff));
597 bcastSourceLayout = xegpu::SliceAttr::get(
598 resLayout.getContext(), bcastSourceLayout,
601 return bcastSourceLayout;
606xegpu::DistributeLayoutAttr
610 assert(isa<xegpu::SliceAttr>(resLayout) &&
611 "reduction result layout must be slice layout");
613 xegpu::SliceAttr sliceLayout = dyn_cast<xegpu::SliceAttr>(resLayout);
615 assert((reduceDims == sliceLayout.getDims().asArrayRef()) &&
616 "reduction dims must match with slice dims");
618 return sliceLayout.getParent();
621xegpu::DistributeLayoutAttr
632xegpu::DistributeLayoutAttr
643xegpu::DistributeLayoutAttr
645 int resElemTyBitWidth,
int srcElemTyBitWidth) {
650 size_t sgDataSize = sgData.size();
651 size_t instDataSize = instData.size();
652 size_t laneDataSize = laneData.size();
656 int64_t dim = resLayout.getRank() - 1;
658 if (srcElemTyBitWidth <= resElemTyBitWidth) {
659 int bitWidthRatio = resElemTyBitWidth / srcElemTyBitWidth;
661 sgDataValue = sgData.back() * bitWidthRatio;
663 instDataValue = instData.back() * bitWidthRatio;
665 laneDataValue = laneData.back() * bitWidthRatio;
667 int bitWidthRatio = srcElemTyBitWidth / resElemTyBitWidth;
669 assert((sgData.back() % bitWidthRatio) == 0 &&
670 "sgData not divisible by bitWidthRatio");
671 sgDataValue = sgData.back() / bitWidthRatio;
674 assert((instData.back() % bitWidthRatio) == 0 &&
675 "instData not divisible by bitWidthRatio");
676 instDataValue = instData.back() / bitWidthRatio;
679 assert((laneData.back() % bitWidthRatio) == 0 &&
680 "laneData not divisible by bitWidthRatio");
681 laneDataValue = laneData.back() / bitWidthRatio;
685 xegpu::DistributeLayoutAttr finalSrcLayout;
687 resLayout.setDimData(dim, sgDataValue, instDataValue, laneDataValue);
689 return finalSrcLayout;
696xegpu::DistributeLayoutAttr
702 size_t sgDataSize = sgData.size();
703 size_t instDataSize = instData.size();
704 size_t laneDataSize = laneData.size();
708 int64_t dim = resLayout.getRank() - 1;
712 constexpr int ratio = 2;
714 assert((sgData.back() % ratio) == 0 &&
715 "sgData not divisible by interleave ratio");
716 sgDataValue = sgData.back() / ratio;
719 assert((instData.back() % ratio) == 0 &&
720 "instData not divisible by interleave ratio");
721 instDataValue = instData.back() / ratio;
724 assert((laneData.back() % ratio) == 0 &&
725 "laneData not divisible by interleave ratio");
726 laneDataValue = laneData.back() / ratio;
729 return resLayout.setDimData(dim, sgDataValue, instDataValue, laneDataValue);
736xegpu::DistributeLayoutAttr
742 size_t sgDataSize = sgData.size();
743 size_t instDataSize = instData.size();
744 size_t laneDataSize = laneData.size();
748 int64_t dim = resLayout.getRank() - 1;
752 constexpr int ratio = 2;
754 sgDataValue = sgData.back() * ratio;
756 instDataValue = instData.back() * ratio;
758 laneDataValue = laneData.back() * ratio;
760 return resLayout.setDimData(dim, sgDataValue, instDataValue, laneDataValue);
770 int srcShapeSize = srcShape.size();
771 int resShapeSize = resShape.size();
772 int dimDiff = resShapeSize - srcShapeSize;
777 auto resSgLayout = resLayout.getEffectiveSgLayoutAsInt();
778 auto resLaneLayout = resLayout.getEffectiveLaneLayoutAsInt();
779 for (
int i = 0; i < dimDiff; i++) {
780 assert((resSgLayout.size() == 0 || resSgLayout[i] == 1) &&
781 (resLaneLayout.size() == 0 || resLaneLayout[i] == 1) &&
782 "Leading dimensions being sliced off must not be distributed");
784 return resLayout.dropDims(llvm::to_vector(llvm::seq<int64_t>(0, dimDiff)));
793xegpu::DistributeLayoutAttr
798 int srcShapeSize = srcShape.size();
799 int resShapeSize = resShape.size();
800 int dimDiff = resShapeSize - srcShapeSize;
805 auto resSgLayout = resLayout.getEffectiveSgLayoutAsInt();
806 auto resLaneLayout = resLayout.getEffectiveLaneLayoutAsInt();
807 for (
int i = 0; i < dimDiff; i++) {
808 assert((resSgLayout.size() == 0 || resSgLayout[i] == 1) &&
809 (resLaneLayout.size() == 0 || resLaneLayout[i] == 1) &&
810 "Leading dimensions being sliced off must not be distributed");
812 return resLayout.dropDims(llvm::to_vector(llvm::seq<int64_t>(0, dimDiff)));
822xegpu::DistributeLayoutAttr
827 int srcShapeSize = srcShape.size();
828 int resShapeSize = resShape.size();
829 int dimDiff = srcShapeSize - resShapeSize;
830 auto context = resLayout.getContext();
834 auto sgLayout = resLayout.getEffectiveSgLayoutAsInt();
835 auto sgData = resLayout.getEffectiveSgDataAsInt();
836 auto instData = resLayout.getEffectiveInstDataAsInt();
837 auto laneLayout = resLayout.getEffectiveLaneLayoutAsInt();
838 auto laneData = resLayout.getEffectiveLaneDataAsInt();
839 auto order = resLayout.getEffectiveOrderAsInt();
849 for (
auto &o : order)
855 for (
int i = 0; i < dimDiff; i++) {
856 if (!sgLayout.empty())
857 sgLayout.insert(sgLayout.begin(), 1);
859 sgData.insert(sgData.begin(), 1);
860 if (!instData.empty())
861 instData.insert(instData.begin(), 1);
862 if (!laneLayout.empty())
863 laneLayout.insert(laneLayout.begin(), 1);
864 if (!laneData.empty())
865 laneData.insert(laneData.begin(), 1);
866 order.push_back(dimDiff - 1 - i);
871 if (!resLayout.getOrder())
874 return buildLayout(context, sgLayout, sgData, instData, laneLayout,
875 laneData, orderAttr);
882xegpu::DistributeLayoutAttr
906 xegpu::SliceAttr::get(resLayout.getContext(), resLayout, sliceDimsAttr);
913 auto srcLayout = resLayout;
916 for (
const auto &dimGroup : llvm::reverse(splitDimGroups))
917 srcLayout = srcLayout.collapseDims(dimGroup);
926 auto srcLayout = resLayout;
927 for (
int64_t dstIdx =
static_cast<int64_t>(collapseDims.size()) - 1;
928 dstIdx >= 0; --dstIdx) {
930 if (srcDims.empty()) {
931 srcLayout = srcLayout.dropDims({dstIdx});
934 if (srcDims.size() == 1)
937 targetShape.reserve(srcDims.size());
939 targetShape.push_back(srcShape[d]);
940 srcLayout = srcLayout.expandDim(dstIdx, targetShape);
958xegpu::DistributeLayoutAttr
961 return srcLayout.transposeDims(permutation);
972xegpu::DistributeLayoutAttr
981 auto resLayout = srcLayout;
984 for (
int64_t srcIdx =
static_cast<int64_t>(splitDimGroups.size()) - 1;
985 srcIdx >= 0; --srcIdx) {
987 if (resDims.size() <= 1)
990 targetShape.reserve(resDims.size());
992 targetShape.push_back(resShape[d]);
993 resLayout = resLayout.expandDim(srcIdx, targetShape);
1002 auto resLayout = srcLayout;
1005 for (
int64_t dstIdx =
static_cast<int64_t>(collapseDims.size()) - 1;
1006 dstIdx >= 0; --dstIdx) {
1010 if (srcDims.empty())
1012 if (srcDims.size() == 1)
1014 resLayout = resLayout.collapseDims(llvm::to_vector(srcDims));
1031 if (
auto transpose = dyn_cast<vector::TransposeOp>(op)) {
1032 if (!operandLayouts[0])
1035 transpose.getPermutation());
1039 if (
auto shapeCast = dyn_cast<vector::ShapeCastOp>(op)) {
1040 if (!operandLayouts[0])
1043 operandLayouts[0], shapeCast.getSourceVectorType().getShape(),
1044 shapeCast.getResultVectorType().getShape());
1050 for (xegpu::DistributeLayoutAttr layout : operandLayouts)
1087 auto getDivisors = [](
int64_t n) {
1089 for (
int64_t i = 1; i * i <= n; ++i) {
1093 divs.push_back(n / i);
1102 if (dim == rank - 1) {
1103 current[dim] = remaining;
1107 for (
int64_t factor : getDivisors(remaining)) {
1108 current[dim] = factor;
1109 generate(dim + 1, remaining / factor);
1135 int64_t rank = wgShape.size();
1136 assert(rank > 0 &&
"wgShape must be non-empty");
1137 assert(
static_cast<int64_t>(instData.size()) == rank &&
1138 "instData rank must match wgShape rank");
1145 for (
const auto &sgLayout : allFactorizations) {
1147 for (
int64_t dim = 0; dim < rank; ++dim) {
1151 if (dim == broadcastDim) {
1152 sgData = wgShape[dim];
1154 if (wgShape[dim] % sgLayout[dim] != 0) {
1158 sgData = wgShape[dim] / sgLayout[dim];
1160 if (sgData % instData[dim] != 0) {
1166 candidates.push_back(sgLayout);
1172 int64_t spreadLhs = *llvm::max_element(lhs) - *llvm::min_element(lhs);
1173 int64_t spreadRhs = *llvm::max_element(rhs) - *llvm::min_element(rhs);
1174 if (spreadLhs != spreadRhs)
1175 return spreadLhs < spreadRhs;
1186 bool transform =
false,
bool transpose =
false) {
1187 int rank = dataShape.size();
1191 return std::nullopt;
1192 auto [bWidths, bHeights, bCounts] = blockWHC.value();
1198 assert(rank >= 2 &&
"dataShape must be at least 2D for 2D-block IO");
1205 if (instWidth < 0 || instHeight < 0)
1206 return std::nullopt;
1207 instData.back() = instWidth;
1208 instData[rank - 2] = instHeight;
1224 auto [bWidths, bHeights, bCounts] = blockWHC.value();
1225 int rank = dataShape.size();
1226 assert(rank >= 2 &&
"dataShape must be at least 2D for 2D-block IO");
1229 for (
int width : bWidths) {
1230 if (width <= 0 || dataShape[rank - 1] % width != 0)
1232 for (
int height : bHeights) {
1233 if (height <= 0 || dataShape[rank - 2] % height != 0)
1236 instData[rank - 1] = width;
1237 instData[rank - 2] = height;
1238 instDataCandidates.push_back(std::move(instData));
1245 int64_t hL = lhs[rank - 2], wL = lhs[rank - 1];
1246 int64_t hR = rhs[rank - 2], wR = rhs[rank - 1];
1247 if (hL * wL != hR * wR)
1248 return hL * wL > hR * wR;
1249 if (std::min(hL, wL) != std::min(hR, wR))
1250 return std::min(hL, wL) > std::min(hR, wR);
1256 if (!sgLayouts.empty())
1257 return buildSgLayout(context, dataShape, sgLayouts.front(), -1);
1268 VectorType aTy, VectorType bTy, VectorType cdTy,
1272 const unsigned dataALen = aTy.getShape()[aTy.getRank() - 2];
1273 auto supportedALen = uArchInstruction->
getSupportedM(aTy.getElementType());
1278 const unsigned dataBLen = bTy.getShape().back();
1279 auto supportedBLen = uArchInstruction->
getSupportedN(bTy.getElementType());
1283 auto supportedCLen = uArchInstruction->
getSupportedN(cdTy.getElementType());
1286 if (maxALen == -1 || maxBLen == -1 || maxCLen == -1)
1287 return std::nullopt;
1289 auto supportedKLen = uArchInstruction->
getSupportedK(aTy.getElementType());
1290 if (supportedKLen.empty())
1291 return std::nullopt;
1292 auto kDimSize = supportedKLen[0];
1295 instDataA[aTy.getRank() - 2] = maxALen;
1296 instDataA[aTy.getRank() - 1] = kDimSize;
1298 instDataB[bTy.getRank() - 2] = kDimSize;
1299 instDataB[bTy.getRank() - 1] = maxBLen;
1301 instDataCD[cdTy.getRank() - 2] = maxALen;
1302 instDataCD[cdTy.getRank() - 1] = maxCLen;
1303 return std::make_tuple(instDataA, instDataB, instDataCD);
1316 int64_t rank = instShape.size();
1319 laneLayout[innermost] = std::min(subgroupSize, instShape[innermost]);
1320 laneData[innermost] =
1321 std::min(instShape[innermost] / laneLayout[innermost], maxChunkSize);
1322 return {laneLayout, laneData};
1337 bool transform =
false,
bool transpose =
false) {
1338 int64_t rank = instShape.size();
1339 assert(rank >= 2 &&
"Expected at least a 2D shape for a 2D block op");
1343 laneData[packDim] = llvm::divideCeil(packingSize, bitwidth);
1345 int64_t laneDim = transpose ? rank - 2 : rank - 1;
1346 laneLayout[laneDim] =
1347 std::min(subgroupSize, instShape[laneDim] / laneData[laneDim]);
1350 for (
int64_t i = 0; i < rank; ++i)
1351 order.push_back(rank - 1 - i);
1352 std::swap(order[0], order[1]);
1356 for (
int64_t i = 0; i < rank; ++i) {
1357 int64_t laneProduct = laneLayout[i] * laneData[i];
1358 assert(instShape[i] % laneProduct == 0 &&
1359 "lane_layout * lane_data must evenly divide the inst shape");
1362 return {laneLayout, laneData, order};
1424 int subgroupSize,
int64_t maxReduceVectorSize,
1425 xegpu::DistributeLayoutAttr consumerLayout =
nullptr) {
1426 int srcRank = srcShape.size();
1428 auto isReduced = [&](
int dim) {
1429 return llvm::is_contained(reductionDims, dim);
1435 auto consumerSlice = dyn_cast_if_present<xegpu::SliceAttr>(consumerLayout);
1436 bool reusedParent =
false;
1437 if (consumerSlice &&
1438 consumerSlice.getDims().asArrayRef().equals(reductionDims)) {
1439 auto parent = consumerSlice.getParent();
1441 parent.getEffectiveLaneLayoutAsInt();
1443 if (
static_cast<int>(parentLaneLayout.size()) == srcRank &&
1444 static_cast<int>(parentLaneData.size()) == srcRank &&
1446 laneLayout = std::move(parentLaneLayout);
1447 laneData = std::move(parentLaneData);
1448 reusedParent =
true;
1449 parentInstData = parent.getEffectiveInstDataAsInt();
1450 if (
static_cast<int>(parentInstData.size()) != srcRank)
1451 parentInstData.clear();
1455 for (
int i = 0; i < srcRank; ++i)
1456 laneLayout[i] = std::min(
1457 laneLayout[i], std::max<int64_t>(1, srcShape[i] / laneData[i]));
1463 if (!reusedParent) {
1465 if (consumerLayout) {
1466 consumerLaneLayout = consumerLayout.getEffectiveLaneLayoutAsInt();
1467 consumerLaneData = consumerLayout.getEffectiveLaneDataAsInt();
1469 for (
int i = 0, c = 0; i < srcRank; ++i) {
1472 if (c <
static_cast<int>(consumerLaneLayout.size()))
1473 laneLayout[i] = consumerLaneLayout[c];
1474 if (c <
static_cast<int>(consumerLaneData.size()))
1475 laneData[i] = consumerLaneData[c];
1480 for (
int i = 0; i < srcRank; ++i)
1481 laneLayout[i] = std::min(laneLayout[i],
1482 std::max<int64_t>(1, srcShape[i] / laneData[i]));
1487 int innermost = srcRank - 1;
1488 if (isReduced(innermost)) {
1492 laneLayout[innermost] =
1493 std::min(spareLanes, std::max<int64_t>(1, srcShape[innermost]));
1495 if (laneLayout[innermost] == 1) {
1499 if (vectorBudget > 1)
1500 laneData[innermost] =
1501 std::min(vectorBudget * laneData[innermost], srcShape[innermost]);
1512 int firstInnerDim = std::max(0, srcRank - 2);
1513 for (
int i = 0; i < srcRank; ++i) {
1514 instData[i] = laneLayout[i] * laneData[i];
1515 if (isReduced(i) || i < firstInnerDim || parentInstData.empty())
1519 int64_t wider = parentInstData[i];
1520 if (wider > instData[i] && wider % instData[i] == 0 &&
1521 srcShape[i] % wider == 0)
1522 instData[i] = wider;
1525 return {laneLayout, laneData, instData};
1588static std::optional<
1589 std::tuple<xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr,
1590 xegpu::DistributeLayoutAttr>>
1593 xegpu::DistributeLayoutAttr consumerLayout,
int numSg,
1601 std::optional<LayoutRepresentation> consumerSgLayout = std::nullopt;
1602 if (consumerLayout && consumerLayout.isForWorkgroup()) {
1603 consumerSgLayout = consumerLayout.getEffectiveSgLayoutAsInt();
1608 auto pickSgLayout = [&]() -> std::optional<LayoutRepresentation> {
1614 if (layoutsA.empty() || layoutsB.empty() || layoutsCD.empty())
1615 return std::nullopt;
1617 std::optional<LayoutRepresentation> bestPick;
1618 for (
auto &sgLayout : layoutsB) {
1619 if (llvm::is_contained(layoutsA, sgLayout) &&
1620 llvm::is_contained(layoutsCD, sgLayout)) {
1622 if (consumerSgLayout.has_value() && sgLayout == *consumerSgLayout)
1629 bestPick = sgLayout;
1637 int64_t mDimA = aTy.getRank() - 2;
1638 int64_t mDimCD = cdTy.getRank() - 2;
1639 auto supportedM = uArchInstruction->
getSupportedM(aTy.getElementType());
1640 llvm::sort(supportedM, std::greater<uint32_t>());
1642 std::optional<LayoutRepresentation> bestPick;
1643 for (
unsigned m : supportedM) {
1644 if (m == 0 || aTy.getShape()[mDimA] % m != 0)
1646 instDataA[mDimA] = m;
1647 instDataCD[mDimCD] = m;
1648 if ((bestPick = pickSgLayout()))
1652 return std::nullopt;
1654 const auto &picked = *bestPick;
1656 auto dpasALayout =
buildSgLayout(context, aTy.getShape(), picked,
1658 auto dpasBLayout =
buildSgLayout(context, bTy.getShape(), picked,
1660 auto dpasCDLayout =
buildSgLayout(context, cdTy.getShape(), picked);
1661 return std::make_tuple(dpasALayout, dpasBLayout, dpasCDLayout);
1668 std::tuple<xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr,
1669 xegpu::DistributeLayoutAttr>>
1671 VectorType bTy, VectorType cdTy,
1672 xegpu::DistributeLayoutAttr consumerLayout,
int numSg,
1674 auto context = aTy.getContext();
1675 const auto *uArchInstruction =
1676 dyn_cast<xegpu::uArch::SubgroupMatrixMultiplyAcc>(uArch->
getInstruction(
1678 if (!uArchInstruction)
1679 return std::nullopt;
1682 auto [laneLayoutA, laneDataA, orderA] =
1684 aTy.getElementType().getIntOrFloatBitWidth(),
1685 uArchInstruction->getPackedFormatBitSizeA());
1687 bTy.getShape(), subgroupSize,
1688 bTy.getElementType().getIntOrFloatBitWidth(),
1689 uArchInstruction->getPackedFormatBitSizeB(),
true);
1690 auto [laneLayoutCD, laneDataCD, orderCD] =
1692 cdTy.getElementType().getIntOrFloatBitWidth(),
1693 cdTy.getElementType().getIntOrFloatBitWidth());
1697 return std::nullopt;
1701 "Number of subgroups must be provided for sg layout creation.");
1703 numSg, *instDataVecs, uArchInstruction);
1705 auto [instDataA, instDataB, instDataCD] = *instDataVecs;
1706 return std::make_tuple(
1715 return std::make_tuple(aLayout, bLayout, cdLayout);
1717 return std::nullopt;
1724static xegpu::DistributeLayoutAttr
1726 VectorType scaleTy, xegpu::DistributeLayoutAttr matrixLayout,
1728 if (!scaleTy || !matrixLayout)
1736 if (scaleShape.empty())
1739 auto uArchInstruction =
1740 dyn_cast<xegpu::uArch::SubgroupScaledMatrixMultiplyAcc>(
1744 int64_t rank = matrixLayout.getRank();
1745 assert(rank >= 2 &&
"dpas layouts must be at least two dimensions");
1752 auto order = matrixLayout.getOrder();
1756 if (!sgLayout.empty() && !sgData.empty()) {
1757 scaleSgLayout.assign(sgLayout.begin(), sgLayout.end());
1758 scaleSgData.assign(sgData.begin(), sgData.end());
1759 scaleSgData[rank - 2] = std::max<int64_t>(
1760 scaleShape[rank - 2] / (matrixShape[rank - 2] / sgData[rank - 2]), 1);
1761 scaleSgData[rank - 1] = std::max<int64_t>(
1762 scaleShape[rank - 1] / (matrixShape[rank - 1] / sgData[rank - 1]), 1);
1769 if (!instData.empty()) {
1770 scaleInstData.assign(instData.begin(), instData.end());
1772 scaleInstData[rank - 2] = std::max<int64_t>(
1773 scaleShape[rank - 2] / (matrixShape[rank - 2] / instData[rank - 2]),
1776 scaleInstData[rank - 1] = std::max<int64_t>(
1777 scaleShape[rank - 1] / (matrixShape[rank - 1] / instData[rank - 1]),
1783 if (!laneLayout.empty() && !laneData.empty()) {
1784 scaleLaneLayout.assign(laneLayout.begin(), laneLayout.end());
1785 scaleLaneData.assign(laneData.size(), 1);
1787 bool isRowMajor = uArchInstruction->isLaneLayoutRowMajorOrder();
1788 if (isBScale ^ isRowMajor)
1789 std::swap(scaleLaneLayout[rank - 2], scaleLaneLayout[rank - 1]);
1794 auto layoutCap = scaleInstData.empty() ? scaleShape : scaleInstData;
1795 for (
int64_t d = rank - 2; d < rank; ++d)
1796 scaleLaneLayout[d] = std::min<int64_t>(layoutCap[d], scaleLaneLayout[d]);
1798 return buildLayout(context, scaleSgLayout, scaleSgData, scaleInstData,
1799 scaleLaneLayout, scaleLaneData, order);
1806 std::tuple<xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr,
1807 xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr,
1808 xegpu::DistributeLayoutAttr>>
1810 VectorType bTy, VectorType cdTy, VectorType aScaleTy,
1811 VectorType bScaleTy,
1812 xegpu::DistributeLayoutAttr consumerLayout,
int numSg,
1814 auto context = aTy.getContext();
1815 const auto *uArchInstruction =
1816 dyn_cast<xegpu::uArch::SubgroupMatrixMultiplyAcc>(uArch->
getInstruction(
1818 if (!uArchInstruction)
1819 return std::nullopt;
1822 auto [laneLayoutA, laneDataA, orderA] =
1824 aTy.getElementType().getIntOrFloatBitWidth(),
1825 uArchInstruction->getPackedFormatBitSizeA());
1827 bTy.getShape(), subgroupSize,
1828 bTy.getElementType().getIntOrFloatBitWidth(),
1829 uArchInstruction->getPackedFormatBitSizeB(),
true);
1830 auto [laneLayoutCD, laneDataCD, orderCD] =
1832 cdTy.getElementType().getIntOrFloatBitWidth(),
1833 cdTy.getElementType().getIntOrFloatBitWidth());
1836 return std::nullopt;
1840 "Number of subgroups must be provided for sg layout creation.");
1843 *instDataVecs, uArchInstruction);
1845 return std::nullopt;
1847 auto [dpasALayout, dpasBLayout, dpasCDLayout] = *dpasLayouts;
1856 return std::make_tuple(dpasALayout, dpasBLayout, dpasCDLayout, aScaleLayout,
1860 auto [instDataA, instDataB, instDataCD] = *instDataVecs;
1867 laneLayoutCD, laneDataCD);
1874 return std::make_tuple(dpasALayout, dpasBLayout, dpasCDLayout, aScaleLayout,
1879 auto dpasCDLayout =
buildLaneLayout(context, laneLayoutCD, laneDataCD);
1886 return std::make_tuple(dpasALayout, dpasBLayout, dpasCDLayout, aScaleLayout,
1889 return std::nullopt;
1901 assert(dataShape.size() >= 2 &&
"Expected at least 2D shape for ND op");
1905 auto [laneLayout, laneData, order] =
1920 "Expected the block IO layout to satisfy uArch block constraints");
1927 "Number of subgroups must be provided for sg layout creation.");
1929 uArchInstruction, numSg);
1938xegpu::DistributeLayoutAttr
1940 VectorType srcVecTy,
int numSg,
1942 const auto *uArchInstruction =
1943 dyn_cast<xegpu::uArch::Subgroup2DBlockStoreInstruction>(
1944 uArch->getInstruction(
1946 if (!uArchInstruction)
1949 srcVecTy.getElementType(), numSg,
1950 uArchInstruction,
uArch);
1956xegpu::DistributeLayoutAttr
1958 xegpu::TensorDescType tdescTy,
int numSg,
1960 const auto *uArchInstruction =
1961 dyn_cast<xegpu::uArch::Subgroup2DBlockPrefetchInstruction>(
1964 if (!uArchInstruction)
1967 tdescTy.getElementType(), numSg,
1968 uArchInstruction, uArch);
1976xegpu::DistributeLayoutAttr
1978 VectorType resVecTy,
1979 xegpu::DistributeLayoutAttr consumerLayout,
1983 if (!consumerLayout) {
1984 const auto *uArchInstruction =
1985 dyn_cast<xegpu::uArch::Subgroup2DBlockLoadInstruction>(
1988 if (!uArchInstruction)
1991 resVecTy.getElementType(), numSg,
1992 uArchInstruction, uArch);
1995 assert(consumerLayout.isForWorkgroup() &&
1996 "Expected consumer layout to be a complete workgroup-level layout");
1997 return consumerLayout;
2000 auto context = resVecTy.getContext();
2001 Type elemTy = resVecTy.getElementType();
2003 auto dataShape = resVecTy.getShape();
2004 const auto *uArchInstruction =
2005 dyn_cast<xegpu::uArch::Subgroup2DBlockLoadInstruction>(
2008 if (!uArchInstruction)
2011 int rank = resVecTy.getRank();
2013 consumerLayout.getEffectiveInstDataAsInt();
2015 consumerLayout.getEffectiveLaneLayoutAsInt();
2017 consumerLayout.getEffectiveLaneDataAsInt();
2019 assert(!consumerLaneLayout.empty() && !consumerLaneData.empty() &&
2020 "Expected consumer layout to have lane_layout and lane_data");
2026 consumerLaneLayout[rank - 2] > 1 && consumerLaneLayout[rank - 1] == 1;
2031 bool hasTransform = !hasTranspose && canTransform &&
2032 consumerLaneData[rank - 2] > 1 &&
2033 consumerLaneData[rank - 1] == 1;
2034 assert((consumerLaneData[rank - 2] == 1 || consumerLaneData[rank - 1] == 1) &&
2035 "Expected consumer lane data to have at most one non-unit dim");
2038 auto blockWHC = uArchInstruction->getBlockWidthHeightCount(
2039 elemTy, hasTransform, hasTranspose,
2043 auto [bWidths, bHeights, bCounts] = blockWHC.value();
2048 unsigned packingSize = hasTransform || hasTranspose
2050 : uArchInstruction->getPackedFormatBitSize();
2053 hasTransform, hasTranspose);
2061 int64_t height = consumerInstData[rank - 2];
2062 int64_t width = consumerInstData[rank - 1];
2063 auto maxBlockCount = *llvm::max_element(bCounts);
2064 auto maxWidth = *llvm::max_element(bWidths);
2065 if (llvm::is_contained(bWidths,
static_cast<int>(width)) ||
2066 (width % maxWidth == 0 && width / maxWidth < maxBlockCount)) {
2067 if (llvm::is_contained(bHeights,
static_cast<int>(height))) {
2069 "Expected the load layout to satisfy uArch block constraints");
2071 laneLayout, laneData, orderAttr);
2083 if (!hasTranspose && !hasTransform &&
2084 consumerInstData[rank - 1] %
2085 (laneLayout[rank - 1] * laneData[rank - 1]) !=
2090 hasTransform =
true;
2097 dataShape, elemTy, uArchInstruction, hasTransform, hasTranspose);
2102 "Expected the load layout to satisfy uArch block constraints");
2108 "Expected the lane layout to satisfy uArch block constraints");
2109 return consumerLayout;
2116static xegpu::DistributeLayoutAttr
2121 if (candidates.empty())
2124 return buildSgLayout(context, wgShape, candidates.front(), -1);
2133 auto [laneLayout, laneData] =
2137 for (
size_t i = 0; i < srcShape.size(); ++i)
2138 instData[i] = laneLayout[i] * laneData[i];
2142 "Number of subgroups must be provided for sg layout creation.");
2162 xegpu::DistributeLayoutAttr consumerLayout,
int maxChunkSize,
2165 if (!consumerLayout)
2167 resShape, subgroupSize, numSg);
2169 return consumerLayout;
2172 consumerLayout.getEffectiveInstDataAsInt();
2174 consumerLayout.getEffectiveLaneLayoutAsInt();
2176 consumerLayout.getEffectiveLaneDataAsInt();
2178 assert(!consumerLaneLayout.empty() && !consumerLaneData.empty() &&
2179 "Expected consumer layout to have lane_layout and lane_data");
2186 std::min(consumerLaneData.back(),
static_cast<int64_t>(maxChunkSize));
2190 instData.resize(resShape.size());
2191 for (
size_t i = 0; i < resShape.size(); ++i)
2192 instData[i] = laneLayout[i] * laneData[i];
2201xegpu::DistributeLayoutAttr
2203 VectorType resVecTy,
int contigChunkSize,
2204 xegpu::DistributeLayoutAttr consumerLayout,
2205 int numSg,
const uArch::uArch *uArch) {
2207 const int subgroupSize = uArch->getSubgroupSize();
2209 auto context = resVecTy.getContext();
2213 const auto *uArchInstruction = dyn_cast<xegpu::uArch::LoadGatherInstruction>(
2216 std::min(uArchInstruction->getMaxLaneAccessSizeBytes(), contigChunkSize);
2219 maxChunkSize, resShape, subgroupSize,
2227 xegpu::DistributeLayoutAttr consumerLayout,
int numSg,
2232 auto context = resVecTy.getContext();
2234 const auto *uArchInstruction = dyn_cast<xegpu::uArch::LoadGatherInstruction>(
2237 std::min(uArchInstruction->getMaxLaneAccessSizeBytes(), contigChunkSize);
2239 maxChunkSize, resShape, subgroupSize,
2244xegpu::DistributeLayoutAttr
2246 VectorType srcVecTy,
int contigChunkSize,
2249 const int subgroupSize =
uArch->getSubgroupSize();
2251 auto context = srcVecTy.getContext();
2255 const auto *uArchInstruction =
2256 dyn_cast<xegpu::uArch::StoreScatterInstruction>(
2259 std::min(uArchInstruction->getMaxLaneAccessSizeBytes(), contigChunkSize);
2261 srcShape, subgroupSize, numSg);
2269 const int subgroupSize =
uArch->getSubgroupSize();
2271 auto context = srcVecTy.getContext();
2273 const auto *uArchInstruction =
2274 dyn_cast<xegpu::uArch::StoreScatterInstruction>(
2277 std::min(uArchInstruction->getMaxLaneAccessSizeBytes(), contigChunkSize);
2280 srcShape, subgroupSize, numSg);
2298std::optional<xegpu::DistributeLayoutAttr>
2300 xegpu::DistributeLayoutAttr specifiedLayout,
2301 xegpu::DistributeLayoutAttr consumerLayout,
Type elemTy,
2303 const int subgroupSize) {
2304 if (!specifiedLayout)
2305 return specifiedLayout;
2307 specifiedLayout.getEffectiveInstDataAsInt();
2308 if (specifiedInstData.empty())
2309 return specifiedLayout;
2310 if (!specifiedLayout.getEffectiveLaneLayoutAsInt().empty() &&
2311 !specifiedLayout.getEffectiveLaneDataAsInt().empty())
2312 return specifiedLayout;
2315 auto *context = specifiedLayout.getContext();
2317 if (consumerLayout) {
2318 auto consumerLaneLayout = consumerLayout.getEffectiveLaneLayoutAsInt();
2319 auto consumerLaneData = consumerLayout.getEffectiveLaneDataAsInt();
2320 if (!consumerLaneLayout.empty() && !consumerLaneData.empty() &&
2324 consumerLaneLayout, consumerLaneData);
2327 specifiedInstData, subgroupSize, maxChunkSize);
2329 return std::nullopt;
2337std::optional<xegpu::DistributeLayoutAttr>
2339 xegpu::DistributeLayoutAttr specifiedLayout,
Type elemTy,
2341 const int subgroupSize) {
2342 if (!specifiedLayout)
2343 return specifiedLayout;
2345 specifiedLayout.getEffectiveInstDataAsInt();
2346 if (specifiedInstData.empty())
2347 return specifiedLayout;
2348 if (!specifiedLayout.getEffectiveLaneLayoutAsInt().empty() &&
2349 !specifiedLayout.getEffectiveLaneDataAsInt().empty())
2350 return specifiedLayout;
2353 auto *context = specifiedLayout.getContext();
2356 specifiedInstData, subgroupSize, maxChunkSize);
2358 return std::nullopt;
2367std::optional<xegpu::DistributeLayoutAttr>
2369 xegpu::DistributeLayoutAttr specifiedLayout,
Type elemTy,
2371 const int subgroupSize) {
2372 if (!specifiedLayout)
2373 return specifiedLayout;
2375 specifiedLayout.getEffectiveInstDataAsInt();
2376 if (specifiedInstData.empty())
2377 return specifiedLayout;
2378 if (!specifiedLayout.getEffectiveLaneLayoutAsInt().empty() &&
2379 !specifiedLayout.getEffectiveLaneDataAsInt().empty())
2380 return specifiedLayout;
2382 auto *context = specifiedLayout.getContext();
2387 return std::nullopt;
2396std::optional<xegpu::DistributeLayoutAttr>
2398 xegpu::DistributeLayoutAttr specifiedLayout,
2399 xegpu::DistributeLayoutAttr consumerLayout,
Type elemTy,
2401 const int subgroupSize) {
2402 if (!specifiedLayout)
2403 return specifiedLayout;
2405 specifiedLayout.getEffectiveInstDataAsInt();
2406 if (specifiedInstData.empty())
2407 return specifiedLayout;
2408 if (!specifiedLayout.getEffectiveLaneLayoutAsInt().empty() &&
2409 !specifiedLayout.getEffectiveLaneDataAsInt().empty())
2410 return specifiedLayout;
2411 if (!consumerLayout)
2412 return specifiedLayout;
2414 consumerLayout.getEffectiveLaneLayoutAsInt();
2416 consumerLayout.getEffectiveLaneDataAsInt();
2417 if (consumerLaneLayout.empty() || consumerLaneData.empty())
2418 return specifiedLayout;
2420 auto *context = specifiedLayout.getContext();
2421 int rank = specifiedInstData.size();
2426 for (
int i = 0; i < rank; i++) {
2427 if (consumerLaneLayout[i] > 1) {
2428 laneLayout.push_back(
2429 std::max(
static_cast<int64_t>(subgroupSize), consumerLaneLayout[i]));
2431 laneLayout.push_back(1);
2436 return std::nullopt;
2439 consumerLayout.getOrder());
2447 std::tuple<xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr,
2448 xegpu::DistributeLayoutAttr>>
2450 xegpu::DistributeLayoutAttr bLayout,
2451 xegpu::DistributeLayoutAttr cdLayout,
2452 VectorType aTy, VectorType bTy,
2455 auto context = aTy.getContext();
2456 const auto *uArchInstruction =
2457 dyn_cast<xegpu::uArch::SubgroupMatrixMultiplyAcc>(uArch->
getInstruction(
2459 if (!uArchInstruction)
2460 return std::nullopt;
2463 laneLayoutCD, laneDataCD;
2470 if (isa<xegpu::uArch::Xe2, xegpu::uArch::Xe3p>(uArch)) {
2471 std::tie(laneLayoutA, laneDataA, orderA) =
2473 aTy.getElementType().getIntOrFloatBitWidth(),
2474 uArchInstruction->getPackedFormatBitSizeA());
2476 bTy.getShape(), subgroupSize,
2477 bTy.getElementType().getIntOrFloatBitWidth(),
2478 uArchInstruction->getPackedFormatBitSizeB(),
true);
2480 cdTy.getShape(), subgroupSize,
2481 cdTy.getElementType().getIntOrFloatBitWidth(),
2482 cdTy.getElementType().getIntOrFloatBitWidth());
2484 assert(
false &&
"Unsupported uArch for DPAS lane layout completion");
2490 return std::nullopt;
2491 return std::make_tuple(
2493 aLayout.getOrder()),
2495 bLayout.getOrder()),
2497 cdLayout.getOrder()));
2504 std::tuple<xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr,
2505 xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr,
2506 xegpu::DistributeLayoutAttr>>
2508 xegpu::DistributeLayoutAttr aLayout, xegpu::DistributeLayoutAttr bLayout,
2509 xegpu::DistributeLayoutAttr cdLayout, VectorType aTy, VectorType bTy,
2510 VectorType cdTy, VectorType aScaleTy, VectorType bScaleTy,
2513 aLayout, bLayout, cdLayout, aTy, bTy, cdTy, uArch);
2515 return std::nullopt;
2516 auto context = aTy.getContext();
2517 auto [completedA, completedB, completedCD] = *completed;
2524 return std::make_tuple(completedA, completedB, completedCD, aScaleLayout,
2610 auto srcShape = srcVecTy.getShape();
2611 int srcRank = srcShape.size();
2612 auto context = srcVecTy.getContext();
2614 const int subgroupSize =
uArch->getSubgroupSize();
2615 int64_t maxReduceVectorSize = 16;
2616 xegpu::DistributeLayoutAttr srcLayout;
2618 xegpu::SliceAttr consumerSliceLayout =
2619 dyn_cast_if_present<xegpu::SliceAttr>(consumerLayout);
2620 if (consumerSliceLayout &&
2621 consumerSliceLayout.getDims().asArrayRef().equals(reductionDims)) {
2622 srcLayout = consumerSliceLayout.getParent();
2624 srcLayout.getEffectiveSgLayoutAsInt();
2627 for (
int dim = 0; dim < srcRank; dim++) {
2628 if (llvm::is_contained(reductionDims, dim))
2630 srcLayout.setDimData(dim, srcSgData.value()[dim], -1, -1);
2634 consumerLayout ? consumerLayout.getEffectiveSgLayoutAsInt()
2637 consumerLayout ? consumerLayout.getEffectiveSgDataAsInt()
2640 consumerLayout ? consumerLayout.getEffectiveOrderAsInt()
2643 consumerLayout ? consumerLayout.getOrder() :
nullptr;
2645 int remainingSgCount =
2646 consumerLayout ? consumerLayout.getNumSubgroups() : numSg;
2647 int consumerIdx = 0;
2650 for (
int i = 0; i < srcRank; i++) {
2651 if (!llvm::is_contained(reductionDims, i) &&
2652 consumerIdx <
static_cast<int>(consumerSgLayout.size())) {
2653 sgLayout[i] = consumerSgLayout[consumerIdx];
2654 sgData[i] = consumerSgData[consumerIdx];
2655 remainingSgCount /= sgLayout[i];
2662 for (
int i = 0; i < srcRank; i++) {
2663 if (llvm::is_contained(reductionDims, i)) {
2665 std::min(srcShape[i],
static_cast<int64_t>(remainingSgCount));
2666 assert((srcShape[i] % sgLayout[i] == 0) &&
2667 "source shape not divisible by sg_layout");
2668 sgData[i] = srcShape[i] / sgLayout[i];
2669 remainingSgCount /= sgLayout[i];
2675 int numRetainedDims = srcRank -
static_cast<int>(reductionDims.size());
2676 if (orderAttr && !orderAttr.empty() &&
2677 static_cast<int>(consumerOrder.size()) == numRetainedDims) {
2679 int retainedRank = 0;
2680 for (
int dim = 0; dim < srcRank; dim++)
2681 if (!llvm::is_contained(reductionDims, dim))
2682 order[dim] = consumerOrder[retainedRank++];
2685 for (
int reducedDim = 0; reducedDim < srcRank; reducedDim++) {
2686 if (!llvm::is_contained(reductionDims, reducedDim))
2691 insertRank = order[reducedDim - 1];
2694 else if (srcRank > 1)
2695 insertRank = order[reducedDim + 1] + 1;
2696 for (
int otherDim = 0; otherDim < srcRank; otherDim++)
2697 if (order[otherDim] >= insertRank)
2699 order[reducedDim] = insertRank;
2704 assert(remainingSgCount == 1 &&
"not all subgroups distributed");
2705 srcLayout =
buildLayout(context, sgLayout, sgData,
2710 auto [laneLayout, laneData, instData] =
2712 maxReduceVectorSize, consumerLayout);
2716 xegpu::SliceAttr consumerSliceLayout =
2717 dyn_cast_if_present<xegpu::SliceAttr>(consumerLayout);
2718 if (consumerSliceLayout &&
2719 consumerSliceLayout.getDims().asArrayRef().equals(reductionDims)) {
2723 srcLayout = consumerSliceLayout.getParent();
2726 srcShape, reductionDims, subgroupSize, maxReduceVectorSize,
2733 return xegpu::SliceAttr::get(context, srcLayout,
2741 VectorType srcVecTy,
2744 auto srcShape = srcVecTy.getShape();
2745 auto context = srcVecTy.getContext();
2746 auto subgroupSize =
uArch->getSubgroupSize();
2747 xegpu::LayoutAttr srcLayout;
2751 "subgroup layout assignment not supported for reduction (op "
2752 "is not expected at this level).");
2755 "instData layout assignment not supported for reduction (op "
2756 "is not expected at this level).");
2759 laneLayout[0] = std::min(
static_cast<int64_t>(subgroupSize), srcShape[0]);
2764 auto result = xegpu::SliceAttr::get(context, srcLayout,
2782static xegpu::DistributeLayoutAttr
2785 size_t innerMostDim,
int ratio,
int64_t bound,
2791 consumerLayout.getEffectiveLaneLayoutAsInt();
2798 sgDataValue = sgData[innerMostDim];
2799 while ((sgDataValue <= bound) && (sgDataValue % ratio) != 0)
2802 instDataValue = instData[innerMostDim];
2803 const int innermostDimLaneLayout = laneLayout.empty()
2805 : laneLayout[innerMostDim];
2806 while ((instDataValue <= bound) &&
2807 (instDataValue % (innermostDimLaneLayout * ratio) != 0))
2809 assert((bound % instDataValue) == 0 &&
2810 "bound, instData, and laneLayout for innermost must be 2^n!");
2812 laneDataValue = laneData[innerMostDim];
2813 while ((laneDataValue <= bound) && (laneDataValue % ratio) != 0)
2817 return consumerLayout.setDimData(innerMostDim, sgDataValue, instDataValue,
2847 int srcElemTyBitWidth = srcVecTy.getElementType().getIntOrFloatBitWidth();
2848 int resElemTyBitWidth = resVecTy.getElementType().getIntOrFloatBitWidth();
2853 assert(consumerLayout.getRank() ==
static_cast<int64_t>(srcShape.size()) &&
2854 "laneData must be available for all dimensions");
2858 if (srcElemTyBitWidth <= resElemTyBitWidth)
2859 return consumerLayout;
2864 size_t innerMostDim = srcShape.size() - 1;
2865 int bitWidthRatio = srcElemTyBitWidth / resElemTyBitWidth;
2867 innerMostDim, bitWidthRatio,
2868 resShape[innerMostDim],
uArch);
2891 assert(consumerLayout.getRank() ==
static_cast<int64_t>(resShape.size()) &&
2892 "consumer layout rank must match source shape rank");
2897 const size_t innerMostDim = resShape.size() - 1;
2898 constexpr int ratio = 2;
2900 innerMostDim, ratio,
2901 resShape[innerMostDim],
uArch);
2920 for (
int64_t dim : llvm::reverse(dimGroup)) {
2921 int64_t tileSize = tileShape.empty() ? 1 : tileShape[dim];
2922 if (counts[dim] != 1) {
2923 if (stride * tileSize != expectedStride)
2925 expectedStride = stride * tileSize * counts[dim];
2927 stride *=
shape[dim];
2950 if (llvm::all_of(dimGroup,
2951 [&](
int64_t dim) {
return sgData[dim] ==
shape[dim]; }))
2956 if (llvm::any_of(dimGroup, [&](
int64_t dim) {
2957 return sgLayout[dim] * sgData[dim] >
shape[dim];
2963 auto orderPos = [&](
int64_t dim) {
2964 return std::distance(order.begin(), llvm::find(order, dim));
2967 dimGroup, [&](
int64_t dim) {
return sgLayout[dim] > 1; });
2968 for (
size_t i = 1; i < spreadDims.size(); ++i)
2969 if (orderPos(spreadDims[i]) > orderPos(spreadDims[i - 1]))
2974 collapsedSgData *= sgData[dim];
2988static xegpu::DistributeLayoutAttr
2991 xegpu::DistributeLayoutAttr consumerLayout) {
2994 if (sgLayout.empty())
2995 return consumerLayout;
3001 return consumerLayout;
3005 if (isa<xegpu::SliceAttr>(consumerLayout))
3013 remaining *= sgLayout[dim];
3014 for (
int64_t dim : dimGroup) {
3015 int64_t count = std::min(remaining, resShape[dim]);
3016 if (remaining % count != 0 || resShape[dim] % count != 0)
3018 sgLayout[dim] = count;
3019 sgData[dim] = resShape[dim] / count;
3026 return buildLayout(consumerLayout.getContext(), sgLayout, sgData,
3030xegpu::DistributeLayoutAttr
3032 VectorType srcVecTy, VectorType resVecTy,
3033 DistributeLayoutAttr consumerLayout) {
3034 if (!consumerLayout)
3035 return consumerLayout;
3041 return consumerLayout;
3050 return consumerLayout;
3053 consumerLayout.getEffectiveLaneLayoutAsInt();
3056 xegpu::DistributeLayoutAttr resLayout = [&]() -> DistributeLayoutAttr {
3057 DistributeLayoutAttr layout = consumerLayout;
3060 while (i < dimGroup.size() && laneLayout[dimGroup[i]] == 1)
3063 for (++i; i < dimGroup.size(); ++i) {
3065 int64_t dimSize = resShape[dim];
3066 int64_t lanes = laneLayout[dim];
3067 if (lanes <= 0 || dimSize % lanes != 0)
3068 return consumerLayout;
3070 layout.setDimData(dim, -1,
3071 instData.empty() ? -1 : dimSize, dimSize / lanes);
3089 int64_t collapsedLaneData = 1;
3091 collapsedLaneData *= resLaneData[dim];
3097 if (!resInstData.empty() &&
3110 VectorType resVectorTy, xegpu::DistributeLayoutAttr consumerLayout,
3113 xegpu::DistributeLayoutAttr requiredResLayout;
3115 consumerLayout.getEffectiveInstDataAsInt();
3117 consumerLayout.getEffectiveLaneDataAsInt();
3119 consumerLayout.getEffectiveLaneLayoutAsInt();
3123 requiredResLayout = consumerLayout;
3124 int srcRank = srcShape.size();
3128 assert(
false &&
"subgroup/instData layout assignment not supported for "
3129 "insertStridedSlice.");
3131 for (
int dim = 0; dim < srcRank; dim++) {
3133 if (srcShape[dim] == 1) {
3136 assert(srcShape[dim] % consumerLaneLayout[dim] == 0 &&
3137 "srcShape must be divisible by laneLayout for all dimensions");
3138 laneDataValue = std::min(srcShape[dim] / consumerLaneLayout[dim],
3139 consumerLaneData[dim]);
3142 requiredResLayout.setDimData(dim, -1, -1, laneDataValue);
3145 return requiredResLayout;
3155 OpOperand &operand, xegpu::DistributeLayoutAttr resLayout) {
3162 if (
auto broadcast = dyn_cast<vector::BroadcastOp>(op)) {
3163 auto srcTy = dyn_cast<VectorType>(
broadcast.getSourceType());
3167 resLayout,
broadcast.getResultVectorType().getShape(),
3174 if (
auto reduction = dyn_cast<vector::MultiDimReductionOp>(op)) {
3183 if (
auto reduction = dyn_cast<vector::ReductionOp>(op))
3188 if (
auto bitcast = dyn_cast<vector::BitCastOp>(op)) {
3189 int resElemBitWidth =
3190 bitcast.getResultVectorType().getElementType().getIntOrFloatBitWidth();
3191 int srcElemBitWidth =
3192 bitcast.getSourceVectorType().getElementType().getIntOrFloatBitWidth();
3199 if (
auto shapeCast = dyn_cast<vector::ShapeCastOp>(op)) {
3201 resLayout, shapeCast.getResultVectorType().getShape(),
3202 shapeCast.getSourceVectorType().getShape());
3207 if (
auto insertSlice = dyn_cast<vector::InsertStridedSliceOp>(op)) {
3210 resLayout, insertSlice.getDestVectorType().getShape(),
3211 insertSlice.getSourceVectorType().getShape());
3219 if (
auto insert = dyn_cast<vector::InsertOp>(op)) {
3220 VectorType resVecTy = dyn_cast<VectorType>(insert.getResult().getType());
3221 VectorType valueToStoreTy =
3222 dyn_cast<VectorType>(insert.getValueToStore().getType());
3224 if ((idx == 0) && valueToStoreTy) {
3226 valueToStoreTy.getShape());
3234 if (
auto extract = dyn_cast<vector::ExtractOp>(op)) {
3235 VectorType srcVecTy = dyn_cast<VectorType>(extract.getSource().getType());
3236 VectorType resVecTy = dyn_cast<VectorType>(extract.getResult().getType());
3237 if (!srcVecTy || !resVecTy)
3240 srcVecTy.getShape());
3245 if (
auto transpose = dyn_cast<vector::TransposeOp>(op)) {
3247 transpose.getPermutation());
3252 if (
auto bitcast = dyn_cast<vector::BitCastOp>(op)) {
3253 int resElemBitWidth =
3254 bitcast.getResultVectorType().getElementType().getIntOrFloatBitWidth();
3255 int srcElemBitWidth =
3256 bitcast.getSourceVectorType().getElementType().getIntOrFloatBitWidth();
3262 if (
auto interleave = dyn_cast<vector::InterleaveOp>(op)) {
3267 if (
auto deinterleave = dyn_cast<vector::DeinterleaveOp>(op)) {
3272 if (dyn_cast<vector::ExtractStridedSliceOp>(op))
3288 RegionBranchTerminatorOpInterface terminator,
OpOperand &operand) {
3289 auto branch = dyn_cast<RegionBranchOpInterface>(terminator->getParentOp());
3293 branch.getSuccessorOperandInputMapping(mapping,
3295 auto it = mapping.find(&operand);
3296 if (it == mapping.end())
3298 xegpu::DistributeLayoutAttr iterArgLayout;
3299 for (
auto arg : llvm::make_isa_range<BlockArgument>(it->second)) {
3301 assert((!iterArgLayout || !layout || iterArgLayout.isEqualTo(layout)) &&
3302 "region inputs fed by one terminator operand disagree on layout");
3304 iterArgLayout = layout;
3306 return iterArgLayout;
3312 RegionBranchTerminatorOpInterface terminator,
OpOperand &operand) {
3313 auto branch = dyn_cast<RegionBranchOpInterface>(terminator->getParentOp());
3317 branch.getSuccessorOperandInputMapping(mapping,
3319 auto it = mapping.find(&operand);
3320 if (it == mapping.end())
3322 for (
Value input : it->second)
3323 if (
auto result = dyn_cast<OpResult>(input))
3336 if (isa<xegpu::AnchorLayoutInterface>(op))
3344 if (isa<RegionBranchOpInterface>(op))
3349 if (
auto terminator = dyn_cast<RegionBranchTerminatorOpInterface>(op)) {
3356 xegpu::DistributeLayoutAttr resLayout;
3357 if (op->
getNumResults() == 1 || isa<vector::DeinterleaveOp>(op))
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 xegpu::LayoutAttr buildLayout(mlir::MLIRContext *context, ArrayRef< int64_t > sgLayout, ArrayRef< int64_t > sgData, ArrayRef< int64_t > instData, ArrayRef< int64_t > laneLayout, ArrayRef< int64_t > laneData, DenseI32ArrayAttr orderAttr=nullptr)
static xegpu::DistributeLayoutAttr createScaleLayout(mlir::MLIRContext *context, VectorType matrixTy, VectorType scaleTy, xegpu::DistributeLayoutAttr matrixLayout, bool isBScale, const xegpu::uArch::uArch *uArch)
Helper to create a scale layout derived from a matrix operand layout.
static xegpu::DistributeLayoutAttr adjustInnermostDimForDivisibility(xegpu::DistributeLayoutAttr consumerLayout, xegpu::LayoutKind layoutKind, size_t innerMostDim, int ratio, int64_t bound, const xegpu::uArch::uArch *uArch)
Adjusts consumerLayout's innermost-dim data field selected by layoutKind so that the source layout ca...
static void walkRegionBackward(Region ®ion, xegpu::BackwardLayoutVisitor &visitor)
Visits the ops of region backward; see xegpu::walkBackward.
static xegpu::DistributeLayoutAttr setupDefaultScatterIOLayout(xegpu::LayoutKind layoutKind, mlir::MLIRContext *context, int maxChunkSize, ArrayRef< int64_t > srcShape, int subgroupSize, int numSg)
Select a default scatter IO layout with at most maxChunkSize elements per lane.
static xegpu::DistributeLayoutAttr setupShapeCastSgResultLayout(ArrayRef< int64_t > resShape, ArrayRef< SmallVector< int64_t > > splitDimGroups, xegpu::DistributeLayoutAttr consumerLayout)
Subgroup level of setupShapeCastResultLayout.
static xegpu::DistributeLayoutAttr get2DBlockIOSubgroupLayout(MLIRContext *context, ArrayRef< int64_t > dataShape, Type elemTy, const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction, int numSg)
Picks the subgroup layout for a 2D block IO op (store_nd / prefetch_nd).
static std::pair< SmallVector< int64_t >, SmallVector< int64_t > > computeScatterIOLaneLayoutAndData(ArrayRef< int64_t > instShape, int64_t subgroupSize, int64_t maxChunkSize)
Computes lane_layout and lane_data for scatter-style store anchor layouts (store scatter,...
static bool isReady(Region *region, const DenseMap< Region *, SmallPtrSet< Region *, 2 > > &targets, const SetVector< Region * > &visitedRegions)
Return whether every target recorded for region has been visited.
static xegpu::LayoutAttr buildInstDataLayoutWithLane(mlir::MLIRContext *context, ArrayRef< int64_t > instData, ArrayRef< int64_t > laneLayout, ArrayRef< int64_t > laneData, DenseI32ArrayAttr orderAttr=nullptr)
static SmallVector< Region * > getBackwardRegionOrder(Operation *op)
Order regions for walkBackward, preferring successors before predecessors and breaking ties by revers...
static xegpu::LayoutAttr buildSgLayout(mlir::MLIRContext *context, ArrayRef< int64_t > wgTileShape, ArrayRef< int64_t > sgLayout, int dimK=-1, DenseI32ArrayAttr orderAttr=nullptr)
static xegpu::DistributeLayoutAttr setupGenericLoadAnchorLayout(xegpu::LayoutKind layoutKind, mlir::MLIRContext *context, xegpu::DistributeLayoutAttr consumerLayout, int maxChunkSize, ArrayRef< int64_t > resShape, int subgroupSize, int numSg)
Select a layout for load_gather or load_matrix.
static bool isLayoutPreservingVectorProducer(Operation *op)
Accept pure vector generators and elementwise ops that preserve vector shape.
static xegpu::DistributeLayoutAttr getParentResultLayoutForYieldOperand(RegionBranchTerminatorOpInterface terminator, OpOperand &operand)
static xegpu::DistributeLayoutAttr setupDefault2DBlockIOLayout(xegpu::LayoutKind layoutKind, ArrayRef< int64_t > dataShape, Type elemTy, int numSg, const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction, const xegpu::uArch::uArch *uArch)
Select a default 2D block IO layout without transpose or transform.
static std::optional< SmallVector< int64_t > > get2DBlockIOInstDataLayout(ArrayRef< int64_t > dataShape, Type elemTy, const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction, bool transform=false, bool transpose=false)
Helper function to compute inst_data vectors for DPAS operands A, B, and C/D.
static xegpu::DistributeLayoutAttr getDefaultScatterIOSubgroupLayout(mlir::MLIRContext *context, ArrayRef< int64_t > wgShape, ArrayRef< int64_t > instData, int numSg)
Select the most balanced numSg factorization of wgShape whose sg_data is a multiple of instData.
static SmallVector< LayoutRepresentation > getSgLayoutCandidates(ArrayRef< int64_t > wgShape, ArrayRef< int64_t > instData, int64_t sgCount, int64_t broadcastDim=-1)
static SmallVector< LayoutRepresentation > enumerateFactorizations(int64_t total, int64_t rank)
Enumerates all ways to split total into rank factors whose product equals total.
static bool isCollapsibleSgGroup(ArrayRef< int64_t > dimGroup, ArrayRef< int64_t > shape, ArrayRef< int64_t > sgLayout, ArrayRef< int64_t > sgData, ArrayRef< int64_t > order)
Checks that collapsing dimGroup of a subgroup layout, which multiplies sg_layout and sg_data across t...
static bool isContiguousTiling(ArrayRef< int64_t > dimGroup, ArrayRef< int64_t > shape, ArrayRef< int64_t > counts, ArrayRef< int64_t > tileShape, int64_t expectedStride)
Checks that the tiles a split group is cut into walk the collapsed source dim with one constant strid...
SmallVector< int64_t > LayoutRepresentation
static xegpu::DistributeLayoutAttr getLayoutFromUsePoints(Value result)
static std::tuple< SmallVector< int64_t >, SmallVector< int64_t >, SmallVector< int64_t > > compute2DBlockIOLaneLayout(ArrayRef< int64_t > instShape, int64_t subgroupSize, int64_t bitwidth, int64_t packingSize, bool transform=false, bool transpose=false)
static xegpu::DistributeLayoutAttr getLoopCarriedLayoutForYieldOperand(RegionBranchTerminatorOpInterface terminator, OpOperand &operand)
static constexpr unsigned kMaxRematerializableChainOps
static void propagateResultsToRegularOperands(Operation *op)
static bool collectRematerializableChain(Operation *root, SmallVectorImpl< Operation * > &chain)
Collect each eligible producer once, producers first, for cloning with an IRMapping.
static bool isValidLaneLayout(ArrayRef< int64_t > dataShape, ArrayRef< int64_t > laneLayout, ArrayRef< int64_t > laneData)
static std::tuple< SmallVector< int64_t >, SmallVector< int64_t >, SmallVector< int64_t > > computeReductionLaneLayoutAndData(ArrayRef< int64_t > srcShape, ArrayRef< int64_t > reductionDims, int subgroupSize, int64_t maxReduceVectorSize, xegpu::DistributeLayoutAttr consumerLayout=nullptr)
Derives (lane_layout, lane_data, inst_data) for a vector.multi_reduction source from the layout reque...
static std::optional< std::tuple< xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr > > getDpasSubgroupLayouts(mlir::MLIRContext *context, VectorType aTy, VectorType bTy, VectorType cdTy, xegpu::DistributeLayoutAttr consumerLayout, int numSg, std::tuple< SmallVector< int64_t >, SmallVector< int64_t >, SmallVector< int64_t > > instDataVecs, const xegpu::uArch::MMAInstructionInterface *uArchInstruction)
Helper function to set up subgroup layouts for DPAS operands A, B, and C/D.
static xegpu::LayoutAttr buildLaneLayout(mlir::MLIRContext *context, ArrayRef< int64_t > laneLayout, ArrayRef< int64_t > laneData, DenseI32ArrayAttr orderAttr=nullptr)
static std::optional< std::tuple< SmallVector< int64_t >, SmallVector< int64_t >, SmallVector< int64_t > > > getDpasInstDataLayouts(VectorType aTy, VectorType bTy, VectorType cdTy, const xegpu::uArch::MMAInstructionInterface *uArchInstruction)
Helper function to compute inst_data vectors for DPAS operands A, B, and C/D.
Attributes are known-constant values of operations.
Block represents an ordered list of Operations.
This is a utility class for mapping one set of IR entities to another.
auto lookup(T from) const
Lookup a mapped value within the map.
MLIRContext is the top-level object for a collection of MLIR operations.
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
This class represents an operand of an operation.
unsigned getOperandNumber() const
Return which operand this is in the OpOperand list of the Operation.
This is a value defined by a result of an operation.
void walkInherentAttrs(Operation *op, InherentAttrVisitor visitor) const
Visit the inherent attributes stored in the properties of op.
Operation is the basic unit of execution within MLIR.
bool hasDiscardableAttrOfType(NameT &&name)
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
unsigned getNumRegions()
Returns the number of regions held by this operation.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
MutableArrayRef< OpOperand > getOpOperands()
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.
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Attribute removeDiscardableAttr(StringAttr name)
Remove the discardable attribute with the specified name if it exists.
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),...
unsigned getNumResults()
Return the number of results held by this operation.
This class represents a point being branched from in the methods of the RegionBranchOpInterface.
This class represents a successor of a region.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
unsigned getNumArguments()
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
bool 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.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< int32_t > content)
Operation * getOwner() const
Return the owner of this operand.
Callbacks for walkBackward.
virtual bool shouldRevisitRegions(RegionBranchOpInterface regionOp)
Called after visitRegionOp.
virtual void visitTerminator(RegionBranchTerminatorOpInterface terminator)=0
A terminator forwarding values between regions or to their parent op.
virtual void visitRegionOp(RegionBranchOpInterface regionOp)=0
A region branch op (e.g. scf.for), visited after all of its regions.
virtual void visitRegularOp(Operation *op)=0
Any other op.
bool hasElementwiseMappableTraits(Operation *op)
Together, Elementwise, Scalarizable, Vectorizable, and Tensorizable provide an easy way for scalar op...
@ Subgroup2DBlockPrefetch
@ SubgroupMatrixMultiplyAcc
@ SubgroupScaledMatrixMultiplyAcc
DistributeLayoutAttr inferShapeCastSourceLayout(DistributeLayoutAttr resLayout, ArrayRef< int64_t > resShape, ArrayRef< int64_t > srcShape)
Infers the source layout attribute for a shape cast operation given the result layout attribute,...
bool matchDimCollapse(ArrayRef< int64_t > src, ArrayRef< int64_t > dst, SmallVector< SmallVector< int64_t > > &collapseDims)
DistributeLayoutAttr setupLoadNdAnchorLayout(LayoutKind layoutKind, VectorType vectorTy, DistributeLayoutAttr consumerLayout, int numSg, const uArch::uArch *uArch)
Sets up the anchor layout for a load_nd operation.
DistributeLayoutAttr inferResultLayoutFromSourceForNonAnchorOp(Operation *op, ArrayRef< DistributeLayoutAttr > operandLayouts)
Infers the result layout attribute for a non-anchor operation from the layouts of its source operands...
DistributeLayoutAttr setupInterleaveResultLayout(LayoutKind layoutKind, VectorType srcVectorTy, VectorType resVectorTy, DistributeLayoutAttr consumerLayout, const uArch::uArch *uArch)
Sets up the result layout for an interleave operation to ensure the source layout can be safely deriv...
DistributeLayoutAttr inferTransposeSourceLayout(DistributeLayoutAttr resLayout, ArrayRef< int64_t > permutation)
Infers the source layout attribute for a transpose operation given the result layout attribute and pe...
DistributeLayoutAttr inferInsertSourceLayout(DistributeLayoutAttr resLayout, ArrayRef< int64_t > resShape, ArrayRef< int64_t > srcShape)
Infers the source layout attribute for an insert operation.
std::optional< std::tuple< DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr > > completeDpasMxLaneLayoutFromInstData(DistributeLayoutAttr aLayout, DistributeLayoutAttr bLayout, DistributeLayoutAttr cdLayout, VectorType aTy, VectorType bTy, VectorType cdTy, VectorType aScaleTy, VectorType bScaleTy, const uArch::uArch *uArch)
Like completeDpasLaneLayoutFromInstData, but for dpas_mx: additionally re-derives the A_scale / B_sca...
DistributeLayoutAttr inferInsertStridedSliceSourceLayout(DistributeLayoutAttr resLayout, ArrayRef< int64_t > resShape, ArrayRef< int64_t > srcShape)
Infers the source layout attribute for an insert strided slice operation given the result layout attr...
DistributeLayoutAttr setupStoreMatrixAnchorLayout(LayoutKind layoutKind, VectorType vectorTy, int contigChunkSize, int numSg, const uArch::uArch *uArch)
Sets up the anchor layout for a store matrix operation.
void removeTemporaryLayoutAttrs(Operation *op)
Removes the temporary layout attributes for each OpOperand and OpResult of the given operation.
std::optional< std::tuple< DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr > > completeDpasLaneLayoutFromInstData(DistributeLayoutAttr aLayout, DistributeLayoutAttr bLayout, DistributeLayoutAttr cdLayout, VectorType aTy, VectorType bTy, VectorType cdTy, const uArch::uArch *uArch)
Completes user-provided DPAS A/B/C-D anchors that carry only inst_data by filling in lane_layout / la...
void setTemporaryLayout(const T &operandOrResult, const DistributeLayoutAttr layout)
LogicalResult propagateRegionArgsToInits(RegionBranchOpInterface regionOp, GetLayoutFnTy getLayoutOfValue, SetOperandLayoutFnTy setOperandLayout, SetTDescArgLayoutFnTy setTDescArgLayout)
Propagate layouts from a region branch op's region entry block arguments back to its init operands.
LayoutKind
Specifies the level of a layout hierarchy for comparison or propagation.
SmallVector< NamedAttribute > dropInstDataOnAttrs(ArrayRef< NamedAttribute > attrs)
Updates the NamedAttribute sequence by dropping inst-data information from any DistributeLayoutAttr f...
DistributeLayoutAttr inferSourceLayoutFromResultForNonAnchorOp(OpOperand &operand, DistributeLayoutAttr resLayout)
Infers the source layout attribute for an operand using result layout attribute.
DistributeLayoutAttr inferInterleaveSourceLayout(DistributeLayoutAttr resLayout)
Infers the source layout attribute for an interleave operation given the result layout attribute.
DistributeLayoutAttr setupLoadGatherAnchorLayout(LayoutKind layoutKind, VectorType vectorTy, int contigChunkSize, DistributeLayoutAttr consumerLayout, int numSg, const uArch::uArch *uArch)
Sets up the anchor layout for a load gather operation.
bool matchUnitDimExpansion(ArrayRef< int64_t > src, ArrayRef< int64_t > dst, SmallVector< int64_t > &expandedUnitDims)
int getLargestDivisor(T dim, ArrayRef< T > candidates, ArrayRef< T > candidateMultiples={})
Helper Function to find a proper instruction multiple for the user-supplied sg-level data shape (dive...
bool recoverTemporaryLayouts(Operation *rootOp)
Attach layout attributes to all vector-type operands of operations within the given operation's neste...
DistributeLayoutAttr inferBroadcastSourceLayout(DistributeLayoutAttr resLayout, ArrayRef< int64_t > resShape, ArrayRef< int64_t > srcShape)
Infers the source layout attribute for a broadcast operation given the result layout attribute,...
std::optional< std::tuple< DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr > > setupDpasMxLayout(LayoutKind layoutKind, VectorType aTy, VectorType bTy, VectorType cdTy, VectorType aScaleTy, VectorType bScaleTy, DistributeLayoutAttr consumerLayout, int numSg, const uArch::uArch *uArch)
Sets up the anchor layouts for dpas_mx operands (A, B, C/D, A_scale, and B_scale).
void walkBackward(Operation *root, BackwardLayoutVisitor &visitor)
Walk function bodies under root in CFG post-order, visiting ops within each block back to front and n...
SliceAttr setupMultiReductionResultLayout(LayoutKind layoutKind, VectorType srcVectorTy, DistributeLayoutAttr consumerLayout, SmallVector< int64_t > reductionDims, int numSg, const uArch::uArch *uArch)
Note on the consumerLayout argument used by the consumer-driven setup* / complete* helpers below:
llvm::function_ref< void(OpOperand &, DistributeLayoutAttr)> SetOperandLayoutFnTy
The region helpers below choose layouts and pass each one to a callback; the caller decides when it r...
llvm::function_ref< DistributeLayoutAttr(Value)> GetLayoutFnTy
Callable returning the propagated layout for a given Value, used by the layout-propagation helpers be...
std::optional< DistributeLayoutAttr > completeScatterLoadLaneLayoutFromInstData(DistributeLayoutAttr userSpecifiedLayout, DistributeLayoutAttr consumerLayout, Type elemTy, const xegpu::uArch::LoadGatherInstruction *uArchInstruction, const int subgroupSize)
If the consumer layout has only inst_data (no lane_layout/lane_data), completes it by running the cor...
bool matchSplitDimExpansion(ArrayRef< int64_t > src, ArrayRef< int64_t > dst, SmallVector< SmallVector< int64_t > > &splitDimGroups)
DistributeLayoutAttr setupLoadMatrixAnchorLayout(LayoutKind layoutKind, VectorType vectorTy, int contigChunkSize, DistributeLayoutAttr consumerLayout, int numSg, const uArch::uArch *uArch)
Sets up the anchor layout for load matrix operation.
DistributeLayoutAttr setupStoreScatterAnchorLayout(LayoutKind layoutKind, VectorType vectorTy, int contigChunkSize, int numSg, const uArch::uArch *uArch)
Sets up the anchor layout for a store scatter operation.
DistributeLayoutAttr setupBitCastResultLayout(LayoutKind layoutKind, VectorType srcVectorTy, VectorType resVectorTy, DistributeLayoutAttr consumerLayout, const uArch::uArch *uArch)
Setup the result layout attribute for a bitcast operation based on element type bitwidths.
void propagateRegionResultsToYieldOperands(RegionBranchTerminatorOpInterface terminator, GetLayoutFnTy getLayoutOfValue, SetOperandLayoutFnTy setOperandLayout)
Propagate layouts to the operands of a region branch terminator: each operand gets,...
void removeLayoutAttr(const T &operandOrResult)
Removes the LayoutAttr for a given OpOperand or OpResult if it exists.
void dropInstDataOnInherentAttrs(Operation *op)
Drops inst-data information from DistributeLayoutAttrs stored as inherent attributes on the operation...
bool isLayoutCarrierType(Type type)
Returns true if values of type can carry a DistributeLayoutAttr, i.e.
DistributeLayoutAttr getDistributeLayoutAttr(const Value value)
Retrieves the DistributeLayoutAttr associated with a given Value, or nullptr if none is found.
SmallVector< NamedAttribute > dropSgLayoutAndDataOnAttrs(ArrayRef< NamedAttribute > attrs)
Updates the NamedAttribute sequence by dropping sg-layout and sg-data information from any Distribute...
DistributeLayoutAttr setupPrefetchNdAnchorLayout(LayoutKind layoutKind, TensorDescType tdescTy, int numSg, const uArch::uArch *uArch)
Sets up the anchor layout for a prefetch_nd operation.
DistributeLayoutAttr inferShapeCastResultLayout(DistributeLayoutAttr srcLayout, ArrayRef< int64_t > srcShape, ArrayRef< int64_t > resShape)
Infers the result layout attribute for a shape cast operation given the source layout attribute,...
DistributeLayoutAttr inferExtractSourceLayout(DistributeLayoutAttr resLayout, ArrayRef< int64_t > resShape, ArrayRef< int64_t > srcShape)
Infers the source layout attribute for an extract operation.
std::string getTemporaryLayoutName(const OpOperand &operand)
Return the attribute name for the OpOperand to attach DistributeLayoutAttr.
DistributeLayoutAttr inferBitCastSourceLayout(DistributeLayoutAttr resLayout, int resElemTyBitWidth, int srcElemTyBitWidth)
Infers the source layout attribute for a bitcast operation given the result layout attribute,...
DistributeLayoutAttr setupInsertStridedSliceResultLayout(LayoutKind layoutKind, VectorType srcVectorTy, VectorType resVectorTy, DistributeLayoutAttr consumerLayout, const uArch::uArch *uArch)
Sets up the result layout for an insert strided slice operation.
DistributeLayoutAttr setupShapeCastResultLayout(LayoutKind layoutKind, VectorType srcVectorTy, VectorType resVectorTy, DistributeLayoutAttr consumerLayout)
Sets up the result layout for a shape cast that splits one source dim into several consecutive result...
DistributeLayoutAttr inferReductionSourceLayout(DistributeLayoutAttr resLayout)
Infers the source layout attribute for a reduction operation given the result layout attribute and re...
std::optional< DistributeLayoutAttr > completeScatterStoreLaneLayoutFromInstData(DistributeLayoutAttr specifiedLayout, Type elemTy, const xegpu::uArch::StoreScatterInstruction *uArchInstruction, const int subgroupSize)
Like completeScatterLoadLaneLayoutFromInstData, but for scatter stores (store_scatter / store_matrix)...
std::optional< DistributeLayoutAttr > completeBlockStoreLaneLayoutFromInstData(DistributeLayoutAttr specifiedLayout, Type elemTy, const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction, const int subgroupSize)
Completes a user-provided 2D-block store_nd / prefetch_nd anchor that has only inst_data.
DistributeLayoutAttr inferDeinterleaveSourceLayout(DistributeLayoutAttr resLayout)
Infers the source layout attribute for a deinterleave operation given the result layout attribute.
DistributeLayoutAttr getConsumerLayoutAt(OpOperand &operand)
Gets the expected layout for a given consumer operand.
void removeLayoutAttrs(Operation *op)
Removes the DistributeLayoutAttr for each OpOperand and OpResult of the given operation if they exist...
DistributeLayoutAttr inferMultiReductionSourceLayout(DistributeLayoutAttr resLayout, SmallVector< int64_t > reduceDims)
Infers the source layout attribute for a reduction operation given the result layout attribute and re...
bool isTriviallyRematerializable(Operation *op)
Returns true if the vector produced by op is cheap to recompute in any layout, i.e.
Value rematerialize(OpBuilder &builder, Value value)
Clone a bounded chain of pure vector generators and layout-preserving elementwise ops without layout ...
DistributeLayoutAttr setupStoreNdAnchorLayout(LayoutKind layoutKind, VectorType vectorTy, int numSg, const uArch::uArch *uArch)
Sets up the anchor layout for a store_nd operation.
DistributeLayoutAttr inferTransposeResultLayout(DistributeLayoutAttr srcLayout, ArrayRef< int64_t > permutation)
Infers the result layout attribute for a transpose operation given the source layout attribute and pe...
std::optional< DistributeLayoutAttr > completeBlockLoadLaneLayoutFromInstData(DistributeLayoutAttr specifiedLayout, DistributeLayoutAttr consumerLayout, Type elemTy, const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction, const int subgroupSize)
Like completeBlockStoreLaneLayoutFromInstData, but for load_nd.
void setTensorDescLayout(Value value, DistributeLayoutAttr layout)
Sets layout on the type of the tensor_desc value value, replacing any layout the type already has.
std::optional< std::tuple< DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr > > setupDpasLayout(LayoutKind layoutKind, VectorType aTy, VectorType bTy, VectorType cdTy, DistributeLayoutAttr consumerLayout, int numSg, const uArch::uArch *uArch)
Sets up the anchor layouts for a dpas operands (A, B, and C/D).
SliceAttr setupReductionResultLayout(LayoutKind layoutKind, VectorType srcVectorTy, const uArch::uArch *uArch)
Sets up layout for Reduction operations by creating a SliceAttr for the result.
Include the generated interface declarations.
DenseMap< OpOperand *, SmallVector< Value > > RegionBranchSuccessorMapping
A mapping from successor operands to successor inputs.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
AffineMap inversePermutation(AffineMap map)
Returns a map of codomain to domain dimensions such that the first codomain dimension for a particula...
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
int64_t computeProduct(ArrayRef< int64_t > basis)
Self-explicit.
llvm::SetVector< T, Vector, Set, N > SetVector
detail::DenseArrayAttrImpl< int32_t > DenseI32ArrayAttr
Operation * clone(OpBuilder &b, Operation *op, TypeRange newResultTypes, ValueRange newOperands)
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
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.
SmallVector< int64_t > invertPermutationVector(ArrayRef< int64_t > permutation)
Helper method to apply to inverse a permutation.
virtual int32_t getPackedFormatBitSize() const =0
std::optional< BlockShapes > getBlockWidthHeightCount(Type elemTy, bool hasTransform=false, bool hasTranspose=false, bool upConv=false) const
int32_t getMaxLaneAccessSizeBytes() const override
virtual llvm::SmallVector< uint32_t, 8 > getSupportedN(Type type) const =0
virtual llvm::SmallVector< uint32_t, 8 > getSupportedK(Type type) const =0
virtual llvm::SmallVector< uint32_t, 8 > getSupportedM(Type type) const =0
int32_t getMaxLaneAccessSizeBytes() const override
virtual unsigned getGeneralPackedFormatBitSize() const =0
virtual int getSubgroupSize() const =0
const Instruction * getInstruction(InstructionKind instKind) const