validate_instruction.cpp 25 KB

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