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/Arithmetic/IR/Arithmetic.h"
16 #include "mlir/Dialect/MemRef/IR/MemRef.h"
17 #include "mlir/IR/Attributes.h"
18 #include "mlir/IR/Builders.h"
19 #include "mlir/IR/BuiltinOps.h"
20 #include "mlir/IR/BuiltinTypes.h"
21 #include "mlir/IR/DialectImplementation.h"
22 #include "mlir/IR/FunctionImplementation.h"
23 #include "mlir/IR/Matchers.h"
24 #include "mlir/IR/OpImplementation.h"
25 #include "mlir/IR/PatternMatch.h"
26 #include "mlir/IR/TypeUtilities.h"
27 #include "mlir/Transforms/InliningUtils.h"
28 #include "llvm/ADT/TypeSwitch.h"
29 
30 using namespace mlir;
31 using namespace mlir::gpu;
32 
33 #include "mlir/Dialect/GPU/GPUOpsDialect.cpp.inc"
34 
35 //===----------------------------------------------------------------------===//
36 // MMAMatrixType
37 //===----------------------------------------------------------------------===//
38 
39 MMAMatrixType MMAMatrixType::get(ArrayRef<int64_t> shape, Type elementType,
40                                  StringRef operand) {
41   return Base::get(elementType.getContext(), shape, elementType, operand);
42 }
43 
44 MMAMatrixType
45 MMAMatrixType::getChecked(function_ref<InFlightDiagnostic()> emitError,
46                           ArrayRef<int64_t> shape, Type elementType,
47                           StringRef operand) {
48   return Base::getChecked(emitError, elementType.getContext(), shape,
49                           elementType, operand);
50 }
51 
52 unsigned MMAMatrixType::getNumDims() const { return getImpl()->numDims; }
53 
54 ArrayRef<int64_t> MMAMatrixType::getShape() const {
55   return getImpl()->getShape();
56 }
57 
58 Type MMAMatrixType::getElementType() const { return getImpl()->elementType; }
59 
60 StringRef MMAMatrixType::getOperand() const { return getImpl()->getOperand(); }
61 
62 bool MMAMatrixType::isValidElementType(Type elementType) {
63   return elementType.isF16() || elementType.isF32();
64 }
65 
66 LogicalResult
67 MMAMatrixType::verify(function_ref<InFlightDiagnostic()> emitError,
68                       ArrayRef<int64_t> shape, Type elementType,
69                       StringRef operand) {
70   if (!operand.equals("AOp") && !operand.equals("BOp") &&
71       !operand.equals("COp"))
72     return emitError() << "operand expected to be one of AOp, BOp or COp";
73 
74   if (shape.size() != 2)
75     return emitError() << "MMAMatrixType must have exactly two dimensions";
76 
77   if (!MMAMatrixType::isValidElementType(elementType))
78     return emitError() << "MMAMatrixType elements must be F16 or F32";
79 
80   return success();
81 }
82 
83 //===----------------------------------------------------------------------===//
84 // GPUDialect
85 //===----------------------------------------------------------------------===//
86 
87 /// GPU memory space identifiers.
88 enum GPUMemorySpace {
89   /// Generic memory space identifier.
90   kGenericMemorySpace = 0,
91 
92   /// Global memory space identifier.
93   kGlobalMemorySpace = 1,
94 
95   /// Shared memory space identifier.
96   kSharedMemorySpace = 3
97 };
98 
99 bool GPUDialect::isKernel(Operation *op) {
100   UnitAttr isKernelAttr = op->getAttrOfType<UnitAttr>(getKernelFuncAttrName());
101   return static_cast<bool>(isKernelAttr);
102 }
103 
104 namespace {
105 /// This class defines the interface for handling inlining with gpu
106 /// operations.
107 struct GPUInlinerInterface : public DialectInlinerInterface {
108   using DialectInlinerInterface::DialectInlinerInterface;
109 
110   /// All gpu dialect ops can be inlined.
111   bool isLegalToInline(Operation *, Region *, bool,
112                        BlockAndValueMapping &) const final {
113     return true;
114   }
115 };
116 } // namespace
117 
118 void GPUDialect::initialize() {
119   addTypes<AsyncTokenType>();
120   addTypes<DeviceAsyncTokenType>();
121   addTypes<MMAMatrixType>();
122   addOperations<
123 #define GET_OP_LIST
124 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
125       >();
126   addAttributes<
127 #define GET_ATTRDEF_LIST
128 #include "mlir/Dialect/GPU/GPUOpsAttributes.cpp.inc"
129       >();
130   addInterfaces<GPUInlinerInterface>();
131 }
132 
133 Type GPUDialect::parseType(DialectAsmParser &parser) const {
134   // Parse the main keyword for the type.
135   StringRef keyword;
136   if (parser.parseKeyword(&keyword))
137     return Type();
138   MLIRContext *context = getContext();
139 
140   // Handle 'async token' types.
141   if (keyword == "async.token")
142     return AsyncTokenType::get(context);
143   // Handle 'device async token' types.
144   if (keyword == "device.async.token")
145     return DeviceAsyncTokenType::get(context);
146 
147   if (keyword == "mma_matrix") {
148     SMLoc beginLoc = parser.getNameLoc();
149 
150     // Parse '<'.
151     if (parser.parseLess())
152       return nullptr;
153 
154     // Parse the size and elementType.
155     SmallVector<int64_t> shape;
156     Type elementType;
157     if (parser.parseDimensionList(shape, /*allowDynamic=*/false) ||
158         parser.parseType(elementType))
159       return nullptr;
160 
161     // Parse ','
162     if (parser.parseComma())
163       return nullptr;
164 
165     // Parse operand.
166     std::string operand;
167     if (failed(parser.parseOptionalString(&operand)))
168       return nullptr;
169 
170     // Parse '>'.
171     if (parser.parseGreater())
172       return nullptr;
173 
174     return MMAMatrixType::getChecked(mlir::detail::getDefaultDiagnosticEmitFn(
175                                          parser.getEncodedSourceLoc(beginLoc)),
176                                      shape, elementType, operand);
177   }
178 
179   parser.emitError(parser.getNameLoc(), "unknown gpu type: " + keyword);
180   return Type();
181 }
182 
183 void GPUDialect::printType(Type type, DialectAsmPrinter &os) const {
184   TypeSwitch<Type>(type)
185       .Case<AsyncTokenType>([&](Type) { os << "async.token"; })
186       .Case<DeviceAsyncTokenType>([&](Type) { os << "device.async.token"; })
187       .Case<MMAMatrixType>([&](MMAMatrixType fragTy) {
188         os << "mma_matrix<";
189         auto shape = fragTy.getShape();
190         for (auto dim = shape.begin(), e = shape.end() - 1; dim != e; ++dim)
191           os << *dim << 'x';
192         os << shape.back() << 'x' << fragTy.getElementType();
193         os << ", \"" << fragTy.getOperand() << "\"" << '>';
194       })
195       .Default([](Type) { llvm_unreachable("unexpected 'gpu' type kind"); });
196 }
197 
198 LogicalResult GPUDialect::verifyOperationAttribute(Operation *op,
199                                                    NamedAttribute attr) {
200   if (!attr.getValue().isa<UnitAttr>() ||
201       attr.getName() != getContainerModuleAttrName())
202     return success();
203 
204   auto module = dyn_cast<ModuleOp>(op);
205   if (!module)
206     return op->emitError("expected '")
207            << getContainerModuleAttrName() << "' attribute to be attached to '"
208            << ModuleOp::getOperationName() << '\'';
209 
210   auto walkResult = module.walk([&module](LaunchFuncOp launchOp) -> WalkResult {
211     // Ignore launches that are nested more or less deep than functions in the
212     // module we are currently checking.
213     if (!launchOp->getParentOp() ||
214         launchOp->getParentOp()->getParentOp() != module)
215       return success();
216 
217     // Ignore launch ops with missing attributes here. The errors will be
218     // reported by the verifiers of those ops.
219     if (!launchOp->getAttrOfType<SymbolRefAttr>(
220             LaunchFuncOp::getKernelAttrName()))
221       return success();
222 
223     // Check that `launch_func` refers to a well-formed GPU kernel module.
224     StringAttr kernelModuleName = launchOp.getKernelModuleName();
225     auto kernelModule = module.lookupSymbol<GPUModuleOp>(kernelModuleName);
226     if (!kernelModule)
227       return launchOp.emitOpError()
228              << "kernel module '" << kernelModuleName.getValue()
229              << "' is undefined";
230 
231     // Check that `launch_func` refers to a well-formed kernel function.
232     Operation *kernelFunc = module.lookupSymbol(launchOp.kernelAttr());
233     if (!kernelFunc)
234       return launchOp.emitOpError("kernel function '")
235              << launchOp.kernel() << "' is undefined";
236     auto kernelConvertedFunction = dyn_cast<FunctionOpInterface>(kernelFunc);
237     if (!kernelConvertedFunction) {
238       InFlightDiagnostic diag = launchOp.emitOpError()
239                                 << "referenced kernel '" << launchOp.kernel()
240                                 << "' is not a function";
241       diag.attachNote(kernelFunc->getLoc()) << "see the kernel definition here";
242       return diag;
243     }
244 
245     if (!kernelFunc->getAttrOfType<mlir::UnitAttr>(
246             GPUDialect::getKernelFuncAttrName()))
247       return launchOp.emitOpError("kernel function is missing the '")
248              << GPUDialect::getKernelFuncAttrName() << "' attribute";
249 
250     // TODO: If the kernel isn't a GPU function (which happens during separate
251     // compilation), do not check type correspondence as it would require the
252     // verifier to be aware of the type conversion.
253     auto kernelGPUFunction = dyn_cast<gpu::GPUFuncOp>(kernelFunc);
254     if (!kernelGPUFunction)
255       return success();
256 
257     unsigned actualNumArguments = launchOp.getNumKernelOperands();
258     unsigned expectedNumArguments = kernelGPUFunction.getNumArguments();
259     if (expectedNumArguments != actualNumArguments)
260       return launchOp.emitOpError("got ")
261              << actualNumArguments << " kernel operands but expected "
262              << expectedNumArguments;
263 
264     auto functionType = kernelGPUFunction.getFunctionType();
265     for (unsigned i = 0; i < expectedNumArguments; ++i) {
266       if (launchOp.getKernelOperand(i).getType() != functionType.getInput(i)) {
267         return launchOp.emitOpError("type of function argument ")
268                << i << " does not match";
269       }
270     }
271 
272     return success();
273   });
274 
275   return walkResult.wasInterrupted() ? failure() : success();
276 }
277 
278 /// Parses an optional list of async operands with an optional leading keyword.
279 /// (`async`)? (`[` ssa-id-list `]`)?
280 ///
281 /// This method is used by the tablegen assembly format for async ops as well.
282 static ParseResult parseAsyncDependencies(
283     OpAsmParser &parser, Type &asyncTokenType,
284     SmallVectorImpl<OpAsmParser::UnresolvedOperand> &asyncDependencies) {
285   auto loc = parser.getCurrentLocation();
286   if (succeeded(parser.parseOptionalKeyword("async"))) {
287     if (parser.getNumResults() == 0)
288       return parser.emitError(loc, "needs to be named when marked 'async'");
289     asyncTokenType = parser.getBuilder().getType<AsyncTokenType>();
290   }
291   return parser.parseOperandList(asyncDependencies,
292                                  OpAsmParser::Delimiter::OptionalSquare);
293 }
294 
295 /// Prints optional async dependencies with its leading keyword.
296 ///   (`async`)? (`[` ssa-id-list `]`)?
297 // Used by the tablegen assembly format for several async ops.
298 static void printAsyncDependencies(OpAsmPrinter &printer, Operation *op,
299                                    Type asyncTokenType,
300                                    OperandRange asyncDependencies) {
301   if (asyncTokenType)
302     printer << "async";
303   if (asyncDependencies.empty())
304     return;
305   if (asyncTokenType)
306     printer << ' ';
307   printer << '[';
308   llvm::interleaveComma(asyncDependencies, printer);
309   printer << ']';
310 }
311 
312 //===----------------------------------------------------------------------===//
313 // AllReduceOp
314 //===----------------------------------------------------------------------===//
315 
316 LogicalResult gpu::AllReduceOp::verifyRegions() {
317   if (body().empty() != op().hasValue())
318     return emitError("expected either an op attribute or a non-empty body");
319   if (!body().empty()) {
320     if (body().getNumArguments() != 2)
321       return emitError("expected two region arguments");
322     for (auto argument : body().getArguments()) {
323       if (argument.getType() != getType())
324         return emitError("incorrect region argument type");
325     }
326     unsigned yieldCount = 0;
327     for (Block &block : body()) {
328       if (auto yield = dyn_cast<gpu::YieldOp>(block.getTerminator())) {
329         if (yield.getNumOperands() != 1)
330           return emitError("expected one gpu.yield operand");
331         if (yield.getOperand(0).getType() != getType())
332           return emitError("incorrect gpu.yield type");
333         ++yieldCount;
334       }
335     }
336     if (yieldCount == 0)
337       return emitError("expected gpu.yield op in region");
338   } else {
339     gpu::AllReduceOperation opName = *op();
340     if ((opName == gpu::AllReduceOperation::AND ||
341          opName == gpu::AllReduceOperation::OR ||
342          opName == gpu::AllReduceOperation::XOR) &&
343         !getType().isa<IntegerType>()) {
344       return emitError()
345              << '`' << gpu::stringifyAllReduceOperation(opName)
346              << "` accumulator is only compatible with Integer type";
347     }
348   }
349   return success();
350 }
351 
352 // TODO: Support optional custom attributes (without dialect prefix).
353 static ParseResult parseAllReduceOperation(AsmParser &parser,
354                                            AllReduceOperationAttr &attr) {
355   StringRef enumStr;
356   if (!parser.parseOptionalKeyword(&enumStr)) {
357     Optional<AllReduceOperation> op = gpu::symbolizeAllReduceOperation(enumStr);
358     if (!op)
359       return parser.emitError(parser.getCurrentLocation(), "invalid op kind");
360     attr = AllReduceOperationAttr::get(parser.getContext(), *op);
361   }
362   return success();
363 }
364 
365 static void printAllReduceOperation(AsmPrinter &printer, Operation *op,
366                                     AllReduceOperationAttr attr) {
367   if (attr)
368     attr.print(printer);
369 }
370 
371 //===----------------------------------------------------------------------===//
372 // AsyncOpInterface
373 //===----------------------------------------------------------------------===//
374 
375 void gpu::addAsyncDependency(Operation *op, Value token) {
376   op->insertOperands(0, {token});
377   if (!op->template hasTrait<OpTrait::AttrSizedOperandSegments>())
378     return;
379   auto attrName =
380       OpTrait::AttrSizedOperandSegments<void>::getOperandSegmentSizeAttr();
381   auto sizeAttr = op->template getAttrOfType<DenseIntElementsAttr>(attrName);
382 
383   // Async dependencies is the only variadic operand.
384   if (!sizeAttr)
385     return;
386 
387   SmallVector<int32_t, 8> sizes(sizeAttr.getValues<int32_t>());
388   ++sizes.front();
389   op->setAttr(attrName, Builder(op->getContext()).getI32VectorAttr(sizes));
390 }
391 
392 //===----------------------------------------------------------------------===//
393 // LaunchOp
394 //===----------------------------------------------------------------------===//
395 
396 void LaunchOp::build(OpBuilder &builder, OperationState &result,
397                      Value gridSizeX, Value gridSizeY, Value gridSizeZ,
398                      Value blockSizeX, Value blockSizeY, Value blockSizeZ,
399                      Value dynamicSharedMemorySize, Type asyncTokenType,
400                      ValueRange asyncDependencies) {
401   result.addOperands(asyncDependencies);
402   if (asyncTokenType)
403     result.types.push_back(builder.getType<AsyncTokenType>());
404 
405   // Add grid and block sizes as op operands, followed by the data operands.
406   result.addOperands(
407       {gridSizeX, gridSizeY, gridSizeZ, blockSizeX, blockSizeY, blockSizeZ});
408   if (dynamicSharedMemorySize)
409     result.addOperands(dynamicSharedMemorySize);
410 
411   // Create a kernel body region with kNumConfigRegionAttributes + N arguments,
412   // where the first kNumConfigRegionAttributes arguments have `index` type and
413   // the rest have the same types as the data operands.
414   Region *kernelRegion = result.addRegion();
415   Block *body = new Block();
416   for (unsigned i = 0; i < kNumConfigRegionAttributes; ++i)
417     body->addArgument(builder.getIndexType(), result.location);
418   kernelRegion->push_back(body);
419   SmallVector<int32_t, 8> segmentSizes(8, 1);
420   segmentSizes.front() = asyncDependencies.size();
421   segmentSizes.back() = dynamicSharedMemorySize ? 1 : 0;
422   result.addAttribute(getOperandSegmentSizeAttr(),
423                       builder.getI32VectorAttr(segmentSizes));
424 }
425 
426 KernelDim3 LaunchOp::getBlockIds() {
427   assert(!body().empty() && "LaunchOp body must not be empty.");
428   auto args = body().getArguments();
429   return KernelDim3{args[0], args[1], args[2]};
430 }
431 
432 KernelDim3 LaunchOp::getThreadIds() {
433   assert(!body().empty() && "LaunchOp body must not be empty.");
434   auto args = body().getArguments();
435   return KernelDim3{args[3], args[4], args[5]};
436 }
437 
438 KernelDim3 LaunchOp::getGridSize() {
439   assert(!body().empty() && "LaunchOp body must not be empty.");
440   auto args = body().getArguments();
441   return KernelDim3{args[6], args[7], args[8]};
442 }
443 
444 KernelDim3 LaunchOp::getBlockSize() {
445   assert(!body().empty() && "LaunchOp body must not be empty.");
446   auto args = body().getArguments();
447   return KernelDim3{args[9], args[10], args[11]};
448 }
449 
450 KernelDim3 LaunchOp::getGridSizeOperandValues() {
451   auto operands = getOperands().drop_front(asyncDependencies().size());
452   return KernelDim3{operands[0], operands[1], operands[2]};
453 }
454 
455 KernelDim3 LaunchOp::getBlockSizeOperandValues() {
456   auto operands = getOperands().drop_front(asyncDependencies().size());
457   return KernelDim3{operands[3], operands[4], operands[5]};
458 }
459 
460 LogicalResult LaunchOp::verifyRegions() {
461   // Kernel launch takes kNumConfigOperands leading operands for grid/block
462   // sizes and transforms them into kNumConfigRegionAttributes region arguments
463   // for block/thread identifiers and grid/block sizes.
464   if (!body().empty()) {
465     if (body().getNumArguments() !=
466         LaunchOp::kNumConfigOperands + getNumOperands() -
467             (dynamicSharedMemorySize() ? 1 : 0) - asyncDependencies().size())
468       return emitOpError("unexpected number of region arguments");
469   }
470 
471   // Block terminators without successors are expected to exit the kernel region
472   // and must be `gpu.terminator`.
473   for (Block &block : body()) {
474     if (block.empty())
475       continue;
476     if (block.back().getNumSuccessors() != 0)
477       continue;
478     if (!isa<gpu::TerminatorOp>(&block.back())) {
479       return block.back()
480           .emitError()
481           .append("expected '", gpu::TerminatorOp::getOperationName(),
482                   "' or a terminator with successors")
483           .attachNote(getLoc())
484           .append("in '", LaunchOp::getOperationName(), "' body region");
485     }
486   }
487 
488   if (getNumResults() == 0 && asyncToken())
489     return emitOpError("needs to be named when async keyword is specified");
490 
491   return success();
492 }
493 
494 // Pretty-print the kernel grid/block size assignment as
495 //   (%iter-x, %iter-y, %iter-z) in
496 //   (%size-x = %ssa-use, %size-y = %ssa-use, %size-z = %ssa-use)
497 // where %size-* and %iter-* will correspond to the body region arguments.
498 static void printSizeAssignment(OpAsmPrinter &p, KernelDim3 size,
499                                 KernelDim3 operands, KernelDim3 ids) {
500   p << '(' << ids.x << ", " << ids.y << ", " << ids.z << ") in (";
501   p << size.x << " = " << operands.x << ", ";
502   p << size.y << " = " << operands.y << ", ";
503   p << size.z << " = " << operands.z << ')';
504 }
505 
506 void LaunchOp::print(OpAsmPrinter &p) {
507   if (asyncToken()) {
508     p << " async";
509     if (!asyncDependencies().empty())
510       p << " [" << asyncDependencies() << ']';
511   }
512   // Print the launch configuration.
513   p << ' ' << getBlocksKeyword();
514   printSizeAssignment(p, getGridSize(), getGridSizeOperandValues(),
515                       getBlockIds());
516   p << ' ' << getThreadsKeyword();
517   printSizeAssignment(p, getBlockSize(), getBlockSizeOperandValues(),
518                       getThreadIds());
519   if (dynamicSharedMemorySize())
520     p << ' ' << getDynamicSharedMemorySizeKeyword() << ' '
521       << dynamicSharedMemorySize();
522 
523   p << ' ';
524   p.printRegion(body(), /*printEntryBlockArgs=*/false);
525   p.printOptionalAttrDict((*this)->getAttrs(), /*elidedAttrs=*/{
526                               LaunchOp::getOperandSegmentSizeAttr()});
527 }
528 
529 // Parse the size assignment blocks for blocks and threads.  These have the form
530 //   (%region_arg, %region_arg, %region_arg) in
531 //   (%region_arg = %operand, %region_arg = %operand, %region_arg = %operand)
532 // where %region_arg are percent-identifiers for the region arguments to be
533 // introduced further (SSA defs), and %operand are percent-identifiers for the
534 // SSA value uses.
535 static ParseResult
536 parseSizeAssignment(OpAsmParser &parser,
537                     MutableArrayRef<OpAsmParser::UnresolvedOperand> sizes,
538                     MutableArrayRef<OpAsmParser::UnresolvedOperand> regionSizes,
539                     MutableArrayRef<OpAsmParser::UnresolvedOperand> indices) {
540   assert(indices.size() == 3 && "space for three indices expected");
541   SmallVector<OpAsmParser::UnresolvedOperand, 3> args;
542   if (parser.parseOperandList(args, OpAsmParser::Delimiter::Paren,
543                               /*allowResultNumber=*/false) ||
544       parser.parseKeyword("in") || parser.parseLParen())
545     return failure();
546   std::move(args.begin(), args.end(), indices.begin());
547 
548   for (int i = 0; i < 3; ++i) {
549     if (i != 0 && parser.parseComma())
550       return failure();
551     if (parser.parseOperand(regionSizes[i], /*allowResultNumber=*/false) ||
552         parser.parseEqual() || parser.parseOperand(sizes[i]))
553       return failure();
554   }
555 
556   return parser.parseRParen();
557 }
558 
559 /// Parses a Launch operation.
560 /// operation ::= `gpu.launch` (`async` `[` ssa-id-list `]`)?
561 //        `blocks` `(` ssa-id-list `)` `in` ssa-reassignment
562 ///       `threads` `(` ssa-id-list `)` `in` ssa-reassignment
563 ///       region attr-dict?
564 /// ssa-reassignment ::= `(` ssa-id `=` ssa-use (`,` ssa-id `=` ssa-use)* `)`
565 ParseResult LaunchOp::parse(OpAsmParser &parser, OperationState &result) {
566   // Sizes of the grid and block.
567   SmallVector<OpAsmParser::UnresolvedOperand, LaunchOp::kNumConfigOperands>
568       sizes(LaunchOp::kNumConfigOperands);
569   MutableArrayRef<OpAsmParser::UnresolvedOperand> sizesRef(sizes);
570 
571   // Actual (data) operands passed to the kernel.
572   SmallVector<OpAsmParser::UnresolvedOperand, 4> dataOperands;
573 
574   // Region arguments to be created.
575   SmallVector<OpAsmParser::UnresolvedOperand, 16> regionArgs(
576       LaunchOp::kNumConfigRegionAttributes);
577   MutableArrayRef<OpAsmParser::UnresolvedOperand> regionArgsRef(regionArgs);
578 
579   // Parse optional async dependencies.
580   SmallVector<OpAsmParser::UnresolvedOperand, 4> asyncDependencies;
581   Type asyncTokenType;
582   if (failed(
583           parseAsyncDependencies(parser, asyncTokenType, asyncDependencies)) ||
584       parser.resolveOperands(asyncDependencies, asyncTokenType,
585                              result.operands))
586     return failure();
587   if (parser.getNumResults() > 0)
588     result.types.push_back(asyncTokenType);
589 
590   // Parse the size assignment segments: the first segment assigns grid sizes
591   // and defines values for block identifiers; the second segment assigns block
592   // sizes and defines values for thread identifiers.  In the region argument
593   // list, identifiers precede sizes, and block-related values precede
594   // thread-related values.
595   if (parser.parseKeyword(LaunchOp::getBlocksKeyword().data()) ||
596       parseSizeAssignment(parser, sizesRef.take_front(3),
597                           regionArgsRef.slice(6, 3),
598                           regionArgsRef.slice(0, 3)) ||
599       parser.parseKeyword(LaunchOp::getThreadsKeyword().data()) ||
600       parseSizeAssignment(parser, sizesRef.drop_front(3),
601                           regionArgsRef.slice(9, 3),
602                           regionArgsRef.slice(3, 3)) ||
603       parser.resolveOperands(sizes, parser.getBuilder().getIndexType(),
604                              result.operands))
605     return failure();
606 
607   OpAsmParser::UnresolvedOperand dynamicSharedMemorySize;
608   bool hasDynamicSharedMemorySize = false;
609   if (!parser.parseOptionalKeyword(
610           LaunchOp::getDynamicSharedMemorySizeKeyword())) {
611     hasDynamicSharedMemorySize = true;
612     if (parser.parseOperand(dynamicSharedMemorySize) ||
613         parser.resolveOperand(dynamicSharedMemorySize,
614                               parser.getBuilder().getI32Type(),
615                               result.operands))
616       return failure();
617   }
618 
619   // Introduce the body region and parse it. The region has
620   // kNumConfigRegionAttributes arguments that correspond to
621   // block/thread identifiers and grid/block sizes, all of the `index` type.
622   Type index = parser.getBuilder().getIndexType();
623   SmallVector<Type, LaunchOp::kNumConfigRegionAttributes> dataTypes(
624       LaunchOp::kNumConfigRegionAttributes, index);
625   Region *body = result.addRegion();
626   if (parser.parseRegion(*body, regionArgs, dataTypes) ||
627       parser.parseOptionalAttrDict(result.attributes))
628     return failure();
629 
630   SmallVector<int32_t, 8> segmentSizes(8, 1);
631   segmentSizes.front() = asyncDependencies.size();
632   segmentSizes.back() = hasDynamicSharedMemorySize ? 1 : 0;
633   result.addAttribute(LaunchOp::getOperandSegmentSizeAttr(),
634                       parser.getBuilder().getI32VectorAttr(segmentSizes));
635   return success();
636 }
637 
638 /// Simplify the gpu.launch when the range of a thread or block ID is
639 /// trivially known to be one.
640 struct FoldLaunchArguments : public OpRewritePattern<LaunchOp> {
641   using OpRewritePattern<LaunchOp>::OpRewritePattern;
642   LogicalResult matchAndRewrite(LaunchOp op,
643                                 PatternRewriter &rewriter) const override {
644     // If the range implies a single value for `id`, replace `id`'s uses by
645     // zero.
646     Value zero;
647     bool simplified = false;
648     auto constPropIdUses = [&](Value id, Value size) {
649       // Check if size is trivially one.
650       if (!matchPattern(size, m_One()))
651         return;
652       if (!simplified) {
653         // Create a zero value the first time.
654         OpBuilder::InsertionGuard guard(rewriter);
655         rewriter.setInsertionPointToStart(&op.body().front());
656         zero =
657             rewriter.create<arith::ConstantIndexOp>(op.getLoc(), /*value=*/0);
658       }
659       id.replaceAllUsesWith(zero);
660       simplified = true;
661     };
662     constPropIdUses(op.getBlockIds().x, op.gridSizeX());
663     constPropIdUses(op.getBlockIds().y, op.gridSizeY());
664     constPropIdUses(op.getBlockIds().z, op.gridSizeZ());
665     constPropIdUses(op.getThreadIds().x, op.blockSizeX());
666     constPropIdUses(op.getThreadIds().y, op.blockSizeY());
667     constPropIdUses(op.getThreadIds().z, op.blockSizeZ());
668 
669     return success(simplified);
670   }
671 };
672 
673 void LaunchOp::getCanonicalizationPatterns(RewritePatternSet &rewrites,
674                                            MLIRContext *context) {
675   rewrites.add<FoldLaunchArguments>(context);
676 }
677 
678 //===----------------------------------------------------------------------===//
679 // LaunchFuncOp
680 //===----------------------------------------------------------------------===//
681 
682 void LaunchFuncOp::build(OpBuilder &builder, OperationState &result,
683                          GPUFuncOp kernelFunc, KernelDim3 gridSize,
684                          KernelDim3 blockSize, Value dynamicSharedMemorySize,
685                          ValueRange kernelOperands, Type asyncTokenType,
686                          ValueRange asyncDependencies) {
687   result.addOperands(asyncDependencies);
688   if (asyncTokenType)
689     result.types.push_back(builder.getType<AsyncTokenType>());
690 
691   // Add grid and block sizes as op operands, followed by the data operands.
692   result.addOperands({gridSize.x, gridSize.y, gridSize.z, blockSize.x,
693                       blockSize.y, blockSize.z});
694   if (dynamicSharedMemorySize)
695     result.addOperands(dynamicSharedMemorySize);
696   result.addOperands(kernelOperands);
697   auto kernelModule = kernelFunc->getParentOfType<GPUModuleOp>();
698   auto kernelSymbol =
699       SymbolRefAttr::get(kernelModule.getNameAttr(),
700                          {SymbolRefAttr::get(kernelFunc.getNameAttr())});
701   result.addAttribute(getKernelAttrName(), kernelSymbol);
702   SmallVector<int32_t, 9> segmentSizes(9, 1);
703   segmentSizes.front() = asyncDependencies.size();
704   segmentSizes[segmentSizes.size() - 2] = dynamicSharedMemorySize ? 1 : 0;
705   segmentSizes.back() = static_cast<int32_t>(kernelOperands.size());
706   result.addAttribute(getOperandSegmentSizeAttr(),
707                       builder.getI32VectorAttr(segmentSizes));
708 }
709 
710 unsigned LaunchFuncOp::getNumKernelOperands() {
711   return getNumOperands() - asyncDependencies().size() - kNumConfigOperands -
712          (dynamicSharedMemorySize() ? 1 : 0);
713 }
714 
715 StringAttr LaunchFuncOp::getKernelModuleName() {
716   return kernel().getRootReference();
717 }
718 
719 StringAttr LaunchFuncOp::getKernelName() { return kernel().getLeafReference(); }
720 
721 Value LaunchFuncOp::getKernelOperand(unsigned i) {
722   return getOperand(asyncDependencies().size() + kNumConfigOperands +
723                     (dynamicSharedMemorySize() ? 1 : 0) + i);
724 }
725 
726 KernelDim3 LaunchFuncOp::getGridSizeOperandValues() {
727   auto operands = getOperands().drop_front(asyncDependencies().size());
728   return KernelDim3{operands[0], operands[1], operands[2]};
729 }
730 
731 KernelDim3 LaunchFuncOp::getBlockSizeOperandValues() {
732   auto operands = getOperands().drop_front(asyncDependencies().size());
733   return KernelDim3{operands[3], operands[4], operands[5]};
734 }
735 
736 LogicalResult LaunchFuncOp::verify() {
737   auto module = (*this)->getParentOfType<ModuleOp>();
738   if (!module)
739     return emitOpError("expected to belong to a module");
740 
741   if (!module->getAttrOfType<UnitAttr>(
742           GPUDialect::getContainerModuleAttrName()))
743     return emitOpError("expected the closest surrounding module to have the '" +
744                        GPUDialect::getContainerModuleAttrName() +
745                        "' attribute");
746 
747   auto kernelAttr = (*this)->getAttrOfType<SymbolRefAttr>(getKernelAttrName());
748   if (!kernelAttr)
749     return emitOpError("symbol reference attribute '" + getKernelAttrName() +
750                        "' must be specified");
751 
752   return success();
753 }
754 
755 static ParseResult parseLaunchFuncOperands(
756     OpAsmParser &parser,
757     SmallVectorImpl<OpAsmParser::UnresolvedOperand> &argNames,
758     SmallVectorImpl<Type> &argTypes) {
759   if (parser.parseOptionalKeyword("args"))
760     return success();
761   SmallVector<NamedAttrList> argAttrs;
762   bool isVariadic = false;
763   return function_interface_impl::parseFunctionArgumentList(
764       parser, /*allowAttributes=*/false,
765       /*allowVariadic=*/false, argNames, argTypes, argAttrs, isVariadic);
766 }
767 
768 static void printLaunchFuncOperands(OpAsmPrinter &printer, Operation *,
769                                     OperandRange operands, TypeRange types) {
770   if (operands.empty())
771     return;
772   printer << "args(";
773   llvm::interleaveComma(llvm::zip(operands, types), printer,
774                         [&](const auto &pair) {
775                           printer.printOperand(std::get<0>(pair));
776                           printer << " : ";
777                           printer.printType(std::get<1>(pair));
778                         });
779   printer << ")";
780 }
781 
782 //
783 
784 //===----------------------------------------------------------------------===//
785 // ShuffleOp
786 //===----------------------------------------------------------------------===//
787 
788 void ShuffleOp::build(OpBuilder &builder, OperationState &result, Value value,
789                       int32_t offset, int32_t width, ShuffleMode mode) {
790   build(builder, result, value,
791         builder.create<arith::ConstantOp>(result.location,
792                                           builder.getI32IntegerAttr(offset)),
793         builder.create<arith::ConstantOp>(result.location,
794                                           builder.getI32IntegerAttr(width)),
795         mode);
796 }
797 
798 //===----------------------------------------------------------------------===//
799 // GPUFuncOp
800 //===----------------------------------------------------------------------===//
801 
802 /// Adds a new block argument that corresponds to buffers located in
803 /// workgroup memory.
804 BlockArgument GPUFuncOp::addWorkgroupAttribution(Type type, Location loc) {
805   auto attrName = getNumWorkgroupAttributionsAttrName();
806   auto attr = (*this)->getAttrOfType<IntegerAttr>(attrName);
807   (*this)->setAttr(attrName,
808                    IntegerAttr::get(attr.getType(), attr.getValue() + 1));
809   return getBody().insertArgument(
810       getFunctionType().getNumInputs() + attr.getInt(), type, loc);
811 }
812 
813 /// Adds a new block argument that corresponds to buffers located in
814 /// private memory.
815 BlockArgument GPUFuncOp::addPrivateAttribution(Type type, Location loc) {
816   // Buffers on the private memory always come after buffers on the workgroup
817   // memory.
818   return getBody().addArgument(type, loc);
819 }
820 
821 void GPUFuncOp::build(OpBuilder &builder, OperationState &result,
822                       StringRef name, FunctionType type,
823                       TypeRange workgroupAttributions,
824                       TypeRange privateAttributions,
825                       ArrayRef<NamedAttribute> attrs) {
826   result.addAttribute(SymbolTable::getSymbolAttrName(),
827                       builder.getStringAttr(name));
828   result.addAttribute(getTypeAttrName(), TypeAttr::get(type));
829   result.addAttribute(getNumWorkgroupAttributionsAttrName(),
830                       builder.getI64IntegerAttr(workgroupAttributions.size()));
831   result.addAttributes(attrs);
832   Region *body = result.addRegion();
833   Block *entryBlock = new Block;
834 
835   // TODO: Allow passing in proper locations here.
836   for (Type argTy : type.getInputs())
837     entryBlock->addArgument(argTy, result.location);
838   for (Type argTy : workgroupAttributions)
839     entryBlock->addArgument(argTy, result.location);
840   for (Type argTy : privateAttributions)
841     entryBlock->addArgument(argTy, result.location);
842 
843   body->getBlocks().push_back(entryBlock);
844 }
845 
846 /// Parses a GPU function memory attribution.
847 ///
848 /// memory-attribution ::= (`workgroup` `(` ssa-id-and-type-list `)`)?
849 ///                        (`private` `(` ssa-id-and-type-list `)`)?
850 ///
851 /// Note that this function parses only one of the two similar parts, with the
852 /// keyword provided as argument.
853 static ParseResult
854 parseAttributions(OpAsmParser &parser, StringRef keyword,
855                   SmallVectorImpl<OpAsmParser::UnresolvedOperand> &args,
856                   SmallVectorImpl<Type> &argTypes) {
857   // If we could not parse the keyword, just assume empty list and succeed.
858   if (failed(parser.parseOptionalKeyword(keyword)))
859     return success();
860 
861   if (failed(parser.parseLParen()))
862     return failure();
863 
864   // Early exit for an empty list.
865   if (succeeded(parser.parseOptionalRParen()))
866     return success();
867 
868   do {
869     OpAsmParser::UnresolvedOperand arg;
870     Type type;
871 
872     if (parser.parseOperand(arg, /*allowResultNumber=*/false) ||
873         parser.parseColonType(type))
874       return failure();
875 
876     args.push_back(arg);
877     argTypes.push_back(type);
878   } while (succeeded(parser.parseOptionalComma()));
879 
880   return parser.parseRParen();
881 }
882 
883 /// Parses a GPU function.
884 ///
885 /// <operation> ::= `gpu.func` symbol-ref-id `(` argument-list `)`
886 ///                 (`->` function-result-list)? memory-attribution `kernel`?
887 ///                 function-attributes? region
888 ParseResult GPUFuncOp::parse(OpAsmParser &parser, OperationState &result) {
889   SmallVector<OpAsmParser::UnresolvedOperand> entryArgs;
890   SmallVector<NamedAttrList> argAttrs;
891   SmallVector<NamedAttrList> resultAttrs;
892   SmallVector<Type> argTypes;
893   SmallVector<Type> resultTypes;
894   bool isVariadic;
895 
896   // Parse the function name.
897   StringAttr nameAttr;
898   if (parser.parseSymbolName(nameAttr, ::mlir::SymbolTable::getSymbolAttrName(),
899                              result.attributes))
900     return failure();
901 
902   auto signatureLocation = parser.getCurrentLocation();
903   if (failed(function_interface_impl::parseFunctionSignature(
904           parser, /*allowVariadic=*/false, entryArgs, argTypes, argAttrs,
905           isVariadic, resultTypes, resultAttrs)))
906     return failure();
907 
908   if (entryArgs.empty() && !argTypes.empty())
909     return parser.emitError(signatureLocation)
910            << "gpu.func requires named arguments";
911 
912   // Construct the function type. More types will be added to the region, but
913   // not to the function type.
914   Builder &builder = parser.getBuilder();
915   auto type = builder.getFunctionType(argTypes, resultTypes);
916   result.addAttribute(GPUFuncOp::getTypeAttrName(), TypeAttr::get(type));
917 
918   // Parse workgroup memory attributions.
919   if (failed(parseAttributions(parser, GPUFuncOp::getWorkgroupKeyword(),
920                                entryArgs, argTypes)))
921     return failure();
922 
923   // Store the number of operands we just parsed as the number of workgroup
924   // memory attributions.
925   unsigned numWorkgroupAttrs = argTypes.size() - type.getNumInputs();
926   result.addAttribute(GPUFuncOp::getNumWorkgroupAttributionsAttrName(),
927                       builder.getI64IntegerAttr(numWorkgroupAttrs));
928 
929   // Parse private memory attributions.
930   if (failed(parseAttributions(parser, GPUFuncOp::getPrivateKeyword(),
931                                entryArgs, argTypes)))
932     return failure();
933 
934   // Parse the kernel attribute if present.
935   if (succeeded(parser.parseOptionalKeyword(GPUFuncOp::getKernelKeyword())))
936     result.addAttribute(GPUDialect::getKernelFuncAttrName(),
937                         builder.getUnitAttr());
938 
939   // Parse attributes.
940   if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
941     return failure();
942   function_interface_impl::addArgAndResultAttrs(builder, result, argAttrs,
943                                                 resultAttrs);
944 
945   // Parse the region. If no argument names were provided, take all names
946   // (including those of attributions) from the entry block.
947   auto *body = result.addRegion();
948   return parser.parseRegion(*body, entryArgs, argTypes);
949 }
950 
951 static void printAttributions(OpAsmPrinter &p, StringRef keyword,
952                               ArrayRef<BlockArgument> values) {
953   if (values.empty())
954     return;
955 
956   p << ' ' << keyword << '(';
957   llvm::interleaveComma(
958       values, p, [&p](BlockArgument v) { p << v << " : " << v.getType(); });
959   p << ')';
960 }
961 
962 void GPUFuncOp::print(OpAsmPrinter &p) {
963   p << ' ';
964   p.printSymbolName(getName());
965 
966   FunctionType type = getFunctionType();
967   function_interface_impl::printFunctionSignature(p, *this, type.getInputs(),
968                                                   /*isVariadic=*/false,
969                                                   type.getResults());
970 
971   printAttributions(p, getWorkgroupKeyword(), getWorkgroupAttributions());
972   printAttributions(p, getPrivateKeyword(), getPrivateAttributions());
973   if (isKernel())
974     p << ' ' << getKernelKeyword();
975 
976   function_interface_impl::printFunctionAttributes(
977       p, *this, type.getNumInputs(), type.getNumResults(),
978       {getNumWorkgroupAttributionsAttrName(),
979        GPUDialect::getKernelFuncAttrName()});
980   p << ' ';
981   p.printRegion(getBody(), /*printEntryBlockArgs=*/false);
982 }
983 
984 LogicalResult GPUFuncOp::verifyType() {
985   Type type = getFunctionTypeAttr().getValue();
986   if (!type.isa<FunctionType>())
987     return emitOpError("requires '" + getTypeAttrName() +
988                        "' attribute of function type");
989 
990   if (isKernel() && getFunctionType().getNumResults() != 0)
991     return emitOpError() << "expected void return type for kernel function";
992 
993   return success();
994 }
995 
996 static LogicalResult verifyAttributions(Operation *op,
997                                         ArrayRef<BlockArgument> attributions,
998                                         unsigned memorySpace) {
999   for (Value v : attributions) {
1000     auto type = v.getType().dyn_cast<MemRefType>();
1001     if (!type)
1002       return op->emitOpError() << "expected memref type in attribution";
1003 
1004     if (type.getMemorySpaceAsInt() != memorySpace) {
1005       return op->emitOpError()
1006              << "expected memory space " << memorySpace << " in attribution";
1007     }
1008   }
1009   return success();
1010 }
1011 
1012 /// Verifies the body of the function.
1013 LogicalResult GPUFuncOp::verifyBody() {
1014   unsigned numFuncArguments = getNumArguments();
1015   unsigned numWorkgroupAttributions = getNumWorkgroupAttributions();
1016   unsigned numBlockArguments = front().getNumArguments();
1017   if (numBlockArguments < numFuncArguments + numWorkgroupAttributions)
1018     return emitOpError() << "expected at least "
1019                          << numFuncArguments + numWorkgroupAttributions
1020                          << " arguments to body region";
1021 
1022   ArrayRef<Type> funcArgTypes = getFunctionType().getInputs();
1023   for (unsigned i = 0; i < numFuncArguments; ++i) {
1024     Type blockArgType = front().getArgument(i).getType();
1025     if (funcArgTypes[i] != blockArgType)
1026       return emitOpError() << "expected body region argument #" << i
1027                            << " to be of type " << funcArgTypes[i] << ", got "
1028                            << blockArgType;
1029   }
1030 
1031   if (failed(verifyAttributions(getOperation(), getWorkgroupAttributions(),
1032                                 GPUDialect::getWorkgroupAddressSpace())) ||
1033       failed(verifyAttributions(getOperation(), getPrivateAttributions(),
1034                                 GPUDialect::getPrivateAddressSpace())))
1035     return failure();
1036 
1037   return success();
1038 }
1039 
1040 //===----------------------------------------------------------------------===//
1041 // ReturnOp
1042 //===----------------------------------------------------------------------===//
1043 
1044 LogicalResult gpu::ReturnOp::verify() {
1045   GPUFuncOp function = (*this)->getParentOfType<GPUFuncOp>();
1046 
1047   FunctionType funType = function.getFunctionType();
1048 
1049   if (funType.getNumResults() != operands().size())
1050     return emitOpError()
1051         .append("expected ", funType.getNumResults(), " result operands")
1052         .attachNote(function.getLoc())
1053         .append("return type declared here");
1054 
1055   for (const auto &pair : llvm::enumerate(
1056            llvm::zip(function.getFunctionType().getResults(), operands()))) {
1057     Type type;
1058     Value operand;
1059     std::tie(type, operand) = pair.value();
1060     if (type != operand.getType())
1061       return emitOpError() << "unexpected type `" << operand.getType()
1062                            << "' for operand #" << pair.index();
1063   }
1064   return success();
1065 }
1066 
1067 //===----------------------------------------------------------------------===//
1068 // GPUModuleOp
1069 //===----------------------------------------------------------------------===//
1070 
1071 void GPUModuleOp::build(OpBuilder &builder, OperationState &result,
1072                         StringRef name) {
1073   ensureTerminator(*result.addRegion(), builder, result.location);
1074   result.attributes.push_back(builder.getNamedAttr(
1075       ::mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(name)));
1076 }
1077 
1078 ParseResult GPUModuleOp::parse(OpAsmParser &parser, OperationState &result) {
1079   StringAttr nameAttr;
1080   if (parser.parseSymbolName(nameAttr, mlir::SymbolTable::getSymbolAttrName(),
1081                              result.attributes))
1082     return failure();
1083 
1084   // If module attributes are present, parse them.
1085   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
1086     return failure();
1087 
1088   // Parse the module body.
1089   auto *body = result.addRegion();
1090   if (parser.parseRegion(*body, None, None))
1091     return failure();
1092 
1093   // Ensure that this module has a valid terminator.
1094   GPUModuleOp::ensureTerminator(*body, parser.getBuilder(), result.location);
1095   return success();
1096 }
1097 
1098 void GPUModuleOp::print(OpAsmPrinter &p) {
1099   p << ' ';
1100   p.printSymbolName(getName());
1101   p.printOptionalAttrDictWithKeyword((*this)->getAttrs(),
1102                                      {mlir::SymbolTable::getSymbolAttrName()});
1103   p << ' ';
1104   p.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
1105                 /*printBlockTerminators=*/false);
1106 }
1107 
1108 //===----------------------------------------------------------------------===//
1109 // GPUMemcpyOp
1110 //===----------------------------------------------------------------------===//
1111 
1112 LogicalResult MemcpyOp::verify() {
1113   auto srcType = src().getType();
1114   auto dstType = dst().getType();
1115 
1116   if (getElementTypeOrSelf(srcType) != getElementTypeOrSelf(dstType))
1117     return emitOpError("arguments have incompatible element type");
1118 
1119   if (failed(verifyCompatibleShape(srcType, dstType)))
1120     return emitOpError("arguments have incompatible shape");
1121 
1122   return success();
1123 }
1124 
1125 //===----------------------------------------------------------------------===//
1126 // GPU_SubgroupMmaLoadMatrixOp
1127 //===----------------------------------------------------------------------===//
1128 
1129 /// Return true if the last dimension of the MemRefType has unit stride. Also
1130 /// return true for memrefs with no strides.
1131 static bool isLastMemrefDimUnitStride(MemRefType type) {
1132   int64_t offset;
1133   SmallVector<int64_t> strides;
1134   if (failed(getStridesAndOffset(type, strides, offset))) {
1135     return false;
1136   }
1137   return strides.back() == 1;
1138 }
1139 
1140 LogicalResult SubgroupMmaLoadMatrixOp::verify() {
1141   auto srcType = srcMemref().getType();
1142   auto resType = res().getType();
1143   auto resMatrixType = resType.cast<gpu::MMAMatrixType>();
1144   auto operand = resMatrixType.getOperand();
1145   auto srcMemrefType = srcType.cast<MemRefType>();
1146   auto srcMemSpace = srcMemrefType.getMemorySpaceAsInt();
1147 
1148   if (!isLastMemrefDimUnitStride(srcMemrefType))
1149     return emitError(
1150         "expected source memref most minor dim must have unit stride");
1151 
1152   if (srcMemSpace != kGenericMemorySpace && srcMemSpace != kSharedMemorySpace &&
1153       srcMemSpace != kGlobalMemorySpace)
1154     return emitError(
1155         "source memorySpace kGenericMemorySpace, kSharedMemorySpace or "
1156         "kGlobalMemorySpace only allowed");
1157 
1158   if (!operand.equals("AOp") && !operand.equals("BOp") &&
1159       !operand.equals("COp"))
1160     return emitError("only AOp, BOp and COp can be loaded");
1161 
1162   return success();
1163 }
1164 
1165 //===----------------------------------------------------------------------===//
1166 // GPU_SubgroupMmaStoreMatrixOp
1167 //===----------------------------------------------------------------------===//
1168 
1169 LogicalResult SubgroupMmaStoreMatrixOp::verify() {
1170   auto srcType = src().getType();
1171   auto dstType = dstMemref().getType();
1172   auto srcMatrixType = srcType.cast<gpu::MMAMatrixType>();
1173   auto dstMemrefType = dstType.cast<MemRefType>();
1174   auto dstMemSpace = dstMemrefType.getMemorySpaceAsInt();
1175 
1176   if (!isLastMemrefDimUnitStride(dstMemrefType))
1177     return emitError(
1178         "expected destination memref most minor dim must have unit stride");
1179 
1180   if (dstMemSpace != kGenericMemorySpace && dstMemSpace != kSharedMemorySpace &&
1181       dstMemSpace != kGlobalMemorySpace)
1182     return emitError("destination memorySpace of kGenericMemorySpace, "
1183                      "kGlobalMemorySpace or kSharedMemorySpace only allowed");
1184 
1185   if (!srcMatrixType.getOperand().equals("COp"))
1186     return emitError(
1187         "expected the operand matrix being stored to have 'COp' operand type");
1188 
1189   return success();
1190 }
1191 
1192 //===----------------------------------------------------------------------===//
1193 // GPU_SubgroupMmaComputeOp
1194 //===----------------------------------------------------------------------===//
1195 
1196 LogicalResult SubgroupMmaComputeOp::verify() {
1197   enum OperandMap { A, B, C };
1198   SmallVector<MMAMatrixType, 3> opTypes;
1199   opTypes.push_back(opA().getType().cast<MMAMatrixType>());
1200   opTypes.push_back(opB().getType().cast<MMAMatrixType>());
1201   opTypes.push_back(opC().getType().cast<MMAMatrixType>());
1202 
1203   if (!opTypes[A].getOperand().equals("AOp") ||
1204       !opTypes[B].getOperand().equals("BOp") ||
1205       !opTypes[C].getOperand().equals("COp"))
1206     return emitError("operands must be in the order AOp, BOp, COp");
1207 
1208   ArrayRef<int64_t> aShape, bShape, cShape;
1209   aShape = opTypes[A].getShape();
1210   bShape = opTypes[B].getShape();
1211   cShape = opTypes[C].getShape();
1212 
1213   if (aShape[1] != bShape[0] || aShape[0] != cShape[0] ||
1214       bShape[1] != cShape[1])
1215     return emitError("operand shapes do not satisfy matmul constraints");
1216 
1217   return success();
1218 }
1219 
1220 /// This is a common class used for patterns of the form
1221 /// "someop(memrefcast) -> someop".  It folds the source of any memref.cast
1222 /// into the root operation directly.
1223 static LogicalResult foldMemRefCast(Operation *op) {
1224   bool folded = false;
1225   for (OpOperand &operand : op->getOpOperands()) {
1226     auto cast = operand.get().getDefiningOp<mlir::memref::CastOp>();
1227     if (cast) {
1228       operand.set(cast.getOperand());
1229       folded = true;
1230     }
1231   }
1232   return success(folded);
1233 }
1234 
1235 LogicalResult MemcpyOp::fold(ArrayRef<Attribute> operands,
1236                              SmallVectorImpl<::mlir::OpFoldResult> &results) {
1237   return foldMemRefCast(*this);
1238 }
1239 
1240 LogicalResult MemsetOp::fold(ArrayRef<Attribute> operands,
1241                              SmallVectorImpl<::mlir::OpFoldResult> &results) {
1242   return foldMemRefCast(*this);
1243 }
1244 
1245 //===----------------------------------------------------------------------===//
1246 // GPU_WaitOp
1247 //===----------------------------------------------------------------------===//
1248 
1249 namespace {
1250 
1251 /// Remove gpu.wait op use of gpu.wait op def without async dependencies.
1252 /// %t = gpu.wait async []       // No async dependencies.
1253 /// ...  gpu.wait ... [%t, ...]  // %t can be removed.
1254 struct EraseRedundantGpuWaitOpPairs : public OpRewritePattern<WaitOp> {
1255 public:
1256   using OpRewritePattern::OpRewritePattern;
1257 
1258   LogicalResult matchAndRewrite(WaitOp op,
1259                                 PatternRewriter &rewriter) const final {
1260     auto predicate = [](Value value) {
1261       auto waitOp = value.getDefiningOp<WaitOp>();
1262       return waitOp && waitOp->getNumOperands() == 0;
1263     };
1264     if (llvm::none_of(op.asyncDependencies(), predicate))
1265       return failure();
1266     SmallVector<Value> validOperands;
1267     for (Value operand : op->getOperands()) {
1268       if (predicate(operand))
1269         continue;
1270       validOperands.push_back(operand);
1271     }
1272     op->setOperands(validOperands);
1273     return success();
1274   }
1275 };
1276 
1277 /// Simplify trivial gpu.wait ops for the following patterns.
1278 /// 1. %t = gpu.wait async ... ops, where %t has no uses (regardless of async
1279 /// dependencies).
1280 /// 2. %t1 = gpu.wait async [%t0], in this case, we can replace uses of %t1 with
1281 /// %t0.
1282 /// 3. gpu.wait [] ops, i.e gpu.wait ops that neither have any async
1283 /// dependencies nor return any token.
1284 struct SimplifyGpuWaitOp : public OpRewritePattern<WaitOp> {
1285 public:
1286   using OpRewritePattern::OpRewritePattern;
1287 
1288   LogicalResult matchAndRewrite(WaitOp op,
1289                                 PatternRewriter &rewriter) const final {
1290     // Erase gpu.wait ops that neither have any async dependencies nor return
1291     // any async token.
1292     if (op.asyncDependencies().empty() && !op.asyncToken()) {
1293       rewriter.eraseOp(op);
1294       return success();
1295     }
1296     // Replace uses of %t1 = gpu.wait async [%t0] ops with %t0 and erase the op.
1297     if (llvm::hasSingleElement(op.asyncDependencies()) && op.asyncToken()) {
1298       rewriter.replaceOp(op, op.asyncDependencies());
1299       return success();
1300     }
1301     // Erase %t = gpu.wait async ... ops, where %t has no uses.
1302     if (op.asyncToken() && op.asyncToken().use_empty()) {
1303       rewriter.eraseOp(op);
1304       return success();
1305     }
1306     return failure();
1307   }
1308 };
1309 
1310 } // end anonymous namespace
1311 
1312 void WaitOp::getCanonicalizationPatterns(RewritePatternSet &results,
1313                                          MLIRContext *context) {
1314   results.add<EraseRedundantGpuWaitOpPairs, SimplifyGpuWaitOp>(context);
1315 }
1316 
1317 //===----------------------------------------------------------------------===//
1318 // GPU_AllocOp
1319 //===----------------------------------------------------------------------===//
1320 
1321 LogicalResult AllocOp::verify() {
1322   auto memRefType = memref().getType().cast<MemRefType>();
1323 
1324   if (static_cast<int64_t>(dynamicSizes().size()) !=
1325       memRefType.getNumDynamicDims())
1326     return emitOpError("dimension operand count does not equal memref "
1327                        "dynamic dimension count");
1328 
1329   unsigned numSymbols = 0;
1330   if (!memRefType.getLayout().isIdentity())
1331     numSymbols = memRefType.getLayout().getAffineMap().getNumSymbols();
1332   if (symbolOperands().size() != numSymbols) {
1333     return emitOpError(
1334         "symbol operand count does not equal memref symbol count");
1335   }
1336 
1337   return success();
1338 }
1339 
1340 namespace {
1341 
1342 /// Folding of memref.dim(gpu.alloc(%size), %idx) -> %size similar to
1343 /// `memref::AllocOp`.
1344 struct SimplifyDimOfAllocOp : public OpRewritePattern<memref::DimOp> {
1345   using OpRewritePattern<memref::DimOp>::OpRewritePattern;
1346 
1347   LogicalResult matchAndRewrite(memref::DimOp dimOp,
1348                                 PatternRewriter &rewriter) const override {
1349     auto index = dimOp.index().getDefiningOp<arith::ConstantIndexOp>();
1350     if (!index)
1351       return failure();
1352 
1353     auto memrefType = dimOp.source().getType().dyn_cast<MemRefType>();
1354     if (!memrefType || !memrefType.isDynamicDim(index.value()))
1355       return failure();
1356 
1357     auto alloc = dimOp.source().getDefiningOp<AllocOp>();
1358     if (!alloc)
1359       return failure();
1360 
1361     Value substituteOp = *(alloc.dynamicSizes().begin() +
1362                            memrefType.getDynamicDimIndex(index.value()));
1363     rewriter.replaceOp(dimOp, substituteOp);
1364     return success();
1365   }
1366 };
1367 
1368 } // namespace
1369 
1370 void AllocOp::getCanonicalizationPatterns(RewritePatternSet &results,
1371                                           MLIRContext *context) {
1372   results.add<SimplifyDimOfAllocOp>(context);
1373 }
1374 
1375 //===----------------------------------------------------------------------===//
1376 // GPU_DeviceAsyncCopyOp
1377 //===----------------------------------------------------------------------===//
1378 
1379 LogicalResult DeviceAsyncCopyOp::verify() {
1380   auto srcMemref = src().getType().cast<MemRefType>();
1381   auto dstMemref = dst().getType().cast<MemRefType>();
1382   unsigned workgroupAddressSpace = GPUDialect::getWorkgroupAddressSpace();
1383   if (!isLastMemrefDimUnitStride(srcMemref))
1384     return emitError("source memref most minor dim must have unit stride");
1385   if (!isLastMemrefDimUnitStride(dstMemref))
1386     return emitError("destination memref most minor dim must have unit stride");
1387   if (dstMemref.getMemorySpaceAsInt() != workgroupAddressSpace)
1388     return emitError("destination memref must have memory space ")
1389            << workgroupAddressSpace;
1390   if (dstMemref.getElementType() != srcMemref.getElementType())
1391     return emitError("source and destination must have the same element type");
1392   if (size_t(srcMemref.getRank()) != srcIndices().size())
1393     return emitOpError() << "expected " << srcMemref.getRank()
1394                          << " source indices, got " << srcIndices().size();
1395   if (size_t(dstMemref.getRank()) != dstIndices().size())
1396     return emitOpError() << "expected " << dstMemref.getRank()
1397                          << " destination indices, got " << dstIndices().size();
1398   return success();
1399 }
1400 
1401 #include "mlir/Dialect/GPU/GPUOpInterfaces.cpp.inc"
1402 #include "mlir/Dialect/GPU/GPUOpsEnums.cpp.inc"
1403 
1404 #define GET_ATTRDEF_CLASSES
1405 #include "mlir/Dialect/GPU/GPUOpsAttributes.cpp.inc"
1406 
1407 #define GET_OP_CLASSES
1408 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
1409