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