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 
13 #include "mlir/Dialect/GPU/GPUDialect.h"
14 
15 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
16 #include "mlir/Dialect/StandardOps/IR/Ops.h"
17 #include "mlir/IR/Attributes.h"
18 #include "mlir/IR/Builders.h"
19 #include "mlir/IR/BuiltinOps.h"
20 #include "mlir/IR/BuiltinTypes.h"
21 #include "mlir/IR/DialectImplementation.h"
22 #include "mlir/IR/FunctionImplementation.h"
23 #include "mlir/IR/OpImplementation.h"
24 #include "mlir/IR/PatternMatch.h"
25 #include "mlir/IR/TypeUtilities.h"
26 #include "llvm/ADT/TypeSwitch.h"
27 
28 using namespace mlir;
29 using namespace mlir::gpu;
30 
31 //===----------------------------------------------------------------------===//
32 // MMAMatrixType
33 //===----------------------------------------------------------------------===//
34 
35 MMAMatrixType MMAMatrixType::get(ArrayRef<int64_t> shape, Type elementType,
36                                  StringRef operand) {
37   return Base::get(elementType.getContext(), shape, elementType, operand);
38 }
39 
40 MMAMatrixType
41 MMAMatrixType::getChecked(function_ref<InFlightDiagnostic()> emitError,
42                           ArrayRef<int64_t> shape, Type elementType,
43                           StringRef operand) {
44   return Base::getChecked(emitError, elementType.getContext(), shape,
45                           elementType, operand);
46 }
47 
48 unsigned MMAMatrixType::getNumDims() const { return getImpl()->numDims; }
49 
50 ArrayRef<int64_t> MMAMatrixType::getShape() const {
51   return getImpl()->getShape();
52 }
53 
54 Type MMAMatrixType::getElementType() const { return getImpl()->elementType; }
55 
56 StringRef MMAMatrixType::getOperand() const { return getImpl()->getOperand(); }
57 
58 bool MMAMatrixType::isValidElementType(Type elementType) {
59   return elementType.isF16() || elementType.isF32();
60 }
61 
62 LogicalResult
63 MMAMatrixType::verify(function_ref<InFlightDiagnostic()> emitError,
64                       ArrayRef<int64_t> shape, Type elementType,
65                       StringRef operand) {
66   if (!operand.equals("AOp") && !operand.equals("BOp") &&
67       !operand.equals("COp"))
68     return emitError() << "operand expected to be one of AOp, BOp or COp";
69 
70   if (shape.size() != 2)
71     return emitError() << "MMAMatrixType must have exactly two dimensions";
72 
73   if (!MMAMatrixType::isValidElementType(elementType))
74     return emitError() << "MMAMatrixType elements must be F16 or F32";
75 
76   return success();
77 }
78 
79 //===----------------------------------------------------------------------===//
80 // GPUDialect
81 //===----------------------------------------------------------------------===//
82 
83 /// GPU memory space identifiers.
84 enum GPUMemorySpace {
85   /// Generic memory space identifier.
86   kGenericMemorySpace = 0,
87 
88   /// Global memory space identifier.
89   kGlobalMemorySpace = 1,
90 
91   /// Shared memory space identifier.
92   kSharedMemorySpace = 3
93 };
94 
95 bool GPUDialect::isKernel(Operation *op) {
96   UnitAttr isKernelAttr = op->getAttrOfType<UnitAttr>(getKernelFuncAttrName());
97   return static_cast<bool>(isKernelAttr);
98 }
99 
100 void GPUDialect::initialize() {
101   addTypes<AsyncTokenType>();
102   addTypes<MMAMatrixType>();
103   addOperations<
104 #define GET_OP_LIST
105 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
106       >();
107 }
108 
109 Type GPUDialect::parseType(DialectAsmParser &parser) const {
110   // Parse the main keyword for the type.
111   StringRef keyword;
112   if (parser.parseKeyword(&keyword))
113     return Type();
114   MLIRContext *context = getContext();
115 
116   // Handle 'async token' types.
117   if (keyword == "async.token")
118     return AsyncTokenType::get(context);
119 
120   if (keyword == "mma_matrix") {
121     llvm::SMLoc beginLoc = parser.getNameLoc();
122 
123     // Parse '<'.
124     if (parser.parseLess())
125       return nullptr;
126 
127     // Parse the size and elementType.
128     SmallVector<int64_t> shape;
129     Type elementType;
130     if (parser.parseDimensionList(shape, /*allowDynamic=*/false) ||
131         parser.parseType(elementType))
132       return nullptr;
133 
134     // Parse ','
135     if (parser.parseComma())
136       return nullptr;
137 
138     // Parse operand.
139     StringRef operand;
140     if (failed(parser.parseOptionalString(&operand)))
141       return nullptr;
142 
143     // Parse '>'.
144     if (parser.parseGreater())
145       return nullptr;
146 
147     return MMAMatrixType::getChecked(mlir::detail::getDefaultDiagnosticEmitFn(
148                                          parser.getEncodedSourceLoc(beginLoc)),
149                                      shape, elementType, operand);
150   }
151 
152   parser.emitError(parser.getNameLoc(), "unknown gpu type: " + keyword);
153   return Type();
154 }
155 
156 void GPUDialect::printType(Type type, DialectAsmPrinter &os) const {
157   TypeSwitch<Type>(type)
158       .Case<AsyncTokenType>([&](Type) { os << "async.token"; })
159       .Case<MMAMatrixType>([&](MMAMatrixType fragTy) {
160         os << "mma_matrix<";
161         auto shape = fragTy.getShape();
162         for (auto dim = shape.begin(), e = shape.end() - 1; dim != e; ++dim)
163           os << *dim << 'x';
164         os << shape.back() << 'x' << fragTy.getElementType();
165         os << ", \"" << fragTy.getOperand() << "\"" << '>';
166       })
167       .Default([](Type) { llvm_unreachable("unexpected 'gpu' type kind"); });
168 }
169 
170 LogicalResult GPUDialect::verifyOperationAttribute(Operation *op,
171                                                    NamedAttribute attr) {
172   if (!attr.second.isa<UnitAttr>() ||
173       attr.first != getContainerModuleAttrName())
174     return success();
175 
176   auto module = dyn_cast<ModuleOp>(op);
177   if (!module)
178     return op->emitError("expected '")
179            << getContainerModuleAttrName() << "' attribute to be attached to '"
180            << ModuleOp::getOperationName() << '\'';
181 
182   auto walkResult = module.walk([&module](LaunchFuncOp launchOp) -> WalkResult {
183     // Ignore launches that are nested more or less deep than functions in the
184     // module we are currently checking.
185     if (!launchOp->getParentOp() ||
186         launchOp->getParentOp()->getParentOp() != module)
187       return success();
188 
189     // Ignore launch ops with missing attributes here. The errors will be
190     // reported by the verifiers of those ops.
191     if (!launchOp->getAttrOfType<SymbolRefAttr>(
192             LaunchFuncOp::getKernelAttrName()))
193       return success();
194 
195     // Check that `launch_func` refers to a well-formed GPU kernel module.
196     StringRef kernelModuleName = launchOp.getKernelModuleName();
197     auto kernelModule = module.lookupSymbol<GPUModuleOp>(kernelModuleName);
198     if (!kernelModule)
199       return launchOp.emitOpError()
200              << "kernel module '" << kernelModuleName << "' is undefined";
201 
202     // Check that `launch_func` refers to a well-formed kernel function.
203     Operation *kernelFunc = module.lookupSymbol(launchOp.kernel());
204     auto kernelGPUFunction = dyn_cast_or_null<gpu::GPUFuncOp>(kernelFunc);
205     auto kernelLLVMFunction = dyn_cast_or_null<LLVM::LLVMFuncOp>(kernelFunc);
206     if (!kernelGPUFunction && !kernelLLVMFunction)
207       return launchOp.emitOpError("kernel function '")
208              << launchOp.kernel() << "' is undefined";
209     if (!kernelFunc->getAttrOfType<mlir::UnitAttr>(
210             GPUDialect::getKernelFuncAttrName()))
211       return launchOp.emitOpError("kernel function is missing the '")
212              << GPUDialect::getKernelFuncAttrName() << "' attribute";
213 
214     // TODO: if the kernel function has been converted to
215     // the LLVM dialect but the caller hasn't (which happens during the
216     // separate compilation), do not check type correspondence as it would
217     // require the verifier to be aware of the LLVM type conversion.
218     if (kernelLLVMFunction)
219       return success();
220 
221     unsigned actualNumArguments = launchOp.getNumKernelOperands();
222     unsigned expectedNumArguments = kernelGPUFunction.getNumArguments();
223     if (expectedNumArguments != actualNumArguments)
224       return launchOp.emitOpError("got ")
225              << actualNumArguments << " kernel operands but expected "
226              << expectedNumArguments;
227 
228     auto functionType = kernelGPUFunction.getType();
229     for (unsigned i = 0; i < expectedNumArguments; ++i) {
230       if (launchOp.getKernelOperand(i).getType() != functionType.getInput(i)) {
231         return launchOp.emitOpError("type of function argument ")
232                << i << " does not match";
233       }
234     }
235 
236     return success();
237   });
238 
239   return walkResult.wasInterrupted() ? failure() : success();
240 }
241 
242 template <typename T>
243 static LogicalResult verifyIndexOp(T op) {
244   auto dimension = op.dimension();
245   if (dimension != "x" && dimension != "y" && dimension != "z")
246     return op.emitError("dimension \"") << dimension << "\" is invalid";
247   return success();
248 }
249 
250 static LogicalResult verifyAllReduce(gpu::AllReduceOp allReduce) {
251   if (allReduce.body().empty() != allReduce.op().hasValue())
252     return allReduce.emitError(
253         "expected either an op attribute or a non-empty body");
254   if (!allReduce.body().empty()) {
255     if (allReduce.body().getNumArguments() != 2)
256       return allReduce.emitError("expected two region arguments");
257     for (auto argument : allReduce.body().getArguments()) {
258       if (argument.getType() != allReduce.getType())
259         return allReduce.emitError("incorrect region argument type");
260     }
261     unsigned yieldCount = 0;
262     for (Block &block : allReduce.body()) {
263       if (auto yield = dyn_cast<gpu::YieldOp>(block.getTerminator())) {
264         if (yield.getNumOperands() != 1)
265           return allReduce.emitError("expected one gpu.yield operand");
266         if (yield.getOperand(0).getType() != allReduce.getType())
267           return allReduce.emitError("incorrect gpu.yield type");
268         ++yieldCount;
269       }
270     }
271     if (yieldCount == 0)
272       return allReduce.emitError("expected gpu.yield op in region");
273   } else {
274     StringRef opName = *allReduce.op();
275     if ((opName == "and" || opName == "or" || opName == "xor") &&
276         !allReduce.getType().isa<IntegerType>()) {
277       return allReduce.emitError()
278              << '`' << opName << '`'
279              << " accumulator is only compatible with Integer type";
280     }
281   }
282   return success();
283 }
284 
285 static LogicalResult verifyShuffleOp(gpu::ShuffleOp shuffleOp) {
286   auto type = shuffleOp.value().getType();
287   if (shuffleOp.result().getType() != type) {
288     return shuffleOp.emitOpError()
289            << "requires the same type for value operand and result";
290   }
291   if (!type.isSignlessIntOrFloat() || type.getIntOrFloatBitWidth() != 32) {
292     return shuffleOp.emitOpError()
293            << "requires value operand type to be f32 or i32";
294   }
295   return success();
296 }
297 
298 static void printShuffleOp(OpAsmPrinter &p, ShuffleOp op) {
299   p << ShuffleOp::getOperationName() << ' ' << op.getOperands() << ' '
300     << op.mode() << " : " << op.value().getType();
301 }
302 
303 static ParseResult parseShuffleOp(OpAsmParser &parser, OperationState &state) {
304   SmallVector<OpAsmParser::OperandType, 3> operandInfo;
305   if (parser.parseOperandList(operandInfo, 3))
306     return failure();
307 
308   StringRef mode;
309   if (parser.parseKeyword(&mode))
310     return failure();
311   state.addAttribute("mode", parser.getBuilder().getStringAttr(mode));
312 
313   Type valueType;
314   Type int32Type = parser.getBuilder().getIntegerType(32);
315   Type int1Type = parser.getBuilder().getI1Type();
316   if (parser.parseColonType(valueType) ||
317       parser.resolveOperands(operandInfo, {valueType, int32Type, int32Type},
318                              parser.getCurrentLocation(), state.operands) ||
319       parser.addTypesToList({valueType, int1Type}, state.types))
320     return failure();
321   return success();
322 }
323 
324 //===----------------------------------------------------------------------===//
325 // AsyncOpInterface
326 //===----------------------------------------------------------------------===//
327 
328 void gpu::addAsyncDependency(Operation *op, Value token) {
329   op->insertOperands(0, {token});
330   if (!op->template hasTrait<OpTrait::AttrSizedOperandSegments>())
331     return;
332   auto attrName =
333       OpTrait::AttrSizedOperandSegments<void>::getOperandSegmentSizeAttr();
334   auto sizeAttr = op->template getAttrOfType<DenseIntElementsAttr>(attrName);
335   if (!sizeAttr)
336     return; // Async dependencies is the only variadic operand.
337   SmallVector<int32_t, 8> sizes;
338   for (auto size : sizeAttr.getIntValues())
339     sizes.push_back(size.getSExtValue());
340   ++sizes.front();
341   op->setAttr(attrName, Builder(op->getContext()).getI32VectorAttr(sizes));
342 }
343 
344 //===----------------------------------------------------------------------===//
345 // LaunchOp
346 //===----------------------------------------------------------------------===//
347 
348 void LaunchOp::build(OpBuilder &builder, OperationState &result,
349                      Value gridSizeX, Value gridSizeY, Value gridSizeZ,
350                      Value blockSizeX, Value blockSizeY, Value blockSizeZ) {
351   // Add grid and block sizes as op operands, followed by the data operands.
352   result.addOperands(
353       {gridSizeX, gridSizeY, gridSizeZ, blockSizeX, blockSizeY, blockSizeZ});
354 
355   // Create a kernel body region with kNumConfigRegionAttributes + N arguments,
356   // where the first kNumConfigRegionAttributes arguments have `index` type and
357   // the rest have the same types as the data operands.
358   Region *kernelRegion = result.addRegion();
359   Block *body = new Block();
360   body->addArguments(
361       std::vector<Type>(kNumConfigRegionAttributes, builder.getIndexType()));
362   kernelRegion->push_back(body);
363 }
364 
365 KernelDim3 LaunchOp::getBlockIds() {
366   assert(!body().empty() && "LaunchOp body must not be empty.");
367   auto args = body().getArguments();
368   return KernelDim3{args[0], args[1], args[2]};
369 }
370 
371 KernelDim3 LaunchOp::getThreadIds() {
372   assert(!body().empty() && "LaunchOp body must not be empty.");
373   auto args = body().getArguments();
374   return KernelDim3{args[3], args[4], args[5]};
375 }
376 
377 KernelDim3 LaunchOp::getGridSize() {
378   assert(!body().empty() && "LaunchOp body must not be empty.");
379   auto args = body().getArguments();
380   return KernelDim3{args[6], args[7], args[8]};
381 }
382 
383 KernelDim3 LaunchOp::getBlockSize() {
384   assert(!body().empty() && "LaunchOp body must not be empty.");
385   auto args = body().getArguments();
386   return KernelDim3{args[9], args[10], args[11]};
387 }
388 
389 KernelDim3 LaunchOp::getGridSizeOperandValues() {
390   return KernelDim3{getOperand(0), getOperand(1), getOperand(2)};
391 }
392 
393 KernelDim3 LaunchOp::getBlockSizeOperandValues() {
394   return KernelDim3{getOperand(3), getOperand(4), getOperand(5)};
395 }
396 
397 static LogicalResult verify(LaunchOp op) {
398   // Kernel launch takes kNumConfigOperands leading operands for grid/block
399   // sizes and transforms them into kNumConfigRegionAttributes region arguments
400   // for block/thread identifiers and grid/block sizes.
401   if (!op.body().empty()) {
402     if (op.body().getNumArguments() !=
403         LaunchOp::kNumConfigOperands + op.getNumOperands())
404       return op.emitOpError("unexpected number of region arguments");
405   }
406 
407   // Block terminators without successors are expected to exit the kernel region
408   // and must be `gpu.terminator`.
409   for (Block &block : op.body()) {
410     if (block.empty())
411       continue;
412     if (block.back().getNumSuccessors() != 0)
413       continue;
414     if (!isa<gpu::TerminatorOp>(&block.back())) {
415       return block.back()
416           .emitError()
417           .append("expected '", gpu::TerminatorOp::getOperationName(),
418                   "' or a terminator with successors")
419           .attachNote(op.getLoc())
420           .append("in '", LaunchOp::getOperationName(), "' body region");
421     }
422   }
423 
424   return success();
425 }
426 
427 // Pretty-print the kernel grid/block size assignment as
428 //   (%iter-x, %iter-y, %iter-z) in
429 //   (%size-x = %ssa-use, %size-y = %ssa-use, %size-z = %ssa-use)
430 // where %size-* and %iter-* will correspond to the body region arguments.
431 static void printSizeAssignment(OpAsmPrinter &p, KernelDim3 size,
432                                 KernelDim3 operands, KernelDim3 ids) {
433   p << '(' << ids.x << ", " << ids.y << ", " << ids.z << ") in (";
434   p << size.x << " = " << operands.x << ", ";
435   p << size.y << " = " << operands.y << ", ";
436   p << size.z << " = " << operands.z << ')';
437 }
438 
439 static void printLaunchOp(OpAsmPrinter &p, LaunchOp op) {
440   // Print the launch configuration.
441   p << LaunchOp::getOperationName() << ' ' << op.getBlocksKeyword();
442   printSizeAssignment(p, op.getGridSize(), op.getGridSizeOperandValues(),
443                       op.getBlockIds());
444   p << ' ' << op.getThreadsKeyword();
445   printSizeAssignment(p, op.getBlockSize(), op.getBlockSizeOperandValues(),
446                       op.getThreadIds());
447 
448   p.printRegion(op.body(), /*printEntryBlockArgs=*/false);
449   p.printOptionalAttrDict(op->getAttrs());
450 }
451 
452 // Parse the size assignment blocks for blocks and threads.  These have the form
453 //   (%region_arg, %region_arg, %region_arg) in
454 //   (%region_arg = %operand, %region_arg = %operand, %region_arg = %operand)
455 // where %region_arg are percent-identifiers for the region arguments to be
456 // introduced further (SSA defs), and %operand are percent-identifiers for the
457 // SSA value uses.
458 static ParseResult
459 parseSizeAssignment(OpAsmParser &parser,
460                     MutableArrayRef<OpAsmParser::OperandType> sizes,
461                     MutableArrayRef<OpAsmParser::OperandType> regionSizes,
462                     MutableArrayRef<OpAsmParser::OperandType> indices) {
463   assert(indices.size() == 3 && "space for three indices expected");
464   SmallVector<OpAsmParser::OperandType, 3> args;
465   if (parser.parseRegionArgumentList(args, /*requiredOperandCount=*/3,
466                                      OpAsmParser::Delimiter::Paren) ||
467       parser.parseKeyword("in") || parser.parseLParen())
468     return failure();
469   std::move(args.begin(), args.end(), indices.begin());
470 
471   for (int i = 0; i < 3; ++i) {
472     if (i != 0 && parser.parseComma())
473       return failure();
474     if (parser.parseRegionArgument(regionSizes[i]) || parser.parseEqual() ||
475         parser.parseOperand(sizes[i]))
476       return failure();
477   }
478 
479   return parser.parseRParen();
480 }
481 
482 // Parses a Launch operation.
483 // operation ::= `gpu.launch` `blocks` `(` ssa-id-list `)` `in` ssa-reassignment
484 //                           `threads` `(` ssa-id-list `)` `in` ssa-reassignment
485 //                            region attr-dict?
486 // ssa-reassignment ::= `(` ssa-id `=` ssa-use (`,` ssa-id `=` ssa-use)* `)`
487 static ParseResult parseLaunchOp(OpAsmParser &parser, OperationState &result) {
488   // Sizes of the grid and block.
489   SmallVector<OpAsmParser::OperandType, LaunchOp::kNumConfigOperands> sizes(
490       LaunchOp::kNumConfigOperands);
491   MutableArrayRef<OpAsmParser::OperandType> sizesRef(sizes);
492 
493   // Actual (data) operands passed to the kernel.
494   SmallVector<OpAsmParser::OperandType, 4> dataOperands;
495 
496   // Region arguments to be created.
497   SmallVector<OpAsmParser::OperandType, 16> regionArgs(
498       LaunchOp::kNumConfigRegionAttributes);
499   MutableArrayRef<OpAsmParser::OperandType> regionArgsRef(regionArgs);
500 
501   // Parse the size assignment segments: the first segment assigns grid sizes
502   // and defines values for block identifiers; the second segment assigns block
503   // sizes and defines values for thread identifiers.  In the region argument
504   // list, identifiers precede sizes, and block-related values precede
505   // thread-related values.
506   if (parser.parseKeyword(LaunchOp::getBlocksKeyword().data()) ||
507       parseSizeAssignment(parser, sizesRef.take_front(3),
508                           regionArgsRef.slice(6, 3),
509                           regionArgsRef.slice(0, 3)) ||
510       parser.parseKeyword(LaunchOp::getThreadsKeyword().data()) ||
511       parseSizeAssignment(parser, sizesRef.drop_front(3),
512                           regionArgsRef.slice(9, 3),
513                           regionArgsRef.slice(3, 3)) ||
514       parser.resolveOperands(sizes, parser.getBuilder().getIndexType(),
515                              result.operands))
516     return failure();
517 
518   // Introduce the body region and parse it. The region has
519   // kNumConfigRegionAttributes arguments that correspond to
520   // block/thread identifiers and grid/block sizes, all of the `index` type.
521   Type index = parser.getBuilder().getIndexType();
522   SmallVector<Type, LaunchOp::kNumConfigRegionAttributes> dataTypes(
523       LaunchOp::kNumConfigRegionAttributes, index);
524   Region *body = result.addRegion();
525   return failure(parser.parseRegion(*body, regionArgs, dataTypes) ||
526                  parser.parseOptionalAttrDict(result.attributes));
527 }
528 
529 //===----------------------------------------------------------------------===//
530 // LaunchFuncOp
531 //===----------------------------------------------------------------------===//
532 
533 void LaunchFuncOp::build(OpBuilder &builder, OperationState &result,
534                          GPUFuncOp kernelFunc, KernelDim3 gridSize,
535                          KernelDim3 blockSize, ValueRange kernelOperands) {
536   // Add grid and block sizes as op operands, followed by the data operands.
537   result.addOperands({gridSize.x, gridSize.y, gridSize.z, blockSize.x,
538                       blockSize.y, blockSize.z});
539   result.addOperands(kernelOperands);
540   auto kernelModule = kernelFunc->getParentOfType<GPUModuleOp>();
541   auto kernelSymbol = builder.getSymbolRefAttr(
542       kernelModule.getName(), {builder.getSymbolRefAttr(kernelFunc.getName())});
543   result.addAttribute(getKernelAttrName(), kernelSymbol);
544   SmallVector<int32_t, 8> segmentSizes(8, 1);
545   segmentSizes.front() = 0; // Initially no async dependencies.
546   segmentSizes.back() = static_cast<int32_t>(kernelOperands.size());
547   result.addAttribute(getOperandSegmentSizeAttr(),
548                       builder.getI32VectorAttr(segmentSizes));
549 }
550 
551 unsigned LaunchFuncOp::getNumKernelOperands() {
552   return getNumOperands() - asyncDependencies().size() - kNumConfigOperands;
553 }
554 
555 StringRef LaunchFuncOp::getKernelModuleName() {
556   return kernel().getRootReference();
557 }
558 
559 StringRef LaunchFuncOp::getKernelName() { return kernel().getLeafReference(); }
560 
561 Value LaunchFuncOp::getKernelOperand(unsigned i) {
562   return getOperand(asyncDependencies().size() + kNumConfigOperands + i);
563 }
564 
565 KernelDim3 LaunchFuncOp::getGridSizeOperandValues() {
566   auto operands = getOperands().drop_front(asyncDependencies().size());
567   return KernelDim3{operands[0], operands[1], operands[2]};
568 }
569 
570 KernelDim3 LaunchFuncOp::getBlockSizeOperandValues() {
571   auto operands = getOperands().drop_front(asyncDependencies().size());
572   return KernelDim3{operands[3], operands[4], operands[5]};
573 }
574 
575 static LogicalResult verify(LaunchFuncOp op) {
576   auto module = op->getParentOfType<ModuleOp>();
577   if (!module)
578     return op.emitOpError("expected to belong to a module");
579 
580   if (!module->getAttrOfType<UnitAttr>(
581           GPUDialect::getContainerModuleAttrName()))
582     return op.emitOpError(
583         "expected the closest surrounding module to have the '" +
584         GPUDialect::getContainerModuleAttrName() + "' attribute");
585 
586   auto kernelAttr = op->getAttrOfType<SymbolRefAttr>(op.getKernelAttrName());
587   if (!kernelAttr)
588     return op.emitOpError("symbol reference attribute '" +
589                           op.getKernelAttrName() + "' must be specified");
590 
591   return success();
592 }
593 
594 static ParseResult
595 parseLaunchFuncOperands(OpAsmParser &parser,
596                         SmallVectorImpl<OpAsmParser::OperandType> &argNames,
597                         SmallVectorImpl<Type> &argTypes) {
598   if (parser.parseOptionalKeyword("args"))
599     return success();
600   SmallVector<NamedAttrList, 4> argAttrs;
601   bool isVariadic = false;
602   return function_like_impl::parseFunctionArgumentList(
603       parser, /*allowAttributes=*/false,
604       /*allowVariadic=*/false, argNames, argTypes, argAttrs, isVariadic);
605 }
606 
607 static void printLaunchFuncOperands(OpAsmPrinter &printer, Operation *,
608                                     OperandRange operands, TypeRange types) {
609   if (operands.empty())
610     return;
611   printer << "args(";
612   llvm::interleaveComma(llvm::zip(operands, types), printer,
613                         [&](const auto &pair) {
614                           printer.printOperand(std::get<0>(pair));
615                           printer << " : ";
616                           printer.printType(std::get<1>(pair));
617                         });
618   printer << ")";
619 }
620 
621 //===----------------------------------------------------------------------===//
622 // GPUFuncOp
623 //===----------------------------------------------------------------------===//
624 
625 /// Adds a new block argument that corresponds to buffers located in
626 /// workgroup memory.
627 BlockArgument GPUFuncOp::addWorkgroupAttribution(Type type) {
628   auto attrName = getNumWorkgroupAttributionsAttrName();
629   auto attr = (*this)->getAttrOfType<IntegerAttr>(attrName);
630   (*this)->setAttr(attrName,
631                    IntegerAttr::get(attr.getType(), attr.getValue() + 1));
632   return getBody().insertArgument(getType().getNumInputs() + attr.getInt(),
633                                   type);
634 }
635 
636 /// Adds a new block argument that corresponds to buffers located in
637 /// private memory.
638 BlockArgument GPUFuncOp::addPrivateAttribution(Type type) {
639   // Buffers on the private memory always come after buffers on the workgroup
640   // memory.
641   return getBody().addArgument(type);
642 }
643 
644 void GPUFuncOp::build(OpBuilder &builder, OperationState &result,
645                       StringRef name, FunctionType type,
646                       TypeRange workgroupAttributions,
647                       TypeRange privateAttributions,
648                       ArrayRef<NamedAttribute> attrs) {
649   result.addAttribute(SymbolTable::getSymbolAttrName(),
650                       builder.getStringAttr(name));
651   result.addAttribute(getTypeAttrName(), TypeAttr::get(type));
652   result.addAttribute(getNumWorkgroupAttributionsAttrName(),
653                       builder.getI64IntegerAttr(workgroupAttributions.size()));
654   result.addAttributes(attrs);
655   Region *body = result.addRegion();
656   Block *entryBlock = new Block;
657   entryBlock->addArguments(type.getInputs());
658   entryBlock->addArguments(workgroupAttributions);
659   entryBlock->addArguments(privateAttributions);
660 
661   body->getBlocks().push_back(entryBlock);
662 }
663 
664 /// Parses a GPU function memory attribution.
665 ///
666 /// memory-attribution ::= (`workgroup` `(` ssa-id-and-type-list `)`)?
667 ///                        (`private` `(` ssa-id-and-type-list `)`)?
668 ///
669 /// Note that this function parses only one of the two similar parts, with the
670 /// keyword provided as argument.
671 static ParseResult
672 parseAttributions(OpAsmParser &parser, StringRef keyword,
673                   SmallVectorImpl<OpAsmParser::OperandType> &args,
674                   SmallVectorImpl<Type> &argTypes) {
675   // If we could not parse the keyword, just assume empty list and succeed.
676   if (failed(parser.parseOptionalKeyword(keyword)))
677     return success();
678 
679   if (failed(parser.parseLParen()))
680     return failure();
681 
682   // Early exit for an empty list.
683   if (succeeded(parser.parseOptionalRParen()))
684     return success();
685 
686   do {
687     OpAsmParser::OperandType arg;
688     Type type;
689 
690     if (parser.parseRegionArgument(arg) || parser.parseColonType(type))
691       return failure();
692 
693     args.push_back(arg);
694     argTypes.push_back(type);
695   } while (succeeded(parser.parseOptionalComma()));
696 
697   return parser.parseRParen();
698 }
699 
700 /// Parses a GPU function.
701 ///
702 /// <operation> ::= `gpu.func` symbol-ref-id `(` argument-list `)`
703 ///                 (`->` function-result-list)? memory-attribution `kernel`?
704 ///                 function-attributes? region
705 static ParseResult parseGPUFuncOp(OpAsmParser &parser, OperationState &result) {
706   SmallVector<OpAsmParser::OperandType, 8> entryArgs;
707   SmallVector<NamedAttrList, 1> argAttrs;
708   SmallVector<NamedAttrList, 1> resultAttrs;
709   SmallVector<Type, 8> argTypes;
710   SmallVector<Type, 4> resultTypes;
711   bool isVariadic;
712 
713   // Parse the function name.
714   StringAttr nameAttr;
715   if (parser.parseSymbolName(nameAttr, ::mlir::SymbolTable::getSymbolAttrName(),
716                              result.attributes))
717     return failure();
718 
719   auto signatureLocation = parser.getCurrentLocation();
720   if (failed(function_like_impl::parseFunctionSignature(
721           parser, /*allowVariadic=*/false, entryArgs, argTypes, argAttrs,
722           isVariadic, resultTypes, resultAttrs)))
723     return failure();
724 
725   if (entryArgs.empty() && !argTypes.empty())
726     return parser.emitError(signatureLocation)
727            << "gpu.func requires named arguments";
728 
729   // Construct the function type. More types will be added to the region, but
730   // not to the function type.
731   Builder &builder = parser.getBuilder();
732   auto type = builder.getFunctionType(argTypes, resultTypes);
733   result.addAttribute(GPUFuncOp::getTypeAttrName(), TypeAttr::get(type));
734 
735   // Parse workgroup memory attributions.
736   if (failed(parseAttributions(parser, GPUFuncOp::getWorkgroupKeyword(),
737                                entryArgs, argTypes)))
738     return failure();
739 
740   // Store the number of operands we just parsed as the number of workgroup
741   // memory attributions.
742   unsigned numWorkgroupAttrs = argTypes.size() - type.getNumInputs();
743   result.addAttribute(GPUFuncOp::getNumWorkgroupAttributionsAttrName(),
744                       builder.getI64IntegerAttr(numWorkgroupAttrs));
745 
746   // Parse private memory attributions.
747   if (failed(parseAttributions(parser, GPUFuncOp::getPrivateKeyword(),
748                                entryArgs, argTypes)))
749     return failure();
750 
751   // Parse the kernel attribute if present.
752   if (succeeded(parser.parseOptionalKeyword(GPUFuncOp::getKernelKeyword())))
753     result.addAttribute(GPUDialect::getKernelFuncAttrName(),
754                         builder.getUnitAttr());
755 
756   // Parse attributes.
757   if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
758     return failure();
759   function_like_impl::addArgAndResultAttrs(builder, result, argAttrs,
760                                            resultAttrs);
761 
762   // Parse the region. If no argument names were provided, take all names
763   // (including those of attributions) from the entry block.
764   auto *body = result.addRegion();
765   return parser.parseRegion(*body, entryArgs, argTypes);
766 }
767 
768 static void printAttributions(OpAsmPrinter &p, StringRef keyword,
769                               ArrayRef<BlockArgument> values) {
770   if (values.empty())
771     return;
772 
773   p << ' ' << keyword << '(';
774   llvm::interleaveComma(
775       values, p, [&p](BlockArgument v) { p << v << " : " << v.getType(); });
776   p << ')';
777 }
778 
779 /// Prints a GPU Func op.
780 static void printGPUFuncOp(OpAsmPrinter &p, GPUFuncOp op) {
781   p << GPUFuncOp::getOperationName() << ' ';
782   p.printSymbolName(op.getName());
783 
784   FunctionType type = op.getType();
785   function_like_impl::printFunctionSignature(
786       p, op.getOperation(), type.getInputs(),
787       /*isVariadic=*/false, type.getResults());
788 
789   printAttributions(p, op.getWorkgroupKeyword(), op.getWorkgroupAttributions());
790   printAttributions(p, op.getPrivateKeyword(), op.getPrivateAttributions());
791   if (op.isKernel())
792     p << ' ' << op.getKernelKeyword();
793 
794   function_like_impl::printFunctionAttributes(
795       p, op.getOperation(), type.getNumInputs(), type.getNumResults(),
796       {op.getNumWorkgroupAttributionsAttrName(),
797        GPUDialect::getKernelFuncAttrName()});
798   p.printRegion(op.getBody(), /*printEntryBlockArgs=*/false);
799 }
800 
801 /// Hook for FunctionLike verifier.
802 LogicalResult GPUFuncOp::verifyType() {
803   Type type = getTypeAttr().getValue();
804   if (!type.isa<FunctionType>())
805     return emitOpError("requires '" + getTypeAttrName() +
806                        "' attribute of function type");
807 
808   if (isKernel() && getType().getNumResults() != 0)
809     return emitOpError() << "expected void return type for kernel function";
810 
811   return success();
812 }
813 
814 static LogicalResult verifyAttributions(Operation *op,
815                                         ArrayRef<BlockArgument> attributions,
816                                         unsigned memorySpace) {
817   for (Value v : attributions) {
818     auto type = v.getType().dyn_cast<MemRefType>();
819     if (!type)
820       return op->emitOpError() << "expected memref type in attribution";
821 
822     if (type.getMemorySpaceAsInt() != memorySpace) {
823       return op->emitOpError()
824              << "expected memory space " << memorySpace << " in attribution";
825     }
826   }
827   return success();
828 }
829 
830 /// Verifies the body of the function.
831 LogicalResult GPUFuncOp::verifyBody() {
832   unsigned numFuncArguments = getNumArguments();
833   unsigned numWorkgroupAttributions = getNumWorkgroupAttributions();
834   unsigned numBlockArguments = front().getNumArguments();
835   if (numBlockArguments < numFuncArguments + numWorkgroupAttributions)
836     return emitOpError() << "expected at least "
837                          << numFuncArguments + numWorkgroupAttributions
838                          << " arguments to body region";
839 
840   ArrayRef<Type> funcArgTypes = getType().getInputs();
841   for (unsigned i = 0; i < numFuncArguments; ++i) {
842     Type blockArgType = front().getArgument(i).getType();
843     if (funcArgTypes[i] != blockArgType)
844       return emitOpError() << "expected body region argument #" << i
845                            << " to be of type " << funcArgTypes[i] << ", got "
846                            << blockArgType;
847   }
848 
849   if (failed(verifyAttributions(getOperation(), getWorkgroupAttributions(),
850                                 GPUDialect::getWorkgroupAddressSpace())) ||
851       failed(verifyAttributions(getOperation(), getPrivateAttributions(),
852                                 GPUDialect::getPrivateAddressSpace())))
853     return failure();
854 
855   return success();
856 }
857 
858 //===----------------------------------------------------------------------===//
859 // ReturnOp
860 //===----------------------------------------------------------------------===//
861 
862 static ParseResult parseReturnOp(OpAsmParser &parser, OperationState &result) {
863   llvm::SmallVector<OpAsmParser::OperandType, 4> operands;
864   llvm::SmallVector<Type, 4> types;
865   if (parser.parseOperandList(operands) ||
866       parser.parseOptionalColonTypeList(types) ||
867       parser.resolveOperands(operands, types, parser.getCurrentLocation(),
868                              result.operands))
869     return failure();
870 
871   return success();
872 }
873 
874 static LogicalResult verify(gpu::ReturnOp returnOp) {
875   GPUFuncOp function = returnOp->getParentOfType<GPUFuncOp>();
876 
877   FunctionType funType = function.getType();
878 
879   if (funType.getNumResults() != returnOp.operands().size())
880     return returnOp.emitOpError()
881         .append("expected ", funType.getNumResults(), " result operands")
882         .attachNote(function.getLoc())
883         .append("return type declared here");
884 
885   for (auto pair : llvm::enumerate(
886            llvm::zip(function.getType().getResults(), returnOp.operands()))) {
887     Type type;
888     Value operand;
889     std::tie(type, operand) = pair.value();
890     if (type != operand.getType())
891       return returnOp.emitOpError() << "unexpected type `" << operand.getType()
892                                     << "' for operand #" << pair.index();
893   }
894   return success();
895 }
896 
897 //===----------------------------------------------------------------------===//
898 // GPUModuleOp
899 //===----------------------------------------------------------------------===//
900 
901 void GPUModuleOp::build(OpBuilder &builder, OperationState &result,
902                         StringRef name) {
903   ensureTerminator(*result.addRegion(), builder, result.location);
904   result.attributes.push_back(builder.getNamedAttr(
905       ::mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(name)));
906 }
907 
908 static ParseResult parseGPUModuleOp(OpAsmParser &parser,
909                                     OperationState &result) {
910   StringAttr nameAttr;
911   if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
912                              result.attributes))
913     return failure();
914 
915   // If module attributes are present, parse them.
916   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
917     return failure();
918 
919   // Parse the module body.
920   auto *body = result.addRegion();
921   if (parser.parseRegion(*body, None, None))
922     return failure();
923 
924   // Ensure that this module has a valid terminator.
925   GPUModuleOp::ensureTerminator(*body, parser.getBuilder(), result.location);
926   return success();
927 }
928 
929 static void print(OpAsmPrinter &p, GPUModuleOp op) {
930   p << op.getOperationName() << ' ';
931   p.printSymbolName(op.getName());
932   p.printOptionalAttrDictWithKeyword(op->getAttrs(),
933                                      {SymbolTable::getSymbolAttrName()});
934   p.printRegion(op->getRegion(0), /*printEntryBlockArgs=*/false,
935                 /*printBlockTerminators=*/false);
936 }
937 
938 //===----------------------------------------------------------------------===//
939 // GPUMemcpyOp
940 //===----------------------------------------------------------------------===//
941 
942 static LogicalResult verify(MemcpyOp op) {
943   auto srcType = op.src().getType();
944   auto dstType = op.dst().getType();
945 
946   if (getElementTypeOrSelf(srcType) != getElementTypeOrSelf(dstType))
947     return op.emitOpError("arguments have incompatible element type");
948 
949   if (failed(verifyCompatibleShape(srcType, dstType)))
950     return op.emitOpError("arguments have incompatible shape");
951 
952   return success();
953 }
954 
955 static ParseResult parseAsyncDependencies(
956     OpAsmParser &parser, Type &asyncTokenType,
957     SmallVectorImpl<OpAsmParser::OperandType> &asyncDependencies) {
958   auto loc = parser.getCurrentLocation();
959   if (succeeded(parser.parseOptionalKeyword("async"))) {
960     if (parser.getNumResults() == 0)
961       return parser.emitError(loc, "needs to be named when marked 'async'");
962     asyncTokenType = parser.getBuilder().getType<AsyncTokenType>();
963   }
964   return parser.parseOperandList(asyncDependencies,
965                                  OpAsmParser::Delimiter::OptionalSquare);
966 }
967 
968 static void printAsyncDependencies(OpAsmPrinter &printer, Operation *op,
969                                    Type asyncTokenType,
970                                    OperandRange asyncDependencies) {
971   if (asyncTokenType)
972     printer << "async ";
973   if (asyncDependencies.empty())
974     return;
975   printer << "[";
976   llvm::interleaveComma(asyncDependencies, printer);
977   printer << "]";
978 }
979 
980 //===----------------------------------------------------------------------===//
981 // GPU_SubgroupMmaLoadMatrixOp
982 //===----------------------------------------------------------------------===//
983 
984 static LogicalResult verify(SubgroupMmaLoadMatrixOp op) {
985   auto srcType = op.srcMemref().getType();
986   auto resType = op.res().getType();
987   auto resMatrixType = resType.cast<gpu::MMAMatrixType>();
988   auto operand = resMatrixType.getOperand();
989   auto srcMemrefType = srcType.cast<MemRefType>();
990   auto srcMemSpace = srcMemrefType.getMemorySpaceAsInt();
991 
992   if (!srcMemrefType.getAffineMaps().empty() &&
993       !srcMemrefType.getAffineMaps().front().isIdentity())
994     return op.emitError("expected identity layout map for source memref");
995 
996   if (srcMemSpace != kGenericMemorySpace && srcMemSpace != kSharedMemorySpace &&
997       srcMemSpace != kGlobalMemorySpace)
998     return op.emitError(
999         "source memorySpace kGenericMemorySpace, kSharedMemorySpace or "
1000         "kGlobalMemorySpace only allowed");
1001 
1002   if (!operand.equals("AOp") && !operand.equals("BOp") &&
1003       !operand.equals("COp"))
1004     return op.emitError("only AOp, BOp and COp can be loaded");
1005 
1006   return success();
1007 }
1008 
1009 //===----------------------------------------------------------------------===//
1010 // GPU_SubgroupMmaStoreMatrixOp
1011 //===----------------------------------------------------------------------===//
1012 
1013 static LogicalResult verify(SubgroupMmaStoreMatrixOp op) {
1014   auto srcType = op.src().getType();
1015   auto dstType = op.dstMemref().getType();
1016   auto srcMatrixType = srcType.cast<gpu::MMAMatrixType>();
1017   auto dstMemrefType = dstType.cast<MemRefType>();
1018   auto dstMemSpace = dstMemrefType.getMemorySpaceAsInt();
1019 
1020   if (!dstMemrefType.getAffineMaps().empty() &&
1021       !dstMemrefType.getAffineMaps().front().isIdentity())
1022     return op.emitError("expected identity layout map for destination memref");
1023 
1024   if (dstMemSpace != kGenericMemorySpace && dstMemSpace != kSharedMemorySpace &&
1025       dstMemSpace != kGlobalMemorySpace)
1026     return op.emitError(
1027         "destination memorySpace of kGenericMemorySpace, "
1028         "kGlobalMemorySpace or kSharedMemorySpace only allowed");
1029 
1030   if (!srcMatrixType.getOperand().equals("COp"))
1031     return op.emitError(
1032         "expected the operand matrix being stored to have 'COp' operand type");
1033 
1034   return success();
1035 }
1036 
1037 //===----------------------------------------------------------------------===//
1038 // GPU_SubgroupMmaComputeOp
1039 //===----------------------------------------------------------------------===//
1040 
1041 static LogicalResult verify(SubgroupMmaComputeOp op) {
1042   enum OperandMap { A, B, C };
1043   SmallVector<MMAMatrixType, 3> opTypes;
1044 
1045   auto populateOpInfo = [&opTypes, &op]() {
1046     opTypes.push_back(op.opA().getType().cast<MMAMatrixType>());
1047     opTypes.push_back(op.opB().getType().cast<MMAMatrixType>());
1048     opTypes.push_back(op.opC().getType().cast<MMAMatrixType>());
1049   };
1050   populateOpInfo();
1051 
1052   if (!opTypes[A].getOperand().equals("AOp") ||
1053       !opTypes[B].getOperand().equals("BOp") ||
1054       !opTypes[C].getOperand().equals("COp"))
1055     return op.emitError("operands must be in the order AOp, BOp, COp");
1056 
1057   ArrayRef<int64_t> aShape, bShape, cShape;
1058   aShape = opTypes[A].getShape();
1059   bShape = opTypes[B].getShape();
1060   cShape = opTypes[C].getShape();
1061 
1062   if (aShape[1] != bShape[0] || aShape[0] != cShape[0] ||
1063       bShape[1] != cShape[1])
1064     return op.emitError("operand shapes do not satisfy matmul constraints");
1065 
1066   return success();
1067 }
1068 
1069 #include "mlir/Dialect/GPU/GPUOpInterfaces.cpp.inc"
1070 
1071 #define GET_OP_CLASSES
1072 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
1073