1 //===- SPIRVOps.cpp - MLIR SPIR-V operations ------------------------------===// 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 defines the operations in the SPIR-V dialect. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h" 14 15 #include "mlir/Dialect/SPIRV/IR/ParserUtils.h" 16 #include "mlir/Dialect/SPIRV/IR/SPIRVAttributes.h" 17 #include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h" 18 #include "mlir/Dialect/SPIRV/IR/SPIRVOpTraits.h" 19 #include "mlir/Dialect/SPIRV/IR/SPIRVTypes.h" 20 #include "mlir/Dialect/SPIRV/IR/TargetAndABI.h" 21 #include "mlir/IR/Builders.h" 22 #include "mlir/IR/BuiltinOps.h" 23 #include "mlir/IR/BuiltinTypes.h" 24 #include "mlir/IR/FunctionImplementation.h" 25 #include "mlir/IR/OpDefinition.h" 26 #include "mlir/IR/OpImplementation.h" 27 #include "mlir/IR/TypeUtilities.h" 28 #include "mlir/Interfaces/CallInterfaces.h" 29 #include "llvm/ADT/APFloat.h" 30 #include "llvm/ADT/APInt.h" 31 #include "llvm/ADT/StringExtras.h" 32 #include "llvm/ADT/bit.h" 33 34 using namespace mlir; 35 36 // TODO: generate these strings using ODS. 37 static constexpr const char kMemoryAccessAttrName[] = "memory_access"; 38 static constexpr const char kSourceMemoryAccessAttrName[] = 39 "source_memory_access"; 40 static constexpr const char kAlignmentAttrName[] = "alignment"; 41 static constexpr const char kSourceAlignmentAttrName[] = "source_alignment"; 42 static constexpr const char kBranchWeightAttrName[] = "branch_weights"; 43 static constexpr const char kCallee[] = "callee"; 44 static constexpr const char kClusterSize[] = "cluster_size"; 45 static constexpr const char kControl[] = "control"; 46 static constexpr const char kDefaultValueAttrName[] = "default_value"; 47 static constexpr const char kExecutionScopeAttrName[] = "execution_scope"; 48 static constexpr const char kEqualSemanticsAttrName[] = "equal_semantics"; 49 static constexpr const char kFnNameAttrName[] = "fn"; 50 static constexpr const char kGroupOperationAttrName[] = "group_operation"; 51 static constexpr const char kIndicesAttrName[] = "indices"; 52 static constexpr const char kInitializerAttrName[] = "initializer"; 53 static constexpr const char kInterfaceAttrName[] = "interface"; 54 static constexpr const char kMemoryScopeAttrName[] = "memory_scope"; 55 static constexpr const char kSemanticsAttrName[] = "semantics"; 56 static constexpr const char kSpecIdAttrName[] = "spec_id"; 57 static constexpr const char kTypeAttrName[] = "type"; 58 static constexpr const char kUnequalSemanticsAttrName[] = "unequal_semantics"; 59 static constexpr const char kValueAttrName[] = "value"; 60 static constexpr const char kValuesAttrName[] = "values"; 61 static constexpr const char kCompositeSpecConstituentsName[] = "constituents"; 62 63 //===----------------------------------------------------------------------===// 64 // Common utility functions 65 //===----------------------------------------------------------------------===// 66 67 /// Returns true if the given op is a function-like op or nested in a 68 /// function-like op without a module-like op in the middle. 69 static bool isNestedInFunctionLikeOp(Operation *op) { 70 if (!op) 71 return false; 72 if (op->hasTrait<OpTrait::SymbolTable>()) 73 return false; 74 if (op->hasTrait<OpTrait::FunctionLike>()) 75 return true; 76 return isNestedInFunctionLikeOp(op->getParentOp()); 77 } 78 79 /// Returns true if the given op is an module-like op that maintains a symbol 80 /// table. 81 static bool isDirectInModuleLikeOp(Operation *op) { 82 return op && op->hasTrait<OpTrait::SymbolTable>(); 83 } 84 85 static LogicalResult extractValueFromConstOp(Operation *op, int32_t &value) { 86 auto constOp = dyn_cast_or_null<spirv::ConstantOp>(op); 87 if (!constOp) { 88 return failure(); 89 } 90 auto valueAttr = constOp.value(); 91 auto integerValueAttr = valueAttr.dyn_cast<IntegerAttr>(); 92 if (!integerValueAttr) { 93 return failure(); 94 } 95 value = integerValueAttr.getInt(); 96 return success(); 97 } 98 99 template <typename Ty> 100 static ArrayAttr 101 getStrArrayAttrForEnumList(Builder &builder, ArrayRef<Ty> enumValues, 102 function_ref<StringRef(Ty)> stringifyFn) { 103 if (enumValues.empty()) { 104 return nullptr; 105 } 106 SmallVector<StringRef, 1> enumValStrs; 107 enumValStrs.reserve(enumValues.size()); 108 for (auto val : enumValues) { 109 enumValStrs.emplace_back(stringifyFn(val)); 110 } 111 return builder.getStrArrayAttr(enumValStrs); 112 } 113 114 /// Parses the next string attribute in `parser` as an enumerant of the given 115 /// `EnumClass`. 116 template <typename EnumClass> 117 static ParseResult 118 parseEnumStrAttr(EnumClass &value, OpAsmParser &parser, 119 StringRef attrName = spirv::attributeName<EnumClass>()) { 120 Attribute attrVal; 121 NamedAttrList attr; 122 auto loc = parser.getCurrentLocation(); 123 if (parser.parseAttribute(attrVal, parser.getBuilder().getNoneType(), 124 attrName, attr)) { 125 return failure(); 126 } 127 if (!attrVal.isa<StringAttr>()) { 128 return parser.emitError(loc, "expected ") 129 << attrName << " attribute specified as string"; 130 } 131 auto attrOptional = 132 spirv::symbolizeEnum<EnumClass>(attrVal.cast<StringAttr>().getValue()); 133 if (!attrOptional) { 134 return parser.emitError(loc, "invalid ") 135 << attrName << " attribute specification: " << attrVal; 136 } 137 value = attrOptional.getValue(); 138 return success(); 139 } 140 141 /// Parses the next string attribute in `parser` as an enumerant of the given 142 /// `EnumClass` and inserts the enumerant into `state` as an 32-bit integer 143 /// attribute with the enum class's name as attribute name. 144 template <typename EnumClass> 145 static ParseResult 146 parseEnumStrAttr(EnumClass &value, OpAsmParser &parser, OperationState &state, 147 StringRef attrName = spirv::attributeName<EnumClass>()) { 148 if (parseEnumStrAttr(value, parser)) { 149 return failure(); 150 } 151 state.addAttribute(attrName, parser.getBuilder().getI32IntegerAttr( 152 llvm::bit_cast<int32_t>(value))); 153 return success(); 154 } 155 156 /// Parses the next keyword in `parser` as an enumerant of the given `EnumClass` 157 /// and inserts the enumerant into `state` as an 32-bit integer attribute with 158 /// the enum class's name as attribute name. 159 template <typename EnumClass> 160 static ParseResult 161 parseEnumKeywordAttr(EnumClass &value, OpAsmParser &parser, 162 OperationState &state, 163 StringRef attrName = spirv::attributeName<EnumClass>()) { 164 if (parseEnumKeywordAttr(value, parser)) { 165 return failure(); 166 } 167 state.addAttribute(attrName, parser.getBuilder().getI32IntegerAttr( 168 llvm::bit_cast<int32_t>(value))); 169 return success(); 170 } 171 172 /// Parses Function, Selection and Loop control attributes. If no control is 173 /// specified, "None" is used as a default. 174 template <typename EnumClass> 175 static ParseResult 176 parseControlAttribute(OpAsmParser &parser, OperationState &state, 177 StringRef attrName = spirv::attributeName<EnumClass>()) { 178 if (succeeded(parser.parseOptionalKeyword(kControl))) { 179 EnumClass control; 180 if (parser.parseLParen() || parseEnumKeywordAttr(control, parser, state) || 181 parser.parseRParen()) 182 return failure(); 183 return success(); 184 } 185 // Set control to "None" otherwise. 186 Builder builder = parser.getBuilder(); 187 state.addAttribute(attrName, builder.getI32IntegerAttr(0)); 188 return success(); 189 } 190 191 /// Parses optional memory access attributes attached to a memory access 192 /// operand/pointer. Specifically, parses the following syntax: 193 /// (`[` memory-access `]`)? 194 /// where: 195 /// memory-access ::= `"None"` | `"Volatile"` | `"Aligned", ` 196 /// integer-literal | `"NonTemporal"` 197 static ParseResult parseMemoryAccessAttributes(OpAsmParser &parser, 198 OperationState &state) { 199 // Parse an optional list of attributes staring with '[' 200 if (parser.parseOptionalLSquare()) { 201 // Nothing to do 202 return success(); 203 } 204 205 spirv::MemoryAccess memoryAccessAttr; 206 if (parseEnumStrAttr(memoryAccessAttr, parser, state, 207 kMemoryAccessAttrName)) { 208 return failure(); 209 } 210 211 if (spirv::bitEnumContains(memoryAccessAttr, spirv::MemoryAccess::Aligned)) { 212 // Parse integer attribute for alignment. 213 Attribute alignmentAttr; 214 Type i32Type = parser.getBuilder().getIntegerType(32); 215 if (parser.parseComma() || 216 parser.parseAttribute(alignmentAttr, i32Type, kAlignmentAttrName, 217 state.attributes)) { 218 return failure(); 219 } 220 } 221 return parser.parseRSquare(); 222 } 223 224 // TODO Make sure to merge this and the previous function into one template 225 // parameterized by memory access attribute name and alignment. Doing so now 226 // results in VS2017 in producing an internal error (at the call site) that's 227 // not detailed enough to understand what is happening. 228 static ParseResult parseSourceMemoryAccessAttributes(OpAsmParser &parser, 229 OperationState &state) { 230 // Parse an optional list of attributes staring with '[' 231 if (parser.parseOptionalLSquare()) { 232 // Nothing to do 233 return success(); 234 } 235 236 spirv::MemoryAccess memoryAccessAttr; 237 if (parseEnumStrAttr(memoryAccessAttr, parser, state, 238 kSourceMemoryAccessAttrName)) { 239 return failure(); 240 } 241 242 if (spirv::bitEnumContains(memoryAccessAttr, spirv::MemoryAccess::Aligned)) { 243 // Parse integer attribute for alignment. 244 Attribute alignmentAttr; 245 Type i32Type = parser.getBuilder().getIntegerType(32); 246 if (parser.parseComma() || 247 parser.parseAttribute(alignmentAttr, i32Type, kSourceAlignmentAttrName, 248 state.attributes)) { 249 return failure(); 250 } 251 } 252 return parser.parseRSquare(); 253 } 254 255 template <typename MemoryOpTy> 256 static void printMemoryAccessAttribute( 257 MemoryOpTy memoryOp, OpAsmPrinter &printer, 258 SmallVectorImpl<StringRef> &elidedAttrs, 259 Optional<spirv::MemoryAccess> memoryAccessAtrrValue = None, 260 Optional<uint32_t> alignmentAttrValue = None) { 261 // Print optional memory access attribute. 262 if (auto memAccess = (memoryAccessAtrrValue ? memoryAccessAtrrValue 263 : memoryOp.memory_access())) { 264 elidedAttrs.push_back(kMemoryAccessAttrName); 265 266 printer << " [\"" << stringifyMemoryAccess(*memAccess) << "\""; 267 268 if (spirv::bitEnumContains(*memAccess, spirv::MemoryAccess::Aligned)) { 269 // Print integer alignment attribute. 270 if (auto alignment = (alignmentAttrValue ? alignmentAttrValue 271 : memoryOp.alignment())) { 272 elidedAttrs.push_back(kAlignmentAttrName); 273 printer << ", " << alignment; 274 } 275 } 276 printer << "]"; 277 } 278 elidedAttrs.push_back(spirv::attributeName<spirv::StorageClass>()); 279 } 280 281 // TODO Make sure to merge this and the previous function into one template 282 // parameterized by memory access attribute name and alignment. Doing so now 283 // results in VS2017 in producing an internal error (at the call site) that's 284 // not detailed enough to understand what is happening. 285 template <typename MemoryOpTy> 286 static void printSourceMemoryAccessAttribute( 287 MemoryOpTy memoryOp, OpAsmPrinter &printer, 288 SmallVectorImpl<StringRef> &elidedAttrs, 289 Optional<spirv::MemoryAccess> memoryAccessAtrrValue = None, 290 Optional<uint32_t> alignmentAttrValue = None) { 291 292 printer << ", "; 293 294 // Print optional memory access attribute. 295 if (auto memAccess = (memoryAccessAtrrValue ? memoryAccessAtrrValue 296 : memoryOp.memory_access())) { 297 elidedAttrs.push_back(kSourceMemoryAccessAttrName); 298 299 printer << " [\"" << stringifyMemoryAccess(*memAccess) << "\""; 300 301 if (spirv::bitEnumContains(*memAccess, spirv::MemoryAccess::Aligned)) { 302 // Print integer alignment attribute. 303 if (auto alignment = (alignmentAttrValue ? alignmentAttrValue 304 : memoryOp.alignment())) { 305 elidedAttrs.push_back(kSourceAlignmentAttrName); 306 printer << ", " << alignment; 307 } 308 } 309 printer << "]"; 310 } 311 elidedAttrs.push_back(spirv::attributeName<spirv::StorageClass>()); 312 } 313 314 static LogicalResult verifyCastOp(Operation *op, 315 bool requireSameBitWidth = true, 316 bool skipBitWidthCheck = false) { 317 // Some CastOps have no limit on bit widths for result and operand type. 318 if (skipBitWidthCheck) 319 return success(); 320 321 Type operandType = op->getOperand(0).getType(); 322 Type resultType = op->getResult(0).getType(); 323 324 // ODS checks that result type and operand type have the same shape. 325 if (auto vectorType = operandType.dyn_cast<VectorType>()) { 326 operandType = vectorType.getElementType(); 327 resultType = resultType.cast<VectorType>().getElementType(); 328 } 329 330 if (auto coopMatrixType = 331 operandType.dyn_cast<spirv::CooperativeMatrixNVType>()) { 332 operandType = coopMatrixType.getElementType(); 333 resultType = 334 resultType.cast<spirv::CooperativeMatrixNVType>().getElementType(); 335 } 336 337 auto operandTypeBitWidth = operandType.getIntOrFloatBitWidth(); 338 auto resultTypeBitWidth = resultType.getIntOrFloatBitWidth(); 339 auto isSameBitWidth = operandTypeBitWidth == resultTypeBitWidth; 340 341 if (requireSameBitWidth) { 342 if (!isSameBitWidth) { 343 return op->emitOpError( 344 "expected the same bit widths for operand type and result " 345 "type, but provided ") 346 << operandType << " and " << resultType; 347 } 348 return success(); 349 } 350 351 if (isSameBitWidth) { 352 return op->emitOpError( 353 "expected the different bit widths for operand type and result " 354 "type, but provided ") 355 << operandType << " and " << resultType; 356 } 357 return success(); 358 } 359 360 template <typename MemoryOpTy> 361 static LogicalResult verifyMemoryAccessAttribute(MemoryOpTy memoryOp) { 362 // ODS checks for attributes values. Just need to verify that if the 363 // memory-access attribute is Aligned, then the alignment attribute must be 364 // present. 365 auto *op = memoryOp.getOperation(); 366 auto memAccessAttr = op->getAttr(kMemoryAccessAttrName); 367 if (!memAccessAttr) { 368 // Alignment attribute shouldn't be present if memory access attribute is 369 // not present. 370 if (op->getAttr(kAlignmentAttrName)) { 371 return memoryOp.emitOpError( 372 "invalid alignment specification without aligned memory access " 373 "specification"); 374 } 375 return success(); 376 } 377 378 auto memAccessVal = memAccessAttr.template cast<IntegerAttr>(); 379 auto memAccess = spirv::symbolizeMemoryAccess(memAccessVal.getInt()); 380 381 if (!memAccess) { 382 return memoryOp.emitOpError("invalid memory access specifier: ") 383 << memAccessVal; 384 } 385 386 if (spirv::bitEnumContains(*memAccess, spirv::MemoryAccess::Aligned)) { 387 if (!op->getAttr(kAlignmentAttrName)) { 388 return memoryOp.emitOpError("missing alignment value"); 389 } 390 } else { 391 if (op->getAttr(kAlignmentAttrName)) { 392 return memoryOp.emitOpError( 393 "invalid alignment specification with non-aligned memory access " 394 "specification"); 395 } 396 } 397 return success(); 398 } 399 400 // TODO Make sure to merge this and the previous function into one template 401 // parameterized by memory access attribute name and alignment. Doing so now 402 // results in VS2017 in producing an internal error (at the call site) that's 403 // not detailed enough to understand what is happening. 404 template <typename MemoryOpTy> 405 static LogicalResult verifySourceMemoryAccessAttribute(MemoryOpTy memoryOp) { 406 // ODS checks for attributes values. Just need to verify that if the 407 // memory-access attribute is Aligned, then the alignment attribute must be 408 // present. 409 auto *op = memoryOp.getOperation(); 410 auto memAccessAttr = op->getAttr(kSourceMemoryAccessAttrName); 411 if (!memAccessAttr) { 412 // Alignment attribute shouldn't be present if memory access attribute is 413 // not present. 414 if (op->getAttr(kSourceAlignmentAttrName)) { 415 return memoryOp.emitOpError( 416 "invalid alignment specification without aligned memory access " 417 "specification"); 418 } 419 return success(); 420 } 421 422 auto memAccessVal = memAccessAttr.template cast<IntegerAttr>(); 423 auto memAccess = spirv::symbolizeMemoryAccess(memAccessVal.getInt()); 424 425 if (!memAccess) { 426 return memoryOp.emitOpError("invalid memory access specifier: ") 427 << memAccessVal; 428 } 429 430 if (spirv::bitEnumContains(*memAccess, spirv::MemoryAccess::Aligned)) { 431 if (!op->getAttr(kSourceAlignmentAttrName)) { 432 return memoryOp.emitOpError("missing alignment value"); 433 } 434 } else { 435 if (op->getAttr(kSourceAlignmentAttrName)) { 436 return memoryOp.emitOpError( 437 "invalid alignment specification with non-aligned memory access " 438 "specification"); 439 } 440 } 441 return success(); 442 } 443 444 template <typename BarrierOp> 445 static LogicalResult verifyMemorySemantics(BarrierOp op) { 446 // According to the SPIR-V specification: 447 // "Despite being a mask and allowing multiple bits to be combined, it is 448 // invalid for more than one of these four bits to be set: Acquire, Release, 449 // AcquireRelease, or SequentiallyConsistent. Requesting both Acquire and 450 // Release semantics is done by setting the AcquireRelease bit, not by setting 451 // two bits." 452 auto memorySemantics = op.memory_semantics(); 453 auto atMostOneInSet = spirv::MemorySemantics::Acquire | 454 spirv::MemorySemantics::Release | 455 spirv::MemorySemantics::AcquireRelease | 456 spirv::MemorySemantics::SequentiallyConsistent; 457 458 auto bitCount = llvm::countPopulation( 459 static_cast<uint32_t>(memorySemantics & atMostOneInSet)); 460 if (bitCount > 1) { 461 return op.emitError("expected at most one of these four memory constraints " 462 "to be set: `Acquire`, `Release`," 463 "`AcquireRelease` or `SequentiallyConsistent`"); 464 } 465 return success(); 466 } 467 468 template <typename LoadStoreOpTy> 469 static LogicalResult verifyLoadStorePtrAndValTypes(LoadStoreOpTy op, Value ptr, 470 Value val) { 471 // ODS already checks ptr is spirv::PointerType. Just check that the pointee 472 // type of the pointer and the type of the value are the same 473 // 474 // TODO: Check that the value type satisfies restrictions of 475 // SPIR-V OpLoad/OpStore operations 476 if (val.getType() != 477 ptr.getType().cast<spirv::PointerType>().getPointeeType()) { 478 return op.emitOpError("mismatch in result type and pointer type"); 479 } 480 return success(); 481 } 482 483 template <typename BlockReadWriteOpTy> 484 static LogicalResult verifyBlockReadWritePtrAndValTypes(BlockReadWriteOpTy op, 485 Value ptr, Value val) { 486 auto valType = val.getType(); 487 if (auto valVecTy = valType.dyn_cast<VectorType>()) 488 valType = valVecTy.getElementType(); 489 490 if (valType != ptr.getType().cast<spirv::PointerType>().getPointeeType()) { 491 return op.emitOpError("mismatch in result type and pointer type"); 492 } 493 return success(); 494 } 495 496 static ParseResult parseVariableDecorations(OpAsmParser &parser, 497 OperationState &state) { 498 auto builtInName = llvm::convertToSnakeFromCamelCase( 499 stringifyDecoration(spirv::Decoration::BuiltIn)); 500 if (succeeded(parser.parseOptionalKeyword("bind"))) { 501 Attribute set, binding; 502 // Parse optional descriptor binding 503 auto descriptorSetName = llvm::convertToSnakeFromCamelCase( 504 stringifyDecoration(spirv::Decoration::DescriptorSet)); 505 auto bindingName = llvm::convertToSnakeFromCamelCase( 506 stringifyDecoration(spirv::Decoration::Binding)); 507 Type i32Type = parser.getBuilder().getIntegerType(32); 508 if (parser.parseLParen() || 509 parser.parseAttribute(set, i32Type, descriptorSetName, 510 state.attributes) || 511 parser.parseComma() || 512 parser.parseAttribute(binding, i32Type, bindingName, 513 state.attributes) || 514 parser.parseRParen()) { 515 return failure(); 516 } 517 } else if (succeeded(parser.parseOptionalKeyword(builtInName))) { 518 StringAttr builtIn; 519 if (parser.parseLParen() || 520 parser.parseAttribute(builtIn, builtInName, state.attributes) || 521 parser.parseRParen()) { 522 return failure(); 523 } 524 } 525 526 // Parse other attributes 527 if (parser.parseOptionalAttrDict(state.attributes)) 528 return failure(); 529 530 return success(); 531 } 532 533 static void printVariableDecorations(Operation *op, OpAsmPrinter &printer, 534 SmallVectorImpl<StringRef> &elidedAttrs) { 535 // Print optional descriptor binding 536 auto descriptorSetName = llvm::convertToSnakeFromCamelCase( 537 stringifyDecoration(spirv::Decoration::DescriptorSet)); 538 auto bindingName = llvm::convertToSnakeFromCamelCase( 539 stringifyDecoration(spirv::Decoration::Binding)); 540 auto descriptorSet = op->getAttrOfType<IntegerAttr>(descriptorSetName); 541 auto binding = op->getAttrOfType<IntegerAttr>(bindingName); 542 if (descriptorSet && binding) { 543 elidedAttrs.push_back(descriptorSetName); 544 elidedAttrs.push_back(bindingName); 545 printer << " bind(" << descriptorSet.getInt() << ", " << binding.getInt() 546 << ")"; 547 } 548 549 // Print BuiltIn attribute if present 550 auto builtInName = llvm::convertToSnakeFromCamelCase( 551 stringifyDecoration(spirv::Decoration::BuiltIn)); 552 if (auto builtin = op->getAttrOfType<StringAttr>(builtInName)) { 553 printer << " " << builtInName << "(\"" << builtin.getValue() << "\")"; 554 elidedAttrs.push_back(builtInName); 555 } 556 557 printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs); 558 } 559 560 // Get bit width of types. 561 static unsigned getBitWidth(Type type) { 562 if (type.isa<spirv::PointerType>()) { 563 // Just return 64 bits for pointer types for now. 564 // TODO: Make sure not caller relies on the actual pointer width value. 565 return 64; 566 } 567 568 if (type.isIntOrFloat()) 569 return type.getIntOrFloatBitWidth(); 570 571 if (auto vectorType = type.dyn_cast<VectorType>()) { 572 assert(vectorType.getElementType().isIntOrFloat()); 573 return vectorType.getNumElements() * 574 vectorType.getElementType().getIntOrFloatBitWidth(); 575 } 576 llvm_unreachable("unhandled bit width computation for type"); 577 } 578 579 /// Walks the given type hierarchy with the given indices, potentially down 580 /// to component granularity, to select an element type. Returns null type and 581 /// emits errors with the given loc on failure. 582 static Type 583 getElementType(Type type, ArrayRef<int32_t> indices, 584 function_ref<InFlightDiagnostic(StringRef)> emitErrorFn) { 585 if (indices.empty()) { 586 emitErrorFn("expected at least one index for spv.CompositeExtract"); 587 return nullptr; 588 } 589 590 for (auto index : indices) { 591 if (auto cType = type.dyn_cast<spirv::CompositeType>()) { 592 if (cType.hasCompileTimeKnownNumElements() && 593 (index < 0 || 594 static_cast<uint64_t>(index) >= cType.getNumElements())) { 595 emitErrorFn("index ") << index << " out of bounds for " << type; 596 return nullptr; 597 } 598 type = cType.getElementType(index); 599 } else { 600 emitErrorFn("cannot extract from non-composite type ") 601 << type << " with index " << index; 602 return nullptr; 603 } 604 } 605 return type; 606 } 607 608 static Type 609 getElementType(Type type, Attribute indices, 610 function_ref<InFlightDiagnostic(StringRef)> emitErrorFn) { 611 auto indicesArrayAttr = indices.dyn_cast<ArrayAttr>(); 612 if (!indicesArrayAttr) { 613 emitErrorFn("expected a 32-bit integer array attribute for 'indices'"); 614 return nullptr; 615 } 616 if (!indicesArrayAttr.size()) { 617 emitErrorFn("expected at least one index for spv.CompositeExtract"); 618 return nullptr; 619 } 620 621 SmallVector<int32_t, 2> indexVals; 622 for (auto indexAttr : indicesArrayAttr) { 623 auto indexIntAttr = indexAttr.dyn_cast<IntegerAttr>(); 624 if (!indexIntAttr) { 625 emitErrorFn("expected an 32-bit integer for index, but found '") 626 << indexAttr << "'"; 627 return nullptr; 628 } 629 indexVals.push_back(indexIntAttr.getInt()); 630 } 631 return getElementType(type, indexVals, emitErrorFn); 632 } 633 634 static Type getElementType(Type type, Attribute indices, Location loc) { 635 auto errorFn = [&](StringRef err) -> InFlightDiagnostic { 636 return ::mlir::emitError(loc, err); 637 }; 638 return getElementType(type, indices, errorFn); 639 } 640 641 static Type getElementType(Type type, Attribute indices, OpAsmParser &parser, 642 llvm::SMLoc loc) { 643 auto errorFn = [&](StringRef err) -> InFlightDiagnostic { 644 return parser.emitError(loc, err); 645 }; 646 return getElementType(type, indices, errorFn); 647 } 648 649 /// Returns true if the given `block` only contains one `spv.mlir.merge` op. 650 static inline bool isMergeBlock(Block &block) { 651 return !block.empty() && std::next(block.begin()) == block.end() && 652 isa<spirv::MergeOp>(block.front()); 653 } 654 655 //===----------------------------------------------------------------------===// 656 // Common parsers and printers 657 //===----------------------------------------------------------------------===// 658 659 // Parses an atomic update op. If the update op does not take a value (like 660 // AtomicIIncrement) `hasValue` must be false. 661 static ParseResult parseAtomicUpdateOp(OpAsmParser &parser, 662 OperationState &state, bool hasValue) { 663 spirv::Scope scope; 664 spirv::MemorySemantics memoryScope; 665 SmallVector<OpAsmParser::OperandType, 2> operandInfo; 666 OpAsmParser::OperandType ptrInfo, valueInfo; 667 Type type; 668 llvm::SMLoc loc; 669 if (parseEnumStrAttr(scope, parser, state, kMemoryScopeAttrName) || 670 parseEnumStrAttr(memoryScope, parser, state, kSemanticsAttrName) || 671 parser.parseOperandList(operandInfo, (hasValue ? 2 : 1)) || 672 parser.getCurrentLocation(&loc) || parser.parseColonType(type)) 673 return failure(); 674 675 auto ptrType = type.dyn_cast<spirv::PointerType>(); 676 if (!ptrType) 677 return parser.emitError(loc, "expected pointer type"); 678 679 SmallVector<Type, 2> operandTypes; 680 operandTypes.push_back(ptrType); 681 if (hasValue) 682 operandTypes.push_back(ptrType.getPointeeType()); 683 if (parser.resolveOperands(operandInfo, operandTypes, parser.getNameLoc(), 684 state.operands)) 685 return failure(); 686 return parser.addTypeToList(ptrType.getPointeeType(), state.types); 687 } 688 689 // Prints an atomic update op. 690 static void printAtomicUpdateOp(Operation *op, OpAsmPrinter &printer) { 691 printer << op->getName() << " \""; 692 auto scopeAttr = op->getAttrOfType<IntegerAttr>(kMemoryScopeAttrName); 693 printer << spirv::stringifyScope( 694 static_cast<spirv::Scope>(scopeAttr.getInt())) 695 << "\" \""; 696 auto memorySemanticsAttr = op->getAttrOfType<IntegerAttr>(kSemanticsAttrName); 697 printer << spirv::stringifyMemorySemantics( 698 static_cast<spirv::MemorySemantics>( 699 memorySemanticsAttr.getInt())) 700 << "\" " << op->getOperands() << " : " << op->getOperand(0).getType(); 701 } 702 703 // Verifies an atomic update op. 704 static LogicalResult verifyAtomicUpdateOp(Operation *op) { 705 auto ptrType = op->getOperand(0).getType().cast<spirv::PointerType>(); 706 auto elementType = ptrType.getPointeeType(); 707 if (!elementType.isa<IntegerType>()) 708 return op->emitOpError( 709 "pointer operand must point to an integer value, found ") 710 << elementType; 711 712 if (op->getNumOperands() > 1) { 713 auto valueType = op->getOperand(1).getType(); 714 if (valueType != elementType) 715 return op->emitOpError("expected value to have the same type as the " 716 "pointer operand's pointee type ") 717 << elementType << ", but found " << valueType; 718 } 719 return success(); 720 } 721 722 static ParseResult parseGroupNonUniformArithmeticOp(OpAsmParser &parser, 723 OperationState &state) { 724 spirv::Scope executionScope; 725 spirv::GroupOperation groupOperation; 726 OpAsmParser::OperandType valueInfo; 727 if (parseEnumStrAttr(executionScope, parser, state, 728 kExecutionScopeAttrName) || 729 parseEnumStrAttr(groupOperation, parser, state, 730 kGroupOperationAttrName) || 731 parser.parseOperand(valueInfo)) 732 return failure(); 733 734 Optional<OpAsmParser::OperandType> clusterSizeInfo; 735 if (succeeded(parser.parseOptionalKeyword(kClusterSize))) { 736 clusterSizeInfo = OpAsmParser::OperandType(); 737 if (parser.parseLParen() || parser.parseOperand(*clusterSizeInfo) || 738 parser.parseRParen()) 739 return failure(); 740 } 741 742 Type resultType; 743 if (parser.parseColonType(resultType)) 744 return failure(); 745 746 if (parser.resolveOperand(valueInfo, resultType, state.operands)) 747 return failure(); 748 749 if (clusterSizeInfo.hasValue()) { 750 Type i32Type = parser.getBuilder().getIntegerType(32); 751 if (parser.resolveOperand(*clusterSizeInfo, i32Type, state.operands)) 752 return failure(); 753 } 754 755 return parser.addTypeToList(resultType, state.types); 756 } 757 758 static void printGroupNonUniformArithmeticOp(Operation *groupOp, 759 OpAsmPrinter &printer) { 760 printer << groupOp->getName() << " \"" 761 << stringifyScope(static_cast<spirv::Scope>( 762 groupOp->getAttrOfType<IntegerAttr>(kExecutionScopeAttrName) 763 .getInt())) 764 << "\" \"" 765 << stringifyGroupOperation(static_cast<spirv::GroupOperation>( 766 groupOp->getAttrOfType<IntegerAttr>(kGroupOperationAttrName) 767 .getInt())) 768 << "\" " << groupOp->getOperand(0); 769 770 if (groupOp->getNumOperands() > 1) 771 printer << " " << kClusterSize << '(' << groupOp->getOperand(1) << ')'; 772 printer << " : " << groupOp->getResult(0).getType(); 773 } 774 775 static LogicalResult verifyGroupNonUniformArithmeticOp(Operation *groupOp) { 776 spirv::Scope scope = static_cast<spirv::Scope>( 777 groupOp->getAttrOfType<IntegerAttr>(kExecutionScopeAttrName).getInt()); 778 if (scope != spirv::Scope::Workgroup && scope != spirv::Scope::Subgroup) 779 return groupOp->emitOpError( 780 "execution scope must be 'Workgroup' or 'Subgroup'"); 781 782 spirv::GroupOperation operation = static_cast<spirv::GroupOperation>( 783 groupOp->getAttrOfType<IntegerAttr>(kGroupOperationAttrName).getInt()); 784 if (operation == spirv::GroupOperation::ClusteredReduce && 785 groupOp->getNumOperands() == 1) 786 return groupOp->emitOpError("cluster size operand must be provided for " 787 "'ClusteredReduce' group operation"); 788 if (groupOp->getNumOperands() > 1) { 789 Operation *sizeOp = groupOp->getOperand(1).getDefiningOp(); 790 int32_t clusterSize = 0; 791 792 // TODO: support specialization constant here. 793 if (failed(extractValueFromConstOp(sizeOp, clusterSize))) 794 return groupOp->emitOpError( 795 "cluster size operand must come from a constant op"); 796 797 if (!llvm::isPowerOf2_32(clusterSize)) 798 return groupOp->emitOpError( 799 "cluster size operand must be a power of two"); 800 } 801 return success(); 802 } 803 804 static ParseResult parseUnaryOp(OpAsmParser &parser, OperationState &state) { 805 OpAsmParser::OperandType operandInfo; 806 Type type; 807 if (parser.parseOperand(operandInfo) || parser.parseColonType(type) || 808 parser.resolveOperands(operandInfo, type, state.operands)) { 809 return failure(); 810 } 811 state.addTypes(type); 812 return success(); 813 } 814 815 static void printUnaryOp(Operation *unaryOp, OpAsmPrinter &printer) { 816 printer << unaryOp->getName() << ' ' << unaryOp->getOperand(0) << " : " 817 << unaryOp->getOperand(0).getType(); 818 } 819 820 /// Result of a logical op must be a scalar or vector of boolean type. 821 static Type getUnaryOpResultType(Builder &builder, Type operandType) { 822 Type resultType = builder.getIntegerType(1); 823 if (auto vecType = operandType.dyn_cast<VectorType>()) { 824 return VectorType::get(vecType.getNumElements(), resultType); 825 } 826 return resultType; 827 } 828 829 static ParseResult parseLogicalUnaryOp(OpAsmParser &parser, 830 OperationState &state) { 831 OpAsmParser::OperandType operandInfo; 832 Type type; 833 if (parser.parseOperand(operandInfo) || parser.parseColonType(type) || 834 parser.resolveOperand(operandInfo, type, state.operands)) { 835 return failure(); 836 } 837 state.addTypes(getUnaryOpResultType(parser.getBuilder(), type)); 838 return success(); 839 } 840 841 static ParseResult parseLogicalBinaryOp(OpAsmParser &parser, 842 OperationState &result) { 843 SmallVector<OpAsmParser::OperandType, 2> ops; 844 Type type; 845 if (parser.parseOperandList(ops, 2) || parser.parseColonType(type) || 846 parser.resolveOperands(ops, type, result.operands)) { 847 return failure(); 848 } 849 result.addTypes(getUnaryOpResultType(parser.getBuilder(), type)); 850 return success(); 851 } 852 853 static void printLogicalOp(Operation *logicalOp, OpAsmPrinter &printer) { 854 printer << logicalOp->getName() << ' ' << logicalOp->getOperands() << " : " 855 << logicalOp->getOperand(0).getType(); 856 } 857 858 static ParseResult parseShiftOp(OpAsmParser &parser, OperationState &state) { 859 SmallVector<OpAsmParser::OperandType, 2> operandInfo; 860 Type baseType; 861 Type shiftType; 862 auto loc = parser.getCurrentLocation(); 863 864 if (parser.parseOperandList(operandInfo, 2) || parser.parseColon() || 865 parser.parseType(baseType) || parser.parseComma() || 866 parser.parseType(shiftType) || 867 parser.resolveOperands(operandInfo, {baseType, shiftType}, loc, 868 state.operands)) { 869 return failure(); 870 } 871 state.addTypes(baseType); 872 return success(); 873 } 874 875 static void printShiftOp(Operation *op, OpAsmPrinter &printer) { 876 Value base = op->getOperand(0); 877 Value shift = op->getOperand(1); 878 printer << op->getName() << ' ' << base << ", " << shift << " : " 879 << base.getType() << ", " << shift.getType(); 880 } 881 882 static LogicalResult verifyShiftOp(Operation *op) { 883 if (op->getOperand(0).getType() != op->getResult(0).getType()) { 884 return op->emitError("expected the same type for the first operand and " 885 "result, but provided ") 886 << op->getOperand(0).getType() << " and " 887 << op->getResult(0).getType(); 888 } 889 return success(); 890 } 891 892 static void buildLogicalBinaryOp(OpBuilder &builder, OperationState &state, 893 Value lhs, Value rhs) { 894 assert(lhs.getType() == rhs.getType()); 895 896 Type boolType = builder.getI1Type(); 897 if (auto vecType = lhs.getType().dyn_cast<VectorType>()) 898 boolType = VectorType::get(vecType.getShape(), boolType); 899 state.addTypes(boolType); 900 901 state.addOperands({lhs, rhs}); 902 } 903 904 static void buildLogicalUnaryOp(OpBuilder &builder, OperationState &state, 905 Value value) { 906 Type boolType = builder.getI1Type(); 907 if (auto vecType = value.getType().dyn_cast<VectorType>()) 908 boolType = VectorType::get(vecType.getShape(), boolType); 909 state.addTypes(boolType); 910 911 state.addOperands(value); 912 } 913 914 //===----------------------------------------------------------------------===// 915 // spv.AccessChainOp 916 //===----------------------------------------------------------------------===// 917 918 static Type getElementPtrType(Type type, ValueRange indices, Location baseLoc) { 919 auto ptrType = type.dyn_cast<spirv::PointerType>(); 920 if (!ptrType) { 921 emitError(baseLoc, "'spv.AccessChain' op expected a pointer " 922 "to composite type, but provided ") 923 << type; 924 return nullptr; 925 } 926 927 auto resultType = ptrType.getPointeeType(); 928 auto resultStorageClass = ptrType.getStorageClass(); 929 int32_t index = 0; 930 931 for (auto indexSSA : indices) { 932 auto cType = resultType.dyn_cast<spirv::CompositeType>(); 933 if (!cType) { 934 emitError(baseLoc, 935 "'spv.AccessChain' op cannot extract from non-composite type ") 936 << resultType << " with index " << index; 937 return nullptr; 938 } 939 index = 0; 940 if (resultType.isa<spirv::StructType>()) { 941 Operation *op = indexSSA.getDefiningOp(); 942 if (!op) { 943 emitError(baseLoc, "'spv.AccessChain' op index must be an " 944 "integer spv.Constant to access " 945 "element of spv.struct"); 946 return nullptr; 947 } 948 949 // TODO: this should be relaxed to allow 950 // integer literals of other bitwidths. 951 if (failed(extractValueFromConstOp(op, index))) { 952 emitError(baseLoc, 953 "'spv.AccessChain' index must be an integer spv.Constant to " 954 "access element of spv.struct, but provided ") 955 << op->getName(); 956 return nullptr; 957 } 958 if (index < 0 || static_cast<uint64_t>(index) >= cType.getNumElements()) { 959 emitError(baseLoc, "'spv.AccessChain' op index ") 960 << index << " out of bounds for " << resultType; 961 return nullptr; 962 } 963 } 964 resultType = cType.getElementType(index); 965 } 966 return spirv::PointerType::get(resultType, resultStorageClass); 967 } 968 969 void spirv::AccessChainOp::build(OpBuilder &builder, OperationState &state, 970 Value basePtr, ValueRange indices) { 971 auto type = getElementPtrType(basePtr.getType(), indices, state.location); 972 assert(type && "Unable to deduce return type based on basePtr and indices"); 973 build(builder, state, type, basePtr, indices); 974 } 975 976 static ParseResult parseAccessChainOp(OpAsmParser &parser, 977 OperationState &state) { 978 OpAsmParser::OperandType ptrInfo; 979 SmallVector<OpAsmParser::OperandType, 4> indicesInfo; 980 Type type; 981 auto loc = parser.getCurrentLocation(); 982 SmallVector<Type, 4> indicesTypes; 983 984 if (parser.parseOperand(ptrInfo) || 985 parser.parseOperandList(indicesInfo, OpAsmParser::Delimiter::Square) || 986 parser.parseColonType(type) || 987 parser.resolveOperand(ptrInfo, type, state.operands)) { 988 return failure(); 989 } 990 991 // Check that the provided indices list is not empty before parsing their 992 // type list. 993 if (indicesInfo.empty()) { 994 return emitError(state.location, "'spv.AccessChain' op expected at " 995 "least one index "); 996 } 997 998 if (parser.parseComma() || parser.parseTypeList(indicesTypes)) 999 return failure(); 1000 1001 // Check that the indices types list is not empty and that it has a one-to-one 1002 // mapping to the provided indices. 1003 if (indicesTypes.size() != indicesInfo.size()) { 1004 return emitError(state.location, "'spv.AccessChain' op indices " 1005 "types' count must be equal to indices " 1006 "info count"); 1007 } 1008 1009 if (parser.resolveOperands(indicesInfo, indicesTypes, loc, state.operands)) 1010 return failure(); 1011 1012 auto resultType = getElementPtrType( 1013 type, llvm::makeArrayRef(state.operands).drop_front(), state.location); 1014 if (!resultType) { 1015 return failure(); 1016 } 1017 1018 state.addTypes(resultType); 1019 return success(); 1020 } 1021 1022 static void print(spirv::AccessChainOp op, OpAsmPrinter &printer) { 1023 printer << spirv::AccessChainOp::getOperationName() << ' ' << op.base_ptr() 1024 << '[' << op.indices() << "] : " << op.base_ptr().getType() << ", " 1025 << op.indices().getTypes(); 1026 } 1027 1028 static LogicalResult verify(spirv::AccessChainOp accessChainOp) { 1029 SmallVector<Value, 4> indices(accessChainOp.indices().begin(), 1030 accessChainOp.indices().end()); 1031 auto resultType = getElementPtrType(accessChainOp.base_ptr().getType(), 1032 indices, accessChainOp.getLoc()); 1033 if (!resultType) { 1034 return failure(); 1035 } 1036 1037 auto providedResultType = 1038 accessChainOp.getType().dyn_cast<spirv::PointerType>(); 1039 if (!providedResultType) { 1040 return accessChainOp.emitOpError( 1041 "result type must be a pointer, but provided") 1042 << providedResultType; 1043 } 1044 1045 if (resultType != providedResultType) { 1046 return accessChainOp.emitOpError("invalid result type: expected ") 1047 << resultType << ", but provided " << providedResultType; 1048 } 1049 1050 return success(); 1051 } 1052 1053 //===----------------------------------------------------------------------===// 1054 // spv.mlir.addressof 1055 //===----------------------------------------------------------------------===// 1056 1057 void spirv::AddressOfOp::build(OpBuilder &builder, OperationState &state, 1058 spirv::GlobalVariableOp var) { 1059 build(builder, state, var.type(), builder.getSymbolRefAttr(var)); 1060 } 1061 1062 static LogicalResult verify(spirv::AddressOfOp addressOfOp) { 1063 auto varOp = dyn_cast_or_null<spirv::GlobalVariableOp>( 1064 SymbolTable::lookupNearestSymbolFrom(addressOfOp->getParentOp(), 1065 addressOfOp.variable())); 1066 if (!varOp) { 1067 return addressOfOp.emitOpError("expected spv.GlobalVariable symbol"); 1068 } 1069 if (addressOfOp.pointer().getType() != varOp.type()) { 1070 return addressOfOp.emitOpError( 1071 "result type mismatch with the referenced global variable's type"); 1072 } 1073 return success(); 1074 } 1075 1076 //===----------------------------------------------------------------------===// 1077 // spv.AtomicCompareExchangeWeak 1078 //===----------------------------------------------------------------------===// 1079 1080 static ParseResult parseAtomicCompareExchangeWeakOp(OpAsmParser &parser, 1081 OperationState &state) { 1082 spirv::Scope memoryScope; 1083 spirv::MemorySemantics equalSemantics, unequalSemantics; 1084 SmallVector<OpAsmParser::OperandType, 3> operandInfo; 1085 Type type; 1086 if (parseEnumStrAttr(memoryScope, parser, state, kMemoryScopeAttrName) || 1087 parseEnumStrAttr(equalSemantics, parser, state, 1088 kEqualSemanticsAttrName) || 1089 parseEnumStrAttr(unequalSemantics, parser, state, 1090 kUnequalSemanticsAttrName) || 1091 parser.parseOperandList(operandInfo, 3)) 1092 return failure(); 1093 1094 auto loc = parser.getCurrentLocation(); 1095 if (parser.parseColonType(type)) 1096 return failure(); 1097 1098 auto ptrType = type.dyn_cast<spirv::PointerType>(); 1099 if (!ptrType) 1100 return parser.emitError(loc, "expected pointer type"); 1101 1102 if (parser.resolveOperands( 1103 operandInfo, 1104 {ptrType, ptrType.getPointeeType(), ptrType.getPointeeType()}, 1105 parser.getNameLoc(), state.operands)) 1106 return failure(); 1107 1108 return parser.addTypeToList(ptrType.getPointeeType(), state.types); 1109 } 1110 1111 static void print(spirv::AtomicCompareExchangeWeakOp atomOp, 1112 OpAsmPrinter &printer) { 1113 printer << spirv::AtomicCompareExchangeWeakOp::getOperationName() << " \"" 1114 << stringifyScope(atomOp.memory_scope()) << "\" \"" 1115 << stringifyMemorySemantics(atomOp.equal_semantics()) << "\" \"" 1116 << stringifyMemorySemantics(atomOp.unequal_semantics()) << "\" " 1117 << atomOp.getOperands() << " : " << atomOp.pointer().getType(); 1118 } 1119 1120 static LogicalResult verify(spirv::AtomicCompareExchangeWeakOp atomOp) { 1121 // According to the spec: 1122 // "The type of Value must be the same as Result Type. The type of the value 1123 // pointed to by Pointer must be the same as Result Type. This type must also 1124 // match the type of Comparator." 1125 if (atomOp.getType() != atomOp.value().getType()) 1126 return atomOp.emitOpError("value operand must have the same type as the op " 1127 "result, but found ") 1128 << atomOp.value().getType() << " vs " << atomOp.getType(); 1129 1130 if (atomOp.getType() != atomOp.comparator().getType()) 1131 return atomOp.emitOpError( 1132 "comparator operand must have the same type as the op " 1133 "result, but found ") 1134 << atomOp.comparator().getType() << " vs " << atomOp.getType(); 1135 1136 Type pointeeType = 1137 atomOp.pointer().getType().cast<spirv::PointerType>().getPointeeType(); 1138 if (atomOp.getType() != pointeeType) 1139 return atomOp.emitOpError( 1140 "pointer operand's pointee type must have the same " 1141 "as the op result type, but found ") 1142 << pointeeType << " vs " << atomOp.getType(); 1143 1144 // TODO: Unequal cannot be set to Release or Acquire and Release. 1145 // In addition, Unequal cannot be set to a stronger memory-order then Equal. 1146 1147 return success(); 1148 } 1149 1150 //===----------------------------------------------------------------------===// 1151 // spv.BitcastOp 1152 //===----------------------------------------------------------------------===// 1153 1154 static LogicalResult verify(spirv::BitcastOp bitcastOp) { 1155 // TODO: The SPIR-V spec validation rules are different for different 1156 // versions. 1157 auto operandType = bitcastOp.operand().getType(); 1158 auto resultType = bitcastOp.result().getType(); 1159 if (operandType == resultType) { 1160 return bitcastOp.emitError( 1161 "result type must be different from operand type"); 1162 } 1163 if (operandType.isa<spirv::PointerType>() && 1164 !resultType.isa<spirv::PointerType>()) { 1165 return bitcastOp.emitError( 1166 "unhandled bit cast conversion from pointer type to non-pointer type"); 1167 } 1168 if (!operandType.isa<spirv::PointerType>() && 1169 resultType.isa<spirv::PointerType>()) { 1170 return bitcastOp.emitError( 1171 "unhandled bit cast conversion from non-pointer type to pointer type"); 1172 } 1173 auto operandBitWidth = getBitWidth(operandType); 1174 auto resultBitWidth = getBitWidth(resultType); 1175 if (operandBitWidth != resultBitWidth) { 1176 return bitcastOp.emitOpError("mismatch in result type bitwidth ") 1177 << resultBitWidth << " and operand type bitwidth " 1178 << operandBitWidth; 1179 } 1180 return success(); 1181 } 1182 1183 //===----------------------------------------------------------------------===// 1184 // spv.BranchOp 1185 //===----------------------------------------------------------------------===// 1186 1187 Optional<MutableOperandRange> 1188 spirv::BranchOp::getMutableSuccessorOperands(unsigned index) { 1189 assert(index == 0 && "invalid successor index"); 1190 return targetOperandsMutable(); 1191 } 1192 1193 //===----------------------------------------------------------------------===// 1194 // spv.BranchConditionalOp 1195 //===----------------------------------------------------------------------===// 1196 1197 Optional<MutableOperandRange> 1198 spirv::BranchConditionalOp::getMutableSuccessorOperands(unsigned index) { 1199 assert(index < 2 && "invalid successor index"); 1200 return index == kTrueIndex ? trueTargetOperandsMutable() 1201 : falseTargetOperandsMutable(); 1202 } 1203 1204 static ParseResult parseBranchConditionalOp(OpAsmParser &parser, 1205 OperationState &state) { 1206 auto &builder = parser.getBuilder(); 1207 OpAsmParser::OperandType condInfo; 1208 Block *dest; 1209 1210 // Parse the condition. 1211 Type boolTy = builder.getI1Type(); 1212 if (parser.parseOperand(condInfo) || 1213 parser.resolveOperand(condInfo, boolTy, state.operands)) 1214 return failure(); 1215 1216 // Parse the optional branch weights. 1217 if (succeeded(parser.parseOptionalLSquare())) { 1218 IntegerAttr trueWeight, falseWeight; 1219 NamedAttrList weights; 1220 1221 auto i32Type = builder.getIntegerType(32); 1222 if (parser.parseAttribute(trueWeight, i32Type, "weight", weights) || 1223 parser.parseComma() || 1224 parser.parseAttribute(falseWeight, i32Type, "weight", weights) || 1225 parser.parseRSquare()) 1226 return failure(); 1227 1228 state.addAttribute(kBranchWeightAttrName, 1229 builder.getArrayAttr({trueWeight, falseWeight})); 1230 } 1231 1232 // Parse the true branch. 1233 SmallVector<Value, 4> trueOperands; 1234 if (parser.parseComma() || 1235 parser.parseSuccessorAndUseList(dest, trueOperands)) 1236 return failure(); 1237 state.addSuccessors(dest); 1238 state.addOperands(trueOperands); 1239 1240 // Parse the false branch. 1241 SmallVector<Value, 4> falseOperands; 1242 if (parser.parseComma() || 1243 parser.parseSuccessorAndUseList(dest, falseOperands)) 1244 return failure(); 1245 state.addSuccessors(dest); 1246 state.addOperands(falseOperands); 1247 state.addAttribute( 1248 spirv::BranchConditionalOp::getOperandSegmentSizeAttr(), 1249 builder.getI32VectorAttr({1, static_cast<int32_t>(trueOperands.size()), 1250 static_cast<int32_t>(falseOperands.size())})); 1251 1252 return success(); 1253 } 1254 1255 static void print(spirv::BranchConditionalOp branchOp, OpAsmPrinter &printer) { 1256 printer << spirv::BranchConditionalOp::getOperationName() << ' ' 1257 << branchOp.condition(); 1258 1259 if (auto weights = branchOp.branch_weights()) { 1260 printer << " ["; 1261 llvm::interleaveComma(weights->getValue(), printer, [&](Attribute a) { 1262 printer << a.cast<IntegerAttr>().getInt(); 1263 }); 1264 printer << "]"; 1265 } 1266 1267 printer << ", "; 1268 printer.printSuccessorAndUseList(branchOp.getTrueBlock(), 1269 branchOp.getTrueBlockArguments()); 1270 printer << ", "; 1271 printer.printSuccessorAndUseList(branchOp.getFalseBlock(), 1272 branchOp.getFalseBlockArguments()); 1273 } 1274 1275 static LogicalResult verify(spirv::BranchConditionalOp branchOp) { 1276 if (auto weights = branchOp.branch_weights()) { 1277 if (weights->getValue().size() != 2) { 1278 return branchOp.emitOpError("must have exactly two branch weights"); 1279 } 1280 if (llvm::all_of(*weights, [](Attribute attr) { 1281 return attr.cast<IntegerAttr>().getValue().isNullValue(); 1282 })) 1283 return branchOp.emitOpError("branch weights cannot both be zero"); 1284 } 1285 1286 return success(); 1287 } 1288 1289 //===----------------------------------------------------------------------===// 1290 // spv.CompositeConstruct 1291 //===----------------------------------------------------------------------===// 1292 1293 static ParseResult parseCompositeConstructOp(OpAsmParser &parser, 1294 OperationState &state) { 1295 SmallVector<OpAsmParser::OperandType, 4> operands; 1296 Type type; 1297 auto loc = parser.getCurrentLocation(); 1298 1299 if (parser.parseOperandList(operands) || parser.parseColonType(type)) { 1300 return failure(); 1301 } 1302 auto cType = type.dyn_cast<spirv::CompositeType>(); 1303 if (!cType) { 1304 return parser.emitError( 1305 loc, "result type must be a composite type, but provided ") 1306 << type; 1307 } 1308 1309 if (cType.hasCompileTimeKnownNumElements() && 1310 operands.size() != cType.getNumElements()) { 1311 return parser.emitError(loc, "has incorrect number of operands: expected ") 1312 << cType.getNumElements() << ", but provided " << operands.size(); 1313 } 1314 // TODO: Add support for constructing a vector type from the vector operands. 1315 // According to the spec: "for constructing a vector, the operands may 1316 // also be vectors with the same component type as the Result Type component 1317 // type". 1318 SmallVector<Type, 4> elementTypes; 1319 elementTypes.reserve(operands.size()); 1320 for (auto index : llvm::seq<uint32_t>(0, operands.size())) { 1321 elementTypes.push_back(cType.getElementType(index)); 1322 } 1323 state.addTypes(type); 1324 return parser.resolveOperands(operands, elementTypes, loc, state.operands); 1325 } 1326 1327 static void print(spirv::CompositeConstructOp compositeConstructOp, 1328 OpAsmPrinter &printer) { 1329 printer << spirv::CompositeConstructOp::getOperationName() << " " 1330 << compositeConstructOp.constituents() << " : " 1331 << compositeConstructOp.getResult().getType(); 1332 } 1333 1334 static LogicalResult verify(spirv::CompositeConstructOp compositeConstructOp) { 1335 auto cType = compositeConstructOp.getType().cast<spirv::CompositeType>(); 1336 SmallVector<Value, 4> constituents(compositeConstructOp.constituents()); 1337 1338 if (cType.isa<spirv::CooperativeMatrixNVType>()) { 1339 if (constituents.size() != 1) 1340 return compositeConstructOp.emitError( 1341 "has incorrect number of operands: expected ") 1342 << "1, but provided " << constituents.size(); 1343 } else if (constituents.size() != cType.getNumElements()) { 1344 return compositeConstructOp.emitError( 1345 "has incorrect number of operands: expected ") 1346 << cType.getNumElements() << ", but provided " 1347 << constituents.size(); 1348 } 1349 1350 for (auto index : llvm::seq<uint32_t>(0, constituents.size())) { 1351 if (constituents[index].getType() != cType.getElementType(index)) { 1352 return compositeConstructOp.emitError( 1353 "operand type mismatch: expected operand type ") 1354 << cType.getElementType(index) << ", but provided " 1355 << constituents[index].getType(); 1356 } 1357 } 1358 1359 return success(); 1360 } 1361 1362 //===----------------------------------------------------------------------===// 1363 // spv.CompositeExtractOp 1364 //===----------------------------------------------------------------------===// 1365 1366 void spirv::CompositeExtractOp::build(OpBuilder &builder, OperationState &state, 1367 Value composite, 1368 ArrayRef<int32_t> indices) { 1369 auto indexAttr = builder.getI32ArrayAttr(indices); 1370 auto elementType = 1371 getElementType(composite.getType(), indexAttr, state.location); 1372 if (!elementType) { 1373 return; 1374 } 1375 build(builder, state, elementType, composite, indexAttr); 1376 } 1377 1378 static ParseResult parseCompositeExtractOp(OpAsmParser &parser, 1379 OperationState &state) { 1380 OpAsmParser::OperandType compositeInfo; 1381 Attribute indicesAttr; 1382 Type compositeType; 1383 llvm::SMLoc attrLocation; 1384 1385 if (parser.parseOperand(compositeInfo) || 1386 parser.getCurrentLocation(&attrLocation) || 1387 parser.parseAttribute(indicesAttr, kIndicesAttrName, state.attributes) || 1388 parser.parseColonType(compositeType) || 1389 parser.resolveOperand(compositeInfo, compositeType, state.operands)) { 1390 return failure(); 1391 } 1392 1393 Type resultType = 1394 getElementType(compositeType, indicesAttr, parser, attrLocation); 1395 if (!resultType) { 1396 return failure(); 1397 } 1398 state.addTypes(resultType); 1399 return success(); 1400 } 1401 1402 static void print(spirv::CompositeExtractOp compositeExtractOp, 1403 OpAsmPrinter &printer) { 1404 printer << spirv::CompositeExtractOp::getOperationName() << ' ' 1405 << compositeExtractOp.composite() << compositeExtractOp.indices() 1406 << " : " << compositeExtractOp.composite().getType(); 1407 } 1408 1409 static LogicalResult verify(spirv::CompositeExtractOp compExOp) { 1410 auto indicesArrayAttr = compExOp.indices().dyn_cast<ArrayAttr>(); 1411 auto resultType = getElementType(compExOp.composite().getType(), 1412 indicesArrayAttr, compExOp.getLoc()); 1413 if (!resultType) 1414 return failure(); 1415 1416 if (resultType != compExOp.getType()) { 1417 return compExOp.emitOpError("invalid result type: expected ") 1418 << resultType << " but provided " << compExOp.getType(); 1419 } 1420 1421 return success(); 1422 } 1423 1424 //===----------------------------------------------------------------------===// 1425 // spv.CompositeInsert 1426 //===----------------------------------------------------------------------===// 1427 1428 void spirv::CompositeInsertOp::build(OpBuilder &builder, OperationState &state, 1429 Value object, Value composite, 1430 ArrayRef<int32_t> indices) { 1431 auto indexAttr = builder.getI32ArrayAttr(indices); 1432 build(builder, state, composite.getType(), object, composite, indexAttr); 1433 } 1434 1435 static ParseResult parseCompositeInsertOp(OpAsmParser &parser, 1436 OperationState &state) { 1437 SmallVector<OpAsmParser::OperandType, 2> operands; 1438 Type objectType, compositeType; 1439 Attribute indicesAttr; 1440 auto loc = parser.getCurrentLocation(); 1441 1442 return failure( 1443 parser.parseOperandList(operands, 2) || 1444 parser.parseAttribute(indicesAttr, kIndicesAttrName, state.attributes) || 1445 parser.parseColonType(objectType) || 1446 parser.parseKeywordType("into", compositeType) || 1447 parser.resolveOperands(operands, {objectType, compositeType}, loc, 1448 state.operands) || 1449 parser.addTypesToList(compositeType, state.types)); 1450 } 1451 1452 static LogicalResult verify(spirv::CompositeInsertOp compositeInsertOp) { 1453 auto indicesArrayAttr = compositeInsertOp.indices().dyn_cast<ArrayAttr>(); 1454 auto objectType = 1455 getElementType(compositeInsertOp.composite().getType(), indicesArrayAttr, 1456 compositeInsertOp.getLoc()); 1457 if (!objectType) 1458 return failure(); 1459 1460 if (objectType != compositeInsertOp.object().getType()) { 1461 return compositeInsertOp.emitOpError("object operand type should be ") 1462 << objectType << ", but found " 1463 << compositeInsertOp.object().getType(); 1464 } 1465 1466 if (compositeInsertOp.composite().getType() != compositeInsertOp.getType()) { 1467 return compositeInsertOp.emitOpError("result type should be the same as " 1468 "the composite type, but found ") 1469 << compositeInsertOp.composite().getType() << " vs " 1470 << compositeInsertOp.getType(); 1471 } 1472 1473 return success(); 1474 } 1475 1476 static void print(spirv::CompositeInsertOp compositeInsertOp, 1477 OpAsmPrinter &printer) { 1478 printer << spirv::CompositeInsertOp::getOperationName() << " " 1479 << compositeInsertOp.object() << ", " << compositeInsertOp.composite() 1480 << compositeInsertOp.indices() << " : " 1481 << compositeInsertOp.object().getType() << " into " 1482 << compositeInsertOp.composite().getType(); 1483 } 1484 1485 //===----------------------------------------------------------------------===// 1486 // spv.Constant 1487 //===----------------------------------------------------------------------===// 1488 1489 static ParseResult parseConstantOp(OpAsmParser &parser, OperationState &state) { 1490 Attribute value; 1491 if (parser.parseAttribute(value, kValueAttrName, state.attributes)) 1492 return failure(); 1493 1494 Type type = value.getType(); 1495 if (type.isa<NoneType, TensorType>()) { 1496 if (parser.parseColonType(type)) 1497 return failure(); 1498 } 1499 1500 return parser.addTypeToList(type, state.types); 1501 } 1502 1503 static void print(spirv::ConstantOp constOp, OpAsmPrinter &printer) { 1504 printer << spirv::ConstantOp::getOperationName() << ' ' << constOp.value(); 1505 if (constOp.getType().isa<spirv::ArrayType>()) 1506 printer << " : " << constOp.getType(); 1507 } 1508 1509 static LogicalResult verify(spirv::ConstantOp constOp) { 1510 auto opType = constOp.getType(); 1511 auto value = constOp.value(); 1512 auto valueType = value.getType(); 1513 1514 // ODS already generates checks to make sure the result type is valid. We just 1515 // need to additionally check that the value's attribute type is consistent 1516 // with the result type. 1517 if (value.isa<IntegerAttr, FloatAttr>()) { 1518 if (valueType != opType) 1519 return constOp.emitOpError("result type (") 1520 << opType << ") does not match value type (" << valueType << ")"; 1521 return success(); 1522 } 1523 if (value.isa<DenseIntOrFPElementsAttr, SparseElementsAttr>()) { 1524 if (valueType == opType) 1525 return success(); 1526 auto arrayType = opType.dyn_cast<spirv::ArrayType>(); 1527 auto shapedType = valueType.dyn_cast<ShapedType>(); 1528 if (!arrayType) { 1529 return constOp.emitOpError( 1530 "must have spv.array result type for array value"); 1531 } 1532 1533 int numElements = arrayType.getNumElements(); 1534 auto opElemType = arrayType.getElementType(); 1535 while (auto t = opElemType.dyn_cast<spirv::ArrayType>()) { 1536 numElements *= t.getNumElements(); 1537 opElemType = t.getElementType(); 1538 } 1539 if (!opElemType.isIntOrFloat()) 1540 return constOp.emitOpError("only support nested array result type"); 1541 1542 auto valueElemType = shapedType.getElementType(); 1543 if (valueElemType != opElemType) { 1544 return constOp.emitOpError("result element type (") 1545 << opElemType << ") does not match value element type (" 1546 << valueElemType << ")"; 1547 } 1548 1549 if (numElements != shapedType.getNumElements()) { 1550 return constOp.emitOpError("result number of elements (") 1551 << numElements << ") does not match value number of elements (" 1552 << shapedType.getNumElements() << ")"; 1553 } 1554 return success(); 1555 } 1556 if (auto attayAttr = value.dyn_cast<ArrayAttr>()) { 1557 auto arrayType = opType.dyn_cast<spirv::ArrayType>(); 1558 if (!arrayType) 1559 return constOp.emitOpError( 1560 "must have spv.array result type for array value"); 1561 Type elemType = arrayType.getElementType(); 1562 for (Attribute element : attayAttr.getValue()) { 1563 if (element.getType() != elemType) 1564 return constOp.emitOpError("has array element whose type (") 1565 << element.getType() 1566 << ") does not match the result element type (" << elemType 1567 << ')'; 1568 } 1569 return success(); 1570 } 1571 return constOp.emitOpError("cannot have value of type ") << valueType; 1572 } 1573 1574 bool spirv::ConstantOp::isBuildableWith(Type type) { 1575 // Must be valid SPIR-V type first. 1576 if (!type.isa<spirv::SPIRVType>()) 1577 return false; 1578 1579 if (isa<SPIRVDialect>(type.getDialect())) { 1580 // TODO: support constant struct 1581 return type.isa<spirv::ArrayType>(); 1582 } 1583 1584 return true; 1585 } 1586 1587 spirv::ConstantOp spirv::ConstantOp::getZero(Type type, Location loc, 1588 OpBuilder &builder) { 1589 if (auto intType = type.dyn_cast<IntegerType>()) { 1590 unsigned width = intType.getWidth(); 1591 if (width == 1) 1592 return builder.create<spirv::ConstantOp>(loc, type, 1593 builder.getBoolAttr(false)); 1594 return builder.create<spirv::ConstantOp>( 1595 loc, type, builder.getIntegerAttr(type, APInt(width, 0))); 1596 } 1597 if (auto floatType = type.dyn_cast<FloatType>()) { 1598 return builder.create<spirv::ConstantOp>( 1599 loc, type, builder.getFloatAttr(floatType, 0.0)); 1600 } 1601 if (auto vectorType = type.dyn_cast<VectorType>()) { 1602 Type elemType = vectorType.getElementType(); 1603 if (elemType.isa<IntegerType>()) { 1604 return builder.create<spirv::ConstantOp>( 1605 loc, type, 1606 DenseElementsAttr::get(vectorType, 1607 IntegerAttr::get(elemType, 0.0).getValue())); 1608 } 1609 if (elemType.isa<FloatType>()) { 1610 return builder.create<spirv::ConstantOp>( 1611 loc, type, 1612 DenseFPElementsAttr::get(vectorType, 1613 FloatAttr::get(elemType, 0.0).getValue())); 1614 } 1615 } 1616 1617 llvm_unreachable("unimplemented types for ConstantOp::getZero()"); 1618 } 1619 1620 spirv::ConstantOp spirv::ConstantOp::getOne(Type type, Location loc, 1621 OpBuilder &builder) { 1622 if (auto intType = type.dyn_cast<IntegerType>()) { 1623 unsigned width = intType.getWidth(); 1624 if (width == 1) 1625 return builder.create<spirv::ConstantOp>(loc, type, 1626 builder.getBoolAttr(true)); 1627 return builder.create<spirv::ConstantOp>( 1628 loc, type, builder.getIntegerAttr(type, APInt(width, 1))); 1629 } 1630 if (auto floatType = type.dyn_cast<FloatType>()) { 1631 return builder.create<spirv::ConstantOp>( 1632 loc, type, builder.getFloatAttr(floatType, 1.0)); 1633 } 1634 if (auto vectorType = type.dyn_cast<VectorType>()) { 1635 Type elemType = vectorType.getElementType(); 1636 if (elemType.isa<IntegerType>()) { 1637 return builder.create<spirv::ConstantOp>( 1638 loc, type, 1639 DenseElementsAttr::get(vectorType, 1640 IntegerAttr::get(elemType, 1.0).getValue())); 1641 } 1642 if (elemType.isa<FloatType>()) { 1643 return builder.create<spirv::ConstantOp>( 1644 loc, type, 1645 DenseFPElementsAttr::get(vectorType, 1646 FloatAttr::get(elemType, 1.0).getValue())); 1647 } 1648 } 1649 1650 llvm_unreachable("unimplemented types for ConstantOp::getOne()"); 1651 } 1652 1653 //===----------------------------------------------------------------------===// 1654 // spv.EntryPoint 1655 //===----------------------------------------------------------------------===// 1656 1657 void spirv::EntryPointOp::build(OpBuilder &builder, OperationState &state, 1658 spirv::ExecutionModel executionModel, 1659 spirv::FuncOp function, 1660 ArrayRef<Attribute> interfaceVars) { 1661 build(builder, state, 1662 spirv::ExecutionModelAttr::get(builder.getContext(), executionModel), 1663 builder.getSymbolRefAttr(function), 1664 builder.getArrayAttr(interfaceVars)); 1665 } 1666 1667 static ParseResult parseEntryPointOp(OpAsmParser &parser, 1668 OperationState &state) { 1669 spirv::ExecutionModel execModel; 1670 SmallVector<OpAsmParser::OperandType, 0> identifiers; 1671 SmallVector<Type, 0> idTypes; 1672 SmallVector<Attribute, 4> interfaceVars; 1673 1674 FlatSymbolRefAttr fn; 1675 if (parseEnumStrAttr(execModel, parser, state) || 1676 parser.parseAttribute(fn, Type(), kFnNameAttrName, state.attributes)) { 1677 return failure(); 1678 } 1679 1680 if (!parser.parseOptionalComma()) { 1681 // Parse the interface variables 1682 do { 1683 // The name of the interface variable attribute isnt important 1684 auto attrName = "var_symbol"; 1685 FlatSymbolRefAttr var; 1686 NamedAttrList attrs; 1687 if (parser.parseAttribute(var, Type(), attrName, attrs)) { 1688 return failure(); 1689 } 1690 interfaceVars.push_back(var); 1691 } while (!parser.parseOptionalComma()); 1692 } 1693 state.addAttribute(kInterfaceAttrName, 1694 parser.getBuilder().getArrayAttr(interfaceVars)); 1695 return success(); 1696 } 1697 1698 static void print(spirv::EntryPointOp entryPointOp, OpAsmPrinter &printer) { 1699 printer << spirv::EntryPointOp::getOperationName() << " \"" 1700 << stringifyExecutionModel(entryPointOp.execution_model()) << "\" "; 1701 printer.printSymbolName(entryPointOp.fn()); 1702 auto interfaceVars = entryPointOp.interface().getValue(); 1703 if (!interfaceVars.empty()) { 1704 printer << ", "; 1705 llvm::interleaveComma(interfaceVars, printer); 1706 } 1707 } 1708 1709 static LogicalResult verify(spirv::EntryPointOp entryPointOp) { 1710 // Checks for fn and interface symbol reference are done in spirv::ModuleOp 1711 // verification. 1712 return success(); 1713 } 1714 1715 //===----------------------------------------------------------------------===// 1716 // spv.ExecutionMode 1717 //===----------------------------------------------------------------------===// 1718 1719 void spirv::ExecutionModeOp::build(OpBuilder &builder, OperationState &state, 1720 spirv::FuncOp function, 1721 spirv::ExecutionMode executionMode, 1722 ArrayRef<int32_t> params) { 1723 build(builder, state, builder.getSymbolRefAttr(function), 1724 spirv::ExecutionModeAttr::get(builder.getContext(), executionMode), 1725 builder.getI32ArrayAttr(params)); 1726 } 1727 1728 static ParseResult parseExecutionModeOp(OpAsmParser &parser, 1729 OperationState &state) { 1730 spirv::ExecutionMode execMode; 1731 Attribute fn; 1732 if (parser.parseAttribute(fn, kFnNameAttrName, state.attributes) || 1733 parseEnumStrAttr(execMode, parser, state)) { 1734 return failure(); 1735 } 1736 1737 SmallVector<int32_t, 4> values; 1738 Type i32Type = parser.getBuilder().getIntegerType(32); 1739 while (!parser.parseOptionalComma()) { 1740 NamedAttrList attr; 1741 Attribute value; 1742 if (parser.parseAttribute(value, i32Type, "value", attr)) { 1743 return failure(); 1744 } 1745 values.push_back(value.cast<IntegerAttr>().getInt()); 1746 } 1747 state.addAttribute(kValuesAttrName, 1748 parser.getBuilder().getI32ArrayAttr(values)); 1749 return success(); 1750 } 1751 1752 static void print(spirv::ExecutionModeOp execModeOp, OpAsmPrinter &printer) { 1753 printer << spirv::ExecutionModeOp::getOperationName() << " "; 1754 printer.printSymbolName(execModeOp.fn()); 1755 printer << " \"" << stringifyExecutionMode(execModeOp.execution_mode()) 1756 << "\""; 1757 auto values = execModeOp.values(); 1758 if (!values.size()) 1759 return; 1760 printer << ", "; 1761 llvm::interleaveComma(values, printer, [&](Attribute a) { 1762 printer << a.cast<IntegerAttr>().getInt(); 1763 }); 1764 } 1765 1766 //===----------------------------------------------------------------------===// 1767 // spv.func 1768 //===----------------------------------------------------------------------===// 1769 1770 static ParseResult parseFuncOp(OpAsmParser &parser, OperationState &state) { 1771 SmallVector<OpAsmParser::OperandType, 4> entryArgs; 1772 SmallVector<NamedAttrList, 4> argAttrs; 1773 SmallVector<NamedAttrList, 4> resultAttrs; 1774 SmallVector<Type, 4> argTypes; 1775 SmallVector<Type, 4> resultTypes; 1776 auto &builder = parser.getBuilder(); 1777 1778 // Parse the name as a symbol. 1779 StringAttr nameAttr; 1780 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(), 1781 state.attributes)) 1782 return failure(); 1783 1784 // Parse the function signature. 1785 bool isVariadic = false; 1786 if (function_like_impl::parseFunctionSignature( 1787 parser, /*allowVariadic=*/false, entryArgs, argTypes, argAttrs, 1788 isVariadic, resultTypes, resultAttrs)) 1789 return failure(); 1790 1791 auto fnType = builder.getFunctionType(argTypes, resultTypes); 1792 state.addAttribute(function_like_impl::getTypeAttrName(), 1793 TypeAttr::get(fnType)); 1794 1795 // Parse the optional function control keyword. 1796 spirv::FunctionControl fnControl; 1797 if (parseEnumStrAttr(fnControl, parser, state)) 1798 return failure(); 1799 1800 // If additional attributes are present, parse them. 1801 if (parser.parseOptionalAttrDictWithKeyword(state.attributes)) 1802 return failure(); 1803 1804 // Add the attributes to the function arguments. 1805 assert(argAttrs.size() == argTypes.size()); 1806 assert(resultAttrs.size() == resultTypes.size()); 1807 function_like_impl::addArgAndResultAttrs(builder, state, argAttrs, 1808 resultAttrs); 1809 1810 // Parse the optional function body. 1811 auto *body = state.addRegion(); 1812 OptionalParseResult result = parser.parseOptionalRegion( 1813 *body, entryArgs, entryArgs.empty() ? ArrayRef<Type>() : argTypes); 1814 return failure(result.hasValue() && failed(*result)); 1815 } 1816 1817 static void print(spirv::FuncOp fnOp, OpAsmPrinter &printer) { 1818 // Print function name, signature, and control. 1819 printer << spirv::FuncOp::getOperationName() << " "; 1820 printer.printSymbolName(fnOp.sym_name()); 1821 auto fnType = fnOp.getType(); 1822 function_like_impl::printFunctionSignature(printer, fnOp, fnType.getInputs(), 1823 /*isVariadic=*/false, 1824 fnType.getResults()); 1825 printer << " \"" << spirv::stringifyFunctionControl(fnOp.function_control()) 1826 << "\""; 1827 function_like_impl::printFunctionAttributes( 1828 printer, fnOp, fnType.getNumInputs(), fnType.getNumResults(), 1829 {spirv::attributeName<spirv::FunctionControl>()}); 1830 1831 // Print the body if this is not an external function. 1832 Region &body = fnOp.body(); 1833 if (!body.empty()) 1834 printer.printRegion(body, /*printEntryBlockArgs=*/false, 1835 /*printBlockTerminators=*/true); 1836 } 1837 1838 LogicalResult spirv::FuncOp::verifyType() { 1839 auto type = getTypeAttr().getValue(); 1840 if (!type.isa<FunctionType>()) 1841 return emitOpError("requires '" + getTypeAttrName() + 1842 "' attribute of function type"); 1843 if (getType().getNumResults() > 1) 1844 return emitOpError("cannot have more than one result"); 1845 return success(); 1846 } 1847 1848 LogicalResult spirv::FuncOp::verifyBody() { 1849 FunctionType fnType = getType(); 1850 1851 auto walkResult = walk([fnType](Operation *op) -> WalkResult { 1852 if (auto retOp = dyn_cast<spirv::ReturnOp>(op)) { 1853 if (fnType.getNumResults() != 0) 1854 return retOp.emitOpError("cannot be used in functions returning value"); 1855 } else if (auto retOp = dyn_cast<spirv::ReturnValueOp>(op)) { 1856 if (fnType.getNumResults() != 1) 1857 return retOp.emitOpError( 1858 "returns 1 value but enclosing function requires ") 1859 << fnType.getNumResults() << " results"; 1860 1861 auto retOperandType = retOp.value().getType(); 1862 auto fnResultType = fnType.getResult(0); 1863 if (retOperandType != fnResultType) 1864 return retOp.emitOpError(" return value's type (") 1865 << retOperandType << ") mismatch with function's result type (" 1866 << fnResultType << ")"; 1867 } 1868 return WalkResult::advance(); 1869 }); 1870 1871 // TODO: verify other bits like linkage type. 1872 1873 return failure(walkResult.wasInterrupted()); 1874 } 1875 1876 void spirv::FuncOp::build(OpBuilder &builder, OperationState &state, 1877 StringRef name, FunctionType type, 1878 spirv::FunctionControl control, 1879 ArrayRef<NamedAttribute> attrs) { 1880 state.addAttribute(SymbolTable::getSymbolAttrName(), 1881 builder.getStringAttr(name)); 1882 state.addAttribute(getTypeAttrName(), TypeAttr::get(type)); 1883 state.addAttribute(spirv::attributeName<spirv::FunctionControl>(), 1884 builder.getI32IntegerAttr(static_cast<uint32_t>(control))); 1885 state.attributes.append(attrs.begin(), attrs.end()); 1886 state.addRegion(); 1887 } 1888 1889 // CallableOpInterface 1890 Region *spirv::FuncOp::getCallableRegion() { 1891 return isExternal() ? nullptr : &body(); 1892 } 1893 1894 // CallableOpInterface 1895 ArrayRef<Type> spirv::FuncOp::getCallableResults() { 1896 return getType().getResults(); 1897 } 1898 1899 //===----------------------------------------------------------------------===// 1900 // spv.FunctionCall 1901 //===----------------------------------------------------------------------===// 1902 1903 static LogicalResult verify(spirv::FunctionCallOp functionCallOp) { 1904 auto fnName = functionCallOp.callee(); 1905 1906 auto funcOp = 1907 dyn_cast_or_null<spirv::FuncOp>(SymbolTable::lookupNearestSymbolFrom( 1908 functionCallOp->getParentOp(), fnName)); 1909 if (!funcOp) { 1910 return functionCallOp.emitOpError("callee function '") 1911 << fnName << "' not found in nearest symbol table"; 1912 } 1913 1914 auto functionType = funcOp.getType(); 1915 1916 if (functionCallOp.getNumResults() > 1) { 1917 return functionCallOp.emitOpError( 1918 "expected callee function to have 0 or 1 result, but provided ") 1919 << functionCallOp.getNumResults(); 1920 } 1921 1922 if (functionType.getNumInputs() != functionCallOp.getNumOperands()) { 1923 return functionCallOp.emitOpError( 1924 "has incorrect number of operands for callee: expected ") 1925 << functionType.getNumInputs() << ", but provided " 1926 << functionCallOp.getNumOperands(); 1927 } 1928 1929 for (uint32_t i = 0, e = functionType.getNumInputs(); i != e; ++i) { 1930 if (functionCallOp.getOperand(i).getType() != functionType.getInput(i)) { 1931 return functionCallOp.emitOpError( 1932 "operand type mismatch: expected operand type ") 1933 << functionType.getInput(i) << ", but provided " 1934 << functionCallOp.getOperand(i).getType() << " for operand number " 1935 << i; 1936 } 1937 } 1938 1939 if (functionType.getNumResults() != functionCallOp.getNumResults()) { 1940 return functionCallOp.emitOpError( 1941 "has incorrect number of results has for callee: expected ") 1942 << functionType.getNumResults() << ", but provided " 1943 << functionCallOp.getNumResults(); 1944 } 1945 1946 if (functionCallOp.getNumResults() && 1947 (functionCallOp.getResult(0).getType() != functionType.getResult(0))) { 1948 return functionCallOp.emitOpError("result type mismatch: expected ") 1949 << functionType.getResult(0) << ", but provided " 1950 << functionCallOp.getResult(0).getType(); 1951 } 1952 1953 return success(); 1954 } 1955 1956 CallInterfaceCallable spirv::FunctionCallOp::getCallableForCallee() { 1957 return (*this)->getAttrOfType<SymbolRefAttr>(kCallee); 1958 } 1959 1960 Operation::operand_range spirv::FunctionCallOp::getArgOperands() { 1961 return arguments(); 1962 } 1963 1964 //===----------------------------------------------------------------------===// 1965 // spv.GlobalVariable 1966 //===----------------------------------------------------------------------===// 1967 1968 void spirv::GlobalVariableOp::build(OpBuilder &builder, OperationState &state, 1969 Type type, StringRef name, 1970 unsigned descriptorSet, unsigned binding) { 1971 build(builder, state, TypeAttr::get(type), builder.getStringAttr(name), 1972 nullptr); 1973 state.addAttribute( 1974 spirv::SPIRVDialect::getAttributeName(spirv::Decoration::DescriptorSet), 1975 builder.getI32IntegerAttr(descriptorSet)); 1976 state.addAttribute( 1977 spirv::SPIRVDialect::getAttributeName(spirv::Decoration::Binding), 1978 builder.getI32IntegerAttr(binding)); 1979 } 1980 1981 void spirv::GlobalVariableOp::build(OpBuilder &builder, OperationState &state, 1982 Type type, StringRef name, 1983 spirv::BuiltIn builtin) { 1984 build(builder, state, TypeAttr::get(type), builder.getStringAttr(name), 1985 nullptr); 1986 state.addAttribute( 1987 spirv::SPIRVDialect::getAttributeName(spirv::Decoration::BuiltIn), 1988 builder.getStringAttr(spirv::stringifyBuiltIn(builtin))); 1989 } 1990 1991 static ParseResult parseGlobalVariableOp(OpAsmParser &parser, 1992 OperationState &state) { 1993 // Parse variable name. 1994 StringAttr nameAttr; 1995 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(), 1996 state.attributes)) { 1997 return failure(); 1998 } 1999 2000 // Parse optional initializer 2001 if (succeeded(parser.parseOptionalKeyword(kInitializerAttrName))) { 2002 FlatSymbolRefAttr initSymbol; 2003 if (parser.parseLParen() || 2004 parser.parseAttribute(initSymbol, Type(), kInitializerAttrName, 2005 state.attributes) || 2006 parser.parseRParen()) 2007 return failure(); 2008 } 2009 2010 if (parseVariableDecorations(parser, state)) { 2011 return failure(); 2012 } 2013 2014 Type type; 2015 auto loc = parser.getCurrentLocation(); 2016 if (parser.parseColonType(type)) { 2017 return failure(); 2018 } 2019 if (!type.isa<spirv::PointerType>()) { 2020 return parser.emitError(loc, "expected spv.ptr type"); 2021 } 2022 state.addAttribute(kTypeAttrName, TypeAttr::get(type)); 2023 2024 return success(); 2025 } 2026 2027 static void print(spirv::GlobalVariableOp varOp, OpAsmPrinter &printer) { 2028 auto *op = varOp.getOperation(); 2029 SmallVector<StringRef, 4> elidedAttrs{ 2030 spirv::attributeName<spirv::StorageClass>()}; 2031 printer << spirv::GlobalVariableOp::getOperationName(); 2032 2033 // Print variable name. 2034 printer << ' '; 2035 printer.printSymbolName(varOp.sym_name()); 2036 elidedAttrs.push_back(SymbolTable::getSymbolAttrName()); 2037 2038 // Print optional initializer 2039 if (auto initializer = varOp.initializer()) { 2040 printer << " " << kInitializerAttrName << '('; 2041 printer.printSymbolName(initializer.getValue()); 2042 printer << ')'; 2043 elidedAttrs.push_back(kInitializerAttrName); 2044 } 2045 2046 elidedAttrs.push_back(kTypeAttrName); 2047 printVariableDecorations(op, printer, elidedAttrs); 2048 printer << " : " << varOp.type(); 2049 } 2050 2051 static LogicalResult verify(spirv::GlobalVariableOp varOp) { 2052 // SPIR-V spec: "Storage Class is the Storage Class of the memory holding the 2053 // object. It cannot be Generic. It must be the same as the Storage Class 2054 // operand of the Result Type." 2055 // Also, Function storage class is reserved by spv.Variable. 2056 auto storageClass = varOp.storageClass(); 2057 if (storageClass == spirv::StorageClass::Generic || 2058 storageClass == spirv::StorageClass::Function) { 2059 return varOp.emitOpError("storage class cannot be '") 2060 << stringifyStorageClass(storageClass) << "'"; 2061 } 2062 2063 if (auto init = 2064 varOp->getAttrOfType<FlatSymbolRefAttr>(kInitializerAttrName)) { 2065 Operation *initOp = SymbolTable::lookupNearestSymbolFrom( 2066 varOp->getParentOp(), init.getValue()); 2067 // TODO: Currently only variable initialization with specialization 2068 // constants and other variables is supported. They could be normal 2069 // constants in the module scope as well. 2070 if (!initOp || 2071 !isa<spirv::GlobalVariableOp, spirv::SpecConstantOp>(initOp)) { 2072 return varOp.emitOpError("initializer must be result of a " 2073 "spv.SpecConstant or spv.GlobalVariable op"); 2074 } 2075 } 2076 2077 return success(); 2078 } 2079 2080 //===----------------------------------------------------------------------===// 2081 // spv.GroupBroadcast 2082 //===----------------------------------------------------------------------===// 2083 2084 static LogicalResult verify(spirv::GroupBroadcastOp broadcastOp) { 2085 spirv::Scope scope = broadcastOp.execution_scope(); 2086 if (scope != spirv::Scope::Workgroup && scope != spirv::Scope::Subgroup) 2087 return broadcastOp.emitOpError( 2088 "execution scope must be 'Workgroup' or 'Subgroup'"); 2089 2090 if (auto localIdTy = broadcastOp.localid().getType().dyn_cast<VectorType>()) 2091 if (!(localIdTy.getNumElements() == 2 || localIdTy.getNumElements() == 3)) 2092 return broadcastOp.emitOpError("localid is a vector and can be with only " 2093 " 2 or 3 components, actual number is ") 2094 << localIdTy.getNumElements(); 2095 2096 return success(); 2097 } 2098 2099 //===----------------------------------------------------------------------===// 2100 // spv.GroupNonUniformBallotOp 2101 //===----------------------------------------------------------------------===// 2102 2103 static LogicalResult verify(spirv::GroupNonUniformBallotOp ballotOp) { 2104 spirv::Scope scope = ballotOp.execution_scope(); 2105 if (scope != spirv::Scope::Workgroup && scope != spirv::Scope::Subgroup) 2106 return ballotOp.emitOpError( 2107 "execution scope must be 'Workgroup' or 'Subgroup'"); 2108 2109 return success(); 2110 } 2111 2112 //===----------------------------------------------------------------------===// 2113 // spv.GroupNonUniformBroadcast 2114 //===----------------------------------------------------------------------===// 2115 2116 static LogicalResult verify(spirv::GroupNonUniformBroadcastOp broadcastOp) { 2117 spirv::Scope scope = broadcastOp.execution_scope(); 2118 if (scope != spirv::Scope::Workgroup && scope != spirv::Scope::Subgroup) 2119 return broadcastOp.emitOpError( 2120 "execution scope must be 'Workgroup' or 'Subgroup'"); 2121 2122 // SPIR-V spec: "Before version 1.5, Id must come from a 2123 // constant instruction. 2124 auto targetEnv = spirv::getDefaultTargetEnv(broadcastOp.getContext()); 2125 if (auto spirvModule = broadcastOp->getParentOfType<spirv::ModuleOp>()) 2126 targetEnv = spirv::lookupTargetEnvOrDefault(spirvModule); 2127 2128 if (targetEnv.getVersion() < spirv::Version::V_1_5) { 2129 auto *idOp = broadcastOp.id().getDefiningOp(); 2130 if (!idOp || !isa<spirv::ConstantOp, // for normal constant 2131 spirv::ReferenceOfOp>(idOp)) // for spec constant 2132 return broadcastOp.emitOpError("id must be the result of a constant op"); 2133 } 2134 2135 return success(); 2136 } 2137 2138 //===----------------------------------------------------------------------===// 2139 // spv.SubgroupBlockReadINTEL 2140 //===----------------------------------------------------------------------===// 2141 2142 static ParseResult parseSubgroupBlockReadINTELOp(OpAsmParser &parser, 2143 OperationState &state) { 2144 // Parse the storage class specification 2145 spirv::StorageClass storageClass; 2146 OpAsmParser::OperandType ptrInfo; 2147 Type elementType; 2148 if (parseEnumStrAttr(storageClass, parser) || parser.parseOperand(ptrInfo) || 2149 parser.parseColon() || parser.parseType(elementType)) { 2150 return failure(); 2151 } 2152 2153 auto ptrType = spirv::PointerType::get(elementType, storageClass); 2154 if (auto valVecTy = elementType.dyn_cast<VectorType>()) 2155 ptrType = spirv::PointerType::get(valVecTy.getElementType(), storageClass); 2156 2157 if (parser.resolveOperand(ptrInfo, ptrType, state.operands)) { 2158 return failure(); 2159 } 2160 2161 state.addTypes(elementType); 2162 return success(); 2163 } 2164 2165 static void print(spirv::SubgroupBlockReadINTELOp blockReadOp, 2166 OpAsmPrinter &printer) { 2167 SmallVector<StringRef, 4> elidedAttrs; 2168 printer << spirv::SubgroupBlockReadINTELOp::getOperationName() << " " 2169 << blockReadOp.ptr(); 2170 printer << " : " << blockReadOp.getType(); 2171 } 2172 2173 static LogicalResult verify(spirv::SubgroupBlockReadINTELOp blockReadOp) { 2174 if (failed(verifyBlockReadWritePtrAndValTypes(blockReadOp, blockReadOp.ptr(), 2175 blockReadOp.value()))) 2176 return failure(); 2177 2178 return success(); 2179 } 2180 2181 //===----------------------------------------------------------------------===// 2182 // spv.SubgroupBlockWriteINTEL 2183 //===----------------------------------------------------------------------===// 2184 2185 static ParseResult parseSubgroupBlockWriteINTELOp(OpAsmParser &parser, 2186 OperationState &state) { 2187 // Parse the storage class specification 2188 spirv::StorageClass storageClass; 2189 SmallVector<OpAsmParser::OperandType, 2> operandInfo; 2190 auto loc = parser.getCurrentLocation(); 2191 Type elementType; 2192 if (parseEnumStrAttr(storageClass, parser) || 2193 parser.parseOperandList(operandInfo, 2) || parser.parseColon() || 2194 parser.parseType(elementType)) { 2195 return failure(); 2196 } 2197 2198 auto ptrType = spirv::PointerType::get(elementType, storageClass); 2199 if (auto valVecTy = elementType.dyn_cast<VectorType>()) 2200 ptrType = spirv::PointerType::get(valVecTy.getElementType(), storageClass); 2201 2202 if (parser.resolveOperands(operandInfo, {ptrType, elementType}, loc, 2203 state.operands)) { 2204 return failure(); 2205 } 2206 return success(); 2207 } 2208 2209 static void print(spirv::SubgroupBlockWriteINTELOp blockWriteOp, 2210 OpAsmPrinter &printer) { 2211 SmallVector<StringRef, 4> elidedAttrs; 2212 printer << spirv::SubgroupBlockWriteINTELOp::getOperationName() << " " 2213 << blockWriteOp.ptr() << ", " << blockWriteOp.value(); 2214 printer << " : " << blockWriteOp.value().getType(); 2215 } 2216 2217 static LogicalResult verify(spirv::SubgroupBlockWriteINTELOp blockWriteOp) { 2218 if (failed(verifyBlockReadWritePtrAndValTypes( 2219 blockWriteOp, blockWriteOp.ptr(), blockWriteOp.value()))) 2220 return failure(); 2221 2222 return success(); 2223 } 2224 2225 //===----------------------------------------------------------------------===// 2226 // spv.GroupNonUniformElectOp 2227 //===----------------------------------------------------------------------===// 2228 2229 void spirv::GroupNonUniformElectOp::build(OpBuilder &builder, 2230 OperationState &state, 2231 spirv::Scope scope) { 2232 build(builder, state, builder.getI1Type(), scope); 2233 } 2234 2235 static LogicalResult verify(spirv::GroupNonUniformElectOp groupOp) { 2236 spirv::Scope scope = groupOp.execution_scope(); 2237 if (scope != spirv::Scope::Workgroup && scope != spirv::Scope::Subgroup) 2238 return groupOp.emitOpError( 2239 "execution scope must be 'Workgroup' or 'Subgroup'"); 2240 2241 return success(); 2242 } 2243 2244 //===----------------------------------------------------------------------===// 2245 // spv.LoadOp 2246 //===----------------------------------------------------------------------===// 2247 2248 void spirv::LoadOp::build(OpBuilder &builder, OperationState &state, 2249 Value basePtr, MemoryAccessAttr memoryAccess, 2250 IntegerAttr alignment) { 2251 auto ptrType = basePtr.getType().cast<spirv::PointerType>(); 2252 build(builder, state, ptrType.getPointeeType(), basePtr, memoryAccess, 2253 alignment); 2254 } 2255 2256 static ParseResult parseLoadOp(OpAsmParser &parser, OperationState &state) { 2257 // Parse the storage class specification 2258 spirv::StorageClass storageClass; 2259 OpAsmParser::OperandType ptrInfo; 2260 Type elementType; 2261 if (parseEnumStrAttr(storageClass, parser) || parser.parseOperand(ptrInfo) || 2262 parseMemoryAccessAttributes(parser, state) || 2263 parser.parseOptionalAttrDict(state.attributes) || parser.parseColon() || 2264 parser.parseType(elementType)) { 2265 return failure(); 2266 } 2267 2268 auto ptrType = spirv::PointerType::get(elementType, storageClass); 2269 if (parser.resolveOperand(ptrInfo, ptrType, state.operands)) { 2270 return failure(); 2271 } 2272 2273 state.addTypes(elementType); 2274 return success(); 2275 } 2276 2277 static void print(spirv::LoadOp loadOp, OpAsmPrinter &printer) { 2278 auto *op = loadOp.getOperation(); 2279 SmallVector<StringRef, 4> elidedAttrs; 2280 StringRef sc = stringifyStorageClass( 2281 loadOp.ptr().getType().cast<spirv::PointerType>().getStorageClass()); 2282 printer << spirv::LoadOp::getOperationName() << " \"" << sc << "\" " 2283 << loadOp.ptr(); 2284 2285 printMemoryAccessAttribute(loadOp, printer, elidedAttrs); 2286 2287 printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs); 2288 printer << " : " << loadOp.getType(); 2289 } 2290 2291 static LogicalResult verify(spirv::LoadOp loadOp) { 2292 // SPIR-V spec : "Result Type is the type of the loaded object. It must be a 2293 // type with fixed size; i.e., it cannot be, nor include, any 2294 // OpTypeRuntimeArray types." 2295 if (failed(verifyLoadStorePtrAndValTypes(loadOp, loadOp.ptr(), 2296 loadOp.value()))) { 2297 return failure(); 2298 } 2299 return verifyMemoryAccessAttribute(loadOp); 2300 } 2301 2302 //===----------------------------------------------------------------------===// 2303 // spv.mlir.loop 2304 //===----------------------------------------------------------------------===// 2305 2306 void spirv::LoopOp::build(OpBuilder &builder, OperationState &state) { 2307 state.addAttribute("loop_control", 2308 builder.getI32IntegerAttr( 2309 static_cast<uint32_t>(spirv::LoopControl::None))); 2310 state.addRegion(); 2311 } 2312 2313 static ParseResult parseLoopOp(OpAsmParser &parser, OperationState &state) { 2314 if (parseControlAttribute<spirv::LoopControl>(parser, state)) 2315 return failure(); 2316 return parser.parseRegion(*state.addRegion(), /*arguments=*/{}, 2317 /*argTypes=*/{}); 2318 } 2319 2320 static void print(spirv::LoopOp loopOp, OpAsmPrinter &printer) { 2321 auto *op = loopOp.getOperation(); 2322 2323 printer << spirv::LoopOp::getOperationName(); 2324 auto control = loopOp.loop_control(); 2325 if (control != spirv::LoopControl::None) 2326 printer << " control(" << spirv::stringifyLoopControl(control) << ")"; 2327 printer.printRegion(op->getRegion(0), /*printEntryBlockArgs=*/false, 2328 /*printBlockTerminators=*/true); 2329 } 2330 2331 /// Returns true if the given `srcBlock` contains only one `spv.Branch` to the 2332 /// given `dstBlock`. 2333 static inline bool hasOneBranchOpTo(Block &srcBlock, Block &dstBlock) { 2334 // Check that there is only one op in the `srcBlock`. 2335 if (!llvm::hasSingleElement(srcBlock)) 2336 return false; 2337 2338 auto branchOp = dyn_cast<spirv::BranchOp>(srcBlock.back()); 2339 return branchOp && branchOp.getSuccessor() == &dstBlock; 2340 } 2341 2342 static LogicalResult verify(spirv::LoopOp loopOp) { 2343 auto *op = loopOp.getOperation(); 2344 2345 // We need to verify that the blocks follow the following layout: 2346 // 2347 // +-------------+ 2348 // | entry block | 2349 // +-------------+ 2350 // | 2351 // v 2352 // +-------------+ 2353 // | loop header | <-----+ 2354 // +-------------+ | 2355 // | 2356 // ... | 2357 // \ | / | 2358 // v | 2359 // +---------------+ | 2360 // | loop continue | -----+ 2361 // +---------------+ 2362 // 2363 // ... 2364 // \ | / 2365 // v 2366 // +-------------+ 2367 // | merge block | 2368 // +-------------+ 2369 2370 auto ®ion = op->getRegion(0); 2371 // Allow empty region as a degenerated case, which can come from 2372 // optimizations. 2373 if (region.empty()) 2374 return success(); 2375 2376 // The last block is the merge block. 2377 Block &merge = region.back(); 2378 if (!isMergeBlock(merge)) 2379 return loopOp.emitOpError( 2380 "last block must be the merge block with only one 'spv.mlir.merge' op"); 2381 2382 if (std::next(region.begin()) == region.end()) 2383 return loopOp.emitOpError( 2384 "must have an entry block branching to the loop header block"); 2385 // The first block is the entry block. 2386 Block &entry = region.front(); 2387 2388 if (std::next(region.begin(), 2) == region.end()) 2389 return loopOp.emitOpError( 2390 "must have a loop header block branched from the entry block"); 2391 // The second block is the loop header block. 2392 Block &header = *std::next(region.begin(), 1); 2393 2394 if (!hasOneBranchOpTo(entry, header)) 2395 return loopOp.emitOpError( 2396 "entry block must only have one 'spv.Branch' op to the second block"); 2397 2398 if (std::next(region.begin(), 3) == region.end()) 2399 return loopOp.emitOpError( 2400 "requires a loop continue block branching to the loop header block"); 2401 // The second to last block is the loop continue block. 2402 Block &cont = *std::prev(region.end(), 2); 2403 2404 // Make sure that we have a branch from the loop continue block to the loop 2405 // header block. 2406 if (llvm::none_of( 2407 llvm::seq<unsigned>(0, cont.getNumSuccessors()), 2408 [&](unsigned index) { return cont.getSuccessor(index) == &header; })) 2409 return loopOp.emitOpError("second to last block must be the loop continue " 2410 "block that branches to the loop header block"); 2411 2412 // Make sure that no other blocks (except the entry and loop continue block) 2413 // branches to the loop header block. 2414 for (auto &block : llvm::make_range(std::next(region.begin(), 2), 2415 std::prev(region.end(), 2))) { 2416 for (auto i : llvm::seq<unsigned>(0, block.getNumSuccessors())) { 2417 if (block.getSuccessor(i) == &header) { 2418 return loopOp.emitOpError("can only have the entry and loop continue " 2419 "block branching to the loop header block"); 2420 } 2421 } 2422 } 2423 2424 return success(); 2425 } 2426 2427 Block *spirv::LoopOp::getEntryBlock() { 2428 assert(!body().empty() && "op region should not be empty!"); 2429 return &body().front(); 2430 } 2431 2432 Block *spirv::LoopOp::getHeaderBlock() { 2433 assert(!body().empty() && "op region should not be empty!"); 2434 // The second block is the loop header block. 2435 return &*std::next(body().begin()); 2436 } 2437 2438 Block *spirv::LoopOp::getContinueBlock() { 2439 assert(!body().empty() && "op region should not be empty!"); 2440 // The second to last block is the loop continue block. 2441 return &*std::prev(body().end(), 2); 2442 } 2443 2444 Block *spirv::LoopOp::getMergeBlock() { 2445 assert(!body().empty() && "op region should not be empty!"); 2446 // The last block is the loop merge block. 2447 return &body().back(); 2448 } 2449 2450 void spirv::LoopOp::addEntryAndMergeBlock() { 2451 assert(body().empty() && "entry and merge block already exist"); 2452 body().push_back(new Block()); 2453 auto *mergeBlock = new Block(); 2454 body().push_back(mergeBlock); 2455 OpBuilder builder = OpBuilder::atBlockEnd(mergeBlock); 2456 2457 // Add a spv.mlir.merge op into the merge block. 2458 builder.create<spirv::MergeOp>(getLoc()); 2459 } 2460 2461 //===----------------------------------------------------------------------===// 2462 // spv.mlir.merge 2463 //===----------------------------------------------------------------------===// 2464 2465 static LogicalResult verify(spirv::MergeOp mergeOp) { 2466 auto *parentOp = mergeOp->getParentOp(); 2467 if (!parentOp || !isa<spirv::SelectionOp, spirv::LoopOp>(parentOp)) 2468 return mergeOp.emitOpError( 2469 "expected parent op to be 'spv.mlir.selection' or 'spv.mlir.loop'"); 2470 2471 Block &parentLastBlock = mergeOp->getParentRegion()->back(); 2472 if (mergeOp.getOperation() != parentLastBlock.getTerminator()) 2473 return mergeOp.emitOpError("can only be used in the last block of " 2474 "'spv.mlir.selection' or 'spv.mlir.loop'"); 2475 return success(); 2476 } 2477 2478 //===----------------------------------------------------------------------===// 2479 // spv.module 2480 //===----------------------------------------------------------------------===// 2481 2482 void spirv::ModuleOp::build(OpBuilder &builder, OperationState &state, 2483 Optional<StringRef> name) { 2484 ensureTerminator(*state.addRegion(), builder, state.location); 2485 if (name) { 2486 state.attributes.append(mlir::SymbolTable::getSymbolAttrName(), 2487 builder.getStringAttr(*name)); 2488 } 2489 } 2490 2491 void spirv::ModuleOp::build(OpBuilder &builder, OperationState &state, 2492 spirv::AddressingModel addressingModel, 2493 spirv::MemoryModel memoryModel, 2494 Optional<StringRef> name) { 2495 state.addAttribute( 2496 "addressing_model", 2497 builder.getI32IntegerAttr(static_cast<int32_t>(addressingModel))); 2498 state.addAttribute("memory_model", builder.getI32IntegerAttr( 2499 static_cast<int32_t>(memoryModel))); 2500 ensureTerminator(*state.addRegion(), builder, state.location); 2501 if (name) { 2502 state.attributes.append(mlir::SymbolTable::getSymbolAttrName(), 2503 builder.getStringAttr(*name)); 2504 } 2505 } 2506 2507 static ParseResult parseModuleOp(OpAsmParser &parser, OperationState &state) { 2508 Region *body = state.addRegion(); 2509 2510 // If the name is present, parse it. 2511 StringAttr nameAttr; 2512 parser.parseOptionalSymbolName(nameAttr, SymbolTable::getSymbolAttrName(), 2513 state.attributes); 2514 2515 // Parse attributes 2516 spirv::AddressingModel addrModel; 2517 spirv::MemoryModel memoryModel; 2518 if (parseEnumKeywordAttr(addrModel, parser, state) || 2519 parseEnumKeywordAttr(memoryModel, parser, state)) 2520 return failure(); 2521 2522 if (succeeded(parser.parseOptionalKeyword("requires"))) { 2523 spirv::VerCapExtAttr vceTriple; 2524 if (parser.parseAttribute(vceTriple, 2525 spirv::ModuleOp::getVCETripleAttrName(), 2526 state.attributes)) 2527 return failure(); 2528 } 2529 2530 if (parser.parseOptionalAttrDictWithKeyword(state.attributes)) 2531 return failure(); 2532 2533 if (parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{})) 2534 return failure(); 2535 2536 spirv::ModuleOp::ensureTerminator(*body, parser.getBuilder(), state.location); 2537 return success(); 2538 } 2539 2540 static void print(spirv::ModuleOp moduleOp, OpAsmPrinter &printer) { 2541 printer << spirv::ModuleOp::getOperationName(); 2542 2543 if (Optional<StringRef> name = moduleOp.getName()) { 2544 printer << ' '; 2545 printer.printSymbolName(*name); 2546 } 2547 2548 SmallVector<StringRef, 2> elidedAttrs; 2549 2550 printer << " " << spirv::stringifyAddressingModel(moduleOp.addressing_model()) 2551 << " " << spirv::stringifyMemoryModel(moduleOp.memory_model()); 2552 auto addressingModelAttrName = spirv::attributeName<spirv::AddressingModel>(); 2553 auto memoryModelAttrName = spirv::attributeName<spirv::MemoryModel>(); 2554 elidedAttrs.assign({addressingModelAttrName, memoryModelAttrName, 2555 SymbolTable::getSymbolAttrName()}); 2556 2557 if (Optional<spirv::VerCapExtAttr> triple = moduleOp.vce_triple()) { 2558 printer << " requires " << *triple; 2559 elidedAttrs.push_back(spirv::ModuleOp::getVCETripleAttrName()); 2560 } 2561 2562 printer.printOptionalAttrDictWithKeyword(moduleOp->getAttrs(), elidedAttrs); 2563 printer.printRegion(moduleOp.body(), /*printEntryBlockArgs=*/false, 2564 /*printBlockTerminators=*/false); 2565 } 2566 2567 static LogicalResult verify(spirv::ModuleOp moduleOp) { 2568 auto &op = *moduleOp.getOperation(); 2569 auto *dialect = op.getDialect(); 2570 DenseMap<std::pair<spirv::FuncOp, spirv::ExecutionModel>, spirv::EntryPointOp> 2571 entryPoints; 2572 SymbolTable table(moduleOp); 2573 2574 for (auto &op : moduleOp.getBlock()) { 2575 if (op.getDialect() != dialect) 2576 return op.emitError("'spv.module' can only contain spv.* ops"); 2577 2578 // For EntryPoint op, check that the function and execution model is not 2579 // duplicated in EntryPointOps. Also verify that the interface specified 2580 // comes from globalVariables here to make this check cheaper. 2581 if (auto entryPointOp = dyn_cast<spirv::EntryPointOp>(op)) { 2582 auto funcOp = table.lookup<spirv::FuncOp>(entryPointOp.fn()); 2583 if (!funcOp) { 2584 return entryPointOp.emitError("function '") 2585 << entryPointOp.fn() << "' not found in 'spv.module'"; 2586 } 2587 if (auto interface = entryPointOp.interface()) { 2588 for (Attribute varRef : interface) { 2589 auto varSymRef = varRef.dyn_cast<FlatSymbolRefAttr>(); 2590 if (!varSymRef) { 2591 return entryPointOp.emitError( 2592 "expected symbol reference for interface " 2593 "specification instead of '") 2594 << varRef; 2595 } 2596 auto variableOp = 2597 table.lookup<spirv::GlobalVariableOp>(varSymRef.getValue()); 2598 if (!variableOp) { 2599 return entryPointOp.emitError("expected spv.GlobalVariable " 2600 "symbol reference instead of'") 2601 << varSymRef << "'"; 2602 } 2603 } 2604 } 2605 2606 auto key = std::pair<spirv::FuncOp, spirv::ExecutionModel>( 2607 funcOp, entryPointOp.execution_model()); 2608 auto entryPtIt = entryPoints.find(key); 2609 if (entryPtIt != entryPoints.end()) { 2610 return entryPointOp.emitError("duplicate of a previous EntryPointOp"); 2611 } 2612 entryPoints[key] = entryPointOp; 2613 } else if (auto funcOp = dyn_cast<spirv::FuncOp>(op)) { 2614 if (funcOp.isExternal()) 2615 return op.emitError("'spv.module' cannot contain external functions"); 2616 2617 // TODO: move this check to spv.func. 2618 for (auto &block : funcOp) 2619 for (auto &op : block) { 2620 if (op.getDialect() != dialect) 2621 return op.emitError( 2622 "functions in 'spv.module' can only contain spv.* ops"); 2623 } 2624 } 2625 } 2626 2627 return success(); 2628 } 2629 2630 //===----------------------------------------------------------------------===// 2631 // spv.mlir.referenceof 2632 //===----------------------------------------------------------------------===// 2633 2634 static LogicalResult verify(spirv::ReferenceOfOp referenceOfOp) { 2635 auto *specConstSym = SymbolTable::lookupNearestSymbolFrom( 2636 referenceOfOp->getParentOp(), referenceOfOp.spec_const()); 2637 Type constType; 2638 2639 auto specConstOp = dyn_cast_or_null<spirv::SpecConstantOp>(specConstSym); 2640 if (specConstOp) 2641 constType = specConstOp.default_value().getType(); 2642 2643 auto specConstCompositeOp = 2644 dyn_cast_or_null<spirv::SpecConstantCompositeOp>(specConstSym); 2645 if (specConstCompositeOp) 2646 constType = specConstCompositeOp.type(); 2647 2648 if (!specConstOp && !specConstCompositeOp) 2649 return referenceOfOp.emitOpError( 2650 "expected spv.SpecConstant or spv.SpecConstantComposite symbol"); 2651 2652 if (referenceOfOp.reference().getType() != constType) 2653 return referenceOfOp.emitOpError("result type mismatch with the referenced " 2654 "specialization constant's type"); 2655 2656 return success(); 2657 } 2658 2659 //===----------------------------------------------------------------------===// 2660 // spv.Return 2661 //===----------------------------------------------------------------------===// 2662 2663 static LogicalResult verify(spirv::ReturnOp returnOp) { 2664 // Verification is performed in spv.func op. 2665 return success(); 2666 } 2667 2668 //===----------------------------------------------------------------------===// 2669 // spv.ReturnValue 2670 //===----------------------------------------------------------------------===// 2671 2672 static LogicalResult verify(spirv::ReturnValueOp retValOp) { 2673 // Verification is performed in spv.func op. 2674 return success(); 2675 } 2676 2677 //===----------------------------------------------------------------------===// 2678 // spv.Select 2679 //===----------------------------------------------------------------------===// 2680 2681 void spirv::SelectOp::build(OpBuilder &builder, OperationState &state, 2682 Value cond, Value trueValue, Value falseValue) { 2683 build(builder, state, trueValue.getType(), cond, trueValue, falseValue); 2684 } 2685 2686 static LogicalResult verify(spirv::SelectOp op) { 2687 if (auto conditionTy = op.condition().getType().dyn_cast<VectorType>()) { 2688 auto resultVectorTy = op.result().getType().dyn_cast<VectorType>(); 2689 if (!resultVectorTy) { 2690 return op.emitOpError("result expected to be of vector type when " 2691 "condition is of vector type"); 2692 } 2693 if (resultVectorTy.getNumElements() != conditionTy.getNumElements()) { 2694 return op.emitOpError("result should have the same number of elements as " 2695 "the condition when condition is of vector type"); 2696 } 2697 } 2698 return success(); 2699 } 2700 2701 //===----------------------------------------------------------------------===// 2702 // spv.mlir.selection 2703 //===----------------------------------------------------------------------===// 2704 2705 static ParseResult parseSelectionOp(OpAsmParser &parser, 2706 OperationState &state) { 2707 if (parseControlAttribute<spirv::SelectionControl>(parser, state)) 2708 return failure(); 2709 return parser.parseRegion(*state.addRegion(), /*arguments=*/{}, 2710 /*argTypes=*/{}); 2711 } 2712 2713 static void print(spirv::SelectionOp selectionOp, OpAsmPrinter &printer) { 2714 auto *op = selectionOp.getOperation(); 2715 2716 printer << spirv::SelectionOp::getOperationName(); 2717 auto control = selectionOp.selection_control(); 2718 if (control != spirv::SelectionControl::None) 2719 printer << " control(" << spirv::stringifySelectionControl(control) << ")"; 2720 printer.printRegion(op->getRegion(0), /*printEntryBlockArgs=*/false, 2721 /*printBlockTerminators=*/true); 2722 } 2723 2724 static LogicalResult verify(spirv::SelectionOp selectionOp) { 2725 auto *op = selectionOp.getOperation(); 2726 2727 // We need to verify that the blocks follow the following layout: 2728 // 2729 // +--------------+ 2730 // | header block | 2731 // +--------------+ 2732 // / | \ 2733 // ... 2734 // 2735 // 2736 // +---------+ +---------+ +---------+ 2737 // | case #0 | | case #1 | | case #2 | ... 2738 // +---------+ +---------+ +---------+ 2739 // 2740 // 2741 // ... 2742 // \ | / 2743 // v 2744 // +-------------+ 2745 // | merge block | 2746 // +-------------+ 2747 2748 auto ®ion = op->getRegion(0); 2749 // Allow empty region as a degenerated case, which can come from 2750 // optimizations. 2751 if (region.empty()) 2752 return success(); 2753 2754 // The last block is the merge block. 2755 if (!isMergeBlock(region.back())) 2756 return selectionOp.emitOpError( 2757 "last block must be the merge block with only one 'spv.mlir.merge' op"); 2758 2759 if (std::next(region.begin()) == region.end()) 2760 return selectionOp.emitOpError("must have a selection header block"); 2761 2762 return success(); 2763 } 2764 2765 Block *spirv::SelectionOp::getHeaderBlock() { 2766 assert(!body().empty() && "op region should not be empty!"); 2767 // The first block is the loop header block. 2768 return &body().front(); 2769 } 2770 2771 Block *spirv::SelectionOp::getMergeBlock() { 2772 assert(!body().empty() && "op region should not be empty!"); 2773 // The last block is the loop merge block. 2774 return &body().back(); 2775 } 2776 2777 void spirv::SelectionOp::addMergeBlock() { 2778 assert(body().empty() && "entry and merge block already exist"); 2779 auto *mergeBlock = new Block(); 2780 body().push_back(mergeBlock); 2781 OpBuilder builder = OpBuilder::atBlockEnd(mergeBlock); 2782 2783 // Add a spv.mlir.merge op into the merge block. 2784 builder.create<spirv::MergeOp>(getLoc()); 2785 } 2786 2787 spirv::SelectionOp spirv::SelectionOp::createIfThen( 2788 Location loc, Value condition, 2789 function_ref<void(OpBuilder &builder)> thenBody, OpBuilder &builder) { 2790 auto selectionOp = 2791 builder.create<spirv::SelectionOp>(loc, spirv::SelectionControl::None); 2792 2793 selectionOp.addMergeBlock(); 2794 Block *mergeBlock = selectionOp.getMergeBlock(); 2795 Block *thenBlock = nullptr; 2796 2797 // Build the "then" block. 2798 { 2799 OpBuilder::InsertionGuard guard(builder); 2800 thenBlock = builder.createBlock(mergeBlock); 2801 thenBody(builder); 2802 builder.create<spirv::BranchOp>(loc, mergeBlock); 2803 } 2804 2805 // Build the header block. 2806 { 2807 OpBuilder::InsertionGuard guard(builder); 2808 builder.createBlock(thenBlock); 2809 builder.create<spirv::BranchConditionalOp>( 2810 loc, condition, thenBlock, 2811 /*trueArguments=*/ArrayRef<Value>(), mergeBlock, 2812 /*falseArguments=*/ArrayRef<Value>()); 2813 } 2814 2815 return selectionOp; 2816 } 2817 2818 //===----------------------------------------------------------------------===// 2819 // spv.SpecConstant 2820 //===----------------------------------------------------------------------===// 2821 2822 static ParseResult parseSpecConstantOp(OpAsmParser &parser, 2823 OperationState &state) { 2824 StringAttr nameAttr; 2825 Attribute valueAttr; 2826 2827 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(), 2828 state.attributes)) 2829 return failure(); 2830 2831 // Parse optional spec_id. 2832 if (succeeded(parser.parseOptionalKeyword(kSpecIdAttrName))) { 2833 IntegerAttr specIdAttr; 2834 if (parser.parseLParen() || 2835 parser.parseAttribute(specIdAttr, kSpecIdAttrName, state.attributes) || 2836 parser.parseRParen()) 2837 return failure(); 2838 } 2839 2840 if (parser.parseEqual() || 2841 parser.parseAttribute(valueAttr, kDefaultValueAttrName, state.attributes)) 2842 return failure(); 2843 2844 return success(); 2845 } 2846 2847 static void print(spirv::SpecConstantOp constOp, OpAsmPrinter &printer) { 2848 printer << spirv::SpecConstantOp::getOperationName() << ' '; 2849 printer.printSymbolName(constOp.sym_name()); 2850 if (auto specID = constOp->getAttrOfType<IntegerAttr>(kSpecIdAttrName)) 2851 printer << ' ' << kSpecIdAttrName << '(' << specID.getInt() << ')'; 2852 printer << " = " << constOp.default_value(); 2853 } 2854 2855 static LogicalResult verify(spirv::SpecConstantOp constOp) { 2856 if (auto specID = constOp->getAttrOfType<IntegerAttr>(kSpecIdAttrName)) 2857 if (specID.getValue().isNegative()) 2858 return constOp.emitOpError("SpecId cannot be negative"); 2859 2860 auto value = constOp.default_value(); 2861 if (value.isa<IntegerAttr, FloatAttr>()) { 2862 // Make sure bitwidth is allowed. 2863 if (!value.getType().isa<spirv::SPIRVType>()) 2864 return constOp.emitOpError("default value bitwidth disallowed"); 2865 return success(); 2866 } 2867 return constOp.emitOpError( 2868 "default value can only be a bool, integer, or float scalar"); 2869 } 2870 2871 //===----------------------------------------------------------------------===// 2872 // spv.StoreOp 2873 //===----------------------------------------------------------------------===// 2874 2875 static ParseResult parseStoreOp(OpAsmParser &parser, OperationState &state) { 2876 // Parse the storage class specification 2877 spirv::StorageClass storageClass; 2878 SmallVector<OpAsmParser::OperandType, 2> operandInfo; 2879 auto loc = parser.getCurrentLocation(); 2880 Type elementType; 2881 if (parseEnumStrAttr(storageClass, parser) || 2882 parser.parseOperandList(operandInfo, 2) || 2883 parseMemoryAccessAttributes(parser, state) || parser.parseColon() || 2884 parser.parseType(elementType)) { 2885 return failure(); 2886 } 2887 2888 auto ptrType = spirv::PointerType::get(elementType, storageClass); 2889 if (parser.resolveOperands(operandInfo, {ptrType, elementType}, loc, 2890 state.operands)) { 2891 return failure(); 2892 } 2893 return success(); 2894 } 2895 2896 static void print(spirv::StoreOp storeOp, OpAsmPrinter &printer) { 2897 auto *op = storeOp.getOperation(); 2898 SmallVector<StringRef, 4> elidedAttrs; 2899 StringRef sc = stringifyStorageClass( 2900 storeOp.ptr().getType().cast<spirv::PointerType>().getStorageClass()); 2901 printer << spirv::StoreOp::getOperationName() << " \"" << sc << "\" " 2902 << storeOp.ptr() << ", " << storeOp.value(); 2903 2904 printMemoryAccessAttribute(storeOp, printer, elidedAttrs); 2905 2906 printer << " : " << storeOp.value().getType(); 2907 printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs); 2908 } 2909 2910 static LogicalResult verify(spirv::StoreOp storeOp) { 2911 // SPIR-V spec : "Pointer is the pointer to store through. Its type must be an 2912 // OpTypePointer whose Type operand is the same as the type of Object." 2913 if (failed(verifyLoadStorePtrAndValTypes(storeOp, storeOp.ptr(), 2914 storeOp.value()))) { 2915 return failure(); 2916 } 2917 return verifyMemoryAccessAttribute(storeOp); 2918 } 2919 2920 //===----------------------------------------------------------------------===// 2921 // spv.Unreachable 2922 //===----------------------------------------------------------------------===// 2923 2924 static LogicalResult verify(spirv::UnreachableOp unreachableOp) { 2925 auto *op = unreachableOp.getOperation(); 2926 auto *block = op->getBlock(); 2927 // Fast track: if this is in entry block, its invalid. Otherwise, if no 2928 // predecessors, it's valid. 2929 if (block->isEntryBlock()) 2930 return unreachableOp.emitOpError("cannot be used in reachable block"); 2931 if (block->hasNoPredecessors()) 2932 return success(); 2933 2934 // TODO: further verification needs to analyze reachability from 2935 // the entry block. 2936 2937 return success(); 2938 } 2939 2940 //===----------------------------------------------------------------------===// 2941 // spv.Variable 2942 //===----------------------------------------------------------------------===// 2943 2944 static ParseResult parseVariableOp(OpAsmParser &parser, OperationState &state) { 2945 // Parse optional initializer 2946 Optional<OpAsmParser::OperandType> initInfo; 2947 if (succeeded(parser.parseOptionalKeyword("init"))) { 2948 initInfo = OpAsmParser::OperandType(); 2949 if (parser.parseLParen() || parser.parseOperand(*initInfo) || 2950 parser.parseRParen()) 2951 return failure(); 2952 } 2953 2954 if (parseVariableDecorations(parser, state)) { 2955 return failure(); 2956 } 2957 2958 // Parse result pointer type 2959 Type type; 2960 if (parser.parseColon()) 2961 return failure(); 2962 auto loc = parser.getCurrentLocation(); 2963 if (parser.parseType(type)) 2964 return failure(); 2965 2966 auto ptrType = type.dyn_cast<spirv::PointerType>(); 2967 if (!ptrType) 2968 return parser.emitError(loc, "expected spv.ptr type"); 2969 state.addTypes(ptrType); 2970 2971 // Resolve the initializer operand 2972 if (initInfo) { 2973 if (parser.resolveOperand(*initInfo, ptrType.getPointeeType(), 2974 state.operands)) 2975 return failure(); 2976 } 2977 2978 auto attr = parser.getBuilder().getI32IntegerAttr( 2979 llvm::bit_cast<int32_t>(ptrType.getStorageClass())); 2980 state.addAttribute(spirv::attributeName<spirv::StorageClass>(), attr); 2981 2982 return success(); 2983 } 2984 2985 static void print(spirv::VariableOp varOp, OpAsmPrinter &printer) { 2986 SmallVector<StringRef, 4> elidedAttrs{ 2987 spirv::attributeName<spirv::StorageClass>()}; 2988 printer << spirv::VariableOp::getOperationName(); 2989 2990 // Print optional initializer 2991 if (varOp.getNumOperands() != 0) 2992 printer << " init(" << varOp.initializer() << ")"; 2993 2994 printVariableDecorations(varOp, printer, elidedAttrs); 2995 printer << " : " << varOp.getType(); 2996 } 2997 2998 static LogicalResult verify(spirv::VariableOp varOp) { 2999 // SPIR-V spec: "Storage Class is the Storage Class of the memory holding the 3000 // object. It cannot be Generic. It must be the same as the Storage Class 3001 // operand of the Result Type." 3002 if (varOp.storage_class() != spirv::StorageClass::Function) { 3003 return varOp.emitOpError( 3004 "can only be used to model function-level variables. Use " 3005 "spv.GlobalVariable for module-level variables."); 3006 } 3007 3008 auto pointerType = varOp.pointer().getType().cast<spirv::PointerType>(); 3009 if (varOp.storage_class() != pointerType.getStorageClass()) 3010 return varOp.emitOpError( 3011 "storage class must match result pointer's storage class"); 3012 3013 if (varOp.getNumOperands() != 0) { 3014 // SPIR-V spec: "Initializer must be an <id> from a constant instruction or 3015 // a global (module scope) OpVariable instruction". 3016 auto *initOp = varOp.getOperand(0).getDefiningOp(); 3017 if (!initOp || !isa<spirv::ConstantOp, // for normal constant 3018 spirv::ReferenceOfOp, // for spec constant 3019 spirv::AddressOfOp>(initOp)) 3020 return varOp.emitOpError("initializer must be the result of a " 3021 "constant or spv.GlobalVariable op"); 3022 } 3023 3024 // TODO: generate these strings using ODS. 3025 auto *op = varOp.getOperation(); 3026 auto descriptorSetName = llvm::convertToSnakeFromCamelCase( 3027 stringifyDecoration(spirv::Decoration::DescriptorSet)); 3028 auto bindingName = llvm::convertToSnakeFromCamelCase( 3029 stringifyDecoration(spirv::Decoration::Binding)); 3030 auto builtInName = llvm::convertToSnakeFromCamelCase( 3031 stringifyDecoration(spirv::Decoration::BuiltIn)); 3032 3033 for (const auto &attr : {descriptorSetName, bindingName, builtInName}) { 3034 if (op->getAttr(attr)) 3035 return varOp.emitOpError("cannot have '") 3036 << attr << "' attribute (only allowed in spv.GlobalVariable)"; 3037 } 3038 3039 return success(); 3040 } 3041 3042 //===----------------------------------------------------------------------===// 3043 // spv.VectorShuffle 3044 //===----------------------------------------------------------------------===// 3045 3046 static LogicalResult verify(spirv::VectorShuffleOp shuffleOp) { 3047 VectorType resultType = shuffleOp.getType().cast<VectorType>(); 3048 3049 size_t numResultElements = resultType.getNumElements(); 3050 if (numResultElements != shuffleOp.components().size()) 3051 return shuffleOp.emitOpError("result type element count (") 3052 << numResultElements 3053 << ") mismatch with the number of component selectors (" 3054 << shuffleOp.components().size() << ")"; 3055 3056 size_t totalSrcElements = 3057 shuffleOp.vector1().getType().cast<VectorType>().getNumElements() + 3058 shuffleOp.vector2().getType().cast<VectorType>().getNumElements(); 3059 3060 for (const auto &selector : 3061 shuffleOp.components().getAsValueRange<IntegerAttr>()) { 3062 uint32_t index = selector.getZExtValue(); 3063 if (index >= totalSrcElements && 3064 index != std::numeric_limits<uint32_t>().max()) 3065 return shuffleOp.emitOpError("component selector ") 3066 << index << " out of range: expected to be in [0, " 3067 << totalSrcElements << ") or 0xffffffff"; 3068 } 3069 return success(); 3070 } 3071 3072 //===----------------------------------------------------------------------===// 3073 // spv.CooperativeMatrixLoadNV 3074 //===----------------------------------------------------------------------===// 3075 3076 static ParseResult parseCooperativeMatrixLoadNVOp(OpAsmParser &parser, 3077 OperationState &state) { 3078 SmallVector<OpAsmParser::OperandType, 3> operandInfo; 3079 Type strideType = parser.getBuilder().getIntegerType(32); 3080 Type columnMajorType = parser.getBuilder().getIntegerType(1); 3081 Type ptrType; 3082 Type elementType; 3083 if (parser.parseOperandList(operandInfo, 3) || 3084 parseMemoryAccessAttributes(parser, state) || parser.parseColon() || 3085 parser.parseType(ptrType) || parser.parseKeywordType("as", elementType)) { 3086 return failure(); 3087 } 3088 if (parser.resolveOperands(operandInfo, 3089 {ptrType, strideType, columnMajorType}, 3090 parser.getNameLoc(), state.operands)) { 3091 return failure(); 3092 } 3093 3094 state.addTypes(elementType); 3095 return success(); 3096 } 3097 3098 static void print(spirv::CooperativeMatrixLoadNVOp M, OpAsmPrinter &printer) { 3099 printer << spirv::CooperativeMatrixLoadNVOp::getOperationName() << " " 3100 << M.pointer() << ", " << M.stride() << ", " << M.columnmajor(); 3101 // Print optional memory access attribute. 3102 if (auto memAccess = M.memory_access()) 3103 printer << " [\"" << stringifyMemoryAccess(*memAccess) << "\"]"; 3104 printer << " : " << M.pointer().getType() << " as " << M.getType(); 3105 } 3106 3107 static LogicalResult verifyPointerAndCoopMatrixType(Operation *op, Type pointer, 3108 Type coopMatrix) { 3109 Type pointeeType = pointer.cast<spirv::PointerType>().getPointeeType(); 3110 if (!pointeeType.isa<spirv::ScalarType>() && !pointeeType.isa<VectorType>()) 3111 return op->emitError( 3112 "Pointer must point to a scalar or vector type but provided ") 3113 << pointeeType; 3114 spirv::StorageClass storage = 3115 pointer.cast<spirv::PointerType>().getStorageClass(); 3116 if (storage != spirv::StorageClass::Workgroup && 3117 storage != spirv::StorageClass::StorageBuffer && 3118 storage != spirv::StorageClass::PhysicalStorageBuffer) 3119 return op->emitError( 3120 "Pointer storage class must be Workgroup, StorageBuffer or " 3121 "PhysicalStorageBufferEXT but provided ") 3122 << stringifyStorageClass(storage); 3123 return success(); 3124 } 3125 3126 //===----------------------------------------------------------------------===// 3127 // spv.CooperativeMatrixStoreNV 3128 //===----------------------------------------------------------------------===// 3129 3130 static ParseResult parseCooperativeMatrixStoreNVOp(OpAsmParser &parser, 3131 OperationState &state) { 3132 SmallVector<OpAsmParser::OperandType, 4> operandInfo; 3133 Type strideType = parser.getBuilder().getIntegerType(32); 3134 Type columnMajorType = parser.getBuilder().getIntegerType(1); 3135 Type ptrType; 3136 Type elementType; 3137 if (parser.parseOperandList(operandInfo, 4) || 3138 parseMemoryAccessAttributes(parser, state) || parser.parseColon() || 3139 parser.parseType(ptrType) || parser.parseComma() || 3140 parser.parseType(elementType)) { 3141 return failure(); 3142 } 3143 if (parser.resolveOperands( 3144 operandInfo, {ptrType, elementType, strideType, columnMajorType}, 3145 parser.getNameLoc(), state.operands)) { 3146 return failure(); 3147 } 3148 3149 return success(); 3150 } 3151 3152 static void print(spirv::CooperativeMatrixStoreNVOp coopMatrix, 3153 OpAsmPrinter &printer) { 3154 printer << spirv::CooperativeMatrixStoreNVOp::getOperationName() << " " 3155 << coopMatrix.pointer() << ", " << coopMatrix.object() << ", " 3156 << coopMatrix.stride() << ", " << coopMatrix.columnmajor(); 3157 // Print optional memory access attribute. 3158 if (auto memAccess = coopMatrix.memory_access()) 3159 printer << " [\"" << stringifyMemoryAccess(*memAccess) << "\"]"; 3160 printer << " : " << coopMatrix.pointer().getType() << ", " 3161 << coopMatrix.getOperand(1).getType(); 3162 } 3163 3164 //===----------------------------------------------------------------------===// 3165 // spv.CooperativeMatrixMulAddNV 3166 //===----------------------------------------------------------------------===// 3167 3168 static LogicalResult 3169 verifyCoopMatrixMulAdd(spirv::CooperativeMatrixMulAddNVOp op) { 3170 if (op.c().getType() != op.result().getType()) 3171 return op.emitOpError("result and third operand must have the same type"); 3172 auto typeA = op.a().getType().cast<spirv::CooperativeMatrixNVType>(); 3173 auto typeB = op.b().getType().cast<spirv::CooperativeMatrixNVType>(); 3174 auto typeC = op.c().getType().cast<spirv::CooperativeMatrixNVType>(); 3175 auto typeR = op.result().getType().cast<spirv::CooperativeMatrixNVType>(); 3176 if (typeA.getRows() != typeR.getRows() || 3177 typeA.getColumns() != typeB.getRows() || 3178 typeB.getColumns() != typeR.getColumns()) 3179 return op.emitOpError("matrix size must match"); 3180 if (typeR.getScope() != typeA.getScope() || 3181 typeR.getScope() != typeB.getScope() || 3182 typeR.getScope() != typeC.getScope()) 3183 return op.emitOpError("matrix scope must match"); 3184 if (typeA.getElementType() != typeB.getElementType() || 3185 typeR.getElementType() != typeC.getElementType()) 3186 return op.emitOpError("matrix element type must match"); 3187 return success(); 3188 } 3189 3190 //===----------------------------------------------------------------------===// 3191 // spv.MatrixTimesScalar 3192 //===----------------------------------------------------------------------===// 3193 3194 static LogicalResult verifyMatrixTimesScalar(spirv::MatrixTimesScalarOp op) { 3195 // We already checked that result and matrix are both of matrix type in the 3196 // auto-generated verify method. 3197 3198 auto inputMatrix = op.matrix().getType().cast<spirv::MatrixType>(); 3199 auto resultMatrix = op.result().getType().cast<spirv::MatrixType>(); 3200 3201 // Check that the scalar type is the same as the matrix element type. 3202 if (op.scalar().getType() != inputMatrix.getElementType()) 3203 return op.emitError("input matrix components' type and scaling value must " 3204 "have the same type"); 3205 3206 // Note that the next three checks could be done using the AllTypesMatch 3207 // trait in the Op definition file but it generates a vague error message. 3208 3209 // Check that the input and result matrices have the same columns' count 3210 if (inputMatrix.getNumColumns() != resultMatrix.getNumColumns()) 3211 return op.emitError("input and result matrices must have the same " 3212 "number of columns"); 3213 3214 // Check that the input and result matrices' have the same rows count 3215 if (inputMatrix.getNumRows() != resultMatrix.getNumRows()) 3216 return op.emitError("input and result matrices' columns must have " 3217 "the same size"); 3218 3219 // Check that the input and result matrices' have the same component type 3220 if (inputMatrix.getElementType() != resultMatrix.getElementType()) 3221 return op.emitError("input and result matrices' columns must have " 3222 "the same component type"); 3223 3224 return success(); 3225 } 3226 3227 //===----------------------------------------------------------------------===// 3228 // spv.CopyMemory 3229 //===----------------------------------------------------------------------===// 3230 3231 static void print(spirv::CopyMemoryOp copyMemory, OpAsmPrinter &printer) { 3232 auto *op = copyMemory.getOperation(); 3233 printer << spirv::CopyMemoryOp::getOperationName() << ' '; 3234 3235 StringRef targetStorageClass = 3236 stringifyStorageClass(copyMemory.target() 3237 .getType() 3238 .cast<spirv::PointerType>() 3239 .getStorageClass()); 3240 printer << " \"" << targetStorageClass << "\" " << copyMemory.target() 3241 << ", "; 3242 3243 StringRef sourceStorageClass = 3244 stringifyStorageClass(copyMemory.source() 3245 .getType() 3246 .cast<spirv::PointerType>() 3247 .getStorageClass()); 3248 printer << " \"" << sourceStorageClass << "\" " << copyMemory.source(); 3249 3250 SmallVector<StringRef, 4> elidedAttrs; 3251 printMemoryAccessAttribute(copyMemory, printer, elidedAttrs); 3252 printSourceMemoryAccessAttribute(copyMemory, printer, elidedAttrs, 3253 copyMemory.source_memory_access(), 3254 copyMemory.source_alignment()); 3255 3256 printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs); 3257 3258 Type pointeeType = 3259 copyMemory.target().getType().cast<spirv::PointerType>().getPointeeType(); 3260 printer << " : " << pointeeType; 3261 } 3262 3263 static ParseResult parseCopyMemoryOp(OpAsmParser &parser, 3264 OperationState &state) { 3265 spirv::StorageClass targetStorageClass; 3266 OpAsmParser::OperandType targetPtrInfo; 3267 3268 spirv::StorageClass sourceStorageClass; 3269 OpAsmParser::OperandType sourcePtrInfo; 3270 3271 Type elementType; 3272 3273 if (parseEnumStrAttr(targetStorageClass, parser) || 3274 parser.parseOperand(targetPtrInfo) || parser.parseComma() || 3275 parseEnumStrAttr(sourceStorageClass, parser) || 3276 parser.parseOperand(sourcePtrInfo) || 3277 parseMemoryAccessAttributes(parser, state)) { 3278 return failure(); 3279 } 3280 3281 if (!parser.parseOptionalComma()) { 3282 // Parse 2nd memory access attributes. 3283 if (parseSourceMemoryAccessAttributes(parser, state)) { 3284 return failure(); 3285 } 3286 } 3287 3288 if (parser.parseColon() || parser.parseType(elementType)) 3289 return failure(); 3290 3291 if (parser.parseOptionalAttrDict(state.attributes)) 3292 return failure(); 3293 3294 auto targetPtrType = spirv::PointerType::get(elementType, targetStorageClass); 3295 auto sourcePtrType = spirv::PointerType::get(elementType, sourceStorageClass); 3296 3297 if (parser.resolveOperand(targetPtrInfo, targetPtrType, state.operands) || 3298 parser.resolveOperand(sourcePtrInfo, sourcePtrType, state.operands)) { 3299 return failure(); 3300 } 3301 3302 return success(); 3303 } 3304 3305 static LogicalResult verifyCopyMemory(spirv::CopyMemoryOp copyMemory) { 3306 Type targetType = 3307 copyMemory.target().getType().cast<spirv::PointerType>().getPointeeType(); 3308 3309 Type sourceType = 3310 copyMemory.source().getType().cast<spirv::PointerType>().getPointeeType(); 3311 3312 if (targetType != sourceType) { 3313 return copyMemory.emitOpError( 3314 "both operands must be pointers to the same type"); 3315 } 3316 3317 if (failed(verifyMemoryAccessAttribute(copyMemory))) { 3318 return failure(); 3319 } 3320 3321 // TODO - According to the spec: 3322 // 3323 // If two masks are present, the first applies to Target and cannot include 3324 // MakePointerVisible, and the second applies to Source and cannot include 3325 // MakePointerAvailable. 3326 // 3327 // Add such verification here. 3328 3329 return verifySourceMemoryAccessAttribute(copyMemory); 3330 } 3331 3332 //===----------------------------------------------------------------------===// 3333 // spv.Transpose 3334 //===----------------------------------------------------------------------===// 3335 3336 static LogicalResult verifyTranspose(spirv::TransposeOp op) { 3337 auto inputMatrix = op.matrix().getType().cast<spirv::MatrixType>(); 3338 auto resultMatrix = op.result().getType().cast<spirv::MatrixType>(); 3339 3340 // Verify that the input and output matrices have correct shapes. 3341 if (inputMatrix.getNumRows() != resultMatrix.getNumColumns()) 3342 return op.emitError("input matrix rows count must be equal to " 3343 "output matrix columns count"); 3344 3345 if (inputMatrix.getNumColumns() != resultMatrix.getNumRows()) 3346 return op.emitError("input matrix columns count must be equal to " 3347 "output matrix rows count"); 3348 3349 // Verify that the input and output matrices have the same component type 3350 if (inputMatrix.getElementType() != resultMatrix.getElementType()) 3351 return op.emitError("input and output matrices must have the same " 3352 "component type"); 3353 3354 return success(); 3355 } 3356 3357 //===----------------------------------------------------------------------===// 3358 // spv.MatrixTimesMatrix 3359 //===----------------------------------------------------------------------===// 3360 3361 static LogicalResult verifyMatrixTimesMatrix(spirv::MatrixTimesMatrixOp op) { 3362 auto leftMatrix = op.leftmatrix().getType().cast<spirv::MatrixType>(); 3363 auto rightMatrix = op.rightmatrix().getType().cast<spirv::MatrixType>(); 3364 auto resultMatrix = op.result().getType().cast<spirv::MatrixType>(); 3365 3366 // left matrix columns' count and right matrix rows' count must be equal 3367 if (leftMatrix.getNumColumns() != rightMatrix.getNumRows()) 3368 return op.emitError("left matrix columns' count must be equal to " 3369 "the right matrix rows' count"); 3370 3371 // right and result matrices columns' count must be the same 3372 if (rightMatrix.getNumColumns() != resultMatrix.getNumColumns()) 3373 return op.emitError( 3374 "right and result matrices must have equal columns' count"); 3375 3376 // right and result matrices component type must be the same 3377 if (rightMatrix.getElementType() != resultMatrix.getElementType()) 3378 return op.emitError("right and result matrices' component type must" 3379 " be the same"); 3380 3381 // left and result matrices component type must be the same 3382 if (leftMatrix.getElementType() != resultMatrix.getElementType()) 3383 return op.emitError("left and result matrices' component type" 3384 " must be the same"); 3385 3386 // left and result matrices rows count must be the same 3387 if (leftMatrix.getNumRows() != resultMatrix.getNumRows()) 3388 return op.emitError("left and result matrices must have equal rows'" 3389 " count"); 3390 3391 return success(); 3392 } 3393 3394 //===----------------------------------------------------------------------===// 3395 // spv.SpecConstantComposite 3396 //===----------------------------------------------------------------------===// 3397 3398 static ParseResult parseSpecConstantCompositeOp(OpAsmParser &parser, 3399 OperationState &state) { 3400 3401 StringAttr compositeName; 3402 if (parser.parseSymbolName(compositeName, SymbolTable::getSymbolAttrName(), 3403 state.attributes)) 3404 return failure(); 3405 3406 if (parser.parseLParen()) 3407 return failure(); 3408 3409 SmallVector<Attribute, 4> constituents; 3410 3411 do { 3412 // The name of the constituent attribute isn't important 3413 const char *attrName = "spec_const"; 3414 FlatSymbolRefAttr specConstRef; 3415 NamedAttrList attrs; 3416 3417 if (parser.parseAttribute(specConstRef, Type(), attrName, attrs)) 3418 return failure(); 3419 3420 constituents.push_back(specConstRef); 3421 } while (!parser.parseOptionalComma()); 3422 3423 if (parser.parseRParen()) 3424 return failure(); 3425 3426 state.addAttribute(kCompositeSpecConstituentsName, 3427 parser.getBuilder().getArrayAttr(constituents)); 3428 3429 Type type; 3430 if (parser.parseColonType(type)) 3431 return failure(); 3432 3433 state.addAttribute(kTypeAttrName, TypeAttr::get(type)); 3434 3435 return success(); 3436 } 3437 3438 static void print(spirv::SpecConstantCompositeOp op, OpAsmPrinter &printer) { 3439 printer << spirv::SpecConstantCompositeOp::getOperationName() << " "; 3440 printer.printSymbolName(op.sym_name()); 3441 printer << " ("; 3442 auto constituents = op.constituents().getValue(); 3443 3444 if (!constituents.empty()) 3445 llvm::interleaveComma(constituents, printer); 3446 3447 printer << ") : " << op.type(); 3448 } 3449 3450 static LogicalResult verify(spirv::SpecConstantCompositeOp constOp) { 3451 auto cType = constOp.type().dyn_cast<spirv::CompositeType>(); 3452 auto constituents = constOp.constituents().getValue(); 3453 3454 if (!cType) 3455 return constOp.emitError( 3456 "result type must be a composite type, but provided ") 3457 << constOp.type(); 3458 3459 if (cType.isa<spirv::CooperativeMatrixNVType>()) 3460 return constOp.emitError("unsupported composite type ") << cType; 3461 else if (constituents.size() != cType.getNumElements()) 3462 return constOp.emitError("has incorrect number of operands: expected ") 3463 << cType.getNumElements() << ", but provided " 3464 << constituents.size(); 3465 3466 for (auto index : llvm::seq<uint32_t>(0, constituents.size())) { 3467 auto constituent = constituents[index].dyn_cast<FlatSymbolRefAttr>(); 3468 3469 auto constituentSpecConstOp = 3470 dyn_cast<spirv::SpecConstantOp>(SymbolTable::lookupNearestSymbolFrom( 3471 constOp->getParentOp(), constituent.getValue())); 3472 3473 if (constituentSpecConstOp.default_value().getType() != 3474 cType.getElementType(index)) 3475 return constOp.emitError("has incorrect types of operands: expected ") 3476 << cType.getElementType(index) << ", but provided " 3477 << constituentSpecConstOp.default_value().getType(); 3478 } 3479 3480 return success(); 3481 } 3482 3483 //===----------------------------------------------------------------------===// 3484 // spv.SpecConstantOperation 3485 //===----------------------------------------------------------------------===// 3486 3487 static ParseResult parseSpecConstantOperationOp(OpAsmParser &parser, 3488 OperationState &state) { 3489 Region *body = state.addRegion(); 3490 3491 if (parser.parseKeyword("wraps")) 3492 return failure(); 3493 3494 body->push_back(new Block); 3495 Block &block = body->back(); 3496 Operation *wrappedOp = parser.parseGenericOperation(&block, block.begin()); 3497 3498 if (!wrappedOp) 3499 return failure(); 3500 3501 OpBuilder builder(parser.getBuilder().getContext()); 3502 builder.setInsertionPointToEnd(&block); 3503 builder.create<spirv::YieldOp>(wrappedOp->getLoc(), wrappedOp->getResult(0)); 3504 state.location = wrappedOp->getLoc(); 3505 3506 state.addTypes(wrappedOp->getResult(0).getType()); 3507 3508 if (parser.parseOptionalAttrDict(state.attributes)) 3509 return failure(); 3510 3511 return success(); 3512 } 3513 3514 static void print(spirv::SpecConstantOperationOp op, OpAsmPrinter &printer) { 3515 printer << op.getOperationName() << " wraps "; 3516 printer.printGenericOp(&op.body().front().front()); 3517 } 3518 3519 static LogicalResult verify(spirv::SpecConstantOperationOp constOp) { 3520 Block &block = constOp.getRegion().getBlocks().front(); 3521 3522 if (block.getOperations().size() != 2) 3523 return constOp.emitOpError("expected exactly 2 nested ops"); 3524 3525 Operation &enclosedOp = block.getOperations().front(); 3526 3527 if (!enclosedOp.hasTrait<OpTrait::spirv::UsableInSpecConstantOp>()) 3528 return constOp.emitOpError("invalid enclosed op"); 3529 3530 for (auto operand : enclosedOp.getOperands()) 3531 if (!isa<spirv::ConstantOp, spirv::ReferenceOfOp, 3532 spirv::SpecConstantOperationOp>(operand.getDefiningOp())) 3533 return constOp.emitOpError( 3534 "invalid operand, must be defined by a constant operation"); 3535 3536 return success(); 3537 } 3538 3539 //===----------------------------------------------------------------------===// 3540 // spv.GLSL.FrexpStruct 3541 //===----------------------------------------------------------------------===// 3542 static LogicalResult 3543 verifyGLSLFrexpStructOp(spirv::GLSLFrexpStructOp frexpStructOp) { 3544 spirv::StructType structTy = 3545 frexpStructOp.result().getType().dyn_cast<spirv::StructType>(); 3546 3547 if (structTy.getNumElements() != 2) 3548 return frexpStructOp.emitError("result type must be a struct type " 3549 "with two memebers"); 3550 3551 Type significandTy = structTy.getElementType(0); 3552 Type exponentTy = structTy.getElementType(1); 3553 VectorType exponentVecTy = exponentTy.dyn_cast<VectorType>(); 3554 IntegerType exponentIntTy = exponentTy.dyn_cast<IntegerType>(); 3555 3556 Type operandTy = frexpStructOp.operand().getType(); 3557 VectorType operandVecTy = operandTy.dyn_cast<VectorType>(); 3558 FloatType operandFTy = operandTy.dyn_cast<FloatType>(); 3559 3560 if (significandTy != operandTy) 3561 return frexpStructOp.emitError("member zero of the resulting struct type " 3562 "must be the same type as the operand"); 3563 3564 if (exponentVecTy) { 3565 IntegerType componentIntTy = 3566 exponentVecTy.getElementType().dyn_cast<IntegerType>(); 3567 if (!(componentIntTy && componentIntTy.getWidth() == 32)) 3568 return frexpStructOp.emitError( 3569 "member one of the resulting struct type must" 3570 "be a scalar or vector of 32 bit integer type"); 3571 } else if (!(exponentIntTy && exponentIntTy.getWidth() == 32)) { 3572 return frexpStructOp.emitError( 3573 "member one of the resulting struct type " 3574 "must be a scalar or vector of 32 bit integer type"); 3575 } 3576 3577 // Check that the two member types have the same number of components 3578 if (operandVecTy && exponentVecTy && 3579 (exponentVecTy.getNumElements() == operandVecTy.getNumElements())) 3580 return success(); 3581 3582 if (operandFTy && exponentIntTy) 3583 return success(); 3584 3585 return frexpStructOp.emitError( 3586 "member one of the resulting struct type " 3587 "must have the same number of components as the operand type"); 3588 } 3589 3590 //===----------------------------------------------------------------------===// 3591 // spv.GLSL.Ldexp 3592 //===----------------------------------------------------------------------===// 3593 3594 static LogicalResult verify(spirv::GLSLLdexpOp ldexpOp) { 3595 Type significandType = ldexpOp.x().getType(); 3596 Type exponentType = ldexpOp.exp().getType(); 3597 3598 if (significandType.isa<FloatType>() != exponentType.isa<IntegerType>()) 3599 return ldexpOp.emitOpError("operands must both be scalars or vectors"); 3600 3601 auto getNumElements = [](Type type) -> unsigned { 3602 if (auto vectorType = type.dyn_cast<VectorType>()) 3603 return vectorType.getNumElements(); 3604 return 1; 3605 }; 3606 3607 if (getNumElements(significandType) != getNumElements(exponentType)) 3608 return ldexpOp.emitOpError( 3609 "operands must have the same number of elements"); 3610 3611 return success(); 3612 } 3613 3614 //===----------------------------------------------------------------------===// 3615 // spv.ImageDrefGather 3616 //===----------------------------------------------------------------------===// 3617 3618 static LogicalResult verify(spirv::ImageDrefGatherOp imageDrefGatherOp) { 3619 // TODO: Support optional operands. 3620 VectorType resultType = 3621 imageDrefGatherOp.result().getType().cast<VectorType>(); 3622 auto sampledImageType = imageDrefGatherOp.sampledimage() 3623 .getType() 3624 .cast<spirv::SampledImageType>(); 3625 auto imageType = sampledImageType.getImageType().cast<spirv::ImageType>(); 3626 3627 if (resultType.getNumElements() != 4) 3628 return imageDrefGatherOp.emitOpError( 3629 "result type must be a vector of four components"); 3630 3631 Type elementType = resultType.getElementType(); 3632 Type sampledElementType = imageType.getElementType(); 3633 if (!sampledElementType.isa<NoneType>() && elementType != sampledElementType) 3634 return imageDrefGatherOp.emitOpError( 3635 "the component type of result must be the same as sampled type of the " 3636 "underlying image type"); 3637 3638 spirv::Dim imageDim = imageType.getDim(); 3639 spirv::ImageSamplingInfo imageMS = imageType.getSamplingInfo(); 3640 3641 if (imageDim != spirv::Dim::Dim2D && imageDim != spirv::Dim::Cube && 3642 imageDim != spirv::Dim::Rect) 3643 return imageDrefGatherOp.emitOpError( 3644 "the Dim operand of the underlying image type must be 2D, Cube, or " 3645 "Rect"); 3646 3647 if (imageMS != spirv::ImageSamplingInfo::SingleSampled) 3648 return imageDrefGatherOp.emitOpError( 3649 "the MS operand of the underlying image type must be 0"); 3650 3651 return success(); 3652 } 3653 3654 //===----------------------------------------------------------------------===// 3655 // spv.ImageQuerySize 3656 //===----------------------------------------------------------------------===// 3657 3658 static LogicalResult verify(spirv::ImageQuerySizeOp imageQuerySizeOp) { 3659 spirv::ImageType imageType = 3660 imageQuerySizeOp.image().getType().cast<spirv::ImageType>(); 3661 Type resultType = imageQuerySizeOp.result().getType(); 3662 3663 spirv::Dim dim = imageType.getDim(); 3664 spirv::ImageSamplingInfo samplingInfo = imageType.getSamplingInfo(); 3665 spirv::ImageSamplerUseInfo samplerInfo = imageType.getSamplerUseInfo(); 3666 switch (dim) { 3667 case spirv::Dim::Dim1D: 3668 case spirv::Dim::Dim2D: 3669 case spirv::Dim::Dim3D: 3670 case spirv::Dim::Cube: 3671 if (!(samplingInfo == spirv::ImageSamplingInfo::MultiSampled || 3672 samplerInfo == spirv::ImageSamplerUseInfo::SamplerUnknown || 3673 samplerInfo == spirv::ImageSamplerUseInfo::NoSampler)) 3674 return imageQuerySizeOp.emitError( 3675 "if Dim is 1D, 2D, 3D, or Cube, " 3676 "it must also have either an MS of 1 or a Sampled of 0 or 2"); 3677 break; 3678 case spirv::Dim::Buffer: 3679 case spirv::Dim::Rect: 3680 break; 3681 default: 3682 return imageQuerySizeOp.emitError("the Dim operand of the image type must " 3683 "be 1D, 2D, 3D, Buffer, Cube, or Rect"); 3684 } 3685 3686 unsigned componentNumber = 0; 3687 switch (dim) { 3688 case spirv::Dim::Dim1D: 3689 case spirv::Dim::Buffer: 3690 componentNumber = 1; 3691 break; 3692 case spirv::Dim::Dim2D: 3693 case spirv::Dim::Cube: 3694 case spirv::Dim::Rect: 3695 componentNumber = 2; 3696 break; 3697 case spirv::Dim::Dim3D: 3698 componentNumber = 3; 3699 break; 3700 default: 3701 break; 3702 } 3703 3704 if (imageType.getArrayedInfo() == spirv::ImageArrayedInfo::Arrayed) 3705 componentNumber += 1; 3706 3707 unsigned resultComponentNumber = 1; 3708 if (auto resultVectorType = resultType.dyn_cast<VectorType>()) 3709 resultComponentNumber = resultVectorType.getNumElements(); 3710 3711 if (componentNumber != resultComponentNumber) 3712 return imageQuerySizeOp.emitError("expected the result to have ") 3713 << componentNumber << " component(s), but found " 3714 << resultComponentNumber << " component(s)"; 3715 3716 return success(); 3717 } 3718 3719 namespace mlir { 3720 namespace spirv { 3721 3722 // TableGen'erated operation interfaces for querying versions, extensions, and 3723 // capabilities. 3724 #include "mlir/Dialect/SPIRV/IR/SPIRVAvailability.cpp.inc" 3725 } // namespace spirv 3726 } // namespace mlir 3727 3728 // TablenGen'erated operation definitions. 3729 #define GET_OP_CLASSES 3730 #include "mlir/Dialect/SPIRV/IR/SPIRVOps.cpp.inc" 3731 3732 namespace mlir { 3733 namespace spirv { 3734 // TableGen'erated operation availability interface implementations. 3735 #include "mlir/Dialect/SPIRV/IR/SPIRVOpAvailabilityImpl.inc" 3736 3737 } // namespace spirv 3738 } // namespace mlir 3739