MLIR 24.0.0git
XeGPUDialect.cpp
Go to the documentation of this file.
1//===- XeGPUDialect.cpp - MLIR XeGPU dialect implementation -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
16#include "mlir/IR/Builders.h"
18#include "llvm/ADT/SmallVectorExtras.h"
19#include "llvm/ADT/TypeSwitch.h"
20#include "llvm/Support/Debug.h"
21
22using std::optional;
23
24namespace mlir {
25namespace xegpu {
26
27#define GET_OP_INTERFACE_CLASSES
28#include "mlir/Dialect/XeGPU/IR/XeGPUOpInterface.cpp.inc"
29
30// A `srcShape` consists of N distribution units, each being `subShapesLayout` x
31// `subShape`. A `delinearizedId` is used to identify a particular `subShape`
32// within each distribution unit.
33// Example:
34// WG data is 128x256. SG data is 16x32, in 4x2 layout, this gives a
35// distribution unit of shape 64x64, we have 2x4 such distribution units.
36// `delinearizedId` is used to identify a 16x32 of a subgroup in each
37// distribution unit.
38static SmallVector<SmallVector<Value>>
40 SmallVector<Value> delinearizedId,
41 ArrayRef<int64_t> subShapesLayout, ArrayRef<int64_t> subShape,
42 ArrayRef<int64_t> srcShape) {
44
45 // A distribution unit must be less than or equal to `srcShape`
46 SmallVector<int64_t> distUnitShape = llvm::map_to_vector(
47 llvm::zip_equal(srcShape,
48 computeElementwiseMul(subShapesLayout, subShape)),
49 [](const auto &t) { return std::min(std::get<0>(t), std::get<1>(t)); });
50
51 // Get the offset of `subShape` within a distribution unit.
52 SmallVector<Value> distUnitLocalOffset = llvm::map_to_vector(
53 llvm::zip(delinearizedId, subShape), [&](const auto &t) -> Value {
54 return builder.createOrFold<arith::MulIOp>(
55 loc, std::get<0>(t),
56 builder.createOrFold<arith::ConstantIndexOp>(loc, std::get<1>(t)));
57 });
58
59 // For each dist unit
60 for (SmallVector<int64_t> unitOffs :
61 StaticTileOffsetRange(srcShape, distUnitShape)) {
62 // Get dist unit offset within `srcShape`.
64 llvm::map_to_vector(unitOffs, [&](int64_t d) -> Value {
65 return arith::ConstantIndexOp::create(builder, loc, d);
66 });
67 // Calculate `subShape` offset within `srcShape`.
69 llvm::map_to_vector(llvm::zip_equal(base, distUnitLocalOffset),
70 [&](const auto &t) -> Value {
71 return builder.createOrFold<arith::AddIOp>(
72 loc, std::get<0>(t), std::get<1>(t));
73 });
74 // Do not go beyond `srcShape` bounds.
75 SmallVector<Value> mods = llvm::map_to_vector(
76 llvm::zip_equal(adds, srcShape), [&](const auto &t) -> Value {
77 return builder.createOrFold<arith::RemUIOp>(
78 loc, std::get<0>(t),
79 arith::ConstantIndexOp::create(builder, loc, std::get<1>(t)));
80 });
81
82 coordinates.push_back(mods);
83 }
84 return coordinates;
85}
86
90 // Compute distribution unit shape (clamped to srcShape).
91 SmallVector<int64_t> distUnitShape(shape.size());
92 for (size_t i = 0; i < shape.size(); ++i)
93 distUnitShape[i] = std::min(shape[i], layout[i] * subShape[i]);
94
95 // Compute local offset of this ID within a distribution unit.
96 SmallVector<int64_t> localOffset(shape.size());
97 for (size_t i = 0; i < shape.size(); ++i)
98 localOffset[i] = canonicalIds[i] * subShape[i];
99
100 // Enumerate all distribution units and compute coordinates.
102 for (SmallVector<int64_t> unitOffs :
103 StaticTileOffsetRange(shape, distUnitShape)) {
104 SmallVector<int64_t> coord(shape.size());
105 for (size_t i = 0; i < shape.size(); ++i)
106 coord[i] = (unitOffs[i] + localOffset[i]) % shape[i];
107 coordinates.push_back(coord);
108 }
109 return coordinates;
110}
111
112/// Expands per-distribution-unit block-start coordinates into the full list of
113/// element coordinates each block covers: every element of the `subShape`-sized
114/// region (row-major) offset by the block start. Comparing these instead of the
115/// bare block starts lets layouts that differ only in `lane_data` blocking, but
116/// own the same elements in the same order, be recognized as equivalent.
119 ArrayRef<int64_t> subShape) {
120 SmallVector<int64_t> unitTile(subShape.size(), 1);
122 for (const SmallVector<int64_t> &start : blockStarts) {
123 for (SmallVector<int64_t> off : StaticTileOffsetRange(subShape, unitTile)) {
124 SmallVector<int64_t> coord(start.size());
125 for (size_t i = 0; i < start.size(); ++i)
126 coord[i] = start[i] + off[i];
127 expanded.push_back(std::move(coord));
128 }
129 }
130 return expanded;
131}
132
133/// Returns true if `self` and `other` distribute `shape` identically at
134/// `level`: every id in `[0, size)` owns the same coordinates under both.
135///
136/// At the Lane level, layouts that pack `lane_data` differently can still own
137/// the same per-lane elements in the same order; their block starts differ but
138/// the expanded per-element coordinates match. So block starts are expanded
139/// (via `expandBlockCoords`) before comparing, but only when it can change the
140/// result (Lane level with differing `lane_data`) - otherwise comparing the
141/// cheaper block starts is already exact.
142///
143/// TODO: Extend the same handling to the Subgroup level (sg_data repacks).
144static bool compareDistributedCoords(xegpu::DistributeLayoutAttr self,
145 const xegpu::DistributeLayoutAttr &other,
147 xegpu::LayoutKind level, int64_t size) {
148 bool expandCoords =
149 level == xegpu::LayoutKind::Lane &&
150 self.getEffectiveLaneDataAsInt() != other.getEffectiveLaneDataAsInt();
151 SmallVector<int64_t> selfSubShape, otherSubShape;
152 if (expandCoords) {
153 selfSubShape = self.getEffectiveLaneDataAsInt();
154 otherSubShape = other.getEffectiveLaneDataAsInt();
155 }
156 for (int64_t id : llvm::seq<int64_t>(0, size)) {
157 auto coords = self.computeStaticDistributedCoords(id, shape);
158 auto otherCoords = other.computeStaticDistributedCoords(id, shape);
159 if (expandCoords) {
160 coords = expandBlockCoords(coords, selfSubShape);
161 otherCoords = expandBlockCoords(otherCoords, otherSubShape);
162 }
163 if (coords != otherCoords)
164 return false;
165 }
166 return true;
167}
168
169// Checks if the given memref type represents shared local memory (SLM).
170bool XeGPUDialect::isSharedMemory(const MemRefType &memrefTy) {
171 Attribute attr = memrefTy.getMemorySpace();
172 if (!attr)
173 return false; // Default memory space is not shared local memory
174 if (auto intAttr = llvm::dyn_cast_if_present<IntegerAttr>(attr))
175 return intAttr.getInt() == 3;
176 if (auto memrefSpace = llvm::dyn_cast_if_present<MemorySpaceAttr>(attr))
177 return memrefSpace.getValue() == MemorySpace::SLM;
178 if (auto xevmSpace = llvm::dyn_cast_if_present<xevm::AddrSpaceAttr>(attr))
179 return xevmSpace.getValue() == xevm::AddrSpace::SHARED;
180 return gpu::GPUDialect::isWorkgroupMemoryAddressSpace(attr);
181}
182
183//===----------------------------------------------------------------------===//
184// XeGPU_BlockTensorDescAttr
185//===----------------------------------------------------------------------===//
186BlockTensorDescAttr BlockTensorDescAttr::get(mlir::MLIRContext *context,
187 xegpu::MemorySpace memory_space,
188 int array_length,
189 bool boundary_check) {
190 auto scopeAttr = MemorySpaceAttr::get(context, memory_space);
191 auto lengthAttr =
192 IntegerAttr::get(IntegerType::get(context, 64), array_length);
193 auto boundaryAttr = BoolAttr::get(context, boundary_check);
194 return Base::get(context, scopeAttr, lengthAttr, boundaryAttr);
195}
196
197bool BlockTensorDescAttr::hasDefaultsOnly() {
198 return getMemorySpace().getValue() == xegpu::MemorySpace::Global &&
199 getArrayLength().getInt() == 1 && getBoundaryCheck().getValue();
200}
201
202//===----------------------------------------------------------------------===//
203// XeGPU_LayoutAttr
204//===----------------------------------------------------------------------===//
205LogicalResult
206LayoutAttr::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
207 DenseI32ArrayAttr sg_layout, DenseI32ArrayAttr sg_data,
208 DenseI32ArrayAttr inst_data, DenseI32ArrayAttr lane_layout,
209 DenseI32ArrayAttr lane_data, DenseI32ArrayAttr order) {
210
211 // Special case for store_matrix
212 if (!sg_layout && !inst_data && !lane_layout)
213 return success();
214
215 // generate code to check sg_laout, inst_data and lane_layout having the same
216 // rank if they are not null.
217
218 if (sg_layout && inst_data && sg_layout.size() != inst_data.size()) {
219 return emitError()
220 << "expected sg_layout and inst_data to have the same rank";
221 }
222
223 if (sg_layout && lane_layout && sg_layout.size() != lane_layout.size()) {
224 return emitError()
225 << "expected sg_layout and lane_layout to have the same rank";
226 }
227
228 if (inst_data && lane_layout && inst_data.size() != lane_layout.size()) {
229 return emitError() << "expected inst_data and lane_layout to have the same "
230 "rank, got inst_data "
231 << inst_data.size() << ", lane_layout "
232 << lane_layout.size();
233 }
234
235 if ((sg_layout && !sg_data) || (!sg_layout && sg_data))
236 return emitError() << "sg_layout and sg_data must be used together";
237 if (sg_layout && sg_data && sg_layout.size() != sg_data.size())
238 return emitError()
239 << "expected sg_data and sg_layout to have the same rank";
240
241 if ((lane_layout && !lane_data) || (!lane_layout && lane_data))
242 return emitError() << "lane_layout and lane_data must be used together";
243 if (lane_layout && lane_data && lane_layout.size() != lane_data.size())
244 return emitError()
245 << "expected lane_data and lane_layout to have the same rank";
246
247 if (order) {
248 if (!sg_layout && !lane_layout)
249 return emitError()
250 << "expected sg_layout/lane_layout being used with order";
251
252 if (sg_layout && order.size() != sg_layout.size())
253 return emitError()
254 << "expected order and sg_layout to have the same rank";
255
256 if (lane_layout && order.size() != lane_layout.size())
257 return emitError()
258 << "expected order and lane_layout to have the same rank";
259 }
260
261 return success();
262}
263
264FailureOr<SmallVector<Value>>
265LayoutAttr::delinearizeId(OpBuilder &builder, Location loc, Value linearId) {
266
267 SmallVector<int64_t> sgLayoutInt;
268 if (isForWorkgroup()) {
269 sgLayoutInt = getEffectiveSgLayoutAsInt();
270 } else if (isForSubgroup()) {
271 sgLayoutInt = getEffectiveLaneLayoutAsInt();
272 } else {
273 return failure();
274 }
275
276 DenseI32ArrayAttr orderAttr = getOrder();
277
278 // Handle order attribute
279 SmallVector<int64_t> order;
280 if (orderAttr && !orderAttr.empty()) {
281 order = llvm::map_to_vector(orderAttr.asArrayRef(), [](int32_t idx) {
282 return static_cast<int64_t>(idx);
283 });
284 } else {
285 // Default order: [1, 0] for 2D (row-major), [2, 1, 0] for 3D, etc.
286 order = llvm::to_vector(
287 llvm::reverse(llvm::seq<int64_t>(0, sgLayoutInt.size())));
288 }
289
290 if (order.size() != sgLayoutInt.size()) {
291 return failure();
292 }
293
294 SmallVector<Value> result(sgLayoutInt.size());
295 Value remaining = linearId;
296
297 /// Process dimensions in the order they appear in the order array
298 /// The first dimension in order is the fastest-changing
299 ///
300 /// Example walkthrough for linearId=22, sgLayout=[2,4,4], order=[2,1,0]:
301 ///
302 /// Initial: remaining=22, dimIdx = order[i], dimSize = sgLayout[dimIdx],
303 /// result=[?,?,?]
304 ///
305 /// i=0 (process columns, dimIdx=2, dimSize=4):
306 /// result[2] = 22 % 4 = 2 (column coordinate)
307 /// remaining = 22 / 4 = 5 (5 complete groups of 4 columns processed)
308 ///
309 /// i=1 (process rows, dimIdx=1, dimSize=4):
310 /// result[1] = 5 % 4 = 1 (row coordinate)
311 /// remaining = 5 / 4 = 1 (1 complete group of 4 rows processed)
312 ///
313 /// i=2 (process layers, dimIdx=0, dimSize=2):
314 /// result[0] = 1 % 2 = 1 (layer coordinate)
315 /// (no remaining update - last iteration)
316 ///
317 /// Final result: [1,1,2] = Layer 1, Row 1, Column 2
318 for (size_t i = 0; i < order.size(); ++i) {
319 int64_t dimIdx = order[i];
320 int64_t dimSize = sgLayoutInt[dimIdx];
321
322 Value dimSizeVal =
323 builder.createOrFold<arith::ConstantIndexOp>(loc, dimSize);
324
325 /// Extract the coordinate for this dimension using modulo operation
326 /// This gives us "how far within this dimension" we are
327 /// e.g., linearId=22, dimSize=4: 22 % 4 = 2 (we're at position 2 within
328 /// this dimension)
329 result[dimIdx] =
330 builder.createOrFold<arith::RemUIOp>(loc, remaining, dimSizeVal);
331
332 /// Update remaining for the next dimension by removing what we've already
333 /// processed. Division tells us "how many complete groups of this dimension
334 /// we've gone through" e.g., linearId=22, dimSize=4: 22 / 4 = 5 (we've
335 /// completed 5 groups of 4) Skip this for the last iteration since there's
336 /// no next dimension to process
337 if (i < order.size() - 1) {
338 remaining =
339 builder.createOrFold<arith::DivUIOp>(loc, remaining, dimSizeVal);
340 }
341 }
342 return result;
343}
344
345/// Implements DistributeLayoutAttr::computeDistributedCoords to generate
346/// instructions for computing multi-dimensional offsets when distributed by
347/// LayoutAttr.
348FailureOr<SmallVector<SmallVector<Value>>>
349LayoutAttr::computeDistributedCoords(OpBuilder &builder, Location loc,
350 Value linearId, ArrayRef<int64_t> shape) {
351 SmallVector<int64_t> layout;
352 SmallVector<int64_t> subShape;
353 if (isForWorkgroup()) {
354 layout = getEffectiveSgLayoutAsInt();
355 subShape = getEffectiveSgDataAsInt();
356 } else if (isForSubgroup()) {
357 layout = getEffectiveLaneLayoutAsInt();
358 subShape = getEffectiveLaneDataAsInt();
359 } else {
360 return failure();
361 }
362 assert(!subShape.empty() && "sgdata or lanedata cannot be empty for "
363 "distributed coordinates computation");
364
365 // delinearize Ids
366 auto maybeIds = delinearizeId(builder, loc, linearId);
367 if (failed(maybeIds))
368 return failure();
369 SmallVector<Value> ids = *maybeIds;
370
371 return genCoordinates(builder, loc, ids, layout, subShape, shape);
372}
373
374bool LayoutAttr::isEqualTo(const xegpu::DistributeLayoutAttr &other) {
375 if (dyn_cast<xegpu::SliceAttr>(other))
376 return false;
377
378 return *this == dyn_cast<xegpu::LayoutAttr>(other);
379}
380
381/// Implements DistributeLayoutAttr::computeStaticDistributedCoords to
382/// compute multi-dimensional offsets for a given linear ID when distributed by
383/// LayoutAttr.
384SmallVector<SmallVector<int64_t>>
385LayoutAttr::computeStaticDistributedCoords(int64_t linearId,
386 ArrayRef<int64_t> shape) {
387 SmallVector<int64_t> layoutVec;
388 SmallVector<int64_t> subShape;
389 SmallVector<int64_t> instData;
390 if (isForWorkgroup()) {
391 layoutVec = getEffectiveSgLayoutAsInt();
392 subShape = getEffectiveSgDataAsInt();
393 } else if (isForSubgroup()) {
394 instData = getEffectiveInstDataAsInt();
395 layoutVec = getEffectiveLaneLayoutAsInt();
396 subShape = getEffectiveLaneDataAsInt();
397 }
398 if (!instData.empty()) {
399 linearId = 0;
400 subShape = instData;
401 }
402 assert(!subShape.empty() && "sgdata or lanedata cannot be empty");
403
404 // Delinearize the linear ID using the order attribute.
405 SmallVector<int64_t> order = getEffectiveOrderAsInt();
406 SmallVector<int64_t> delinearizedId(layoutVec.size());
407 int64_t remaining = linearId;
408 for (size_t i = 0; i < order.size(); ++i) {
409 int64_t dimIdx = order[i];
410 delinearizedId[dimIdx] = remaining % layoutVec[dimIdx];
411 remaining = remaining / layoutVec[dimIdx];
412 }
413
414 return genStaticCoordinates(delinearizedId, layoutVec, subShape, shape);
415}
416
417// set the layout for unit dims: sg_data, inst_data and lane_data to 1
418DistributeLayoutAttr
419LayoutAttr::setUnitDimData(SmallVector<int64_t> unitDims) const {
420 auto sgDataOpt = getSgData();
421 auto instDataOpt = getInstData();
422 auto laneDataOpt = getLaneData();
423
424 SmallVector<int32_t> sgData;
425 SmallVector<int32_t> instData;
426 SmallVector<int32_t> laneData;
427
428 if (sgDataOpt)
429 sgData = llvm::to_vector(sgDataOpt.asArrayRef());
430
431 if (instDataOpt)
432 instData = llvm::to_vector(instDataOpt.asArrayRef());
433
434 if (laneDataOpt)
435 laneData = llvm::to_vector(laneDataOpt.asArrayRef());
436
437 for (auto dim : unitDims) {
438 if (dim < static_cast<int64_t>(sgData.size()))
439 sgData[dim] = 1;
440 if (dim < static_cast<int64_t>(instData.size()))
441 instData[dim] = 1;
442 if (dim < static_cast<int64_t>(laneData.size()))
443 laneData[dim] = 1;
444 }
445
446 return LayoutAttr::get(
447 getContext(), getSgLayout(),
448 sgData.empty() ? DenseI32ArrayAttr()
450 instData.empty() ? DenseI32ArrayAttr()
451 : DenseI32ArrayAttr::get(getContext(), instData),
452 getLaneLayout(),
453 laneData.empty() ? DenseI32ArrayAttr()
454 : DenseI32ArrayAttr::get(getContext(), laneData),
455 getOrder());
456}
457
458// set the layout for the sepcified unit dims: sg_lane and lane_layout to 1
459DistributeLayoutAttr
460LayoutAttr::setUnitDimLayout(SmallVector<int64_t> unitDims) const {
461 auto sgLayoutOpt = getSgLayout();
462 auto laneLayoutOpt = getLaneLayout();
463
464 SmallVector<int32_t> sgLayout;
465 SmallVector<int32_t> laneLayout;
466
467 if (sgLayoutOpt)
468 sgLayout = llvm::to_vector(sgLayoutOpt.asArrayRef());
469 if (laneLayoutOpt)
470 laneLayout = llvm::to_vector(laneLayoutOpt.asArrayRef());
471
472 for (auto dim : unitDims) {
473 if (dim < static_cast<int64_t>(sgLayout.size()))
474 sgLayout[dim] = 1;
475 if (dim < static_cast<int64_t>(laneLayout.size()))
476 laneLayout[dim] = 1;
477 }
478
479 return LayoutAttr::get(
480 getContext(),
481 sgLayout.empty() ? DenseI32ArrayAttr()
482 : DenseI32ArrayAttr::get(getContext(), sgLayout),
483 getSgData(), getInstData(),
484 laneLayout.empty() ? DenseI32ArrayAttr()
485 : DenseI32ArrayAttr::get(getContext(), laneLayout),
486 getLaneData(), getOrder());
487}
488
489// Derive a new layout with sg_data, inst_data and lane_data set to the
490// specified values for the given dimension
491DistributeLayoutAttr LayoutAttr::setDimData(int64_t dim, int64_t sgData,
492 int64_t instData,
493 int64_t laneData) {
494
495 SmallVector<int64_t> sgDataVec = getEffectiveSgDataAsInt();
496 SmallVector<int64_t> instDataVec = getEffectiveInstDataAsInt();
497 SmallVector<int64_t> laneDataVec = getEffectiveLaneDataAsInt();
498
499 if (dim < static_cast<int64_t>(sgDataVec.size()) && sgData != -1)
500 sgDataVec[dim] = sgData;
501 if (dim < static_cast<int64_t>(instDataVec.size()) && instData != -1)
502 instDataVec[dim] = instData;
503 if (dim < static_cast<int64_t>(laneDataVec.size()) && laneData != -1)
504 laneDataVec[dim] = laneData;
505
506 SmallVector<int32_t> sgDataVec32(sgDataVec.begin(), sgDataVec.end());
507 SmallVector<int32_t> instDataVec32(instDataVec.begin(), instDataVec.end());
508 SmallVector<int32_t> laneDataVec32(laneDataVec.begin(), laneDataVec.end());
509
510 return LayoutAttr::get(
511 getContext(), getSgLayout(),
512 sgDataVec.empty() ? DenseI32ArrayAttr()
513 : DenseI32ArrayAttr::get(getContext(), sgDataVec32),
514 instDataVec.empty() ? DenseI32ArrayAttr()
515 : DenseI32ArrayAttr::get(getContext(), instDataVec32),
516 getLaneLayout(),
517 laneDataVec.empty() ? DenseI32ArrayAttr()
518 : DenseI32ArrayAttr::get(getContext(), laneDataVec32),
519 getOrder());
520}
521
522// Derive a new layout by removing dimensions.
523// `dimGroup` specifies a group of dimensions to be removed in the derived
524// layout.
525DistributeLayoutAttr LayoutAttr::dropDims(SmallVector<int64_t> dimGroup) {
526
527 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
528 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
529 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
530 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
531 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
532 DenseI32ArrayAttr origOrderAttr = getOrder();
533
534 SmallVector<int64_t> sortedDimGroup = dimGroup;
535 llvm::sort(sortedDimGroup);
536
537 for (auto dimIdx : llvm::reverse(sortedDimGroup)) {
538 if (!sgLayout.empty()) {
539 sgLayout.erase(sgLayout.begin() + dimIdx);
540 sgData.erase(sgData.begin() + dimIdx);
541 }
542 if (!instData.empty())
543 instData.erase(instData.begin() + dimIdx);
544 if (!laneLayout.empty()) {
545 laneLayout.erase(laneLayout.begin() + dimIdx);
546 laneData.erase(laneData.begin() + dimIdx);
547 }
548 }
549
550 // Only emit a new order attribute when the input had one, so that "no
551 // order" inputs do not gain a synthetic default that would later trip
552 // adjacency checks in collapseDims.
553 SmallVector<int64_t> newOrder;
554 if (origOrderAttr && !origOrderAttr.empty()) {
555 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
556 for (int64_t d : origOrder) {
557 if (llvm::is_contained(dimGroup, d))
558 continue;
559 int64_t offset =
560 llvm::count_if(dimGroup, [&](int64_t s) { return s < d; });
561 newOrder.push_back(d - offset);
562 }
563 if ((sgLayout.empty() && laneLayout.empty()) || newOrder.size() == 1)
564 newOrder.clear();
565 }
566
567 auto toAttr = [&](ArrayRef<int64_t> v) -> DenseI32ArrayAttr {
568 if (v.empty())
569 return nullptr;
570 SmallVector<int32_t> v32(v.begin(), v.end());
571 return DenseI32ArrayAttr::get(getContext(), v32);
572 };
573 auto droppedLayout = xegpu::LayoutAttr::get(
574 getContext(), toAttr(sgLayout), toAttr(sgData), toAttr(instData),
575 toAttr(laneLayout), toAttr(laneData), toAttr(newOrder));
576 return droppedLayout;
577}
578
579// Derive a new layout by collapsing dimensions.
580// `dimGroup` specifies a group of adjacent dimensions
581// that are collapsed into a single dimension in the derived layout.
582DistributeLayoutAttr LayoutAttr::collapseDims(SmallVector<int64_t> dimGroup) {
583
584 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
585 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
586 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
587 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
588 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
589 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
590
591 SmallVector<int64_t> sortedDimGroup = dimGroup;
592 llvm::sort(sortedDimGroup);
593 // Dims must be adjacent in the walk order
594 bool hasExplicitWalkOrder = getOrder() && !getOrder().empty();
595 for (size_t dimIdx = 1; dimIdx < sortedDimGroup.size(); ++dimIdx) {
596 int64_t prev = sortedDimGroup[dimIdx - 1];
597 int64_t curr = sortedDimGroup[dimIdx];
598
599 if (hasExplicitWalkOrder) {
600 // Walk order matters if dims are not trivially collapsible
601 if ((sgLayout.empty() || (sgLayout[prev] == 1 && sgLayout[curr] == 1)) &&
602 (laneLayout.empty() ||
603 (laneLayout[prev] == 1 && laneLayout[curr] == 1)))
604 continue;
605 if (std::abs(origOrder[prev] - origOrder[curr]) != 1)
606 llvm::report_fatal_error(
607 "dimensions being collapsed must be adjacent in order");
608 } else if (curr - prev != 1)
609 llvm::report_fatal_error("dimensions being collapsed must be adjacent");
610 }
611
612 int firstDim = sortedDimGroup.front();
613
614 // collapse the dimensions in dimGroup into one dimension by multiplying their
615 // sizes together
616
617 if (!sgLayout.empty()) {
618 int64_t collapsedSglayout = 1, collapsedSgData = 1;
619 for (auto dimIdx : dimGroup) {
620 collapsedSglayout *= sgLayout[dimIdx];
621 collapsedSgData *= sgData[dimIdx];
622 }
623 for (auto dimIdx : llvm::reverse(sortedDimGroup)) {
624 sgLayout.erase(sgLayout.begin() + dimIdx, sgLayout.begin() + dimIdx + 1);
625 sgData.erase(sgData.begin() + dimIdx, sgData.begin() + dimIdx + 1);
626 }
627 sgLayout.insert(sgLayout.begin() + firstDim, collapsedSglayout);
628 sgData.insert(sgData.begin() + firstDim, collapsedSgData);
629 }
630
631 if (!instData.empty()) {
632 int64_t collapsedInstData = 1;
633 for (auto dimIdx : dimGroup)
634 collapsedInstData *= instData[dimIdx];
635 for (auto dimIdx : llvm::reverse(sortedDimGroup))
636 instData.erase(instData.begin() + dimIdx, instData.begin() + dimIdx + 1);
637 instData.insert(instData.begin() + firstDim, collapsedInstData);
638 }
639
640 if (!laneLayout.empty()) {
641 int64_t collapsedLaneLayout = 1, collapsedLaneData = 1;
642 for (auto dimIdx : dimGroup) {
643 collapsedLaneLayout *= laneLayout[dimIdx];
644 collapsedLaneData *= laneData[dimIdx];
645 }
646 for (auto dimIdx : llvm::reverse(sortedDimGroup)) {
647 laneLayout.erase(laneLayout.begin() + dimIdx,
648 laneLayout.begin() + dimIdx + 1);
649 laneData.erase(laneData.begin() + dimIdx, laneData.begin() + dimIdx + 1);
650 }
651 laneLayout.insert(laneLayout.begin() + firstDim, collapsedLaneLayout);
652 laneData.insert(laneData.begin() + firstDim, collapsedLaneData);
653 }
654
655 SmallVector<int64_t> newOrder;
656 DenseI32ArrayAttr orderAttr = getOrder();
657 if (orderAttr && !orderAttr.empty()) {
658
659 for (auto dimIdx : llvm::reverse(sortedDimGroup)) {
660 if (dimIdx != firstDim)
661 origOrder.erase(origOrder.begin() + dimIdx);
662 }
663 // say we have orderVec = {5, 3, 2, 1, 0}
664 // Create indices [0, 1, 2, 3, 4]
665 SmallVector<size_t> indices =
666 llvm::to_vector(llvm::seq<size_t>(0, origOrder.size()));
667
668 // Sort indices based on corresponding values
669 llvm::sort(indices,
670 [&](size_t a, size_t b) { return origOrder[a] < origOrder[b]; });
671
672 newOrder = llvm::to_vector(llvm::map_range(
673 indices, [&](size_t i) { return static_cast<int64_t>(i); }));
674 }
675
676 auto toAttr = [&](ArrayRef<int64_t> v) -> DenseI32ArrayAttr {
677 if (v.empty())
678 return nullptr;
679 SmallVector<int32_t> v32(v.begin(), v.end());
680 return DenseI32ArrayAttr::get(getContext(), v32);
681 };
682 auto collapsedLayout = xegpu::LayoutAttr::get(
683 getContext(), toAttr(sgLayout), toAttr(sgData), toAttr(instData),
684 toAttr(laneLayout), toAttr(laneData), toAttr(newOrder));
685 return collapsedLayout;
686}
687
688// Derive a new layout by expanding a single dimension `dim` into multiple
689// adjacent dimensions whose extents are given by `targetShape`.
690//
691// The expanded dims are row-major (innermost is fastest-varying), so every
692// field is spread innermost-first. For sg and lane levels the data component
693// (sg_data / lane_data) is distributed first and the layout component
694// (sg_layout / lane_layout) then strides over the per-dim leftover; this
695// shared inner-first sweep is what makes "wrap-around" distributions correct.
696// When the data component spans the full extent (replicated/broadcast across
697// subgroups or lanes), the layout component is capped by the full extent
698// instead of the leftover. order entries past `dim` shift up by
699// `targetShape.size() - 1`.
700//
701// Examples (rank-1 input; the tile is the vector being expanded):
702// vector<4096> -> vector<8x16x32>, sg_layout=[8], sg_data=[512]
703// -> sg_layout=[8,1,1], sg_data=[1,16,32] (split: innermost-first)
704// vector<32> -> vector<2x16>, sg_layout=[4], sg_data=[4]
705// -> sg_layout=[1,4], sg_data=[1,4] (split: innermost-first,
706// wrap-around)
707// vector<64> -> vector<8x8>, sg_layout=[2], sg_data=[64]
708// -> sg_layout=[2,1], sg_data=[8,8] (replicated: outermost-first)
709// vector<4096> -> vector<8x16x32>, inst_data=[32], lane_layout=[16],
710// lane_data=[1]
711// -> inst_data=[1,1,32], lane_layout=[1,1,16], lane_data=[1,1,1]
712// (split: innermost-first)
713DistributeLayoutAttr LayoutAttr::expandDim(int64_t dim,
714 ArrayRef<int64_t> targetShape) {
715 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
716 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
717 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
718 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
719 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
720
721 int64_t origRank = getRank();
722 int64_t expCount = static_cast<int64_t>(targetShape.size());
723 assert(dim >= 0 && dim < origRank && "dim out of range");
724 assert(expCount >= 1 && "targetShape must have at least one dim");
725 int64_t newRank = origRank + expCount - 1;
726
727 // Snapshot the per-dim values we need before any field is mutated by
728 // splice() below; without this, computations that read e.g. `laneLayout[dim]`
729 // after laneLayout has already been expanded would see the wrong value.
730 int64_t origSgLayoutDim = sgLayout.empty() ? 1 : sgLayout[dim];
731 int64_t origSgDataDim = sgData.empty() ? 1 : sgData[dim];
732 int64_t origLaneLayoutDim = laneLayout.empty() ? 1 : laneLayout[dim];
733 int64_t origLaneDataDim = laneData.empty() ? 1 : laneData[dim];
734 int64_t origInstDataDim = instData.empty() ? 1 : instData[dim];
735
736 // Distribute `total` over the new dims, at most `dimSizeCap[i]` on dim i.
737 // Fill from the innermost dim.
738 auto spread = [&](int64_t total,
739 ArrayRef<int64_t> dimSizeCap) -> SmallVector<int64_t> {
740 SmallVector<int64_t> out(expCount, 1);
741 int64_t remaining = total;
742 for (int64_t i = expCount - 1; i >= 0; --i) {
743 if (remaining == 1)
744 break;
745 int64_t take = std::min(remaining, dimSizeCap[i]);
746 assert(take > 0 && "expandDim distribution must not be zero");
747 assert(remaining % take == 0 &&
748 "expandDims must divide evenly across dims");
749 out[i] = take;
750 remaining /= take;
751 }
752 assert(remaining == 1 && "expandDims total must fit within target shape");
753 return out;
754 };
755
756 // Splice `expanded` (length expCount) into `vec` at position `dim`,
757 // replacing the single entry at `dim`.
758 auto splice = [&](SmallVector<int64_t> &vec, ArrayRef<int64_t> expanded) {
759 if (vec.empty())
760 return;
761 vec.erase(vec.begin() + dim);
762 vec.insert(vec.begin() + dim, expanded.begin(), expanded.end());
763 };
764
765 bool hasSgLayout = !sgLayout.empty();
766 bool hasSgData = !sgData.empty();
767 bool hasLaneLayout = !laneLayout.empty();
768 bool hasLaneData = !laneData.empty();
769 bool hasInstData = !instData.empty();
770
771 // Distribute sg_data first, then sg_layout over what each dim has left.
772 // - Split dim: the shape_cast must keep which subgroup owns each element,
773 // and filling from the innermost dim does that.
774 // - Replicated dim (sg_data spans the whole dim): every subgroup holds all
775 // of it, so the replicas could sit on any of the new dims. As a heuristic,
776 // put them all on the outermost one: the inner dims are often reduced, and
777 // replicas there would make the reduction split them across subgroups.
778 bool sgDataReplicated =
779 hasSgData && origSgDataDim == computeProduct(targetShape);
780 SmallVector<int64_t> expSgData(expCount, 1);
781 if (hasSgData) {
782 expSgData = spread(origSgDataDim, targetShape);
783 splice(sgData, expSgData);
784 }
785 SmallVector<int64_t> expSgLayout(expCount, 1);
786 if (hasSgLayout) {
787 if (sgDataReplicated) {
788 expSgLayout[0] = origSgLayoutDim;
789 } else {
790 SmallVector<int64_t> dimSizeCap(targetShape.begin(), targetShape.end());
791 if (hasSgData)
792 for (int64_t i = 0; i < expCount; ++i)
793 dimSizeCap[i] /= expSgData[i];
794 expSgLayout = spread(origSgLayoutDim, dimSizeCap);
795 }
796 splice(sgLayout, expSgLayout);
797 }
798
799 // Per-sg extent feeding lane_layout / lane_data / inst_data.
800 SmallVector<int64_t> perSgShape(targetShape.begin(), targetShape.end());
801 if (hasSgLayout && !sgDataReplicated)
802 for (int64_t i = 0; i < expCount; ++i)
803 perSgShape[i] /= expSgLayout[i];
804
805 // lane_data first, then lane_layout into the per-dim leftover. When lane_data
806 // is replicated across lanes it spans the full per-sg extent, so lane_layout
807 // is capped by perSgShape itself instead of the leftover.
808 bool laneDataReplicated =
809 hasLaneData && origLaneDataDim == computeProduct(perSgShape);
810 SmallVector<int64_t> expLaneLayout(expCount, 1);
811 SmallVector<int64_t> expLaneData(expCount, 1);
812 if (hasLaneData)
813 expLaneData = spread(origLaneDataDim, perSgShape);
814 if (hasLaneLayout) {
815 SmallVector<int64_t> dimSizeCap(perSgShape.begin(), perSgShape.end());
816 if (hasLaneData && !laneDataReplicated)
817 for (int64_t i = 0; i < expCount; ++i)
818 dimSizeCap[i] /= expLaneData[i];
819 expLaneLayout = spread(origLaneLayoutDim, dimSizeCap);
820 }
821 if (hasLaneData)
822 splice(laneData, expLaneData);
823 if (hasLaneLayout)
824 splice(laneLayout, expLaneLayout);
825
826 // inst_data: seed each dim from the per-lane atom
827 // `laneLayout[i]*laneData[i]`, spread the remaining factor over the leftover,
828 // then scale back by the atom. Without lane info, spread inst_data directly
829 // over the per-sg extent.
830 if (hasInstData) {
831 SmallVector<int64_t> expInstData;
832 if (!hasLaneLayout || !hasLaneData) {
833 expInstData = spread(origInstDataDim, perSgShape);
834 } else {
835 int64_t laneAtom = origLaneLayoutDim * origLaneDataDim;
836 SmallVector<int64_t> atom(expCount, 1);
837 SmallVector<int64_t> dimSizeCap(expCount, 1);
838 for (int64_t i = 0; i < expCount; ++i) {
839 atom[i] = expLaneLayout[i] * expLaneData[i];
840 dimSizeCap[i] = perSgShape[i] / atom[i];
841 }
842 expInstData = spread(origInstDataDim / laneAtom, dimSizeCap);
843 for (int64_t i = 0; i < expCount; ++i)
844 expInstData[i] *= atom[i];
845 }
846 splice(instData, expInstData);
847 }
848
849 // order: replace `dim`'s entry with the expanded dim indices in
850 // innermost-fastest order; shift every other entry past `dim` up by
851 // (expCount - 1).
852 SmallVector<int64_t> newOrder;
853 DenseI32ArrayAttr orderAttr = getOrder();
854 if (orderAttr && !orderAttr.empty()) {
855 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
856 newOrder.reserve(newRank);
857 for (int64_t o : origOrder) {
858 if (o == dim) {
859 // Innermost dim of the expanded group is fastest-varying.
860 for (int64_t i = expCount - 1; i >= 0; --i)
861 newOrder.push_back(dim + i);
862 } else if (o > dim) {
863 newOrder.push_back(o + expCount - 1);
864 } else {
865 newOrder.push_back(o);
866 }
867 }
868 }
869
870 auto toAttr = [&](ArrayRef<int64_t> v) -> DenseI32ArrayAttr {
871 if (v.empty())
872 return nullptr;
873 SmallVector<int32_t> v32(v.begin(), v.end());
874 return DenseI32ArrayAttr::get(getContext(), v32);
875 };
876 return xegpu::LayoutAttr::get(getContext(), toAttr(sgLayout), toAttr(sgData),
877 toAttr(instData), toAttr(laneLayout),
878 toAttr(laneData), toAttr(newOrder));
879}
880
881// Derive a new layout by transpose the layout using `permutation`.
882DistributeLayoutAttr LayoutAttr::transposeDims(ArrayRef<int64_t> permutation) {
883
884 SmallVector<int64_t> origSgLayout = getEffectiveSgLayoutAsInt();
885 SmallVector<int64_t> origSgData = getEffectiveSgDataAsInt();
886 SmallVector<int64_t> origInstData = getEffectiveInstDataAsInt();
887 SmallVector<int64_t> origLaneLayout = getEffectiveLaneLayoutAsInt();
888 SmallVector<int64_t> origLaneData = getEffectiveLaneDataAsInt();
889 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
890
891 SmallVector<int32_t> sgLayout;
892 SmallVector<int32_t> sgData;
893 SmallVector<int32_t> instData;
894 SmallVector<int32_t> laneLayout;
895 SmallVector<int32_t> laneData;
896 SmallVector<int32_t> order;
897
898 for (int64_t idx : permutation) {
899 if (!origLaneLayout.empty()) {
900 laneLayout.push_back(static_cast<int32_t>(origLaneLayout[idx]));
901 laneData.push_back(static_cast<int32_t>(origLaneData[idx]));
902 }
903 if (!origInstData.empty())
904 instData.push_back(static_cast<int32_t>(origInstData[idx]));
905 if (!origSgLayout.empty()) {
906 sgLayout.push_back(static_cast<int32_t>(origSgLayout[idx]));
907 sgData.push_back(static_cast<int32_t>(origSgData[idx]));
908 }
909 }
910
911 // `order` is distinct from the size-valued fields above: its *values* are
912 // dimension indices (order[0] is the fastest-varying dim), not per-position
913 // sizes. A transpose relabels dimensions (source dim d becomes result dim
914 // inversePerm[d]) so the dimension values are remapped through the inverse
915 // permutation: newOrder[i] = inversePerm[origOrder[i]].
916 //
917 // The linearization order this describes is invariant under transpose: a
918 // transpose only renames dimensions, so the subgroup ID assigned to a given
919 // block of data must stay the same. Remapping the values through the inverse
920 // permutation is exactly what preserves that order.
921 SmallVector<int64_t> inversePermutation =
922 invertPermutationVector(permutation);
923 for (int64_t dim : origOrder)
924 order.push_back(static_cast<int32_t>(inversePermutation[dim]));
925 if (origLaneLayout.empty() && origSgLayout.empty())
926 order.clear();
927
928 auto toAttr = [&](ArrayRef<int32_t> v) -> DenseI32ArrayAttr {
929 return v.empty() ? nullptr : DenseI32ArrayAttr::get(getContext(), v);
930 };
931 return xegpu::LayoutAttr::get(getContext(), toAttr(sgLayout), toAttr(sgData),
932 toAttr(instData), toAttr(laneLayout),
933 toAttr(laneData), toAttr(order));
934}
935
936/// Check if this layout is a transpose of another layout.
937bool LayoutAttr::isTransposeOf(const xegpu::DistributeLayoutAttr &other,
938 ArrayRef<int64_t> perm,
939 const xegpu::LayoutKind kind) {
940 if (!other)
941 return false;
942 if (getRank() != other.getRank() ||
943 perm.size() != static_cast<size_t>(getRank()))
944 return false;
945 if (!isPermutationVector(perm))
946 return false;
947 // vector.transpose semantics: dst[i] = src[perm[i]]. So `this` (= dst) is a
948 // transpose of `other` (= src) via `perm` iff for all i, dst[i] ==
949 // src[perm[i]].
950 auto checkTranspose = [](ArrayRef<int64_t> dst, ArrayRef<int64_t> src,
951 ArrayRef<int64_t> perm) {
952 for (const auto &ta : llvm::enumerate(perm)) {
953 if (dst[ta.index()] != src[ta.value()])
954 return false;
955 }
956 return true;
957 };
958 // `order` is different: its *values* are dimension indices, so a transpose
959 // relabels them through the inverse permutation rather than reindexing by
960 // position. `this` (= dst) is a transpose of `other` (= src) iff
961 // dst.order[i] == inversePerm[src.order[i]] for all i. This matches the
962 // convention produced by `transposeDims`.
963 auto checkOrderTranspose = [](ArrayRef<int64_t> dstOrder,
964 ArrayRef<int64_t> srcOrder,
965 ArrayRef<int64_t> perm) {
966 if (dstOrder.size() != srcOrder.size())
967 return false;
968 SmallVector<int64_t> inversePerm = invertPermutationVector(perm);
969 for (auto [d, s] : llvm::zip_equal(dstOrder, srcOrder)) {
970 if (d != inversePerm[s])
971 return false;
972 }
973 return true;
974 };
975 if (kind == xegpu::LayoutKind::Subgroup)
976 return checkTranspose(getEffectiveSgLayoutAsInt(),
977 other.getEffectiveSgLayoutAsInt(), perm) &&
978 checkTranspose(getEffectiveSgDataAsInt(),
979 other.getEffectiveSgDataAsInt(), perm) &&
980 checkOrderTranspose(getEffectiveOrderAsInt(),
981 other.getEffectiveOrderAsInt(), perm);
982 if (kind == xegpu::LayoutKind::InstData)
983 return checkTranspose(getEffectiveInstDataAsInt(),
984 other.getEffectiveInstDataAsInt(), perm);
985 if (kind == xegpu::LayoutKind::Lane)
986 return checkTranspose(getEffectiveLaneLayoutAsInt(),
987 other.getEffectiveLaneLayoutAsInt(), perm) &&
988 checkTranspose(getEffectiveLaneDataAsInt(),
989 other.getEffectiveLaneDataAsInt(), perm) &&
990 checkOrderTranspose(getEffectiveOrderAsInt(),
991 other.getEffectiveOrderAsInt(), perm);
992
993 return false;
994}
995
996bool LayoutAttr::isCompatibleWith(const xegpu::DistributeLayoutAttr &other,
997 SmallVector<int64_t> shape,
998 xegpu::LayoutKind level) {
999 if (!other)
1000 return false;
1001 if (getEffectiveOrderAsInt() == other.getEffectiveOrderAsInt()) {
1002 // short cut when order is the same, no need to compute coords and compare
1003 if (level == xegpu::LayoutKind::Subgroup)
1004 if (getEffectiveSgLayoutAsInt() == other.getEffectiveSgLayoutAsInt() &&
1005 getEffectiveSgDataAsInt() == other.getEffectiveSgDataAsInt())
1006 return true;
1007 if (level == xegpu::LayoutKind::Lane)
1008 if (getEffectiveLaneLayoutAsInt() ==
1009 other.getEffectiveLaneLayoutAsInt() &&
1010 getEffectiveLaneDataAsInt() == other.getEffectiveLaneDataAsInt())
1011 return true;
1012 }
1013
1014 auto compareCoordsForAllIds = [&](int64_t size) {
1015 return compareDistributedCoords(*this, other, shape, level, size);
1016 };
1017
1018 if (level == xegpu::LayoutKind::Subgroup) {
1019 int64_t wgSize = computeProduct(getEffectiveSgLayoutAsInt());
1020 return compareCoordsForAllIds(wgSize);
1021 }
1022 if (level == xegpu::LayoutKind::InstData) {
1023 return (getEffectiveInstDataAsInt() == other.getEffectiveInstDataAsInt());
1024 }
1025 if (level == xegpu::LayoutKind::Lane) {
1026 int64_t subgroupSize = computeProduct(getEffectiveLaneLayoutAsInt());
1027 return compareCoordsForAllIds(subgroupSize);
1028 }
1029 return true;
1030}
1031
1032//===----------------------------------------------------------------------===//
1033// XeGPU_SliceAttr
1034//===----------------------------------------------------------------------===//
1035LogicalResult
1036SliceAttr::verify(llvm::function_ref<InFlightDiagnostic()> emitError,
1037 xegpu::DistributeLayoutAttr parent, DenseI64ArrayAttr dims) {
1038
1039 if (!dims)
1040 return emitError() << "expected dims attribute";
1041
1042 // check every element in dims is unique and smaller than rank
1043 llvm::SmallDenseSet<int64_t> seen;
1044 for (int64_t dim : dims.asArrayRef()) {
1045 if (dim < 0)
1046 return emitError() << "invalid dim (" << dim << ") in slice attribute.";
1047 if (!seen.insert(dim).second)
1048 return emitError() << "repeated dim (" << dim << ") in slice attribute.";
1049 }
1050 return success();
1051}
1052
1053SliceAttr SliceAttr::flatten() const {
1054 xegpu::DistributeLayoutAttr parent = getParent();
1055 SmallVector<DenseI64ArrayAttr> slicedDims({getDims()});
1056
1057 while (auto sliceAttr = dyn_cast<xegpu::SliceAttr>(parent)) {
1058 parent = sliceAttr.getParent();
1059 slicedDims.push_back(sliceAttr.getDims());
1060 }
1061
1062 auto layoutAttr = dyn_cast<xegpu::LayoutAttr>(parent);
1063 SmallVector<int64_t> indices =
1064 llvm::to_vector(llvm::seq<int64_t>(0, layoutAttr.getRank()));
1065
1066 // get remaining dims (flattened) by applying slice ops with all slicedDims
1067 SmallVector<int64_t> remainingDims(indices);
1068 for (auto dim : llvm::reverse(slicedDims))
1069 remainingDims = XeGPUDialect::slice(llvm::ArrayRef<int64_t>(remainingDims),
1070 dim.asArrayRef());
1071
1072 // get flattened sliced dims by applying slice ops with the remaining dims
1073 SmallVector<int64_t> flattenedDims = XeGPUDialect::slice(
1074 llvm::ArrayRef<int64_t>(indices), llvm::ArrayRef<int64_t>(remainingDims));
1075
1076 return xegpu::SliceAttr::get(
1077 getContext(), layoutAttr,
1078 DenseI64ArrayAttr::get(getContext(), flattenedDims));
1079}
1080
1081FailureOr<SmallVector<Value>>
1082SliceAttr::delinearizeId(OpBuilder &builder, Location loc, Value linearId) {
1083 SliceAttr attr = flatten();
1084 auto parent = dyn_cast<LayoutAttr>(attr.getParent());
1085 return parent.delinearizeId(builder, loc, linearId);
1086}
1087
1088// Implements DistributeLayoutAttr::computeDistributedCoords to generate
1089// instructions for computing multi-dimensional offsets when distributed by
1090// LayoutAttr.
1091FailureOr<SmallVector<SmallVector<Value>>>
1092SliceAttr::computeDistributedCoords(OpBuilder &builder, Location loc,
1093 Value linearId, ArrayRef<int64_t> shape) {
1094 assert(getRank() == static_cast<int64_t>(shape.size()) && "invalid shape.");
1095
1096 SmallVector<int64_t> layout;
1097 SmallVector<int64_t> subShape;
1098 if (isForWorkgroup()) {
1099 layout = getEffectiveSgLayoutAsInt();
1100 subShape = getEffectiveSgDataAsInt();
1101 } else if (isForSubgroup()) {
1102 layout = getEffectiveLaneLayoutAsInt();
1103 subShape = getEffectiveLaneDataAsInt();
1104 } else {
1105 return failure();
1106 }
1107
1108 if (subShape.empty())
1109 return failure();
1110
1111 // delinearize Ids
1112 auto maybeIds = delinearizeId(builder, loc, linearId);
1113 if (failed(maybeIds))
1114 return failure();
1115
1116 // The effective sgIds for offsets computing correspond
1117 // to the dims that are not sliced.
1118 ArrayRef<int64_t> dims = flatten().getDims().asArrayRef();
1119 SmallVector<Value> canonicalIds =
1120 XeGPUDialect::slice(ArrayRef<Value>(*maybeIds), dims);
1121
1122 return genCoordinates(builder, loc, canonicalIds, layout, subShape, shape);
1123}
1124
1125/// Implements DistributeLayoutAttr::computeStaticDistributedCoords to
1126/// compute multi-dimensional offsets for a given linear ID when distributed by
1127/// SliceAttr. Delegates delinearization to the parent LayoutAttr, then uses
1128/// only the non-sliced dimensions for coordinate computation.
1129SmallVector<SmallVector<int64_t>>
1130SliceAttr::computeStaticDistributedCoords(int64_t linearId,
1131 ArrayRef<int64_t> shape) {
1132 assert(getRank() == static_cast<int64_t>(shape.size()) && "invalid shape.");
1133
1134 SmallVector<int64_t> layout;
1135 SmallVector<int64_t> subShape;
1136 SmallVector<int64_t> instData;
1137 if (isForWorkgroup()) {
1138 layout = getEffectiveSgLayoutAsInt();
1139 subShape = getEffectiveSgDataAsInt();
1140 } else if (isForSubgroup()) {
1141 instData = getEffectiveInstDataAsInt();
1142 layout = getEffectiveLaneLayoutAsInt();
1143 subShape = getEffectiveLaneDataAsInt();
1144 }
1145 if (!instData.empty()) {
1146 linearId = 0;
1147 subShape = instData;
1148 }
1149
1150 assert(!subShape.empty() && "sgdata or lanedata cannot be empty");
1151
1152 // Delinearize the ID using the parent layout (same as the IR version).
1153 SliceAttr flattened = flatten();
1154 auto parent = dyn_cast<LayoutAttr>(flattened.getParent());
1155 SmallVector<int64_t> parentLayoutVec;
1156 if (parent.isForWorkgroup())
1157 parentLayoutVec = parent.getEffectiveSgLayoutAsInt();
1158 else
1159 parentLayoutVec = parent.getEffectiveLaneLayoutAsInt();
1160
1161 SmallVector<int64_t> order = parent.getEffectiveOrderAsInt();
1162 SmallVector<int64_t> allIds(parentLayoutVec.size());
1163 int64_t remaining = linearId;
1164 for (size_t i = 0; i < order.size(); ++i) {
1165 int64_t dimIdx = order[i];
1166 allIds[dimIdx] = remaining % parentLayoutVec[dimIdx];
1167 if (i < order.size() - 1)
1168 remaining = remaining / parentLayoutVec[dimIdx];
1169 }
1170
1171 // The effective IDs for coordinate computation correspond
1172 // to the dims that are not sliced.
1173 ArrayRef<int64_t> dims = flattened.getDims().asArrayRef();
1174 SmallVector<int64_t> canonicalIds =
1175 XeGPUDialect::slice(ArrayRef<int64_t>(allIds), dims);
1176
1177 return genStaticCoordinates(canonicalIds, layout, subShape, shape);
1178}
1179
1180bool SliceAttr::isSliceOf(const xegpu::DistributeLayoutAttr &other) {
1181 auto flattenedThis = flatten();
1182 // If other is a LayoutAttr, just compare directly with parent of
1183 // flattenedThis.
1184 if (auto otherLayout = dyn_cast<xegpu::LayoutAttr>(other))
1185 return flattenedThis.getParent() == otherLayout;
1186 // If other is a SliceAttr, flatten it first before comparing.
1187 auto flattenedOther = dyn_cast<xegpu::SliceAttr>(other).flatten();
1188 // Both must have common parent LayoutAttr.
1189 if (flattenedThis.getParent() != flattenedOther.getParent())
1190 return false;
1191 // otherFlattened's sliced dims must be a subset of flattenedThis's sliced
1192 // dims.
1193 llvm::SmallDenseSet<int64_t> thisDims(
1194 flattenedThis.getDims().asArrayRef().begin(),
1195 flattenedThis.getDims().asArrayRef().end());
1196 return llvm::all_of(flattenedOther.getDims().asArrayRef(),
1197 [&](int64_t dim) { return thisDims.contains(dim); });
1198}
1199
1200bool SliceAttr::isEqualTo(const xegpu::DistributeLayoutAttr &other) {
1201 if (dyn_cast<xegpu::LayoutAttr>(other))
1202 return false;
1203
1204 auto flattenedThis = flatten();
1205 auto flattenedOther = dyn_cast<xegpu::SliceAttr>(other).flatten();
1206
1207 return ((flattenedThis.getParent() == flattenedOther.getParent()) &&
1208 (flattenedThis.getDims() == flattenedOther.getDims()));
1209}
1210
1211bool SliceAttr::isCompatibleWith(const xegpu::DistributeLayoutAttr &other,
1212 SmallVector<int64_t> shape,
1213 xegpu::LayoutKind level) {
1214 if (!other)
1215 return false;
1216 if (getEffectiveOrderAsInt() == other.getEffectiveOrderAsInt()) {
1217 // short cut when order is the same, no need to compute coords and compare
1218 if (level == xegpu::LayoutKind::Subgroup)
1219 if (getEffectiveSgLayoutAsInt() == other.getEffectiveSgLayoutAsInt() &&
1220 getEffectiveSgDataAsInt() == other.getEffectiveSgDataAsInt())
1221 return true;
1222 if (level == xegpu::LayoutKind::Lane)
1223 if (getEffectiveLaneLayoutAsInt() ==
1224 other.getEffectiveLaneLayoutAsInt() &&
1225 getEffectiveLaneDataAsInt() == other.getEffectiveLaneDataAsInt())
1226 return true;
1227 }
1228
1229 auto compareCoordsForAllIds = [&](int64_t size) {
1230 return compareDistributedCoords(*this, other, shape, level, size);
1231 };
1232
1233 auto flattenedThis = flatten();
1234 auto parent = dyn_cast<LayoutAttr>(flattenedThis.getParent());
1235 if (level == xegpu::LayoutKind::Subgroup) {
1236 int64_t wgSize = computeProduct(parent.getEffectiveSgLayoutAsInt());
1237 return compareCoordsForAllIds(wgSize);
1238 }
1239 if (level == xegpu::LayoutKind::InstData) {
1240 return (getEffectiveInstDataAsInt() == other.getEffectiveInstDataAsInt());
1241 }
1242 if (level == xegpu::LayoutKind::Lane) {
1243 int64_t subgroupSize = computeProduct(parent.getEffectiveLaneLayoutAsInt());
1244 return compareCoordsForAllIds(subgroupSize);
1245 }
1246 return true;
1247}
1248
1249xegpu::SliceAttr SliceAttr::dropSliceDims(ArrayRef<int64_t> sliceDimsToDrop) {
1250 if (sliceDimsToDrop.empty())
1251 return *this;
1252 SmallVector<int64_t> sliceDims{getDims().asArrayRef()};
1253 for (auto dim : sliceDimsToDrop) {
1254 auto foundIt = std::find(sliceDims.begin(), sliceDims.end(), dim);
1255 assert(foundIt != sliceDims.end() &&
1256 "Expected to find the specified reduction dim in slice dims");
1257 sliceDims.erase(foundIt);
1258 }
1259
1260 auto sliceWithoutDims = xegpu::SliceAttr::get(
1261 this->getContext(), getParent(),
1262 DenseI64ArrayAttr::get(this->getContext(), sliceDims));
1263
1264 return sliceWithoutDims;
1265}
1266
1267// Helper function to adjust dimensions from sliced space to parent space
1268// say we have a parent shape of rank 4, and slice dims [1,3], so the sliced
1269// shape is of rank 2, if we want to set unit dim [0] in sliced space, it maps
1270// to dim [0] in parent space; if we want to set unit dim [1] in sliced space,
1271// it maps to dim [2] in parent space.
1272static SmallVector<int64_t>
1274 ArrayRef<int64_t> sliceDims) {
1275 // Rather than recovering the exact parent rank, we compute a safe upper
1276 // bound so that dimsToMap can be adjusted safely. This upper bound is
1277 // defined as max(dimsToMap, sliceDims) + 1 + sliceDims.size().
1278 int64_t maxDim = -1;
1279 maxDim =
1280 std::max(maxDim, *std::max_element(sliceDims.begin(), sliceDims.end()));
1281 maxDim =
1282 std::max(maxDim, *std::max_element(dimsToMap.begin(), dimsToMap.end()));
1283 int64_t parentSpaceRank = maxDim + sliceDims.size() + 1;
1284
1285 // get remaining dims in parent space after applying slicing with parent's
1286 // slice Dims
1287 llvm::SmallDenseSet<int64_t> slicedDimsSet(sliceDims.begin(),
1288 sliceDims.end());
1289 SmallVector<int64_t> remainingDims;
1290 for (int64_t i = 0; i < parentSpaceRank; ++i) {
1291 if (!slicedDimsSet.contains(i))
1292 remainingDims.push_back(i);
1293 }
1294
1295 // Map unit dims from sliced space to parent space
1296 SmallVector<int64_t> adjustUnitDims;
1297 for (auto dim : dimsToMap) {
1298 int64_t mappedDim = remainingDims[dim];
1299 adjustUnitDims.push_back(mappedDim);
1300 }
1301
1302 return adjustUnitDims;
1303}
1304
1305// set the layout for unit dims: sg_data, inst_data and lane_data to 1
1306DistributeLayoutAttr
1307SliceAttr::setUnitDimData(SmallVector<int64_t> unitDims) const {
1308 DistributeLayoutAttr parentLayout = getParent();
1309
1310 ArrayRef<int64_t> sliceDims = getDims().asArrayRef();
1311
1312 SmallVector<int64_t> adjustUnitDims =
1313 mapSlicedDimsToParentSpace(unitDims, sliceDims);
1314
1315 return SliceAttr::get(getContext(),
1316 parentLayout.setUnitDimData(adjustUnitDims), getDims());
1317}
1318
1319// set the layout for the sepcified unit dims: sg_lane and lane_layout to 1
1320DistributeLayoutAttr
1321SliceAttr::setUnitDimLayout(SmallVector<int64_t> unitDims) const {
1322 DistributeLayoutAttr parentLayout = getParent();
1323
1324 ArrayRef<int64_t> sliceDims = getDims().asArrayRef();
1325
1326 SmallVector<int64_t> adjustUnitDims =
1327 mapSlicedDimsToParentSpace(unitDims, sliceDims);
1328
1329 return SliceAttr::get(
1330 getContext(), parentLayout.setUnitDimLayout(adjustUnitDims), getDims());
1331}
1332
1333// Derive a new layout with sg_data, inst_data and lane_data set to the
1334// specified values for the given dimension
1335DistributeLayoutAttr SliceAttr::setDimData(int64_t dim, int64_t sgData,
1336 int64_t instData, int64_t laneData) {
1337 ArrayRef<int64_t> sliceDims = getDims().asArrayRef();
1338 auto parent = getParent();
1339
1340 SmallVector<int64_t> dimSet;
1341 dimSet.push_back(dim);
1342 SmallVector<int64_t> adjustDims =
1343 mapSlicedDimsToParentSpace(dimSet, sliceDims);
1344 return SliceAttr::get(
1345 getContext(),
1346 parent.setDimData(adjustDims[0], sgData, instData, laneData), getDims());
1347}
1348
1349// Derive a new layout by removing dimensions. `dimGroup` specifies a group of
1350// dimensions to be removed in the derived layout.
1351//
1352// Example: drop the 2nd dimension from a rank-3 sliced view.
1353//
1354// Suppose:
1355// xegpu.layout = slice<layout<[V0, V1, V2, V3, V4]>, [1, 3]>
1356//
1357// The slice removes parent dims [1, 3], so the sliced-space dims map to
1358// parent dims [V0, V2, V4].
1359//
1360// If we drop sliced-space dim 1 (the 2nd dim), that corresponds to dropping
1361// parent dim 2, result in parent layout [V0, V1, V3, V4] after dropping.
1362// After parent dim 2 is removed, sliced dims [1, 3] must be reindexed to [1,
1363// 2].
1364//
1365// Result:
1366// xegpu.layout = slice<layout<[0, 1, 3, 4]>, [1, 2]>
1367DistributeLayoutAttr SliceAttr::dropDims(SmallVector<int64_t> dimGroup) {
1368 // Map the sliced dims from parent space to collapsed space
1369 SmallVector<int64_t> sliceDims = llvm::to_vector(getDims().asArrayRef());
1370 SmallVector<int64_t> dimsInParentSpace =
1371 mapSlicedDimsToParentSpace(dimGroup, sliceDims);
1372
1373 auto droppedParent = getParent().dropDims(dimsInParentSpace);
1374
1375 // Adjust the sliced dims after dropping dims in parent space. For example, if
1376 // we drop dim 2 in parent space, the dims after dim 2 will all be shifted by
1377 // 1, so sliced dim 3 will be adjusted to 2.
1378 SmallVector<int64_t> newSliceDims;
1379 for (int64_t d : sliceDims) {
1380 int64_t offset =
1381 llvm::count_if(dimsInParentSpace, [&](int64_t s) { return s < d; });
1382 newSliceDims.push_back(d - offset);
1383 }
1384
1385 return SliceAttr::get(getContext(), droppedParent,
1386 DenseI64ArrayAttr::get(getContext(), newSliceDims));
1387}
1388
1389// Derive a new layout by collapsing dimensions.
1390// `dimGroup` specifies a group of adjacent dimensions
1391// that are collapsed into a single dimension in the derived layout.
1392DistributeLayoutAttr SliceAttr::collapseDims(SmallVector<int64_t> dimGroup) {
1393
1394 // Map the sliced dims from parent space to collapsed space
1395 SmallVector<int64_t> sliceDims = llvm::to_vector(getDims().asArrayRef());
1396 assert("expect sliceDims not being collapsed" &&
1397 llvm::none_of(dimGroup, [&](int64_t dim) {
1398 return llvm::is_contained(sliceDims, dim);
1399 }));
1400 SmallVector<int64_t> dimsInParentSpace =
1401 mapSlicedDimsToParentSpace(dimGroup, sliceDims);
1402
1403 auto collapsedParent = getParent().collapseDims(dimsInParentSpace);
1404 return SliceAttr::get(getContext(), collapsedParent,
1405 DenseI64ArrayAttr::get(getContext(), sliceDims));
1406}
1407
1408// Derive a new layout by expanding a single sliced-space dim into multiple
1409// adjacent dims. The dim is mapped to parent space, the parent layout is
1410// expanded there, and the slice dims that lie past the expanded position
1411// are shifted up by `targetShape.size() - 1`.
1412DistributeLayoutAttr SliceAttr::expandDim(int64_t dim,
1413 ArrayRef<int64_t> targetShape) {
1414 // `dim` is in slice space; map it to parent space (parent dims listed in
1415 // `sliceDims` are removed by the slice, so the mapping always lands on a
1416 // non-sliced parent dim).
1417 ArrayRef<int64_t> sliceDims = getDims().asArrayRef();
1418 SmallVector<int64_t> dimSet = {dim};
1419 SmallVector<int64_t> dimsInParentSpace =
1420 mapSlicedDimsToParentSpace(dimSet, sliceDims);
1421 int64_t parentDim = dimsInParentSpace[0];
1422
1423 auto expandedParent = getParent().expandDim(parentDim, targetShape);
1424
1425 int64_t shift = static_cast<int64_t>(targetShape.size()) - 1;
1426 SmallVector<int64_t> newSliceDims;
1427 newSliceDims.reserve(sliceDims.size());
1428 for (int64_t s : sliceDims)
1429 newSliceDims.push_back(s > parentDim ? s + shift : s);
1430
1431 return SliceAttr::get(getContext(), expandedParent,
1432 DenseI64ArrayAttr::get(getContext(), newSliceDims));
1433}
1434
1436 ArrayRef<int64_t> permutation) {
1437 SmallVector<int64_t> sortedSliceDims = llvm::to_vector(sliceDims);
1438 llvm::sort(sortedSliceDims);
1439
1440 for (size_t i = 1; i < sortedSliceDims.size(); ++i) {
1441 assert((sortedSliceDims[i] == sortedSliceDims[i - 1] + 1) &&
1442 "slice dims non consecutive, cannot be transposed");
1443 }
1444
1445 SmallVector<int64_t> permForParent;
1446 if (sortedSliceDims.front() == 0) {
1447 // Example: sliceDims.size() = 2, permutation= {1, 0}
1448 // result: {3, 2, 1, 0}.
1449 for (int64_t dim : permutation)
1450 permForParent.push_back(dim + sortedSliceDims.size());
1451 for (int64_t i = sortedSliceDims.size() - 1; i >= 0; --i)
1452 permForParent.push_back(i);
1453 } else {
1454 // Example: sliceDims.size() = 2, permutation = {0, 1}
1455 // result: {3, 2, 0, 1}.
1456 for (int64_t i = sortedSliceDims.size() - 1; i >= 0; --i)
1457 permForParent.push_back(i + permutation.size());
1458 for (int64_t dim : permutation)
1459 permForParent.push_back(dim);
1460 }
1461 return permForParent;
1462}
1463
1464// Derive a new layout by transpose the layout using `permutation`.
1465DistributeLayoutAttr SliceAttr::transposeDims(ArrayRef<int64_t> permutation) {
1466 SmallVector<int64_t> sliceDims = llvm::to_vector(getDims().asArrayRef());
1467 DistributeLayoutAttr parent = getParent();
1468 SmallVector<int64_t> permForParent =
1469 getPermForParentLayout(sliceDims, permutation);
1470 auto transposedParent = parent.transposeDims(permForParent);
1471 return SliceAttr::get(getContext(), transposedParent,
1472 DenseI64ArrayAttr::get(getContext(), sliceDims));
1473}
1474
1475/// Check if this layout is a transpose of another layout.
1476bool SliceAttr::isTransposeOf(const xegpu::DistributeLayoutAttr &other,
1477 ArrayRef<int64_t> perm,
1478 const xegpu::LayoutKind kind) {
1479 // other must be a SliceAttr with the same slice dims.
1480 auto otherSlice = dyn_cast<xegpu::SliceAttr>(other);
1481 if (!otherSlice || getDims() != otherSlice.getDims())
1482 return false;
1483 // check whether the parent layout is transpose of each other.
1484 SmallVector<int64_t> sliceDims = llvm::to_vector(getDims().asArrayRef());
1485 DistributeLayoutAttr parent = getParent();
1486 SmallVector<int64_t> permForParent = getPermForParentLayout(sliceDims, perm);
1487 auto otherParent = otherSlice.getParent();
1488 return parent.isTransposeOf(otherParent, permForParent, kind);
1489}
1490
1491//===----------------------------------------------------------------------===//
1492// XeGPU_RangeAttr
1493//===----------------------------------------------------------------------===//
1494
1495LogicalResult
1496RangeAttr::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
1497 IntegerAttr startOfRange, IntegerAttr endOfRange) {
1498 if (startOfRange.getInt() >= endOfRange.getInt())
1499 return emitError() << "'end' : " << endOfRange.getInt()
1500 << " must be greater than 'start' : "
1501 << startOfRange.getInt();
1502
1503 return success();
1504}
1505
1506//===----------------------------------------------------------------------===//
1507// XeGPU_TensorDescType
1508//===----------------------------------------------------------------------===//
1509
1510mlir::Type TensorDescType::parse(AsmParser &parser) {
1511 llvm::SmallVector<int64_t> shape;
1512 mlir::Type elementType;
1513 mlir::FailureOr<mlir::Attribute> encoding;
1514 mlir::FailureOr<mlir::Attribute> layout;
1515
1516 // Parse literal '<'
1517 if (parser.parseLess())
1518 return {};
1519
1520 auto shapeLoc = parser.getCurrentLocation();
1521 if (mlir::failed(parser.parseDimensionList(shape))) {
1522 parser.emitError(shapeLoc, "failed to parse parameter 'shape'");
1523 return {};
1524 }
1525
1526 auto elemTypeLoc = parser.getCurrentLocation();
1527 if (mlir::failed(parser.parseType(elementType))) {
1528 parser.emitError(elemTypeLoc, "failed to parse parameter 'elementType'");
1529 return {};
1530 }
1531
1532 // parse optional attributes
1533 while (mlir::succeeded(parser.parseOptionalComma())) {
1534 mlir::Attribute attr;
1535 ParseResult res = parser.parseAttribute(attr);
1536 if (mlir::succeeded(res)) {
1537 if (mlir::isa<DistributeLayoutAttr>(attr)) {
1538 layout = attr;
1539 continue;
1540 }
1541 if (mlir::isa<BlockTensorDescAttr>(attr)) {
1542 encoding = attr;
1543 continue;
1544 }
1545 }
1546 return {};
1547 }
1548
1549 // Parse literal '>'
1550 if (parser.parseGreater())
1551 return {};
1552
1553 MLIRContext *ctxt = parser.getContext();
1554 return TensorDescType::getChecked(
1555 [&]() { return parser.emitError(parser.getNameLoc()); }, ctxt, shape,
1556 elementType, encoding.value_or(BlockTensorDescAttr::get(ctxt)),
1557 layout.value_or(mlir::Attribute()));
1558}
1559
1560void TensorDescType::print(AsmPrinter &printer) const {
1561 printer << "<";
1562
1563 auto shape = getShape();
1564 for (int64_t dim : shape) {
1565 if (mlir::ShapedType::isDynamic(dim))
1566 printer << '?';
1567 else
1568 printer << dim;
1569 printer << 'x';
1570 }
1571
1572 printer << getElementType();
1573
1574 auto encoding = getEncoding();
1575 auto blockAttr = llvm::dyn_cast_if_present<BlockTensorDescAttr>(encoding);
1576 if (encoding && (!blockAttr || !blockAttr.hasDefaultsOnly()))
1577 printer << ", " << encoding;
1578
1579 if (auto layout = getLayout())
1580 printer << ", " << layout;
1581
1582 printer << ">";
1583}
1584
1585TensorDescType TensorDescType::get(llvm::ArrayRef<int64_t> shape,
1586 mlir::Type elementType, int array_length,
1587 bool boundary_check,
1588 MemorySpace memory_space,
1589 mlir::Attribute layout) {
1590 auto *context = elementType.getContext();
1591 auto attr = BlockTensorDescAttr::get(context, memory_space, array_length,
1592 boundary_check);
1593 return Base::get(context, shape, elementType, attr, layout);
1594}
1595
1596LogicalResult
1597TensorDescType::verify(llvm::function_ref<InFlightDiagnostic()> emitError,
1598 llvm::ArrayRef<int64_t> shape, mlir::Type elementType,
1599 mlir::Attribute encoding, mlir::Attribute layout) {
1600 size_t rank = shape.size();
1601
1602 if (rank == 0)
1603 return emitError() << "expected non-zero rank tensor";
1604
1605 if (mlir::ShapedType::isDynamicShape(shape))
1606 return emitError() << "expected static shape";
1607
1608 auto blockAttr = mlir::dyn_cast_if_present<BlockTensorDescAttr>(encoding);
1609 if (blockAttr) {
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";
1614 }
1615
1616 if (!elementType.isIntOrFloat())
1617 return emitError() << "unsupported element type " << elementType
1618 << ": expected integer or float";
1619
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";
1624
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 "
1630 << layoutAttr;
1631 }
1632 }
1633
1634 return success();
1635}
1636
1637//===----------------------------------------------------------------------===//
1638// XeGPU_MemDescType
1639//===----------------------------------------------------------------------===//
1640mlir::Type MemDescType::parse(AsmParser &parser) {
1641 llvm::SmallVector<int64_t> shape;
1642 mlir::Type elementType;
1643 mlir::FailureOr<MemLayoutAttr> layout;
1644
1645 // Parse literal '<'
1646 if (parser.parseLess())
1647 return {};
1648
1649 auto shapeLoc = parser.getCurrentLocation();
1650 if (mlir::failed(parser.parseDimensionList(shape, false, true))) {
1651 parser.emitError(shapeLoc, "failed to parse parameter 'shape'");
1652 return {};
1653 }
1654
1655 auto elemTypeLoc = parser.getCurrentLocation();
1656 if (mlir::failed(parser.parseType(elementType))) {
1657 parser.emitError(elemTypeLoc, "failed to parse parameter 'elementType'");
1658 return {};
1659 }
1660
1661 // parse optional attributes
1662 if (mlir::succeeded(parser.parseOptionalComma())) {
1663 MemLayoutAttr attr;
1664 ParseResult res = parser.parseAttribute(attr);
1665 if (mlir::failed(res))
1666 return {};
1667 layout = attr;
1668 }
1669
1670 // Parse literal '>'
1671 if (parser.parseGreater())
1672 return {};
1673
1674 MLIRContext *ctxt = parser.getContext();
1675 return MemDescType::getChecked(
1676 [&]() { return parser.emitError(parser.getNameLoc()); }, ctxt, shape,
1677 elementType, layout.value_or(MemLayoutAttr()));
1678}
1679
1680void MemDescType::print(AsmPrinter &printer) const {
1681 printer << "<";
1682
1683 printer.printDimensionList(getShape());
1684 printer << 'x';
1685 printer << getElementType();
1686
1687 if (auto layout = getMemLayout())
1688 printer << ", " << layout;
1689
1690 printer << ">";
1691}
1692
1693//===----------------------------------------------------------------------===//
1694// XeGPU_MemDescType
1695//===----------------------------------------------------------------------===//
1696
1697Attribute MemLayoutAttr::parse(AsmParser &parser, Type type) {
1698
1699 auto *context = parser.getContext();
1700 llvm::SMLoc loc = parser.getCurrentLocation();
1701
1702 llvm::SmallDenseSet<StringRef> seenKeys;
1703 SmallVector<NamedAttribute> attributes;
1704
1705 auto parseElt = [&]() -> ParseResult {
1706 StringRef nameId;
1707 if (failed(parser.parseKeyword(&nameId)))
1708 return parser.emitError(loc, "expected valid attribute name");
1709
1710 if (!seenKeys.insert(nameId).second)
1711 return parser.emitError(loc, "duplicate key '")
1712 << nameId << " in mem layout attribute";
1713
1714 if (failed(parser.parseEqual()))
1715 return failure();
1716
1717 Attribute attr;
1718 if (failed(parser.parseAttribute(attr)))
1719 return failure();
1720 attributes.emplace_back(nameId, attr);
1721 return success();
1722 };
1723
1724 // Parse literal '<'
1725 if (parser.parseLess())
1726 return {};
1727
1728 if (failed(parser.parseCommaSeparatedList(parseElt)))
1729 return {};
1730
1731 // Parse literal '>'
1732 if (parser.parseGreater())
1733 return {};
1734
1735 return parser.getChecked<MemLayoutAttr>(
1736 loc, context, DictionaryAttr::get(context, attributes));
1737}
1738
1739void MemLayoutAttr::print(AsmPrinter &printer) const {
1740 printer << "<";
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)
1745 printer << ", ";
1746 }
1747 printer << ">";
1748}
1749// a helper utility to perform binary operation on OpFoldResult.
1750// If both a and b are attributes, it will simply return the result.
1751// Otherwise, the corresponding arith op will be generated, and an
1752// contant op will be created if one of them is an attribute.
1753template <typename ArithOp>
1755 OpBuilder &builder) {
1756 auto aVal = getValueOrCreateConstantIndexOp(builder, loc, a);
1757 auto bVal = getValueOrCreateConstantIndexOp(builder, loc, b);
1758 return ArithOp::create(builder, loc, aVal, bVal).getResult();
1759}
1760
1761// a helper utility to perform division operation on OpFoldResult and int64_t.
1762#define div(a, b) \
1763 genBinOp<arith::DivSIOp>(a, builder.getIndexAttr(b), loc, builder)
1764
1765// a helper utility to perform reminder operation on OpFoldResult and int64_t.
1766#define rem(a, b) \
1767 genBinOp<arith::RemSIOp>(a, builder.getIndexAttr(b), loc, builder)
1768
1769// a helper utility to perform multiply operation on OpFoldResult and int64_t.
1770#define mul(a, b) \
1771 genBinOp<arith::MulIOp>(a, builder.getIndexAttr(b), loc, builder)
1772
1773// a helper utility to perform addition operation on two OpFoldResult.
1774#define add(a, b) genBinOp<arith::AddIOp>(a, b, loc, builder)
1775
1776// block the given offsets according to the block shape
1777// say the original offset is [y, x], and the block shape is [By, Bx],
1778// then the blocked offset is [y/By, x/Bx, y%By, x%Bx]
1780 ArrayRef<OpFoldResult> offsets,
1781 ArrayRef<int64_t> blockShape) {
1782
1783 assert(offsets.size() == blockShape.size() &&
1784 "offsets and blockShape must have the same size");
1785 SmallVector<OpFoldResult> blockedOffsets;
1786 SmallVector<OpFoldResult> divs, rems;
1787
1788 for (auto [offset, block] : llvm::zip(offsets, blockShape)) {
1789 divs.push_back(div(offset, block));
1790 rems.push_back(rem(offset, block));
1791 }
1792 blockedOffsets.append(divs.begin(), divs.end());
1793 blockedOffsets.append(rems.begin(), rems.end());
1794
1795 return blockedOffsets;
1796}
1797
1798// Get strides as vector of integer for MemDesc.
1799SmallVector<int64_t> MemDescType::getStrideShape() {
1800
1801 SmallVector<int64_t> matrixShape(getShape().begin(), getShape().end());
1802
1803 ArrayAttr strideAttr = getStrideAttr();
1804 SmallVector<int64_t> strides;
1805 for (Attribute attr : strideAttr.getValue()) {
1806 strides.push_back(cast<IntegerAttr>(attr).getInt());
1807 }
1808
1809 SmallVector<int64_t> innerBlkShape = getBlockShape();
1810
1811 // get perm from FCD to LCD
1812 // perm[i] = the dim with i-th smallest stride
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]; });
1816
1817 assert(strides[perm[0]] == 1 && "inner most dim must have stride 1");
1818
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]];
1824
1825 // compute the original matrix shape using the stride info
1826 // and compute the number of blocks in each dimension
1827 // The shape of highest dim can't be derived from stride info,
1828 // but doesn't impact the stride computation for blocked layout.
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]];
1834 }
1835
1836 int64_t innerBlkSize = 1;
1837 for (auto s : innerBlkShape)
1838 innerBlkSize *= s;
1839
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]];
1845 }
1846
1847 // combine the inner and outer strides
1848 SmallVector<int64_t> blockedStrides;
1849 blockedStrides.append(outerBlkStride.begin(), outerBlkStride.end());
1850 blockedStrides.append(innerBlkStride.begin(), innerBlkStride.end());
1851
1852 return blockedStrides;
1853}
1854
1855// Calculate the linear offset using the blocked offsets and stride
1856Value MemDescType::getLinearOffsets(OpBuilder &builder, Location loc,
1857 ArrayRef<OpFoldResult> offsets) {
1858
1859 SmallVector<int64_t> matrixShape(getShape().begin(), getShape().end());
1860 SmallVector<int64_t> blockShape = getBlockShape();
1861 SmallVector<int64_t> strides = getStrideShape();
1862 SmallVector<OpFoldResult> blockedOffsets;
1863
1864 // blockshape equal to matrixshape means no blocking
1865 if (llvm::equal(blockShape, matrixShape)) {
1866 // remove the outer dims from strides
1867 strides.erase(strides.begin(), strides.begin() + matrixShape.size());
1868 } else {
1869 assert(offsets.size() == blockShape.size() &&
1870 "offsets and blockShape must have the same size");
1871 // say the original offset is [y, x], and the block shape is [By, Bx],
1872 // then the blocked offset is [y/By, x/Bx, y%By, x%Bx]
1873
1874 SmallVector<OpFoldResult> divs, rems;
1875
1876 for (auto [offset, block] : llvm::zip(offsets, blockShape)) {
1877 divs.push_back(div(offset, block));
1878 rems.push_back(rem(offset, block));
1879 }
1880 blockedOffsets.append(divs.begin(), divs.end());
1881 blockedOffsets.append(rems.begin(), rems.end());
1882 offsets = blockedOffsets;
1883 }
1884
1885 // Start with initial value as matrix descriptor's base offset.
1886 Value linearOffset = arith::ConstantIndexOp::create(builder, loc, 0);
1887 for (size_t i = 0; i < offsets.size(); ++i) {
1888 OpFoldResult mulResult = mul(offsets[i], strides[i]);
1889 Value mulVal = getValueOrCreateConstantIndexOp(builder, loc, mulResult);
1890 linearOffset = arith::AddIOp::create(builder, loc, mulVal, linearOffset);
1891 }
1892
1893 return linearOffset;
1894}
1895
1896} // namespace xegpu
1897} // namespace mlir
1898
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>
return success()
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
ArrayAttr()
b getContext())
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
Definition SPIRVOps.cpp:230
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition Traits.cpp:117
static Value splice(OpBuilder &b, Location loc, ValueRange values, VectorType regTileType)
#define mul(a, b)
#define div(a, b)
#define rem(a, b)
Attributes are known-constant values of operations.
Definition Attributes.h:25
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...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
This class helps build Operations.
Definition Builders.h:210
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...
Definition Builders.h:528
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.
Definition Types.cpp:35
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Specialization of arith.constant op that returns an integer of index type.
Definition Arith.h:85
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:453
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< int32_t > content)
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
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.
Definition XeGPU.h:31
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.
Definition Utils.cpp:114
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.