MLIR 24.0.0git
mlir::xegpu Namespace Reference

Namespaces

namespace  detail
namespace  uArch

Classes

class  BackwardLayoutVisitor
 Callbacks for walkBackward. More...
struct  UnrollOptions
 Options to control the XeGPU unrolling. More...

Typedefs

using GetLayoutFnTy = llvm::function_ref<DistributeLayoutAttr(Value)>
 Callable returning the propagated layout for a given Value, used by the layout-propagation helpers below.
using SetOperandLayoutFnTy
 The region helpers below choose layouts and pass each one to a callback; the caller decides when it reaches the IR.
using SetTDescArgLayoutFnTy
 Called with the layout chosen for a tensor_desc region argument (e.g.
using SubShapeAndCountFn
 Callback type for computing sub-shape and count for 1:N (or 1:1 shape-changing) VectorType conversion.

Enumerations

enum class  LayoutKind { Lane , InstData , Subgroup }
 Specifies the level of a layout hierarchy for comparison or propagation. More...

Functions

void registerTransformDialectExtension (DialectRegistry &registry)
void populateXeGPUPeepHoleOptimizerPatterns (RewritePatternSet &patterns)
 Appends patterns for optimizing block load operations into patterns.
void populateXeGPUArrayLengthOptimizationPatterns (RewritePatternSet &patterns)
 Appends patterns for array length optimization into patterns.
void populateXeGPUSubgroupDistributePatterns (RewritePatternSet &patterns)
 Appends patterns for XeGPU SIMT distribution into patterns.
void populateXeGPUMoveFuncBodyToWarpOpPatterns (RewritePatternSet &patterns)
 Appends patterns for moving function body into gpu.warp_execute_on_lane0 op.
void populateXeGPUWgToSgDistributeTypeConversions (TypeConverter &converter, Operation *topLevelOp)
 Define the type conversions needed for XeGPU workgroup to subgroup distribution.
void populateXeGPUWgToSgDistributePatterns (RewritePatternSet &patterns)
 Appends patterns for XeGPU workgroup to subgroup distribution into patterns.
void populateXeGPUSgToLaneDistributeTypeConversions (TypeConverter &typeConverter, Operation *topLevelOp)
 Define only the type conversions needed for XeGPU subgroup to lane distribution.
void populateXeGPUSgToLaneDistributeTypeConversionAndLegality (TypeConverter &typeConverter, RewritePatternSet &patterns, ConversionTarget &target, Operation *topLevelOp)
 Defines type conversions and legality for XeGPU subgroup to lane distribution and appends the required conversion patterns into patterns.
void runContiguityAnalysis (Operation *root)
 Run the AxisInfo-based contiguity analysis over root and stamp a contiguity attribute on every xegpu.load / xegpu.store whose offsets are contiguous (in runs of >= 2) along the innermost dimension.
void populateXeGPUUnrollPatterns (RewritePatternSet &patterns, const UnrollOptions &options)
 Collect a set of patterns to unroll xegpu operations to a smaller shapes.
LogicalResult propagateLayouts (OpBuilder &builder, Operation *target, LayoutKind layoutKind, unsigned indexBitWidth, bool printOnly=false)
LogicalResult resolveLayoutConflicts (Operation *target)
void rematerializeConversionSources (OpBuilder &builder, Operation *target)
 Replace layout conversions of cheap producer chains by recomputation.
void sinkElementwiseConversions (OpBuilder &builder, Operation *target)
 Sink xegpu.convert_layout ops past the elementwise operations they feed, so that an elementwise op runs in the coarser 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.
void propagateRegionResultsToYieldOperands (RegionBranchTerminatorOpInterface terminator, GetLayoutFnTy getLayoutOfValue, SetOperandLayoutFnTy setOperandLayout)
 Propagate layouts to the operands of a region branch terminator: each operand gets, via getLayoutOfValue, the layout of the region argument it feeds, or else of the region result it feeds, recorded via setOperandLayout.
void walkBackward (Operation *root, BackwardLayoutVisitor &visitor)
 Walk function bodies under root in CFG post-order, visiting ops within each block back to front and nested regions before their parent op.
bool recoverTemporaryLayouts (Operation *rootOp)
 Attach layout attributes to all vector-type operands of operations within the given operation's nested region.
template<typename T, typename = std::enable_if_t<std::is_same_v<T, OpOperand> || std::is_same_v<T, OpResult>>>
void removeLayoutAttr (const T &operandOrResult)
 Removes the LayoutAttr for a given OpOperand or OpResult if it exists.
void removeLayoutAttrs (Operation *op)
 Removes the DistributeLayoutAttr for each OpOperand and OpResult of the given operation if they exist.
void removeTemporaryLayoutAttrs (Operation *op)
 Removes the temporary layout attributes for each OpOperand and OpResult of the given operation.
SmallVector< NamedAttribute > dropSgLayoutAndDataOnAttrs (ArrayRef< NamedAttribute > attrs)
 Updates the NamedAttribute sequence by dropping sg-layout and sg-data information from any DistributeLayoutAttr found.
SmallVector< NamedAttribute > dropInstDataOnAttrs (ArrayRef< NamedAttribute > attrs)
 Updates the NamedAttribute sequence by dropping inst-data information from any DistributeLayoutAttr found.
void dropInstDataOnInherentAttrs (Operation *op)
 Drops inst-data information from DistributeLayoutAttrs stored as inherent attributes on the operation.
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, result shape, and source shape.
DistributeLayoutAttr inferMultiReductionSourceLayout (DistributeLayoutAttr resLayout, SmallVector< int64_t > reduceDims)
 Infers the source layout attribute for a reduction operation given the result layout attribute and reduced dims.
DistributeLayoutAttr inferReductionSourceLayout (DistributeLayoutAttr resLayout)
 Infers the source layout attribute for a reduction operation given the result layout attribute and reduced dims.
DistributeLayoutAttr inferTransposeSourceLayout (DistributeLayoutAttr resLayout, ArrayRef< int64_t > permutation)
 Infers the source layout attribute for a transpose operation given the result layout attribute and permutation.
DistributeLayoutAttr inferBitCastSourceLayout (DistributeLayoutAttr resLayout, int resElemTyBitWidth, int srcElemTyBitWidth)
 Infers the source layout attribute for a bitcast operation given the result layout attribute, result element type bitwidth, and source element type bitwidth.
DistributeLayoutAttr inferInterleaveSourceLayout (DistributeLayoutAttr resLayout)
 Infers the source layout attribute for an interleave operation given the result layout attribute.
DistributeLayoutAttr inferDeinterleaveSourceLayout (DistributeLayoutAttr resLayout)
 Infers the source layout attribute for a deinterleave operation given the result layout attribute.
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, result shape, and source shape.
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 attribute, result shape, and source shape.
DistributeLayoutAttr inferInsertSourceLayout (DistributeLayoutAttr resLayout, ArrayRef< int64_t > resShape, ArrayRef< int64_t > srcShape)
 Infers the source layout attribute for an insert operation.
DistributeLayoutAttr inferExtractSourceLayout (DistributeLayoutAttr resLayout, ArrayRef< int64_t > resShape, ArrayRef< int64_t > srcShape)
 Infers the source layout attribute for an extract operation.
DistributeLayoutAttr inferSourceLayoutFromResultForNonAnchorOp (OpOperand &operand, DistributeLayoutAttr resLayout)
 Infers the source layout attribute for an operand using result layout attribute.
DistributeLayoutAttr inferTransposeResultLayout (DistributeLayoutAttr srcLayout, ArrayRef< int64_t > permutation)
 Infers the result layout attribute for a transpose operation given the source layout attribute and permutation.
DistributeLayoutAttr inferShapeCastResultLayout (DistributeLayoutAttr srcLayout, ArrayRef< int64_t > srcShape, ArrayRef< int64_t > resShape)
 Infers the result layout attribute for a shape cast operation given the source layout attribute, source shape, and result shape.
DistributeLayoutAttr inferResultLayoutFromSourceForNonAnchorOp (Operation *op, ArrayRef< DistributeLayoutAttr > operandLayouts)
 Infers the result layout attribute for a non-anchor operation from the layouts of its source operands (the forward counterpart of inferSourceLayoutFromResultForNonAnchorOp).
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:
SliceAttr setupReductionResultLayout (LayoutKind layoutKind, VectorType srcVectorTy, const uArch::uArch *uArch)
 Sets up layout for Reduction operations by creating a SliceAttr for the result.
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.
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 derived.
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 dims, so that the source layout can be safely derived by collapsing each split group.
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 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.
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 setupStoreMatrixAnchorLayout (LayoutKind layoutKind, VectorType vectorTy, int contigChunkSize, int numSg, const uArch::uArch *uArch)
 Sets up the anchor layout for a store matrix operation.
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 corresponding scatter-style Lane-kind setup rule with inst_data as the destination shape.
std::optional< DistributeLayoutAttr > completeScatterStoreLaneLayoutFromInstData (DistributeLayoutAttr specifiedLayout, Type elemTy, const xegpu::uArch::StoreScatterInstruction *uArchInstruction, const int subgroupSize)
 Like completeScatterLoadLaneLayoutFromInstData, but for scatter stores (store_scatter / store_matrix).
std::optional< DistributeLayoutAttr > completeBlockStoreLaneLayoutFromInstData (DistributeLayoutAttr specifiedLayout, Type elemTy, const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction, const int subgroupSize)
 Completes a user-provided 2D-block store_nd / prefetch_nd anchor that has only inst_data.
std::optional< DistributeLayoutAttr > completeBlockLoadLaneLayoutFromInstData (DistributeLayoutAttr specifiedLayout, DistributeLayoutAttr consumerLayout, Type elemTy, const xegpu::uArch::BlockIOInstructionInterface *uArchInstruction, const int subgroupSize)
 Like completeBlockStoreLaneLayoutFromInstData, but for load_nd.
DistributeLayoutAttr setupStoreNdAnchorLayout (LayoutKind layoutKind, VectorType vectorTy, int numSg, const uArch::uArch *uArch)
 Sets up the anchor layout for a store_nd operation.
DistributeLayoutAttr setupPrefetchNdAnchorLayout (LayoutKind layoutKind, TensorDescType tdescTy, int numSg, const uArch::uArch *uArch)
 Sets up the anchor layout for a prefetch_nd operation.
DistributeLayoutAttr setupLoadNdAnchorLayout (LayoutKind layoutKind, VectorType vectorTy, DistributeLayoutAttr consumerLayout, int numSg, const uArch::uArch *uArch)
 Sets up the anchor layout for a load_nd operation.
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).
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).
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 / lane_data derived from the operand shapes (mirrors the InstData branch of setupDpasLayout).
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_scale layouts from the completed A / B layouts.
DistributeLayoutAttr getConsumerLayoutAt (OpOperand &operand)
 Gets the expected layout for a given consumer operand.
