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