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