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