1 // Copyright (c) 2015-2016 The Khronos Group Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Performs validation on instructions that appear inside of a SPIR-V block. 16 17 #include "source/val/validate.h" 18 19 #include <algorithm> 20 #include <cassert> 21 #include <sstream> 22 #include <string> 23 #include <vector> 24 25 #include "source/binary.h" 26 #include "source/diagnostic.h" 27 #include "source/enum_set.h" 28 #include "source/enum_string_mapping.h" 29 #include "source/extensions.h" 30 #include "source/opcode.h" 31 #include "source/operand.h" 32 #include "source/spirv_constant.h" 33 #include "source/spirv_definition.h" 34 #include "source/spirv_target_env.h" 35 #include "source/spirv_validator_options.h" 36 #include "source/util/string_utils.h" 37 #include "source/val/function.h" 38 #include "source/val/validation_state.h" 39 40 namespace spvtools { 41 namespace val { 42 namespace { 43 44 std::string ToString(const CapabilitySet& capabilities, 45 const AssemblyGrammar& grammar) { 46 std::stringstream ss; 47 capabilities.ForEach([&grammar, &ss](SpvCapability cap) { 48 spv_operand_desc desc; 49 if (SPV_SUCCESS == 50 grammar.lookupOperand(SPV_OPERAND_TYPE_CAPABILITY, cap, &desc)) 51 ss << desc->name << " "; 52 else 53 ss << cap << " "; 54 }); 55 return ss.str(); 56 } 57 58 // Returns capabilities that enable an opcode. An empty result is interpreted 59 // as no prohibition of use of the opcode. If the result is non-empty, then 60 // the opcode may only be used if at least one of the capabilities is specified 61 // by the module. 62 CapabilitySet EnablingCapabilitiesForOp(const ValidationState_t& state, 63 SpvOp opcode) { 64 // Exceptions for SPV_AMD_shader_ballot 65 switch (opcode) { 66 // Normally these would require Group capability 67 case SpvOpGroupIAddNonUniformAMD: 68 case SpvOpGroupFAddNonUniformAMD: 69 case SpvOpGroupFMinNonUniformAMD: 70 case SpvOpGroupUMinNonUniformAMD: 71 case SpvOpGroupSMinNonUniformAMD: 72 case SpvOpGroupFMaxNonUniformAMD: 73 case SpvOpGroupUMaxNonUniformAMD: 74 case SpvOpGroupSMaxNonUniformAMD: 75 if (state.HasExtension(kSPV_AMD_shader_ballot)) return CapabilitySet(); 76 break; 77 default: 78 break; 79 } 80 // Look it up in the grammar 81 spv_opcode_desc opcode_desc = {}; 82 if (SPV_SUCCESS == state.grammar().lookupOpcode(opcode, &opcode_desc)) { 83 return state.grammar().filterCapsAgainstTargetEnv( 84 opcode_desc->capabilities, opcode_desc->numCapabilities); 85 } 86 return CapabilitySet(); 87 } 88 89 // Returns SPV_SUCCESS if the given operand is enabled by capabilities declared 90 // in the module. Otherwise issues an error message and returns 91 // SPV_ERROR_INVALID_CAPABILITY. 92 spv_result_t CheckRequiredCapabilities(ValidationState_t& state, 93 const Instruction* inst, 94 size_t which_operand, 95 spv_operand_type_t type, 96 uint32_t operand) { 97 // Mere mention of PointSize, ClipDistance, or CullDistance in a Builtin 98 // decoration does not require the associated capability. The use of such 99 // a variable value should trigger the capability requirement, but that's 100 // not implemented yet. This rule is independent of target environment. 101 // See https://github.com/KhronosGroup/SPIRV-Tools/issues/365 102 if (type == SPV_OPERAND_TYPE_BUILT_IN) { 103 switch (operand) { 104 case SpvBuiltInPointSize: 105 case SpvBuiltInClipDistance: 106 case SpvBuiltInCullDistance: 107 return SPV_SUCCESS; 108 default: 109 break; 110 } 111 } else if (type == SPV_OPERAND_TYPE_FP_ROUNDING_MODE) { 112 // Allow all FP rounding modes if requested 113 if (state.features().free_fp_rounding_mode) { 114 return SPV_SUCCESS; 115 } 116 } else if (type == SPV_OPERAND_TYPE_GROUP_OPERATION && 117 state.features().group_ops_reduce_and_scans && 118 (operand <= uint32_t(SpvGroupOperationExclusiveScan))) { 119 // Allow certain group operations if requested. 120 return SPV_SUCCESS; 121 } 122 123 CapabilitySet enabling_capabilities; 124 spv_operand_desc operand_desc = nullptr; 125 const auto lookup_result = 126 state.grammar().lookupOperand(type, operand, &operand_desc); 127 if (lookup_result == SPV_SUCCESS) { 128 // Allow FPRoundingMode decoration if requested. 129 if (type == SPV_OPERAND_TYPE_DECORATION && 130 operand_desc->value == SpvDecorationFPRoundingMode) { 131 if (state.features().free_fp_rounding_mode) return SPV_SUCCESS; 132 133 // Vulkan API requires more capabilities on rounding mode. 134 if (spvIsVulkanEnv(state.context()->target_env)) { 135 enabling_capabilities.Add(SpvCapabilityStorageUniformBufferBlock16); 136 enabling_capabilities.Add(SpvCapabilityStorageUniform16); 137 enabling_capabilities.Add(SpvCapabilityStoragePushConstant16); 138 enabling_capabilities.Add(SpvCapabilityStorageInputOutput16); 139 } 140 } else { 141 enabling_capabilities = state.grammar().filterCapsAgainstTargetEnv( 142 operand_desc->capabilities, operand_desc->numCapabilities); 143 } 144 145 if (!state.HasAnyOfCapabilities(enabling_capabilities)) { 146 return state.diag(SPV_ERROR_INVALID_CAPABILITY, inst) 147 << "Operand " << which_operand << " of " 148 << spvOpcodeString(inst->opcode()) 149 << " requires one of these capabilities: " 150 << ToString(enabling_capabilities, state.grammar()); 151 } 152 } 153 154 return SPV_SUCCESS; 155 } 156 157 // Returns operand's required extensions. 158 ExtensionSet RequiredExtensions(const ValidationState_t& state, 159 spv_operand_type_t type, uint32_t operand) { 160 spv_operand_desc operand_desc; 161 if (state.grammar().lookupOperand(type, operand, &operand_desc) == 162 SPV_SUCCESS) { 163 assert(operand_desc); 164 // If this operand is incorporated into core SPIR-V before or in the current 165 // target environment, we don't require extensions anymore. 166 if (spvVersionForTargetEnv(state.grammar().target_env()) >= 167 operand_desc->minVersion) 168 return {}; 169 return {operand_desc->numExtensions, operand_desc->extensions}; 170 } 171 172 return {}; 173 } 174 175 // Returns SPV_ERROR_INVALID_BINARY and emits a diagnostic if the instruction 176 // is explicitly reserved in the SPIR-V core spec. Otherwise return 177 // SPV_SUCCESS. 178 spv_result_t ReservedCheck(ValidationState_t& _, const Instruction* inst) { 179 const SpvOp opcode = inst->opcode(); 180 switch (opcode) { 181 // These instructions are enabled by a capability, but should never 182 // be used anyway. 183 case SpvOpImageSparseSampleProjImplicitLod: 184 case SpvOpImageSparseSampleProjExplicitLod: 185 case SpvOpImageSparseSampleProjDrefImplicitLod: 186 case SpvOpImageSparseSampleProjDrefExplicitLod: { 187 spv_opcode_desc inst_desc; 188 _.grammar().lookupOpcode(opcode, &inst_desc); 189 return _.diag(SPV_ERROR_INVALID_BINARY, inst) 190 << "Invalid Opcode name 'Op" << inst_desc->name << "'"; 191 } 192 default: 193 break; 194 } 195 return SPV_SUCCESS; 196 } 197 198 // Returns SPV_ERROR_INVALID_BINARY and emits a diagnostic if the instruction 199 // is invalid because of an execution environment constraint. 200 spv_result_t EnvironmentCheck(ValidationState_t& _, const Instruction* inst) { 201 const SpvOp opcode = inst->opcode(); 202 switch (opcode) { 203 case SpvOpUndef: 204 if (_.features().bans_op_undef) { 205 return _.diag(SPV_ERROR_INVALID_BINARY, inst) 206 << "OpUndef is disallowed"; 207 } 208 break; 209 default: 210 break; 211 } 212 return SPV_SUCCESS; 213 } 214 215 // Returns SPV_ERROR_INVALID_CAPABILITY and emits a diagnostic if the 216 // instruction is invalid because the required capability isn't declared 217 // in the module. 218 spv_result_t CapabilityCheck(ValidationState_t& _, const Instruction* inst) { 219 const SpvOp opcode = inst->opcode(); 220 CapabilitySet opcode_caps = EnablingCapabilitiesForOp(_, opcode); 221 if (!_.HasAnyOfCapabilities(opcode_caps)) { 222 return _.diag(SPV_ERROR_INVALID_CAPABILITY, inst) 223 << "Opcode " << spvOpcodeString(opcode) 224 << " requires one of these capabilities: " 225 << ToString(opcode_caps, _.grammar()); 226 } 227 for (size_t i = 0; i < inst->operands().size(); ++i) { 228 const auto& operand = inst->operand(i); 229 const auto word = inst->word(operand.offset); 230 if (spvOperandIsConcreteMask(operand.type)) { 231 // Check for required capabilities for each bit position of the mask. 232 for (uint32_t mask_bit = 0x80000000; mask_bit; mask_bit >>= 1) { 233 if (word & mask_bit) { 234 spv_result_t status = 235 CheckRequiredCapabilities(_, inst, i + 1, operand.type, mask_bit); 236 if (status != SPV_SUCCESS) return status; 237 } 238 } 239 } else if (spvIsIdType(operand.type)) { 240 // TODO(dneto): Check the value referenced by this Id, if we can compute 241 // it. For now, just punt, to fix issue 248: 242 // https://github.com/KhronosGroup/SPIRV-Tools/issues/248 243 } else { 244 // Check the operand word as a whole. 245 spv_result_t status = 246 CheckRequiredCapabilities(_, inst, i + 1, operand.type, word); 247 if (status != SPV_SUCCESS) return status; 248 } 249 } 250 return SPV_SUCCESS; 251 } 252 253 // Checks that all extensions required by the given instruction's operands were 254 // declared in the module. 255 spv_result_t ExtensionCheck(ValidationState_t& _, const Instruction* inst) { 256 const SpvOp opcode = inst->opcode(); 257 for (size_t operand_index = 0; operand_index < inst->operands().size(); 258 ++operand_index) { 259 const auto& operand = inst->operand(operand_index); 260 const uint32_t word = inst->word(operand.offset); 261 const ExtensionSet required_extensions = 262 RequiredExtensions(_, operand.type, word); 263 if (!_.HasAnyOfExtensions(required_extensions)) { 264 return _.diag(SPV_ERROR_MISSING_EXTENSION, inst) 265 << spvtools::utils::CardinalToOrdinal(operand_index + 1) 266 << " operand of " << spvOpcodeString(opcode) << ": operand " 267 << word << " requires one of these extensions: " 268 << ExtensionSetToString(required_extensions); 269 } 270 } 271 return SPV_SUCCESS; 272 } 273 274 // Checks that the instruction can be used in this target environment's base 275 // version. Assumes that CapabilityCheck has checked direct capability 276 // dependencies for the opcode. 277 spv_result_t VersionCheck(ValidationState_t& _, const Instruction* inst) { 278 const auto opcode = inst->opcode(); 279 spv_opcode_desc inst_desc; 280 const spv_result_t r = _.grammar().lookupOpcode(opcode, &inst_desc); 281 assert(r == SPV_SUCCESS); 282 (void)r; 283 284 const auto min_version = inst_desc->minVersion; 285 286 if (inst_desc->numCapabilities > 0u) { 287 // We already checked that the direct capability dependency has been 288 // satisfied. We don't need to check any further. 289 return SPV_SUCCESS; 290 } 291 292 ExtensionSet exts(inst_desc->numExtensions, inst_desc->extensions); 293 if (exts.IsEmpty()) { 294 // If no extensions can enable this instruction, then emit error messages 295 // only concerning core SPIR-V versions if errors happen. 296 if (min_version == ~0u) { 297 return _.diag(SPV_ERROR_WRONG_VERSION, inst) 298 << spvOpcodeString(opcode) << " is reserved for future use."; 299 } 300 301 if (spvVersionForTargetEnv(_.grammar().target_env()) < min_version) { 302 return _.diag(SPV_ERROR_WRONG_VERSION, inst) 303 << spvOpcodeString(opcode) << " requires " 304 << spvTargetEnvDescription( 305 static_cast<spv_target_env>(min_version)) 306 << " at minimum."; 307 } 308 // Otherwise, we only error out when no enabling extensions are registered. 309 } else if (!_.HasAnyOfExtensions(exts)) { 310 if (min_version == ~0u) { 311 return _.diag(SPV_ERROR_MISSING_EXTENSION, inst) 312 << spvOpcodeString(opcode) 313 << " requires one of the following extensions: " 314 << ExtensionSetToString(exts); 315 } 316 317 if (static_cast<uint32_t>(_.grammar().target_env()) < min_version) { 318 return _.diag(SPV_ERROR_WRONG_VERSION, inst) 319 << spvOpcodeString(opcode) << " requires " 320 << spvTargetEnvDescription( 321 static_cast<spv_target_env>(min_version)) 322 << " at minimum or one of the following extensions: " 323 << ExtensionSetToString(exts); 324 } 325 } 326 327 return SPV_SUCCESS; 328 } 329 330 // Checks that the Resuld <id> is within the valid bound. 331 spv_result_t LimitCheckIdBound(ValidationState_t& _, const Instruction* inst) { 332 if (inst->id() >= _.getIdBound()) { 333 return _.diag(SPV_ERROR_INVALID_BINARY, inst) 334 << "Result <id> '" << inst->id() 335 << "' must be less than the ID bound '" << _.getIdBound() << "'."; 336 } 337 return SPV_SUCCESS; 338 } 339 340 // Checks that the number of OpTypeStruct members is within the limit. 341 spv_result_t LimitCheckStruct(ValidationState_t& _, const Instruction* inst) { 342 if (SpvOpTypeStruct != inst->opcode()) { 343 return SPV_SUCCESS; 344 } 345 346 // Number of members is the number of operands of the instruction minus 1. 347 // One operand is the result ID. 348 const uint16_t limit = 349 static_cast<uint16_t>(_.options()->universal_limits_.max_struct_members); 350 if (inst->operands().size() - 1 > limit) { 351 return _.diag(SPV_ERROR_INVALID_BINARY, inst) 352 << "Number of OpTypeStruct members (" << inst->operands().size() - 1 353 << ") has exceeded the limit (" << limit << ")."; 354 } 355 356 // Section 2.17 of SPIRV Spec specifies that the "Structure Nesting Depth" 357 // must be less than or equal to 255. 358 // This is interpreted as structures including other structures as members. 359 // The code does not follow pointers or look into arrays to see if we reach a 360 // structure downstream. 361 // The nesting depth of a struct is 1+(largest depth of any member). 362 // Scalars are at depth 0. 363 uint32_t max_member_depth = 0; 364 // Struct members start at word 2 of OpTypeStruct instruction. 365 for (size_t word_i = 2; word_i < inst->words().size(); ++word_i) { 366 auto member = inst->word(word_i); 367 auto memberTypeInstr = _.FindDef(member); 368 if (memberTypeInstr && SpvOpTypeStruct == memberTypeInstr->opcode()) { 369 max_member_depth = std::max( 370 max_member_depth, _.struct_nesting_depth(memberTypeInstr->id())); 371 } 372 } 373 374 const uint32_t depth_limit = _.options()->universal_limits_.max_struct_depth; 375 const uint32_t cur_depth = 1 + max_member_depth; 376 _.set_struct_nesting_depth(inst->id(), cur_depth); 377 if (cur_depth > depth_limit) { 378 return _.diag(SPV_ERROR_INVALID_BINARY, inst) 379 << "Structure Nesting Depth may not be larger than " << depth_limit 380 << ". Found " << cur_depth << "."; 381 } 382 return SPV_SUCCESS; 383 } 384 385 // Checks that the number of (literal, label) pairs in OpSwitch is within the 386 // limit. 387 spv_result_t LimitCheckSwitch(ValidationState_t& _, const Instruction* inst) { 388 if (SpvOpSwitch == inst->opcode()) { 389 // The instruction syntax is as follows: 390 // OpSwitch <selector ID> <Default ID> literal label literal label ... 391 // literal,label pairs come after the first 2 operands. 392 // It is guaranteed at this point that num_operands is an even numner. 393 size_t num_pairs = (inst->operands().size() - 2) / 2; 394 const unsigned int num_pairs_limit = 395 _.options()->universal_limits_.max_switch_branches; 396 if (num_pairs > num_pairs_limit) { 397 return _.diag(SPV_ERROR_INVALID_BINARY, inst) 398 << "Number of (literal, label) pairs in OpSwitch (" << num_pairs 399 << ") exceeds the limit (" << num_pairs_limit << ")."; 400 } 401 } 402 return SPV_SUCCESS; 403 } 404 405 // Ensure the number of variables of the given class does not exceed the limit. 406 spv_result_t LimitCheckNumVars(ValidationState_t& _, const uint32_t var_id, 407 const SpvStorageClass storage_class) { 408 if (SpvStorageClassFunction == storage_class) { 409 _.registerLocalVariable(var_id); 410 const uint32_t num_local_vars_limit = 411 _.options()->universal_limits_.max_local_variables; 412 if (_.num_local_vars() > num_local_vars_limit) { 413 return _.diag(SPV_ERROR_INVALID_BINARY, nullptr) 414 << "Number of local variables ('Function' Storage Class) " 415 "exceeded the valid limit (" 416 << num_local_vars_limit << ")."; 417 } 418 } else { 419 _.registerGlobalVariable(var_id); 420 const uint32_t num_global_vars_limit = 421 _.options()->universal_limits_.max_global_variables; 422 if (_.num_global_vars() > num_global_vars_limit) { 423 return _.diag(SPV_ERROR_INVALID_BINARY, nullptr) 424 << "Number of Global Variables (Storage Class other than " 425 "'Function') exceeded the valid limit (" 426 << num_global_vars_limit << ")."; 427 } 428 } 429 return SPV_SUCCESS; 430 } 431 432 // Parses OpExtension instruction and logs warnings if unsuccessful. 433 spv_result_t CheckIfKnownExtension(ValidationState_t& _, 434 const Instruction* inst) { 435 const std::string extension_str = GetExtensionString(&(inst->c_inst())); 436 Extension extension; 437 if (!GetExtensionFromString(extension_str.c_str(), &extension)) { 438 return _.diag(SPV_WARNING, inst) 439 << "Found unrecognized extension " << extension_str; 440 } 441 return SPV_SUCCESS; 442 } 443 444 } // namespace 445 446 spv_result_t InstructionPass(ValidationState_t& _, const Instruction* inst) { 447 const SpvOp opcode = inst->opcode(); 448 if (opcode == SpvOpExtension) { 449 CheckIfKnownExtension(_, inst); 450 } else if (opcode == SpvOpCapability) { 451 _.RegisterCapability(inst->GetOperandAs<SpvCapability>(0)); 452 } else if (opcode == SpvOpMemoryModel) { 453 if (_.has_memory_model_specified()) { 454 return _.diag(SPV_ERROR_INVALID_LAYOUT, inst) 455 << "OpMemoryModel should only be provided once."; 456 } 457 _.set_addressing_model(inst->GetOperandAs<SpvAddressingModel>(0)); 458 _.set_memory_model(inst->GetOperandAs<SpvMemoryModel>(1)); 459 460 if (_.memory_model() != SpvMemoryModelVulkanKHR && 461 _.HasCapability(SpvCapabilityVulkanMemoryModelKHR)) { 462 return _.diag(SPV_ERROR_INVALID_DATA, inst) 463 << "VulkanMemoryModelKHR capability must only be specified if the " 464 "VulkanKHR memory model is used."; 465 } 466 467 if (spvIsWebGPUEnv(_.context()->target_env)) { 468 if (_.addressing_model() != SpvAddressingModelLogical) { 469 return _.diag(SPV_ERROR_INVALID_DATA, inst) 470 << "Addressing model must be Logical for WebGPU environment."; 471 } 472 if (_.memory_model() != SpvMemoryModelVulkanKHR) { 473 return _.diag(SPV_ERROR_INVALID_DATA, inst) 474 << "Memory model must be VulkanKHR for WebGPU environment."; 475 } 476 } 477 } else if (opcode == SpvOpExecutionMode) { 478 const uint32_t entry_point = inst->word(1); 479 _.RegisterExecutionModeForEntryPoint(entry_point, 480 SpvExecutionMode(inst->word(2))); 481 } else if (opcode == SpvOpVariable) { 482 const auto storage_class = inst->GetOperandAs<SpvStorageClass>(2); 483 if (auto error = LimitCheckNumVars(_, inst->id(), storage_class)) { 484 return error; 485 } 486 if (storage_class == SpvStorageClassGeneric) 487 return _.diag(SPV_ERROR_INVALID_BINARY, inst) 488 << "OpVariable storage class cannot be Generic"; 489 if (_.current_layout_section() == kLayoutFunctionDefinitions) { 490 if (storage_class != SpvStorageClassFunction) { 491 return _.diag(SPV_ERROR_INVALID_LAYOUT, inst) 492 << "Variables must have a function[7] storage class inside" 493 " of a function"; 494 } 495 if (_.current_function().IsFirstBlock( 496 _.current_function().current_block()->id()) == false) { 497 return _.diag(SPV_ERROR_INVALID_CFG, inst) 498 << "Variables can only be defined " 499 "in the first block of a " 500 "function"; 501 } 502 } else { 503 if (storage_class == SpvStorageClassFunction) { 504 return _.diag(SPV_ERROR_INVALID_LAYOUT, inst) 505 << "Variables can not have a function[7] storage class " 506 "outside of a function"; 507 } 508 } 509 } 510 511 // SPIR-V Spec 2.16.3: Validation Rules for Kernel Capabilities: The 512 // Signedness in OpTypeInt must always be 0. 513 if (SpvOpTypeInt == inst->opcode() && _.HasCapability(SpvCapabilityKernel) && 514 inst->GetOperandAs<uint32_t>(2) != 0u) { 515 return _.diag(SPV_ERROR_INVALID_BINARY, inst) 516 << "The Signedness in OpTypeInt " 517 "must always be 0 when Kernel " 518 "capability is used."; 519 } 520 521 if (auto error = ExtensionCheck(_, inst)) return error; 522 if (auto error = ReservedCheck(_, inst)) return error; 523 if (auto error = EnvironmentCheck(_, inst)) return error; 524 if (auto error = CapabilityCheck(_, inst)) return error; 525 if (auto error = LimitCheckIdBound(_, inst)) return error; 526 if (auto error = LimitCheckStruct(_, inst)) return error; 527 if (auto error = LimitCheckSwitch(_, inst)) return error; 528 if (auto error = VersionCheck(_, inst)) return error; 529 530 // All instruction checks have passed. 531 return SPV_SUCCESS; 532 } 533 534 } // namespace val 535 } // namespace spvtools 536