MLIR 24.0.0git
GPUDialect.cpp
Go to the documentation of this file.
1//===- GPUDialect.cpp - MLIR Dialect for GPU Kernels implementation -------===//
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//
9// This file implements the GPU kernel-related dialect and its operations.
10//
11//===----------------------------------------------------------------------===//
12
14
21#include "mlir/IR/Attributes.h"
22#include "mlir/IR/Builders.h"
24#include "mlir/IR/BuiltinOps.h"
26#include "mlir/IR/Diagnostics.h"
28#include "mlir/IR/Matchers.h"
31#include "mlir/IR/SymbolTable.h"
37#include "llvm/ADT/STLExtras.h"
38#include "llvm/ADT/TypeSwitch.h"
39#include "llvm/Support/ErrorHandling.h"
40#include "llvm/Support/FormatVariadic.h"
41#include "llvm/Support/InterleavedRange.h"
42#include <cassert>
43#include <numeric>
44#include <optional>
45
46using namespace mlir;
47using namespace mlir::gpu;
48
49#include "mlir/Dialect/GPU/IR/GPUOpsDialect.cpp.inc"
50
51namespace {
52// Attribute storage definitions live in MLIRGPUBase. Keep interface metadata
53// here: some attribute interfaces build GPU/Arith/Math IR, and their models
54// belong with the operation implementation rather than the representations.
55template <typename... Attrs>
56void registerAttributeMetadata(
57 Dialect &dialect,
58 function_ref<void(TypeID, AbstractAttribute &&)> addAttribute) {
59 (addAttribute(Attrs::getTypeID(), AbstractAttribute::get<Attrs>(dialect)),
60 ...);
61}
62
63struct GPUDialectBytecodeInterface : BytecodeDialectInterface {
64 using BytecodeDialectInterface::BytecodeDialectInterface;
65
66 void writeVersion(DialectBytecodeWriter &writer) const override {
67 writer.writeVarInt(1);
68 }
69
70 std::unique_ptr<DialectVersion>
71 readVersion(DialectBytecodeReader &reader) const override {
72 uint64_t version;
73 if (failed(reader.readVarInt(version)))
74 return nullptr;
75 if (version != 1) {
76 reader.emitError("unsupported gpu dialect bytecode version");
77 return nullptr;
78 }
79 return std::make_unique<DialectVersion>();
80 }
81};
82} // namespace
83
84int64_t GPUMappingMaskAttr::getMaxNumPhysicalIds() const { return 64; }
85
86/// 8 4 0
87/// Example mask : 0 0 0 1 1 0 1 0 0
88///
89/// Active physical (resp. logical) is 2 (0), 4 (1) and 5 (2).
90/// Logical id for e.g. 5 (2) constructs filter (1 << 5 - 1).
91///
92/// Example mask : 0 0 0 1 1 0 1 0 0
93/// Example filter: 0 0 0 0 1 1 1 1 1
94/// Intersection : 0 0 0 0 1 0 1 0 0
95/// PopCnt : 2
96Value GPUMappingMaskAttr::createLogicalLinearMappingId(
97 OpBuilder &b, Value physicalLinearMappingId) const {
98 Location loc = physicalLinearMappingId.getLoc();
99 Value mask =
100 arith::ConstantOp::create(b, loc, b.getI64IntegerAttr(getMask()));
101 Value one = arith::ConstantOp::create(b, loc, b.getI64IntegerAttr(1));
102 Value filter = arith::ShLIOp::create(b, loc, one, physicalLinearMappingId);
103 filter = arith::SubIOp::create(b, loc, filter, one);
104 Value filteredId = arith::AndIOp::create(b, loc, mask, filter);
105 return math::CtPopOp::create(b, loc, filteredId);
106}
107
108/// 8 4 0
109/// Example mask : 0 0 0 1 1 0 1 0 0
110///
111/// Active physical (resp. logical) is 2 (0), 4 (1) and 5 (2).
112/// Logical id for e.g. 5 (2) constructs filter (1 << 5).
113///
114/// Example mask : 0 0 0 1 1 0 1 0 0
115/// Example filter: 0 0 0 1 0 0 0 0 0
116/// Intersection : 0 0 0 1 0 0 0 0 0
117/// Cmp : 1
118Value GPUMappingMaskAttr::createIsActiveIdPredicate(
119 OpBuilder &b, Value physicalLinearMappingId) const {
120 Location loc = physicalLinearMappingId.getLoc();
121 Value mask =
122 arith::ConstantOp::create(b, loc, b.getI64IntegerAttr(getMask()));
123 Value one = arith::ConstantOp::create(b, loc, b.getI64IntegerAttr(1));
124 Value filter = arith::ShLIOp::create(b, loc, one, physicalLinearMappingId);
125 Value filtered = arith::AndIOp::create(b, loc, mask, filter);
126 Value zero = arith::ConstantOp::create(b, loc, b.getI64IntegerAttr(0));
127 return arith::CmpIOp::create(b, loc, arith::CmpIPredicate::ne, filtered,
128 zero);
129}
130
131bool GPUDialect::isKernel(Operation *op) {
132 if (auto gpuFunc = dyn_cast<GPUFuncOp>(op))
133 return gpuFunc.isKernel();
134 return static_cast<bool>(
135 op->getDiscardableAttrOfType<UnitAttr>(getKernelFuncAttrName()));
136}
137
138namespace {
139/// This class defines the interface for handling inlining with gpu
140/// operations.
141struct GPUInlinerInterface : public DialectInlinerInterface {
142 using DialectInlinerInterface::DialectInlinerInterface;
143
144 /// All gpu dialect ops can be inlined.
145 bool isLegalToInline(Operation *, Region *, bool, IRMapping &) const final {
146 return true;
147 }
148};
149} // namespace
150
151void GPUDialect::initialize() {
152 addInterfaces<GPUDialectBytecodeInterface>();
153 addTypes<AsyncTokenType>();
154 addTypes<MMAMatrixType>();
155 addTypes<NamedBarrierType>();
156 addTypes<SparseDnTensorHandleType>();
157 addTypes<SparseSpMatHandleType>();
158 addTypes<SparseSpGEMMOpHandleType>();
159 // Match addAttributes while keeping the storage and interface instantiations
160 // in their respective implementation libraries.
161 registerAttributeMetadata<
162#define GET_ATTRDEF_LIST
163#include "mlir/Dialect/GPU/IR/GPUOpsAttributes.cpp.inc"
164 >(*this, [this](TypeID id, AbstractAttribute &&attribute) {
165 addAttribute(id, std::move(attribute));
166 });
168 addInterfaces<GPUInlinerInterface>();
169 declarePromisedInterface<bufferization::BufferDeallocationOpInterface,
170 TerminatorOp>();
171 declarePromisedInterfaces<ValueBoundsOpInterface, ClusterDimOp,
172 ClusterDimBlocksOp, ClusterIdOp, ClusterBlockIdOp,
173 BlockDimOp, BlockIdOp, GridDimOp, ThreadIdOp,
174 LaneIdOp, SubgroupIdOp, GlobalIdOp, NumSubgroupsOp,
175 SubgroupSizeOp, LaunchOp, SubgroupBroadcastOp>();
176 declarePromisedInterfaces<memref::IndexedAccessOpInterface,
177 SubgroupMmaLoadMatrixOp,
178 SubgroupMmaStoreMatrixOp>();
179}
180
181static std::string getSparseHandleKeyword(SparseHandleKind kind) {
182 switch (kind) {
184 return "sparse.dntensor_handle";
186 return "sparse.spmat_handle";
188 return "sparse.spgemmop_handle";
189 }
190 llvm_unreachable("unknown sparse handle kind");
191 return "";
192}
193
194Type GPUDialect::parseType(DialectAsmParser &parser) const {
195 // Parse the main keyword for the type.
196 StringRef keyword;
197 if (parser.parseKeyword(&keyword))
198 return Type();
199 MLIRContext *context = getContext();
200
201 // Handle 'async token' types.
202 if (keyword == "async.token")
203 return AsyncTokenType::get(context);
204
205 if (keyword == "mma_matrix") {
206 SMLoc beginLoc = parser.getNameLoc();
207
208 // Parse '<'.
209 if (parser.parseLess())
210 return nullptr;
211
212 // Parse the size and elementType.
214 Type elementType;
215 if (parser.parseDimensionList(shape, /*allowDynamic=*/false) ||
216 parser.parseType(elementType))
217 return nullptr;
218
219 // Parse ','
220 if (parser.parseComma())
221 return nullptr;
222
223 // Parse operand.
224 std::string operand;
225 if (failed(parser.parseOptionalString(&operand)))
226 return nullptr;
227
228 // Parse '>'.
229 if (parser.parseGreater())
230 return nullptr;
231
233 parser.getEncodedSourceLoc(beginLoc)),
234 shape, elementType, operand);
235 }
236
237 if (keyword == "named_barrier")
238 return NamedBarrierType::get(context);
239
241 return SparseDnTensorHandleType::get(context);
243 return SparseSpMatHandleType::get(context);
245 return SparseSpGEMMOpHandleType::get(context);
246
247 parser.emitError(parser.getNameLoc(), "unknown gpu type: " + keyword);
248 return Type();
249}
250// TODO: print refined type here. Notice that should be corresponding to the
251// parser
252void GPUDialect::printType(Type type, DialectAsmPrinter &os) const {
253 TypeSwitch<Type>(type)
254 .Case<AsyncTokenType>([&](Type) { os << "async.token"; })
255 .Case<NamedBarrierType>([&](Type) { os << "named_barrier"; })
256 .Case<SparseDnTensorHandleType>([&](Type) {
258 })
259 .Case<SparseSpMatHandleType>(
261 .Case<SparseSpGEMMOpHandleType>([&](Type) {
263 })
264 .Case([&](MMAMatrixType fragTy) {
265 os << "mma_matrix<";
266 auto shape = fragTy.getShape();
267 for (auto dim = shape.begin(), e = shape.end() - 1; dim != e; ++dim)
268 os << *dim << 'x';
269 os << shape.back() << 'x' << fragTy.getElementType();
270 os << ", \"" << fragTy.getOperand() << "\"" << '>';
271 })
272 .DefaultUnreachable("unexpected 'gpu' type kind");
273}
274
275static LogicalResult verifyKnownLaunchSizeAttr(Operation *op,
276 NamedAttribute attr) {
277 auto array = dyn_cast<DenseI32ArrayAttr>(attr.getValue());
278 if (!array)
279 return op->emitOpError(Twine(attr.getName()) +
280 " must be a dense i32 array");
281 if (array.size() != 3)
282 return op->emitOpError(Twine(attr.getName()) +
283 " must contain exactly 3 elements");
284 return success();
285}
286
287LogicalResult GPUDialect::verifyOperationAttribute(Operation *op,
288 NamedAttribute attr) {
289 if (attr.getName() == getKnownBlockSizeAttrHelper().getName())
290 return verifyKnownLaunchSizeAttr(op, attr);
291 if (attr.getName() == getKnownGridSizeAttrHelper().getName())
292 return verifyKnownLaunchSizeAttr(op, attr);
293 if (attr.getName() == getKnownClusterSizeAttrHelper().getName())
294 return verifyKnownLaunchSizeAttr(op, attr);
295 if (!llvm::isa<UnitAttr>(attr.getValue()) ||
296 attr.getName() != getContainerModuleAttrName())
297 return success();
298
299 auto module = dyn_cast<ModuleOp>(op);
300 if (!module)
301 return op->emitError("expected '")
302 << getContainerModuleAttrName() << "' attribute to be attached to '"
303 << ModuleOp::getOperationName() << '\'';
304 return success();
305}
306
307/// Parses an optional list of async operands with an optional leading keyword.
308/// (`async`)? (`[` ssa-id-list `]`)?
309///
310/// This method is used by the tablegen assembly format for async ops as well.
311static ParseResult parseAsyncDependencies(
312 OpAsmParser &parser, Type &asyncTokenType,
314 auto loc = parser.getCurrentLocation();
315 if (succeeded(parser.parseOptionalKeyword("async"))) {
316 if (parser.getNumResults() == 0)
317 return parser.emitError(loc, "needs to be named when marked 'async'");
318 asyncTokenType = parser.getBuilder().getType<AsyncTokenType>();
319 }
320 return parser.parseOperandList(asyncDependencies,
322}
323
324/// Prints optional async dependencies with its leading keyword.
325/// (`async`)? (`[` ssa-id-list `]`)?
326// Used by the tablegen assembly format for several async ops.
328 Type asyncTokenType,
329 OperandRange asyncDependencies) {
330 if (asyncTokenType)
331 printer << "async";
332 if (asyncDependencies.empty())
333 return;
334 if (asyncTokenType)
335 printer << ' ';
336 printer << llvm::interleaved_array(asyncDependencies);
337}
338
339// GPU Memory attributions functions shared by LaunchOp and GPUFuncOp.
340/// Parses a GPU function memory attribution.
341///
342/// memory-attribution ::= (`workgroup` `(` ssa-id-and-type-list `)`)?
343/// (`private` `(` ssa-id-and-type-list `)`)?
344///
345/// Note that this function parses only one of the two similar parts, with the
346/// keyword provided as argument.
347static ParseResult
348parseAttributions(OpAsmParser &parser, StringRef keyword,
350 // If we could not parse the keyword, just assume empty list and succeed.
351 if (failed(parser.parseOptionalKeyword(keyword)))
352 return success();
353
355 /*allowType=*/true);
356}
357
358static void printAttributions(OpAsmPrinter &p, StringRef keyword,
360 ArrayAttr attributes = {}) {
361 if (values.empty())
362 return;
363
364 p << ' ' << keyword << '(';
365 llvm::interleaveComma(
366 llvm::enumerate(values), p, [&p, attributes](auto pair) {
367 BlockArgument v = pair.value();
368 p << v << " : " << v.getType();
369
370 size_t attributionIndex = pair.index();
371 DictionaryAttr attrs;
372 if (attributes && attributionIndex < attributes.size())
373 attrs = llvm::cast<DictionaryAttr>(attributes[attributionIndex]);
374 if (attrs)
375 p.printOptionalAttrDict(attrs.getValue());
376 });
377 p << ')';
378}
379
380/// Verifies a GPU function memory attribution.
381static LogicalResult verifyAttributions(Operation *op,
382 ArrayRef<BlockArgument> attributions,
383 gpu::AddressSpace memorySpace) {
384 for (Value v : attributions) {
385 auto type = llvm::dyn_cast<MemRefType>(v.getType());
386 if (!type)
387 return op->emitOpError() << "expected memref type in attribution";
388
389 // We can only verify the address space if it hasn't already been lowered
390 // from the AddressSpaceAttr to a target-specific numeric value.
391 auto addressSpace =
392 llvm::dyn_cast_or_null<gpu::AddressSpaceAttr>(type.getMemorySpace());
393 if (!addressSpace)
394 continue;
395 if (addressSpace.getValue() != memorySpace)
396 return op->emitOpError()
397 << "expected memory space " << stringifyAddressSpace(memorySpace)
398 << " in attribution";
399 }
400 return success();
401}
402
403//===----------------------------------------------------------------------===//
404// AllReduceOp
405//===----------------------------------------------------------------------===//
406
407static LogicalResult verifyReduceOpAndType(gpu::AllReduceOperation opName,
408 Type resType) {
409 using Kind = gpu::AllReduceOperation;
410 if (llvm::is_contained({Kind::MINNUMF, Kind::MAXNUMF, Kind::MINIMUMF,
411 Kind::MAXIMUMF, Kind::MINIMUMNUMF, Kind::MAXIMUMNUMF},
412 opName)) {
413 if (!isa<FloatType>(resType))
414 return failure();
415 }
416
417 if (llvm::is_contained({Kind::MINSI, Kind::MINUI, Kind::MAXSI, Kind::MAXUI,
418 Kind::AND, Kind::OR, Kind::XOR},
419 opName)) {
420 if (!isa<IntegerType>(resType))
421 return failure();
422 }
423
424 return success();
425}
426
427LogicalResult gpu::AllReduceOp::verifyRegions() {
428 if (getBody().empty() != getOp().has_value())
429 return emitError("expected either an op attribute or a non-empty body");
430 if (!getBody().empty()) {
431 if (getBody().getNumArguments() != 2)
432 return emitError("expected two region arguments");
433 for (auto argument : getBody().getArguments()) {
434 if (argument.getType() != getType())
435 return emitError("incorrect region argument type");
436 }
437 unsigned yieldCount = 0;
438 for (Block &block : getBody()) {
439 if (auto yield = dyn_cast<gpu::YieldOp>(block.getTerminator())) {
440 if (yield.getNumOperands() != 1)
441 return emitError("expected one gpu.yield operand");
442 if (yield.getOperand(0).getType() != getType())
443 return emitError("incorrect gpu.yield type");
444 ++yieldCount;
445 }
446 }
447 if (yieldCount == 0)
448 return emitError("expected gpu.yield op in region");
449 } else {
450 gpu::AllReduceOperation opName = *getOp();
451 if (failed(verifyReduceOpAndType(opName, getType()))) {
452 return emitError() << '`' << gpu::stringifyAllReduceOperation(opName)
453 << "` reduction operation is not compatible with type "
454 << getType();
455 }
456 }
457
458 return success();
459}
460
462 auto launchOp = dyn_cast<gpu::LaunchOp>(op->getParentOp());
463 if (!launchOp)
464 return false;
465
466 Region &body = launchOp.getBody();
467 assert(!body.empty() && "Invalid region");
468
469 // Only convert ops in gpu::launch entry block for now.
470 return op->getBlock() == &body.front();
471}
472
473OpFoldResult gpu::AllReduceOp::fold(FoldAdaptor /*adaptor*/) {
474 if (!getUniform() && canMakeGroupOpUniform(*this)) {
475 setUniform(true);
476 return getResult();
477 }
478
479 return nullptr;
480}
481
482//===----------------------------------------------------------------------===//
483// SubgroupReduceOp
484//===----------------------------------------------------------------------===//
485
486LogicalResult gpu::SubgroupReduceOp::verify() {
487 Type elemType = getType();
488 if (auto vecTy = dyn_cast<VectorType>(elemType)) {
489 if (vecTy.isScalable())
490 return emitOpError() << "is not compatible with scalable vector types";
491
492 elemType = vecTy.getElementType();
493 }
494
495 gpu::AllReduceOperation opName = getOp();
496 if (failed(verifyReduceOpAndType(opName, elemType))) {
497 return emitError() << '`' << gpu::stringifyAllReduceOperation(opName)
498 << "` reduction operation is not compatible with type "
499 << getType();
500 }
501
502 auto clusterSize = getClusterSize();
503 if (clusterSize) {
504 uint32_t size = *clusterSize;
505 if (!llvm::isPowerOf2_32(size)) {
506 return emitOpError() << "cluster size " << size
507 << " is not a power of two";
508 }
509 }
510
511 uint32_t stride = getClusterStride();
512 if (stride != 1 && !clusterSize) {
513 return emitOpError() << "cluster stride can only be specified if cluster "
514 "size is specified";
515 }
516 if (!llvm::isPowerOf2_32(stride)) {
517 return emitOpError() << "cluster stride " << stride
518 << " is not a power of two";
519 }
520
521 return success();
522}
523
524OpFoldResult gpu::SubgroupReduceOp::fold(FoldAdaptor /*adaptor*/) {
525 if (getClusterSize() == 1)
526 return getValue();
527
528 if (!getUniform() && canMakeGroupOpUniform(*this)) {
529 setUniform(true);
530 return getResult();
531 }
532
533 return nullptr;
534}
535
536//===----------------------------------------------------------------------===//
537// AsyncOpInterface
538//===----------------------------------------------------------------------===//
539
541 op->insertOperands(0, {token});
542 if (!op->template hasTrait<OpTrait::AttrSizedOperandSegments>())
543 return;
544 auto attrName =
546 auto sizeAttr = dyn_cast_or_null<DenseI32ArrayAttr>(
547 op->getInherentAttr(attrName).value_or(Attribute{}));
548
549 // Async dependencies is the only variadic operand.
550 if (!sizeAttr)
551 return;
552
553 SmallVector<int32_t, 8> sizes(sizeAttr.asArrayRef());
554 ++sizes.front();
555 op->setInherentAttr(StringAttr::get(op->getContext(), attrName),
557}
558
559//===----------------------------------------------------------------------===//
560// LaunchOp
561//===----------------------------------------------------------------------===//
562
563void LaunchOp::build(OpBuilder &builder, OperationState &result,
564 Value gridSizeX, Value gridSizeY, Value gridSizeZ,
565 Value getBlockSizeX, Value getBlockSizeY,
566 Value getBlockSizeZ, Value dynamicSharedMemorySize,
567 Type asyncTokenType, ValueRange asyncDependencies,
568 Value asyncObject, TypeRange workgroupAttributions,
569 TypeRange privateAttributions, Value clusterSizeX,
570 Value clusterSizeY, Value clusterSizeZ,
571 FlatSymbolRefAttr module, FlatSymbolRefAttr function) {
572 OpBuilder::InsertionGuard g(builder);
573
574 if (!workgroupAttributions.empty())
575 result.addAttribute(
576 getWorkgroupAttributionsAttrName(result.name),
577 builder.getI64IntegerAttr(workgroupAttributions.size()));
578
579 // Add Op operands.
580 result.addOperands(asyncDependencies);
581 if (asyncTokenType)
582 result.types.push_back(builder.getType<AsyncTokenType>());
583
584 // Add grid and block sizes as op operands, followed by the data operands.
585 result.addOperands({gridSizeX, gridSizeY, gridSizeZ, getBlockSizeX,
586 getBlockSizeY, getBlockSizeZ});
587 if (clusterSizeX)
588 result.addOperands(clusterSizeX);
589 if (clusterSizeY)
590 result.addOperands(clusterSizeY);
591 if (clusterSizeZ)
592 result.addOperands(clusterSizeZ);
593 if (dynamicSharedMemorySize)
594 result.addOperands(dynamicSharedMemorySize);
595 if (asyncObject)
596 result.addOperands(asyncObject);
597
598 // Add optional module and function attributes.
599 if (module)
600 result.addAttribute(getModuleAttrName(result.name), module);
601 if (function)
602 result.addAttribute(getFunctionAttrName(result.name), function);
603
604 // Create a kernel body region with kNumConfigRegionAttributes + N memory
605 // attributions, where the first kNumConfigRegionAttributes arguments have
606 // `index` type and the rest have the same types as the data operands.
607 Region *kernelRegion = result.addRegion();
608 Block *body = builder.createBlock(kernelRegion);
609 // TODO: Allow passing in proper locations here.
610 for (unsigned i = 0; i < kNumConfigRegionAttributes; ++i)
611 body->addArgument(builder.getIndexType(), result.location);
612 // Add WorkGroup & Private attributions to the region arguments.
613 for (Type argTy : workgroupAttributions)
614 body->addArgument(argTy, result.location);
615 for (Type argTy : privateAttributions)
616 body->addArgument(argTy, result.location);
617 // Fill OperandSegmentSize Attribute.
618 SmallVector<int32_t, 12> segmentSizes(12, 1);
619 segmentSizes.front() = asyncDependencies.size();
620 segmentSizes[7] = clusterSizeX ? 1 : 0;
621 segmentSizes[8] = clusterSizeY ? 1 : 0;
622 segmentSizes[9] = clusterSizeZ ? 1 : 0;
623 segmentSizes[10] = dynamicSharedMemorySize ? 1 : 0;
624 segmentSizes[11] = asyncObject ? 1 : 0;
625 result.addAttribute(getOperandSegmentSizeAttr(),
626 builder.getDenseI32ArrayAttr(segmentSizes));
627}
628
629KernelDim3 LaunchOp::getBlockIds() {
630 assert(!getBody().empty() && "LaunchOp body must not be empty.");
631 auto args = getBody().getArguments();
632 return KernelDim3{args[0], args[1], args[2]};
633}
634
635KernelDim3 LaunchOp::getThreadIds() {
636 assert(!getBody().empty() && "LaunchOp body must not be empty.");
637 auto args = getBody().getArguments();
638 return KernelDim3{args[3], args[4], args[5]};
639}
640
641KernelDim3 LaunchOp::getGridSize() {
642 assert(!getBody().empty() && "LaunchOp body must not be empty.");
643 auto args = getBody().getArguments();
644 return KernelDim3{args[6], args[7], args[8]};
645}
646
647KernelDim3 LaunchOp::getBlockSize() {
648 assert(!getBody().empty() && "LaunchOp body must not be empty.");
649 auto args = getBody().getArguments();
650 return KernelDim3{args[9], args[10], args[11]};
651}
652
653std::optional<KernelDim3> LaunchOp::getClusterIds() {
654 assert(!getBody().empty() && "LaunchOp body must not be empty.");
655 if (!hasClusterSize())
656 return std::nullopt;
657 auto args = getBody().getArguments();
658 return KernelDim3{args[12], args[13], args[14]};
659}
660
661std::optional<KernelDim3> LaunchOp::getClusterSize() {
662 assert(!getBody().empty() && "LaunchOp body must not be empty.");
663 if (!hasClusterSize())
664 return std::nullopt;
665 auto args = getBody().getArguments();
666 return KernelDim3{args[15], args[16], args[17]};
667}
668
669KernelDim3 LaunchOp::getGridSizeOperandValues() {
670 auto operands = getOperands().drop_front(getAsyncDependencies().size());
671 return KernelDim3{operands[0], operands[1], operands[2]};
672}
673
674KernelDim3 LaunchOp::getBlockSizeOperandValues() {
675 auto operands = getOperands().drop_front(getAsyncDependencies().size());
676 return KernelDim3{operands[3], operands[4], operands[5]};
677}
678
679std::optional<KernelDim3> LaunchOp::getClusterSizeOperandValues() {
680 auto operands = getOperands().drop_front(getAsyncDependencies().size());
681 if (!hasClusterSize())
682 return std::nullopt;
683 return KernelDim3{operands[6], operands[7], operands[8]};
684}
685
686template <typename OpTy>
687static LogicalResult verifyLaunchAsyncModel(OpTy op) {
688 if (!op.getAsyncDependencies().empty() && !op.getAsyncToken())
689 return op.emitOpError("dependency operands require the dependency-based "
690 "async model i.e. returning a token");
691 if (op.getAsyncToken() && op.getAsyncObject())
692 return op.emitOpError("stream-based and dependency-based async models are "
693 "mutually exclusive");
694 if (op.getNumResults() == 0 && op.getAsyncToken())
695 return op.emitOpError("needs to be named when async keyword is specified");
696 return success();
697}
698
699LogicalResult LaunchOp::verify() {
700 if (verifyLaunchAsyncModel(*this).failed())
701 return failure();
702
703 if (!(hasClusterSize()) &&
704 (getClusterSizeX() || getClusterSizeY() || getClusterSizeZ()))
705 return emitOpError() << "cluster size must be all present";
706 return success();
707}
708
709LogicalResult LaunchOp::verifyRegions() {
710 // Kernel launch takes kNumConfigOperands leading operands for grid/block
711 // sizes and transforms them into kNumConfigRegionAttributes region arguments
712 // for block/thread identifiers and grid/block sizes.
713 if (getBody().empty()) {
714 return emitOpError("body region is empty");
715 }
716 unsigned actualNumRegionArgs = getBody().getNumArguments();
717 unsigned expectedNumRegionArgs =
718 getNumConfigRegionAttributes() + getNumWorkgroupAttributions();
719 if (actualNumRegionArgs < expectedNumRegionArgs) {
720 return emitOpError("expected at least ")
721 << expectedNumRegionArgs << " region arguments, but got "
722 << actualNumRegionArgs;
723 }
724
725 // Verify Attributions Address Spaces.
726 if (failed(verifyAttributions(getOperation(), getWorkgroupAttributionBBArgs(),
727 GPUDialect::getWorkgroupAddressSpace())) ||
728 failed(verifyAttributions(getOperation(), getPrivateAttributions(),
729 GPUDialect::getPrivateAddressSpace())))
730 return failure();
731
732 // Block terminators without successors are expected to exit the kernel region
733 // and must be `gpu.terminator`.
734 for (Block &block : getBody()) {
735 if (block.empty())
736 continue;
737 if (block.back().getNumSuccessors() != 0)
738 continue;
739 if (!isa<gpu::TerminatorOp>(&block.back())) {
740 return block.back()
741 .emitError()
742 .append("expected '", gpu::TerminatorOp::getOperationName(),
743 "' or a terminator with successors")
744 .attachNote(getLoc())
745 .append("in '", LaunchOp::getOperationName(), "' body region");
746 }
747 }
748
749 return success();
750}
751
752// Pretty-print the kernel grid/block size assignment as
753// (%iter-x, %iter-y, %iter-z) in
754// (%size-x = %ssa-use, %size-y = %ssa-use, %size-z = %ssa-use)
755// where %size-* and %iter-* will correspond to the body region arguments.
757 KernelDim3 operands, KernelDim3 ids) {
758 p << '(' << ids.x << ", " << ids.y << ", " << ids.z << ") in (";
759 p << size.x << " = " << operands.x << ", ";
760 p << size.y << " = " << operands.y << ", ";
761 p << size.z << " = " << operands.z << ')';
762}
763
764void LaunchOp::print(OpAsmPrinter &p) {
765 if (auto asyncObject = getAsyncObject()) {
766 p << " <" << asyncObject << " : " << asyncObject.getType() << ">";
767 }
768 if (getAsyncToken()) {
769 p << " async";
770 if (!getAsyncDependencies().empty())
771 p << " [" << getAsyncDependencies() << ']';
772 }
773 // Print the launch configuration.
774 if (hasClusterSize()) {
775 p << ' ' << getClustersKeyword();
776 printSizeAssignment(p, getClusterSize().value(),
777 getClusterSizeOperandValues().value(),
778 getClusterIds().value());
779 }
780 p << ' ' << getBlocksKeyword();
781 printSizeAssignment(p, getGridSize(), getGridSizeOperandValues(),
782 getBlockIds());
783 p << ' ' << getThreadsKeyword();
784 printSizeAssignment(p, getBlockSize(), getBlockSizeOperandValues(),
785 getThreadIds());
786 if (getDynamicSharedMemorySize())
787 p << ' ' << getDynamicSharedMemorySizeKeyword() << ' '
788 << getDynamicSharedMemorySize();
789
790 // Print optional module attribute.
791 StringRef moduleAttrName = getModuleAttrName();
792 if (auto module = getModule()) {
793 p << ' ' << moduleAttrName << '(';
794 p.printSymbolName(*module);
795 p << ')';
796 }
797 // Print optional function attribute.
798 StringRef functionAttrName = getFunctionAttrName();
799 if (auto function = getFunction()) {
800 p << ' ' << functionAttrName << '(';
801 p.printSymbolName(*function);
802 p << ')';
803 }
804
805 if (getCooperative())
806 p << " cooperative";
807
808 printAttributions(p, getWorkgroupKeyword(), getWorkgroupAttributionBBArgs());
809 printAttributions(p, getPrivateKeyword(), getPrivateAttributions());
810
811 p << ' ';
812
813 p.printRegion(getBody(), /*printEntryBlockArgs=*/false);
815 (*this)->getDiscardableAttrDictionary().getValue(), /*elidedAttrs=*/{
816 LaunchOp::getOperandSegmentSizeAttr(),
817 getWorkgroupAttributionsAttrName(), getCooperativeAttrName(),
818 moduleAttrName, functionAttrName});
819}
820
821// Parse the size assignment blocks for blocks and threads. These have the form
822// (%region_arg, %region_arg, %region_arg) in
823// (%region_arg = %operand, %region_arg = %operand, %region_arg = %operand)
824// where %region_arg are percent-identifiers for the region arguments to be
825// introduced further (SSA defs), and %operand are percent-identifiers for the
826// SSA value uses.
827static ParseResult
832 StringRef keyword) {
833 assert(indices.size() == 3 && "space for three indices expected");
836 /*allowResultNumber=*/false) ||
837 parser.parseKeyword("in") || parser.parseLParen())
838 return failure();
839
840 if (args.size() != 3) {
841 return parser.emitError(parser.getNameLoc())
842 << keyword << " expects 3 arguments, but got " << args.size();
843 }
844 std::move(args.begin(), args.end(), indices.begin());
845
846 for (int i = 0; i < 3; ++i) {
847 if (i != 0 && parser.parseComma())
848 return failure();
849 if (parser.parseOperand(regionSizes[i], /*allowResultNumber=*/false) ||
850 parser.parseEqual() || parser.parseOperand(sizes[i]))
851 return failure();
852 }
853
854 return parser.parseRParen();
855}
856
857/// Parses a Launch operation.
858/// operation ::= `gpu.launch` (`<` ssa-use `:` type `>`)?
859/// (`async` `[` ssa-id-list `]`)?
860/// (`clusters` `(` ssa-id-list `)` `in` ssa-reassignment)?
861/// `blocks` `(` ssa-id-list `)` `in` ssa-reassignment
862/// `threads` `(` ssa-id-list `)` `in` ssa-reassignment
863/// (`dynamic_shared_memory_size` ssa-use)?
864/// (`module(` symbol-ref-id `)`)?
865/// (`function(` symbol-ref-id `)`)?
866/// memory-attribution
867/// region attr-dict?
868/// ssa-reassignment ::= `(` ssa-id `=` ssa-use (`,` ssa-id `=` ssa-use)* `)`
869ParseResult LaunchOp::parse(OpAsmParser &parser, OperationState &result) {
870 // Sizes of the grid and block.
872 sizes(LaunchOp::kNumConfigOperands);
873
874 // Region arguments to be created.
876 LaunchOp::kNumConfigRegionAttributes);
877
878 // Parse optional asyncObject: < value : type >
879 OpAsmParser::UnresolvedOperand asyncObjectOperand;
880 Type asyncObjectType;
881 bool hasAsyncObject = false;
882 if (succeeded(parser.parseOptionalLess())) {
883 hasAsyncObject = true;
884 if (parser.parseOperand(asyncObjectOperand) || parser.parseColon() ||
885 parser.parseType(asyncObjectType) || parser.parseGreater())
886 return failure();
887 }
888
889 // Parse optional async dependencies.
891 Type asyncTokenType;
892 if (failed(
893 parseAsyncDependencies(parser, asyncTokenType, asyncDependencies)) ||
894 parser.resolveOperands(asyncDependencies, asyncTokenType,
895 result.operands))
896 return failure();
897 if (parser.getNumResults() > 0) {
898 if (!asyncTokenType)
899 return parser.emitError(
900 parser.getNameLoc(),
901 "gpu.launch requires 'async' keyword to return a value");
902 result.types.push_back(asyncTokenType);
903 }
904
905 bool hasCluster = false;
906 if (succeeded(parser.parseOptionalKeyword(LaunchOp::getClustersKeyword()))) {
907 hasCluster = true;
908 sizes.resize(9);
909 regionArgs.resize(18);
910 }
912 MutableArrayRef<OpAsmParser::UnresolvedOperand> regionArgsRef(regionArgs);
913
914 // Last three segment assigns the cluster size. In the region argument
915 // list, this is last 6 arguments.
916 if (hasCluster) {
918 parser, sizesRef.drop_front(6), regionArgsRef.slice(15, 3),
919 regionArgsRef.slice(12, 3), LaunchOp::getClustersKeyword()))
920 return failure();
921 }
922 // Parse the size assignment segments: the first segment assigns grid sizes
923 // and defines values for block identifiers; the second segment assigns block
924 // sizes and defines values for thread identifiers. In the region argument
925 // list, identifiers precede sizes, and block-related values precede
926 // thread-related values.
927 if (parser.parseKeyword(LaunchOp::getBlocksKeyword()) ||
928 parseSizeAssignment(parser, sizesRef.take_front(3),
929 regionArgsRef.slice(6, 3), regionArgsRef.slice(0, 3),
930 LaunchOp::getBlocksKeyword()) ||
931 parser.parseKeyword(LaunchOp::getThreadsKeyword()) ||
932 parseSizeAssignment(parser, sizesRef.drop_front(3),
933 regionArgsRef.slice(9, 3), regionArgsRef.slice(3, 3),
934 LaunchOp::getThreadsKeyword()) ||
935 parser.resolveOperands(sizes, parser.getBuilder().getIndexType(),
936 result.operands))
937 return failure();
938
939 OpAsmParser::UnresolvedOperand dynamicSharedMemorySize;
940 bool hasDynamicSharedMemorySize = false;
941 if (!parser.parseOptionalKeyword(
942 LaunchOp::getDynamicSharedMemorySizeKeyword())) {
943 hasDynamicSharedMemorySize = true;
944 if (parser.parseOperand(dynamicSharedMemorySize) ||
945 parser.resolveOperand(dynamicSharedMemorySize,
946 parser.getBuilder().getI32Type(),
947 result.operands))
948 return failure();
949 }
950
951 // Resolve the asyncObject operand
952 if (hasAsyncObject && parser.resolveOperand(asyncObjectOperand,
953 asyncObjectType, result.operands))
954 return failure();
955
956 // Parse optional module attribute.
957 StringRef moduleAttrName = getModuleAttrName(result.name);
958 if (succeeded(parser.parseOptionalKeyword(moduleAttrName))) {
959 FlatSymbolRefAttr moduleSymbol;
960 if (parser.parseLParen() ||
961 parser.parseAttribute(moduleSymbol, Type(), moduleAttrName,
962 result.attributes) ||
963 parser.parseRParen())
964 return failure();
965 }
966 // Parse optional function attribute.
967 StringRef functionAttrName = getFunctionAttrName(result.name);
968 if (succeeded(parser.parseOptionalKeyword(functionAttrName))) {
969 FlatSymbolRefAttr funcSymbol;
970 if (parser.parseLParen() ||
971 parser.parseAttribute(funcSymbol, Type(), functionAttrName,
972 result.attributes) ||
973 parser.parseRParen())
974 return failure();
975 }
976
977 // Parse optional cooperative keyword.
978 if (succeeded(parser.parseOptionalKeyword("cooperative")))
979 result.addAttribute("cooperative", parser.getBuilder().getUnitAttr());
980
981 // Create the region arguments: fixed launch-config args (`index`), then
982 // workgroup / private attribution args. The workgroup count is stored in the
983 // inherent `workgroup_attributions` attribute when non-zero.
984 Type index = parser.getBuilder().getIndexType();
986 LaunchOp::kNumConfigRegionAttributes + 6, index);
987
989 for (auto ssaValueAndType : llvm::zip(regionArgs, dataTypes)) {
991 arg.ssaName = std::get<0>(ssaValueAndType);
992 arg.type = std::get<1>(ssaValueAndType);
993 regionArguments.push_back(arg);
994 }
995
996 Builder &builder = parser.getBuilder();
997 // Parse workgroup memory attributions.
998 if (failed(parseAttributions(parser, LaunchOp::getWorkgroupKeyword(),
999 regionArguments)))
1000 return failure();
1001
1002 // Store the number of operands we just parsed as the number of workgroup
1003 // memory attributions.
1004 unsigned numWorkgroupAttrs = regionArguments.size() -
1005 LaunchOp::kNumConfigRegionAttributes -
1006 (hasCluster ? 6 : 0);
1007 if (numWorkgroupAttrs != 0)
1008 result.addAttribute(LaunchOp::getWorkgroupAttributionsAttrName(result.name),
1009 builder.getI64IntegerAttr(numWorkgroupAttrs));
1010
1011 // Parse private memory attributions.
1012 if (failed(parseAttributions(parser, LaunchOp::getPrivateKeyword(),
1013 regionArguments)))
1014 return failure();
1015
1016 // Introduce the body region and parse it. The region has
1017 // kNumConfigRegionAttributes arguments that correspond to
1018 // block/thread identifiers and grid/block sizes, all having `index` type.
1019 Region *body = result.addRegion();
1020 if (parser.parseRegion(*body, regionArguments) ||
1021 parser.parseOptionalAttrDict(result.attributes))
1022 return failure();
1023
1024 SmallVector<int32_t, 12> segmentSizes(12, 1);
1025 segmentSizes.front() = asyncDependencies.size();
1026
1027 if (!hasCluster) {
1028 segmentSizes[7] = 0;
1029 segmentSizes[8] = 0;
1030 segmentSizes[9] = 0;
1031 }
1032 segmentSizes[10] = hasDynamicSharedMemorySize ? 1 : 0;
1033 segmentSizes[11] = hasAsyncObject ? 1 : 0;
1034 result.addAttribute(LaunchOp::getOperandSegmentSizeAttr(),
1035 parser.getBuilder().getDenseI32ArrayAttr(segmentSizes));
1036 return success();
1037}
1038
1039/// Simplify the gpu.launch when the range of a thread or block ID is
1040/// trivially known to be one.
1041struct FoldLaunchArguments : public OpRewritePattern<LaunchOp> {
1042 using OpRewritePattern<LaunchOp>::OpRewritePattern;
1043 LogicalResult matchAndRewrite(LaunchOp op,
1044 PatternRewriter &rewriter) const override {
1045 // If the range implies a single value for `id`, replace `id`'s uses by
1046 // zero.
1047 Value zero;
1048 bool simplified = false;
1049 auto constPropIdUses = [&](Value id, Value size) {
1050 // Check if size is trivially one.
1051 if (!matchPattern(size, m_One()))
1052 return;
1053 if (id.getUses().empty())
1054 return;
1055 if (!simplified) {
1056 // Create a zero value the first time.
1057 OpBuilder::InsertionGuard guard(rewriter);
1058 rewriter.setInsertionPointToStart(&op.getBody().front());
1059 zero =
1060 arith::ConstantIndexOp::create(rewriter, op.getLoc(), /*value=*/0);
1061 }
1062 rewriter.replaceAllUsesWith(id, zero);
1063 simplified = true;
1064 };
1065 constPropIdUses(op.getBlockIds().x, op.getGridSizeX());
1066 constPropIdUses(op.getBlockIds().y, op.getGridSizeY());
1067 constPropIdUses(op.getBlockIds().z, op.getGridSizeZ());
1068 constPropIdUses(op.getThreadIds().x, op.getBlockSizeX());
1069 constPropIdUses(op.getThreadIds().y, op.getBlockSizeY());
1070 constPropIdUses(op.getThreadIds().z, op.getBlockSizeZ());
1071
1072 return success(simplified);
1073 }
1074};
1075
1076void LaunchOp::getCanonicalizationPatterns(RewritePatternSet &rewrites,
1077 MLIRContext *context) {
1078 rewrites.add<FoldLaunchArguments>(context);
1079}
1080
1081/// Adds a new block argument that corresponds to buffers located in
1082/// workgroup memory.
1083BlockArgument LaunchOp::addWorkgroupAttribution(Type type, Location loc) {
1084 int64_t cur = getWorkgroupAttributions().value_or(0);
1085 setWorkgroupAttributions(std::optional<int64_t>(cur + 1));
1086 return getBody().insertArgument(
1087 getNumConfigRegionAttributes() + static_cast<unsigned>(cur), type, loc);
1088}
1089
1090/// Adds a new block argument that corresponds to buffers located in
1091/// private memory.
1092BlockArgument LaunchOp::addPrivateAttribution(Type type, Location loc) {
1093 // Buffers on the private memory always come after buffers on the workgroup
1094 // memory.
1095 return getBody().addArgument(type, loc);
1096}
1097
1098//===----------------------------------------------------------------------===//
1099// LaunchFuncOp
1100//===----------------------------------------------------------------------===//
1101
1102void LaunchFuncOp::build(OpBuilder &builder, OperationState &result,
1103 SymbolRefAttr kernelSymbol, KernelDim3 gridSize,
1104 KernelDim3 getBlockSize, Value dynamicSharedMemorySize,
1105 ValueRange kernelOperands, Type asyncTokenType,
1106 ValueRange asyncDependencies, Value asyncObject,
1107 std::optional<KernelDim3> clusterSize) {
1108 assert(kernelSymbol.getNestedReferences().size() == 1 &&
1109 "expected a symbol reference with a single nested reference");
1110 result.addOperands(asyncDependencies);
1111 if (asyncTokenType)
1112 result.types.push_back(builder.getType<AsyncTokenType>());
1113
1114 // Add grid and block sizes as op operands, followed by the data operands.
1115 result.addOperands({gridSize.x, gridSize.y, gridSize.z, getBlockSize.x,
1117 if (clusterSize.has_value())
1118 result.addOperands({clusterSize->x, clusterSize->y, clusterSize->z});
1119 if (dynamicSharedMemorySize)
1120 result.addOperands(dynamicSharedMemorySize);
1121 result.addOperands(kernelOperands);
1122 if (asyncObject)
1123 result.addOperands(asyncObject);
1124
1125 Properties &prop = result.getOrAddProperties<Properties>();
1126 prop.kernel = kernelSymbol;
1127 size_t segmentSizesLen = std::size(prop.operandSegmentSizes);
1128 // Initialize the segment sizes to 1.
1129 llvm::fill(prop.operandSegmentSizes, 1);
1130 prop.operandSegmentSizes[0] = asyncDependencies.size();
1131 if (!clusterSize.has_value()) {
1132 prop.operandSegmentSizes[segmentSizesLen - 4] = 0;
1133 prop.operandSegmentSizes[segmentSizesLen - 5] = 0;
1134 prop.operandSegmentSizes[segmentSizesLen - 6] = 0;
1135 }
1136 prop.operandSegmentSizes[segmentSizesLen - 3] =
1137 dynamicSharedMemorySize ? 1 : 0;
1138 prop.operandSegmentSizes[segmentSizesLen - 2] =
1139 static_cast<int32_t>(kernelOperands.size());
1140 prop.operandSegmentSizes[segmentSizesLen - 1] = asyncObject ? 1 : 0;
1141}
1142
1143void LaunchFuncOp::build(OpBuilder &builder, OperationState &result,
1144 GPUFuncOp kernelFunc, KernelDim3 gridSize,
1145 KernelDim3 getBlockSize, Value dynamicSharedMemorySize,
1146 ValueRange kernelOperands, Type asyncTokenType,
1147 ValueRange asyncDependencies, Value asyncObject,
1148 std::optional<KernelDim3> clusterSize) {
1149 auto kernelModule = kernelFunc->getParentOfType<GPUModuleOp>();
1150 auto kernelSymbol =
1151 SymbolRefAttr::get(kernelModule.getNameAttr(),
1152 {SymbolRefAttr::get(kernelFunc.getNameAttr())});
1153 build(builder, result, kernelSymbol, gridSize, getBlockSize,
1154 dynamicSharedMemorySize, kernelOperands, asyncTokenType,
1155 asyncDependencies, asyncObject, clusterSize);
1156}
1157
1158StringAttr LaunchFuncOp::getKernelModuleName() {
1159 return getKernel().getRootReference();
1160}
1161
1162StringAttr LaunchFuncOp::getKernelName() {
1163 return getKernel().getLeafReference();
1164}
1165
1166unsigned LaunchFuncOp::getNumKernelOperands() {
1167 return getKernelOperands().size();
1168}
1169
1170Value LaunchFuncOp::getKernelOperand(unsigned i) {
1171 return getKernelOperands()[i];
1172}
1173
1174KernelDim3 LaunchFuncOp::getGridSizeOperandValues() {
1175 auto operands = getOperands().drop_front(getAsyncDependencies().size());
1176 return KernelDim3{operands[0], operands[1], operands[2]};
1177}
1178
1179KernelDim3 LaunchFuncOp::getBlockSizeOperandValues() {
1180 auto operands = getOperands().drop_front(getAsyncDependencies().size());
1181 return KernelDim3{operands[3], operands[4], operands[5]};
1182}
1183
1184KernelDim3 LaunchFuncOp::getClusterSizeOperandValues() {
1185 assert(hasClusterSize() &&
1186 "cluster size is not set, check hasClusterSize() first");
1187 auto operands = getOperands().drop_front(getAsyncDependencies().size());
1188 return KernelDim3{operands[6], operands[7], operands[8]};
1189}
1190
1191LogicalResult LaunchFuncOp::verify() {
1192 if (verifyLaunchAsyncModel(*this).failed())
1193 return failure();
1194
1195 auto module = (*this)->getParentOfType<ModuleOp>();
1196 if (!module)
1197 return emitOpError("expected to belong to a module");
1198
1199 if (!module->getDiscardableAttrOfType<UnitAttr>(
1200 GPUDialect::getContainerModuleAttrName()))
1201 return emitOpError("expected the closest surrounding module to have the '" +
1202 GPUDialect::getContainerModuleAttrName() +
1203 "' attribute");
1204
1205 if (hasClusterSize()) {
1206 if (getClusterSizeY().getType() != getClusterSizeX().getType() ||
1207 getClusterSizeZ().getType() != getClusterSizeX().getType())
1208 return emitOpError()
1209 << "expects types of the cluster dimensions must be the same";
1210 }
1211
1212 return success();
1213}
1214
1215LogicalResult
1216LaunchFuncOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1217 LaunchFuncOp launchOp = *this;
1219 // GPU modules cannot be nested within each other, escape to resolve the name.
1220 if (isa<GPUModuleOp>(table))
1222
1223 // Ignore launches that are nested more or less deep than functions in the
1224 // module we are currently checking.
1225 if (!launchOp->getParentOp() ||
1226 launchOp->getParentOp()->getParentOp() != table)
1227 return success();
1228
1229 // Ignore launch ops with missing attributes here. The errors will be
1230 // reported by the verifiers of those ops.
1231 if (!launchOp.getKernelAttr())
1232 return success();
1233
1234 // Check that `launch_func` refers to a well-formed GPU kernel container.
1235 StringAttr kernelContainerName = launchOp.getKernelModuleName();
1236 Operation *kernelContainer =
1237 symbolTable.lookupNearestSymbolFrom(table, kernelContainerName);
1238 if (!kernelContainer)
1239 return launchOp.emitOpError()
1240 << "kernel container '" << kernelContainerName.getValue()
1241 << "' is undefined";
1242
1243 // If the container is a GPU binary op return success.
1244 if (isa<BinaryOp>(kernelContainer))
1245 return success();
1246
1247 auto kernelModule = dyn_cast<GPUModuleOp>(kernelContainer);
1248 if (!kernelModule)
1249 return launchOp.emitOpError()
1250 << "kernel module '" << kernelContainerName.getValue()
1251 << "' is undefined";
1252
1253 // Check that `launch_func` refers to a well-formed kernel function.
1254 Operation *kernelFunc = symbolTable.lookupNearestSymbolFrom(
1255 kernelModule, launchOp.getKernelName());
1256 if (!kernelFunc)
1257 return launchOp.emitOpError("kernel function '")
1258 << launchOp.getKernel() << "' is undefined";
1259 auto kernelConvertedFunction = dyn_cast<FunctionOpInterface>(kernelFunc);
1260 if (!kernelConvertedFunction) {
1261 InFlightDiagnostic diag = launchOp.emitOpError()
1262 << "referenced kernel '" << launchOp.getKernel()
1263 << "' is not a function";
1264 diag.attachNote(kernelFunc->getLoc()) << "see the kernel definition here";
1265 return diag;
1266 }
1267
1268 if (!GPUDialect::isKernel(kernelFunc))
1269 return launchOp.emitOpError("kernel function is missing the '")
1270 << GPUDialect::getKernelFuncAttrName() << "' attribute";
1271
1272 // TODO: If the kernel isn't a GPU function (which happens during separate
1273 // compilation), do not check type correspondence as it would require the
1274 // verifier to be aware of the type conversion.
1275 auto kernelGPUFunction = dyn_cast<gpu::GPUFuncOp>(kernelFunc);
1276 if (!kernelGPUFunction)
1277 return success();
1278
1279 unsigned actualNumArguments = launchOp.getNumKernelOperands();
1280 unsigned expectedNumArguments = kernelGPUFunction.getNumArguments();
1281 if (expectedNumArguments != actualNumArguments)
1282 return launchOp.emitOpError("got ")
1283 << actualNumArguments << " kernel operands but expected "
1284 << expectedNumArguments;
1285
1286 FunctionType functionType = kernelGPUFunction.getFunctionType();
1287 for (unsigned i = 0; i < expectedNumArguments; ++i) {
1288 if (launchOp.getKernelOperand(i).getType() != functionType.getInput(i)) {
1289 return launchOp.emitOpError("type of function argument ")
1290 << i << " does not match";
1291 }
1292 }
1293
1294 return success();
1295}
1296
1297static ParseResult
1299 std::optional<OpAsmParser::UnresolvedOperand> clusterValue,
1300 Type &clusterXTy, Type &clusterYTy, Type &clusterZTy) {
1301 if (succeeded(parser.parseOptionalColon())) {
1302 if (parser.parseType(dimTy))
1303 return failure();
1304 } else {
1305 dimTy = IndexType::get(parser.getContext());
1306 }
1307 if (clusterValue.has_value()) {
1308 clusterXTy = clusterYTy = clusterZTy = dimTy;
1309 }
1310 return success();
1311}
1312
1313static void printLaunchDimType(OpAsmPrinter &printer, Operation *op, Type dimTy,
1314 Value clusterValue, Type clusterXTy,
1315 Type clusterYTy, Type clusterZTy) {
1316 if (!dimTy.isIndex())
1317 printer << ": " << dimTy;
1318}
1319
1320static ParseResult parseLaunchFuncOperands(
1321 OpAsmParser &parser,
1323 SmallVectorImpl<Type> &argTypes) {
1324 if (parser.parseOptionalKeyword("args"))
1325 return success();
1326
1327 auto parseElement = [&]() -> ParseResult {
1328 return failure(parser.parseOperand(argNames.emplace_back()) ||
1329 parser.parseColonType(argTypes.emplace_back()));
1330 };
1331
1333 parseElement, " in argument list");
1334}
1335
1337 OperandRange operands, TypeRange types) {
1338 if (operands.empty())
1339 return;
1340 printer << "args(";
1341 llvm::interleaveComma(llvm::zip_equal(operands, types), printer,
1342 [&](const auto &pair) {
1343 auto [operand, type] = pair;
1344 printer << operand << " : " << type;
1345 });
1346 printer << ")";
1347}
1348
1349//===----------------------------------------------------------------------===//
1350// ShuffleOp
1351//===----------------------------------------------------------------------===//
1352
1353void ShuffleOp::build(OpBuilder &builder, OperationState &result, Value value,
1354 int32_t offset, int32_t width, ShuffleMode mode) {
1355 build(builder, result, value,
1356 arith::ConstantOp::create(builder, result.location,
1357 builder.getI32IntegerAttr(offset)),
1358 arith::ConstantOp::create(builder, result.location,
1359 builder.getI32IntegerAttr(width)),
1360 mode);
1361}
1362
1363//===----------------------------------------------------------------------===//
1364// RotateOp
1365//===----------------------------------------------------------------------===//
1366
1367LogicalResult RotateOp::verify() {
1368 uint32_t offset = getOffset();
1369 uint32_t width = getWidth();
1370
1371 if (offset >= width) {
1372 return emitOpError() << "offset must be in the range [0, " << width << ")";
1373 }
1374
1375 return success();
1376}
1377
1378//===----------------------------------------------------------------------===//
1379// BarrierOp
1380//===----------------------------------------------------------------------===//
1381
1382LogicalResult BarrierOp::verify() {
1383 BarrierScope scope = getScope();
1384
1385 if (getNamedBarrier() && scope != BarrierScope::Workgroup)
1386 return emitOpError("named barriers require workgroup scope");
1387
1388 return success();
1389}
1390
1391/// Remove gpu.barrier after gpu.barrier, the threads are already synchronized!
1392static LogicalResult eraseRedundantGpuBarrierOps(BarrierOp op,
1393 PatternRewriter &rewriter) {
1394 auto nextOp = dyn_cast_or_null<BarrierOp>(op->getNextNode());
1395 if (!nextOp)
1396 return failure();
1397
1398 // Cannot merge barriers of different scopes.
1399 if (op.getScope() != nextOp.getScope())
1400 return failure();
1401
1402 // Cannot merge named barriers unless both refer to the same handle.
1403 if (op.getNamedBarrier() != nextOp.getNamedBarrier())
1404 return failure();
1405
1406 std::optional<ArrayAttr> thisMemfence = op.getAddressSpaces();
1407 std::optional<ArrayAttr> nextMemfence = nextOp.getAddressSpaces();
1408
1409 if (thisMemfence) {
1410 rewriter.modifyOpInPlace(op, [&]() {
1411 if (!nextMemfence) {
1412 op.removeAddressSpacesAttr();
1413 return;
1414 }
1415 // Fast path - merge where the two barriers fence the same spaces.
1416 if (*thisMemfence == *nextMemfence) {
1417 return;
1418 }
1419
1420 llvm::SmallSetVector<Attribute, 4> mergedSpaces;
1421 for (Attribute attr : *thisMemfence)
1422 mergedSpaces.insert(attr);
1423 for (Attribute attr : *nextMemfence)
1424 mergedSpaces.insert(attr);
1425 op.setAddressSpacesAttr(rewriter.getArrayAttr(mergedSpaces.takeVector()));
1426 });
1427 }
1428
1429 rewriter.eraseOp(nextOp);
1430 return success();
1431}
1432
1433void BarrierOp::getCanonicalizationPatterns(RewritePatternSet &results,
1434 MLIRContext *context) {
1436}
1437
1438void BarrierOp::build(mlir::OpBuilder &odsBuilder,
1439 mlir::OperationState &odsState,
1440 std::optional<AddressSpace> addressSpace) {
1441 ArrayAttr addressSpacesAttr;
1442 if (addressSpace)
1443 addressSpacesAttr = odsBuilder.getArrayAttr(
1444 AddressSpaceAttr::get(odsBuilder.getContext(), addressSpace.value()));
1445 build(
1446 odsBuilder, odsState, addressSpacesAttr, /*named_barrier=*/Value{},
1447 BarrierScopeAttr::get(odsBuilder.getContext(), BarrierScope::Workgroup));
1448}
1449
1450/// Builds a barrier that causes memory operations affecting `memrefToFence` to
1451/// be completed after the barrier is concluded. Currently, this means setting
1452/// the fenced address spaces to those of the given memref if it is a gpu
1453/// address space.
1454void BarrierOp::build(OpBuilder &builder, OperationState &odsState,
1455 Value memrefToFence) {
1456 std::optional<AddressSpace> addrSpaceToFence;
1457 if (auto memrefType = dyn_cast<BaseMemRefType>(memrefToFence.getType()))
1458 if (auto addrSpaceAttr = dyn_cast_if_present<gpu::AddressSpaceAttr>(
1459 memrefType.getMemorySpace()))
1460 addrSpaceToFence = addrSpaceAttr.getValue();
1461 return build(builder, odsState, addrSpaceToFence);
1462}
1463
1464//===----------------------------------------------------------------------===//
1465// GPUFuncOp
1466//===----------------------------------------------------------------------===//
1467
1468/// Adds a new block argument that corresponds to buffers located in
1469/// workgroup memory.
1470BlockArgument GPUFuncOp::addWorkgroupAttribution(Type type, Location loc) {
1471 int64_t cur = getWorkgroupAttributions().value_or(0);
1472 setWorkgroupAttributions(std::optional<int64_t>(cur + 1));
1473 return getBody().insertArgument(
1474 getFunctionType().getNumInputs() + static_cast<unsigned>(cur), type, loc);
1475}
1476
1477/// Adds a new block argument that corresponds to buffers located in
1478/// private memory.
1479BlockArgument GPUFuncOp::addPrivateAttribution(Type type, Location loc) {
1480 // Buffers on the private memory always come after buffers on the workgroup
1481 // memory.
1482 return getBody().addArgument(type, loc);
1483}
1484
1485void GPUFuncOp::build(OpBuilder &builder, OperationState &result,
1486 StringRef name, FunctionType type,
1487 TypeRange workgroupAttributions,
1488 TypeRange privateAttributions,
1490 OpBuilder::InsertionGuard g(builder);
1491
1492 result.getOrAddProperties<Properties>().sym_name =
1493 builder.getStringAttr(name);
1494 result.addAttribute(getFunctionTypeAttrName(result.name),
1495 TypeAttr::get(type));
1496 result.addAttribute(getWorkgroupAttributionsAttrName(result.name),
1497 builder.getI64IntegerAttr(workgroupAttributions.size()));
1498 result.addAttributes(attrs);
1499 Region *body = result.addRegion();
1500 Block *entryBlock = builder.createBlock(body);
1501
1502 // TODO: Allow passing in proper locations here.
1503 for (Type argTy : type.getInputs())
1504 entryBlock->addArgument(argTy, result.location);
1505 for (Type argTy : workgroupAttributions)
1506 entryBlock->addArgument(argTy, result.location);
1507 for (Type argTy : privateAttributions)
1508 entryBlock->addArgument(argTy, result.location);
1509}
1510
1511/// Parses a GPU function memory attribution.
1512///
1513/// memory-attribution ::= (`workgroup` `(` ssa-id-and-type-list `)`)?
1514/// (`private` `(` ssa-id-and-type-list `)`)?
1515///
1516/// Note that this function parses only one of the two similar parts, with the
1517/// keyword provided as argument.
1518static ParseResult
1519parseAttributions(OpAsmParser &parser, StringRef keyword,
1521 Attribute &attributionAttrs) {
1522 // If we could not parse the keyword, just assume empty list and succeed.
1523 if (failed(parser.parseOptionalKeyword(keyword)))
1524 return success();
1525
1526 size_t existingArgs = args.size();
1527 ParseResult result =
1529 /*allowType=*/true, /*allowAttrs=*/true);
1530 if (failed(result))
1531 return result;
1532
1533 bool hadAttrs = llvm::any_of(ArrayRef(args).drop_front(existingArgs),
1534 [](const OpAsmParser::Argument &arg) -> bool {
1535 return arg.attrs && !arg.attrs.empty();
1536 });
1537 if (!hadAttrs) {
1538 attributionAttrs = nullptr;
1539 return result;
1540 }
1541
1542 Builder &builder = parser.getBuilder();
1543 SmallVector<Attribute> attributionAttrsVec;
1544 for (const auto &argument : ArrayRef(args).drop_front(existingArgs)) {
1545 if (!argument.attrs)
1546 attributionAttrsVec.push_back(builder.getDictionaryAttr({}));
1547 else
1548 attributionAttrsVec.push_back(argument.attrs);
1549 }
1550 attributionAttrs = builder.getArrayAttr(attributionAttrsVec);
1551 return result;
1552}
1553
1554/// Parses a GPU function.
1555///
1556/// <operation> ::= `gpu.func` symbol-ref-id `(` argument-list `)`
1557/// (`->` function-result-list)? memory-attribution `kernel`?
1558/// function-attributes? region
1559ParseResult GPUFuncOp::parse(OpAsmParser &parser, OperationState &result) {
1561 SmallVector<DictionaryAttr> resultAttrs;
1562 SmallVector<Type> resultTypes;
1563 bool isVariadic;
1564
1565 // Parse the function name.
1566 StringAttr nameAttr;
1567 if (parser.parseSymbolName(nameAttr, getSymNameAttrName(result.name),
1568 result.attributes))
1569 return failure();
1570
1571 auto signatureLocation = parser.getCurrentLocation();
1573 parser, /*allowVariadic=*/false, entryArgs, isVariadic, resultTypes,
1574 resultAttrs)))
1575 return failure();
1576
1577 if (!entryArgs.empty() && entryArgs[0].ssaName.name.empty())
1578 return parser.emitError(signatureLocation)
1579 << "gpu.func requires named arguments";
1580
1581 // Construct the function type. More types will be added to the region, but
1582 // not to the function type.
1583 Builder &builder = parser.getBuilder();
1584
1585 SmallVector<Type> argTypes;
1586 for (auto &arg : entryArgs)
1587 argTypes.push_back(arg.type);
1588 auto type = builder.getFunctionType(argTypes, resultTypes);
1589 result.addAttribute(getFunctionTypeAttrName(result.name),
1590 TypeAttr::get(type));
1591
1593 builder, result, entryArgs, resultAttrs, getArgAttrsAttrName(result.name),
1594 getResAttrsAttrName(result.name));
1595
1596 Attribute workgroupAttributionAttrs;
1597 // Parse workgroup memory attributions.
1598 if (failed(parseAttributions(parser, GPUFuncOp::getWorkgroupKeyword(),
1599 entryArgs, workgroupAttributionAttrs)))
1600 return failure();
1601
1602 // Store the number of operands we just parsed as the number of workgroup
1603 // memory attributions.
1604 unsigned numWorkgroupAttrs = entryArgs.size() - type.getNumInputs();
1605 if (numWorkgroupAttrs != 0)
1606 result.addAttribute(
1607 GPUFuncOp::getWorkgroupAttributionsAttrName(result.name),
1608 builder.getI64IntegerAttr(numWorkgroupAttrs));
1609 if (workgroupAttributionAttrs)
1610 result.addAttribute(GPUFuncOp::getWorkgroupAttribAttrsAttrName(result.name),
1611 workgroupAttributionAttrs);
1612
1613 Attribute privateAttributionAttrs;
1614 // Parse private memory attributions.
1615 if (failed(parseAttributions(parser, GPUFuncOp::getPrivateKeyword(),
1616 entryArgs, privateAttributionAttrs)))
1617 return failure();
1618 if (privateAttributionAttrs)
1619 result.addAttribute(GPUFuncOp::getPrivateAttribAttrsAttrName(result.name),
1620 privateAttributionAttrs);
1621
1622 // Parse the kernel attribute if present.
1623 if (succeeded(parser.parseOptionalKeyword(GPUFuncOp::getKernelKeyword())))
1624 result.addAttribute(GPUFuncOp::getKernelAttrName(result.name),
1625 builder.getUnitAttr());
1626
1627 // Parse attributes.
1628 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
1629 return failure();
1630
1631 // Parse the region. If no argument names were provided, take all names
1632 // (including those of attributions) from the entry block.
1633 auto *body = result.addRegion();
1634 return parser.parseRegion(*body, entryArgs);
1635}
1636
1637void GPUFuncOp::print(OpAsmPrinter &p) {
1638 p << ' ';
1639 p.printSymbolName(getName());
1640
1641 FunctionType type = getFunctionType();
1642 function_interface_impl::printFunctionSignature(p, *this, type.getInputs(),
1643 /*isVariadic=*/false,
1644 type.getResults());
1645
1646 printAttributions(p, getWorkgroupKeyword(), getWorkgroupAttributionBBArgs(),
1647 getWorkgroupAttribAttrs().value_or(nullptr));
1648 printAttributions(p, getPrivateKeyword(), getPrivateAttributions(),
1649 getPrivateAttribAttrs().value_or(nullptr));
1650 if (isKernel())
1651 p << ' ' << getKernelKeyword();
1652
1654 p, *this,
1655 {getWorkgroupAttributionsAttrName(), getKernelAttrName(),
1656 GPUDialect::getKernelFuncAttrName(), getFunctionTypeAttrName(),
1657 getArgAttrsAttrName(), getResAttrsAttrName(),
1658 getWorkgroupAttribAttrsAttrName(), getPrivateAttribAttrsAttrName()});
1659 p << ' ';
1660 p.printRegion(getBody(), /*printEntryBlockArgs=*/false);
1661}
1662
1663static DictionaryAttr getAttributionAttrs(GPUFuncOp op, unsigned index,
1664 StringAttr attrName) {
1665 ArrayAttr allAttrs = attrName == op.getWorkgroupAttribAttrsAttrName()
1666 ? op.getWorkgroupAttribAttrsAttr()
1667 : op.getPrivateAttribAttrsAttr();
1668 if (!allAttrs || index >= allAttrs.size())
1669 return DictionaryAttr();
1670 return llvm::cast<DictionaryAttr>(allAttrs[index]);
1671}
1672
1673DictionaryAttr GPUFuncOp::getworkgroupAttributionAttrs(unsigned index) {
1674 return getAttributionAttrs(*this, index, getWorkgroupAttribAttrsAttrName());
1675}
1676
1677DictionaryAttr GPUFuncOp::getPrivateAttributionAttrs(unsigned index) {
1678 return getAttributionAttrs(*this, index, getPrivateAttribAttrsAttrName());
1679}
1680
1681static void setAttributionAttrs(GPUFuncOp op, unsigned index,
1682 DictionaryAttr value, StringAttr attrName) {
1683 MLIRContext *ctx = op.getContext();
1684 ArrayAttr allAttrs = attrName == op.getWorkgroupAttribAttrsAttrName()
1685 ? op.getWorkgroupAttribAttrsAttr()
1686 : op.getPrivateAttribAttrsAttr();
1687 SmallVector<Attribute> elements;
1688 if (allAttrs)
1689 elements.append(allAttrs.begin(), allAttrs.end());
1690 while (elements.size() <= index)
1691 elements.push_back(DictionaryAttr::get(ctx));
1692 if (!value)
1693 elements[index] = DictionaryAttr::get(ctx);
1694 else
1695 elements[index] = value;
1696 ArrayAttr newValue = ArrayAttr::get(ctx, elements);
1697 if (attrName == op.getWorkgroupAttribAttrsAttrName())
1698 op.setWorkgroupAttribAttrsAttr(newValue);
1699 else
1700 op.setPrivateAttribAttrsAttr(newValue);
1701}
1702
1703void GPUFuncOp::setworkgroupAttributionAttrs(unsigned index,
1704 DictionaryAttr value) {
1705 setAttributionAttrs(*this, index, value, getWorkgroupAttribAttrsAttrName());
1706}
1707
1708void GPUFuncOp::setPrivateAttributionAttrs(unsigned int index,
1709 DictionaryAttr value) {
1710 setAttributionAttrs(*this, index, value, getPrivateAttribAttrsAttrName());
1711}
1712
1713static Attribute getAttributionAttr(GPUFuncOp op, unsigned index,
1714 StringAttr name, StringAttr attrsName) {
1715 DictionaryAttr dict = getAttributionAttrs(op, index, attrsName);
1716 if (!dict)
1717 return Attribute();
1718 return dict.get(name);
1719}
1720
1721Attribute GPUFuncOp::getWorkgroupAttributionAttr(unsigned index,
1722 StringAttr name) {
1723 assert(index < getNumWorkgroupAttributions() &&
1724 "index must map to a workgroup attribution");
1725 return getAttributionAttr(*this, index, name,
1726 getWorkgroupAttribAttrsAttrName());
1727}
1728
1729Attribute GPUFuncOp::getPrivateAttributionAttr(unsigned index,
1730 StringAttr name) {
1731 assert(index < getNumPrivateAttributions() &&
1732 "index must map to a private attribution");
1733 return getAttributionAttr(*this, index, name,
1734 getPrivateAttribAttrsAttrName());
1735}
1736
1737static void setAttributionAttr(GPUFuncOp op, unsigned index, StringAttr name,
1738 Attribute value, StringAttr attrsName) {
1739 MLIRContext *ctx = op.getContext();
1741 DictionaryAttr oldDict = getAttributionAttrs(op, index, attrsName);
1742 if (oldDict)
1743 elems.append(oldDict.getValue().begin(), oldDict.getValue().end());
1744
1745 bool found = false;
1746 bool mustSort = true;
1747 for (unsigned i = 0, e = elems.size(); i < e; ++i) {
1748 if (elems[i].getName() == name) {
1749 found = true;
1750 if (!value) {
1751 std::swap(elems[i], elems[elems.size() - 1]);
1752 elems.pop_back();
1753 } else {
1754 mustSort = false;
1755 elems[i] = NamedAttribute(elems[i].getName(), value);
1756 }
1757 break;
1758 }
1759 }
1760 if (!found) {
1761 if (!value)
1762 return;
1763 elems.emplace_back(name, value);
1764 }
1765 if (mustSort) {
1766 DictionaryAttr::sortInPlace(elems);
1767 }
1768 auto newDict = DictionaryAttr::getWithSorted(ctx, elems);
1769 setAttributionAttrs(op, index, newDict, attrsName);
1770}
1771
1772void GPUFuncOp::setWorkgroupAttributionAttr(unsigned index, StringAttr name,
1773 Attribute value) {
1774 assert(index < getNumWorkgroupAttributions() &&
1775 "index must map to a workgroup attribution");
1776 setAttributionAttr(*this, index, name, value,
1777 getWorkgroupAttribAttrsAttrName());
1778}
1779
1780void GPUFuncOp::setPrivateAttributionAttr(unsigned index, StringAttr name,
1781 Attribute value) {
1782 assert(index < getNumPrivateAttributions() &&
1783 "index must map to a private attribution");
1784 setAttributionAttr(*this, index, name, value,
1785 getPrivateAttribAttrsAttrName());
1786}
1787
1788LogicalResult GPUFuncOp::verifyType() {
1789 if (isKernel() && getFunctionType().getNumResults() != 0)
1790 return emitOpError() << "expected void return type for kernel function";
1791
1792 return success();
1793}
1794
1795/// Verifies the body of the function.
1796LogicalResult GPUFuncOp::verifyBody() {
1797 if (empty())
1798 return emitOpError() << "expected body with at least one block";
1799 unsigned numFuncArguments = getNumArguments();
1800 unsigned numWorkgroupAttributions = getNumWorkgroupAttributions();
1801 unsigned numBlockArguments = front().getNumArguments();
1802 if (numBlockArguments < numFuncArguments + numWorkgroupAttributions)
1803 return emitOpError() << "expected at least "
1804 << numFuncArguments + numWorkgroupAttributions
1805 << " arguments to body region";
1806
1807 ArrayRef<Type> funcArgTypes = getFunctionType().getInputs();
1808 for (unsigned i = 0; i < numFuncArguments; ++i) {
1809 Type blockArgType = front().getArgument(i).getType();
1810 if (funcArgTypes[i] != blockArgType)
1811 return emitOpError() << "expected body region argument #" << i
1812 << " to be of type " << funcArgTypes[i] << ", got "
1813 << blockArgType;
1814 }
1815
1816 if (failed(verifyAttributions(getOperation(), getWorkgroupAttributionBBArgs(),
1817 GPUDialect::getWorkgroupAddressSpace())) ||
1818 failed(verifyAttributions(getOperation(), getPrivateAttributions(),
1819 GPUDialect::getPrivateAddressSpace())))
1820 return failure();
1821
1822 return success();
1823}
1824
1825//===----------------------------------------------------------------------===//
1826// ReturnOp
1827//===----------------------------------------------------------------------===//
1828
1829LogicalResult gpu::ReturnOp::verify() {
1830 GPUFuncOp function = (*this)->getParentOfType<GPUFuncOp>();
1831
1832 FunctionType funType = function.getFunctionType();
1833
1834 if (funType.getNumResults() != getOperands().size())
1835 return emitOpError()
1836 .append("expected ", funType.getNumResults(), " result operands")
1837 .attachNote(function.getLoc())
1838 .append("return type declared here");
1839
1840 for (const auto &pair : llvm::enumerate(
1841 llvm::zip(function.getFunctionType().getResults(), getOperands()))) {
1842 auto [type, operand] = pair.value();
1843 if (type != operand.getType())
1844 return emitOpError() << "unexpected type `" << operand.getType()
1845 << "' for operand #" << pair.index();
1846 }
1847 return success();
1848}
1849
1850//===----------------------------------------------------------------------===//
1851// GPUModuleOp
1852//===----------------------------------------------------------------------===//
1853
1854LogicalResult GPUModuleOp::readProperties(DialectBytecodeReader &reader,
1855 OperationState &state) {
1856 auto &properties = state.getOrAddProperties<Properties>();
1857 // Preserve the pre-DLTI field order for unversioned bytecode.
1858 if (failed(reader.readOptionalAttribute(properties.offloadingHandler)) ||
1859 failed(reader.readAttribute(properties.sym_name)) ||
1860 failed(reader.readOptionalAttribute(properties.sym_visibility)) ||
1861 failed(reader.readOptionalAttribute(properties.targets)))
1862 return failure();
1863
1864 if (failed(reader.getDialectVersion<GPUDialect>()))
1865 return success();
1866 return reader.readOptionalAttribute(properties.dlti);
1867}
1868
1869void GPUModuleOp::writeProperties(DialectBytecodeWriter &writer) {
1870 Properties &properties = getProperties();
1871 writer.writeOptionalAttribute(properties.offloadingHandler);
1872 writer.writeAttribute(properties.sym_name);
1873 writer.writeOptionalAttribute(properties.sym_visibility);
1874 writer.writeOptionalAttribute(properties.targets);
1876 writer.writeOptionalAttribute(properties.dlti);
1877}
1878
1879void GPUModuleOp::build(OpBuilder &builder, OperationState &result,
1880 StringRef name, ArrayAttr targets,
1881 Attribute offloadingHandler) {
1882 result.addRegion()->emplaceBlock();
1883 Properties &props = result.getOrAddProperties<Properties>();
1884 if (targets)
1885 props.targets = targets;
1886 props.setSymName(builder.getStringAttr(name));
1887 props.offloadingHandler = offloadingHandler;
1888}
1889
1890void GPUModuleOp::build(OpBuilder &builder, OperationState &result,
1891 StringRef name, ArrayRef<Attribute> targets,
1892 Attribute offloadingHandler) {
1893 build(builder, result, name,
1894 targets.empty() ? ArrayAttr() : builder.getArrayAttr(targets),
1895 offloadingHandler);
1896}
1897
1898bool GPUModuleOp::hasTarget(Attribute target) {
1899 if (ArrayAttr targets = getTargetsAttr())
1900 return llvm::count(targets.getValue(), target);
1901 return false;
1902}
1903
1904void GPUModuleOp::setTargets(ArrayRef<TargetAttrInterface> targets) {
1905 ArrayAttr &targetsAttr = getProperties().targets;
1906 SmallVector<Attribute> targetsVector(targets);
1907 targetsAttr = ArrayAttr::get(getContext(), targetsVector);
1908}
1909
1910LogicalResult GPUModuleOp::verify() {
1911 auto targets = getTargetsAttr();
1912
1913 if (!targets)
1914 return success();
1915
1916 for (auto target : targets) {
1917 if (auto verifyTargetAttr =
1918 llvm::dyn_cast<TargetAttrVerifyInterface>(target)) {
1919 if (verifyTargetAttr.verifyTarget(getOperation()).failed())
1920 return failure();
1921 }
1922 }
1923 return success();
1924}
1925
1926//===----------------------------------------------------------------------===//
1927// GPUBinaryOp
1928//===----------------------------------------------------------------------===//
1929void BinaryOp::build(OpBuilder &builder, OperationState &result, StringRef name,
1930 Attribute offloadingHandler, ArrayAttr objects) {
1931 auto &properties = result.getOrAddProperties<Properties>();
1932 result.attributes.push_back(builder.getNamedAttr(
1933 getSymNameAttrName(result.name), builder.getStringAttr(name)));
1934 properties.objects = objects;
1935 if (offloadingHandler)
1936 properties.offloadingHandler = offloadingHandler;
1937 else
1938 properties.offloadingHandler = builder.getAttr<SelectObjectAttr>(nullptr);
1939}
1940
1941void BinaryOp::build(OpBuilder &builder, OperationState &result, StringRef name,
1942 Attribute offloadingHandler, ArrayRef<Attribute> objects) {
1943 build(builder, result, name, offloadingHandler,
1944 objects.empty() ? ArrayAttr() : builder.getArrayAttr(objects));
1945}
1946
1947static ParseResult parseOffloadingHandler(OpAsmParser &parser,
1948 Attribute &offloadingHandler) {
1949 if (succeeded(parser.parseOptionalLess())) {
1950 if (parser.parseAttribute(offloadingHandler))
1951 return failure();
1952 if (parser.parseGreater())
1953 return failure();
1954 }
1955 if (!offloadingHandler)
1956 offloadingHandler = parser.getBuilder().getAttr<SelectObjectAttr>(nullptr);
1957 return success();
1958}
1959
1961 Attribute offloadingHandler) {
1962 if (offloadingHandler != SelectObjectAttr::get(op->getContext(), nullptr))
1963 printer << '<' << offloadingHandler << '>';
1964}
1965
1966//===----------------------------------------------------------------------===//
1967// GPUMemcpyOp
1968//===----------------------------------------------------------------------===//
1969
1970LogicalResult MemcpyOp::verify() {
1971 auto srcType = getSrc().getType();
1972 auto dstType = getDst().getType();
1973
1974 if (getElementTypeOrSelf(srcType) != getElementTypeOrSelf(dstType))
1975 return emitOpError("arguments have incompatible element type");
1976
1977 if (failed(verifyCompatibleShape(srcType, dstType)))
1978 return emitOpError("arguments have incompatible shape");
1979
1980 return success();
1981}
1982
1983namespace {
1984/// Erases a common case of copy ops where a destination value is used only by
1985/// the copy op, alloc and dealloc ops.
1986struct EraseTrivialCopyOp : public OpRewritePattern<MemcpyOp> {
1987 using OpRewritePattern<MemcpyOp>::OpRewritePattern;
1988
1989 LogicalResult matchAndRewrite(MemcpyOp op,
1990 PatternRewriter &rewriter) const override {
1991 Value dest = op.getDst();
1992 Operation *destDefOp = dest.getDefiningOp();
1993 // `dest` must be defined by an op having Allocate memory effect in order to
1994 // perform the folding.
1995 if (!destDefOp ||
1997 return failure();
1998 // We can erase `op` iff `dest` has no other use apart from its
1999 // use by `op` and dealloc ops.
2000 if (llvm::any_of(dest.getUsers(), [op, dest](Operation *user) {
2001 return user != op &&
2002 !hasSingleEffect<MemoryEffects::Free>(user, dest);
2003 }))
2004 return failure();
2005 // We can perform the folding if and only if op has a single async
2006 // dependency and produces an async token as result, or if it does not have
2007 // any async dependency and does not produce any async token result.
2008 if (op.getAsyncDependencies().size() > 1 ||
2009 ((op.getAsyncDependencies().empty() && op.getAsyncToken()) ||
2010 (!op.getAsyncDependencies().empty() && !op.getAsyncToken())))
2011 return failure();
2012 rewriter.replaceOp(op, op.getAsyncDependencies());
2013 return success();
2014 }
2015};
2016} // end anonymous namespace
2017
2018void MemcpyOp::getCanonicalizationPatterns(RewritePatternSet &results,
2019 MLIRContext *context) {
2020 results.add<EraseTrivialCopyOp>(context);
2021}
2022
2023//===----------------------------------------------------------------------===//
2024// GPU_SubgroupMmaLoadMatrixOp
2025//===----------------------------------------------------------------------===//
2026
2027LogicalResult SubgroupMmaLoadMatrixOp::verify() {
2028 auto srcType = getSrcMemref().getType();
2029 auto resType = getRes().getType();
2030 auto resMatrixType = llvm::cast<gpu::MMAMatrixType>(resType);
2031 auto operand = resMatrixType.getOperand();
2032 auto srcMemrefType = llvm::cast<MemRefType>(srcType);
2033
2034 if (!srcMemrefType.isLastDimUnitStride())
2035 return emitError(
2036 "expected source memref most minor dim must have unit stride");
2037
2038 if (operand != "AOp" && operand != "BOp" && operand != "COp")
2039 return emitError("only AOp, BOp and COp can be loaded");
2040
2041 return success();
2042}
2043
2044//===----------------------------------------------------------------------===//
2045// GPU_SubgroupMmaStoreMatrixOp
2046//===----------------------------------------------------------------------===//
2047
2048LogicalResult SubgroupMmaStoreMatrixOp::verify() {
2049 auto srcType = getSrc().getType();
2050 auto dstType = getDstMemref().getType();
2051 auto srcMatrixType = llvm::cast<gpu::MMAMatrixType>(srcType);
2052 auto dstMemrefType = llvm::cast<MemRefType>(dstType);
2053
2054 if (!dstMemrefType.isLastDimUnitStride())
2055 return emitError(
2056 "expected destination memref most minor dim must have unit stride");
2057
2058 if (srcMatrixType.getOperand() != "COp")
2059 return emitError(
2060 "expected the operand matrix being stored to have 'COp' operand type");
2061
2062 return success();
2063}
2064
2065//===----------------------------------------------------------------------===//
2066// GPU_SubgroupMmaComputeOp
2067//===----------------------------------------------------------------------===//
2068
2069LogicalResult SubgroupMmaComputeOp::verify() {
2070 enum OperandMap { A, B, C };
2072 opTypes.push_back(llvm::cast<MMAMatrixType>(getOpA().getType()));
2073 opTypes.push_back(llvm::cast<MMAMatrixType>(getOpB().getType()));
2074 opTypes.push_back(llvm::cast<MMAMatrixType>(getOpC().getType()));
2075
2076 if (opTypes[A].getOperand() != "AOp" || opTypes[B].getOperand() != "BOp" ||
2077 opTypes[C].getOperand() != "COp")
2078 return emitError("operands must be in the order AOp, BOp, COp");
2079
2080 ArrayRef<int64_t> aShape, bShape, cShape;
2081 aShape = opTypes[A].getShape();
2082 bShape = opTypes[B].getShape();
2083 cShape = opTypes[C].getShape();
2084
2085 if (aShape[1] != bShape[0] || aShape[0] != cShape[0] ||
2086 bShape[1] != cShape[1])
2087 return emitError("operand shapes do not satisfy matmul constraints");
2088
2089 return success();
2090}
2091
2092LogicalResult MemcpyOp::fold(FoldAdaptor adaptor,
2094 return memref::foldMemRefCast(*this);
2095}
2096
2097LogicalResult MemsetOp::fold(FoldAdaptor adaptor,
2099 return memref::foldMemRefCast(*this);
2100}
2101
2102//===----------------------------------------------------------------------===//
2103// GPU_WaitOp
2104//===----------------------------------------------------------------------===//
2105
2106namespace {
2107/// Remove gpu.wait op use of gpu.wait op def without async dependencies.
2108/// %t = gpu.wait async [] // No async dependencies.
2109/// ... gpu.wait ... [%t, ...] // %t can be removed.
2110struct EraseRedundantGpuWaitOpPairs : public OpRewritePattern<WaitOp> {
2111public:
2112 using Base::Base;
2113
2114 LogicalResult matchAndRewrite(WaitOp op,
2115 PatternRewriter &rewriter) const final {
2116 auto predicate = [](Value value) {
2117 auto waitOp = value.getDefiningOp<WaitOp>();
2118 return waitOp && waitOp->getNumOperands() == 0;
2119 };
2120 if (llvm::none_of(op.getAsyncDependencies(), predicate))
2121 return failure();
2122 SmallVector<Value> validOperands;
2123 for (Value operand : op->getOperands()) {
2124 if (predicate(operand))
2125 continue;
2126 validOperands.push_back(operand);
2127 }
2128 rewriter.modifyOpInPlace(op, [&]() { op->setOperands(validOperands); });
2129 return success();
2130 }
2131};
2132
2133/// Simplify trivial gpu.wait ops for the following patterns.
2134/// 1. %t = gpu.wait async ... ops, where %t has no uses (regardless of async
2135/// dependencies).
2136/// 2. %t1 = gpu.wait async [%t0], in this case, we can replace uses of %t1 with
2137/// %t0.
2138/// 3. gpu.wait [] ops, i.e gpu.wait ops that neither have any async
2139/// dependencies nor return any token.
2140struct SimplifyGpuWaitOp : public OpRewritePattern<WaitOp> {
2141public:
2142 using Base::Base;
2143
2144 LogicalResult matchAndRewrite(WaitOp op,
2145 PatternRewriter &rewriter) const final {
2146 // Erase gpu.wait ops that neither have any async dependencies nor return
2147 // any async token.
2148 if (op.getAsyncDependencies().empty() && !op.getAsyncToken()) {
2149 rewriter.eraseOp(op);
2150 return success();
2151 }
2152 // Replace uses of %t1 = gpu.wait async [%t0] ops with %t0 and erase the op.
2153 if (llvm::hasSingleElement(op.getAsyncDependencies()) &&
2154 op.getAsyncToken()) {
2155 rewriter.replaceOp(op, op.getAsyncDependencies());
2156 return success();
2157 }
2158 // Erase %t = gpu.wait async ... ops, where %t has no uses.
2159 if (op.getAsyncToken() && op.getAsyncToken().use_empty()) {
2160 rewriter.eraseOp(op);
2161 return success();
2162 }
2163 return failure();
2164 }
2165};
2166} // end anonymous namespace
2167
2168void WaitOp::getCanonicalizationPatterns(RewritePatternSet &results,
2169 MLIRContext *context) {
2170 results.add<EraseRedundantGpuWaitOpPairs, SimplifyGpuWaitOp>(context);
2171}
2172
2173//===----------------------------------------------------------------------===//
2174// GPU_AllocOp
2175//===----------------------------------------------------------------------===//
2176
2177LogicalResult AllocOp::verify() {
2178 auto memRefType = llvm::cast<MemRefType>(getMemref().getType());
2179
2180 if (failed(verifyDynamicDimensionCount(getOperation(), memRefType,
2181 getDynamicSizes())))
2182 return failure();
2183
2184 unsigned numSymbols = 0;
2185 if (!memRefType.getLayout().isIdentity())
2186 numSymbols = memRefType.getLayout().getAffineMap().getNumSymbols();
2187 if (getSymbolOperands().size() != numSymbols) {
2188 return emitOpError(
2189 "symbol operand count does not equal memref symbol count");
2190 }
2191
2192 return success();
2193}
2194
2195namespace {
2196/// Folding of memref.dim(gpu.alloc(%size), %idx) -> %size similar to
2197/// `memref::AllocOp`.
2198struct SimplifyDimOfAllocOp : public OpRewritePattern<memref::DimOp> {
2199 using OpRewritePattern<memref::DimOp>::OpRewritePattern;
2200
2201 LogicalResult matchAndRewrite(memref::DimOp dimOp,
2202 PatternRewriter &rewriter) const override {
2203 std::optional<int64_t> index = dimOp.getConstantIndex();
2204 if (!index)
2205 return failure();
2206
2207 int64_t indexVal = index.value();
2208 auto memrefType = llvm::dyn_cast<MemRefType>(dimOp.getSource().getType());
2209 if (!memrefType || indexVal < 0 || indexVal >= memrefType.getRank() ||
2210 !memrefType.isDynamicDim(indexVal))
2211 return failure();
2212
2213 auto alloc = dimOp.getSource().getDefiningOp<AllocOp>();
2214 if (!alloc)
2215 return failure();
2216
2217 Value substituteOp = *(alloc.getDynamicSizes().begin() +
2218 memrefType.getDynamicDimIndex(indexVal));
2219 rewriter.replaceOp(dimOp, substituteOp);
2220 return success();
2221 }
2222};
2223} // namespace
2224
2225void AllocOp::getCanonicalizationPatterns(RewritePatternSet &results,
2226 MLIRContext *context) {
2227 results.add<SimplifyDimOfAllocOp>(context);
2228}
2229
2230//===----------------------------------------------------------------------===//
2231// DynamicSharedMemoryOp
2232//===----------------------------------------------------------------------===//
2233
2234LogicalResult gpu::DynamicSharedMemoryOp::verify() {
2235 if (!getOperation()->getParentWithTrait<OpTrait::SymbolTable>())
2236 return emitOpError() << "must be inside an op with symbol table";
2237
2238 MemRefType memrefType = getResultMemref().getType();
2239 // Check address space
2240 if (!GPUDialect::hasWorkgroupMemoryAddressSpace(memrefType)) {
2241 return emitOpError() << "address space must be "
2242 << gpu::AddressSpaceAttr::getMnemonic() << "<"
2243 << stringifyEnum(gpu::AddressSpace::Workgroup) << ">";
2244 }
2245 if (memrefType.hasStaticShape()) {
2246 return emitOpError() << "result memref type must be memref<?xi8, "
2247 "#gpu.address_space<workgroup>>";
2248 }
2249 return success();
2250}
2251
2252//===----------------------------------------------------------------------===//
2253// GPU WarpExecuteOnLane0Op
2254//===----------------------------------------------------------------------===//
2255
2256void WarpExecuteOnLane0Op::print(OpAsmPrinter &p) {
2257 p << "(" << getLaneid() << ")";
2258
2259 SmallVector<StringRef> coreAttr = {getWarpSizeAttrName()};
2260 p << "[" << getWarpSize() << "]";
2261
2262 if (!getArgs().empty())
2263 p << " args(" << getArgs() << " : " << getArgs().getTypes() << ")";
2264 if (!getResults().empty())
2265 p << " -> (" << getResults().getTypes() << ')';
2266 p << " ";
2267 p.printRegion(getRegion(),
2268 /*printEntryBlockArgs=*/true,
2269 /*printBlockTerminators=*/!getResults().empty());
2271 getOperation()->getDiscardableAttrDictionary().getValue(), coreAttr);
2272}
2273
2274ParseResult WarpExecuteOnLane0Op::parse(OpAsmParser &parser,
2276 // Create the region.
2277 result.regions.reserve(1);
2278 Region *warpRegion = result.addRegion();
2279
2280 auto &builder = parser.getBuilder();
2282
2283 // Parse predicate operand.
2284 if (parser.parseLParen() ||
2285 parser.parseOperand(laneId, /*allowResultNumber=*/false) ||
2286 parser.parseRParen())
2287 return failure();
2288
2289 int64_t warpSize;
2290 if (parser.parseLSquare() || parser.parseInteger(warpSize) ||
2291 parser.parseRSquare())
2292 return failure();
2293 result.addAttribute(getWarpSizeAttrName(OperationName(getOperationName(),
2294 builder.getContext())),
2295 builder.getI64IntegerAttr(warpSize));
2296
2297 if (parser.resolveOperand(laneId, builder.getIndexType(), result.operands))
2298 return failure();
2299
2300 llvm::SMLoc inputsOperandsLoc;
2302 SmallVector<Type> inputTypes;
2303 if (succeeded(parser.parseOptionalKeyword("args"))) {
2304 if (parser.parseLParen())
2305 return failure();
2306
2307 inputsOperandsLoc = parser.getCurrentLocation();
2308 if (parser.parseOperandList(inputsOperands) ||
2309 parser.parseColonTypeList(inputTypes) || parser.parseRParen())
2310 return failure();
2311 }
2312 if (parser.resolveOperands(inputsOperands, inputTypes, inputsOperandsLoc,
2313 result.operands))
2314 return failure();
2315
2316 // Parse optional results type list.
2317 if (parser.parseOptionalArrowTypeList(result.types))
2318 return failure();
2319 // Parse the region.
2320 if (parser.parseRegion(*warpRegion, /*arguments=*/{},
2321 /*argTypes=*/{}))
2322 return failure();
2323 WarpExecuteOnLane0Op::ensureTerminator(*warpRegion, builder, result.location);
2324
2325 // Parse the optional attribute list.
2326 if (parser.parseOptionalAttrDict(result.attributes))
2327 return failure();
2328 return success();
2329}
2330
2331void WarpExecuteOnLane0Op::getSuccessorRegions(
2333 if (!point.isParent()) {
2334 regions.push_back(RegionSuccessor(getOperation()));
2335 return;
2336 }
2337
2338 // The warp region is always executed
2339 regions.push_back(RegionSuccessor(&getWarpRegion()));
2340}
2341
2342ValueRange WarpExecuteOnLane0Op::getSuccessorInputs(RegionSuccessor successor) {
2343 return successor.isOperation() ? ValueRange(getResults()) : ValueRange();
2344}
2345void WarpExecuteOnLane0Op::build(OpBuilder &builder, OperationState &result,
2346 TypeRange resultTypes, Value laneId,
2347 int64_t warpSize) {
2348 build(builder, result, resultTypes, laneId, warpSize,
2349 /*operands=*/{}, /*argTypes=*/{});
2350}
2351
2352void WarpExecuteOnLane0Op::build(OpBuilder &builder, OperationState &result,
2353 TypeRange resultTypes, Value laneId,
2354 int64_t warpSize, ValueRange args,
2355 TypeRange blockArgTypes) {
2356 result.addOperands(laneId);
2357 result.addAttribute(getAttributeNames()[0],
2358 builder.getI64IntegerAttr(warpSize));
2359 result.addTypes(resultTypes);
2360 result.addOperands(args);
2361 assert(args.size() == blockArgTypes.size());
2362 OpBuilder::InsertionGuard guard(builder);
2363 Region *warpRegion = result.addRegion();
2364 Block *block = builder.createBlock(warpRegion);
2365 for (auto [type, arg] : llvm::zip_equal(blockArgTypes, args))
2366 block->addArgument(type, arg.getLoc());
2367}
2368
2369/// Helper check if the distributed vector type is consistent with the expanded
2370/// type and distributed size.
2371static LogicalResult verifyDistributedType(Type expanded, Type distributed,
2372 int64_t warpSize, Operation *op) {
2373 // If the types matches there is no distribution.
2374 if (expanded == distributed)
2375 return success();
2376 auto expandedVecType = llvm::dyn_cast<VectorType>(expanded);
2377 auto distributedVecType = llvm::dyn_cast<VectorType>(distributed);
2378 if (!expandedVecType || !distributedVecType)
2379 return op->emitOpError("expected vector type for distributed operands.");
2380 if (expandedVecType.getRank() != distributedVecType.getRank() ||
2381 expandedVecType.getElementType() != distributedVecType.getElementType())
2382 return op->emitOpError(
2383 "expected distributed vectors to have same rank and element type.");
2384
2385 SmallVector<int64_t> scales(expandedVecType.getRank(), 1);
2386 for (int64_t i = 0, e = expandedVecType.getRank(); i < e; i++) {
2387 int64_t eDim = expandedVecType.getDimSize(i);
2388 int64_t dDim = distributedVecType.getDimSize(i);
2389 if (eDim == dDim)
2390 continue;
2391 if (eDim % dDim != 0)
2392 return op->emitOpError()
2393 << "expected expanded vector dimension #" << i << " (" << eDim
2394 << ") to be a multipler of the distributed vector dimension ("
2395 << dDim << ")";
2396 scales[i] = eDim / dDim;
2397 }
2398 if (llvm::product_of(scales) != warpSize)
2399 return op->emitOpError()
2400 << "incompatible distribution dimensions from " << expandedVecType
2401 << " to " << distributedVecType << " with warp size = " << warpSize;
2402
2403 return success();
2404}
2405
2406LogicalResult WarpExecuteOnLane0Op::verify() {
2407 if (getArgs().size() != getWarpRegion().getNumArguments())
2408 return emitOpError(
2409 "expected same number op arguments and block arguments.");
2410 auto yield = dyn_cast<gpu::YieldOp>(getBody()->getTerminator());
2411 if (!yield)
2412 return emitOpError("expected body to be terminated with 'gpu.yield'");
2413 if (yield.getNumOperands() != getNumResults())
2414 return emitOpError(
2415 "expected same number of yield operands and return values.");
2416 int64_t warpSize = getWarpSize();
2417 for (auto [regionArg, arg] :
2418 llvm::zip_equal(getWarpRegion().getArguments(), getArgs())) {
2419 if (failed(verifyDistributedType(regionArg.getType(), arg.getType(),
2420 warpSize, getOperation())))
2421 return failure();
2422 }
2423 for (auto [yieldOperand, result] :
2424 llvm::zip_equal(yield.getOperands(), getResults())) {
2425 if (failed(verifyDistributedType(yieldOperand.getType(), result.getType(),
2426 warpSize, getOperation())))
2427 return failure();
2428 }
2429 return success();
2430}
2431bool WarpExecuteOnLane0Op::areTypesCompatible(Type lhs, Type rhs) {
2432 return succeeded(
2433 verifyDistributedType(lhs, rhs, getWarpSize(), getOperation()));
2434}
2435
2436gpu::YieldOp WarpExecuteOnLane0Op::getTerminator() {
2437 return cast<gpu::YieldOp>(getBody()->getTerminator());
2438}
2439
2440//===----------------------------------------------------------------------===//
2441// GPU_SubgroupBroadcastOp
2442//===----------------------------------------------------------------------===//
2443
2444void gpu::SubgroupBroadcastOp::inferResultRanges(
2445 ArrayRef<ConstantIntRanges> argRanges, SetIntRangeFn setResultRange) {
2446 setResultRange(getResult(), argRanges.front());
2447}
2448
2449Speculation::Speculatability gpu::SubgroupBroadcastOp::getSpeculatability() {
2450 switch (getBroadcastType()) {
2451 case BroadcastType::first_active_lane:
2452 // Cannot speculate first_lane broadcast, because speculating it across
2453 // control flow can change the active lanes.
2455 case BroadcastType::specific_lane:
2456 // Speculation should be safe as long as we inside structured control flow.
2458 }
2459 llvm_unreachable("Unknown BroadcastType");
2460}
2461
2462LogicalResult gpu::SubgroupBroadcastOp::verify() {
2463 switch (getBroadcastType()) {
2464 case BroadcastType::first_active_lane:
2465 if (getLane())
2466 return emitOpError()
2467 << "lane can only be specified for `specific_lane` broadcast";
2468 return success();
2469 case BroadcastType::specific_lane:
2470 if (!getLane())
2471 return emitOpError()
2472 << "lane must be specified for `specific_lane` broadcast";
2473 return success();
2474 }
2475 llvm_unreachable("Unknown BroadcastType");
2476}
2477
2478OpFoldResult gpu::SubgroupBroadcastOp::fold(FoldAdaptor /*adaptor*/) {
2479 // Broadcast result is always uniform.
2480 if (auto prev = getSrc().getDefiningOp<SubgroupBroadcastOp>())
2481 return prev.getResult();
2482
2483 return nullptr;
2484}
2485
2486//===----------------------------------------------------------------------===//
2487// GPU_BallotOp
2488//===----------------------------------------------------------------------===//
2489
2490// No custom implementations needed; ballot uses default behavior from ODS.
2491
2492#include "mlir/Dialect/GPU/IR/GPUOpInterfaces.cpp.inc"
2493
2494#define GET_OP_CLASSES
2495#include "mlir/Dialect/GPU/IR/GPUOps.cpp.inc"
return success()
static void printLaunchFuncOperands(OpAsmPrinter &printer, Operation *, OperandRange operands, TypeRange types)
static ParseResult parseAsyncDependencies(OpAsmParser &parser, Type &asyncTokenType, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &asyncDependencies)
Parses an optional list of async operands with an optional leading keyword.
static void setAttributionAttrs(GPUFuncOp op, unsigned index, DictionaryAttr value, StringAttr attrName)
static void printAttributions(OpAsmPrinter &p, StringRef keyword, ArrayRef< BlockArgument > values, ArrayAttr attributes={})
static LogicalResult verifyDistributedType(Type expanded, Type distributed, int64_t warpSize, Operation *op)
Helper check if the distributed vector type is consistent with the expanded type and distributed size...
static void printAsyncDependencies(OpAsmPrinter &printer, Operation *op, Type asyncTokenType, OperandRange asyncDependencies)
Prints optional async dependencies with its leading keyword.
static ParseResult parseSizeAssignment(OpAsmParser &parser, MutableArrayRef< OpAsmParser::UnresolvedOperand > sizes, MutableArrayRef< OpAsmParser::UnresolvedOperand > regionSizes, MutableArrayRef< OpAsmParser::UnresolvedOperand > indices, StringRef keyword)
static LogicalResult eraseRedundantGpuBarrierOps(BarrierOp op, PatternRewriter &rewriter)
Remove gpu.barrier after gpu.barrier, the threads are already synchronized!
static ParseResult parseOffloadingHandler(OpAsmParser &parser, Attribute &offloadingHandler)
static DictionaryAttr getAttributionAttrs(GPUFuncOp op, unsigned index, StringAttr attrName)
static void printLaunchDimType(OpAsmPrinter &printer, Operation *op, Type dimTy, Value clusterValue, Type clusterXTy, Type clusterYTy, Type clusterZTy)
static bool canMakeGroupOpUniform(Operation *op)
static std::string getSparseHandleKeyword(SparseHandleKind kind)
static LogicalResult verifyKnownLaunchSizeAttr(Operation *op, NamedAttribute attr)
static LogicalResult verifyLaunchAsyncModel(OpTy op)
static ParseResult parseAttributions(OpAsmParser &parser, StringRef keyword, SmallVectorImpl< OpAsmParser::Argument > &args)
Parses a GPU function memory attribution.
static ParseResult parseLaunchDimType(OpAsmParser &parser, Type &dimTy, std::optional< OpAsmParser::UnresolvedOperand > clusterValue, Type &clusterXTy, Type &clusterYTy, Type &clusterZTy)
static void setAttributionAttr(GPUFuncOp op, unsigned index, StringAttr name, Attribute value, StringAttr attrsName)
static ParseResult parseLaunchFuncOperands(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &argNames, SmallVectorImpl< Type > &argTypes)
static void printOffloadingHandler(OpAsmPrinter &printer, Operation *op, Attribute offloadingHandler)
static LogicalResult verifyReduceOpAndType(gpu::AllReduceOperation opName, Type resType)
static void printSizeAssignment(OpAsmPrinter &p, KernelDim3 size, KernelDim3 operands, KernelDim3 ids)
static Attribute getAttributionAttr(GPUFuncOp op, unsigned index, StringAttr name, StringAttr attrsName)
static LogicalResult verifyAttributions(Operation *op, ArrayRef< BlockArgument > attributions, gpu::AddressSpace memorySpace)
Verifies a GPU function memory attribution.
static bool isLegalToInline(InlinerInterface &interface, Region *src, Region *insertRegion, bool shouldCloneInlinedRegion, IRMapping &valueMapping)
Utility to check that all of the operations within 'src' can be inlined.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
ArrayAttr()
b getContext())
template bool mlir::hasSingleEffect< MemoryEffects::Allocate >(Operation *)
static void getDynamicSizes(RankedTensorType tp, ValueRange sizes, SmallVectorImpl< Value > &dynSizes)
Collects the dynamic dimension sizes for tp with the assumption that sizes are the dimension sizes fo...
static sycl::kernel * getKernel(ze_module_handle_t zeModule, const char *name)
This class contains all of the static information common to all instances of a registered Attribute.
static AbstractAttribute get(Dialect &dialect)
This method is used by Dialect objects when they register the list of attributes they contain.
ParseResult parseSymbolName(StringAttr &result)
Parse an -identifier and store it (without the '@' symbol) in a string attribute.
@ Paren
Parens surrounding zero or more operands.
@ OptionalSquare
Square brackets supporting zero or more ops, or nothing.
virtual ParseResult parseColonTypeList(SmallVectorImpl< Type > &result)=0
Parse a colon followed by a type list, which must have at least one type.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
MLIRContext * getContext() const
virtual Location getEncodedSourceLoc(SMLoc loc)=0
Re-encode the given source location as an MLIR location and return it.
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseOptionalColon()=0
Parse a : token if present.
virtual ParseResult parseLSquare()=0
Parse a [ token.
virtual ParseResult parseRSquare()=0
Parse a ] token.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual ParseResult parseDimensionList(SmallVectorImpl< int64_t > &dimensions, bool allowDynamic=true, bool withTrailingX=true)=0
Parse a dimension list of a tensor or memref type.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result)=0
Parse a named dictionary into 'result' if the attributes keyword is present.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseColon()=0
Parse a : token.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseOptionalString(std::string *string)=0
Parse a quoted string token if present.
virtual ParseResult parseOptionalLess()=0
Parse a '<' token if present.
virtual ParseResult parseGreater()=0
Parse a '>' token.
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseComma()=0
Parse a , token.
virtual ParseResult parseOptionalArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an optional arrow followed by a type list.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
virtual void printSymbolName(StringRef symbolRef)
Print the given string as a symbol reference, i.e.
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class represents an argument of a Block.
Definition Value.h:308
Block represents an ordered list of Operations.
Definition Block.h:34
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
Definition Block.cpp:158
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
UnitAttr getUnitAttr()
Definition Builders.cpp:106
IntegerAttr getI32IntegerAttr(int32_t value)
Definition Builders.cpp:208
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition Builders.cpp:171
FunctionType getFunctionType(TypeRange inputs, TypeRange results)
Definition Builders.cpp:84
IntegerType getI32Type()
Definition Builders.cpp:71
IntegerAttr getI64IntegerAttr(int64_t value)
Definition Builders.cpp:120
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
Definition Builders.h:94
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition Builders.cpp:275
MLIRContext * getContext() const
Definition Builders.h:56
IndexType getIndexType()
Definition Builders.cpp:59
DictionaryAttr getDictionaryAttr(ArrayRef< NamedAttribute > value)
Definition Builders.cpp:112
NamedAttribute getNamedAttr(StringRef name, Attribute val)
Definition Builders.cpp:102
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
Definition Builders.h:101
The DialectAsmParser has methods for interacting with the asm parser when parsing attributes and type...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
This class defines a virtual interface for reading a bytecode stream, providing hooks into the byteco...
virtual LogicalResult readVarInt(uint64_t &result)=0
Read a variable width integer.
virtual FailureOr< const DialectVersion * > getDialectVersion(StringRef dialectName) const =0
Retrieve the dialect version by name if available.
virtual LogicalResult readOptionalAttribute(Attribute &attr)=0
Read an optional reference to the given attribute.
virtual InFlightDiagnostic emitError(const Twine &msg={}) const =0
Emit an error to the reader.
virtual LogicalResult readAttribute(Attribute &result)=0
Read a reference to the given attribute.
This class defines a virtual interface for writing to a bytecode stream, providing hooks into the byt...
virtual void writeOptionalAttribute(Attribute attr)=0
virtual void writeVarInt(uint64_t value)=0
Write a variable width integer to the output stream.
virtual void writeAttribute(Attribute attr)=0
Write a reference to the given attribute.
virtual int64_t getBytecodeVersion() const =0
Return the bytecode version being emitted for.
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
Definition Dialect.h:38
A symbol reference with a reference path containing a single element.
This class represents a diagnostic that is inflight and set to be reported.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
StringAttr getName() const
Return the name of the attribute.
Attribute getValue() const
Return the value of the attribute.
Definition Attributes.h:181
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual size_t getNumResults() const =0
Return the number of declared SSA results.
virtual ParseResult parseRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
virtual ParseResult parseArgumentList(SmallVectorImpl< Argument > &result, Delimiter delimiter=Delimiter::None, bool allowType=false, bool allowAttrs=false)=0
Parse zero or more arguments with a specified surrounding delimiter.
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Definition Builders.cpp:439
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
This class represents a single result from folding an operation.
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
void setInherentAttr(StringAttr name, Attribute value)
Set an inherent attribute by name.
void insertOperands(unsigned index, ValueRange operands)
Insert the given operands into the operand list at the given 'index'.
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
std::optional< Attribute > getInherentAttr(StringRef name)
Access an inherent attribute by name: returns an empty optional if there is no inherent attribute wit...
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
AttrClass getDiscardableAttrOfType(StringRef name)
Access a discardable attribute by name and cast it to AttrClass.
Definition Operation.h:495
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:233
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class represents a point being branched from in the methods of the RegionBranchOpInterface.
bool isParent() const
Returns true if branching from the parent op.
This class represents a successor of a region.
bool isOperation() const
Return true if the successor is an operation.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & front()
Definition Region.h:65
bool empty()
Definition Region.h:60
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
This class represents a collection of SymbolTables.
virtual Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
static Operation * getNearestSymbolTable(Operation *from)
Returns the nearest symbol table from a given operation from.
This class provides an efficient unique identifier for a specific C++ type.
Definition TypeID.h:107
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIndex() const
Definition Types.cpp:56
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
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
user_range getUsers() const
Definition Value.h:218
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:453
MMAMatrix represents a matrix held by a subgroup for matrix-matrix multiply accumulate operations.
Definition GPUBase.h:132
ArrayRef< int64_t > getShape() const
Get shape of the matrix.
Definition GPUBase.cpp:129
Type getElementType() const
Get elementType of a single element.
Definition GPUBase.cpp:133
StringRef getOperand() const
The general form of operation this type supports is given by the equation C += A*B.
Definition GPUBase.cpp:135
static MMAMatrixType getChecked(function_ref< InFlightDiagnostic()> emitError, ArrayRef< int64_t > shape, Type elementType, StringRef operand)
Get MMAMatrixType at a particular location and verify construction Invariants.
Definition GPUBase.cpp:120
Speculatability
This enum is returned from the getSpeculatability method in the ConditionallySpeculatable op interfac...
constexpr auto Speculatable
constexpr auto NotSpeculatable
@ kDialectVersioning
Dialects versioning was added in version 1.
Definition Encoding.h:32
void addArgAndResultAttrs(Builder &builder, OperationState &result, ArrayRef< DictionaryAttr > argAttrs, ArrayRef< DictionaryAttr > resultAttrs, StringAttr argAttrsName, StringAttr resAttrsName)
Adds argument and result attributes, provided as argAttrs and resultAttrs arguments,...
llvm::unique_function< InFlightDiagnostic()> getDefaultDiagnosticEmitFn(MLIRContext *ctx)
Utility method to generate a callback that can be used to generate a diagnostic when checking the con...
ParseResult parseFunctionSignatureWithArguments(OpAsmParser &parser, bool allowVariadic, SmallVectorImpl< OpAsmParser::Argument > &arguments, bool &isVariadic, SmallVectorImpl< Type > &resultTypes, SmallVectorImpl< DictionaryAttr > &resultAttrs)
Parses a function signature using parser.
void printFunctionAttributes(OpAsmPrinter &p, Operation *op, ArrayRef< StringRef > elided={})
Prints the list of function prefixed with the "attributes" keyword.
void printFunctionSignature(OpAsmPrinter &p, FunctionOpInterface op, ArrayRef< Type > argTypes, bool isVariadic, ArrayRef< Type > resultTypes)
Prints the signature of the function-like operation op.
void registerAttributeStorage(MLIRContext *context)
Register storage whose definitions are private to MLIRGPUBase.
Definition GPUBase.cpp:504
void addAsyncDependency(Operation *op, Value token)
SparseHandleKind
Definition GPUBase.h:174
LogicalResult foldMemRefCast(Operation *op, Value inner=nullptr)
This is a common utility used for patterns of the form "someop(memref.cast) -> someop".
Definition MemRefOps.cpp:48
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
SmallVector< unsigned > getBlockSize(AffineMap dimToLvl)
Given the dimToLvl map, returns the block sizes in a vector.
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
llvm::function_ref< void(Value, const ConstantIntRanges &)> SetIntRangeFn
The type of the setResultRanges callback provided to ops implementing InferIntRangeInterface.
LogicalResult verifyDynamicDimensionCount(Operation *op, ShapedType type, ValueRange dynamicSizes)
Verify that the number of dynamic size operands matches the number of dynamic dimensions in the shape...
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
detail::constant_int_predicate_matcher m_One()
Matches a constant scalar / vector splat / tensor splat integer one.
Definition Matchers.h:478
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147
LogicalResult verifyCompatibleShape(ArrayRef< int64_t > shape1, ArrayRef< int64_t > shape2)
Returns success if the given two shapes are compatible.
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
Simplify the gpu.launch when the range of a thread or block ID is trivially known to be one.
LogicalResult matchAndRewrite(LaunchOp op, PatternRewriter &rewriter) const override
This is the representation of an operand reference.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
This represents an operation in an abstracted form, suitable for use with the builder APIs.
T & getOrAddProperties()
Get (or create) the properties of the provided type to be set on the operation on creation.
Utility class for the GPU dialect to represent triples of Values accessible through ....
Definition GPUDialect.h:29