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<
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 kernelGPUFunction = dyn_cast_or_null<gpu::GPUFuncOp>(kernelFunc);
98     auto kernelLLVMFunction = dyn_cast_or_null<LLVM::LLVMFuncOp>(kernelFunc);
99     if (!kernelGPUFunction && !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                                         : kernelGPUFunction.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(ValueRange 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                      ValueRange 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 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                                 ValueRange 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   ValueRange operands = op.getOperands();
289 
290   // Print the launch configuration.
291   p << LaunchOp::getOperationName() << ' ' << op.getBlocksKeyword();
292   printSizeAssignment(p, op.getGridSize(), operands.take_front(3),
293                       op.getBlockIds());
294   p << ' ' << op.getThreadsKeyword();
295   printSizeAssignment(p, op.getBlockSize(), operands.slice(3, 3),
296                       op.getThreadIds());
297 
298   // From now on, the first kNumConfigOperands operands corresponding to grid
299   // and block sizes are irrelevant, so we can drop them.
300   operands = operands.drop_front(LaunchOp::kNumConfigOperands);
301 
302   // Print the data argument remapping.
303   if (!op.body().empty() && !operands.empty()) {
304     p << ' ' << op.getArgsKeyword() << '(';
305     Block *entryBlock = &op.body().front();
306     interleaveComma(llvm::seq<int>(0, operands.size()), p, [&](int i) {
307       p << *entryBlock->getArgument(LaunchOp::kNumConfigRegionAttributes + i)
308         << " = " << *operands[i];
309     });
310     p << ") ";
311   }
312 
313   // Print the types of data arguments.
314   if (!operands.empty())
315     p << ": " << operands.getTypes();
316 
317   p.printRegion(op.body(), /*printEntryBlockArgs=*/false);
318   p.printOptionalAttrDict(op.getAttrs());
319 }
320 
321 // Parse the size assignment blocks for blocks and threads.  These have the form
322 //   (%region_arg, %region_arg, %region_arg) in
323 //   (%region_arg = %operand, %region_arg = %operand, %region_arg = %operand)
324 // where %region_arg are percent-identifiers for the region arguments to be
325 // introduced further (SSA defs), and %operand are percent-identifiers for the
326 // SSA value uses.
327 static ParseResult
328 parseSizeAssignment(OpAsmParser &parser,
329                     MutableArrayRef<OpAsmParser::OperandType> sizes,
330                     MutableArrayRef<OpAsmParser::OperandType> regionSizes,
331                     MutableArrayRef<OpAsmParser::OperandType> indices) {
332   assert(indices.size() == 3 && "space for three indices expected");
333   SmallVector<OpAsmParser::OperandType, 3> args;
334   if (parser.parseRegionArgumentList(args, /*requiredOperandCount=*/3,
335                                      OpAsmParser::Delimiter::Paren) ||
336       parser.parseKeyword("in") || parser.parseLParen())
337     return failure();
338   std::move(args.begin(), args.end(), indices.begin());
339 
340   for (int i = 0; i < 3; ++i) {
341     if (i != 0 && parser.parseComma())
342       return failure();
343     if (parser.parseRegionArgument(regionSizes[i]) || parser.parseEqual() ||
344         parser.parseOperand(sizes[i]))
345       return failure();
346   }
347 
348   return parser.parseRParen();
349 }
350 
351 // Parses a Launch operation.
352 // operation ::= `gpu.launch` `blocks` `(` ssa-id-list `)` `in` ssa-reassignment
353 //                           `threads` `(` ssa-id-list `)` `in` ssa-reassignment
354 //                             (`args` ssa-reassignment `:` type-list)?
355 //                             region attr-dict?
356 // ssa-reassignment ::= `(` ssa-id `=` ssa-use (`,` ssa-id `=` ssa-use)* `)`
357 ParseResult parseLaunchOp(OpAsmParser &parser, OperationState &result) {
358   // Sizes of the grid and block.
359   SmallVector<OpAsmParser::OperandType, LaunchOp::kNumConfigOperands> sizes(
360       LaunchOp::kNumConfigOperands);
361   MutableArrayRef<OpAsmParser::OperandType> sizesRef(sizes);
362 
363   // Actual (data) operands passed to the kernel.
364   SmallVector<OpAsmParser::OperandType, 4> dataOperands;
365 
366   // Region arguments to be created.
367   SmallVector<OpAsmParser::OperandType, 16> regionArgs(
368       LaunchOp::kNumConfigRegionAttributes);
369   MutableArrayRef<OpAsmParser::OperandType> regionArgsRef(regionArgs);
370 
371   // Parse the size assignment segments: the first segment assigns grid sizes
372   // and defines values for block identifiers; the second segment assigns block
373   // sizes and defines values for thread identifiers.  In the region argument
374   // list, identifiers precede sizes, and block-related values precede
375   // thread-related values.
376   if (parser.parseKeyword(LaunchOp::getBlocksKeyword().data()) ||
377       parseSizeAssignment(parser, sizesRef.take_front(3),
378                           regionArgsRef.slice(6, 3),
379                           regionArgsRef.slice(0, 3)) ||
380       parser.parseKeyword(LaunchOp::getThreadsKeyword().data()) ||
381       parseSizeAssignment(parser, sizesRef.drop_front(3),
382                           regionArgsRef.slice(9, 3),
383                           regionArgsRef.slice(3, 3)) ||
384       parser.resolveOperands(sizes, parser.getBuilder().getIndexType(),
385                              result.operands))
386     return failure();
387 
388   // If kernel argument renaming segment is present, parse it.  When present,
389   // the segment should have at least one element.  If this segment is present,
390   // so is the trailing type list.  Parse it as well and use the parsed types
391   // to resolve the operands passed to the kernel arguments.
392   SmallVector<Type, 4> dataTypes;
393   if (!parser.parseOptionalKeyword(LaunchOp::getArgsKeyword())) {
394     llvm::SMLoc argsLoc = parser.getCurrentLocation();
395 
396     regionArgs.push_back({});
397     dataOperands.push_back({});
398     if (parser.parseLParen() || parser.parseRegionArgument(regionArgs.back()) ||
399         parser.parseEqual() || parser.parseOperand(dataOperands.back()))
400       return failure();
401 
402     while (!parser.parseOptionalComma()) {
403       regionArgs.push_back({});
404       dataOperands.push_back({});
405       if (parser.parseRegionArgument(regionArgs.back()) ||
406           parser.parseEqual() || parser.parseOperand(dataOperands.back()))
407         return failure();
408     }
409 
410     if (parser.parseRParen() || parser.parseColonTypeList(dataTypes) ||
411         parser.resolveOperands(dataOperands, dataTypes, argsLoc,
412                                result.operands))
413       return failure();
414   }
415 
416   // Introduce the body region and parse it.  The region has
417   // kNumConfigRegionAttributes leading arguments that correspond to
418   // block/thread identifiers and grid/block sizes, all of the `index` type.
419   // Follow the actual kernel arguments.
420   Type index = parser.getBuilder().getIndexType();
421   dataTypes.insert(dataTypes.begin(), LaunchOp::kNumConfigRegionAttributes,
422                    index);
423   Region *body = result.addRegion();
424   return failure(parser.parseRegion(*body, regionArgs, dataTypes) ||
425                  parser.parseOptionalAttrDict(result.attributes));
426 }
427 
428 void LaunchOp::eraseKernelArgument(unsigned index) {
429   Block &entryBlock = body().front();
430   assert(index < entryBlock.getNumArguments() - kNumConfigRegionAttributes &&
431          "kernel argument index overflow");
432   entryBlock.eraseArgument(kNumConfigRegionAttributes + index);
433   getOperation()->eraseOperand(kNumConfigOperands + index);
434 }
435 
436 namespace {
437 // Clone any known constants passed as operands to the kernel into its body.
438 class PropagateConstantBounds : public OpRewritePattern<LaunchOp> {
439   using OpRewritePattern<LaunchOp>::OpRewritePattern;
440 
441   PatternMatchResult matchAndRewrite(LaunchOp launchOp,
442                                      PatternRewriter &rewriter) const override {
443     auto origInsertionPoint = rewriter.saveInsertionPoint();
444     rewriter.setInsertionPointToStart(&launchOp.body().front());
445 
446     // Traverse operands passed to kernel and check if some of them are known
447     // constants.  If so, clone the constant operation inside the kernel region
448     // and use it instead of passing the value from the parent region.  Perform
449     // the traversal in the inverse order to simplify index arithmetics when
450     // dropping arguments.
451     SmallVector<Value *, 8> operands(launchOp.getKernelOperandValues().begin(),
452                                      launchOp.getKernelOperandValues().end());
453     SmallVector<Value *, 8> kernelArgs(launchOp.getKernelArguments().begin(),
454                                        launchOp.getKernelArguments().end());
455     bool found = false;
456     for (unsigned i = operands.size(); i > 0; --i) {
457       unsigned index = i - 1;
458       Value *operand = operands[index];
459       if (!isa_and_nonnull<ConstantOp>(operand->getDefiningOp())) {
460         continue;
461       }
462 
463       found = true;
464       Value *internalConstant =
465           rewriter.clone(*operand->getDefiningOp())->getResult(0);
466       Value *kernelArg = kernelArgs[index];
467       kernelArg->replaceAllUsesWith(internalConstant);
468       launchOp.eraseKernelArgument(index);
469     }
470     rewriter.restoreInsertionPoint(origInsertionPoint);
471 
472     if (!found)
473       return matchFailure();
474 
475     rewriter.updatedRootInPlace(launchOp);
476     return matchSuccess();
477   }
478 };
479 } // end namespace
480 
481 void LaunchOp::getCanonicalizationPatterns(OwningRewritePatternList &results,
482                                            MLIRContext *context) {
483   results.insert<PropagateConstantBounds>(context);
484 }
485 
486 //===----------------------------------------------------------------------===//
487 // LaunchFuncOp
488 //===----------------------------------------------------------------------===//
489 
490 void LaunchFuncOp::build(Builder *builder, OperationState &result,
491                          GPUFuncOp kernelFunc, Value *gridSizeX,
492                          Value *gridSizeY, Value *gridSizeZ, Value *blockSizeX,
493                          Value *blockSizeY, Value *blockSizeZ,
494                          ValueRange kernelOperands) {
495   // Add grid and block sizes as op operands, followed by the data operands.
496   result.addOperands(
497       {gridSizeX, gridSizeY, gridSizeZ, blockSizeX, blockSizeY, blockSizeZ});
498   result.addOperands(kernelOperands);
499   result.addAttribute(getKernelAttrName(),
500                       builder->getStringAttr(kernelFunc.getName()));
501   auto kernelModule = kernelFunc.getParentOfType<ModuleOp>();
502   if (Optional<StringRef> kernelModuleName = kernelModule.getName())
503     result.addAttribute(getKernelModuleAttrName(),
504                         builder->getSymbolRefAttr(*kernelModuleName));
505 }
506 
507 void LaunchFuncOp::build(Builder *builder, OperationState &result,
508                          GPUFuncOp kernelFunc, KernelDim3 gridSize,
509                          KernelDim3 blockSize, ValueRange kernelOperands) {
510   build(builder, result, kernelFunc, gridSize.x, gridSize.y, gridSize.z,
511         blockSize.x, blockSize.y, blockSize.z, kernelOperands);
512 }
513 
514 StringRef LaunchFuncOp::kernel() {
515   return getAttrOfType<StringAttr>(getKernelAttrName()).getValue();
516 }
517 
518 unsigned LaunchFuncOp::getNumKernelOperands() {
519   return getNumOperands() - kNumConfigOperands;
520 }
521 
522 StringRef LaunchFuncOp::getKernelModuleName() {
523   return getAttrOfType<SymbolRefAttr>(getKernelModuleAttrName())
524       .getRootReference();
525 }
526 
527 Value *LaunchFuncOp::getKernelOperand(unsigned i) {
528   return getOperation()->getOperand(i + kNumConfigOperands);
529 }
530 
531 KernelDim3 LaunchFuncOp::getGridSizeOperandValues() {
532   return KernelDim3{getOperand(0), getOperand(1), getOperand(2)};
533 }
534 
535 KernelDim3 LaunchFuncOp::getBlockSizeOperandValues() {
536   return KernelDim3{getOperand(3), getOperand(4), getOperand(5)};
537 }
538 
539 LogicalResult verify(LaunchFuncOp op) {
540   auto module = op.getParentOfType<ModuleOp>();
541   if (!module)
542     return op.emitOpError("expected to belong to a module");
543 
544   if (!module.getAttrOfType<UnitAttr>(GPUDialect::getContainerModuleAttrName()))
545     return op.emitOpError(
546         "expected the closest surrounding module to have the '" +
547         GPUDialect::getContainerModuleAttrName() + "' attribute");
548 
549   auto kernelAttr = op.getAttrOfType<StringAttr>(op.getKernelAttrName());
550   if (!kernelAttr)
551     return op.emitOpError("string attribute '" + op.getKernelAttrName() +
552                           "' must be specified");
553 
554   auto kernelModuleAttr =
555       op.getAttrOfType<SymbolRefAttr>(op.getKernelModuleAttrName());
556   if (!kernelModuleAttr)
557     return op.emitOpError("symbol reference attribute '" +
558                           op.getKernelModuleAttrName() + "' must be specified");
559 
560   return success();
561 }
562 
563 //===----------------------------------------------------------------------===//
564 // GPUFuncOp
565 //===----------------------------------------------------------------------===//
566 
567 void GPUFuncOp::build(Builder *builder, OperationState &result, StringRef name,
568                       FunctionType type, ArrayRef<Type> workgroupAttributions,
569                       ArrayRef<Type> privateAttributions,
570                       ArrayRef<NamedAttribute> attrs) {
571   result.addAttribute(SymbolTable::getSymbolAttrName(),
572                       builder->getStringAttr(name));
573   result.addAttribute(getTypeAttrName(), TypeAttr::get(type));
574   result.addAttribute(getNumWorkgroupAttributionsAttrName(),
575                       builder->getI64IntegerAttr(workgroupAttributions.size()));
576   result.addAttributes(attrs);
577   Region *body = result.addRegion();
578   Block *entryBlock = new Block;
579   entryBlock->addArguments(type.getInputs());
580   entryBlock->addArguments(workgroupAttributions);
581   entryBlock->addArguments(privateAttributions);
582 
583   body->getBlocks().push_back(entryBlock);
584 }
585 
586 /// Parses a GPU function memory attribution.
587 ///
588 /// memory-attribution ::= (`workgroup` `(` ssa-id-and-type-list `)`)?
589 ///                        (`private` `(` ssa-id-and-type-list `)`)?
590 ///
591 /// Note that this function parses only one of the two similar parts, with the
592 /// keyword provided as argument.
593 static ParseResult
594 parseAttributions(OpAsmParser &parser, StringRef keyword,
595                   SmallVectorImpl<OpAsmParser::OperandType> &args,
596                   SmallVectorImpl<Type> &argTypes) {
597   // If we could not parse the keyword, just assume empty list and succeed.
598   if (failed(parser.parseOptionalKeyword(keyword)))
599     return success();
600 
601   if (failed(parser.parseLParen()))
602     return failure();
603 
604   // Early exit for an empty list.
605   if (succeeded(parser.parseOptionalRParen()))
606     return success();
607 
608   do {
609     OpAsmParser::OperandType arg;
610     Type type;
611 
612     if (parser.parseRegionArgument(arg) || parser.parseColonType(type))
613       return failure();
614 
615     args.push_back(arg);
616     argTypes.push_back(type);
617   } while (succeeded(parser.parseOptionalComma()));
618 
619   return parser.parseRParen();
620 }
621 
622 /// Parses a GPU function.
623 ///
624 /// <operation> ::= `gpu.func` symbol-ref-id `(` argument-list `)`
625 ///                 (`->` function-result-list)? memory-attribution `kernel`?
626 ///                 function-attributes? region
627 static ParseResult parseGPUFuncOp(OpAsmParser &parser, OperationState &result) {
628   SmallVector<OpAsmParser::OperandType, 8> entryArgs;
629   SmallVector<SmallVector<NamedAttribute, 2>, 1> argAttrs;
630   SmallVector<SmallVector<NamedAttribute, 2>, 1> resultAttrs;
631   SmallVector<Type, 8> argTypes;
632   SmallVector<Type, 4> resultTypes;
633   bool isVariadic;
634 
635   // Parse the function name.
636   StringAttr nameAttr;
637   if (parser.parseSymbolName(nameAttr, ::mlir::SymbolTable::getSymbolAttrName(),
638                              result.attributes))
639     return failure();
640 
641   auto signatureLocation = parser.getCurrentLocation();
642   if (failed(impl::parseFunctionSignature(
643           parser, /*allowVariadic=*/false, entryArgs, argTypes, argAttrs,
644           isVariadic, resultTypes, resultAttrs)))
645     return failure();
646 
647   if (entryArgs.empty() && !argTypes.empty())
648     return parser.emitError(signatureLocation)
649            << "gpu.func requires named arguments";
650 
651   // Construct the function type. More types will be added to the region, but
652   // not to the functiont type.
653   Builder &builder = parser.getBuilder();
654   auto type = builder.getFunctionType(argTypes, resultTypes);
655   result.addAttribute(GPUFuncOp::getTypeAttrName(), TypeAttr::get(type));
656 
657   // Parse workgroup memory attributions.
658   if (failed(parseAttributions(parser, GPUFuncOp::getWorkgroupKeyword(),
659                                entryArgs, argTypes)))
660     return failure();
661 
662   // Store the number of operands we just parsed as the number of workgroup
663   // memory attributions.
664   unsigned numWorkgroupAttrs = argTypes.size() - type.getNumInputs();
665   result.addAttribute(GPUFuncOp::getNumWorkgroupAttributionsAttrName(),
666                       builder.getI64IntegerAttr(numWorkgroupAttrs));
667 
668   // Parse private memory attributions.
669   if (failed(parseAttributions(parser, GPUFuncOp::getPrivateKeyword(),
670                                entryArgs, argTypes)))
671     return failure();
672 
673   // Parse the kernel attribute if present.
674   if (succeeded(parser.parseOptionalKeyword(GPUFuncOp::getKernelKeyword())))
675     result.addAttribute(GPUDialect::getKernelFuncAttrName(),
676                         builder.getUnitAttr());
677 
678   // Parse attributes.
679   if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
680     return failure();
681   mlir::impl::addArgAndResultAttrs(builder, result, argAttrs, resultAttrs);
682 
683   // Parse the region. If no argument names were provided, take all names
684   // (including those of attributions) from the entry block.
685   auto *body = result.addRegion();
686   return parser.parseRegion(*body, entryArgs, argTypes);
687 }
688 
689 static void printAttributions(OpAsmPrinter &p, StringRef keyword,
690                               ArrayRef<BlockArgument *> values) {
691   if (values.empty())
692     return;
693 
694   p << ' ' << keyword << '(';
695   interleaveComma(values, p,
696                   [&p](BlockArgument *v) { p << *v << " : " << v->getType(); });
697   p << ')';
698 }
699 
700 /// Prints a GPU Func op.
701 void printGPUFuncOp(OpAsmPrinter &p, GPUFuncOp op) {
702   p << GPUFuncOp::getOperationName() << ' ';
703   p.printSymbolName(op.getName());
704 
705   FunctionType type = op.getType();
706   impl::printFunctionSignature(p, op.getOperation(), type.getInputs(),
707                                /*isVariadic=*/false, type.getResults());
708 
709   printAttributions(p, op.getWorkgroupKeyword(), op.getWorkgroupAttributions());
710   printAttributions(p, op.getPrivateKeyword(), op.getPrivateAttributions());
711   if (op.isKernel())
712     p << ' ' << op.getKernelKeyword();
713 
714   impl::printFunctionAttributes(p, op.getOperation(), type.getNumInputs(),
715                                 type.getNumResults(),
716                                 {op.getNumWorkgroupAttributionsAttrName(),
717                                  GPUDialect::getKernelFuncAttrName()});
718   p.printRegion(op.getBody(), /*printEntryBlockArgs=*/false);
719 }
720 
721 void GPUFuncOp::setType(FunctionType newType) {
722   auto oldType = getType();
723   assert(newType.getNumResults() == oldType.getNumResults() &&
724          "unimplemented: changes to the number of results");
725 
726   SmallVector<char, 16> nameBuf;
727   for (int i = newType.getNumInputs(), e = oldType.getNumInputs(); i < e; i++)
728     removeAttr(getArgAttrName(i, nameBuf));
729 
730   setAttr(getTypeAttrName(), TypeAttr::get(newType));
731 }
732 
733 /// Hook for FunctionLike verifier.
734 LogicalResult GPUFuncOp::verifyType() {
735   Type type = getTypeAttr().getValue();
736   if (!type.isa<FunctionType>())
737     return emitOpError("requires '" + getTypeAttrName() +
738                        "' attribute of function type");
739   return success();
740 }
741 
742 static LogicalResult verifyAttributions(Operation *op,
743                                         ArrayRef<BlockArgument *> attributions,
744                                         unsigned memorySpace) {
745   for (Value *v : attributions) {
746     auto type = v->getType().dyn_cast<MemRefType>();
747     if (!type)
748       return op->emitOpError() << "expected memref type in attribution";
749 
750     if (type.getMemorySpace() != memorySpace) {
751       return op->emitOpError()
752              << "expected memory space " << memorySpace << " in attribution";
753     }
754   }
755   return success();
756 }
757 
758 /// Verifies the body of the function.
759 LogicalResult GPUFuncOp::verifyBody() {
760   unsigned numFuncArguments = getNumArguments();
761   unsigned numWorkgroupAttributions = getNumWorkgroupAttributions();
762   unsigned numBlockArguments = front().getNumArguments();
763   if (numBlockArguments < numFuncArguments + numWorkgroupAttributions)
764     return emitOpError() << "expected at least "
765                          << numFuncArguments + numWorkgroupAttributions
766                          << " arguments to body region";
767 
768   ArrayRef<Type> funcArgTypes = getType().getInputs();
769   for (unsigned i = 0; i < numFuncArguments; ++i) {
770     Type blockArgType = front().getArgument(i)->getType();
771     if (funcArgTypes[i] != blockArgType)
772       return emitOpError() << "expected body region argument #" << i
773                            << " to be of type " << funcArgTypes[i] << ", got "
774                            << blockArgType;
775   }
776 
777   if (failed(verifyAttributions(getOperation(), getWorkgroupAttributions(),
778                                 GPUDialect::getWorkgroupAddressSpace())) ||
779       failed(verifyAttributions(getOperation(), getPrivateAttributions(),
780                                 GPUDialect::getPrivateAddressSpace())))
781     return failure();
782 
783   return success();
784 }
785 
786 // Namespace avoids ambiguous ReturnOpOperandAdaptor.
787 namespace mlir {
788 namespace gpu {
789 #define GET_OP_CLASSES
790 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
791 } // namespace gpu
792 } // namespace mlir
793