MLIR 24.0.0git
XeGPUUtils.cpp
Go to the documentation of this file.
1//===---- XeGPUUtils.cpp - MLIR Utilities for XeGPUOps ------------------===//
2//
3// Part of the MLIR 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 utility methods for working with the XeGPU dialect.
10//
11//===----------------------------------------------------------------------===//
12
22#include "mlir/IR/Builders.h"
23#include "mlir/IR/BuiltinOps.h"
24#include "mlir/IR/Operation.h"
25#include "mlir/IR/ValueRange.h"
29#include "llvm/Support/Casting.h"
30#include "llvm/Support/FormatVariadic.h"
31#include <cstdint>
32#include <numeric>
33
34using namespace mlir;
35
36/// convert ArrayRef<ValueRange> into SmallVector<Value>
39 for (const auto &vals : values)
40 llvm::append_range(result, vals);
41 return result;
42}
43
44FailureOr<VectorType>
45mlir::xegpu::getDistributedVectorType(xegpu::TensorDescType tdescTy) {
46 auto layout = llvm::dyn_cast_if_present<LayoutAttr>(tdescTy.getLayout());
47 // It only works for subgroup level layout, which only has lane_layout
48 // and lane_data, and is to distribute a SIMD code into SIMT code.
49 if (!layout || !layout.isForSubgroup())
50 return failure();
51
52 SmallVector<int64_t> laneData(layout.getLaneData().asArrayRef());
53 SmallVector<int64_t> laneLayout(layout.getLaneLayout().asArrayRef());
54 auto tdescShape = tdescTy.getShape();
55 auto elementType = tdescTy.getElementType();
56
57 // compute sgSize by multiply elements of laneLayout
58 // e.g. for 2D layout, sgSize = laneLayout[0] * laneLayout[1]
59 // e.g. for 1D layout, sgSize = laneLayout[0]
60 int64_t sgSize = llvm::product_of(laneLayout);
61
62 // Check if the tensor descriptor shape is distributable.
63 int64_t tensorSize = 1;
64 for (auto [tdescDim, laneDim, laneDataDim] :
65 llvm::zip_equal(tdescShape, laneLayout, laneData)) {
66 assert((tdescDim % (laneDim * laneDataDim) == 0) &&
67 "tensor descriptor shape is not distributable");
68 tensorSize *= tdescDim;
69 }
70 // tensorSize must be adjusted for array_length.
71 tensorSize *= tdescTy.getArrayLength();
72
73 return VectorType::get({tensorSize / sgSize}, elementType);
74}
75
76FailureOr<VectorType>
77mlir::xegpu::getDistributedVectorType(VectorType originalType,
78 xegpu::LayoutAttr layout) {
79 int64_t rank = originalType.getRank();
80 if (rank < 1)
81 return failure();
82 ArrayRef<int64_t> shape = originalType.getShape();
83 // For rank > 2, leading dimensions are treated as batch/array dimensions.
84 // Drop them and use the product as arrayLength.
85 int arrayLength = 1;
86 while (shape.size() > 2) {
87 arrayLength *= shape[0];
88 shape = shape.drop_front();
89 }
90 // Drop matching leading dims from layout if the layout rank exceeds the
91 // remaining shape rank.
92 auto laneLayout = layout.getEffectiveLaneLayoutAsInt();
93 auto laneData = layout.getEffectiveLaneDataAsInt();
94 while (!laneLayout.empty() && laneLayout.size() > shape.size()) {
95 laneLayout.erase(laneLayout.begin());
96 laneData.erase(laneData.begin());
97 }
98 auto trimmedLayout = xegpu::LayoutAttr::get(
99 layout.getContext(),
100 SmallVector<int32_t>(laneLayout.begin(), laneLayout.end()),
101 SmallVector<int32_t>(laneData.begin(), laneData.end()));
102 auto helperTdescTy = xegpu::TensorDescType::get(
103 shape, originalType.getElementType(), arrayLength,
104 /*boundary_check=*/true,
105 /*memory_space=*/xegpu::MemorySpace::Global, trimmedLayout);
106 return xegpu::getDistributedVectorType(helperTdescTy);
107}
108
109FailureOr<VectorType>
110xegpu::getDistVecTypeBasedOnLaneLayout(xegpu::DistributeLayoutAttr layout,
111 VectorType originalType) {
112 if (!layout)
113 return failure();
114 assert((isa<xegpu::LayoutAttr>(layout) || isa<xegpu::SliceAttr>(layout)) &&
115 "Expecting a valid layout.");
116
117 int64_t vectorRank = originalType.getRank();
118 int64_t layoutRank = layout.getRank();
119 assert(vectorRank >= layoutRank && "Vector rank must be >= layout rank.");
120
121 // When the vector has more dimensions than the layout, only the trailing
122 // dimensions are distributed. Leading dimensions are preserved as-is.
123 int64_t offset = vectorRank - layoutRank;
124 ArrayRef<int64_t> fullShape = originalType.getShape();
125 SmallVector<int64_t> trailingShape(fullShape.begin() + offset,
126 fullShape.end());
127 auto distributedShapeOrFailure =
128 layout.computeDistributedShape(trailingShape);
129 if (failed(distributedShapeOrFailure))
130 return failure();
131
132 SmallVector<int64_t> resultShape(fullShape.begin(),
133 fullShape.begin() + offset);
134 resultShape.append(distributedShapeOrFailure->begin(),
135 distributedShapeOrFailure->end());
136 return VectorType::get(resultShape, originalType.getElementType());
137}
138
139std::string xegpu::getTemporaryLayoutName(const OpOperand &operand) {
140 const StringRef prefix("layout_operand_");
141 unsigned idx = const_cast<OpOperand &>(operand).getOperandNumber();
142 return llvm::formatv("{0}{1}", prefix, idx).str();
143}
144
146 const StringRef prefix = "layout_result_";
147 return llvm::formatv("{0}{1}", prefix, result.getResultNumber()).str();
148}
149
151 return isa<VectorType, xegpu::TensorDescType>(type);
152}
153
154xegpu::DistributeLayoutAttr xegpu::getDistributeLayoutAttr(const Value value) {
155 if (!value)
156 return nullptr;
157
158 if (auto result = dyn_cast<OpResult>(value)) {
159 Operation *defOp = result.getDefiningOp();
160 assert(defOp && "result must have a defining op");
161
162 if (auto anchorOp = dyn_cast<xegpu::AnchorLayoutInterface>(defOp)) {
163 auto layout = anchorOp.getAnchorLayout();
164 return layout;
165 }
166
167 std::string layoutName = getTemporaryLayoutName(result);
168 if (defOp->hasDiscardableAttr(layoutName)) {
169 auto layout =
170 defOp->getDiscardableAttrOfType<xegpu::DistributeLayoutAttr>(
171 layoutName);
172 return layout;
173 }
174 }
175
176 if (auto arg = dyn_cast<BlockArgument>(value)) {
177 auto *parentOp = arg.getOwner()->getParentOp();
178 auto loop = dyn_cast_if_present<LoopLikeOpInterface>(parentOp);
179 if (loop)
180 if (OpOperand *tiedInit = loop.getTiedLoopInit(arg))
181 return getTemporaryLayout(*tiedInit);
182 // An scf.while "after" argument is tied to no init operand; scf.condition
183 // feeds it. Only a pass-through is supported: the forwarded value must be
184 // the matching "before" argument, whose tied init operand carries the
185 // layout.
186 if (auto whileOp = dyn_cast_if_present<scf::WhileOp>(parentOp);
187 whileOp && arg.getOwner()->getParent() == &whileOp.getAfter()) {
188 Value forwarded = whileOp.getConditionOp().getArgs()[arg.getArgNumber()];
189 if (auto beforeArg = dyn_cast<BlockArgument>(forwarded))
190 if (OpOperand *tiedInit = whileOp.getTiedLoopInit(beforeArg))
191 return getTemporaryLayout(*tiedInit);
192 }
193 }
194
195 if (auto tdescTy =
196 dyn_cast_if_present<xegpu::TensorDescType>(value.getType()))
197 return tdescTy.getLayoutAttr();
198
199 return nullptr;
200}
201xegpu::DistributeLayoutAttr
203 Operation *op = opr.getOwner();
204 unsigned idx = const_cast<OpOperand &>(opr).getOperandNumber();
205
206 if (auto anchorOp = dyn_cast<xegpu::AnchorLayoutInterface>(op)) {
207 if (auto dpasOp = dyn_cast<xegpu::DpasOp>(op)) {
208 if (idx == 0) {
209 return dpasOp.getLayoutAAttr();
210 } else if (idx == 1) {
211 return dpasOp.getLayoutBAttr();
212 } else if (idx == 2) {
213 return dpasOp.getLayoutCdAttr();
214 }
215 }
216 if (auto dpasMxOp = dyn_cast<xegpu::DpasMxOp>(op)) {
217 // DpasMxOp has operands: a, b, optional acc, optional scale_a, optional
218 // scale_b
219 unsigned currentIdx = 0;
220
221 if (idx == currentIdx++)
222 return dpasMxOp.getLayoutAAttr();
223
224 if (idx == currentIdx++)
225 return dpasMxOp.getLayoutBAttr();
226
227 if (dpasMxOp.getAcc())
228 if (idx == currentIdx++)
229 return dpasMxOp.getLayoutCdAttr();
230
231 if (dpasMxOp.getScaleA())
232 if (idx == currentIdx++)
233 return dpasMxOp.getLayoutAScaleAttr();
234
235 if (dpasMxOp.getScaleB())
236 if (idx == currentIdx++)
237 return dpasMxOp.getLayoutBScaleAttr();
238
239 return nullptr;
240 }
241 if (auto convertOp = dyn_cast<xegpu::ConvertLayoutOp>(op)) {
242 return convertOp.getEffectiveInputLayout();
243 }
244 auto layout = anchorOp.getAnchorLayout();
245
246 if (idx == 0)
247 return layout;
248
249 // For StoreNdOp and StoreMatrixOp,
250 // the layout is valid for the first two operands: value and memref/tdesc.
251 if (isa<xegpu::StoreNdOp, xegpu::StoreMatrixOp>(op) && (idx < 2))
252 return layout;
253
254 // For gather/scatter ops the mask and offsets share the value's layout.
255 if (isa<xegpu::StoreScatterOp, xegpu::LoadGatherOp>(op))
256 return layout;
257 }
258
259 std::string layoutName = xegpu::getTemporaryLayoutName(opr);
260 if (op->hasDiscardableAttr(layoutName)) {
261 auto layout =
262 op->getDiscardableAttrOfType<xegpu::DistributeLayoutAttr>(layoutName);
263 return layout;
264 }
265
266 return nullptr;
267}
268
269// Returns the permanent layout attribute for the given result if it's
270// available on the defining op. Otherwise returns the provided layout.
271xegpu::DistributeLayoutAttr
272maybePickPermanentLayout(xegpu::DistributeLayoutAttr layout,
273 const OpResult &result, mlir::Operation *owner,
274 const std::string &name) {
275 xegpu::DistributeLayoutAttr candidate = layout;
276
277 if (auto loadOp = dyn_cast<xegpu::LoadGatherOp>(owner)) {
278 if (auto perm = loadOp.getLayoutAttr())
279 candidate = perm;
280 }
281
282 return candidate;
283}
284
285// Returns the permanent layout attribute for the given operand if it's
286// available on the defining op. Otherwise returns the provided layout.
287xegpu::DistributeLayoutAttr
288maybePickPermanentLayout(xegpu::DistributeLayoutAttr layout,
289 const OpOperand &operand, mlir::Operation *owner,
290 const std::string &name) {
291 xegpu::DistributeLayoutAttr candidate = layout;
292 unsigned idx = const_cast<OpOperand &>(operand).getOperandNumber();
293
294 if (auto storeOp = dyn_cast<xegpu::StoreScatterOp>(owner)) {
295 if (idx == 0) {
296 if (auto perm = storeOp.getLayoutAttr())
297 candidate = perm;
298 }
299 }
300
301 return candidate;
302}
303
304// TODO-LayoutRefactor: Remove this function after replacing use
305// with setTemporaryLayout or setAnchorLayout
307 const mlir::OpResult &result,
308 const mlir::xegpu::DistributeLayoutAttr layout) {
309 Operation *owner = result.getOwner();
310
311 if (auto anchorOp = dyn_cast<xegpu::AnchorLayoutInterface>(owner)) {
312 if (anchorOp.getAnchorLayout() == layout)
313 return;
314 anchorOp.setAnchorLayout(layout);
315 return;
316 }
317
318 std::string name = xegpu::getTemporaryLayoutName(result);
319 if (owner->hasDiscardableAttrOfType<DistributeLayoutAttr>(name)) {
320 return;
321 }
322 if (layout) {
323 owner->setDiscardableAttr(name, layout);
324 }
325}
326
327// TODO-LayoutRefactor: Remove this function after replacing use
328// with setTemporaryLayout or setAnchorLayout
330 const DistributeLayoutAttr layout) {
331 Operation *owner = operand.getOwner();
332 unsigned idx = const_cast<OpOperand &>(operand).getOperandNumber();
333
334 if (!layout) {
335 return;
336 }
337 if (auto anchorOp = dyn_cast<xegpu::AnchorLayoutInterface>(owner)) {
338 if (auto dpasOp = dyn_cast<xegpu::DpasOp>(owner)) {
339 if (idx == 0) {
340 return dpasOp.setLayoutAAttr(layout);
341 } else if (idx == 1) {
342 return dpasOp.setLayoutBAttr(layout);
343 } else if (idx == 2) {
344 return dpasOp.setLayoutCdAttr(layout);
345 }
346 }
347 if (auto convertOp = dyn_cast<xegpu::ConvertLayoutOp>(owner)) {
348 return convertOp.setInputLayoutAttr(layout);
349 }
350
351 // For store operations (StoreScatterOp, StoreNdOp, StoreMatrixOp),
352 // the layout is valid for the first two operands: value and memref/tdesc.
353 // For other operations, the layout applies to the first operand only.
354 if (isa<xegpu::StoreScatterOp, xegpu::StoreNdOp, xegpu::StoreMatrixOp>(
355 owner)) {
356 if (idx < 2) {
357 anchorOp.setAnchorLayout(layout);
358 }
359 } else {
360 if (idx == 0) {
361 anchorOp.setAnchorLayout(layout);
362 }
363 }
364 }
365
366 std::string name = xegpu::getTemporaryLayoutName(operand);
367 if (owner->hasDiscardableAttrOfType<DistributeLayoutAttr>(name)) {
368 return;
369 }
370 if (layout) {
371 owner->setDiscardableAttr(name, layout);
372 }
373}
374
375template <typename T, typename>
376xegpu::DistributeLayoutAttr
377xegpu::getTemporaryLayout(const T &operandOrResult) {
378 Operation *op = operandOrResult.getOwner();
379
380 std::string layoutName = xegpu::getTemporaryLayoutName(operandOrResult);
381 if (op->hasDiscardableAttr(layoutName)) {
382 auto layout =
383 op->getDiscardableAttrOfType<xegpu::DistributeLayoutAttr>(layoutName);
384 return layout;
385 }
386
387 return nullptr;
388}
389
390template xegpu::DistributeLayoutAttr
392template xegpu::DistributeLayoutAttr
394
395template <typename T, typename>
396void xegpu::setTemporaryLayout(const T &operandOrResult,
397 const xegpu::DistributeLayoutAttr layout) {
398 Operation *owner = operandOrResult.getOwner();
399 std::string name = xegpu::getTemporaryLayoutName(operandOrResult);
400 if (owner->hasDiscardableAttrOfType<xegpu::DistributeLayoutAttr>(name)) {
401 return;
402 }
403 if (layout) {
404 owner->setDiscardableAttr(name, layout);
405 }
406}
407
409 const mlir::OpResult &result,
410 const mlir::xegpu::DistributeLayoutAttr layout);
411
413 const mlir::OpOperand &operand,
414 const mlir::xegpu::DistributeLayoutAttr layout);
415
416void xegpu::setTensorDescLayout(Value value, DistributeLayoutAttr layout) {
417 auto tdescTy = cast<xegpu::TensorDescType>(value.getType());
418 value.setType(xegpu::TensorDescType::get(
419 tdescTy.getContext(), tdescTy.getShape(), tdescTy.getElementType(),
420 tdescTy.getEncoding(), layout));
421}
422
426 auto vecTy = dyn_cast<VectorType>(value.getType());
427 if (!vecTy)
428 return {value};
429
430 ArrayRef<int64_t> srcShape = vecTy.getShape();
431 if (!computeShapeRatio(srcShape, shape))
432 return {value};
433
434 int64_t srcShapeRank = srcShape.size();
435 int64_t targetShapeRank = shape.size();
436
437 SmallVector<int64_t> adjustedTargetShape(srcShape.size());
438 int64_t rankDiff = srcShapeRank - targetShapeRank;
439 std::fill(adjustedTargetShape.begin(), adjustedTargetShape.begin() + rankDiff,
440 1);
441 llvm::copy(shape, adjustedTargetShape.begin() + rankDiff);
442
444 for (SmallVector<int64_t> offsets :
445 StaticTileOffsetRange(srcShape, adjustedTargetShape)) {
446 SmallVector<int64_t> staticStrides(offsets.size(), 1);
447 Value slice = vector::ExtractStridedSliceOp::create(
448 builder, loc, value, offsets, adjustedTargetShape, staticStrides);
449
450 // Reshape to remove leading unit dims if needed
451 if (srcShapeRank > targetShapeRank) {
452 auto targetTy = VectorType::get(shape, vecTy.getElementType());
453 slice = vector::ShapeCastOp::create(builder, loc, targetTy, slice);
454 }
455 result.push_back(slice);
456 }
457
458 return result;
459}
460
462 ValueRange values,
464 VectorType inputTy = dyn_cast<VectorType>(values[0].getType());
465 assert(llvm::all_of(values.getTypes(),
466 [&](Type type) { return type == inputTy; }) &&
467 "values must be of the same VectorType");
468
469 Type elemTy = inputTy.getElementType();
470 ArrayRef<int64_t> tileShape = inputTy.getShape();
471
472 VectorType resultTy = VectorType::get(shape, elemTy);
473 auto zeroAttr = builder.getZeroAttr(elemTy);
474 Value result = arith::ConstantOp::create(
475 builder, loc, resultTy, DenseElementsAttr::get(resultTy, zeroAttr));
476
477 for (auto [src, offsets] :
478 llvm::zip_equal(values, StaticTileOffsetRange(shape, tileShape))) {
479 SmallVector<int64_t> staticStrides(tileShape.size(), 1);
480 result = vector::InsertStridedSliceOp::create(builder, loc, src, result,
481 offsets, staticStrides);
482 }
483 return result;
484}
485
486std::optional<std::string> xegpu::getChipStr(Operation *op) {
487 auto gpuModuleOp = op->getParentOfType<gpu::GPUModuleOp>();
488
489 if (!gpuModuleOp)
490 return std::nullopt;
491
492 auto targetAttrs = gpuModuleOp.getTargets();
493 if (targetAttrs) {
494 for (auto &attr : *targetAttrs) {
495 auto xevmAttr = llvm::dyn_cast<xevm::XeVMTargetAttr>(attr);
496 if (xevmAttr)
497 return xevmAttr.getChip().str();
498 }
499 }
500
501 return std::nullopt;
502}
503
505 int64_t subgroupSize) {
506 auto gpuFunc = op->getParentOfType<gpu::GPUFuncOp>();
507 if (!gpuFunc)
508 return failure();
509 std::optional<ArrayRef<int32_t>> blockSize = gpuFunc.getKnownBlockSize();
510 if (!blockSize)
511 return failure();
512 if (!llvm::all_of(*blockSize, [](int32_t dim) {
513 return dim > 0 && llvm::isPowerOf2_32(dim);
514 }))
515 return failure();
516 int64_t numSubgroups = llvm::product_of(*blockSize) / subgroupSize;
517 if (numSubgroups < 1)
518 return failure();
519 return numSubgroups;
520}
521
522/// Generates element-wise addition ops of two arrays with same length.
524 Location loc,
527 assert(lhs.size() == rhs.size() && "lhs and rhs must have the same size");
529 for (auto [l, r] : llvm::zip_equal(lhs, rhs)) {
530 auto lval = getValueOrCreateConstantIndexOp(builder, loc, l);
531 auto rval = getValueOrCreateConstantIndexOp(builder, loc, r);
532 results.push_back(builder.createOrFold<arith::AddIOp>(loc, lval, rval));
533 }
534 return results;
535}
536
537/// Generates element-wise addition ops of two arrays with automatic alignment.
538/// When the input arrays have different sizes, the shorter array is
539/// right-aligned with the longer array, and the unmatched leading elements from
540/// the longer array are preserved unchanged. This is commonly used for offset
541/// computation where higher-dimensional offsets need to be added to
542/// lower-dimensional adjustments.
543///
544/// Example:
545/// lhs = [l1, l2, l3], rhs = [r1, r2]
546/// Result: [11, l2+r1, l3+r2]
551 // ensure a is longer than b
552 ArrayRef<OpFoldResult> a = lhs.size() >= rhs.size() ? lhs : rhs;
553 ArrayRef<OpFoldResult> b = lhs.size() >= rhs.size() ? rhs : lhs;
554 SmallVector<OpFoldResult> results(a.take_front(a.size() - b.size()));
555 a = a.slice(a.size() - b.size());
556 results.append(addElementwise(builder, loc, a, b));
557 return results;
558}
559
560template <typename T>
562 ArrayRef<T> candidateMultiples) {
563 static_assert(std::is_integral<T>::value, "T must be an integer type");
564 int largest = -1;
565 SmallVector<T> multiples = {1};
566 if (!candidateMultiples.empty())
567 multiples =
568 SmallVector<T>(candidateMultiples.begin(), candidateMultiples.end());
569 for (T candidate : candidates) {
570 for (T multiple : multiples) {
571 int value = static_cast<int>(candidate * multiple);
572 if (value != 0 && dim % value == 0 && value > largest)
573 largest = value;
574 }
575 }
576 return largest;
577}
578
579/// Returns the flags held by `fastmath`, or none if it is null.
580static arith::FastMathFlags getFlags(arith::FastMathFlagsAttr fastmath) {
581 return fastmath ? fastmath.getValue() : arith::FastMathFlags::none;
582}
583
585 vector::CombiningKind kind, uint32_t size,
586 arith::FastMathFlagsAttr fastmath) {
587 // First reduce on a single thread to get per lane reduction value.
588 Value laneVal = vector::ReductionOp::create(builder, loc, kind, input,
589 getFlags(fastmath));
590 // Parallel reduction using butterfly shuffles.
591 for (uint64_t i = 1; i < size; i <<= 1) {
592 Value shuffled =
593 gpu::ShuffleOp::create(builder, loc, laneVal, i, /** width = **/ size,
594 /** mode = **/ gpu::ShuffleMode::XOR)
595 .getShuffleResult();
596 laneVal =
597 makeArithReduction(builder, loc, kind, laneVal, shuffled, fastmath);
598 }
599 return laneVal;
600}
601
604 vector::CombiningKind kind,
605 int64_t reductionDim, Location loc,
606 PatternRewriter &rewriter,
607 arith::FastMathFlagsAttr fastmath) {
608 VectorType sourceType = src.getType();
609 int64_t sourceRank = sourceType.getRank();
610 // Expecting at least a 2D source vector. Leading dimensions (all except the
611 // last two) must be unit.
612 assert(sourceRank >= 2 && "expected at least a 2D source vector");
613 for (int64_t i = 0; i < sourceRank - 2; ++i)
614 assert(sourceType.getShape()[i] == 1 &&
615 "expected leading dimensions to be unit");
616 int64_t rowIdx = sourceRank - 2;
617 int64_t columnIdx = sourceRank - 1;
618 assert((reductionDim == rowIdx || reductionDim == columnIdx) &&
619 "expected the reduction dim to be one of the last two dims");
620 int64_t sourceH = sourceType.getShape()[rowIdx];
621 int64_t sourceW = sourceType.getShape()[columnIdx];
622 int nSlices = (reductionDim == rowIdx) ? sourceW : sourceH;
623 // Create a constant vector to hold the result of the reduction.
624 TypedAttr zeroAttr = rewriter.getZeroAttr(sourceType.getElementType());
625 Value reductionResult = arith::ConstantOp::create(
626 rewriter, loc, acc.getType(),
627 DenseElementsAttr::get(acc.getType(), zeroAttr));
628 auto srcLayout = xegpu::getTemporaryLayout(dyn_cast<OpResult>(src));
629 auto accLayout = xegpu::getTemporaryLayout(dyn_cast<OpResult>(acc));
630 // Reduction result should have the same layout as the accumulator.
631 xegpu::setTemporaryLayout(cast<OpResult>(reductionResult), accLayout);
632 // For each slice of the source, extract the slice vector, do a reduction
633 // and, insert the reduced value back to the result vector.
634 int64_t accRank = acc.getType().getRank();
635 for (int i = 0; i < nSlices; ++i) {
636 // Build nD offsets, sizes, and strides. Leading unit dims get
637 // offset=0, size=1. The last two dims are set based on reductionDim.
638 SmallVector<int64_t> sliceOffsets(sourceRank, 0);
639 SmallVector<int64_t> sliceSizes(sourceRank, 1);
640 SmallVector<int64_t> strides(sourceRank, 1);
641 if (reductionDim == columnIdx) {
642 sliceOffsets[rowIdx] = i;
643 sliceSizes[columnIdx] = sourceW;
644 } else {
645 sliceOffsets[columnIdx] = i;
646 sliceSizes[rowIdx] = sourceH;
647 }
648
649 vector::ExtractStridedSliceOp extractOp =
650 vector::ExtractStridedSliceOp::create(rewriter, loc, src, sliceOffsets,
651 sliceSizes, strides);
652 // Extract strided slice has the same layout as src.
653 xegpu::setTemporaryLayout(extractOp->getOpResult(0), srcLayout);
654
655 int64_t nSliceElements = extractOp.getResult().getType().getNumElements();
656
657 vector::ShapeCastOp slice = vector::ShapeCastOp::create(
658 rewriter, loc,
659 VectorType::get({nSliceElements}, sourceType.getElementType()),
660 extractOp.getResult());
661
662 // Shape cast output has the same layout as the accumulator. Shape cast
663 // source has the same layout as the original reduction source.
664 xegpu::setTemporaryLayout(slice->getOpOperand(0), srcLayout);
665 xegpu::setTemporaryLayout(slice->getOpResult(0), accLayout);
666 // Extract and reduction results in scalars, so no result layout is needed.
667 // Build multi-dim index into acc (sourceRank-1 dims, i.e. source shape with
668 // the reduction dim removed). Leading unit dims get index 0.
669 SmallVector<int64_t> accIdx(accRank, 0);
670 accIdx[accRank - 1] = i;
671 Value accExtract = vector::ExtractOp::create(rewriter, loc, acc, accIdx);
672 Value reduction = vector::ReductionOp::create(
673 rewriter, loc, kind, slice.getResult(), accExtract, getFlags(fastmath));
674 reductionResult = vector::InsertOp::create(rewriter, loc, reduction,
675 reductionResult, accIdx);
676 // Insert op should have the same layout as the accumulator.
677 xegpu::setTemporaryLayout(cast<OpResult>(reductionResult), accLayout);
678 }
679 return reductionResult;
680}
681
684 vector::CombiningKind kind, int64_t reductionDim, int64_t reductionSize,
685 Location loc, PatternRewriter &rewriter,
686 arith::FastMathFlagsAttr fastmath) {
687 VectorType sourceType = src.getType();
688 int64_t sourceRank = sourceType.getRank();
689 // Expecting at least a 2D source vector. Leading dimensions (all except the
690 // last two) must be unit.
691 assert(sourceRank >= 2 && "expected at least a 2D source vector");
692 for (int64_t i = 0; i < sourceRank - 2; ++i)
693 assert(sourceType.getShape()[i] == 1 &&
694 "expected leading dimensions to be unit");
695 int64_t rowIdx = sourceRank - 2;
696 int64_t columnIdx = sourceRank - 1;
697 int64_t sourceH = sourceType.getShape()[rowIdx];
698 int64_t sourceW = sourceType.getShape()[columnIdx];
699
700 // Create a constant vector to hold the result of the reduction.
701 TypedAttr zeroAttr = rewriter.getZeroAttr(sourceType.getElementType());
702 Value reductionResult = arith::ConstantOp::create(
703 rewriter, loc, acc.getType(),
704 DenseElementsAttr::get(acc.getType(), zeroAttr));
705
706 // nSlices is the number of reduction operations needed to reduce the entire
707 // source vector. For example, if reductionDim is the row dim, we are
708 // reducing across rows, and each slice is a column. So the number of slices
709 // is the number of columns, which is sourceW.
710 int nSlices = (reductionDim == rowIdx) ? sourceW : sourceH;
711
712 // For each slice of the source, extract the slice vector, do a reduction
713 // and, insert the reduced value back to the result vector.
714 int64_t accRank = acc.getType().getRank();
715 for (int i = 0; i < nSlices; ++i) {
716 // Build nD offsets, sizes, and strides. Leading unit dims get
717 // offset=0, size=1. The last two dims are set based on reductionDim.
718 SmallVector<int64_t> sliceOffsets(sourceRank, 0);
719 SmallVector<int64_t> sliceSizes(sourceRank, 1);
720 SmallVector<int64_t> strides(sourceRank, 1);
721 if (reductionDim == columnIdx) {
722 sliceOffsets[rowIdx] = i;
723 sliceSizes[columnIdx] = sourceW;
724 } else {
725 sliceOffsets[columnIdx] = i;
726 sliceSizes[rowIdx] = sourceH;
727 }
728
729 vector::ExtractStridedSliceOp extractOp =
730 vector::ExtractStridedSliceOp::create(rewriter, loc, src, sliceOffsets,
731 sliceSizes, strides);
732 int64_t nSliceElements = extractOp.getResult().getType().getNumElements();
733 vector::ShapeCastOp slice = vector::ShapeCastOp::create(
734 rewriter, loc,
735 VectorType::get({nSliceElements}, sourceType.getElementType()),
736 extractOp.getResult());
737
738 SmallVector<int64_t> accIdx(accRank, 0);
739 accIdx[accRank - 1] = i;
740 Value accExtract = vector::ExtractOp::create(rewriter, loc, acc, accIdx);
741 Value fullReduce = xegpu::subgroupReduction(loc, rewriter, slice, kind,
742 reductionSize, fastmath);
743 fullReduce = vector::makeArithReduction(rewriter, loc, kind, fullReduce,
744 accExtract, fastmath);
745 reductionResult = vector::InsertOp::create(rewriter, loc, fullReduce,
746 reductionResult, accIdx);
747 }
748 return reductionResult;
749}
750
751/// Returns the neutral value of the float min or max reduction `kind` over
752/// elements of `semantics`. The reduction combines this value under its
753/// fast-math `flags`, so build only a value that the format can represent and
754/// the flags allow:
755/// - A kind that ignores NaN operands uses a quiet NaN, if the format has one
756/// and `nnan` is not set.
757/// - Otherwise it uses the infinity that never wins, if the format has one and
758/// `ninf` is not set.
759/// - Otherwise it uses the lowest (for max) or highest (for min) finite value.
760/// That value never wins either: no number that the format and the flags
761/// allow is below the lowest or above the highest finite value.
762static APFloat getMinMaxNeutral(const llvm::fltSemantics &semantics,
763 vector::CombiningKind kind,
764 arith::FastMathFlags flags) {
765 bool isMax = kind == vector::CombiningKind::MAXIMUMF ||
766 kind == vector::CombiningKind::MAXNUMF ||
767 kind == vector::CombiningKind::MAXIMUMNUMF;
768 bool ignoresNaN = kind != vector::CombiningKind::MINIMUMF &&
769 kind != vector::CombiningKind::MAXIMUMF;
770 if (ignoresNaN && APFloat::semanticsHasNaN(semantics) &&
771 !arith::bitEnumContainsAny(flags, arith::FastMathFlags::nnan))
772 return APFloat::getQNaN(semantics);
773 bool useInf = APFloat::semanticsHasInf(semantics) &&
774 !arith::bitEnumContainsAny(flags, arith::FastMathFlags::ninf);
775 if (!isMax)
776 return useInf ? APFloat::getInf(semantics) : APFloat::getLargest(semantics);
777 // An unsigned format has no negative values. Its lowest value is zero, or
778 // its smallest positive value if it has no zero.
779 if (!APFloat::semanticsHasSignedRepr(semantics))
780 return APFloat::semanticsHasZero(semantics)
781 ? APFloat::getZero(semantics)
782 : APFloat::getSmallest(semantics);
783 return useInf ? APFloat::getInf(semantics, /*Negative=*/true)
784 : APFloat::getLargest(semantics, /*Negative=*/true);
785}
786
788 Type type, vector::CombiningKind kind,
789 arith::FastMathFlagsAttr fastmath) {
790 auto vecTy = dyn_cast<VectorType>(type);
791 Type elemTy = vecTy ? vecTy.getElementType() : type;
792
793 // Helper to create either a splat vector or scalar constant from an attr.
794 auto makeConst = [&](Attribute scalarAttr) -> Value {
795 if (vecTy)
796 return arith::ConstantOp::create(
797 builder, loc, vecTy, DenseElementsAttr::get(vecTy, scalarAttr));
798 return arith::ConstantOp::create(builder, loc, cast<TypedAttr>(scalarAttr));
799 };
800
801 switch (kind) {
802 case vector::CombiningKind::ADD:
803 case vector::CombiningKind::XOR:
804 case vector::CombiningKind::OR:
805 case vector::CombiningKind::MAXUI:
806 return makeConst(builder.getZeroAttr(elemTy));
807
808 case vector::CombiningKind::MUL:
809 return makeConst(builder.getOneAttr(elemTy));
810
811 case vector::CombiningKind::AND:
812 if (auto intTy = dyn_cast<IntegerType>(elemTy))
813 return makeConst(
814 builder.getIntegerAttr(elemTy, APInt::getAllOnes(intTy.getWidth())));
815 if (elemTy.isIndex())
816 return makeConst(builder.getIndexAttr(-1));
817 return nullptr;
818
819 case vector::CombiningKind::MINSI:
820 if (auto intTy = dyn_cast<IntegerType>(elemTy))
821 return makeConst(builder.getIntegerAttr(
822 elemTy, APInt::getSignedMaxValue(intTy.getWidth())));
823 return nullptr;
824
825 case vector::CombiningKind::MINUI:
826 if (auto intTy = dyn_cast<IntegerType>(elemTy))
827 return makeConst(
828 builder.getIntegerAttr(elemTy, APInt::getMaxValue(intTy.getWidth())));
829 return nullptr;
830
831 case vector::CombiningKind::MAXSI:
832 if (auto intTy = dyn_cast<IntegerType>(elemTy))
833 return makeConst(builder.getIntegerAttr(
834 elemTy, APInt::getSignedMinValue(intTy.getWidth())));
835 return nullptr;
836
837 case vector::CombiningKind::MINIMUMF:
838 case vector::CombiningKind::MAXIMUMF:
839 case vector::CombiningKind::MINNUMF:
840 case vector::CombiningKind::MINIMUMNUMF:
841 case vector::CombiningKind::MAXNUMF:
842 case vector::CombiningKind::MAXIMUMNUMF:
843 if (auto floatTy = dyn_cast<FloatType>(elemTy))
844 return makeConst(builder.getFloatAttr(
845 elemTy, getMinMaxNeutral(floatTy.getFloatSemantics(), kind,
846 getFlags(fastmath))));
847 return nullptr;
848 }
849 return nullptr;
850}
851
852/// Explicit instantiations
853template int xegpu::getLargestDivisor<int>(int dim, ArrayRef<int> candidates,
854 ArrayRef<int> candidateMultiples);
855template int
857 ArrayRef<unsigned> candidateMultiples);
858
859std::optional<SmallVector<int64_t>>
861 if (vals.size() < 2)
862 return std::nullopt;
863 if (llvm::any_of(vals.drop_back(2), [](int64_t v) { return v != 1; }))
864 return std::nullopt;
865 return SmallVector<int64_t>(vals.take_back(2));
866}
867
868bool xegpu::requirePacked(const xegpu::DistributeLayoutAttr layout) {
869 if (!layout)
870 return false;
871 auto laneData =
872 getInner2DIfUnitLeadingDims(layout.getEffectiveLaneDataAsInt());
873 return laneData && (*laneData)[0] != 1;
874}
875
876bool xegpu::requireTranspose(const xegpu::DistributeLayoutAttr layout,
877 const xegpu::uArch::uArch *uArch) {
878 // Return false for unsupported targets.
879 // TODO: Add more support or move to target info.
880 if (!isa<xegpu::uArch::Xe2>(uArch) && !isa<xegpu::uArch::Xe3p>(uArch))
881 return false;
882 if (!layout)
883 return false;
884 auto laneLayout =
885 getInner2DIfUnitLeadingDims(layout.getEffectiveLaneLayoutAsInt());
886 return laneLayout && (*laneLayout)[0] == uArch->getSubgroupSize() &&
887 (*laneLayout)[1] == 1;
888}
889
890bool xegpu::hasStaticShapeAndStrides(MemRefType type) {
891 if (!type.hasStaticShape())
892 return false;
893 SmallVector<int64_t> strides;
894 int64_t offset;
895 return succeeded(type.getStridesAndOffset(strides, offset)) &&
896 llvm::none_of(strides, ShapedType::isDynamic);
897}
898
900 Value baseAddr, Value elemOffset,
901 MemRefType memrefTy) {
902 Type type = elemOffset.getType();
903 assert(baseAddr.getType() == type &&
904 "expected base address and offset of the same type");
905 auto makeConst = [&](int64_t value) -> Value {
906 return arith::ConstantOp::create(builder, loc, type,
907 builder.getIntegerAttr(type, value));
908 };
909
910 // finalAddr = baseAddr + elemOffset * bitWidth / 8
911 unsigned elemBits = memrefTy.getElementTypeBitWidth();
912 Value byteOffset;
913 if (elemBits % 8 == 0) {
914 // For byte-sized elements divide by 8 statically so that the division is
915 // folded into the constant:
916 // finalAddr = baseAddr + elemOffset * (bitWidth / 8)
917 byteOffset = arith::MulIOp::create(builder, loc, elemOffset,
918 makeConst(elemBits / 8));
919 } else {
920 // For sub-byte elements multiply first and then divide by 8, otherwise the
921 // byte size would be zero (e.g. 4 / 8 == 0 for i4):
922 // finalAddr = baseAddr + (elemOffset * bitWidth) / 8
923 Value bitSize = makeConst(elemBits);
924 Value eight = makeConst(8);
925 byteOffset = arith::DivUIOp::create(
926 builder, loc, arith::MulIOp::create(builder, loc, elemOffset, bitSize),
927 eight);
928 }
929 return arith::AddIOp::create(builder, loc, baseAddr, byteOffset);
930}
931
932// Check if dst shape is an expansion of src shape by inserting unit dimensions.
933// Returns true if all dimensions in src match corresponding dimensions in dst
934// (after skipping unit dimensions), and populates expandedUnitDims with the
935// indices of the unit dimensions in dst that were added (not present in src).
936// Example: src=[2,3], dst=[1,2,3,1] -> true, expandedUnitDims=[0,3]
938 SmallVector<int64_t> &expandedUnitDims) {
939 // All unit dimensions in dst that don't appear in src are the expanded
940 // unit dimensions
941 size_t srcIdx = 0;
942 for (size_t dstIdx = 0; dstIdx < dst.size(); ++dstIdx)
943 if (srcIdx < src.size() && src[srcIdx] == dst[dstIdx])
944 srcIdx++;
945 else if (dst[dstIdx] == 1)
946 expandedUnitDims.push_back(dstIdx);
947 else
948 return false;
949 return srcIdx == src.size();
950}
951
952// Checks if dst shape is an expansion of src shape where each dimension in src
953// is split into one or more consecutive dimensions in dst whose product equals
954// the original dimension. Populates splitDimGroups with groups of dst indices
955// for each src dimension; later groups hold higher dims. Example: src=[6,4],
956// dst=[2,3,2,2] -> [[0, 1], [2, 3]]. Shapes that only insert unit dimensions
957// are rejected here.
960 SmallVector<SmallVector<int64_t>> &splitDimGroups) {
961 SmallVector<int64_t> expandedUnitDims;
962 if (matchUnitDimExpansion(src, dst, expandedUnitDims) &&
963 !expandedUnitDims.empty())
964 return false;
965
966 // each dim in src can be mapped to one or more dims in dst whose product
967 // equals to the src dim
968 size_t srcIdx = 0;
969 int64_t accumulatedSize = 1;
970 SmallVector<int64_t> currentDstDims;
971
972 splitDimGroups.clear();
973 for (size_t dstIdx = 0; dstIdx < dst.size(); ++dstIdx) {
974 if (srcIdx >= src.size())
975 return false;
976 accumulatedSize *= dst[dstIdx];
977 currentDstDims.push_back(dstIdx);
978
979 if (accumulatedSize == src[srcIdx]) {
980 // Also collect trailing unit dims in destination, if any.
981 // Leading unit dims were implicitly collected.
982 if (srcIdx == src.size() - 1) {
983 while (++dstIdx < dst.size() && dst[dstIdx] == 1)
984 currentDstDims.push_back(dstIdx);
985 }
986 // Record the mapping: srcIdx -> currentDstDims
987 splitDimGroups.push_back(currentDstDims);
988 // move to next src dim
989 srcIdx++;
990 accumulatedSize = 1;
991 currentDstDims.clear();
992 } else if (accumulatedSize > src[srcIdx]) {
993 return false;
994 }
995 }
996 return srcIdx == src.size();
997}
998
999//===----------------------------------------------------------------------===//
1000// Context-aware type conversion utilities
1001//===----------------------------------------------------------------------===//
1002
1003// Pre-computes distributed VectorType mappings for every value carried through
1004// an SCF region-branch op (scf.while, scf.for, scf.if): block args (iter_args /
1005// before-/after-args), op results, and the terminator operands feeding them.
1006// These positions share one logical value and must convert identically, so each
1007// is derived from a single source -- the layout of the feeding value (loop
1008// init, `scf.condition` operand, or `scf.if` result) -- via
1009// `getDistributeLayoutAttr(Value)`, and keyed by `Value`. Keying by Value is
1010// required because the SCF converters
1011// detach/replace the loop body mid-conversion (scf.while detaches before/after
1012// blocks -> a detached-arg layout query trips an ilist assertion; scf.for
1013// rebuilds the op, which loses the temporary `layout_operand_N` attrs -> the
1014// query returns null). Recording results and terminator operands lets a 1:N
1015// pass resolve them from the map after stripping the loop op's transient attrs
1016// (see XeGPUBlocking).
1019 SubShapeAndCountFn getSubShapeAndCount) {
1021 // Derive the distributed types from the feeding value's layout (the single
1022 // authoritative source) and record them for every value that shares this
1023 // loop-carried position.
1024 auto recordTypes = [&](Value layoutSrc, ArrayRef<Value> dests) {
1025 auto vecTy = dyn_cast<VectorType>(layoutSrc.getType());
1026 if (!vecTy)
1027 return;
1028 auto layout = xegpu::getDistributeLayoutAttr(layoutSrc);
1029 if (!layout)
1030 return;
1031 auto [subShape, count] = getSubShapeAndCount(vecTy, layout);
1032 if (count <= 0)
1033 return;
1034 auto newTy = VectorType::get(subShape, vecTy.getElementType());
1035 for (Value dest : dests)
1036 loopArgTypes[dest] = SmallVector<Type>(count, newTy);
1037 };
1038 topLevelOp->walk([&](Operation *op) {
1039 if (auto whileOp = dyn_cast<scf::WhileOp>(op)) {
1040 // "before" args (and the after-region yield operands that feed them)
1041 // correspond to the while `inits` operands.
1042 auto yieldOp =
1043 cast<scf::YieldOp>(whileOp.getAfterBody()->getTerminator());
1044 for (auto [init, beforeArg, yieldVal] :
1045 llvm::zip(whileOp.getInits(), whileOp.getBeforeArguments(),
1046 yieldOp.getOperands()))
1047 recordTypes(init, {beforeArg, yieldVal});
1048 // "after" args and the while results correspond to the operands of the
1049 // embedded `scf.condition` op (not the `inits`).
1050 scf::ConditionOp condOp = whileOp.getConditionOp();
1051 for (auto [condArg, afterArg, res] :
1052 llvm::zip(condOp.getArgs(), whileOp.getAfterArguments(),
1053 whileOp.getResults()))
1054 recordTypes(condArg, {afterArg, res});
1055 return;
1056 }
1057 if (auto forOp = dyn_cast<scf::ForOp>(op)) {
1058 // Each loop-carried position pairs an init operand with its iter_arg,
1059 // its loop result, and the yield operand that feeds the next iteration.
1060 auto yieldOp = cast<scf::YieldOp>(forOp.getBody()->getTerminator());
1061 for (auto [init, arg, res, yieldVal] :
1062 llvm::zip(forOp.getInitArgs(), forOp.getRegionIterArgs(),
1063 forOp.getResults(), yieldOp.getOperands()))
1064 recordTypes(init, {arg, res, yieldVal});
1065 return;
1066 }
1067 if (auto ifOp = dyn_cast<scf::IfOp>(op)) {
1068 // Each result and its then/else yield operands share one position and
1069 // must convert identically; derive all from the result's layout.
1070 scf::YieldOp thenYield = ifOp.thenYield();
1071 scf::YieldOp elseYield = ifOp.elseBlock() ? ifOp.elseYield() : nullptr;
1072 for (auto [idx, res] : llvm::enumerate(ifOp.getResults())) {
1073 SmallVector<Value> dests{res, thenYield.getOperand(idx)};
1074 if (elseYield)
1075 dests.push_back(elseYield.getOperand(idx));
1076 recordTypes(res, dests);
1077 }
1078 return;
1079 }
1080 });
1081 return loopArgTypes;
1082}
1083
1085 TypeConverter &converter, SubShapeAndCountFn getSubShapeAndCount,
1086 DenseMap<Value, SmallVector<Type>> loopArgTypes) {
1087 // Context-aware VectorType conversion (1:1 shape-changing or 1:N). For
1088 // SCF loop block arguments (scf.while, scf.for), uses the pre-computed
1089 // map. For all other Values, retrieves the layout directly via
1090 // getDistributeLayoutAttr.
1091 auto loopArgTypeMap = std::make_shared<DenseMap<Value, SmallVector<Type>>>(
1092 std::move(loopArgTypes));
1093 converter.addConversion(
1094 [loopArgTypeMap, getSubShapeAndCount](
1095 Value v,
1096 SmallVectorImpl<Type> &result) -> std::optional<LogicalResult> {
1097 if (!isa<VectorType>(v.getType()))
1098 return std::nullopt;
1099
1100 // Check the pre-computed map first. It covers every value carried
1101 // through an SCF loop (operands, block args, results, yield
1102 // operands), all keyed by Value identity.
1103 auto it = loopArgTypeMap->find(v);
1104 if (it != loopArgTypeMap->end()) {
1105 result.append(it->second.begin(), it->second.end());
1106 return success();
1107 }
1108
1109 // For all other Values, retrieve the layout directly.
1110 auto layout = xegpu::getDistributeLayoutAttr(v);
1111 if (!layout)
1112 return std::nullopt;
1113
1114 auto vecType = cast<VectorType>(v.getType());
1115 auto [subShape, count] = getSubShapeAndCount(vecType, layout);
1116 if (count <= 0)
1117 return std::nullopt;
1118
1119 auto newTy = VectorType::get(subShape, vecType.getElementType());
1120 result.append(count, newTy);
1121 return success();
1122 });
1123}
1124
1126 Operation *root,
1127 const llvm::SmallSetVector<UnrealizedConversionCastOp, 8> &existingCasts) {
1128 // Structural type conversion can generate some redundant
1129 // UnrealizedConversionCastOps to materialize the original type from the
1130 // type converted (sub-tile) type. These are redundant at this point and
1131 // can be eliminated by either folding the cancelling cast chain or, when
1132 // the original and final shapes differ but their element counts match,
1133 // inserting a vector.shape_cast instead.
1134 //
1135 // Example (shape differs but element count matches -> shape_cast):
1136 // %1 = UnrealizedConversionCastOp %0 : vector<16x1xf32>
1137 // to vector<16x16xf32>
1138 // %2 = UnrealizedConversionCastOp %1 : vector<16x16xf32>
1139 // to vector<16xf32>
1140 // becomes:
1141 // %2 = vector.shape_cast %0 : vector<16x1xf32> to vector<16xf32>
1142 //
1143 // For unpaired casts that emulate a pack (1:N) or unpack (N:1) between a
1144 // single large VectorType and N identically-typed smaller VectorTypes,
1145 // lower to vector.extract_strided_slice / vector.insert_strided_slice.
1146 auto hasIdenticalVectorTypes = [](ValueRange values) {
1147 auto types = values.getTypes();
1148 return !types.empty() && llvm::all_of(types, [&](Type type) {
1149 return isa<VectorType>(type) && type == types.front();
1150 });
1151 };
1152 OpBuilder builder(root);
1153 root->walk([&](UnrealizedConversionCastOp op) {
1154 if (existingCasts.contains(op))
1155 return;
1156 // Handle N:1 cast (N >= 1) where all inputs come from a single 1:N cast.
1157 if (op.getNumResults() == 1 && op.getNumOperands() >= 1) {
1158 auto defOp =
1159 op.getInputs()[0].getDefiningOp<UnrealizedConversionCastOp>();
1160 if (defOp && !existingCasts.contains(defOp) &&
1161 defOp.getNumOperands() == 1 &&
1162 defOp.getNumResults() == op.getNumOperands() &&
1163 llvm::all_of(op.getInputs(),
1164 [&](Value v) { return v.getDefiningOp() == defOp; })) {
1165 Value orig = defOp.getInputs()[0];
1166 auto origTy = dyn_cast<VectorType>(orig.getType());
1167 auto resTy = dyn_cast<VectorType>(op.getResult(0).getType());
1168 if (origTy && resTy &&
1169 origTy.getNumElements() == resTy.getNumElements() &&
1170 origTy != resTy) {
1171 builder.setInsertionPoint(op);
1172 auto shapeCast =
1173 vector::ShapeCastOp::create(builder, op.getLoc(), resTy, orig);
1174 op.replaceAllUsesWith(ValueRange{shapeCast.getResult()});
1175 } else {
1176 op.replaceAllUsesWith(ValueRange{orig});
1177 }
1178 return;
1179 }
1180 // Unpaired N:1 cast emulating unpack: stitch inputs into the output
1181 // shape via vector.insert_strided_slice.
1182 auto outputTy = dyn_cast<VectorType>(op.getResult(0).getType());
1183 if (op.getNumOperands() > 1 && outputTy &&
1184 hasIdenticalVectorTypes(op.getInputs())) {
1185 builder.setInsertionPoint(op);
1187 builder, op.getLoc(), op.getInputs(), outputTy.getShape());
1188 op->replaceAllUsesWith(ValueRange(result));
1189 }
1190 return;
1191 }
1192 // Handle 1:N cast where the single input comes from an N:1 cast.
1193 if (op.getNumOperands() == 1 && op.getNumResults() > 1) {
1194 auto defOp =
1195 op.getInputs()[0].getDefiningOp<UnrealizedConversionCastOp>();
1196 if (defOp && !existingCasts.contains(defOp) &&
1197 defOp.getNumResults() == 1 &&
1198 defOp.getNumOperands() == op.getNumResults() &&
1199 llvm::equal(ValueRange(defOp.getInputs()).getTypes(),
1200 op->getResultTypes())) {
1201 op.replaceAllUsesWith(defOp.getInputs());
1202 return;
1203 }
1204 // Unpaired 1:N cast emulating pack: split the input into the output
1205 // tile shape via vector.extract_strided_slice.
1206 auto tileTy = dyn_cast<VectorType>(op.getResult(0).getType());
1207 if (tileTy && hasIdenticalVectorTypes(op.getResults())) {
1208 builder.setInsertionPoint(op);
1210 builder, op.getLoc(), op.getInputs()[0], tileTy.getShape());
1211 op->replaceAllUsesWith(results);
1212 }
1213 return;
1214 }
1215 });
1216
1217 // Erase dead casts iteratively.
1218 bool changed = true;
1219 while (changed) {
1220 changed = false;
1221 root->walk([&](UnrealizedConversionCastOp op) {
1222 if (existingCasts.contains(op))
1223 return;
1224 if (op.use_empty()) {
1225 op.erase();
1226 changed = true;
1227 }
1228 });
1229 }
1230}
1231
1232// Checks if dst shape is a collapse of src shape where each dim in dst is
1233// produced by one or more consecutive dims in src whose product equals the dst
1234// dim. Populates collapseDims with one group per dst dim listing the src
1235// indices collapsed into it. Unit dims in dst that have no backing src dim
1236// (leading, in-between, or trailing) get empty groups; src unit dims that
1237// fall past the last consumed dst dim are absorbed into the most-recent
1238// non-empty group.
1239// Examples:
1240// src=[8,16,32], dst=[1,4096] -> true, collapseDims=[[],[0,1,2]]
1241// src=[8,16,32], dst=[4096,1] -> true, collapseDims=[[0,1,2],[]]
1242// src=[2,3,4], dst=[6,4] -> true, collapseDims=[[0,1],[2]]
1243// src=[64], dst=[64] -> true, collapseDims=[[0]]
1245 SmallVector<SmallVector<int64_t>> &collapseDims) {
1246 collapseDims.clear();
1247 collapseDims.resize(dst.size());
1248
1249 // Cheap precondition: src and dst must describe the same number of
1250 // elements. Bails out early on mismatched shapes without walking the dims.
1251 int64_t srcProd = std::accumulate(src.begin(), src.end(), int64_t{1},
1252 std::multiplies<int64_t>());
1253 int64_t dstProd = std::accumulate(dst.begin(), dst.end(), int64_t{1},
1254 std::multiplies<int64_t>());
1255 if (srcProd != dstProd)
1256 return false;
1257
1258 // Step 1: validate the partition on the unit-dim-stripped (compact) shapes.
1259 // Unit dims play no role in the matching decision — they only need to be
1260 // placed somewhere in the final groups (handled in step 2).
1261 SmallVector<int64_t> srcCompact, dstCompact;
1262 for (int64_t s : src)
1263 if (s != 1)
1264 srcCompact.push_back(s);
1265 for (int64_t d : dst)
1266 if (d != 1)
1267 dstCompact.push_back(d);
1268
1269 size_t s = 0;
1270 for (int64_t need : dstCompact) {
1271 int64_t acc = 1;
1272 while (s < srcCompact.size() && acc < need)
1273 acc *= srcCompact[s++];
1274 if (acc != need)
1275 return false;
1276 }
1277 if (s != srcCompact.size())
1278 return false;
1279
1280 // Step 2: assign each original src index to the correct original dst group.
1281 // Walk dst in original order, advancing past unit dst dims (they keep their
1282 // pre-initialized empty group). Walk src in original order; non-unit src
1283 // dims accumulate into the current dst group, unit src dims attach to the
1284 // current group when one is open or to the most-recent non-empty group
1285 // after dst is exhausted (leading unit src dims with no group yet are
1286 // dropped).
1287 size_t dstIdx = 0;
1288 while (dstIdx < dst.size() && dst[dstIdx] == 1)
1289 dstIdx++;
1290
1291 int64_t lastNonEmpty = -1;
1292 int64_t acc = 1;
1293 for (size_t srcIdx = 0; srcIdx < src.size(); ++srcIdx) {
1294 if (dstIdx >= dst.size()) {
1295 // dst exhausted; remaining src dims are unit (validated above) and
1296 // attach to the last non-empty group, if any.
1297 if (lastNonEmpty >= 0)
1298 collapseDims[lastNonEmpty].push_back(srcIdx);
1299 continue;
1300 }
1301 acc *= src[srcIdx];
1302 collapseDims[dstIdx].push_back(srcIdx);
1303 lastNonEmpty = dstIdx;
1304 if (acc == dst[dstIdx]) {
1305 acc = 1;
1306 ++dstIdx;
1307 while (dstIdx < dst.size() && dst[dstIdx] == 1)
1308 ++dstIdx;
1309 }
1310 }
1311 return true;
1312}
return success()
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
static SmallVector< Value > slice(OpBuilder &b, Location loc, Value value, VectorType nativeType)
xegpu::DistributeLayoutAttr maybePickPermanentLayout(xegpu::DistributeLayoutAttr layout, const OpResult &result, mlir::Operation *owner, const std::string &name)
static APFloat getMinMaxNeutral(const llvm::fltSemantics &semantics, vector::CombiningKind kind, arith::FastMathFlags flags)
Returns the neutral value of the float min or max reduction kind over elements of semantics.
static arith::FastMathFlags getFlags(arith::FastMathFlagsAttr fastmath)
Returns the flags held by fastmath, or none if it is null.
Attributes are known-constant values of operations.
Definition Attributes.h:25
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
FloatAttr getFloatAttr(Type type, double value)
Definition Builders.cpp:263
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:333
TypedAttr getOneAttr(Type type)
Definition Builders.cpp:351
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
This class helps build Operations.
Definition Builders.h:210
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Definition Builders.h:528
This class represents an operand of an operation.
Definition Value.h:256
This is a value defined by a result of an operation.
Definition Value.h:456
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
bool hasDiscardableAttrOfType(NameT &&name)
Definition Operation.h:508
void setDiscardableAttr(StringAttr name, Attribute value)
Set a discardable attribute by name.
Definition Operation.h:514
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
Definition Operation.h:255
bool hasDiscardableAttr(StringRef name)
Return true if this operation has a discardable attribute with the provided name.
Definition Operation.h:505
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
AttrClass getDiscardableAttrOfType(StringRef name)
Access a discardable attribute by name and cast it to AttrClass.
Definition Operation.h:495
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
A range-style iterator that allows for iterating over the offsets of all potential tiles of size tile...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIndex() const
Definition Types.cpp:56
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
type_range getTypes() const
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
void setType(Type newType)
Mutate the type of this Value to be of the specified type.
Definition Value.h:116
Type getType() const
Return the type of this value.
Definition Value.h:105
Operation * getOwner() const
Return the owner of this operand.
Definition UseDefLists.h:38
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
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.
bool matchDimCollapse(ArrayRef< int64_t > src, ArrayRef< int64_t > dst, SmallVector< SmallVector< int64_t > > &collapseDims)
Value createVectorWithShapeFromValues(OpBuilder &builder, Location loc, ValueRange values, ArrayRef< int64_t > shape)
Create a vector of shape from a set of values using vector.insert_stride_slice.
bool requirePacked(const DistributeLayoutAttr layout)
Helper function to check if the layout is packed.
void setTemporaryLayout(const T &operandOrResult, const DistributeLayoutAttr layout)
void setDistributeLayoutAttr(const OpResult &Result, const DistributeLayoutAttr layout)
[to-be-deprecated] Sets the DistributeLayoutAttr for a given OpResult user should use setAnchorLayout...
bool matchUnitDimExpansion(ArrayRef< int64_t > src, ArrayRef< int64_t > dst, SmallVector< int64_t > &expandedUnitDims)
std::optional< SmallVector< int64_t > > getInner2DIfUnitLeadingDims(ArrayRef< int64_t > vals)
Returns the innermost 2 entries of vals if it is at least 2D and all of its leading entries are unit;...
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...
FailureOr< int64_t > getNumSubgroupsFromBlockSize(Operation *op, int64_t subgroupSize)
Returns the number of subgroups the kernel enclosing op runs, derived from the known_block_size of it...
bool hasStaticShapeAndStrides(MemRefType type)
Returns true if type has a static shape and static strides.
FailureOr< VectorType > getDistVecTypeBasedOnLaneLayout(DistributeLayoutAttr layout, VectorType originalType)
Helper function to get distributed vector type for a source vector type according to the lane_layout.
bool requireTranspose(const DistributeLayoutAttr layout, const uArch::uArch *uArch)
Helper function to check if the layout requires a transpose effect.
bool matchSplitDimExpansion(ArrayRef< int64_t > src, ArrayRef< int64_t > dst, SmallVector< SmallVector< int64_t > > &splitDimGroups)
bool isLayoutCarrierType(Type type)
Returns true if values of type can carry a DistributeLayoutAttr, i.e.
DistributeLayoutAttr getDistributeLayoutAttr(const Value value)
Retrieves the DistributeLayoutAttr associated with a given Value, or nullptr if none is found.
DenseMap< Value, SmallVector< Type > > precomputeLoopBlockArgTypes(Operation *topLevelOp, SubShapeAndCountFn getSubShapeAndCount)
Pre-computes distributed VectorType mappings for every value carried through an SCF loop under topLev...
std::string getTemporaryLayoutName(const OpOperand &operand)
Return the attribute name for the OpOperand to attach DistributeLayoutAttr.
Value addElemOffsetInBytes(OpBuilder &builder, Location loc, Value baseAddr, Value elemOffset, MemRefType memrefTy)
Returns baseAddr + elemOffset * bitWidth / 8, i.e.
std::optional< std::string > getChipStr(Operation *op)
Retrieves the chip string from the XeVM target attribute of the parent GPU module operation.
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 lowerToVectorReductions(TypedValue< VectorType > src, TypedValue< VectorType > acc, vector::CombiningKind kind, int64_t reductionDim, Location loc, PatternRewriter &rewriter, arith::FastMathFlagsAttr fastmath=nullptr)
Given a src and an acc argumments from a vector::MultiDimReductionOp, lower to a set of vector::Reduc...
SmallVector< Value > extractVectorsWithShapeFromValue(OpBuilder &builder, Location loc, Value value, ArrayRef< int64_t > shape)
Extract a set of small vectors from a value with a given shape using vector.extract_stride_slice.
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...
Value lowerCrossLaneReductionToShuffles(TypedValue< VectorType > src, TypedValue< VectorType > acc, vector::CombiningKind kind, int64_t reductionDim, int64_t reductionSize, Location loc, PatternRewriter &rewriter, arith::FastMathFlagsAttr fastmath=nullptr)
Lowers cross-lane reductions to shuffle operations on a 2D vector.
std::function< std::pair< SmallVector< int64_t >, int >( VectorType, DistributeLayoutAttr)> SubShapeAndCountFn
Callback type for computing sub-shape and count for 1:N (or 1:1 shape-changing) VectorType conversion...
Definition XeGPUUtils.h:290
void setTensorDescLayout(Value value, DistributeLayoutAttr layout)
Sets layout on the type of the tensor_desc value value, replacing any layout the type already has.
void cleanupUnrealizedConversionCasts(Operation *root, const llvm::SmallSetVector< UnrealizedConversionCastOp, 8 > &existingCasts)
Cleans up UnrealizedConversionCastOps inserted during SCF structural type conversion and/or XeGPU unr...
SmallVector< Value > flattenValues(ArrayRef< ValueRange > values)
Flatten a set of ValueRange into a single SmallVector<Value>
SmallVector< OpFoldResult > addWithRightAligned(OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > lhs, ArrayRef< OpFoldResult > rhs)
Generates element-wise addition ops of two arrays with automatic alignment.
SmallVector< OpFoldResult > addElementwise(OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > lhs, ArrayRef< OpFoldResult > rhs)
Generates element-wise addition ops of two arrays with same length.
FailureOr< VectorType > getDistributedVectorType(xegpu::TensorDescType tdescTy)
If tensor descriptor has a layout attribute it is used in SIMT mode.
Value subgroupReduction(Location loc, OpBuilder &builder, Value input, vector::CombiningKind kind, uint32_t size, arith::FastMathFlagsAttr fastmath=nullptr)
Given an input value representing per-lane data, this function returns the result after performing a ...
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
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
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
Definition Utils.cpp:114
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
std::optional< SmallVector< int64_t > > computeShapeRatio(ArrayRef< int64_t > shape, ArrayRef< int64_t > subShape)
Return the multi-dimensional integral ratio of subShape to the trailing dimensions of shape.
virtual int getSubgroupSize() const =0