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