bool isTriviallyRematerializable (Operation *op)
 Returns true if the vector produced by op is cheap to recompute in any layout, i.e.
Value rematerialize (OpBuilder &builder, Value value)
 Clone a bounded chain of pure vector generators and layout-preserving elementwise ops without layout attributes.
SmallVector< Value > flattenValues (ArrayRef< ValueRange > values)
 Flatten a set of ValueRange into a single SmallVector<Value>
FailureOr< VectorType > getDistributedVectorType (xegpu::TensorDescType tdescTy)
 If tensor descriptor has a layout attribute it is used in SIMT mode.
FailureOr< VectorType > getDistributedVectorType (VectorType originalType, LayoutAttr layout)
 Helper to get the distributed vector type for a given vector type according to a given LayoutAttr.
FailureOr< VectorType > getDistVecTypeBasedOnLaneLayout (DistributeLayoutAttr layout, VectorType originalType)
 Helper function to get distributed vector type for a source vector type according to the lane_layout.
SmallVector< Value > extractVectorsWithShapeFromValue (OpBuilder &builder, Location loc, Value value, ArrayRef< int64_t > shape)
 Extract a set of small vectors from a value with a given shape using vector.extract_stride_slice.
Value createVectorWithShapeFromValues (OpBuilder &builder, Location loc, ValueRange values, ArrayRef< int64_t > shape)
 Create a vector of shape from a set of values using vector.insert_stride_slice.
std::optional< std::string > getChipStr (Operation *op)
 Retrieves the chip string from the XeVM target attribute of the parent GPU module 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 its parent gpu.func.
SmallVector< OpFoldResult > addElementwise (OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > lhs, ArrayRef< OpFoldResult > rhs)
 Generates element-wise addition ops of two arrays with same length.
SmallVector< OpFoldResult > addWithRightAligned (OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > lhs, ArrayRef< OpFoldResult > rhs)
 Generates element-wise addition ops of two arrays with automatic alignment.
Value subgroupReduction (Location loc, OpBuilder &builder, Value input, vector::CombiningKind kind, uint32_t size, arith::FastMathFlagsAttr fastmath=nullptr)
 Given an input value representing per-lane data, this function returns the result after performing a reduction on the input over all lanes (number of lanes given by size).
Value lowerToVectorReductions (TypedValue< VectorType > src, TypedValue< VectorType > acc, vector::CombiningKind kind, int64_t reductionDim, Location loc, PatternRewriter &rewriter, arith::FastMathFlagsAttr fastmath=nullptr)
 Given a src and an acc argumments from a vector::MultiDimReductionOp, lower to a set of vector::ReductionOp ops over 1D slices extracted from src.
Value createReductionNeutralValue (OpBuilder &builder, Location loc, Type type, vector::CombiningKind kind, arith::FastMathFlagsAttr fastmath=nullptr)
 Creates a constant filled with the neutral (identity) value for the given reduction kind.
Value lowerCrossLaneReductionToShuffles (TypedValue< VectorType > src, TypedValue< VectorType > acc, vector::CombiningKind kind, int64_t reductionDim, int64_t reductionSize, Location loc, PatternRewriter &rewriter, arith::FastMathFlagsAttr fastmath=nullptr)
 Lowers cross-lane reductions to shuffle operations on a 2D vector.
template<typename T>
int getLargestDivisor (T dim, ArrayRef< T > candidates, ArrayRef< T > candidateMultiples={})
 Helper Function to find a proper instruction multiple for the user-supplied sg-level data shape (diven by dim).
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 getDistributeLayoutAttr (const OpOperand &opr)
 Retrieves the DistributeLayoutAttr associated with a given OpOperand.
void setDistributeLayoutAttr (const OpResult &Result, const DistributeLayoutAttr layout)
 [to-be-deprecated] Sets the DistributeLayoutAttr for a given OpResult user should use setAnchorLayout instead
void setDistributeLayoutAttr (const OpOperand &opr, const DistributeLayoutAttr layout)
 [to-be-deprecated] Sets the DistributeLayoutAttr for a given OpOperand user should use setAnchorLayout instead
std::string getTemporaryLayoutName (const OpOperand &operand)
 Return the attribute name for the OpOperand to attach DistributeLayoutAttr.
std::string getTemporaryLayoutName (const OpResult result)
 Return the attribute name for the OpResult to attach DistributeLayoutAttr.
template<typename T, typename = std::enable_if_t<std::is_same_v<T, OpOperand> || std::is_same_v<T, OpResult>>>
DistributeLayoutAttr getTemporaryLayout (const T &operandOrResult)
 get and set distribute layout attribute for non-anchor operations (and offsets/masks of load/store ops before we get rid of their temp attrs)
template<typename T, typename = std::enable_if_t<std::is_same_v<T, OpOperand> || std::is_same_v<T, OpResult>>>
void setTemporaryLayout (const T &operandOrResult, const DistributeLayoutAttr layout)
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< SmallVector< int64_t > > getInner2DIfUnitLeadingDims (ArrayRef< int64_t > vals)
 Returns the innermost 2 entries of vals if it is at least 2D and all of its leading entries are unit; std::nullopt otherwise.
bool requirePacked (const DistributeLayoutAttr layout)
 Helper function to check if the layout is packed.
bool requireTranspose (const DistributeLayoutAttr layout, const uArch::uArch *uArch)
 Helper function to check if the layout requires a transpose effect.
bool hasStaticShapeAndStrides (MemRefType type)
 Returns true if type has a static shape and static strides.
Value addElemOffsetInBytes (OpBuilder &builder, Location loc, Value baseAddr, Value elemOffset, MemRefType memrefTy)
 Returns baseAddr + elemOffset * bitWidth / 8, i.e.
bool matchUnitDimExpansion (ArrayRef< int64_t > src, ArrayRef< int64_t > dst, SmallVector< int64_t > &expandedUnitDims)
bool matchSplitDimExpansion (ArrayRef< int64_t > src, ArrayRef< int64_t > dst, SmallVector< SmallVector< int64_t > > &splitDimGroups)
DenseMap< Value, SmallVector< Type > > precomputeLoopBlockArgTypes (Operation *topLevelOp, SubShapeAndCountFn getSubShapeAndCount)
 Pre-computes distributed VectorType mappings for every value carried through an SCF loop under topLevelOp (1:1 shape-changing or 1:N): the region block args (scf.while before/after args, scf.for iter_args), the loop results, and the terminator operands feeding them.
