MLIR 24.0.0git
VectorToXeGPU.cpp
Go to the documentation of this file.
1//===- VectorToXeGPU.cpp - Convert vector to XeGPU dialect ------*- 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// This file implements lowering of vector operations to XeGPU dialect ops.
10//
11//===----------------------------------------------------------------------===//
12
15
26#include "mlir/IR/Matchers.h"
28#include "mlir/Pass/Pass.h"
30#include "llvm/ADT/TypeSwitch.h"
31
32#include <algorithm>
33#include <optional>
34
35namespace mlir {
36#define GEN_PASS_DEF_CONVERTVECTORTOXEGPU
37#include "mlir/Conversion/Passes.h.inc"
38} // namespace mlir
39
40using namespace mlir;
41
42namespace {
43// Return true if value represents a zero constant.
44static bool isZeroConstant(Value val) {
45 auto constant = val.getDefiningOp<arith::ConstantOp>();
46 if (!constant)
47 return false;
48
49 return TypeSwitch<Attribute, bool>(constant.getValue())
50 .Case([](FloatAttr floatAttr) { return floatAttr.getValue().isZero(); })
51 .Case([](IntegerAttr intAttr) { return intAttr.getValue().isZero(); })
52 .Default(false);
53}
54
55// Return true if the transfer padding value is compatible with the implicit
56// padding of an nd block load. LoadNdOp fills out-of-bounds elements with zero,
57// so a zero constant matches its semantics exactly. A poison padding means the
58// out-of-bounds elements are "don't care", so any implicit padding (including
59// zero) is also acceptable.
60static bool isZeroOrPoisonPadding(Value val) {
61 return isZeroConstant(val) || val.getDefiningOp<ub::PoisonOp>();
62}
63
64// Return true if the permutation map keeps every dimension in place except the
65// innermost two, which are swapped, e.g.:
66// (d0, d1) -> (d1, d0)
67// (d0, d1, d2) -> (d2, d1)
68// (d0, d1, d2, d3) -> (d0, d1, d3, d2)
69// This is the only non-identity permutation an nd block load can realize (by
70// loading the untransposed block and applying a trailing vector.transpose).
71static bool isInnermostTwoDimsTransposed(AffineMap map) {
72 unsigned numResults = map.getNumResults();
73 if (numResults < 2)
74 return false;
75 MLIRContext *ctx = map.getContext();
76 unsigned numInputs = map.getNumInputs();
77 // All but the innermost two results must match the minor-identity map.
78 for (unsigned i = 0; i + 2 < numResults; ++i)
79 if (map.getResult(i) != getAffineDimExpr(numInputs - numResults + i, ctx))
80 return false;
81 // The innermost two results must be the last two input dims, swapped.
82 return map.getResult(numResults - 2) ==
83 getAffineDimExpr(numInputs - 1, ctx) &&
84 map.getResult(numResults - 1) == getAffineDimExpr(numInputs - 2, ctx);
85}
86
87// Return true if `uArch` can transfer a `shape`-shaped tile of `elemTy`
88// elements with the subgroup 2D block instruction `instKind`.
89//
90// A 2D block instruction accesses the two innermost dimensions of the tile;
91// leading dimensions are unrolled into a sequence of 2D accesses. The
92// innermost 2D tile does not have to match a hardware block exactly, because
93// the later XeGPU passes (layout propagation and blocking) split it into
94// hardware-sized blocks - but that split only exists when each of the two
95// innermost extents is a multiple of a supported block extent. Transfers
96// without such a split cannot be expressed with block instructions at all and
97// must use a different lowering.
98static bool isSupportedBlockShape(const xegpu::uArch::uArch *uArch,
101 bool hasTranspose = false) {
102 if (shape.size() < 2)
103 return false;
104 if (!uArch || !uArch->isSupportedInstruction(instKind))
105 return false;
106
107 const auto *blockInst = dyn_cast<xegpu::uArch::BlockIOInstructionInterface>(
108 uArch->getInstruction(instKind));
109 if (!blockInst)
110 return false;
111
112 int width = static_cast<int>(shape.back());
113 int height = static_cast<int>(shape[shape.size() - 2]);
114
115 // A tile is accessible when both of its extents are multiples of a supported
116 // block extent, so that the later XeGPU passes can split it into hardware
117 // blocks. A missing entry means this variant does not support the element
118 // type.
119 auto fitsBlockShapes = [&](bool hasTransform) {
120 std::optional<xegpu::uArch::BlockIOInstructionInterface::BlockShapes>
121 blockShapes = blockInst->getBlockWidthHeightCount(elemTy, hasTransform,
122 hasTranspose);
123 if (!blockShapes)
124 return false;
125 auto [widths, heights, counts] = *blockShapes;
126 return xegpu::getLargestDivisor(width, widths) != -1 &&
127 xegpu::getLargestDivisor(height, heights) != -1;
128 };
129
130 // Whether a tile is eventually loaded with the transformed (VNNI) variant is
131 // only decided later, when layout propagation knows whether it feeds the B
132 // operand of a matrix operation, so accept a tile that either variant can
133 // access.
134 return fitsBlockShapes(/*hasTransform=*/false) ||
135 fitsBlockShapes(/*hasTransform=*/true);
136}
137
138static LogicalResult transferPreconditions(PatternRewriter &rewriter,
139 VectorTransferOpInterface xferOp) {
140 if (xferOp.getMask() ||
141 cast<vector::MaskableOpInterface>(xferOp.getOperation()).isMasked())
142 return rewriter.notifyMatchFailure(xferOp,
143 "Masked transfer is not supported");
144
145 auto srcTy = dyn_cast<MemRefType>(xferOp.getShapedType());
146 if (!srcTy)
147 return rewriter.notifyMatchFailure(xferOp, "Expects memref source");
148 if (isa<VectorType>(srcTy.getElementType()))
149 return rewriter.notifyMatchFailure(xferOp,
150 "Expects a memref of scalar elements");
151
152 // Validate further transfer op semantics.
153 SmallVector<int64_t> strides;
154 int64_t offset;
155 if (failed(srcTy.getStridesAndOffset(strides, offset)))
156 return rewriter.notifyMatchFailure(xferOp,
157 "The memref strides cannot be inferred");
158 if (strides.empty())
159 return rewriter.notifyMatchFailure(xferOp, "0D memref is not supported");
160 if (strides.back() != 1)
161 return rewriter.notifyMatchFailure(
162 xferOp, "Buffer must be contiguous in the innermost dimension");
163
164 VectorType vecTy = xferOp.getVectorType();
165 unsigned vecRank = vecTy.getRank();
166 if (vecRank == 0)
167 return rewriter.notifyMatchFailure(xferOp, "0D vectors are not supported");
168
169 AffineMap map = xferOp.getPermutationMap();
170 if (!map.isProjectedPermutation(/*allowZeroInResults=*/true))
171 return rewriter.notifyMatchFailure(xferOp, "Unsupported permutation map");
172 // The transfer is built from a run of innermost source dimensions, as wide as
173 // the vector, with one dimension of slack for a 1D transfer: dropping the
174 // broadcast results of a map like (d1, 0) leaves a rank-1 transfer that still
175 // reads d1, and the scattered path reads along any dimension anyway.
176 unsigned numInputDims = map.getNumInputs();
177 unsigned numAccessibleDims = std::max(vecRank, 2u);
178 unsigned firstAccessibleDim =
179 numInputDims > numAccessibleDims ? numInputDims - numAccessibleDims : 0;
180 for (AffineExpr expr : map.getResults().take_back(vecRank)) {
181 // A broadcast result names no source dimension, so it constrains nothing.
182 auto dim = dyn_cast<AffineDimExpr>(expr);
183 if (!dim)
184 continue;
185 if (dim.getPosition() < firstAccessibleDim)
186 return rewriter.notifyMatchFailure(
187 xferOp, "Only the innermost dimensions can be accessed");
188 }
189
190 return success();
191}
192
193// Returns the memref strides in vector-dimension order: the stride at vector
194// dimension `v` is the stride of the memref dimension the permutation map has
195// `v` read, so that stepping one element along `v` steps that far in memory.
196//
197// Example:
198// For a memref of rank 3 with strides `[s0, s1, s2]` read into a rank-2
199// vector through `(d0, d1, d2) -> (d2, d1)`, the result is `[s2, s1]`.
200//
201static SmallVector<Value> getStridesInVectorOrder(AffineMap permMap,
202 ArrayRef<Value> strides) {
203 return llvm::map_to_vector(permMap.getResults(), [&](AffineExpr expr) {
204 return strides[cast<AffineDimExpr>(expr).getPosition()];
205 });
206}
207
208// Computes memory strides and a memref offset for vector transfer operations,
209// handling both static and dynamic memrefs while applying permutation
210// transformations for XeGPU lowering.
211template <
212 typename OpType,
213 typename = std::enable_if_t<llvm::is_one_of<
214 std::decay_t<OpType>, vector::TransferReadOp, vector::TransferWriteOp,
215 vector::GatherOp, vector::ScatterOp>::value>>
216static std::pair<SmallVector<Value>, Value>
217computeMemrefMeta(OpType xferOp, PatternRewriter &rewriter) {
218 SmallVector<Value> strides;
219 Value baseMemref = xferOp.getBase();
220 MemRefType memrefType = dyn_cast<MemRefType>(baseMemref.getType());
221
222 Location loc = xferOp.getLoc();
223 Value offsetVal = nullptr;
224 if (memrefType.hasStaticShape()) {
225 int64_t offset;
226 SmallVector<int64_t> intStrides;
227 if (failed(memrefType.getStridesAndOffset(intStrides, offset)))
228 return {{}, offsetVal};
229 bool hasDynamicStrides = llvm::any_of(intStrides, [](int64_t strideVal) {
230 return ShapedType::isDynamic(strideVal);
231 });
232
233 if (!hasDynamicStrides)
234 for (int64_t s : intStrides)
235 strides.push_back(arith::ConstantIndexOp::create(rewriter, loc, s));
236
237 if (!ShapedType::isDynamic(offset))
238 offsetVal = arith::ConstantIndexOp::create(rewriter, loc, offset);
239 }
240
241 if (strides.empty() || !offsetVal) {
242 // For dynamic shape memref, use memref.extract_strided_metadata to get
243 // stride values
244 unsigned rank = memrefType.getRank();
245 Type indexType = rewriter.getIndexType();
246
247 // Result types: [base_memref, offset, stride0, stride1, ..., strideN-1,
248 // size0, size1, ..., sizeN-1]
249 SmallVector<Type> resultTypes;
250 resultTypes.push_back(MemRefType::get(
251 {}, memrefType.getElementType())); // base memref (unranked)
252 resultTypes.push_back(indexType); // offset
253
254 for (unsigned i = 0; i < rank; ++i)
255 resultTypes.push_back(indexType); // strides
256
257 for (unsigned i = 0; i < rank; ++i)
258 resultTypes.push_back(indexType); // sizes
259
260 auto meta = memref::ExtractStridedMetadataOp::create(
261 rewriter, loc, resultTypes, baseMemref);
262
263 if (strides.empty())
264 strides.append(meta.getStrides().begin(), meta.getStrides().end());
265
266 if (!offsetVal)
267 offsetVal = meta.getOffset();
268 }
269
270 // Strides are returned in original memref order; permutation is applied in
271 // computeOffsets only where offsets are indexed in vector order.
272 return {strides, offsetVal};
273}
274
275// Adds the transfer's indices to `baseOffset`, the memref's own element offset:
276// the element at `indices` sits at `baseOffset + sum(indices[d] * strides[d])`.
277static Value computeBaseOffset(VectorTransferOpInterface xferOp,
278 PatternRewriter &rewriter,
279 ArrayRef<Value> strides, Value baseOffset) {
280 Location loc = xferOp.getLoc();
281 for (auto [index, stride] : llvm::zip_equal(xferOp.getIndices(), strides)) {
282 Value contrib = arith::MulIOp::create(rewriter, loc, index, stride);
283 baseOffset = arith::AddIOp::create(rewriter, loc, baseOffset, contrib);
284 }
285 return baseOffset;
286}
287
288// This function compute the vectors of localOffsets for scattered load/stores.
289// It is used in the lowering of vector.transfer_read/write to
290// load_gather/store_scatter Example:
291// %0 = vector.transfer_read %expand_shape[%block_id_y, %c0, %c0, %c0, %c0],
292// %cst {in_bounds = [true, true, true, true]}>} :
293// memref<8x4x2x6x32xbf16>, vector<4x2x6x32xbf16>
294//
295// %6 = vector.step: vector<4xindex>
296// %7 = vector.step: vector<2xindex>
297// %8 = vector.step: vector<6xindex>
298// %9 = vector.step: vector<32xindex>
299// %10 = arith.mul %6, 384
300// %11 = arith.mul %7, 192
301// %12 = arith.mul %8, 32
302// %13 = arith.mul %9, 1
303// %14 = vector.shape_cast %10: vector<4xindex> -> vector<4x1x1x1xbf16>
304// %15 = vector.shape_cast %11: vector<2xindex> -> vector<1x2x1x1xbf16>
305// %16 = vector.shape_cast %12: vector<6xindex> -> vector<1x1x6x1xbf16>
306// %17 = vector.shape_cast %13: vector<32xindex> -> vector<1x1x1x32xbf16>
307// %18 = vector.broadcast %14: vector<4x1x1x1xbf16> -> vector<4x2x6x32xindex>
308// %19 = vector.broadcast %15: vector<1x2x1x1xbf16> -> vector<4x2x6x32xindex>
309// %20 = vector.broadcast %16: vector<1x1x6x1xbf16> -> vector<4x2x6x32xindex>
310// %21 = vector.broadcast %17: vector<1x1x1x32xbf16> -> vector<4x2x6x32xindex>
311// %22 = arith.add %18, %19
312// %23 = arith.add %20, %21
313// %local_offsets = arith.add %22, %23
314// %orig_offset = %block_id_y * 4x2x6x32 // consider using affine map
315// %offsets = memref_offset + orig_offset + local_offsets
316static Value computeOffsets(VectorTransferOpInterface xferOp,
317 PatternRewriter &rewriter, ArrayRef<Value> strides,
318 Value baseOffset) {
319 Location loc = xferOp.getLoc();
320 VectorType vectorType = xferOp.getVectorType();
321 ArrayRef<int64_t> vectorShape = vectorType.getShape();
322
323 // Create vector.step operations for each dimension
324 SmallVector<Value> stepVectors;
325 llvm::map_to_vector(vectorShape, [&](int64_t dim) {
326 auto stepType = VectorType::get({dim}, rewriter.getIndexType());
327 auto stepOp = vector::StepOp::create(rewriter, loc, stepType);
328 stepVectors.push_back(stepOp);
329 return stepOp;
330 });
331
332 SmallVector<Value> vectorStrides =
333 getStridesInVectorOrder(xferOp.getPermutationMap(), strides);
334
335 // Multiply step vectors by corresponding strides
336 size_t vectorRank = vectorShape.size();
337 SmallVector<Value> strideMultiplied;
338 for (size_t i = 0; i < vectorRank; ++i) {
339 Value strideValue = vectorStrides[i];
340 auto mulType = dyn_cast<VectorType>(stepVectors[i].getType());
341 auto bcastOp =
342 vector::BroadcastOp::create(rewriter, loc, mulType, strideValue);
343 auto mulOp = arith::MulIOp::create(rewriter, loc, stepVectors[i], bcastOp);
344 strideMultiplied.push_back(mulOp);
345 }
346
347 // Shape cast each multiplied vector to add singleton dimensions
348 SmallVector<Value> shapeCasted;
349 for (size_t i = 0; i < vectorRank; ++i) {
350 SmallVector<int64_t> newShape(vectorRank, 1);
351 newShape[i] = vectorShape[i];
352 auto newType = VectorType::get(newShape, rewriter.getIndexType());
353 auto castOp = vector::ShapeCastOp::create(rewriter, loc, newType,
354 strideMultiplied[i]);
355 shapeCasted.push_back(castOp);
356 }
357
358 // Broadcast each shape-casted vector to full vector shape
359 SmallVector<Value> broadcasted;
360 auto fullIndexVectorType =
361 VectorType::get(vectorShape, rewriter.getIndexType());
362 for (Value shapeCastVal : shapeCasted) {
363 auto broadcastOp = vector::BroadcastOp::create(
364 rewriter, loc, fullIndexVectorType, shapeCastVal);
365 broadcasted.push_back(broadcastOp);
366 }
367
368 // Add all broadcasted vectors together to compute local offsets
369 Value localOffsets = broadcasted[0];
370 for (size_t i = 1; i < broadcasted.size(); ++i)
371 localOffsets =
372 arith::AddIOp::create(rewriter, loc, localOffsets, broadcasted[i]);
373
374 // Broadcast base offset to match vector shape
375 baseOffset = computeBaseOffset(xferOp, rewriter, strides, baseOffset);
376 Value bcastBase = vector::BroadcastOp::create(
377 rewriter, loc, fullIndexVectorType, baseOffset);
378 localOffsets = arith::AddIOp::create(rewriter, loc, bcastBase, localOffsets);
379 return localOffsets;
380}
381
382// Returns the size of memref dimension `dim` as a value.
383static Value getMemrefDimSize(VectorTransferOpInterface xferOp, unsigned dim,
384 PatternRewriter &rewriter) {
385 Location loc = xferOp.getLoc();
386 auto memrefTy = cast<MemRefType>(xferOp.getShapedType());
387 if (memrefTy.isDynamicDim(dim))
388 return memref::DimOp::create(rewriter, loc, xferOp.getBase(), dim)
389 .getResult();
390 return arith::ConstantIndexOp::create(rewriter, loc, memrefTy.getDimSize(dim))
391 .getResult();
392}
393
394// Builds the mask a scattered access needs to stay within the source bounds.
395//
396// The element at vector position `i` along vector dimension `v` accesses memref
397// dimension `d` (the one `v` maps to) at `indices[d] + i`, so it is in bounds
398// iff `i < dim(d) - indices[d]`. Dimensions the transfer declares in-bounds are
399// skipped; non-vector dimensions are always in bounds by the op's contract. The
400// per-dimension masks are spread over the full vector shape and combined, the
401// same way `computeOffsets` spreads the per-dimension offsets.
402//
403// Example, for a `vector<8xf32>` read of a `memref<?xf32>` at `%off`:
404// %dim = memref.dim %src, %c0
405// %limit = arith.subi %dim, %off
406// %step = vector.step : vector<8xindex>
407// %bcast = vector.broadcast %limit : index to vector<8xindex>
408// %mask = arith.cmpi slt, %step, %bcast : vector<8xindex>
409static Value computeInBoundsMask(VectorTransferOpInterface xferOp,
410 PatternRewriter &rewriter) {
411 Location loc = xferOp.getLoc();
412 ArrayRef<int64_t> vectorShape = xferOp.getVectorType().getShape();
413 auto maskType = VectorType::get(vectorShape, rewriter.getI1Type());
414 AffineMap map = xferOp.getPermutationMap();
415 OperandRange indices = xferOp.getIndices();
416
417 Value mask;
418 for (unsigned v = 0, e = vectorShape.size(); v < e; ++v) {
419 if (xferOp.isDimInBounds(v))
420 continue;
421 unsigned d = cast<AffineDimExpr>(map.getResult(v)).getPosition();
422 Value bound = getMemrefDimSize(xferOp, d, rewriter);
423 // A negative limit masks the dimension off entirely, which is what a
424 // starting index past the end of the dimension should do.
425 Value limit = arith::SubIOp::create(rewriter, loc, bound, indices[d]);
426 auto stepType = VectorType::get({vectorShape[v]}, rewriter.getIndexType());
427 Value step = vector::StepOp::create(rewriter, loc, stepType);
428 Value limitVec =
429 vector::BroadcastOp::create(rewriter, loc, stepType, limit);
430 Value dimMask = arith::CmpIOp::create(
431 rewriter, loc, arith::CmpIPredicate::slt, step, limitVec);
432 if (vectorShape.size() > 1) {
433 SmallVector<int64_t> expandedShape(vectorShape.size(), 1);
434 expandedShape[v] = vectorShape[v];
435 dimMask = vector::ShapeCastOp::create(
436 rewriter, loc, VectorType::get(expandedShape, rewriter.getI1Type()),
437 dimMask);
438 dimMask = vector::BroadcastOp::create(rewriter, loc, maskType, dimMask);
439 }
440 mask = mask
441 ? arith::AndIOp::create(rewriter, loc, mask, dimMask).getResult()
442 : dimMask;
443 }
444 if (mask)
445 return mask;
446 return vector::ConstantMaskOp::create(rewriter, loc, maskType, vectorShape);
447}
448
449// Builds that mask as a scalar `i1`, for a transfer of a single element. The
450// element sits at `indices`, so `i < dim(d) - indices[d]` at `i == 0` reduces
451// to `indices[d] < dim(d)`, which needs neither the limit subtraction nor the
452// step vector. The dimensions checked are the same.
453//
454// Example, for a `vector<1xf32>` read of a `memref<?xf32>` at `%off`:
455// %dim = memref.dim %src, %c0
456// %mask = arith.cmpi slt, %off, %dim : index
457static Value computeUnitInBoundsMask(VectorTransferOpInterface xferOp,
458 PatternRewriter &rewriter) {
459 Location loc = xferOp.getLoc();
460 AffineMap map = xferOp.getPermutationMap();
461 OperandRange indices = xferOp.getIndices();
462
463 Value mask;
464 for (unsigned v = 0, e = xferOp.getVectorType().getRank(); v < e; ++v) {
465 if (xferOp.isDimInBounds(v))
466 continue;
467 unsigned d = cast<AffineDimExpr>(map.getResult(v)).getPosition();
468 Value bound = getMemrefDimSize(xferOp, d, rewriter);
469 Value dimMask = arith::CmpIOp::create(
470 rewriter, loc, arith::CmpIPredicate::slt, indices[d], bound);
471 mask = mask
472 ? arith::AndIOp::create(rewriter, loc, mask, dimMask).getResult()
473 : dimMask;
474 }
475 if (mask)
476 return mask;
477 return arith::ConstantOp::create(rewriter, loc, rewriter.getBoolAttr(true));
478}
479
480// Compute the element-wise offsets for vector.gather or vector.scatter ops.
481//
482// This function linearizes the base offsets of the gather/scatter operation
483// and combines them with the per-element indices to produce a final vector of
484// memory offsets.
485template <
486 typename OpType,
487 typename = std::enable_if_t<llvm::is_one_of<
488 std::decay_t<OpType>, vector::GatherOp, vector::ScatterOp>::value>>
489static Value computeOffsets(PatternRewriter &rewriter, OpType gatScatOp,
490 ArrayRef<Value> strides, Value baseOffset) {
491 Location loc = gatScatOp.getLoc();
492 SmallVector<Value> offsets = gatScatOp.getOffsets();
493 for (size_t i = 0; i < offsets.size(); ++i) {
494 Value offsetContrib =
495 arith::MulIOp::create(rewriter, loc, offsets[i], strides[i]);
496 baseOffset =
497 arith::AddIOp::create(rewriter, loc, baseOffset, offsetContrib);
498 }
499 Value indices = gatScatOp.getIndices();
500 VectorType vecType = cast<VectorType>(indices.getType());
501
502 Value strideVector =
503 vector::BroadcastOp::create(rewriter, loc, vecType, strides.back())
504 .getResult();
505 Value stridedIndices =
506 arith::MulIOp::create(rewriter, loc, strideVector, indices).getResult();
507
508 Value baseVector =
509 vector::BroadcastOp::create(
510 rewriter, loc,
511 VectorType::get(vecType.getShape(), rewriter.getIndexType()),
512 baseOffset)
513 .getResult();
514 return arith::AddIOp::create(rewriter, loc, baseVector, stridedIndices)
515 .getResult();
516}
517
518// Collapses shapes of a nD memref to the target rank while applying offsets for
519// the collapsed dimensions. Returns the new memref value and the remaining
520// offsets for the last targetRank dimensions. For example:
521// input: %memref = memref<2x4x8x32xf32>, offsets=[%i0, %i1, %i2, %i3],
522// output: %memref[%i0, %i1, 0, 0] -> memref<8x32xf32>, offsets: [%i2, %i3]
523static std::pair<Value, SmallVector<OpFoldResult>>
524convertMemrefAndOffsetsToTargetRank(PatternRewriter &rewriter, Location loc,
527 int64_t targetRank) {
528 auto memrefType = cast<MemRefType>(memref.getType());
529 unsigned rank = memrefType.getRank();
530
531 if (rank <= targetRank)
532 return {memref, offsets};
533
534 int64_t numCombinedDims = rank - targetRank;
535 SmallVector<OpFoldResult> subviewOffsets;
536 SmallVector<OpFoldResult> subviewSizes;
537 SmallVector<OpFoldResult> subviewStrides;
538
539 // For the combined dimensions: use the provided offsets, size=1, stride=1
540 for (unsigned i = 0; i < numCombinedDims; ++i) {
541 subviewOffsets.push_back(offsets[i]);
542 subviewSizes.push_back(rewriter.getI64IntegerAttr(1));
543 subviewStrides.push_back(rewriter.getI64IntegerAttr(1));
544 }
545
546 // For the last targetRank dimensions: offset=0, use full size, stride=1
547 SmallVector<int64_t> resultShape;
548 auto originalShape = memrefType.getShape();
549 auto meta = memref::ExtractStridedMetadataOp::create(rewriter, loc, memref);
550 for (unsigned i = numCombinedDims; i < rank; ++i) {
551 subviewOffsets.push_back(rewriter.getI64IntegerAttr(0));
552 if (ShapedType::isDynamic(originalShape[i])) {
553 subviewSizes.push_back(meta.getSizes()[i]);
554 resultShape.push_back(ShapedType::kDynamic);
555 } else {
556 subviewSizes.push_back(rewriter.getI64IntegerAttr(originalShape[i]));
557 resultShape.push_back(originalShape[i]);
558 }
559 subviewStrides.push_back(rewriter.getI64IntegerAttr(1));
560 }
561
562 auto resultType = memref::SubViewOp::inferRankReducedResultType(
563 resultShape, memrefType, subviewOffsets, subviewSizes, subviewStrides);
564 auto subviewOp =
565 memref::SubViewOp::create(rewriter, loc, resultType, memref,
566 subviewOffsets, subviewSizes, subviewStrides);
567
568 // Return the remaining offsets for the last targetRank dimensions
569 SmallVector<OpFoldResult> newOffsets(offsets.begin() + numCombinedDims,
570 offsets.end());
571 return {subviewOp.getResult(), newOffsets};
572}
573
574template <
575 typename OpType,
576 typename = std::enable_if_t<llvm::is_one_of<
577 std::decay_t<OpType>, vector::TransferReadOp, vector::TransferWriteOp,
578 vector::GatherOp, vector::ScatterOp>::value>>
579// Convert memref to i64 base pointer
580static Value memrefToIndexPtr(OpType xferOp, PatternRewriter &rewriter) {
581 Location loc = xferOp.getLoc();
582 auto indexPtr = memref::ExtractAlignedPointerAsIndexOp::create(
583 rewriter, loc, xferOp.getBase())
584 .getResult();
585 return arith::IndexCastOp::create(rewriter, loc, rewriter.getI64Type(),
586 indexPtr)
587 .getResult();
588}
589
590// Returns true if every use of `vec` extracts a scalar element from it. An
591// unused value does not qualify.
592static bool isUsedAsScalar(Value vec) {
593 if (vec.use_empty())
594 return false;
595 return llvm::all_of(vec.getUsers(), [](Operation *user) {
596 auto extractOp = dyn_cast<vector::ExtractOp>(user);
597 return extractOp && !isa<VectorType>(extractOp.getResult().getType());
598 });
599}
600
601// Lowers a transfer of a single element to a scalar `xegpu.load`.
602//
603// The transfer touches one location, which its own indices name, so the load
604// takes a scalar offset and a scalar mask - no descriptor, no lane vectors -
605// and the result is broadcast back to the transfer's unit-size vector type.
606//
607// %off = arith.addi %base, %contrib : index
608// %inb = arith.cmpi slt, %idx, %dim : index
609// %val = xegpu.load %src[%off], %inb : i64, index, i1 -> f32
610// %vec = vector.broadcast %val : f32 to vector<1xf32>
611static LogicalResult lowerToScalarLoadOp(vector::TransferReadOp readOp,
612 PatternRewriter &rewriter) {
613 Location loc = readOp.getLoc();
614 VectorType vectorType = readOp.getVectorType();
615 if (!isa<MemRefType>(readOp.getShapedType()))
616 return rewriter.notifyMatchFailure(readOp, "Expected memref source");
617
618 auto meta = computeMemrefMeta(readOp, rewriter);
619 if (meta.first.empty())
620 return rewriter.notifyMatchFailure(readOp, "Failed to compute strides");
621
622 Value offset = computeBaseOffset(readOp, rewriter, meta.first, meta.second);
623 Value flatMemref = memrefToIndexPtr(readOp, rewriter);
624
625 Value mask = computeUnitInBoundsMask(readOp, rewriter);
626 auto loadOp = xegpu::LoadGatherOp::create(
627 rewriter, loc, vectorType.getElementType(), flatMemref, offset, mask,
628 /*l1_hint=*/xegpu::CachePolicyAttr{},
629 /*l2_hint=*/xegpu::CachePolicyAttr{},
630 /*l3_hint=*/xegpu::CachePolicyAttr{},
631 /*layout=*/nullptr, /*contiguity=*/nullptr);
632
633 // A masked-off xegpu.load is unspecified, so the padding has to be applied
634 // explicitly, as in lowerToScatteredLoadOp. A poison padding is "don't care".
635 Value scalar = loadOp.getResult();
636 if (readOp.hasOutOfBoundsDim() &&
637 !readOp.getPadding().getDefiningOp<ub::PoisonOp>())
638 scalar = arith::SelectOp::create(rewriter, loc, mask, scalar,
639 readOp.getPadding());
640
641 rewriter.replaceOpWithNewOp<vector::BroadcastOp>(readOp, vectorType, scalar);
642 return success();
643}
644
645static LogicalResult lowerToScatteredLoadOp(vector::TransferReadOp readOp,
646 PatternRewriter &rewriter) {
647
648 Location loc = readOp.getLoc();
649 VectorType vectorType = readOp.getVectorType();
650 auto memrefType = dyn_cast<MemRefType>(readOp.getShapedType());
651 if (!memrefType)
652 return rewriter.notifyMatchFailure(readOp, "Expected memref source");
653
654 auto meta = computeMemrefMeta(readOp, rewriter);
655 if (meta.first.empty())
656 return rewriter.notifyMatchFailure(readOp, "Failed to compute strides");
657
658 Value localOffsets =
659 computeOffsets(readOp, rewriter, meta.first, meta.second);
660
661 Value flatMemref = memrefToIndexPtr(readOp, rewriter);
662
663 Value mask = computeInBoundsMask(readOp, rewriter);
664 auto gatherOp = xegpu::LoadGatherOp::create(
665 rewriter, loc, vectorType, flatMemref, localOffsets, mask,
666 /*l1_hint=*/xegpu::CachePolicyAttr{},
667 /*l2_hint=*/xegpu::CachePolicyAttr{},
668 /*l3_hint=*/xegpu::CachePolicyAttr{},
669 /*layout=*/nullptr, /*contiguity=*/nullptr);
670
671 // The masked-off lanes of an xegpu.load are unspecified, so the transfer's
672 // padding has to be applied explicitly. A poison padding leaves them "don't
673 // care", so the select can be skipped.
674 Value result = gatherOp.getResult();
675 if (readOp.hasOutOfBoundsDim() &&
676 !readOp.getPadding().getDefiningOp<ub::PoisonOp>()) {
677 Value padding = vector::BroadcastOp::create(rewriter, loc, vectorType,
678 readOp.getPadding());
679 result = arith::SelectOp::create(rewriter, loc, mask, result, padding);
680 }
681
682 rewriter.replaceOp(readOp, result);
683 return success();
684}
685
686// An nd block load fetches a 2D block, which a 1D transfer does not ask for -
687// but a leading unit dimension gives it one:
688//
689// %v = vector.transfer_read %src[%i0, %i1] : memref<32x64xf32>, vector<8xf32>
690// becomes
691// %b = vector.transfer_read %src[%i0, %i1]
692// : memref<32x64xf32>, vector<1x8xf32>
693// %v = vector.shape_cast %b : vector<1x8xf32> to vector<8xf32>
694//
695// Only a transfer running along the innermost source dimension qualifies. That
696// dimension is contiguous, which transferPreconditions has already checked, so
697// the <1xN> block it asks for is one the hardware can fetch. A transfer along
698// any other dimension would need the unit dimension on the other side, and a
699// <Nx1> block is not a shape the layouts downstream can distribute - the
700// scattered path is the one that fits it.
701static LogicalResult lowerToUnitDimRead(vector::TransferReadOp readOp,
702 PatternRewriter &rewriter) {
703 VectorType vecTy = readOp.getVectorType();
704 AffineMap map = readOp.getPermutationMap();
705 int64_t numInputs = map.getNumInputs();
706 int64_t pos = cast<AffineDimExpr>(map.getResult(0)).getPosition();
707 if (numInputs < 2 || pos != numInputs - 1)
708 return rewriter.notifyMatchFailure(
709 readOp, "1D transfer does not run along the innermost dimension");
710
711 Value block = vector::TransferReadOp::create(
712 rewriter, readOp.getLoc(),
713 VectorType::get({1, vecTy.getDimSize(0)}, vecTy.getElementType()),
714 readOp.getBase(), readOp.getIndices(),
715 AffineMapAttr::get(
716 AffineMap::getMinorIdentityMap(numInputs, 2, map.getContext())),
717 readOp.getPadding(), /*mask=*/Value(),
718 rewriter.getBoolArrayAttr({true, readOp.isDimInBounds(0)}));
719
720 rewriter.replaceOpWithNewOp<vector::ShapeCastOp>(readOp, vecTy, block);
721 return success();
722}
723
724// Lowers a transfer whose permutation map broadcasts some of the vector
725// dimensions into a transfer of just the data in memory - the map with its
726// broadcast results dropped - plus the vector ops that expand it back:
727//
728// %r = vector.transfer_read %src[%i0, %i1, %i2], %pad
729// {permutation_map = affine_map<(d0, d1, d2) -> (d2, 0)>,
730// in_bounds = [false, false]} : memref<256x32x512xf16>, vector<64x64xf16>
731// becomes
732// %v = vector.transfer_read %src[%i0, %i1, %i2], %pad
733// {permutation_map = affine_map<(d0, d1, d2) -> (d2)>,
734// in_bounds = [false]} : memref<256x32x512xf16>, vector<64xf16>
735// %c = vector.shape_cast %v : vector<64xf16> to vector<1x64xf16>
736// %t = vector.transpose %c, [1, 0] : vector<1x64xf16> to vector<64x1xf16>
737// %r = vector.broadcast %t : vector<64x1xf16> to vector<64x64xf16>
738//
739// A broadcast result names no source dimension, so only the dimensions the map
740// does name hold data; dropping the rest leaves the transfer that reads it, at
741// the extents and bounds checks those dimensions had. The dropped results come
742// back as unit dimensions, which the transpose moves to the positions those
743// results held, and vector.broadcast stretches to their final extents.
744static LogicalResult lowerBroadcastRead(vector::TransferReadOp readOp,
745 PatternRewriter &rewriter) {
746 Location loc = readOp.getLoc();
747 VectorType vecTy = readOp.getVectorType();
748 ArrayRef<int64_t> vecShape = vecTy.getShape();
749 AffineMap map = readOp.getPermutationMap();
750 int64_t vecRank = vecTy.getRank();
751
752 SmallVector<int64_t> dataPos, bcastPos;
753 for (int64_t i = 0; i < vecRank; ++i) {
754 if (isa<AffineDimExpr>(map.getResult(i)))
755 dataPos.push_back(i);
756 else
757 bcastPos.push_back(i);
758 }
759
760 SmallVector<AffineExpr> readExprs;
761 SmallVector<int64_t> readShape;
762 SmallVector<bool> readInBounds;
763 for (int64_t i : dataPos) {
764 readExprs.push_back(map.getResult(i));
765 readShape.push_back(vecShape[i]);
766 readInBounds.push_back(readOp.isDimInBounds(i));
767 }
768 // An all-broadcast map leaves no data dimension to read. Read one element of
769 // the innermost source dimension instead - a 0D transfer is not supported,
770 // and one element is all the data such a transfer holds.
771 if (readExprs.empty()) {
772 readExprs.push_back(rewriter.getAffineDimExpr(map.getNumInputs() - 1));
773 readShape.push_back(1);
774 readInBounds.push_back(true);
775 }
776
777 auto readTy = VectorType::get(readShape, vecTy.getElementType());
778 Value read = vector::TransferReadOp::create(
779 rewriter, loc, readTy, readOp.getBase(), readOp.getIndices(),
780 AffineMapAttr::get(
781 AffineMap::get(map.getNumInputs(), 0, readExprs, map.getContext())),
782 readOp.getPadding(), /*mask=*/Value(),
783 rewriter.getBoolArrayAttr(readInBounds));
784
785 // Grow the transfer back to the requested rank, one unit dimension per
786 // dropped result. The shape_cast adds them innermost, where they leave the
787 // dimension the data came in on innermost too, and the transpose moves them
788 // to the positions their results held. Only unit dimensions move, so the
789 // transpose permutes dimensions without shuffling elements between them.
790 SmallVector<int64_t> order(bcastPos);
791 llvm::append_range(order, dataPos);
792 SmallVector<int64_t> castShape(bcastPos.size(), 1);
793 for (int64_t i : dataPos)
794 castShape.push_back(vecShape[i]);
795 auto castTy = VectorType::get(castShape, vecTy.getElementType());
796 Value cast = castTy == readTy
797 ? read
798 : vector::ShapeCastOp::create(rewriter, loc, castTy, read);
799
800 if (!llvm::is_sorted(order)) {
801 SmallVector<int64_t> perm(vecRank);
802 for (int64_t i = 0; i < vecRank; ++i)
803 perm[order[i]] = i;
804 cast = vector::TransposeOp::create(rewriter, loc, cast, perm);
805 }
806
807 if (cast.getType() == vecTy)
808 rewriter.replaceOp(readOp, cast);
809 else
810 rewriter.replaceOpWithNewOp<vector::BroadcastOp>(readOp, vecTy, cast);
811 return success();
812}
813
814static LogicalResult lowerToScatteredStoreOp(vector::TransferWriteOp writeOp,
815 PatternRewriter &rewriter) {
816
817 Location loc = writeOp.getLoc();
818 auto memrefType = dyn_cast<MemRefType>(writeOp.getShapedType());
819 if (!memrefType)
820 return rewriter.notifyMatchFailure(writeOp, "Expected memref source");
821
822 auto meta = computeMemrefMeta(writeOp, rewriter);
823 if (meta.first.empty())
824 return rewriter.notifyMatchFailure(writeOp, "Failed to compute strides");
825
826 Value localOffsets =
827 computeOffsets(writeOp, rewriter, meta.first, meta.second);
828
829 Value flatMemref = memrefToIndexPtr(writeOp, rewriter);
830
831 // Out-of-bounds elements are simply not stored, so the mask is all this
832 // needs - no counterpart to the read's padding.
833 Value mask = computeInBoundsMask(writeOp, rewriter);
834 xegpu::StoreScatterOp::create(rewriter, loc, writeOp.getVector(), flatMemref,
835 localOffsets, mask,
836 /*l1_hint=*/xegpu::CachePolicyAttr{},
837 /*l2_hint=*/xegpu::CachePolicyAttr{},
838 /*l3_hint=*/xegpu::CachePolicyAttr{},
839 /*layout=*/nullptr, /*contiguity=*/nullptr);
840 rewriter.eraseOp(writeOp);
841 return success();
842}
843
844// Rewrites a transfer_read whose permutation map broadcasts some vector
845// dimensions into a transfer of just the data in memory plus the vector ops
846// that expand it back (see lowerBroadcastRead), so that the conversion
847// patterns only see maps without broadcast results.
848struct LegalizeBroadcastTransferRead
849 : public OpRewritePattern<vector::TransferReadOp> {
850 using Base::Base;
851
852 LogicalResult matchAndRewrite(vector::TransferReadOp readOp,
853 PatternRewriter &rewriter) const override {
854 if (readOp.getPermutationMap().getBroadcastDims().empty())
855 return rewriter.notifyMatchFailure(readOp, "No broadcast dimension");
856 if (failed(transferPreconditions(rewriter, readOp)))
857 return failure();
858 return lowerBroadcastRead(readOp, rewriter);
859 }
860};
861
862// Returns true if the target's 2D block load can fetch the `tileShape` tile of
863// a non-SLM transfer_read: a scalar int/float element type, out-of-bounds
864// padding that matches load_nd's implicit zero padding, and a tile shape the
865// block load can access.
866static bool is2DBlockLoadable(vector::TransferReadOp readOp,
867 ArrayRef<int64_t> tileShape,
868 bool hasTranspose = false) {
869 auto readMemTy = cast<MemRefType>(readOp.getShapedType());
870 if (!readMemTy.getElementType().isIntOrFloat())
871 return false;
872 if (readOp.hasOutOfBoundsDim() && !isZeroOrPoisonPadding(readOp.getPadding()))
873 return false;
874 const xegpu::uArch::uArch *uArch =
875 xegpu::uArch::getUArch(xegpu::getChipStr(readOp).value_or(""));
876 return isSupportedBlockShape(
878 readOp.getVectorType().getElementType(), hasTranspose);
879}
880
881// Gives a 1D transfer_read the leading unit dimension an nd block load needs
882// (see lowerToUnitDimRead). Only worth it where the target's 2D block load can
883// access the resulting <1xN> tile; otherwise TransferReadLowering takes the 1D
884// vector as is on the scattered path.
885struct PromoteTransferReadToUnitDim
886 : public OpRewritePattern<vector::TransferReadOp> {
887 using Base::Base;
888
889 LogicalResult matchAndRewrite(vector::TransferReadOp readOp,
890 PatternRewriter &rewriter) const override {
891 VectorType vecTy = readOp.getVectorType();
892 if (vecTy.getRank() != 1)
893 return rewriter.notifyMatchFailure(readOp, "Not a 1D transfer");
894 // A broadcast map is left to LegalizeBroadcastTransferRead.
895 if (!readOp.getPermutationMap().getBroadcastDims().empty())
896 return rewriter.notifyMatchFailure(readOp, "Broadcast permutation map");
897 if (failed(transferPreconditions(rewriter, readOp)))
898 return failure();
899
900 // SLM reads lower to load_matrix, which takes the 1D vector as is.
901 if (xegpu::XeGPUDialect::isSharedMemory(
902 cast<MemRefType>(readOp.getShapedType())))
903 return rewriter.notifyMatchFailure(readOp, "SLM transfer");
904 // A single element only extracted to a scalar becomes a scalar load.
905 if (vecTy.getNumElements() == 1 && isUsedAsScalar(readOp.getResult()))
906 return rewriter.notifyMatchFailure(readOp, "Used as a scalar");
907 if (!is2DBlockLoadable(readOp, {1, vecTy.getDimSize(0)}))
908 return rewriter.notifyMatchFailure(
909 readOp, "<1xN> tile is not accessible by a 2D block load");
910
911 return lowerToUnitDimRead(readOp, rewriter);
912 }
913};
914
915struct TransferReadLowering : public OpRewritePattern<vector::TransferReadOp> {
916 using Base::Base;
917
918 LogicalResult matchAndRewrite(vector::TransferReadOp readOp,
919 PatternRewriter &rewriter) const override {
920 Location loc = readOp.getLoc();
921
922 if (failed(transferPreconditions(rewriter, readOp)))
923 return failure();
924
925 // Broadcast maps are rewritten away by the transfer_read legalization that
926 // runs ahead of this pattern.
927 if (!readOp.getPermutationMap().getBroadcastDims().empty())
928 return rewriter.notifyMatchFailure(
929 readOp, "Broadcast permutation map must be legalized first");
930
931 auto readMemTy = cast<MemRefType>(readOp.getShapedType());
932 VectorType loadedVecTy = readOp.getVectorType();
933 bool isOutOfBounds = readOp.hasOutOfBoundsDim();
934 // Check if the memref has address space 3 (shared local memory)
935 bool isSharedMemory = xegpu::XeGPUDialect::isSharedMemory(readMemTy);
936 // Handle the SLM case.
937 if (isSharedMemory) {
938 // load_matrix supports 1D and 2D loads from SLM.
939 if (loadedVecTy.getRank() != 1 && loadedVecTy.getRank() != 2)
940 return rewriter.notifyMatchFailure(
941 readOp, "Only 1D and 2D vector loads are supported for SLM");
942 AffineMap readMap = readOp.getPermutationMap();
943 if (!readMap.isMinorIdentity())
944 return rewriter.notifyMatchFailure(
945 readOp,
946 "Non identity transposition is not supported for SLM loads.");
947 // Out of bounds case is not supported for SLM loads.
948 if (isOutOfBounds)
949 return rewriter.notifyMatchFailure(
950 readOp, "Out-of-bounds access is not supported for SLM loads");
951
952 // Create mem_desc for SLM
953 auto memDescType =
954 xegpu::MemDescType::get(rewriter.getContext(), readMemTy.getShape(),
955 readMemTy.getElementType(),
956 /*mem_layout=*/nullptr);
957 auto createMemDescOp = xegpu::CreateMemDescOp::create(
958 rewriter, loc, memDescType, readOp.getBase());
959 // Convert indices to OpFoldResult for LoadMatrixOp
960 SmallVector<OpFoldResult> indices =
961 getAsOpFoldResult(readOp.getIndices());
962 auto loadMatrixOp = xegpu::LoadMatrixOp::create(
963 rewriter, loc, loadedVecTy, createMemDescOp.getResult(), indices,
964 /*layout=*/nullptr);
965
966 rewriter.replaceOp(readOp, loadMatrixOp.getResult());
967 return success();
968 }
969
970 // A transfer of a single element that is only ever extracted to a scalar
971 // becomes a scalar load, at any rank: the vector is a wrapper its consumers
972 // undo, so neither an nd descriptor nor a lane-vector gather buys anything.
973 // A unit-size vector genuinely used as a vector keeps the paths below.
974 if (loadedVecTy.getNumElements() == 1 && isUsedAsScalar(readOp.getResult()))
975 return lowerToScalarLoadOp(readOp, rewriter);
976
977 // An nd block load can realize a minor-identity map directly, or an
978 // innermost-two-dims transpose via a trailing vector.transpose. Any other
979 // permutation (e.g. a mid-vector transpose of a high-dim load) is left to
980 // the scattered path, which permutes strides explicitly.
981 AffineMap readMap = readOp.getPermutationMap();
982 bool isTransposeLoad = isInnermostTwoDimsTransposed(readMap);
983
984 // A block load transfers the tile as it is laid out in memory, so a
985 // transposing read describes a tile whose innermost two dims are swapped.
986 Type elementType = loadedVecTy.getElementType();
987 SmallVector<int64_t> descShape(loadedVecTy.getShape());
988 if (isTransposeLoad) {
989 size_t rank = descShape.size();
990 assert(rank >= 2 && "Transpose requires at least 2 dimensions");
991 std::swap(descShape[rank - 1], descShape[rank - 2]);
992 }
993 // Swapping a unit dimension moves no data - e.g. a <1x64> tile read as
994 // <64x1> - so the tile is loaded as is and the trailing vector.transpose is
995 // only a reshape, with no need for the transposing block load variant.
996 bool needsTransposedBlockLoad = isTransposeLoad &&
997 descShape[descShape.size() - 1] != 1 &&
998 descShape[descShape.size() - 2] != 1;
999
1000 // Prefer an nd block load. It requires a vector of rank >= 2 backed by a
1001 // scalar-element memref, a map the block load can realize, and a tile shape
1002 // the target's 2D block load can access. 1D vectors use the scattered
1003 // xegpu.load path instead, which has a richer interface (e.g. layout
1004 // capabilities). Out-of-bounds reads are allowed as long as the padding
1005 // matches load_nd's implicit zero padding.
1006 bool canLowerToLoadNd =
1007 loadedVecTy.getRank() > 1 &&
1008 (readMap.isMinorIdentity() || isTransposeLoad) &&
1009 is2DBlockLoadable(readOp, descShape,
1010 /*hasTranspose=*/needsTransposedBlockLoad);
1011
1012 if (canLowerToLoadNd) {
1013 // The load produces the memory-ordered tile; the transpose below restores
1014 // the shape the transfer_read asked for.
1015 if (isTransposeLoad)
1016 loadedVecTy = VectorType::get(descShape, elementType);
1017 auto descType = xegpu::TensorDescType::get(
1018 descShape, elementType, /*array_length=*/1,
1019 /*boundary_check=*/isOutOfBounds, xegpu::MemorySpace::Global);
1020 auto [src, indices] = convertMemrefAndOffsetsToTargetRank(
1021 rewriter, loc, readOp.getBase(),
1022 getAsOpFoldResult(readOp.getIndices()), loadedVecTy.getRank());
1023 // By default, no specific caching policy is assigned.
1024 xegpu::CachePolicyAttr hint = nullptr;
1025 xegpu::CreateNdDescOp ndDesc = xegpu::CreateNdDescOp::create(
1026 rewriter, loc, descType, dyn_cast<TypedValue<MemRefType>>(src));
1027
1028 Operation *loadedOp =
1029 xegpu::LoadNdOp::create(rewriter, loc, loadedVecTy, ndDesc, indices,
1030 /*packed=*/nullptr, /*transpose=*/nullptr,
1031 /*l1_hint=*/hint,
1032 /*l2_hint=*/hint, /*l3_hint=*/hint,
1033 /*layout=*/nullptr);
1034 if (isTransposeLoad) {
1035 // Undo the innermost-two-dims swap with a trailing vector.transpose:
1036 // keep the leading dimensions in place and interchange only the last
1037 // two.
1038 int64_t rank = loadedVecTy.getRank();
1039 SmallVector<int64_t> perm(llvm::to_vector(llvm::seq<int64_t>(0, rank)));
1040 std::swap(perm[rank - 1], perm[rank - 2]);
1041 loadedOp = vector::TransposeOp::create(rewriter, loc,
1042 loadedOp->getResult(0), perm);
1043 }
1044 rewriter.replaceOp(readOp, loadedOp);
1045 return success();
1046 }
1047
1048 // Fall back to a scattered load. It supports arbitrary permutations and any
1049 // rank, and masks off the out-of-bounds elements.
1050 return lowerToScatteredLoadOp(readOp, rewriter);
1051 }
1052};
1053
1054struct TransferWriteLowering
1055 : public OpRewritePattern<vector::TransferWriteOp> {
1056 using Base::Base;
1057
1058 LogicalResult matchAndRewrite(vector::TransferWriteOp writeOp,
1059 PatternRewriter &rewriter) const override {
1060 Location loc = writeOp.getLoc();
1061
1062 if (failed(transferPreconditions(rewriter, writeOp)))
1063 return failure();
1064 // Perform common data transfer checks.
1065 VectorType vecTy = writeOp.getVectorType();
1066 auto writeMemTy = cast<MemRefType>(writeOp.getShapedType());
1067 // Check if the memref has address space 3 (shared local memory)
1068 bool isSharedMemory = xegpu::XeGPUDialect::isSharedMemory(writeMemTy);
1069
1070 // For shared local memory (address space 3), use create_mem_desc +
1071 // store_matrix
1072 if (isSharedMemory) {
1073 // store_matrix supports 1D and 2D stores to SLM.
1074 if (vecTy.getRank() != 1 && vecTy.getRank() != 2)
1075 return rewriter.notifyMatchFailure(
1076 writeOp, "Only 1D and 2D vector stores are supported for SLM");
1077 // store_matrix writes the payload along the innermost dimensions of the
1078 // mem_desc, so it cannot express a transposed or strided store, e.g. a
1079 // 1D vector written along a non-innermost dimension.
1080 if (!writeOp.getPermutationMap().isMinorIdentity())
1081 return rewriter.notifyMatchFailure(
1082 writeOp,
1083 "Non identity transposition is not supported for SLM stores.");
1084 // Out of bounds case is not supported for SLM stores.
1085 if (writeOp.hasOutOfBoundsDim())
1086 return rewriter.notifyMatchFailure(
1087 writeOp, "Out-of-bounds access is not supported for SLM stores");
1088 // Create mem_desc for SLM
1089 auto memDescType =
1090 xegpu::MemDescType::get(rewriter.getContext(), writeMemTy.getShape(),
1091 writeMemTy.getElementType(),
1092 /*mem_layout=*/nullptr);
1093
1094 auto createMemDescOp = xegpu::CreateMemDescOp::create(
1095 rewriter, loc, memDescType, writeOp.getBase());
1096
1097 // Convert indices to OpFoldResult for StoreMatrixOp
1098 SmallVector<OpFoldResult> indices =
1099 getAsOpFoldResult(writeOp.getIndices());
1100
1101 xegpu::StoreMatrixOp::create(rewriter, loc, writeOp.getVector(),
1102 createMemDescOp.getResult(), indices,
1103 /*layout=*/nullptr);
1104
1105 rewriter.eraseOp(writeOp);
1106 return success();
1107 }
1108
1109 const xegpu::uArch::uArch *uArch =
1110 xegpu::uArch::getUArch(xegpu::getChipStr(writeOp).value_or(""));
1111
1112 // Prefer an nd block store. It requires a vector of rank >= 2 backed by a
1113 // scalar-element memref, a minor-identity map (block stores have no
1114 // transpose support), and a tile shape the target's 2D block store can
1115 // access. 1D vectors use the scattered xegpu.store path instead, which has
1116 // a richer interface. Out-of-bounds writes are handled by the descriptor's
1117 // boundary check.
1118 AffineMap map = writeOp.getPermutationMap();
1119 bool canLowerToStoreNd =
1120 vecTy.getRank() > 1 && map.isMinorIdentity() &&
1121 writeMemTy.getElementType().isIntOrFloat() &&
1122 isSupportedBlockShape(
1123 uArch, xegpu::uArch::InstructionKind::Subgroup2DBlockStore,
1124 vecTy.getShape(), vecTy.getElementType());
1125
1126 if (canLowerToStoreNd) {
1127 auto [src, indices] = convertMemrefAndOffsetsToTargetRank(
1128 rewriter, loc, writeOp.getBase(),
1129 getAsOpFoldResult(writeOp.getIndices()), vecTy.getRank());
1130
1131 auto descType = xegpu::TensorDescType::get(
1132 vecTy.getShape(), vecTy.getElementType(),
1133 /*array_length=*/1, /*boundary_check=*/writeOp.hasOutOfBoundsDim(),
1134 xegpu::MemorySpace::Global);
1135 // By default, no specific caching policy is assigned.
1136 xegpu::CachePolicyAttr hint = nullptr;
1137 xegpu::CreateNdDescOp ndDesc = xegpu::CreateNdDescOp::create(
1138 rewriter, loc, descType, dyn_cast<TypedValue<MemRefType>>(src));
1139
1140 auto storeOp = xegpu::StoreNdOp::create(
1141 rewriter, loc, writeOp.getVector(), ndDesc, indices,
1142 /*l1_hint=*/hint,
1143 /*l2_hint=*/hint, /*l3_hint=*/hint,
1144 /*layout=*/nullptr);
1145 rewriter.replaceOp(writeOp, storeOp);
1146 return success();
1147 }
1148
1149 // Fall back to a scattered store. It supports arbitrary permutations and
1150 // any rank, and masks off the out-of-bounds elements.
1151 return lowerToScatteredStoreOp(writeOp, rewriter);
1152 }
1153};
1154
1155struct GatherLowering : public OpRewritePattern<vector::GatherOp> {
1156 using Base::Base;
1157
1158 LogicalResult matchAndRewrite(vector::GatherOp gatherOp,
1159 PatternRewriter &rewriter) const override {
1160 auto srcTy = dyn_cast<MemRefType>(gatherOp.getBase().getType());
1161 if (!srcTy)
1162 return rewriter.notifyMatchFailure(gatherOp, "Expects memref source");
1163
1164 if (gatherOp.getVectorType().isScalable())
1165 return rewriter.notifyMatchFailure(gatherOp,
1166 "Scalable vectors are not supported");
1167
1168 Location loc = gatherOp.getLoc();
1169 VectorType vectorType = gatherOp.getVectorType();
1170
1171 auto meta = computeMemrefMeta(gatherOp, rewriter);
1172 if (meta.first.empty())
1173 return rewriter.notifyMatchFailure(gatherOp, "Failed to compute strides");
1174
1175 Value localOffsets =
1176 computeOffsets(rewriter, gatherOp, meta.first, meta.second);
1177 Value flatMemref = memrefToIndexPtr(gatherOp, rewriter);
1178
1179 auto xeGatherOp = xegpu::LoadGatherOp::create(
1180 rewriter, loc, vectorType, flatMemref, localOffsets, gatherOp.getMask(),
1181 /*l1_hint=*/xegpu::CachePolicyAttr{},
1182 /*l2_hint=*/xegpu::CachePolicyAttr{},
1183 /*l3_hint=*/xegpu::CachePolicyAttr{},
1184 /*layout=*/nullptr, /*contiguity=*/nullptr);
1185
1186 auto selectOp =
1187 arith::SelectOp::create(rewriter, loc, gatherOp.getMask(),
1188 xeGatherOp.getResult(), gatherOp.getPassThru());
1189 rewriter.replaceOp(gatherOp, selectOp.getResult());
1190 return success();
1191 }
1192};
1193
1194struct ScatterLowering : public OpRewritePattern<vector::ScatterOp> {
1195 using Base::Base;
1196
1197 LogicalResult matchAndRewrite(vector::ScatterOp scatterOp,
1198 PatternRewriter &rewriter) const override {
1199 auto srcTy = dyn_cast<MemRefType>(scatterOp.getBase().getType());
1200 if (!srcTy)
1201 return rewriter.notifyMatchFailure(scatterOp, "Expects memref source");
1202
1203 if (scatterOp.getVectorType().isScalable())
1204 return rewriter.notifyMatchFailure(scatterOp,
1205 "Scalable vectors are not supported");
1206
1207 Location loc = scatterOp.getLoc();
1208 auto meta = computeMemrefMeta(scatterOp, rewriter);
1209 if (meta.first.empty())
1210 return rewriter.notifyMatchFailure(scatterOp,
1211 "Failed to compute strides");
1212
1213 Value localOffsets =
1214 computeOffsets(rewriter, scatterOp, meta.first, meta.second);
1215 Value flatMemref = memrefToIndexPtr(scatterOp, rewriter);
1216
1217 xegpu::StoreScatterOp::create(rewriter, loc, scatterOp.getValueToStore(),
1218 flatMemref, localOffsets, scatterOp.getMask(),
1219 /*l1_hint=*/xegpu::CachePolicyAttr{},
1220 /*l2_hint=*/xegpu::CachePolicyAttr{},
1221 /*l3_hint=*/xegpu::CachePolicyAttr{},
1222 /*layout=*/nullptr,
1223 /*contiguity=*/nullptr);
1224 rewriter.eraseOp(scatterOp);
1225 return success();
1226 }
1227};
1228
1229struct LoadLowering : public OpRewritePattern<vector::LoadOp> {
1230 using Base::Base;
1231
1232 LogicalResult matchAndRewrite(vector::LoadOp loadOp,
1233 PatternRewriter &rewriter) const override {
1234 Location loc = loadOp.getLoc();
1235
1236 VectorType vecTy = loadOp.getResult().getType();
1237 MemRefType memTy = loadOp.getBase().getType();
1238 // The plain vector.load lowering only supports 1D/2D block loads.
1239 if (vecTy.getRank() != 1 && vecTy.getRank() != 2)
1240 return rewriter.notifyMatchFailure(loadOp, "Expects 1D or 2D vector");
1241 if (!memTy.getElementType().isIntOrFloat())
1242 return rewriter.notifyMatchFailure(
1243 loadOp, "Unsupported memref element type: expected integer or float");
1244
1245 // Boundary check is available only for block instructions.
1246 bool boundaryCheck = vecTy.getRank() > 1;
1247 // By default, no specific caching policy is assigned.
1248 xegpu::CachePolicyAttr hint = nullptr;
1249
1250 auto [src, indices] = convertMemrefAndOffsetsToTargetRank(
1251 rewriter, loc, loadOp.getBase(), getAsOpFoldResult(loadOp.getIndices()),
1252 vecTy.getRank());
1253
1254 auto descType = xegpu::TensorDescType::get(
1255 vecTy.getShape(), vecTy.getElementType(), /*array_length=*/1,
1256 boundaryCheck, xegpu::MemorySpace::Global);
1257
1258 xegpu::CreateNdDescOp ndDesc = xegpu::CreateNdDescOp::create(
1259 rewriter, loc, descType, dyn_cast<TypedValue<MemRefType>>(src));
1260 auto loadNdOp =
1261 xegpu::LoadNdOp::create(rewriter, loc, vecTy, ndDesc, indices,
1262 /*packed=*/nullptr, /*transpose=*/nullptr,
1263 /*l1_hint=*/hint,
1264 /*l2_hint=*/hint, /*l3_hint=*/hint,
1265 /*layout=*/nullptr);
1266 rewriter.replaceOp(loadOp, loadNdOp);
1267
1268 return success();
1269 }
1270};
1271
1272struct StoreLowering : public OpRewritePattern<vector::StoreOp> {
1273 using Base::Base;
1274
1275 LogicalResult matchAndRewrite(vector::StoreOp storeOp,
1276 PatternRewriter &rewriter) const override {
1277 Location loc = storeOp.getLoc();
1278
1279 TypedValue<VectorType> vector = storeOp.getValueToStore();
1280 VectorType vecTy = vector.getType();
1281 MemRefType memTy = storeOp.getBase().getType();
1282 // The plain vector.store lowering only supports 1D/2D block stores.
1283 if (vecTy.getRank() != 1 && vecTy.getRank() != 2)
1284 return rewriter.notifyMatchFailure(storeOp, "Expects 1D or 2D vector");
1285 if (!memTy.getElementType().isIntOrFloat())
1286 return rewriter.notifyMatchFailure(
1287 storeOp,
1288 "Unsupported memref element type: expected integer or float");
1289
1290 // Boundary check is available only for block instructions.
1291 bool boundaryCheck = vecTy.getRank() > 1;
1292
1293 auto [src, indices] = convertMemrefAndOffsetsToTargetRank(
1294 rewriter, loc, storeOp.getBase(),
1295 getAsOpFoldResult(storeOp.getIndices()), vecTy.getRank());
1296
1297 auto descType = xegpu::TensorDescType::get(
1298 vecTy.getShape(), vecTy.getElementType(),
1299 /*array_length=*/1, boundaryCheck, xegpu::MemorySpace::Global);
1300
1301 // By default, no specific caching policy is assigned.
1302 xegpu::CachePolicyAttr hint = nullptr;
1303 xegpu::CreateNdDescOp ndDesc = xegpu::CreateNdDescOp::create(
1304 rewriter, loc, descType, dyn_cast<TypedValue<MemRefType>>(src));
1305
1306 auto storeNdOp =
1307 xegpu::StoreNdOp::create(rewriter, loc, vector, ndDesc, indices,
1308 /*l1_hint=*/hint,
1309 /*l2_hint=*/hint, /*l3_hint=*/hint,
1310 /*layout=*/nullptr);
1311
1312 rewriter.replaceOp(storeOp, storeNdOp);
1313
1314 return success();
1315 }
1316};
1317
1318// If `indexingMaps` describe a (batched) row-major matmul
1319// lhs[b..., m, k], rhs[b..., k, n], acc[b..., m, n]
1320// return the number of leading batch dims (0 for a plain 2D matmul);
1321// otherwise return std::nullopt.
1322static std::optional<int64_t>
1323getRowMajorMatmulBatchRank(ArrayAttr indexingMaps) {
1324 if (indexingMaps.size() != 3)
1325 return std::nullopt;
1326
1327 AffineMap mapA = cast<AffineMapAttr>(indexingMaps[0]).getValue();
1328 AffineMap mapB = cast<AffineMapAttr>(indexingMaps[1]).getValue();
1329 AffineMap mapC = cast<AffineMapAttr>(indexingMaps[2]).getValue();
1330
1331 // The result map exposes the batch dims followed by the core (m, n) dims.
1332 if (mapC.getNumResults() < 2)
1333 return std::nullopt;
1334 int64_t batchRank = mapC.getNumResults() - 2;
1335
1336 // A single `k` reduction gives batchRank + 3 iteration dims; each operand
1337 // map exposes batchRank + 2 dims (batch dims + 2 core dims).
1338 unsigned numDims = static_cast<unsigned>(batchRank) + 3;
1339 unsigned numOperandResults = static_cast<unsigned>(batchRank) + 2;
1340 if (mapA.getNumInputs() != numDims || mapB.getNumInputs() != numDims ||
1341 mapC.getNumInputs() != numDims)
1342 return std::nullopt;
1343 if (mapA.getNumResults() != numOperandResults ||
1344 mapB.getNumResults() != numOperandResults)
1345 return std::nullopt;
1346
1347 // Reconstruct the canonical maps from the batch/m/n dims of the result and
1348 // the k dim of lhs, then compare against the actual maps.
1349 MLIRContext *context = indexingMaps.getContext();
1350 ArrayRef<AffineExpr> batchDims = mapC.getResults().take_front(batchRank);
1351 AffineExpr m = mapC.getResult(batchRank);
1352 AffineExpr n = mapC.getResult(batchRank + 1);
1353 AffineExpr k = mapA.getResult(batchRank + 1);
1354
1355 SmallVector<AffineExpr> aDims = llvm::to_vector(batchDims);
1356 aDims.push_back(m);
1357 aDims.push_back(k);
1358 SmallVector<AffineExpr> bDims = llvm::to_vector(batchDims);
1359 bDims.push_back(k);
1360 bDims.push_back(n);
1361 SmallVector<AffineExpr> cDims = llvm::to_vector(batchDims);
1362 cDims.push_back(m);
1363 cDims.push_back(n);
1364
1365 auto expected = ArrayAttr::get(
1366 context,
1367 {AffineMapAttr::get(AffineMap::get(numDims, 0, aDims, context)),
1368 AffineMapAttr::get(AffineMap::get(numDims, 0, bDims, context)),
1369 AffineMapAttr::get(AffineMap::get(numDims, 0, cDims, context))});
1370 if (indexingMaps != expected)
1371 return std::nullopt;
1372 return batchRank;
1373}
1374
1375struct ContractionLowering : public vector::AddContractionOpRewritePattern {
1376 using Base::Base;
1377
1378 LogicalResult
1379 matchAndRewriteAddContractOp(vector::ContractionOp contractOp,
1380 PatternRewriter &rewriter) const override {
1381 Location loc = contractOp.getLoc();
1382
1383 TypedValue<VectorType> lhs = contractOp.getLhs();
1384 TypedValue<VectorType> rhs = contractOp.getRhs();
1385 TypedValue<Type> acc = contractOp.getAcc();
1386 VectorType accType = dyn_cast<VectorType>(acc.getType());
1387 if (!accType)
1388 return rewriter.notifyMatchFailure(contractOp, "Expects vector acc");
1389
1390 std::optional<int64_t> batchRank =
1391 getRowMajorMatmulBatchRank(contractOp.getIndexingMapsAttr());
1392 if (!batchRank)
1393 return rewriter.notifyMatchFailure(
1394 contractOp,
1395 "Expects a (batched) row-major matmul: leading dims must "
1396 "be batch dims shared by lhs, rhs, and acc; innermost two "
1397 "dims must be (M, K), (K, N), and (M, N)");
1398
1399 // xegpu.dpas operands are limited to 2 batch + 2 core dims.
1400 if (*batchRank > 2)
1401 return rewriter.notifyMatchFailure(contractOp,
1402 "Expects operands of rank 4 or less");
1403
1404 auto dpasOp = xegpu::DpasOp::create(
1405 rewriter, loc, contractOp.getResultType(), lhs, rhs, acc,
1406 /*layout_a=*/nullptr, /*layout_b=*/nullptr, /*layout_cd=*/nullptr);
1407 rewriter.replaceOp(contractOp, dpasOp);
1408
1409 return success();
1410 }
1411};
1412
1413// Returns the `vector.shape_cast` that flattened a value of type `ndType` into
1414// `flat`, if that is how `flat` was produced.
1415static vector::ShapeCastOp getFlattenCast(Value flat, VectorType ndType) {
1416 auto shapeCast = flat.getDefiningOp<vector::ShapeCastOp>();
1417 if (shapeCast && shapeCast.getSourceVectorType() == ndType)
1418 return shapeCast;
1419 return nullptr;
1420}
1421
1422static DenseElementsAttr getDenseConstant(Value flat) {
1423 DenseElementsAttr elements;
1424 if (matchPattern(flat, m_Constant(&elements)))
1425 return elements;
1426 return nullptr;
1427}
1428
1429static vector::BroadcastOp getSplatBroadcast(Value flat) {
1430 auto broadcast = flat.getDefiningOp<vector::BroadcastOp>();
1431 if (broadcast && !isa<VectorType>(broadcast.getSourceType()))
1432 return broadcast;
1433 return nullptr;
1434}
1435
1436// Returns true if the cast `unflatten` creates will fold away, i.e. if `flat`
1437// is a flattening cast, a constant or a splat.
1438static bool canUnflatten(Value flat, VectorType ndType) {
1439 return getFlattenCast(flat, ndType) || getDenseConstant(flat) ||
1440 getSplatBroadcast(flat);
1441}
1442
1443// Reshape `flat` to `ndType`; `canUnflatten` must hold so the cast folds away.
1444static Value unflatten(PatternRewriter &rewriter, Value flat,
1445 VectorType ndType) {
1446 assert(canUnflatten(flat, ndType) && "expected the cast to fold away");
1447 return vector::ShapeCastOp::create(rewriter, flat.getLoc(), ndType, flat);
1448}
1449
1450// Restore the N-D form of a flattened `vector.gather` / `vector.scatter`.
1451//
1452// XeGPU layouts are expressed in terms of the N-D shape of the accessed data,
1453// so a flattened gather/scatter forces layout propagation to reason through the
1454// surrounding `vector.shape_cast` ops. That adds complexity and tends to yield
1455// layouts that lower to unoptimized code.
1456//
1457// Before:
1458// %cst = arith.constant dense<0.0> : vector<8192xbf16>
1459// %fi = vector.shape_cast %idx : vector<128x64xindex> to vector<8192xindex>
1460// %fm = vector.shape_cast %mask : vector<128x64xi1> to vector<8192xi1>
1461// %fr = vector.gather %src[%c0] [%fi], %fm, %cst : memref<?xbf16>,
1462// vector<8192xindex>, vector<8192xi1>, vector<8192xbf16>
1463// into vector<8192xbf16>
1464// %res = vector.shape_cast %fr : vector<8192xbf16> to vector<128x64xbf16>
1465//
1466// After:
1467// %cst = arith.constant dense<0.0> : vector<128x64xbf16>
1468// %res = vector.gather %src[%c0] [%idx], %mask, %cst : memref<?xbf16>,
1469// vector<128x64xindex>, vector<128x64xi1>, vector<128x64xbf16>
1470// into vector<128x64xbf16>
1471template <typename OpTy>
1472struct UnflattenGatherScatter : public OpRewritePattern<OpTy> {
1473 using OpRewritePattern<OpTy>::OpRewritePattern;
1474
1475 LogicalResult matchAndRewrite(OpTy op,
1476 PatternRewriter &rewriter) const override {
1477 constexpr bool isGather = std::is_same_v<OpTy, vector::GatherOp>;
1478
1479 if (!isa<MemRefType>(op.getBase().getType()))
1480 return rewriter.notifyMatchFailure(op, "expects a memref source");
1481
1482 if (op.getIndexVectorType().getRank() != 1)
1483 return rewriter.notifyMatchFailure(op, "index vector is not 1-D");
1484
1485 // The N-D shape comes from the index operand's producer: this only undoes
1486 // a flattening that already happened, it never invents a shape.
1487 auto indexCast =
1488 op.getIndices().template getDefiningOp<vector::ShapeCastOp>();
1489 if (!indexCast || indexCast.getSourceVectorType().getRank() < 2)
1490 return rewriter.notifyMatchFailure(
1491 op, "index vector is not a shape_cast of an N-D vector");
1492 VectorType ndIndexType = indexCast.getSourceVectorType();
1493 VectorType ndMaskType =
1494 ndIndexType.cloneWith(std::nullopt, rewriter.getI1Type());
1495 VectorType ndType = ndIndexType.cloneWith(
1496 std::nullopt, op.getVectorType().getElementType());
1497
1498 // Check everything before creating any IR: a partially applied rewrite
1499 // would leave dead ops behind.
1500 if (!canUnflatten(op.getMask(), ndMaskType))
1501 return rewriter.notifyMatchFailure(op, "cannot un-flatten the mask");
1502
1503 if constexpr (isGather) {
1504 if (!canUnflatten(op.getPassThru(), ndType))
1505 return rewriter.notifyMatchFailure(op,
1506 "cannot un-flatten the pass-thru");
1507
1508 Value mask = unflatten(rewriter, op.getMask(), ndMaskType);
1509 Value passThru = unflatten(rewriter, op.getPassThru(), ndType);
1510 auto ndGather = vector::GatherOp::create(
1511 rewriter, op.getLoc(), ndType, op.getBase(), op.getOffsets(),
1512 indexCast.getSource(), mask, passThru, op.getAlignmentAttr());
1513 ndGather->setDiscardableAttrs(op->getDiscardableAttrDictionary());
1514 rewriter.replaceOpWithNewOp<vector::ShapeCastOp>(op, op.getVectorType(),
1515 ndGather);
1516 } else {
1517 if (!canUnflatten(op.getValueToStore(), ndType))
1518 return rewriter.notifyMatchFailure(
1519 op, "cannot un-flatten the stored value");
1520
1521 Value mask = unflatten(rewriter, op.getMask(), ndMaskType);
1522 Value valueToStore = unflatten(rewriter, op.getValueToStore(), ndType);
1523 // Only operand types change, and this keeps the optional tensor result
1524 // untouched.
1525 rewriter.modifyOpInPlace(op, [&] {
1526 op.getIndicesMutable().assign(indexCast.getSource());
1527 op.getMaskMutable().assign(mask);
1528 op.getValueToStoreMutable().assign(valueToStore);
1529 });
1530 }
1531 return success();
1532 }
1533};
1534
1535// Rewrite a broadcast that is immediately transposed into a shape_cast that
1536// inserts the new dims where they finally belong, followed by a broadcast that
1537// stretches them in place.
1538//
1539// This lets layout propagation give %v the slice dim of the row reduction
1540// that typically produces it (dims = [1] below, not [0]):
1541// #row = #xegpu.layout<lane_layout = [1, 16], lane_data = [1, 1]>
1542// #col = #xegpu.layout<lane_layout = [16, 1], lane_data = [1, 1],
1543// order = [0, 1]>
1544//
1545// Before:
1546// // %v : #xegpu.slice<#col, dims = [0]>
1547// %b = vector.broadcast %v : vector<16xf32> to vector<64x16xf32> // #col
1548// %t = vector.transpose %b, [1, 0]
1549// : vector<64x16xf32> to vector<16x64xf32> // #row
1550//
1551// After:
1552// // %v : #xegpu.slice<#row, dims = [1]>
1553// %c = vector.shape_cast %v : vector<16xf32> to vector<16x1xf32> // #row
1554// %t = vector.broadcast %c
1555// : vector<16x1xf32> to vector<16x64xf32> // #row
1556struct TransposedBroadcastToStretch
1557 : public OpRewritePattern<vector::TransposeOp> {
1558 using OpRewritePattern<vector::TransposeOp>::OpRewritePattern;
1559
1560 LogicalResult matchAndRewrite(vector::TransposeOp op,
1561 PatternRewriter &rewriter) const override {
1562 auto bcast = op.getVector().getDefiningOp<vector::BroadcastOp>();
1563 if (!bcast)
1564 return rewriter.notifyMatchFailure(op, "not transposing a broadcast");
1565
1566 // Scalar sources are left to FoldTransposeBroadcast.
1567 auto srcTy = dyn_cast<VectorType>(bcast.getSourceType());
1568 if (!srcTy || srcTy.getRank() < 1)
1569 return rewriter.notifyMatchFailure(op,
1570 "broadcast source is not a vector");
1571
1572 VectorType bcastTy = bcast.getResultVectorType();
1573 if (srcTy.isScalable() || bcastTy.isScalable())
1574 return rewriter.notifyMatchFailure(op, "scalable vectors");
1575
1576 int64_t srcRank = srcTy.getRank();
1577 int64_t numNewDims = bcastTy.getRank() - srcRank;
1578 if (numNewDims < 1)
1579 return rewriter.notifyMatchFailure(op, "broadcast adds no dims");
1580
1581 // Only a pure prepend; no source dim may be stretched.
1582 if (srcTy.getShape() != bcastTy.getShape().take_back(srcRank))
1583 return rewriter.notifyMatchFailure(op,
1584 "broadcast stretches a source dim");
1585
1586 // Source dims must move to the front and new dims to the back, both in
1587 // order.
1588 ArrayRef<int64_t> perm = op.getPermutation();
1589 for (int64_t i = 0; i < srcRank; ++i)
1590 if (perm[i] != numNewDims + i)
1591 return rewriter.notifyMatchFailure(
1592 op, "source dims do not move to the front in order");
1593 for (int64_t i = 0; i < numNewDims; ++i)
1594 if (perm[srcRank + i] != i)
1595 return rewriter.notifyMatchFailure(
1596 op, "broadcast dims do not stay trailing in order");
1597
1598 // Source shape followed by one unit dim per new dim.
1599 SmallVector<int64_t> castShape(srcTy.getShape());
1600 castShape.append(numNewDims, 1);
1601 auto castTy = VectorType::get(castShape, srcTy.getElementType());
1602
1603 DictionaryAttr attrs = op->getDiscardableAttrDictionary();
1604 auto cast = vector::ShapeCastOp::create(rewriter, op.getLoc(), castTy,
1605 bcast.getSource());
1606 auto stretch = rewriter.replaceOpWithNewOp<vector::BroadcastOp>(
1607 op, op.getResultVectorType(), cast);
1608 stretch->setDiscardableAttrs(attrs);
1609 return success();
1610 }
1611};
1612
1613// Bring the vector ops into a form the conversion patterns lower directly (see
1614// populateVectorToXeGPULegalizationPatterns).
1615static LogicalResult legalizeForVectorToXeGPU(Operation *root) {
1616 RewritePatternSet patterns(root->getContext());
1618 return applyPatternsGreedily(root, std::move(patterns));
1619}
1620
1621// Returns `memrefTy` with its memory space replaced by `newMemSpace`.
1622static MemRefType withMemorySpace(MemRefType memrefTy, Attribute newMemSpace) {
1623 return MemRefType::get(memrefTy.getShape(), memrefTy.getElementType(),
1624 memrefTy.getLayout(), newMemSpace);
1625}
1626
1627// Rewrite every `memref.alloca` not already in shared local memory (SLM) to
1628// be in SLM (address space 3), and propagate the new memory space through
1629// memref-producing aliasing users (e.g. memref.cast, memref.subview,
1630// memref.expand_shape, ...). Consumers that take a memref operand but
1631// produce a non-memref result (e.g. vector.transfer_read, vector.load) are
1632// left untouched: their operand type simply reflects the new memory space.
1633//
1634// This makes `xegpu.load_matrix`/`xegpu.store_matrix` lowering work end-to-end
1635// for IR coming from bufferization, which by default assigns memory space 0/1
1636// to allocations.
1637static void promoteAllocasToSLM(Operation *root) {
1638 MLIRContext *ctx = root->getContext();
1639 Attribute slmAttr = IntegerAttr::get(IntegerType::get(ctx, 64), 3);
1640
1641 // A user is treated as a memref-producing alias (e.g. memref.cast,
1642 // memref.subview, memref.expand_shape, ...) if it is side-effect free and
1643 // produces at least one memref result. This excludes ops like memref.copy
1644 // that have memory effects.
1645 auto isMemrefResultOp = [](Operation *op) {
1646 if (!isMemoryEffectFree(op))
1647 return false;
1648 return llvm::any_of(op->getResultTypes(),
1649 [](Type t) { return isa<MemRefType>(t); });
1650 };
1651
1652 // Update `v`'s type to have SLM memory space, then walk forward through
1653 // memref-producing users and update their result types accordingly.
1654 std::function<void(Value)> propagate = [&](Value v) {
1655 auto memrefTy = dyn_cast<MemRefType>(v.getType());
1656 if (!memrefTy || xegpu::XeGPUDialect::isSharedMemory(memrefTy))
1657 return;
1658 v.setType(withMemorySpace(memrefTy, slmAttr));
1659 for (Operation *user : v.getUsers()) {
1660 if (!isMemrefResultOp(user))
1661 continue;
1662 for (Value result : user->getResults())
1663 propagate(result);
1664 }
1665 };
1666
1668 root->walk([&](memref::AllocaOp op) {
1669 auto memrefTy = dyn_cast<MemRefType>(op.getResult().getType());
1670 if (!memrefTy || xegpu::XeGPUDialect::isSharedMemory(memrefTy))
1671 return;
1672 allocas.push_back(op);
1673 });
1674
1675 for (memref::AllocaOp alloca : allocas) {
1676 OpBuilder builder(alloca);
1677 auto memrefTy = cast<MemRefType>(alloca.getResult().getType());
1678 auto newTy = withMemorySpace(memrefTy, slmAttr);
1679 auto newOp = memref::AllocaOp::create(
1680 builder, alloca.getLoc(), newTy, alloca.getDynamicSizes(),
1681 alloca.getSymbolOperands(), alloca.getAlignmentAttr());
1682 alloca.getResult().replaceAllUsesWith(newOp.getResult());
1683 alloca.erase();
1684 // Propagate the new memory space through memref-producing consumers.
1685 for (Operation *user : newOp.getResult().getUsers()) {
1686 if (!isMemrefResultOp(user))
1687 continue;
1688 for (Value result : user->getResults())
1689 propagate(result);
1690 }
1691 }
1692}
1693
1694struct ConvertVectorToXeGPUPass
1695 : public impl::ConvertVectorToXeGPUBase<ConvertVectorToXeGPUPass> {
1696 void runOnOperation() override {
1697 // Promote local allocations to SLM (address space 3) so that
1698 // load_matrix/store_matrix lowerings have well-typed memref operands.
1699 promoteAllocasToSLM(getOperation());
1700
1701 // Undo any flattening of gather/scatter operands, so that the conversion
1702 // below sees the N-D shape the XeGPU layouts are expressed in, and rewrite
1703 // transfer_reads the conversion patterns cannot lower as they are.
1704 if (failed(legalizeForVectorToXeGPU(getOperation())))
1705 return signalPassFailure();
1706
1707 RewritePatternSet patterns(&getContext());
1710 if (failed(applyPatternsGreedily(getOperation(), std::move(patterns))))
1711 return signalPassFailure();
1712 }
1713};
1714} // namespace
1715
1717 RewritePatternSet &patterns) {
1718 MLIRContext *ctx = patterns.getContext();
1719 patterns
1720 .add<TransferReadLowering, TransferWriteLowering, LoadLowering,
1721 ScatterLowering, GatherLowering, StoreLowering, ContractionLowering>(
1722 ctx);
1723 // Tried ahead of TransferReadLowering, which would otherwise take a 1D
1724 // transfer on the scattered path.
1725 patterns.add<PromoteTransferReadToUnitDim>(ctx, /*benefit=*/2);
1726}
1727
1729 RewritePatternSet &patterns) {
1730 MLIRContext *ctx = patterns.getContext();
1731 // Un-flatten every gather/scatter that was flattened to 1-D operands, so
1732 // that the conversion patterns and the XeGPU layouts downstream of them see
1733 // the N-D shape of the accessed data. The shape_cast canonicalizations clean
1734 // up the casts the un-flattening leaves behind.
1735 patterns.add<UnflattenGatherScatter<vector::GatherOp>,
1736 UnflattenGatherScatter<vector::ScatterOp>,
1737 TransposedBroadcastToStretch>(ctx);
1738 vector::ShapeCastOp::getCanonicalizationPatterns(patterns, ctx);
1739 // Rewrite transfer_reads with a broadcast permutation map into a transfer of
1740 // the data plus the vector ops that expand it.
1741 patterns.add<LegalizeBroadcastTransferRead>(ctx);
1742}
return success()
lhs
ArrayAttr()
b getContext())
static std::optional< VectorShape > vectorShape(Type type)
static Value broadcast(Location loc, Value toBroadcast, unsigned numElements, const TypeConverter &typeConverter, ConversionPatternRewriter &rewriter)
Broadcasts the value to vector with numElements number of elements.
static bool isSharedMemory(MemRefType type)
Return true if this is a shared memory memref type.
Base type for affine expression.
Definition AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
static AffineMap getMinorIdentityMap(unsigned dims, unsigned results, MLIRContext *context)
Returns an identity affine map (d0, ..., dn) -> (dp, ..., dn) on the most minor dimensions.
MLIRContext * getContext() const
bool isMinorIdentity() const
Returns true if this affine map is a minor identity, i.e.
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
bool isProjectedPermutation(bool allowZeroInResults=false) const
Returns true if the AffineMap represents a subset (i.e.
ArrayRef< AffineExpr > getResults() const
unsigned getNumResults() const
unsigned getNumInputs() const
AffineExpr getResult(unsigned idx) const
static AffineMap getPermutationMap(ArrayRef< unsigned > permutation, MLIRContext *context)
Returns an AffineMap representing a permutation.
Attributes are known-constant values of operations.
Definition Attributes.h:25
IntegerType getI64Type()
Definition Builders.cpp:73
IntegerAttr getI64IntegerAttr(int64_t value)
Definition Builders.cpp:120
BoolAttr getBoolAttr(bool value)
Definition Builders.cpp:108
AffineExpr getAffineDimExpr(unsigned position)
Definition Builders.cpp:373
IntegerType getI1Type()
Definition Builders.cpp:61
MLIRContext * getContext() const
Definition Builders.h:56
IndexType getIndexType()
Definition Builders.cpp:59
ArrayAttr getBoolArrayAttr(ArrayRef< bool > values)
Definition Builders.cpp:279
An attribute that represents a reference to a dense vector or tensor object.
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
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:851
user_range getUsers()
Returns a range of all users.
Definition Operation.h:927
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:233
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
bool use_empty() const
Returns true if this value has no uses.
Definition Value.h:208
Type getType() const
Return the type of this value.
Definition Value.h:105
user_range getUsers() const
Definition Value.h:218
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:453
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
const uArch * getUArch(llvm::StringRef archName)
Definition uArchCommon.h:24
int getLargestDivisor(T dim, ArrayRef< T > candidates, ArrayRef< T > candidateMultiples={})
Helper Function to find a proper instruction multiple for the user-supplied sg-level data shape (dive...
std::optional< std::string > getChipStr(Operation *op)
Retrieves the chip string from the XeVM target attribute of the parent GPU module operation.
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
void populateVectorToXeGPULegalizationPatterns(RewritePatternSet &patterns)
Collect a set of patterns that bring vector ops into a form the conversion patterns lower directly: g...
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
LogicalResult applyPatternsGreedily(Region &region, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
Definition Value.h:496
void populateVectorToXeGPUConversionPatterns(RewritePatternSet &patterns)
Collect a set of patterns to convert from the vector to XeGPU ops.
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147
OpFoldResult getAsOpFoldResult(Value val)
Given a value, try to extract a constant Attribute.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
void populatePrepareVectorToMMAPatterns(RewritePatternSet &patterns)
Populate patterns that prepare vector operations for lowering to GPU dialect MMA matrix operations.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
Convenience wrapper for patterns that are only intended for default contractions, i....
bool isSupportedInstruction(InstructionKind instr) const
Definition uArchBase.h:153
const Instruction * getInstruction(InstructionKind instKind) const
Definition uArchBase.h:146