18#include "llvm/ADT/SmallVectorExtras.h"
19#include "llvm/ADT/TypeSwitch.h"
20#include "llvm/Support/Debug.h"
27void XeGPUDialect::initialize() {
29#define GET_TYPEDEF_LIST
30#include <mlir/Dialect/XeGPU/IR/XeGPUTypes.cpp.inc>
34#include <mlir/Dialect/XeGPU/IR/XeGPU.cpp.inc>
37#define GET_ATTRDEF_LIST
38#include <mlir/Dialect/XeGPU/IR/XeGPUAttrs.cpp.inc>
41#define GET_OP_INTERFACE_CLASSES
42#include "mlir/Dialect/XeGPU/IR/XeGPUOpInterface.cpp.inc"
61 llvm::zip_equal(srcShape,
63 [](
const auto &t) {
return std::min(std::get<0>(t), std::get<1>(t)); });
67 llvm::zip(delinearizedId, subShape), [&](
const auto &t) ->
Value {
83 llvm::map_to_vector(llvm::zip_equal(base, distUnitLocalOffset),
84 [&](
const auto &t) ->
Value {
86 loc, std::get<0>(t), std::get<1>(t));
90 llvm::zip_equal(adds, srcShape), [&](
const auto &t) ->
Value {
96 coordinates.push_back(mods);
106 for (
size_t i = 0; i <
shape.size(); ++i)
107 distUnitShape[i] = std::min(
shape[i], layout[i] * subShape[i]);
111 for (
size_t i = 0; i <
shape.size(); ++i)
112 localOffset[i] = canonicalIds[i] * subShape[i];
119 for (
size_t i = 0; i <
shape.size(); ++i)
120 coord[i] = (unitOffs[i] + localOffset[i]) %
shape[i];
121 coordinates.push_back(coord);
127bool XeGPUDialect::isSharedMemory(
const MemRefType &memrefTy) {
128 Attribute attr = memrefTy.getMemorySpace();
131 if (
auto intAttr = llvm::dyn_cast_if_present<IntegerAttr>(attr))
132 return intAttr.getInt() == 3;
133 if (
auto memrefSpace = llvm::dyn_cast_if_present<MemorySpaceAttr>(attr))
134 return memrefSpace.getValue() == MemorySpace::SLM;
135 if (
auto xevmSpace = llvm::dyn_cast_if_present<xevm::AddrSpaceAttr>(attr))
136 return xevmSpace.getValue() == xevm::AddrSpace::SHARED;
137 return gpu::GPUDialect::isWorkgroupMemoryAddressSpace(attr);
144 xegpu::MemorySpace memory_space,
146 bool boundary_check) {
147 auto scopeAttr = MemorySpaceAttr::get(context, memory_space);
149 IntegerAttr::get(IntegerType::get(context, 64), array_length);
151 return Base::get(context, scopeAttr, lengthAttr, boundaryAttr);
154bool BlockTensorDescAttr::hasDefaultsOnly() {
155 return getMemorySpace().getValue() == xegpu::MemorySpace::Global &&
156 getArrayLength().getInt() == 1 && getBoundaryCheck().getValue();
163LayoutAttr::verify(llvm::function_ref<mlir::InFlightDiagnostic()>
emitError,
169 if (!sg_layout && !inst_data && !lane_layout)
175 if (sg_layout && inst_data && sg_layout.size() != inst_data.size()) {
177 <<
"expected sg_layout and inst_data to have the same rank";
180 if (sg_layout && lane_layout && sg_layout.size() != lane_layout.size()) {
182 <<
"expected sg_layout and lane_layout to have the same rank";
185 if (inst_data && lane_layout && inst_data.size() != lane_layout.size()) {
186 return emitError() <<
"expected inst_data and lane_layout to have the same "
187 "rank, got inst_data "
188 << inst_data.size() <<
", lane_layout "
189 << lane_layout.size();
192 if ((sg_layout && !sg_data) || (!sg_layout && sg_data))
193 return emitError() <<
"sg_layout and sg_data must be used together";
194 if (sg_layout && sg_data && sg_layout.size() != sg_data.size())
196 <<
"expected sg_data and sg_layout to have the same rank";
198 if ((lane_layout && !lane_data) || (!lane_layout && lane_data))
199 return emitError() <<
"lane_layout and lane_data must be used together";
200 if (lane_layout && lane_data && lane_layout.size() != lane_data.size())
202 <<
"expected lane_data and lane_layout to have the same rank";
205 if (!sg_layout && !lane_layout)
207 <<
"expected sg_layout/lane_layout being used with order";
209 if (sg_layout && order.size() != sg_layout.size())
211 <<
"expected order and sg_layout to have the same rank";
213 if (lane_layout && order.size() != lane_layout.size())
215 <<
"expected order and lane_layout to have the same rank";
221FailureOr<SmallVector<Value>>
222LayoutAttr::delinearizeId(OpBuilder &builder, Location loc, Value linearId) {
224 SmallVector<int64_t> sgLayoutInt;
225 if (isForWorkgroup()) {
226 sgLayoutInt = getEffectiveSgLayoutAsInt();
227 }
else if (isForSubgroup()) {
228 sgLayoutInt = getEffectiveLaneLayoutAsInt();
236 SmallVector<int64_t> order;
237 if (orderAttr && !orderAttr.empty()) {
238 order = llvm::map_to_vector(orderAttr.
asArrayRef(), [](int32_t idx) {
239 return static_cast<int64_t>(idx);
243 order = llvm::to_vector(
244 llvm::reverse(llvm::seq<int64_t>(0, sgLayoutInt.size())));
247 if (order.size() != sgLayoutInt.size()) {
251 SmallVector<Value>
result(sgLayoutInt.size());
252 Value remaining = linearId;
275 for (
size_t i = 0; i < order.size(); ++i) {
276 int64_t dimIdx = order[i];
277 int64_t dimSize = sgLayoutInt[dimIdx];
280 builder.
createOrFold<arith::ConstantIndexOp>(loc, dimSize);
287 builder.
createOrFold<arith::RemUIOp>(loc, remaining, dimSizeVal);
294 if (i < order.size() - 1) {
296 builder.
createOrFold<arith::DivUIOp>(loc, remaining, dimSizeVal);
305FailureOr<SmallVector<SmallVector<Value>>>
306LayoutAttr::computeDistributedCoords(OpBuilder &builder, Location loc,
307 Value linearId, ArrayRef<int64_t> shape) {
308 SmallVector<int64_t> layout;
309 SmallVector<int64_t> subShape;
310 if (isForWorkgroup()) {
311 layout = getEffectiveSgLayoutAsInt();
312 subShape = getEffectiveSgDataAsInt();
313 }
else if (isForSubgroup()) {
314 layout = getEffectiveLaneLayoutAsInt();
315 subShape = getEffectiveLaneDataAsInt();
319 assert(!subShape.empty() &&
"sgdata or lanedata cannot be empty for "
320 "distributed coordinates computation");
323 auto maybeIds = delinearizeId(builder, loc, linearId);
326 SmallVector<Value> ids = *maybeIds;
328 return genCoordinates(builder, loc, ids, layout, subShape, shape);
331bool LayoutAttr::isEqualTo(
const xegpu::DistributeLayoutAttr &other) {
332 if (dyn_cast<xegpu::SliceAttr>(other))
335 return *
this == dyn_cast<xegpu::LayoutAttr>(other);
341SmallVector<SmallVector<int64_t>>
342LayoutAttr::computeStaticDistributedCoords(int64_t linearId,
343 ArrayRef<int64_t> shape) {
344 SmallVector<int64_t> layoutVec;
345 SmallVector<int64_t> subShape;
346 SmallVector<int64_t> instData;
347 if (isForWorkgroup()) {
348 layoutVec = getEffectiveSgLayoutAsInt();
349 subShape = getEffectiveSgDataAsInt();
350 }
else if (isForSubgroup()) {
351 instData = getEffectiveInstDataAsInt();
352 layoutVec = getEffectiveLaneLayoutAsInt();
353 subShape = getEffectiveLaneDataAsInt();
355 if (!instData.empty()) {
359 assert(!subShape.empty() &&
"sgdata or lanedata cannot be empty");
362 SmallVector<int64_t> order = getEffectiveOrderAsInt();
363 SmallVector<int64_t> delinearizedId(layoutVec.size());
364 int64_t remaining = linearId;
365 for (
size_t i = 0; i < order.size(); ++i) {
366 int64_t dimIdx = order[i];
367 delinearizedId[dimIdx] = remaining % layoutVec[dimIdx];
368 remaining = remaining / layoutVec[dimIdx];
376LayoutAttr::setUnitDimData(SmallVector<int64_t> unitDims)
const {
377 auto sgDataOpt = getSgData();
378 auto instDataOpt = getInstData();
379 auto laneDataOpt = getLaneData();
381 SmallVector<int32_t> sgData;
382 SmallVector<int32_t> instData;
383 SmallVector<int32_t> laneData;
386 sgData = llvm::to_vector(sgDataOpt.asArrayRef());
389 instData = llvm::to_vector(instDataOpt.asArrayRef());
392 laneData = llvm::to_vector(laneDataOpt.asArrayRef());
394 for (
auto dim : unitDims) {
395 if (dim <
static_cast<int64_t
>(sgData.size()))
397 if (dim <
static_cast<int64_t
>(instData.size()))
399 if (dim <
static_cast<int64_t
>(laneData.size()))
403 return LayoutAttr::get(
417LayoutAttr::setUnitDimLayout(SmallVector<int64_t> unitDims)
const {
418 auto sgLayoutOpt = getSgLayout();
419 auto laneLayoutOpt = getLaneLayout();
421 SmallVector<int32_t> sgLayout;
422 SmallVector<int32_t> laneLayout;
425 sgLayout = llvm::to_vector(sgLayoutOpt.asArrayRef());
427 laneLayout = llvm::to_vector(laneLayoutOpt.asArrayRef());
429 for (
auto dim : unitDims) {
430 if (dim <
static_cast<int64_t
>(sgLayout.size()))
432 if (dim <
static_cast<int64_t
>(laneLayout.size()))
436 return LayoutAttr::get(
440 getSgData(), getInstData(),
443 getLaneData(), getOrder());
448DistributeLayoutAttr LayoutAttr::setDimData(int64_t dim, int64_t sgData,
452 SmallVector<int64_t> sgDataVec = getEffectiveSgDataAsInt();
453 SmallVector<int64_t> instDataVec = getEffectiveInstDataAsInt();
454 SmallVector<int64_t> laneDataVec = getEffectiveLaneDataAsInt();
456 if (dim <
static_cast<int64_t
>(sgDataVec.size()) && sgData != -1)
457 sgDataVec[dim] = sgData;
458 if (dim <
static_cast<int64_t
>(instDataVec.size()) && instData != -1)
459 instDataVec[dim] = instData;
460 if (dim <
static_cast<int64_t
>(laneDataVec.size()) && laneData != -1)
461 laneDataVec[dim] = laneData;
463 SmallVector<int32_t> sgDataVec32(sgDataVec.begin(), sgDataVec.end());
464 SmallVector<int32_t> instDataVec32(instDataVec.begin(), instDataVec.end());
465 SmallVector<int32_t> laneDataVec32(laneDataVec.begin(), laneDataVec.end());
467 return LayoutAttr::get(
482DistributeLayoutAttr LayoutAttr::dropDims(SmallVector<int64_t> dimGroup) {
484 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
485 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
486 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
487 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
488 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
489 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
491 SmallVector<int64_t> sortedDimGroup = dimGroup;
492 llvm::sort(sortedDimGroup);
494 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
495 if (!sgLayout.empty()) {
496 sgLayout.erase(sgLayout.begin() + dimIdx);
497 sgData.erase(sgData.begin() + dimIdx);
499 if (!instData.empty())
500 instData.erase(instData.begin() + dimIdx);
501 if (!laneLayout.empty()) {
502 laneLayout.erase(laneLayout.begin() + dimIdx);
503 laneData.erase(laneData.begin() + dimIdx);
507 SmallVector<int64_t> newOrder;
508 for (int64_t d : origOrder) {
509 if (llvm::is_contained(dimGroup, d))
511 int64_t offset = llvm::count_if(dimGroup, [&](int64_t s) {
return s < d; });
512 newOrder.push_back(d - offset);
514 if ((sgLayout.empty() && laneLayout.empty()) || newOrder.size() == 1)
520 SmallVector<int32_t> v32(v.begin(), v.end());
523 auto droppedLayout = xegpu::LayoutAttr::get(
524 getContext(), toAttr(sgLayout), toAttr(sgData), toAttr(instData),
525 toAttr(laneLayout), toAttr(laneData), toAttr(newOrder));
526 return droppedLayout;
532DistributeLayoutAttr LayoutAttr::collapseDims(SmallVector<int64_t> dimGroup) {
534 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
535 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
536 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
537 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
538 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
539 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
541 SmallVector<int64_t> sortedDimGroup = dimGroup;
542 llvm::sort(sortedDimGroup);
543 int64_t dimBeforeCurrent = -1;
544 for (
auto dimIdx : sortedDimGroup) {
548 if (dimBeforeCurrent >= 0) {
549 if (getOrder() && !getOrder().empty()) {
550 int64_t orderBefore = origOrder[dimBeforeCurrent];
551 int64_t orderCurrent = origOrder[dimIdx];
552 if (orderBefore != (orderCurrent - 1))
553 llvm::report_fatal_error(
554 "dimensions being collapsed must be adjacent in order");
556 if (dimIdx != (dimBeforeCurrent + 1))
557 llvm::report_fatal_error(
558 "dimensions being collapsed must be adjacent");
561 dimBeforeCurrent = dimIdx;
564 int firstDim = sortedDimGroup.front();
569 if (!sgLayout.empty()) {
570 int64_t collapsedSglayout = 1, collapsedSgData = 1;
571 for (
auto dimIdx : dimGroup) {
572 collapsedSglayout *= sgLayout[dimIdx];
573 collapsedSgData *= sgData[dimIdx];
575 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
576 sgLayout.erase(sgLayout.begin() + dimIdx, sgLayout.begin() + dimIdx + 1);
577 sgData.erase(sgData.begin() + dimIdx, sgData.begin() + dimIdx + 1);
579 sgLayout.insert(sgLayout.begin() + firstDim, collapsedSglayout);
580 sgData.insert(sgData.begin() + firstDim, collapsedSgData);
583 if (!instData.empty()) {
584 int64_t collapsedInstData = 1;
585 for (
auto dimIdx : dimGroup)
586 collapsedInstData *= instData[dimIdx];
587 for (
auto dimIdx : llvm::reverse(sortedDimGroup))
588 instData.erase(instData.begin() + dimIdx, instData.begin() + dimIdx + 1);
589 instData.insert(instData.begin() + firstDim, collapsedInstData);
592 if (!laneLayout.empty()) {
593 int64_t collapsedLaneLayout = 1, collapsedLaneData = 1;
594 for (
auto dimIdx : dimGroup) {
595 collapsedLaneLayout *= laneLayout[dimIdx];
596 collapsedLaneData *= laneData[dimIdx];
598 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
599 laneLayout.erase(laneLayout.begin() + dimIdx,
600 laneLayout.begin() + dimIdx + 1);
601 laneData.erase(laneData.begin() + dimIdx, laneData.begin() + dimIdx + 1);
603 laneLayout.insert(laneLayout.begin() + firstDim, collapsedLaneLayout);
604 laneData.insert(laneData.begin() + firstDim, collapsedLaneData);
607 SmallVector<int64_t> newOrder;
609 if (orderAttr && !orderAttr.empty()) {
611 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
612 if (dimIdx != firstDim)
613 origOrder.erase(origOrder.begin() + dimIdx);
618 llvm::to_vector(llvm::seq<size_t>(0, origOrder.size()));
622 [&](
size_t a,
size_t b) {
return origOrder[a] < origOrder[
b]; });
624 newOrder = llvm::to_vector(llvm::map_range(
625 indices, [&](
size_t i) {
return static_cast<int64_t
>(i); }));
631 SmallVector<int32_t> v32(v.begin(), v.end());
634 auto collapsedLayout = xegpu::LayoutAttr::get(
635 getContext(), toAttr(sgLayout), toAttr(sgData), toAttr(instData),
636 toAttr(laneLayout), toAttr(laneData), toAttr(newOrder));
637 return collapsedLayout;
641DistributeLayoutAttr LayoutAttr::transposeDims(ArrayRef<int64_t> permutation) {
643 SmallVector<int64_t> origSgLayout = getEffectiveSgLayoutAsInt();
644 SmallVector<int64_t> origSgData = getEffectiveSgDataAsInt();
645 SmallVector<int64_t> origInstData = getEffectiveInstDataAsInt();
646 SmallVector<int64_t> origLaneLayout = getEffectiveLaneLayoutAsInt();
647 SmallVector<int64_t> origLaneData = getEffectiveLaneDataAsInt();
648 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
650 SmallVector<int32_t> sgLayout;
651 SmallVector<int32_t> sgData;
652 SmallVector<int32_t> instData;
653 SmallVector<int32_t> laneLayout;
654 SmallVector<int32_t> laneData;
655 SmallVector<int32_t> order;
657 for (int64_t idx : permutation) {
658 if (!origLaneLayout.empty()) {
659 laneLayout.push_back(
static_cast<int32_t
>(origLaneLayout[idx]));
660 laneData.push_back(
static_cast<int32_t
>(origLaneData[idx]));
662 if (!origInstData.empty())
663 instData.push_back(
static_cast<int32_t
>(origInstData[idx]));
664 if (!origSgLayout.empty()) {
665 sgLayout.push_back(
static_cast<int32_t
>(origSgLayout[idx]));
666 sgData.push_back(
static_cast<int32_t
>(origSgData[idx]));
668 order.push_back(
static_cast<int32_t
>(origOrder[idx]));
670 if (origLaneLayout.empty() && origSgLayout.empty())
676 return xegpu::LayoutAttr::get(
getContext(), toAttr(sgLayout), toAttr(sgData),
677 toAttr(instData), toAttr(laneLayout),
678 toAttr(laneData), toAttr(order));
682bool LayoutAttr::isTransposeOf(
const xegpu::DistributeLayoutAttr &other,
683 ArrayRef<int64_t> perm,
687 if (getRank() != other.getRank() ||
688 perm.size() !=
static_cast<size_t>(getRank()))
692 auto checkTranspose = [](ArrayRef<int64_t> dst, ArrayRef<int64_t> src,
693 ArrayRef<int64_t> perm) {
694 for (
const auto &ta : llvm::enumerate(perm)) {
695 if (src[ta.index()] != dst[ta.value()])
701 return checkTranspose(getEffectiveSgLayoutAsInt(),
702 other.getEffectiveSgLayoutAsInt(), perm) &&
703 checkTranspose(getEffectiveSgDataAsInt(),
704 other.getEffectiveSgDataAsInt(), perm) &&
705 checkTranspose(getEffectiveOrderAsInt(),
706 other.getEffectiveOrderAsInt(), perm);
708 return checkTranspose(getEffectiveInstDataAsInt(),
709 other.getEffectiveInstDataAsInt(), perm);
711 return checkTranspose(getEffectiveLaneLayoutAsInt(),
712 other.getEffectiveLaneLayoutAsInt(), perm) &&
713 checkTranspose(getEffectiveLaneDataAsInt(),
714 other.getEffectiveLaneDataAsInt(), perm) &&
715 checkTranspose(getEffectiveOrderAsInt(),
716 other.getEffectiveOrderAsInt(), perm);
721bool LayoutAttr::isCompatibleWith(
const xegpu::DistributeLayoutAttr &other,
722 SmallVector<int64_t> shape,
726 if (getEffectiveOrderAsInt() == other.getEffectiveOrderAsInt()) {
729 if (getEffectiveSgLayoutAsInt() == other.getEffectiveSgLayoutAsInt() &&
730 getEffectiveSgDataAsInt() == other.getEffectiveSgDataAsInt())
733 if (getEffectiveLaneLayoutAsInt() ==
734 other.getEffectiveLaneLayoutAsInt() &&
735 getEffectiveLaneDataAsInt() == other.getEffectiveLaneDataAsInt())
739 auto compareCoordsForAllIds = [&](int64_t size) {
740 for (int64_t
id : llvm::seq<int64_t>(0, size)) {
741 auto coords = computeStaticDistributedCoords(
id, shape);
742 auto otherCoords = other.computeStaticDistributedCoords(
id, shape);
743 if (coords != otherCoords)
751 return compareCoordsForAllIds(wgSize);
754 return (getEffectiveInstDataAsInt() == other.getEffectiveInstDataAsInt());
757 int64_t subgroupSize =
computeProduct(getEffectiveLaneLayoutAsInt());
758 return compareCoordsForAllIds(subgroupSize);
767SliceAttr::verify(llvm::function_ref<InFlightDiagnostic()>
emitError,
771 return emitError() <<
"expected dims attribute";
774 llvm::SmallDenseSet<int64_t> seen;
777 return emitError() <<
"invalid dim (" << dim <<
") in slice attribute.";
778 if (!seen.insert(dim).second)
779 return emitError() <<
"repeated dim (" << dim <<
") in slice attribute.";
784SliceAttr SliceAttr::flatten()
const {
785 xegpu::DistributeLayoutAttr parent = getParent();
786 SmallVector<DenseI64ArrayAttr> slicedDims({
getDims()});
788 while (
auto sliceAttr = dyn_cast<xegpu::SliceAttr>(parent)) {
789 parent = sliceAttr.getParent();
790 slicedDims.push_back(sliceAttr.getDims());
793 auto layoutAttr = dyn_cast<xegpu::LayoutAttr>(parent);
795 llvm::to_vector(llvm::seq<int64_t>(0, layoutAttr.getRank()));
798 SmallVector<int64_t> remainingDims(
indices);
799 for (
auto dim : llvm::reverse(slicedDims))
800 remainingDims = XeGPUDialect::slice(llvm::ArrayRef<int64_t>(remainingDims),
804 SmallVector<int64_t> flattenedDims = XeGPUDialect::slice(
805 llvm::ArrayRef<int64_t>(
indices), llvm::ArrayRef<int64_t>(remainingDims));
807 return xegpu::SliceAttr::get(
812FailureOr<SmallVector<Value>>
813SliceAttr::delinearizeId(OpBuilder &builder, Location loc, Value linearId) {
814 SliceAttr attr = flatten();
815 auto parent = dyn_cast<LayoutAttr>(attr.getParent());
816 return parent.delinearizeId(builder, loc, linearId);
822FailureOr<SmallVector<SmallVector<Value>>>
823SliceAttr::computeDistributedCoords(OpBuilder &builder, Location loc,
824 Value linearId, ArrayRef<int64_t> shape) {
825 assert(getRank() ==
static_cast<int64_t
>(shape.size()) &&
"invalid shape.");
827 SmallVector<int64_t> layout;
828 SmallVector<int64_t> subShape;
829 if (isForWorkgroup()) {
830 layout = getEffectiveSgLayoutAsInt();
831 subShape = getEffectiveSgDataAsInt();
832 }
else if (isForSubgroup()) {
833 layout = getEffectiveLaneLayoutAsInt();
834 subShape = getEffectiveLaneDataAsInt();
839 if (subShape.empty())
843 auto maybeIds = delinearizeId(builder, loc, linearId);
849 ArrayRef<int64_t> dims = flatten().getDims().
asArrayRef();
850 SmallVector<Value> canonicalIds =
851 XeGPUDialect::slice(ArrayRef<Value>(*maybeIds), dims);
853 return genCoordinates(builder, loc, canonicalIds, layout, subShape, shape);
860SmallVector<SmallVector<int64_t>>
861SliceAttr::computeStaticDistributedCoords(int64_t linearId,
862 ArrayRef<int64_t> shape) {
863 assert(getRank() ==
static_cast<int64_t
>(shape.size()) &&
"invalid shape.");
865 SmallVector<int64_t> layout;
866 SmallVector<int64_t> subShape;
867 SmallVector<int64_t> instData;
868 if (isForWorkgroup()) {
869 layout = getEffectiveSgLayoutAsInt();
870 subShape = getEffectiveSgDataAsInt();
871 }
else if (isForSubgroup()) {
872 instData = getEffectiveInstDataAsInt();
873 layout = getEffectiveLaneLayoutAsInt();
874 subShape = getEffectiveLaneDataAsInt();
876 if (!instData.empty()) {
881 assert(!subShape.empty() &&
"sgdata or lanedata cannot be empty");
884 SliceAttr flattened = flatten();
885 auto parent = dyn_cast<LayoutAttr>(flattened.getParent());
886 SmallVector<int64_t> parentLayoutVec;
887 if (parent.isForWorkgroup())
888 parentLayoutVec = parent.getEffectiveSgLayoutAsInt();
890 parentLayoutVec = parent.getEffectiveLaneLayoutAsInt();
892 SmallVector<int64_t> order = parent.getEffectiveOrderAsInt();
893 SmallVector<int64_t> allIds(parentLayoutVec.size());
894 int64_t remaining = linearId;
895 for (
size_t i = 0; i < order.size(); ++i) {
896 int64_t dimIdx = order[i];
897 allIds[dimIdx] = remaining % parentLayoutVec[dimIdx];
898 if (i < order.size() - 1)
899 remaining = remaining / parentLayoutVec[dimIdx];
904 ArrayRef<int64_t> dims = flattened.getDims().asArrayRef();
905 SmallVector<int64_t> canonicalIds =
906 XeGPUDialect::slice(ArrayRef<int64_t>(allIds), dims);
911bool SliceAttr::isSliceOf(
const xegpu::DistributeLayoutAttr &other) {
912 auto flattenedThis = flatten();
915 if (
auto otherLayout = dyn_cast<xegpu::LayoutAttr>(other))
916 return flattenedThis.getParent() == otherLayout;
918 auto flattenedOther = dyn_cast<xegpu::SliceAttr>(other).flatten();
920 if (flattenedThis.getParent() != flattenedOther.getParent())
924 llvm::SmallDenseSet<int64_t> thisDims(
925 flattenedThis.getDims().asArrayRef().begin(),
926 flattenedThis.getDims().asArrayRef().end());
927 return llvm::all_of(flattenedOther.getDims().asArrayRef(),
928 [&](int64_t dim) { return thisDims.contains(dim); });
931bool SliceAttr::isEqualTo(
const xegpu::DistributeLayoutAttr &other) {
932 if (dyn_cast<xegpu::LayoutAttr>(other))
935 auto flattenedThis = flatten();
936 auto flattenedOther = dyn_cast<xegpu::SliceAttr>(other).flatten();
938 return ((flattenedThis.getParent() == flattenedOther.getParent()) &&
939 (flattenedThis.getDims() == flattenedOther.getDims()));
942bool SliceAttr::isCompatibleWith(
const xegpu::DistributeLayoutAttr &other,
943 SmallVector<int64_t> shape,
947 if (getEffectiveOrderAsInt() == other.getEffectiveOrderAsInt()) {
950 if (getEffectiveSgLayoutAsInt() == other.getEffectiveSgLayoutAsInt() &&
951 getEffectiveSgDataAsInt() == other.getEffectiveSgDataAsInt())
954 if (getEffectiveLaneLayoutAsInt() ==
955 other.getEffectiveLaneLayoutAsInt() &&
956 getEffectiveLaneDataAsInt() == other.getEffectiveLaneDataAsInt())
960 auto compareCoordsForAllIds = [&](int64_t size) {
961 for (int64_t
id : llvm::seq<int64_t>(0, size)) {
962 auto coords = computeStaticDistributedCoords(
id, shape);
963 auto otherCoords = other.computeStaticDistributedCoords(
id, shape);
964 if (coords != otherCoords)
970 auto flattenedThis = flatten();
971 auto parent = dyn_cast<LayoutAttr>(flattenedThis.getParent());
973 int64_t wgSize =
computeProduct(parent.getEffectiveSgLayoutAsInt());
974 return compareCoordsForAllIds(wgSize);
977 return (getEffectiveInstDataAsInt() == other.getEffectiveInstDataAsInt());
980 int64_t subgroupSize =
computeProduct(parent.getEffectiveLaneLayoutAsInt());
981 return compareCoordsForAllIds(subgroupSize);
986xegpu::SliceAttr SliceAttr::dropSliceDims(ArrayRef<int64_t> sliceDimsToDrop) {
987 if (sliceDimsToDrop.empty())
989 SmallVector<int64_t> sliceDims{
getDims().asArrayRef()};
990 for (
auto dim : sliceDimsToDrop) {
991 auto foundIt = std::find(sliceDims.begin(), sliceDims.end(), dim);
992 assert(foundIt != sliceDims.end() &&
993 "Expected to find the specified reduction dim in slice dims");
994 sliceDims.erase(foundIt);
997 auto sliceWithoutDims = xegpu::SliceAttr::get(
1001 return sliceWithoutDims;
1009static SmallVector<int64_t>
1017 std::max(maxDim, *std::max_element(sliceDims.begin(), sliceDims.end()));
1019 std::max(maxDim, *std::max_element(dimsToMap.begin(), dimsToMap.end()));
1020 int64_t parentSpaceRank = maxDim + sliceDims.size() + 1;
1024 llvm::SmallDenseSet<int64_t> slicedDimsSet(sliceDims.begin(),
1027 for (
int64_t i = 0; i < parentSpaceRank; ++i) {
1028 if (!slicedDimsSet.contains(i))
1029 remainingDims.push_back(i);
1034 for (
auto dim : dimsToMap) {
1035 int64_t mappedDim = remainingDims[dim];
1036 adjustUnitDims.push_back(mappedDim);
1039 return adjustUnitDims;
1045 DistributeLayoutAttr parentLayout = getParent();
1053 parentLayout.setUnitDimData(adjustUnitDims), getDims());
1059 DistributeLayoutAttr parentLayout = getParent();
1066 return SliceAttr::get(
1067 getContext(), parentLayout.setUnitDimLayout(adjustUnitDims), getDims());
1072DistributeLayoutAttr SliceAttr::setDimData(int64_t dim, int64_t sgData,
1073 int64_t instData, int64_t laneData) {
1074 ArrayRef<int64_t> sliceDims =
getDims().asArrayRef();
1075 auto parent = getParent();
1077 SmallVector<int64_t> dimSet;
1078 dimSet.push_back(dim);
1079 SmallVector<int64_t> adjustDims =
1081 return SliceAttr::get(
1083 parent.setDimData(adjustDims[0], sgData, instData, laneData),
getDims());
1104DistributeLayoutAttr SliceAttr::dropDims(SmallVector<int64_t> dimGroup) {
1106 SmallVector<int64_t> sliceDims = llvm::to_vector(
getDims().asArrayRef());
1107 SmallVector<int64_t> dimsInParentSpace =
1110 auto droppedParent = getParent().dropDims(dimsInParentSpace);
1115 SmallVector<int64_t> newSliceDims;
1116 for (int64_t d : sliceDims) {
1118 llvm::count_if(dimsInParentSpace, [&](int64_t s) {
return s < d; });
1119 newSliceDims.push_back(d - offset);
1122 return SliceAttr::get(
getContext(), droppedParent,
1129DistributeLayoutAttr SliceAttr::collapseDims(SmallVector<int64_t> dimGroup) {
1132 SmallVector<int64_t> sliceDims = llvm::to_vector(
getDims().asArrayRef());
1133 assert(
"expect sliceDims not being collapsed" &&
1134 llvm::none_of(dimGroup, [&](int64_t dim) {
1135 return llvm::is_contained(sliceDims, dim);
1137 SmallVector<int64_t> dimsInParentSpace =
1140 auto collapsedParent = getParent().collapseDims(dimsInParentSpace);
1141 return SliceAttr::get(
getContext(), collapsedParent,
1148 llvm::sort(sortedSliceDims);
1150 for (
size_t i = 1; i < sortedSliceDims.size(); ++i) {
1151 assert((sortedSliceDims[i] == sortedSliceDims[i - 1] + 1) &&
1152 "slice dims non consecutive, cannot be transposed");
1156 if (sortedSliceDims.front() == 0) {
1159 for (
int64_t dim : permutation)
1160 permForParent.push_back(dim + sortedSliceDims.size());
1161 for (
int64_t i = sortedSliceDims.size() - 1; i >= 0; --i)
1162 permForParent.push_back(i);
1166 for (
int64_t i = sortedSliceDims.size() - 1; i >= 0; --i)
1167 permForParent.push_back(i + permutation.size());
1168 for (
int64_t dim : permutation)
1169 permForParent.push_back(dim);
1171 return permForParent;
1177 DistributeLayoutAttr parent = getParent();
1180 auto transposedParent = parent.transposeDims(permForParent);
1181 return SliceAttr::get(
getContext(), transposedParent,
1186bool SliceAttr::isTransposeOf(
const xegpu::DistributeLayoutAttr &other,
1190 auto otherSlice = dyn_cast<xegpu::SliceAttr>(other);
1191 if (!otherSlice || getDims() != otherSlice.getDims())
1195 DistributeLayoutAttr parent = getParent();
1197 auto otherParent = otherSlice.getParent();
1198 return parent.isTransposeOf(otherParent, permForParent, kind);
1206RangeAttr::verify(llvm::function_ref<mlir::InFlightDiagnostic()>
emitError,
1207 IntegerAttr startOfRange, IntegerAttr endOfRange) {
1208 if (startOfRange.getInt() >= endOfRange.getInt())
1209 return emitError() <<
"'end' : " << endOfRange.getInt()
1210 <<
" must be greater than 'start' : "
1211 << startOfRange.getInt();
1220mlir::Type TensorDescType::parse(AsmParser &parser) {
1221 llvm::SmallVector<int64_t> shape;
1222 mlir::Type elementType;
1223 mlir::FailureOr<mlir::Attribute> encoding;
1224 mlir::FailureOr<mlir::Attribute> layout;
1232 parser.
emitError(shapeLoc,
"failed to parse parameter 'shape'");
1237 if (mlir::failed(parser.
parseType(elementType))) {
1238 parser.
emitError(elemTypeLoc,
"failed to parse parameter 'elementType'");
1244 mlir::Attribute attr;
1246 if (mlir::succeeded(res)) {
1247 if (mlir::isa<DistributeLayoutAttr>(attr)) {
1251 if (mlir::isa<BlockTensorDescAttr>(attr)) {
1264 return TensorDescType::getChecked(
1266 elementType, encoding.value_or(BlockTensorDescAttr::get(ctxt)),
1267 layout.value_or(mlir::Attribute()));
1270void TensorDescType::print(AsmPrinter &printer)
const {
1274 for (int64_t dim : shape) {
1275 if (mlir::ShapedType::isDynamic(dim))
1284 auto encoding = getEncoding();
1285 auto blockAttr = llvm::dyn_cast_if_present<BlockTensorDescAttr>(encoding);
1286 if (encoding && (!blockAttr || !blockAttr.hasDefaultsOnly()))
1287 printer <<
", " << encoding;
1289 if (
auto layout = getLayout())
1290 printer <<
", " << layout;
1295TensorDescType TensorDescType::get(llvm::ArrayRef<int64_t> shape,
1296 mlir::Type elementType,
int array_length,
1297 bool boundary_check,
1298 MemorySpace memory_space,
1299 mlir::Attribute layout) {
1301 auto attr = BlockTensorDescAttr::get(context, memory_space, array_length,
1303 return Base::get(context, shape, elementType, attr, layout);
1307TensorDescType::verify(llvm::function_ref<InFlightDiagnostic()>
emitError,
1308 llvm::ArrayRef<int64_t> shape, mlir::Type elementType,
1309 mlir::Attribute encoding, mlir::Attribute layout) {
1310 size_t rank = shape.size();
1313 return emitError() <<
"expected non-zero rank tensor";
1315 auto blockAttr = mlir::dyn_cast_if_present<BlockTensorDescAttr>(encoding);
1317 MemorySpaceAttr memorySpaceAttr = blockAttr.getMemorySpace();
1318 if (rank > 1 && memorySpaceAttr &&
1319 memorySpaceAttr.getValue() == MemorySpace::SLM)
1320 return emitError() <<
"SLM is only supported for 1D block tensor";
1324 return emitError() <<
"unsupported element type " << elementType
1325 <<
": expected integer or float";
1327 if (
auto layoutAttr =
1328 mlir::dyn_cast_if_present<DistributeLayoutAttr>(layout)) {
1329 if (rank != (
size_t)layoutAttr.getRank())
1330 return emitError() <<
"expected layout rank to match tensor rank";
1332 if (!layoutAttr.isDistributable(SmallVector<int64_t>(shape))) {
1333 std::string shapeStr;
1334 llvm::raw_string_ostream stream(shapeStr);
1335 llvm::interleaveComma(shape, stream);
1336 return emitError() <<
"cannot distribute [" << shapeStr <<
"] using "
1347mlir::Type MemDescType::parse(AsmParser &parser) {
1348 llvm::SmallVector<int64_t> shape;
1349 mlir::Type elementType;
1350 mlir::FailureOr<MemLayoutAttr> layout;
1358 parser.
emitError(shapeLoc,
"failed to parse parameter 'shape'");
1363 if (mlir::failed(parser.
parseType(elementType))) {
1364 parser.
emitError(elemTypeLoc,
"failed to parse parameter 'elementType'");
1372 if (mlir::failed(res))
1382 return MemDescType::getChecked(
1384 elementType, layout.value_or(MemLayoutAttr()));
1387void MemDescType::print(AsmPrinter &printer)
const {
1394 if (
auto layout = getMemLayout())
1395 printer <<
", " << layout;
1404Attribute MemLayoutAttr::parse(AsmParser &parser, Type type) {
1409 llvm::SmallDenseSet<StringRef> seenKeys;
1410 SmallVector<NamedAttribute> attributes;
1412 auto parseElt = [&]() -> ParseResult {
1415 return parser.
emitError(loc,
"expected valid attribute name");
1417 if (!seenKeys.insert(nameId).second)
1418 return parser.
emitError(loc,
"duplicate key '")
1419 << nameId <<
" in mem layout attribute";
1427 attributes.emplace_back(nameId, attr);
1443 loc, context, DictionaryAttr::get(context, attributes));
1446void MemLayoutAttr::print(AsmPrinter &printer)
const {
1448 ArrayRef<NamedAttribute> attrs = getAttrs().getValue();
1449 for (
size_t i = 0; i < attrs.size(); i++) {
1450 printer << attrs[i].getName().str() <<
" = " << attrs[i].getValue();
1451 if (i < attrs.size() - 1)
1460template <
typename ArithOp>
1465 return ArithOp::create(builder, loc, aVal, bVal).getResult();
1470 genBinOp<arith::DivSIOp>(a, builder.getIndexAttr(b), loc, builder)
1474 genBinOp<arith::RemSIOp>(a, builder.getIndexAttr(b), loc, builder)
1478 genBinOp<arith::MulIOp>(a, builder.getIndexAttr(b), loc, builder)
1481#define add(a, b) genBinOp<arith::AddIOp>(a, b, loc, builder)
1490 assert(offsets.size() == blockShape.size() &&
1491 "offsets and blockShape must have the same size");
1495 for (
auto [offset, block] : llvm::zip(offsets, blockShape)) {
1496 divs.push_back(
div(offset, block));
1497 rems.push_back(
rem(offset, block));
1499 blockedOffsets.append(divs.begin(), divs.end());
1500 blockedOffsets.append(rems.begin(), rems.end());
1502 return blockedOffsets;
1510 ArrayAttr strideAttr = getStrideAttr();
1512 for (
Attribute attr : strideAttr.getValue()) {
1513 strides.push_back(cast<IntegerAttr>(attr).getInt());
1521 llvm::to_vector<4>(llvm::seq<int>(0, strides.size()));
1522 llvm::sort(perm, [&](
int a,
int b) {
return strides[a] < strides[
b]; });
1524 assert(strides[perm[0]] == 1 &&
"inner most dim must have stride 1");
1526 SmallVector<int64_t> innerBlkStride(innerBlkShape.size());
1527 innerBlkStride[perm[0]] = 1;
1528 for (
size_t i = 1; i < perm.size(); ++i)
1529 innerBlkStride[perm[i]] =
1530 innerBlkStride[perm[i - 1]] * innerBlkShape[perm[i - 1]];
1536 SmallVector<int64_t> matrixShapeOrig(matrixShape.size());
1537 SmallVector<int64_t> BlkShapeOrig(matrixShape.size());
1538 for (
size_t i = 0; i < perm.size() - 1; ++i) {
1539 matrixShapeOrig[perm[i]] = strides[perm[i + 1]] / strides[perm[i]];
1540 BlkShapeOrig[perm[i]] = matrixShapeOrig[perm[i]] / innerBlkShape[perm[i]];
1543 int64_t innerBlkSize = 1;
1544 for (
auto s : innerBlkShape)
1547 SmallVector<int64_t> outerBlkStride(matrixShape.size());
1548 outerBlkStride[perm[0]] = innerBlkSize;
1549 for (
size_t i = 0; i < perm.size() - 1; ++i) {
1550 outerBlkStride[perm[i + 1]] =
1551 outerBlkStride[perm[i]] * BlkShapeOrig[perm[i]];
1555 SmallVector<int64_t> blockedStrides;
1556 blockedStrides.append(outerBlkStride.begin(), outerBlkStride.end());
1557 blockedStrides.append(innerBlkStride.begin(), innerBlkStride.end());
1559 return blockedStrides;
1563Value MemDescType::getLinearOffsets(OpBuilder &builder, Location loc,
1564 ArrayRef<OpFoldResult> offsets) {
1567 SmallVector<int64_t> blockShape = getBlockShape();
1568 SmallVector<int64_t> strides = getStrideShape();
1569 SmallVector<OpFoldResult> blockedOffsets;
1572 if (llvm::equal(blockShape, matrixShape)) {
1574 strides.erase(strides.begin(), strides.begin() + matrixShape.size());
1576 assert(offsets.size() == blockShape.size() &&
1577 "offsets and blockShape must have the same size");
1581 SmallVector<OpFoldResult> divs, rems;
1583 for (
auto [offset, block] : llvm::zip(offsets, blockShape)) {
1584 divs.push_back(
div(offset, block));
1585 rems.push_back(
rem(offset, block));
1587 blockedOffsets.append(divs.begin(), divs.end());
1588 blockedOffsets.append(rems.begin(), rems.end());
1589 offsets = blockedOffsets;
1594 for (
size_t i = 0; i < offsets.size(); ++i) {
1595 OpFoldResult mulResult =
mul(offsets[i], strides[i]);
1597 linearOffset = arith::AddIOp::create(builder, loc, mulVal, linearOffset);
1600 return linearOffset;
1606#include <mlir/Dialect/XeGPU/IR/XeGPUDialect.cpp.inc>
1607#define GET_ATTRDEF_CLASSES
1608#include <mlir/Dialect/XeGPU/IR/XeGPUAttrs.cpp.inc>
1609#define GET_TYPEDEF_CLASSES
1610#include <mlir/Dialect/XeGPU/IR/XeGPUTypes.cpp.inc>
static Type getElementType(Type type)
Determine the element type of type.
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
MLIRContext * getContext() const
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual ParseResult parseDimensionList(SmallVectorImpl< int64_t > &dimensions, bool allowDynamic=true, bool withTrailingX=true)=0
Parse a dimension list of a tensor or memref type.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseOptionalComma()=0
Parse a , token if present.
auto getChecked(SMLoc loc, ParamsT &&...params)
Invoke the getChecked method of the given Attribute or Type class, using the provided location to emi...
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseGreater()=0
Parse a '>' token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
void printDimensionList(ArrayRef< int64_t > shape)
Attributes are known-constant values of operations.
static BoolAttr get(MLIRContext *context, bool value)
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.
This class helps build Operations.
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
This class represents a single result from folding an operation.
A range-style iterator that allows for iterating over the offsets of all potential tiles of size tile...
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.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Specialization of arith.constant op that returns an integer of index type.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< int32_t > content)
ArrayRef< T > asArrayRef() const
auto getDims(VectorType vType)
Returns a range over the dims (size and scalability) of a VectorType.
static SmallVector< SmallVector< int64_t > > genStaticCoordinates(llvm::ArrayRef< int64_t > canonicalIds, llvm::ArrayRef< int64_t > layout, llvm::ArrayRef< int64_t > subShape, llvm::ArrayRef< int64_t > shape)
LayoutKind
Specifies the level of a layout hierarchy for comparison or propagation.
static SmallVector< int64_t > mapSlicedDimsToParentSpace(const SmallVector< int64_t > &dimsToMap, ArrayRef< int64_t > sliceDims)
SmallVector< OpFoldResult > getBlockedOffsets(OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > offsets, ArrayRef< int64_t > blockShape)
OpFoldResult genBinOp(OpFoldResult a, OpFoldResult b, Location loc, OpBuilder &builder)
static SmallVector< SmallVector< Value > > genCoordinates(OpBuilder &builder, Location loc, SmallVector< Value > delinearizedId, ArrayRef< int64_t > subShapesLayout, ArrayRef< int64_t > subShape, ArrayRef< int64_t > srcShape)
SmallVector< int64_t > getPermForParentLayout(ArrayRef< int64_t > sliceDims, ArrayRef< int64_t > permutation)
Include the generated interface declarations.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
SmallVector< int64_t > computeElementwiseMul(ArrayRef< int64_t > v1, ArrayRef< int64_t > v2)
Return a vector containing llvm::zip_equal(v1, v2) multiplied elementwise.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
int64_t computeProduct(ArrayRef< int64_t > basis)
Self-explicit.
detail::DenseArrayAttrImpl< int32_t > DenseI32ArrayAttr
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
bool isPermutationVector(ArrayRef< int64_t > interchange)
Method to check if an interchange vector is a permutation.