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 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
15 #include "mlir/Dialect/StandardOps/Ops.h"
16 #include "mlir/IR/Builders.h"
17 #include "mlir/IR/Function.h"
18 #include "mlir/IR/FunctionImplementation.h"
19 #include "mlir/IR/Module.h"
20 #include "mlir/IR/OpImplementation.h"
21 #include "mlir/IR/PatternMatch.h"
22 #include "mlir/IR/StandardTypes.h"
23 
24 using namespace mlir;
25 using namespace mlir::gpu;
26 
27 //===----------------------------------------------------------------------===//
28 // GPUDialect
29 //===----------------------------------------------------------------------===//
30 
31 StringRef GPUDialect::getDialectName() { return "gpu"; }
32 
33 bool GPUDialect::isKernel(Operation *op) {
34   UnitAttr isKernelAttr = op->getAttrOfType<UnitAttr>(getKernelFuncAttrName());
35   return static_cast<bool>(isKernelAttr);
36 }
37 
38 GPUDialect::GPUDialect(MLIRContext *context)
39     : Dialect(getDialectName(), context) {
40   addOperations<
41 #define GET_OP_LIST
42 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
43       >();
44 }
45 
46 LogicalResult GPUDialect::verifyOperationAttribute(Operation *op,
47                                                    NamedAttribute attr) {
48   if (!attr.second.isa<UnitAttr>() ||
49       !attr.first.is(getContainerModuleAttrName()))
50     return success();
51 
52   auto module = dyn_cast<ModuleOp>(op);
53   if (!module)
54     return op->emitError("expected '")
55            << getContainerModuleAttrName() << "' attribute to be attached to '"
56            << ModuleOp::getOperationName() << '\'';
57 
58   auto walkResult = module.walk([&module](LaunchFuncOp launchOp) -> WalkResult {
59     // Ignore launches that are nested more or less deep than functions in the
60     // module we are currently checking.
61     if (!launchOp.getParentOp() ||
62         launchOp.getParentOp()->getParentOp() != module)
63       return success();
64 
65     // Ignore launch ops with missing attributes here. The errors will be
66     // reported by the verifiers of those ops.
67     if (!launchOp.getAttrOfType<StringAttr>(
68             LaunchFuncOp::getKernelAttrName()) ||
69         !launchOp.getAttrOfType<SymbolRefAttr>(
70             LaunchFuncOp::getKernelModuleAttrName()))
71       return success();
72 
73     // Check that `launch_func` refers to a well-formed GPU kernel module.
74     StringRef kernelModuleName = launchOp.getKernelModuleName();
75     auto kernelModule = module.lookupSymbol<GPUModuleOp>(kernelModuleName);
76     if (!kernelModule)
77       return launchOp.emitOpError()
78              << "kernel module '" << kernelModuleName << "' is undefined";
79 
80     // Check that `launch_func` refers to a well-formed kernel function.
81     StringRef kernelName = launchOp.kernel();
82     Operation *kernelFunc = kernelModule.lookupSymbol(kernelName);
83     auto kernelGPUFunction = dyn_cast_or_null<gpu::GPUFuncOp>(kernelFunc);
84     auto kernelLLVMFunction = dyn_cast_or_null<LLVM::LLVMFuncOp>(kernelFunc);
85     if (!kernelGPUFunction && !kernelLLVMFunction)
86       return launchOp.emitOpError("kernel function '")
87              << kernelName << "' is undefined";
88     if (!kernelFunc->getAttrOfType<mlir::UnitAttr>(
89             GPUDialect::getKernelFuncAttrName()))
90       return launchOp.emitOpError("kernel function is missing the '")
91              << GPUDialect::getKernelFuncAttrName() << "' attribute";
92 
93     unsigned actualNumArguments = launchOp.getNumKernelOperands();
94     unsigned expectedNumArguments = kernelLLVMFunction
95                                         ? kernelLLVMFunction.getNumArguments()
96                                         : kernelGPUFunction.getNumArguments();
97     if (expectedNumArguments != actualNumArguments)
98       return launchOp.emitOpError("got ")
99              << actualNumArguments << " kernel operands but expected "
100              << expectedNumArguments;
101 
102     // Due to the ordering of the current impl of lowering and LLVMLowering,
103     // type checks need to be temporarily disabled.
104     // TODO(ntv,zinenko,herhut): reactivate checks once "changing gpu.launchFunc
105     // to encode target module" has landed.
106     // auto functionType = kernelFunc.getType();
107     // for (unsigned i = 0; i < numKernelFuncArgs; ++i) {
108     //   if (getKernelOperand(i).getType() != functionType.getInput(i)) {
109     //     return emitOpError("type of function argument ")
110     //            << i << " does not match";
111     //   }
112     // }
113 
114     return success();
115   });
116 
117   return walkResult.wasInterrupted() ? failure() : success();
118 }
119 
120 template <typename T> static LogicalResult verifyIndexOp(T op) {
121   auto dimension = op.dimension();
122   if (dimension != "x" && dimension != "y" && dimension != "z")
123     return op.emitError("dimension \"") << dimension << "\" is invalid";
124   return success();
125 }
126 
127 static LogicalResult verifyAllReduce(gpu::AllReduceOp allReduce) {
128   if (allReduce.body().empty() != allReduce.op().hasValue())
129     return allReduce.emitError(
130         "expected either an op attribute or a non-empty body");
131   if (!allReduce.body().empty()) {
132     if (allReduce.body().front().getNumArguments() != 2)
133       return allReduce.emitError("expected two region arguments");
134     for (auto argument : allReduce.body().front().getArguments()) {
135       if (argument.getType() != allReduce.getType())
136         return allReduce.emitError("incorrect region argument type");
137     }
138     unsigned yieldCount = 0;
139     for (Block &block : allReduce.body()) {
140       if (auto yield = dyn_cast<gpu::YieldOp>(block.getTerminator())) {
141         if (yield.getNumOperands() != 1)
142           return allReduce.emitError("expected one gpu.yield operand");
143         if (yield.getOperand(0).getType() != allReduce.getType())
144           return allReduce.emitError("incorrect gpu.yield type");
145         ++yieldCount;
146       }
147     }
148     if (yieldCount == 0)
149       return allReduce.emitError("expected gpu.yield op in region");
150   }
151   return success();
152 }
153 
154 static LogicalResult verifyShuffleOp(gpu::ShuffleOp shuffleOp) {
155   auto type = shuffleOp.value().getType();
156   if (shuffleOp.result().getType() != type) {
157     return shuffleOp.emitOpError()
158            << "requires the same type for value operand and result";
159   }
160   if (!type.isIntOrFloat() || type.getIntOrFloatBitWidth() != 32) {
161     return shuffleOp.emitOpError()
162            << "requires value operand type to be f32 or i32";
163   }
164   return success();
165 }
166 
167 static void printShuffleOp(OpAsmPrinter &p, ShuffleOp op) {
168   p << ShuffleOp::getOperationName() << ' ' << op.getOperands() << ' '
169     << op.mode() << " : " << op.value().getType();
170 }
171 
172 static ParseResult parseShuffleOp(OpAsmParser &parser, OperationState &state) {
173   SmallVector<OpAsmParser::OperandType, 3> operandInfo;
174   if (parser.parseOperandList(operandInfo, 3))
175     return failure();
176 
177   StringRef mode;
178   if (parser.parseKeyword(&mode))
179     return failure();
180   state.addAttribute("mode", parser.getBuilder().getStringAttr(mode));
181 
182   Type valueType;
183   Type int32Type = parser.getBuilder().getIntegerType(32);
184   Type int1Type = parser.getBuilder().getI1Type();
185   if (parser.parseColonType(valueType) ||
186       parser.resolveOperands(operandInfo, {valueType, int32Type, int32Type},
187                              parser.getCurrentLocation(), state.operands) ||
188       parser.addTypesToList({valueType, int1Type}, state.types))
189     return failure();
190   return success();
191 }
192 
193 //===----------------------------------------------------------------------===//
194 // LaunchOp
195 //===----------------------------------------------------------------------===//
196 
197 void LaunchOp::build(Builder *builder, OperationState &result, Value gridSizeX,
198                      Value gridSizeY, Value gridSizeZ, Value blockSizeX,
199                      Value blockSizeY, Value blockSizeZ) {
200   // Add grid and block sizes as op operands, followed by the data operands.
201   result.addOperands(
202       {gridSizeX, gridSizeY, gridSizeZ, blockSizeX, blockSizeY, blockSizeZ});
203 
204   // Create a kernel body region with kNumConfigRegionAttributes + N arguments,
205   // where the first kNumConfigRegionAttributes arguments have `index` type and
206   // the rest have the same types as the data operands.
207   Region *kernelRegion = result.addRegion();
208   Block *body = new Block();
209   body->addArguments(
210       std::vector<Type>(kNumConfigRegionAttributes, builder->getIndexType()));
211   kernelRegion->push_back(body);
212 }
213 
214 KernelDim3 LaunchOp::getBlockIds() {
215   assert(!body().getBlocks().empty() && "FuncOp body must not be empty.");
216   auto args = body().getBlocks().front().getArguments();
217   return KernelDim3{args[0], args[1], args[2]};
218 }
219 
220 KernelDim3 LaunchOp::getThreadIds() {
221   assert(!body().getBlocks().empty() && "FuncOp body must not be empty.");
222   auto args = body().getBlocks().front().getArguments();
223   return KernelDim3{args[3], args[4], args[5]};
224 }
225 
226 KernelDim3 LaunchOp::getGridSize() {
227   assert(!body().getBlocks().empty() && "FuncOp body must not be empty.");
228   auto args = body().getBlocks().front().getArguments();
229   return KernelDim3{args[6], args[7], args[8]};
230 }
231 
232 KernelDim3 LaunchOp::getBlockSize() {
233   assert(!body().getBlocks().empty() && "FuncOp body must not be empty.");
234   auto args = body().getBlocks().front().getArguments();
235   return KernelDim3{args[9], args[10], args[11]};
236 }
237 
238 KernelDim3 LaunchOp::getGridSizeOperandValues() {
239   return KernelDim3{getOperand(0), getOperand(1), getOperand(2)};
240 }
241 
242 KernelDim3 LaunchOp::getBlockSizeOperandValues() {
243   return KernelDim3{getOperand(3), getOperand(4), getOperand(5)};
244 }
245 
246 static LogicalResult verify(LaunchOp op) {
247   // Kernel launch takes kNumConfigOperands leading operands for grid/block
248   // sizes and transforms them into kNumConfigRegionAttributes region arguments
249   // for block/thread identifiers and grid/block sizes.
250   if (!op.body().empty()) {
251     Block &entryBlock = op.body().front();
252     if (entryBlock.getNumArguments() !=
253         LaunchOp::kNumConfigOperands + op.getNumOperands())
254       return op.emitOpError("unexpected number of region arguments");
255   }
256 
257   // Block terminators without successors are expected to exit the kernel region
258   // and must be `gpu.terminator`.
259   for (Block &block : op.body()) {
260     if (block.empty())
261       continue;
262     if (block.back().getNumSuccessors() != 0)
263       continue;
264     if (!isa<gpu::TerminatorOp>(&block.back())) {
265       return block.back()
266           .emitError()
267           .append("expected '", gpu::TerminatorOp::getOperationName(),
268                   "' or a terminator with successors")
269           .attachNote(op.getLoc())
270           .append("in '", LaunchOp::getOperationName(), "' body region");
271     }
272   }
273 
274   return success();
275 }
276 
277 // Pretty-print the kernel grid/block size assignment as
278 //   (%iter-x, %iter-y, %iter-z) in
279 //   (%size-x = %ssa-use, %size-y = %ssa-use, %size-z = %ssa-use)
280 // where %size-* and %iter-* will correspond to the body region arguments.
281 static void printSizeAssignment(OpAsmPrinter &p, KernelDim3 size,
282                                 ValueRange operands, KernelDim3 ids) {
283   p << '(' << ids.x << ", " << ids.y << ", " << ids.z << ") in (";
284   p << size.x << " = " << operands[0] << ", ";
285   p << size.y << " = " << operands[1] << ", ";
286   p << size.z << " = " << operands[2] << ')';
287 }
288 
289 static void printLaunchOp(OpAsmPrinter &p, LaunchOp op) {
290   ValueRange operands = op.getOperands();
291 
292   // Print the launch configuration.
293   p << LaunchOp::getOperationName() << ' ' << op.getBlocksKeyword();
294   printSizeAssignment(p, op.getGridSize(), operands.take_front(3),
295                       op.getBlockIds());
296   p << ' ' << op.getThreadsKeyword();
297   printSizeAssignment(p, op.getBlockSize(), operands.slice(3, 3),
298                       op.getThreadIds());
299 
300   p.printRegion(op.body(), /*printEntryBlockArgs=*/false);
301   p.printOptionalAttrDict(op.getAttrs());
302 }
303 
304 // Parse the size assignment blocks for blocks and threads.  These have the form
305 //   (%region_arg, %region_arg, %region_arg) in
306 //   (%region_arg = %operand, %region_arg = %operand, %region_arg = %operand)
307 // where %region_arg are percent-identifiers for the region arguments to be
308 // introduced further (SSA defs), and %operand are percent-identifiers for the
309 // SSA value uses.
310 static ParseResult
311 parseSizeAssignment(OpAsmParser &parser,
312                     MutableArrayRef<OpAsmParser::OperandType> sizes,
313                     MutableArrayRef<OpAsmParser::OperandType> regionSizes,
314                     MutableArrayRef<OpAsmParser::OperandType> indices) {
315   assert(indices.size() == 3 && "space for three indices expected");
316   SmallVector<OpAsmParser::OperandType, 3> args;
317   if (parser.parseRegionArgumentList(args, /*requiredOperandCount=*/3,
318                                      OpAsmParser::Delimiter::Paren) ||
319       parser.parseKeyword("in") || parser.parseLParen())
320     return failure();
321   std::move(args.begin(), args.end(), indices.begin());
322 
323   for (int i = 0; i < 3; ++i) {
324     if (i != 0 && parser.parseComma())
325       return failure();
326     if (parser.parseRegionArgument(regionSizes[i]) || parser.parseEqual() ||
327         parser.parseOperand(sizes[i]))
328       return failure();
329   }
330 
331   return parser.parseRParen();
332 }
333 
334 // Parses a Launch operation.
335 // operation ::= `gpu.launch` `blocks` `(` ssa-id-list `)` `in` ssa-reassignment
336 //                           `threads` `(` ssa-id-list `)` `in` ssa-reassignment
337 //                            region attr-dict?
338 // ssa-reassignment ::= `(` ssa-id `=` ssa-use (`,` ssa-id `=` ssa-use)* `)`
339 static ParseResult parseLaunchOp(OpAsmParser &parser, OperationState &result) {
340   // Sizes of the grid and block.
341   SmallVector<OpAsmParser::OperandType, LaunchOp::kNumConfigOperands> sizes(
342       LaunchOp::kNumConfigOperands);
343   MutableArrayRef<OpAsmParser::OperandType> sizesRef(sizes);
344 
345   // Actual (data) operands passed to the kernel.
346   SmallVector<OpAsmParser::OperandType, 4> dataOperands;
347 
348   // Region arguments to be created.
349   SmallVector<OpAsmParser::OperandType, 16> regionArgs(
350       LaunchOp::kNumConfigRegionAttributes);
351   MutableArrayRef<OpAsmParser::OperandType> regionArgsRef(regionArgs);
352 
353   // Parse the size assignment segments: the first segment assigns grid sizes
354   // and defines values for block identifiers; the second segment assigns block
355   // sizes and defines values for thread identifiers.  In the region argument
356   // list, identifiers precede sizes, and block-related values precede
357   // thread-related values.
358   if (parser.parseKeyword(LaunchOp::getBlocksKeyword().data()) ||
359       parseSizeAssignment(parser, sizesRef.take_front(3),
360                           regionArgsRef.slice(6, 3),
361                           regionArgsRef.slice(0, 3)) ||
362       parser.parseKeyword(LaunchOp::getThreadsKeyword().data()) ||
363       parseSizeAssignment(parser, sizesRef.drop_front(3),
364                           regionArgsRef.slice(9, 3),
365                           regionArgsRef.slice(3, 3)) ||
366       parser.resolveOperands(sizes, parser.getBuilder().getIndexType(),
367                              result.operands))
368     return failure();
369 
370   // Introduce the body region and parse it. The region has
371   // kNumConfigRegionAttributes arguments that correspond to
372   // block/thread identifiers and grid/block sizes, all of the `index` type.
373   Type index = parser.getBuilder().getIndexType();
374   SmallVector<Type, LaunchOp::kNumConfigRegionAttributes> dataTypes(
375       LaunchOp::kNumConfigRegionAttributes, index);
376   Region *body = result.addRegion();
377   return failure(parser.parseRegion(*body, regionArgs, dataTypes) ||
378                  parser.parseOptionalAttrDict(result.attributes));
379 }
380 
381 //===----------------------------------------------------------------------===//
382 // LaunchFuncOp
383 //===----------------------------------------------------------------------===//
384 
385 void LaunchFuncOp::build(Builder *builder, OperationState &result,
386                          GPUFuncOp kernelFunc, Value gridSizeX, Value gridSizeY,
387                          Value gridSizeZ, Value blockSizeX, Value blockSizeY,
388                          Value blockSizeZ, ValueRange kernelOperands) {
389   // Add grid and block sizes as op operands, followed by the data operands.
390   result.addOperands(
391       {gridSizeX, gridSizeY, gridSizeZ, blockSizeX, blockSizeY, blockSizeZ});
392   result.addOperands(kernelOperands);
393   result.addAttribute(getKernelAttrName(),
394                       builder->getStringAttr(kernelFunc.getName()));
395   auto kernelModule = kernelFunc.getParentOfType<GPUModuleOp>();
396   result.addAttribute(getKernelModuleAttrName(),
397                       builder->getSymbolRefAttr(kernelModule.getName()));
398 }
399 
400 void LaunchFuncOp::build(Builder *builder, OperationState &result,
401                          GPUFuncOp kernelFunc, KernelDim3 gridSize,
402                          KernelDim3 blockSize, ValueRange kernelOperands) {
403   build(builder, result, kernelFunc, gridSize.x, gridSize.y, gridSize.z,
404         blockSize.x, blockSize.y, blockSize.z, kernelOperands);
405 }
406 
407 StringRef LaunchFuncOp::kernel() {
408   return getAttrOfType<StringAttr>(getKernelAttrName()).getValue();
409 }
410 
411 unsigned LaunchFuncOp::getNumKernelOperands() {
412   return getNumOperands() - kNumConfigOperands;
413 }
414 
415 StringRef LaunchFuncOp::getKernelModuleName() {
416   return getAttrOfType<SymbolRefAttr>(getKernelModuleAttrName())
417       .getRootReference();
418 }
419 
420 Value LaunchFuncOp::getKernelOperand(unsigned i) {
421   return getOperation()->getOperand(i + kNumConfigOperands);
422 }
423 
424 KernelDim3 LaunchFuncOp::getGridSizeOperandValues() {
425   return KernelDim3{getOperand(0), getOperand(1), getOperand(2)};
426 }
427 
428 KernelDim3 LaunchFuncOp::getBlockSizeOperandValues() {
429   return KernelDim3{getOperand(3), getOperand(4), getOperand(5)};
430 }
431 
432 static LogicalResult verify(LaunchFuncOp op) {
433   auto module = op.getParentOfType<ModuleOp>();
434   if (!module)
435     return op.emitOpError("expected to belong to a module");
436 
437   if (!module.getAttrOfType<UnitAttr>(GPUDialect::getContainerModuleAttrName()))
438     return op.emitOpError(
439         "expected the closest surrounding module to have the '" +
440         GPUDialect::getContainerModuleAttrName() + "' attribute");
441 
442   auto kernelAttr = op.getAttrOfType<StringAttr>(op.getKernelAttrName());
443   if (!kernelAttr)
444     return op.emitOpError("string attribute '" + op.getKernelAttrName() +
445                           "' must be specified");
446 
447   auto kernelModuleAttr =
448       op.getAttrOfType<SymbolRefAttr>(op.getKernelModuleAttrName());
449   if (!kernelModuleAttr)
450     return op.emitOpError("symbol reference attribute '" +
451                           op.getKernelModuleAttrName() + "' must be specified");
452 
453   return success();
454 }
455 
456 //===----------------------------------------------------------------------===//
457 // GPUFuncOp
458 //===----------------------------------------------------------------------===//
459 
460 /// Adds a workgroup attribution to "op" of the MemRef type with the given shape
461 /// and element type.
462 Value GPUFuncOp::addWorkgroupAttribution(ArrayRef<int64_t> shape,
463                                          Type elementType) {
464   unsigned pos = getNumFuncArguments() + getNumWorkgroupAttributions();
465   Block &bodyBlock = body().front();
466   Value attribution = bodyBlock.insertArgument(
467       std::next(bodyBlock.args_begin(), pos),
468       MemRefType::get(shape, elementType, /*affineMapComposition=*/{},
469                       GPUDialect::getWorkgroupAddressSpace()));
470   auto numWorkgroupBuffersAttr =
471       getAttrOfType<IntegerAttr>(getNumWorkgroupAttributionsAttrName());
472   setAttr(getNumWorkgroupAttributionsAttrName(),
473           IntegerAttr::get(numWorkgroupBuffersAttr.getType(),
474                            numWorkgroupBuffersAttr.getValue() + 1));
475   return attribution;
476 }
477 
478 void GPUFuncOp::build(Builder *builder, OperationState &result, StringRef name,
479                       FunctionType type, ArrayRef<Type> workgroupAttributions,
480                       ArrayRef<Type> privateAttributions,
481                       ArrayRef<NamedAttribute> attrs) {
482   result.addAttribute(SymbolTable::getSymbolAttrName(),
483                       builder->getStringAttr(name));
484   result.addAttribute(getTypeAttrName(), TypeAttr::get(type));
485   result.addAttribute(getNumWorkgroupAttributionsAttrName(),
486                       builder->getI64IntegerAttr(workgroupAttributions.size()));
487   result.addAttributes(attrs);
488   Region *body = result.addRegion();
489   Block *entryBlock = new Block;
490   entryBlock->addArguments(type.getInputs());
491   entryBlock->addArguments(workgroupAttributions);
492   entryBlock->addArguments(privateAttributions);
493 
494   body->getBlocks().push_back(entryBlock);
495 }
496 
497 /// Parses a GPU function memory attribution.
498 ///
499 /// memory-attribution ::= (`workgroup` `(` ssa-id-and-type-list `)`)?
500 ///                        (`private` `(` ssa-id-and-type-list `)`)?
501 ///
502 /// Note that this function parses only one of the two similar parts, with the
503 /// keyword provided as argument.
504 static ParseResult
505 parseAttributions(OpAsmParser &parser, StringRef keyword,
506                   SmallVectorImpl<OpAsmParser::OperandType> &args,
507                   SmallVectorImpl<Type> &argTypes) {
508   // If we could not parse the keyword, just assume empty list and succeed.
509   if (failed(parser.parseOptionalKeyword(keyword)))
510     return success();
511 
512   if (failed(parser.parseLParen()))
513     return failure();
514 
515   // Early exit for an empty list.
516   if (succeeded(parser.parseOptionalRParen()))
517     return success();
518 
519   do {
520     OpAsmParser::OperandType arg;
521     Type type;
522 
523     if (parser.parseRegionArgument(arg) || parser.parseColonType(type))
524       return failure();
525 
526     args.push_back(arg);
527     argTypes.push_back(type);
528   } while (succeeded(parser.parseOptionalComma()));
529 
530   return parser.parseRParen();
531 }
532 
533 /// Parses a GPU function.
534 ///
535 /// <operation> ::= `gpu.func` symbol-ref-id `(` argument-list `)`
536 ///                 (`->` function-result-list)? memory-attribution `kernel`?
537 ///                 function-attributes? region
538 static ParseResult parseGPUFuncOp(OpAsmParser &parser, OperationState &result) {
539   SmallVector<OpAsmParser::OperandType, 8> entryArgs;
540   SmallVector<SmallVector<NamedAttribute, 2>, 1> argAttrs;
541   SmallVector<SmallVector<NamedAttribute, 2>, 1> resultAttrs;
542   SmallVector<Type, 8> argTypes;
543   SmallVector<Type, 4> resultTypes;
544   bool isVariadic;
545 
546   // Parse the function name.
547   StringAttr nameAttr;
548   if (parser.parseSymbolName(nameAttr, ::mlir::SymbolTable::getSymbolAttrName(),
549                              result.attributes))
550     return failure();
551 
552   auto signatureLocation = parser.getCurrentLocation();
553   if (failed(impl::parseFunctionSignature(
554           parser, /*allowVariadic=*/false, entryArgs, argTypes, argAttrs,
555           isVariadic, resultTypes, resultAttrs)))
556     return failure();
557 
558   if (entryArgs.empty() && !argTypes.empty())
559     return parser.emitError(signatureLocation)
560            << "gpu.func requires named arguments";
561 
562   // Construct the function type. More types will be added to the region, but
563   // not to the function type.
564   Builder &builder = parser.getBuilder();
565   auto type = builder.getFunctionType(argTypes, resultTypes);
566   result.addAttribute(GPUFuncOp::getTypeAttrName(), TypeAttr::get(type));
567 
568   // Parse workgroup memory attributions.
569   if (failed(parseAttributions(parser, GPUFuncOp::getWorkgroupKeyword(),
570                                entryArgs, argTypes)))
571     return failure();
572 
573   // Store the number of operands we just parsed as the number of workgroup
574   // memory attributions.
575   unsigned numWorkgroupAttrs = argTypes.size() - type.getNumInputs();
576   result.addAttribute(GPUFuncOp::getNumWorkgroupAttributionsAttrName(),
577                       builder.getI64IntegerAttr(numWorkgroupAttrs));
578 
579   // Parse private memory attributions.
580   if (failed(parseAttributions(parser, GPUFuncOp::getPrivateKeyword(),
581                                entryArgs, argTypes)))
582     return failure();
583 
584   // Parse the kernel attribute if present.
585   if (succeeded(parser.parseOptionalKeyword(GPUFuncOp::getKernelKeyword())))
586     result.addAttribute(GPUDialect::getKernelFuncAttrName(),
587                         builder.getUnitAttr());
588 
589   // Parse attributes.
590   if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
591     return failure();
592   mlir::impl::addArgAndResultAttrs(builder, result, argAttrs, resultAttrs);
593 
594   // Parse the region. If no argument names were provided, take all names
595   // (including those of attributions) from the entry block.
596   auto *body = result.addRegion();
597   return parser.parseRegion(*body, entryArgs, argTypes);
598 }
599 
600 static void printAttributions(OpAsmPrinter &p, StringRef keyword,
601                               ArrayRef<BlockArgument> values) {
602   if (values.empty())
603     return;
604 
605   p << ' ' << keyword << '(';
606   interleaveComma(values, p,
607                   [&p](BlockArgument v) { p << v << " : " << v.getType(); });
608   p << ')';
609 }
610 
611 /// Prints a GPU Func op.
612 static void printGPUFuncOp(OpAsmPrinter &p, GPUFuncOp op) {
613   p << GPUFuncOp::getOperationName() << ' ';
614   p.printSymbolName(op.getName());
615 
616   FunctionType type = op.getType();
617   impl::printFunctionSignature(p, op.getOperation(), type.getInputs(),
618                                /*isVariadic=*/false, type.getResults());
619 
620   printAttributions(p, op.getWorkgroupKeyword(), op.getWorkgroupAttributions());
621   printAttributions(p, op.getPrivateKeyword(), op.getPrivateAttributions());
622   if (op.isKernel())
623     p << ' ' << op.getKernelKeyword();
624 
625   impl::printFunctionAttributes(p, op.getOperation(), type.getNumInputs(),
626                                 type.getNumResults(),
627                                 {op.getNumWorkgroupAttributionsAttrName(),
628                                  GPUDialect::getKernelFuncAttrName()});
629   p.printRegion(op.getBody(), /*printEntryBlockArgs=*/false);
630 }
631 
632 void GPUFuncOp::setType(FunctionType newType) {
633   auto oldType = getType();
634   assert(newType.getNumResults() == oldType.getNumResults() &&
635          "unimplemented: changes to the number of results");
636 
637   SmallVector<char, 16> nameBuf;
638   for (int i = newType.getNumInputs(), e = oldType.getNumInputs(); i < e; i++)
639     removeAttr(getArgAttrName(i, nameBuf));
640 
641   setAttr(getTypeAttrName(), TypeAttr::get(newType));
642 }
643 
644 /// Hook for FunctionLike verifier.
645 LogicalResult GPUFuncOp::verifyType() {
646   Type type = getTypeAttr().getValue();
647   if (!type.isa<FunctionType>())
648     return emitOpError("requires '" + getTypeAttrName() +
649                        "' attribute of function type");
650 
651   if (isKernel() && getType().getNumResults() != 0)
652     return emitOpError() << "expected void return type for kernel function";
653 
654   return success();
655 }
656 
657 static LogicalResult verifyAttributions(Operation *op,
658                                         ArrayRef<BlockArgument> attributions,
659                                         unsigned memorySpace) {
660   for (Value v : attributions) {
661     auto type = v.getType().dyn_cast<MemRefType>();
662     if (!type)
663       return op->emitOpError() << "expected memref type in attribution";
664 
665     if (type.getMemorySpace() != memorySpace) {
666       return op->emitOpError()
667              << "expected memory space " << memorySpace << " in attribution";
668     }
669   }
670   return success();
671 }
672 
673 /// Verifies the body of the function.
674 LogicalResult GPUFuncOp::verifyBody() {
675   unsigned numFuncArguments = getNumArguments();
676   unsigned numWorkgroupAttributions = getNumWorkgroupAttributions();
677   unsigned numBlockArguments = front().getNumArguments();
678   if (numBlockArguments < numFuncArguments + numWorkgroupAttributions)
679     return emitOpError() << "expected at least "
680                          << numFuncArguments + numWorkgroupAttributions
681                          << " arguments to body region";
682 
683   ArrayRef<Type> funcArgTypes = getType().getInputs();
684   for (unsigned i = 0; i < numFuncArguments; ++i) {
685     Type blockArgType = front().getArgument(i).getType();
686     if (funcArgTypes[i] != blockArgType)
687       return emitOpError() << "expected body region argument #" << i
688                            << " to be of type " << funcArgTypes[i] << ", got "
689                            << blockArgType;
690   }
691 
692   if (failed(verifyAttributions(getOperation(), getWorkgroupAttributions(),
693                                 GPUDialect::getWorkgroupAddressSpace())) ||
694       failed(verifyAttributions(getOperation(), getPrivateAttributions(),
695                                 GPUDialect::getPrivateAddressSpace())))
696     return failure();
697 
698   return success();
699 }
700 
701 //===----------------------------------------------------------------------===//
702 // ReturnOp
703 //===----------------------------------------------------------------------===//
704 
705 static ParseResult parseReturnOp(OpAsmParser &parser, OperationState &result) {
706   llvm::SmallVector<OpAsmParser::OperandType, 4> operands;
707   llvm::SmallVector<Type, 4> types;
708   if (parser.parseOperandList(operands) ||
709       parser.parseOptionalColonTypeList(types) ||
710       parser.resolveOperands(operands, types, parser.getCurrentLocation(),
711                              result.operands))
712     return failure();
713 
714   return success();
715 }
716 
717 static LogicalResult verify(gpu::ReturnOp returnOp) {
718   GPUFuncOp function = returnOp.getParentOfType<GPUFuncOp>();
719 
720   FunctionType funType = function.getType();
721 
722   if (funType.getNumResults() != returnOp.operands().size())
723     return returnOp.emitOpError()
724         .append("expected ", funType.getNumResults(), " result operands")
725         .attachNote(function.getLoc())
726         .append("return type declared here");
727 
728   for (auto pair : llvm::enumerate(
729            llvm::zip(function.getType().getResults(), returnOp.operands()))) {
730     Type type;
731     Value operand;
732     std::tie(type, operand) = pair.value();
733     if (type != operand.getType())
734       return returnOp.emitOpError() << "unexpected type `" << operand.getType()
735                                     << "' for operand #" << pair.index();
736   }
737   return success();
738 }
739 
740 //===----------------------------------------------------------------------===//
741 // GPUModuleOp
742 //===----------------------------------------------------------------------===//
743 
744 void GPUModuleOp::build(Builder *builder, OperationState &result,
745                         StringRef name) {
746   ensureTerminator(*result.addRegion(), *builder, result.location);
747   result.attributes.push_back(builder->getNamedAttr(
748       ::mlir::SymbolTable::getSymbolAttrName(), builder->getStringAttr(name)));
749 }
750 
751 static ParseResult parseGPUModuleOp(OpAsmParser &parser,
752                                     OperationState &result) {
753   StringAttr nameAttr;
754   if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
755                              result.attributes))
756     return failure();
757 
758   // If module attributes are present, parse them.
759   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
760     return failure();
761 
762   // Parse the module body.
763   auto *body = result.addRegion();
764   if (parser.parseRegion(*body, None, None))
765     return failure();
766 
767   // Ensure that this module has a valid terminator.
768   GPUModuleOp::ensureTerminator(*body, parser.getBuilder(), result.location);
769   return success();
770 }
771 
772 static void print(OpAsmPrinter &p, GPUModuleOp op) {
773   p << op.getOperationName() << ' ';
774   p.printSymbolName(op.getName());
775   p.printOptionalAttrDictWithKeyword(op.getAttrs(),
776                                      {SymbolTable::getSymbolAttrName()});
777   p.printRegion(op.getOperation()->getRegion(0), /*printEntryBlockArgs=*/false,
778                 /*printBlockTerminators=*/false);
779 }
780 
781 // Namespace avoids ambiguous ReturnOpOperandAdaptor.
782 namespace mlir {
783 namespace gpu {
784 #define GET_OP_CLASSES
785 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
786 } // namespace gpu
787 } // namespace mlir
788