MLIR 24.0.0git
XeGPUWgToSgDistribute.cpp
Go to the documentation of this file.
1//===- XeGPUWgToSgDistribute.cpp - XeGPU Workgroup to Subgroup Pass -------===//
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//===----------------------------------------------------------------------===//
9
25#include "llvm/ADT/SetVector.h"
26#include <optional>
27
28namespace mlir {
29namespace xegpu {
30#define GEN_PASS_DEF_XEGPUWGTOSGDISTRIBUTE
31#include "mlir/Dialect/XeGPU/Transforms/Passes.h.inc"
32} // namespace xegpu
33} // namespace mlir
34
35using namespace mlir;
36
37namespace {
38
39// Retrieve the RangeAttr if it is specified.
40static xegpu::RangeAttr getRangeSpecAttr(Operation *op) {
41 Operation *parent = op->getParentOfType<scf::IfOp>();
42 while (parent) {
43 if (auto attr = llvm::dyn_cast_if_present<xegpu::RangeAttr>(
44 parent->getDiscardableAttr("sg_id_range")))
45 return attr;
46 parent = parent->getParentOfType<scf::IfOp>();
47 }
48 return {};
49}
50
51static std::pair<SmallVector<int64_t>, int>
52getSgShapeAndCount(ArrayRef<int64_t> shape,
53 xegpu::DistributeLayoutAttr layout) {
54 int count = 1;
56 auto distributedShape = layout.computeDistributedShape(
57 SmallVector<int64_t>(shape.begin(), shape.end()));
58 if (failed(distributedShape))
59 return std::make_pair(sgShape, count);
60 auto sgData = layout.getEffectiveSgDataAsInt();
61 count = computeProduct(distributedShape.value()) / computeProduct(sgData);
62 return std::make_pair(sgData, count);
63}
64
65/// Utility helper for deriving a list of offsets for each sub-TensorDescs
66/// or sub-MemDescs to be accessed by current subgroup (sgId) based on the
67/// associated distribute layout attribute, the shape, subgroup id and the
68/// original offsets of the op
69template <typename OpType,
70 typename = std::enable_if_t<llvm::is_one_of<
71 OpType, xegpu::LoadNdOp, xegpu::StoreNdOp, xegpu::PrefetchNdOp,
72 xegpu::LoadMatrixOp, xegpu::StoreMatrixOp>::value>>
73static LogicalResult
74genOffsetsList(ConversionPatternRewriter &rewriter, OpType op,
76 Location loc = op.getLoc();
77 SmallVector<OpFoldResult> origOffsets = op.getMixedOffsets();
78 // not applicable to ops without offsets operands.
79 if (origOffsets.empty())
80 return failure();
81
82 // if op is xegpu::CreateNdDescOp, call op.getDescLayoutAttr()
83 xegpu::DistributeLayoutAttr layout;
84 if constexpr (std::is_same_v<OpType, xegpu::LoadMatrixOp> ||
85 std::is_same_v<OpType, xegpu::StoreMatrixOp>) {
86 layout = op.getLayoutAttr();
87 } else {
88 layout = op.getDescLayoutAttr();
89 }
90
91 // not applicable to ops without workgroup layout attributes
92 if (!layout || !layout.isForWorkgroup())
93 return failure();
94
95 Value sgId =
96 gpu::SubgroupIdOp::create(rewriter, loc, /*upper_bound=*/nullptr);
97
98 // verify and adjust the sgId if the range specifier is present
99 xegpu::RangeAttr sgIdRange = getRangeSpecAttr(op);
100 if (sgIdRange) {
101 int64_t startOfRange = sgIdRange.getStart().getInt();
102 int64_t endOfRange = sgIdRange.getEnd().getInt();
103 // verify the RangeAttr against the layout attribute
104 if (layout.getNumSubgroups() != endOfRange - startOfRange)
105 return rewriter.notifyMatchFailure(
106 op, "sg_layout size must match the sg_id_range");
107 // adjust the sgId if necessary
108 if (startOfRange > 0) {
109 Value startOfRangeVal =
110 arith::ConstantIndexOp::create(rewriter, loc, startOfRange);
111 sgId = index::SubOp::create(rewriter, loc, sgId, startOfRangeVal);
112 }
113 }
114
115 // Compute the list of subgroup-relative offsets for sub-tensors or sub-memory
116 // descriptors to be accessed, based on the layout information.
117 ArrayRef<int64_t> wgShape = op.getDataShape();
118 auto maybeDescOffsets =
119 layout.computeDistributedCoords(rewriter, loc, sgId, wgShape);
120 if (failed(maybeDescOffsets))
121 return failure();
122
123 // Compute the final global offsets for each accessed sub-tensor
124 // or sub-memory descriptor.
125 for (const auto &sgOffsets : *maybeDescOffsets) {
127 rewriter, loc, getAsOpFoldResult(sgOffsets), origOffsets);
128 offsetsList.push_back(std::move(newOffsets));
129 }
130
131 // callback(offsetsList);
132 return success();
133}
134
135/// This pattern transforms the CreateNdDescOp to create a subgroup descriptor
136/// from a workgroup descriptor. It replaces the offsets and sizes with
137/// appropriate values for the subgroup.
138/// It uses round-robin assignment to distribute the work to the subgroups.
139/// Following create_nd_desc operation:
140/// %tdesc = xegpu.create_nd_tdesc %src : memref<24x24xf32>
141/// -> !xegpu.tensor_desc<24x24xf32, #xegpu.layout<sg_layout = [4, 4],
142/// sg_data = [2, 2], lane_layout = [2, 2], lane_data = [1, 1]>>
143/// is converted to 9 subgroup level operations based on the sg_layout &
144/// sg_data:
145/// %tdesc = xegpu.create_nd_tdesc %src : memref<24x24xf32> ->
146/// !xegpu.tensor_desc<2x2xf32, #xegpu.layout<lane_layout = [2, 2],
147/// lane_data = [1, 1]>>
148///
149/// The sg_layout and sg_data attributes are dropped after the pass as they are
150/// no longer needed.
151///
152/// 24x24 matrix distribution example:
153/// sg_layout = [4, 4], sg_data = [2, 2]
154/// Each 8x8 matrix within the 24x24 matrix is called a distribution unit.
155/// dist_unit_shape = [8, 8] --> sg_layout[i] * sg_data[i]
156///
157/// +------------------------+
158/// | 8x8 | 8x8 | 8x8 | <- 3 tiles across
159/// |-----+-----+-----|
160/// | 8x8 | 8x8 | 8x8 | <- 3 tiles down
161/// |-----+-----+-----|
162/// | 8x8 | 8x8 | 8x8 |
163/// +------------------------+
164///
165/// Each 8x8 tile is further subdivided among subgroups:
166/// +------------------------+
167/// | 2x2 2x2 2x2 2x2 | <- 4 subgroups across (each handles 2 columns)
168/// | 2x2 2x2 2x2 2x2 | <- 4 subgroups down (each handles 2 rows)
169/// | 2x2 2x2 2x2 2x2 |
170/// | 2x2 2x2 2x2 2x2 |
171/// +------------------------+
172///
173/// Since the 24x24 matrix is divided into 8x8 distribution units, there will be
174/// 9 distribution units (3x3) in total. Hence the 9 subgroup level operations.
175
176/// The pass currently has entire distribution logic in the WgToSgCreateNdOp
177/// pattern and all the other ops just follow.
178/// TODO: Decouple the distribution logic from WgToSgCreateNdOp for all the
179/// ops in the pass.
180// This pattern transforms the CreateNdDescOp to create a
181// subgroup descriptor from a workgroup descriptor.
182struct WgToSgCreateNdOp : public OpConversionPattern<xegpu::CreateNdDescOp> {
183 using OpConversionPattern<xegpu::CreateNdDescOp>::OpConversionPattern;
184
185 LogicalResult
186 matchAndRewrite(xegpu::CreateNdDescOp op, OneToNOpAdaptor adaptor,
187 ConversionPatternRewriter &rewriter) const override {
188
189 Location loc = op.getLoc();
190 MLIRContext *ctx = op.getContext();
191 xegpu::TensorDescType tdescTy = op.getType();
192 auto layout = dyn_cast<xegpu::DistributeLayoutAttr>(tdescTy.getLayout());
193 if (!layout || !layout.isForWorkgroup())
194 return failure();
195
196 Type elemTy = tdescTy.getElementType();
197 ArrayRef<int64_t> wgShape = tdescTy.getShape();
198
199 SmallVector<int64_t> sgShape;
200 int count;
201 std::tie(sgShape, count) = getSgShapeAndCount(wgShape, layout);
202 xegpu::TensorDescType newTdescTy =
203 xegpu::TensorDescType::get(ctx, sgShape, elemTy, tdescTy.getEncoding(),
204 layout.dropSgLayoutAndData());
205
206 Value src = op.getSource();
207 SmallVector<Value> newCreateNdOps(count);
208 std::generate(newCreateNdOps.begin(), newCreateNdOps.end(), [&]() -> Value {
209 if (isa<MemRefType>(src.getType()))
210 return xegpu::CreateNdDescOp::create(rewriter, loc, newTdescTy,
211 cast<TypedValue<MemRefType>>(src));
212 return xegpu::CreateNdDescOp::create(rewriter, loc, newTdescTy, src,
213 op.getMixedSizes(),
214 op.getMixedStrides());
215 });
216
217 rewriter.replaceOpWithMultiple(op, {newCreateNdOps});
218 return success();
219 }
220};
221
222/// This pattern transforms the LoadNdOp to load subgroup data.
223struct WgToSgLoadNdOp : public OpConversionPattern<xegpu::LoadNdOp> {
224 using OpConversionPattern<xegpu::LoadNdOp>::OpConversionPattern;
225 LogicalResult
226 matchAndRewrite(xegpu::LoadNdOp op, OneToNOpAdaptor adaptor,
227 ConversionPatternRewriter &rewriter) const override {
228
229 SmallVector<SmallVector<OpFoldResult>> offsetsList;
230 if (failed(genOffsetsList(rewriter, op, offsetsList)))
231 return failure();
232
233 xegpu::DistributeLayoutAttr layout = op.getLayoutAttr();
234 if (layout)
235 layout = layout.dropSgLayoutAndData();
236 SmallVector<Value> newOps;
237 for (auto [tdesc, offsets] :
238 llvm::zip(adaptor.getTensorDesc(), offsetsList)) {
239 auto tdescTy = dyn_cast<xegpu::TensorDescType>(tdesc.getType());
240 VectorType newResTy =
241 VectorType::get(tdescTy.getShape(), tdescTy.getElementType());
242 auto newOp = xegpu::LoadNdOp::create(
243 rewriter, op.getLoc(), newResTy, tdesc, offsets,
244 /*packed = */ nullptr, /*transpose = */ nullptr, op.getL1HintAttr(),
245 op.getL2HintAttr(), op.getL3HintAttr(), layout);
246 newOps.push_back(newOp);
247 }
248 rewriter.replaceOpWithMultiple(op, {newOps});
249
250 return success();
251 }
252};
253
254/// This pattern transforms the StoreNdOp to store subgroup data.
255struct WgToSgStoreNdOp : public OpConversionPattern<xegpu::StoreNdOp> {
256 using OpConversionPattern<xegpu::StoreNdOp>::OpConversionPattern;
257 LogicalResult
258 matchAndRewrite(xegpu::StoreNdOp op, OneToNOpAdaptor adaptor,
259 ConversionPatternRewriter &rewriter) const override {
260 SmallVector<SmallVector<OpFoldResult>> offsetsList;
261 if (failed(genOffsetsList(rewriter, op, offsetsList)))
262 return failure();
263
264 xegpu::DistributeLayoutAttr layout = op.getLayoutAttr();
265 if (layout)
266 layout = layout.dropSgLayoutAndData();
267 for (auto [v, tdesc, offsets] :
268 llvm::zip(adaptor.getValue(), adaptor.getTensorDesc(), offsetsList)) {
269 xegpu::StoreNdOp::create(rewriter, op.getLoc(), v, tdesc, offsets,
270 op.getL1HintAttr(), op.getL2HintAttr(),
271 op.getL3HintAttr(), layout);
272 }
273 rewriter.eraseOp(op);
274
275 return success();
276 }
277};
278
279/// This pattern transforms the PrefetchNdOp to prefetch subgroup data.
280struct WgToSgPrefetchNdOp : public OpConversionPattern<xegpu::PrefetchNdOp> {
281 using OpConversionPattern<xegpu::PrefetchNdOp>::OpConversionPattern;
282 LogicalResult
283 matchAndRewrite(xegpu::PrefetchNdOp op, OneToNOpAdaptor adaptor,
284 ConversionPatternRewriter &rewriter) const override {
285 SmallVector<SmallVector<OpFoldResult>> offsetsList;
286 if (failed(genOffsetsList(rewriter, op, offsetsList)))
287 return failure();
288
289 xegpu::DistributeLayoutAttr layout = op.getLayoutAttr();
290 if (layout)
291 layout = layout.dropSgLayoutAndData();
292 for (auto [tdesc, offsets] :
293 llvm::zip(adaptor.getTensorDesc(), offsetsList)) {
294 xegpu::PrefetchNdOp::create(rewriter, op.getLoc(), tdesc, offsets,
295 op.getL1HintAttr(), op.getL2HintAttr(),
296 op.getL3HintAttr(), layout);
297 }
298 rewriter.eraseOp(op);
299
300 return success();
301 }
302};
303
304/// This pattern transforms the DpasOp to work at subgroup level.
305struct WgToSgDpasOp : public OpConversionPattern<xegpu::DpasOp> {
306 using OpConversionPattern<xegpu::DpasOp>::OpConversionPattern;
307 LogicalResult
308 matchAndRewrite(xegpu::DpasOp op, OneToNOpAdaptor adaptor,
309 ConversionPatternRewriter &rewriter) const override {
310 Location loc = op.getLoc();
311 VectorType resultTy = op.getResult().getType();
312 if (resultTy.getRank() < 2)
313 return failure();
314
315 auto layoutCd = op.getLayoutCdAttr();
316 auto layoutA = op.getLayoutAAttr();
317 auto layoutB = op.getLayoutBAttr();
318 if (!layoutCd || !layoutA || !layoutB)
319 return failure();
320 size_t i = 0;
321 SmallVector<Value> newDpasOps;
322 for (auto aVec : adaptor.getLhs()) {
323 for (auto bVec : adaptor.getRhs()) {
324
325 Value tmpC;
326 if (op.getAcc())
327 tmpC = adaptor.getAcc()[i++];
328
329 ArrayRef<int64_t> aVecShape =
330 cast<VectorType>(aVec.getType()).getShape();
331 ArrayRef<int64_t> bVecShape =
332 cast<VectorType>(bVec.getType()).getShape();
333 // Build result shape: batch dims from A + [M, N] from last dims of
334 // A and B.
335 SmallVector<int64_t> resShape(aVecShape.drop_back(2));
336 resShape.push_back(aVecShape[aVecShape.size() - 2]);
337 resShape.push_back(bVecShape[bVecShape.size() - 1]);
338 VectorType resTy = VectorType::get(resShape, resultTy.getElementType());
339 auto newDpasOp = xegpu::DpasOp::create(
340 rewriter, loc, resTy, aVec, bVec, tmpC,
341 /*layout_a=*/nullptr, /*layout_b=*/nullptr, /*layout_cd=*/nullptr);
342 newDpasOp.setLayoutCdAttr(layoutCd.dropSgLayoutAndData());
343 newDpasOp.setLayoutAAttr(layoutA.dropSgLayoutAndData());
344 newDpasOp.setLayoutBAttr(layoutB.dropSgLayoutAndData());
345
346 newDpasOps.push_back(newDpasOp);
347 }
348 }
349 rewriter.replaceOpWithMultiple(op, {newDpasOps});
350 return success();
351 }
352};
353
354/// This pattern transforms the DpasMxOp to work at subgroup level.
355struct WgToSgDpasMxOp : public OpConversionPattern<xegpu::DpasMxOp> {
356 using OpConversionPattern<xegpu::DpasMxOp>::OpConversionPattern;
357 LogicalResult
358 matchAndRewrite(xegpu::DpasMxOp op, OneToNOpAdaptor adaptor,
359 ConversionPatternRewriter &rewriter) const override {
360
361 Location loc = op.getLoc();
362 VectorType resultTy = op.getResult().getType();
363
364 if (resultTy.getRank() < 2)
365 return failure();
366
367 auto layoutCd = op.getLayoutCdAttr();
368 auto layoutA = op.getLayoutAAttr();
369 auto layoutB = op.getLayoutBAttr();
370 auto layoutAScale = op.getLayoutAScaleAttr();
371 auto layoutBScale = op.getLayoutBScaleAttr();
372
373 if (!layoutCd || !layoutA || !layoutB || !layoutAScale || !layoutBScale)
374 return failure();
375
376 size_t index_c = 0;
377 SmallVector<Value> newDpasMxOps;
378 for (auto [index_a, aVec] : llvm::enumerate(adaptor.getA())) {
379 for (auto [index_b, bVec] : llvm::enumerate(adaptor.getB())) {
380 Value accVal = (op.getAcc()) ? adaptor.getAcc()[index_c++] : Value();
381 Value scaleAVal =
382 (op.getScaleA()) ? adaptor.getScaleA()[index_a] : Value();
383 Value scaleBVal =
384 (op.getScaleB()) ? adaptor.getScaleB()[index_b] : Value();
385
386 ArrayRef<int64_t> aVecShape =
387 cast<VectorType>(aVec.getType()).getShape();
388 ArrayRef<int64_t> bVecShape =
389 cast<VectorType>(bVec.getType()).getShape();
390 // Build result shape: batch dims from A + [M, N]
391 SmallVector<int64_t> resShape(aVecShape.drop_back(2));
392 resShape.push_back(aVecShape[aVecShape.size() - 2]);
393 resShape.push_back(bVecShape[bVecShape.size() - 1]);
394 VectorType resTy = VectorType::get(resShape, resultTy.getElementType());
395 auto newDpasMxOp = xegpu::DpasMxOp::create(
396 rewriter, loc, resTy, aVec, bVec, accVal, scaleAVal, scaleBVal,
397 layoutA.dropSgLayoutAndData(), layoutB.dropSgLayoutAndData(),
398 layoutCd.dropSgLayoutAndData(), layoutAScale.dropSgLayoutAndData(),
399 layoutBScale.dropSgLayoutAndData());
400
401 newDpasMxOps.push_back(newDpasMxOp);
402 }
403 }
404 rewriter.replaceOpWithMultiple(op, {newDpasMxOps});
405 return success();
406 }
407};
408
409/// This pattern transforms vector.broadcast ops to work at subgroup level.
410struct WgToSgVectorBroadcastOp
411 : public OpConversionPattern<vector::BroadcastOp> {
412 using OpConversionPattern<vector::BroadcastOp>::OpConversionPattern;
413
414 LogicalResult
415 matchAndRewrite(vector::BroadcastOp op, OneToNOpAdaptor adaptor,
416 ConversionPatternRewriter &rewriter) const override {
417
418 VectorType resultType = op.getResult().getType();
419 ArrayRef<int64_t> wgShape = resultType.getShape();
420
421 xegpu::DistributeLayoutAttr layout =
422 xegpu::getTemporaryLayout(llvm::cast<OpResult>(op.getResult()));
423 if (!layout || !layout.isForWorkgroup())
424 return failure();
425
426 SmallVector<int64_t> sgShape;
427 int count;
428 std::tie(sgShape, count) = getSgShapeAndCount(wgShape, layout);
429 VectorType newResultType =
430 VectorType::get(sgShape, resultType.getElementType());
431
432 SmallVector<Value> newBroadcastOps;
433 auto distSource = adaptor.getOperands().front();
434 int numDistributions = count / distSource.size();
435 for (int i = 0; i < numDistributions; ++i) {
436 for (auto operand : distSource) {
437 auto newBroadcast = vector::BroadcastOp::create(rewriter, op.getLoc(),
438 newResultType, operand);
439
440 newBroadcastOps.push_back(newBroadcast.getResult());
441 }
442 }
443 rewriter.replaceOpWithMultiple(op, {newBroadcastOps});
444 return success();
445 }
446};
447
448// This pattern transforms elementwise ops to work at subgroup level.
449struct WgToSgElementwiseOp : public ConversionPattern {
450 WgToSgElementwiseOp(MLIRContext *ctx)
451 : ConversionPattern(MatchAnyOpTypeTag(), /*benefit=*/1, ctx) {}
452
453 LogicalResult
454 matchAndRewrite(Operation *op, ArrayRef<ValueRange> operands,
455 ConversionPatternRewriter &rewriter) const override {
456 // Only match ops with elementwise trait and single result.
458 return failure();
459
460 auto resultType = dyn_cast<VectorType>(op->getResult(0).getType());
461 assert(resultType && "Expected result to be a VectorType");
462
463 ArrayRef<int64_t> wgShape = resultType.getShape();
464
465 xegpu::DistributeLayoutAttr layout =
466 xegpu::getTemporaryLayout(llvm::cast<OpResult>(op->getResult(0)));
467 if (!layout || !layout.isForWorkgroup())
468 return failure();
469
470 SmallVector<int64_t> sgShape = getSgShapeAndCount(wgShape, layout).first;
471
472 size_t numVariants = operands.empty() ? 0 : operands.front().size();
473
474 if (llvm::any_of(operands, [&](const ValueRange &operandVec) {
475 return operandVec.size() != numVariants;
476 }))
477 return failure();
479 SmallVector<Value> newResults;
480 VectorType newResultType =
481 VectorType::get(sgShape, resultType.getElementType());
483 for (size_t i = 0; i < numVariants; ++i) {
485 for (auto &operandVec : operands)
486 opOperands.push_back(operandVec[i]);
487
488 OperationState state(op->getLoc(), op->getName());
489 state.addOperands(opOperands);
490 state.addTypes(newResultType);
491 state.addAttributes(op->getDiscardableAttrDictionary().getValue());
492 state.propertiesAttr = op->getPropertiesAsAttribute();
493 Operation *newOp = rewriter.create(state);
495 newResults.push_back(newOp->getResult(0));
497
498 rewriter.replaceOpWithMultiple(op, {newResults});
499 return success();
500 }
501};
503// clang-format off
504// Pattern for lowering ConvertLayoutOp based on sg_layout and sg_data.
505// If input_layout and target_layout have identical sg_layout and sg_data,
506// the op is rewritten to a subgroup-level ConvertLayoutOp with these fields
507// dropped. For example:
508// #a = #xegpu.layout<sg_layout = [2, 2], sg_data = [16, 16], inst_data = [16, 16]>
509// #b = #xegpu.layout<sg_layout = [2, 2], sg_data = [16, 16], inst_data = [8, 16]>
510// xegpu.convert_layout %1 <{input_layout = #a, target_layout = #b}> : vector<32x64xf32>
511// becomes:
512// #a = #xegpu.layout<inst_data = [16, 16]>
513// #b = #xegpu.layout<inst_data = [8, 16]>
514// xegpu.convert_layout %1 <{input_layout = #a, target_layout = #b}> : vector<16x16xf32>
515// (vector<16x16xf32> is determined by sg_data = [16, 16])
516//
517// If sg_layout or sg_data differ, SLM is used to redistribute data across subgroups.
518// For example:
519// #a = #xegpu.layout<sg_layout = [1, 4], sg_data = [32, 16], inst_data = [16, 16]>
520// #b = #xegpu.layout<sg_layout = [2, 2], sg_data = [16, 32], inst_data = [8, 16]>
521// xegpu.convert_layout %1 <{input_layout = #a, target_layout = #b}> : vector<32x64xf32>
522// is lowered to:
523// #a = #xegpu.layout<inst_data = [16, 16]>
524// #b = #xegpu.layout<inst_data = [8, 16]>
525// store_matrix %1, %slm <{layout_input_0 = #a}> : vector<32x16>, mem_desc<32x64xf32>
526// %d = load_matrix %slm <{layout_result_0 = #a}> : mem_desc<32x64xf32> -> vector<16x32xf32>
527// xegpu.convert_layout %d <{input_layout = #a, target_layout = #b}> : vector<16x32xf32>
528// clang-format on
529struct WgToSgConvertLayoutOp
530 : public OpConversionPattern<xegpu::ConvertLayoutOp> {
531 using OpConversionPattern<xegpu::ConvertLayoutOp>::OpConversionPattern;
532
533 LogicalResult
534 matchAndRewrite(xegpu::ConvertLayoutOp op, OneToNOpAdaptor adaptor,
535 ConversionPatternRewriter &rewriter) const override {
536 Location loc = op.getLoc();
537 auto inputLayout = op.getEffectiveInputLayout();
538 auto targetLayout = op.getTargetLayout();
539
540 if (!inputLayout || !targetLayout || !inputLayout.isForWorkgroup() ||
541 !targetLayout.isForWorkgroup())
542 return rewriter.notifyMatchFailure(
543 op, "Input and target layouts must have subgroup layout");
544
545 Type resultType = op.getResult().getType();
546 if (resultType.isIntOrFloat()) {
547 rewriter.replaceOp(op, op.getSource());
548 assert(!inputLayout.dropSgLayoutAndData() &&
549 !targetLayout.dropSgLayoutAndData() &&
550 "unexpected layout attributes for scalar type");
551 return success();
552 }
553
554 ArrayRef<int64_t> wgShape = cast<VectorType>(resultType).getShape();
555 SmallVector<int64_t> inputSgLayout =
556 inputLayout.getEffectiveSgLayoutAsInt();
557 SmallVector<int64_t> inputSgData = inputLayout.getEffectiveSgDataAsInt();
558 SmallVector<int64_t> targetSgLayout =
559 targetLayout.getEffectiveSgLayoutAsInt();
560 SmallVector<int64_t> targetSgData = targetLayout.getEffectiveSgDataAsInt();
561
562 // Fast path: if sg_layout and sg_data are identical, no SLM needed
563 SmallVector<int64_t> wgShapeVec(wgShape.begin(), wgShape.end());
564 if (inputLayout.isCompatibleWith(targetLayout, wgShapeVec,
566 inputLayout = inputLayout.dropSgLayoutAndData();
567 targetLayout = targetLayout.dropSgLayoutAndData();
568
569 SmallVector<Value> newOps(adaptor.getSource());
570 if (inputLayout && targetLayout) {
571 for (auto [i, src] : llvm::enumerate(adaptor.getSource())) {
572 auto newOp = xegpu::ConvertLayoutOp::create(
573 rewriter, loc, src.getType(), src, inputLayout, targetLayout);
574 newOps[i] = newOp;
575 }
576 }
577 rewriter.replaceOpWithMultiple(op, {newOps});
578 return success();
579 }
580
581 // SLM path: layouts differ, need cross-subgroup data redistribution
582 Type elemTy = cast<VectorType>(op.getSource().getType()).getElementType();
583
584 SmallVector<int64_t> slmShape = llvm::to_vector(wgShape);
585
586 // Calculate SLM size requirements
587 auto bitWidth = elemTy.getIntOrFloatBitWidth();
588 auto bytesPerElement = bitWidth / 8;
589 auto slmSize = computeProduct(slmShape) * bytesPerElement;
590
591 // Allocate SLM
592 auto slmTy = MemRefType::get({slmSize}, rewriter.getI8Type(), {}, 3);
593 auto slm = memref::AllocaOp::create(rewriter, loc, slmTy);
594
595 auto memDescType = xegpu::MemDescType::get(rewriter.getContext(), slmShape,
596 elemTy, nullptr);
597 auto memDesc =
598 xegpu::CreateMemDescOp::create(rewriter, loc, memDescType, slm);
599
600 auto sgId = gpu::SubgroupIdOp::create(rewriter, loc,
601 rewriter.getIndexType(), nullptr);
602
603 // STORE PHASE: Each subgroup stores in SLM using input layout
604 auto storeCoords = inputLayout.computeDistributedCoords(
605 rewriter, loc, sgId.getResult(), wgShape);
606 if (failed(storeCoords))
607 return failure();
608
609 // Store to SLM
610 for (auto [src, coords] : llvm::zip(adaptor.getSource(), *storeCoords)) {
611 SmallVector<OpFoldResult> storeMatrixOffsets;
612 for (Value coord : coords) {
613 storeMatrixOffsets.push_back(coord);
614 }
615 xegpu::StoreMatrixOp::create(rewriter, loc, src, memDesc.getResult(),
616 storeMatrixOffsets, nullptr /*layout*/);
617 }
618
619 gpu::BarrierOp::create(rewriter, loc);
620
621 // LOAD PHASE: Each target subgroup loads from SLM using target layout
622 auto loadCoords = targetLayout.computeDistributedCoords(
623 rewriter, loc, sgId.getResult(), wgShape);
624 if (failed(loadCoords))
625 return failure();
626
627 VectorType loadType = VectorType::get(targetSgData, elemTy);
628
629 // Load vectors from SLM
630 SmallVector<Value> finalResults;
631 for (auto coords : *loadCoords) {
632 SmallVector<OpFoldResult> loadMatrixOffsets;
633 for (Value coord : coords) {
634 loadMatrixOffsets.push_back(coord);
635 }
636 auto loadOp = xegpu::LoadMatrixOp::create(
637 rewriter, loc, loadType, memDesc.getResult(), loadMatrixOffsets,
638 targetLayout.dropSgLayoutAndData());
639
640 finalResults.push_back(loadOp.getResult());
641 }
642
643 // Wait until every subgroup has read the buffer before it can be written
644 // again, e.g. by the next iteration of an enclosing loop.
645 gpu::BarrierOp::create(rewriter, loc);
646
647 rewriter.replaceOpWithMultiple(op, {finalResults});
648 return success();
649 }
650};
651
652// This pattern distributes arith.constant op into subgroup-level constants
653struct WgToSgArithConstantOp : public OpConversionPattern<arith::ConstantOp> {
654 using OpConversionPattern<arith::ConstantOp>::OpConversionPattern;
655
656 LogicalResult
657 matchAndRewrite(arith::ConstantOp op, OneToNOpAdaptor adaptor,
658 ConversionPatternRewriter &rewriter) const override {
659 auto vecAttr = dyn_cast<DenseElementsAttr>(op.getValue());
660 auto vecType = dyn_cast<VectorType>(op.getType());
661 if (!vecAttr || !vecType)
662 return failure();
663
664 xegpu::DistributeLayoutAttr layout =
665 xegpu::getTemporaryLayout(dyn_cast<OpResult>(op.getResult()));
666 if (!layout || !layout.isForWorkgroup())
667 return failure();
668
669 ArrayRef<int64_t> wgShape = vecType.getShape();
670 SmallVector<int64_t> sgShape;
671 int count;
672 std::tie(sgShape, count) = getSgShapeAndCount(wgShape, layout);
673
674 auto newType = VectorType::get(sgShape, vecType.getElementType());
675 Location loc = op.getLoc();
676 auto eltType = vecType.getElementType();
677
678 if (vecAttr.isSplat()) {
679 // Splat: single value for all subgroups
680 Attribute singleVal = vecAttr.getSplatValue<Attribute>();
681 auto sgAttr = DenseElementsAttr::get(newType, singleVal);
682 SmallVector<Value> newConstOps;
683 for (int i = 0; i < count; ++i) {
684 auto cstOp = arith::ConstantOp::create(rewriter, loc, newType, sgAttr);
685 newConstOps.push_back(cstOp);
686 }
687 rewriter.replaceOpWithMultiple(op, {newConstOps});
688 return success();
689 } else if (sgShape == wgShape) { // if the entire vector is shared by all
690 // subgroups, don't distribute
691 auto newConstOp =
692 arith::ConstantOp::create(rewriter, op.getLoc(), vecType, vecAttr);
693 rewriter.replaceOp(op, newConstOp);
694 return success();
695 } else {
696 // Non-splat constant
697 // Only supports 1D & 2D
698 // TODO: support other cases that require SLM access
699 if (!eltType.isIndex())
700 return rewriter.notifyMatchFailure(
701 op, "Unsupported element type for non-splat constant op.");
702
703 if (wgShape.size() > 2)
704 return rewriter.notifyMatchFailure(
705 op, "Only 1D & 2D vector constant supported");
706
707 SmallVector<Attribute> values(vecAttr.getValues<Attribute>());
708 int64_t rowStride = 0, colStride = 0;
709 int64_t rows = wgShape.size() == 1 ? 1 : wgShape[0];
710 int64_t cols = wgShape.size() == 1 ? wgShape[0] : wgShape[1];
711
712 // Compute colStride and rowStride, and check for constant strides.
713 if (cols > 1) {
714 colStride = cast<IntegerAttr>(values[1]).getInt() -
715 cast<IntegerAttr>(values[0]).getInt();
716 }
717 if (rows > 1) {
718 rowStride = cast<IntegerAttr>(values[cols]).getInt() -
719 cast<IntegerAttr>(values[0]).getInt();
720 }
721
722 for (int64_t r = 0; r < rows; ++r) {
723 for (int64_t c = 0; c < cols; ++c) {
724 int64_t idx = r * cols + c;
725 // Check column stride
726 if (c > 0 && cols > 1) {
727 int64_t prevIdx = r * cols + (c - 1);
728 int64_t diff = cast<IntegerAttr>(values[idx]).getInt() -
729 cast<IntegerAttr>(values[prevIdx]).getInt();
730 if (diff != colStride)
731 return rewriter.notifyMatchFailure(
732 op, "Non-constant column stride in constant op.");
733 }
734 // Check row stride
735 if (r > 0 && rows > 1) {
736 int64_t prevIdx = (r - 1) * cols + c;
737 int64_t diff = cast<IntegerAttr>(values[idx]).getInt() -
738 cast<IntegerAttr>(values[prevIdx]).getInt();
739 if (diff != rowStride)
740 return rewriter.notifyMatchFailure(
741 op, "Non-constant row stride in constant op.");
742 }
743 }
744 }
745
746 // Create a constant for the base tile.
747 // For 2D case, extract the top-left sgShape[0] x sgShape[1] submatrix.
748 // For 1D case, extract the first sgShape[0] elements.
749 SmallVector<Attribute> baseTileValues;
750 int baseTileCols = sgShape[sgShape.size() - 1];
751 int64_t baseTileRows = sgShape.size() == 1 ? 1 : sgShape[0];
752 for (int64_t r = 0; r < baseTileRows; ++r) {
753 for (int64_t c = 0; c < baseTileCols; ++c) {
754 baseTileValues.push_back(values[r * cols + c]);
755 }
756 }
757
758 auto tileAttr = DenseElementsAttr::get(VectorType::get(sgShape, eltType),
759 baseTileValues);
760 auto baseConstVec = arith::ConstantOp::create(rewriter, loc, tileAttr);
761
762 // Get subgroup id
763 Value sgId =
764 gpu::SubgroupIdOp::create(rewriter, loc, /*upper_bound=*/nullptr);
765 auto sgOffsets =
766 layout.computeDistributedCoords(rewriter, loc, sgId, wgShape);
767 if (failed(sgOffsets))
768 return failure();
769
770 SmallVector<Value, 2> strideConsts;
771 strideConsts.push_back(
772 arith::ConstantIndexOp::create(rewriter, loc, colStride));
773 if (rows > 1)
774 strideConsts.insert(
775 strideConsts.begin(),
776 arith::ConstantIndexOp::create(rewriter, loc, rowStride));
777
778 SmallVector<Value> newConstOps;
779 for (auto offsets : *sgOffsets) {
780 // Multiply offset with stride, broadcast it and add to baseConstVec
781 Value mulOffset = arith::ConstantIndexOp::create(rewriter, loc, 0);
782 for (size_t i = 0; i < strideConsts.size(); ++i) {
783 Value mul =
784 arith::MulIOp::create(rewriter, loc, rewriter.getIndexType(),
785 offsets[i], strideConsts[i]);
786 mulOffset = arith::AddIOp::create(
787 rewriter, loc, rewriter.getIndexType(), mulOffset, mul);
788 }
789 // Broadcast to baseConstVec size
790 auto bcastOffset = vector::BroadcastOp::create(
791 rewriter, loc, baseConstVec.getType(), mulOffset);
792 auto finalConst =
793 arith::AddIOp::create(rewriter, loc, baseConstVec, bcastOffset);
794 newConstOps.push_back(finalConst);
795 }
796 rewriter.replaceOpWithMultiple(op, {newConstOps});
797 return success();
798 }
799 }
800};
801
802// This pattern transforms the LoadGatherOp with explicit offsets to load
803// subgroup data
804struct WgToSgLoadGatherOp : public OpConversionPattern<xegpu::LoadGatherOp> {
805 using OpConversionPattern<xegpu::LoadGatherOp>::OpConversionPattern;
806 LogicalResult
807 matchAndRewrite(xegpu::LoadGatherOp op, OneToNOpAdaptor adaptor,
808 ConversionPatternRewriter &rewriter) const override {
809
810 Location loc = op.getLoc();
811 VectorType resultType = dyn_cast<VectorType>(op.getResult().getType());
812 if (!resultType)
813 return failure();
814 ArrayRef<int64_t> wgShape = resultType.getShape();
815
816 xegpu::DistributeLayoutAttr layout = op.getLayoutAttr();
817
818 if (!layout || !layout.isForWorkgroup())
819 return failure();
820
821 SmallVector<int64_t> sgShape = getSgShapeAndCount(wgShape, layout).first;
822
823 // The offsets need to be distributed
824 auto offsetsVecType =
825 dyn_cast<VectorType>(adaptor.getOffsets().front().getType());
826 auto maskVecType =
827 dyn_cast<VectorType>(adaptor.getMask().front().getType());
828 if (!offsetsVecType || !maskVecType ||
829 offsetsVecType.getShape() != maskVecType.getShape()) {
830 return rewriter.notifyMatchFailure(op,
831 "offsets have not been distributed");
832 }
833
834 SmallVector<Value> newLoadOps;
835 VectorType newTy = VectorType::get(sgShape, resultType.getElementType());
836 for (auto [offsets, mask] :
837 llvm::zip(adaptor.getOffsets(), adaptor.getMask())) {
838 auto newLayout = layout.dropSgLayoutAndData();
839 auto newLoadOp = xegpu::LoadGatherOp::create(
840 rewriter, loc, newTy, op.getSource(), offsets, mask,
841 op.getL1HintAttr(), op.getL2HintAttr(), op.getL3HintAttr(), newLayout,
842 /*contiguity=*/nullptr);
843 newLoadOps.push_back(newLoadOp);
844 }
845 rewriter.replaceOpWithMultiple(op, {newLoadOps});
846 return success();
847 }
848};
849
850// This pattern transforms the StoreScatterOp with explicit offsets to store
851// subgroup data
852struct WgToSgStoreScatterOp
853 : public OpConversionPattern<xegpu::StoreScatterOp> {
854 using OpConversionPattern<xegpu::StoreScatterOp>::OpConversionPattern;
855 LogicalResult
856 matchAndRewrite(xegpu::StoreScatterOp op, OneToNOpAdaptor adaptor,
857 ConversionPatternRewriter &rewriter) const override {
858
859 Location loc = op.getLoc();
860 VectorType valueType = dyn_cast<VectorType>(op.getValue().getType());
861 if (!valueType)
862 return failure();
863
864 xegpu::DistributeLayoutAttr layout = op.getLayoutAttr();
865
866 if (!layout || !layout.isForWorkgroup())
867 return failure();
868
869 // The offsets need to be distributed
870 auto offsetsVecType =
871 dyn_cast<VectorType>(adaptor.getOffsets().front().getType());
872 auto maskVecType =
873 dyn_cast<VectorType>(adaptor.getMask().front().getType());
874 if (!offsetsVecType || !maskVecType ||
875 offsetsVecType.getShape() != maskVecType.getShape()) {
876 return rewriter.notifyMatchFailure(op,
877 "offsets have not been distributed");
878 }
879
880 for (auto [val, offs, mask] : llvm::zip(
881 adaptor.getValue(), adaptor.getOffsets(), adaptor.getMask())) {
882 xegpu::StoreScatterOp::create(
883 rewriter, loc, val, op.getDest(), offs, mask, op.getL1HintAttr(),
884 op.getL2HintAttr(), op.getL3HintAttr(), layout.dropSgLayoutAndData(),
885 /*contiguity=*/nullptr);
886 }
887 rewriter.eraseOp(op);
888 return success();
889 }
890};
891
892struct WgToSgLoadMatrixOp : public OpConversionPattern<xegpu::LoadMatrixOp> {
893 using OpConversionPattern<xegpu::LoadMatrixOp>::OpConversionPattern;
894 LogicalResult
895 matchAndRewrite(xegpu::LoadMatrixOp op, OneToNOpAdaptor adaptor,
896 ConversionPatternRewriter &rewriter) const override {
897
898 SmallVector<SmallVector<OpFoldResult>> offsetsList;
899 if (failed(genOffsetsList(rewriter, op, offsetsList)))
900 return failure();
901
902 ArrayRef<int64_t> wgShape = op.getDataShape();
903 VectorType valueTy = llvm::dyn_cast<VectorType>(op.getRes().getType());
904 assert(valueTy && "the value type must be vector type!");
905 Type elemTy = valueTy.getElementType();
906
907 xegpu::DistributeLayoutAttr layout = op.getLayoutAttr();
908 SmallVector<int64_t> sgShape = getSgShapeAndCount(wgShape, layout).first;
909 VectorType newResTy = VectorType::get(sgShape, elemTy);
910 SmallVector<Value> newOps;
911 for (auto offsets : offsetsList) {
912 auto newOp = xegpu::LoadMatrixOp::create(rewriter, op.getLoc(), newResTy,
913 op.getMemDesc(), offsets,
914 layout.dropSgLayoutAndData());
915 newOps.push_back(newOp);
916 }
917 rewriter.replaceOpWithMultiple(op, {newOps});
918
919 return success();
920 }
921};
922
923struct WgToSgStoreMatrixOp : public OpConversionPattern<xegpu::StoreMatrixOp> {
924 using OpConversionPattern<xegpu::StoreMatrixOp>::OpConversionPattern;
925 LogicalResult
926 matchAndRewrite(xegpu::StoreMatrixOp op, OneToNOpAdaptor adaptor,
927 ConversionPatternRewriter &rewriter) const override {
928
929 SmallVector<SmallVector<OpFoldResult>> offsetsList;
930 if (failed(genOffsetsList(rewriter, op, offsetsList)))
931 return failure();
932
933 xegpu::DistributeLayoutAttr layout = op.getLayoutAttr();
934 for (auto [v, offsets] : llvm::zip(adaptor.getData(), offsetsList))
935 xegpu::StoreMatrixOp::create(rewriter, op.getLoc(), v, op.getMemDesc(),
936 offsets, layout.dropSgLayoutAndData());
937 rewriter.eraseOp(op);
938 return success();
939 }
940};
941
942// This pattern distributes the vector.step ops to work at subgroup level
943struct WgToSgVectorStepOp : public OpConversionPattern<vector::StepOp> {
944 using OpConversionPattern<vector::StepOp>::OpConversionPattern;
945 LogicalResult
946 matchAndRewrite(vector::StepOp op, OneToNOpAdaptor adaptor,
947 ConversionPatternRewriter &rewriter) const override {
948 xegpu::DistributeLayoutAttr layout =
949 xegpu::getTemporaryLayout(dyn_cast<OpResult>(op.getResult()));
950 if (!layout || !layout.isForWorkgroup())
951 return failure();
952
953 Location loc = op.getLoc();
954 VectorType type = op.getResult().getType();
955 auto wgShape = type.getShape();
956 std::optional<SmallVector<int64_t>> sgShape =
957 getSgShapeAndCount(wgShape, layout).first;
958 if (!sgShape)
959 return failure();
960
961 Value sgId =
962 gpu::SubgroupIdOp::create(rewriter, loc, /*upper_bound=*/nullptr);
963 auto sgOffsets =
964 layout.computeDistributedCoords(rewriter, loc, sgId, wgShape);
965 if (failed(sgOffsets))
966 return failure();
967
968 VectorType newTy = type.cloneWith(*sgShape, type.getElementType());
969 auto steps = vector::StepOp::create(rewriter, loc, newTy);
970 SmallVector<Value> newOps;
971 for (auto offsets : *sgOffsets) {
972 // Broadcast the offset scalar to a vector & add to the base steps
973 auto bcastOffset =
974 vector::BroadcastOp::create(rewriter, loc, newTy, offsets[0]);
975 auto finalSteps =
976 arith::AddIOp::create(rewriter, loc, steps, bcastOffset);
977 newOps.push_back(finalSteps);
978 }
979
980 rewriter.replaceOpWithMultiple(op, {newOps});
981 return success();
982 }
983};
984
985// This pattern transforms vector.shape_cast ops to work at subgroup level.
986struct WgToSgVectorShapeCastOp
987 : public OpConversionPattern<vector::ShapeCastOp> {
988 using OpConversionPattern<vector::ShapeCastOp>::OpConversionPattern;
989
990 LogicalResult
991 matchAndRewrite(vector::ShapeCastOp op, OneToNOpAdaptor adaptor,
992 ConversionPatternRewriter &rewriter) const override {
993
994 VectorType resultType = dyn_cast<VectorType>(op.getResult().getType());
995 if (!resultType)
996 return failure();
997
998 ArrayRef<int64_t> wgShape = resultType.getShape();
999 xegpu::DistributeLayoutAttr layout =
1000 xegpu::getTemporaryLayout(dyn_cast<OpResult>(op.getResult()));
1001 if (!layout || !layout.isForWorkgroup())
1002 return failure();
1003
1004 // Check that srcShape and destShape, if they differ, only differ by
1005 // expand of unit dimensions.
1006 auto srcType = dyn_cast<VectorType>(op.getSource().getType());
1007 if (!srcType)
1008 return failure();
1009
1010 ArrayRef<int64_t> srcShape = srcType.getShape();
1011
1012 xegpu::DistributeLayoutAttr layoutToDistribute = layout;
1013 SmallVector<int64_t> expandedUnitDims;
1014 if (xegpu::matchUnitDimExpansion(srcShape, wgShape, expandedUnitDims)) {
1015 xegpu::DistributeLayoutAttr sourceLayout =
1016 xegpu::getTemporaryLayout(op->getOpOperand(0));
1017
1018 if (!sourceLayout.isSliceOf(layout))
1019 return rewriter.notifyMatchFailure(
1020 op, "The ShapeCast op only expands dimensions, the input layout "
1021 "must be a slice of the result layout.");
1022
1023 assert(layoutToDistribute.isEqualTo(
1024 layoutToDistribute.setUnitDimData(expandedUnitDims)) &&
1025 "The sg_data for unit dimensions should be set as 1");
1026 }
1027
1028 SmallVector<int64_t> sgShape =
1029 getSgShapeAndCount(wgShape, layoutToDistribute).first;
1030 VectorType newResultType =
1031 VectorType::get(sgShape, resultType.getElementType());
1032
1033 SmallVector<Value> newShapeCastOps;
1034 for (auto src : adaptor.getSource()) {
1035 auto newShapeCast = vector::ShapeCastOp::create(rewriter, op.getLoc(),
1036 newResultType, src);
1037 newShapeCastOps.push_back(newShapeCast.getResult());
1038 }
1039
1040 rewriter.replaceOpWithMultiple(op, {newShapeCastOps});
1041 return success();
1042 }
1043};
1044
1045/// This pattern transforms vector.multi_dim_reduction operations from
1046/// workgroup-level to subgroup-level execution with support for multiple
1047/// reduction dimensions.
1048///
1049/// Steps include:
1050/// 1. LOCAL REDUCTION :
1051/// - Each subgroup performs local reduction on its data slice
1052/// - Uses ZERO accumulator to avoid double-counting during cross-subgroup
1053/// phase
1054///
1055/// 2. CROSS-SUBGROUP :
1056/// - Determines if cross-subgroup reduction is needed (when sg_layout > 1 in
1057/// reduction dims & sgData[reduction dims] < wgData[reduction dims])
1058/// - If not needed, adds original accumulator and returns local results
1059///
1060/// 3. SHARED LOCAL MEMORY (SLM) PHASE (when cross-subgroup reduction needed):
1061/// a) SLM Layout Design:
1062/// - Rows: subgroups participating in reduction (product of sg_layout in
1063/// reduction dims)
1064/// - Cols: total result elements across non-reduction dimensions
1065///
1066/// b) Store Phase:
1067/// - Each subgroup stores its local reduction result to SLM
1068/// - Row offset: linearized index of subgroup in reduction dimensions
1069/// - Col offset: linearized index of subgroup in non-reduction dimensions
1070///
1071/// c) Load and Final Reduction Phase:
1072/// - Each subgroup loads a column of data (all reduction participants for
1073/// its position)
1074/// - Performs final reduction along the loaded dimension
1075/// - Adds original accumulator to get final result
1076///
1077struct WgToSgMultiDimReductionOp
1078 : public OpConversionPattern<vector::MultiDimReductionOp> {
1079 using OpConversionPattern<vector::MultiDimReductionOp>::OpConversionPattern;
1080
1081 LogicalResult
1082 matchAndRewrite(vector::MultiDimReductionOp op, OneToNOpAdaptor adaptor,
1083 ConversionPatternRewriter &rewriter) const override {
1084 Location loc = op.getLoc();
1085
1086 VectorType srcType = op.getSourceVectorType();
1087 Type resultTy = op.getResult().getType();
1088 VectorType dstVecType = dyn_cast<VectorType>(resultTy);
1089 bool isScalarResult = !dstVecType;
1090
1091 auto originalSrcShape = srcType.getShape();
1092 Type elemTy = srcType.getElementType();
1093
1094 xegpu::DistributeLayoutAttr layout =
1095 xegpu::getTemporaryLayout(dyn_cast<OpResult>(op.getResult()));
1096 if (!layout || !layout.isForWorkgroup())
1097 return failure();
1098
1099 auto reductionDims = llvm::to_vector(op.getReductionDims());
1100
1101 // Get sg_layout and sg_data from the parent layout
1102 SmallVector<int64_t> sgLayout;
1103 SmallVector<int64_t> sgData;
1104 xegpu::DistributeLayoutAttr parentLayout;
1105 if (auto sliceAttr = dyn_cast<xegpu::SliceAttr>(layout)) {
1106 parentLayout = sliceAttr.getParent();
1107 sgLayout = parentLayout.getEffectiveSgLayoutAsInt();
1108 sgData = parentLayout.getEffectiveSgDataAsInt();
1109 } else
1110 return rewriter.notifyMatchFailure(
1111 op, "Reduction should have SliceAttr layout");
1112
1113 // Step 1: perform local subgroup reductions with neutral accumulator
1114 SmallVector<Value> localReductions;
1115 auto sgSrcs = adaptor.getSource();
1116 auto sgSrcType = dyn_cast<VectorType>(sgSrcs.front().getType());
1117 SmallVector<int64_t> sgSrcShape(sgSrcType.getShape().begin(),
1118 sgSrcType.getShape().end());
1119
1120 // Determine the SG-level destination type.
1121 // For scalar results (all dims reduced), the sg result is also scalar.
1122 // For vector results, compute the sg destination shape from layout.
1123 Type sgDstType;
1124 if (dstVecType) {
1125 auto originalDstShape = dstVecType.getShape();
1126 SmallVector<int64_t> sgDstShape =
1127 getSgShapeAndCount(originalDstShape, layout).first;
1128 sgDstType = VectorType::get(sgDstShape, elemTy);
1129 } else {
1130 sgDstType = elemTy;
1131 }
1132
1133 for (auto sgSrc : sgSrcs) {
1134 // Create neutral accumulator for local reduction
1135 Value neutralLocalAcc = xegpu::createReductionNeutralValue(
1136 rewriter, loc, sgDstType, op.getKind(), op.getFastmathAttr());
1137 // Local reduction with neutral accumulator
1138 auto localReduce = vector::MultiDimReductionOp::create(
1139 rewriter, loc, sgDstType, op.getKind(), sgSrc, neutralLocalAcc,
1140 reductionDims, op.getFastmath());
1141 localReductions.push_back(localReduce.getResult());
1142 }
1143
1144 // Check if cross-subgroup reduction is needed for any reduction dimension
1145 SmallVector<int64_t> crossSgReductionDims;
1146 for (int64_t reductionDim : reductionDims) {
1147 bool needsCrossSubgroupReduction =
1148 (sgLayout[reductionDim] > 1) &&
1149 (sgData[reductionDim] < originalSrcShape[reductionDim]);
1150
1151 if (needsCrossSubgroupReduction) {
1152 crossSgReductionDims.push_back(reductionDim);
1153 }
1154 }
1155
1156 // If no cross-subgroup reduction needed, add accumulator and return
1157 if (crossSgReductionDims.empty()) {
1158 SmallVector<Value> results;
1159 for (auto localResult : localReductions) {
1160 auto finalResult = vector::makeArithReduction(
1161 rewriter, loc, op.getKind(), localResult, adaptor.getAcc()[0],
1162 op.getFastmathAttr());
1163 results.push_back(finalResult);
1164 }
1165 rewriter.replaceOpWithMultiple(op, {results});
1166 return success();
1167 }
1168
1169 // Step 2: cross-subgroup reduction using SLM - allocating slm memory
1170 auto slmStoreDataShape = sgSrcShape;
1171 for (int64_t dim : reductionDims)
1172 slmStoreDataShape[dim] = 1;
1173 VectorType slmStoreDataType = VectorType::get(slmStoreDataShape, elemTy);
1174 SmallVector<Value> slmStoreData;
1175 for (auto localResult : localReductions) {
1176 if (isScalarResult) {
1177 // Scalar result: broadcast scalar to vector<1x...x1> for SLM store
1178 slmStoreData.push_back(vector::BroadcastOp::create(
1179 rewriter, loc, slmStoreDataType, localResult));
1180 } else {
1181 slmStoreData.push_back(vector::ShapeCastOp::create(
1182 rewriter, loc, slmStoreDataType, localResult));
1183 }
1184 }
1185 // for reduction dimension, SLM stores partial results from each subgroup
1186 SmallVector<int64_t> slmShape(originalSrcShape.begin(),
1187 originalSrcShape.end());
1188 SmallVector<int> slmSgData(sgData.begin(), sgData.end());
1189 SmallVector<int> slmSgLayout(sgLayout.begin(), sgLayout.end());
1190 for (int dim : reductionDims) {
1191 slmShape[dim] = sgLayout[dim];
1192 slmSgData[dim] = 1;
1193 }
1194 xegpu::LayoutAttr slmStoreLayout =
1195 xegpu::LayoutAttr::get(rewriter.getContext(), slmSgLayout, slmSgData);
1196
1197 // Allocate SLM
1198 auto bitWidth = elemTy.getIntOrFloatBitWidth();
1199 auto bytesPerElement = bitWidth / 8;
1200 auto slmSize = computeProduct(slmShape) * bytesPerElement;
1201 auto slmTy = MemRefType::get({slmSize}, rewriter.getI8Type(), {}, 3);
1202 auto slm = memref::AllocaOp::create(rewriter, loc, slmTy);
1203
1204 auto memDescType = xegpu::MemDescType::get(rewriter.getContext(), slmShape,
1205 elemTy, nullptr);
1206 auto memDesc =
1207 xegpu::CreateMemDescOp::create(rewriter, loc, memDescType, slm);
1208
1209 // Step 3: Store local results to SLM
1210 auto sgId = gpu::SubgroupIdOp::create(rewriter, loc,
1211 rewriter.getIndexType(), nullptr);
1212
1213 auto slmStoreCoords =
1214 slmStoreLayout.computeDistributedCoords(rewriter, loc, sgId, slmShape);
1215 if (failed(slmStoreCoords))
1216 return failure();
1217 for (auto [data, coord] : llvm::zip(slmStoreData, *slmStoreCoords)) {
1218 SmallVector<OpFoldResult> coordOfr(coord.begin(), coord.end());
1219 xegpu::StoreMatrixOp::create(rewriter, loc, data, memDesc.getResult(),
1220 coordOfr,
1221 /*layout=*/nullptr);
1222 }
1223
1224 gpu::BarrierOp::create(rewriter, loc);
1225
1226 // Step 4: Load from SLM for final reduction
1227 SmallVector<int64_t> slmLoadDataShape(sgSrcShape.begin(), sgSrcShape.end());
1228 for (int64_t dim : reductionDims) {
1229 slmLoadDataShape[dim] = slmShape[dim];
1230 slmSgData[dim] = slmShape[dim];
1231 }
1232 xegpu::LayoutAttr slmLoadLayout =
1233 xegpu::LayoutAttr::get(rewriter.getContext(), slmSgLayout, slmSgData);
1234 auto slmLoadCoords =
1235 slmLoadLayout.computeDistributedCoords(rewriter, loc, sgId, slmShape);
1236 if (failed(slmLoadCoords))
1237 return failure();
1238
1239 VectorType slmLoadType = VectorType::get(slmLoadDataShape, elemTy);
1240 SmallVector<Value> slmLoadData;
1241 for (auto coord : *slmLoadCoords) {
1242 SmallVector<OpFoldResult> coordOfr(coord.begin(), coord.end());
1243 slmLoadData.push_back(xegpu::LoadMatrixOp::create(
1244 rewriter, loc, slmLoadType, memDesc.getResult(), coordOfr,
1245 /*layout=*/nullptr));
1246 }
1247
1248 // Wait until every subgroup has read the buffer before it can be written
1249 // again, e.g. by the next iteration of an enclosing loop.
1250 gpu::BarrierOp::create(rewriter, loc);
1251
1252 // Step 5: Perform final reduction with neutral accumulator and add the
1253 // original accumulator at the end
1254 Value neutralFinalAcc = xegpu::createReductionNeutralValue(
1255 rewriter, loc, sgDstType, op.getKind(), op.getFastmathAttr());
1256
1257 SmallVector<Value> finalResults;
1258 for (size_t i = 0; i < slmLoadData.size(); ++i) {
1259 auto loaded = slmLoadData[i];
1260 auto finalReduce = vector::MultiDimReductionOp::create(
1261 rewriter, loc, sgDstType, op.getKind(), loaded, neutralFinalAcc,
1262 reductionDims, op.getFastmath());
1263 finalResults.push_back(vector::makeArithReduction(
1264 rewriter, loc, op.getKind(), finalReduce.getResult(),
1265 adaptor.getAcc()[i], op.getFastmathAttr()));
1266 }
1267 rewriter.replaceOpWithMultiple(op, {finalResults});
1268 return success();
1269 }
1270};
1271
1272// This pattern transforms vector.transpose ops to work at subgroup level.
1273struct WgToSgVectorTransposeOp
1274 : public OpConversionPattern<vector::TransposeOp> {
1275 using OpConversionPattern<vector::TransposeOp>::OpConversionPattern;
1276
1277 LogicalResult
1278 matchAndRewrite(vector::TransposeOp op, OneToNOpAdaptor adaptor,
1279 ConversionPatternRewriter &rewriter) const override {
1280 VectorType resultType = op.getResultVectorType();
1281
1282 ArrayRef<int64_t> wgShape = resultType.getShape();
1283 xegpu::DistributeLayoutAttr layout =
1284 xegpu::getTemporaryLayout(dyn_cast<OpResult>(op.getResult()));
1285 if (!layout || !layout.isForWorkgroup())
1286 return failure();
1287 xegpu::DistributeLayoutAttr sourceLayout =
1288 xegpu::getTemporaryLayout(op->getOpOperand(0));
1289 if (!sourceLayout || !sourceLayout.isForWorkgroup())
1290 return failure();
1291
1292 SmallVector<int64_t> sourceSgLayout =
1293 sourceLayout.getEffectiveSgLayoutAsInt();
1294 SmallVector<int64_t> resultSgLayout = layout.getEffectiveSgLayoutAsInt();
1295
1296 ArrayRef<int64_t> permutation = op.getPermutation();
1297 size_t permutationSize = permutation.size();
1298 if (sourceSgLayout.size() != permutationSize ||
1299 resultSgLayout.size() != permutationSize) {
1300 return rewriter.notifyMatchFailure(
1301 op, "Layouts and permutation must have the same rank");
1302 }
1303
1304 // Check that sgLayout, sgData & order are properly transposed for source
1305 // and result
1306 if (!layout.isTransposeOf(sourceLayout, permutation,
1307 xegpu::LayoutKind::Subgroup))
1308 return rewriter.notifyMatchFailure(
1309 op, "Result layout is not a valid transpose of source layout "
1310 "according to permutation");
1311
1312 SmallVector<int64_t> sgShape = getSgShapeAndCount(wgShape, layout).first;
1313 VectorType newResultType =
1314 VectorType::get(sgShape, resultType.getElementType());
1315
1316 SmallVector<Value> newTransposeOps;
1317 for (auto src : adaptor.getVector()) {
1318 auto newTranspose = vector::TransposeOp::create(
1319 rewriter, op.getLoc(), newResultType, src, permutation);
1320 newTransposeOps.push_back(newTranspose.getResult());
1321 }
1322 rewriter.replaceOpWithMultiple(op, {newTransposeOps});
1323 return success();
1324 }
1325};
1326
1327// Distribute vector mask ops to work at subgroup level.
1328template <typename MaskOpType>
1329struct WgToSgVectorMaskOp : public OpConversionPattern<MaskOpType> {
1330 using OpConversionPattern<MaskOpType>::OpConversionPattern;
1331
1332 LogicalResult matchAndRewrite(
1333 MaskOpType op,
1334 typename OpConversionPattern<MaskOpType>::OneToNOpAdaptor adaptor,
1335 ConversionPatternRewriter &rewriter) const override {
1336 xegpu::DistributeLayoutAttr layout =
1337 xegpu::getTemporaryLayout(dyn_cast<OpResult>(op.getResult()));
1338 if (!layout || !layout.isForWorkgroup())
1339 return failure();
1340
1341 Location loc = op.getLoc();
1342 VectorType type = op.getResult().getType();
1343 auto wgShape = type.getShape();
1344
1345 SmallVector<Value> wgMaskDimSizes;
1346 if constexpr (std::is_same_v<MaskOpType, vector::ConstantMaskOp>) {
1347 for (int64_t maskSize : op.getMaskDimSizes()) {
1348 wgMaskDimSizes.push_back(
1349 arith::ConstantIndexOp::create(rewriter, loc, maskSize));
1350 }
1351 } else if constexpr (std::is_same_v<MaskOpType, vector::CreateMaskOp>) {
1352 wgMaskDimSizes = llvm::to_vector(op.getOperands());
1353 }
1354
1355 Value sgId =
1356 gpu::SubgroupIdOp::create(rewriter, loc, /*upper_bound=*/nullptr);
1357 auto sgOffsets =
1358 layout.computeDistributedCoords(rewriter, loc, sgId, wgShape);
1359 if (failed(sgOffsets))
1360 return failure();
1361
1362 SmallVector<int64_t> sgShape = getSgShapeAndCount(wgShape, layout).first;
1363 VectorType resultType = VectorType::get(sgShape, type.getElementType());
1364
1365 // In each dimension, each subgroup computes its local mask size as:
1366 // min(max(wgMaskDimSize[d] - offset[d], 0), sgDimSize[d])
1367 SmallVector<Value> newCreateMaskOps;
1368 for (auto offsetSet : *sgOffsets) {
1369 SmallVector<Value> maskOperands;
1370
1371 for (auto [i, wgMaskDimSize] : llvm::enumerate(wgMaskDimSizes)) {
1372 Value dimSizeVal =
1373 arith::ConstantIndexOp::create(rewriter, loc, sgShape[i]);
1374 Value offset = offsetSet[i];
1375 Value adjustedMaskSize =
1376 arith::SubIOp::create(rewriter, loc, wgMaskDimSize, offset);
1377 Value zero = arith::ConstantIndexOp::create(rewriter, loc, 0);
1378 Value nonNegative =
1379 arith::MaxSIOp::create(rewriter, loc, adjustedMaskSize, zero);
1380 Value sgMaskSize =
1381 arith::MinSIOp::create(rewriter, loc, nonNegative, dimSizeVal);
1382 maskOperands.push_back(sgMaskSize);
1383 }
1384
1385 auto newCreateMaskOp =
1386 vector::CreateMaskOp::create(rewriter, loc, resultType, maskOperands);
1387 newCreateMaskOps.push_back(newCreateMaskOp.getResult());
1388 }
1389
1390 rewriter.replaceOpWithMultiple(op, {newCreateMaskOps});
1391 return success();
1392 }
1393};
1394
1395using WgToSgVectorConstantMaskOp = WgToSgVectorMaskOp<vector::ConstantMaskOp>;
1396using WgToSgVectorCreateMaskOp = WgToSgVectorMaskOp<vector::CreateMaskOp>;
1397
1398// This pattern transforms vector.bitcast ops to work at subgroup level.
1399struct WgToSgVectorBitCastOp : public OpConversionPattern<vector::BitCastOp> {
1400 using OpConversionPattern<vector::BitCastOp>::OpConversionPattern;
1401
1402 LogicalResult
1403 matchAndRewrite(vector::BitCastOp op, OneToNOpAdaptor adaptor,
1404 ConversionPatternRewriter &rewriter) const override {
1405 VectorType resultType = op.getResultVectorType();
1406
1407 ArrayRef<int64_t> wgShape = resultType.getShape();
1408 xegpu::DistributeLayoutAttr layout =
1409 xegpu::getTemporaryLayout(dyn_cast<OpResult>(op.getResult()));
1410 if (!layout || !layout.isForWorkgroup())
1411 return failure();
1412
1413 SmallVector<int64_t> sgShape = getSgShapeAndCount(wgShape, layout).first;
1414 VectorType newResultType =
1415 VectorType::get(sgShape, resultType.getElementType());
1416
1417 SmallVector<Value> newBitCastOps;
1418 for (auto src : adaptor.getSource()) {
1419 auto newBitCast =
1420 vector::BitCastOp::create(rewriter, op.getLoc(), newResultType, src);
1421 newBitCastOps.push_back(newBitCast.getResult());
1422 }
1423
1424 rewriter.replaceOpWithMultiple(op, {newBitCastOps});
1425 return success();
1426 }
1427};
1428
1429// This pattern transforms vector.interleave ops to work at subgroup level.
1430struct WgToSgVectorInterleaveOp
1431 : public OpConversionPattern<vector::InterleaveOp> {
1432 using OpConversionPattern<vector::InterleaveOp>::OpConversionPattern;
1433
1434 LogicalResult
1435 matchAndRewrite(vector::InterleaveOp op, OneToNOpAdaptor adaptor,
1436 ConversionPatternRewriter &rewriter) const override {
1437 VectorType resultType = op.getResultVectorType();
1438
1439 ArrayRef<int64_t> wgShape = resultType.getShape();
1440 xegpu::DistributeLayoutAttr layout =
1441 xegpu::getTemporaryLayout(dyn_cast<OpResult>(op.getResult()));
1442 if (!layout || !layout.isForWorkgroup())
1443 return failure();
1444
1445 SmallVector<int64_t> sgShape = getSgShapeAndCount(wgShape, layout).first;
1446 VectorType newResultType =
1447 VectorType::get(sgShape, resultType.getElementType());
1448
1449 SmallVector<Value> newInterleaveOps;
1450 // Interleave operates pairwise: each lhs value is interleaved with
1451 // corresponding rhs value
1452 for (auto [lhs, rhs] : llvm::zip(adaptor.getLhs(), adaptor.getRhs())) {
1453 auto newInterleave = vector::InterleaveOp::create(
1454 rewriter, op.getLoc(), newResultType, lhs, rhs);
1455 newInterleaveOps.push_back(newInterleave.getResult());
1456 }
1457
1458 rewriter.replaceOpWithMultiple(op, {newInterleaveOps});
1459 return success();
1460 }
1461};
1462
1463// This pattern transforms vector.deinterleave ops to work at subgroup level.
1464struct WgToSgVectorDeinterleaveOp
1465 : public OpConversionPattern<vector::DeinterleaveOp> {
1466 using OpConversionPattern<vector::DeinterleaveOp>::OpConversionPattern;
1467
1468 LogicalResult
1469 matchAndRewrite(vector::DeinterleaveOp op, OneToNOpAdaptor adaptor,
1470 ConversionPatternRewriter &rewriter) const override {
1471 SmallVector<Value> newRes1Ops;
1472 SmallVector<Value> newRes2Ops;
1473
1474 for (auto src : adaptor.getSource()) {
1475 auto newDeinterleave =
1476 vector::DeinterleaveOp::create(rewriter, op.getLoc(), src);
1477 newRes1Ops.push_back(newDeinterleave.getResultEven());
1478 newRes2Ops.push_back(newDeinterleave.getResultOdd());
1479 }
1480
1481 SmallVector<SmallVector<Value>> results = {newRes1Ops, newRes2Ops};
1482 rewriter.replaceOpWithMultiple(op, results);
1483 return success();
1484 }
1485};
1486
1487} // namespace
1488
1489namespace mlir {
1490namespace xegpu {
1492 Operation *topLevelOp) {
1493 // Pass through all types by default.
1494 converter.addConversion([](Type type) -> Type { return type; });
1495
1496 // For TensorDescType, convert WG-level tensor descs to N SG-level descs.
1497 converter.addConversion(
1498 [](xegpu::TensorDescType type,
1499 SmallVectorImpl<Type> &result) -> std::optional<LogicalResult> {
1500 xegpu::DistributeLayoutAttr layout = type.getLayoutAttr();
1501 if (!layout || !layout.isForWorkgroup())
1502 return std::nullopt;
1503
1504 Type elemTy = type.getElementType();
1505 ArrayRef<int64_t> shape = type.getShape();
1506
1507 int count;
1508 SmallVector<int64_t> subShape;
1509 std::tie(subShape, count) = getSgShapeAndCount(shape, layout);
1510
1511 layout = layout.dropSgLayoutAndData();
1512
1513 auto newTy = xegpu::TensorDescType::get(
1514 type.getContext(), subShape, elemTy, type.getEncoding(), layout);
1515 result.append(count, newTy);
1516 return success();
1517 });
1518
1519 // Context-aware VectorType conversion based on sg_layout/sg_data
1520 // (1:1 shape-changing or 1:N).
1521 auto getSubShapeAndCount = [](VectorType vecTy,
1522 xegpu::DistributeLayoutAttr layout)
1523 -> std::pair<SmallVector<int64_t>, int> {
1524 if (!layout.isForWorkgroup())
1525 return {{}, 0};
1526 return getSgShapeAndCount(vecTy.getShape(), layout);
1527 };
1528 auto loopArgTypes =
1529 xegpu::precomputeLoopBlockArgTypes(topLevelOp, getSubShapeAndCount);
1530 xegpu::addVectorTypeConversion(converter, getSubShapeAndCount,
1531 std::move(loopArgTypes));
1532}
1533
1535 patterns.add<WgToSgCreateNdOp, WgToSgLoadNdOp, WgToSgStoreNdOp, WgToSgDpasOp,
1536 WgToSgDpasMxOp, WgToSgPrefetchNdOp, WgToSgElementwiseOp,
1537 WgToSgVectorBroadcastOp, WgToSgConvertLayoutOp,
1538 WgToSgArithConstantOp, WgToSgLoadGatherOp, WgToSgStoreScatterOp,
1539 WgToSgLoadMatrixOp, WgToSgStoreMatrixOp, WgToSgVectorStepOp,
1540 WgToSgVectorShapeCastOp, WgToSgMultiDimReductionOp,
1541 WgToSgVectorTransposeOp, WgToSgVectorConstantMaskOp,
1542 WgToSgVectorCreateMaskOp, WgToSgVectorBitCastOp,
1543 WgToSgVectorInterleaveOp, WgToSgVectorDeinterleaveOp>(
1544 patterns.getContext());
1545}
1546} // namespace xegpu
1547} // namespace mlir
1548
1549namespace {
1550struct XeGPUWgToSgDistributePass
1551 : public xegpu::impl::XeGPUWgToSgDistributeBase<XeGPUWgToSgDistributePass> {
1552 void runOnOperation() override;
1553};
1554} // namespace
1555
1556void XeGPUWgToSgDistributePass::runOnOperation() {
1557
1558 Operation *op = getOperation();
1560 signalPassFailure();
1561 return;
1562 }
1563
1564 // Collect existing UnrealizedConversionCastOps. These must be preserved.
1565 llvm::SmallSetVector<UnrealizedConversionCastOp, 8> existingCasts;
1566 getOperation()->walk(
1567 [&](UnrealizedConversionCastOp castOp) { existingCasts.insert(castOp); });
1568
1569 // Perform workgroup to subgroup distribution for TensorDesc and Vector
1570 // values, as well as XeGPU, Arith, and Vector operations. Uses a
1571 // context-aware type converter that inspects Values to retrieve the
1572 // distribute layout attribute for 1:N type conversion.
1573 MLIRContext *ctx = &getContext();
1574 RewritePatternSet patterns(ctx);
1575 ConversionTarget target(*ctx);
1576 TypeConverter converter;
1577 // Source (N:1) and target (1:1) materializations using
1578 // UnrealizedConversionCastOp.
1579 auto materializeCast = [](OpBuilder &builder, Type type, ValueRange inputs,
1580 Location loc) -> Value {
1581 return UnrealizedConversionCastOp::create(builder, loc, type, inputs)
1582 .getResult(0);
1583 };
1584 converter.addSourceMaterialization(materializeCast);
1585 converter.addTargetMaterialization(materializeCast);
1587 getOperation());
1588
1589 auto getTensorDescType = [](Operation *op) -> xegpu::TensorDescType {
1590 if (auto createOp = dyn_cast<xegpu::CreateNdDescOp>(op))
1591 return createOp.getType();
1592 if (auto loadOp = dyn_cast<xegpu::LoadNdOp>(op))
1593 return loadOp.getTensorDescType();
1594 if (auto storeOp = dyn_cast<xegpu::StoreNdOp>(op))
1595 return storeOp.getTensorDescType();
1596 if (auto prefetchOp = dyn_cast<xegpu::PrefetchNdOp>(op))
1597 return prefetchOp.getTensorDescType();
1598 return xegpu::TensorDescType();
1599 };
1600
1601 auto isLegal = [&](xegpu::DistributeLayoutAttr layout) -> bool {
1602 return !layout || !layout.isForWorkgroup();
1603 };
1604
1605 target.addDynamicallyLegalOp<xegpu::CreateNdDescOp, xegpu::LoadNdOp,
1606 xegpu::StoreNdOp, xegpu::PrefetchNdOp>(
1607 [=](Operation *op) -> bool {
1608 auto tdescTy = getTensorDescType(op);
1609 auto layout = dyn_cast_if_present<xegpu::DistributeLayoutAttr>(
1610 tdescTy.getLayout());
1611 return isLegal(layout);
1612 });
1613
1614 target.addDynamicallyLegalOp<xegpu::DpasOp>([=](xegpu::DpasOp op) -> bool {
1615 auto layout = op.getLayoutCdAttr();
1616 return isLegal(layout);
1617 });
1618
1619 target.addDynamicallyLegalOp<xegpu::DpasMxOp>(
1620 [=](xegpu::DpasMxOp op) -> bool {
1621 auto layout = op.getLayoutCdAttr();
1622 return isLegal(layout);
1623 });
1624
1625 target.addDynamicallyLegalOp<xegpu::LoadMatrixOp>(
1626 [=](xegpu::LoadMatrixOp op) -> bool {
1627 return isLegal(op.getLayoutAttr());
1628 });
1629
1630 target.addDynamicallyLegalOp<xegpu::StoreMatrixOp>(
1631 [=](xegpu::StoreMatrixOp op) -> bool {
1632 return isLegal(op.getLayoutAttr());
1633 });
1634
1635 target.addDynamicallyLegalOp<arith::ConstantOp>(
1636 [=](arith::ConstantOp op) -> bool {
1637 auto vecType = dyn_cast<VectorType>(op.getType());
1638 if (!vecType)
1639 return true;
1640
1641 auto layout =
1642 xegpu::getTemporaryLayout(dyn_cast<OpResult>(op.getResult()));
1643 return isLegal(layout);
1644 });
1645
1646 target.addDynamicallyLegalOp<
1647 vector::ShapeCastOp, vector::StepOp, vector::TransposeOp,
1648 vector::BroadcastOp, vector::MultiDimReductionOp, vector::ConstantMaskOp,
1649 vector::CreateMaskOp, vector::BitCastOp, vector::InterleaveOp,
1650 vector::DeinterleaveOp>([=](Operation *op) -> bool {
1651 // Check for either a SliceAttr or LayoutAttr on the result.
1652 auto layout =
1653 xegpu::getTemporaryLayout(dyn_cast<OpResult>(op->getResult(0)));
1654 return isLegal(layout);
1655 });
1656
1657 target.addDynamicallyLegalOp<xegpu::LoadGatherOp>(
1658 [=](xegpu::LoadGatherOp op) -> bool {
1659 auto layout = op.getLayoutAttr();
1660 return isLegal(layout);
1661 });
1662
1663 target.addDynamicallyLegalOp<xegpu::StoreScatterOp>(
1664 [=](xegpu::StoreScatterOp op) -> bool {
1665 auto layout = op.getLayoutAttr();
1666 return isLegal(layout);
1667 });
1668
1669 target.addDynamicallyLegalOp<xegpu::ConvertLayoutOp>(
1670 [=](xegpu::ConvertLayoutOp op) -> bool {
1671 return isLegal(op.getEffectiveInputLayout()) &&
1672 isLegal(op.getTargetLayout());
1673 });
1674
1675 target.addDynamicallyLegalDialect<math::MathDialect, arith::ArithDialect>(
1676 [=](Operation *op) -> std::optional<bool> {
1677 // Only handle elementwise mappable ops
1679 return true;
1680
1681 VectorType resultType =
1682 dyn_cast<VectorType>(op->getResult(0).getType());
1683 if (!resultType)
1684 return true;
1685
1686 // Check if all operands are vectors of the same shape
1687 // TODO: Support other types.
1688 for (Value operand : op->getOperands()) {
1689 VectorType operandType = dyn_cast<VectorType>(operand.getType());
1690 if (!operandType || operandType.getShape() != resultType.getShape()) {
1691 return true;
1692 }
1693 }
1694
1695 xegpu::DistributeLayoutAttr layout =
1697 return isLegal(layout);
1698 });
1699
1700 target.addLegalOp<UnrealizedConversionCastOp>();
1701
1702 target.markUnknownOpDynamicallyLegal([](Operation *) { return true; });
1703
1705 target);
1707 if (failed(
1708 applyPartialConversion(getOperation(), target, std::move(patterns))))
1709 return signalPassFailure();
1710
1711 // Fold cancelling cast chains and erase dead casts.
1712 xegpu::cleanupUnrealizedConversionCasts(getOperation(), existingCasts);
1713 xegpu::removeTemporaryLayoutAttrs(getOperation());
1714}
return success()
lhs
b getContext())
#define mul(a, b)
Attributes are known-constant values of operations.
Definition Attributes.h:25
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext * getContext() const
Return the context this location is uniqued in.
Definition Location.h:86
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Attribute getDiscardableAttr(StringRef name)
Access a discardable attribute by name, returns a null Attribute if the discardable attribute does no...
Definition Operation.h:487
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Attribute getPropertiesAsAttribute()
Return the properties converted to an attribute.
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
Definition Operation.h:255
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
Definition Operation.h:555
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
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.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:453
bool hasElementwiseMappableTraits(Operation *op)
Together, Elementwise, Scalarizable, Vectorizable, and Tensorizable provide an easy way for scalar op...
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
void populateSCFStructuralTypeConversionsAndLegality(const TypeConverter &typeConverter, RewritePatternSet &patterns, ConversionTarget &target, PatternBenefit benefit=1)
Populates patterns for SCF structural type conversions and sets up the provided ConversionTarget with...
Value makeArithReduction(OpBuilder &b, Location loc, CombiningKind kind, Value v1, Value acc, arith::FastMathFlagsAttr fastmath=nullptr, Value mask=nullptr)
Returns the result value of reducing two scalar/vector values with the corresponding arith operation.
void removeTemporaryLayoutAttrs(Operation *op)
Removes the temporary layout attributes for each OpOperand and OpResult of the given operation.
void populateXeGPUWgToSgDistributeTypeConversions(TypeConverter &converter, Operation *topLevelOp)
Define the type conversions needed for XeGPU workgroup to subgroup distribution.
bool matchUnitDimExpansion(ArrayRef< int64_t > src, ArrayRef< int64_t > dst, SmallVector< int64_t > &expandedUnitDims)
bool recoverTemporaryLayouts(Operation *rootOp)
Attach layout attributes to all vector-type operands of operations within the given operation's neste...
DenseMap< Value, SmallVector< Type > > precomputeLoopBlockArgTypes(Operation *topLevelOp, SubShapeAndCountFn getSubShapeAndCount)
Pre-computes distributed VectorType mappings for every value carried through an SCF loop under topLev...
void populateXeGPUWgToSgDistributePatterns(RewritePatternSet &patterns)
Appends patterns for XeGPU workgroup to subgroup distribution into patterns.
void addVectorTypeConversion(TypeConverter &converter, SubShapeAndCountFn getSubShapeAndCount, DenseMap< Value, SmallVector< Type > > loopArgTypes)
Adds a context-aware VectorType conversion to converter (1:1 shape-changing or 1:N,...
Value createReductionNeutralValue(OpBuilder &builder, Location loc, Type type, vector::CombiningKind kind, arith::FastMathFlagsAttr fastmath=nullptr)
Creates a constant filled with the neutral (identity) value for the given reduction kind.
DistributeLayoutAttr getTemporaryLayout(const T &operandOrResult)
get and set distribute layout attribute for non-anchor operations (and offsets/masks of load/store op...
void removeLayoutAttrs(Operation *op)
Removes the DistributeLayoutAttr for each OpOperand and OpResult of the given operation if they exist...
void cleanupUnrealizedConversionCasts(Operation *root, const llvm::SmallSetVector< UnrealizedConversionCastOp, 8 > &existingCasts)
Cleans up UnrealizedConversionCastOps inserted during SCF structural type conversion and/or XeGPU unr...
SmallVector< OpFoldResult > addWithRightAligned(OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > lhs, ArrayRef< OpFoldResult > rhs)
Generates element-wise addition ops of two arrays with automatic alignment.
Include the generated interface declarations.
int64_t computeProduct(ArrayRef< int64_t > basis)
Self-explicit.
OpFoldResult getAsOpFoldResult(Value val)
Given a value, try to extract a constant Attribute.
This represents an operation in an abstracted form, suitable for use with the builder APIs.