void addVectorTypeConversion (TypeConverter &converter, SubShapeAndCountFn getSubShapeAndCount, DenseMap< Value, SmallVector< Type > > loopArgTypes)
 Adds a context-aware VectorType conversion to converter (1:1 shape-changing or 1:N, depending on getSubShapeAndCount's returned count).
void cleanupUnrealizedConversionCasts (Operation *root, const llvm::SmallSetVector< UnrealizedConversionCastOp, 8 > &existingCasts)
 Cleans up UnrealizedConversionCastOps inserted during SCF structural type conversion and/or XeGPU unrolling.
bool matchDimCollapse (ArrayRef< int64_t > src, ArrayRef< int64_t > dst, SmallVector< SmallVector< int64_t > > &collapseDims)
static SmallVector< SmallVector< Value > > genCoordinates (OpBuilder &builder, Location loc, SmallVector< Value > delinearizedId, ArrayRef< int64_t > subShapesLayout, ArrayRef< int64_t > subShape, ArrayRef< int64_t > srcShape)
static SmallVector< SmallVector< int64_t > > genStaticCoordinates (llvm::ArrayRef< int64_t > canonicalIds, llvm::ArrayRef< int64_t > layout, llvm::ArrayRef< int64_t > subShape, llvm::ArrayRef< int64_t > shape)
static SmallVector< SmallVector< int64_t > > expandBlockCoords (ArrayRef< SmallVector< int64_t > > blockStarts, ArrayRef< int64_t > subShape)
 Expands per-distribution-unit block-start coordinates into the full list of element coordinates each block covers: every element of the subShape-sized region (row-major) offset by the block start.
static bool compareDistributedCoords (xegpu::DistributeLayoutAttr self, const xegpu::DistributeLayoutAttr &other, ArrayRef< int64_t > shape, xegpu::LayoutKind level, int64_t size)
 Returns true if self and other distribute shape identically at level: every id in [0, size) owns the same coordinates under both.
static SmallVector< int64_t > mapSlicedDimsToParentSpace (const SmallVector< int64_t > &dimsToMap, ArrayRef< int64_t > sliceDims)
SmallVector< int64_t > getPermForParentLayout (ArrayRef< int64_t > sliceDims, ArrayRef< int64_t > permutation)
template<typename ArithOp>
OpFoldResult genBinOp (OpFoldResult a, OpFoldResult b, Location loc, OpBuilder &builder)
SmallVector< OpFoldResult > getBlockedOffsets (OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > offsets, ArrayRef< int64_t > blockShape)

Typedef Documentation

◆ GetLayoutFnTy

using mlir::xegpu::GetLayoutFnTy = llvm::function_ref<DistributeLayoutAttr(Value)>

Callable returning the propagated layout for a given Value, used by the layout-propagation helpers below.

Definition at line 51 of file XeGPULayoutImpl.h.

◆ SetOperandLayoutFnTy

Initial value:
llvm::function_ref<void(OpOperand &, DistributeLayoutAttr)>
This class represents an operand of an operation.
Definition Value.h:256

The region helpers below choose layouts and pass each one to a callback; the caller decides when it reaches the IR.

Layout recovery writes it at once; layout propagation keeps it and writes it after its walk.

Called with the layout chosen for a use, which ends up as the operand's temporary layout (layout_operand_N). A null layout means none was chosen.

Definition at line 59 of file XeGPULayoutImpl.h.

◆ SetTDescArgLayoutFnTy

Initial value:
llvm::function_ref<void(BlockArgument, DistributeLayoutAttr)>
This class represents an argument of a Block.
Definition Value.h:308

Called with the layout chosen for a tensor_desc region argument (e.g.

an scf.for iter_arg), which ends up in the argument's type.

Definition at line 63 of file XeGPULayoutImpl.h.

◆ SubShapeAndCountFn

Initial value:
std::function<std::pair<SmallVector<int64_t>, int>(
VectorType, DistributeLayoutAttr)>

Callback type for computing sub-shape and count for 1:N (or 1:1 shape-changing) VectorType conversion.

Given a VectorType and its DistributeLayoutAttr, returns (subShape, count). A count <= 0 signals "no conversion needed"; count == 1 is a 1:1 shape-changing conversion; count > 1 produces count copies of subShape.

Definition at line 290 of file XeGPUUtils.h.

Enumeration Type Documentation

◆ LayoutKind

enum class mlir::xegpu::LayoutKind
strong

Specifies the level of a layout hierarchy for comparison or propagation.

Enumerator
Lane 
InstData 
Subgroup 

Definition at line 31 of file XeGPU.h.

Function Documentation

◆ addElementwise()

SmallVector< OpFoldResult > mlir::xegpu::addElementwise ( OpBuilder & builder,
Location loc,
ArrayRef< OpFoldResult > lhs,
ArrayRef< OpFoldResult > rhs )

Generates element-wise addition ops of two arrays with same length.

Definition at line 523 of file XeGPUUtils.cpp.

References mlir::OpBuilder::createOrFold(), and mlir::getValueOrCreateConstantIndexOp().

Referenced by addWithRightAligned().

◆ addElemOffsetInBytes()

Value mlir::xegpu::addElemOffsetInBytes ( OpBuilder & builder,
Location loc,
Value baseAddr,
Value elemOffset,
MemRefType memrefTy )

Returns baseAddr + elemOffset * bitWidth / 8, i.e.

advances the byte address baseAddr by elemOffset elements of memrefTy's element type. Sub-byte element types (e.g. i4) are supported. baseAddr and elemOffset must have the same index or integer type, which is also the result type.

Definition at line 899 of file XeGPUUtils.cpp.

References mlir::Builder::getIntegerAttr(), and mlir::Value::getType().

◆ addVectorTypeConversion()

void mlir::xegpu::addVectorTypeConversion ( TypeConverter & converter,
SubShapeAndCountFn getSubShapeAndCount,
DenseMap< Value, SmallVector< Type > > loopArgTypes )

Adds a context-aware VectorType conversion to converter (1:1 shape-changing or 1:N, depending on getSubShapeAndCount's returned count).

getSubShapeAndCount computes (subShape, count) for a VectorType and its layout; count <= 0 means no conversion needed. loopArgTypes (typically obtained from precomputeLoopBlockArgTypes) provides the pre-computed types for SCF loop block arguments (scf.while, scf.for); pass an empty map if the IR has no such loops.

Definition at line 1084 of file XeGPUUtils.cpp.

References getDistributeLayoutAttr(), mlir::Value::getType(), result, and success().

Referenced by populateXeGPUSgToLaneDistributeTypeConversions(), and populateXeGPUWgToSgDistributeTypeConversions().

◆ addWithRightAligned()

SmallVector< OpFoldResult > mlir::xegpu::addWithRightAligned ( OpBuilder & builder,
Location loc,
ArrayRef< OpFoldResult > lhs,
ArrayRef< OpFoldResult > rhs )

Generates element-wise addition ops of two arrays with automatic alignment.

When the input arrays have different sizes, the shorter array is right-aligned with the longer array, and the unmatched leading elements from the longer array are preserved unchanged. This is commonly used for offset computation where higher-dimensional offsets need to be added to lower-dimensional adjustments.

Example: lhs = [l1, l2, l3], rhs = [r1, r2] Result: [11, l2+r1, l3+r2]

Definition at line 548 of file XeGPUUtils.cpp.

References addElementwise(), and b.

◆ cleanupUnrealizedConversionCasts()

void mlir::xegpu::cleanupUnrealizedConversionCasts ( Operation * root,
const llvm::SmallSetVector< UnrealizedConversionCastOp, 8 > & existingCasts )

Cleans up UnrealizedConversionCastOps inserted during SCF structural type conversion and/or XeGPU unrolling.

Folds cancelling N:1->1:N and 1:N->N:1 cast chains (inserting vector.shape_cast when shapes differ but element counts match). Unpaired pack (1:N) and unpack (N:1) casts between a single large VectorType and N identically-typed smaller VectorTypes are lowered to vector.extract_strided_slice / vector.insert_strided_slice. Dead casts are erased. Casts in existingCasts are preserved.

Definition at line 1125 of file XeGPUUtils.cpp.

References createVectorWithShapeFromValues(), extractVectorsWithShapeFromValue(), mlir::Value::getType(), mlir::ValueRange::getTypes(), result, mlir::OpBuilder::setInsertionPoint(), ValueRange, and mlir::Operation::walk().

◆ compareDistributedCoords()

bool mlir::xegpu::compareDistributedCoords ( xegpu::DistributeLayoutAttr self,
const xegpu::DistributeLayoutAttr & other,
ArrayRef< int64_t > shape,
xegpu::LayoutKind level,
int64_t size )
static

Returns true if self and other distribute shape identically at level: every id in [0, size) owns the same coordinates under both.

At the Lane level, layouts that pack lane_data differently can still own the same per-lane elements in the same order; their block starts differ but the expanded per-element coordinates match. So block starts are expanded (via expandBlockCoords) before comparing, but only when it can change the result (Lane level with differing lane_data) - otherwise comparing the cheaper block starts is already exact.

TODO: Extend the same handling to the Subgroup level (sg_data repacks).

Definition at line 144 of file XeGPUDialect.cpp.

References expandBlockCoords(), and Lane.

◆ completeBlockLoadLaneLayoutFromInstData()

std::optional< DistributeLayoutAttr > mlir::xegpu::completeBlockLoadLaneLayoutFromInstData ( DistributeLayoutAttr specifiedLayout,
DistributeLayoutAttr consumerLayout,
Type elemTy,
const xegpu::uArch::BlockIOInstructionInterface * uArchInstruction,
const int subgroupSize )

Like completeBlockStoreLaneLayoutFromInstData, but for load_nd.

The consumer layout supplies the transform / transpose / packing properties; the lane factorization is recomputed from inst_data (load-side lane counts differ from the consumer's).

◆ completeBlockStoreLaneLayoutFromInstData()

std::optional< DistributeLayoutAttr > mlir::xegpu::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.

These ops are data sinks, so lane info is derived purely from inst_data using the shared BlockIOInstructionInterface; one helper serves both store_nd and prefetch_nd.

◆ completeDpasLaneLayoutFromInstData()

std::optional< std::tuple< DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr > > mlir::xegpu::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 / lane_data derived from the operand shapes (mirrors the InstData branch of setupDpasLayout).

Returns nullopt if the uArch lacks the matmul instruction.

◆ completeDpasMxLaneLayoutFromInstData()

std::optional< std::tuple< DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr > > mlir::xegpu::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_scale layouts from the completed A / B layouts.

◆ completeScatterLoadLaneLayoutFromInstData()

std::optional< DistributeLayoutAttr > mlir::xegpu::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 corresponding scatter-style Lane-kind setup rule with inst_data as the destination shape.

The resulting lane info is merged with the consumer's inst_data so downstream setup* paths see a fully-populated layout. Returns the layout unchanged when it is null, has no inst_data, or already carries lane info; returns nullopt when the derived lane factorization does not divide the user's inst_data (an invalid inst_data).

◆ completeScatterStoreLaneLayoutFromInstData()

std::optional< DistributeLayoutAttr > mlir::xegpu::completeScatterStoreLaneLayoutFromInstData ( DistributeLayoutAttr specifiedLayout,
Type elemTy,
const xegpu::uArch::StoreScatterInstruction * uArchInstruction,
const int subgroupSize )

Like completeScatterLoadLaneLayoutFromInstData, but for scatter stores (store_scatter / store_matrix).

A store is a data sink: lane info is derived purely from inst_data using the uArch's StoreScatter per-lane store width, with no consumer layout to reuse.

◆ createReductionNeutralValue()

Value mlir::xegpu::createReductionNeutralValue ( OpBuilder & builder,
Location loc,
Type type,
vector::CombiningKind kind,
arith::FastMathFlagsAttr fastmath = nullptr )

Creates a constant filled with the neutral (identity) value for the given reduction kind.

For example: 0 for ADD/OR/XOR, 1 for MUL, all ones for AND, and max/min signed/unsigned int for MINSI/MINUI/MAXSI/MAXUI. For float min/max kinds, the value must fit the element type and be allowed by fastmath:

  • A quiet NaN for the kinds that ignore NaN operands, if the type has NaN and nnan is not set.
  • Otherwise the infinity that never wins, if the type has it and ninf is not set.
  • Otherwise the lowest (for max) or highest (for min) finite value. If type is a VectorType, returns a splat vector constant; otherwise returns a scalar constant. Returns nullptr if the element type is incompatible with the requested reduction kind.

Definition at line 787 of file XeGPUUtils.cpp.

References mlir::DenseElementsAttr::get(), getFlags(), mlir::Builder::getFloatAttr(), mlir::Builder::getIndexAttr(), mlir::Builder::getIntegerAttr(), getMinMaxNeutral(), mlir::Builder::getOneAttr(), mlir::Builder::getZeroAttr(), and mlir::Type::isIndex().

◆ createVectorWithShapeFromValues()

Value mlir::xegpu::createVectorWithShapeFromValues ( OpBuilder & builder,
Location loc,
ValueRange values,
ArrayRef< int64_t > shape )

Create a vector of shape from a set of values using vector.insert_stride_slice.

Definition at line 461 of file XeGPUUtils.cpp.

References mlir::DenseElementsAttr::get(), mlir::getType(), mlir::ValueRange::getTypes(), mlir::Builder::getZeroAttr(), and result.

Referenced by cleanupUnrealizedConversionCasts().

◆ dropInstDataOnAttrs()

SmallVector< NamedAttribute > mlir::xegpu::dropInstDataOnAttrs ( ArrayRef< NamedAttribute > attrs)

Updates the NamedAttribute sequence by dropping inst-data information from any DistributeLayoutAttr found.

Definition at line 61 of file XeGPULayoutImpl.cpp.

◆ dropInstDataOnInherentAttrs()

void mlir::xegpu::dropInstDataOnInherentAttrs ( Operation * op)

Drops inst-data information from DistributeLayoutAttrs stored as inherent attributes on the operation.

Definition at line 78 of file XeGPULayoutImpl.cpp.

References mlir::Operation::getName(), and mlir::OperationName::walkInherentAttrs().

◆ dropSgLayoutAndDataOnAttrs()

SmallVector< NamedAttribute > mlir::xegpu::dropSgLayoutAndDataOnAttrs ( ArrayRef< NamedAttribute > attrs)

Updates the NamedAttribute sequence by dropping sg-layout and sg-data information from any DistributeLayoutAttr found.

Definition at line 43 of file XeGPULayoutImpl.cpp.

◆ expandBlockCoords()

SmallVector< SmallVector< int64_t > > mlir::xegpu::expandBlockCoords ( ArrayRef< SmallVector< int64_t > > blockStarts,
ArrayRef< int64_t > subShape )
static

Expands per-distribution-unit block-start coordinates into the full list of element coordinates each block covers: every element of the subShape-sized region (row-major) offset by the block start.

Comparing these instead of the bare block starts lets layouts that differ only in lane_data blocking, but own the same elements in the same order, be recognized as equivalent.

Definition at line 118 of file XeGPUDialect.cpp.

Referenced by compareDistributedCoords().

◆ extractVectorsWithShapeFromValue()

SmallVector< Value > mlir::xegpu::extractVectorsWithShapeFromValue ( OpBuilder & builder,
Location loc,
Value value,
ArrayRef< int64_t > shape )

Extract a set of small vectors from a value with a given shape using vector.extract_stride_slice.

Definition at line 424 of file XeGPUUtils.cpp.

References mlir::computeShapeRatio(), mlir::Value::getType(), result, and slice().

Referenced by cleanupUnrealizedConversionCasts().

◆ flattenValues()

SmallVector< Value > mlir::xegpu::flattenValues ( ArrayRef< ValueRange > values)

Flatten a set of ValueRange into a single SmallVector<Value>

convert ArrayRef<ValueRange> into SmallVector<Value>

Definition at line 37 of file XeGPUUtils.cpp.

References result.

◆ genBinOp()

template<typename ArithOp>
OpFoldResult mlir::xegpu::genBinOp ( OpFoldResult a,
OpFoldResult b,
Location loc,
OpBuilder & builder )

Definition at line 1754 of file XeGPUDialect.cpp.

References b, and mlir::getValueOrCreateConstantIndexOp().

◆ genCoordinates()

SmallVector< SmallVector< Value > > mlir::xegpu::genCoordinates ( OpBuilder & builder,
Location loc,
SmallVector< Value > delinearizedId,
ArrayRef< int64_t > subShapesLayout,
ArrayRef< int64_t > subShape,
ArrayRef< int64_t > srcShape )
static

◆ genStaticCoordinates()

SmallVector< SmallVector< int64_t > > mlir::xegpu::genStaticCoordinates ( llvm::ArrayRef< int64_t > canonicalIds,
llvm::ArrayRef< int64_t > layout,
llvm::ArrayRef< int64_t > subShape,
llvm::ArrayRef< int64_t > shape )
static

Definition at line 87 of file XeGPUDialect.cpp.

◆ getBlockedOffsets()

SmallVector< OpFoldResult > mlir::xegpu::getBlockedOffsets ( OpBuilder & builder,
Location loc,
ArrayRef< OpFoldResult > offsets,
ArrayRef< int64_t > blockShape )

Definition at line 1779 of file XeGPUDialect.cpp.

References div, and rem.

◆ getChipStr()

std::optional< std::string > mlir::xegpu::getChipStr ( Operation * op)

Retrieves the chip string from the XeVM target attribute of the parent GPU module operation.

Returns the chip identifier if found, or nullopt if no GPU module parent or XeVM target attribute exists.

Definition at line 486 of file XeGPUUtils.cpp.

References mlir::Operation::getParentOfType().

◆ getConsumerLayoutAt()

xegpu::DistributeLayoutAttr mlir::xegpu::getConsumerLayoutAt ( OpOperand & operand)

Gets the expected layout for a given consumer operand.

Returns the layout required on operand: anchor ops report their declared per-operand layout directly; non-anchor ops back-derive it from their result layout via inferSourceLayoutFromResultForNonAnchorOp.

This will check if the owning operation of the consumer operand is one of the special layout users and determine the expected layout accordingly.

Definition at line 3331 of file XeGPULayoutImpl.cpp.

References getDistributeLayoutAttr(), getLoopCarriedLayoutForYieldOperand(), mlir::Operation::getNumResults(), mlir::detail::IROperandBase::getOwner(), mlir::Operation::getParentOp(), getParentResultLayoutForYieldOperand(), mlir::Operation::getResult(), and inferSourceLayoutFromResultForNonAnchorOp().

◆ getDistributedVectorType() [1/2]

FailureOr< VectorType > mlir::xegpu::getDistributedVectorType ( VectorType originalType,
LayoutAttr layout )

Helper to get the distributed vector type for a given vector type according to a given LayoutAttr.

◆ getDistributedVectorType() [2/2]

FailureOr< VectorType > mlir::xegpu::getDistributedVectorType ( xegpu::TensorDescType tdescTy)

If tensor descriptor has a layout attribute it is used in SIMT mode.

In this mode, the distributed vector shape is determined as follows: Definitions: lane_data_size = lane_data[0] × lane_data[1] subgroup_size = lane_layout[0] × lane_layout[1] distribution_unit_size = subgroup_size × lane_data_size

Case 1: Regular loads/stores. The following conditions must be met:

  • tensor_desc[0] == lane_layout[0] Distributed vector is a 1D vector with shape: [chunk_size]

Case 2: Block loads/stores Additional definitions: tensor_size = tensor_desc[0] * .. * tensor_desc[r-1] * array_length n_distribution_units = tensor_size / distribution_unit_size fragment_size = n_distribution_units * lane_data_size Given above definitions, the following conditions must be met:

  • tensor_desc[0] % (lane_layout[0] × lane_data[0]) == 0
  • tensor_desc[1] % (lane_layout[1] × lane_data[1]) == 0 Distributed vector is a 1D vector with shape: [fragment_size]

Definition at line 45 of file XeGPUUtils.cpp.

◆ getDistributeLayoutAttr() [1/2]

xegpu::DistributeLayoutAttr mlir::xegpu::getDistributeLayoutAttr ( const OpOperand & opr)

Retrieves the DistributeLayoutAttr associated with a given OpOperand.

It will first check the operand_layout_{id} of the owner operation. If not found, it will check the operand itself and its defining op.

Definition at line 202 of file XeGPUUtils.cpp.

References mlir::Operation::getDiscardableAttrOfType(), mlir::detail::IROperandBase::getOwner(), getTemporaryLayoutName(), and mlir::Operation::hasDiscardableAttr().

◆ getDistributeLayoutAttr() [2/2]

xegpu::DistributeLayoutAttr mlir::xegpu::getDistributeLayoutAttr ( const Value value)

Retrieves the DistributeLayoutAttr associated with a given Value, or nullptr if none is found.

For TensorDescType values it is extracted from the TensorDescType itself; for an op result, from the attributes of the defining operation.

A block argument carries no attribute of its own, so it is resolved through the operand that feeds it:

  • an iter_arg of a loop, including scf.while's "before" arguments, resolves through its tied init operand;
  • an scf.while "after" argument is fed by scf.condition rather than by an init operand. Only a pass-through before region is handled: the forwarded value must be a "before" argument, and the layout comes from that argument's tied init operand. If the before region forwards anything computed, nullptr is returned.

Definition at line 154 of file XeGPUUtils.cpp.

References mlir::Operation::getDiscardableAttrOfType(), getTemporaryLayout(), getTemporaryLayoutName(), mlir::Value::getType(), mlir::Operation::hasDiscardableAttr(), and result.

Referenced by addVectorTypeConversion(), forwardFillRegularOp(), getConsumerLayoutAt(), getLayoutFromUsePoints(), getLoopCarriedLayoutForYieldOperand(), getParentResultLayoutForYieldOperand(), populateXeGPUSgToLaneDistributeTypeConversionAndLegality(), precomputeLoopBlockArgTypes(), propagateLayouts(), and sinkElementwiseConversions().

◆ getDistVecTypeBasedOnLaneLayout()

FailureOr< VectorType > mlir::xegpu::getDistVecTypeBasedOnLaneLayout ( DistributeLayoutAttr layout,
VectorType originalType )

Helper function to get distributed vector type for a source vector type according to the lane_layout.

We simply divide each dimension of tensor descriptor shape by corresponding lane_layout dimension. If array_length > 1, that is appended to the front of the distributed shape.

Examples:

original vector shape lane_layout distributed vector shape
32x16 [1, 16] 32x1
32x16 [2, 8] 16x2
2x32x16 [1, 16] 2x32x1

Referenced by populateXeGPUSgToLaneDistributeTypeConversions().

◆ getInner2DIfUnitLeadingDims()

std::optional< SmallVector< int64_t > > mlir::xegpu::getInner2DIfUnitLeadingDims ( ArrayRef< int64_t > vals)

Returns the innermost 2 entries of vals if it is at least 2D and all of its leading entries are unit; std::nullopt otherwise.

Definition at line 860 of file XeGPUUtils.cpp.

◆ getLargestDivisor()

template<typename T>
int mlir::xegpu::getLargestDivisor ( T dim,
ArrayRef< T > candidates,
ArrayRef< T > candidateMultiples = {} )

Helper Function to find a proper instruction multiple for the user-supplied sg-level data shape (diven by dim).

candidates are uArch allowed shapes. candidateMultiples are uArch multiples of such shapes (i.e. block count or array length).

Definition at line 561 of file XeGPUUtils.cpp.

Referenced by get2DBlockIOInstDataLayout(), and getDpasInstDataLayouts().

◆ getNumSubgroupsFromBlockSize()

FailureOr< int64_t > mlir::xegpu::getNumSubgroupsFromBlockSize ( Operation * op,
int64_t subgroupSize )

Returns the number of subgroups the kernel enclosing op runs, derived from the known_block_size of its parent gpu.func.

Fails when there is no such parent, when the attribute is absent, when a block dimension is not a positive power of two, or when the block does not cover a whole subgroup.

Definition at line 504 of file XeGPUUtils.cpp.

References mlir::Operation::getParentOfType().

◆ getPermForParentLayout()

SmallVector< int64_t > mlir::xegpu::getPermForParentLayout ( ArrayRef< int64_t > sliceDims,
ArrayRef< int64_t > permutation )

Definition at line 1435 of file XeGPUDialect.cpp.

◆ getTemporaryLayout()

template<typename T, typename = std::enable_if_t<std::is_same_v<T, OpOperand> || std::is_same_v<T, OpResult>>>
DistributeLayoutAttr mlir::xegpu::getTemporaryLayout ( const T & operandOrResult)

get and set distribute layout attribute for non-anchor operations (and offsets/masks of load/store ops before we get rid of their temp attrs)

Referenced by forwardInitsToRegionArgs(), forwardYieldOperandsToRegionResults(), getDistributeLayoutAttr(), lowerToVectorReductions(), populateXeGPUSgToLaneDistributeTypeConversionAndLegality(), xegpu::getTemporaryLayout< mlir::OpOperand >(), and xegpu::getTemporaryLayout< mlir::OpResult >().

◆ getTemporaryLayoutName() [1/2]

std::string mlir::xegpu::getTemporaryLayoutName ( const OpOperand & operand)

Return the attribute name for the OpOperand to attach DistributeLayoutAttr.

Definition at line 139 of file XeGPUUtils.cpp.

Referenced by getDistributeLayoutAttr(), getDistributeLayoutAttr(), removeLayoutAttr(), and setDistributeLayoutAttr().

◆ getTemporaryLayoutName() [2/2]

std::string mlir::xegpu::getTemporaryLayoutName ( const OpResult result)

Return the attribute name for the OpResult to attach DistributeLayoutAttr.

Definition at line 145 of file XeGPUUtils.cpp.

References result.

◆ hasStaticShapeAndStrides()

bool mlir::xegpu::hasStaticShapeAndStrides ( MemRefType type)

Returns true if type has a static shape and static strides.

Definition at line 890 of file XeGPUUtils.cpp.

◆ inferBitCastSourceLayout()

DistributeLayoutAttr mlir::xegpu::inferBitCastSourceLayout ( DistributeLayoutAttr resLayout,
int resElemTyBitWidth,
int srcElemTyBitWidth )

Infers the source layout attribute for a bitcast operation given the result layout attribute, result element type bitwidth, and source element type bitwidth.

◆ inferBroadcastSourceLayout()

DistributeLayoutAttr mlir::xegpu::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, result shape, and source shape.

◆ inferDeinterleaveSourceLayout()

DistributeLayoutAttr mlir::xegpu::inferDeinterleaveSourceLayout ( DistributeLayoutAttr resLayout)

Infers the source layout attribute for a deinterleave operation given the result layout attribute.

Deinterleave halves the innermost dimension size.

◆ inferExtractSourceLayout()

DistributeLayoutAttr mlir::xegpu::inferExtractSourceLayout ( DistributeLayoutAttr resLayout,
ArrayRef< int64_t > resShape,
ArrayRef< int64_t > srcShape )

Infers the source layout attribute for an extract operation.

Adds leading dimensions to the source layout to match the source shape size.

◆ inferInsertSourceLayout()

DistributeLayoutAttr mlir::xegpu::inferInsertSourceLayout ( DistributeLayoutAttr resLayout,
ArrayRef< int64_t > resShape,
ArrayRef< int64_t > srcShape )

Infers the source layout attribute for an insert operation.

using same logic as inferInsertStridedSliceSourceLayout

◆ inferInsertStridedSliceSourceLayout()

DistributeLayoutAttr mlir::xegpu::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 attribute, result shape, and source shape.

Removes leading dimensions from the result layout to match the source shape size.

◆ inferInterleaveSourceLayout()

DistributeLayoutAttr mlir::xegpu::inferInterleaveSourceLayout ( DistributeLayoutAttr resLayout)

Infers the source layout attribute for an interleave operation given the result layout attribute.

Interleave doubles the innermost dimension size.

◆ inferMultiReductionSourceLayout()

DistributeLayoutAttr mlir::xegpu::inferMultiReductionSourceLayout ( DistributeLayoutAttr resLayout,
SmallVector< int64_t > reduceDims )

Infers the source layout attribute for a reduction operation given the result layout attribute and reduced dims.

◆ inferReductionSourceLayout()

DistributeLayoutAttr mlir::xegpu::inferReductionSourceLayout ( DistributeLayoutAttr resLayout)

Infers the source layout attribute for a reduction operation given the result layout attribute and reduced dims.

◆ inferResultLayoutFromSourceForNonAnchorOp()

DistributeLayoutAttr mlir::xegpu::inferResultLayoutFromSourceForNonAnchorOp ( Operation * op,
ArrayRef< DistributeLayoutAttr > operandLayouts )

Infers the result layout attribute for a non-anchor operation from the layouts of its source operands (the forward counterpart of inferSourceLayoutFromResultForNonAnchorOp).

operandLayouts is indexed by operand number; entries may be null for operands without a known layout. Returns nullptr when no forward rule applies (the result is then left un-laid-out).

Referenced by forwardFillRegularOp().

◆ inferShapeCastResultLayout()

DistributeLayoutAttr mlir::xegpu::inferShapeCastResultLayout ( DistributeLayoutAttr srcLayout,
ArrayRef< int64_t > srcShape,
ArrayRef< int64_t > resShape )

Infers the result layout attribute for a shape cast operation given the source layout attribute, source shape, and result shape.

Inverse of inferShapeCastSourceLayout. Returns nullptr for shape-cast patterns whose forward direction is ambiguous (e.g. unit-dim expansion).

◆ inferShapeCastSourceLayout()

DistributeLayoutAttr mlir::xegpu::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, result shape, and source shape.

◆ inferSourceLayoutFromResultForNonAnchorOp()

DistributeLayoutAttr mlir::xegpu::inferSourceLayoutFromResultForNonAnchorOp ( OpOperand & operand,
DistributeLayoutAttr resLayout )

Infers the source layout attribute for an operand using result layout attribute.

Referenced by getConsumerLayoutAt(), and propagateResultsToRegularOperands().

◆ inferTransposeResultLayout()

DistributeLayoutAttr mlir::xegpu::inferTransposeResultLayout ( DistributeLayoutAttr srcLayout,
ArrayRef< int64_t > permutation )

Infers the result layout attribute for a transpose operation given the source layout attribute and permutation.

Inverse of inferTransposeSourceLayout.

◆ inferTransposeSourceLayout()

DistributeLayoutAttr mlir::xegpu::inferTransposeSourceLayout ( DistributeLayoutAttr resLayout,
ArrayRef< int64_t > permutation )

Infers the source layout attribute for a transpose operation given the result layout attribute and permutation.

◆ isLayoutCarrierType()

bool mlir::xegpu::isLayoutCarrierType ( Type type)

Returns true if values of type can carry a DistributeLayoutAttr, i.e.

type is a vector or a tensor descriptor.

Definition at line 150 of file XeGPUUtils.cpp.

Referenced by forwardFillRegularOp(), propagateRegionResultsToYieldOperands(), and updateFunctionOpInterface().

◆ isTriviallyRematerializable()

bool mlir::xegpu::isTriviallyRematerializable ( Operation * op)

Returns true if the vector produced by op is cheap to recompute in any layout, i.e.

rematerialize would succeed: a bounded chain of pure vector generators (vector.step, splat arith.constant, vector.create_mask, scalar vector.broadcast) and layout-preserving elementwise ops.

Definition at line 259 of file XeGPULayoutImpl.cpp.

References collectRematerializableChain().

Referenced by sinkElementwiseConversions().

◆ lowerCrossLaneReductionToShuffles()

Value mlir::xegpu::lowerCrossLaneReductionToShuffles ( TypedValue< VectorType > src,
TypedValue< VectorType > acc,
vector::CombiningKind kind,
int64_t reductionDim,
int64_t reductionSize,
Location loc,
PatternRewriter & rewriter,
arith::FastMathFlagsAttr fastmath = nullptr )

Lowers cross-lane reductions to shuffle operations on a 2D vector.

Extracts slices along the reduction dimension, performs subgroup reductions with shuffles across reductionSize work-items, and inserts the results back into an accumulator vector. fastmath holds the fast-math flags of the reduction being lowered. For float kinds, they are set on every combining operation: the shuffle reductions (see subgroupReduction) and the combine with each accumulator element.

Definition at line 682 of file XeGPUUtils.cpp.

References mlir::DenseElementsAttr::get(), mlir::Value::getType(), mlir::Builder::getZeroAttr(), mlir::vector::makeArithReduction(), slice(), and subgroupReduction().

◆ lowerToVectorReductions()

Value mlir::xegpu::lowerToVectorReductions ( TypedValue< VectorType > src,
TypedValue< VectorType > acc,
vector::CombiningKind kind,
int64_t reductionDim,
Location loc,
PatternRewriter & rewriter,
arith::FastMathFlagsAttr fastmath = nullptr )

Given a src and an acc argumments from a vector::MultiDimReductionOp, lower to a set of vector::ReductionOp ops over 1D slices extracted from src.

The reduction is performed along reductionDim. The result is a vector with the same shape as acc. fastmath holds the fast-math flags of the vector::MultiDimReductionOp. Each new vector::ReductionOp gets them. TODO: Only 2D to 1D reduction is supported for now.

Definition at line 602 of file XeGPUUtils.cpp.

References mlir::DenseElementsAttr::get(), getFlags(), getTemporaryLayout(), mlir::Value::getType(), mlir::Builder::getZeroAttr(), setTemporaryLayout(), and slice().

◆ mapSlicedDimsToParentSpace()

SmallVector< int64_t > mlir::xegpu::mapSlicedDimsToParentSpace ( const SmallVector< int64_t > & dimsToMap,
ArrayRef< int64_t > sliceDims )
static

Definition at line 1273 of file XeGPUDialect.cpp.

◆ matchDimCollapse()

bool mlir::xegpu::matchDimCollapse ( ArrayRef< int64_t > src,
ArrayRef< int64_t > dst,
SmallVector< SmallVector< int64_t > > & collapseDims )

Definition at line 1244 of file XeGPUUtils.cpp.

◆ matchSplitDimExpansion()

bool mlir::xegpu::matchSplitDimExpansion ( ArrayRef< int64_t > src,
ArrayRef< int64_t > dst,
SmallVector< SmallVector< int64_t > > & splitDimGroups )

Definition at line 958 of file XeGPUUtils.cpp.

References matchUnitDimExpansion().

Referenced by setupShapeCastResultLayout().

◆ matchUnitDimExpansion()

bool mlir::xegpu::matchUnitDimExpansion ( ArrayRef< int64_t > src,
ArrayRef< int64_t > dst,
SmallVector< int64_t > & expandedUnitDims )

Definition at line 937 of file XeGPUUtils.cpp.

Referenced by matchSplitDimExpansion().

◆ populateXeGPUArrayLengthOptimizationPatterns()

void mlir::xegpu::populateXeGPUArrayLengthOptimizationPatterns ( RewritePatternSet & patterns)

Appends patterns for array length optimization into patterns.

Definition at line 237 of file XeGPUArrayLengthOptimization.cpp.

References mlir::RewritePatternSet::add(), and mlir::RewritePatternSet::getContext().

◆ populateXeGPUMoveFuncBodyToWarpOpPatterns()

void mlir::xegpu::populateXeGPUMoveFuncBodyToWarpOpPatterns ( RewritePatternSet & patterns)

Appends patterns for moving function body into gpu.warp_execute_on_lane0 op.

References options, and target.

◆ populateXeGPUPeepHoleOptimizerPatterns()

void mlir::xegpu::populateXeGPUPeepHoleOptimizerPatterns ( RewritePatternSet & patterns)

Appends patterns for optimizing block load operations into patterns.

Definition at line 587 of file XeGPUPeepHoleOptimizer.cpp.

References mlir::RewritePatternSet::add(), and mlir::RewritePatternSet::getContext().

◆ populateXeGPUSgToLaneDistributeTypeConversionAndLegality()

void mlir::xegpu::populateXeGPUSgToLaneDistributeTypeConversionAndLegality ( TypeConverter & typeConverter,
RewritePatternSet & patterns,
ConversionTarget & target,
Operation * topLevelOp )

Defines type conversions and legality for XeGPU subgroup to lane distribution and appends the required conversion patterns into patterns.

Appends patterns for XeGPU subgroup to lane distribution into patterns.

Definition at line 2777 of file XeGPUSgToLaneDistribute.cpp.

References mlir::RewritePatternSet::add(), mlir::RewritePatternSet::getContext(), getDistributeLayoutAttr(), getTemporaryLayout(), mlir::OpTrait::hasElementwiseMappableTraits(), populateXeGPUSgToLaneDistributeTypeConversions(), and target.

◆ populateXeGPUSgToLaneDistributeTypeConversions()

void mlir::xegpu::populateXeGPUSgToLaneDistributeTypeConversions ( TypeConverter & typeConverter,
Operation * topLevelOp )

Define only the type conversions needed for XeGPU subgroup to lane distribution.

Definition at line 2747 of file XeGPUSgToLaneDistribute.cpp.

References addVectorTypeConversion(), getDistVecTypeBasedOnLaneLayout(), and precomputeLoopBlockArgTypes().

Referenced by populateXeGPUSgToLaneDistributeTypeConversionAndLegality().

◆ populateXeGPUSubgroupDistributePatterns()

void mlir::xegpu::populateXeGPUSubgroupDistributePatterns ( RewritePatternSet & patterns)

Appends patterns for XeGPU SIMT distribution into patterns.

◆ populateXeGPUUnrollPatterns()

void mlir::xegpu::populateXeGPUUnrollPatterns ( RewritePatternSet & patterns,
const UnrollOptions & options )

Collect a set of patterns to unroll xegpu operations to a smaller shapes.

Users can control whether an operation to be unrolled or not, as well as its target shape via options structure. (via setting filterConstraint and nativeShape respectively, both of them are function refs taking op as input). An op is unrolled to the targetShape as follows, for each of its operands:

  1. the unrolled type unrolledType and number of unrolled instances numUnrolledInstances are computed from the targetShape.
  2. pack each operand. ExtractStridedSlice are created to break-up the vector operands. And BuiltinUnrealizedCastOp are created to break-up the TensorDesc operands.
  3. the original op is cloned numUnrolledInstances times, once for each result.
  4. unpack the results. InsertStridedSlice are inserted for VectorType result, and BuiltinUnrealizedCastOp are inserted for TensorDescType result to re-assemble the slices into the original shape.

Definition at line 1036 of file XeGPUUnroll.cpp.

References mlir::RewritePatternSet::add(), mlir::RewritePatternSet::getContext(), and options.

◆ populateXeGPUWgToSgDistributePatterns()

void mlir::xegpu::populateXeGPUWgToSgDistributePatterns ( RewritePatternSet & patterns)

Appends patterns for XeGPU workgroup to subgroup distribution into patterns.

Definition at line 1534 of file XeGPUWgToSgDistribute.cpp.

References mlir::RewritePatternSet::add(), and mlir::RewritePatternSet::getContext().

◆ populateXeGPUWgToSgDistributeTypeConversions()

void mlir::xegpu::populateXeGPUWgToSgDistributeTypeConversions ( TypeConverter & converter,
Operation * topLevelOp )

Define the type conversions needed for XeGPU workgroup to subgroup distribution.

This includes a context-aware 1:N conversion for VectorType (using the distribute layout attribute on the Value) and a 1:N conversion for TensorDescType.

Definition at line 1491 of file XeGPUWgToSgDistribute.cpp.

References addVectorTypeConversion(), mlir::Type::getContext(), precomputeLoopBlockArgTypes(), result, and success().

◆ precomputeLoopBlockArgTypes()

DenseMap< Value, SmallVector< Type > > mlir::xegpu::precomputeLoopBlockArgTypes ( Operation * topLevelOp,
SubShapeAndCountFn getSubShapeAndCount )

Pre-computes distributed VectorType mappings for every value carried through an SCF loop under topLevelOp (1:1 shape-changing or 1:N): the region block args (scf.while before/after args, scf.for iter_args), the loop results, and the terminator operands feeding them.

Each is derived from a single source – the layout of the feeding value (loop init or scf.condition operand) – and keyed by Value, because the SCF converters detach/replace the loop body mid-conversion, after which a layout query on a block arg returns null. Recording results and terminator operands lets a 1:N pass resolve them from the map after stripping the loop op's transient layout attrs. scf.if has no loop-carried block args and needs no entry.

Definition at line 1018 of file XeGPUUtils.cpp.

References getDistributeLayoutAttr(), mlir::Value::getType(), and mlir::Operation::walk().

Referenced by populateXeGPUSgToLaneDistributeTypeConversions(), and populateXeGPUWgToSgDistributeTypeConversions().

◆ propagateLayouts()

LogicalResult mlir::xegpu::propagateLayouts ( OpBuilder & builder,
Operation * target,
LayoutKind layoutKind,
unsigned indexBitWidth,
bool printOnly = false )

◆ propagateRegionArgsToInits()

LogicalResult mlir::xegpu::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.

The block argument's layout is obtained via getLayoutOfValue; the matching layout is then recorded, via setOperandLayout, on each init operand that flows into that block argument (e.g. scf.for's iter_args inits), and, via setTDescArgLayout, for tensor descriptor block arguments.

◆ propagateRegionResultsToYieldOperands()

void mlir::xegpu::propagateRegionResultsToYieldOperands ( RegionBranchTerminatorOpInterface terminator,
GetLayoutFnTy getLayoutOfValue,
SetOperandLayoutFnTy setOperandLayout )

Propagate layouts to the operands of a region branch terminator: each operand gets, via getLayoutOfValue, the layout of the region argument it feeds, or else of the region result it feeds, recorded via setOperandLayout.

Definition at line 319 of file XeGPULayoutImpl.cpp.

References isLayoutCarrierType().

◆ recoverTemporaryLayouts()

bool mlir::xegpu::recoverTemporaryLayouts ( Operation * rootOp)

Attach layout attributes to all vector-type operands of operations within the given operation's nested region.

Reports an error if any vector operand lacks a layout attribute.

Definition at line 443 of file XeGPULayoutImpl.cpp.

References removeTemporaryLayoutAttrs(), and walkBackward().

◆ registerTransformDialectExtension()

void mlir::xegpu::registerTransformDialectExtension ( DialectRegistry & registry)

◆ rematerialize()

Value mlir::xegpu::rematerialize ( OpBuilder & builder,
Value value )

Clone a bounded chain of pure vector generators and layout-preserving elementwise ops without layout attributes.

Each producer is cloned once, immediately after its original; scalar operands remain shared. Return null if the chain is ineligible, without modifying the IR.

Definition at line 266 of file XeGPULayoutImpl.cpp.

References mlir::clone(), mlir::OpBuilder::clone(), collectRematerializableChain(), mlir::Value::getDefiningOp(), mlir::IRMapping::lookup(), removeLayoutAttrs(), and mlir::OpBuilder::setInsertionPointAfter().

Referenced by rematerializeConversionSources().

◆ rematerializeConversionSources()

void mlir::xegpu::rematerializeConversionSources ( OpBuilder & builder,
Operation * parentOp )

Replace layout conversions of cheap producer chains by recomputation.

step = vector.step {L1} cast = arith.index_castui step {L1} cvt = xegpu.convert_layout cast : L1 -> L2 use(cast) {L1} use(cvt) {L2}

becomes

step = vector.step {L1} step' = vector.step cast = arith.index_castui step {L1} cast' = arith.index_castui step' use(cast) {L1} use(cast') {L2}

Clone the whole vector producer chain so the original and rematerialized values can serve consumers with different layouts. Clones carry no layout attributes; layout-dependent passes recover them from the use points. For small, layout-preserving chains, recomputation can avoid cross-subgroup data movement through SLM.

Definition at line 1799 of file XeGPUPropagateLayout.cpp.

References mlir::clone(), rematerialize(), and mlir::Operation::walk().

◆ removeLayoutAttr()

template<typename T, typename = std::enable_if_t<std::is_same_v<T, OpOperand> || std::is_same_v<T, OpResult>>>
void mlir::xegpu::removeLayoutAttr ( const T & operandOrResult)

◆ removeLayoutAttrs()

void mlir::xegpu::removeLayoutAttrs ( Operation * op)

Removes the DistributeLayoutAttr for each OpOperand and OpResult of the given operation if they exist.

If the operation contains regions, it is also applied recursively to the contained operations

Definition at line 466 of file XeGPULayoutImpl.cpp.

References mlir::Operation::getDiscardableAttrDictionary(), mlir::Operation::removeDiscardableAttr(), and mlir::Operation::walk().

Referenced by rematerialize().

◆ removeTemporaryLayoutAttrs()

void mlir::xegpu::removeTemporaryLayoutAttrs ( Operation * op)

Removes the temporary layout attributes for each OpOperand and OpResult of the given operation.

Recursive for contained operations if the given operation contains regions.

Definition at line 479 of file XeGPULayoutImpl.cpp.

References mlir::Operation::getDiscardableAttrDictionary(), mlir::Operation::removeDiscardableAttr(), and mlir::Operation::walk().

Referenced by recoverTemporaryLayouts().

◆ requirePacked()

bool mlir::xegpu::requirePacked ( const DistributeLayoutAttr layout)

Helper function to check if the layout is packed.

Layout is packed if lane_data[rank-2] != 1 (data packed from col dimension). TODO: Move to target info.

◆ requireTranspose()

bool mlir::xegpu::requireTranspose ( const DistributeLayoutAttr layout,
const uArch::uArch * uArch )

Helper function to check if the layout requires a transpose effect.

◆ resolveLayoutConflicts()

LogicalResult mlir::xegpu::resolveLayoutConflicts ( Operation * target)

Definition at line 2089 of file XeGPUPropagateLayout.cpp.

References target.

◆ runContiguityAnalysis()

void mlir::xegpu::runContiguityAnalysis ( Operation * root)

Run the AxisInfo-based contiguity analysis over root and stamp a contiguity attribute on every xegpu.load / xegpu.store whose offsets are contiguous (in runs of >= 2) along the innermost dimension.

The stamped value is the inner-dim contiguity; it is a target-independent property consumed downstream (e.g. to derive a lane_data split). Ops that already carry a contiguity attribute are left untouched.

Definition at line 910 of file XeGPUContiguityAnalysis.cpp.

References mlir::DataFlowSolver::initializeAndRun(), load, mlir::DataFlowSolver::load(), and mlir::Operation::walk().

◆ setDistributeLayoutAttr() [1/2]

void mlir::xegpu::setDistributeLayoutAttr ( const OpOperand & opr,
const DistributeLayoutAttr layout )

[to-be-deprecated] Sets the DistributeLayoutAttr for a given OpOperand user should use setAnchorLayout instead

Definition at line 329 of file XeGPUUtils.cpp.

References mlir::detail::IROperandBase::getOwner(), getTemporaryLayoutName(), mlir::Operation::hasDiscardableAttrOfType(), and mlir::Operation::setDiscardableAttr().

◆ setDistributeLayoutAttr() [2/2]

void mlir::xegpu::setDistributeLayoutAttr ( const OpResult & Result,
const DistributeLayoutAttr layout )

[to-be-deprecated] Sets the DistributeLayoutAttr for a given OpResult user should use setAnchorLayout instead

References result.

Referenced by forwardFillRegularOp(), forwardYieldOperandsToRegionResults(), and sinkElementwiseConversions().

◆ setTemporaryLayout()

template<typename T, typename = std::enable_if_t<std::is_same_v<T, OpOperand> || std::is_same_v<T, OpResult>>>
void mlir::xegpu::setTemporaryLayout ( const T & operandOrResult,
const DistributeLayoutAttr layout )

◆ setTensorDescLayout()

void mlir::xegpu::setTensorDescLayout ( Value value,
DistributeLayoutAttr layout )

Sets layout on the type of the tensor_desc value value, replacing any layout the type already has.

Definition at line 416 of file XeGPUUtils.cpp.

References mlir::Value::getType(), and mlir::Value::setType().

Referenced by forwardFillRegularOp(), propagateResultsToRegularOperands(), and updateFunctionOpInterface().

◆ setupBitCastResultLayout()

xegpu::DistributeLayoutAttr mlir::xegpu::setupBitCastResultLayout ( xegpu::LayoutKind layoutKind,
VectorType srcVecTy,
VectorType resVecTy,
DistributeLayoutAttr consumerLayout,
const uArch::uArch * uArch )

Setup the result layout attribute for a bitcast operation based on element type bitwidths.

Sets up the result layout for a bitcast operation.

This ensures the source layout can always be derived from the result layout.

When casting from a narrower to a wider element type (srcElemTyBitWidth < resElemTyBitWidth), the result layout's innermost dimension data sizes (inst_data, lane_data) are scaled up by the bitwidth ratio. This maintains the invariant that the source layout can be recovered by adjusting the result layout based on bitwidth ratio of input vs output.

When casting to a smaller bitwidth, adjusts the layout dimensions (sgData, instData, or laneData) by multiplying by the bitwidth ratio to ensure the result layout can be correctly divided back to the source layout during inference.

Examples:

  1. Casting f32 -> f16 (32-bit to 16-bit, bitWidthRatio = 2): Consumer layout: instData=[1, 16], subgroupSize=16 Source shape: [8, 32] Result layout: instData=[1, 32] (16 * 2) The innermost dimension is multiplied by 2 to maintain consistency.
  2. Casting f32 -> i8 (32-bit to 8-bit, bitWidthRatio = 4): Consumer instData=[1, 16], subgroupSize=16 Source shape: [4, 128] adjust the instData from [1, 16] to [1, 16 * 4 = 64]
  3. Casting i8 -> i32 (8-bit to 32-bit, bitWidthRatio = 1/4): Consumer layout: laneLayout=[1, 16], laneData=[1, 4] No adjustment needed - returns consumer layout directly.

Definition at line 2843 of file XeGPULayoutImpl.cpp.

References adjustInnermostDimForDivisibility().

◆ setupDpasLayout()

std::optional< std::tuple< DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr > > mlir::xegpu::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).

