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 void LaunchOp::print(OpAsmPrinter &p) { 449 // Print the launch configuration. 450 p << ' ' << getBlocksKeyword(); 451 printSizeAssignment(p, getGridSize(), getGridSizeOperandValues(), 452 getBlockIds()); 453 p << ' ' << getThreadsKeyword(); 454 printSizeAssignment(p, getBlockSize(), getBlockSizeOperandValues(), 455 getThreadIds()); 456 if (dynamicSharedMemorySize()) 457 p << ' ' << getDynamicSharedMemorySizeKeyword() << ' ' 458 << dynamicSharedMemorySize(); 459 460 p << ' '; 461 p.printRegion(body(), /*printEntryBlockArgs=*/false); 462 p.printOptionalAttrDict((*this)->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` 497 /// ssa-reassignment 498 /// `threads` `(` ssa-id-list `)` `in` 499 /// ssa-reassignment 500 /// region attr-dict? 501 /// ssa-reassignment ::= `(` ssa-id `=` ssa-use (`,` ssa-id `=` ssa-use)* `)` 502 ParseResult LaunchOp::parse(OpAsmParser &parser, OperationState &result) { 503 // Sizes of the grid and block. 504 SmallVector<OpAsmParser::OperandType, LaunchOp::kNumConfigOperands> sizes( 505 LaunchOp::kNumConfigOperands); 506 MutableArrayRef<OpAsmParser::OperandType> sizesRef(sizes); 507 508 // Actual (data) operands passed to the kernel. 509 SmallVector<OpAsmParser::OperandType, 4> dataOperands; 510 511 // Region arguments to be created. 512 SmallVector<OpAsmParser::OperandType, 16> regionArgs( 513 LaunchOp::kNumConfigRegionAttributes); 514 MutableArrayRef<OpAsmParser::OperandType> regionArgsRef(regionArgs); 515 516 // Parse the size assignment segments: the first segment assigns grid sizes 517 // and defines values for block identifiers; the second segment assigns block 518 // sizes and defines values for thread identifiers. In the region argument 519 // list, identifiers precede sizes, and block-related values precede 520 // thread-related values. 521 if (parser.parseKeyword(LaunchOp::getBlocksKeyword().data()) || 522 parseSizeAssignment(parser, sizesRef.take_front(3), 523 regionArgsRef.slice(6, 3), 524 regionArgsRef.slice(0, 3)) || 525 parser.parseKeyword(LaunchOp::getThreadsKeyword().data()) || 526 parseSizeAssignment(parser, sizesRef.drop_front(3), 527 regionArgsRef.slice(9, 3), 528 regionArgsRef.slice(3, 3)) || 529 parser.resolveOperands(sizes, parser.getBuilder().getIndexType(), 530 result.operands)) 531 return failure(); 532 533 OpAsmParser::OperandType dynamicSharedMemorySize; 534 if (!parser.parseOptionalKeyword( 535 LaunchOp::getDynamicSharedMemorySizeKeyword())) 536 if (parser.parseOperand(dynamicSharedMemorySize) || 537 parser.resolveOperand(dynamicSharedMemorySize, 538 parser.getBuilder().getI32Type(), 539 result.operands)) 540 return failure(); 541 542 // Introduce the body region and parse it. The region has 543 // kNumConfigRegionAttributes arguments that correspond to 544 // block/thread identifiers and grid/block sizes, all of the `index` type. 545 Type index = parser.getBuilder().getIndexType(); 546 SmallVector<Type, LaunchOp::kNumConfigRegionAttributes> dataTypes( 547 LaunchOp::kNumConfigRegionAttributes, index); 548 Region *body = result.addRegion(); 549 return failure(parser.parseRegion(*body, regionArgs, dataTypes) || 550 parser.parseOptionalAttrDict(result.attributes)); 551 } 552 553 /// Simplify the gpu.launch when the range of a thread or block ID is 554 /// trivially known to be one. 555 struct FoldLaunchArguments : public OpRewritePattern<LaunchOp> { 556 using OpRewritePattern<LaunchOp>::OpRewritePattern; 557 LogicalResult matchAndRewrite(LaunchOp op, 558 PatternRewriter &rewriter) const override { 559 // If the range implies a single value for `id`, replace `id`'s uses by 560 // zero. 561 Value zero; 562 bool simplified = false; 563 auto constPropIdUses = [&](Value id, Value size) { 564 // Check if size is trivially one. 565 if (!matchPattern(size, m_One())) 566 return; 567 if (!simplified) { 568 // Create a zero value the first time. 569 OpBuilder::InsertionGuard guard(rewriter); 570 rewriter.setInsertionPointToStart(&op.body().front()); 571 zero = 572 rewriter.create<arith::ConstantIndexOp>(op.getLoc(), /*value=*/0); 573 } 574 id.replaceAllUsesWith(zero); 575 simplified = true; 576 }; 577 constPropIdUses(op.getBlockIds().x, op.gridSizeX()); 578 constPropIdUses(op.getBlockIds().y, op.gridSizeY()); 579 constPropIdUses(op.getBlockIds().z, op.gridSizeZ()); 580 constPropIdUses(op.getThreadIds().x, op.blockSizeX()); 581 constPropIdUses(op.getThreadIds().y, op.blockSizeY()); 582 constPropIdUses(op.getThreadIds().z, op.blockSizeZ()); 583 584 return success(simplified); 585 } 586 }; 587 588 void LaunchOp::getCanonicalizationPatterns(RewritePatternSet &rewrites, 589 MLIRContext *context) { 590 rewrites.add<FoldLaunchArguments>(context); 591 } 592 593 //===----------------------------------------------------------------------===// 594 // LaunchFuncOp 595 //===----------------------------------------------------------------------===// 596 597 void LaunchFuncOp::build(OpBuilder &builder, OperationState &result, 598 GPUFuncOp kernelFunc, KernelDim3 gridSize, 599 KernelDim3 blockSize, Value dynamicSharedMemorySize, 600 ValueRange kernelOperands) { 601 // Add grid and block sizes as op operands, followed by the data operands. 602 result.addOperands({gridSize.x, gridSize.y, gridSize.z, blockSize.x, 603 blockSize.y, blockSize.z}); 604 if (dynamicSharedMemorySize) 605 result.addOperands(dynamicSharedMemorySize); 606 result.addOperands(kernelOperands); 607 auto kernelModule = kernelFunc->getParentOfType<GPUModuleOp>(); 608 auto kernelSymbol = 609 SymbolRefAttr::get(kernelModule.getNameAttr(), 610 {SymbolRefAttr::get(kernelFunc.getNameAttr())}); 611 result.addAttribute(getKernelAttrName(), kernelSymbol); 612 SmallVector<int32_t, 9> segmentSizes(9, 1); 613 segmentSizes.front() = 0; // Initially no async dependencies. 614 segmentSizes[segmentSizes.size() - 2] = dynamicSharedMemorySize ? 1 : 0; 615 segmentSizes.back() = static_cast<int32_t>(kernelOperands.size()); 616 result.addAttribute(getOperandSegmentSizeAttr(), 617 builder.getI32VectorAttr(segmentSizes)); 618 } 619 620 unsigned LaunchFuncOp::getNumKernelOperands() { 621 return getNumOperands() - asyncDependencies().size() - kNumConfigOperands - 622 (dynamicSharedMemorySize() ? 1 : 0); 623 } 624 625 StringAttr LaunchFuncOp::getKernelModuleName() { 626 return kernel().getRootReference(); 627 } 628 629 StringAttr LaunchFuncOp::getKernelName() { return kernel().getLeafReference(); } 630 631 Value LaunchFuncOp::getKernelOperand(unsigned i) { 632 return getOperand(asyncDependencies().size() + kNumConfigOperands + 633 (dynamicSharedMemorySize() ? 1 : 0) + i); 634 } 635 636 KernelDim3 LaunchFuncOp::getGridSizeOperandValues() { 637 auto operands = getOperands().drop_front(asyncDependencies().size()); 638 return KernelDim3{operands[0], operands[1], operands[2]}; 639 } 640 641 KernelDim3 LaunchFuncOp::getBlockSizeOperandValues() { 642 auto operands = getOperands().drop_front(asyncDependencies().size()); 643 return KernelDim3{operands[3], operands[4], operands[5]}; 644 } 645 646 LogicalResult LaunchFuncOp::verify() { 647 auto module = (*this)->getParentOfType<ModuleOp>(); 648 if (!module) 649 return emitOpError("expected to belong to a module"); 650 651 if (!module->getAttrOfType<UnitAttr>( 652 GPUDialect::getContainerModuleAttrName())) 653 return emitOpError("expected the closest surrounding module to have the '" + 654 GPUDialect::getContainerModuleAttrName() + 655 "' attribute"); 656 657 auto kernelAttr = (*this)->getAttrOfType<SymbolRefAttr>(getKernelAttrName()); 658 if (!kernelAttr) 659 return emitOpError("symbol reference attribute '" + getKernelAttrName() + 660 "' must be specified"); 661 662 return success(); 663 } 664 665 static ParseResult 666 parseLaunchFuncOperands(OpAsmParser &parser, 667 SmallVectorImpl<OpAsmParser::OperandType> &argNames, 668 SmallVectorImpl<Type> &argTypes) { 669 if (parser.parseOptionalKeyword("args")) 670 return success(); 671 SmallVector<NamedAttrList> argAttrs; 672 SmallVector<Location> argLocations; 673 bool isVariadic = false; 674 return function_interface_impl::parseFunctionArgumentList( 675 parser, /*allowAttributes=*/false, 676 /*allowVariadic=*/false, argNames, argTypes, argAttrs, argLocations, 677 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, Location loc) { 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, loc); 707 } 708 709 /// Adds a new block argument that corresponds to buffers located in 710 /// private memory. 711 BlockArgument GPUFuncOp::addPrivateAttribution(Type type, Location loc) { 712 // Buffers on the private memory always come after buffers on the workgroup 713 // memory. 714 return getBody().addArgument(type, loc); 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 731 // TODO: Allow passing in proper locations here. 732 for (Type argTy : type.getInputs()) 733 entryBlock->addArgument(argTy, result.location); 734 for (Type argTy : workgroupAttributions) 735 entryBlock->addArgument(argTy, result.location); 736 for (Type argTy : privateAttributions) 737 entryBlock->addArgument(argTy, result.location); 738 739 body->getBlocks().push_back(entryBlock); 740 } 741 742 /// Parses a GPU function memory attribution. 743 /// 744 /// memory-attribution ::= (`workgroup` `(` ssa-id-and-type-list `)`)? 745 /// (`private` `(` ssa-id-and-type-list `)`)? 746 /// 747 /// Note that this function parses only one of the two similar parts, with the 748 /// keyword provided as argument. 749 static ParseResult 750 parseAttributions(OpAsmParser &parser, StringRef keyword, 751 SmallVectorImpl<OpAsmParser::OperandType> &args, 752 SmallVectorImpl<Type> &argTypes) { 753 // If we could not parse the keyword, just assume empty list and succeed. 754 if (failed(parser.parseOptionalKeyword(keyword))) 755 return success(); 756 757 if (failed(parser.parseLParen())) 758 return failure(); 759 760 // Early exit for an empty list. 761 if (succeeded(parser.parseOptionalRParen())) 762 return success(); 763 764 do { 765 OpAsmParser::OperandType arg; 766 Type type; 767 768 if (parser.parseRegionArgument(arg) || parser.parseColonType(type)) 769 return failure(); 770 771 args.push_back(arg); 772 argTypes.push_back(type); 773 } while (succeeded(parser.parseOptionalComma())); 774 775 return parser.parseRParen(); 776 } 777 778 /// Parses a GPU function. 779 /// 780 /// <operation> ::= `gpu.func` symbol-ref-id `(` argument-list `)` 781 /// (`->` function-result-list)? memory-attribution `kernel`? 782 /// function-attributes? region 783 ParseResult GPUFuncOp::parse(OpAsmParser &parser, OperationState &result) { 784 SmallVector<OpAsmParser::OperandType> entryArgs; 785 SmallVector<NamedAttrList> argAttrs; 786 SmallVector<NamedAttrList> resultAttrs; 787 SmallVector<Type> argTypes; 788 SmallVector<Type> resultTypes; 789 SmallVector<Location> argLocations; 790 bool isVariadic; 791 792 // Parse the function name. 793 StringAttr nameAttr; 794 if (parser.parseSymbolName(nameAttr, ::mlir::SymbolTable::getSymbolAttrName(), 795 result.attributes)) 796 return failure(); 797 798 auto signatureLocation = parser.getCurrentLocation(); 799 if (failed(function_interface_impl::parseFunctionSignature( 800 parser, /*allowVariadic=*/false, entryArgs, argTypes, argAttrs, 801 argLocations, isVariadic, resultTypes, resultAttrs))) 802 return failure(); 803 804 if (entryArgs.empty() && !argTypes.empty()) 805 return parser.emitError(signatureLocation) 806 << "gpu.func requires named arguments"; 807 808 // Construct the function type. More types will be added to the region, but 809 // not to the function type. 810 Builder &builder = parser.getBuilder(); 811 auto type = builder.getFunctionType(argTypes, resultTypes); 812 result.addAttribute(GPUFuncOp::getTypeAttrName(), TypeAttr::get(type)); 813 814 // Parse workgroup memory attributions. 815 if (failed(parseAttributions(parser, GPUFuncOp::getWorkgroupKeyword(), 816 entryArgs, argTypes))) 817 return failure(); 818 819 // Store the number of operands we just parsed as the number of workgroup 820 // memory attributions. 821 unsigned numWorkgroupAttrs = argTypes.size() - type.getNumInputs(); 822 result.addAttribute(GPUFuncOp::getNumWorkgroupAttributionsAttrName(), 823 builder.getI64IntegerAttr(numWorkgroupAttrs)); 824 825 // Parse private memory attributions. 826 if (failed(parseAttributions(parser, GPUFuncOp::getPrivateKeyword(), 827 entryArgs, argTypes))) 828 return failure(); 829 830 // Parse the kernel attribute if present. 831 if (succeeded(parser.parseOptionalKeyword(GPUFuncOp::getKernelKeyword()))) 832 result.addAttribute(GPUDialect::getKernelFuncAttrName(), 833 builder.getUnitAttr()); 834 835 // Parse attributes. 836 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes))) 837 return failure(); 838 function_interface_impl::addArgAndResultAttrs(builder, result, argAttrs, 839 resultAttrs); 840 841 // Parse the region. If no argument names were provided, take all names 842 // (including those of attributions) from the entry block. 843 auto *body = result.addRegion(); 844 return parser.parseRegion(*body, entryArgs, argTypes); 845 } 846 847 static void printAttributions(OpAsmPrinter &p, StringRef keyword, 848 ArrayRef<BlockArgument> values) { 849 if (values.empty()) 850 return; 851 852 p << ' ' << keyword << '('; 853 llvm::interleaveComma( 854 values, p, [&p](BlockArgument v) { p << v << " : " << v.getType(); }); 855 p << ')'; 856 } 857 858 void GPUFuncOp::print(OpAsmPrinter &p) { 859 p << ' '; 860 p.printSymbolName(getName()); 861 862 FunctionType type = getType(); 863 function_interface_impl::printFunctionSignature(p, *this, type.getInputs(), 864 /*isVariadic=*/false, 865 type.getResults()); 866 867 printAttributions(p, getWorkgroupKeyword(), getWorkgroupAttributions()); 868 printAttributions(p, getPrivateKeyword(), getPrivateAttributions()); 869 if (isKernel()) 870 p << ' ' << getKernelKeyword(); 871 872 function_interface_impl::printFunctionAttributes( 873 p, *this, type.getNumInputs(), type.getNumResults(), 874 {getNumWorkgroupAttributionsAttrName(), 875 GPUDialect::getKernelFuncAttrName()}); 876 p << ' '; 877 p.printRegion(getBody(), /*printEntryBlockArgs=*/false); 878 } 879 880 LogicalResult GPUFuncOp::verifyType() { 881 Type type = getTypeAttr().getValue(); 882 if (!type.isa<FunctionType>()) 883 return emitOpError("requires '" + getTypeAttrName() + 884 "' attribute of function type"); 885 886 if (isKernel() && getType().getNumResults() != 0) 887 return emitOpError() << "expected void return type for kernel function"; 888 889 return success(); 890 } 891 892 static LogicalResult verifyAttributions(Operation *op, 893 ArrayRef<BlockArgument> attributions, 894 unsigned memorySpace) { 895 for (Value v : attributions) { 896 auto type = v.getType().dyn_cast<MemRefType>(); 897 if (!type) 898 return op->emitOpError() << "expected memref type in attribution"; 899 900 if (type.getMemorySpaceAsInt() != memorySpace) { 901 return op->emitOpError() 902 << "expected memory space " << memorySpace << " in attribution"; 903 } 904 } 905 return success(); 906 } 907 908 /// Verifies the body of the function. 909 LogicalResult GPUFuncOp::verifyBody() { 910 unsigned numFuncArguments = getNumArguments(); 911 unsigned numWorkgroupAttributions = getNumWorkgroupAttributions(); 912 unsigned numBlockArguments = front().getNumArguments(); 913 if (numBlockArguments < numFuncArguments + numWorkgroupAttributions) 914 return emitOpError() << "expected at least " 915 << numFuncArguments + numWorkgroupAttributions 916 << " arguments to body region"; 917 918 ArrayRef<Type> funcArgTypes = getType().getInputs(); 919 for (unsigned i = 0; i < numFuncArguments; ++i) { 920 Type blockArgType = front().getArgument(i).getType(); 921 if (funcArgTypes[i] != blockArgType) 922 return emitOpError() << "expected body region argument #" << i 923 << " to be of type " << funcArgTypes[i] << ", got " 924 << blockArgType; 925 } 926 927 if (failed(verifyAttributions(getOperation(), getWorkgroupAttributions(), 928 GPUDialect::getWorkgroupAddressSpace())) || 929 failed(verifyAttributions(getOperation(), getPrivateAttributions(), 930 GPUDialect::getPrivateAddressSpace()))) 931 return failure(); 932 933 return success(); 934 } 935 936 //===----------------------------------------------------------------------===// 937 // ReturnOp 938 //===----------------------------------------------------------------------===// 939 940 LogicalResult gpu::ReturnOp::verify() { 941 GPUFuncOp function = (*this)->getParentOfType<GPUFuncOp>(); 942 943 FunctionType funType = function.getType(); 944 945 if (funType.getNumResults() != operands().size()) 946 return emitOpError() 947 .append("expected ", funType.getNumResults(), " result operands") 948 .attachNote(function.getLoc()) 949 .append("return type declared here"); 950 951 for (const auto &pair : llvm::enumerate( 952 llvm::zip(function.getType().getResults(), operands()))) { 953 Type type; 954 Value operand; 955 std::tie(type, operand) = pair.value(); 956 if (type != operand.getType()) 957 return emitOpError() << "unexpected type `" << operand.getType() 958 << "' for operand #" << pair.index(); 959 } 960 return success(); 961 } 962 963 //===----------------------------------------------------------------------===// 964 // GPUModuleOp 965 //===----------------------------------------------------------------------===// 966 967 void GPUModuleOp::build(OpBuilder &builder, OperationState &result, 968 StringRef name) { 969 ensureTerminator(*result.addRegion(), builder, result.location); 970 result.attributes.push_back(builder.getNamedAttr( 971 ::mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(name))); 972 } 973 974 ParseResult GPUModuleOp::parse(OpAsmParser &parser, OperationState &result) { 975 StringAttr nameAttr; 976 if (parser.parseSymbolName(nameAttr, mlir::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 void GPUModuleOp::print(OpAsmPrinter &p) { 995 p << ' '; 996 p.printSymbolName(getName()); 997 p.printOptionalAttrDictWithKeyword((*this)->getAttrs(), 998 {mlir::SymbolTable::getSymbolAttrName()}); 999 p << ' '; 1000 p.printRegion(getRegion(), /*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