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"
52static SmallVector<SmallVector<Value>>
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);
139 for (
size_t i = 0; i < start.size(); ++i)
140 coord[i] = start[i] + off[i];
141 expanded.push_back(std::move(coord));
159 const xegpu::DistributeLayoutAttr &other,
164 self.getEffectiveLaneDataAsInt() != other.getEffectiveLaneDataAsInt();
167 selfSubShape = self.getEffectiveLaneDataAsInt();
168 otherSubShape = other.getEffectiveLaneDataAsInt();
170 for (
int64_t id : llvm::seq<int64_t>(0, size)) {
171 auto coords = self.computeStaticDistributedCoords(
id,
shape);
172 auto otherCoords = other.computeStaticDistributedCoords(
id,
shape);
177 if (coords != otherCoords)
184bool XeGPUDialect::isSharedMemory(
const MemRefType &memrefTy) {
185 Attribute attr = memrefTy.getMemorySpace();
188 if (
auto intAttr = llvm::dyn_cast_if_present<IntegerAttr>(attr))
189 return intAttr.getInt() == 3;
190 if (
auto memrefSpace = llvm::dyn_cast_if_present<MemorySpaceAttr>(attr))
191 return memrefSpace.getValue() == MemorySpace::SLM;
192 if (
auto xevmSpace = llvm::dyn_cast_if_present<xevm::AddrSpaceAttr>(attr))
193 return xevmSpace.getValue() == xevm::AddrSpace::SHARED;
194 return gpu::GPUDialect::isWorkgroupMemoryAddressSpace(attr);
201 xegpu::MemorySpace memory_space,
203 bool boundary_check) {
204 auto scopeAttr = MemorySpaceAttr::get(context, memory_space);
206 IntegerAttr::get(IntegerType::get(context, 64), array_length);
208 return Base::get(context, scopeAttr, lengthAttr, boundaryAttr);
211bool BlockTensorDescAttr::hasDefaultsOnly() {
212 return getMemorySpace().getValue() == xegpu::MemorySpace::Global &&
213 getArrayLength().getInt() == 1 && getBoundaryCheck().getValue();
220LayoutAttr::verify(llvm::function_ref<mlir::InFlightDiagnostic()>
emitError,
226 if (!sg_layout && !inst_data && !lane_layout)
232 if (sg_layout && inst_data && sg_layout.size() != inst_data.size()) {
234 <<
"expected sg_layout and inst_data to have the same rank";
237 if (sg_layout && lane_layout && sg_layout.size() != lane_layout.size()) {
239 <<
"expected sg_layout and lane_layout to have the same rank";
242 if (inst_data && lane_layout && inst_data.size() != lane_layout.size()) {
243 return emitError() <<
"expected inst_data and lane_layout to have the same "
244 "rank, got inst_data "
245 << inst_data.size() <<
", lane_layout "
246 << lane_layout.size();
249 if ((sg_layout && !sg_data) || (!sg_layout && sg_data))
250 return emitError() <<
"sg_layout and sg_data must be used together";
251 if (sg_layout && sg_data && sg_layout.size() != sg_data.size())
253 <<
"expected sg_data and sg_layout to have the same rank";
255 if ((lane_layout && !lane_data) || (!lane_layout && lane_data))
256 return emitError() <<
"lane_layout and lane_data must be used together";
257 if (lane_layout && lane_data && lane_layout.size() != lane_data.size())
259 <<
"expected lane_data and lane_layout to have the same rank";
262 if (!sg_layout && !lane_layout)
264 <<
"expected sg_layout/lane_layout being used with order";
266 if (sg_layout && order.size() != sg_layout.size())
268 <<
"expected order and sg_layout to have the same rank";
270 if (lane_layout && order.size() != lane_layout.size())
272 <<
"expected order and lane_layout to have the same rank";
278FailureOr<SmallVector<Value>>
279LayoutAttr::delinearizeId(OpBuilder &builder, Location loc, Value linearId) {
281 SmallVector<int64_t> sgLayoutInt;
282 if (isForWorkgroup()) {
283 sgLayoutInt = getEffectiveSgLayoutAsInt();
284 }
else if (isForSubgroup()) {
285 sgLayoutInt = getEffectiveLaneLayoutAsInt();
293 SmallVector<int64_t> order;
294 if (orderAttr && !orderAttr.empty()) {
295 order = llvm::map_to_vector(orderAttr.asArrayRef(), [](int32_t idx) {
296 return static_cast<int64_t>(idx);
300 order = llvm::to_vector(
301 llvm::reverse(llvm::seq<int64_t>(0, sgLayoutInt.size())));
304 if (order.size() != sgLayoutInt.size()) {
308 SmallVector<Value>
result(sgLayoutInt.size());
309 Value remaining = linearId;
332 for (
size_t i = 0; i < order.size(); ++i) {
333 int64_t dimIdx = order[i];
334 int64_t dimSize = sgLayoutInt[dimIdx];
337 builder.createOrFold<arith::ConstantIndexOp>(loc, dimSize);
344 builder.createOrFold<arith::RemUIOp>(loc, remaining, dimSizeVal);
351 if (i < order.size() - 1) {
353 builder.createOrFold<arith::DivUIOp>(loc, remaining, dimSizeVal);
362FailureOr<SmallVector<SmallVector<Value>>>
363LayoutAttr::computeDistributedCoords(OpBuilder &builder, Location loc,
364 Value linearId, ArrayRef<int64_t> shape) {
365 SmallVector<int64_t> layout;
366 SmallVector<int64_t> subShape;
367 if (isForWorkgroup()) {
368 layout = getEffectiveSgLayoutAsInt();
369 subShape = getEffectiveSgDataAsInt();
370 }
else if (isForSubgroup()) {
371 layout = getEffectiveLaneLayoutAsInt();
372 subShape = getEffectiveLaneDataAsInt();
376 assert(!subShape.empty() &&
"sgdata or lanedata cannot be empty for "
377 "distributed coordinates computation");
380 auto maybeIds = delinearizeId(builder, loc, linearId);
383 SmallVector<Value> ids = *maybeIds;
385 return genCoordinates(builder, loc, ids, layout, subShape, shape);
388bool LayoutAttr::isEqualTo(
const xegpu::DistributeLayoutAttr &other) {
389 if (dyn_cast<xegpu::SliceAttr>(other))
392 return *
this == dyn_cast<xegpu::LayoutAttr>(other);
398SmallVector<SmallVector<int64_t>>
399LayoutAttr::computeStaticDistributedCoords(int64_t linearId,
400 ArrayRef<int64_t> shape) {
401 SmallVector<int64_t> layoutVec;
402 SmallVector<int64_t> subShape;
403 SmallVector<int64_t> instData;
404 if (isForWorkgroup()) {
405 layoutVec = getEffectiveSgLayoutAsInt();
406 subShape = getEffectiveSgDataAsInt();
407 }
else if (isForSubgroup()) {
408 instData = getEffectiveInstDataAsInt();
409 layoutVec = getEffectiveLaneLayoutAsInt();
410 subShape = getEffectiveLaneDataAsInt();
412 if (!instData.empty()) {
416 assert(!subShape.empty() &&
"sgdata or lanedata cannot be empty");
419 SmallVector<int64_t> order = getEffectiveOrderAsInt();
420 SmallVector<int64_t> delinearizedId(layoutVec.size());
421 int64_t remaining = linearId;
422 for (
size_t i = 0; i < order.size(); ++i) {
423 int64_t dimIdx = order[i];
424 delinearizedId[dimIdx] = remaining % layoutVec[dimIdx];
425 remaining = remaining / layoutVec[dimIdx];
433LayoutAttr::setUnitDimData(SmallVector<int64_t> unitDims)
const {
434 auto sgDataOpt = getSgData();
435 auto instDataOpt = getInstData();
436 auto laneDataOpt = getLaneData();
438 SmallVector<int32_t> sgData;
439 SmallVector<int32_t> instData;
440 SmallVector<int32_t> laneData;
443 sgData = llvm::to_vector(sgDataOpt.asArrayRef());
446 instData = llvm::to_vector(instDataOpt.asArrayRef());
449 laneData = llvm::to_vector(laneDataOpt.asArrayRef());
451 for (
auto dim : unitDims) {
452 if (dim <
static_cast<int64_t
>(sgData.size()))
454 if (dim <
static_cast<int64_t
>(instData.size()))
456 if (dim <
static_cast<int64_t
>(laneData.size()))
460 return LayoutAttr::get(
474LayoutAttr::setUnitDimLayout(SmallVector<int64_t> unitDims)
const {
475 auto sgLayoutOpt = getSgLayout();
476 auto laneLayoutOpt = getLaneLayout();
478 SmallVector<int32_t> sgLayout;
479 SmallVector<int32_t> laneLayout;
482 sgLayout = llvm::to_vector(sgLayoutOpt.asArrayRef());
484 laneLayout = llvm::to_vector(laneLayoutOpt.asArrayRef());
486 for (
auto dim : unitDims) {
487 if (dim <
static_cast<int64_t
>(sgLayout.size()))
489 if (dim <
static_cast<int64_t
>(laneLayout.size()))
493 return LayoutAttr::get(
497 getSgData(), getInstData(),
500 getLaneData(), getOrder());
505DistributeLayoutAttr LayoutAttr::setDimData(int64_t dim, int64_t sgData,
509 SmallVector<int64_t> sgDataVec = getEffectiveSgDataAsInt();
510 SmallVector<int64_t> instDataVec = getEffectiveInstDataAsInt();
511 SmallVector<int64_t> laneDataVec = getEffectiveLaneDataAsInt();
513 if (dim <
static_cast<int64_t
>(sgDataVec.size()) && sgData != -1)
514 sgDataVec[dim] = sgData;
515 if (dim <
static_cast<int64_t
>(instDataVec.size()) && instData != -1)
516 instDataVec[dim] = instData;
517 if (dim <
static_cast<int64_t
>(laneDataVec.size()) && laneData != -1)
518 laneDataVec[dim] = laneData;
520 SmallVector<int32_t> sgDataVec32(sgDataVec.begin(), sgDataVec.end());
521 SmallVector<int32_t> instDataVec32(instDataVec.begin(), instDataVec.end());
522 SmallVector<int32_t> laneDataVec32(laneDataVec.begin(), laneDataVec.end());
524 return LayoutAttr::get(
539DistributeLayoutAttr LayoutAttr::dropDims(SmallVector<int64_t> dimGroup) {
541 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
542 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
543 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
544 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
545 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
548 SmallVector<int64_t> sortedDimGroup = dimGroup;
549 llvm::sort(sortedDimGroup);
551 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
552 if (!sgLayout.empty()) {
553 sgLayout.erase(sgLayout.begin() + dimIdx);
554 sgData.erase(sgData.begin() + dimIdx);
556 if (!instData.empty())
557 instData.erase(instData.begin() + dimIdx);
558 if (!laneLayout.empty()) {
559 laneLayout.erase(laneLayout.begin() + dimIdx);
560 laneData.erase(laneData.begin() + dimIdx);
567 SmallVector<int64_t> newOrder;
568 if (origOrderAttr && !origOrderAttr.empty()) {
569 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
570 for (int64_t d : origOrder) {
571 if (llvm::is_contained(dimGroup, d))
574 llvm::count_if(dimGroup, [&](int64_t s) {
return s < d; });
575 newOrder.push_back(d - offset);
577 if ((sgLayout.empty() && laneLayout.empty()) || newOrder.size() == 1)
584 SmallVector<int32_t> v32(v.begin(), v.end());
587 auto droppedLayout = xegpu::LayoutAttr::get(
588 getContext(), toAttr(sgLayout), toAttr(sgData), toAttr(instData),
589 toAttr(laneLayout), toAttr(laneData), toAttr(newOrder));
590 return droppedLayout;
596DistributeLayoutAttr LayoutAttr::collapseDims(SmallVector<int64_t> dimGroup) {
598 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
599 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
600 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
601 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
602 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
603 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
605 SmallVector<int64_t> sortedDimGroup = dimGroup;
606 llvm::sort(sortedDimGroup);
607 int64_t dimBeforeCurrent = -1;
608 for (
auto dimIdx : sortedDimGroup) {
612 if (dimBeforeCurrent >= 0) {
613 if (getOrder() && !getOrder().empty()) {
614 int64_t orderBefore = origOrder[dimBeforeCurrent];
615 int64_t orderCurrent = origOrder[dimIdx];
616 if (orderBefore != (orderCurrent - 1))
617 llvm::report_fatal_error(
618 "dimensions being collapsed must be adjacent in order");
620 if (dimIdx != (dimBeforeCurrent + 1))
621 llvm::report_fatal_error(
622 "dimensions being collapsed must be adjacent");
625 dimBeforeCurrent = dimIdx;
628 int firstDim = sortedDimGroup.front();
633 if (!sgLayout.empty()) {
634 int64_t collapsedSglayout = 1, collapsedSgData = 1;
635 for (
auto dimIdx : dimGroup) {
636 collapsedSglayout *= sgLayout[dimIdx];
637 collapsedSgData *= sgData[dimIdx];
639 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
640 sgLayout.erase(sgLayout.begin() + dimIdx, sgLayout.begin() + dimIdx + 1);
641 sgData.erase(sgData.begin() + dimIdx, sgData.begin() + dimIdx + 1);
643 sgLayout.insert(sgLayout.begin() + firstDim, collapsedSglayout);
644 sgData.insert(sgData.begin() + firstDim, collapsedSgData);
647 if (!instData.empty()) {
648 int64_t collapsedInstData = 1;
649 for (
auto dimIdx : dimGroup)
650 collapsedInstData *= instData[dimIdx];
651 for (
auto dimIdx : llvm::reverse(sortedDimGroup))
652 instData.erase(instData.begin() + dimIdx, instData.begin() + dimIdx + 1);
653 instData.insert(instData.begin() + firstDim, collapsedInstData);
656 if (!laneLayout.empty()) {
657 int64_t collapsedLaneLayout = 1, collapsedLaneData = 1;
658 for (
auto dimIdx : dimGroup) {
659 collapsedLaneLayout *= laneLayout[dimIdx];
660 collapsedLaneData *= laneData[dimIdx];
662 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
663 laneLayout.erase(laneLayout.begin() + dimIdx,
664 laneLayout.begin() + dimIdx + 1);
665 laneData.erase(laneData.begin() + dimIdx, laneData.begin() + dimIdx + 1);
667 laneLayout.insert(laneLayout.begin() + firstDim, collapsedLaneLayout);
668 laneData.insert(laneData.begin() + firstDim, collapsedLaneData);
671 SmallVector<int64_t> newOrder;
673 if (orderAttr && !orderAttr.empty()) {
675 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
676 if (dimIdx != firstDim)
677 origOrder.erase(origOrder.begin() + dimIdx);
682 llvm::to_vector(llvm::seq<size_t>(0, origOrder.size()));
686 [&](
size_t a,
size_t b) {
return origOrder[a] < origOrder[
b]; });
688 newOrder = llvm::to_vector(llvm::map_range(
689 indices, [&](
size_t i) {
return static_cast<int64_t
>(i); }));
695 SmallVector<int32_t> v32(v.begin(), v.end());
698 auto collapsedLayout = xegpu::LayoutAttr::get(
699 getContext(), toAttr(sgLayout), toAttr(sgData), toAttr(instData),
700 toAttr(laneLayout), toAttr(laneData), toAttr(newOrder));
701 return collapsedLayout;
724DistributeLayoutAttr LayoutAttr::expandDim(int64_t dim,
725 ArrayRef<int64_t> targetShape) {
726 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
727 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
728 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
729 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
730 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
732 int64_t origRank = getRank();
733 int64_t expCount =
static_cast<int64_t
>(targetShape.size());
734 assert(dim >= 0 && dim < origRank &&
"dim out of range");
735 assert(expCount >= 1 &&
"targetShape must have at least one dim");
736 int64_t newRank = origRank + expCount - 1;
741 int64_t origSgLayoutDim = sgLayout.empty() ? 1 : sgLayout[dim];
742 int64_t origSgDataDim = sgData.empty() ? 1 : sgData[dim];
743 int64_t origLaneLayoutDim = laneLayout.empty() ? 1 : laneLayout[dim];
744 int64_t origLaneDataDim = laneData.empty() ? 1 : laneData[dim];
745 int64_t origInstDataDim = instData.empty() ? 1 : instData[dim];
749 auto spread = [&](int64_t total,
750 ArrayRef<int64_t> dimSizeCap) -> SmallVector<int64_t> {
751 SmallVector<int64_t> out(expCount, 1);
752 int64_t remaining = total;
753 for (int64_t i = expCount - 1; i >= 0; --i) {
756 int64_t take = std::min(remaining, dimSizeCap[i]);
757 assert(take > 0 &&
"expandDim distribution must not be zero");
758 assert(remaining % take == 0 &&
759 "expandDims must divide evenly across dims");
763 assert(remaining == 1 &&
"expandDims total must fit within target shape");
769 auto splice = [&](SmallVector<int64_t> &vec, ArrayRef<int64_t> expanded) {
772 vec.erase(vec.begin() + dim);
773 vec.insert(vec.begin() + dim, expanded.begin(), expanded.end());
776 bool hasSgLayout = !sgLayout.empty();
777 bool hasSgData = !sgData.empty();
778 bool hasLaneLayout = !laneLayout.empty();
779 bool hasLaneData = !laneData.empty();
780 bool hasInstData = !instData.empty();
785 bool sgDataReplicated =
787 SmallVector<int64_t> expSgData(expCount, 1);
789 expSgData = spread(origSgDataDim, targetShape);
790 splice(sgData, expSgData);
792 SmallVector<int64_t> expSgLayout(expCount, 1);
794 SmallVector<int64_t> dimSizeCap(targetShape.begin(), targetShape.end());
795 if (hasSgData && !sgDataReplicated)
796 for (int64_t i = 0; i < expCount; ++i)
797 dimSizeCap[i] /= expSgData[i];
798 expSgLayout = spread(origSgLayoutDim, dimSizeCap);
799 splice(sgLayout, expSgLayout);
803 SmallVector<int64_t> perSgShape(targetShape.begin(), targetShape.end());
804 if (hasSgLayout && !sgDataReplicated)
805 for (int64_t i = 0; i < expCount; ++i)
806 perSgShape[i] /= expSgLayout[i];
811 bool laneDataReplicated =
813 SmallVector<int64_t> expLaneLayout(expCount, 1);
814 SmallVector<int64_t> expLaneData(expCount, 1);
816 expLaneData = spread(origLaneDataDim, perSgShape);
818 SmallVector<int64_t> dimSizeCap(perSgShape.begin(), perSgShape.end());
819 if (hasLaneData && !laneDataReplicated)
820 for (int64_t i = 0; i < expCount; ++i)
821 dimSizeCap[i] /= expLaneData[i];
822 expLaneLayout = spread(origLaneLayoutDim, dimSizeCap);
825 splice(laneData, expLaneData);
827 splice(laneLayout, expLaneLayout);
834 SmallVector<int64_t> expInstData;
835 if (!hasLaneLayout || !hasLaneData) {
836 expInstData = spread(origInstDataDim, perSgShape);
838 int64_t laneAtom = origLaneLayoutDim * origLaneDataDim;
839 SmallVector<int64_t> atom(expCount, 1);
840 SmallVector<int64_t> dimSizeCap(expCount, 1);
841 for (int64_t i = 0; i < expCount; ++i) {
842 atom[i] = expLaneLayout[i] * expLaneData[i];
843 dimSizeCap[i] = perSgShape[i] / atom[i];
845 expInstData = spread(origInstDataDim / laneAtom, dimSizeCap);
846 for (int64_t i = 0; i < expCount; ++i)
847 expInstData[i] *= atom[i];
849 splice(instData, expInstData);
855 SmallVector<int64_t> newOrder;
857 if (orderAttr && !orderAttr.empty()) {
858 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
859 newOrder.reserve(newRank);
860 for (int64_t o : origOrder) {
863 for (int64_t i = expCount - 1; i >= 0; --i)
864 newOrder.push_back(dim + i);
865 }
else if (o > dim) {
866 newOrder.push_back(o + expCount - 1);
868 newOrder.push_back(o);
876 SmallVector<int32_t> v32(v.begin(), v.end());
879 return xegpu::LayoutAttr::get(
getContext(), toAttr(sgLayout), toAttr(sgData),
880 toAttr(instData), toAttr(laneLayout),
881 toAttr(laneData), toAttr(newOrder));
885DistributeLayoutAttr LayoutAttr::transposeDims(ArrayRef<int64_t> permutation) {
887 SmallVector<int64_t> origSgLayout = getEffectiveSgLayoutAsInt();
888 SmallVector<int64_t> origSgData = getEffectiveSgDataAsInt();
889 SmallVector<int64_t> origInstData = getEffectiveInstDataAsInt();
890 SmallVector<int64_t> origLaneLayout = getEffectiveLaneLayoutAsInt();
891 SmallVector<int64_t> origLaneData = getEffectiveLaneDataAsInt();
892 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
894 SmallVector<int32_t> sgLayout;
895 SmallVector<int32_t> sgData;
896 SmallVector<int32_t> instData;
897 SmallVector<int32_t> laneLayout;
898 SmallVector<int32_t> laneData;
899 SmallVector<int32_t> order;
901 for (int64_t idx : permutation) {
902 if (!origLaneLayout.empty()) {
903 laneLayout.push_back(
static_cast<int32_t
>(origLaneLayout[idx]));
904 laneData.push_back(
static_cast<int32_t
>(origLaneData[idx]));
906 if (!origInstData.empty())
907 instData.push_back(
static_cast<int32_t
>(origInstData[idx]));
908 if (!origSgLayout.empty()) {
909 sgLayout.push_back(
static_cast<int32_t
>(origSgLayout[idx]));
910 sgData.push_back(
static_cast<int32_t
>(origSgData[idx]));
926 for (int64_t dim : origOrder)
928 if (origLaneLayout.empty() && origSgLayout.empty())
934 return xegpu::LayoutAttr::get(
getContext(), toAttr(sgLayout), toAttr(sgData),
935 toAttr(instData), toAttr(laneLayout),
936 toAttr(laneData), toAttr(order));
940bool LayoutAttr::isTransposeOf(
const xegpu::DistributeLayoutAttr &other,
941 ArrayRef<int64_t> perm,
945 if (getRank() != other.getRank() ||
946 perm.size() !=
static_cast<size_t>(getRank()))
953 auto checkTranspose = [](ArrayRef<int64_t> dst, ArrayRef<int64_t> src,
954 ArrayRef<int64_t> perm) {
955 for (
const auto &ta : llvm::enumerate(perm)) {
956 if (dst[ta.index()] != src[ta.value()])
966 auto checkOrderTranspose = [](ArrayRef<int64_t> dstOrder,
967 ArrayRef<int64_t> srcOrder,
968 ArrayRef<int64_t> perm) {
969 if (dstOrder.size() != srcOrder.size())
972 for (
auto [d, s] : llvm::zip_equal(dstOrder, srcOrder)) {
973 if (d != inversePerm[s])
979 return checkTranspose(getEffectiveSgLayoutAsInt(),
980 other.getEffectiveSgLayoutAsInt(), perm) &&
981 checkTranspose(getEffectiveSgDataAsInt(),
982 other.getEffectiveSgDataAsInt(), perm) &&
983 checkOrderTranspose(getEffectiveOrderAsInt(),
984 other.getEffectiveOrderAsInt(), perm);
986 return checkTranspose(getEffectiveInstDataAsInt(),
987 other.getEffectiveInstDataAsInt(), perm);
989 return checkTranspose(getEffectiveLaneLayoutAsInt(),
990 other.getEffectiveLaneLayoutAsInt(), perm) &&
991 checkTranspose(getEffectiveLaneDataAsInt(),
992 other.getEffectiveLaneDataAsInt(), perm) &&
993 checkOrderTranspose(getEffectiveOrderAsInt(),
994 other.getEffectiveOrderAsInt(), perm);
999bool LayoutAttr::isCompatibleWith(
const xegpu::DistributeLayoutAttr &other,
1000 SmallVector<int64_t> shape,
1004 if (getEffectiveOrderAsInt() == other.getEffectiveOrderAsInt()) {
1007 if (getEffectiveSgLayoutAsInt() == other.getEffectiveSgLayoutAsInt() &&
1008 getEffectiveSgDataAsInt() == other.getEffectiveSgDataAsInt())
1011 if (getEffectiveLaneLayoutAsInt() ==
1012 other.getEffectiveLaneLayoutAsInt() &&
1013 getEffectiveLaneDataAsInt() == other.getEffectiveLaneDataAsInt())
1017 auto compareCoordsForAllIds = [&](int64_t size) {
1023 return compareCoordsForAllIds(wgSize);
1026 return (getEffectiveInstDataAsInt() == other.getEffectiveInstDataAsInt());
1029 int64_t subgroupSize =
computeProduct(getEffectiveLaneLayoutAsInt());
1030 return compareCoordsForAllIds(subgroupSize);
1039SliceAttr::verify(llvm::function_ref<InFlightDiagnostic()>
emitError,
1043 return emitError() <<
"expected dims attribute";
1046 llvm::SmallDenseSet<int64_t> seen;
1047 for (int64_t dim : dims.asArrayRef()) {
1049 return emitError() <<
"invalid dim (" << dim <<
") in slice attribute.";
1050 if (!seen.insert(dim).second)
1051 return emitError() <<
"repeated dim (" << dim <<
") in slice attribute.";
1056SliceAttr SliceAttr::flatten()
const {
1057 xegpu::DistributeLayoutAttr parent = getParent();
1058 SmallVector<DenseI64ArrayAttr> slicedDims({
getDims()});
1060 while (
auto sliceAttr = dyn_cast<xegpu::SliceAttr>(parent)) {
1061 parent = sliceAttr.getParent();
1062 slicedDims.push_back(sliceAttr.getDims());
1065 auto layoutAttr = dyn_cast<xegpu::LayoutAttr>(parent);
1066 SmallVector<int64_t>
indices =
1067 llvm::to_vector(llvm::seq<int64_t>(0, layoutAttr.getRank()));
1070 SmallVector<int64_t> remainingDims(
indices);
1071 for (
auto dim : llvm::reverse(slicedDims))
1072 remainingDims = XeGPUDialect::slice(llvm::ArrayRef<int64_t>(remainingDims),
1076 SmallVector<int64_t> flattenedDims = XeGPUDialect::slice(
1077 llvm::ArrayRef<int64_t>(
indices), llvm::ArrayRef<int64_t>(remainingDims));
1079 return xegpu::SliceAttr::get(
1084FailureOr<SmallVector<Value>>
1085SliceAttr::delinearizeId(OpBuilder &builder, Location loc, Value linearId) {
1086 SliceAttr attr = flatten();
1087 auto parent = dyn_cast<LayoutAttr>(attr.getParent());
1088 return parent.delinearizeId(builder, loc, linearId);
1094FailureOr<SmallVector<SmallVector<Value>>>
1095SliceAttr::computeDistributedCoords(OpBuilder &builder, Location loc,
1096 Value linearId, ArrayRef<int64_t> shape) {
1097 assert(getRank() ==
static_cast<int64_t
>(shape.size()) &&
"invalid shape.");
1099 SmallVector<int64_t> layout;
1100 SmallVector<int64_t> subShape;
1101 if (isForWorkgroup()) {
1102 layout = getEffectiveSgLayoutAsInt();
1103 subShape = getEffectiveSgDataAsInt();
1104 }
else if (isForSubgroup()) {
1105 layout = getEffectiveLaneLayoutAsInt();
1106 subShape = getEffectiveLaneDataAsInt();
1111 if (subShape.empty())
1115 auto maybeIds = delinearizeId(builder, loc, linearId);
1121 ArrayRef<int64_t> dims = flatten().getDims().asArrayRef();
1122 SmallVector<Value> canonicalIds =
1123 XeGPUDialect::slice(ArrayRef<Value>(*maybeIds), dims);
1125 return genCoordinates(builder, loc, canonicalIds, layout, subShape, shape);
1132SmallVector<SmallVector<int64_t>>
1133SliceAttr::computeStaticDistributedCoords(int64_t linearId,
1134 ArrayRef<int64_t> shape) {
1135 assert(getRank() ==
static_cast<int64_t
>(shape.size()) &&
"invalid shape.");
1137 SmallVector<int64_t> layout;
1138 SmallVector<int64_t> subShape;
1139 SmallVector<int64_t> instData;
1140 if (isForWorkgroup()) {
1141 layout = getEffectiveSgLayoutAsInt();
1142 subShape = getEffectiveSgDataAsInt();
1143 }
else if (isForSubgroup()) {
1144 instData = getEffectiveInstDataAsInt();
1145 layout = getEffectiveLaneLayoutAsInt();
1146 subShape = getEffectiveLaneDataAsInt();
1148 if (!instData.empty()) {
1150 subShape = instData;
1153 assert(!subShape.empty() &&
"sgdata or lanedata cannot be empty");
1156 SliceAttr flattened = flatten();
1157 auto parent = dyn_cast<LayoutAttr>(flattened.getParent());
1158 SmallVector<int64_t> parentLayoutVec;
1159 if (parent.isForWorkgroup())
1160 parentLayoutVec = parent.getEffectiveSgLayoutAsInt();
1162 parentLayoutVec = parent.getEffectiveLaneLayoutAsInt();
1164 SmallVector<int64_t> order = parent.getEffectiveOrderAsInt();
1165 SmallVector<int64_t> allIds(parentLayoutVec.size());
1166 int64_t remaining = linearId;
1167 for (
size_t i = 0; i < order.size(); ++i) {
1168 int64_t dimIdx = order[i];
1169 allIds[dimIdx] = remaining % parentLayoutVec[dimIdx];
1170 if (i < order.size() - 1)
1171 remaining = remaining / parentLayoutVec[dimIdx];
1176 ArrayRef<int64_t> dims = flattened.getDims().asArrayRef();
1177 SmallVector<int64_t> canonicalIds =
1178 XeGPUDialect::slice(ArrayRef<int64_t>(allIds), dims);
1183bool SliceAttr::isSliceOf(
const xegpu::DistributeLayoutAttr &other) {
1184 auto flattenedThis = flatten();
1187 if (
auto otherLayout = dyn_cast<xegpu::LayoutAttr>(other))
1188 return flattenedThis.getParent() == otherLayout;
1190 auto flattenedOther = dyn_cast<xegpu::SliceAttr>(other).flatten();
1192 if (flattenedThis.getParent() != flattenedOther.getParent())
1196 llvm::SmallDenseSet<int64_t> thisDims(
1197 flattenedThis.getDims().asArrayRef().begin(),
1198 flattenedThis.getDims().asArrayRef().end());
1199 return llvm::all_of(flattenedOther.getDims().asArrayRef(),
1200 [&](int64_t dim) { return thisDims.contains(dim); });
1203bool SliceAttr::isEqualTo(
const xegpu::DistributeLayoutAttr &other) {
1204 if (dyn_cast<xegpu::LayoutAttr>(other))
1207 auto flattenedThis = flatten();
1208 auto flattenedOther = dyn_cast<xegpu::SliceAttr>(other).flatten();
1210 return ((flattenedThis.getParent() == flattenedOther.getParent()) &&
1211 (flattenedThis.getDims() == flattenedOther.getDims()));
1214bool SliceAttr::isCompatibleWith(
const xegpu::DistributeLayoutAttr &other,
1215 SmallVector<int64_t> shape,
1219 if (getEffectiveOrderAsInt() == other.getEffectiveOrderAsInt()) {
1222 if (getEffectiveSgLayoutAsInt() == other.getEffectiveSgLayoutAsInt() &&
1223 getEffectiveSgDataAsInt() == other.getEffectiveSgDataAsInt())
1226 if (getEffectiveLaneLayoutAsInt() ==
1227 other.getEffectiveLaneLayoutAsInt() &&
1228 getEffectiveLaneDataAsInt() == other.getEffectiveLaneDataAsInt())
1232 auto compareCoordsForAllIds = [&](int64_t size) {
1236 auto flattenedThis = flatten();
1237 auto parent = dyn_cast<LayoutAttr>(flattenedThis.getParent());
1239 int64_t wgSize =
computeProduct(parent.getEffectiveSgLayoutAsInt());
1240 return compareCoordsForAllIds(wgSize);
1243 return (getEffectiveInstDataAsInt() == other.getEffectiveInstDataAsInt());
1246 int64_t subgroupSize =
computeProduct(parent.getEffectiveLaneLayoutAsInt());
1247 return compareCoordsForAllIds(subgroupSize);
1252xegpu::SliceAttr SliceAttr::dropSliceDims(ArrayRef<int64_t> sliceDimsToDrop) {
1253 if (sliceDimsToDrop.empty())
1255 SmallVector<int64_t> sliceDims{
getDims().asArrayRef()};
1256 for (
auto dim : sliceDimsToDrop) {
1257 auto foundIt = std::find(sliceDims.begin(), sliceDims.end(), dim);
1258 assert(foundIt != sliceDims.end() &&
1259 "Expected to find the specified reduction dim in slice dims");
1260 sliceDims.erase(foundIt);
1263 auto sliceWithoutDims = xegpu::SliceAttr::get(
1267 return sliceWithoutDims;
1275static SmallVector<int64_t>
1283 std::max(maxDim, *std::max_element(sliceDims.begin(), sliceDims.end()));
1285 std::max(maxDim, *std::max_element(dimsToMap.begin(), dimsToMap.end()));
1286 int64_t parentSpaceRank = maxDim + sliceDims.size() + 1;
1290 llvm::SmallDenseSet<int64_t> slicedDimsSet(sliceDims.begin(),
1293 for (
int64_t i = 0; i < parentSpaceRank; ++i) {
1294 if (!slicedDimsSet.contains(i))
1295 remainingDims.push_back(i);
1300 for (
auto dim : dimsToMap) {
1301 int64_t mappedDim = remainingDims[dim];
1302 adjustUnitDims.push_back(mappedDim);
1305 return adjustUnitDims;
1311 DistributeLayoutAttr parentLayout = getParent();
1319 parentLayout.setUnitDimData(adjustUnitDims), getDims());
1324SliceAttr::setUnitDimLayout(SmallVector<int64_t> unitDims)
const {
1325 DistributeLayoutAttr parentLayout = getParent();
1327 ArrayRef<int64_t> sliceDims = getDims().asArrayRef();
1329 SmallVector<int64_t> adjustUnitDims =
1332 return SliceAttr::get(
1333 getContext(), parentLayout.setUnitDimLayout(adjustUnitDims), getDims());
1338DistributeLayoutAttr SliceAttr::setDimData(int64_t dim, int64_t sgData,
1339 int64_t instData, int64_t laneData) {
1340 ArrayRef<int64_t> sliceDims =
getDims().asArrayRef();
1341 auto parent = getParent();
1343 SmallVector<int64_t> dimSet;
1344 dimSet.push_back(dim);
1345 SmallVector<int64_t> adjustDims =
1347 return SliceAttr::get(
1349 parent.setDimData(adjustDims[0], sgData, instData, laneData),
getDims());
1370DistributeLayoutAttr SliceAttr::dropDims(SmallVector<int64_t> dimGroup) {
1372 SmallVector<int64_t> sliceDims = llvm::to_vector(
getDims().asArrayRef());
1373 SmallVector<int64_t> dimsInParentSpace =
1376 auto droppedParent = getParent().dropDims(dimsInParentSpace);
1381 SmallVector<int64_t> newSliceDims;
1382 for (int64_t d : sliceDims) {
1384 llvm::count_if(dimsInParentSpace, [&](int64_t s) {
return s < d; });
1385 newSliceDims.push_back(d - offset);
1388 return SliceAttr::get(
getContext(), droppedParent,
1395DistributeLayoutAttr SliceAttr::collapseDims(SmallVector<int64_t> dimGroup) {
1398 SmallVector<int64_t> sliceDims = llvm::to_vector(
getDims().asArrayRef());
1399 assert(
"expect sliceDims not being collapsed" &&
1400 llvm::none_of(dimGroup, [&](int64_t dim) {
1401 return llvm::is_contained(sliceDims, dim);
1403 SmallVector<int64_t> dimsInParentSpace =
1406 auto collapsedParent = getParent().collapseDims(dimsInParentSpace);
1407 return SliceAttr::get(
getContext(), collapsedParent,
1415DistributeLayoutAttr SliceAttr::expandDim(int64_t dim,
1416 ArrayRef<int64_t> targetShape) {
1420 ArrayRef<int64_t> sliceDims =
getDims().asArrayRef();
1421 SmallVector<int64_t> dimSet = {dim};
1422 SmallVector<int64_t> dimsInParentSpace =
1424 int64_t parentDim = dimsInParentSpace[0];
1426 auto expandedParent = getParent().expandDim(parentDim, targetShape);
1428 int64_t shift =
static_cast<int64_t
>(targetShape.size()) - 1;
1429 SmallVector<int64_t> newSliceDims;
1430 newSliceDims.reserve(sliceDims.size());
1431 for (int64_t s : sliceDims)
1432 newSliceDims.push_back(s > parentDim ? s + shift : s);
1434 return SliceAttr::get(
getContext(), expandedParent,
1441 llvm::sort(sortedSliceDims);
1443 for (
size_t i = 1; i < sortedSliceDims.size(); ++i) {
1444 assert((sortedSliceDims[i] == sortedSliceDims[i - 1] + 1) &&
1445 "slice dims non consecutive, cannot be transposed");
1449 if (sortedSliceDims.front() == 0) {
1452 for (
int64_t dim : permutation)
1453 permForParent.push_back(dim + sortedSliceDims.size());
1454 for (
int64_t i = sortedSliceDims.size() - 1; i >= 0; --i)
1455 permForParent.push_back(i);
1459 for (
int64_t i = sortedSliceDims.size() - 1; i >= 0; --i)
1460 permForParent.push_back(i + permutation.size());
1461 for (
int64_t dim : permutation)
1462 permForParent.push_back(dim);
1464 return permForParent;
1470 DistributeLayoutAttr parent = getParent();
1473 auto transposedParent = parent.transposeDims(permForParent);
1474 return SliceAttr::get(
getContext(), transposedParent,
1479bool SliceAttr::isTransposeOf(
const xegpu::DistributeLayoutAttr &other,
1480 ArrayRef<int64_t> perm,
1483 auto otherSlice = dyn_cast<xegpu::SliceAttr>(other);
1484 if (!otherSlice || getDims() != otherSlice.getDims())
1487 SmallVector<int64_t> sliceDims = llvm::to_vector(getDims().asArrayRef());
1488 DistributeLayoutAttr parent = getParent();
1490 auto otherParent = otherSlice.getParent();
1491 return parent.isTransposeOf(otherParent, permForParent, kind);
1499RangeAttr::verify(llvm::function_ref<mlir::InFlightDiagnostic()>
emitError,
1500 IntegerAttr startOfRange, IntegerAttr endOfRange) {
1501 if (startOfRange.getInt() >= endOfRange.getInt())
1502 return emitError() <<
"'end' : " << endOfRange.getInt()
1503 <<
" must be greater than 'start' : "
1504 << startOfRange.getInt();
1513mlir::Type TensorDescType::parse(AsmParser &parser) {
1514 llvm::SmallVector<int64_t> shape;
1515 mlir::Type elementType;
1516 mlir::FailureOr<mlir::Attribute> encoding;
1517 mlir::FailureOr<mlir::Attribute> layout;
1520 if (parser.parseLess())
1523 auto shapeLoc = parser.getCurrentLocation();
1524 if (mlir::failed(parser.parseDimensionList(shape))) {
1525 parser.emitError(shapeLoc,
"failed to parse parameter 'shape'");
1529 auto elemTypeLoc = parser.getCurrentLocation();
1530 if (mlir::failed(parser.parseType(elementType))) {
1531 parser.emitError(elemTypeLoc,
"failed to parse parameter 'elementType'");
1536 while (mlir::succeeded(parser.parseOptionalComma())) {
1537 mlir::Attribute attr;
1538 ParseResult res = parser.parseAttribute(attr);
1539 if (mlir::succeeded(res)) {
1540 if (mlir::isa<DistributeLayoutAttr>(attr)) {
1544 if (mlir::isa<BlockTensorDescAttr>(attr)) {
1553 if (parser.parseGreater())
1556 MLIRContext *ctxt = parser.getContext();
1557 return TensorDescType::getChecked(
1558 [&]() {
return parser.emitError(parser.getNameLoc()); }, ctxt, shape,
1559 elementType, encoding.value_or(BlockTensorDescAttr::get(ctxt)),
1560 layout.value_or(mlir::Attribute()));
1563void TensorDescType::print(AsmPrinter &printer)
const {
1567 for (int64_t dim : shape) {
1568 if (mlir::ShapedType::isDynamic(dim))
1577 auto encoding = getEncoding();
1578 auto blockAttr = llvm::dyn_cast_if_present<BlockTensorDescAttr>(encoding);
1579 if (encoding && (!blockAttr || !blockAttr.hasDefaultsOnly()))
1580 printer <<
", " << encoding;
1582 if (
auto layout = getLayout())
1583 printer <<
", " << layout;
1588TensorDescType TensorDescType::get(llvm::ArrayRef<int64_t> shape,
1589 mlir::Type elementType,
int array_length,
1590 bool boundary_check,
1591 MemorySpace memory_space,
1592 mlir::Attribute layout) {
1594 auto attr = BlockTensorDescAttr::get(context, memory_space, array_length,
1596 return Base::get(context, shape, elementType, attr, layout);
1600TensorDescType::verify(llvm::function_ref<InFlightDiagnostic()>
emitError,
1601 llvm::ArrayRef<int64_t> shape, mlir::Type elementType,
1602 mlir::Attribute encoding, mlir::Attribute layout) {
1603 size_t rank = shape.size();
1606 return emitError() <<
"expected non-zero rank tensor";
1608 auto blockAttr = mlir::dyn_cast_if_present<BlockTensorDescAttr>(encoding);
1610 MemorySpaceAttr memorySpaceAttr = blockAttr.getMemorySpace();
1611 if (rank > 1 && memorySpaceAttr &&
1612 memorySpaceAttr.getValue() == MemorySpace::SLM)
1613 return emitError() <<
"SLM is only supported for 1D block tensor";
1617 return emitError() <<
"unsupported element type " << elementType
1618 <<
": expected integer or float";
1620 if (
auto layoutAttr =
1621 mlir::dyn_cast_if_present<DistributeLayoutAttr>(layout)) {
1622 if (rank != (
size_t)layoutAttr.getRank())
1623 return emitError() <<
"expected layout rank to match tensor rank";
1625 if (!layoutAttr.isDistributable(SmallVector<int64_t>(shape))) {
1626 std::string shapeStr;
1627 llvm::raw_string_ostream stream(shapeStr);
1628 llvm::interleaveComma(shape, stream);
1629 return emitError() <<
"cannot distribute [" << shapeStr <<
"] using "
1640mlir::Type MemDescType::parse(AsmParser &parser) {
1641 llvm::SmallVector<int64_t> shape;
1642 mlir::Type elementType;
1643 mlir::FailureOr<MemLayoutAttr> layout;
1646 if (parser.parseLess())
1649 auto shapeLoc = parser.getCurrentLocation();
1650 if (mlir::failed(parser.parseDimensionList(shape,
false,
true))) {
1651 parser.emitError(shapeLoc,
"failed to parse parameter 'shape'");
1655 auto elemTypeLoc = parser.getCurrentLocation();
1656 if (mlir::failed(parser.parseType(elementType))) {
1657 parser.emitError(elemTypeLoc,
"failed to parse parameter 'elementType'");
1662 if (mlir::succeeded(parser.parseOptionalComma())) {
1664 ParseResult res = parser.parseAttribute(attr);
1665 if (mlir::failed(res))
1671 if (parser.parseGreater())
1675 return MemDescType::getChecked(
1676 [&]() {
return parser.emitError(parser.getNameLoc()); }, ctxt, shape,
1677 elementType, layout.value_or(MemLayoutAttr()));
1680void MemDescType::print(AsmPrinter &printer)
const {
1683 printer.printDimensionList(
getShape());
1687 if (
auto layout = getMemLayout())
1688 printer <<
", " << layout;
1697Attribute MemLayoutAttr::parse(AsmParser &parser, Type type) {
1699 auto *context = parser.getContext();
1700 llvm::SMLoc loc = parser.getCurrentLocation();
1702 llvm::SmallDenseSet<StringRef> seenKeys;
1703 SmallVector<NamedAttribute> attributes;
1705 auto parseElt = [&]() -> ParseResult {
1707 if (
failed(parser.parseKeyword(&nameId)))
1708 return parser.emitError(loc,
"expected valid attribute name");
1710 if (!seenKeys.insert(nameId).second)
1711 return parser.emitError(loc,
"duplicate key '")
1712 << nameId <<
" in mem layout attribute";
1714 if (
failed(parser.parseEqual()))
1718 if (
failed(parser.parseAttribute(attr)))
1720 attributes.emplace_back(nameId, attr);
1725 if (parser.parseLess())
1728 if (
failed(parser.parseCommaSeparatedList(parseElt)))
1732 if (parser.parseGreater())
1735 return parser.getChecked<MemLayoutAttr>(
1736 loc, context, DictionaryAttr::get(context, attributes));
1739void MemLayoutAttr::print(AsmPrinter &printer)
const {
1741 ArrayRef<NamedAttribute> attrs = getAttrs().getValue();
1742 for (
size_t i = 0; i < attrs.size(); i++) {
1743 printer << attrs[i].getName().str() <<
" = " << attrs[i].getValue();
1744 if (i < attrs.size() - 1)
1753template <
typename ArithOp>
1758 return ArithOp::create(builder, loc, aVal, bVal).getResult();
1763 genBinOp<arith::DivSIOp>(a, builder.getIndexAttr(b), loc, builder)
1767 genBinOp<arith::RemSIOp>(a, builder.getIndexAttr(b), loc, builder)
1771 genBinOp<arith::MulIOp>(a, builder.getIndexAttr(b), loc, builder)
1774#define add(a, b) genBinOp<arith::AddIOp>(a, b, loc, builder)
1783 assert(offsets.size() == blockShape.size() &&
1784 "offsets and blockShape must have the same size");
1788 for (
auto [offset, block] : llvm::zip(offsets, blockShape)) {
1789 divs.push_back(
div(offset, block));
1790 rems.push_back(
rem(offset, block));
1792 blockedOffsets.append(divs.begin(), divs.end());
1793 blockedOffsets.append(rems.begin(), rems.end());
1795 return blockedOffsets;
1805 for (
Attribute attr : strideAttr.getValue()) {
1806 strides.push_back(cast<IntegerAttr>(attr).getInt());
1809 SmallVector<int64_t> innerBlkShape = getBlockShape();
1813 SmallVector<int, 4> perm =
1814 llvm::to_vector<4>(llvm::seq<int>(0, strides.size()));
1815 llvm::sort(perm, [&](
int a,
int b) {
return strides[a] < strides[
b]; });
1817 assert(strides[perm[0]] == 1 &&
"inner most dim must have stride 1");
1819 SmallVector<int64_t> innerBlkStride(innerBlkShape.size());
1820 innerBlkStride[perm[0]] = 1;
1821 for (
size_t i = 1; i < perm.size(); ++i)
1822 innerBlkStride[perm[i]] =
1823 innerBlkStride[perm[i - 1]] * innerBlkShape[perm[i - 1]];
1829 SmallVector<int64_t> matrixShapeOrig(matrixShape.size());
1830 SmallVector<int64_t> BlkShapeOrig(matrixShape.size());
1831 for (
size_t i = 0; i < perm.size() - 1; ++i) {
1832 matrixShapeOrig[perm[i]] = strides[perm[i + 1]] / strides[perm[i]];
1833 BlkShapeOrig[perm[i]] = matrixShapeOrig[perm[i]] / innerBlkShape[perm[i]];
1836 int64_t innerBlkSize = 1;
1837 for (
auto s : innerBlkShape)
1840 SmallVector<int64_t> outerBlkStride(matrixShape.size());
1841 outerBlkStride[perm[0]] = innerBlkSize;
1842 for (
size_t i = 0; i < perm.size() - 1; ++i) {
1843 outerBlkStride[perm[i + 1]] =
1844 outerBlkStride[perm[i]] * BlkShapeOrig[perm[i]];
1848 SmallVector<int64_t> blockedStrides;
1849 blockedStrides.append(outerBlkStride.begin(), outerBlkStride.end());
1850 blockedStrides.append(innerBlkStride.begin(), innerBlkStride.end());
1852 return blockedStrides;
1856Value MemDescType::getLinearOffsets(OpBuilder &builder, Location loc,
1857 ArrayRef<OpFoldResult> offsets) {
1860 SmallVector<int64_t> blockShape = getBlockShape();
1861 SmallVector<int64_t> strides = getStrideShape();
1862 SmallVector<OpFoldResult> blockedOffsets;
1865 if (llvm::equal(blockShape, matrixShape)) {
1867 strides.erase(strides.begin(), strides.begin() + matrixShape.size());
1869 assert(offsets.size() == blockShape.size() &&
1870 "offsets and blockShape must have the same size");
1874 SmallVector<OpFoldResult> divs, rems;
1876 for (
auto [offset, block] : llvm::zip(offsets, blockShape)) {
1877 divs.push_back(
div(offset, block));
1878 rems.push_back(
rem(offset, block));
1880 blockedOffsets.append(divs.begin(), divs.end());
1881 blockedOffsets.append(rems.begin(), rems.end());
1882 offsets = blockedOffsets;
1887 for (
size_t i = 0; i < offsets.size(); ++i) {
1888 OpFoldResult mulResult =
mul(offsets[i], strides[i]);
1890 linearOffset = arith::AddIOp::create(builder, loc, mulVal, linearOffset);
1893 return linearOffset;
1899#include <mlir/Dialect/XeGPU/IR/XeGPUDialect.cpp.inc>
1900#define GET_ATTRDEF_CLASSES
1901#include <mlir/Dialect/XeGPU/IR/XeGPUAttrs.cpp.inc>
1902#define GET_TYPEDEF_CLASSES
1903#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.
Attributes are known-constant values of operations.
MLIRContext * getContext() const
Return the context this attribute belongs to.
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)
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 bool compareDistributedCoords(xegpu::DistributeLayoutAttr self, const xegpu::DistributeLayoutAttr &other, ArrayRef< int64_t > shape, xegpu::LayoutKind level, int64_t size)
Returns true if self and other distribute shape identically at level: every id in [0,...
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)
static SmallVector< SmallVector< int64_t > > expandBlockCoords(ArrayRef< SmallVector< int64_t > > blockStarts, ArrayRef< int64_t > subShape)
Expands per-distribution-unit block-start coordinates into the full list of element coordinates each ...
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.
AffineMap inversePermutation(AffineMap map)
Returns a map of codomain to domain dimensions such that the first codomain dimension for a particula...
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.
SmallVector< int64_t > invertPermutationVector(ArrayRef< int64_t > permutation)
Helper method to apply to inverse a permutation.