MLIR 23.0.0git
XeGPUBlocking.cpp
Go to the documentation of this file.
1//===---- XeGPUBlocking.cpp ---- XeGPU Blocking Pass ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/Support/DebugLog.h"
23
24namespace mlir {
25namespace xegpu {
26#define GEN_PASS_DEF_XEGPUBLOCKING
27#include "mlir/Dialect/XeGPU/Transforms/Passes.h.inc"
28} // namespace xegpu
29} // namespace mlir
30
31#define DEBUG_TYPE "xegpu-blocking"
32
33using namespace mlir;
34
35namespace {
36
37// reslove the unrealized conversion cast ops generated when doing SCF
38// Structural Type Conversion. It will have two formats, N:1 vector
39// cast and 1:N vector cast. vector::insert_strided_slice ops will be
40// used for the first case, and vector::extract_strided_slice ops will be
41// used for the second case.
42static void
43resolveUnrealizedConversionCastOp(UnrealizedConversionCastOp castOp) {
44 ValueRange inputs = castOp.getInputs();
45 ValueRange outputs = castOp.getOutputs();
46
47 auto hasIdenticalVectorTypes = [](ValueRange values) {
48 auto types = values.getTypes();
49 return llvm::all_of(types, [&](Type type) {
50 return isa<VectorType>(type) && type == types.front();
51 });
52 };
53
54 // We only interest in the case where all inputs and outputs have the
55 // identical VectorTypes
56 if (!hasIdenticalVectorTypes(inputs) || !hasIdenticalVectorTypes(outputs)) {
57 LDBG() << "skip unrealized conversion cast op not emulating pack/unpack.";
58 return;
59 }
60
61 VectorType outputTy = dyn_cast<VectorType>(outputs[0].getType());
62 OpBuilder builder(castOp);
63 if (inputs.size() > 1 && outputs.size() == 1) {
64 // the castOp is emulating an unpack op
65 ArrayRef<int64_t> shape = outputTy.getShape();
67 builder, castOp.getLoc(), inputs, shape);
68 castOp->replaceAllUsesWith(ValueRange(result));
69 castOp->erase();
70 } else if (castOp.getNumResults() > 1 && castOp.getNumOperands() == 1) {
71 // the castOp is emulating a pack op
72 ArrayRef<int64_t> tileShape = outputTy.getShape();
74 builder, castOp.getLoc(), inputs[0], tileShape);
75 castOp->replaceAllUsesWith(results);
76 castOp->erase();
77 }
78}
79
80//===------------------------------------------------------------------------===//
81// The XeGPUBlockingPass leverages the unroll patterns for XeGPU and Vector ops
82// to partition operations that process large shapes into multiple operations on
83// smaller shapes, as specified by the inst_data in the layout attribute. This
84// enables each resulting operation to be efficiently mapped to a hardware
85// instruction.
86//===------------------------------------------------------------------------===//
87
88class XeGPUBlockingPass final
89 : public xegpu::impl::XeGPUBlockingBase<XeGPUBlockingPass> {
90public:
91 void runOnOperation() override;
92
93private:
94 // Get the tile shape for a given OpOperand or OpResult by examining the
95 // corresponding layout attribute. If layout is not present or is not a
96 // subgroup level layout, it returns std::nullopt.
97 template <typename T,
98 typename = std::enable_if_t<std::is_same_v<T, OpOperand> ||
99 std::is_same_v<T, OpResult>>>
100 std::optional<SmallVector<int64_t>>
101 getTileShape(const T &operandOrResult) const;
102
103 // Get the tile shape for a given operation.
104 std::optional<SmallVector<int64_t>> getTileShape(Operation *op) const;
105
106 // Determine if the operation requires unrolling. Return false if all operands
107 // and results have tile shapes identical to their original types. Otherwise,
108 // return true.
109 bool needsUnroll(Operation *op) const;
110};
111} // namespace
112
113template <typename T, typename>
114std::optional<SmallVector<int64_t>>
115XeGPUBlockingPass::getTileShape(const T &operandOrResult) const {
116 Value value;
117 if constexpr (std::is_same_v<T, OpOperand>) {
118 value = operandOrResult.get();
119 } else {
120 value = (Value)operandOrResult;
121 }
122
123 xegpu::DistributeLayoutAttr layout =
124 xegpu::getDistributeLayoutAttr(operandOrResult);
125 if (layout && layout.isForSubgroup()) {
126 if (!layout.getEffectiveInstDataAsInt().empty()) {
127 SmallVector<int64_t> instData = layout.getEffectiveInstDataAsInt();
128 return instData;
129 }
130 if (auto type = dyn_cast<ShapedType>(value.getType()))
131 return llvm::to_vector(type.getShape());
132 }
133 LDBG() << "failed to getTileShape for: " << value;
134 return std::nullopt;
135}
136
137std::optional<SmallVector<int64_t>>
138XeGPUBlockingPass::getTileShape(Operation *op) const {
139 if (isa<xegpu::CreateNdDescOp, xegpu::UpdateNdOffsetOp, xegpu::LoadMatrixOp>(
140 op))
141 return getTileShape(op->getOpResult(0));
142 if (isa<xegpu::PrefetchNdOp, xegpu::LoadNdOp, xegpu::PrefetchOp,
143 xegpu::StoreMatrixOp>(op))
144 return getTileShape(op->getOpOperand(0));
145 if (isa<xegpu::StoreNdOp>(op))
146 return getTileShape(op->getOpOperand(1));
147
148 if (isa<xegpu::LoadGatherOp>(op))
149 return getTileShape(op->getOpResult(0));
150
151 if (auto convertLayoutOp = dyn_cast<xegpu::ConvertLayoutOp>(op)) {
152 auto inputInstData =
153 convertLayoutOp.getInputLayout().getEffectiveInstDataAsInt();
154 auto targetInstData =
155 convertLayoutOp.getTargetLayout().getEffectiveInstDataAsInt();
156 // return the one with larger size
157 if (computeProduct(inputInstData) >= computeProduct(targetInstData))
158 return inputInstData;
159 else
160 return targetInstData;
161 }
162
163 if (isa<xegpu::StoreScatterOp>(op))
164 return getTileShape(op->getOpOperand(0));
165
166 if (isa<xegpu::DpasOp>(op)) {
167 std::optional<SmallVector<int64_t>> aTile =
169 std::optional<SmallVector<int64_t>> bTile =
171
172 if (!aTile || aTile->size() != 2 || !bTile || bTile->size() != 2)
173 return std::nullopt;
174
175 // semantic check for A and B
176 if ((*aTile)[1] != (*bTile)[0])
177 return std::nullopt;
178
179 // semantic check for C
180 if (op->getNumOperands() == 3) {
181 std::optional<SmallVector<int64_t>> cTile =
183 int64_t expectedCTile[2] = {(*aTile)[0], (*bTile)[1]};
184 if (!cTile || !llvm::equal(*cTile, expectedCTile))
185 return std::nullopt;
186 }
187
188 return SmallVector<int64_t>({(*aTile)[0], (*aTile)[1], (*bTile)[1]});
189 }
190
192 return getTileShape(op->getOpResult(0));
193
194 if (isa<vector::MultiDimReductionOp>(op))
195 return getTileShape(op->getOpOperand(0));
196
197 if (isa<vector::TransposeOp, vector::BroadcastOp, vector::StepOp,
198 vector::ShapeCastOp, vector::ConstantMaskOp, vector::CreateMaskOp>(
199 op))
200 return getTileShape(op->getOpResult(0));
201
202 return std::nullopt;
203}
204
205bool XeGPUBlockingPass::needsUnroll(Operation *op) const {
206 // skip the op if any of its operands or results has workgroup level layouts
207 bool hasWgLayoutOperands =
208 llvm::any_of(op->getOpOperands(), [](OpOperand &opr) {
209 xegpu::DistributeLayoutAttr layout =
210 xegpu::getDistributeLayoutAttr(opr);
211 return layout && layout.isForWorkgroup();
212 });
213 bool hasWgLayoutResults =
214 llvm::any_of(op->getOpResults(), [](OpResult result) {
215 xegpu::DistributeLayoutAttr layout =
216 xegpu::getDistributeLayoutAttr(result);
217 return layout && layout.isForWorkgroup();
218 });
219 if (hasWgLayoutOperands || hasWgLayoutResults) {
220 LDBG() << "skip unrolling for op with workgroup level layout: " << *op;
221 return false;
222 }
223
224 auto isUnrollable = [](Value value, ArrayRef<int64_t> tileShape) {
225 Type valTy = value.getType();
226 if (auto tdescTy = dyn_cast<xegpu::TensorDescType>(valTy)) {
227 xegpu::DistributeLayoutAttr layout = tdescTy.getLayoutAttr();
228 return layout && !layout.getEffectiveInstDataAsInt().empty();
229 }
230 auto shapedType = dyn_cast<ShapedType>(valTy);
231 return shapedType && !llvm::equal(tileShape, shapedType.getShape());
232 };
233
234 bool hasUnrollableOperands =
235 llvm::any_of(op->getOpOperands(), [&](OpOperand &opr) {
236 std::optional<SmallVector<int64_t>> tileShape = getTileShape(opr);
237 return tileShape.has_value() && isUnrollable(opr.get(), *tileShape);
238 });
239 bool hasUnrollableResults =
240 llvm::any_of(op->getOpResults(), [&](OpResult result) {
241 std::optional<SmallVector<int64_t>> tileShape = getTileShape(result);
242 return tileShape.has_value() && isUnrollable(result, *tileShape);
243 });
244 // ConvertLayoutOp must be processed to drop the inst_data in the layout
245 bool isConvertLayoutWithInstData = false;
246 if (auto convertLayoutOp = dyn_cast<xegpu::ConvertLayoutOp>(op)) {
247 auto targettLayout = convertLayoutOp.getTargetLayout();
248 if (targettLayout && !targettLayout.getEffectiveInstDataAsInt().empty()) {
249 isConvertLayoutWithInstData = true;
250 }
251 }
252 return hasUnrollableOperands || hasUnrollableResults ||
253 isConvertLayoutWithInstData;
254}
255
256void XeGPUBlockingPass::runOnOperation() {
257 MLIRContext *ctx = &getContext();
258 Operation *op = getOperation();
259
261 signalPassFailure();
262 return;
263 }
264
265 auto getTileShapeAndCount = [](llvm::ArrayRef<int64_t> shape,
266 xegpu::DistributeLayoutAttr layout) {
267 int count = 1;
268 SmallVector<int64_t> tileShape(shape);
269 if (layout && !layout.getEffectiveInstDataAsInt().empty()) {
270 tileShape = layout.getEffectiveInstDataAsInt();
271 count = computeProduct(shape) / computeProduct(tileShape);
272 }
273 return std::make_pair(tileShape, count);
274 };
275
276 // Perform type conversion for SCF control folow ops
277 TypeConverter converter;
278 converter.addConversion([](Type type) -> Type { return type; });
279 converter.addConversion(
280 [&](RankedTensorType type,
281 SmallVectorImpl<Type> &result) -> std::optional<LogicalResult> {
282 Type elemTy = type.getElementType();
283 ArrayRef<int64_t> shape = type.getShape();
284
285 auto layout =
286 llvm::dyn_cast_if_present<xegpu::LayoutAttr>(type.getEncoding());
287 if (layout && layout.isForWorkgroup())
288 return failure();
289
290 int count;
291 SmallVector<int64_t> subShape;
292 std::tie(subShape, count) = getTileShapeAndCount(shape, layout);
293 auto newTy = VectorType::get(subShape, elemTy);
294 result.append(count, newTy);
295 return success();
296 });
297 converter.addConversion(
298 [&](xegpu::TensorDescType type,
299 SmallVectorImpl<Type> &result) -> std::optional<LogicalResult> {
300 Type elemTy = type.getElementType();
301 ArrayRef<int64_t> shape = type.getShape();
302
303 xegpu::DistributeLayoutAttr layout = type.getLayoutAttr();
304 if (layout && layout.isForWorkgroup())
305 return failure();
306
307 int count;
308 SmallVector<int64_t> subShape;
309 std::tie(subShape, count) = getTileShapeAndCount(shape, layout);
310
311 if (layout)
312 layout = layout.dropInstData();
313
314 auto newTy = xegpu::TensorDescType::get(
315 type.getContext(), subShape, elemTy, type.getEncoding(), layout);
316 result.append(count, newTy);
317 return success();
318 });
319
321
322 xegpu::UnrollOptions options;
323 options.setFilterConstraint(
324 [&](Operation *op) -> LogicalResult { return success(needsUnroll(op)); });
325
326 options.setNativeShapeFn([&](Operation *op) { return getTileShape(op); });
327
328 options.setUnrolledTypesFn([&](ShapedType type, ArrayRef<int64_t> tileShape,
329 bool returnSingleType = false) {
330 Type elemTy = type.getElementType();
331 Type newTy;
332
333 if (auto tdescTy = dyn_cast<xegpu::TensorDescType>(type)) {
334
335 Attribute encoding = tdescTy.getEncoding();
336
337 newTy =
338 xegpu::TensorDescType::get(ctx, tileShape, elemTy, encoding,
339 tdescTy.getLayoutAttr().dropInstData());
340 } else {
341 newTy = VectorType::get(tileShape, elemTy);
342 }
343
344 if (returnSingleType)
345 return SmallVector<Type>{newTy};
346 std::optional<SmallVector<int64_t>> ratio =
347 computeShapeRatio(type.getShape(), tileShape);
348 assert(ratio && "The shape of the type must be a multiple of tileShape.");
349 return SmallVector<Type>(computeProduct(*ratio), newTy);
350 });
351
352 RewritePatternSet patterns(ctx);
353 vector::UnrollVectorOptions vectorOptions;
354 vectorOptions.setNativeShapeFn(options.nativeShape);
355
357 vector::populateVectorUnrollPatterns(patterns, vectorOptions);
358
359 // Note: The pattern driver does op folding as well and clean up.
360 // But intermediate insert/extract strided slice ops with
361 // unrealized conversion cast ops in the middle does not get
362 // cleaned up in this step. One more round of folding is needed
363 // after the walk to resolve those unrealized conversion cast ops.
364 (void)applyPatternsGreedily(op, std::move(patterns));
365
366 op->walk([](Operation *op) {
367 // Remove the layout attributes cached per operands.
368 for (OpOperand &opr : op->getOpOperands()) {
369 std::string name = xegpu::getTemporaryLayoutName(opr);
370 if (op->hasAttrOfType<xegpu::DistributeLayoutAttr>(name))
371 op->removeAttr(name);
372 }
373
374 // Update the layout attributes per result.
375 for (OpResult result : op->getOpResults()) {
376 std::string name = xegpu::getTemporaryLayoutName(result);
377 if (auto layout = op->getAttrOfType<xegpu::DistributeLayoutAttr>(name)) {
378 op->removeAttr(name);
379 if (!isa<LoopLikeOpInterface>(op))
380 xegpu::setDistributeLayoutAttr(result, layout.dropInstData());
381 }
382 }
383
384 // Resolve unrealized conversion cast ops emulating pack/unpack
385 if (auto castOp = dyn_cast<UnrealizedConversionCastOp>(op))
386 resolveUnrealizedConversionCastOp(castOp);
387 });
388
389 // One more round of folding to clean up the intermediate
390 // insert/extract strided slice ops.
391 RewritePatternSet emptyPatterns(ctx);
392 (void)applyPatternsGreedily(op, std::move(emptyPatterns));
393}
return success()
b getContext())
static std::array< int64_t, 2 > getTileShape(ArrayRef< int64_t > operandShape, Type elementType, int64_t lineSizeBits)
Returns the number of 8 x [128|256|512] bit tiles that compose the given operand shape.
Definition MMAUtils.cpp:37
static llvm::ManagedStatic< PassManagerOptions > options
This class helps build Operations.
Definition Builders.h:209
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
OpResult getOpResult(unsigned idx)
Definition Operation.h:447
AttrClass getAttrOfType(StringAttr name)
Definition Operation.h:576
bool hasAttrOfType(NameT &&name)
Definition Operation.h:601
MutableArrayRef< OpOperand > getOpOperands()
Definition Operation.h:409
unsigned getNumOperands()
Definition Operation.h:372
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:823
result_range getOpResults()
Definition Operation.h:446
Attribute removeAttr(StringAttr name)
Remove the attribute with the specified name if it exists.
Definition Operation.h:626
OpOperand & getOpOperand(unsigned idx)
Definition Operation.h:414
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:430
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:389
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 hasElementwiseMappableTraits(Operation *op)
Together, Elementwise, Scalarizable, Vectorizable, and Tensorizable provide an easy way for scalar op...
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.
void populateXeGPUUnrollPatterns(RewritePatternSet &patterns, const UnrollOptions &options)
Collect a set of patterns to unroll xegpu operations to a smaller shapes.
void setDistributeLayoutAttr(const OpResult &Result, const DistributeLayoutAttr layout)
[to-be-deprecated] Sets the DistributeLayoutAttr for a given OpResult user should use setAnchorLayout...
bool recoverTemporaryLayouts(Operation *rootOp)
Attach layout attributes to all vector-type operands of operations within the given operation's neste...
void doSCFStructuralTypeConversionWithTensorType(Operation *op, TypeConverter converter)
Do type conversion for SCF structural ops, e.g., scf.for using SCF structure type convertion patterns...
DistributeLayoutAttr getDistributeLayoutAttr(const Value value)
Retrieves the DistributeLayoutAttr associated with a given Value.
std::string getTemporaryLayoutName(const OpOperand &operand)
Return the attribute name for the OpOperand to attach DistributeLayoutAttr.
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.
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:307
LogicalResult applyPatternsGreedily(Region &region, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
int64_t computeProduct(ArrayRef< int64_t > basis)
Self-explicit.
std::optional< SmallVector< int64_t > > computeShapeRatio(ArrayRef< int64_t > shape, ArrayRef< int64_t > subShape)
Return the multi-dimensional integral ratio of subShape to the trailing dimensions of shape.
UnrollVectorOptions & setNativeShapeFn(NativeShapeFnType fn)