The numSg and consumerLayout (optional) are only used by sg layout creation.

◆ setupDpasMxLayout()

std::optional< std::tuple< DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr, DistributeLayoutAttr > > mlir::xegpu::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).

The numSg and consumerLayout (optional) are only used by sg layout creation. A_scale and B_scale are optional.

◆ setupInsertStridedSliceResultLayout()

DistributeLayoutAttr mlir::xegpu::setupInsertStridedSliceResultLayout ( LayoutKind layoutKind,
VectorType srcVectorTy,
VectorType resVectorTy,
DistributeLayoutAttr consumerLayout,
const uArch::uArch * uArch )

Sets up the result layout for an insert strided slice operation.

Creates a result layout based on the specified layout kind (InstData or Lane).

◆ setupInterleaveResultLayout()

xegpu::DistributeLayoutAttr mlir::xegpu::setupInterleaveResultLayout ( xegpu::LayoutKind layoutKind,
VectorType srcVecTy,
VectorType resVecTy,
DistributeLayoutAttr consumerLayout,
const uArch::uArch * uArch )

Sets up the result layout for an interleave operation to ensure the source layout can be safely derived.

Interleave doubles the innermost dimension, so the result layout must ensure that laneData is at least 2 (or a multiple of 2), and instData must be divisible by innermostDimLaneLayout * 2.

