validate_instruction.cpp 22 KB

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