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