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") && !operand.equals("DOp"))
68     return emitError() << "operand expected to be one of AOp, BOp, COp or DOp";
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 impl::parseFunctionArgumentList(parser, /*allowAttributes=*/false,
603                                          /*allowVariadic=*/false, argNames,
604                                          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(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   mlir::impl::addArgAndResultAttrs(builder, result, argAttrs, resultAttrs);
760 
761   // Parse the region. If no argument names were provided, take all names
762   // (including those of attributions) from the entry block.
763   auto *body = result.addRegion();
764   return parser.parseRegion(*body, entryArgs, argTypes);
765 }
766 
767 static void printAttributions(OpAsmPrinter &p, StringRef keyword,
768                               ArrayRef<BlockArgument> values) {
769   if (values.empty())
770     return;
771 
772   p << ' ' << keyword << '(';
773   llvm::interleaveComma(
774       values, p, [&p](BlockArgument v) { p << v << " : " << v.getType(); });
775   p << ')';
776 }
777 
778 /// Prints a GPU Func op.
779 static void printGPUFuncOp(OpAsmPrinter &p, GPUFuncOp op) {
780   p << GPUFuncOp::getOperationName() << ' ';
781   p.printSymbolName(op.getName());
782 
783   FunctionType type = op.getType();
784   impl::printFunctionSignature(p, op.getOperation(), type.getInputs(),
785                                /*isVariadic=*/false, type.getResults());
786 
787   printAttributions(p, op.getWorkgroupKeyword(), op.getWorkgroupAttributions());
788   printAttributions(p, op.getPrivateKeyword(), op.getPrivateAttributions());
789   if (op.isKernel())
790     p << ' ' << op.getKernelKeyword();
791 
792   impl::printFunctionAttributes(p, op.getOperation(), type.getNumInputs(),
793                                 type.getNumResults(),
794                                 {op.getNumWorkgroupAttributionsAttrName(),
795                                  GPUDialect::getKernelFuncAttrName()});
796   p.printRegion(op.getBody(), /*printEntryBlockArgs=*/false);
797 }
798 
799 void GPUFuncOp::setType(FunctionType newType) {
800   auto oldType = getType();
801   assert(newType.getNumResults() == oldType.getNumResults() &&
802          "unimplemented: changes to the number of results");
803 
804   SmallVector<char, 16> nameBuf;
805   for (int i = newType.getNumInputs(), e = oldType.getNumInputs(); i < e; i++)
806     (*this)->removeAttr(getArgAttrName(i, nameBuf));
807 
808   (*this)->setAttr(getTypeAttrName(), TypeAttr::get(newType));
809 }
810 
811 /// Hook for FunctionLike verifier.
812 LogicalResult GPUFuncOp::verifyType() {
813   Type type = getTypeAttr().getValue();
814   if (!type.isa<FunctionType>())
815     return emitOpError("requires '" + getTypeAttrName() +
816                        "' attribute of function type");
817 
818   if (isKernel() && getType().getNumResults() != 0)
819     return emitOpError() << "expected void return type for kernel function";
820 
821   return success();
822 }
823 
824 static LogicalResult verifyAttributions(Operation *op,
825                                         ArrayRef<BlockArgument> attributions,
826                                         unsigned memorySpace) {
827   for (Value v : attributions) {
828     auto type = v.getType().dyn_cast<MemRefType>();
829     if (!type)
830       return op->emitOpError() << "expected memref type in attribution";
831 
832     if (type.getMemorySpaceAsInt() != memorySpace) {
833       return op->emitOpError()
834              << "expected memory space " << memorySpace << " in attribution";
835     }
836   }
837   return success();
838 }
839 
840 /// Verifies the body of the function.
841 LogicalResult GPUFuncOp::verifyBody() {
842   unsigned numFuncArguments = getNumArguments();
843   unsigned numWorkgroupAttributions = getNumWorkgroupAttributions();
844   unsigned numBlockArguments = front().getNumArguments();
845   if (numBlockArguments < numFuncArguments + numWorkgroupAttributions)
846     return emitOpError() << "expected at least "
847                          << numFuncArguments + numWorkgroupAttributions
848                          << " arguments to body region";
849 
850   ArrayRef<Type> funcArgTypes = getType().getInputs();
851   for (unsigned i = 0; i < numFuncArguments; ++i) {
852     Type blockArgType = front().getArgument(i).getType();
853     if (funcArgTypes[i] != blockArgType)
854       return emitOpError() << "expected body region argument #" << i
855                            << " to be of type " << funcArgTypes[i] << ", got "
856                            << blockArgType;
857   }
858 
859   if (failed(verifyAttributions(getOperation(), getWorkgroupAttributions(),
860                                 GPUDialect::getWorkgroupAddressSpace())) ||
861       failed(verifyAttributions(getOperation(), getPrivateAttributions(),
862                                 GPUDialect::getPrivateAddressSpace())))
863     return failure();
864 
865   return success();
866 }
867 
868 //===----------------------------------------------------------------------===//
869 // ReturnOp
870 //===----------------------------------------------------------------------===//
871 
872 static ParseResult parseReturnOp(OpAsmParser &parser, OperationState &result) {
873   llvm::SmallVector<OpAsmParser::OperandType, 4> operands;
874   llvm::SmallVector<Type, 4> types;
875   if (parser.parseOperandList(operands) ||
876       parser.parseOptionalColonTypeList(types) ||
877       parser.resolveOperands(operands, types, parser.getCurrentLocation(),
878                              result.operands))
879     return failure();
880 
881   return success();
882 }
883 
884 static LogicalResult verify(gpu::ReturnOp returnOp) {
885   GPUFuncOp function = returnOp->getParentOfType<GPUFuncOp>();
886 
887   FunctionType funType = function.getType();
888 
889   if (funType.getNumResults() != returnOp.operands().size())
890     return returnOp.emitOpError()
891         .append("expected ", funType.getNumResults(), " result operands")
892         .attachNote(function.getLoc())
893         .append("return type declared here");
894 
895   for (auto pair : llvm::enumerate(
896            llvm::zip(function.getType().getResults(), returnOp.operands()))) {
897     Type type;
898     Value operand;
899     std::tie(type, operand) = pair.value();
900     if (type != operand.getType())
901       return returnOp.emitOpError() << "unexpected type `" << operand.getType()
902                                     << "' for operand #" << pair.index();
903   }
904   return success();
905 }
906 
907 //===----------------------------------------------------------------------===//
908 // GPUModuleOp
909 //===----------------------------------------------------------------------===//
910 
911 void GPUModuleOp::build(OpBuilder &builder, OperationState &result,
912                         StringRef name) {
913   ensureTerminator(*result.addRegion(), builder, result.location);
914   result.attributes.push_back(builder.getNamedAttr(
915       ::mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(name)));
916 }
917 
918 static ParseResult parseGPUModuleOp(OpAsmParser &parser,
919                                     OperationState &result) {
920   StringAttr nameAttr;
921   if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
922                              result.attributes))
923     return failure();
924 
925   // If module attributes are present, parse them.
926   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
927     return failure();
928 
929   // Parse the module body.
930   auto *body = result.addRegion();
931   if (parser.parseRegion(*body, None, None))
932     return failure();
933 
934   // Ensure that this module has a valid terminator.
935   GPUModuleOp::ensureTerminator(*body, parser.getBuilder(), result.location);
936   return success();
937 }
938 
939 static void print(OpAsmPrinter &p, GPUModuleOp op) {
940   p << op.getOperationName() << ' ';
941   p.printSymbolName(op.getName());
942   p.printOptionalAttrDictWithKeyword(op->getAttrs(),
943                                      {SymbolTable::getSymbolAttrName()});
944   p.printRegion(op->getRegion(0), /*printEntryBlockArgs=*/false,
945                 /*printBlockTerminators=*/false);
946 }
947 
948 //===----------------------------------------------------------------------===//
949 // GPUMemcpyOp
950 //===----------------------------------------------------------------------===//
951 
952 static LogicalResult verify(MemcpyOp op) {
953   auto srcType = op.src().getType();
954   auto dstType = op.dst().getType();
955 
956   if (getElementTypeOrSelf(srcType) != getElementTypeOrSelf(dstType))
957     return op.emitOpError("arguments have incompatible element type");
958 
959   if (failed(verifyCompatibleShape(srcType, dstType)))
960     return op.emitOpError("arguments have incompatible shape");
961 
962   return success();
963 }
964 
965 static ParseResult parseAsyncDependencies(
966     OpAsmParser &parser, Type &asyncTokenType,
967     SmallVectorImpl<OpAsmParser::OperandType> &asyncDependencies) {
968   auto loc = parser.getCurrentLocation();
969   if (succeeded(parser.parseOptionalKeyword("async"))) {
970     if (parser.getNumResults() == 0)
971       return parser.emitError(loc, "needs to be named when marked 'async'");
972     asyncTokenType = parser.getBuilder().getType<AsyncTokenType>();
973   }
974   return parser.parseOperandList(asyncDependencies,
975                                  OpAsmParser::Delimiter::OptionalSquare);
976 }
977 
978 static void printAsyncDependencies(OpAsmPrinter &printer, Operation *op,
979                                    Type asyncTokenType,
980                                    OperandRange asyncDependencies) {
981   if (asyncTokenType)
982     printer << "async ";
983   if (asyncDependencies.empty())
984     return;
985   printer << "[";
986   llvm::interleaveComma(asyncDependencies, printer);
987   printer << "]";
988 }
989 
990 //===----------------------------------------------------------------------===//
991 // GPU_SubgroupMmaLoadMatrixOp
992 //===----------------------------------------------------------------------===//
993 
994 static LogicalResult verify(SubgroupMmaLoadMatrixOp op) {
995   auto srcType = op.srcMemref().getType();
996   auto resType = op.res().getType();
997   auto resMatrixType = resType.cast<gpu::MMAMatrixType>();
998   auto operand = resMatrixType.getOperand();
999   auto srcMemrefType = srcType.cast<MemRefType>();
1000   auto srcMemSpace = srcMemrefType.getMemorySpaceAsInt();
1001 
1002   if (!srcMemrefType.getAffineMaps().empty() &&
1003       !srcMemrefType.getAffineMaps().front().isIdentity())
1004     return op.emitError("expected identity layout map for source memref");
1005 
1006   if (srcMemSpace != kGenericMemorySpace && srcMemSpace != kSharedMemorySpace &&
1007       srcMemSpace != kGlobalMemorySpace)
1008     return op.emitError(
1009         "source memorySpace kGenericMemorySpace, kSharedMemorySpace or "
1010         "kGlobalMemorySpace only allowed");
1011 
1012   if (!operand.equals("AOp") && !operand.equals("BOp") &&
1013       !operand.equals("COp"))
1014     return op.emitError("only AOp, BOp and COp can be loaded");
1015 
1016   return success();
1017 }
1018 
1019 //===----------------------------------------------------------------------===//
1020 // GPU_SubgroupMmaStoreMatrixOp
1021 //===----------------------------------------------------------------------===//
1022 
1023 static LogicalResult verify(SubgroupMmaStoreMatrixOp op) {
1024   auto srcType = op.src().getType();
1025   auto dstType = op.dstMemref().getType();
1026   auto srcMatrixType = srcType.cast<gpu::MMAMatrixType>();
1027   auto dstMemrefType = dstType.cast<MemRefType>();
1028   auto dstMemSpace = dstMemrefType.getMemorySpaceAsInt();
1029 
1030   if (!dstMemrefType.getAffineMaps().empty() &&
1031       !dstMemrefType.getAffineMaps().front().isIdentity())
1032     return op.emitError("expected identity layout map for destination memref");
1033 
1034   if (dstMemSpace != kGenericMemorySpace && dstMemSpace != kSharedMemorySpace &&
1035       dstMemSpace != kGlobalMemorySpace)
1036     return op.emitError(
1037         "destination memorySpace of kGenericMemorySpace, "
1038         "kGlobalMemorySpace or kSharedMemorySpace only allowed");
1039 
1040   if (!srcMatrixType.getOperand().equals("DOp"))
1041     return op.emitError(
1042         "expected the operand matrix being stored to have 'DOp' operand type");
1043 
1044   return success();
1045 }
1046 
1047 //===----------------------------------------------------------------------===//
1048 // GPU_SubgroupMmaComputeOp
1049 //===----------------------------------------------------------------------===//
1050 
1051 static LogicalResult verify(SubgroupMmaComputeOp op) {
1052   enum OperandMap { A, B, C };
1053   SmallVector<MMAMatrixType, 3> opTypes;
1054 
1055   auto populateOpInfo = [&opTypes, &op]() {
1056     opTypes.push_back(op.opA().getType().cast<MMAMatrixType>());
1057     opTypes.push_back(op.opB().getType().cast<MMAMatrixType>());
1058     opTypes.push_back(op.opC().getType().cast<MMAMatrixType>());
1059   };
1060   populateOpInfo();
1061 
1062   if (!opTypes[A].getOperand().equals("AOp") ||
1063       !opTypes[B].getOperand().equals("BOp") ||
1064       !opTypes[C].getOperand().equals("COp"))
1065     return op.emitError("operands must be in the order AOp, BOp, COp");
1066 
1067   ArrayRef<int64_t> aShape, bShape, cShape;
1068   aShape = opTypes[A].getShape();
1069   bShape = opTypes[B].getShape();
1070   cShape = opTypes[C].getShape();
1071 
1072   if (aShape[1] != bShape[0] || aShape[0] != cShape[0] ||
1073       bShape[1] != cShape[1])
1074     return op.emitError("operand shapes do not satisfy matmul constraints");
1075 
1076   return success();
1077 }
1078 
1079 #include "mlir/Dialect/GPU/GPUOpInterfaces.cpp.inc"
1080 
1081 #define GET_OP_CLASSES
1082 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
1083