MLIR 24.0.0git
XeGPULayoutImpl.cpp
Go to the documentation of this file.
1//===---- XeGPULayoutImpl.cpp - MLIR Utilities for XeGPUOps
2//------------------===//
3//
4// Part of the MLIR Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements layout utility functions for XeGPU dialect
11// transformation.
12//
13//===----------------------------------------------------------------------===//
14
24#include "mlir/IR/Builders.h"
25#include "mlir/IR/IRMapping.h"
26#include "mlir/IR/Operation.h"
27#include "mlir/IR/ValueRange.h"
32#include "llvm/ADT/DenseSet.h"
33#include "llvm/ADT/PostOrderIterator.h"
34#include "llvm/ADT/SetVector.h"
35#include "llvm/Support/FormatVariadic.h"
36#include <cstdint>
37#include <functional>
38#include <numeric>
39
40using namespace mlir;
41
45 out.reserve(attrs.size());
46
47 for (auto attr : attrs) {
48 if (auto dist = dyn_cast<xegpu::DistributeLayoutAttr>(attr.getValue())) {
49 auto newLayout = dist.dropSgLayoutAndData();
50 if (newLayout)
51 out.emplace_back(attr.getName(), newLayout);
52 } else {
53 out.push_back(attr);
54 }
55 }
56
57 return out;
58}
59
63 out.reserve(attrs.size());
64
65 for (auto attr : attrs) {
66 if (auto dist = dyn_cast<xegpu::DistributeLayoutAttr>(attr.getValue())) {
67 auto newLayout = dist.dropInstData();
68 if (newLayout)
69 out.emplace_back(attr.getName(), newLayout);
70 } else {
71 out.push_back(attr);
72 }
73 }
74
75 return out;
76}
77
79 op->getName().walkInherentAttrs(op, [](StringRef, Attribute &attr) {
80 if (auto dist = dyn_cast<xegpu::DistributeLayoutAttr>(attr))
81 attr = dist.dropInstData();
82 });
83}
84
85/// Return whether every target recorded for `region` has been visited.
86static bool isReady(Region *region,
87 const DenseMap<Region *, SmallPtrSet<Region *, 2>> &targets,
88 const SetVector<Region *> &visitedRegions) {
89 auto it = targets.find(region);
90 if (it == targets.end())
91 return true;
92 for (Region *target : it->second)
93 if (!visitedRegions.contains(target))
94 return false;
95 return true;
96}
97
98/// Order regions for walkBackward, preferring successors before predecessors
99/// and breaking ties by reverse region order.
101 SmallVector<Region *> regions;
102 for (Region &region : llvm::reverse(op->getRegions()))
103 regions.push_back(&region);
104 auto regionOp = dyn_cast<RegionBranchOpInterface>(op);
105 if (!regionOp)
106 return regions;
107
108 // Track inter-region edges and exits to the parent op. Ignore self-edges.
111 for (Region *region : regions) {
113 regionOp.getSuccessorRegions(*region, successors);
114 for (const RegionSuccessor &successor : successors) {
115 if (successor.isOperation())
116 exits.insert(region);
117 else if (successor.getSuccessor() != region)
118 targets[region].insert(successor.getSuccessor());
119 }
120 }
121
122 SetVector<Region *> visitedRegions;
123 while (visitedRegions.size() < regions.size()) {
124 // If no region is ready, every unvisited region is on a cycle (e.g.
125 // scf.while before <-> after). Break it at an exit region when possible:
126 // its consumers outside the op are already visited, and its in-cycle
127 // successor is then visited after it, like a use across a loop back edge.
128 // Returns the first unvisited region that satisfies `pred`, or null.
129 auto findFirst = [&](auto pred) -> Region * {
130 for (Region *region : regions)
131 if (!visitedRegions.contains(region) && pred(region))
132 return region;
133 return nullptr;
134 };
135 Region *chosen = findFirst([&](Region *region) {
136 return isReady(region, targets, visitedRegions);
137 });
138 if (!chosen)
139 chosen =
140 findFirst([&](Region *region) { return exits.contains(region); });
141 if (!chosen)
142 chosen = findFirst([](Region *) { return true; });
143 visitedRegions.insert(chosen);
144 }
145 return visitedRegions.takeVector();
146}
147
148/// Visits the ops of `region` backward; see xegpu::walkBackward.
149static void walkRegionBackward(Region &region,
151 if (region.empty())
152 return;
153 // CFG post-order visits successor blocks first, except across back edges.
154 llvm::ReversePostOrderTraversal<Region *> rpot(&region);
155 SmallVector<Block *> blocks(rpot.begin(), rpot.end());
156 for (Block *block : llvm::reverse(blocks)) {
157 for (Operation &op : llvm::reverse(*block)) {
158 auto walkNestedRegions = [&]() {
159 for (Region *nested : getBackwardRegionOrder(&op))
160 walkRegionBackward(*nested, visitor);
161 };
162 walkNestedRegions();
163 auto terminator = dyn_cast<RegionBranchTerminatorOpInterface>(&op);
164 if (terminator && isa<RegionBranchOpInterface>(op.getParentOp())) {
165 visitor.visitTerminator(terminator);
166 } else if (auto regionOp = dyn_cast<RegionBranchOpInterface>(&op)) {
167 visitor.visitRegionOp(regionOp);
168 // Pipelined loops pass values along iter_arg chains; each walk moves a
169 // layout request back one iter_arg: allow region args + 1 walks.
170 unsigned numRegionArgs = 0;
171 for (Region &region : op.getRegions())
172 numRegionArgs += region.getNumArguments();
173 for (unsigned i = 0;
174 i < numRegionArgs + 1 && visitor.shouldRevisitRegions(regionOp);
175 ++i) {
176 walkNestedRegions();
177 visitor.visitRegionOp(regionOp);
178 }
179 } else {
180 visitor.visitRegularOp(&op);
181 }
182 }
183 }
184}
185
187 root->walk([&](FunctionOpInterface funcOp) {
188 if (!funcOp.isExternal())
189 walkRegionBackward(funcOp.getFunctionBody(), visitor);
190 });
191}
192
193static xegpu::DistributeLayoutAttr getLayoutFromUsePoints(Value result) {
194 xegpu::DistributeLayoutAttr layout = nullptr;
195 for (OpOperand &use : result.getUses()) {
196 if (auto tmpLayout = xegpu::getDistributeLayoutAttr(use)) {
197 if (!layout)
198 layout = tmpLayout;
199 break;
200 }
201 }
202 return layout;
203}
204
205static constexpr unsigned kMaxRematerializableChainOps = 16;
206
207/// Accept pure vector generators and elementwise ops that preserve vector
208/// shape. Generators have no vector operands; elementwise ops share their
209/// result layout with their vector operands, so the chain needs no layout
210/// inference.
212 if (op->getNumResults() != 1 || op->getNumRegions() != 0 ||
213 !isa<VectorType>(op->getResult(0).getType()) || !isMemoryEffectFree(op))
214 return false;
215 if (auto constant = dyn_cast<arith::ConstantOp>(op)) {
216 auto value = dyn_cast<DenseElementsAttr>(constant.getValue());
217 return value && value.isSplat();
218 }
219 if (isa<vector::StepOp, vector::CreateMaskOp>(op))
220 return true;
221 if (auto broadcast = dyn_cast<vector::BroadcastOp>(op))
222 return !isa<VectorType>(broadcast.getSource().getType());
224}
225
226/// Collect each eligible producer once, producers first, for cloning with an
227/// IRMapping. Reject chains exceeding the duplication limit or reaching an
228/// unsupported producer or vector block argument.
231 // Re-push each op below its producers to obtain an iterative post-order walk.
232 SmallVector<std::pair<Operation *, bool>> worklist{{root, false}};
233 DenseSet<Operation *> visited;
234 while (!worklist.empty()) {
235 auto [op, expanded] = worklist.pop_back_val();
236 if (expanded) {
237 chain.push_back(op);
238 continue;
239 }
240 if (!visited.insert(op).second)
241 continue;
242 if (visited.size() > kMaxRematerializableChainOps ||
244 return false;
245 worklist.emplace_back(op, true);
246 for (Value operand : op->getOperands()) {
247 if (!isa<VectorType>(operand.getType()))
248 continue;
249 Operation *producer = operand.getDefiningOp();
250 if (!producer)
251 return false;
252 if (!visited.contains(producer))
253 worklist.emplace_back(producer, false);
254 }
255 }
256 return true;
257}
258
260 if (!op)
261 return false;
263 return collectRematerializableChain(op, chain);
264}
265
267 Operation *producer = value.getDefiningOp();
269 if (!producer || !collectRematerializableChain(producer, chain))
270 return nullptr;
271 // Clone producers first so vector operands map to clones; scalars stay
272 // shared.
273 OpBuilder::InsertionGuard guard(builder);
274 IRMapping mapping;
275 for (Operation *op : chain) {
276 builder.setInsertionPointAfter(op);
277 Operation *clone = builder.clone(*op, mapping);
279 }
280 return mapping.lookup(value);
281}
282
283// For regular operations: First the result layouts are propagated from uses.
284// Then the result layouts are propagated to uses (operands).
286 if (op->getNumResults() == 0)
287 return;
288 if (op->getNumResults() > 1 && !isa<vector::DeinterleaveOp>(op))
289 return;
290 OpResult result = op->getResult(0);
291 xegpu::DistributeLayoutAttr resLayout = getLayoutFromUsePoints(result);
292 Type resultType = result.getType();
293
294 if (!resLayout)
295 return;
296
297 // Recover layout for TensorDesc type results by updating the type to include
298 // the layout.
299 if (auto tdescTy = dyn_cast<xegpu::TensorDescType>(resultType);
300 tdescTy && !tdescTy.getLayoutAttr())
302
303 // Recover layout for vector type results, or for multi-reduction ops which
304 // may reduce to a scalar that still needs a layout.
305 if (isa<VectorType>(resultType) || isa<vector::MultiDimReductionOp>(op))
307
308 if (isa<vector::DeinterleaveOp>(op))
309 xegpu::setTemporaryLayout(op->getResult(1), resLayout);
310
311 for (OpOperand &opr : op->getOpOperands()) {
312 xegpu::DistributeLayoutAttr operandLayout =
314 if (isa<VectorType>(opr.get().getType()) && operandLayout)
315 xegpu::setTemporaryLayout(opr, operandLayout);
316 }
317}
318
320 RegionBranchTerminatorOpInterface terminator,
321 GetLayoutFnTy getLayoutOfValue, SetOperandLayoutFnTy setOperandLayout) {
322 auto regionOp = dyn_cast<RegionBranchOpInterface>(terminator->getParentOp());
323 if (!regionOp)
324 return;
326 regionOp.getSuccessorOperandInputMapping(mapping,
327 RegionBranchPoint(terminator));
328 for (const auto &[successorOperand, successorInputs] : mapping) {
329 if (!xegpu::isLayoutCarrierType(successorOperand->get().getType()))
330 continue;
331 // Prefer the layout of a region argument, e.g. a loop's iter_arg.
332 xegpu::DistributeLayoutAttr layout;
333 for (auto arg : llvm::make_isa_range<BlockArgument>(successorInputs))
334 if ((layout = getLayoutOfValue(arg)))
335 break;
336 // Otherwise the region result's (an operand feeds at most one).
337 if (!layout)
338 for (Value input : successorInputs)
339 if (isa<OpResult>(input))
340 layout = getLayoutOfValue(input);
341 setOperandLayout(*successorOperand, layout);
342 }
343}
344
345// Propagate layout from region arguments to region op's init operands. This
346// sets the temporary layout for region arguments and init operands.
347LogicalResult
348xegpu::propagateRegionArgsToInits(mlir::RegionBranchOpInterface regionOp,
349 xegpu::GetLayoutFnTy getLayoutOfValue,
350 SetOperandLayoutFnTy setOperandLayout,
351 SetTDescArgLayoutFnTy setTDescArgLayout) {
352 // Iterate all regions of the region op. For each block argument that has a
353 // layout (obtained via `getLayoutOfValue`), trace back to find the
354 // corresponding init operand of the regionOp and set the layout on it.
355 // This works generically for scf.for, scf.while, and other
356 // RegionBranchOpInterface ops.
357 for (Region &region : regionOp->getRegions()) {
358 RegionSuccessor regionSuccessor(&region);
359 // Use getSuccessorInputs to get the block arguments that correspond to
360 // predecessor operands. This correctly handles ops like scf.for where
361 // the induction variable is a block arg but not a successor input.
362 ValueRange successorInputs = regionOp.getSuccessorInputs(regionSuccessor);
363 for (auto [inputIdx, regionArg] : llvm::enumerate(successorInputs)) {
364 auto layout = getLayoutOfValue(regionArg);
365 if (!layout)
366 continue;
367
368 // Pass on the layout of tensor_desc block args (it ends up in the type).
369 if (auto tdescTy = dyn_cast<xegpu::TensorDescType>(regionArg.getType());
370 tdescTy && !tdescTy.getLayoutAttr())
371 setTDescArgLayout(cast<BlockArgument>(regionArg), layout);
372
373 // Pass on the layout of region op operands, like scf.for's init operands.
374 // Find all predecessor values that flow into this block argument.
375 SmallVector<Value> predValues;
376 regionOp.getPredecessorValues(regionSuccessor, inputIdx, predValues);
377 for (Value predVal : predValues) {
378 // Match predecessor value to an operand of the regionOp.
379 for (OpOperand &operand : regionOp->getOpOperands()) {
380 if (operand.get() == predVal)
381 setOperandLayout(operand, layout);
382 }
383 }
384 }
385 }
386 return success();
387}
388
389// Prerequisite for Layout Recovery
390// It relies on the following invariant:
391// 1. there is no layout conflict between different uses of the same definition.
392// 2. each definition has a well-defined layout requirement at its use point.
393// - Every definition must have at least one use that appears after it in
394// topological order.
395// - TODO: If a definition has no such use (e.g., a loop result or region
396// output), an explicit convert_layout operation is inserted to create a
397// use.
398// - Only the result of convert_layout is permitted to have no subsequent
399// use.
400//
401// The recovery proceeds by scanning the operation in reverse topological order
402// as follows:
403// For regular operations: First the result layouts are propagated from uses.
404// Then the result layouts are propagated to operands.
405//
406// For region operations (e.g., loops):
407// - A terminator operand takes the layout of the region argument it
408// feeds (from while op's cond region), or else of the region result
409// (from their use points).
410// - The region op, visited after its regions, sets its result layouts
411// from their use points and its init operands from the region
412// arguments.
413namespace {
414/// Recover temporary layouts through the shared backward walk.
415struct LayoutRecovery final : public xegpu::BackwardLayoutVisitor {
416 void visitTerminator(RegionBranchTerminatorOpInterface terminator) override {
418 terminator, getLayoutFromUsePoints,
420 }
421 void visitRegionOp(RegionBranchOpInterface regionOp) override {
422 // The region results take the layout of their uses.
423 for (OpResult result : regionOp->getResults()) {
424 xegpu::DistributeLayoutAttr layout = getLayoutFromUsePoints(result);
425 if (!layout)
426 continue;
428 if (auto tdescTy = dyn_cast<xegpu::TensorDescType>(result.getType());
429 tdescTy && !tdescTy.getLayoutAttr())
431 }
435 }
436 void visitRegularOp(Operation *op) override {
437 if (!isa<xegpu::AnchorLayoutInterface>(op))
439 }
440};
441} // namespace
442
445 LayoutRecovery recovery;
446 walkBackward(rootOp, recovery);
447 return true;
448}
449
450template <typename T, typename>
451void xegpu::removeLayoutAttr(const T &operandOrResult) {
452 Operation *owner = operandOrResult.getOwner();
453 std::string name = xegpu::getTemporaryLayoutName(operandOrResult);
454 if (owner->hasDiscardableAttrOfType<DistributeLayoutAttr>(name))
455 owner->removeDiscardableAttr(name);
456}
457
458// Explicit instantiation for OpResult
459template void
461
462// Explicit instantiation for OpOperand
463template void
465
467 op->walk([&](Operation *nestOp) {
468 // Remove all attributes of DistributeLayoutAttr type
469 SmallVector<StringAttr> attrsToRemove;
470 for (auto namedAttr : nestOp->getDiscardableAttrDictionary().getValue()) {
471 if (isa<DistributeLayoutAttr>(namedAttr.getValue()))
472 attrsToRemove.push_back(namedAttr.getName());
473 }
474 for (auto attrName : attrsToRemove)
475 nestOp->removeDiscardableAttr(attrName);
476 });
477}
478
480 op->walk([&](Operation *nestOp) {
481 SmallVector<StringAttr> attrsToRemove;
482 for (auto namedAttr : nestOp->getDiscardableAttrDictionary().getValue()) {
483 if (isa<xegpu::DistributeLayoutAttr>(namedAttr.getValue()))
484 attrsToRemove.push_back(namedAttr.getName());
485 }
486 for (auto attrName : attrsToRemove)
487 nestOp->removeDiscardableAttr(attrName);
488 });
489}
490
491static xegpu::LayoutAttr buildInstDataLayoutWithLane(
492 mlir::MLIRContext *context, ArrayRef<int64_t> instData,
493 ArrayRef<int64_t> laneLayout, ArrayRef<int64_t> laneData,
494 DenseI32ArrayAttr orderAttr = nullptr) {
495 auto toI32Attr = [&](auto range) {
496 SmallVector<int32_t> v(range.begin(), range.end());
497 return DenseI32ArrayAttr::get(context, v);
498 };
499 return xegpu::LayoutAttr::get(context, /*sg_layout=*/nullptr,
500 /*sg_data=*/nullptr, toI32Attr(instData),
501 toI32Attr(laneLayout), toI32Attr(laneData),
502 orderAttr);
503}
504
506 ArrayRef<int64_t> laneLayout,
507 ArrayRef<int64_t> laneData) {
508 return !llvm::any_of(llvm::seq<int>(0, dataShape.size()), [&](int dim) {
509 return dataShape[dim] % (laneLayout[dim] * laneData[dim]) != 0;
510 });
511}
512
513static xegpu::LayoutAttr
515 ArrayRef<int64_t> laneData,
516 DenseI32ArrayAttr orderAttr = nullptr) {
517 auto toI32Attr = [&](auto range) {
518 SmallVector<int32_t> v(range.begin(), range.end());
519 return DenseI32ArrayAttr::get(context, v);
520 };
521 return xegpu::LayoutAttr::get(context, /*sg_layout=*/nullptr,
522 /*sg_data=*/nullptr,
523 /*inst_data=*/nullptr, toI32Attr(laneLayout),
524 toI32Attr(laneData), orderAttr);
525}
526
527static xegpu::LayoutAttr
529 ArrayRef<int64_t> sgData, ArrayRef<int64_t> instData,
530 ArrayRef<int64_t> laneLayout, ArrayRef<int64_t> laneData,
531 DenseI32ArrayAttr orderAttr = nullptr) {
532 auto toI32Attr = [&](auto range) {
533 SmallVector<int32_t> v(range.begin(), range.end());
534 return DenseI32ArrayAttr::get(context, v);
535 };
536 return xegpu::LayoutAttr::get(
537 context, sgLayout.empty() ? nullptr : toI32Attr(sgLayout),
538 sgData.empty() ? nullptr : toI32Attr(sgData),
539 instData.empty() ? nullptr : toI32Attr(instData),
540 laneLayout.empty() ? nullptr : toI32Attr(laneLayout),
541 laneData.empty() ? nullptr : toI32Attr(laneData), orderAttr);
542}
543
544static xegpu::LayoutAttr buildSgLayout(mlir::MLIRContext *context,
545 ArrayRef<int64_t> wgTileShape,
546 ArrayRef<int64_t> sgLayout,
547 int dimK = -1,
548 DenseI32ArrayAttr orderAttr = nullptr) {
549 SmallVector<int64_t> sgData(sgLayout.size());
550 for (int dim = 0; dim < (int)sgLayout.size(); ++dim) {
551 if (dim == dimK)
552 sgData[dim] = wgTileShape[dim];
553 else
554 sgData[dim] = wgTileShape[dim] / sgLayout[dim];
555 }
556 return buildLayout(context, sgLayout, sgData,
557 /*inst_data=*/{}, /*lane_layout=*/{},
558 /*lane_data=*/{}, /*order=*/nullptr);
559}
560
561/// Infers the source layout attribute for a broadcast operation given the
562/// result layout attribute, result shape, source shape.
563xegpu::DistributeLayoutAttr
564xegpu::inferBroadcastSourceLayout(xegpu::DistributeLayoutAttr resLayout,
565 ArrayRef<int64_t> resShape,
566 ArrayRef<int64_t> srcShape) {
567
568 SmallVector<int64_t> bcastDims;
569 size_t dimDiff = resShape.size() - srcShape.size();
570 auto bcastSourceLayout = resLayout;
571
572 // Right-aligned source in result, look for stretched unit dims.
573 for (size_t i = dimDiff; i < resShape.size(); i++) {
574 if ((srcShape[i - dimDiff] == 1) && (resShape[i] != 1))
575 bcastDims.push_back(i);
576 }
577
578 // Case UnitDimStretch (e.g., 1x4 -> 4x4): the source layout data field must
579 // be 1.
580 if (!bcastDims.empty())
581 bcastSourceLayout = bcastSourceLayout.setUnitDimData(bcastDims);
582
583 // Case RankDiff:
584 if (dimDiff) {
585 SmallVector<int64_t> sliceDims;
586 bool isOuterDimDiffUnitDims = llvm::all_of(
587 resShape.take_front(dimDiff), [&](int64_t dim) { return dim == 1; });
588 if (dimDiff && bcastDims.size() == dimDiff && isOuterDimDiffUnitDims) {
589 // Case RankDiffInnerDims (e.g., 1x4 -> 1x16x4):
590 // slice the expanded inner dims
591 sliceDims.assign(bcastDims.begin(), bcastDims.end());
592 } else {
593 // Case RankDiffOuterDims (e.g., 1x4 -> 1x1x4):
594 // slice the outer dims
595 llvm::append_range(sliceDims, llvm::seq<int64_t>(0, dimDiff));
596 }
597 bcastSourceLayout = xegpu::SliceAttr::get(
598 resLayout.getContext(), bcastSourceLayout,
599 DenseI64ArrayAttr::get(resLayout.getContext(), sliceDims));
600 }
601 return bcastSourceLayout;
602}
603
604/// Infers the source layout attribute for a reduction operation given the
605/// result layout attribute and reduced dims.
606xegpu::DistributeLayoutAttr
607xegpu::inferMultiReductionSourceLayout(xegpu::DistributeLayoutAttr resLayout,
608 SmallVector<int64_t> reduceDims) {
609
610 assert(isa<xegpu::SliceAttr>(resLayout) &&
611 "reduction result layout must be slice layout");
612
613 xegpu::SliceAttr sliceLayout = dyn_cast<xegpu::SliceAttr>(resLayout);
614
615 assert((reduceDims == sliceLayout.getDims().asArrayRef()) &&
616 "reduction dims must match with slice dims");
617
618 return sliceLayout.getParent();
619}
620
621xegpu::DistributeLayoutAttr
622xegpu::inferReductionSourceLayout(xegpu::DistributeLayoutAttr resLayout) {
623 return xegpu::inferMultiReductionSourceLayout(resLayout, {0});
624}
625
626/// Infers the source layout attribute for a transpose operation given the
627/// result layout attribute and permutation.
628///
629/// vector.transpose semantics is `result[i] = source[permutation[i]]`, so
630/// `result_layout[i] = source_layout[permutation[i]]`. To recover the source
631/// layout from the result layout we must apply the inverse permutation.
632xegpu::DistributeLayoutAttr
633xegpu::inferTransposeSourceLayout(xegpu::DistributeLayoutAttr resLayout,
634 ArrayRef<int64_t> permutation) {
636 invertPermutationVector(permutation);
637 return resLayout.transposeDims(inversePermutation);
638}
639
640/// Infers the source layout attribute for a bitcast operation given the
641/// result layout attribute, result element type bitwidth, and source element
642/// type bitwidth.
643xegpu::DistributeLayoutAttr
644xegpu::inferBitCastSourceLayout(xegpu::DistributeLayoutAttr resLayout,
645 int resElemTyBitWidth, int srcElemTyBitWidth) {
646
647 SmallVector<int64_t> sgData = resLayout.getEffectiveSgDataAsInt();
648 SmallVector<int64_t> instData = resLayout.getEffectiveInstDataAsInt();
649 SmallVector<int64_t> laneData = resLayout.getEffectiveLaneDataAsInt();
650 size_t sgDataSize = sgData.size();
651 size_t instDataSize = instData.size();
652 size_t laneDataSize = laneData.size();
653 int64_t sgDataValue = -1;
654 int64_t instDataValue = -1;
655 int64_t laneDataValue = -1;
656 int64_t dim = resLayout.getRank() - 1;
657
658 if (srcElemTyBitWidth <= resElemTyBitWidth) {
659 int bitWidthRatio = resElemTyBitWidth / srcElemTyBitWidth;
660 if (sgDataSize)
661 sgDataValue = sgData.back() * bitWidthRatio;
662 if (instDataSize)
663 instDataValue = instData.back() * bitWidthRatio;
664 if (laneDataSize)
665 laneDataValue = laneData.back() * bitWidthRatio;
666 } else {
667 int bitWidthRatio = srcElemTyBitWidth / resElemTyBitWidth;
668 if (sgDataSize) {
669 assert((sgData.back() % bitWidthRatio) == 0 &&
670 "sgData not divisible by bitWidthRatio");
671 sgDataValue = sgData.back() / bitWidthRatio;
672 }
673 if (instDataSize) {
674 assert((instData.back() % bitWidthRatio) == 0 &&
675 "instData not divisible by bitWidthRatio");
676 instDataValue = instData.back() / bitWidthRatio;
677 }
678 if (laneDataSize) {
679 assert((laneData.back() % bitWidthRatio) == 0 &&
680 "laneData not divisible by bitWidthRatio");
681 laneDataValue = laneData.back() / bitWidthRatio;
682 }
683 }
684
685 xegpu::DistributeLayoutAttr finalSrcLayout;
686 finalSrcLayout =
687 resLayout.setDimData(dim, sgDataValue, instDataValue, laneDataValue);
688
689 return finalSrcLayout;
690}
691
692/// Infers the source layout attribute for an interleave operation given the
693/// result layout attribute. Interleave doubles the size of the innermost
694/// dimension, so the layout inference is similar to bitcast where the source
695/// element type is larger than the result element type (ratio = 2).
696xegpu::DistributeLayoutAttr
697xegpu::inferInterleaveSourceLayout(xegpu::DistributeLayoutAttr resLayout) {
698
699 SmallVector<int64_t> sgData = resLayout.getEffectiveSgDataAsInt();
700 SmallVector<int64_t> instData = resLayout.getEffectiveInstDataAsInt();
701 SmallVector<int64_t> laneData = resLayout.getEffectiveLaneDataAsInt();
702 size_t sgDataSize = sgData.size();
703 size_t instDataSize = instData.size();
704 size_t laneDataSize = laneData.size();
705 int64_t sgDataValue = -1;
706 int64_t instDataValue = -1;
707 int64_t laneDataValue = -1;
708 int64_t dim = resLayout.getRank() - 1;
709
710 // Interleave doubles the innermost dimension, so we need to halve the
711 // layout values (similar to bitcast with ratio = 2)
712 constexpr int ratio = 2;
713 if (sgDataSize) {
714 assert((sgData.back() % ratio) == 0 &&
715 "sgData not divisible by interleave ratio");
716 sgDataValue = sgData.back() / ratio;
717 }
718 if (instDataSize) {
719 assert((instData.back() % ratio) == 0 &&
720 "instData not divisible by interleave ratio");
721 instDataValue = instData.back() / ratio;
722 }
723 if (laneDataSize) {
724 assert((laneData.back() % ratio) == 0 &&
725 "laneData not divisible by interleave ratio");
726 laneDataValue = laneData.back() / ratio;
727 }
728
729 return resLayout.setDimData(dim, sgDataValue, instDataValue, laneDataValue);
730}
731
732/// Infers the source layout attribute for a deinterleave operation given the
733/// result layout attribute. Deinterleave halves the size of the innermost
734/// dimension, so the layout inference is similar to bitcast where the source
735/// element type is smaller than the result element type (ratio = 2).
736xegpu::DistributeLayoutAttr
737xegpu::inferDeinterleaveSourceLayout(xegpu::DistributeLayoutAttr resLayout) {
738
739 SmallVector<int64_t> sgData = resLayout.getEffectiveSgDataAsInt();
740 SmallVector<int64_t> instData = resLayout.getEffectiveInstDataAsInt();
741 SmallVector<int64_t> laneData = resLayout.getEffectiveLaneDataAsInt();
742 size_t sgDataSize = sgData.size();
743 size_t instDataSize = instData.size();
744 size_t laneDataSize = laneData.size();
745 int64_t sgDataValue = -1;
746 int64_t instDataValue = -1;
747 int64_t laneDataValue = -1;
748 int64_t dim = resLayout.getRank() - 1;
749
750 // Deinterleave halves the innermost dimension, so we need to double the
751 // layout values (similar to bitcast with ratio = 2)
752 constexpr int ratio = 2;
753 if (sgDataSize)
754 sgDataValue = sgData.back() * ratio;
755 if (instDataSize)
756 instDataValue = instData.back() * ratio;
757 if (laneDataSize)
758 laneDataValue = laneData.back() * ratio;
759
760 return resLayout.setDimData(dim, sgDataValue, instDataValue, laneDataValue);
761}
762
763/// Infers the source layout attribute for an insert strided slice operation
764/// given the result layout attribute, result shape, and source shape. Removes
765/// leading dimensions from the result layout to match the source shape size.
766xegpu::DistributeLayoutAttr xegpu::inferInsertStridedSliceSourceLayout(
767 xegpu::DistributeLayoutAttr resLayout, ArrayRef<int64_t> resShape,
768 ArrayRef<int64_t> srcShape) {
769
770 int srcShapeSize = srcShape.size();
771 int resShapeSize = resShape.size();
772 int dimDiff = resShapeSize - srcShapeSize;
773
774 if (dimDiff > 0) {
775 // assert that the leading dimensions being sliced off are not distributed
776 // (i.e. sg_layout and lane_layout for those dimensions are all 1)
777 auto resSgLayout = resLayout.getEffectiveSgLayoutAsInt();
778 auto resLaneLayout = resLayout.getEffectiveLaneLayoutAsInt();
779 for (int i = 0; i < dimDiff; i++) {
780 assert((resSgLayout.size() == 0 || resSgLayout[i] == 1) &&
781 (resLaneLayout.size() == 0 || resLaneLayout[i] == 1) &&
782 "Leading dimensions being sliced off must not be distributed");
783 }
784 return resLayout.dropDims(llvm::to_vector(llvm::seq<int64_t>(0, dimDiff)));
785 }
786 return resLayout;
787}
788
789/// Infers the source layout attribute for an insert operation
790/// given the result layout attribute, result shape, and source shape. Removes
791/// leading dimensions from the result layout to match the source shape size.
792// TODO: add propagation support for insert op
793xegpu::DistributeLayoutAttr
794xegpu::inferInsertSourceLayout(xegpu::DistributeLayoutAttr resLayout,
795 ArrayRef<int64_t> resShape,
796 ArrayRef<int64_t> srcShape) {
797
798 int srcShapeSize = srcShape.size();
799 int resShapeSize = resShape.size();
800 int dimDiff = resShapeSize - srcShapeSize;
801
802 if (dimDiff > 0) {
803 // assert that the leading dimensions being sliced off are not distributed
804 // (i.e. sg_layout and lane_layout for those dimensions are all 1)
805 auto resSgLayout = resLayout.getEffectiveSgLayoutAsInt();
806 auto resLaneLayout = resLayout.getEffectiveLaneLayoutAsInt();
807 for (int i = 0; i < dimDiff; i++) {
808 assert((resSgLayout.size() == 0 || resSgLayout[i] == 1) &&
809 (resLaneLayout.size() == 0 || resLaneLayout[i] == 1) &&
810 "Leading dimensions being sliced off must not be distributed");
811 }
812 return resLayout.dropDims(llvm::to_vector(llvm::seq<int64_t>(0, dimDiff)));
813 }
814 return resLayout;
815}
816
817/// Infers the source layout attribute for extract operation
818/// given the result layout attribute, result shape, and source shape. Adds
819/// leading dimensions to the source layout to match the source shape size.
820// TODO: add layout attribute interface: expandDim() and use it here.
821// TODO: add propagation support for extract op
822xegpu::DistributeLayoutAttr
823xegpu::inferExtractSourceLayout(xegpu::DistributeLayoutAttr resLayout,
824 ArrayRef<int64_t> resShape,
825 ArrayRef<int64_t> srcShape) {
826
827 int srcShapeSize = srcShape.size();
828 int resShapeSize = resShape.size();
829 int dimDiff = srcShapeSize - resShapeSize;
830 auto context = resLayout.getContext();
831 // construct the source layout by adding unit dimensions to the front of
832 // result layout
833 if (dimDiff > 0) {
834 auto sgLayout = resLayout.getEffectiveSgLayoutAsInt();
835 auto sgData = resLayout.getEffectiveSgDataAsInt();
836 auto instData = resLayout.getEffectiveInstDataAsInt();
837 auto laneLayout = resLayout.getEffectiveLaneLayoutAsInt();
838 auto laneData = resLayout.getEffectiveLaneDataAsInt();
839 auto order = resLayout.getEffectiveOrderAsInt();
840
841 // Example: result shape is 3D with order [1, 2, 0], source shape is 5D
842 // (adding 2 leading dimensions). Expected source order: [3, 4, 2, 1, 0]
843 // Step 1: shift existing order by dimDiff: [1, 2, 0] -> [3, 4, 2]
844 // Step 2: append new leading dims in reverse (slowest first): [3, 4, 2, 1,
845 // 0]
846
847 // Shift existing dimension indices in order by dimDiff to account for the
848 // new leading dimensions being added to the source shape
849 for (auto &o : order)
850 o += dimDiff;
851
852 // Add unit dimensions to the front of non-empty layout vectors and append
853 // the new dimension indices to the order array in reverse (slowest
854 // dimension has the lowest index and appears last in the order array)
855 for (int i = 0; i < dimDiff; i++) {
856 if (!sgLayout.empty())
857 sgLayout.insert(sgLayout.begin(), 1);
858 if (!sgData.empty())
859 sgData.insert(sgData.begin(), 1);
860 if (!instData.empty())
861 instData.insert(instData.begin(), 1);
862 if (!laneLayout.empty())
863 laneLayout.insert(laneLayout.begin(), 1);
864 if (!laneData.empty())
865 laneData.insert(laneData.begin(), 1);
866 order.push_back(dimDiff - 1 - i);
867 }
868
870 context, SmallVector<int32_t>(order.begin(), order.end()));
871 if (!resLayout.getOrder())
872 orderAttr = nullptr;
873
874 return buildLayout(context, sgLayout, sgData, instData, laneLayout,
875 laneData, orderAttr);
876 }
877 return resLayout;
878}
879
880/// Infers the source layout attribute for a shape cast operation given the
881/// result layout attribute, result shape, and source shape.
882xegpu::DistributeLayoutAttr
883xegpu::inferShapeCastSourceLayout(xegpu::DistributeLayoutAttr resLayout,
884 ArrayRef<int64_t> resShape,
885 ArrayRef<int64_t> srcShape) {
886
887 // There are three use cases:
888 // 1. expand dims of low-rank dimensions (e.g., 1D to 2D): to set up the
889 // tensor before broadcast
890 // 2. split dim of a high-rank dimension (e.g., 1D to 2D): to setup tensor
891 // for multi-stage reduction
892 // 3. combines all dims to a single dim and put in the innermost dim in 2d as
893 // [1, combinedData] or [combinedData]. Say, [2, 4, 8] -> [1, 64] or [64]
894 // Use cases are only supported after workgroup distribution,
895 // like cross-sg reduction saves multidimension data to
896 // 1D slm buffer, shapecast inserted by cse/canonicalization passes.
897
898 // Use case 1: Shapes only differ by expanding unit dimensions, for broadcast
899 SmallVector<int64_t> expandedUnitDims;
900
901 if (xegpu::matchUnitDimExpansion(srcShape, resShape, expandedUnitDims)) {
902 // create a slice layout for the source by removing the expanded unit dims
903 auto sliceDimsAttr = DenseI64ArrayAttr::get(
904 resLayout.getContext(), ArrayRef<int64_t>(expandedUnitDims));
905 auto srcLayout =
906 xegpu::SliceAttr::get(resLayout.getContext(), resLayout, sliceDimsAttr);
907 return srcLayout;
908 }
909
910 // Use case 2: Dim split from source to result, for multi-stage reduction
911 SmallVector<SmallVector<int64_t>> splitDimGroups;
912 if (xegpu::matchSplitDimExpansion(srcShape, resShape, splitDimGroups)) {
913 auto srcLayout = resLayout;
914 // Later groups hold higher dims. Collapse from the last one so earlier
915 // groups keep their indices.
916 for (const auto &dimGroup : llvm::reverse(splitDimGroups))
917 srcLayout = srcLayout.collapseDims(dimGroup);
918
919 return srcLayout;
920 }
921
922 // Use case 3: General dim collapse, for cross-sg reduction to SLM and other
923 // shape casts where consecutive src dims fold into a single dst dim.
925 if (xegpu::matchDimCollapse(srcShape, resShape, collapseDims)) {
926 auto srcLayout = resLayout;
927 for (int64_t dstIdx = static_cast<int64_t>(collapseDims.size()) - 1;
928 dstIdx >= 0; --dstIdx) {
929 ArrayRef<int64_t> srcDims = collapseDims[dstIdx];
930 if (srcDims.empty()) {
931 srcLayout = srcLayout.dropDims({dstIdx});
932 continue;
933 }
934 if (srcDims.size() == 1)
935 continue;
936 SmallVector<int64_t> targetShape;
937 targetShape.reserve(srcDims.size());
938 for (int64_t d : srcDims)
939 targetShape.push_back(srcShape[d]);
940 srcLayout = srcLayout.expandDim(dstIdx, targetShape);
941 }
942 return srcLayout;
943 }
944 return nullptr;
945}
946
947//===----------------------------------------------------------------------===//
948// Forward layout inference (source layout -> result layout)
949//===----------------------------------------------------------------------===//
950
951/// Infers the result layout attribute for a transpose operation given the
952/// source layout attribute and permutation.
953///
954/// vector.transpose semantics is `result[i] = source[permutation[i]]`, so
955/// `result_layout[i] = source_layout[permutation[i]]`, which is exactly
956/// `srcLayout.transposeDims(permutation)`. This is the inverse of
957/// inferTransposeSourceLayout (which applies the inverse permutation).
958xegpu::DistributeLayoutAttr
959xegpu::inferTransposeResultLayout(xegpu::DistributeLayoutAttr srcLayout,
960 ArrayRef<int64_t> permutation) {
961 return srcLayout.transposeDims(permutation);
962}
963
964/// Infers the result layout attribute for a shape cast operation given the
965/// source layout attribute, source shape, and result shape. This is the
966/// inverse of inferShapeCastSourceLayout: a dim-split (src -> res) is undone by
967/// collapsing the split groups, and a dim-collapse (src -> res) is undone by
968/// expanding the collapsed groups. The unit-dim-expansion case is not inverted
969/// here because recovering which result dims are the expanded unit dims would
970/// require the SliceAttr the backward direction produces; such patterns return
971/// nullptr (leaving the result un-laid-out).
972xegpu::DistributeLayoutAttr
973xegpu::inferShapeCastResultLayout(xegpu::DistributeLayoutAttr srcLayout,
974 ArrayRef<int64_t> srcShape,
975 ArrayRef<int64_t> resShape) {
976 // Case: source dims were split into result dims (forward of use case 2 in
977 // inferShapeCastSourceLayout). Undo by expanding each source dim into its
978 // group of result dims.
979 SmallVector<SmallVector<int64_t>> splitDimGroups;
980 if (xegpu::matchSplitDimExpansion(srcShape, resShape, splitDimGroups)) {
981 auto resLayout = srcLayout;
982 // Later groups hold higher dims. Expand from the last one so earlier
983 // dims keep their indices.
984 for (int64_t srcIdx = static_cast<int64_t>(splitDimGroups.size()) - 1;
985 srcIdx >= 0; --srcIdx) {
986 ArrayRef<int64_t> resDims = splitDimGroups[srcIdx];
987 if (resDims.size() <= 1)
988 continue;
989 SmallVector<int64_t> targetShape;
990 targetShape.reserve(resDims.size());
991 for (int64_t d : resDims)
992 targetShape.push_back(resShape[d]);
993 resLayout = resLayout.expandDim(srcIdx, targetShape);
994 }
995 return resLayout;
996 }
997
998 // Case: source dims were collapsed into result dims (forward of use case 3).
999 // Undo by collapsing each group of source dims into its single result dim.
1001 if (xegpu::matchDimCollapse(srcShape, resShape, collapseDims)) {
1002 auto resLayout = srcLayout;
1003 // Process result dims from innermost to outermost so that collapsing a
1004 // group does not shift the indices of groups not yet processed.
1005 for (int64_t dstIdx = static_cast<int64_t>(collapseDims.size()) - 1;
1006 dstIdx >= 0; --dstIdx) {
1007 ArrayRef<int64_t> srcDims = collapseDims[dstIdx];
1008 // A result dim with no backing source dims is a trailing/leading unit
1009 // dim; its forward inference is ambiguous, so bail out.
1010 if (srcDims.empty())
1011 return nullptr;
1012 if (srcDims.size() == 1)
1013 continue;
1014 resLayout = resLayout.collapseDims(llvm::to_vector(srcDims));
1015 }
1016 return resLayout;
1017 }
1018
1019 return nullptr;
1020}
1021
1022/// Infers the result layout attribute for a non-anchor operation from the
1023/// layouts of its source operands. Forward counterpart of
1024/// inferSourceLayoutFromResultForNonAnchorOp.
1025xegpu::DistributeLayoutAttr xegpu::inferResultLayoutFromSourceForNonAnchorOp(
1027 if (op->getNumResults() != 1)
1028 return nullptr;
1029
1030 // For vector::TransposeOp, infer the result layout from the source layout.
1031 if (auto transpose = dyn_cast<vector::TransposeOp>(op)) {
1032 if (!operandLayouts[0])
1033 return nullptr;
1034 return xegpu::inferTransposeResultLayout(operandLayouts[0],
1035 transpose.getPermutation());
1036 }
1037
1038 // For vector::ShapeCastOp, infer the result layout from the source layout.
1039 if (auto shapeCast = dyn_cast<vector::ShapeCastOp>(op)) {
1040 if (!operandLayouts[0])
1041 return nullptr;
1043 operandLayouts[0], shapeCast.getSourceVectorType().getShape(),
1044 shapeCast.getResultVectorType().getShape());
1045 }
1046
1047 // For elementwise operations, all operands and the result share the same
1048 // layout. Use the first operand that carries a layout.
1050 for (xegpu::DistributeLayoutAttr layout : operandLayouts)
1051 if (layout)
1052 return layout;
1053 return nullptr;
1054 }
1055
1056 // TODO: add forward inference rules for the remaining ops; their result is
1057 // left un-laid-out until then.
1058 // - vector::BroadcastOp: the forward direction is under-determined. The
1059 // backward rule (inferBroadcastSourceLayout) either sets broadcast dims to
1060 // unit data (losing the original data on those dims) or wraps the result
1061 // in a SliceAttr; neither is generally invertible from the source layout
1062 // alone, so a forward rule must decide how to distribute the new/stretched
1063 // dims.
1064 // - vector::BitCastOp, vector::MultiDimReductionOp / vector::ReductionOp,
1065 // vector::InterleaveOp / vector::DeinterleaveOp, and the insert / extract
1066 // / strided-slice family.
1067 return nullptr;
1068}
1069
1070//===----------------------------------------------------------------------===//
1071// Layout derivation helpers: factorize sgCount into
1072// sg_layout candidates, then
1073// compute per-subgroup (sgData) and per-lane
1074// (lane_layout/lane_data/inst_data).
1075//===----------------------------------------------------------------------===//
1076
1078
1079/// Enumerates all ways to split `total` into `rank` factors whose product
1080/// equals `total`. Returns the list of all such factorizations.
1082 int64_t rank) {
1084 SmallVector<int64_t> current(rank, 0);
1085
1086 // Returns all divisors of `n` in ascending order.
1087 auto getDivisors = [](int64_t n) {
1089 for (int64_t i = 1; i * i <= n; ++i) {
1090 if (n % i == 0) {
1091 divs.push_back(i);
1092 if (i != n / i)
1093 divs.push_back(n / i);
1094 }
1095 }
1096 llvm::sort(divs);
1097 return divs;
1098 };
1099
1100 std::function<void(int64_t, int64_t)> generate = [&](int64_t dim,
1101 int64_t remaining) {
1102 if (dim == rank - 1) {
1103 current[dim] = remaining;
1104 results.push_back(LayoutRepresentation(current));
1105 return;
1106 }
1107 for (int64_t factor : getDivisors(remaining)) {
1108 current[dim] = factor;
1109 generate(dim + 1, remaining / factor);
1110 }
1111 };
1112
1113 generate(0, total);
1114 return results;
1115}
1116
1117// Computes all valid N-dimensional sg_layout candidates for the given
1118// sgCount, whose sgData (= wgShape / sgLayout):
1119// 1. Evenly divides wgShape (i.e., wgShape[d] % sgLayout[d] == 0).
1120// 2. Is a multiple of instData (i.e., sgData[d] % instData[d] == 0).
1121// Results are sorted by balance (smallest max-min spread first), with
1122// lexicographic order as a tiebreaker.
1123//
1124// `broadcastDim` (default -1 = none) marks a dimension broadcast across
1125// subgroups rather than distributed (e.g. the K/contraction dim of a DPAS
1126// operand). Its full extent stays in every subgroup, so rule 1 is skipped for
1127// it, but rule 2 (multiple of instData) still applies.
1128//
1129// Example (2D):
1130// wgShape = [128, 64], instData = [8, 16], sgCount = 32
1131// Returns: [[8,4], [16,2]], corresponding to sgData [16,16] and [8,32].
1134 int64_t sgCount, int64_t broadcastDim = -1) {
1135 int64_t rank = wgShape.size();
1136 assert(rank > 0 && "wgShape must be non-empty");
1137 assert(static_cast<int64_t>(instData.size()) == rank &&
1138 "instData rank must match wgShape rank");
1139
1140 // Step 1: Get all N-D factorizations of sgCount.
1141 auto allFactorizations = enumerateFactorizations(sgCount, rank);
1142
1143 // Step 2: Filter to keep only valid candidates.
1145 for (const auto &sgLayout : allFactorizations) {
1146 bool valid = true;
1147 for (int64_t dim = 0; dim < rank; ++dim) {
1148 // A broadcast dim keeps its full extent in every subgroup; others are
1149 // split evenly by sgLayout[dim].
1150 int64_t sgData;
1151 if (dim == broadcastDim) {
1152 sgData = wgShape[dim];
1153 } else {
1154 if (wgShape[dim] % sgLayout[dim] != 0) {
1155 valid = false;
1156 break;
1157 }
1158 sgData = wgShape[dim] / sgLayout[dim];
1159 }
1160 if (sgData % instData[dim] != 0) {
1161 valid = false;
1162 break;
1163 }
1164 }
1165 if (valid)
1166 candidates.push_back(sgLayout);
1167 }
1168
1169 // Step 3: Sort by balance (smallest max-min spread), then lexicographic.
1170 llvm::sort(candidates, [](const LayoutRepresentation &lhs,
1171 const LayoutRepresentation &rhs) {
1172 int64_t spreadLhs = *llvm::max_element(lhs) - *llvm::min_element(lhs);
1173 int64_t spreadRhs = *llvm::max_element(rhs) - *llvm::min_element(rhs);
1174 if (spreadLhs != spreadRhs)
1175 return spreadLhs < spreadRhs;
1176 return lhs < rhs;
1177 });
1178 return candidates;
1179}
1180
1181/// Helper function to compute inst_data vectors for DPAS operands A, B, and
1182/// C/D.
1183static std::optional<SmallVector<int64_t>> get2DBlockIOInstDataLayout(
1184 ArrayRef<int64_t> dataShape, Type elemTy,
1185 const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction,
1186 bool transform = false, bool transpose = false) {
1187 int rank = dataShape.size();
1188 auto blockWHC =
1189 uArchInstruction->getBlockWidthHeightCount(elemTy, transform, transpose);
1190 if (!blockWHC)
1191 return std::nullopt;
1192 auto [bWidths, bHeights, bCounts] = blockWHC.value();
1193 // Compute inst_data from hardware block params. For Nd ops, the lane
1194 // factorization above (laneLayout / laneData) is rigid; inst_data must be
1195 // a multiple of lane_layout * lane_data on each dim (Category A
1196 // invariant).
1197 SmallVector<int64_t> instData(rank, 1);
1198 assert(rank >= 2 && "dataShape must be at least 2D for 2D-block IO");
1199 int instWidth =
1200 xegpu::getLargestDivisor(static_cast<int>(dataShape.back()), bWidths);
1201 int instHeight =
1202 xegpu::getLargestDivisor(static_cast<int>(dataShape[rank - 2]), bHeights);
1203 // No supported hardware block size divides the data dim (e.g. innermost dim
1204 // of 1 vs. minimum block width 16): not realizable as a 2D-block instruction.
1205 if (instWidth < 0 || instHeight < 0)
1206 return std::nullopt;
1207 instData.back() = instWidth;
1208 instData[rank - 2] = instHeight;
1209
1210 return instData;
1211}
1212
1213/// Picks the subgroup layout for a 2D block IO op (store_nd / prefetch_nd).
1214/// Every supported block (height, width) dividing the shape is tried, largest
1215/// area first and the more square block first among equal areas, until one
1216/// admits a subgroup layout.
1217static xegpu::DistributeLayoutAttr get2DBlockIOSubgroupLayout(
1218 MLIRContext *context, ArrayRef<int64_t> dataShape, Type elemTy,
1219 const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction,
1220 int numSg) {
1221 auto blockWHC = uArchInstruction->getBlockWidthHeightCount(elemTy);
1222 if (!blockWHC)
1223 return nullptr;
1224 auto [bWidths, bHeights, bCounts] = blockWHC.value();
1225 int rank = dataShape.size();
1226 assert(rank >= 2 && "dataShape must be at least 2D for 2D-block IO");
1227
1228 SmallVector<SmallVector<int64_t>> instDataCandidates;
1229 for (int width : bWidths) {
1230 if (width <= 0 || dataShape[rank - 1] % width != 0)
1231 continue;
1232 for (int height : bHeights) {
1233 if (height <= 0 || dataShape[rank - 2] % height != 0)
1234 continue;
1235 SmallVector<int64_t> instData(rank, 1);
1236 instData[rank - 1] = width;
1237 instData[rank - 2] = height;
1238 instDataCandidates.push_back(std::move(instData));
1239 }
1240 }
1241 // Largest area first; among equal areas, the more square block first (e.g.
1242 // 16x16 before 8x32 before 4x64), then the wider one.
1243 llvm::stable_sort(instDataCandidates, [&](ArrayRef<int64_t> lhs,
1244 ArrayRef<int64_t> rhs) {
1245 int64_t hL = lhs[rank - 2], wL = lhs[rank - 1];
1246 int64_t hR = rhs[rank - 2], wR = rhs[rank - 1];
1247 if (hL * wL != hR * wR)
1248 return hL * wL > hR * wR;
1249 if (std::min(hL, wL) != std::min(hR, wR))
1250 return std::min(hL, wL) > std::min(hR, wR);
1251 return wL > wR;
1252 });
1253
1254 for (ArrayRef<int64_t> instData : instDataCandidates) {
1255 auto sgLayouts = getSgLayoutCandidates(dataShape, instData, numSg);
1256 if (!sgLayouts.empty())
1257 return buildSgLayout(context, dataShape, sgLayouts.front(), /*dimK=*/-1);
1258 }
1259 return nullptr;
1260}
1261
1262/// Helper function to compute inst_data vectors for DPAS operands A, B, and
1263/// C/D. Look up the uArch table and search for the largest supported block size
1264/// that divides the data shape
1265static std::optional<std::tuple<SmallVector<int64_t>, SmallVector<int64_t>,
1268 VectorType aTy, VectorType bTy, VectorType cdTy,
1269 const xegpu::uArch::MMAInstructionInterface *uArchInstruction) {
1270
1271 // M dimension is the second-to-last dim of A (handles batch dims).
1272 const unsigned dataALen = aTy.getShape()[aTy.getRank() - 2];
1273 auto supportedALen = uArchInstruction->getSupportedM(aTy.getElementType());
1274 const int maxALen =
1275 xegpu::getLargestDivisor(dataALen, ArrayRef<unsigned>(supportedALen));
1276
1277 // N dimension is the last dim of B.
1278 const unsigned dataBLen = bTy.getShape().back();
1279 auto supportedBLen = uArchInstruction->getSupportedN(bTy.getElementType());
1280 const int maxBLen =
1281 xegpu::getLargestDivisor(dataBLen, ArrayRef<unsigned>(supportedBLen));
1282
1283 auto supportedCLen = uArchInstruction->getSupportedN(cdTy.getElementType());
1284 const int maxCLen =
1285 xegpu::getLargestDivisor(dataBLen, ArrayRef<unsigned>(supportedCLen));
1286 if (maxALen == -1 || maxBLen == -1 || maxCLen == -1)
1287 return std::nullopt;
1288
1289 auto supportedKLen = uArchInstruction->getSupportedK(aTy.getElementType());
1290 if (supportedKLen.empty())
1291 return std::nullopt;
1292 auto kDimSize = supportedKLen[0];
1293
1294 SmallVector<int64_t> instDataA(aTy.getRank(), 1);
1295 instDataA[aTy.getRank() - 2] = maxALen;
1296 instDataA[aTy.getRank() - 1] = kDimSize;
1297 SmallVector<int64_t> instDataB(bTy.getRank(), 1);
1298 instDataB[bTy.getRank() - 2] = kDimSize;
1299 instDataB[bTy.getRank() - 1] = maxBLen;
1300 SmallVector<int64_t> instDataCD(cdTy.getRank(), 1);
1301 instDataCD[cdTy.getRank() - 2] = maxALen;
1302 instDataCD[cdTy.getRank() - 1] = maxCLen;
1303 return std::make_tuple(instDataA, instDataB, instDataCD);
1304}
1305
1306/// Computes lane_layout and lane_data for scatter-style store anchor layouts
1307/// (store scatter, store matrix). Lanes and the per-lane vector both live on
1308/// the innermost dim:
1309/// - laneLayout[innermost] = min(subgroupSize, srcShape[innermost])
1310/// - laneData[innermost] = min(srcShape[innermost] / laneLayout[innermost],
1311/// maxChunkSize)
1312/// All other entries are 1.
1313static std::pair<SmallVector<int64_t>, SmallVector<int64_t>>
1315 int64_t subgroupSize, int64_t maxChunkSize) {
1316 int64_t rank = instShape.size();
1317 SmallVector<int64_t> laneLayout(rank, 1), laneData(rank, 1);
1318 int64_t innermost = rank - 1;
1319 laneLayout[innermost] = std::min(subgroupSize, instShape[innermost]);
1320 laneData[innermost] =
1321 std::min(instShape[innermost] / laneLayout[innermost], maxChunkSize);
1322 return {laneLayout, laneData};
1323}
1324
1325// Computes the (lane_layout, lane_data, order) a 2D block instruction can
1326// deliver over `instShape`, from the element `bitwidth` and the variant's
1327// `packingSize`. lane_data packs elements narrower than the packing size along
1328// the packing dim: the innermost one, or the one above it when transformed
1329// (VNNI). Lanes are spread along the innermost dim, or the one above it when
1330// transposed, which makes that dim fastest-changing and so returns a reversed
1331// `order`. `order` is empty for the variants that keep the default. Leading
1332// dims are unit.
1333static std::tuple<SmallVector<int64_t>, SmallVector<int64_t>,
1336 int64_t bitwidth, int64_t packingSize,
1337 bool transform = false, bool transpose = false) {
1338 int64_t rank = instShape.size();
1339 assert(rank >= 2 && "Expected at least a 2D shape for a 2D block op");
1340 SmallVector<int64_t> laneLayout(rank, 1), laneData(rank, 1), order;
1341
1342 int64_t packDim = transform ? rank - 2 : rank - 1;
1343 laneData[packDim] = llvm::divideCeil(packingSize, bitwidth);
1344
1345 int64_t laneDim = transpose ? rank - 2 : rank - 1;
1346 laneLayout[laneDim] =
1347 std::min(subgroupSize, instShape[laneDim] / laneData[laneDim]);
1348
1349 if (transpose) {
1350 for (int64_t i = 0; i < rank; ++i)
1351 order.push_back(rank - 1 - i);
1352 std::swap(order[0], order[1]);
1353 }
1354
1355 // assert that the lane layout and data fit in the inst shape
1356 for (int64_t i = 0; i < rank; ++i) {
1357 int64_t laneProduct = laneLayout[i] * laneData[i];
1358 assert(instShape[i] % laneProduct == 0 &&
1359 "lane_layout * lane_data must evenly divide the inst shape");
1360 (void)laneProduct;
1361 }
1362 return {laneLayout, laneData, order};
1363}
1364
1365/// Derives (lane_layout, lane_data, inst_data) for a vector.multi_reduction
1366/// source from the layout requested by its result's consumer. Each returned
1367/// vector has one entry per source dimension.
1368///
1369/// Reuse the consumer's slice parent when the slice dimensions exactly match
1370/// `reductionDims`, the parent's effective lane_layout and lane_data each have
1371/// one entry per source dimension, and the lane layout uses all `subgroupSize`
1372/// lanes. Clamp reused lane counts to srcShape[i] / lane_data[i], since the
1373/// sliced dimensions may have different extents in the reduction source.
1374///
1375/// If the consumer's slice parent cannot be reused, initialize lane_layout and
1376/// lane_data to 1, then copy available consumer entries onto non-reduced source
1377/// dimensions in order, with the same clamp: a consumer that broadcasts along
1378/// a unit dimension may place lanes on it.
1379///
1380/// For a derived (not reused) layout, assign any unused lanes to the innermost
1381/// dimension if it is reduced, up to the same bound. If that dimension still
1382/// has only one lane, then the lane can reduce a vector limited by
1383/// maxReduceVectorSize and the source dimension's size. The vector budget
1384/// (maxReduceVectorSize) applies to the product of lane_data across all
1385/// dimensions. If that product already meets or exceeds the budget, leave
1386/// lane_data unchanged.
1387///
1388/// Set inst_data[i] to lane_layout[i] * lane_data[i]. On non-reduced
1389/// dimensions among the last two, preserve a reused parent's larger
1390/// inst_data[i]; leading dimensions are not widened because lane-level
1391/// distribution only supports unit leading dimensions.
1392///
1393/// Source layout examples with subgroupSize = maxReduceVectorSize = 16:
1394/// \code
1395/// // Reuse a matching slice parent's lane layout and data.
1396/// srcShape=[32, 64], reductionDims=[1], consumer=slice(parent, dims=[1])
1397/// parent: lane_layout=[1, 16], lane_data=[1, 1]
1398/// source: lane_layout=[1, 16], lane_data=[1, 1], inst_data=[1, 16]
1399///
1400/// // Preserve dim 0 blocking and limit dim 1 lanes to the source size.
1401/// srcShape=[16, 4], reductionDims=[1], consumer=slice(parent, dims=[1])
1402/// parent: lane_layout=[1, 16], lane_data=[1, 1], inst_data=[8, 16]
1403/// source: lane_layout=[1, 4], lane_data=[1, 1], inst_data=[8, 4]
1404///
1405/// // Assign spare lanes to the innermost dimension when it is reduced.
1406/// srcShape=[16, 32, 32], reductionDims=[2]
1407/// consumer: lane_layout=[1, 2], lane_data=[1, 1]
1408/// source: lane_layout=[1, 2, 8], lane_data=[1, 1, 1], inst_data=[1, 2, 8]
1409///
1410/// // Keep the consumer's lanes on the non-reduced dimension.
1411/// srcShape=[32, 64], reductionDims=[0]
1412/// consumer: lane_layout=[16], lane_data=[1]
1413/// source: lane_layout=[1, 16], lane_data=[1, 1], inst_data=[1, 16]
1414///
1415/// // For a scalar reduction, put lanes on the innermost dimension.
1416/// srcShape=[32, 64], reductionDims=[0, 1]
1417/// consumer: none
1418/// source: lane_layout=[1, 16], lane_data=[1, 1], inst_data=[1, 16]
1419/// \endcode
1420static std::tuple<SmallVector<int64_t>, SmallVector<int64_t>,
1423 ArrayRef<int64_t> srcShape, ArrayRef<int64_t> reductionDims,
1424 int subgroupSize, int64_t maxReduceVectorSize,
1425 xegpu::DistributeLayoutAttr consumerLayout = nullptr) {
1426 int srcRank = srcShape.size();
1427 SmallVector<int64_t> laneLayout(srcRank, 1), laneData(srcRank, 1);
1428 auto isReduced = [&](int dim) {
1429 return llvm::is_contained(reductionDims, dim);
1430 };
1431
1432 // A matching slice parent provides lane information for reduced dimensions
1433 // as well as the dimensions present in the result.
1434 SmallVector<int64_t> parentInstData;
1435 auto consumerSlice = dyn_cast_if_present<xegpu::SliceAttr>(consumerLayout);
1436 bool reusedParent = false;
1437 if (consumerSlice &&
1438 consumerSlice.getDims().asArrayRef().equals(reductionDims)) {
1439 auto parent = consumerSlice.getParent();
1440 SmallVector<int64_t> parentLaneLayout =
1441 parent.getEffectiveLaneLayoutAsInt();
1442 SmallVector<int64_t> parentLaneData = parent.getEffectiveLaneDataAsInt();
1443 if (static_cast<int>(parentLaneLayout.size()) == srcRank &&
1444 static_cast<int>(parentLaneData.size()) == srcRank &&
1445 computeProduct(parentLaneLayout) == subgroupSize) {
1446 laneLayout = std::move(parentLaneLayout);
1447 laneData = std::move(parentLaneData);
1448 reusedParent = true;
1449 parentInstData = parent.getEffectiveInstDataAsInt();
1450 if (static_cast<int>(parentInstData.size()) != srcRank)
1451 parentInstData.clear();
1452
1453 // The parent may come from a broadcast to a larger shape. Bound its
1454 // lane counts by the source extent, accounting for per-lane packing.
1455 for (int i = 0; i < srcRank; ++i)
1456 laneLayout[i] = std::min(
1457 laneLayout[i], std::max<int64_t>(1, srcShape[i] / laneData[i]));
1458 }
1459 }
1460
1461 // Without a reusable parent, map result dimensions to non-reduced source
1462 // dimensions.
1463 if (!reusedParent) {
1464 SmallVector<int64_t> consumerLaneLayout, consumerLaneData;
1465 if (consumerLayout) {
1466 consumerLaneLayout = consumerLayout.getEffectiveLaneLayoutAsInt();
1467 consumerLaneData = consumerLayout.getEffectiveLaneDataAsInt();
1468 }
1469 for (int i = 0, c = 0; i < srcRank; ++i) {
1470 if (isReduced(i))
1471 continue;
1472 if (c < static_cast<int>(consumerLaneLayout.size()))
1473 laneLayout[i] = consumerLaneLayout[c];
1474 if (c < static_cast<int>(consumerLaneData.size()))
1475 laneData[i] = consumerLaneData[c];
1476 ++c;
1477 }
1478
1479 // Cap laneLayout using srcShape.
1480 for (int i = 0; i < srcRank; ++i)
1481 laneLayout[i] = std::min(laneLayout[i],
1482 std::max<int64_t>(1, srcShape[i] / laneData[i]));
1483
1484 // Assign spare lanes only when the innermost source dimension is reduced,
1485 // matching the distribution typically used by memory loads and DPAS
1486 // results.
1487 int innermost = srcRank - 1;
1488 if (isReduced(innermost)) {
1489 int64_t spareLanes =
1490 std::max<int64_t>(1, subgroupSize / computeProduct(laneLayout));
1491 if (spareLanes > 1)
1492 laneLayout[innermost] =
1493 std::min(spareLanes, std::max<int64_t>(1, srcShape[innermost]));
1494
1495 if (laneLayout[innermost] == 1) {
1496 // Adjust lane_data on this dimension using the remaining vector budget,
1497 // capped by the source extent.
1498 int64_t vectorBudget = maxReduceVectorSize / computeProduct(laneData);
1499 if (vectorBudget > 1)
1500 laneData[innermost] =
1501 std::min(vectorBudget * laneData[innermost], srcShape[innermost]);
1502 }
1503 }
1504 }
1505
1506 // Preserve compatible consumer blocking on non-reduced dimensions so the
1507 // reduction result can use the same instruction tiles as its consumer. Only
1508 // the last two dimensions are widened: lane-level distribution of
1509 // multi_reduction requires the blocked source to be unit on the dimensions
1510 // before them.
1511 SmallVector<int64_t> instData(srcRank);
1512 int firstInnerDim = std::max(0, srcRank - 2);
1513 for (int i = 0; i < srcRank; ++i) {
1514 instData[i] = laneLayout[i] * laneData[i];
1515 if (isReduced(i) || i < firstInnerDim || parentInstData.empty())
1516 continue;
1517 // The lane product must divide the instruction tile, which must divide
1518 // the source extent.
1519 int64_t wider = parentInstData[i];
1520 if (wider > instData[i] && wider % instData[i] == 0 &&
1521 srcShape[i] % wider == 0)
1522 instData[i] = wider;
1523 }
1524
1525 return {laneLayout, laneData, instData};
1526}
1527
1528//===----------------------------------------------------------------------===//
1529// Result/anchor-layout setup. Each op category derives lane_layout/lane_data
1530// (and inst_data / sgData) differently. Two things vary across ops:
1531//
1532// * Consumer dependence: consumer-driven ops prefer the layout requested by
1533// their downstream uses and fall back to uArch defaults only when it is
1534// absent/invalid; sinks (StoreNd, PrefetchNd) have no consumer and always
1535// pick their own layout from uArch.
1536//
1537// * Derivation direction between inst_data and lane_layout/lane_data. Both
1538// obey the invariant inst_data = k * lane_layout * lane_data, where `k` is
1539// a per-dim integer >= 1 giving how many times each lane repeats its
1540// access to cover one instruction's data tile (k == 1 means one lane
1541// position per element; k > 1 means the instruction loads/stores several
1542// elements per lane along that dim). Ops solve this invariant from
1543// opposite ends:
1544// - Rigid-lane ops (Nd block IO, DPAS): hardware fixes lane_layout /
1545// lane_data first, then inst_data is built as a multiple of their
1546// product (using get2DBlockIOInstDataLayout / getDpasInstDataLayouts).
1547// - inst_data-first ops (scatter load): take inst_data from the consumer
1548// and derive lane_layout/lane_data underneath it.
1549//
1550// - DPAS (+DPAS_MX) : rigid lanes — inst_data from HW block dims; A/B/C/D
1551// lanes/data follow each operand's matmul role; DPAS_MX
1552// additionally lays out the scale operand.
1553// - LoadNd : consumer-driven, rigid lanes — honors the consumer's
1554// inst_data / lane / sg_layout (incl. transpose & VNNI
1555// packing) when it satisfies uArch block constraints,
1556// else falls back to the default 2D-block scheme (lanes
1557// on the last dim, rank-2 if transposed). The fallback
1558// picks the LARGEST uArch block that divides the data
1559// shape, so the resulting inst_data block can be bigger
1560// than what the consumer asked for (fewer, wider
1561// loads).
1562// - StoreNd/PrefetchNd: data sinks, no consumer, rigid lanes — pick the
1563// 2D-block layout directly from uArch (no VNNI
1564// packing).
1565// - Load (scatter) : load_gather / load_matrix, consumer-driven,
1566// inst_data-first — reuse the consumer's inst_data and
1567// derive lane_layout/lane_data, else default to lanes +
1568// per-lane chunk on the innermost dim (chunk capped by
1569// maxChunkSize).
1570// - Store (scatter) : store_scatter / store_matrix — same scatter scheme,
1571// but always self-derived from the scatter default.
1572// - Reduction : multi_reduction derives source lanes and instruction
1573// blocking from the consumer, assigning spare lanes to
1574// the innermost dim if reduced. The result layout is a
1575// slice over the reduction dims. See
1576// setupMultiReductionResultLayout for each layout kind.
1577// - BitCast/Interleave: scale the innermost data field by the bitwidth /
1578// interleave ratio so the source layout divides back
1579// out.
1580// - InsertStridedSlice: clamp lane_data per dim to fit the inserted slice
1581// (Lane kind only; sg/inst layouts unsupported).
1582//===----------------------------------------------------------------------===//
1583
1584/// Helper function to set up subgroup layouts for DPAS operands A, B, and
1585/// C/D. Compute subgroup layout candidates based on wgtile and instData, and
1586/// then pick the best one that satisfies all operands and the consumer (if
1587/// specified).
1588static std::optional<
1589 std::tuple<xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr,
1590 xegpu::DistributeLayoutAttr>>
1592 mlir::MLIRContext *context, VectorType aTy, VectorType bTy, VectorType cdTy,
1593 xegpu::DistributeLayoutAttr consumerLayout, int numSg,
1595 instDataVecs,
1596 const xegpu::uArch::MMAInstructionInterface *uArchInstruction) {
1597 SmallVector<int64_t> instDataA = std::get<0>(instDataVecs);
1598 SmallVector<int64_t> instDataB = std::get<1>(instDataVecs);
1599 SmallVector<int64_t> instDataCD = std::get<2>(instDataVecs);
1600
1601 std::optional<LayoutRepresentation> consumerSgLayout = std::nullopt;
1602 if (consumerLayout && consumerLayout.isForWorkgroup()) {
1603 consumerSgLayout = consumerLayout.getEffectiveSgLayoutAsInt();
1604 }
1605
1606 // Picks the best subgroup layout common to A, B and C/D for the given
1607 // inst_data, or std::nullopt if there is none.
1608 auto pickSgLayout = [&]() -> std::optional<LayoutRepresentation> {
1609 auto layoutsA = getSgLayoutCandidates(aTy.getShape(), instDataA, numSg,
1610 /*broadcastDim=*/aTy.getRank() - 1);
1611 auto layoutsB = getSgLayoutCandidates(bTy.getShape(), instDataB, numSg,
1612 /*broadcastDim=*/bTy.getRank() - 2);
1613 auto layoutsCD = getSgLayoutCandidates(cdTy.getShape(), instDataCD, numSg);
1614 if (layoutsA.empty() || layoutsB.empty() || layoutsCD.empty())
1615 return std::nullopt;
1616
1617 std::optional<LayoutRepresentation> bestPick;
1618 for (auto &sgLayout : layoutsB) {
1619 if (llvm::is_contained(layoutsA, sgLayout) &&
1620 llvm::is_contained(layoutsCD, sgLayout)) {
1621 // Is in (A and B and CD) and matches consumer -> best pick
1622 if (consumerSgLayout.has_value() && sgLayout == *consumerSgLayout)
1623 return sgLayout;
1624 // Is in (A and B and CD) layoutsB is ordered from most
1625 // balanced to least. So the first one we see is the most balanced
1626 // one, remember it and later only update if there is one that matches
1627 // the consumer.
1628 if (!bestPick)
1629 bestPick = sgLayout;
1630 }
1631 }
1632 return bestPick;
1633 };
1634
1635 // Try supported M (repeat count) values, largest first, until one admits a
1636 // common subgroup layout. N and K are fixed, so only M can shrink.
1637 int64_t mDimA = aTy.getRank() - 2;
1638 int64_t mDimCD = cdTy.getRank() - 2;
1639 auto supportedM = uArchInstruction->getSupportedM(aTy.getElementType());
1640 llvm::sort(supportedM, std::greater<uint32_t>());
1641
1642 std::optional<LayoutRepresentation> bestPick;
1643 for (unsigned m : supportedM) {
1644 if (m == 0 || aTy.getShape()[mDimA] % m != 0)
1645 continue;
1646 instDataA[mDimA] = m;
1647 instDataCD[mDimCD] = m;
1648 if ((bestPick = pickSgLayout()))
1649 break;
1650 }
1651 if (!bestPick)
1652 return std::nullopt;
1653
1654 const auto &picked = *bestPick;
1655
1656 auto dpasALayout = buildSgLayout(context, aTy.getShape(), picked,
1657 /*dimK=*/aTy.getRank() - 1);
1658 auto dpasBLayout = buildSgLayout(context, bTy.getShape(), picked,
1659 /*dimK=*/bTy.getRank() - 2);
1660 auto dpasCDLayout = buildSgLayout(context, cdTy.getShape(), picked);
1661 return std::make_tuple(dpasALayout, dpasBLayout, dpasCDLayout);
1662}
1663
1664/// Sets up the anchor layouts for dpas operands (A, B, and C/D).
1665/// The numSg and consumerLayout (optional) are only used by sg layout
1666/// creation.
1667std::optional<
1668 std::tuple<xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr,
1669 xegpu::DistributeLayoutAttr>>
1670xegpu::setupDpasLayout(xegpu::LayoutKind layoutKind, VectorType aTy,
1671 VectorType bTy, VectorType cdTy,
1672 xegpu::DistributeLayoutAttr consumerLayout, int numSg,
1673 const xegpu::uArch::uArch *uArch) {
1674 auto context = aTy.getContext();
1675 const auto *uArchInstruction =
1676 dyn_cast<xegpu::uArch::SubgroupMatrixMultiplyAcc>(uArch->getInstruction(
1678 if (!uArchInstruction)
1679 return std::nullopt;
1680 auto subgroupSize = uArch->getSubgroupSize();
1681
1682 auto [laneLayoutA, laneDataA, orderA] =
1683 compute2DBlockIOLaneLayout(aTy.getShape(), subgroupSize,
1684 aTy.getElementType().getIntOrFloatBitWidth(),
1685 uArchInstruction->getPackedFormatBitSizeA());
1686 auto [laneLayoutB, laneDataB, orderB] = compute2DBlockIOLaneLayout(
1687 bTy.getShape(), subgroupSize,
1688 bTy.getElementType().getIntOrFloatBitWidth(),
1689 uArchInstruction->getPackedFormatBitSizeB(), /*vnni=*/true);
1690 auto [laneLayoutCD, laneDataCD, orderCD] =
1691 compute2DBlockIOLaneLayout(cdTy.getShape(), subgroupSize,
1692 cdTy.getElementType().getIntOrFloatBitWidth(),
1693 cdTy.getElementType().getIntOrFloatBitWidth());
1694
1695 auto instDataVecs = getDpasInstDataLayouts(aTy, bTy, cdTy, uArchInstruction);
1696 if (!instDataVecs)
1697 return std::nullopt;
1698
1699 if (layoutKind == xegpu::LayoutKind::Subgroup) {
1700 assert(numSg > 0 &&
1701 "Number of subgroups must be provided for sg layout creation.");
1702 return getDpasSubgroupLayouts(context, aTy, bTy, cdTy, consumerLayout,
1703 numSg, *instDataVecs, uArchInstruction);
1704 } else if (layoutKind == xegpu::LayoutKind::InstData) {
1705 auto [instDataA, instDataB, instDataCD] = *instDataVecs;
1706 return std::make_tuple(
1707 buildInstDataLayoutWithLane(context, instDataA, laneLayoutA, laneDataA),
1708 buildInstDataLayoutWithLane(context, instDataB, laneLayoutB, laneDataB),
1709 buildInstDataLayoutWithLane(context, instDataCD, laneLayoutCD,
1710 laneDataCD));
1711 } else if (layoutKind == xegpu::LayoutKind::Lane) {
1712 auto aLayout = buildLaneLayout(context, laneLayoutA, laneDataA);
1713 auto bLayout = buildLaneLayout(context, laneLayoutB, laneDataB);
1714 auto cdLayout = buildLaneLayout(context, laneLayoutCD, laneDataCD);
1715 return std::make_tuple(aLayout, bLayout, cdLayout);
1716 }
1717 return std::nullopt;
1718}
1719
1720/// Helper to create a scale layout derived from a matrix operand layout.
1721/// The scale layout is computed by mapping each dimension of the matrix
1722/// layout to the corresponding scale tensor dimension using the ratio
1723/// between the matrix and scale shapes.
1724static xegpu::DistributeLayoutAttr
1725createScaleLayout(mlir::MLIRContext *context, VectorType matrixTy,
1726 VectorType scaleTy, xegpu::DistributeLayoutAttr matrixLayout,
1727 bool isBScale, const xegpu::uArch::uArch *uArch) {
1728 if (!scaleTy || !matrixLayout)
1729 return nullptr;
1730
1731 // Calculate scaling factor by dividing matrix shape by scale shape
1732 ArrayRef<int64_t> matrixShape = matrixTy.getShape();
1733 ArrayRef<int64_t> scaleShape = scaleTy.getShape();
1734
1735 // Scale shapes can be 1D or 2D, handle both cases
1736 if (scaleShape.empty())
1737 return nullptr;
1738
1739 auto uArchInstruction =
1740 dyn_cast<xegpu::uArch::SubgroupScaledMatrixMultiplyAcc>(
1741 uArch->getInstruction(
1743
1744 int64_t rank = matrixLayout.getRank();
1745 assert(rank >= 2 && "dpas layouts must be at least two dimensions");
1746
1747 SmallVector<int64_t> sgLayout = matrixLayout.getEffectiveSgLayoutAsInt();
1748 SmallVector<int64_t> sgData = matrixLayout.getEffectiveSgDataAsInt();
1749 SmallVector<int64_t> instData = matrixLayout.getEffectiveInstDataAsInt();
1750 SmallVector<int64_t> laneLayout = matrixLayout.getEffectiveLaneLayoutAsInt();
1751 SmallVector<int64_t> laneData = matrixLayout.getEffectiveLaneDataAsInt();
1752 auto order = matrixLayout.getOrder();
1753
1754 SmallVector<int64_t> scaleSgLayout;
1755 SmallVector<int64_t> scaleSgData;
1756 if (!sgLayout.empty() && !sgData.empty()) {
1757 scaleSgLayout.assign(sgLayout.begin(), sgLayout.end());
1758 scaleSgData.assign(sgData.begin(), sgData.end());
1759 scaleSgData[rank - 2] = std::max<int64_t>(
1760 scaleShape[rank - 2] / (matrixShape[rank - 2] / sgData[rank - 2]), 1);
1761 scaleSgData[rank - 1] = std::max<int64_t>(
1762 scaleShape[rank - 1] / (matrixShape[rank - 1] / sgData[rank - 1]), 1);
1763 }
1764
1765 // For DPAS_MX scales: if matrix has inst_data, scale needs adjusted
1766 // inst_data. Scale inst_data is derived from matrix inst_data divided by
1767 // scale factor.
1768 SmallVector<int64_t> scaleInstData;
1769 if (!instData.empty()) {
1770 scaleInstData.assign(instData.begin(), instData.end());
1771 if (isBScale)
1772 scaleInstData[rank - 2] = std::max<int64_t>(
1773 scaleShape[rank - 2] / (matrixShape[rank - 2] / instData[rank - 2]),
1774 1);
1775 else
1776 scaleInstData[rank - 1] = std::max<int64_t>(
1777 scaleShape[rank - 1] / (matrixShape[rank - 1] / instData[rank - 1]),
1778 1);
1779 }
1780
1781 SmallVector<int64_t> scaleLaneLayout;
1782 SmallVector<int64_t> scaleLaneData;
1783 if (!laneLayout.empty() && !laneData.empty()) {
1784 scaleLaneLayout.assign(laneLayout.begin(), laneLayout.end());
1785 scaleLaneData.assign(laneData.size(), 1);
1786
1787 bool isRowMajor = uArchInstruction->isLaneLayoutRowMajorOrder();
1788 if (isBScale ^ isRowMajor)
1789 std::swap(scaleLaneLayout[rank - 2], scaleLaneLayout[rank - 1]);
1790 // Cap lane_layout by the per-instruction tile (inst_data) on each dim.
1791 // Then derive lane_data = inst_data / lane_layout so the Category A
1792 // invariant inst_data = lane_layout * lane_data * k (with k = 1) holds
1793 // for the scale operand's load_nd consumer.
1794 auto layoutCap = scaleInstData.empty() ? scaleShape : scaleInstData;
1795 for (int64_t d = rank - 2; d < rank; ++d)
1796 scaleLaneLayout[d] = std::min<int64_t>(layoutCap[d], scaleLaneLayout[d]);
1797 }
1798 return buildLayout(context, scaleSgLayout, scaleSgData, scaleInstData,
1799 scaleLaneLayout, scaleLaneData, order);
1800}
1801
1802/// Sets up the anchor layouts for dpas_mx operands (A, B, C/D, A_scale, and
1803/// B_scale). The numSg and consumerLayout (optional) are only used by sg
1804/// layout creation.
1805std::optional<
1806 std::tuple<xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr,
1807 xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr,
1808 xegpu::DistributeLayoutAttr>>
1809xegpu::setupDpasMxLayout(xegpu::LayoutKind layoutKind, VectorType aTy,
1810 VectorType bTy, VectorType cdTy, VectorType aScaleTy,
1811 VectorType bScaleTy,
1812 xegpu::DistributeLayoutAttr consumerLayout, int numSg,
1813 const xegpu::uArch::uArch *uArch) {
1814 auto context = aTy.getContext();
1815 const auto *uArchInstruction =
1816 dyn_cast<xegpu::uArch::SubgroupMatrixMultiplyAcc>(uArch->getInstruction(
1818 if (!uArchInstruction)
1819 return std::nullopt;
1820 auto subgroupSize = uArch->getSubgroupSize();
1821
1822 auto [laneLayoutA, laneDataA, orderA] =
1823 compute2DBlockIOLaneLayout(aTy.getShape(), subgroupSize,
1824 aTy.getElementType().getIntOrFloatBitWidth(),
1825 uArchInstruction->getPackedFormatBitSizeA());
1826 auto [laneLayoutB, laneDataB, orderB] = compute2DBlockIOLaneLayout(
1827 bTy.getShape(), subgroupSize,
1828 bTy.getElementType().getIntOrFloatBitWidth(),
1829 uArchInstruction->getPackedFormatBitSizeB(), /*vnni=*/true);
1830 auto [laneLayoutCD, laneDataCD, orderCD] =
1831 compute2DBlockIOLaneLayout(cdTy.getShape(), subgroupSize,
1832 cdTy.getElementType().getIntOrFloatBitWidth(),
1833 cdTy.getElementType().getIntOrFloatBitWidth());
1834 auto instDataVecs = getDpasInstDataLayouts(aTy, bTy, cdTy, uArchInstruction);
1835 if (!instDataVecs)
1836 return std::nullopt;
1837
1838 if (layoutKind == xegpu::LayoutKind::Subgroup) {
1839 assert(numSg > 0 &&
1840 "Number of subgroups must be provided for sg layout creation.");
1841 auto dpasLayouts =
1842 getDpasSubgroupLayouts(context, aTy, bTy, cdTy, consumerLayout, numSg,
1843 *instDataVecs, uArchInstruction);
1844 if (!dpasLayouts)
1845 return std::nullopt;
1846
1847 auto [dpasALayout, dpasBLayout, dpasCDLayout] = *dpasLayouts;
1848
1849 // Create scale layouts
1850 auto aScaleLayout =
1851 createScaleLayout(context, aTy, aScaleTy, dpasALayout, false, uArch);
1852
1853 auto bScaleLayout =
1854 createScaleLayout(context, bTy, bScaleTy, dpasBLayout, true, uArch);
1855
1856 return std::make_tuple(dpasALayout, dpasBLayout, dpasCDLayout, aScaleLayout,
1857 bScaleLayout);
1858 } else if (layoutKind == xegpu::LayoutKind::InstData) {
1859
1860 auto [instDataA, instDataB, instDataCD] = *instDataVecs;
1861
1862 auto dpasALayout =
1863 buildInstDataLayoutWithLane(context, instDataA, laneLayoutA, laneDataA);
1864 auto dpasBLayout =
1865 buildInstDataLayoutWithLane(context, instDataB, laneLayoutB, laneDataB);
1866 auto dpasCDLayout = buildInstDataLayoutWithLane(context, instDataCD,
1867 laneLayoutCD, laneDataCD);
1868
1869 auto aScaleLayout =
1870 createScaleLayout(context, aTy, aScaleTy, dpasALayout, false, uArch);
1871 auto bScaleLayout =
1872 createScaleLayout(context, bTy, bScaleTy, dpasBLayout, true, uArch);
1873
1874 return std::make_tuple(dpasALayout, dpasBLayout, dpasCDLayout, aScaleLayout,
1875 bScaleLayout);
1876 } else if (layoutKind == xegpu::LayoutKind::Lane) {
1877 auto dpasALayout = buildLaneLayout(context, laneLayoutA, laneDataA);
1878 auto dpasBLayout = buildLaneLayout(context, laneLayoutB, laneDataB);
1879 auto dpasCDLayout = buildLaneLayout(context, laneLayoutCD, laneDataCD);
1880
1881 auto aScaleLayout =
1882 createScaleLayout(context, aTy, aScaleTy, dpasALayout, false, uArch);
1883 auto bScaleLayout =
1884 createScaleLayout(context, bTy, bScaleTy, dpasBLayout, true, uArch);
1885
1886 return std::make_tuple(dpasALayout, dpasBLayout, dpasCDLayout, aScaleLayout,
1887 bScaleLayout);
1888 }
1889 return std::nullopt;
1890}
1891
1892/// Select a default 2D block IO layout without transpose or transform.
1893/// `numSg` is needed only in Subgroup mode.
1894static xegpu::DistributeLayoutAttr setupDefault2DBlockIOLayout(
1895 xegpu::LayoutKind layoutKind, ArrayRef<int64_t> dataShape, Type elemTy,
1896 int numSg,
1897 const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction,
1898 const xegpu::uArch::uArch *uArch) {
1899 auto context = elemTy.getContext();
1900 auto subgroupSize = uArch->getSubgroupSize();
1901 assert(dataShape.size() >= 2 && "Expected at least 2D shape for ND op");
1902
1903 // Compute the default 2D block IO lane layout / lane data.
1904 unsigned bitwidth = elemTy.getIntOrFloatBitWidth();
1905 auto [laneLayout, laneData, order] =
1906 compute2DBlockIOLaneLayout(dataShape, subgroupSize, bitwidth,
1907 uArchInstruction->getPackedFormatBitSize());
1908
1909 if (layoutKind == xegpu::LayoutKind::Lane)
1910 return buildLaneLayout(context, laneLayout, laneData);
1911
1912 auto instData =
1913 get2DBlockIOInstDataLayout(dataShape, elemTy, uArchInstruction);
1914 // Shape not realizable as a 2D-block instruction; let the caller report it.
1915 if (!instData)
1916 return nullptr;
1917
1918 if (layoutKind == xegpu::LayoutKind::InstData) {
1919 assert(isValidLaneLayout(*instData, laneLayout, laneData) &&
1920 "Expected the block IO layout to satisfy uArch block constraints");
1921 return buildInstDataLayoutWithLane(context, *instData, laneLayout,
1922 laneData);
1923 }
1924
1925 if (layoutKind == xegpu::LayoutKind::Subgroup) {
1926 assert(numSg > 0 &&
1927 "Number of subgroups must be provided for sg layout creation.");
1928 return get2DBlockIOSubgroupLayout(context, dataShape, elemTy,
1929 uArchInstruction, numSg);
1930 }
1931
1932 return nullptr;
1933}
1934
1935/// Sets up the anchor layout for a store_nd operation. StoreNd picks its
1936/// own layout based on uArch block parameters (it does not take a consumer
1937/// layout, since it is a data sink).
1938xegpu::DistributeLayoutAttr
1940 VectorType srcVecTy, int numSg,
1941 const xegpu::uArch::uArch *uArch) {
1942 const auto *uArchInstruction =
1943 dyn_cast<xegpu::uArch::Subgroup2DBlockStoreInstruction>(
1944 uArch->getInstruction(
1946 if (!uArchInstruction)
1947 return nullptr;
1948 return setupDefault2DBlockIOLayout(layoutKind, srcVecTy.getShape(),
1949 srcVecTy.getElementType(), numSg,
1950 uArchInstruction, uArch);
1951}
1952
1953/// Sets up the anchor layout for a prefetch_nd operation. PrefetchNd has no
1954/// consumer (it produces no value), so it picks its own layout from uArch
1955/// block parameters.
1956xegpu::DistributeLayoutAttr
1958 xegpu::TensorDescType tdescTy, int numSg,
1959 const xegpu::uArch::uArch *uArch) {
1960 const auto *uArchInstruction =
1961 dyn_cast<xegpu::uArch::Subgroup2DBlockPrefetchInstruction>(
1962 uArch->getInstruction(
1964 if (!uArchInstruction)
1965 return nullptr;
1966 return setupDefault2DBlockIOLayout(layoutKind, tdescTy.getShape(),
1967 tdescTy.getElementType(), numSg,
1968 uArchInstruction, uArch);
1969}
1970
1971/// Sets up the anchor layout for a load_nd operation. LoadNd takes a
1972/// consumer layout (from its result's downstream uses) and validates it
1973/// against uArch constraints; if valid, the consumer's `inst_data` /
1974/// `sg_layout` are honored. Otherwise the helper falls back to defaults
1975/// derived from uArch block parameters.
1976xegpu::DistributeLayoutAttr
1978 VectorType resVecTy,
1979 xegpu::DistributeLayoutAttr consumerLayout,
1980 int numSg, const xegpu::uArch::uArch *uArch) {
1981
1982 // Loads without a requested layout use the default block IO layout.
1983 if (!consumerLayout) {
1984 const auto *uArchInstruction =
1985 dyn_cast<xegpu::uArch::Subgroup2DBlockLoadInstruction>(
1986 uArch->getInstruction(
1988 if (!uArchInstruction)
1989 return nullptr;
1990 return setupDefault2DBlockIOLayout(layoutKind, resVecTy.getShape(),
1991 resVecTy.getElementType(), numSg,
1992 uArchInstruction, uArch);
1993 }
1994 if (layoutKind == xegpu::LayoutKind::Subgroup) {
1995 assert(consumerLayout.isForWorkgroup() &&
1996 "Expected consumer layout to be a complete workgroup-level layout");
1997 return consumerLayout;
1998 }
1999
2000 auto context = resVecTy.getContext();
2001 Type elemTy = resVecTy.getElementType();
2002 auto subgroupSize = uArch->getSubgroupSize();
2003 auto dataShape = resVecTy.getShape();
2004 const auto *uArchInstruction =
2005 dyn_cast<xegpu::uArch::Subgroup2DBlockLoadInstruction>(
2006 uArch->getInstruction(
2008 if (!uArchInstruction)
2009 return nullptr;
2010
2011 int rank = resVecTy.getRank();
2012 SmallVector<int64_t> consumerInstData =
2013 consumerLayout.getEffectiveInstDataAsInt();
2014 SmallVector<int64_t> consumerLaneLayout =
2015 consumerLayout.getEffectiveLaneLayoutAsInt();
2016 SmallVector<int64_t> consumerLaneData =
2017 consumerLayout.getEffectiveLaneDataAsInt();
2018
2019 assert(!consumerLaneLayout.empty() && !consumerLaneData.empty() &&
2020 "Expected consumer layout to have lane_layout and lane_data");
2021
2022 // vertical lane layout means that the blockload must be transposed
2023 // note scaleA on PVC has vertical lane layout even without transposed order
2024 // attr
2025 bool hasTranspose =
2026 consumerLaneLayout[rank - 2] > 1 && consumerLaneLayout[rank - 1] == 1;
2027 // VNNI exists only below 32 bits.
2028 bool canTransform =
2029 elemTy.isIntOrFloat() &&
2031 bool hasTransform = !hasTranspose && canTransform &&
2032 consumerLaneData[rank - 2] > 1 &&
2033 consumerLaneData[rank - 1] == 1;
2034 assert((consumerLaneData[rank - 2] == 1 || consumerLaneData[rank - 1] == 1) &&
2035 "Expected consumer lane data to have at most one non-unit dim");
2036
2037 if (layoutKind == xegpu::LayoutKind::InstData) {
2038 auto blockWHC = uArchInstruction->getBlockWidthHeightCount(
2039 elemTy, hasTransform, hasTranspose,
2040 /*upConv=*/false);
2041 if (!blockWHC)
2042 return nullptr;
2043 auto [bWidths, bHeights, bCounts] = blockWHC.value();
2044
2045 // lane_layout and lane_data are the block load's own, not the consumer's: a
2046 // consumer may ask for more elements per lane than the hardware can pack,
2047 // e.g. an f32 multi_reduction wanting 16.
2048 unsigned packingSize = hasTransform || hasTranspose
2050 : uArchInstruction->getPackedFormatBitSize();
2051 auto [laneLayout, laneData, order] = compute2DBlockIOLaneLayout(
2052 dataShape, subgroupSize, elemTy.getIntOrFloatBitWidth(), packingSize,
2053 hasTransform, hasTranspose);
2054 DenseI32ArrayAttr orderAttr =
2055 order.empty()
2056 ? nullptr
2058 context, SmallVector<int32_t>(order.begin(), order.end()));
2059
2060 // See whether the consumer's inst_data satisfies the block constraints.
2061 int64_t height = consumerInstData[rank - 2];
2062 int64_t width = consumerInstData[rank - 1];
2063 auto maxBlockCount = *llvm::max_element(bCounts);
2064 auto maxWidth = *llvm::max_element(bWidths);
2065 if (llvm::is_contained(bWidths, static_cast<int>(width)) ||
2066 (width % maxWidth == 0 && width / maxWidth < maxBlockCount)) {
2067 if (llvm::is_contained(bHeights, static_cast<int>(height))) {
2068 assert(isValidLaneLayout(consumerInstData, laneLayout, laneData) &&
2069 "Expected the load layout to satisfy uArch block constraints");
2070 return buildInstDataLayoutWithLane(context, consumerInstData,
2071 laneLayout, laneData, orderAttr);
2072 }
2073 }
2074
2075 // The consumer's inst_data is not a usable block, so take the uArch's.
2076 // DPAS_MX scales land here. A scale whose innermost dim is too narrow to
2077 // spread packed lanes over (width 16 for an 8-bit scale needing 16 lanes of
2078 // 2 elements) cannot be loaded regularly; transformed, it packs down the
2079 // column instead. A vertical lane_layout is already transposed.
2080 // Only switch if a transformed load is possible (checking via a call
2081 // to 'get2DBlockIOInstDataLayout') otherwise keep the regularone and leave
2082 // the conflict to a convert_layout.
2083 if (!hasTranspose && !hasTransform &&
2084 consumerInstData[rank - 1] %
2085 (laneLayout[rank - 1] * laneData[rank - 1]) !=
2086 0 &&
2087 get2DBlockIOInstDataLayout(dataShape, elemTy, uArchInstruction,
2088 /*transform=*/true,
2089 /*transpose=*/false)) {
2090 hasTransform = true;
2091 std::tie(laneLayout, laneData, order) = compute2DBlockIOLaneLayout(
2092 dataShape, subgroupSize, elemTy.getIntOrFloatBitWidth(),
2093 uArch->getGeneralPackedFormatBitSize(), hasTransform, hasTranspose);
2094 }
2095
2096 auto instData = get2DBlockIOInstDataLayout(
2097 dataShape, elemTy, uArchInstruction, hasTransform, hasTranspose);
2098 // Shape not realizable as a 2D-block instruction; let the caller report it.
2099 if (!instData)
2100 return nullptr;
2101 assert(isValidLaneLayout(*instData, laneLayout, laneData) &&
2102 "Expected the load layout to satisfy uArch block constraints");
2103 return buildInstDataLayoutWithLane(context, *instData, laneLayout, laneData,
2104 orderAttr);
2105 }
2106 if (layoutKind == xegpu::LayoutKind::Lane) {
2107 assert(isValidLaneLayout(dataShape, consumerLaneLayout, consumerLaneData) &&
2108 "Expected the lane layout to satisfy uArch block constraints");
2109 return consumerLayout;
2110 }
2111 return nullptr;
2112}
2113
2114/// Select the most balanced `numSg` factorization of `wgShape` whose sg_data
2115/// is a multiple of `instData`.
2116static xegpu::DistributeLayoutAttr
2118 ArrayRef<int64_t> wgShape,
2119 ArrayRef<int64_t> instData, int numSg) {
2120 auto candidates = getSgLayoutCandidates(wgShape, instData, numSg);
2121 if (candidates.empty())
2122 return nullptr;
2123 // Candidates are ordered most-balanced first.
2124 return buildSgLayout(context, wgShape, candidates.front(), /*dimK=*/-1);
2125}
2126
2127/// Select a default scatter IO layout with at most `maxChunkSize` elements
2128/// per lane. Instruction data is lane_layout * lane_data.
2129static xegpu::DistributeLayoutAttr setupDefaultScatterIOLayout(
2130 xegpu::LayoutKind layoutKind, mlir::MLIRContext *context, int maxChunkSize,
2131 ArrayRef<int64_t> srcShape, int subgroupSize, int numSg) {
2132
2133 auto [laneLayout, laneData] =
2134 computeScatterIOLaneLayoutAndData(srcShape, subgroupSize, maxChunkSize);
2135
2136 SmallVector<int64_t> instData(srcShape.size());
2137 for (size_t i = 0; i < srcShape.size(); ++i)
2138 instData[i] = laneLayout[i] * laneData[i];
2139
2140 if (layoutKind == xegpu::LayoutKind::Subgroup) {
2141 assert(numSg > 0 &&
2142 "Number of subgroups must be provided for sg layout creation.");
2143 return getDefaultScatterIOSubgroupLayout(context, srcShape, instData,
2144 numSg);
2145 }
2146 if (layoutKind == xegpu::LayoutKind::InstData) {
2147 return buildInstDataLayoutWithLane(context, instData, laneLayout, laneData);
2148 }
2149 if (layoutKind == xegpu::LayoutKind::Lane) {
2150 return buildLaneLayout(context, laneLayout, laneData);
2151 }
2152 return nullptr;
2153}
2154
2155/// Select a layout for load_gather or load_matrix. Reuse requested subgroup
2156/// layouts; otherwise keep the consumer's lane_layout, restrict lane_data to a
2157/// bounded innermost chunk, and in InstData mode set inst_data to
2158/// lane_layout * lane_data.
2159/// Without a requested layout, use the default scatter IO layout.
2160static xegpu::DistributeLayoutAttr setupGenericLoadAnchorLayout(
2161 xegpu::LayoutKind layoutKind, mlir::MLIRContext *context,
2162 xegpu::DistributeLayoutAttr consumerLayout, int maxChunkSize,
2163 ArrayRef<int64_t> resShape, int subgroupSize, int numSg) {
2164
2165 if (!consumerLayout)
2166 return setupDefaultScatterIOLayout(layoutKind, context, maxChunkSize,
2167 resShape, subgroupSize, numSg);
2168 if (layoutKind == xegpu::LayoutKind::Subgroup)
2169 return consumerLayout;
2170
2171 SmallVector<int64_t> consumerInstData =
2172 consumerLayout.getEffectiveInstDataAsInt();
2173 SmallVector<int64_t> consumerLaneLayout =
2174 consumerLayout.getEffectiveLaneLayoutAsInt();
2175 SmallVector<int64_t> consumerLaneData =
2176 consumerLayout.getEffectiveLaneDataAsInt();
2177
2178 assert(!consumerLaneLayout.empty() && !consumerLaneData.empty() &&
2179 "Expected consumer layout to have lane_layout and lane_data");
2180 SmallVector<int64_t> laneLayout(consumerLaneLayout);
2181
2182 // A matrix/gather load reads one contiguous span per lane, so a lane can pack
2183 // only along the innermost dim, and only up to maxChunkSize.
2184 SmallVector<int64_t> laneData(consumerLaneData.size(), 1);
2185 laneData.back() =
2186 std::min(consumerLaneData.back(), static_cast<int64_t>(maxChunkSize));
2187
2188 if (layoutKind == xegpu::LayoutKind::InstData) {
2189 SmallVector<int64_t> instData;
2190 instData.resize(resShape.size());
2191 for (size_t i = 0; i < resShape.size(); ++i)
2192 instData[i] = laneLayout[i] * laneData[i];
2193 return buildInstDataLayoutWithLane(context, instData, laneLayout, laneData);
2194 }
2195 if (layoutKind == xegpu::LayoutKind::Lane)
2196 return buildLaneLayout(context, laneLayout, laneData);
2197 return nullptr;
2198}
2199
2200/// Sets up the anchor layout for a load gather operation.
2201xegpu::DistributeLayoutAttr
2203 VectorType resVecTy, int contigChunkSize,
2204 xegpu::DistributeLayoutAttr consumerLayout,
2205 int numSg, const uArch::uArch *uArch) {
2206
2207 const int subgroupSize = uArch->getSubgroupSize();
2208 ArrayRef<int64_t> resShape = resVecTy.getShape();
2209 auto context = resVecTy.getContext();
2210
2211 // The per-lane chunk is bounded by what the offsets prove contiguous
2212 // (`contigChunkSize`) and by what one lane can access in one instruction.
2213 const auto *uArchInstruction = dyn_cast<xegpu::uArch::LoadGatherInstruction>(
2214 uArch->getInstruction(xegpu::uArch::InstructionKind::LoadGather));
2215 int maxChunkSize =
2216 std::min(uArchInstruction->getMaxLaneAccessSizeBytes(), contigChunkSize);
2217
2218 return setupGenericLoadAnchorLayout(layoutKind, context, consumerLayout,
2219 maxChunkSize, resShape, subgroupSize,
2220 numSg);
2221}
2222
2223/// Sets up the anchor layout for load matrix operation.
2224/// TODO: enhance load matrix to indicate lowering to chunked load or not.
2225xegpu::DistributeLayoutAttr xegpu::setupLoadMatrixAnchorLayout(
2226 xegpu::LayoutKind layoutKind, VectorType resVecTy, int contigChunkSize,
2227 xegpu::DistributeLayoutAttr consumerLayout, int numSg,
2228 const xegpu::uArch::uArch *uArch) {
2229
2230 const int subgroupSize = uArch->getSubgroupSize();
2231 ArrayRef<int64_t> resShape = resVecTy.getShape();
2232 auto context = resVecTy.getContext();
2233
2234 const auto *uArchInstruction = dyn_cast<xegpu::uArch::LoadGatherInstruction>(
2236 int maxChunkSize =
2237 std::min(uArchInstruction->getMaxLaneAccessSizeBytes(), contigChunkSize);
2238 return setupGenericLoadAnchorLayout(layoutKind, context, consumerLayout,
2239 maxChunkSize, resShape, subgroupSize,
2240 numSg);
2241}
2242
2243/// Sets up the anchor layout for a store scatter operation.
2244xegpu::DistributeLayoutAttr
2246 VectorType srcVecTy, int contigChunkSize,
2247 int numSg, const uArch::uArch *uArch) {
2248
2249 const int subgroupSize = uArch->getSubgroupSize();
2250 ArrayRef<int64_t> srcShape = srcVecTy.getShape();
2251 auto context = srcVecTy.getContext();
2252
2253 // The per-lane chunk is bounded by what the offsets prove contiguous
2254 // (`contigChunkSize`) and by what one lane can access in one instruction.
2255 const auto *uArchInstruction =
2256 dyn_cast<xegpu::uArch::StoreScatterInstruction>(
2258 int maxChunkSize =
2259 std::min(uArchInstruction->getMaxLaneAccessSizeBytes(), contigChunkSize);
2260 return setupDefaultScatterIOLayout(layoutKind, context, maxChunkSize,
2261 srcShape, subgroupSize, numSg);
2262}
2263
2264/// Sets up the anchor layout for a store matrix operation.
2265xegpu::DistributeLayoutAttr xegpu::setupStoreMatrixAnchorLayout(
2266 xegpu::LayoutKind layoutKind, VectorType srcVecTy, int contigChunkSize,
2267 int numSg, const xegpu::uArch::uArch *uArch) {
2268
2269 const int subgroupSize = uArch->getSubgroupSize();
2270 ArrayRef<int64_t> srcShape = srcVecTy.getShape();
2271 auto context = srcVecTy.getContext();
2272
2273 const auto *uArchInstruction =
2274 dyn_cast<xegpu::uArch::StoreScatterInstruction>(
2276 int maxChunkSize =
2277 std::min(uArchInstruction->getMaxLaneAccessSizeBytes(), contigChunkSize);
2278
2279 return setupDefaultScatterIOLayout(layoutKind, context, maxChunkSize,
2280 srcShape, subgroupSize, numSg);
2281}
2282
2283/// Completes a scatter IO layout by deriving lane_layout and lane_data from
2284/// `specifiedLayout`'s inst_data when they are missing. The layout is returned
2285/// unchanged if `specifiedLayout` is null, carries no inst_data, or already has
2286/// both lane_layout and lane_data.
2287///
2288/// When lane info is absent, inst_data is treated as the effective shape and
2289/// the lane factorization is filled in as follows:
2290/// - If `consumerLayout` is present and its lane_layout / lane_data are a
2291/// valid factorization of inst_data, that consumer lane info is reused so
2292/// the completed layout matches the consumer (avoiding a relayout).
2293/// - Otherwise a standard scatter-style factorization is computed via
2294/// `computeScatterIOLaneLayoutAndData`, bounded by `maxChunkSize` — the
2295/// per-lane load width reported by the uArch's LoadGather instruction
2296/// (`getMaxLaneAccessSizeBytes`).
2297///
2298std::optional<xegpu::DistributeLayoutAttr>
2300 xegpu::DistributeLayoutAttr specifiedLayout,
2301 xegpu::DistributeLayoutAttr consumerLayout, Type elemTy,
2302 const xegpu::uArch::LoadGatherInstruction *uArchInstruction,
2303 const int subgroupSize) {
2304 if (!specifiedLayout)
2305 return specifiedLayout;
2306 SmallVector<int64_t> specifiedInstData =
2307 specifiedLayout.getEffectiveInstDataAsInt();
2308 if (specifiedInstData.empty())
2309 return specifiedLayout;
2310 if (!specifiedLayout.getEffectiveLaneLayoutAsInt().empty() &&
2311 !specifiedLayout.getEffectiveLaneDataAsInt().empty())
2312 return specifiedLayout;
2313
2314 // Reuse the load-side setup with inst_data as the destination shape.
2315 auto *context = specifiedLayout.getContext();
2316 int maxChunkSize = uArchInstruction->getMaxLaneAccessSizeBytes();
2317 if (consumerLayout) {
2318 auto consumerLaneLayout = consumerLayout.getEffectiveLaneLayoutAsInt();
2319 auto consumerLaneData = consumerLayout.getEffectiveLaneDataAsInt();
2320 if (!consumerLaneLayout.empty() && !consumerLaneData.empty() &&
2321 isValidLaneLayout(specifiedInstData, consumerLaneLayout,
2322 consumerLaneData))
2323 return buildInstDataLayoutWithLane(context, specifiedInstData,
2324 consumerLaneLayout, consumerLaneData);
2325 }
2326 auto [defLaneLayout, defLaneData] = computeScatterIOLaneLayoutAndData(
2327 specifiedInstData, subgroupSize, maxChunkSize);
2328 if (!isValidLaneLayout(specifiedInstData, defLaneLayout, defLaneData))
2329 return std::nullopt;
2330 return buildInstDataLayoutWithLane(context, specifiedInstData, defLaneLayout,
2331 defLaneData);
2332}
2333
2334/// Like completeScatterLoadLaneLayoutFromInstData, but for scatter stores. A
2335/// store is a data sink, so lane info is derived purely from inst_data (bounded
2336/// by the uArch's per-lane store width); there is no consumer layout to reuse.
2337std::optional<xegpu::DistributeLayoutAttr>
2339 xegpu::DistributeLayoutAttr specifiedLayout, Type elemTy,
2340 const xegpu::uArch::StoreScatterInstruction *uArchInstruction,
2341 const int subgroupSize) {
2342 if (!specifiedLayout)
2343 return specifiedLayout;
2344 SmallVector<int64_t> specifiedInstData =
2345 specifiedLayout.getEffectiveInstDataAsInt();
2346 if (specifiedInstData.empty())
2347 return specifiedLayout;
2348 if (!specifiedLayout.getEffectiveLaneLayoutAsInt().empty() &&
2349 !specifiedLayout.getEffectiveLaneDataAsInt().empty())
2350 return specifiedLayout;
2351
2352 // Reuse the store-side setup with inst_data as the source shape.
2353 auto *context = specifiedLayout.getContext();
2354 int maxChunkSize = uArchInstruction->getMaxLaneAccessSizeBytes();
2355 auto [defLaneLayout, defLaneData] = computeScatterIOLaneLayoutAndData(
2356 specifiedInstData, subgroupSize, maxChunkSize);
2357 if (!isValidLaneLayout(specifiedInstData, defLaneLayout, defLaneData))
2358 return std::nullopt;
2359 return buildInstDataLayoutWithLane(context, specifiedInstData, defLaneLayout,
2360 defLaneData);
2361}
2362
2363/// Completes a 2D-block store/prefetch layout from its inst_data. store_nd and
2364/// prefetch_nd are data sinks, so lane info is derived purely from inst_data
2365/// (no consumer to reuse). One helper serves both via
2366/// BlockIOInstructionInterface.
2367std::optional<xegpu::DistributeLayoutAttr>
2369 xegpu::DistributeLayoutAttr specifiedLayout, Type elemTy,
2370 const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction,
2371 const int subgroupSize) {
2372 if (!specifiedLayout)
2373 return specifiedLayout;
2374 SmallVector<int64_t> specifiedInstData =
2375 specifiedLayout.getEffectiveInstDataAsInt();
2376 if (specifiedInstData.empty())
2377 return specifiedLayout;
2378 if (!specifiedLayout.getEffectiveLaneLayoutAsInt().empty() &&
2379 !specifiedLayout.getEffectiveLaneDataAsInt().empty())
2380 return specifiedLayout;
2381
2382 auto *context = specifiedLayout.getContext();
2383 auto [laneLayout, laneData, order] = compute2DBlockIOLaneLayout(
2384 specifiedInstData, subgroupSize, elemTy.getIntOrFloatBitWidth(),
2385 uArchInstruction->getPackedFormatBitSize());
2386 if (!isValidLaneLayout(specifiedInstData, laneLayout, laneData))
2387 return std::nullopt;
2388 return buildInstDataLayoutWithLane(context, specifiedInstData, laneLayout,
2389 laneData);
2390}
2391
2392/// Like completeBlockStoreLaneLayoutFromInstData, but for load_nd. The
2393/// consumer's lane_data and order are reused as-is; lane_layout is rebuilt from
2394/// the consumer's lane_layout, bumping every non-unit dim up to the subgroup
2395/// size. The user-provided inst_data is preserved.
2396std::optional<xegpu::DistributeLayoutAttr>
2398 xegpu::DistributeLayoutAttr specifiedLayout,
2399 xegpu::DistributeLayoutAttr consumerLayout, Type elemTy,
2400 const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction,
2401 const int subgroupSize) {
2402 if (!specifiedLayout)
2403 return specifiedLayout;
2404 SmallVector<int64_t> specifiedInstData =
2405 specifiedLayout.getEffectiveInstDataAsInt();
2406 if (specifiedInstData.empty())
2407 return specifiedLayout;
2408 if (!specifiedLayout.getEffectiveLaneLayoutAsInt().empty() &&
2409 !specifiedLayout.getEffectiveLaneDataAsInt().empty())
2410 return specifiedLayout;
2411 if (!consumerLayout)
2412 return specifiedLayout;
2413 SmallVector<int64_t> consumerLaneLayout =
2414 consumerLayout.getEffectiveLaneLayoutAsInt();
2415 SmallVector<int64_t> consumerLaneData =
2416 consumerLayout.getEffectiveLaneDataAsInt();
2417 if (consumerLaneLayout.empty() || consumerLaneData.empty())
2418 return specifiedLayout;
2419
2420 auto *context = specifiedLayout.getContext();
2421 int rank = specifiedInstData.size();
2422
2423 SmallVector<int64_t> laneLayout;
2424 // set the laneLayout to use consumer's LaneLayout as base, but adjust its
2425 // size to match the subgroupsize in case its original value is larger than 1
2426 for (int i = 0; i < rank; i++) {
2427 if (consumerLaneLayout[i] > 1) {
2428 laneLayout.push_back(
2429 std::max(static_cast<int64_t>(subgroupSize), consumerLaneLayout[i]));
2430 } else {
2431 laneLayout.push_back(1);
2432 }
2433 }
2434
2435 if (!isValidLaneLayout(specifiedInstData, laneLayout, consumerLaneData))
2436 return std::nullopt;
2437 return buildInstDataLayoutWithLane(context, specifiedInstData, laneLayout,
2438 consumerLaneData,
2439 consumerLayout.getOrder());
2440}
2441
2442/// Completes user-provided DPAS A/B/C-D anchors that carry only inst_data by
2443/// filling in lane_layout / lane_data. The lane factorization mirrors the
2444/// InstData branch of `setupDpasLayout` (derived from each operand's shape and
2445/// matmul role, B using VNNI packing); the user's inst_data is preserved.
2446std::optional<
2447 std::tuple<xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr,
2448 xegpu::DistributeLayoutAttr>>
2449xegpu::completeDpasLaneLayoutFromInstData(xegpu::DistributeLayoutAttr aLayout,
2450 xegpu::DistributeLayoutAttr bLayout,
2451 xegpu::DistributeLayoutAttr cdLayout,
2452 VectorType aTy, VectorType bTy,
2453 VectorType cdTy,
2454 const xegpu::uArch::uArch *uArch) {
2455 auto context = aTy.getContext();
2456 const auto *uArchInstruction =
2457 dyn_cast<xegpu::uArch::SubgroupMatrixMultiplyAcc>(uArch->getInstruction(
2459 if (!uArchInstruction)
2460 return std::nullopt;
2461 auto subgroupSize = uArch->getSubgroupSize();
2462 llvm::SmallVector<int64_t> laneLayoutA, laneDataA, laneLayoutB, laneDataB,
2463 laneLayoutCD, laneDataCD;
2464 // DPAS operands are never transposed, so the order comes back empty.
2465 llvm::SmallVector<int64_t> orderA, orderB, orderCD;
2466 SmallVector<int64_t> instDataA = aLayout.getEffectiveInstDataAsInt();
2467 SmallVector<int64_t> instDataB = bLayout.getEffectiveInstDataAsInt();
2468 SmallVector<int64_t> instDataCD = cdLayout.getEffectiveInstDataAsInt();
2469
2470 if (isa<xegpu::uArch::Xe2, xegpu::uArch::Xe3p>(uArch)) {
2471 std::tie(laneLayoutA, laneDataA, orderA) =
2472 compute2DBlockIOLaneLayout(aTy.getShape(), subgroupSize,
2473 aTy.getElementType().getIntOrFloatBitWidth(),
2474 uArchInstruction->getPackedFormatBitSizeA());
2475 std::tie(laneLayoutB, laneDataB, orderB) = compute2DBlockIOLaneLayout(
2476 bTy.getShape(), subgroupSize,
2477 bTy.getElementType().getIntOrFloatBitWidth(),
2478 uArchInstruction->getPackedFormatBitSizeB(), /*vnni=*/true);
2479 std::tie(laneLayoutCD, laneDataCD, orderCD) = compute2DBlockIOLaneLayout(
2480 cdTy.getShape(), subgroupSize,
2481 cdTy.getElementType().getIntOrFloatBitWidth(),
2482 cdTy.getElementType().getIntOrFloatBitWidth());
2483 } else {
2484 assert(false && "Unsupported uArch for DPAS lane layout completion");
2485 }
2486
2487 if (!isValidLaneLayout(instDataA, laneLayoutA, laneDataA) ||
2488 !isValidLaneLayout(instDataB, laneLayoutB, laneDataB) ||
2489 !isValidLaneLayout(instDataCD, laneLayoutCD, laneDataCD))
2490 return std::nullopt;
2491 return std::make_tuple(
2492 buildInstDataLayoutWithLane(context, instDataA, laneLayoutA, laneDataA,
2493 aLayout.getOrder()),
2494 buildInstDataLayoutWithLane(context, instDataB, laneLayoutB, laneDataB,
2495 bLayout.getOrder()),
2496 buildInstDataLayoutWithLane(context, instDataCD, laneLayoutCD, laneDataCD,
2497 cdLayout.getOrder()));
2498}
2499
2500/// Like completeDpasLaneLayoutFromInstData, but for dpas_mx: also re-derives
2501/// the A_scale / B_scale layouts from the completed A / B layouts via
2502/// `createScaleLayout`, matching the default path of `setupDpasMxLayout`.
2503std::optional<
2504 std::tuple<xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr,
2505 xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr,
2506 xegpu::DistributeLayoutAttr>>
2508 xegpu::DistributeLayoutAttr aLayout, xegpu::DistributeLayoutAttr bLayout,
2509 xegpu::DistributeLayoutAttr cdLayout, VectorType aTy, VectorType bTy,
2510 VectorType cdTy, VectorType aScaleTy, VectorType bScaleTy,
2511 const xegpu::uArch::uArch *uArch) {
2512 auto completed = completeDpasLaneLayoutFromInstData(
2513 aLayout, bLayout, cdLayout, aTy, bTy, cdTy, uArch);
2514 if (!completed)
2515 return std::nullopt;
2516 auto context = aTy.getContext();
2517 auto [completedA, completedB, completedCD] = *completed;
2518
2519 auto aScaleLayout =
2520 createScaleLayout(context, aTy, aScaleTy, completedA, false, uArch);
2521 auto bScaleLayout =
2522 createScaleLayout(context, bTy, bScaleTy, completedB, true, uArch);
2523
2524 return std::make_tuple(completedA, completedB, completedCD, aScaleLayout,
2525 bScaleLayout);
2526}
2527
2528/// Sets up layout for reduction operations by creating a SliceAttr for the
2529/// result.
2530///
2531/// Algorithm Overview:
2532/// This function attempts to construct a source layout that, when sliced along
2533/// reduction dimensions, produces a result layout compatible with the
2534/// consumer layout.
2535///
2536/// For subgroup layouts, it first tries to align the source layout's subgroup
2537/// layout and data with the consumer's layout on non-reduction dimensions.
2538/// Then, it distributes remaining subgroups across reduction dimensions. When
2539/// the consumer slices exactly `reductionDims`, it reuses the slice's parent
2540/// for the source and adjusts sg_data on the reduction dimensions to fit the
2541/// source extent. This is a best-effort alignment: the goal is to pick a source
2542/// layout that minimizes redistribution against the consumer layout.
2543///
2544/// If the resulting source layout still differs from what some consumer
2545/// expects (e.g. a second, inconsistent consumer), that mismatch is reconciled
2546/// later by layout conflict resolution (`ResolveLayoutConflicts`), which
2547/// inserts a `convert_layout` op.
2548///
2549/// InstData kind: `computeReductionLaneLayoutAndData` derives lane_layout,
2550/// lane_data, and inst_data. It can preserve a reused parent's larger inst_data
2551/// on non-reduced dimensions.
2552///
2553/// Lane kind: a consumer sliced over exactly `reductionDims` is reused.
2554/// This preserves the lane layout chosen during instruction-data propagation.
2555/// For other consumer layouts, `computeReductionLaneLayoutAndData` derives
2556/// lane_layout and lane_data. See that helper for inst_data and lane layout
2557/// examples.
2558///
2559/// The function returns the *result* layout (the SliceAttr). The *source*
2560/// layout it decides on is the parent of that slice. The subgroup examples
2561/// below show both layouts.
2562///
2563/// Subgroup layout examples:
2564/// 1. Row reduction on a 2D tensor:
2565/// srcShape=[32, 128], reductionDims=[1], resShape=[32], subgroupSize=16,
2566/// numSg=32
2567/// * Consumer Layout:
2568/// #xegpu.slice<#xegpu.layout<sg_layout=[4, 8], sg_data=[8, 8]>, dims =
2569/// [1]>
2570/// * Source Layout (decided by this function):
2571/// #xegpu.layout<sg_layout=[4, 8], sg_data=[8, 16]>
2572/// * Result Layout (returned):
2573/// #xegpu.slice<#xegpu.layout<sg_layout=[4, 8], sg_data=[8, 16]>, dims =
2574/// [1]>
2575/// The consumer slices exactly the reduction dim, so its parent layout is
2576/// reused for the source: sg_layout is kept, but the source's sg_data on
2577/// the reduction dim is grown from 8 to 16 (= srcShape[1] / sg_layout[1] =
2578/// 128 / 8) so the source tile is evenly distributed over the reduction
2579/// dim. The non-reduction dimensions keep the consumer's distribution.
2580///
2581/// 2. Same shapes as above, but the consumer has no reusable slice layout.
2582/// Copy its subgroup distribution onto non-reduction dims and assign the
2583/// remaining subgroups to reduction dims.
2584/// 2a. * Consumer Layout:
2585/// #xegpu.layout<sg_layout=[32], sg_data=[1]>
2586/// * Source Layout (decided by this function):
2587/// #xegpu.layout<sg_layout=[32, 1], sg_data=[1, 128]>
2588/// * Result Layout (returned):
2589/// #xegpu.slice<#xegpu.layout<sg_layout=[32, 1], sg_data=[1, 128]>,
2590/// dims = [1]>
2591/// All 32 subgroups are assigned to non-reduction dim 0. Dim 1 stays
2592/// within each subgroup (sg_layout=1), so its sg_data is 128.
2593/// 2b. * Consumer Layout:
2594/// #xegpu.slice<#xegpu.layout<sg_layout=[8, 2, 2], sg_data=[4, 64,
2595/// 32]>, dims = [1, 2]>
2596/// * Source Layout (decided by this function):
2597/// #xegpu.layout<sg_layout=[8, 4], sg_data=[4, 32]>
2598/// * Result Layout (returned):
2599/// #xegpu.slice<#xegpu.layout<sg_layout=[8, 4], sg_data=[4, 32]>,
2600/// dims = [1]>
2601/// The consumer slices dims [1, 2], but the reduction uses dim 1.
2602/// Copy its effective sg_layout=[8] onto dim 0 and assign the
2603/// remaining four subgroups to dim 1.
2604
2606 xegpu::LayoutKind layoutKind, VectorType srcVecTy,
2607 DistributeLayoutAttr consumerLayout, SmallVector<int64_t> reductionDims,
2608 int numSg, const xegpu::uArch::uArch *uArch) {
2609
2610 auto srcShape = srcVecTy.getShape();
2611 int srcRank = srcShape.size();
2612 auto context = srcVecTy.getContext();
2613
2614 const int subgroupSize = uArch->getSubgroupSize();
2615 int64_t maxReduceVectorSize = 16; // extend to spirv vector Size
2616 xegpu::DistributeLayoutAttr srcLayout;
2617 if (layoutKind == xegpu::LayoutKind::Subgroup) {
2618 xegpu::SliceAttr consumerSliceLayout =
2619 dyn_cast_if_present<xegpu::SliceAttr>(consumerLayout);
2620 if (consumerSliceLayout &&
2621 consumerSliceLayout.getDims().asArrayRef().equals(reductionDims)) {
2622 srcLayout = consumerSliceLayout.getParent();
2623 SmallVector<int64_t> sgLayoutFromConsumer =
2624 srcLayout.getEffectiveSgLayoutAsInt();
2625 auto srcSgData = computeShapeRatio(srcShape, sgLayoutFromConsumer);
2626 if (srcSgData)
2627 for (int dim = 0; dim < srcRank; dim++) {
2628 if (llvm::is_contained(reductionDims, dim))
2629 srcLayout =
2630 srcLayout.setDimData(dim, srcSgData.value()[dim], -1, -1);
2631 }
2632 } else {
2633 SmallVector<int64_t> consumerSgLayout =
2634 consumerLayout ? consumerLayout.getEffectiveSgLayoutAsInt()
2636 SmallVector<int64_t> consumerSgData =
2637 consumerLayout ? consumerLayout.getEffectiveSgDataAsInt()
2639 SmallVector<int64_t> consumerOrder =
2640 consumerLayout ? consumerLayout.getEffectiveOrderAsInt()
2642 DenseI32ArrayAttr orderAttr =
2643 consumerLayout ? consumerLayout.getOrder() : nullptr;
2644 SmallVector<int64_t> sgLayout(srcRank), sgData(srcRank), order(srcRank);
2645 int remainingSgCount =
2646 consumerLayout ? consumerLayout.getNumSubgroups() : numSg;
2647 int consumerIdx = 0;
2648
2649 // First pass: match the consumer's layout on non-reduction dims.
2650 for (int i = 0; i < srcRank; i++) {
2651 if (!llvm::is_contained(reductionDims, i) &&
2652 consumerIdx < static_cast<int>(consumerSgLayout.size())) {
2653 sgLayout[i] = consumerSgLayout[consumerIdx];
2654 sgData[i] = consumerSgData[consumerIdx];
2655 remainingSgCount /= sgLayout[i];
2656 consumerIdx++;
2657 }
2658 }
2659
2660 // Second pass: distribute remaining subgroups across the reduction dims.
2661 // The reduction-to-scalar case is handled only by this loop.
2662 for (int i = 0; i < srcRank; i++) {
2663 if (llvm::is_contained(reductionDims, i)) {
2664 sgLayout[i] =
2665 std::min(srcShape[i], static_cast<int64_t>(remainingSgCount));
2666 assert((srcShape[i] % sgLayout[i] == 0) &&
2667 "source shape not divisible by sg_layout");
2668 sgData[i] = srcShape[i] / sgLayout[i];
2669 remainingSgCount /= sgLayout[i];
2670 }
2671 }
2672 // The reduction dims are assumed to be row-major contiguous with the
2673 // left-hand neighbor.
2674 DenseI32ArrayAttr resOrderAttr = nullptr;
2675 int numRetainedDims = srcRank - static_cast<int>(reductionDims.size());
2676 if (orderAttr && !orderAttr.empty() &&
2677 static_cast<int>(consumerOrder.size()) == numRetainedDims) {
2678 // Fill known order
2679 int retainedRank = 0;
2680 for (int dim = 0; dim < srcRank; dim++)
2681 if (!llvm::is_contained(reductionDims, dim))
2682 order[dim] = consumerOrder[retainedRank++];
2683 // Each new order is placed as close as possible to its neighbors,
2684 // row-major. Re-index the order of higher walk orders.
2685 for (int reducedDim = 0; reducedDim < srcRank; reducedDim++) {
2686 if (!llvm::is_contained(reductionDims, reducedDim))
2687 continue;
2688 int64_t insertRank = 0;
2689 // Add as an inner dim to the outer neighbor
2690 if (reducedDim)
2691 insertRank = order[reducedDim - 1];
2692 // Add as an outer dim to the inner neighbor if no left neighbor
2693 // exists.
2694 else if (srcRank > 1)
2695 insertRank = order[reducedDim + 1] + 1;
2696 for (int otherDim = 0; otherDim < srcRank; otherDim++)
2697 if (order[otherDim] >= insertRank)
2698 order[otherDim]++;
2699 order[reducedDim] = insertRank;
2700 }
2701 resOrderAttr = DenseI32ArrayAttr::get(
2702 context, SmallVector<int32_t>(order.begin(), order.end()));
2703 }
2704 assert(remainingSgCount == 1 && "not all subgroups distributed");
2705 srcLayout = buildLayout(context, sgLayout, sgData,
2706 /*instData=*/{}, /*laneLayout=*/{},
2707 /*laneData=*/{}, resOrderAttr);
2708 }
2709 } else if (layoutKind == xegpu::LayoutKind::InstData) {
2710 auto [laneLayout, laneData, instData] =
2711 computeReductionLaneLayoutAndData(srcShape, reductionDims, subgroupSize,
2712 maxReduceVectorSize, consumerLayout);
2713 srcLayout =
2714 buildInstDataLayoutWithLane(context, instData, laneLayout, laneData);
2715 } else if (layoutKind == xegpu::LayoutKind::Lane) {
2716 xegpu::SliceAttr consumerSliceLayout =
2717 dyn_cast_if_present<xegpu::SliceAttr>(consumerLayout);
2718 if (consumerSliceLayout &&
2719 consumerSliceLayout.getDims().asArrayRef().equals(reductionDims)) {
2720 // at the lane level, the consumerSliceLayout can be directly reused
2721 // since the inst_data propagation already insert convert_layout if
2722 // the layout is not consistent
2723 srcLayout = consumerSliceLayout.getParent();
2724 } else {
2725 auto [laneLayout, laneData, instData] = computeReductionLaneLayoutAndData(
2726 srcShape, reductionDims, subgroupSize, maxReduceVectorSize,
2727 consumerLayout);
2728 (void)instData;
2729 srcLayout = buildLaneLayout(context, laneLayout, laneData);
2730 }
2731 }
2732
2733 return xegpu::SliceAttr::get(context, srcLayout,
2734 DenseI64ArrayAttr::get(context, reductionDims));
2735}
2736
2737/// Sets up layout for Reduction operations by creating a SliceAttr for the
2738/// result.
2739xegpu::SliceAttr
2741 VectorType srcVecTy,
2742 const xegpu::uArch::uArch *uArch) {
2743
2744 auto srcShape = srcVecTy.getShape();
2745 auto context = srcVecTy.getContext();
2746 auto subgroupSize = uArch->getSubgroupSize();
2747 xegpu::LayoutAttr srcLayout;
2748
2749 if (layoutKind == xegpu::LayoutKind::Subgroup) {
2750 assert(false &&
2751 "subgroup layout assignment not supported for reduction (op "
2752 "is not expected at this level).");
2753 } else if (layoutKind == xegpu::LayoutKind::InstData) {
2754 assert(false &&
2755 "instData layout assignment not supported for reduction (op "
2756 "is not expected at this level).");
2757 } else if (layoutKind == xegpu::LayoutKind::Lane) {
2758 SmallVector<int64_t> laneLayout(1), laneData(1);
2759 laneLayout[0] = std::min(static_cast<int64_t>(subgroupSize), srcShape[0]);
2760 laneData[0] = 1;
2761 srcLayout = buildLaneLayout(context, laneLayout, laneData);
2762 }
2763
2764 auto result = xegpu::SliceAttr::get(context, srcLayout,
2765 DenseI64ArrayAttr::get(context, 0));
2766 return result;
2767}
2768
2769/// Adjusts `consumerLayout`'s innermost-dim data field selected by
2770/// `layoutKind` so that the source layout can be safely inferred by dividing
2771/// that value by `ratio`. Doubles the value until the divisibility constraint
2772/// is met, bounded above by `bound` like result-shape.
2773///
2774/// Used by ops whose source relates to the result by a fixed factor along the
2775/// innermost dim (e.g., bitcast: bitwidth ratio; interleave: 2x).
2776///
2777/// Divisibility constraints per LayoutKind:
2778/// - Subgroup: sgData[innermost] % ratio == 0
2779/// - InstData: instData[innermost] % (laneLayout[innermost] * ratio) == 0
2780/// (laneLayout falls back to subgroupSize if absent)
2781/// - Lane: laneData[innermost] % ratio == 0
2782static xegpu::DistributeLayoutAttr
2783adjustInnermostDimForDivisibility(xegpu::DistributeLayoutAttr consumerLayout,
2784 xegpu::LayoutKind layoutKind,
2785 size_t innerMostDim, int ratio, int64_t bound,
2786 const xegpu::uArch::uArch *uArch) {
2787 SmallVector<int64_t> sgData = consumerLayout.getEffectiveSgDataAsInt();
2788 SmallVector<int64_t> instData = consumerLayout.getEffectiveInstDataAsInt();
2789 SmallVector<int64_t> laneData = consumerLayout.getEffectiveLaneDataAsInt();
2790 SmallVector<int64_t> laneLayout =
2791 consumerLayout.getEffectiveLaneLayoutAsInt();
2792
2793 int64_t sgDataValue = -1;
2794 int64_t instDataValue = -1;
2795 int64_t laneDataValue = -1;
2796
2797 if (layoutKind == xegpu::LayoutKind::Subgroup) {
2798 sgDataValue = sgData[innerMostDim];
2799 while ((sgDataValue <= bound) && (sgDataValue % ratio) != 0)
2800 sgDataValue *= 2;
2801 } else if (layoutKind == xegpu::LayoutKind::InstData) {
2802 instDataValue = instData[innerMostDim];
2803 const int innermostDimLaneLayout = laneLayout.empty()
2804 ? uArch->getSubgroupSize()
2805 : laneLayout[innerMostDim];
2806 while ((instDataValue <= bound) &&
2807 (instDataValue % (innermostDimLaneLayout * ratio) != 0))
2808 instDataValue *= 2;
2809 assert((bound % instDataValue) == 0 &&
2810 "bound, instData, and laneLayout for innermost must be 2^n!");
2811 } else if (layoutKind == xegpu::LayoutKind::Lane) {
2812 laneDataValue = laneData[innerMostDim];
2813 while ((laneDataValue <= bound) && (laneDataValue % ratio) != 0)
2814 laneDataValue *= 2;
2815 }
2816
2817 return consumerLayout.setDimData(innerMostDim, sgDataValue, instDataValue,
2818 laneDataValue);
2819}
2820
2821/// Sets up the result layout for a bitcast operation.
2822/// When casting to a smaller bitwidth, adjusts the layout dimensions (sgData,
2823/// instData, or laneData) by multiplying by the bitwidth ratio to ensure the
2824/// result layout can be correctly divided back to the source layout during
2825/// inference.
2826///
2827/// Examples:
2828/// 1. Casting f32 -> f16 (32-bit to 16-bit, bitWidthRatio = 2):
2829/// Consumer layout: instData=[1, 16], subgroupSize=16
2830/// Source shape: [8, 32]
2831/// Result layout: instData=[1, 32] (16 * 2)
2832/// The innermost dimension is multiplied by 2 to maintain consistency.
2833///
2834/// 2. Casting f32 -> i8 (32-bit to 8-bit, bitWidthRatio = 4):
2835/// Consumer instData=[1, 16], subgroupSize=16
2836/// Source shape: [4, 128]
2837/// adjust the instData from [1, 16] to [1, 16 * 4 = 64]
2838///
2839/// 3. Casting i8 -> i32 (8-bit to 32-bit, bitWidthRatio = 1/4):
2840/// Consumer layout: laneLayout=[1, 16], laneData=[1, 4]
2841/// No adjustment needed - returns consumer layout directly.
2842///
2843xegpu::DistributeLayoutAttr xegpu::setupBitCastResultLayout(
2844 xegpu::LayoutKind layoutKind, VectorType srcVecTy, VectorType resVecTy,
2845 DistributeLayoutAttr consumerLayout, const xegpu::uArch::uArch *uArch) {
2846
2847 int srcElemTyBitWidth = srcVecTy.getElementType().getIntOrFloatBitWidth();
2848 int resElemTyBitWidth = resVecTy.getElementType().getIntOrFloatBitWidth();
2849
2850 ArrayRef<int64_t> srcShape = srcVecTy.getShape();
2851 ArrayRef<int64_t> resShape = resVecTy.getShape();
2852
2853 assert(consumerLayout.getRank() == static_cast<int64_t>(srcShape.size()) &&
2854 "laneData must be available for all dimensions");
2855
2856 // Casting to same/larger element type: result has fewer (or equal) elements
2857 // along the innermost dim, no adjustment needed.
2858 if (srcElemTyBitWidth <= resElemTyBitWidth)
2859 return consumerLayout;
2860
2861 // Casting to smaller element type: result has more elements along innermost
2862 // dim. Adjust the innermost data field upward so the source layout can be
2863 // recovered by dividing by bitWidthRatio.
2864 size_t innerMostDim = srcShape.size() - 1;
2865 int bitWidthRatio = srcElemTyBitWidth / resElemTyBitWidth;
2866 return adjustInnermostDimForDivisibility(consumerLayout, layoutKind,
2867 innerMostDim, bitWidthRatio,
2868 resShape[innerMostDim], uArch);
2869}
2870
2871/// Sets up the result layout for an interleave operation to ensure the source
2872/// layout can be safely derived. Interleave doubles the innermost dimension,
2873/// so the result layout must ensure that laneData is a multiple
2874/// of 2, and instData must be divisible by innermostDimLaneLayout * 2.
2875///
2876/// Example:
2877/// Interleave: vector<128x256xf4> -> vector<128x512xf4>
2878/// Consumer layout: laneLayout=[1, 16], laneData=[1, 4], instData=[1, 64]
2879/// Result layout adjustment to ensure source can be safely inferred:
2880/// - laneData must be >= 2 and multiple of 2 (so source = laneData/2 is
2881/// valid)
2882/// - instData must be divisible by (16 * 2 = 32) (so source = instData/2 is
2883/// valid)
2884/// - Adjusted instData: ensure (instData % 32 == 0)
2885///
2886xegpu::DistributeLayoutAttr xegpu::setupInterleaveResultLayout(
2887 xegpu::LayoutKind layoutKind, VectorType srcVecTy, VectorType resVecTy,
2888 DistributeLayoutAttr consumerLayout, const xegpu::uArch::uArch *uArch) {
2889
2890 ArrayRef<int64_t> resShape = resVecTy.getShape();
2891 assert(consumerLayout.getRank() == static_cast<int64_t>(resShape.size()) &&
2892 "consumer layout rank must match source shape rank");
2893
2894 // Interleave doubles the innermost dimension (ratio = 2). Adjust the
2895 // innermost data field so the source layout can be recovered by dividing
2896 // by 2.
2897 const size_t innerMostDim = resShape.size() - 1;
2898 constexpr int ratio = 2;
2899 return adjustInnermostDimForDivisibility(consumerLayout, layoutKind,
2900 innerMostDim, ratio,
2901 resShape[innerMostDim], uArch);
2902}
2903
2904/// Checks that the tiles a split group is cut into walk the collapsed source
2905/// dim with one constant stride, which is what `collapseDims` assumes when it
2906/// multiplies a layout field across the group.
2907///
2908/// Along each dim the group is cut into `counts[dim]` tiles of `tileShape[dim]`
2909/// elements (empty for single-element tiles) taken from `shape[dim]`, which
2910/// gives the row-major strides. Walking from the innermost dim out, a dim cut
2911/// into several tiles steps by `tileShape[dim] * stride(dim)` and has to pick
2912/// up where the inner dims left off, `expectedStride`; a dim cut into one tile
2913/// does not step at all, so it only contributes its size.
2916 ArrayRef<int64_t> counts,
2917 ArrayRef<int64_t> tileShape,
2918 int64_t expectedStride) {
2919 int64_t stride = 1;
2920 for (int64_t dim : llvm::reverse(dimGroup)) {
2921 int64_t tileSize = tileShape.empty() ? 1 : tileShape[dim];
2922 if (counts[dim] != 1) {
2923 if (stride * tileSize != expectedStride)
2924 return false;
2925 expectedStride = stride * tileSize * counts[dim];
2926 }
2927 stride *= shape[dim];
2928 }
2929 return true;
2930}
2931
2932/// Checks that collapsing `dimGroup` of a subgroup layout, which multiplies
2933/// sg_layout and sg_data across the group, distributes the collapsed dim
2934/// exactly like the group does. That holds in two cases:
2935/// - Replicas: every dim of the group is held whole, so all subgroups are
2936/// copies of each other.
2937/// - Tiling: no subgroup repeats another's tile, each sg tile is contiguous in
2938/// the collapsed dim, the next subgroup's tile follows it, and the group's
2939/// distributed dims are walked row-major. A dim may repeat its tiles
2940/// round-robin only when every outer dim of the group has sg_layout =
2941/// sg_data = 1, which the contiguity checks imply.
2942/// For example, sg_layout = [1, 2], sg_data = [32, 16] over 32x32 is rejected:
2943/// the sg tile 32x16 is not contiguous in the collapsed dim 1024.
2946 ArrayRef<int64_t> sgLayout,
2947 ArrayRef<int64_t> sgData,
2948 ArrayRef<int64_t> order) {
2949 // Each subgroup holds the whole group, so all subgroups are copies.
2950 if (llvm::all_of(dimGroup,
2951 [&](int64_t dim) { return sgData[dim] == shape[dim]; }))
2952 return true;
2953
2954 // Otherwise, no dim may hold copies: copies on some dims mixed with split
2955 // ones do not collapse.
2956 if (llvm::any_of(dimGroup, [&](int64_t dim) {
2957 return sgLayout[dim] * sgData[dim] > shape[dim];
2958 }))
2959 return false;
2960
2961 // Dims split across subgroups must be ordered row-major, like the collapsed
2962 // dim (order[0] is the fastest).
2963 auto orderPos = [&](int64_t dim) {
2964 return std::distance(order.begin(), llvm::find(order, dim));
2965 };
2966 SmallVector<int64_t> spreadDims = llvm::filter_to_vector(
2967 dimGroup, [&](int64_t dim) { return sgLayout[dim] > 1; });
2968 for (size_t i = 1; i < spreadDims.size(); ++i)
2969 if (orderPos(spreadDims[i]) > orderPos(spreadDims[i - 1]))
2970 return false;
2971
2972 int64_t collapsedSgData = 1;
2973 for (int64_t dim : dimGroup)
2974 collapsedSgData *= sgData[dim];
2975 return isContiguousTiling(dimGroup, shape, sgData, /*tileShape=*/{},
2976 /*expectedStride=*/1) &&
2977 isContiguousTiling(dimGroup, shape, sgLayout, sgData,
2978 /*expectedStride=*/collapsedSgData);
2979}
2980
2981/// Subgroup level of setupShapeCastResultLayout. Keeps `consumerLayout` when
2982/// every split group collapses exactly (see isCollapsibleSgGroup). Otherwise,
2983/// the subgroups of each failing group move to its outermost dims, filling a
2984/// dim before moving inward. The result is a new layout, so it uses the
2985/// default order, under which the moved subgroups collapse exactly; a
2986/// convert_layout gives the consumer its own layout. Returns nullptr when the
2987/// subgroups do not fit the group's dims.
2988static xegpu::DistributeLayoutAttr
2990 ArrayRef<SmallVector<int64_t>> splitDimGroups,
2991 xegpu::DistributeLayoutAttr consumerLayout) {
2992 SmallVector<int64_t> sgLayout = consumerLayout.getEffectiveSgLayoutAsInt();
2993 SmallVector<int64_t> sgData = consumerLayout.getEffectiveSgDataAsInt();
2994 if (sgLayout.empty())
2995 return consumerLayout;
2996 SmallVector<int64_t> order = consumerLayout.getEffectiveOrderAsInt();
2997 if (llvm::all_of(splitDimGroups, [&](ArrayRef<int64_t> dimGroup) {
2998 return isCollapsibleSgGroup(dimGroup, resShape, sgLayout, sgData,
2999 order);
3000 }))
3001 return consumerLayout;
3002
3003 // A slice's effective sg_layout leaves out the subgroups on its sliced dims,
3004 // so a layout rebuilt from it would not use all subgroups.
3005 if (isa<xegpu::SliceAttr>(consumerLayout))
3006 return nullptr;
3007
3008 for (const SmallVector<int64_t> &dimGroup : splitDimGroups) {
3009 if (isCollapsibleSgGroup(dimGroup, resShape, sgLayout, sgData, order))
3010 continue;
3011 int64_t remaining = 1;
3012 for (int64_t dim : dimGroup)
3013 remaining *= sgLayout[dim];
3014 for (int64_t dim : dimGroup) {
3015 int64_t count = std::min(remaining, resShape[dim]);
3016 if (remaining % count != 0 || resShape[dim] % count != 0)
3017 return nullptr;
3018 sgLayout[dim] = count;
3019 sgData[dim] = resShape[dim] / count;
3020 remaining /= count;
3021 }
3022 if (remaining != 1)
3023 return nullptr;
3024 }
3025 // The inst_data and lane phases recompute their fields, so drop them.
3026 return buildLayout(consumerLayout.getContext(), sgLayout, sgData,
3027 /*instData=*/{}, /*laneLayout=*/{}, /*laneData=*/{});
3028}
3029
3030xegpu::DistributeLayoutAttr
3032 VectorType srcVecTy, VectorType resVecTy,
3033 DistributeLayoutAttr consumerLayout) {
3034 if (!consumerLayout)
3035 return consumerLayout;
3036
3037 if (layoutKind == xegpu::LayoutKind::Subgroup) {
3038 SmallVector<SmallVector<int64_t>> splitDimGroups;
3039 if (!xegpu::matchSplitDimExpansion(srcVecTy.getShape(), resVecTy.getShape(),
3040 splitDimGroups))
3041 return consumerLayout;
3042 return setupShapeCastSgResultLayout(resVecTy.getShape(), splitDimGroups,
3043 consumerLayout);
3044 }
3045
3046 ArrayRef<int64_t> resShape = resVecTy.getShape();
3047 SmallVector<SmallVector<int64_t>> splitDimGroups;
3048 if (!xegpu::matchSplitDimExpansion(srcVecTy.getShape(), resShape,
3049 splitDimGroups))
3050 return consumerLayout;
3051
3052 SmallVector<int64_t> laneLayout =
3053 consumerLayout.getEffectiveLaneLayoutAsInt();
3054 SmallVector<int64_t> instData = consumerLayout.getEffectiveInstDataAsInt();
3055
3056 xegpu::DistributeLayoutAttr resLayout = [&]() -> DistributeLayoutAttr {
3057 DistributeLayoutAttr layout = consumerLayout;
3058 for (const SmallVector<int64_t> &dimGroup : splitDimGroups) {
3059 size_t i = 0;
3060 while (i < dimGroup.size() && laneLayout[dimGroup[i]] == 1)
3061 ++i;
3062
3063 for (++i; i < dimGroup.size(); ++i) {
3064 int64_t dim = dimGroup[i];
3065 int64_t dimSize = resShape[dim];
3066 int64_t lanes = laneLayout[dim];
3067 if (lanes <= 0 || dimSize % lanes != 0)
3068 return consumerLayout;
3069 layout =
3070 layout.setDimData(dim, /*sgData=*/-1,
3071 instData.empty() ? -1 : dimSize, dimSize / lanes);
3072 }
3073 }
3074 return layout;
3075 }();
3076
3077 // Stretching does not make every layout collapsible; reject the rest.
3078 SmallVector<int64_t> resInstData = resLayout.getEffectiveInstDataAsInt();
3079 SmallVector<int64_t> resLaneLayout = resLayout.getEffectiveLaneLayoutAsInt();
3080 SmallVector<int64_t> resLaneData = resLayout.getEffectiveLaneDataAsInt();
3081
3082 for (const SmallVector<int64_t> &dimGroup : splitDimGroups) {
3083 // One lane's elements must be a single contiguous run of the collapsed dim.
3084 if (!isContiguousTiling(dimGroup, resShape, resLaneData, /*tileShape=*/{},
3085 /*expectedStride=*/1))
3086 return nullptr;
3087
3088 // Consecutive lanes must be exactly one such run apart.
3089 int64_t collapsedLaneData = 1;
3090 for (int64_t dim : dimGroup)
3091 collapsedLaneData *= resLaneData[dim];
3092 if (!isContiguousTiling(dimGroup, resShape, resLaneLayout, resLaneData,
3093 /*expectedStride=*/collapsedLaneData))
3094 return nullptr;
3095
3096 // The inst tile must walk the result shape the same way.
3097 if (!resInstData.empty() &&
3098 !isContiguousTiling(dimGroup, resShape, resInstData, /*tileShape=*/{},
3099 /*expectedStride=*/1))
3100 return nullptr;
3101 }
3102 return resLayout;
3103}
3104
3105/// Sets up the result layout for an insert strided slice operation.
3106/// Creates a result layout based on the specified layout kind (InstData or
3107/// Lane).
3108xegpu::DistributeLayoutAttr xegpu::setupInsertStridedSliceResultLayout(
3109 xegpu::LayoutKind layoutKind, VectorType srcVectorTy,
3110 VectorType resVectorTy, xegpu::DistributeLayoutAttr consumerLayout,
3111 const xegpu::uArch::uArch *uArch) {
3112
3113 xegpu::DistributeLayoutAttr requiredResLayout;
3114 SmallVector<int64_t> consumerInstData =
3115 consumerLayout.getEffectiveInstDataAsInt();
3116 SmallVector<int64_t> consumerLaneData =
3117 consumerLayout.getEffectiveLaneDataAsInt();
3118 SmallVector<int64_t> consumerLaneLayout =
3119 consumerLayout.getEffectiveLaneLayoutAsInt();
3120 ArrayRef<int64_t> srcShape = srcVectorTy.getShape();
3121 int64_t laneDataValue = -1;
3122
3123 requiredResLayout = consumerLayout;
3124 int srcRank = srcShape.size();
3125
3126 if (layoutKind == xegpu::LayoutKind::Subgroup ||
3127 layoutKind == xegpu::LayoutKind::InstData) {
3128 assert(false && "subgroup/instData layout assignment not supported for "
3129 "insertStridedSlice.");
3130 } else if (layoutKind == xegpu::LayoutKind::Lane) {
3131 for (int dim = 0; dim < srcRank; dim++) {
3132 // A size-1 source dim is broadcast across the lanes of that dim.
3133 if (srcShape[dim] == 1) {
3134 laneDataValue = 1;
3135 } else {
3136 assert(srcShape[dim] % consumerLaneLayout[dim] == 0 &&
3137 "srcShape must be divisible by laneLayout for all dimensions");
3138 laneDataValue = std::min(srcShape[dim] / consumerLaneLayout[dim],
3139 consumerLaneData[dim]);
3140 }
3141 requiredResLayout =
3142 requiredResLayout.setDimData(dim, -1, -1, laneDataValue);
3143 }
3144 }
3145 return requiredResLayout;
3146}
3147
3148/// Back-propagates a known result layout to the layout required on `operand`
3149/// for a non-anchor (layout-propagating) vector op. Dispatches on the op kind —
3150/// broadcast, (multi)reduction, bitcast, shape/transpose, insert/extract,
3151/// interleave, etc. — applying the shape/permutation/bitwidth transform to
3152/// derive the source layout; elementwise and pass-through ops reuse resLayout
3153/// as-is. Returns nullptr for unknown ops or an absent result layout.
3154xegpu::DistributeLayoutAttr xegpu::inferSourceLayoutFromResultForNonAnchorOp(
3155 OpOperand &operand, xegpu::DistributeLayoutAttr resLayout) {
3156 if (!resLayout)
3157 return nullptr;
3158 Operation *op = operand.getOwner();
3159 unsigned idx = operand.getOperandNumber();
3160
3161 // For vector::BroadcastOp, infer the source layout from the result layout.
3162 if (auto broadcast = dyn_cast<vector::BroadcastOp>(op)) {
3163 auto srcTy = dyn_cast<VectorType>(broadcast.getSourceType());
3164 if (!srcTy)
3165 return nullptr;
3167 resLayout, broadcast.getResultVectorType().getShape(),
3168 srcTy.getShape());
3169 }
3170
3171 // For vector::MultiDimReductionOp, infer source layout from result layout
3172 // using reduction dims. Acc operand is expected to have the same layout as
3173 // the result.
3174 if (auto reduction = dyn_cast<vector::MultiDimReductionOp>(op)) {
3175 if (idx == 0) {
3176 SmallVector<int64_t> reductionDims(reduction.getReductionDims());
3177 return xegpu::inferMultiReductionSourceLayout(resLayout, reductionDims);
3178 }
3179 if (idx == 1)
3180 return resLayout;
3181 }
3182
3183 if (auto reduction = dyn_cast<vector::ReductionOp>(op))
3184 return xegpu::inferReductionSourceLayout(resLayout);
3185
3186 // For vector::BitCastOp, infer source layout from result layout using
3187 // element type bitwidths.
3188 if (auto bitcast = dyn_cast<vector::BitCastOp>(op)) {
3189 int resElemBitWidth =
3190 bitcast.getResultVectorType().getElementType().getIntOrFloatBitWidth();
3191 int srcElemBitWidth =
3192 bitcast.getSourceVectorType().getElementType().getIntOrFloatBitWidth();
3193 return xegpu::inferBitCastSourceLayout(resLayout, resElemBitWidth,
3194 srcElemBitWidth);
3195 }
3196
3197 // For vector::ShapeCastOp, infer source layout from result layout using
3198 // shapes.
3199 if (auto shapeCast = dyn_cast<vector::ShapeCastOp>(op)) {
3201 resLayout, shapeCast.getResultVectorType().getShape(),
3202 shapeCast.getSourceVectorType().getShape());
3203 }
3204
3205 // For vector::InsertStridedSliceOp, infer source layout from result
3206 // layout. Dest vector must have the same layout as the result.
3207 if (auto insertSlice = dyn_cast<vector::InsertStridedSliceOp>(op)) {
3208 if (idx == 0) {
3210 resLayout, insertSlice.getDestVectorType().getShape(),
3211 insertSlice.getSourceVectorType().getShape());
3212 }
3213 if (idx == 1)
3214 return resLayout;
3215 }
3216
3217 // For vector::Insert Op, infer source layout from result layout using
3218 // shapes.
3219 if (auto insert = dyn_cast<vector::InsertOp>(op)) {
3220 VectorType resVecTy = dyn_cast<VectorType>(insert.getResult().getType());
3221 VectorType valueToStoreTy =
3222 dyn_cast<VectorType>(insert.getValueToStore().getType());
3223
3224 if ((idx == 0) && valueToStoreTy) {
3225 return xegpu::inferInsertSourceLayout(resLayout, resVecTy.getShape(),
3226 valueToStoreTy.getShape());
3227 }
3228 if (idx == 1)
3229 return resLayout;
3230 }
3231
3232 // For vector::Extract Op, infer source layout from result layout using
3233 // shapes.
3234 if (auto extract = dyn_cast<vector::ExtractOp>(op)) {
3235 VectorType srcVecTy = dyn_cast<VectorType>(extract.getSource().getType());
3236 VectorType resVecTy = dyn_cast<VectorType>(extract.getResult().getType());
3237 if (!srcVecTy || !resVecTy)
3238 return nullptr;
3239 return xegpu::inferExtractSourceLayout(resLayout, resVecTy.getShape(),
3240 srcVecTy.getShape());
3241 }
3242
3243 // For vector::TransposeOp, infer source layout from result layout using
3244 // permutation.
3245 if (auto transpose = dyn_cast<vector::TransposeOp>(op)) {
3246 return xegpu::inferTransposeSourceLayout(resLayout,
3247 transpose.getPermutation());
3248 }
3249
3250 // For vector::BitCastOp, infer source layout from result layout using
3251 // element type bitwidths.
3252 if (auto bitcast = dyn_cast<vector::BitCastOp>(op)) {
3253 int resElemBitWidth =
3254 bitcast.getResultVectorType().getElementType().getIntOrFloatBitWidth();
3255 int srcElemBitWidth =
3256 bitcast.getSourceVectorType().getElementType().getIntOrFloatBitWidth();
3257 return xegpu::inferBitCastSourceLayout(resLayout, resElemBitWidth,
3258 srcElemBitWidth);
3259 }
3260
3261 // for vector::interleave
3262 if (auto interleave = dyn_cast<vector::InterleaveOp>(op)) {
3263 return xegpu::inferInterleaveSourceLayout(resLayout);
3264 }
3265
3266 // for vector::deinterleave
3267 if (auto deinterleave = dyn_cast<vector::DeinterleaveOp>(op)) {
3268 return xegpu::inferDeinterleaveSourceLayout(resLayout);
3269 }
3270
3271 // For vector::ExtractStridedSliceOp, simply return result layout
3272 if (dyn_cast<vector::ExtractStridedSliceOp>(op))
3273 return resLayout;
3274
3275 // For elementwise operations, all operands must have the same layout as
3276 // the result.
3278 return resLayout;
3279
3280 return nullptr;
3281}
3282
3283// For a loop terminator operand (scf.for's scf.yield, scf.while's
3284// scf.condition), returns the layout of the region iter_arg it forwards into,
3285// which is the authoritative loop-carried layout, or nullptr when that position
3286// was never assigned a layout.
3287static xegpu::DistributeLayoutAttr getLoopCarriedLayoutForYieldOperand(
3288 RegionBranchTerminatorOpInterface terminator, OpOperand &operand) {
3289 auto branch = dyn_cast<RegionBranchOpInterface>(terminator->getParentOp());
3290 if (!branch)
3291 return nullptr;
3293 branch.getSuccessorOperandInputMapping(mapping,
3294 RegionBranchPoint(terminator));
3295 auto it = mapping.find(&operand);
3296 if (it == mapping.end())
3297 return nullptr;
3298 xegpu::DistributeLayoutAttr iterArgLayout;
3299 for (auto arg : llvm::make_isa_range<BlockArgument>(it->second)) {
3300 xegpu::DistributeLayoutAttr layout = xegpu::getDistributeLayoutAttr(arg);
3301 assert((!iterArgLayout || !layout || iterArgLayout.isEqualTo(layout)) &&
3302 "region inputs fed by one terminator operand disagree on layout");
3303 if (!iterArgLayout)
3304 iterArgLayout = layout;
3305 }
3306 return iterArgLayout;
3307}
3308
3309// For the terminator of a region op that carries nothing back into its regions
3310// (scf.if), returns the layout of the parent result the operand feeds.
3311static xegpu::DistributeLayoutAttr getParentResultLayoutForYieldOperand(
3312 RegionBranchTerminatorOpInterface terminator, OpOperand &operand) {
3313 auto branch = dyn_cast<RegionBranchOpInterface>(terminator->getParentOp());
3314 if (!branch)
3315 return nullptr;
3317 branch.getSuccessorOperandInputMapping(mapping,
3318 RegionBranchPoint(terminator));
3319 auto it = mapping.find(&operand);
3320 if (it == mapping.end())
3321 return nullptr;
3322 for (Value input : it->second)
3323 if (auto result = dyn_cast<OpResult>(input))
3325 return nullptr;
3326}
3327
3328/// Returns the layout required on `operand`: anchor ops report their declared
3329/// per-operand layout directly; non-anchor ops back-derive it from their result
3330/// layout via inferSourceLayoutFromResultForNonAnchorOp.
3331xegpu::DistributeLayoutAttr xegpu::getConsumerLayoutAt(OpOperand &operand) {
3332 Operation *op = operand.getOwner();
3333 // Anchor ops declare the layout they
3334 // require on each operand. Trust that declaration directly so that
3335 // ResolveLayoutConflicts compares producer-vs-declared
3336 if (isa<xegpu::AnchorLayoutInterface>(op))
3337 return xegpu::getDistributeLayoutAttr(operand);
3338 // Region ops with forwarded operands (scf.for's and scf.while's inits) carry
3339 // the required operand layout as the layout_operand_N that
3340 // propagateRegionArgsToInits back-propagated from the region argument. Do not
3341 // re-derive it from that argument here: conflict resolution inserts
3342 // convert_layout ops as it walks, rewriting the argument's uses, so what
3343 // those uses require depends on how far the walk has progressed.
3344 if (isa<RegionBranchOpInterface>(op))
3345 return xegpu::getDistributeLayoutAttr(operand);
3346 // A region terminator requires the layout of the successor input its operand
3347 // feeds: the region iter_arg for a loop, and the parent result for a region
3348 // op with no loop-carried values (scf.if).
3349 if (auto terminator = dyn_cast<RegionBranchTerminatorOpInterface>(op)) {
3350 if (isa<LoopLikeOpInterface>(op->getParentOp()))
3351 return getLoopCarriedLayoutForYieldOperand(terminator, operand);
3352 return getParentResultLayoutForYieldOperand(terminator, operand);
3353 }
3354 // For non-anchor ops, derive the operand layout from the op's result
3355 // layout via op-specific semantics.
3356 xegpu::DistributeLayoutAttr resLayout;
3357 if (op->getNumResults() == 1 || isa<vector::DeinterleaveOp>(op))
3358 resLayout = xegpu::getDistributeLayoutAttr(op->getResult(0));
3359 return inferSourceLayoutFromResultForNonAnchorOp(operand, resLayout);
3360}
return success()
static Value broadcast(Location loc, Value toBroadcast, unsigned numElements, const TypeConverter &typeConverter, ConversionPatternRewriter &rewriter)
Broadcasts the value to vector with numElements number of elements.
static xegpu::LayoutAttr buildLayout(mlir::MLIRContext *context, ArrayRef< int64_t > sgLayout, ArrayRef< int64_t > sgData, ArrayRef< int64_t > instData, ArrayRef< int64_t > laneLayout, ArrayRef< int64_t > laneData, DenseI32ArrayAttr orderAttr=nullptr)
static xegpu::DistributeLayoutAttr createScaleLayout(mlir::MLIRContext *context, VectorType matrixTy, VectorType scaleTy, xegpu::DistributeLayoutAttr matrixLayout, bool isBScale, const xegpu::uArch::uArch *uArch)
Helper to create a scale layout derived from a matrix operand layout.
static xegpu::DistributeLayoutAttr adjustInnermostDimForDivisibility(xegpu::DistributeLayoutAttr consumerLayout, xegpu::LayoutKind layoutKind, size_t innerMostDim, int ratio, int64_t bound, const xegpu::uArch::uArch *uArch)
Adjusts consumerLayout's innermost-dim data field selected by layoutKind so that the source layout ca...
static void walkRegionBackward(Region &region, xegpu::BackwardLayoutVisitor &visitor)
Visits the ops of region backward; see xegpu::walkBackward.
static xegpu::DistributeLayoutAttr setupDefaultScatterIOLayout(xegpu::LayoutKind layoutKind, mlir::MLIRContext *context, int maxChunkSize, ArrayRef< int64_t > srcShape, int subgroupSize, int numSg)
Select a default scatter IO layout with at most maxChunkSize elements per lane.
static xegpu::DistributeLayoutAttr setupShapeCastSgResultLayout(ArrayRef< int64_t > resShape, ArrayRef< SmallVector< int64_t > > splitDimGroups, xegpu::DistributeLayoutAttr consumerLayout)
Subgroup level of setupShapeCastResultLayout.
static xegpu::DistributeLayoutAttr get2DBlockIOSubgroupLayout(MLIRContext *context, ArrayRef< int64_t > dataShape, Type elemTy, const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction, int numSg)
Picks the subgroup layout for a 2D block IO op (store_nd / prefetch_nd).
static std::pair< SmallVector< int64_t >, SmallVector< int64_t > > computeScatterIOLaneLayoutAndData(ArrayRef< int64_t > instShape, int64_t subgroupSize, int64_t maxChunkSize)
Computes lane_layout and lane_data for scatter-style store anchor layouts (store scatter,...
static bool isReady(Region *region, const DenseMap< Region *, SmallPtrSet< Region *, 2 > > &targets, const SetVector< Region * > &visitedRegions)
Return whether every target recorded for region has been visited.
static xegpu::LayoutAttr buildInstDataLayoutWithLane(mlir::MLIRContext *context, ArrayRef< int64_t > instData, ArrayRef< int64_t > laneLayout, ArrayRef< int64_t > laneData, DenseI32ArrayAttr orderAttr=nullptr)
static SmallVector< Region * > getBackwardRegionOrder(Operation *op)
Order regions for walkBackward, preferring successors before predecessors and breaking ties by revers...
static xegpu::LayoutAttr buildSgLayout(mlir::MLIRContext *context, ArrayRef< int64_t > wgTileShape, ArrayRef< int64_t > sgLayout, int dimK=-1, DenseI32ArrayAttr orderAttr=nullptr)
static xegpu::DistributeLayoutAttr setupGenericLoadAnchorLayout(xegpu::LayoutKind layoutKind, mlir::MLIRContext *context, xegpu::DistributeLayoutAttr consumerLayout, int maxChunkSize, ArrayRef< int64_t > resShape, int subgroupSize, int numSg)
Select a layout for load_gather or load_matrix.
static bool isLayoutPreservingVectorProducer(Operation *op)
Accept pure vector generators and elementwise ops that preserve vector shape.
static xegpu::DistributeLayoutAttr getParentResultLayoutForYieldOperand(RegionBranchTerminatorOpInterface terminator, OpOperand &operand)
static xegpu::DistributeLayoutAttr setupDefault2DBlockIOLayout(xegpu::LayoutKind layoutKind, ArrayRef< int64_t > dataShape, Type elemTy, int numSg, const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction, const xegpu::uArch::uArch *uArch)
Select a default 2D block IO layout without transpose or transform.
static std::optional< SmallVector< int64_t > > get2DBlockIOInstDataLayout(ArrayRef< int64_t > dataShape, Type elemTy, const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction, bool transform=false, bool transpose=false)
Helper function to compute inst_data vectors for DPAS operands A, B, and C/D.
static xegpu::DistributeLayoutAttr getDefaultScatterIOSubgroupLayout(mlir::MLIRContext *context, ArrayRef< int64_t > wgShape, ArrayRef< int64_t > instData, int numSg)
Select the most balanced numSg factorization of wgShape whose sg_data is a multiple of instData.
static SmallVector< LayoutRepresentation > getSgLayoutCandidates(ArrayRef< int64_t > wgShape, ArrayRef< int64_t > instData, int64_t sgCount, int64_t broadcastDim=-1)
static SmallVector< LayoutRepresentation > enumerateFactorizations(int64_t total, int64_t rank)
Enumerates all ways to split total into rank factors whose product equals total.
static bool isCollapsibleSgGroup(ArrayRef< int64_t > dimGroup, ArrayRef< int64_t > shape, ArrayRef< int64_t > sgLayout, ArrayRef< int64_t > sgData, ArrayRef< int64_t > order)
Checks that collapsing dimGroup of a subgroup layout, which multiplies sg_layout and sg_data across t...
static bool isContiguousTiling(ArrayRef< int64_t > dimGroup, ArrayRef< int64_t > shape, ArrayRef< int64_t > counts, ArrayRef< int64_t > tileShape, int64_t expectedStride)
Checks that the tiles a split group is cut into walk the collapsed source dim with one constant strid...
SmallVector< int64_t > LayoutRepresentation
static xegpu::DistributeLayoutAttr getLayoutFromUsePoints(Value result)
static std::tuple< SmallVector< int64_t >, SmallVector< int64_t >, SmallVector< int64_t > > compute2DBlockIOLaneLayout(ArrayRef< int64_t > instShape, int64_t subgroupSize, int64_t bitwidth, int64_t packingSize, bool transform=false, bool transpose=false)
static xegpu::DistributeLayoutAttr getLoopCarriedLayoutForYieldOperand(RegionBranchTerminatorOpInterface terminator, OpOperand &operand)
static constexpr unsigned kMaxRematerializableChainOps
static void propagateResultsToRegularOperands(Operation *op)
static bool collectRematerializableChain(Operation *root, SmallVectorImpl< Operation * > &chain)
Collect each eligible producer once, producers first, for cloning with an IRMapping.
static bool isValidLaneLayout(ArrayRef< int64_t > dataShape, ArrayRef< int64_t > laneLayout, ArrayRef< int64_t > laneData)
static std::tuple< SmallVector< int64_t >, SmallVector< int64_t >, SmallVector< int64_t > > computeReductionLaneLayoutAndData(ArrayRef< int64_t > srcShape, ArrayRef< int64_t > reductionDims, int subgroupSize, int64_t maxReduceVectorSize, xegpu::DistributeLayoutAttr consumerLayout=nullptr)
Derives (lane_layout, lane_data, inst_data) for a vector.multi_reduction source from the layout reque...
static std::optional< std::tuple< xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr, xegpu::DistributeLayoutAttr > > getDpasSubgroupLayouts(mlir::MLIRContext *context, VectorType aTy, VectorType bTy, VectorType cdTy, xegpu::DistributeLayoutAttr consumerLayout, int numSg, std::tuple< SmallVector< int64_t >, SmallVector< int64_t >, SmallVector< int64_t > > instDataVecs, const xegpu::uArch::MMAInstructionInterface *uArchInstruction)
Helper function to set up subgroup layouts for DPAS operands A, B, and C/D.
static xegpu::LayoutAttr buildLaneLayout(mlir::MLIRContext *context, ArrayRef< int64_t > laneLayout, ArrayRef< int64_t > laneData, DenseI32ArrayAttr orderAttr=nullptr)
static std::optional< std::tuple< SmallVector< int64_t >, SmallVector< int64_t >, SmallVector< int64_t > > > getDpasInstDataLayouts(VectorType aTy, VectorType bTy, VectorType cdTy, const xegpu::uArch::MMAInstructionInterface *uArchInstruction)
Helper function to compute inst_data vectors for DPAS operands A, B, and C/D.
Attributes are known-constant values of operations.
Definition Attributes.h:25
Block represents an ordered list of Operations.
Definition Block.h:34
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
auto lookup(T from) const
Lookup a mapped value within the map.
Definition IRMapping.h:72
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
Definition Builders.cpp:581
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:415
This class represents an operand of an operation.
Definition Value.h:256
unsigned getOperandNumber() const
Return which operand this is in the OpOperand list of the Operation.
Definition Value.cpp:231
This is a value defined by a result of an operation.
Definition Value.h:456
void walkInherentAttrs(Operation *op, InherentAttrVisitor visitor) const
Visit the inherent attributes stored in the properties of op.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
bool hasDiscardableAttrOfType(NameT &&name)
Definition Operation.h:508
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
unsigned getNumRegions()
Returns the number of regions held by this operation.
Definition Operation.h:728
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
MutableArrayRef< OpOperand > getOpOperands()
Definition Operation.h:410
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
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition Operation.h:731
Attribute removeDiscardableAttr(StringAttr name)
Remove the discardable attribute with the specified name if it exists.
Definition Operation.h:526
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
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
This class represents a point being branched from in the methods of the RegionBranchOpInterface.
This class represents a successor of a region.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
bool empty()
Definition Region.h:60
unsigned getNumArguments()
Definition Region.h:136
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 provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
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
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< int32_t > content)
Operation * getOwner() const
Return the owner of this operand.
Definition UseDefLists.h:38
Callbacks for walkBackward.
virtual bool shouldRevisitRegions(RegionBranchOpInterface regionOp)
Called after visitRegionOp.
virtual void visitTerminator(RegionBranchTerminatorOpInterface terminator)=0
A terminator forwarding values between regions or to their parent op.
virtual void visitRegionOp(RegionBranchOpInterface regionOp)=0
A region branch op (e.g. scf.for), visited after all of its regions.
virtual void visitRegularOp(Operation *op)=0
Any other op.
bool hasElementwiseMappableTraits(Operation *op)
Together, Elementwise, Scalarizable, Vectorizable, and Tensorizable provide an easy way for scalar op...
DistributeLayoutAttr inferShapeCastSourceLayout(DistributeLayoutAttr resLayout, ArrayRef< int64_t > resShape, ArrayRef< int64_t > srcShape)
Infers the source layout attribute for a shape cast operation given the result layout attribute,...
bool matchDimCollapse(ArrayRef< int64_t > src, ArrayRef< int64_t > dst, SmallVector< SmallVector< int64_t > > &collapseDims)
DistributeLayoutAttr setupLoadNdAnchorLayout(LayoutKind layoutKind, VectorType vectorTy, DistributeLayoutAttr consumerLayout, int numSg, const uArch::uArch *uArch)
Sets up the anchor layout for a load_nd operation.
DistributeLayoutAttr inferResultLayoutFromSourceForNonAnchorOp(Operation *op, ArrayRef< DistributeLayoutAttr > operandLayouts)
Infers the result layout attribute for a non-anchor operation from the layouts of its source operands...
DistributeLayoutAttr setupInterleaveResultLayout(LayoutKind layoutKind, VectorType srcVectorTy, VectorType resVectorTy, DistributeLayoutAttr consumerLayout, const uArch::uArch *uArch)
Sets up the result layout for an interleave operation to ensure the source layout can be safely deriv...
DistributeLayoutAttr inferTransposeSourceLayout(DistributeLayoutAttr resLayout, ArrayRef< int64_t > permutation)
Infers the source layout attribute for a transpose operation given the result layout attribute and pe...
DistributeLayoutAttr inferInsertSourceLayout(DistributeLayoutAttr resLayout, ArrayRef< int64_t > resShape, ArrayRef< int64_t > srcShape)
Infers the source layout attribute for an insert operation.
std::optional< std::tuple< DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr > > completeDpasMxLaneLayoutFromInstData(DistributeLayoutAttr aLayout, DistributeLayoutAttr bLayout, DistributeLayoutAttr cdLayout, VectorType aTy, VectorType bTy, VectorType cdTy, VectorType aScaleTy, VectorType bScaleTy, const uArch::uArch *uArch)
Like completeDpasLaneLayoutFromInstData, but for dpas_mx: additionally re-derives the A_scale / B_sca...
DistributeLayoutAttr inferInsertStridedSliceSourceLayout(DistributeLayoutAttr resLayout, ArrayRef< int64_t > resShape, ArrayRef< int64_t > srcShape)
Infers the source layout attribute for an insert strided slice operation given the result layout attr...
DistributeLayoutAttr setupStoreMatrixAnchorLayout(LayoutKind layoutKind, VectorType vectorTy, int contigChunkSize, int numSg, const uArch::uArch *uArch)
Sets up the anchor layout for a store matrix operation.
void removeTemporaryLayoutAttrs(Operation *op)
Removes the temporary layout attributes for each OpOperand and OpResult of the given operation.
std::optional< std::tuple< DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr > > completeDpasLaneLayoutFromInstData(DistributeLayoutAttr aLayout, DistributeLayoutAttr bLayout, DistributeLayoutAttr cdLayout, VectorType aTy, VectorType bTy, VectorType cdTy, const uArch::uArch *uArch)
Completes user-provided DPAS A/B/C-D anchors that carry only inst_data by filling in lane_layout / la...
void setTemporaryLayout(const T &operandOrResult, const DistributeLayoutAttr layout)
LogicalResult propagateRegionArgsToInits(RegionBranchOpInterface regionOp, GetLayoutFnTy getLayoutOfValue, SetOperandLayoutFnTy setOperandLayout, SetTDescArgLayoutFnTy setTDescArgLayout)
Propagate layouts from a region branch op's region entry block arguments back to its init operands.
LayoutKind
Specifies the level of a layout hierarchy for comparison or propagation.
Definition XeGPU.h:31
SmallVector< NamedAttribute > dropInstDataOnAttrs(ArrayRef< NamedAttribute > attrs)
Updates the NamedAttribute sequence by dropping inst-data information from any DistributeLayoutAttr f...
DistributeLayoutAttr inferSourceLayoutFromResultForNonAnchorOp(OpOperand &operand, DistributeLayoutAttr resLayout)
Infers the source layout attribute for an operand using result layout attribute.
DistributeLayoutAttr inferInterleaveSourceLayout(DistributeLayoutAttr resLayout)
Infers the source layout attribute for an interleave operation given the result layout attribute.
DistributeLayoutAttr setupLoadGatherAnchorLayout(LayoutKind layoutKind, VectorType vectorTy, int contigChunkSize, DistributeLayoutAttr consumerLayout, int numSg, const uArch::uArch *uArch)
Sets up the anchor layout for a load gather operation.
bool matchUnitDimExpansion(ArrayRef< int64_t > src, ArrayRef< int64_t > dst, SmallVector< int64_t > &expandedUnitDims)
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...
bool recoverTemporaryLayouts(Operation *rootOp)
Attach layout attributes to all vector-type operands of operations within the given operation's neste...
DistributeLayoutAttr inferBroadcastSourceLayout(DistributeLayoutAttr resLayout, ArrayRef< int64_t > resShape, ArrayRef< int64_t > srcShape)
Infers the source layout attribute for a broadcast operation given the result layout attribute,...
std::optional< std::tuple< DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr > > setupDpasMxLayout(LayoutKind layoutKind, VectorType aTy, VectorType bTy, VectorType cdTy, VectorType aScaleTy, VectorType bScaleTy, DistributeLayoutAttr consumerLayout, int numSg, const uArch::uArch *uArch)
Sets up the anchor layouts for dpas_mx operands (A, B, C/D, A_scale, and B_scale).
void walkBackward(Operation *root, BackwardLayoutVisitor &visitor)
Walk function bodies under root in CFG post-order, visiting ops within each block back to front and n...
SliceAttr setupMultiReductionResultLayout(LayoutKind layoutKind, VectorType srcVectorTy, DistributeLayoutAttr consumerLayout, SmallVector< int64_t > reductionDims, int numSg, const uArch::uArch *uArch)
Note on the consumerLayout argument used by the consumer-driven setup* / complete* helpers below:
llvm::function_ref< void(OpOperand &, DistributeLayoutAttr)> SetOperandLayoutFnTy
The region helpers below choose layouts and pass each one to a callback; the caller decides when it r...
llvm::function_ref< DistributeLayoutAttr(Value)> GetLayoutFnTy
Callable returning the propagated layout for a given Value, used by the layout-propagation helpers be...
std::optional< DistributeLayoutAttr > completeScatterLoadLaneLayoutFromInstData(DistributeLayoutAttr userSpecifiedLayout, DistributeLayoutAttr consumerLayout, Type elemTy, const xegpu::uArch::LoadGatherInstruction *uArchInstruction, const int subgroupSize)
If the consumer layout has only inst_data (no lane_layout/lane_data), completes it by running the cor...
bool matchSplitDimExpansion(ArrayRef< int64_t > src, ArrayRef< int64_t > dst, SmallVector< SmallVector< int64_t > > &splitDimGroups)
DistributeLayoutAttr setupLoadMatrixAnchorLayout(LayoutKind layoutKind, VectorType vectorTy, int contigChunkSize, DistributeLayoutAttr consumerLayout, int numSg, const uArch::uArch *uArch)
Sets up the anchor layout for load matrix operation.
DistributeLayoutAttr setupStoreScatterAnchorLayout(LayoutKind layoutKind, VectorType vectorTy, int contigChunkSize, int numSg, const uArch::uArch *uArch)
Sets up the anchor layout for a store scatter operation.
DistributeLayoutAttr setupBitCastResultLayout(LayoutKind layoutKind, VectorType srcVectorTy, VectorType resVectorTy, DistributeLayoutAttr consumerLayout, const uArch::uArch *uArch)
Setup the result layout attribute for a bitcast operation based on element type bitwidths.
void propagateRegionResultsToYieldOperands(RegionBranchTerminatorOpInterface terminator, GetLayoutFnTy getLayoutOfValue, SetOperandLayoutFnTy setOperandLayout)
Propagate layouts to the operands of a region branch terminator: each operand gets,...
void removeLayoutAttr(const T &operandOrResult)
Removes the LayoutAttr for a given OpOperand or OpResult if it exists.
void dropInstDataOnInherentAttrs(Operation *op)
Drops inst-data information from DistributeLayoutAttrs stored as inherent attributes on the operation...
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.
SmallVector< NamedAttribute > dropSgLayoutAndDataOnAttrs(ArrayRef< NamedAttribute > attrs)
Updates the NamedAttribute sequence by dropping sg-layout and sg-data information from any Distribute...
DistributeLayoutAttr setupPrefetchNdAnchorLayout(LayoutKind layoutKind, TensorDescType tdescTy, int numSg, const uArch::uArch *uArch)
Sets up the anchor layout for a prefetch_nd operation.
DistributeLayoutAttr inferShapeCastResultLayout(DistributeLayoutAttr srcLayout, ArrayRef< int64_t > srcShape, ArrayRef< int64_t > resShape)
Infers the result layout attribute for a shape cast operation given the source layout attribute,...
DistributeLayoutAttr inferExtractSourceLayout(DistributeLayoutAttr resLayout, ArrayRef< int64_t > resShape, ArrayRef< int64_t > srcShape)
Infers the source layout attribute for an extract operation.
std::string getTemporaryLayoutName(const OpOperand &operand)
Return the attribute name for the OpOperand to attach DistributeLayoutAttr.
DistributeLayoutAttr inferBitCastSourceLayout(DistributeLayoutAttr resLayout, int resElemTyBitWidth, int srcElemTyBitWidth)
Infers the source layout attribute for a bitcast operation given the result layout attribute,...
DistributeLayoutAttr setupInsertStridedSliceResultLayout(LayoutKind layoutKind, VectorType srcVectorTy, VectorType resVectorTy, DistributeLayoutAttr consumerLayout, const uArch::uArch *uArch)
Sets up the result layout for an insert strided slice operation.
DistributeLayoutAttr setupShapeCastResultLayout(LayoutKind layoutKind, VectorType srcVectorTy, VectorType resVectorTy, DistributeLayoutAttr consumerLayout)
Sets up the result layout for a shape cast that splits one source dim into several consecutive result...
DistributeLayoutAttr inferReductionSourceLayout(DistributeLayoutAttr resLayout)
Infers the source layout attribute for a reduction operation given the result layout attribute and re...
std::optional< DistributeLayoutAttr > completeScatterStoreLaneLayoutFromInstData(DistributeLayoutAttr specifiedLayout, Type elemTy, const xegpu::uArch::StoreScatterInstruction *uArchInstruction, const int subgroupSize)
Like completeScatterLoadLaneLayoutFromInstData, but for scatter stores (store_scatter / store_matrix)...
std::optional< DistributeLayoutAttr > completeBlockStoreLaneLayoutFromInstData(DistributeLayoutAttr specifiedLayout, Type elemTy, const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction, const int subgroupSize)
Completes a user-provided 2D-block store_nd / prefetch_nd anchor that has only inst_data.
DistributeLayoutAttr inferDeinterleaveSourceLayout(DistributeLayoutAttr resLayout)
Infers the source layout attribute for a deinterleave operation given the result layout attribute.
DistributeLayoutAttr getConsumerLayoutAt(OpOperand &operand)
Gets the expected layout for a given consumer operand.
void removeLayoutAttrs(Operation *op)
Removes the DistributeLayoutAttr for each OpOperand and OpResult of the given operation if they exist...
DistributeLayoutAttr inferMultiReductionSourceLayout(DistributeLayoutAttr resLayout, SmallVector< int64_t > reduceDims)
Infers the source layout attribute for a reduction operation given the result layout attribute and re...
bool isTriviallyRematerializable(Operation *op)
Returns true if the vector produced by op is cheap to recompute in any layout, i.e.
Value rematerialize(OpBuilder &builder, Value value)
Clone a bounded chain of pure vector generators and layout-preserving elementwise ops without layout ...
DistributeLayoutAttr setupStoreNdAnchorLayout(LayoutKind layoutKind, VectorType vectorTy, int numSg, const uArch::uArch *uArch)
Sets up the anchor layout for a store_nd operation.
DistributeLayoutAttr inferTransposeResultLayout(DistributeLayoutAttr srcLayout, ArrayRef< int64_t > permutation)
Infers the result layout attribute for a transpose operation given the source layout attribute and pe...
std::optional< DistributeLayoutAttr > completeBlockLoadLaneLayoutFromInstData(DistributeLayoutAttr specifiedLayout, DistributeLayoutAttr consumerLayout, Type elemTy, const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction, const int subgroupSize)
Like completeBlockStoreLaneLayoutFromInstData, but for load_nd.
void setTensorDescLayout(Value value, DistributeLayoutAttr layout)
Sets layout on the type of the tensor_desc value value, replacing any layout the type already has.
std::optional< std::tuple< DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr > > setupDpasLayout(LayoutKind layoutKind, VectorType aTy, VectorType bTy, VectorType cdTy, DistributeLayoutAttr consumerLayout, int numSg, const uArch::uArch *uArch)
Sets up the anchor layouts for a dpas operands (A, B, and C/D).
SliceAttr setupReductionResultLayout(LayoutKind layoutKind, VectorType srcVectorTy, const uArch::uArch *uArch)
Sets up layout for Reduction operations by creating a SliceAttr for the result.
Include the generated interface declarations.
DenseMap< OpOperand *, SmallVector< Value > > RegionBranchSuccessorMapping
A mapping from successor operands to successor inputs.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
AffineMap inversePermutation(AffineMap map)
Returns a map of codomain to domain dimensions such that the first codomain dimension for a particula...
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
int64_t computeProduct(ArrayRef< int64_t > basis)
Self-explicit.
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
detail::DenseArrayAttrImpl< int32_t > DenseI32ArrayAttr
Operation * clone(OpBuilder &b, Operation *op, TypeRange newResultTypes, ValueRange newOperands)
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.
SmallVector< int64_t > invertPermutationVector(ArrayRef< int64_t > permutation)
Helper method to apply to inverse a permutation.
virtual int32_t getPackedFormatBitSize() const =0
std::optional< BlockShapes > getBlockWidthHeightCount(Type elemTy, bool hasTransform=false, bool hasTranspose=false, bool upConv=false) const
Definition uArchBase.h:216
int32_t getMaxLaneAccessSizeBytes() const override
Definition uArchBase.h:258
virtual llvm::SmallVector< uint32_t, 8 > getSupportedN(Type type) const =0
virtual llvm::SmallVector< uint32_t, 8 > getSupportedK(Type type) const =0
virtual llvm::SmallVector< uint32_t, 8 > getSupportedM(Type type) const =0
int32_t getMaxLaneAccessSizeBytes() const override
Definition uArchBase.h:263
virtual unsigned getGeneralPackedFormatBitSize() const =0
virtual int getSubgroupSize() const =0
const Instruction * getInstruction(InstructionKind instKind) const
Definition uArchBase.h:146