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