Interleave doubles the innermost dimension, so the result layout must ensure that laneData is a multiple of 2, and instData must be divisible by innermostDimLaneLayout * 2.

Example: Interleave: vector<128x256xf4> -> vector<128x512xf4> Consumer layout: laneLayout=[1, 16], laneData=[1, 4], instData=[1, 64] Result layout adjustment to ensure source can be safely inferred:

  • laneData must be >= 2 and multiple of 2 (so source = laneData/2 is valid)
  • instData must be divisible by (16 * 2 = 32) (so source = instData/2 is valid)
  • Adjusted instData: ensure (instData % 32 == 0)

Definition at line 2886 of file XeGPULayoutImpl.cpp.

References adjustInnermostDimForDivisibility().

◆ setupLoadGatherAnchorLayout()

DistributeLayoutAttr mlir::xegpu::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.

contigChunkSize is the per-lane contiguous run the offsets allow, from the op's contiguity attribute (1 when it is absent). Use a default scatter IO layout when consumerLayout is absent. numSg is needed only for that default in Subgroup mode.

◆ setupLoadMatrixAnchorLayout()

DistributeLayoutAttr mlir::xegpu::setupLoadMatrixAnchorLayout ( LayoutKind layoutKind,
VectorType vectorTy,
int contigChunkSize,
DistributeLayoutAttr consumerLayout,
int numSg,
const uArch::uArch * uArch )

