1 //===- GPUDialect.cpp - MLIR Dialect for GPU Kernels implementation -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the GPU kernel-related dialect and its operations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Dialect/GPU/GPUDialect.h"
14 
15 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
16 #include "mlir/Dialect/MemRef/IR/MemRef.h"
17 #include "mlir/Dialect/StandardOps/IR/Ops.h"
18 #include "mlir/IR/Attributes.h"
19 #include "mlir/IR/Builders.h"
20 #include "mlir/IR/BuiltinOps.h"
21 #include "mlir/IR/BuiltinTypes.h"
22 #include "mlir/IR/DialectImplementation.h"
23 #include "mlir/IR/FunctionImplementation.h"
24 #include "mlir/IR/OpImplementation.h"
25 #include "mlir/IR/PatternMatch.h"
26 #include "mlir/IR/TypeUtilities.h"
27 #include "llvm/ADT/TypeSwitch.h"
28 
29 using namespace mlir;
30 using namespace mlir::gpu;
31 
32 #include "mlir/Dialect/GPU/GPUOpsDialect.cpp.inc"
33 
34 //===----------------------------------------------------------------------===//
35 // MMAMatrixType
36 //===----------------------------------------------------------------------===//
37 
38 MMAMatrixType MMAMatrixType::get(ArrayRef<int64_t> shape, Type elementType,
39                                  StringRef operand) {
40   return Base::get(elementType.getContext(), shape, elementType, operand);
41 }
42 
43 MMAMatrixType
44 MMAMatrixType::getChecked(function_ref<InFlightDiagnostic()> emitError,
45                           ArrayRef<int64_t> shape, Type elementType,
46                           StringRef operand) {
47   return Base::getChecked(emitError, elementType.getContext(), shape,
48                           elementType, operand);
49 }
50 
51 unsigned MMAMatrixType::getNumDims() const { return getImpl()->numDims; }
52 
53 ArrayRef<int64_t> MMAMatrixType::getShape() const {
54   return getImpl()->getShape();
55 }
56 
57 Type MMAMatrixType::getElementType() const { return getImpl()->elementType; }
58 
59 StringRef MMAMatrixType::getOperand() const { return getImpl()->getOperand(); }
60 
61 bool MMAMatrixType::isValidElementType(Type elementType) {
62   return elementType.isF16() || elementType.isF32();
63 }
64 
65 LogicalResult
66 MMAMatrixType::verify(function_ref<InFlightDiagnostic()> emitError,
67                       ArrayRef<int64_t> shape, Type elementType,
68                       StringRef operand) {
69   if (!operand.equals("AOp") && !operand.equals("BOp") &&
70       !operand.equals("COp"))
71     return emitError() << "operand expected to be one of AOp, BOp or COp";
72 
73   if (shape.size() != 2)
74     return emitError() << "MMAMatrixType must have exactly two dimensions";
75 
76   if (!MMAMatrixType::isValidElementType(elementType))
77     return emitError() << "MMAMatrixType elements must be F16 or F32";
78 
79   return success();
80 }
81 
82 //===----------------------------------------------------------------------===//
83 // GPUDialect
84 //===----------------------------------------------------------------------===//
85 
86 /// GPU memory space identifiers.
87 enum GPUMemorySpace {
88   /// Generic memory space identifier.
89   kGenericMemorySpace = 0,
90 
91   /// Global memory space identifier.
92   kGlobalMemorySpace = 1,
93 
94   /// Shared memory space identifier.
95   kSharedMemorySpace = 3
96 };
97 
98 bool GPUDialect::isKernel(Operation *op) {
99   UnitAttr isKernelAttr = op->getAttrOfType<UnitAttr>(getKernelFuncAttrName());
100   return static_cast<bool>(isKernelAttr);
101 }
102 
103 void GPUDialect::initialize() {
104   addTypes<AsyncTokenType>();
105   addTypes<MMAMatrixType>();
106   addOperations<
107 #define GET_OP_LIST
108 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
109       >();
110 }
111 
112 Type GPUDialect::parseType(DialectAsmParser &parser) const {
113   // Parse the main keyword for the type.
114   StringRef keyword;
115   if (parser.parseKeyword(&keyword))
116     return Type();
117   MLIRContext *context = getContext();
118 
119   // Handle 'async token' types.
120   if (keyword == "async.token")
121     return AsyncTokenType::get(context);
122 
123   if (keyword == "mma_matrix") {
124     llvm::SMLoc beginLoc = parser.getNameLoc();
125 
126     // Parse '<'.
127     if (parser.parseLess())
128       return nullptr;
129 
130     // Parse the size and elementType.
131     SmallVector<int64_t> shape;
132     Type elementType;
133     if (parser.parseDimensionList(shape, /*allowDynamic=*/false) ||
134         parser.parseType(elementType))
135       return nullptr;
136 
137     // Parse ','
138     if (parser.parseComma())
139       return nullptr;
140 
141     // Parse operand.
142     StringRef operand;
143     if (failed(parser.parseOptionalString(&operand)))
144       return nullptr;
145 
146     // Parse '>'.
147     if (parser.parseGreater())
148       return nullptr;
149 
150     return MMAMatrixType::getChecked(mlir::detail::getDefaultDiagnosticEmitFn(
151                                          parser.getEncodedSourceLoc(beginLoc)),
152                                      shape, elementType, operand);
153   }
154 
155   parser.emitError(parser.getNameLoc(), "unknown gpu type: " + keyword);
156   return Type();
157 }
158 
159 void GPUDialect::printType(Type type, DialectAsmPrinter &os) const {
160   TypeSwitch<Type>(type)
161       .Case<AsyncTokenType>([&](Type) { os << "async.token"; })
162       .Case<MMAMatrixType>([&](MMAMatrixType fragTy) {
163         os << "mma_matrix<";
164         auto shape = fragTy.getShape();
165         for (auto dim = shape.begin(), e = shape.end() - 1; dim != e; ++dim)
166           os << *dim << 'x';
167         os << shape.back() << 'x' << fragTy.getElementType();
168         os << ", \"" << fragTy.getOperand() << "\"" << '>';
169       })
170       .Default([](Type) { llvm_unreachable("unexpected 'gpu' type kind"); });
171 }
172 
173 LogicalResult GPUDialect::verifyOperationAttribute(Operation *op,
174                                                    NamedAttribute attr) {
175   if (!attr.second.isa<UnitAttr>() ||
176       attr.first != getContainerModuleAttrName())
177     return success();
178 
179   auto module = dyn_cast<ModuleOp>(op);
180   if (!module)
181     return op->emitError("expected '")
182            << getContainerModuleAttrName() << "' attribute to be attached to '"
183            << ModuleOp::getOperationName() << '\'';
184 
185   auto walkResult = module.walk([&module](LaunchFuncOp launchOp) -> WalkResult {
186     // Ignore launches that are nested more or less deep than functions in the
187     // module we are currently checking.
188     if (!launchOp->getParentOp() ||
189         launchOp->getParentOp()->getParentOp() != module)
190       return success();
191 
192     // Ignore launch ops with missing attributes here. The errors will be
193     // reported by the verifiers of those ops.
194     if (!launchOp->getAttrOfType<SymbolRefAttr>(
195             LaunchFuncOp::getKernelAttrName()))
196       return success();
197 
198     // Check that `launch_func` refers to a well-formed GPU kernel module.
199     StringRef kernelModuleName = launchOp.getKernelModuleName();
200     auto kernelModule = module.lookupSymbol<GPUModuleOp>(kernelModuleName);
201     if (!kernelModule)
202       return launchOp.emitOpError()
203              << "kernel module '" << kernelModuleName << "' is undefined";
204 
205     // Check that `launch_func` refers to a well-formed kernel function.
206     Operation *kernelFunc = module.lookupSymbol(launchOp.kernel());
207     auto kernelGPUFunction = dyn_cast_or_null<gpu::GPUFuncOp>(kernelFunc);
208     auto kernelLLVMFunction = dyn_cast_or_null<LLVM::LLVMFuncOp>(kernelFunc);
209     if (!kernelGPUFunction && !kernelLLVMFunction)
210       return launchOp.emitOpError("kernel function '")
211              << launchOp.kernel() << "' is undefined";
212     if (!kernelFunc->getAttrOfType<mlir::UnitAttr>(
213             GPUDialect::getKernelFuncAttrName()))
214       return launchOp.emitOpError("kernel function is missing the '")
215              << GPUDialect::getKernelFuncAttrName() << "' attribute";
216 
217     // TODO: if the kernel function has been converted to
218     // the LLVM dialect but the caller hasn't (which happens during the
219     // separate compilation), do not check type correspondence as it would
220     // require the verifier to be aware of the LLVM type conversion.
221     if (kernelLLVMFunction)
222       return success();
223 
224     unsigned actualNumArguments = launchOp.getNumKernelOperands();
225     unsigned expectedNumArguments = kernelGPUFunction.getNumArguments();
226     if (expectedNumArguments != actualNumArguments)
227       return launchOp.emitOpError("got ")
228              << actualNumArguments << " kernel operands but expected "
229              << expectedNumArguments;
230 
231     auto functionType = kernelGPUFunction.getType();
232     for (unsigned i = 0; i < expectedNumArguments; ++i) {
233       if (launchOp.getKernelOperand(i).getType() != functionType.getInput(i)) {
234         return launchOp.emitOpError("type of function argument ")
235                << i << " does not match";
236       }
237     }
238 
239     return success();
240   });
241 
242   return walkResult.wasInterrupted() ? failure() : success();
243 }
244 
245 template <typename T>
246 static LogicalResult verifyIndexOp(T op) {
247   auto dimension = op.dimension();
248   if (dimension != "x" && dimension != "y" && dimension != "z")
249     return op.emitError("dimension \"") << dimension << "\" is invalid";
250   return success();
251 }
252 
253 static LogicalResult verifyAllReduce(gpu::AllReduceOp allReduce) {
254   if (allReduce.body().empty() != allReduce.op().hasValue())
255     return allReduce.emitError(
256         "expected either an op attribute or a non-empty body");
257   if (!allReduce.body().empty()) {
258     if (allReduce.body().getNumArguments() != 2)
259       return allReduce.emitError("expected two region arguments");
260     for (auto argument : allReduce.body().getArguments()) {
261       if (argument.getType() != allReduce.getType())
262         return allReduce.emitError("incorrect region argument type");
263     }
264     unsigned yieldCount = 0;
265     for (Block &block : allReduce.body()) {
266       if (auto yield = dyn_cast<gpu::YieldOp>(block.getTerminator())) {
267         if (yield.getNumOperands() != 1)
268           return allReduce.emitError("expected one gpu.yield operand");
269         if (yield.getOperand(0).getType() != allReduce.getType())
270           return allReduce.emitError("incorrect gpu.yield type");
271         ++yieldCount;
272       }
273     }
274     if (yieldCount == 0)
275       return allReduce.emitError("expected gpu.yield op in region");
276   } else {
277     StringRef opName = *allReduce.op();
278     if ((opName == "and" || opName == "or" || opName == "xor") &&
279         !allReduce.getType().isa<IntegerType>()) {
280       return allReduce.emitError()
281              << '`' << opName << '`'
282              << " accumulator is only compatible with Integer type";
283     }
284   }
285   return success();
286 }
287 
288 static LogicalResult verifyShuffleOp(gpu::ShuffleOp shuffleOp) {
289   auto type = shuffleOp.value().getType();
290   if (shuffleOp.result().getType() != type) {
291     return shuffleOp.emitOpError()
292            << "requires the same type for value operand and result";
293   }
294   if (!type.isSignlessIntOrFloat() || type.getIntOrFloatBitWidth() != 32) {
295     return shuffleOp.emitOpError()
296            << "requires value operand type to be f32 or i32";
297   }
298   return success();
299 }
300 
301 static void printShuffleOp(OpAsmPrinter &p, ShuffleOp op) {
302   p << ShuffleOp::getOperationName() << ' ' << op.getOperands() << ' '
303     << op.mode() << " : " << op.value().getType();
304 }
305 
306 static ParseResult parseShuffleOp(OpAsmParser &parser, OperationState &state) {
307   SmallVector<OpAsmParser::OperandType, 3> operandInfo;
308   if (parser.parseOperandList(operandInfo, 3))
309     return failure();
310 
311   StringRef mode;
312   if (parser.parseKeyword(&mode))
313     return failure();
314   state.addAttribute("mode", parser.getBuilder().getStringAttr(mode));
315 
316   Type valueType;
317   Type int32Type = parser.getBuilder().getIntegerType(32);
318   Type int1Type = parser.getBuilder().getI1Type();
319   if (parser.parseColonType(valueType) ||
320       parser.resolveOperands(operandInfo, {valueType, int32Type, int32Type},
321                              parser.getCurrentLocation(), state.operands) ||
322       parser.addTypesToList({valueType, int1Type}, state.types))
323     return failure();
324   return success();
325 }
326 
327 //===----------------------------------------------------------------------===//
328 // AsyncOpInterface
329 //===----------------------------------------------------------------------===//
330 
331 void gpu::addAsyncDependency(Operation *op, Value token) {
332   op->insertOperands(0, {token});
333   if (!op->template hasTrait<OpTrait::AttrSizedOperandSegments>())
334     return;
335   auto attrName =
336       OpTrait::AttrSizedOperandSegments<void>::getOperandSegmentSizeAttr();
337   auto sizeAttr = op->template getAttrOfType<DenseIntElementsAttr>(attrName);
338   if (!sizeAttr)
339     return; // Async dependencies is the only variadic operand.
340   SmallVector<int32_t, 8> sizes;
341   for (auto size : sizeAttr.getIntValues())
342     sizes.push_back(size.getSExtValue());
343   ++sizes.front();
344   op->setAttr(attrName, Builder(op->getContext()).getI32VectorAttr(sizes));
345 }
346 
347 //===----------------------------------------------------------------------===//
348 // LaunchOp
349 //===----------------------------------------------------------------------===//
350 
351 void LaunchOp::build(OpBuilder &builder, OperationState &result,
352                      Value gridSizeX, Value gridSizeY, Value gridSizeZ,
353                      Value blockSizeX, Value blockSizeY, Value blockSizeZ) {
354   // Add grid and block sizes as op operands, followed by the data operands.
355   result.addOperands(
356       {gridSizeX, gridSizeY, gridSizeZ, blockSizeX, blockSizeY, blockSizeZ});
357 
358   // Create a kernel body region with kNumConfigRegionAttributes + N arguments,
359   // where the first kNumConfigRegionAttributes arguments have `index` type and
360   // the rest have the same types as the data operands.
361   Region *kernelRegion = result.addRegion();
362   Block *body = new Block();
363   body->addArguments(
364       std::vector<Type>(kNumConfigRegionAttributes, builder.getIndexType()));
365   kernelRegion->push_back(body);
366 }
367 
368 KernelDim3 LaunchOp::getBlockIds() {
369   assert(!body().empty() && "LaunchOp body must not be empty.");
370   auto args = body().getArguments();
371   return KernelDim3{args[0], args[1], args[2]};
372 }
373 
374 KernelDim3 LaunchOp::getThreadIds() {
375   assert(!body().empty() && "LaunchOp body must not be empty.");
376   auto args = body().getArguments();
377   return KernelDim3{args[3], args[4], args[5]};
378 }
379 
380 KernelDim3 LaunchOp::getGridSize() {
381   assert(!body().empty() && "LaunchOp body must not be empty.");
382   auto args = body().getArguments();
383   return KernelDim3{args[6], args[7], args[8]};
384 }
385 
386 KernelDim3 LaunchOp::getBlockSize() {
387   assert(!body().empty() && "LaunchOp body must not be empty.");
388   auto args = body().getArguments();
389   return KernelDim3{args[9], args[10], args[11]};
390 }
391 
392 KernelDim3 LaunchOp::getGridSizeOperandValues() {
393   return KernelDim3{getOperand(0), getOperand(1), getOperand(2)};
394 }
395 
396 KernelDim3 LaunchOp::getBlockSizeOperandValues() {
397   return KernelDim3{getOperand(3), getOperand(4), getOperand(5)};
398 }
399 
400 static LogicalResult verify(LaunchOp op) {
401   // Kernel launch takes kNumConfigOperands leading operands for grid/block
402   // sizes and transforms them into kNumConfigRegionAttributes region arguments
403   // for block/thread identifiers and grid/block sizes.
404   if (!op.body().empty()) {
405     if (op.body().getNumArguments() !=
406         LaunchOp::kNumConfigOperands + op.getNumOperands())
407       return op.emitOpError("unexpected number of region arguments");
408   }
409 
410   // Block terminators without successors are expected to exit the kernel region
411   // and must be `gpu.terminator`.
412   for (Block &block : op.body()) {
413     if (block.empty())
414       continue;
415     if (block.back().getNumSuccessors() != 0)
416       continue;
417     if (!isa<gpu::TerminatorOp>(&block.back())) {
418       return block.back()
419           .emitError()
420           .append("expected '", gpu::TerminatorOp::getOperationName(),
421                   "' or a terminator with successors")
422           .attachNote(op.getLoc())
423           .append("in '", LaunchOp::getOperationName(), "' body region");
424     }
425   }
426 
427   return success();
428 }
429 
430 // Pretty-print the kernel grid/block size assignment as
431 //   (%iter-x, %iter-y, %iter-z) in
432 //   (%size-x = %ssa-use, %size-y = %ssa-use, %size-z = %ssa-use)
433 // where %size-* and %iter-* will correspond to the body region arguments.
434 static void printSizeAssignment(OpAsmPrinter &p, KernelDim3 size,
435                                 KernelDim3 operands, KernelDim3 ids) {
436   p << '(' << ids.x << ", " << ids.y << ", " << ids.z << ") in (";
437   p << size.x << " = " << operands.x << ", ";
438   p << size.y << " = " << operands.y << ", ";
439   p << size.z << " = " << operands.z << ')';
440 }
441 
442 static void printLaunchOp(OpAsmPrinter &p, LaunchOp op) {
443   // Print the launch configuration.
444   p << LaunchOp::getOperationName() << ' ' << op.getBlocksKeyword();
445   printSizeAssignment(p, op.getGridSize(), op.getGridSizeOperandValues(),
446                       op.getBlockIds());
447   p << ' ' << op.getThreadsKeyword();
448   printSizeAssignment(p, op.getBlockSize(), op.getBlockSizeOperandValues(),
449                       op.getThreadIds());
450 
451   p.printRegion(op.body(), /*printEntryBlockArgs=*/false);
452   p.printOptionalAttrDict(op->getAttrs());
453 }
454 
455 // Parse the size assignment blocks for blocks and threads.  These have the form
456 //   (%region_arg, %region_arg, %region_arg) in
457 //   (%region_arg = %operand, %region_arg = %operand, %region_arg = %operand)
458 // where %region_arg are percent-identifiers for the region arguments to be
459 // introduced further (SSA defs), and %operand are percent-identifiers for the
460 // SSA value uses.
461 static ParseResult
462 parseSizeAssignment(OpAsmParser &parser,
463                     MutableArrayRef<OpAsmParser::OperandType> sizes,
464                     MutableArrayRef<OpAsmParser::OperandType> regionSizes,
465                     MutableArrayRef<OpAsmParser::OperandType> indices) {
466   assert(indices.size() == 3 && "space for three indices expected");
467   SmallVector<OpAsmParser::OperandType, 3> args;
468   if (parser.parseRegionArgumentList(args, /*requiredOperandCount=*/3,
469                                      OpAsmParser::Delimiter::Paren) ||
470       parser.parseKeyword("in") || parser.parseLParen())
471     return failure();
472   std::move(args.begin(), args.end(), indices.begin());
473 
474   for (int i = 0; i < 3; ++i) {
475     if (i != 0 && parser.parseComma())
476       return failure();
477     if (parser.parseRegionArgument(regionSizes[i]) || parser.parseEqual() ||
478         parser.parseOperand(sizes[i]))
479       return failure();
480   }
481 
482   return parser.parseRParen();
483 }
484 
485 // Parses a Launch operation.
486 // operation ::= `gpu.launch` `blocks` `(` ssa-id-list `)` `in` ssa-reassignment
487 //                           `threads` `(` ssa-id-list `)` `in` ssa-reassignment
488 //                            region attr-dict?
489 // ssa-reassignment ::= `(` ssa-id `=` ssa-use (`,` ssa-id `=` ssa-use)* `)`
490 static ParseResult parseLaunchOp(OpAsmParser &parser, OperationState &result) {
491   // Sizes of the grid and block.
492   SmallVector<OpAsmParser::OperandType, LaunchOp::kNumConfigOperands> sizes(
493       LaunchOp::kNumConfigOperands);
494   MutableArrayRef<OpAsmParser::OperandType> sizesRef(sizes);
495 
496   // Actual (data) operands passed to the kernel.
497   SmallVector<OpAsmParser::OperandType, 4> dataOperands;
498 
499   // Region arguments to be created.
500   SmallVector<OpAsmParser::OperandType, 16> regionArgs(
501       LaunchOp::kNumConfigRegionAttributes);
502   MutableArrayRef<OpAsmParser::OperandType> regionArgsRef(regionArgs);
503 
504   // Parse the size assignment segments: the first segment assigns grid sizes
505   // and defines values for block identifiers; the second segment assigns block
506   // sizes and defines values for thread identifiers.  In the region argument
507   // list, identifiers precede sizes, and block-related values precede
508   // thread-related values.
509   if (parser.parseKeyword(LaunchOp::getBlocksKeyword().data()) ||
510       parseSizeAssignment(parser, sizesRef.take_front(3),
511                           regionArgsRef.slice(6, 3),
512                           regionArgsRef.slice(0, 3)) ||
513       parser.parseKeyword(LaunchOp::getThreadsKeyword().data()) ||
514       parseSizeAssignment(parser, sizesRef.drop_front(3),
515                           regionArgsRef.slice(9, 3),
516                           regionArgsRef.slice(3, 3)) ||
517       parser.resolveOperands(sizes, parser.getBuilder().getIndexType(),
518                              result.operands))
519     return failure();
520 
521   // Introduce the body region and parse it. The region has
522   // kNumConfigRegionAttributes arguments that correspond to
523   // block/thread identifiers and grid/block sizes, all of the `index` type.
524   Type index = parser.getBuilder().getIndexType();
525   SmallVector<Type, LaunchOp::kNumConfigRegionAttributes> dataTypes(
526       LaunchOp::kNumConfigRegionAttributes, index);
527   Region *body = result.addRegion();
528   return failure(parser.parseRegion(*body, regionArgs, dataTypes) ||
529                  parser.parseOptionalAttrDict(result.attributes));
530 }
531 
532 //===----------------------------------------------------------------------===//
533 // LaunchFuncOp
534 //===----------------------------------------------------------------------===//
535 
536 void LaunchFuncOp::build(OpBuilder &builder, OperationState &result,
537                          GPUFuncOp kernelFunc, KernelDim3 gridSize,
538                          KernelDim3 blockSize, ValueRange kernelOperands) {
539   // Add grid and block sizes as op operands, followed by the data operands.
540   result.addOperands({gridSize.x, gridSize.y, gridSize.z, blockSize.x,
541                       blockSize.y, blockSize.z});
542   result.addOperands(kernelOperands);
543   auto kernelModule = kernelFunc->getParentOfType<GPUModuleOp>();
544   auto kernelSymbol = builder.getSymbolRefAttr(
545       kernelModule.getName(), {builder.getSymbolRefAttr(kernelFunc.getName())});
546   result.addAttribute(getKernelAttrName(), kernelSymbol);
547   SmallVector<int32_t, 8> segmentSizes(8, 1);
548   segmentSizes.front() = 0; // Initially no async dependencies.
549   segmentSizes.back() = static_cast<int32_t>(kernelOperands.size());
550   result.addAttribute(getOperandSegmentSizeAttr(),
551                       builder.getI32VectorAttr(segmentSizes));
552 }
553 
554 unsigned LaunchFuncOp::getNumKernelOperands() {
555   return getNumOperands() - asyncDependencies().size() - kNumConfigOperands;
556 }
557 
558 StringRef LaunchFuncOp::getKernelModuleName() {
559   return kernel().getRootReference();
560 }
561 
562 StringRef LaunchFuncOp::getKernelName() { return kernel().getLeafReference(); }
563 
564 Value LaunchFuncOp::getKernelOperand(unsigned i) {
565   return getOperand(asyncDependencies().size() + kNumConfigOperands + i);
566 }
567 
568 KernelDim3 LaunchFuncOp::getGridSizeOperandValues() {
569   auto operands = getOperands().drop_front(asyncDependencies().size());
570   return KernelDim3{operands[0], operands[1], operands[2]};
571 }
572 
573 KernelDim3 LaunchFuncOp::getBlockSizeOperandValues() {
574   auto operands = getOperands().drop_front(asyncDependencies().size());
575   return KernelDim3{operands[3], operands[4], operands[5]};
576 }
577 
578 static LogicalResult verify(LaunchFuncOp op) {
579   auto module = op->getParentOfType<ModuleOp>();
580   if (!module)
581     return op.emitOpError("expected to belong to a module");
582 
583   if (!module->getAttrOfType<UnitAttr>(
584           GPUDialect::getContainerModuleAttrName()))
585     return op.emitOpError(
586         "expected the closest surrounding module to have the '" +
587         GPUDialect::getContainerModuleAttrName() + "' attribute");
588 
589   auto kernelAttr = op->getAttrOfType<SymbolRefAttr>(op.getKernelAttrName());
590   if (!kernelAttr)
591     return op.emitOpError("symbol reference attribute '" +
592                           op.getKernelAttrName() + "' must be specified");
593 
594   return success();
595 }
596 
597 static ParseResult
598 parseLaunchFuncOperands(OpAsmParser &parser,
599                         SmallVectorImpl<OpAsmParser::OperandType> &argNames,
600                         SmallVectorImpl<Type> &argTypes) {
601   if (parser.parseOptionalKeyword("args"))
602     return success();
603   SmallVector<NamedAttrList, 4> argAttrs;
604   bool isVariadic = false;
605   return function_like_impl::parseFunctionArgumentList(
606       parser, /*allowAttributes=*/false,
607       /*allowVariadic=*/false, argNames, argTypes, argAttrs, isVariadic);
608 }
609 
610 static void printLaunchFuncOperands(OpAsmPrinter &printer, Operation *,
611                                     OperandRange operands, TypeRange types) {
612   if (operands.empty())
613     return;
614   printer << "args(";
615   llvm::interleaveComma(llvm::zip(operands, types), printer,
616                         [&](const auto &pair) {
617                           printer.printOperand(std::get<0>(pair));
618                           printer << " : ";
619                           printer.printType(std::get<1>(pair));
620                         });
621   printer << ")";
622 }
623 
624 //===----------------------------------------------------------------------===//
625 // GPUFuncOp
626 //===----------------------------------------------------------------------===//
627 
628 /// Adds a new block argument that corresponds to buffers located in
629 /// workgroup memory.
630 BlockArgument GPUFuncOp::addWorkgroupAttribution(Type type) {
631   auto attrName = getNumWorkgroupAttributionsAttrName();
632   auto attr = (*this)->getAttrOfType<IntegerAttr>(attrName);
633   (*this)->setAttr(attrName,
634                    IntegerAttr::get(attr.getType(), attr.getValue() + 1));
635   return getBody().insertArgument(getType().getNumInputs() + attr.getInt(),
636                                   type);
637 }
638 
639 /// Adds a new block argument that corresponds to buffers located in
640 /// private memory.
641 BlockArgument GPUFuncOp::addPrivateAttribution(Type type) {
642   // Buffers on the private memory always come after buffers on the workgroup
643   // memory.
644   return getBody().addArgument(type);
645 }
646 
647 void GPUFuncOp::build(OpBuilder &builder, OperationState &result,
648                       StringRef name, FunctionType type,
649                       TypeRange workgroupAttributions,
650                       TypeRange privateAttributions,
651                       ArrayRef<NamedAttribute> attrs) {
652   result.addAttribute(SymbolTable::getSymbolAttrName(),
653                       builder.getStringAttr(name));
654   result.addAttribute(getTypeAttrName(), TypeAttr::get(type));
655   result.addAttribute(getNumWorkgroupAttributionsAttrName(),
656                       builder.getI64IntegerAttr(workgroupAttributions.size()));
657   result.addAttributes(attrs);
658   Region *body = result.addRegion();
659   Block *entryBlock = new Block;
660   entryBlock->addArguments(type.getInputs());
661   entryBlock->addArguments(workgroupAttributions);
662   entryBlock->addArguments(privateAttributions);
663 
664   body->getBlocks().push_back(entryBlock);
665 }
666 
667 /// Parses a GPU function memory attribution.
668 ///
669 /// memory-attribution ::= (`workgroup` `(` ssa-id-and-type-list `)`)?
670 ///                        (`private` `(` ssa-id-and-type-list `)`)?
671 ///
672 /// Note that this function parses only one of the two similar parts, with the
673 /// keyword provided as argument.
674 static ParseResult
675 parseAttributions(OpAsmParser &parser, StringRef keyword,
676                   SmallVectorImpl<OpAsmParser::OperandType> &args,
677                   SmallVectorImpl<Type> &argTypes) {
678   // If we could not parse the keyword, just assume empty list and succeed.
679   if (failed(parser.parseOptionalKeyword(keyword)))
680     return success();
681 
682   if (failed(parser.parseLParen()))
683     return failure();
684 
685   // Early exit for an empty list.
686   if (succeeded(parser.parseOptionalRParen()))
687     return success();
688 
689   do {
690     OpAsmParser::OperandType arg;
691     Type type;
692 
693     if (parser.parseRegionArgument(arg) || parser.parseColonType(type))
694       return failure();
695 
696     args.push_back(arg);
697     argTypes.push_back(type);
698   } while (succeeded(parser.parseOptionalComma()));
699 
700   return parser.parseRParen();
701 }
702 
703 /// Parses a GPU function.
704 ///
705 /// <operation> ::= `gpu.func` symbol-ref-id `(` argument-list `)`
706 ///                 (`->` function-result-list)? memory-attribution `kernel`?
707 ///                 function-attributes? region
708 static ParseResult parseGPUFuncOp(OpAsmParser &parser, OperationState &result) {
709   SmallVector<OpAsmParser::OperandType, 8> entryArgs;
710   SmallVector<NamedAttrList, 1> argAttrs;
711   SmallVector<NamedAttrList, 1> resultAttrs;
712   SmallVector<Type, 8> argTypes;
713   SmallVector<Type, 4> resultTypes;
714   bool isVariadic;
715 
716   // Parse the function name.
717   StringAttr nameAttr;
718   if (parser.parseSymbolName(nameAttr, ::mlir::SymbolTable::getSymbolAttrName(),
719                              result.attributes))
720     return failure();
721 
722   auto signatureLocation = parser.getCurrentLocation();
723   if (failed(function_like_impl::parseFunctionSignature(
724           parser, /*allowVariadic=*/false, entryArgs, argTypes, argAttrs,
725           isVariadic, resultTypes, resultAttrs)))
726     return failure();
727 
728   if (entryArgs.empty() && !argTypes.empty())
729     return parser.emitError(signatureLocation)
730            << "gpu.func requires named arguments";
731 
732   // Construct the function type. More types will be added to the region, but
733   // not to the function type.
734   Builder &builder = parser.getBuilder();
735   auto type = builder.getFunctionType(argTypes, resultTypes);
736   result.addAttribute(GPUFuncOp::getTypeAttrName(), TypeAttr::get(type));
737 
738   // Parse workgroup memory attributions.
739   if (failed(parseAttributions(parser, GPUFuncOp::getWorkgroupKeyword(),
740                                entryArgs, argTypes)))
741     return failure();
742 
743   // Store the number of operands we just parsed as the number of workgroup
744   // memory attributions.
745   unsigned numWorkgroupAttrs = argTypes.size() - type.getNumInputs();
746   result.addAttribute(GPUFuncOp::getNumWorkgroupAttributionsAttrName(),
747                       builder.getI64IntegerAttr(numWorkgroupAttrs));
748 
749   // Parse private memory attributions.
750   if (failed(parseAttributions(parser, GPUFuncOp::getPrivateKeyword(),
751                                entryArgs, argTypes)))
752     return failure();
753 
754   // Parse the kernel attribute if present.
755   if (succeeded(parser.parseOptionalKeyword(GPUFuncOp::getKernelKeyword())))
756     result.addAttribute(GPUDialect::getKernelFuncAttrName(),
757                         builder.getUnitAttr());
758 
759   // Parse attributes.
760   if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
761     return failure();
762   function_like_impl::addArgAndResultAttrs(builder, result, argAttrs,
763                                            resultAttrs);
764 
765   // Parse the region. If no argument names were provided, take all names
766   // (including those of attributions) from the entry block.
767   auto *body = result.addRegion();
768   return parser.parseRegion(*body, entryArgs, argTypes);
769 }
770 
771 static void printAttributions(OpAsmPrinter &p, StringRef keyword,
772                               ArrayRef<BlockArgument> values) {
773   if (values.empty())
774     return;
775 
776   p << ' ' << keyword << '(';
777   llvm::interleaveComma(
778       values, p, [&p](BlockArgument v) { p << v << " : " << v.getType(); });
779   p << ')';
780 }
781 
782 /// Prints a GPU Func op.
783 static void printGPUFuncOp(OpAsmPrinter &p, GPUFuncOp op) {
784   p << GPUFuncOp::getOperationName() << ' ';
785   p.printSymbolName(op.getName());
786 
787   FunctionType type = op.getType();
788   function_like_impl::printFunctionSignature(
789       p, op.getOperation(), type.getInputs(),
790       /*isVariadic=*/false, type.getResults());
791 
792   printAttributions(p, op.getWorkgroupKeyword(), op.getWorkgroupAttributions());
793   printAttributions(p, op.getPrivateKeyword(), op.getPrivateAttributions());
794   if (op.isKernel())
795     p << ' ' << op.getKernelKeyword();
796 
797   function_like_impl::printFunctionAttributes(
798       p, op.getOperation(), type.getNumInputs(), type.getNumResults(),
799       {op.getNumWorkgroupAttributionsAttrName(),
800        GPUDialect::getKernelFuncAttrName()});
801   p.printRegion(op.getBody(), /*printEntryBlockArgs=*/false);
802 }
803 
804 /// Hook for FunctionLike verifier.
805 LogicalResult GPUFuncOp::verifyType() {
806   Type type = getTypeAttr().getValue();
807   if (!type.isa<FunctionType>())
808     return emitOpError("requires '" + getTypeAttrName() +
809                        "' attribute of function type");
810 
811   if (isKernel() && getType().getNumResults() != 0)
812     return emitOpError() << "expected void return type for kernel function";
813 
814   return success();
815 }
816 
817 static LogicalResult verifyAttributions(Operation *op,
818                                         ArrayRef<BlockArgument> attributions,
819                                         unsigned memorySpace) {
820   for (Value v : attributions) {
821     auto type = v.getType().dyn_cast<MemRefType>();
822     if (!type)
823       return op->emitOpError() << "expected memref type in attribution";
824 
825     if (type.getMemorySpaceAsInt() != memorySpace) {
826       return op->emitOpError()
827              << "expected memory space " << memorySpace << " in attribution";
828     }
829   }
830   return success();
831 }
832 
833 /// Verifies the body of the function.
834 LogicalResult GPUFuncOp::verifyBody() {
835   unsigned numFuncArguments = getNumArguments();
836   unsigned numWorkgroupAttributions = getNumWorkgroupAttributions();
837   unsigned numBlockArguments = front().getNumArguments();
838   if (numBlockArguments < numFuncArguments + numWorkgroupAttributions)
839     return emitOpError() << "expected at least "
840                          << numFuncArguments + numWorkgroupAttributions
841                          << " arguments to body region";
842 
843   ArrayRef<Type> funcArgTypes = getType().getInputs();
844   for (unsigned i = 0; i < numFuncArguments; ++i) {
845     Type blockArgType = front().getArgument(i).getType();
846     if (funcArgTypes[i] != blockArgType)
847       return emitOpError() << "expected body region argument #" << i
848                            << " to be of type " << funcArgTypes[i] << ", got "
849                            << blockArgType;
850   }
851 
852   if (failed(verifyAttributions(getOperation(), getWorkgroupAttributions(),
853                                 GPUDialect::getWorkgroupAddressSpace())) ||
854       failed(verifyAttributions(getOperation(), getPrivateAttributions(),
855                                 GPUDialect::getPrivateAddressSpace())))
856     return failure();
857 
858   return success();
859 }
860 
861 //===----------------------------------------------------------------------===//
862 // ReturnOp
863 //===----------------------------------------------------------------------===//
864 
865 static ParseResult parseReturnOp(OpAsmParser &parser, OperationState &result) {
866   llvm::SmallVector<OpAsmParser::OperandType, 4> operands;
867   llvm::SmallVector<Type, 4> types;
868   if (parser.parseOperandList(operands) ||
869       parser.parseOptionalColonTypeList(types) ||
870       parser.resolveOperands(operands, types, parser.getCurrentLocation(),
871                              result.operands))
872     return failure();
873 
874   return success();
875 }
876 
877 static LogicalResult verify(gpu::ReturnOp returnOp) {
878   GPUFuncOp function = returnOp->getParentOfType<GPUFuncOp>();
879 
880   FunctionType funType = function.getType();
881 
882   if (funType.getNumResults() != returnOp.operands().size())
883     return returnOp.emitOpError()
884         .append("expected ", funType.getNumResults(), " result operands")
885         .attachNote(function.getLoc())
886         .append("return type declared here");
887 
888   for (auto pair : llvm::enumerate(
889            llvm::zip(function.getType().getResults(), returnOp.operands()))) {
890     Type type;
891     Value operand;
892     std::tie(type, operand) = pair.value();
893     if (type != operand.getType())
894       return returnOp.emitOpError() << "unexpected type `" << operand.getType()
895                                     << "' for operand #" << pair.index();
896   }
897   return success();
898 }
899 
900 //===----------------------------------------------------------------------===//
901 // GPUModuleOp
902 //===----------------------------------------------------------------------===//
903 
904 void GPUModuleOp::build(OpBuilder &builder, OperationState &result,
905                         StringRef name) {
906   ensureTerminator(*result.addRegion(), builder, result.location);
907   result.attributes.push_back(builder.getNamedAttr(
908       ::mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(name)));
909 }
910 
911 static ParseResult parseGPUModuleOp(OpAsmParser &parser,
912                                     OperationState &result) {
913   StringAttr nameAttr;
914   if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
915                              result.attributes))
916     return failure();
917 
918   // If module attributes are present, parse them.
919   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
920     return failure();
921 
922   // Parse the module body.
923   auto *body = result.addRegion();
924   if (parser.parseRegion(*body, None, None))
925     return failure();
926 
927   // Ensure that this module has a valid terminator.
928   GPUModuleOp::ensureTerminator(*body, parser.getBuilder(), result.location);
929   return success();
930 }
931 
932 static void print(OpAsmPrinter &p, GPUModuleOp op) {
933   p << op.getOperationName() << ' ';
934   p.printSymbolName(op.getName());
935   p.printOptionalAttrDictWithKeyword(op->getAttrs(),
936                                      {SymbolTable::getSymbolAttrName()});
937   p.printRegion(op->getRegion(0), /*printEntryBlockArgs=*/false,
938                 /*printBlockTerminators=*/false);
939 }
940 
941 //===----------------------------------------------------------------------===//
942 // GPUMemcpyOp
943 //===----------------------------------------------------------------------===//
944 
945 static LogicalResult verify(MemcpyOp op) {
946   auto srcType = op.src().getType();
947   auto dstType = op.dst().getType();
948 
949   if (getElementTypeOrSelf(srcType) != getElementTypeOrSelf(dstType))
950     return op.emitOpError("arguments have incompatible element type");
951 
952   if (failed(verifyCompatibleShape(srcType, dstType)))
953     return op.emitOpError("arguments have incompatible shape");
954 
955   return success();
956 }
957 
958 static ParseResult parseAsyncDependencies(
959     OpAsmParser &parser, Type &asyncTokenType,
960     SmallVectorImpl<OpAsmParser::OperandType> &asyncDependencies) {
961   auto loc = parser.getCurrentLocation();
962   if (succeeded(parser.parseOptionalKeyword("async"))) {
963     if (parser.getNumResults() == 0)
964       return parser.emitError(loc, "needs to be named when marked 'async'");
965     asyncTokenType = parser.getBuilder().getType<AsyncTokenType>();
966   }
967   return parser.parseOperandList(asyncDependencies,
968                                  OpAsmParser::Delimiter::OptionalSquare);
969 }
970 
971 static void printAsyncDependencies(OpAsmPrinter &printer, Operation *op,
972                                    Type asyncTokenType,
973                                    OperandRange asyncDependencies) {
974   if (asyncTokenType)
975     printer << "async ";
976   if (asyncDependencies.empty())
977     return;
978   printer << "[";
979   llvm::interleaveComma(asyncDependencies, printer);
980   printer << "]";
981 }
982 
983 //===----------------------------------------------------------------------===//
984 // GPU_SubgroupMmaLoadMatrixOp
985 //===----------------------------------------------------------------------===//
986 
987 static LogicalResult verify(SubgroupMmaLoadMatrixOp op) {
988   auto srcType = op.srcMemref().getType();
989   auto resType = op.res().getType();
990   auto resMatrixType = resType.cast<gpu::MMAMatrixType>();
991   auto operand = resMatrixType.getOperand();
992   auto srcMemrefType = srcType.cast<MemRefType>();
993   auto srcMemSpace = srcMemrefType.getMemorySpaceAsInt();
994 
995   if (!srcMemrefType.getAffineMaps().empty() &&
996       !srcMemrefType.getAffineMaps().front().isIdentity())
997     return op.emitError("expected identity layout map for source memref");
998 
999   if (srcMemSpace != kGenericMemorySpace && srcMemSpace != kSharedMemorySpace &&
1000       srcMemSpace != kGlobalMemorySpace)
1001     return op.emitError(
1002         "source memorySpace kGenericMemorySpace, kSharedMemorySpace or "
1003         "kGlobalMemorySpace only allowed");
1004 
1005   if (!operand.equals("AOp") && !operand.equals("BOp") &&
1006       !operand.equals("COp"))
1007     return op.emitError("only AOp, BOp and COp can be loaded");
1008 
1009   return success();
1010 }
1011 
1012 //===----------------------------------------------------------------------===//
1013 // GPU_SubgroupMmaStoreMatrixOp
1014 //===----------------------------------------------------------------------===//
1015 
1016 static LogicalResult verify(SubgroupMmaStoreMatrixOp op) {
1017   auto srcType = op.src().getType();
1018   auto dstType = op.dstMemref().getType();
1019   auto srcMatrixType = srcType.cast<gpu::MMAMatrixType>();
1020   auto dstMemrefType = dstType.cast<MemRefType>();
1021   auto dstMemSpace = dstMemrefType.getMemorySpaceAsInt();
1022 
1023   if (!dstMemrefType.getAffineMaps().empty() &&
1024       !dstMemrefType.getAffineMaps().front().isIdentity())
1025     return op.emitError("expected identity layout map for destination memref");
1026 
1027   if (dstMemSpace != kGenericMemorySpace && dstMemSpace != kSharedMemorySpace &&
1028       dstMemSpace != kGlobalMemorySpace)
1029     return op.emitError(
1030         "destination memorySpace of kGenericMemorySpace, "
1031         "kGlobalMemorySpace or kSharedMemorySpace only allowed");
1032 
1033   if (!srcMatrixType.getOperand().equals("COp"))
1034     return op.emitError(
1035         "expected the operand matrix being stored to have 'COp' operand type");
1036 
1037   return success();
1038 }
1039 
1040 //===----------------------------------------------------------------------===//
1041 // GPU_SubgroupMmaComputeOp
1042 //===----------------------------------------------------------------------===//
1043 
1044 static LogicalResult verify(SubgroupMmaComputeOp op) {
1045   enum OperandMap { A, B, C };
1046   SmallVector<MMAMatrixType, 3> opTypes;
1047 
1048   auto populateOpInfo = [&opTypes, &op]() {
1049     opTypes.push_back(op.opA().getType().cast<MMAMatrixType>());
1050     opTypes.push_back(op.opB().getType().cast<MMAMatrixType>());
1051     opTypes.push_back(op.opC().getType().cast<MMAMatrixType>());
1052   };
1053   populateOpInfo();
1054 
1055   if (!opTypes[A].getOperand().equals("AOp") ||
1056       !opTypes[B].getOperand().equals("BOp") ||
1057       !opTypes[C].getOperand().equals("COp"))
1058     return op.emitError("operands must be in the order AOp, BOp, COp");
1059 
1060   ArrayRef<int64_t> aShape, bShape, cShape;
1061   aShape = opTypes[A].getShape();
1062   bShape = opTypes[B].getShape();
1063   cShape = opTypes[C].getShape();
1064 
1065   if (aShape[1] != bShape[0] || aShape[0] != cShape[0] ||
1066       bShape[1] != cShape[1])
1067     return op.emitError("operand shapes do not satisfy matmul constraints");
1068 
1069   return success();
1070 }
1071 
1072 /// This is a common class used for patterns of the form
1073 /// "someop(memrefcast) -> someop".  It folds the source of any memref.cast
1074 /// into the root operation directly.
1075 static LogicalResult foldMemRefCast(Operation *op) {
1076   bool folded = false;
1077   for (OpOperand &operand : op->getOpOperands()) {
1078     auto cast = operand.get().getDefiningOp<mlir::memref::CastOp>();
1079     if (cast) {
1080       operand.set(cast.getOperand());
1081       folded = true;
1082     }
1083   }
1084   return success(folded);
1085 }
1086 
1087 LogicalResult MemcpyOp::fold(ArrayRef<Attribute> operands,
1088                              SmallVectorImpl<::mlir::OpFoldResult> &results) {
1089   return foldMemRefCast(*this);
1090 }
1091 
1092 #include "mlir/Dialect/GPU/GPUOpInterfaces.cpp.inc"
1093 
1094 #define GET_OP_CLASSES
1095 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
1096