16#include "llvm/ADT/SmallVectorExtras.h"
17#include "llvm/ADT/TypeSwitch.h"
18#include "llvm/Support/Debug.h"
25void XeGPUDialect::initialize() {
27#define GET_TYPEDEF_LIST
28#include <mlir/Dialect/XeGPU/IR/XeGPUTypes.cpp.inc>
32#include <mlir/Dialect/XeGPU/IR/XeGPU.cpp.inc>
35#define GET_ATTRDEF_LIST
36#include <mlir/Dialect/XeGPU/IR/XeGPUAttrs.cpp.inc>
39#define GET_OP_INTERFACE_CLASSES
40#include "mlir/Dialect/XeGPU/IR/XeGPUOpInterface.cpp.inc"
59 llvm::zip_equal(srcShape,
61 [](
const auto &t) {
return std::min(std::get<0>(t), std::get<1>(t)); });
65 llvm::zip(delinearizedId, subShape), [&](
const auto &t) ->
Value {
81 llvm::map_to_vector(llvm::zip_equal(base, distUnitLocalOffset),
82 [&](
const auto &t) ->
Value {
84 loc, std::get<0>(t), std::get<1>(t));
88 llvm::zip_equal(adds, srcShape), [&](
const auto &t) ->
Value {
94 coordinates.push_back(mods);
104 for (
size_t i = 0; i <
shape.size(); ++i)
105 distUnitShape[i] = std::min(
shape[i], layout[i] * subShape[i]);
109 for (
size_t i = 0; i <
shape.size(); ++i)
110 localOffset[i] = canonicalIds[i] * subShape[i];
117 for (
size_t i = 0; i <
shape.size(); ++i)
118 coord[i] = (unitOffs[i] + localOffset[i]) %
shape[i];
119 coordinates.push_back(coord);
128 xegpu::MemorySpace memory_space,
130 bool boundary_check) {
131 auto scopeAttr = MemorySpaceAttr::get(context, memory_space);
133 IntegerAttr::get(IntegerType::get(context, 64), array_length);
135 return Base::get(context, scopeAttr, lengthAttr, boundaryAttr);
138bool BlockTensorDescAttr::hasDefaultsOnly() {
139 return getMemorySpace().getValue() == xegpu::MemorySpace::Global &&
140 getArrayLength().getInt() == 1 && getBoundaryCheck().getValue();
147LayoutAttr::verify(llvm::function_ref<mlir::InFlightDiagnostic()>
emitError,
153 if (!sg_layout && !inst_data && !lane_layout)
159 if (sg_layout && inst_data && sg_layout.size() != inst_data.size()) {
161 <<
"expected sg_layout and inst_data to have the same rank";
164 if (sg_layout && lane_layout && sg_layout.size() != lane_layout.size()) {
166 <<
"expected sg_layout and lane_layout to have the same rank";
169 if (inst_data && lane_layout && inst_data.size() != lane_layout.size()) {
170 return emitError() <<
"expected inst_data and lane_layout to have the same "
171 "rank, got inst_data "
172 << inst_data.size() <<
", lane_layout "
173 << lane_layout.size();
176 if ((sg_layout && !sg_data) || (!sg_layout && sg_data))
177 return emitError() <<
"sg_layout and sg_data must be used together";
178 if (sg_layout && sg_data && sg_layout.size() != sg_data.size())
180 <<
"expected sg_data and sg_layout to have the same rank";
182 if ((lane_layout && !lane_data) || (!lane_layout && lane_data))
183 return emitError() <<
"lane_layout and lane_data must be used together";
184 if (lane_layout && lane_data && lane_layout.size() != lane_data.size())
186 <<
"expected lane_data and lane_layout to have the same rank";
189 if (!sg_layout && !lane_layout)
191 <<
"expected sg_layout/lane_layout being used with order";
193 if (sg_layout && order.size() != sg_layout.size())
195 <<
"expected order and sg_layout to have the same rank";
197 if (lane_layout && order.size() != lane_layout.size())
199 <<
"expected order and lane_layout to have the same rank";
205FailureOr<SmallVector<Value>>
206LayoutAttr::delinearizeId(OpBuilder &builder, Location loc, Value linearId) {
208 SmallVector<int64_t> sgLayoutInt;
209 if (isForWorkgroup()) {
210 sgLayoutInt = getEffectiveSgLayoutAsInt();
211 }
else if (isForSubgroup()) {
212 sgLayoutInt = getEffectiveLaneLayoutAsInt();
220 SmallVector<int64_t> order;
221 if (orderAttr && !orderAttr.empty()) {
222 order = llvm::map_to_vector(orderAttr.
asArrayRef(), [](int32_t idx) {
223 return static_cast<int64_t>(idx);
227 order = llvm::to_vector(
228 llvm::reverse(llvm::seq<int64_t>(0, sgLayoutInt.size())));
231 if (order.size() != sgLayoutInt.size()) {
235 SmallVector<Value>
result(sgLayoutInt.size());
236 Value remaining = linearId;
259 for (
size_t i = 0; i < order.size(); ++i) {
260 int64_t dimIdx = order[i];
261 int64_t dimSize = sgLayoutInt[dimIdx];
264 builder.
createOrFold<arith::ConstantIndexOp>(loc, dimSize);
271 builder.
createOrFold<arith::RemUIOp>(loc, remaining, dimSizeVal);
278 if (i < order.size() - 1) {
280 builder.
createOrFold<arith::DivUIOp>(loc, remaining, dimSizeVal);
289FailureOr<SmallVector<SmallVector<Value>>>
290LayoutAttr::computeDistributedCoords(OpBuilder &builder, Location loc,
291 Value linearId, ArrayRef<int64_t> shape) {
292 SmallVector<int64_t> layout;
293 SmallVector<int64_t> subShape;
294 if (isForWorkgroup()) {
295 layout = getEffectiveSgLayoutAsInt();
296 subShape = getEffectiveSgDataAsInt();
297 }
else if (isForSubgroup()) {
298 layout = getEffectiveLaneLayoutAsInt();
299 subShape = getEffectiveLaneDataAsInt();
303 assert(!subShape.empty() &&
"sgdata or lanedata cannot be empty for "
304 "distributed coordinates computation");
307 auto maybeIds = delinearizeId(builder, loc, linearId);
310 SmallVector<Value> ids = *maybeIds;
312 return genCoordinates(builder, loc, ids, layout, subShape, shape);
315bool LayoutAttr::isEqualTo(
const xegpu::DistributeLayoutAttr &other) {
316 if (dyn_cast<xegpu::SliceAttr>(other))
319 return *
this == dyn_cast<xegpu::LayoutAttr>(other);
325SmallVector<SmallVector<int64_t>>
326LayoutAttr::computeStaticDistributedCoords(int64_t linearId,
327 ArrayRef<int64_t> shape) {
328 SmallVector<int64_t> layoutVec;
329 SmallVector<int64_t> subShape;
330 SmallVector<int64_t> instData;
331 if (isForWorkgroup()) {
332 layoutVec = getEffectiveSgLayoutAsInt();
333 subShape = getEffectiveSgDataAsInt();
334 }
else if (isForSubgroup()) {
335 instData = getEffectiveInstDataAsInt();
336 layoutVec = getEffectiveLaneLayoutAsInt();
337 subShape = getEffectiveLaneDataAsInt();
339 if (!instData.empty()) {
343 assert(!subShape.empty() &&
"sgdata or lanedata cannot be empty");
346 SmallVector<int64_t> order = getEffectiveOrderAsInt();
347 SmallVector<int64_t> delinearizedId(layoutVec.size());
348 int64_t remaining = linearId;
349 for (
size_t i = 0; i < order.size(); ++i) {
350 int64_t dimIdx = order[i];
351 delinearizedId[dimIdx] = remaining % layoutVec[dimIdx];
352 remaining = remaining / layoutVec[dimIdx];
360LayoutAttr::setUnitDimData(SmallVector<int64_t> unitDims)
const {
361 auto sgDataOpt = getSgData();
362 auto instDataOpt = getInstData();
363 auto laneDataOpt = getLaneData();
365 SmallVector<int32_t> sgData;
366 SmallVector<int32_t> instData;
367 SmallVector<int32_t> laneData;
370 sgData = llvm::to_vector(sgDataOpt.asArrayRef());
373 instData = llvm::to_vector(instDataOpt.asArrayRef());
376 laneData = llvm::to_vector(laneDataOpt.asArrayRef());
378 for (
auto dim : unitDims) {
379 if (dim <
static_cast<int64_t
>(sgData.size()))
381 if (dim <
static_cast<int64_t
>(instData.size()))
383 if (dim <
static_cast<int64_t
>(laneData.size()))
387 return LayoutAttr::get(
401LayoutAttr::setUnitDimLayout(SmallVector<int64_t> unitDims)
const {
402 auto sgLayoutOpt = getSgLayout();
403 auto laneLayoutOpt = getLaneLayout();
405 SmallVector<int32_t> sgLayout;
406 SmallVector<int32_t> laneLayout;
409 sgLayout = llvm::to_vector(sgLayoutOpt.asArrayRef());
411 laneLayout = llvm::to_vector(laneLayoutOpt.asArrayRef());
413 for (
auto dim : unitDims) {
414 if (dim <
static_cast<int64_t
>(sgLayout.size()))
416 if (dim <
static_cast<int64_t
>(laneLayout.size()))
420 return LayoutAttr::get(
424 getSgData(), getInstData(),
427 getLaneData(), getOrder());
432DistributeLayoutAttr LayoutAttr::setDimData(int64_t dim, int64_t sgData,
436 SmallVector<int64_t> sgDataVec = getEffectiveSgDataAsInt();
437 SmallVector<int64_t> instDataVec = getEffectiveInstDataAsInt();
438 SmallVector<int64_t> laneDataVec = getEffectiveLaneDataAsInt();
440 if (dim <
static_cast<int64_t
>(sgDataVec.size()) && sgData != -1)
441 sgDataVec[dim] = sgData;
442 if (dim <
static_cast<int64_t
>(instDataVec.size()) && instData != -1)
443 instDataVec[dim] = instData;
444 if (dim <
static_cast<int64_t
>(laneDataVec.size()) && laneData != -1)
445 laneDataVec[dim] = laneData;
447 SmallVector<int32_t> sgDataVec32(sgDataVec.begin(), sgDataVec.end());
448 SmallVector<int32_t> instDataVec32(instDataVec.begin(), instDataVec.end());
449 SmallVector<int32_t> laneDataVec32(laneDataVec.begin(), laneDataVec.end());
451 return LayoutAttr::get(
466DistributeLayoutAttr LayoutAttr::dropDims(SmallVector<int64_t> dimGroup) {
468 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
469 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
470 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
471 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
472 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
473 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
475 SmallVector<int64_t> sortedDimGroup = dimGroup;
476 llvm::sort(sortedDimGroup);
478 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
479 if (!sgLayout.empty()) {
480 sgLayout.erase(sgLayout.begin() + dimIdx);
481 sgData.erase(sgData.begin() + dimIdx);
483 if (!instData.empty())
484 instData.erase(instData.begin() + dimIdx);
485 if (!laneLayout.empty()) {
486 laneLayout.erase(laneLayout.begin() + dimIdx);
487 laneData.erase(laneData.begin() + dimIdx);
491 SmallVector<int64_t> newOrder;
492 for (int64_t d : origOrder) {
493 if (llvm::is_contained(dimGroup, d))
495 int64_t offset = llvm::count_if(dimGroup, [&](int64_t s) {
return s < d; });
496 newOrder.push_back(d - offset);
498 if ((sgLayout.empty() && laneLayout.empty()) || newOrder.size() == 1)
504 SmallVector<int32_t> v32(v.begin(), v.end());
507 auto droppedLayout = xegpu::LayoutAttr::get(
508 getContext(), toAttr(sgLayout), toAttr(sgData), toAttr(instData),
509 toAttr(laneLayout), toAttr(laneData), toAttr(newOrder));
510 return droppedLayout;
516DistributeLayoutAttr LayoutAttr::collapseDims(SmallVector<int64_t> dimGroup) {
518 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
519 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
520 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
521 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
522 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
523 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
525 SmallVector<int64_t> sortedDimGroup = dimGroup;
526 llvm::sort(sortedDimGroup);
527 int64_t dimBeforeCurrent = -1;
528 for (
auto dimIdx : sortedDimGroup) {
532 if (dimBeforeCurrent >= 0) {
533 if (getOrder() && !getOrder().empty()) {
534 int64_t orderBefore = origOrder[dimBeforeCurrent];
535 int64_t orderCurrent = origOrder[dimIdx];
536 if (orderBefore != (orderCurrent - 1))
537 llvm::report_fatal_error(
538 "dimensions being collapsed must be adjacent in order");
540 if (dimIdx != (dimBeforeCurrent + 1))
541 llvm::report_fatal_error(
542 "dimensions being collapsed must be adjacent");
545 dimBeforeCurrent = dimIdx;
548 int firstDim = sortedDimGroup.front();
553 if (!sgLayout.empty()) {
554 int64_t collapsedSglayout = 1, collapsedSgData = 1;
555 for (
auto dimIdx : dimGroup) {
556 collapsedSglayout *= sgLayout[dimIdx];
557 collapsedSgData *= sgData[dimIdx];
559 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
560 sgLayout.erase(sgLayout.begin() + dimIdx, sgLayout.begin() + dimIdx + 1);
561 sgData.erase(sgData.begin() + dimIdx, sgData.begin() + dimIdx + 1);
563 sgLayout.insert(sgLayout.begin() + firstDim, collapsedSglayout);
564 sgData.insert(sgData.begin() + firstDim, collapsedSgData);
567 if (!instData.empty()) {
568 int64_t collapsedInstData = 1;
569 for (
auto dimIdx : dimGroup)
570 collapsedInstData *= instData[dimIdx];
571 for (
auto dimIdx : llvm::reverse(sortedDimGroup))
572 instData.erase(instData.begin() + dimIdx, instData.begin() + dimIdx + 1);
573 instData.insert(instData.begin() + firstDim, collapsedInstData);
576 if (!laneLayout.empty()) {
577 int64_t collapsedLaneLayout = 1, collapsedLaneData = 1;
578 for (
auto dimIdx : dimGroup) {
579 collapsedLaneLayout *= laneLayout[dimIdx];
580 collapsedLaneData *= laneData[dimIdx];
582 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
583 laneLayout.erase(laneLayout.begin() + dimIdx,
584 laneLayout.begin() + dimIdx + 1);
585 laneData.erase(laneData.begin() + dimIdx, laneData.begin() + dimIdx + 1);
587 laneLayout.insert(laneLayout.begin() + firstDim, collapsedLaneLayout);
588 laneData.insert(laneData.begin() + firstDim, collapsedLaneData);
591 SmallVector<int64_t> newOrder;
593 if (orderAttr && !orderAttr.empty()) {
595 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
596 if (dimIdx != firstDim)
597 origOrder.erase(origOrder.begin() + dimIdx);
602 llvm::to_vector(llvm::seq<size_t>(0, orderAttr.size()));
606 [&](
size_t a,
size_t b) {
return origOrder[a] < origOrder[
b]; });
608 newOrder = llvm::to_vector(llvm::map_range(
609 indices, [&](
size_t i) {
return static_cast<int64_t
>(i); }));
615 SmallVector<int32_t> v32(v.begin(), v.end());
618 auto collapsedLayout = xegpu::LayoutAttr::get(
619 getContext(), toAttr(sgLayout), toAttr(sgData), toAttr(instData),
620 toAttr(laneLayout), toAttr(laneData), toAttr(newOrder));
621 return collapsedLayout;
625DistributeLayoutAttr LayoutAttr::transposeDims(ArrayRef<int64_t> permutation) {
627 SmallVector<int64_t> origSgLayout = getEffectiveSgLayoutAsInt();
628 SmallVector<int64_t> origSgData = getEffectiveSgDataAsInt();
629 SmallVector<int64_t> origInstData = getEffectiveInstDataAsInt();
630 SmallVector<int64_t> origLaneLayout = getEffectiveLaneLayoutAsInt();
631 SmallVector<int64_t> origLaneData = getEffectiveLaneDataAsInt();
632 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
634 SmallVector<int32_t> sgLayout;
635 SmallVector<int32_t> sgData;
636 SmallVector<int32_t> instData;
637 SmallVector<int32_t> laneLayout;
638 SmallVector<int32_t> laneData;
639 SmallVector<int32_t> order;
641 for (int64_t idx : permutation) {
642 if (!origLaneLayout.empty()) {
643 laneLayout.push_back(
static_cast<int32_t
>(origLaneLayout[idx]));
644 laneData.push_back(
static_cast<int32_t
>(origLaneData[idx]));
646 if (!origInstData.empty())
647 instData.push_back(
static_cast<int32_t
>(origInstData[idx]));
648 if (!origSgLayout.empty()) {
649 sgLayout.push_back(
static_cast<int32_t
>(origSgLayout[idx]));
650 sgData.push_back(
static_cast<int32_t
>(origSgData[idx]));
652 order.push_back(
static_cast<int32_t
>(origOrder[idx]));
654 if (origLaneLayout.empty() && origSgLayout.empty())
660 return xegpu::LayoutAttr::get(
getContext(), toAttr(sgLayout), toAttr(sgData),
661 toAttr(instData), toAttr(laneLayout),
662 toAttr(laneData), toAttr(order));
666bool LayoutAttr::isTransposeOf(
const xegpu::DistributeLayoutAttr &other,
667 ArrayRef<int64_t> perm,
671 if (getRank() != other.getRank() ||
672 perm.size() !=
static_cast<size_t>(getRank()))
676 auto checkTranspose = [](ArrayRef<int64_t> dst, ArrayRef<int64_t> src,
677 ArrayRef<int64_t> perm) {
678 for (
const auto &ta : llvm::enumerate(perm)) {
679 if (src[ta.index()] != dst[ta.value()])
685 return checkTranspose(getEffectiveSgLayoutAsInt(),
686 other.getEffectiveSgLayoutAsInt(), perm) &&
687 checkTranspose(getEffectiveSgDataAsInt(),
688 other.getEffectiveSgDataAsInt(), perm) &&
689 checkTranspose(getEffectiveOrderAsInt(),
690 other.getEffectiveOrderAsInt(), perm);
692 return checkTranspose(getEffectiveInstDataAsInt(),
693 other.getEffectiveInstDataAsInt(), perm);
695 return checkTranspose(getEffectiveLaneLayoutAsInt(),
696 other.getEffectiveLaneLayoutAsInt(), perm) &&
697 checkTranspose(getEffectiveLaneDataAsInt(),
698 other.getEffectiveLaneDataAsInt(), perm) &&
699 checkTranspose(getEffectiveOrderAsInt(),
700 other.getEffectiveOrderAsInt(), perm);
705bool LayoutAttr::isCompatibleWith(
const xegpu::DistributeLayoutAttr &other,
706 SmallVector<int64_t> shape,
710 if (getEffectiveOrderAsInt() == other.getEffectiveOrderAsInt()) {
713 if (getEffectiveSgLayoutAsInt() == other.getEffectiveSgLayoutAsInt() &&
714 getEffectiveSgDataAsInt() == other.getEffectiveSgDataAsInt())
717 if (getEffectiveLaneLayoutAsInt() ==
718 other.getEffectiveLaneLayoutAsInt() &&
719 getEffectiveLaneDataAsInt() == other.getEffectiveLaneDataAsInt())
723 auto compareCoordsForAllIds = [&](int64_t size) {
724 for (int64_t
id : llvm::seq<int64_t>(0, size)) {
725 auto coords = computeStaticDistributedCoords(
id, shape);
726 auto otherCoords = other.computeStaticDistributedCoords(
id, shape);
727 if (coords != otherCoords)
735 return compareCoordsForAllIds(wgSize);
738 return (getEffectiveInstDataAsInt() == other.getEffectiveInstDataAsInt());
741 int64_t subgroupSize =
computeProduct(getEffectiveLaneLayoutAsInt());
742 return compareCoordsForAllIds(subgroupSize);
751SliceAttr::verify(llvm::function_ref<InFlightDiagnostic()>
emitError,
755 return emitError() <<
"expected dims attribute";
758 llvm::SmallDenseSet<int64_t> seen;
761 return emitError() <<
"invalid dim (" << dim <<
") in slice attribute.";
762 if (!seen.insert(dim).second)
763 return emitError() <<
"repeated dim (" << dim <<
") in slice attribute.";
768SliceAttr SliceAttr::flatten()
const {
769 xegpu::DistributeLayoutAttr parent = getParent();
770 SmallVector<DenseI64ArrayAttr> slicedDims({
getDims()});
772 while (
auto sliceAttr = dyn_cast<xegpu::SliceAttr>(parent)) {
773 parent = sliceAttr.getParent();
774 slicedDims.push_back(sliceAttr.getDims());
777 auto layoutAttr = dyn_cast<xegpu::LayoutAttr>(parent);
779 llvm::to_vector(llvm::seq<int64_t>(0, layoutAttr.getRank()));
782 SmallVector<int64_t> remainingDims(
indices);
783 for (
auto dim : llvm::reverse(slicedDims))
784 remainingDims = XeGPUDialect::slice(llvm::ArrayRef<int64_t>(remainingDims),
788 SmallVector<int64_t> flattendDims = XeGPUDialect::slice(
789 llvm::ArrayRef<int64_t>(
indices), llvm::ArrayRef<int64_t>(remainingDims));
791 return xegpu::SliceAttr::get(
796FailureOr<SmallVector<Value>>
797SliceAttr::delinearizeId(OpBuilder &builder, Location loc, Value linearId) {
798 SliceAttr attr = flatten();
799 auto parent = dyn_cast<LayoutAttr>(attr.getParent());
800 return parent.delinearizeId(builder, loc, linearId);
806FailureOr<SmallVector<SmallVector<Value>>>
807SliceAttr::computeDistributedCoords(OpBuilder &builder, Location loc,
808 Value linearId, ArrayRef<int64_t> shape) {
809 assert(getRank() ==
static_cast<int64_t
>(shape.size()) &&
"invalid shape.");
811 SmallVector<int64_t> layout;
812 SmallVector<int64_t> subShape;
813 if (isForWorkgroup()) {
814 layout = getEffectiveSgLayoutAsInt();
815 subShape = getEffectiveSgDataAsInt();
816 }
else if (isForSubgroup()) {
817 layout = getEffectiveLaneLayoutAsInt();
818 subShape = getEffectiveLaneDataAsInt();
823 if (subShape.empty())
827 auto maybeIds = delinearizeId(builder, loc, linearId);
833 ArrayRef<int64_t> dims = flatten().getDims().
asArrayRef();
834 SmallVector<Value> canonicalIds =
835 XeGPUDialect::slice(ArrayRef<Value>(*maybeIds), dims);
837 return genCoordinates(builder, loc, canonicalIds, layout, subShape, shape);
844SmallVector<SmallVector<int64_t>>
845SliceAttr::computeStaticDistributedCoords(int64_t linearId,
846 ArrayRef<int64_t> shape) {
847 assert(getRank() ==
static_cast<int64_t
>(shape.size()) &&
"invalid shape.");
849 SmallVector<int64_t> layout;
850 SmallVector<int64_t> subShape;
851 SmallVector<int64_t> instData;
852 if (isForWorkgroup()) {
853 layout = getEffectiveSgLayoutAsInt();
854 subShape = getEffectiveSgDataAsInt();
855 }
else if (isForSubgroup()) {
856 instData = getEffectiveInstDataAsInt();
857 layout = getEffectiveLaneLayoutAsInt();
858 subShape = getEffectiveLaneDataAsInt();
860 if (!instData.empty()) {
865 assert(!subShape.empty() &&
"sgdata or lanedata cannot be empty");
868 SliceAttr flattened = flatten();
869 auto parent = dyn_cast<LayoutAttr>(flattened.getParent());
870 SmallVector<int64_t> parentLayoutVec;
871 if (parent.isForWorkgroup())
872 parentLayoutVec = parent.getEffectiveSgLayoutAsInt();
874 parentLayoutVec = parent.getEffectiveLaneLayoutAsInt();
876 SmallVector<int64_t> order = parent.getEffectiveOrderAsInt();
877 SmallVector<int64_t> allIds(parentLayoutVec.size());
878 int64_t remaining = linearId;
879 for (
size_t i = 0; i < order.size(); ++i) {
880 int64_t dimIdx = order[i];
881 allIds[dimIdx] = remaining % parentLayoutVec[dimIdx];
882 if (i < order.size() - 1)
883 remaining = remaining / parentLayoutVec[dimIdx];
888 ArrayRef<int64_t> dims = flattened.getDims().asArrayRef();
889 SmallVector<int64_t> canonicalIds =
890 XeGPUDialect::slice(ArrayRef<int64_t>(allIds), dims);
895bool SliceAttr::isSliceOf(
const xegpu::DistributeLayoutAttr &other) {
896 auto flattenedThis = flatten();
899 if (
auto otherLayout = dyn_cast<xegpu::LayoutAttr>(other))
900 return flattenedThis.getParent() == otherLayout;
902 auto flattenedOther = dyn_cast<xegpu::SliceAttr>(other).flatten();
904 if (flattenedThis.getParent() != flattenedOther.getParent())
908 llvm::SmallDenseSet<int64_t> thisDims(
909 flattenedThis.getDims().asArrayRef().begin(),
910 flattenedThis.getDims().asArrayRef().end());
911 return llvm::all_of(flattenedOther.getDims().asArrayRef(),
912 [&](int64_t dim) { return thisDims.contains(dim); });
915bool SliceAttr::isEqualTo(
const xegpu::DistributeLayoutAttr &other) {
916 if (dyn_cast<xegpu::LayoutAttr>(other))
919 auto flattenedThis = flatten();
920 auto flattenedOther = dyn_cast<xegpu::SliceAttr>(other).flatten();
922 return ((flattenedThis.getParent() == flattenedOther.getParent()) &&
923 (flattenedThis.getDims() == flattenedOther.getDims()));
926bool SliceAttr::isCompatibleWith(
const xegpu::DistributeLayoutAttr &other,
927 SmallVector<int64_t> shape,
931 if (getEffectiveOrderAsInt() == other.getEffectiveOrderAsInt()) {
934 if (getEffectiveSgLayoutAsInt() == other.getEffectiveSgLayoutAsInt() &&
935 getEffectiveSgDataAsInt() == other.getEffectiveSgDataAsInt())
938 if (getEffectiveLaneLayoutAsInt() ==
939 other.getEffectiveLaneLayoutAsInt() &&
940 getEffectiveLaneDataAsInt() == other.getEffectiveLaneDataAsInt())
944 auto compareCoordsForAllIds = [&](int64_t size) {
945 for (int64_t
id : llvm::seq<int64_t>(0, size)) {
946 auto coords = computeStaticDistributedCoords(
id, shape);
947 auto otherCoords = other.computeStaticDistributedCoords(
id, shape);
948 if (coords != otherCoords)
954 auto flattenedThis = flatten();
955 auto parent = dyn_cast<LayoutAttr>(flattenedThis.getParent());
957 int64_t wgSize =
computeProduct(parent.getEffectiveSgLayoutAsInt());
958 return compareCoordsForAllIds(wgSize);
961 return (getEffectiveInstDataAsInt() == other.getEffectiveInstDataAsInt());
964 int64_t subgroupSize =
computeProduct(parent.getEffectiveLaneLayoutAsInt());
965 return compareCoordsForAllIds(subgroupSize);
970xegpu::SliceAttr SliceAttr::dropSliceDims(ArrayRef<int64_t> sliceDimsToDrop) {
971 if (sliceDimsToDrop.empty())
973 SmallVector<int64_t> sliceDims{
getDims().asArrayRef()};
974 for (
auto dim : sliceDimsToDrop) {
975 auto foundIt = std::find(sliceDims.begin(), sliceDims.end(), dim);
976 assert(foundIt != sliceDims.end() &&
977 "Expected to find the specified reduction dim in slice dims");
978 sliceDims.erase(foundIt);
981 auto sliceWithoutDims = xegpu::SliceAttr::get(
985 return sliceWithoutDims;
993static SmallVector<int64_t>
1001 std::max(maxDim, *std::max_element(sliceDims.begin(), sliceDims.end()));
1003 std::max(maxDim, *std::max_element(dimsToMap.begin(), dimsToMap.end()));
1004 int64_t parentSpaceRank = maxDim + sliceDims.size() + 1;
1008 llvm::SmallDenseSet<int64_t> slicedDimsSet(sliceDims.begin(),
1011 for (
int64_t i = 0; i < parentSpaceRank; ++i) {
1012 if (!slicedDimsSet.contains(i))
1013 remainingDims.push_back(i);
1018 for (
auto dim : dimsToMap) {
1019 int64_t mappedDim = remainingDims[dim];
1020 adjustUnitDims.push_back(mappedDim);
1023 return adjustUnitDims;
1029 DistributeLayoutAttr parentLayout = getParent();
1037 parentLayout.setUnitDimData(adjustUnitDims), getDims());
1043 DistributeLayoutAttr parentLayout = getParent();
1050 return SliceAttr::get(
1051 getContext(), parentLayout.setUnitDimLayout(adjustUnitDims), getDims());
1056DistributeLayoutAttr SliceAttr::setDimData(int64_t dim, int64_t sgData,
1057 int64_t instData, int64_t laneData) {
1058 ArrayRef<int64_t> sliceDims =
getDims().asArrayRef();
1059 auto parent = getParent();
1061 SmallVector<int64_t> dimSet;
1062 dimSet.push_back(dim);
1063 SmallVector<int64_t> adjustDims =
1065 return SliceAttr::get(
1067 parent.setDimData(adjustDims[0], sgData, instData, laneData),
getDims());
1088DistributeLayoutAttr SliceAttr::dropDims(SmallVector<int64_t> dimGroup) {
1090 SmallVector<int64_t> sliceDims = llvm::to_vector(
getDims().asArrayRef());
1091 SmallVector<int64_t> dimsInParentSpace =
1094 auto droppedParent = getParent().dropDims(dimsInParentSpace);
1099 SmallVector<int64_t> newSliceDims;
1100 for (int64_t d : sliceDims) {
1102 llvm::count_if(dimsInParentSpace, [&](int64_t s) {
return s < d; });
1103 newSliceDims.push_back(d - offset);
1106 return SliceAttr::get(
getContext(), droppedParent,
1113DistributeLayoutAttr SliceAttr::collapseDims(SmallVector<int64_t> dimGroup) {
1116 SmallVector<int64_t> sliceDims = llvm::to_vector(
getDims().asArrayRef());
1117 assert(
"expect sliceDims not being collapsed" &&
1118 llvm::none_of(dimGroup, [&](int64_t dim) {
1119 return llvm::is_contained(sliceDims, dim);
1121 SmallVector<int64_t> dimsInParentSpace =
1124 auto collapsedParent = getParent().collapseDims(dimsInParentSpace);
1125 return SliceAttr::get(
getContext(), collapsedParent,
1132 llvm::sort(sortedSliceDims);
1134 for (
size_t i = 1; i < sortedSliceDims.size(); ++i) {
1135 assert((sortedSliceDims[i] == sortedSliceDims[i - 1] + 1) &&
1136 "slice dims non consecutive, cannot be transposed");
1140 if (sortedSliceDims.front() == 0) {
1143 for (
int64_t dim : permutation)
1144 permForParent.push_back(dim + sortedSliceDims.size());
1145 for (
int64_t i = sortedSliceDims.size() - 1; i >= 0; --i)
1146 permForParent.push_back(i);
1150 for (
int64_t i = sortedSliceDims.size() - 1; i >= 0; --i)
1151 permForParent.push_back(i + permutation.size());
1152 for (
int64_t dim : permutation)
1153 permForParent.push_back(dim);
1155 return permForParent;
1161 DistributeLayoutAttr parent = getParent();
1164 auto transposedParent = parent.transposeDims(permForParent);
1165 return SliceAttr::get(
getContext(), transposedParent,
1170bool SliceAttr::isTransposeOf(
const xegpu::DistributeLayoutAttr &other,
1174 auto otherSlice = dyn_cast<xegpu::SliceAttr>(other);
1175 if (!otherSlice || getDims() != otherSlice.getDims())
1179 DistributeLayoutAttr parent = getParent();
1181 auto otherParent = otherSlice.getParent();
1182 return parent.isTransposeOf(otherParent, permForParent, kind);
1190RangeAttr::verify(llvm::function_ref<mlir::InFlightDiagnostic()>
emitError,
1191 IntegerAttr startOfRange, IntegerAttr endOfRange) {
1192 if (startOfRange.getInt() >= endOfRange.getInt())
1193 return emitError() <<
"'end' : " << endOfRange.getInt()
1194 <<
" must be greater than 'start' : "
1195 << startOfRange.getInt();
1204mlir::Type TensorDescType::parse(AsmParser &parser) {
1205 llvm::SmallVector<int64_t> shape;
1206 mlir::Type elementType;
1207 mlir::FailureOr<mlir::Attribute> encoding;
1208 mlir::FailureOr<mlir::Attribute> layout;
1216 parser.
emitError(shapeLoc,
"failed to parse parameter 'shape'");
1221 if (mlir::failed(parser.
parseType(elementType))) {
1222 parser.
emitError(elemTypeLoc,
"failed to parse parameter 'elementType'");
1228 mlir::Attribute attr;
1230 if (mlir::succeeded(res)) {
1231 if (mlir::isa<DistributeLayoutAttr>(attr)) {
1235 if (mlir::isa<BlockTensorDescAttr>(attr)) {
1248 return TensorDescType::getChecked(
1250 elementType, encoding.value_or(BlockTensorDescAttr::get(ctxt)),
1251 layout.value_or(mlir::Attribute()));
1254void TensorDescType::print(AsmPrinter &printer)
const {
1258 for (int64_t dim : shape) {
1259 if (mlir::ShapedType::isDynamic(dim))
1268 auto encoding = getEncoding();
1269 auto blockAttr = llvm::dyn_cast_if_present<BlockTensorDescAttr>(encoding);
1270 if (encoding && (!blockAttr || !blockAttr.hasDefaultsOnly()))
1271 printer <<
", " << encoding;
1273 if (
auto layout = getLayout())
1274 printer <<
", " << layout;
1279TensorDescType TensorDescType::get(llvm::ArrayRef<int64_t> shape,
1280 mlir::Type elementType,
int array_length,
1281 bool boundary_check,
1282 MemorySpace memory_space,
1283 mlir::Attribute layout) {
1285 auto attr = BlockTensorDescAttr::get(context, memory_space, array_length,
1287 return Base::get(context, shape, elementType, attr, layout);
1291TensorDescType::verify(llvm::function_ref<InFlightDiagnostic()>
emitError,
1292 llvm::ArrayRef<int64_t> shape, mlir::Type elementType,
1293 mlir::Attribute encoding, mlir::Attribute layout) {
1294 size_t rank = shape.size();
1297 return emitError() <<
"expected non-zero rank tensor";
1299 auto blockAttr = mlir::dyn_cast_if_present<BlockTensorDescAttr>(encoding);
1301 MemorySpaceAttr memorySpaceAttr = blockAttr.getMemorySpace();
1302 if (rank > 1 && memorySpaceAttr &&
1303 memorySpaceAttr.getValue() == MemorySpace::SLM)
1304 return emitError() <<
"SLM is only supported for 1D block tensor";
1308 return emitError() <<
"unsupported element type " << elementType
1309 <<
": expected integer or float";
1311 if (
auto layoutAttr =
1312 mlir::dyn_cast_if_present<DistributeLayoutAttr>(layout)) {
1313 if (rank != (
size_t)layoutAttr.getRank())
1314 return emitError() <<
"expected layout rank to match tensor rank";
1316 if (!layoutAttr.isDistributable(SmallVector<int64_t>(shape))) {
1317 std::string shapeStr;
1318 llvm::raw_string_ostream stream(shapeStr);
1319 llvm::interleaveComma(shape, stream);
1320 return emitError() <<
"cannot distribute [" << shapeStr <<
"] using "
1331mlir::Type MemDescType::parse(AsmParser &parser) {
1332 llvm::SmallVector<int64_t> shape;
1333 mlir::Type elementType;
1334 mlir::FailureOr<MemLayoutAttr> layout;
1342 parser.
emitError(shapeLoc,
"failed to parse parameter 'shape'");
1347 if (mlir::failed(parser.
parseType(elementType))) {
1348 parser.
emitError(elemTypeLoc,
"failed to parse parameter 'elementType'");
1356 if (mlir::failed(res))
1366 return MemDescType::getChecked(
1368 elementType, layout.value_or(MemLayoutAttr()));
1371void MemDescType::print(AsmPrinter &printer)
const {
1378 if (
auto layout = getMemLayout())
1379 printer <<
", " << layout;
1388Attribute MemLayoutAttr::parse(AsmParser &parser, Type type) {
1393 llvm::SmallDenseSet<StringRef> seenKeys;
1394 SmallVector<NamedAttribute> attributes;
1396 auto parseElt = [&]() -> ParseResult {
1399 return parser.
emitError(loc,
"expected valid attribute name");
1401 if (!seenKeys.insert(nameId).second)
1402 return parser.
emitError(loc,
"duplicate key '")
1403 << nameId <<
" in mem layout attribute";
1411 attributes.emplace_back(nameId, attr);
1427 loc, context, DictionaryAttr::get(context, attributes));
1430void MemLayoutAttr::print(AsmPrinter &printer)
const {
1432 ArrayRef<NamedAttribute> attrs = getAttrs().getValue();
1433 for (
size_t i = 0; i < attrs.size(); i++) {
1434 printer << attrs[i].getName().str() <<
" = " << attrs[i].getValue();
1435 if (i < attrs.size() - 1)
1444template <
typename ArithOp>
1449 return ArithOp::create(builder, loc, aVal, bVal).getResult();
1454 genBinOp<arith::DivSIOp>(a, builder.getIndexAttr(b), loc, builder)
1458 genBinOp<arith::RemSIOp>(a, builder.getIndexAttr(b), loc, builder)
1462 genBinOp<arith::MulIOp>(a, builder.getIndexAttr(b), loc, builder)
1465#define add(a, b) genBinOp<arith::AddIOp>(a, b, loc, builder)
1474 assert(offsets.size() == blockShape.size() &&
1475 "offsets and blockShape must have the same size");
1479 for (
auto [offset, block] : llvm::zip(offsets, blockShape)) {
1480 divs.push_back(
div(offset, block));
1481 rems.push_back(
rem(offset, block));
1483 blockedOffsets.append(divs.begin(), divs.end());
1484 blockedOffsets.append(rems.begin(), rems.end());
1486 return blockedOffsets;
1494 ArrayAttr strideAttr = getStrideAttr();
1496 for (
Attribute attr : strideAttr.getValue()) {
1497 strides.push_back(cast<IntegerAttr>(attr).getInt());
1505 llvm::to_vector<4>(llvm::seq<int>(0, strides.size()));
1506 llvm::sort(perm, [&](
int a,
int b) {
return strides[a] < strides[
b]; });
1508 assert(strides[perm[0]] == 1 &&
"inner most dim must have stride 1");
1510 SmallVector<int64_t> innerBlkStride(innerBlkShape.size());
1511 innerBlkStride[perm[0]] = 1;
1512 for (
size_t i = 1; i < perm.size(); ++i)
1513 innerBlkStride[perm[i]] =
1514 innerBlkStride[perm[i - 1]] * innerBlkShape[perm[i - 1]];
1520 SmallVector<int64_t> matrixShapeOrig(matrixShape.size());
1521 SmallVector<int64_t> BlkShapeOrig(matrixShape.size());
1522 for (
size_t i = 0; i < perm.size() - 1; ++i) {
1523 matrixShapeOrig[perm[i]] = strides[perm[i + 1]] / strides[perm[i]];
1524 BlkShapeOrig[perm[i]] = matrixShapeOrig[perm[i]] / innerBlkShape[perm[i]];
1527 int64_t innerBlkSize = 1;
1528 for (
auto s : innerBlkShape)
1531 SmallVector<int64_t> outerBlkStride(matrixShape.size());
1532 outerBlkStride[perm[0]] = innerBlkSize;
1533 for (
size_t i = 0; i < perm.size() - 1; ++i) {
1534 outerBlkStride[perm[i + 1]] =
1535 outerBlkStride[perm[i]] * BlkShapeOrig[perm[i]];
1539 SmallVector<int64_t> blockedStrides;
1540 blockedStrides.append(outerBlkStride.begin(), outerBlkStride.end());
1541 blockedStrides.append(innerBlkStride.begin(), innerBlkStride.end());
1543 return blockedStrides;
1547Value MemDescType::getLinearOffsets(OpBuilder &builder, Location loc,
1548 ArrayRef<OpFoldResult> offsets) {
1551 SmallVector<int64_t> blockShape = getBlockShape();
1552 SmallVector<int64_t> strides = getStrideShape();
1553 SmallVector<OpFoldResult> blockedOffsets;
1556 if (llvm::equal(blockShape, matrixShape)) {
1558 strides.erase(strides.begin(), strides.begin() + matrixShape.size());
1560 assert(offsets.size() == blockShape.size() &&
1561 "offsets and blockShape must have the same size");
1565 SmallVector<OpFoldResult> divs, rems;
1567 for (
auto [offset, block] : llvm::zip(offsets, blockShape)) {
1568 divs.push_back(
div(offset, block));
1569 rems.push_back(
rem(offset, block));
1571 blockedOffsets.append(divs.begin(), divs.end());
1572 blockedOffsets.append(rems.begin(), rems.end());
1573 offsets = blockedOffsets;
1578 for (
size_t i = 0; i < offsets.size(); ++i) {
1579 OpFoldResult mulResult =
mul(offsets[i], strides[i]);
1581 linearOffset = arith::AddIOp::create(builder, loc, mulVal, linearOffset);
1584 return linearOffset;
1590#include <mlir/Dialect/XeGPU/IR/XeGPUDialect.cpp.inc>
1591#define GET_ATTRDEF_CLASSES
1592#include <mlir/Dialect/XeGPU/IR/XeGPUAttrs.cpp.inc>
1593#define GET_TYPEDEF_CLASSES
1594#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.