1 //===- SPIRVConversion.cpp - SPIR-V Conversion Utilities ------------------===// 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 utilities used to lower to SPIR-V dialect. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "mlir/Dialect/SPIRV/Transforms/SPIRVConversion.h" 14 #include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h" 15 #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h" 16 #include "mlir/Transforms/DialectConversion.h" 17 #include "llvm/ADT/Sequence.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/Support/Debug.h" 20 21 #include <functional> 22 23 #define DEBUG_TYPE "mlir-spirv-conversion" 24 25 using namespace mlir; 26 27 //===----------------------------------------------------------------------===// 28 // Utility functions 29 //===----------------------------------------------------------------------===// 30 31 /// Checks that `candidates` extension requirements are possible to be satisfied 32 /// with the given `targetEnv`. 33 /// 34 /// `candidates` is a vector of vector for extension requirements following 35 /// ((Extension::A OR Extension::B) AND (Extension::C OR Extension::D)) 36 /// convention. 37 template <typename LabelT> 38 static LogicalResult checkExtensionRequirements( 39 LabelT label, const spirv::TargetEnv &targetEnv, 40 const spirv::SPIRVType::ExtensionArrayRefVector &candidates) { 41 for (const auto &ors : candidates) { 42 if (targetEnv.allows(ors)) 43 continue; 44 45 LLVM_DEBUG({ 46 SmallVector<StringRef> extStrings; 47 for (spirv::Extension ext : ors) 48 extStrings.push_back(spirv::stringifyExtension(ext)); 49 50 llvm::dbgs() << label << " illegal: requires at least one extension in [" 51 << llvm::join(extStrings, ", ") 52 << "] but none allowed in target environment\n"; 53 }); 54 return failure(); 55 } 56 return success(); 57 } 58 59 /// Checks that `candidates`capability requirements are possible to be satisfied 60 /// with the given `isAllowedFn`. 61 /// 62 /// `candidates` is a vector of vector for capability requirements following 63 /// ((Capability::A OR Capability::B) AND (Capability::C OR Capability::D)) 64 /// convention. 65 template <typename LabelT> 66 static LogicalResult checkCapabilityRequirements( 67 LabelT label, const spirv::TargetEnv &targetEnv, 68 const spirv::SPIRVType::CapabilityArrayRefVector &candidates) { 69 for (const auto &ors : candidates) { 70 if (targetEnv.allows(ors)) 71 continue; 72 73 LLVM_DEBUG({ 74 SmallVector<StringRef> capStrings; 75 for (spirv::Capability cap : ors) 76 capStrings.push_back(spirv::stringifyCapability(cap)); 77 78 llvm::dbgs() << label << " illegal: requires at least one capability in [" 79 << llvm::join(capStrings, ", ") 80 << "] but none allowed in target environment\n"; 81 }); 82 return failure(); 83 } 84 return success(); 85 } 86 87 /// Returns true if the given `storageClass` needs explicit layout when used in 88 /// Shader environments. 89 static bool needsExplicitLayout(spirv::StorageClass storageClass) { 90 switch (storageClass) { 91 case spirv::StorageClass::PhysicalStorageBuffer: 92 case spirv::StorageClass::PushConstant: 93 case spirv::StorageClass::StorageBuffer: 94 case spirv::StorageClass::Uniform: 95 return true; 96 default: 97 return false; 98 } 99 } 100 101 /// Wraps the given `elementType` in a struct and gets the pointer to the 102 /// struct. This is used to satisfy Vulkan interface requirements. 103 static spirv::PointerType 104 wrapInStructAndGetPointer(Type elementType, spirv::StorageClass storageClass) { 105 auto structType = needsExplicitLayout(storageClass) 106 ? spirv::StructType::get(elementType, /*offsetInfo=*/0) 107 : spirv::StructType::get(elementType); 108 return spirv::PointerType::get(structType, storageClass); 109 } 110 111 //===----------------------------------------------------------------------===// 112 // Type Conversion 113 //===----------------------------------------------------------------------===// 114 115 Type SPIRVTypeConverter::getIndexType(MLIRContext *context) { 116 // Convert to 32-bit integers for now. Might need a way to control this in 117 // future. 118 // TODO: It is probably better to make it 64-bit integers. To 119 // this some support is needed in SPIR-V dialect for Conversion 120 // instructions. The Vulkan spec requires the builtins like 121 // GlobalInvocationID, etc. to be 32-bit (unsigned) integers which should be 122 // SExtended to 64-bit for index computations. 123 return IntegerType::get(context, 32); 124 } 125 126 /// Mapping between SPIR-V storage classes to memref memory spaces. 127 /// 128 /// Note: memref does not have a defined semantics for each memory space; it 129 /// depends on the context where it is used. There are no particular reasons 130 /// behind the number assignments; we try to follow NVVM conventions and largely 131 /// give common storage classes a smaller number. The hope is use symbolic 132 /// memory space representation eventually after memref supports it. 133 // TODO: swap Generic and StorageBuffer assignment to be more akin 134 // to NVVM. 135 #define STORAGE_SPACE_MAP_LIST(MAP_FN) \ 136 MAP_FN(spirv::StorageClass::Generic, 1) \ 137 MAP_FN(spirv::StorageClass::StorageBuffer, 0) \ 138 MAP_FN(spirv::StorageClass::Workgroup, 3) \ 139 MAP_FN(spirv::StorageClass::Uniform, 4) \ 140 MAP_FN(spirv::StorageClass::Private, 5) \ 141 MAP_FN(spirv::StorageClass::Function, 6) \ 142 MAP_FN(spirv::StorageClass::PushConstant, 7) \ 143 MAP_FN(spirv::StorageClass::UniformConstant, 8) \ 144 MAP_FN(spirv::StorageClass::Input, 9) \ 145 MAP_FN(spirv::StorageClass::Output, 10) \ 146 MAP_FN(spirv::StorageClass::CrossWorkgroup, 11) \ 147 MAP_FN(spirv::StorageClass::AtomicCounter, 12) \ 148 MAP_FN(spirv::StorageClass::Image, 13) \ 149 MAP_FN(spirv::StorageClass::CallableDataNV, 14) \ 150 MAP_FN(spirv::StorageClass::IncomingCallableDataNV, 15) \ 151 MAP_FN(spirv::StorageClass::RayPayloadNV, 16) \ 152 MAP_FN(spirv::StorageClass::HitAttributeNV, 17) \ 153 MAP_FN(spirv::StorageClass::IncomingRayPayloadNV, 18) \ 154 MAP_FN(spirv::StorageClass::ShaderRecordBufferNV, 19) \ 155 MAP_FN(spirv::StorageClass::PhysicalStorageBuffer, 20) 156 157 unsigned 158 SPIRVTypeConverter::getMemorySpaceForStorageClass(spirv::StorageClass storage) { 159 #define STORAGE_SPACE_MAP_FN(storage, space) \ 160 case storage: \ 161 return space; 162 163 switch (storage) { STORAGE_SPACE_MAP_LIST(STORAGE_SPACE_MAP_FN) } 164 #undef STORAGE_SPACE_MAP_FN 165 llvm_unreachable("unhandled storage class!"); 166 } 167 168 Optional<spirv::StorageClass> 169 SPIRVTypeConverter::getStorageClassForMemorySpace(unsigned space) { 170 #define STORAGE_SPACE_MAP_FN(storage, space) \ 171 case space: \ 172 return storage; 173 174 switch (space) { 175 STORAGE_SPACE_MAP_LIST(STORAGE_SPACE_MAP_FN) 176 default: 177 return llvm::None; 178 } 179 #undef STORAGE_SPACE_MAP_FN 180 } 181 182 const SPIRVTypeConverter::Options &SPIRVTypeConverter::getOptions() const { 183 return options; 184 } 185 186 #undef STORAGE_SPACE_MAP_LIST 187 188 // TODO: This is a utility function that should probably be exposed by the 189 // SPIR-V dialect. Keeping it local till the use case arises. 190 static Optional<int64_t> 191 getTypeNumBytes(const SPIRVTypeConverter::Options &options, Type type) { 192 if (type.isa<spirv::ScalarType>()) { 193 auto bitWidth = type.getIntOrFloatBitWidth(); 194 // According to the SPIR-V spec: 195 // "There is no physical size or bit pattern defined for values with boolean 196 // type. If they are stored (in conjunction with OpVariable), they can only 197 // be used with logical addressing operations, not physical, and only with 198 // non-externally visible shader Storage Classes: Workgroup, CrossWorkgroup, 199 // Private, Function, Input, and Output." 200 if (bitWidth == 1) 201 return llvm::None; 202 return bitWidth / 8; 203 } 204 205 if (auto vecType = type.dyn_cast<VectorType>()) { 206 auto elementSize = getTypeNumBytes(options, vecType.getElementType()); 207 if (!elementSize) 208 return llvm::None; 209 return vecType.getNumElements() * elementSize.getValue(); 210 } 211 212 if (auto memRefType = type.dyn_cast<MemRefType>()) { 213 // TODO: Layout should also be controlled by the ABI attributes. For now 214 // using the layout from MemRef. 215 int64_t offset; 216 SmallVector<int64_t, 4> strides; 217 if (!memRefType.hasStaticShape() || 218 failed(getStridesAndOffset(memRefType, strides, offset))) 219 return llvm::None; 220 221 // To get the size of the memref object in memory, the total size is the 222 // max(stride * dimension-size) computed for all dimensions times the size 223 // of the element. 224 auto elementSize = getTypeNumBytes(options, memRefType.getElementType()); 225 if (!elementSize) 226 return llvm::None; 227 228 if (memRefType.getRank() == 0) 229 return elementSize; 230 231 auto dims = memRefType.getShape(); 232 if (llvm::is_contained(dims, ShapedType::kDynamicSize) || 233 offset == MemRefType::getDynamicStrideOrOffset() || 234 llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset())) 235 return llvm::None; 236 237 int64_t memrefSize = -1; 238 for (auto shape : enumerate(dims)) 239 memrefSize = std::max(memrefSize, shape.value() * strides[shape.index()]); 240 241 return (offset + memrefSize) * elementSize.getValue(); 242 } 243 244 if (auto tensorType = type.dyn_cast<TensorType>()) { 245 if (!tensorType.hasStaticShape()) 246 return llvm::None; 247 248 auto elementSize = getTypeNumBytes(options, tensorType.getElementType()); 249 if (!elementSize) 250 return llvm::None; 251 252 int64_t size = elementSize.getValue(); 253 for (auto shape : tensorType.getShape()) 254 size *= shape; 255 256 return size; 257 } 258 259 // TODO: Add size computation for other types. 260 return llvm::None; 261 } 262 263 /// Converts a scalar `type` to a suitable type under the given `targetEnv`. 264 static Type convertScalarType(const spirv::TargetEnv &targetEnv, 265 const SPIRVTypeConverter::Options &options, 266 spirv::ScalarType type, 267 Optional<spirv::StorageClass> storageClass = {}) { 268 // Get extension and capability requirements for the given type. 269 SmallVector<ArrayRef<spirv::Extension>, 1> extensions; 270 SmallVector<ArrayRef<spirv::Capability>, 2> capabilities; 271 type.getExtensions(extensions, storageClass); 272 type.getCapabilities(capabilities, storageClass); 273 274 // If all requirements are met, then we can accept this type as-is. 275 if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) && 276 succeeded(checkExtensionRequirements(type, targetEnv, extensions))) 277 return type; 278 279 // Otherwise we need to adjust the type, which really means adjusting the 280 // bitwidth given this is a scalar type. 281 282 if (!options.emulateNon32BitScalarTypes) 283 return nullptr; 284 285 if (auto floatType = type.dyn_cast<FloatType>()) { 286 LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n"); 287 return Builder(targetEnv.getContext()).getF32Type(); 288 } 289 290 auto intType = type.cast<IntegerType>(); 291 LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n"); 292 return IntegerType::get(targetEnv.getContext(), /*width=*/32, 293 intType.getSignedness()); 294 } 295 296 /// Converts a vector `type` to a suitable type under the given `targetEnv`. 297 static Type convertVectorType(const spirv::TargetEnv &targetEnv, 298 const SPIRVTypeConverter::Options &options, 299 VectorType type, 300 Optional<spirv::StorageClass> storageClass = {}) { 301 if (type.getRank() == 1 && type.getNumElements() == 1) 302 return type.getElementType(); 303 304 if (!spirv::CompositeType::isValid(type)) { 305 // TODO: Vector types with more than four elements can be translated into 306 // array types. 307 LLVM_DEBUG(llvm::dbgs() << type << " illegal: > 4-element unimplemented\n"); 308 return nullptr; 309 } 310 311 // Get extension and capability requirements for the given type. 312 SmallVector<ArrayRef<spirv::Extension>, 1> extensions; 313 SmallVector<ArrayRef<spirv::Capability>, 2> capabilities; 314 type.cast<spirv::CompositeType>().getExtensions(extensions, storageClass); 315 type.cast<spirv::CompositeType>().getCapabilities(capabilities, storageClass); 316 317 // If all requirements are met, then we can accept this type as-is. 318 if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) && 319 succeeded(checkExtensionRequirements(type, targetEnv, extensions))) 320 return type; 321 322 auto elementType = convertScalarType( 323 targetEnv, options, type.getElementType().cast<spirv::ScalarType>(), 324 storageClass); 325 if (elementType) 326 return VectorType::get(type.getShape(), elementType); 327 return nullptr; 328 } 329 330 /// Converts a tensor `type` to a suitable type under the given `targetEnv`. 331 /// 332 /// Note that this is mainly for lowering constant tensors. In SPIR-V one can 333 /// create composite constants with OpConstantComposite to embed relative large 334 /// constant values and use OpCompositeExtract and OpCompositeInsert to 335 /// manipulate, like what we do for vectors. 336 static Type convertTensorType(const spirv::TargetEnv &targetEnv, 337 const SPIRVTypeConverter::Options &options, 338 TensorType type) { 339 // TODO: Handle dynamic shapes. 340 if (!type.hasStaticShape()) { 341 LLVM_DEBUG(llvm::dbgs() 342 << type << " illegal: dynamic shape unimplemented\n"); 343 return nullptr; 344 } 345 346 auto scalarType = type.getElementType().dyn_cast<spirv::ScalarType>(); 347 if (!scalarType) { 348 LLVM_DEBUG(llvm::dbgs() 349 << type << " illegal: cannot convert non-scalar element type\n"); 350 return nullptr; 351 } 352 353 Optional<int64_t> scalarSize = getTypeNumBytes(options, scalarType); 354 Optional<int64_t> tensorSize = getTypeNumBytes(options, type); 355 if (!scalarSize || !tensorSize) { 356 LLVM_DEBUG(llvm::dbgs() 357 << type << " illegal: cannot deduce element count\n"); 358 return nullptr; 359 } 360 361 auto arrayElemCount = *tensorSize / *scalarSize; 362 auto arrayElemType = convertScalarType(targetEnv, options, scalarType); 363 if (!arrayElemType) 364 return nullptr; 365 Optional<int64_t> arrayElemSize = getTypeNumBytes(options, arrayElemType); 366 if (!arrayElemSize) { 367 LLVM_DEBUG(llvm::dbgs() 368 << type << " illegal: cannot deduce converted element size\n"); 369 return nullptr; 370 } 371 372 return spirv::ArrayType::get(arrayElemType, arrayElemCount, *arrayElemSize); 373 } 374 375 static Type convertBoolMemrefType(const spirv::TargetEnv &targetEnv, 376 const SPIRVTypeConverter::Options &options, 377 MemRefType type) { 378 Optional<spirv::StorageClass> storageClass = 379 SPIRVTypeConverter::getStorageClassForMemorySpace( 380 type.getMemorySpaceAsInt()); 381 if (!storageClass) { 382 LLVM_DEBUG(llvm::dbgs() 383 << type << " illegal: cannot convert memory space\n"); 384 return nullptr; 385 } 386 387 unsigned numBoolBits = options.boolNumBits; 388 if (numBoolBits != 8) { 389 LLVM_DEBUG(llvm::dbgs() 390 << "using non-8-bit storage for bool types unimplemented"); 391 return nullptr; 392 } 393 auto elementType = IntegerType::get(type.getContext(), numBoolBits) 394 .dyn_cast<spirv::ScalarType>(); 395 if (!elementType) 396 return nullptr; 397 Type arrayElemType = 398 convertScalarType(targetEnv, options, elementType, storageClass); 399 if (!arrayElemType) 400 return nullptr; 401 Optional<int64_t> arrayElemSize = getTypeNumBytes(options, arrayElemType); 402 if (!arrayElemSize) { 403 LLVM_DEBUG(llvm::dbgs() 404 << type << " illegal: cannot deduce converted element size\n"); 405 return nullptr; 406 } 407 408 if (!type.hasStaticShape()) { 409 auto arrayType = 410 spirv::RuntimeArrayType::get(arrayElemType, *arrayElemSize); 411 return wrapInStructAndGetPointer(arrayType, *storageClass); 412 } 413 414 int64_t memrefSize = (type.getNumElements() * numBoolBits + 7) / 8; 415 auto arrayElemCount = (memrefSize + *arrayElemSize - 1) / *arrayElemSize; 416 auto arrayType = 417 spirv::ArrayType::get(arrayElemType, arrayElemCount, *arrayElemSize); 418 419 return wrapInStructAndGetPointer(arrayType, *storageClass); 420 } 421 422 static Type convertMemrefType(const spirv::TargetEnv &targetEnv, 423 const SPIRVTypeConverter::Options &options, 424 MemRefType type) { 425 if (type.getElementType().isa<IntegerType>() && 426 type.getElementTypeBitWidth() == 1) { 427 return convertBoolMemrefType(targetEnv, options, type); 428 } 429 430 Optional<spirv::StorageClass> storageClass = 431 SPIRVTypeConverter::getStorageClassForMemorySpace( 432 type.getMemorySpaceAsInt()); 433 if (!storageClass) { 434 LLVM_DEBUG(llvm::dbgs() 435 << type << " illegal: cannot convert memory space\n"); 436 return nullptr; 437 } 438 439 Type arrayElemType; 440 Type elementType = type.getElementType(); 441 if (auto vecType = elementType.dyn_cast<VectorType>()) { 442 arrayElemType = 443 convertVectorType(targetEnv, options, vecType, storageClass); 444 } else if (auto scalarType = elementType.dyn_cast<spirv::ScalarType>()) { 445 arrayElemType = 446 convertScalarType(targetEnv, options, scalarType, storageClass); 447 } else { 448 LLVM_DEBUG( 449 llvm::dbgs() 450 << type 451 << " unhandled: can only convert scalar or vector element type\n"); 452 return nullptr; 453 } 454 if (!arrayElemType) 455 return nullptr; 456 457 Optional<int64_t> elementSize = getTypeNumBytes(options, elementType); 458 if (!elementSize) { 459 LLVM_DEBUG(llvm::dbgs() 460 << type << " illegal: cannot deduce element size\n"); 461 return nullptr; 462 } 463 464 Optional<int64_t> arrayElemSize = getTypeNumBytes(options, arrayElemType); 465 if (!arrayElemSize) { 466 LLVM_DEBUG(llvm::dbgs() 467 << type << " illegal: cannot deduce converted element size\n"); 468 return nullptr; 469 } 470 471 if (!type.hasStaticShape()) { 472 auto arrayType = 473 spirv::RuntimeArrayType::get(arrayElemType, *arrayElemSize); 474 return wrapInStructAndGetPointer(arrayType, *storageClass); 475 } 476 477 Optional<int64_t> memrefSize = getTypeNumBytes(options, type); 478 if (!memrefSize) { 479 LLVM_DEBUG(llvm::dbgs() 480 << type << " illegal: cannot deduce element count\n"); 481 return nullptr; 482 } 483 484 auto arrayElemCount = *memrefSize / *elementSize; 485 486 487 auto arrayType = 488 spirv::ArrayType::get(arrayElemType, arrayElemCount, *arrayElemSize); 489 490 return wrapInStructAndGetPointer(arrayType, *storageClass); 491 } 492 493 SPIRVTypeConverter::SPIRVTypeConverter(spirv::TargetEnvAttr targetAttr, 494 Options options) 495 : targetEnv(targetAttr), options(options) { 496 // Add conversions. The order matters here: later ones will be tried earlier. 497 498 // Allow all SPIR-V dialect specific types. This assumes all builtin types 499 // adopted in the SPIR-V dialect (i.e., IntegerType, FloatType, VectorType) 500 // were tried before. 501 // 502 // TODO: this assumes that the SPIR-V types are valid to use in 503 // the given target environment, which should be the case if the whole 504 // pipeline is driven by the same target environment. Still, we probably still 505 // want to validate and convert to be safe. 506 addConversion([](spirv::SPIRVType type) { return type; }); 507 508 addConversion([](IndexType indexType) { 509 return SPIRVTypeConverter::getIndexType(indexType.getContext()); 510 }); 511 512 addConversion([this](IntegerType intType) -> Optional<Type> { 513 if (auto scalarType = intType.dyn_cast<spirv::ScalarType>()) 514 return convertScalarType(this->targetEnv, this->options, scalarType); 515 return Type(); 516 }); 517 518 addConversion([this](FloatType floatType) -> Optional<Type> { 519 if (auto scalarType = floatType.dyn_cast<spirv::ScalarType>()) 520 return convertScalarType(this->targetEnv, this->options, scalarType); 521 return Type(); 522 }); 523 524 addConversion([this](VectorType vectorType) { 525 return convertVectorType(this->targetEnv, this->options, vectorType); 526 }); 527 528 addConversion([this](TensorType tensorType) { 529 return convertTensorType(this->targetEnv, this->options, tensorType); 530 }); 531 532 addConversion([this](MemRefType memRefType) { 533 return convertMemrefType(this->targetEnv, this->options, memRefType); 534 }); 535 } 536 537 //===----------------------------------------------------------------------===// 538 // FuncOp Conversion Patterns 539 //===----------------------------------------------------------------------===// 540 541 namespace { 542 /// A pattern for rewriting function signature to convert arguments of functions 543 /// to be of valid SPIR-V types. 544 class FuncOpConversion final : public OpConversionPattern<FuncOp> { 545 public: 546 using OpConversionPattern<FuncOp>::OpConversionPattern; 547 548 LogicalResult 549 matchAndRewrite(FuncOp funcOp, ArrayRef<Value> operands, 550 ConversionPatternRewriter &rewriter) const override; 551 }; 552 } // namespace 553 554 LogicalResult 555 FuncOpConversion::matchAndRewrite(FuncOp funcOp, ArrayRef<Value> operands, 556 ConversionPatternRewriter &rewriter) const { 557 auto fnType = funcOp.getType(); 558 if (fnType.getNumResults() > 1) 559 return failure(); 560 561 TypeConverter::SignatureConversion signatureConverter(fnType.getNumInputs()); 562 for (auto argType : enumerate(fnType.getInputs())) { 563 auto convertedType = getTypeConverter()->convertType(argType.value()); 564 if (!convertedType) 565 return failure(); 566 signatureConverter.addInputs(argType.index(), convertedType); 567 } 568 569 Type resultType; 570 if (fnType.getNumResults() == 1) { 571 resultType = getTypeConverter()->convertType(fnType.getResult(0)); 572 if (!resultType) 573 return failure(); 574 } 575 576 // Create the converted spv.func op. 577 auto newFuncOp = rewriter.create<spirv::FuncOp>( 578 funcOp.getLoc(), funcOp.getName(), 579 rewriter.getFunctionType(signatureConverter.getConvertedTypes(), 580 resultType ? TypeRange(resultType) 581 : TypeRange())); 582 583 // Copy over all attributes other than the function name and type. 584 for (const auto &namedAttr : funcOp->getAttrs()) { 585 if (namedAttr.first != function_like_impl::getTypeAttrName() && 586 namedAttr.first != SymbolTable::getSymbolAttrName()) 587 newFuncOp->setAttr(namedAttr.first, namedAttr.second); 588 } 589 590 rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(), 591 newFuncOp.end()); 592 if (failed(rewriter.convertRegionTypes( 593 &newFuncOp.getBody(), *getTypeConverter(), &signatureConverter))) 594 return failure(); 595 rewriter.eraseOp(funcOp); 596 return success(); 597 } 598 599 void mlir::populateBuiltinFuncToSPIRVPatterns(SPIRVTypeConverter &typeConverter, 600 RewritePatternSet &patterns) { 601 patterns.add<FuncOpConversion>(typeConverter, patterns.getContext()); 602 } 603 604 //===----------------------------------------------------------------------===// 605 // Builtin Variables 606 //===----------------------------------------------------------------------===// 607 608 static spirv::GlobalVariableOp getBuiltinVariable(Block &body, 609 spirv::BuiltIn builtin) { 610 // Look through all global variables in the given `body` block and check if 611 // there is a spv.GlobalVariable that has the same `builtin` attribute. 612 for (auto varOp : body.getOps<spirv::GlobalVariableOp>()) { 613 if (auto builtinAttr = varOp->getAttrOfType<StringAttr>( 614 spirv::SPIRVDialect::getAttributeName( 615 spirv::Decoration::BuiltIn))) { 616 auto varBuiltIn = spirv::symbolizeBuiltIn(builtinAttr.getValue()); 617 if (varBuiltIn && varBuiltIn.getValue() == builtin) { 618 return varOp; 619 } 620 } 621 } 622 return nullptr; 623 } 624 625 /// Gets name of global variable for a builtin. 626 static std::string getBuiltinVarName(spirv::BuiltIn builtin) { 627 return std::string("__builtin_var_") + stringifyBuiltIn(builtin).str() + "__"; 628 } 629 630 /// Gets or inserts a global variable for a builtin within `body` block. 631 static spirv::GlobalVariableOp 632 getOrInsertBuiltinVariable(Block &body, Location loc, spirv::BuiltIn builtin, 633 OpBuilder &builder) { 634 if (auto varOp = getBuiltinVariable(body, builtin)) 635 return varOp; 636 637 OpBuilder::InsertionGuard guard(builder); 638 builder.setInsertionPointToStart(&body); 639 640 spirv::GlobalVariableOp newVarOp; 641 switch (builtin) { 642 case spirv::BuiltIn::NumWorkgroups: 643 case spirv::BuiltIn::WorkgroupSize: 644 case spirv::BuiltIn::WorkgroupId: 645 case spirv::BuiltIn::LocalInvocationId: 646 case spirv::BuiltIn::GlobalInvocationId: { 647 auto ptrType = spirv::PointerType::get( 648 VectorType::get({3}, builder.getIntegerType(32)), 649 spirv::StorageClass::Input); 650 std::string name = getBuiltinVarName(builtin); 651 newVarOp = 652 builder.create<spirv::GlobalVariableOp>(loc, ptrType, name, builtin); 653 break; 654 } 655 case spirv::BuiltIn::SubgroupId: 656 case spirv::BuiltIn::NumSubgroups: 657 case spirv::BuiltIn::SubgroupSize: { 658 auto ptrType = spirv::PointerType::get(builder.getIntegerType(32), 659 spirv::StorageClass::Input); 660 std::string name = getBuiltinVarName(builtin); 661 newVarOp = 662 builder.create<spirv::GlobalVariableOp>(loc, ptrType, name, builtin); 663 break; 664 } 665 default: 666 emitError(loc, "unimplemented builtin variable generation for ") 667 << stringifyBuiltIn(builtin); 668 } 669 return newVarOp; 670 } 671 672 Value mlir::spirv::getBuiltinVariableValue(Operation *op, 673 spirv::BuiltIn builtin, 674 OpBuilder &builder) { 675 Operation *parent = SymbolTable::getNearestSymbolTable(op->getParentOp()); 676 if (!parent) { 677 op->emitError("expected operation to be within a module-like op"); 678 return nullptr; 679 } 680 681 spirv::GlobalVariableOp varOp = getOrInsertBuiltinVariable( 682 *parent->getRegion(0).begin(), op->getLoc(), builtin, builder); 683 Value ptr = builder.create<spirv::AddressOfOp>(op->getLoc(), varOp); 684 return builder.create<spirv::LoadOp>(op->getLoc(), ptr); 685 } 686 687 //===----------------------------------------------------------------------===// 688 // Push constant storage 689 //===----------------------------------------------------------------------===// 690 691 /// Returns the pointer type for the push constant storage containing 692 /// `elementCount` 32-bit integer values. 693 static spirv::PointerType getPushConstantStorageType(unsigned elementCount, 694 Builder &builder) { 695 auto arrayType = spirv::ArrayType::get( 696 SPIRVTypeConverter::getIndexType(builder.getContext()), elementCount, 697 /*stride=*/4); 698 auto structType = spirv::StructType::get({arrayType}, /*offsetInfo=*/0); 699 return spirv::PointerType::get(structType, spirv::StorageClass::PushConstant); 700 } 701 702 /// Returns the push constant varible containing `elementCount` 32-bit integer 703 /// values in `body`. Returns null op if such an op does not exit. 704 static spirv::GlobalVariableOp getPushConstantVariable(Block &body, 705 unsigned elementCount) { 706 for (auto varOp : body.getOps<spirv::GlobalVariableOp>()) { 707 auto ptrType = varOp.type().cast<spirv::PointerType>(); 708 // Note that Vulkan requires "There must be no more than one push constant 709 // block statically used per shader entry point." So we should always reuse 710 // the existing one. 711 if (ptrType.getStorageClass() == spirv::StorageClass::PushConstant) { 712 auto numElements = ptrType.getPointeeType() 713 .cast<spirv::StructType>() 714 .getElementType(0) 715 .cast<spirv::ArrayType>() 716 .getNumElements(); 717 if (numElements == elementCount) 718 return varOp; 719 } 720 } 721 return nullptr; 722 } 723 724 /// Gets or inserts a global variable for push constant storage containing 725 /// `elementCount` 32-bit integer values in `block`. 726 static spirv::GlobalVariableOp 727 getOrInsertPushConstantVariable(Location loc, Block &block, 728 unsigned elementCount, OpBuilder &b) { 729 if (auto varOp = getPushConstantVariable(block, elementCount)) 730 return varOp; 731 732 auto builder = OpBuilder::atBlockBegin(&block, b.getListener()); 733 auto type = getPushConstantStorageType(elementCount, builder); 734 const char *name = "__push_constant_var__"; 735 return builder.create<spirv::GlobalVariableOp>(loc, type, name, 736 /*initializer=*/nullptr); 737 } 738 739 Value spirv::getPushConstantValue(Operation *op, unsigned elementCount, 740 unsigned offset, OpBuilder &builder) { 741 Location loc = op->getLoc(); 742 Operation *parent = SymbolTable::getNearestSymbolTable(op->getParentOp()); 743 if (!parent) { 744 op->emitError("expected operation to be within a module-like op"); 745 return nullptr; 746 } 747 748 spirv::GlobalVariableOp varOp = getOrInsertPushConstantVariable( 749 loc, parent->getRegion(0).front(), elementCount, builder); 750 751 auto i32Type = SPIRVTypeConverter::getIndexType(builder.getContext()); 752 Value zeroOp = spirv::ConstantOp::getZero(i32Type, loc, builder); 753 Value offsetOp = builder.create<spirv::ConstantOp>( 754 loc, i32Type, builder.getI32IntegerAttr(offset)); 755 auto addrOp = builder.create<spirv::AddressOfOp>(loc, varOp); 756 auto acOp = builder.create<spirv::AccessChainOp>( 757 loc, addrOp, llvm::makeArrayRef({zeroOp, offsetOp})); 758 return builder.create<spirv::LoadOp>(loc, acOp); 759 } 760 761 //===----------------------------------------------------------------------===// 762 // Index calculation 763 //===----------------------------------------------------------------------===// 764 765 Value mlir::spirv::linearizeIndex(ValueRange indices, ArrayRef<int64_t> strides, 766 int64_t offset, Location loc, 767 OpBuilder &builder) { 768 assert(indices.size() == strides.size() && 769 "must provide indices for all dimensions"); 770 771 auto indexType = SPIRVTypeConverter::getIndexType(builder.getContext()); 772 773 // TODO: Consider moving to use affine.apply and patterns converting 774 // affine.apply to standard ops. This needs converting to SPIR-V passes to be 775 // broken down into progressive small steps so we can have intermediate steps 776 // using other dialects. At the moment SPIR-V is the final sink. 777 778 Value linearizedIndex = builder.create<spirv::ConstantOp>( 779 loc, indexType, IntegerAttr::get(indexType, offset)); 780 for (auto index : llvm::enumerate(indices)) { 781 Value strideVal = builder.create<spirv::ConstantOp>( 782 loc, indexType, IntegerAttr::get(indexType, strides[index.index()])); 783 Value update = builder.create<spirv::IMulOp>(loc, strideVal, index.value()); 784 linearizedIndex = 785 builder.create<spirv::IAddOp>(loc, linearizedIndex, update); 786 } 787 return linearizedIndex; 788 } 789 790 spirv::AccessChainOp mlir::spirv::getElementPtr( 791 SPIRVTypeConverter &typeConverter, MemRefType baseType, Value basePtr, 792 ValueRange indices, Location loc, OpBuilder &builder) { 793 // Get base and offset of the MemRefType and verify they are static. 794 795 int64_t offset; 796 SmallVector<int64_t, 4> strides; 797 if (failed(getStridesAndOffset(baseType, strides, offset)) || 798 llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset()) || 799 offset == MemRefType::getDynamicStrideOrOffset()) { 800 return nullptr; 801 } 802 803 auto indexType = typeConverter.getIndexType(builder.getContext()); 804 805 SmallVector<Value, 2> linearizedIndices; 806 auto zero = spirv::ConstantOp::getZero(indexType, loc, builder); 807 808 // Add a '0' at the start to index into the struct. 809 linearizedIndices.push_back(zero); 810 811 if (baseType.getRank() == 0) { 812 linearizedIndices.push_back(zero); 813 } else { 814 linearizedIndices.push_back( 815 linearizeIndex(indices, strides, offset, loc, builder)); 816 } 817 return builder.create<spirv::AccessChainOp>(loc, basePtr, linearizedIndices); 818 } 819 820 //===----------------------------------------------------------------------===// 821 // SPIR-V ConversionTarget 822 //===----------------------------------------------------------------------===// 823 824 std::unique_ptr<SPIRVConversionTarget> 825 SPIRVConversionTarget::get(spirv::TargetEnvAttr targetAttr) { 826 std::unique_ptr<SPIRVConversionTarget> target( 827 // std::make_unique does not work here because the constructor is private. 828 new SPIRVConversionTarget(targetAttr)); 829 SPIRVConversionTarget *targetPtr = target.get(); 830 target->addDynamicallyLegalDialect<spirv::SPIRVDialect>( 831 // We need to capture the raw pointer here because it is stable: 832 // target will be destroyed once this function is returned. 833 [targetPtr](Operation *op) { return targetPtr->isLegalOp(op); }); 834 return target; 835 } 836 837 SPIRVConversionTarget::SPIRVConversionTarget(spirv::TargetEnvAttr targetAttr) 838 : ConversionTarget(*targetAttr.getContext()), targetEnv(targetAttr) {} 839 840 bool SPIRVConversionTarget::isLegalOp(Operation *op) { 841 // Make sure this op is available at the given version. Ops not implementing 842 // QueryMinVersionInterface/QueryMaxVersionInterface are available to all 843 // SPIR-V versions. 844 if (auto minVersion = dyn_cast<spirv::QueryMinVersionInterface>(op)) 845 if (minVersion.getMinVersion() > this->targetEnv.getVersion()) { 846 LLVM_DEBUG(llvm::dbgs() 847 << op->getName() << " illegal: requiring min version " 848 << spirv::stringifyVersion(minVersion.getMinVersion()) 849 << "\n"); 850 return false; 851 } 852 if (auto maxVersion = dyn_cast<spirv::QueryMaxVersionInterface>(op)) 853 if (maxVersion.getMaxVersion() < this->targetEnv.getVersion()) { 854 LLVM_DEBUG(llvm::dbgs() 855 << op->getName() << " illegal: requiring max version " 856 << spirv::stringifyVersion(maxVersion.getMaxVersion()) 857 << "\n"); 858 return false; 859 } 860 861 // Make sure this op's required extensions are allowed to use. Ops not 862 // implementing QueryExtensionInterface do not require extensions to be 863 // available. 864 if (auto extensions = dyn_cast<spirv::QueryExtensionInterface>(op)) 865 if (failed(checkExtensionRequirements(op->getName(), this->targetEnv, 866 extensions.getExtensions()))) 867 return false; 868 869 // Make sure this op's required extensions are allowed to use. Ops not 870 // implementing QueryCapabilityInterface do not require capabilities to be 871 // available. 872 if (auto capabilities = dyn_cast<spirv::QueryCapabilityInterface>(op)) 873 if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv, 874 capabilities.getCapabilities()))) 875 return false; 876 877 SmallVector<Type, 4> valueTypes; 878 valueTypes.append(op->operand_type_begin(), op->operand_type_end()); 879 valueTypes.append(op->result_type_begin(), op->result_type_end()); 880 881 // Special treatment for global variables, whose type requirements are 882 // conveyed by type attributes. 883 if (auto globalVar = dyn_cast<spirv::GlobalVariableOp>(op)) 884 valueTypes.push_back(globalVar.type()); 885 886 // Make sure the op's operands/results use types that are allowed by the 887 // target environment. 888 SmallVector<ArrayRef<spirv::Extension>, 4> typeExtensions; 889 SmallVector<ArrayRef<spirv::Capability>, 8> typeCapabilities; 890 for (Type valueType : valueTypes) { 891 typeExtensions.clear(); 892 valueType.cast<spirv::SPIRVType>().getExtensions(typeExtensions); 893 if (failed(checkExtensionRequirements(op->getName(), this->targetEnv, 894 typeExtensions))) 895 return false; 896 897 typeCapabilities.clear(); 898 valueType.cast<spirv::SPIRVType>().getCapabilities(typeCapabilities); 899 if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv, 900 typeCapabilities))) 901 return false; 902 } 903 904 return true; 905 } 906