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