MLIR 24.0.0git
XeGPUPropagateLayout.cpp
Go to the documentation of this file.
1//===- XeGPUPropagateLayout.cpp - XeGPU Layout Propagation ------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
19#include "mlir/IR/Attributes.h"
20#include "mlir/IR/Builders.h"
23#include "mlir/IR/Operation.h"
25#include "mlir/IR/Value.h"
26#include "mlir/IR/Visitors.h"
30#include "mlir/Support/LLVM.h"
31#include "llvm/ADT/ArrayRef.h"
32#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/MapVector.h"
34#include "llvm/ADT/PostOrderIterator.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/Sequence.h"
37#include "llvm/ADT/SetVector.h"
38#include "llvm/ADT/SmallSet.h"
39#include "llvm/ADT/SmallVector.h"
40#include "llvm/ADT/TypeSwitch.h"
41#include "llvm/Support/Casting.h"
42#include "llvm/Support/Debug.h"
43#include "llvm/Support/LogicalResult.h"
44#include "llvm/Support/MathExtras.h"
45#include "llvm/Support/raw_ostream.h"
46
47namespace mlir {
48namespace xegpu {
49#define GEN_PASS_DEF_XEGPUPROPAGATELAYOUT
50#include "mlir/Dialect/XeGPU/Transforms/Passes.h.inc"
51} // namespace xegpu
52} // namespace mlir
53
54#define DEBUG_TYPE "xegpu-propagate-layout"
55#define DBGS() (llvm::dbgs() << "[" DEBUG_TYPE "]: ")
56
57using namespace mlir;
58
59namespace {
60//===----------------------------------------------------------------------===//
61// LayoutPropagation
62//===----------------------------------------------------------------------===//
63
64/// Propagates layouts with a backward scan, then a forward fill.
65///
66/// Backward scan: the shared driver xegpu::walkBackward, used by both layout
67/// propagation and layout recovery, calls the BackwardLayoutVisitor callbacks
68/// visitTerminator / visitRegionOp / visitRegularOp.
69/// - Order: ops are visited backward (consumers before producers), with an
70/// op's regions before the op itself. Regions are visited against control
71/// flow, so scf.while's before region comes before its after region.
72/// - Exceptions: consumers across a loop back edge are visited after their
73/// producer. For scf.while, that also covers the uses in its after region.
74///
75/// One decision per op:
76/// - Values: a value takes the layout requested by its nearest consumer.
77/// Requests are kept in one value -> layout map (requestedLayouts), which
78/// each consumer overwrites. Because consumers are visited from farthest to
79/// nearest, no program-order numbering is needed.
80/// - Propagation functions (visit*Op) do not modify the IR. They take the
81/// layouts requested for the op's results, return the layouts the op
82/// requests of its operands, and may replace a result layout the op
83/// requires (e.g. a reduction). Anchor propagation functions also return
84/// the layout attributes they decide for the op (AnchorLayouts). The driver
85/// keeps all of these and writes them into the IR after the walk
86/// (commitDecisions): anchor attributes, temporary layouts and tensor_desc
87/// types, including the scalar result of a reduction.
88/// - Anchor ops (AnchorLayoutInterface) honour an anchor layout given in the
89/// input IR and at most complete it. Otherwise, anchor ops with results
90/// (loads and dpas) decide from the layout requested for their result.
91/// Their decisions are written into the IR only after the walk, so a loop
92/// body walked again revises them with the layouts requested across the
93/// back edge.
94///
95/// Region boundaries, in the backward scan:
96/// - Terminators (visitTerminator): each operand takes the layout of the
97/// region argument it feeds, if one has been requested, otherwise of the
98/// region result, and gets it as layout_operand_N. This is
99/// propagateRegionResultsToYieldOperands, shared with layout recovery,
100/// which passes its use-point lookup.
101/// - Init operands (visitRegionOp) take the layout of the region argument
102/// they feed (propagateRegionArgsToInits).
103/// - scf.while restriction: an after-region argument must be a pass-through
104/// of a before-region argument. Otherwise propagation reports an error.
105///
106/// Forward fill (forwardFillUnassignedLayouts), in program order, does only
107/// what needs information flowing forward:
108/// - forwardFillRegularOp infers a result's layout from its operand
109/// layouts, and warns "op has users but no layout assigned" when it
110/// can't;
111/// - forwardInitsToRegionArgs gives each loop init operand without a decided
112/// layout the layout of its init value, to which the region argument it
113/// feeds is bound;
114/// - forwardYieldOperandsToRegionResults gives each region result the layout
115/// of the terminator operand that feeds it;
116/// - updateFunctionOpInterface updates the function signatures.
117///
118/// ResolveLayoutConflicts then reconciles producer and consumer layouts.
119class LayoutPropagation final : public xegpu::BackwardLayoutVisitor {
120public:
121 LayoutPropagation(Operation *scopeRoot, xegpu::LayoutKind layoutKind)
122 : scopeRoot(scopeRoot), layoutKind(layoutKind) {}
123
124 /// Runs the backward scan over every function under `scopeRoot` and emits
125 /// its diagnostics. The IR is unchanged until commitDecisions().
126 LogicalResult run();
127
128 /// Returns the layout requested by consumers of `val`, or null if unknown.
129 xegpu::DistributeLayoutAttr getRequestedLayout(Value val) const {
130 return requestedLayouts.lookup(val);
131 }
132
133 /// Prints requested layouts for function arguments and op results.
134 void print(llvm::raw_ostream &os);
135
136 /// Writes the decisions of the walk into the IR.
137 void commitDecisions();
138
139private:
140 // Propagation functions fill `operands` with requested layouts. `results`
141 // starts with layouts requested by consumers and may be overridden by the op.
143 // Anchor propagation functions only read the layouts requested for their
144 // results; an anchor's decision is returned in AnchorLayouts instead.
145 using LayoutsRef = ArrayRef<xegpu::DistributeLayoutAttr>;
146 // Layout attributes an anchor propagation function decides for its op, by
147 // attribute name. The driver writes them into the IR after the walk (see
148 // anchorDecisions), so the propagation functions themselves do not modify the
149 // IR.
150 using AnchorLayouts =
152
153 Operation *scopeRoot;
154 xegpu::LayoutKind layoutKind;
155
156 // Latest non-null layout requested by consumers of each value.
158 // Layout attributes decided for each anchor op, written into the IR only
159 // after the walk.
161 // Layouts decided for uses (terminator and init operands, written as
162 // layout_operand_N) and for values (op results, written as layout_result_N
163 // or into a tensor_desc type, and tensor_desc region arguments).
166
167 // A decision replaces the one from any earlier visit. A null (empty) one
168 // means no decision on this visit and keeps the earlier one.
169 void setOperandDecision(OpOperand &operand,
170 xegpu::DistributeLayoutAttr layout) {
171 if (layout)
172 operandDecisions[&operand] = layout;
173 }
174 void setValueDecision(Value value, xegpu::DistributeLayoutAttr layout) {
175 if (layout)
176 valueDecisions[value] = layout;
177 }
178 void setAnchorDecision(Operation *op, AnchorLayouts layouts) {
179 if (!layouts.empty())
180 anchorDecisions[op] = std::move(layouts);
181 }
182 xegpu::DistributeLayoutAttr getOperandDecision(OpOperand &operand) const {
183 return operandDecisions.lookup(&operand);
184 }
185 // Diagnostics reported by the visits of each op, emitted only after the
186 // walk: a later visit of the op replaces them, like its decisions.
187 struct PendingDiagnostic {
188 DiagnosticSeverity severity;
189 std::string message;
190 };
192 pendingDiagnostics;
193 // Emits the pending diagnostics; returns failure if any of them is an error.
194 LogicalResult emitPendingDiagnostics();
195
196 //===--------------------------------------------------------------------===//
197 // Backward scan
198 //===--------------------------------------------------------------------===//
199
200 // A non-null requested layout replaces the one from any earlier visit.
201 void recordRequestedLayout(Value val, xegpu::DistributeLayoutAttr layout) {
202 if (layout)
203 requestedLayouts[val] = layout;
204 }
205 void visitRegularOp(Operation *op) override;
206 void visitTerminator(RegionBranchTerminatorOpInterface terminator) override;
207 void visitRegionOp(RegionBranchOpInterface regionOp) override;
208 bool shouldRevisitRegions(RegionBranchOpInterface regionOp) override;
209
210 //===--------------------------------------------------------------------===//
211 // Propagation functions
212 //===--------------------------------------------------------------------===//
213
214 void visitOperation(Operation *op, LayoutsMutRef operands,
215 LayoutsMutRef results, AnchorLayouts &anchorLayouts);
216
217 void visitDpasOp(xegpu::DpasOp dpas, LayoutsMutRef operands,
218 LayoutsRef results, AnchorLayouts &anchorLayouts);
219 void visitDpasMxOp(xegpu::DpasMxOp dpasMx, LayoutsMutRef operands,
220 LayoutsRef results, AnchorLayouts &anchorLayouts);
221 void visitStoreNdOp(xegpu::StoreNdOp store, LayoutsMutRef operands,
222 LayoutsRef results, AnchorLayouts &anchorLayouts);
223 void visitStoreScatterOp(xegpu::StoreScatterOp storeScatter,
224 LayoutsMutRef operands, LayoutsRef results,
225 AnchorLayouts &anchorLayouts);
226 void visitLoadNdOp(xegpu::LoadNdOp load, LayoutsMutRef operands,
227 LayoutsRef results, AnchorLayouts &anchorLayouts);
228 void visitLoadGatherOp(xegpu::LoadGatherOp load, LayoutsMutRef operands,
229 LayoutsRef results, AnchorLayouts &anchorLayouts);
230 void visitPrefetchNdOp(xegpu::PrefetchNdOp prefetch, LayoutsMutRef operands,
231 LayoutsRef results, AnchorLayouts &anchorLayouts);
232 void visitLoadMatrixOp(xegpu::LoadMatrixOp load, LayoutsMutRef operands,
233 LayoutsRef results, AnchorLayouts &anchorLayouts);
234 void visitStoreMatrixOp(xegpu::StoreMatrixOp store, LayoutsMutRef operands,
235 LayoutsRef results, AnchorLayouts &anchorLayouts);
236 void visitConvertLayoutOp(xegpu::ConvertLayoutOp convertLayout,
237 LayoutsMutRef operands, LayoutsMutRef results);
238 void visitTransposeOp(vector::TransposeOp transpose, LayoutsMutRef operands,
239 LayoutsMutRef results);
240 void visitVectorBitcastOp(vector::BitCastOp bitcast, LayoutsMutRef operands,
241 LayoutsMutRef results);
242 void visitVectorInterleaveOp(vector::InterleaveOp interleave,
243 LayoutsMutRef operands, LayoutsMutRef results);
244 void visitVectorDeinterleaveOp(vector::DeinterleaveOp deinterleave,
245 LayoutsMutRef operands, LayoutsMutRef results);
246 void visitVectorMultiReductionOp(vector::MultiDimReductionOp reduction,
247 LayoutsMutRef operands,
248 LayoutsMutRef results);
249 void visitVectorReductionOp(vector::ReductionOp reduction,
250 LayoutsMutRef operands, LayoutsMutRef results);
251 void visitVectorBroadCastOp(vector::BroadcastOp broadcast,
252 LayoutsMutRef operands, LayoutsMutRef results);
253 void visitShapeCastOp(vector::ShapeCastOp shapeCast, LayoutsMutRef operands,
254 LayoutsMutRef results);
255 void
256 visitInsertStridedSliceOp(vector::InsertStridedSliceOp insertStridedSlice,
257 LayoutsMutRef operands, LayoutsMutRef results);
258
259 bool hasParamsOfLayoutKind(xegpu::DistributeLayoutAttr anchorLayout);
260
261 // Number of subgroups for `op`. Missing count is fatal in subgroup mode.
262 FailureOr<int64_t> getNumSgOrFail(Operation *op, int sgSize,
263 xegpu::DistributeLayoutAttr consumerLayout);
264
265 // Report a fatal propagation error.
266 void markFailure(Operation *op, const llvm::Twine &message) {
267 pendingDiagnostics[op].push_back(
268 {DiagnosticSeverity::Error, message.str()});
269 }
270 // Report a propagation warning.
271 void markWarning(Operation *op, const llvm::Twine &message) {
272 pendingDiagnostics[op].push_back(
273 {DiagnosticSeverity::Warning, message.str()});
274 }
275};
276} // namespace
277
278void LayoutPropagation::visitOperation(Operation *op, LayoutsMutRef operands,
279 LayoutsMutRef results,
280 AnchorLayouts &anchorLayouts) {
282 .Case([&](xegpu::DpasOp op) {
283 visitDpasOp(op, operands, results, anchorLayouts);
284 })
285 .Case([&](xegpu::DpasMxOp op) {
286 visitDpasMxOp(op, operands, results, anchorLayouts);
287 })
288 .Case([&](xegpu::StoreNdOp op) {
289 visitStoreNdOp(op, operands, results, anchorLayouts);
290 })
291 .Case([&](xegpu::StoreScatterOp op) {
292 visitStoreScatterOp(op, operands, results, anchorLayouts);
293 })
294 .Case([&](xegpu::LoadNdOp op) {
295 visitLoadNdOp(op, operands, results, anchorLayouts);
296 })
297 .Case([&](xegpu::LoadGatherOp op) {
298 visitLoadGatherOp(op, operands, results, anchorLayouts);
299 })
300 .Case([&](xegpu::PrefetchNdOp op) {
301 visitPrefetchNdOp(op, operands, results, anchorLayouts);
302 })
303 .Case([&](vector::TransposeOp op) {
304 visitTransposeOp(op, operands, results);
305 })
306 .Case([&](vector::BitCastOp op) {
307 visitVectorBitcastOp(op, operands, results);
308 })
309 .Case([&](vector::InterleaveOp op) {
310 visitVectorInterleaveOp(op, operands, results);
311 })
312 .Case([&](vector::DeinterleaveOp op) {
313 visitVectorDeinterleaveOp(op, operands, results);
314 })
315 .Case([&](vector::MultiDimReductionOp op) {
316 visitVectorMultiReductionOp(op, operands, results);
317 })
318 .Case([&](vector::ReductionOp op) {
319 visitVectorReductionOp(op, operands, results);
320 })
321 .Case([&](vector::BroadcastOp op) {
322 visitVectorBroadCastOp(op, operands, results);
323 })
324 .Case([&](vector::ShapeCastOp op) {
325 visitShapeCastOp(op, operands, results);
326 })
327 .Case([&](vector::InsertStridedSliceOp op) {
328 visitInsertStridedSliceOp(op, operands, results);
329 })
330 .Case([&](xegpu::LoadMatrixOp op) {
331 visitLoadMatrixOp(op, operands, results, anchorLayouts);
332 })
333 .Case([&](xegpu::StoreMatrixOp op) {
334 visitStoreMatrixOp(op, operands, results, anchorLayouts);
335 })
336 .Case([&](xegpu::ConvertLayoutOp op) {
337 visitConvertLayoutOp(op, operands, results);
338 })
339 // All other ops: every vector / tensor_desc operand takes the layout of
340 // the first result that has one.
341 .Default([&](Operation *op) {
342 auto it = llvm::find_if(
343 results, [](auto layout) { return static_cast<bool>(layout); });
344 if (it == results.end())
345 return;
346 for (auto [operandLayout, operand] :
347 llvm::zip_equal(operands, op->getOperands()))
348 if (xegpu::isLayoutCarrierType(operand.getType()))
349 operandLayout = *it;
350 });
351}
352
353bool LayoutPropagation::hasParamsOfLayoutKind(
354 xegpu::DistributeLayoutAttr anchorLayout) {
355 if (anchorLayout == nullptr) {
356 return false;
357 }
358 if (layoutKind == xegpu::LayoutKind::InstData) {
359 return !(anchorLayout.getEffectiveInstDataAsInt().empty());
360 }
361 if (layoutKind == xegpu::LayoutKind::Lane) {
362 return !(anchorLayout.getEffectiveLaneLayoutAsInt().empty() ||
363 anchorLayout.getEffectiveLaneDataAsInt().empty());
364 }
365 if (layoutKind == xegpu::LayoutKind::Subgroup) {
366 return !(anchorLayout.getEffectiveSgLayoutAsInt().empty() ||
367 anchorLayout.getEffectiveSgDataAsInt().empty());
368 }
369 return false;
370}
371
372FailureOr<int64_t>
373LayoutPropagation::getNumSgOrFail(Operation *op, int sgSize,
374 xegpu::DistributeLayoutAttr consumerLayout) {
375 // The consumer's sg_layout, when present, dictates the count.
376 if (consumerLayout) {
377 auto sgLayout = consumerLayout.getEffectiveSgLayoutAsInt();
378 if (!sgLayout.empty())
379 return llvm::product_of(sgLayout);
380 }
381 // Otherwise fall back to the kernel's known_block_size.
382 if (FailureOr<int64_t> numSg =
384 succeeded(numSg))
385 return *numSg;
386 // Only subgroup mode needs the count; elsewhere a missing one is benign.
387 if (layoutKind == xegpu::LayoutKind::Subgroup) {
388 markFailure(op, "Unable to determine the number of subgroups for the "
389 "operation. Please check @known_block_size is properly "
390 "attached as kernel attributes, with power-of-two "
391 "dimensions covering at least one subgroup.");
392 return failure();
393 }
394 return int64_t{0};
395}
396
397void LayoutPropagation::visitPrefetchNdOp(xegpu::PrefetchNdOp prefetch,
398 LayoutsMutRef operands,
399 LayoutsRef results,
400 AnchorLayouts &anchorLayouts) {
401
402 xegpu::DistributeLayoutAttr prefetchLayout;
403 const auto *uArch = xegpu::uArch::getUArch(getChipStr(prefetch).value_or(""));
404 if (!uArch)
405 return;
406 xegpu::DistributeLayoutAttr anchorLayout = prefetch.getLayoutAttr();
407 if (hasParamsOfLayoutKind(anchorLayout)) {
408 prefetchLayout = anchorLayout;
409 if (layoutKind == xegpu::LayoutKind::InstData) {
410 const auto *uArchInstruction =
411 dyn_cast<xegpu::uArch::Subgroup2DBlockPrefetchInstruction>(
412 uArch->getInstruction(
413 xegpu::uArch::InstructionKind::Subgroup2DBlockPrefetch));
414 if (!uArchInstruction)
415 return;
417 anchorLayout, prefetch.getTensorDescType().getElementType(),
418 uArchInstruction, uArch->getSubgroupSize());
419 if (!completed) {
420 markWarning(
421 prefetch,
422 "Failed to identify lane layouts for the specified inst_data.");
423 return;
424 }
425 anchorLayouts.emplace_back(prefetch.getLayoutAttrName(), *completed);
426 prefetchLayout = *completed;
427 }
428 } else {
429 auto tdescTy = prefetch.getTensorDescType();
430 auto numSgOrErr =
431 getNumSgOrFail(prefetch, uArch->getSubgroupSize(), nullptr);
432 if (failed(numSgOrErr))
433 return;
434
435 auto layoutAttr = xegpu::setupPrefetchNdAnchorLayout(
436 layoutKind, tdescTy, numSgOrErr.value_or(0), uArch);
437 if (!layoutAttr) {
438 markWarning(prefetch,
439 "Failed to determine required layout for prefetch_nd.");
440 return;
441 }
442 prefetchLayout = layoutAttr;
443 anchorLayouts.emplace_back(prefetch.getLayoutAttrName(), layoutAttr);
444 }
445 // Propagate the layout to the source tensor descriptor.
446 operands[0] = prefetchLayout;
447}
448
449void LayoutPropagation::visitVectorMultiReductionOp(
450 vector::MultiDimReductionOp reduction, LayoutsMutRef operands,
451 LayoutsMutRef results) {
452 Type resultTy = reduction.getDestType();
453 // Vector reductions need a layout requested by a consumer; scalar reductions
454 // choose their own result layout.
455 xegpu::DistributeLayoutAttr consumerLayoutAttr;
456 if (!resultTy.isIntOrFloat()) {
457 consumerLayoutAttr = results[0];
458 if (!consumerLayoutAttr)
459 return;
460 }
461
462 VectorType sourceTy = reduction.getSourceVectorType();
463 SmallVector<int64_t> reductionDims(reduction.getReductionDims());
464
465 const auto *uArch =
466 xegpu::uArch::getUArch(xegpu::getChipStr(reduction).value_or(""));
467 if (!uArch)
468 return;
469
470 auto numSgOrErr =
471 getNumSgOrFail(reduction, uArch->getSubgroupSize(), consumerLayoutAttr);
472 if (failed(numSgOrErr))
473 return;
474
475 // Select a valid reduction layout; resolve consumer mismatches later.
476 auto requiredResLayoutAttr = xegpu::setupMultiReductionResultLayout(
477 layoutKind, sourceTy, consumerLayoutAttr, reductionDims,
478 numSgOrErr.value_or(0), uArch);
479
480 results[0] = requiredResLayoutAttr;
481
482 // derive the source layout from the dominant layout and reduction dims
483 auto srcLayoutAttr = xegpu::inferMultiReductionSourceLayout(
484 requiredResLayoutAttr, reductionDims);
485
486 operands[0] = srcLayoutAttr;
487 // Accumulator should have the same layout as the result.
488 operands[1] = requiredResLayoutAttr;
489}
490
491void LayoutPropagation::visitVectorReductionOp(vector::ReductionOp reduction,
492 LayoutsMutRef operands,
493 LayoutsMutRef results) {
494
495 VectorType sourceTy = reduction.getSourceVectorType();
496 const auto *uArch =
497 xegpu::uArch::getUArch(xegpu::getChipStr(reduction).value_or(""));
498 if (!uArch)
499 return;
500
501 auto requiredResLayoutAttr =
502 xegpu::setupReductionResultLayout(layoutKind, sourceTy, uArch);
503 results[0] = requiredResLayoutAttr;
504
505 auto srcLayoutAttr = xegpu::inferReductionSourceLayout(requiredResLayoutAttr);
506 operands[0] = srcLayoutAttr;
507 if (reduction.getAcc())
508 operands[1] = requiredResLayoutAttr;
509}
510
511void LayoutPropagation::visitVectorBroadCastOp(vector::BroadcastOp broadcast,
512 LayoutsMutRef operands,
513 LayoutsMutRef results) {
514 // The layout of the result must be present.
515 xegpu::DistributeLayoutAttr resultLayoutAttr = results[0];
516 if (!resultLayoutAttr)
517 return;
518
519 // Only consider vector to vector broadcasts for now.
520 VectorType resultTy = broadcast.getResultVectorType();
521 VectorType sourceTy = dyn_cast<VectorType>(broadcast.getSourceType());
522 // skip layout propagation for non-vector source operand.
523 if (!sourceTy)
524 return;
525
526 auto srcShape = sourceTy.getShape();
527 auto resShape = resultTy.getShape();
528
529 xegpu::DistributeLayoutAttr srcLayoutAttr =
530 xegpu::inferBroadcastSourceLayout(resultLayoutAttr, resShape, srcShape);
531
532 operands[0] = srcLayoutAttr;
533}
534
535void LayoutPropagation::visitShapeCastOp(vector::ShapeCastOp shapeCast,
536 LayoutsMutRef operands,
537 LayoutsMutRef results) {
538 // The layout of the result must be present.
539 xegpu::DistributeLayoutAttr resultLayoutAttr = results[0];
540 if (!resultLayoutAttr)
541 return;
542 ArrayRef<int64_t> resShape = shapeCast.getResultVectorType().getShape();
543 ArrayRef<int64_t> srcShape = shapeCast.getSourceVectorType().getShape();
544
545 auto requiredResLayoutAttr = xegpu::setupShapeCastResultLayout(
546 layoutKind, shapeCast.getSourceVectorType(),
547 shapeCast.getResultVectorType(), resultLayoutAttr);
548 // The consumer layout cannot be expressed on the source: no lane_data makes
549 // each lane's data a contiguous run of the collapsed source dim. shape_cast
550 // is not an anchor op, so warn and leave the value un-laid-out instead of
551 // propagating a layout that would move data between lanes.
552 if (!requiredResLayoutAttr) {
553 markWarning(shapeCast, "Failed to infer source layout for shape_cast; the "
554 "result layout required by its consumers cannot be "
555 "collapsed onto the source shape.");
556 return;
557 }
558 results[0] = requiredResLayoutAttr;
559
560 xegpu::DistributeLayoutAttr srcLayoutAttr = xegpu::inferShapeCastSourceLayout(
561 requiredResLayoutAttr, resShape, srcShape);
562 // shape_cast is not an anchor op: another consumer of the source value may
563 // still supply a valid layout, so warn instead of stopping the propagation.
564 if (!srcLayoutAttr) {
565 markWarning(shapeCast, "Failed to infer source layout for shape_cast; "
566 "unsupported shape-cast pattern.");
567 return;
568 }
569
570 operands[0] = srcLayoutAttr;
571}
572
573/// Set the layouts for DPAS A, B, and C operands.
574void LayoutPropagation::visitDpasOp(xegpu::DpasOp dpas, LayoutsMutRef operands,
575 LayoutsRef results,
576 AnchorLayouts &anchorLayouts) {
577 xegpu::DistributeLayoutAttr dpasALayout;
578 xegpu::DistributeLayoutAttr dpasBLayout;
579 xegpu::DistributeLayoutAttr dpasCDLayout;
580
581 const auto *uArch = xegpu::uArch::getUArch(getChipStr(dpas).value_or(""));
582 if (!uArch)
583 return;
584 VectorType aTy = dpas.getLhsType();
585 VectorType bTy = dpas.getRhsType();
586 VectorType cdTy = dpas.getResultType();
587
588 xegpu::DistributeLayoutAttr anchorLayoutCD = dpas.getLayoutCdAttr();
589 if (hasParamsOfLayoutKind(anchorLayoutCD)) {
590 xegpu::DistributeLayoutAttr anchorLayoutA = dpas.getLayoutAAttr();
591 xegpu::DistributeLayoutAttr anchorLayoutB = dpas.getLayoutBAttr();
592 assert(hasParamsOfLayoutKind(anchorLayoutA) &&
593 "Expected anchor layout for DPAS A operand.");
594 assert(hasParamsOfLayoutKind(anchorLayoutB) &&
595 "Expected anchor layout for DPAS B operand.");
596 dpasALayout = anchorLayoutA;
597 dpasBLayout = anchorLayoutB;
598 dpasCDLayout = anchorLayoutCD;
599 if (layoutKind == xegpu::LayoutKind::InstData) {
601 anchorLayoutA, anchorLayoutB, anchorLayoutCD, aTy, bTy, cdTy, uArch);
602 if (!completed) {
603 markFailure(
604 dpas,
605 "Failed to identify lane layouts for the specified inst_data.");
606 return;
607 }
608 auto [completedA, completedB, completedCD] = *completed;
609 anchorLayouts.emplace_back(dpas.getLayoutAAttrName(), completedA);
610 anchorLayouts.emplace_back(dpas.getLayoutBAttrName(), completedB);
611 anchorLayouts.emplace_back(dpas.getLayoutCdAttrName(), completedCD);
612 dpasALayout = completedA;
613 dpasBLayout = completedB;
614 dpasCDLayout = completedCD;
615 }
616 } else {
617 xegpu::DistributeLayoutAttr requiredCDLayoutAttr, requiredALayout,
618 requiredBLayout;
619
620 xegpu::DistributeLayoutAttr consumerLayoutAttr = results[0];
621 if (!consumerLayoutAttr)
622 return;
623
624 auto numSgOrErr =
625 getNumSgOrFail(dpas, uArch->getSubgroupSize(), consumerLayoutAttr);
626 if (failed(numSgOrErr))
627 return;
628
629 auto layouts =
630 xegpu::setupDpasLayout(layoutKind, aTy, bTy, cdTy, consumerLayoutAttr,
631 numSgOrErr.value_or(0), uArch);
632 if (!layouts.has_value()) {
633 markFailure(dpas,
634 "Failed to determine required layouts for DPAS operands.");
635 return;
636 }
637
638 std::tie(requiredALayout, requiredBLayout, requiredCDLayoutAttr) = *layouts;
639
640 anchorLayouts.emplace_back(dpas.getLayoutAAttrName(), requiredALayout);
641 anchorLayouts.emplace_back(dpas.getLayoutBAttrName(), requiredBLayout);
642 anchorLayouts.emplace_back(dpas.getLayoutCdAttrName(),
643 requiredCDLayoutAttr);
644 dpasALayout = requiredALayout;
645 dpasBLayout = requiredBLayout;
646 dpasCDLayout = requiredCDLayoutAttr;
647 }
648 operands[0] = dpasALayout;
649 operands[1] = dpasBLayout;
650 if (operands.size() > 2)
651 operands[2] = dpasCDLayout;
652}
653
654/// Propagate layout for DpasMxOp operands using the layout attributes.
655/// DpasMxOp has operands: a, b, acc (optional), scale_a (optional), scale_b
656/// (optional)
657void LayoutPropagation::visitDpasMxOp(xegpu::DpasMxOp dpasMx,
658 LayoutsMutRef operands,
659 LayoutsRef results,
660 AnchorLayouts &anchorLayouts) {
661
662 // Initialize layout variables
663 xegpu::DistributeLayoutAttr dpasMxALayout, dpasMxBLayout, dpasMxCDLayout;
664 xegpu::DistributeLayoutAttr dpasMxAScaleLayout, dpasMxBScaleLayout;
665
666 // Get existing layout attributes from the operation
667 xegpu::DistributeLayoutAttr anchorLayoutA = dpasMx.getLayoutAAttr();
668 xegpu::DistributeLayoutAttr anchorLayoutB = dpasMx.getLayoutBAttr();
669 xegpu::DistributeLayoutAttr anchorLayoutCD = dpasMx.getLayoutCdAttr();
670
671 const auto *uArch = xegpu::uArch::getUArch(getChipStr(dpasMx).value_or(""));
672 if (!uArch)
673 return;
674
675 VectorType aTy = dpasMx.getAType();
676 VectorType bTy = dpasMx.getBType();
677 VectorType cdTy = dpasMx.getResultType();
678
679 // Get scale types if present
680 VectorType aScaleTy;
681 VectorType bScaleTy;
682 Value scaleA = dpasMx.getScaleA();
683 Value scaleB = dpasMx.getScaleB();
684 if (scaleA)
685 aScaleTy = dyn_cast<VectorType>(scaleA.getType());
686 if (scaleB)
687 bScaleTy = dyn_cast<VectorType>(scaleB.getType());
688
689 // Check if all layouts are already set
690 if (anchorLayoutA && anchorLayoutB && anchorLayoutCD &&
691 hasParamsOfLayoutKind(anchorLayoutA) &&
692 hasParamsOfLayoutKind(anchorLayoutB) &&
693 hasParamsOfLayoutKind(anchorLayoutCD)) {
694 dpasMxALayout = anchorLayoutA;
695 dpasMxBLayout = anchorLayoutB;
696 dpasMxCDLayout = anchorLayoutCD;
697
698 // Get scale layouts if available
699 xegpu::DistributeLayoutAttr anchorLayoutAScale =
700 dpasMx.getLayoutAScaleAttr();
701 xegpu::DistributeLayoutAttr anchorLayoutBScale =
702 dpasMx.getLayoutBScaleAttr();
703 if (anchorLayoutAScale)
704 dpasMxAScaleLayout = anchorLayoutAScale;
705 if (anchorLayoutBScale)
706 dpasMxBScaleLayout = anchorLayoutBScale;
707
708 if (layoutKind == xegpu::LayoutKind::InstData) {
710 anchorLayoutA, anchorLayoutB, anchorLayoutCD, aTy, bTy, cdTy,
711 aScaleTy, bScaleTy, uArch);
712 if (!completed) {
713 markFailure(
714 dpasMx,
715 "Failed to identify lane layouts for the specified inst_data.");
716 return;
717 }
718 auto [completedA, completedB, completedCD, completedAScale,
719 completedBScale] = *completed;
720 anchorLayouts.emplace_back(dpasMx.getLayoutAAttrName(), completedA);
721 anchorLayouts.emplace_back(dpasMx.getLayoutBAttrName(), completedB);
722 anchorLayouts.emplace_back(dpasMx.getLayoutCdAttrName(), completedCD);
723 dpasMxALayout = completedA;
724 dpasMxBLayout = completedB;
725 dpasMxCDLayout = completedCD;
726 if (completedAScale) {
727 anchorLayouts.emplace_back(dpasMx.getLayoutAScaleAttrName(),
728 completedAScale);
729 dpasMxAScaleLayout = completedAScale;
730 }
731 if (completedBScale) {
732 anchorLayouts.emplace_back(dpasMx.getLayoutBScaleAttrName(),
733 completedBScale);
734 dpasMxBScaleLayout = completedBScale;
735 }
736 }
737 } else {
738 xegpu::DistributeLayoutAttr requiredCDLayoutAttr, requiredALayout,
739 requiredBLayout, requiredAScaleLayout, requiredBScaleLayout;
740
741 xegpu::DistributeLayoutAttr consumerLayoutAttr = results[0];
742 if (!consumerLayoutAttr)
743 return;
744
745 auto numSgOrErr =
746 getNumSgOrFail(dpasMx, uArch->getSubgroupSize(), consumerLayoutAttr);
747 if (failed(numSgOrErr))
748 return;
749
750 auto layouts = xegpu::setupDpasMxLayout(
751 layoutKind, aTy, bTy, cdTy, aScaleTy, bScaleTy, consumerLayoutAttr,
752 numSgOrErr.value_or(0), uArch);
753 if (!layouts.has_value()) {
754 markFailure(dpasMx,
755 "Failed to determine required layouts for DPAS_MX operands.");
756 return;
757 }
758
759 std::tie(requiredALayout, requiredBLayout, requiredCDLayoutAttr,
760 requiredAScaleLayout, requiredBScaleLayout) = *layouts;
761
762 anchorLayouts.emplace_back(dpasMx.getLayoutAAttrName(), requiredALayout);
763 anchorLayouts.emplace_back(dpasMx.getLayoutBAttrName(), requiredBLayout);
764 anchorLayouts.emplace_back(dpasMx.getLayoutCdAttrName(),
765 requiredCDLayoutAttr);
766 if (requiredAScaleLayout)
767 anchorLayouts.emplace_back(dpasMx.getLayoutAScaleAttrName(),
768 requiredAScaleLayout);
769 if (requiredBScaleLayout)
770 anchorLayouts.emplace_back(dpasMx.getLayoutBScaleAttrName(),
771 requiredBScaleLayout);
772
773 dpasMxALayout = requiredALayout;
774 dpasMxBLayout = requiredBLayout;
775 dpasMxCDLayout = requiredCDLayoutAttr;
776 if (requiredAScaleLayout)
777 dpasMxAScaleLayout = requiredAScaleLayout;
778 if (requiredBScaleLayout)
779 dpasMxBScaleLayout = requiredBScaleLayout;
780 }
781
782 // Propagate layouts to operands. Because acc, scale_a, scale_b are all
783 // optional (AttrSizedOperandSegments), the index of each present operand in
784 // `operands` depends on which optionals are actually supplied. Use the
785 // op's accessors to determine the correct positional index.
786 operands[0] = dpasMxALayout;
787 operands[1] = dpasMxBLayout;
788 unsigned idx = 2;
789 if (dpasMx.getAcc()) {
790 operands[idx] = dpasMxCDLayout;
791 ++idx;
792 }
793 if (dpasMx.getScaleA()) {
794 if (dpasMxAScaleLayout)
795 operands[idx] = dpasMxAScaleLayout;
796 ++idx;
797 }
798 if (dpasMx.getScaleB()) {
799 if (dpasMxBScaleLayout)
800 operands[idx] = dpasMxBScaleLayout;
801 ++idx;
802 }
803}
804
805/// Set the layout for the value and tensor descriptor operands in StoreNdOp.
806void LayoutPropagation::visitStoreNdOp(xegpu::StoreNdOp store,
807 LayoutsMutRef operands,
808 LayoutsRef results,
809 AnchorLayouts &anchorLayouts) {
810 xegpu::DistributeLayoutAttr storeLayout;
811 const auto *uArch = xegpu::uArch::getUArch(getChipStr(store).value_or(""));
812 if (!uArch)
813 return;
814 xegpu::DistributeLayoutAttr anchorLayout = store.getLayoutAttr();
815 if (hasParamsOfLayoutKind(anchorLayout)) {
816 storeLayout = anchorLayout;
817 if (layoutKind == xegpu::LayoutKind::InstData) {
818
819 const auto *uArchInstruction =
820 dyn_cast<xegpu::uArch::Subgroup2DBlockStoreInstruction>(
821 uArch->getInstruction(
822 xegpu::uArch::InstructionKind::Subgroup2DBlockStore));
823 if (!uArchInstruction)
824 return;
826 anchorLayout, store.getValueType().getElementType(), uArchInstruction,
827 uArch->getSubgroupSize());
828 if (!completed) {
829 markFailure(
830 store,
831 "Failed to identify lane layouts for the specified inst_data.");
832 return;
833 }
834 anchorLayouts.emplace_back(store.getLayoutAttrName(), *completed);
835 storeLayout = *completed;
836 }
837 } else {
838 auto numSgOrErr = getNumSgOrFail(store, uArch->getSubgroupSize(), nullptr);
839 if (failed(numSgOrErr))
840 return;
841
842 auto layoutAttr = xegpu::setupStoreNdAnchorLayout(
843 layoutKind, store.getValueType(), numSgOrErr.value_or(0), uArch);
844 if (!layoutAttr) {
845 markFailure(store, "Failed to determine required layout for store_nd.");
846 return;
847 }
848 storeLayout = layoutAttr;
849 anchorLayouts.emplace_back(store.getLayoutAttrName(), layoutAttr);
850 }
851 // Propagate the layout to the value operand.
852 // Both operands should have the same layout
853 for (xegpu::DistributeLayoutAttr &operand : operands)
854 operand = storeLayout;
855}
856
857/// Propagate the layout of the value to the tensor descriptor operand in
858/// LoadNdOp.
859void LayoutPropagation::visitLoadNdOp(xegpu::LoadNdOp load,
860 LayoutsMutRef operands,
861 LayoutsRef results,
862 AnchorLayouts &anchorLayouts) {
863 xegpu::DistributeLayoutAttr loadLayout;
864
865 const auto *uArch = xegpu::uArch::getUArch(getChipStr(load).value_or(""));
866 if (!uArch)
867 return;
868 xegpu::DistributeLayoutAttr consumerLayoutAttr = results[0];
869 xegpu::DistributeLayoutAttr anchorLayout = load.getLayoutAttr();
870 if (hasParamsOfLayoutKind(anchorLayout)) {
871 loadLayout = anchorLayout;
872 if (layoutKind == xegpu::LayoutKind::InstData && consumerLayoutAttr &&
873 !consumerLayoutAttr.getEffectiveLaneLayoutAsInt().empty()) {
874 const auto *uArchInstruction =
875 dyn_cast<xegpu::uArch::Subgroup2DBlockLoadInstruction>(
876 uArch->getInstruction(
877 xegpu::uArch::InstructionKind::Subgroup2DBlockLoad));
878 if (!uArchInstruction)
879 return;
881 anchorLayout, consumerLayoutAttr, load.getType().getElementType(),
882 uArchInstruction, uArch->getSubgroupSize());
883 if (!completed) {
884 markWarning(
885 load,
886 "Failed to identify lane layouts for the specified inst_data.");
887 return;
888 }
889 anchorLayouts.emplace_back(load.getLayoutAttrName(), *completed);
890 loadLayout = *completed;
891 }
892 } else {
893 auto numSgOrErr =
894 getNumSgOrFail(load, uArch->getSubgroupSize(), consumerLayoutAttr);
895 if (failed(numSgOrErr))
896 return;
897 auto layoutAttr = xegpu::setupLoadNdAnchorLayout(
898 layoutKind, load.getType(), consumerLayoutAttr, numSgOrErr.value_or(0),
899 uArch);
900 if (!layoutAttr) {
901 markWarning(load, "Failed to determine required layout for load_nd.");
902 return;
903 }
904 loadLayout = layoutAttr;
905 anchorLayouts.emplace_back(load.getLayoutAttrName(), layoutAttr);
906 }
907 // Propagate the new layout to the tensor descriptor operand.
908 operands[0] = loadLayout;
909}
910
911/// Propagate the layout of the value to the tensor descriptor operand in
912/// ConvertLayoutOp.
913void LayoutPropagation::visitConvertLayoutOp(xegpu::ConvertLayoutOp convert,
914 LayoutsMutRef operands,
915 LayoutsMutRef results) {
916
917 // TODO: fix if one of the layouts is a slice layout
918 auto targetLayoutAttr =
919 dyn_cast<xegpu::LayoutAttr>(convert.getTargetLayoutAttr());
920 // input_layout is optional, so it may be null.
921 auto inputLayoutAttr =
922 dyn_cast_if_present<xegpu::LayoutAttr>(convert.getInputLayoutAttr());
923
924 // The result's propagated layout is authoritative for the converted value.
925 // Fill the lane_layout / lane_data / order parameters the target_layout is
926 // missing from it (sg_layout / sg_data / inst_data are left as-is), so the
927 // target stays consistent with what is actually propagated downstream.
928 auto resultLayoutAttr = dyn_cast_if_present<xegpu::LayoutAttr>(results[0]);
929 if (resultLayoutAttr && targetLayoutAttr) {
930 if (layoutKind == xegpu::LayoutKind::InstData &&
931 !targetLayoutAttr.getLaneLayout()) {
932 targetLayoutAttr = xegpu::LayoutAttr::get(
933 convert.getContext(), targetLayoutAttr.getSgLayout(),
934 targetLayoutAttr.getSgData(), targetLayoutAttr.getInstData(),
935 resultLayoutAttr.getLaneLayout(), resultLayoutAttr.getLaneData(),
936 resultLayoutAttr.getOrder());
937 convert.setTargetLayoutAttr(targetLayoutAttr);
938 }
939 }
940
941 // Fill only the lane_layout / lane_data / order parameters the input_layout
942 // is missing from the target_layout (sg_layout / sg_data / inst_data are left
943 // as-is), so the producer side receives a fully-populated lane layout.
944 if (inputLayoutAttr && targetLayoutAttr) {
945 if (layoutKind == xegpu::LayoutKind::InstData &&
946 !inputLayoutAttr.getLaneLayout()) {
947 auto merged = xegpu::LayoutAttr::get(
948 convert.getContext(), inputLayoutAttr.getSgLayout(),
949 inputLayoutAttr.getSgData(), inputLayoutAttr.getInstData(),
950 targetLayoutAttr.getLaneLayout(), targetLayoutAttr.getLaneData(),
951 targetLayoutAttr.getOrder());
952 convert.setInputLayoutAttr(merged);
953 }
954 }
955
956 // Propagate the effective input layout to the source operand.
957 operands[0] = convert.getEffectiveInputLayout();
958}
959
960/// For vector::TransposeOp, the layout of the result is transposed and
961/// propagated to the operand.
962void LayoutPropagation::visitTransposeOp(vector::TransposeOp transpose,
963 LayoutsMutRef operands,
964 LayoutsMutRef results) {
965 // Need the layout of transpose result to propagate to the operands.
966 xegpu::DistributeLayoutAttr consumerLayoutAttr = results[0];
967 if (!consumerLayoutAttr)
968 return;
969 auto srcLayoutAttr = xegpu::inferTransposeSourceLayout(
970 consumerLayoutAttr, transpose.getPermutation());
971
972 // Propagate the new layout to the vector operand.
973 operands[0] = srcLayoutAttr;
974}
975
976/// For vector::BitCastOp, the lane_data of the source layout is changed based
977/// on the bit width of the source and result types.
978void LayoutPropagation::visitVectorBitcastOp(vector::BitCastOp bitcast,
979 LayoutsMutRef operands,
980 LayoutsMutRef results) {
981 // Need the layout of bitcast result to propagate to the operands.
982 xegpu::DistributeLayoutAttr consumerLayoutAttr = results[0];
983 if (!consumerLayoutAttr)
984 return;
985
986 auto srcVecType = bitcast.getSourceVectorType();
987 auto resVecType = bitcast.getResultVectorType();
988 const auto *uArch =
989 xegpu::uArch::getUArch(xegpu::getChipStr(bitcast).value_or(""));
990 if (!uArch)
991 return;
992 auto requiredResLayoutAttr = setupBitCastResultLayout(
993 layoutKind, srcVecType, resVecType, consumerLayoutAttr, uArch);
994
995 results[0] = requiredResLayoutAttr;
996
997 int inElemTyBitWidth = srcVecType.getElementType().getIntOrFloatBitWidth();
998 int outElemTyBitWidth = resVecType.getElementType().getIntOrFloatBitWidth();
999
1000 // derive the source layout from the dominant layout and reduction dims
1001 auto srcLayoutAttr = xegpu::inferBitCastSourceLayout(
1002 requiredResLayoutAttr, outElemTyBitWidth, inElemTyBitWidth);
1003
1004 operands[0] = srcLayoutAttr;
1005}
1006
1007/// For vector::InterleaveOp, the result has double the innermost dimension
1008/// size compared to each source operand. The layout is propagated from result
1009/// to sources, adjusting for the 2x size increase.
1010void LayoutPropagation::visitVectorInterleaveOp(vector::InterleaveOp interleave,
1011 LayoutsMutRef operands,
1012 LayoutsMutRef results) {
1013 // Need the layout of interleave result to propagate to the operands.
1014 xegpu::DistributeLayoutAttr consumerLayoutAttr = results[0];
1015 if (!consumerLayoutAttr)
1016 return;
1017
1018 auto srcVecType = interleave.getSourceVectorType();
1019 auto resVecType = interleave.getResultVectorType();
1020 const auto *uArch =
1021 xegpu::uArch::getUArch(xegpu::getChipStr(interleave).value_or(""));
1022 if (!uArch)
1023 return;
1024
1025 // Setup the result layout to ensure the source layout can be safely derived
1026 auto requiredResLayoutAttr = setupInterleaveResultLayout(
1027 layoutKind, srcVecType, resVecType, consumerLayoutAttr, uArch);
1028
1029 results[0] = requiredResLayoutAttr;
1030
1031 // Derive the source layout from the result layout (halve the innermost dim)
1032 auto srcLayoutAttr =
1033 xegpu::inferInterleaveSourceLayout(requiredResLayoutAttr);
1034
1035 // Both operands (lhs and rhs) get the same source layout
1036 operands[0] = srcLayoutAttr;
1037 operands[1] = srcLayoutAttr;
1038}
1039
1040/// For vector::DeinterleaveOp, the source has double the innermost dimension
1041/// size compared to each result. The layout is propagated from results to
1042/// source, adjusting for the 2x size decrease in results.
1043void LayoutPropagation::visitVectorDeinterleaveOp(
1044 vector::DeinterleaveOp deinterleave, LayoutsMutRef operands,
1045 LayoutsMutRef results) {
1046 // Need the layout of deinterleave results to propagate to the operand.
1047 // Use the first result's layout (both results should have the same layout)
1048 xegpu::DistributeLayoutAttr consumerLayoutAttr = results[0];
1049 if (!consumerLayoutAttr)
1050 return;
1051
1052 // Derive the source layout from the result layout (double the innermost
1053 // dim) No setup function needed - just infer directly
1054 auto srcLayoutAttr = xegpu::inferDeinterleaveSourceLayout(consumerLayoutAttr);
1055
1056 operands[0] = srcLayoutAttr;
1057}
1058
1059void LayoutPropagation::visitInsertStridedSliceOp(
1060 vector::InsertStridedSliceOp insertStridedSlice, LayoutsMutRef operands,
1061 LayoutsMutRef results) {
1062 // The layout of the result must be present.
1063 xegpu::DistributeLayoutAttr consumerLayoutAttr = results[0];
1064 if (!consumerLayoutAttr)
1065 return;
1066
1067 auto srcVecType = insertStridedSlice.getSourceVectorType();
1068 auto resVecType = insertStridedSlice.getDestVectorType();
1069 const auto *uArch = xegpu::uArch::getUArch(
1070 xegpu::getChipStr(insertStridedSlice).value_or(""));
1071 if (!uArch)
1072 return;
1073
1074 auto requiredResLayoutAttr = xegpu::setupInsertStridedSliceResultLayout(
1075 layoutKind, srcVecType, resVecType, consumerLayoutAttr, uArch);
1076 results[0] = requiredResLayoutAttr;
1077
1078 auto srcLayoutAttr = xegpu::inferInsertStridedSliceSourceLayout(
1079 requiredResLayoutAttr, resVecType.getShape(), srcVecType.getShape());
1080 operands[0] = srcLayoutAttr;
1081 operands[1] = requiredResLayoutAttr;
1082}
1083
1084/// Propagate the layout of the result to the tensor descriptor, mask and
1085/// offset operands in LoadGatherOp.
1086void LayoutPropagation::visitLoadGatherOp(xegpu::LoadGatherOp load,
1087 LayoutsMutRef operands,
1088 LayoutsRef results,
1089 AnchorLayouts &anchorLayouts) {
1090 xegpu::DistributeLayoutAttr requiredAnchorLayoutAttr;
1091 xegpu::DistributeLayoutAttr anchorLayoutAttr = load.getLayoutAttr();
1092 const auto *uArch = xegpu::uArch::getUArch(getChipStr(load).value_or(""));
1093 if (!uArch)
1094 return;
1095 VectorType resVecTy = load.getValueType();
1096 // `contiguity` says how many neighbouring elements one lane may take in a
1097 // single access. Absent, only one element per lane is safe.
1098 int contigChunkSize = load.getContiguity().value_or(1);
1099
1100 xegpu::DistributeLayoutAttr consumerLayoutAttr = results[0];
1101 if (hasParamsOfLayoutKind(anchorLayoutAttr)) {
1102 requiredAnchorLayoutAttr = anchorLayoutAttr;
1103 if (layoutKind == xegpu::LayoutKind::InstData && consumerLayoutAttr &&
1104 !consumerLayoutAttr.getEffectiveLaneLayoutAsInt().empty()) {
1105 const auto uArchInstruction =
1106 dyn_cast<xegpu::uArch::LoadGatherInstruction>(
1107 uArch->getInstruction(xegpu::uArch::InstructionKind::LoadGather));
1108 if (!uArchInstruction)
1109 return;
1111 anchorLayoutAttr, consumerLayoutAttr, resVecTy.getElementType(),
1112 uArchInstruction, uArch->getSubgroupSize());
1113 if (!completed) {
1114 markWarning(
1115 load,
1116 "Failed to identify lane layouts for the specified inst_data.");
1117 return;
1118 }
1119 requiredAnchorLayoutAttr = *completed;
1120 anchorLayouts.emplace_back(load.getLayoutAttrName(),
1121 requiredAnchorLayoutAttr);
1122 }
1123 } else if (!resVecTy) {
1124 markWarning(load, "Not propagating, non-vector payload supplied.");
1125 return;
1126 } else {
1127 auto numSgOrErr =
1128 getNumSgOrFail(load, uArch->getSubgroupSize(), consumerLayoutAttr);
1129 if (failed(numSgOrErr))
1130 return;
1131 requiredAnchorLayoutAttr = xegpu::setupLoadGatherAnchorLayout(
1132 layoutKind, resVecTy, contigChunkSize, consumerLayoutAttr,
1133 numSgOrErr.value_or(0), uArch);
1134 if (!requiredAnchorLayoutAttr) {
1135 markWarning(load, "Failed to determine required layout for load_gather.");
1136 return;
1137 }
1138 anchorLayouts.emplace_back(load.getLayoutAttrName(),
1139 requiredAnchorLayoutAttr);
1140 }
1141
1142 // Propagate the new layout to the tensor descriptor operand.
1143 if (isa<xegpu::TensorDescType>(load.getSourceType()))
1144 operands[0] = requiredAnchorLayoutAttr;
1145 // The offset and mask operands share the value's anchor layout.
1146 operands[1] = requiredAnchorLayoutAttr;
1147 operands[2] = requiredAnchorLayoutAttr;
1148}
1149
1150/// Set the layout for the value, tensor descriptor, offset and mask operands
1151/// in the StoreScatterOp.
1152void LayoutPropagation::visitStoreScatterOp(xegpu::StoreScatterOp storeScatter,
1153 LayoutsMutRef operands,
1154 LayoutsRef results,
1155 AnchorLayouts &anchorLayouts) {
1156
1157 xegpu::DistributeLayoutAttr requiredAnchorLayoutAttr;
1158 xegpu::DistributeLayoutAttr anchorLayoutAttr = storeScatter.getLayoutAttr();
1159 const auto *uArch =
1160 xegpu::uArch::getUArch(getChipStr(storeScatter).value_or(""));
1161 if (!uArch)
1162 return;
1163 VectorType srcVecTy = storeScatter.getValueType();
1164 // `contiguity` says how many neighbouring elements one lane may write in a
1165 // single access. Absent, only one element per lane is safe.
1166 int contigChunkSize = storeScatter.getContiguity().value_or(1);
1167
1168 if (hasParamsOfLayoutKind(anchorLayoutAttr)) {
1169 requiredAnchorLayoutAttr = anchorLayoutAttr;
1170 if (layoutKind == xegpu::LayoutKind::InstData) {
1171 const auto uArchInstruction =
1172 dyn_cast<xegpu::uArch::StoreScatterInstruction>(uArch->getInstruction(
1173 xegpu::uArch::InstructionKind::StoreScatter));
1174 if (!uArchInstruction)
1175 return;
1177 anchorLayoutAttr, srcVecTy.getElementType(), uArchInstruction,
1178 uArch->getSubgroupSize());
1179 if (!completed) {
1180 markFailure(
1181 storeScatter,
1182 "Failed to identify lane layouts for the specified inst_data.");
1183 return;
1184 }
1185 requiredAnchorLayoutAttr = *completed;
1186 anchorLayouts.emplace_back(storeScatter.getLayoutAttrName(),
1187 requiredAnchorLayoutAttr);
1188 }
1189 } else {
1190 if (!srcVecTy) {
1191 markWarning(storeScatter,
1192 "Not propagating, non-vector payload supplied.");
1193 return;
1194 }
1195 auto numSgOrErr =
1196 getNumSgOrFail(storeScatter, uArch->getSubgroupSize(), nullptr);
1197 if (failed(numSgOrErr))
1198 return;
1199 requiredAnchorLayoutAttr = xegpu::setupStoreScatterAnchorLayout(
1200 layoutKind, srcVecTy, contigChunkSize, numSgOrErr.value_or(0), uArch);
1201 if (!requiredAnchorLayoutAttr) {
1202 markFailure(storeScatter,
1203 "Failed to determine required layout for store scatter.");
1204 return;
1205 }
1206 anchorLayouts.emplace_back(storeScatter.getLayoutAttrName(),
1207 requiredAnchorLayoutAttr);
1208 }
1209
1210 // Propagate the payload operand layout
1211 operands[0] = requiredAnchorLayoutAttr;
1212 // Propagate the destination (if tdesc) operand layout
1213 if (isa<xegpu::TensorDescType>(storeScatter.getDestType()))
1214 operands[1] = requiredAnchorLayoutAttr;
1215 // The offset and mask operands share the value's anchor layout.
1216 operands[2] = requiredAnchorLayoutAttr;
1217 operands[3] = requiredAnchorLayoutAttr;
1218}
1219
1220void LayoutPropagation::visitLoadMatrixOp(xegpu::LoadMatrixOp loadMatrixOp,
1221 LayoutsMutRef operands,
1222 LayoutsRef results,
1223 AnchorLayouts &anchorLayouts) {
1224
1225 xegpu::DistributeLayoutAttr consumerLayoutAttr = results[0];
1226 xegpu::DistributeLayoutAttr anchorLayout = loadMatrixOp.getLayoutAttr();
1227
1228 // only need to set anchor layout, no need to porpagate to memdesc and
1229 // offset
1230 if (!hasParamsOfLayoutKind(anchorLayout)) {
1231 VectorType resVecTy =
1232 llvm::cast<VectorType>(loadMatrixOp.getRes().getType());
1233 const auto *uArch =
1234 xegpu::uArch::getUArch(getChipStr(loadMatrixOp).value_or(""));
1235 if (!uArch)
1236 return;
1237 int chunkSize =
1238 1; // placeHolder for future use when LoadMatrix supports coalescing
1239 auto numSgOrErr = getNumSgOrFail(loadMatrixOp, uArch->getSubgroupSize(),
1240 consumerLayoutAttr);
1241 if (failed(numSgOrErr))
1242 return;
1243 auto requiredAnchorLayoutAttr = xegpu::setupLoadMatrixAnchorLayout(
1244 layoutKind, resVecTy, chunkSize, consumerLayoutAttr,
1245 numSgOrErr.value_or(0), uArch);
1246 if (!requiredAnchorLayoutAttr) {
1247 markWarning(loadMatrixOp,
1248 "Failed to determine required layout for load_matrix.");
1249 return;
1250 }
1251 anchorLayouts.emplace_back(loadMatrixOp.getLayoutAttrName(),
1252 requiredAnchorLayoutAttr);
1253 }
1254}
1255
1256void LayoutPropagation::visitStoreMatrixOp(xegpu::StoreMatrixOp storeMatrix,
1257 LayoutsMutRef operands,
1258 LayoutsRef results,
1259 AnchorLayouts &anchorLayouts) {
1260 xegpu::DistributeLayoutAttr requiredAnchorLayoutAttr;
1261 xegpu::DistributeLayoutAttr anchorLayoutAttr = storeMatrix.getLayoutAttr();
1262 VectorType srcVecTy = llvm::cast<VectorType>(storeMatrix.getData().getType());
1263 const auto *uArch =
1264 xegpu::uArch::getUArch(getChipStr(storeMatrix).value_or(""));
1265 if (!uArch)
1266 return;
1267 if (hasParamsOfLayoutKind(anchorLayoutAttr)) {
1268 requiredAnchorLayoutAttr = anchorLayoutAttr;
1269 if (layoutKind == xegpu::LayoutKind::InstData) {
1270 const auto uArchInstruction =
1271 dyn_cast<xegpu::uArch::StoreScatterInstruction>(uArch->getInstruction(
1272 xegpu::uArch::InstructionKind::StoreScatter));
1273 if (!uArchInstruction)
1274 return;
1276 anchorLayoutAttr, srcVecTy.getElementType(), uArchInstruction,
1277 uArch->getSubgroupSize());
1278 if (!completed) {
1279 markFailure(
1280 storeMatrix,
1281 "Failed to identify lane layouts for the specified inst_data.");
1282 return;
1283 }
1284 requiredAnchorLayoutAttr = *completed;
1285 anchorLayouts.emplace_back(storeMatrix.getLayoutAttrName(),
1286 requiredAnchorLayoutAttr);
1287 }
1288 } else {
1289 int chunkSize =
1290 1; // placeHolder for future use when StoreMatrix supports coalescing
1291 auto numSgOrErr =
1292 getNumSgOrFail(storeMatrix, uArch->getSubgroupSize(), nullptr);
1293 if (failed(numSgOrErr))
1294 return;
1295 requiredAnchorLayoutAttr = xegpu::setupStoreMatrixAnchorLayout(
1296 layoutKind, srcVecTy, chunkSize, numSgOrErr.value_or(0), uArch);
1297 if (!requiredAnchorLayoutAttr) {
1298 markFailure(storeMatrix,
1299 "Failed to determine required layout for store matrix.");
1300 return;
1301 }
1302 anchorLayouts.emplace_back(storeMatrix.getLayoutAttrName(),
1303 requiredAnchorLayoutAttr);
1304 }
1305 operands[0] = requiredAnchorLayoutAttr;
1306}
1307
1308//===----------------------------------------------------------------------===//
1309// LayoutPropagation: backward scan
1310//===----------------------------------------------------------------------===//
1311
1312/// Writes the decisions of the walk into the IR. anchorDecisions honours the
1313/// user's input: an anchor layout given in the input IR is not recorded there,
1314/// so it stays as the user wrote it. If that layout is incomplete (it has
1315/// inst_data but no lane layout), anchorDecisions carries the completed
1316/// layout, which keeps the user's inst_data and adds the lane layout derived
1317/// from the consumer's request.
1318void LayoutPropagation::commitDecisions() {
1319 for (auto &[op, layouts] : anchorDecisions) {
1320 for (auto [name, layout] : layouts) {
1321 if (layout)
1322 op->setAttr(name, layout);
1323 else
1324 op->removeAttr(name);
1325 }
1326 }
1327 for (auto [operand, layout] : operandDecisions)
1328 xegpu::setTemporaryLayout(*operand, layout);
1329 for (auto [value, layout] : valueDecisions) {
1330 if (isa<xegpu::TensorDescType>(value.getType()))
1331 xegpu::setTensorDescLayout(value, layout);
1332 else if (auto result = dyn_cast<OpResult>(value))
1334 }
1335}
1336
1337LogicalResult LayoutPropagation::emitPendingDiagnostics() {
1338 bool failed = false;
1339 for (auto &[op, diagnostics] : pendingDiagnostics) {
1340 for (const PendingDiagnostic &diag : diagnostics) {
1341 if (diag.severity == DiagnosticSeverity::Error) {
1342 op->emitError(diag.message);
1343 failed = true;
1344 } else {
1345 op->emitWarning(diag.message);
1346 }
1347 }
1348 }
1349 return failure(failed);
1350}
1351
1352LogicalResult LayoutPropagation::run() {
1353 xegpu::walkBackward(scopeRoot, *this);
1354 return emitPendingDiagnostics();
1355}
1356
1357void LayoutPropagation::visitRegularOp(Operation *op) {
1358 pendingDiagnostics.erase(op);
1359 SmallVector<xegpu::DistributeLayoutAttr> resultLayouts =
1360 llvm::map_to_vector(op->getResults(), [&](Value result) {
1361 return getRequestedLayout(result);
1362 });
1363 SmallVector<xegpu::DistributeLayoutAttr> operandLayouts(op->getNumOperands());
1364 AnchorLayouts anchorLayouts;
1365 visitOperation(op, operandLayouts, resultLayouts, anchorLayouts);
1366
1367 for (auto [operand, layout] :
1368 llvm::zip_equal(op->getOperands(), operandLayouts))
1369 recordRequestedLayout(operand, layout);
1370
1371 if (isa<xegpu::AnchorLayoutInterface>(op)) {
1372 setAnchorDecision(op, std::move(anchorLayouts));
1373 return;
1374 }
1375 // Scalar reductions also need a result layout: conflict resolution uses it
1376 // to derive operand layouts and insert an anchor convert_layout.
1377 for (auto [result, layout] :
1378 llvm::zip_equal(op->getResults(), resultLayouts)) {
1379 if (isa<xegpu::TensorDescType, VectorType>(result.getType()) ||
1380 isa<vector::MultiDimReductionOp, vector::ReductionOp>(op))
1381 setValueDecision(result, layout);
1382 }
1383}
1384
1385void LayoutPropagation::visitTerminator(
1386 RegionBranchTerminatorOpInterface terminator) {
1387 pendingDiagnostics.erase(terminator);
1388 auto regionOp = cast<RegionBranchOpInterface>(terminator->getParentOp());
1390 regionOp.getSuccessorOperandInputMapping(mapping,
1391 RegionBranchPoint(terminator));
1392 // As in layout recovery, each operand takes the layout requested for the
1393 // value it feeds. For scf.condition, the after region has not been visited,
1394 // so only the parent's requested result layout is known.
1396 terminator, [&](Value val) { return getRequestedLayout(val); },
1397 [&](OpOperand &operand, xegpu::DistributeLayoutAttr layout) {
1398 setOperandDecision(operand, layout);
1399 });
1400 for (OpOperand &operand : llvm::reverse(terminator->getOpOperands()))
1401 recordRequestedLayout(operand.get(), getOperandDecision(operand));
1402
1403 for (const auto &[successorOperand, successorInputs] : mapping) {
1404 // Layout lookup for scf.while's after arguments follows pass-through
1405 // before arguments to their tied init operands.
1406 auto loop = dyn_cast<LoopLikeOpInterface>(regionOp.getOperation());
1407 for (auto arg : llvm::make_isa_range<BlockArgument>(successorInputs)) {
1408 if (isa<VectorType>(arg.getType()) &&
1409 !(loop && loop.getTiedLoopInit(arg)) &&
1410 !isa<BlockArgument>(successorOperand->get())) {
1411 markFailure(terminator,
1412 "unsupported region structure: the successor argument it "
1413 "feeds is not tied to an init operand, so its value must "
1414 "be passed through from predecessor region argument.");
1415 }
1416 }
1417 }
1418}
1419
1420/// Returns true when a region argument of `regionOp` now has a requested
1421/// layout that differs from the layout given to the terminator operand that
1422/// feeds it. The walk visits the terminator before the ops that read the
1423/// argument, so the terminator could not see their request. Walking the
1424/// regions again lets the terminator, and the ops before it, use the request.
1425bool LayoutPropagation::shouldRevisitRegions(RegionBranchOpInterface regionOp) {
1426 for (Region &region : regionOp->getRegions()) {
1427 for (Block &block : region) {
1428 auto terminator =
1429 dyn_cast<RegionBranchTerminatorOpInterface>(block.getTerminator());
1430 if (!terminator)
1431 continue;
1433 regionOp.getSuccessorOperandInputMapping(mapping,
1434 RegionBranchPoint(terminator));
1435 // operand: a terminator operand.
1436 for (const auto &[operand, inputs] : mapping) {
1437 if (!xegpu::isLayoutCarrierType(operand->get().getType()))
1438 continue;
1439 // arg: the region argument it feeds.
1440 for (auto arg : llvm::make_isa_range<BlockArgument>(inputs)) {
1441 if (arg.getOwner()->getParentOp() != regionOp.getOperation())
1442 continue;
1443 xegpu::DistributeLayoutAttr requested = getRequestedLayout(arg);
1444 xegpu::DistributeLayoutAttr given = getOperandDecision(*operand);
1445 if (requested && (!given || !given.isEqualTo(requested)))
1446 return true;
1447 }
1448 }
1449 }
1450 }
1451 return false;
1452}
1453
1454void LayoutPropagation::visitRegionOp(RegionBranchOpInterface regionOp) {
1455 // Propagate layouts requested for region arguments to init operands. The
1456 // region results are filled by the forward pass.
1458 regionOp, [&](Value val) { return getRequestedLayout(val); },
1459 [&](OpOperand &operand, xegpu::DistributeLayoutAttr layout) {
1460 setOperandDecision(operand, layout);
1461 },
1462 [&](BlockArgument arg, xegpu::DistributeLayoutAttr layout) {
1463 setValueDecision(arg, layout);
1464 });
1465 for (OpOperand &operand : llvm::reverse(regionOp->getOpOperands()))
1466 recordRequestedLayout(operand.get(), getOperandDecision(operand));
1467}
1468
1469void LayoutPropagation::print(llvm::raw_ostream &os) {
1470 auto printLayout = [&](Value val) {
1471 if (xegpu::DistributeLayoutAttr layout = getRequestedLayout(val))
1472 os << layout;
1473 else
1474 os << "Not assigned.";
1475 os << "\n";
1476 };
1477 auto printFunctionResult = [&](FunctionOpInterface funcOp) {
1478 os << "function: " << funcOp.getName() << ":\n";
1479 for (BlockArgument arg : funcOp.getArguments()) {
1480 os << "argument: " << arg << "\n";
1481 os << "layout : ";
1482 printLayout(arg);
1483 }
1484 funcOp.walk([&](Operation *op) {
1485 if (op->getResults().empty())
1486 return;
1487 os << "op : ";
1488 // For control-flow ops, print the op name only.
1489 if (isa<BranchOpInterface, RegionBranchOpInterface>(op))
1490 os << op->getName();
1491 else
1492 op->print(os);
1493 os << "\n";
1494 for (auto [i, r] : llvm::enumerate(op->getResults())) {
1495 os << "layout for result #" << i << ": ";
1496 printLayout(r);
1497 }
1498 });
1499 };
1500
1501 auto modOp = dyn_cast<ModuleOp>(scopeRoot);
1502 if (!modOp)
1503 return;
1504 for (auto funcOp : modOp.getOps<FunctionOpInterface>())
1505 printFunctionResult(funcOp);
1506 for (auto gpuModOp : modOp.getOps<gpu::GPUModuleOp>())
1507 for (auto gpuFuncOp : gpuModOp.getOps<FunctionOpInterface>())
1508 printFunctionResult(gpuFuncOp);
1509}
1510
1511namespace {
1512//===----------------------------------------------------------------------===//
1513// ResolveLayoutConflicts
1514//===----------------------------------------------------------------------===//
1515
1516/// Helper to get the defining CreateNdDescOp of a tensor descriptor value.
1517/// This function tries to find the defining CreateNdDescOp recursively
1518/// accross control-flow boundaries.
1519static xegpu::CreateNdDescOp getDefiningCreateNdDescOp(Value tdescValue) {
1520 // Try to get the defining CreateNdDescOp of the tensor descriptor.
1521 auto definingOp = tdescValue.getDefiningOp<xegpu::CreateNdDescOp>();
1522 if (definingOp)
1523 return definingOp;
1524 // If tdescValue is an argument, try to get the tied init value from the
1525 // parent loop-like op.
1526 if (auto arg = dyn_cast<BlockArgument>(tdescValue)) {
1527 auto *parentOp = arg.getOwner()->getParentOp();
1528 if (auto loop = dyn_cast<LoopLikeOpInterface>(parentOp)) {
1529 OpOperand *tiedInit = loop.getTiedLoopInit(arg);
1530 if (tiedInit)
1531 return getDefiningCreateNdDescOp(tiedInit->get());
1532 }
1533 }
1534 // If not found, return null.
1535 return nullptr;
1536}
1537
1538struct ResolveLayoutConflicts {
1539 ResolveLayoutConflicts(Operation *parentOp)
1540 : parentOp(parentOp), builder(parentOp->getContext()) {}
1541 LogicalResult run();
1542
1543private:
1544 Operation *parentOp;
1545 OpBuilder builder;
1546 LogicalResult resolveTensorDescConsumer(OpOperand &operand);
1547 LogicalResult resolveVectorConsumer(OpOperand &operand);
1548 LogicalResult assignResultLayout(OpResult &result);
1549};
1550} // namespace
1551
1552LogicalResult ResolveLayoutConflicts::run() {
1553 // Scan all operations in the parent op and resolve layout conflicts at
1554 // tensor descriptor and vector use points.
1555 auto r = parentOp->walk([&](Operation *op) -> WalkResult {
1556 for (OpResult result : op->getResults()) {
1557 // if the operation inputs vector and output scalar, like multi-reduction
1558 // we need to check if the result has layout and add a convert_layout to
1559 // serve as anchor op for the reduction op's layout.
1560 if (result.getType().isIntOrFloat() &&
1561 (isa<vector::MultiDimReductionOp>(op) ||
1562 isa<vector::ReductionOp>(op))) {
1563 auto res = assignResultLayout(result);
1564 if (failed(res)) {
1565 DBGS() << "Failed to assign layout for scalar consumer of reduction "
1566 << *op << "\n";
1567 return WalkResult::interrupt();
1568 }
1569 }
1570 // If the op is a region branch op with a vector result that has no uses,
1571 // we need to add a convert_layout to serve as an anchor op for the
1572 // result's layout.
1573 if (isa<VectorType>(result.getType()) && result.use_empty() &&
1574 isa<RegionBranchOpInterface>(op)) {
1575 auto res = assignResultLayout(result);
1576 if (failed(res)) {
1577 DBGS() << "Failed to assign layout for vector consumer of region op "
1578 << *op << "\n";
1579 return WalkResult::interrupt();
1580 }
1581 }
1582 }
1583 for (OpOperand &operand : op->getOpOperands()) {
1584 // Handle conflicts in tensor descriptor operands.
1585 Type operandType = operand.get().getType();
1586 if (isa<xegpu::AnchorLayoutInterface>(op) &&
1587 isa<xegpu::TensorDescType>(operandType)) {
1588 auto res = resolveTensorDescConsumer(operand);
1589 if (failed(res)) {
1590 DBGS() << "Failed to resolve tensor descriptor consumer: " << *op
1591 << "\n";
1592 return WalkResult::interrupt();
1593 }
1594 }
1595 // Handle conflicts in vector operands.
1596 if (isa<VectorType>(operandType)) {
1597 auto res = resolveVectorConsumer(operand);
1598 if (failed(res)) {
1599 DBGS() << "Failed to resolve vector consumer: " << *op << "\n";
1600 return WalkResult::interrupt();
1601 }
1602 }
1603 }
1604 return WalkResult::advance();
1605 });
1606
1607 if (r.wasInterrupted())
1608 return failure();
1609
1610 LLVM_DEBUG({
1611 DBGS() << "IR after resolving layout conflicts:\n";
1612 parentOp->dump();
1613 });
1614
1615 return success();
1616}
1617
1618LogicalResult ResolveLayoutConflicts::assignResultLayout(OpResult &result) {
1619 Operation *producerOp = result.getDefiningOp();
1620 auto producerLayout = xegpu::getDistributeLayoutAttr(result);
1621 // Insert a convert_layout op to assign the layout.
1623 auto convertOp = xegpu::ConvertLayoutOp::create(
1624 builder, producerOp->getLoc(), result.getType(), result, producerLayout,
1625 producerLayout);
1626 result.replaceAllUsesExcept(convertOp.getResult(), convertOp);
1627 return success();
1628}
1629
1630LogicalResult
1631ResolveLayoutConflicts::resolveVectorConsumer(OpOperand &operand) {
1632 Value vectorValue = operand.get();
1633 Operation *consumerOp = operand.getOwner();
1634 // Get the current layout of the vector value.
1635 auto producerLayout = xegpu::getDistributeLayoutAttr(vectorValue);
1636 if (!producerLayout) {
1637 if (auto vectorTy = dyn_cast<VectorType>(vectorValue.getType());
1638 vectorTy && vectorTy.getRank() > 1)
1639 consumerOp->emitWarning("Expected layout for non-1D vectors.");
1640 return success(); // uniform non-tensor-data vector does not require
1641 // layout
1642 }
1643 // getConsumerLayoutAt also covers region-carried operands (loop init and
1644 // yield operands), so a layout conflict there is reconciled below rather than
1645 // silently trusted to region forwarding.
1646 auto consumerLayout = xegpu::getConsumerLayoutAt(operand);
1647 if (!consumerLayout) {
1648 if (isa<func::ReturnOp>(consumerOp) || isa<gpu::ReturnOp>(consumerOp))
1649 return success();
1650 return consumerOp->emitError(
1651 "No consumer layout found for vector operand.");
1652 }
1653
1654 // If layouts are same, no conflict exists, return success.
1655 if (consumerLayout.isEqualTo(producerLayout))
1656 return success();
1657
1658 // Consumer is a convert_layout: retarget its input_layout to the producer
1659 // instead of chaining a second convert. Always safe (single source
1660 // operand).
1661 if (auto consumerConvert = dyn_cast<xegpu::ConvertLayoutOp>(consumerOp)) {
1662 consumerConvert.setInputLayoutAttr(producerLayout);
1663 return success();
1664 }
1665
1666 // Producer is a convert_layout feeding only this use: retarget its
1667 // target_layout to the consumer instead of appending another convert.
1668 if (auto producerConvert =
1669 vectorValue.getDefiningOp<xegpu::ConvertLayoutOp>();
1670 producerConvert && vectorValue.hasOneUse()) {
1671 // Pin the effective input before retargeting target, else an omitted
1672 // input_layout would follow target and make the conversion a no-op.
1673 producerConvert.setInputLayoutAttr(
1674 producerConvert.getEffectiveInputLayout());
1675 producerConvert.setTargetLayoutAttr(consumerLayout);
1676 return success();
1677 }
1678
1679 // Insert a convert_layout op to resolve the conflict.
1680 builder.setInsertionPointAfterValue(vectorValue);
1681 auto convertOp = xegpu::ConvertLayoutOp::create(
1682 builder, consumerOp->getLoc(), vectorValue.getType(), vectorValue,
1683 producerLayout, consumerLayout);
1684
1685 // Update the operand to use the converted value.
1686 operand.set(convertOp.getResult());
1687 return success();
1688}
1689
1690LogicalResult
1691ResolveLayoutConflicts::resolveTensorDescConsumer(OpOperand &operand) {
1692 Operation *consumerOp = operand.getOwner();
1693 Value tdescValue = operand.get();
1694 auto anchorOp = dyn_cast<xegpu::AnchorLayoutInterface>(consumerOp);
1695 auto currTDescType = dyn_cast<xegpu::TensorDescType>(tdescValue.getType());
1696 assert(anchorOp && currTDescType &&
1697 "Expected anchor layout op and tensor descriptor consumer.");
1698 Attribute currLayout = currTDescType.getLayout();
1699 Attribute expectedLayout = anchorOp.getAnchorLayout();
1700 // A conflict exists in tensor descriptor operand if tensor descriptor's
1701 // layout is different from the anchor layout expected by the consumer.
1702 if (expectedLayout && currLayout && expectedLayout != currLayout) {
1703 // Try to get the defining CreateNdDescOp of the tensor descriptor.
1704 auto conflictingCreateNdOp = getDefiningCreateNdDescOp(tdescValue);
1705 if (!conflictingCreateNdOp) {
1706 DBGS() << "Unable to find defining CreateNdDescOp for tensor descriptor: "
1707 << tdescValue << "\n";
1708 return failure();
1709 }
1710 // Duplicate the CreateNdDescOp with the expected layout.
1711 builder.setInsertionPointAfter(conflictingCreateNdOp);
1712 auto newTensorDescType = xegpu::TensorDescType::get(
1713 conflictingCreateNdOp.getContext(), currTDescType.getShape(),
1714 currTDescType.getElementType(), currTDescType.getEncoding(),
1715 expectedLayout);
1716 auto newOp = xegpu::CreateNdDescOp::create(
1717 builder, consumerOp->getLoc(), TypeRange{newTensorDescType},
1718 conflictingCreateNdOp->getOperands(),
1719 conflictingCreateNdOp.getProperties(),
1720 conflictingCreateNdOp->getDiscardableAttrDictionary().getValue());
1721 // Replace the tensor descriptor operand in the consumer op with the new
1722 // tensor descriptor.
1723 consumerOp->replaceUsesOfWith(tdescValue, newOp.getResult());
1724 }
1725 return success();
1726}
1727
1728using GetLayoutFnTy = function_ref<xegpu::DistributeLayoutAttr(Value)>;
1729
1730/// Update an operation with the layout of its results. For a vector result a
1731/// temporary layout attribute is added to the op; for a tensor descriptor
1732/// result the layout is written into its type.
1733///
1734/// If the global propagation left a result without a layout, forward-fill it
1735/// locally from the operand layouts.
1736static LogicalResult forwardFillRegularOp(mlir::OpBuilder &builder,
1737 mlir::Operation *op,
1738 GetLayoutFnTy getLayoutOfValue) {
1739 // Iterate over all the results.
1740 for (OpResult result : op->getResults()) {
1741 Type resultType = result.getType();
1742 // Layouts are needed only for vector and tensor descriptor types.
1743 if (!xegpu::isLayoutCarrierType(resultType))
1744 continue;
1745 xegpu::DistributeLayoutAttr layout = getLayoutOfValue(result);
1746 if (!layout) {
1747 // Gather operand layouts, indexed by operand number.
1749 srcLayouts.reserve(op->getNumOperands());
1750 bool anyAssigned = false;
1751 for (Value operand : op->getOperands()) {
1752 auto srclayout = xegpu::getDistributeLayoutAttr(operand);
1753 srcLayouts.push_back(srclayout);
1754 anyAssigned |= (srclayout != nullptr);
1755 }
1756 if (anyAssigned) {
1757 layout =
1759 }
1760 }
1761 if (!layout && result.getNumUses() > 0) {
1762 op->emitWarning("op has users but no layout assigned for its result");
1763 }
1764 // If the result is a tensor descriptor type, update the tensor desc type
1765 // with layout.
1766 if (isa<xegpu::TensorDescType>(resultType)) {
1768 continue;
1769 }
1770 // If the result is a vector type, add a temporary layout attribute to the
1771 // op.
1773 }
1774 return success();
1775}
1776
1777/// Replace layout conversions of cheap producer chains by recomputation.
1778///
1779/// %step = vector.step {L1}
1780/// %cast = arith.index_castui %step {L1}
1781/// %cvt = xegpu.convert_layout %cast : L1 -> L2
1782/// use(%cast) {L1}
1783/// use(%cvt) {L2}
1784///
1785/// becomes
1786///
1787/// %step = vector.step {L1}
1788/// %step' = vector.step
1789/// %cast = arith.index_castui %step {L1}
1790/// %cast' = arith.index_castui %step'
1791/// use(%cast) {L1}
1792/// use(%cast') {L2}
1793///
1794/// Clone the whole vector producer chain so the original and rematerialized
1795/// values can serve consumers with different layouts. Clones carry no layout
1796/// attributes; layout-dependent passes recover them from the use points. For
1797/// small, layout-preserving chains, recomputation can avoid cross-subgroup data
1798/// movement through SLM.
1800 Operation *parentOp) {
1802 parentOp->walk(
1803 [&](xegpu::ConvertLayoutOp convert) { conversions.push_back(convert); });
1804 for (xegpu::ConvertLayoutOp convert : conversions) {
1805 Value clone = xegpu::rematerialize(builder, convert.getSource());
1806 if (!clone)
1807 continue;
1808 convert.getResult().replaceAllUsesWith(clone);
1809 convert.erase();
1810 }
1811}
1812
1813/// Optimize elementwise operations by sinking costly layout conversion.
1814///
1815/// %m = vector.create_mask ... {L1}
1816/// %d = arith.mulf ... {L1}
1817/// %cm = xegpu.convert_layout %m : L1 -> L2
1818/// %cd = xegpu.convert_layout %d : L1 -> L2
1819/// %s = arith.select %cm, %cd, %splat {L2}
1820///
1821/// becomes
1822///
1823/// %s' = arith.select %m, %d, %splat {L1}
1824/// %s = xegpu.convert_layout %s' : L1 -> L2
1825///
1826/// We only sink if a coarser layout applies to an elementwise op
1827///
1829 Operation *parentOp) {
1830 llvm::SmallSetVector<xegpu::ConvertLayoutOp, 8> deadConverts;
1831 parentOp->walk([&](Operation *op) {
1833 return;
1834 OpResult result = op->getResult(0);
1835 if (!isa<VectorType>(result.getType()))
1836 return;
1837 xegpu::DistributeLayoutAttr resultLayout =
1839 if (!resultLayout)
1840 return;
1841
1842 // Ensure that all feeding conversions have the same layout.
1844 xegpu::DistributeLayoutAttr uniformConvSrcLayout;
1845 for (OpOperand &operand : op->getOpOperands()) {
1846 Value operandValue = operand.get();
1847 if (!isa<VectorType>(operandValue.getType()))
1848 continue;
1849 auto operandConversionOp =
1850 operandValue.getDefiningOp<xegpu::ConvertLayoutOp>();
1851 // Those that are not a conversion should be easily materializable with
1852 // another layout.
1853 if (!operandConversionOp) {
1854 Operation *definingOp = operandValue.getDefiningOp();
1855 if (!definingOp || !xegpu::isTriviallyRematerializable(definingOp))
1856 return;
1857 continue;
1858 }
1859 xegpu::DistributeLayoutAttr input =
1860 operandConversionOp.getEffectiveInputLayout();
1861 if (!input)
1862 return;
1863 if (!uniformConvSrcLayout)
1864 uniformConvSrcLayout = input;
1865 else if (!uniformConvSrcLayout.isEqualTo(input))
1866 return;
1867 conversions.emplace_back(&operand, operandConversionOp);
1868 }
1869
1870 if (!uniformConvSrcLayout)
1871 return;
1872
1873 // Sink only when it leaves the op coarser.
1874 // Conversion's source layout must be larger than the elemwise result
1875 // layout.
1876 SmallVector<int64_t> resultLayoutInstData =
1877 resultLayout.getEffectiveInstDataAsInt();
1878 SmallVector<int64_t> sourceInstData =
1879 uniformConvSrcLayout.getEffectiveInstDataAsInt();
1880 if (resultLayoutInstData.empty() || sourceInstData.empty() ||
1881 computeProduct(sourceInstData) <= computeProduct(resultLayoutInstData))
1882 return;
1883
1884 // Rewire the conversions, then rematerialize the remaining operands in the
1885 // source layout.
1886 llvm::SmallDenseSet<unsigned> rewiredOpIdxs;
1887 for (auto [operand, convert] : conversions) {
1888 operand->set(convert.getSource());
1889 rewiredOpIdxs.insert(operand->getOperandNumber());
1890 }
1891 for (OpOperand &operand : op->getOpOperands()) {
1892 Value operandValue = operand.get();
1893 if (!isa<VectorType>(operandValue.getType()))
1894 continue;
1895 if (rewiredOpIdxs.contains(operand.getOperandNumber()))
1896 continue;
1897 Operation *definingOp = operandValue.getDefiningOp();
1898 assert(definingOp && xegpu::isTriviallyRematerializable(definingOp) &&
1899 "operand should have been rejected above");
1900 // Rematerialize with uniform source layout.
1901 builder.setInsertionPointAfter(definingOp);
1902 Operation *clone = builder.clone(*definingOp);
1903 OpResult cloneResult =
1904 clone->getResult(cast<OpResult>(operandValue).getResultNumber());
1905 xegpu::removeLayoutAttr(cloneResult);
1906 xegpu::setDistributeLayoutAttr(cloneResult, uniformConvSrcLayout);
1907 operand.set(cloneResult);
1908 }
1909
1910 // Run the op in the source layout and bridge its result back, so that
1911 // `getConsumerLayoutAt` now reports the source layout for every operand.
1913 auto newConvOp = xegpu::ConvertLayoutOp::create(
1914 builder, op->getLoc(), result.getType(), result, uniformConvSrcLayout,
1915 resultLayout);
1916 result.replaceAllUsesExcept(newConvOp.getResult(), newConvOp);
1918 xegpu::setDistributeLayoutAttr(result, uniformConvSrcLayout);
1919
1920 for (auto [operand, convert] : conversions)
1921 if (convert.getResult().use_empty())
1922 deadConverts.insert(convert);
1923 });
1924
1925 // Memory effects block dce
1926 for (xegpu::ConvertLayoutOp convert : deadConverts)
1927 convert.erase();
1928}
1929
1930namespace {
1931struct XeGPUPropagateLayoutPass final
1932 : public xegpu::impl::XeGPUPropagateLayoutBase<XeGPUPropagateLayoutPass> {
1933 XeGPUPropagateLayoutPass() = default;
1934 XeGPUPropagateLayoutPass(const XeGPUPropagateLayoutPass &other) = default;
1935 XeGPUPropagateLayoutPass(xegpu::XeGPUPropagateLayoutOptions options)
1936 : XeGPUPropagateLayoutBase(std::move(options)) {}
1937 void runOnOperation() override;
1938};
1939} // namespace
1940
1941/// Give each init operand of a loop without a layout decided for it the layout
1942/// of its init value: the region argument it feeds is bound to that value.
1943static void forwardInitsToRegionArgs(RegionBranchOpInterface regionOp,
1944 GetLayoutFnTy getLayoutOfValue) {
1945 auto loop = dyn_cast<LoopLikeOpInterface>(regionOp.getOperation());
1946 if (!loop)
1947 return;
1948 for (OpOperand &init : loop.getInitsMutable()) {
1949 if (!isa<VectorType>(init.get().getType()) ||
1951 continue;
1952 if (xegpu::DistributeLayoutAttr layout = getLayoutOfValue(init.get()))
1953 xegpu::setTemporaryLayout(init, layout);
1954 }
1955}
1956
1957/// Assign each region result the layout of the terminator operand forwarded
1958/// to it. Fails if a forwarded vector operand has no layout.
1960 RegionBranchTerminatorOpInterface terminator,
1961 GetLayoutFnTy getLayoutOfValue) {
1962 // Only process if the terminator is inside a region branch op.
1963 auto branchOp = dyn_cast<RegionBranchOpInterface>(terminator->getParentOp());
1964 if (!branchOp)
1965 return success();
1966
1968 branchOp.getSuccessorOperandInputMapping(mapping,
1969 RegionBranchPoint(terminator));
1970 for (const auto &[successorOperand, successorInputs] : mapping) {
1971 for (Value successorInput : successorInputs) {
1972 // We only need to operate on vector types.
1973 if (!isa<VectorType>(successorInput.getType()))
1974 continue;
1975 xegpu::DistributeLayoutAttr successorOperandLayout =
1976 xegpu::getTemporaryLayout(*successorOperand);
1977 // Without a layout decided for the operand, use the layout that forward
1978 // filling has just found for the forwarded value.
1979 if (!successorOperandLayout)
1980 successorOperandLayout = getLayoutOfValue(successorOperand->get());
1981 // The forwarded operand must carry a layout to propagate.
1982 if (!successorOperandLayout)
1983 return failure();
1984 // Assign the yield operand's layout to the region op result it feeds.
1985 if (auto result = dyn_cast<OpResult>(successorInput))
1986 xegpu::setDistributeLayoutAttr(result, successorOperandLayout);
1987 }
1988 }
1989 return success();
1990}
1991
1992static LogicalResult updateFunctionOpInterface(mlir::OpBuilder &builder,
1993 mlir::FunctionOpInterface funcOp,
1994 GetLayoutFnTy getLayoutOfValue) {
1995 // Only process functions whose type is a standard MLIR FunctionType.
1996 // Functions using a different type representation (e.g. llvm.func with
1997 // LLVMFunctionType) are not targets for XeGPU layout propagation, and
1998 // calling setType(FunctionType{}) on them would corrupt their type.
1999 if (!isa<FunctionType>(funcOp.getFunctionType()))
2000 return success();
2001 SmallVector<Type> newArgTypes;
2002 // Update the function arguments.
2003 for (BlockArgument arg : funcOp.getArguments()) {
2004 Type argType = arg.getType();
2005 newArgTypes.push_back(argType);
2006 if (!xegpu::isLayoutCarrierType(argType))
2007 continue;
2008 xegpu::DistributeLayoutAttr layout = getLayoutOfValue(arg);
2009 if (!layout) {
2010 LLVM_DEBUG(DBGS() << "Expecting layout for function argument: " << arg
2011 << " but got none.\n");
2012 return failure();
2013 }
2014 if (isa<xegpu::TensorDescType>(argType)) {
2015 xegpu::setTensorDescLayout(arg, layout);
2016 newArgTypes.back() = arg.getType();
2017 }
2018 }
2019 // Update the function type with the new argument types.
2020 // NOTE: We assume that function results are not expected to have layouts.
2021 funcOp.setType(FunctionType::get(funcOp.getContext(), newArgTypes,
2022 funcOp.getResultTypes()));
2023 return success();
2024}
2025
2026/// Fill the layouts the backward scan leaves to the forward pass, in program
2027/// order: the results of an op from its operand layouts, the region results
2028/// from the terminator operands forwarded to them, and the function
2029/// signatures.
2030static LogicalResult
2032 GetLayoutFnTy getLayoutOfValue) {
2033 // Pre-order: a region op is visited before its regions, so its init
2034 // operands are filled before the ops that use the region arguments.
2035 WalkResult walkResult =
2036 target->walk<WalkOrder::PreOrder>([&](Operation *op) -> WalkResult {
2037 if (op == target)
2038 return WalkResult::advance();
2039 LogicalResult r = success();
2041 .Case([&](RegionBranchTerminatorOpInterface terminator) {
2043 getLayoutOfValue);
2044 })
2045 .Case([&](FunctionOpInterface funcOp) {
2046 r = updateFunctionOpInterface(builder, funcOp, getLayoutOfValue);
2047 })
2048 .Case([&](RegionBranchOpInterface regionOp) {
2049 forwardInitsToRegionArgs(regionOp, getLayoutOfValue);
2050 })
2051 .Default([&](Operation *op) {
2052 r = forwardFillRegularOp(builder, op, getLayoutOfValue);
2053 });
2054 if (failed(r)) {
2055 op->emitError("Failed to update operation with the layout.");
2056 return WalkResult::interrupt();
2057 }
2058 return WalkResult::advance();
2059 });
2060 return failure(walkResult.wasInterrupted());
2061}
2062
2064 LayoutKind layoutKind,
2065 unsigned /*indexBitWidth*/,
2066 bool printOnly) {
2067 LayoutPropagation propagation(target, layoutKind);
2068 LogicalResult result = propagation.run();
2069 // Print the analysis result (for debugging purposes), or stop on a fatal
2070 // error; either way, leave the IR unchanged.
2071 if (printOnly || failed(result)) {
2072 if (printOnly)
2073 propagation.print(llvm::outs());
2074 return result;
2075 }
2076 // Write the decisions into the IR now that no visit can revise them.
2077 propagation.commitDecisions();
2078 // Prefer the producer layout in the IR. Fall back to the requested layout
2079 // for values without one, such as vector function arguments.
2081 builder, target, [&](Value val) -> xegpu::DistributeLayoutAttr {
2082 if (xegpu::DistributeLayoutAttr layout =
2084 return layout;
2085 return propagation.getRequestedLayout(val);
2086 });
2087}
2088
2090 ResolveLayoutConflicts resolver(target);
2091 return resolver.run();
2092}
2093
2094void XeGPUPropagateLayoutPass::runOnOperation() {
2095
2096 xegpu::removeTemporaryLayoutAttrs(getOperation());
2097
2098 xegpu::LayoutKind layoutKind;
2099 if (this->layoutKind == "lane") {
2100 layoutKind = xegpu::LayoutKind::Lane;
2101 } else if (this->layoutKind == "inst") {
2102 layoutKind = xegpu::LayoutKind::InstData;
2103 } else if (this->layoutKind == "subgroup") {
2104 layoutKind = xegpu::LayoutKind::Subgroup;
2105 } else {
2106 getOperation()->emitError("Unsupported layout kind option: " +
2107 this->layoutKind);
2108 signalPassFailure();
2109 return;
2110 }
2111 OpBuilder builder(&getContext());
2112 if (failed(xegpu::propagateLayouts(builder, getOperation(), layoutKind,
2113 this->indexBitWidth, this->printOnly))) {
2114 signalPassFailure();
2115 return;
2116 }
2117 // Resolve layout conflicts if any.
2118 if (failed(xegpu::resolveLayoutConflicts(getOperation()))) {
2119 signalPassFailure();
2120 return;
2121 }
2122 xegpu::rematerializeConversionSources(builder, getOperation());
2123 if (layoutKind == xegpu::LayoutKind::InstData)
2124 xegpu::sinkElementwiseConversions(builder, getOperation());
2125}
return success()
#define DBGS()
Definition Hoisting.cpp:34
b getContext())
auto load
static llvm::ManagedStatic< PassManagerOptions > options
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
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 LogicalResult forwardFillUnassignedLayouts(OpBuilder &builder, Operation *target, GetLayoutFnTy getLayoutOfValue)
Fill the layouts the backward scan leaves to the forward pass, in program order: the results of an op...
static LogicalResult forwardYieldOperandsToRegionResults(RegionBranchTerminatorOpInterface terminator, GetLayoutFnTy getLayoutOfValue)
Assign each region result the layout of the terminator operand forwarded to it.
function_ref< xegpu::DistributeLayoutAttr(Value)> GetLayoutFnTy
static void forwardInitsToRegionArgs(RegionBranchOpInterface regionOp, GetLayoutFnTy getLayoutOfValue)
Give each init operand of a loop without a layout decided for it the layout of its init value: the re...
static LogicalResult forwardFillRegularOp(mlir::OpBuilder &builder, mlir::Operation *op, GetLayoutFnTy getLayoutOfValue)
Update an operation with the layout of its results.
static LogicalResult updateFunctionOpInterface(mlir::OpBuilder &builder, mlir::FunctionOpInterface funcOp, GetLayoutFnTy getLayoutOfValue)
This class represents an argument of a Block.
Definition Value.h:308
Block * getOwner() const
Returns the block that owns this argument.
Definition Value.h:317
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
IRValueT get() const
Return the current value being used by this operand.
void set(IRValueT newValue)
Set the current value being used by this operand.
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 setInsertionPointAfterValue(Value val)
Sets the insertion point to the node after the specified value.
Definition Builders.h:424
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
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
void replaceUsesOfWith(Value from, Value to)
Replace any uses of 'from' with 'to' within this operation.
InFlightDiagnostic emitWarning(const Twine &message={})
Emit a warning about this operation, reporting up to any diagnostic handlers that may be listening.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
LLVM_DUMP_METHOD void dump()
MutableArrayRef< OpOperand > getOpOperands()
Definition Operation.h:410
unsigned getNumOperands()
Definition Operation.h:373
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
void setAttr(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
Definition Operation.h:636
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
void print(raw_ostream &os, const OpPrintingFlags &flags={})
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
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
result_range getResults()
Definition Operation.h:442
Attribute removeAttr(StringAttr name)
Remove the attribute with the specified name if it exists.
Definition Operation.h:654
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.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
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
bool hasOneUse() const
Returns true if this value has exactly one use.
Definition Value.h:197
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
A utility result that is used to signal how to proceed with an ongoing walk:
Definition WalkResult.h:29
static WalkResult advance()
Definition WalkResult.h:47
bool wasInterrupted() const
Returns true if the walk was interrupted.
Definition WalkResult.h:51
static WalkResult interrupt()
Definition WalkResult.h:46
Operation * getOwner() const
Return the owner of this operand.
Definition UseDefLists.h:38
Callbacks for walkBackward.
bool hasElementwiseMappableTraits(Operation *op)
Together, Elementwise, Scalarizable, Vectorizable, and Tensorizable provide an easy way for scalar op...
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
const uArch * getUArch(llvm::StringRef archName)
Definition uArchCommon.h:24
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,...
void sinkElementwiseConversions(OpBuilder &builder, Operation *target)
Sink xegpu.convert_layout ops past the elementwise operations they feed, so that an elementwise op ru...
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...
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
void setDistributeLayoutAttr(const OpResult &Result, const DistributeLayoutAttr layout)
[to-be-deprecated] Sets the DistributeLayoutAttr for a given OpResult user should use setAnchorLayout...
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.
FailureOr< int64_t > getNumSubgroupsFromBlockSize(Operation *op, int64_t subgroupSize)
Returns the number of subgroups the kernel enclosing op runs, derived from the known_block_size of it...
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:
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...
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.
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.
DistributeLayoutAttr setupPrefetchNdAnchorLayout(LayoutKind layoutKind, TensorDescType tdescTy, int numSg, const uArch::uArch *uArch)
Sets up the anchor layout for a prefetch_nd operation.
LogicalResult resolveLayoutConflicts(Operation *target)
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...
std::optional< std::string > getChipStr(Operation *op)
Retrieves the chip string from the XeVM target attribute of the parent GPU module operation.
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)...
DistributeLayoutAttr getTemporaryLayout(const T &operandOrResult)
get and set distribute layout attribute for non-anchor operations (and offsets/masks of load/store op...
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.
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.
LogicalResult propagateLayouts(OpBuilder &builder, Operation *target, LayoutKind layoutKind, unsigned indexBitWidth, bool printOnly=false)
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.
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).
void rematerializeConversionSources(OpBuilder &builder, Operation *target)
Replace layout conversions of cheap producer chains by recomputation.
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.
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
Definition Diagnostics.h:41
int64_t computeProduct(ArrayRef< int64_t > basis)
Self-explicit.
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147
Operation * clone(OpBuilder &b, Operation *op, TypeRange newResultTypes, ValueRange newOperands)
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155