Sets up the anchor layout for load matrix operation.

Use a default scatter IO layout when consumerLayout is absent. numSg is needed only for that default in Subgroup mode.

◆ setupLoadNdAnchorLayout()

DistributeLayoutAttr mlir::xegpu::setupLoadNdAnchorLayout ( LayoutKind layoutKind,
VectorType vectorTy,
DistributeLayoutAttr consumerLayout,
int numSg,
const uArch::uArch * uArch )

Sets up the anchor layout for a load_nd operation.

LoadNd takes a (downstream) consumer layout and validates it against uArch constraints; when valid, the consumer's inst_data / sg_layout are honored. Otherwise defaults derived from uArch block parameters are used. Use the block load's default when consumerLayout is absent. numSg is needed only for that default in Subgroup mode.

◆ setupMultiReductionResultLayout()

xegpu::SliceAttr mlir::xegpu::setupMultiReductionResultLayout ( xegpu::LayoutKind layoutKind,
VectorType srcVecTy,
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:

Sets up layout for reduction operations by creating a SliceAttr for the result.

Layout propagation visits a producer after its consumers, in one backward scan. The consumerLayout passed to these helpers is the layout requested by the nearest consumer, or null if none requests one. They do not pick among or merge several consumers' layouts; an inconsistent consumer is reconciled afterwards by ResolveLayoutConflicts, which inserts a convert_layout on that edge. Sets up layout for Multi-Reduction operations by creating a SliceAttr for the result.

This function first attempts to construct a source layout that, when sliced along reduction dimensions, produces a result layout compatible with the consumer's preferred layout. This minimizes data redistribution overhead. The SliceAttr for the result is then created based on the derived source layout and the specified reduction dimensions.

Algorithm Overview: This function attempts to construct a source layout that, when sliced along reduction dimensions, produces a result layout compatible with the consumer layout.

For subgroup layouts, it first tries to align the source layout's subgroup layout and data with the consumer's layout on non-reduction dimensions. Then, it distributes remaining subgroups across reduction dimensions. When the consumer slices exactly reductionDims, it reuses the slice's parent for the source and adjusts sg_data on the reduction dimensions to fit the source extent. This is a best-effort alignment: the goal is to pick a source layout that minimizes redistribution against the consumer layout.

If the resulting source layout still differs from what some consumer expects (e.g. a second, inconsistent consumer), that mismatch is reconciled later by layout conflict resolution (ResolveLayoutConflicts), which inserts a convert_layout op.

InstData kind: computeReductionLaneLayoutAndData derives lane_layout, lane_data, and inst_data. It can preserve a reused parent's larger inst_data on non-reduced dimensions.

Lane kind: a consumer sliced over exactly reductionDims is reused. This preserves the lane layout chosen during instruction-data propagation. For other consumer layouts, computeReductionLaneLayoutAndData derives lane_layout and lane_data. See that helper for inst_data and lane layout examples.

The function returns the result layout (the SliceAttr). The source layout it decides on is the parent of that slice. The subgroup examples below show both layouts.

Subgroup layout examples:

  1. Row reduction on a 2D tensor: srcShape=[32, 128], reductionDims=[1], resShape=[32], subgroupSize=16, numSg=32
    • Consumer Layout: #xegpu.slice<#xegpu.layout<sg_layout=[4, 8], sg_data=[8, 8]>, dims = [1]>
    • Source Layout (decided by this function): #xegpu.layout<sg_layout=[4, 8], sg_data=[8, 16]>
    • Result Layout (returned): #xegpu.slice<#xegpu.layout<sg_layout=[4, 8], sg_data=[8, 16]>, dims = [1]> The consumer slices exactly the reduction dim, so its parent layout is reused for the source: sg_layout is kept, but the source's sg_data on the reduction dim is grown from 8 to 16 (= srcShape[1] / sg_layout[1] = 128 / 8) so the source tile is evenly distributed over the reduction dim. The non-reduction dimensions keep the consumer's distribution.
  2. Same shapes as above, but the consumer has no reusable slice layout. Copy its subgroup distribution onto non-reduction dims and assign the remaining subgroups to reduction dims. 2a. * Consumer Layout: #xegpu.layout<sg_layout=[32], sg_data=[1]>
    • Source Layout (decided by this function): #xegpu.layout<sg_layout=[32, 1], sg_data=[1, 128]>
    • Result Layout (returned): #xegpu.slice<#xegpu.layout<sg_layout=[32, 1], sg_data=[1, 128]>, dims = [1]> All 32 subgroups are assigned to non-reduction dim 0. Dim 1 stays within each subgroup (sg_layout=1), so its sg_data is 128. 2b. * Consumer Layout: #xegpu.slice<#xegpu.layout<sg_layout=[8, 2, 2], sg_data=[4, 64, 32]>, dims = [1, 2]>
    • Source Layout (decided by this function): #xegpu.layout<sg_layout=[8, 4], sg_data=[4, 32]>
    • Result Layout (returned): #xegpu.slice<#xegpu.layout<sg_layout=[8, 4], sg_data=[4, 32]>, dims = [1]> The consumer slices dims [1, 2], but the reduction uses dim 1. Copy its effective sg_layout=[8] onto dim 0 and assign the remaining four subgroups to dim 1.

Definition at line 2605 of file XeGPULayoutImpl.cpp.

References buildInstDataLayoutWithLane(), buildLaneLayout(), buildLayout(), computeReductionLaneLayoutAndData(), mlir::computeShapeRatio(), mlir::detail::DenseArrayAttrImpl< int32_t >::get(), mlir::detail::DenseArrayAttrImpl< int64_t >::get(), InstData, Lane, and Subgroup.

◆ setupPrefetchNdAnchorLayout()

DistributeLayoutAttr mlir::xegpu::setupPrefetchNdAnchorLayout ( LayoutKind layoutKind,
TensorDescType tdescTy,
int numSg,
const uArch::uArch * uArch )

Sets up the anchor layout for a prefetch_nd operation.

PrefetchNd has no value result and thus no consumer; it picks its layout from uArch block parameters. numSg is only used for Subgroup-kind layouts.

◆ setupReductionResultLayout()

xegpu::SliceAttr mlir::xegpu::setupReductionResultLayout ( xegpu::LayoutKind layoutKind,
VectorType srcVectorTy,
const uArch::uArch * uArch )

Sets up layout for Reduction operations by creating a SliceAttr for the result.

Definition at line 2740 of file XeGPULayoutImpl.cpp.

References buildLaneLayout(), mlir::detail::DenseArrayAttrImpl< int64_t >::get(), InstData, Lane, result, and Subgroup.

◆ setupShapeCastResultLayout()

xegpu::DistributeLayoutAttr mlir::xegpu::setupShapeCastResultLayout ( xegpu::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 dims, so that the source layout can be safely derived by collapsing each split group.

Within a group, the leading dims the lanes do not split and the first dim they do split may stay partial. Every dim after that is stretched to full: lane_data becomes dim_size / lane_layout, and inst_data the dim size.

Example: shape_cast: vector<16x1024xf32> -> vector<16x32x32xf32> Consumer layout: inst_data = [1, 2, 8], lane_layout = [1, 2, 8], lane_data = [1, 1, 1] Adjusted: inst_data = [1, 2, 32], lane_layout = [1, 2, 8], lane_data = [1, 1, 4] The adjusted layout collapses to inst_data = [1, 64], lane_layout = [1, 16], lane_data = [1, 4] on the source, whereas the unadjusted one would have collapsed to a strided inst_data = [1, 16].

Stretching does not guarantee the result layout is collapsible: collapsing also requires each lane to own one contiguous run of the source dim, which the consumer's lane_layout can rule out. This function checks that restriction on the stretched layout and returns nullptr when it does not hold, rejecting the consumer layout.

Example of a rejected layout: shape_cast: vector<16x128xf32> -> vector<16x2x4x16xf32> Consumer layout: inst_data = [1, 2, 2, 4], lane_layout = [1, 2, 2, 4], lane_data = [1, 1, 1, 1] Adjusted: inst_data = [1, 2, 4, 16], lane_layout = [1, 2, 2, 4], lane_data = [1, 1, 2, 4] Each lane owns two runs of 4 elements, 16 apart, instead of the 8 contiguous source elements the collapsed lane_data = [1, 8] claims.

At subgroup level, if a group's sg tile is not contiguous in the collapsed source dim, the group's subgroups are moved to its outermost dims; the consumer then receives its layout through a convert_layout.

Example: shape_cast: vector<32x1024xbf16> -> vector<32x32x32xbf16> Consumer layout: sg_layout = [2, 1, 2], sg_data = [16, 32, 16] Adjusted: sg_layout = [2, 2, 1], sg_data = [16, 16, 32] The consumer's sg tile 32x16 is not contiguous in the collapsed dim 1024, so it has no source layout. The adjusted sg tile 16x32 is, and collapses to sg_layout = [2, 2], sg_data = [16, 512].

Definition at line 3031 of file XeGPULayoutImpl.cpp.

References isContiguousTiling(), matchSplitDimExpansion(), setupShapeCastSgResultLayout(), and Subgroup.

◆ setupStoreMatrixAnchorLayout()

xegpu::DistributeLayoutAttr mlir::xegpu::setupStoreMatrixAnchorLayout ( xegpu::LayoutKind layoutKind,
VectorType vectorTy,
int contigChunkSize,
int numSg,
const uArch::uArch * uArch )

Sets up the anchor layout for a store matrix operation.

numSg is only used for Subgroup-kind layouts.

Definition at line 2265 of file XeGPULayoutImpl.cpp.

References setupDefaultScatterIOLayout(), and mlir::xegpu::uArch::StoreScatter.

◆ setupStoreNdAnchorLayout()

xegpu::DistributeLayoutAttr mlir::xegpu::setupStoreNdAnchorLayout ( xegpu::LayoutKind layoutKind,
VectorType srcVecTy,
int numSg,
const uArch::uArch * uArch )

Sets up the anchor layout for a store_nd operation.

StoreNd does not consider a consumer layout (it is a data sink), and picks its layout from uArch block parameters. numSg is only used for Subgroup-kind layouts.

StoreNd picks its own layout based on uArch block parameters (it does not take a consumer layout, since it is a data sink).

Definition at line 1939 of file XeGPULayoutImpl.cpp.

References setupDefault2DBlockIOLayout(), and mlir::xegpu::uArch::Subgroup2DBlockStore.

◆ setupStoreScatterAnchorLayout()

xegpu::DistributeLayoutAttr mlir::xegpu::setupStoreScatterAnchorLayout ( xegpu::LayoutKind layoutKind,
VectorType vectorTy,
int contigChunkSize,
int numSg,
const uArch::uArch * uArch )

Sets up the anchor layout for a store scatter operation.

contigChunkSize is the per-lane contiguous run the offsets allow, from the op's contiguity attribute (1 when it is absent). numSg is only used for Subgroup-kind layouts.

Definition at line 2245 of file XeGPULayoutImpl.cpp.

References setupDefaultScatterIOLayout(), and mlir::xegpu::uArch::StoreScatter.

◆ sinkElementwiseConversions()

void mlir::xegpu::sinkElementwiseConversions ( OpBuilder & builder,
Operation * parentOp )

Sink xegpu.convert_layout ops past the elementwise operations they feed, so that an elementwise op runs in the coarser layout.

Optimize elementwise operations by sinking costly layout conversion.

m = vector.create_mask ... {L1} d = arith.mulf ... {L1} cm = xegpu.convert_layout m : L1 -> L2 cd = xegpu.convert_layout d : L1 -> L2 s = arith.select cm, cd, splat {L2}

becomes

s' = arith.select m, d, splat {L1} s = xegpu.convert_layout s' : L1 -> L2

We only sink if a coarser layout applies to an elementwise op

Definition at line 1828 of file XeGPUPropagateLayout.cpp.

References mlir::clone(), mlir::OpBuilder::clone(), mlir::computeProduct(), mlir::IROperand< DerivedT, IRValueT >::get(), mlir::Value::getDefiningOp(), getDistributeLayoutAttr(), mlir::Operation::getLoc(), mlir::Operation::getNumResults(), mlir::OpOperand::getOperandNumber(), mlir::Operation::getOpOperands(), mlir::Operation::getResult(), mlir::Value::getType(), mlir::OpTrait::hasElementwiseMappableTraits(), isTriviallyRematerializable(), removeLayoutAttr(), result, mlir::IROperand< DerivedT, IRValueT >::set(), setDistributeLayoutAttr(), mlir::OpBuilder::setInsertionPointAfter(), mlir::OpBuilder::setInsertionPointAfterValue(), and mlir::Operation::walk().

◆ subgroupReduction()

Value mlir::xegpu::subgroupReduction ( Location loc,
OpBuilder & builder,
Value input,
vector::CombiningKind kind,
uint32_t size,
arith::FastMathFlagsAttr fastmath = nullptr )

Given an input value representing per-lane data, this function returns the result after performing a reduction on the input over all lanes (number of lanes given by size).

This uses butterfly shuffles to perform the reduction in a log2(size) number of steps. NOTE: Implementation taken from TestVectorTransforms.cpp For float kinds, fastmath is set on every combining operation.

width =

mode =

Definition at line 584 of file XeGPUUtils.cpp.

References getFlags().

Referenced by lowerCrossLaneReductionToShuffles().

◆ walkBackward()

void mlir::xegpu::walkBackward ( Operation * root,
BackwardLayoutVisitor & visitor )

Walk function bodies under root in CFG post-order, visiting ops within each block back to front and nested regions before their parent op.

Region successors are visited before predecessors where possible. To break cycles, prefer a region that exits to the parent op; this visits scf.while's before region before its after region. The only consumers visited after the producer of their value are those across a loop back edge (scf.for's yield -> iter_args) and, for scf.while, the uses in its after region of what scf.condition passes on. A visitor can ask for the regions of a region op to be walked again (shouldRevisitRegions) once such a consumer has been seen; this happens at most once more than the number of region arguments of the op, per visit of the op.

Definition at line 186 of file XeGPULayoutImpl.cpp.

References mlir::Operation::walk(), and walkRegionBackward().

Referenced by recoverTemporaryLayouts().