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