validate.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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. #include "source/val/validate.h"
  15. #include <algorithm>
  16. #include <cassert>
  17. #include <cstdio>
  18. #include <functional>
  19. #include <iterator>
  20. #include <memory>
  21. #include <sstream>
  22. #include <string>
  23. #include <vector>
  24. #include "source/binary.h"
  25. #include "source/diagnostic.h"
  26. #include "source/enum_string_mapping.h"
  27. #include "source/extensions.h"
  28. #include "source/instruction.h"
  29. #include "source/opcode.h"
  30. #include "source/operand.h"
  31. #include "source/spirv_constant.h"
  32. #include "source/spirv_endian.h"
  33. #include "source/spirv_target_env.h"
  34. #include "source/spirv_validator_options.h"
  35. #include "source/val/construct.h"
  36. #include "source/val/function.h"
  37. #include "source/val/instruction.h"
  38. #include "source/val/validation_state.h"
  39. #include "spirv-tools/libspirv.h"
  40. namespace {
  41. // TODO(issue 1950): The validator only returns a single message anyway, so no
  42. // point in generating more than 1 warning.
  43. static uint32_t kDefaultMaxNumOfWarnings = 1;
  44. } // namespace
  45. namespace spvtools {
  46. namespace val {
  47. namespace {
  48. // Parses OpExtension instruction and registers extension.
  49. void RegisterExtension(ValidationState_t& _,
  50. const spv_parsed_instruction_t* inst) {
  51. const std::string extension_str = spvtools::GetExtensionString(inst);
  52. Extension extension;
  53. if (!GetExtensionFromString(extension_str.c_str(), &extension)) {
  54. // The error will be logged in the ProcessInstruction pass.
  55. return;
  56. }
  57. _.RegisterExtension(extension);
  58. }
  59. // Parses the beginning of the module searching for OpExtension instructions.
  60. // Registers extensions if recognized. Returns SPV_REQUESTED_TERMINATION
  61. // once an instruction which is not SpvOpCapability and SpvOpExtension is
  62. // encountered. According to the SPIR-V spec extensions are declared after
  63. // capabilities and before everything else.
  64. spv_result_t ProcessExtensions(void* user_data,
  65. const spv_parsed_instruction_t* inst) {
  66. const SpvOp opcode = static_cast<SpvOp>(inst->opcode);
  67. if (opcode == SpvOpCapability) return SPV_SUCCESS;
  68. if (opcode == SpvOpExtension) {
  69. ValidationState_t& _ = *(reinterpret_cast<ValidationState_t*>(user_data));
  70. RegisterExtension(_, inst);
  71. return SPV_SUCCESS;
  72. }
  73. // OpExtension block is finished, requesting termination.
  74. return SPV_REQUESTED_TERMINATION;
  75. }
  76. spv_result_t ProcessInstruction(void* user_data,
  77. const spv_parsed_instruction_t* inst) {
  78. ValidationState_t& _ = *(reinterpret_cast<ValidationState_t*>(user_data));
  79. auto* instruction = _.AddOrderedInstruction(inst);
  80. _.RegisterDebugInstruction(instruction);
  81. return SPV_SUCCESS;
  82. }
  83. spv_result_t ValidateForwardDecls(ValidationState_t& _) {
  84. if (_.unresolved_forward_id_count() == 0) return SPV_SUCCESS;
  85. std::stringstream ss;
  86. std::vector<uint32_t> ids = _.UnresolvedForwardIds();
  87. std::transform(
  88. std::begin(ids), std::end(ids),
  89. std::ostream_iterator<std::string>(ss, " "),
  90. bind(&ValidationState_t::getIdName, std::ref(_), std::placeholders::_1));
  91. auto id_str = ss.str();
  92. return _.diag(SPV_ERROR_INVALID_ID, nullptr)
  93. << "The following forward referenced IDs have not been defined:\n"
  94. << id_str.substr(0, id_str.size() - 1);
  95. }
  96. std::vector<std::string> CalculateNamesForEntryPoint(ValidationState_t& _,
  97. const uint32_t id) {
  98. auto id_descriptions = _.entry_point_descriptions(id);
  99. auto id_names = std::vector<std::string>();
  100. id_names.reserve((id_descriptions.size()));
  101. for (auto description : id_descriptions) id_names.push_back(description.name);
  102. return id_names;
  103. }
  104. spv_result_t ValidateEntryPointNameUnique(ValidationState_t& _,
  105. const uint32_t id) {
  106. auto id_names = CalculateNamesForEntryPoint(_, id);
  107. const auto names =
  108. std::unordered_set<std::string>(id_names.begin(), id_names.end());
  109. if (id_names.size() != names.size()) {
  110. std::sort(id_names.begin(), id_names.end());
  111. for (size_t i = 0; i < id_names.size() - 1; i++) {
  112. if (id_names[i] == id_names[i + 1]) {
  113. return _.diag(SPV_ERROR_INVALID_BINARY, _.FindDef(id))
  114. << "Entry point name \"" << id_names[i]
  115. << "\" is not unique, which is not allow in WebGPU env.";
  116. }
  117. }
  118. }
  119. for (const auto other_id : _.entry_points()) {
  120. if (other_id == id) continue;
  121. const auto other_id_names = CalculateNamesForEntryPoint(_, other_id);
  122. for (const auto other_id_name : other_id_names) {
  123. if (names.find(other_id_name) != names.end()) {
  124. return _.diag(SPV_ERROR_INVALID_BINARY, _.FindDef(id))
  125. << "Entry point name \"" << other_id_name
  126. << "\" is not unique, which is not allow in WebGPU env.";
  127. }
  128. }
  129. }
  130. return SPV_SUCCESS;
  131. }
  132. spv_result_t ValidateEntryPointNamesUnique(ValidationState_t& _) {
  133. for (const auto id : _.entry_points()) {
  134. auto result = ValidateEntryPointNameUnique(_, id);
  135. if (result != SPV_SUCCESS) return result;
  136. }
  137. return SPV_SUCCESS;
  138. }
  139. // Entry point validation. Based on 2.16.1 (Universal Validation Rules) of the
  140. // SPIRV spec:
  141. // * There is at least one OpEntryPoint instruction, unless the Linkage
  142. // capability is being used.
  143. // * No function can be targeted by both an OpEntryPoint instruction and an
  144. // OpFunctionCall instruction.
  145. //
  146. // Additionally enforces that entry points for Vulkan and WebGPU should not have
  147. // recursion. And that entry names should be unique for WebGPU.
  148. spv_result_t ValidateEntryPoints(ValidationState_t& _) {
  149. _.ComputeFunctionToEntryPointMapping();
  150. _.ComputeRecursiveEntryPoints();
  151. if (_.entry_points().empty() && !_.HasCapability(SpvCapabilityLinkage)) {
  152. return _.diag(SPV_ERROR_INVALID_BINARY, nullptr)
  153. << "No OpEntryPoint instruction was found. This is only allowed if "
  154. "the Linkage capability is being used.";
  155. }
  156. for (const auto& entry_point : _.entry_points()) {
  157. if (_.IsFunctionCallTarget(entry_point)) {
  158. return _.diag(SPV_ERROR_INVALID_BINARY, _.FindDef(entry_point))
  159. << "A function (" << entry_point
  160. << ") may not be targeted by both an OpEntryPoint instruction and "
  161. "an OpFunctionCall instruction.";
  162. }
  163. // For Vulkan and WebGPU, the static function-call graph for an entry point
  164. // must not contain cycles.
  165. if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) {
  166. if (_.recursive_entry_points().find(entry_point) !=
  167. _.recursive_entry_points().end()) {
  168. return _.diag(SPV_ERROR_INVALID_BINARY, _.FindDef(entry_point))
  169. << "Entry points may not have a call graph with cycles.";
  170. }
  171. }
  172. // For WebGPU all entry point names must be unique.
  173. if (spvIsWebGPUEnv(_.context()->target_env)) {
  174. const auto result = ValidateEntryPointNamesUnique(_);
  175. if (result != SPV_SUCCESS) return result;
  176. }
  177. }
  178. return SPV_SUCCESS;
  179. }
  180. spv_result_t ValidateBinaryUsingContextAndValidationState(
  181. const spv_context_t& context, const uint32_t* words, const size_t num_words,
  182. spv_diagnostic* pDiagnostic, ValidationState_t* vstate) {
  183. auto binary = std::unique_ptr<spv_const_binary_t>(
  184. new spv_const_binary_t{words, num_words});
  185. spv_endianness_t endian;
  186. spv_position_t position = {};
  187. if (spvBinaryEndianness(binary.get(), &endian)) {
  188. return DiagnosticStream(position, context.consumer, "",
  189. SPV_ERROR_INVALID_BINARY)
  190. << "Invalid SPIR-V magic number.";
  191. }
  192. if (spvIsWebGPUEnv(context.target_env) && endian != SPV_ENDIANNESS_LITTLE) {
  193. return DiagnosticStream(position, context.consumer, "",
  194. SPV_ERROR_INVALID_BINARY)
  195. << "WebGPU requires SPIR-V to be little endian.";
  196. }
  197. spv_header_t header;
  198. if (spvBinaryHeaderGet(binary.get(), endian, &header)) {
  199. return DiagnosticStream(position, context.consumer, "",
  200. SPV_ERROR_INVALID_BINARY)
  201. << "Invalid SPIR-V header.";
  202. }
  203. if (header.version > spvVersionForTargetEnv(context.target_env)) {
  204. return DiagnosticStream(position, context.consumer, "",
  205. SPV_ERROR_WRONG_VERSION)
  206. << "Invalid SPIR-V binary version "
  207. << SPV_SPIRV_VERSION_MAJOR_PART(header.version) << "."
  208. << SPV_SPIRV_VERSION_MINOR_PART(header.version)
  209. << " for target environment "
  210. << spvTargetEnvDescription(context.target_env) << ".";
  211. }
  212. if (header.bound > vstate->options()->universal_limits_.max_id_bound) {
  213. return DiagnosticStream(position, context.consumer, "",
  214. SPV_ERROR_INVALID_BINARY)
  215. << "Invalid SPIR-V. The id bound is larger than the max id bound "
  216. << vstate->options()->universal_limits_.max_id_bound << ".";
  217. }
  218. // Look for OpExtension instructions and register extensions.
  219. // This parse should not produce any error messages. Hijack the context and
  220. // replace the message consumer so that we do not pollute any state in input
  221. // consumer.
  222. spv_context_t hijacked_context = context;
  223. hijacked_context.consumer = [](spv_message_level_t, const char*,
  224. const spv_position_t&, const char*) {};
  225. spvBinaryParse(&hijacked_context, vstate, words, num_words,
  226. /* parsed_header = */ nullptr, ProcessExtensions,
  227. /* diagnostic = */ nullptr);
  228. // Parse the module and perform inline validation checks. These checks do
  229. // not require the the knowledge of the whole module.
  230. if (auto error = spvBinaryParse(&context, vstate, words, num_words,
  231. /*parsed_header =*/nullptr,
  232. ProcessInstruction, pDiagnostic)) {
  233. return error;
  234. }
  235. std::vector<Instruction*> visited_entry_points;
  236. for (auto& instruction : vstate->ordered_instructions()) {
  237. {
  238. // In order to do this work outside of Process Instruction we need to be
  239. // able to, briefly, de-const the instruction.
  240. Instruction* inst = const_cast<Instruction*>(&instruction);
  241. if (inst->opcode() == SpvOpEntryPoint) {
  242. const auto entry_point = inst->GetOperandAs<uint32_t>(1);
  243. const auto execution_model = inst->GetOperandAs<SpvExecutionModel>(0);
  244. const char* str = reinterpret_cast<const char*>(
  245. inst->words().data() + inst->operand(2).offset);
  246. ValidationState_t::EntryPointDescription desc;
  247. desc.name = str;
  248. std::vector<uint32_t> interfaces;
  249. for (size_t j = 3; j < inst->operands().size(); ++j)
  250. desc.interfaces.push_back(inst->word(inst->operand(j).offset));
  251. vstate->RegisterEntryPoint(entry_point, execution_model,
  252. std::move(desc));
  253. if (visited_entry_points.size() > 0) {
  254. for (const Instruction* check_inst : visited_entry_points) {
  255. const auto check_execution_model =
  256. check_inst->GetOperandAs<SpvExecutionModel>(0);
  257. const char* check_str = reinterpret_cast<const char*>(
  258. check_inst->words().data() + inst->operand(2).offset);
  259. const std::string check_name(check_str);
  260. if (desc.name == check_name &&
  261. execution_model == check_execution_model) {
  262. return vstate->diag(SPV_ERROR_INVALID_DATA, inst)
  263. << "2 Entry points cannot share the same name and "
  264. "ExecutionMode.";
  265. }
  266. }
  267. }
  268. visited_entry_points.push_back(inst);
  269. }
  270. if (inst->opcode() == SpvOpFunctionCall) {
  271. if (!vstate->in_function_body()) {
  272. return vstate->diag(SPV_ERROR_INVALID_LAYOUT, &instruction)
  273. << "A FunctionCall must happen within a function body.";
  274. }
  275. const auto called_id = inst->GetOperandAs<uint32_t>(2);
  276. if (spvIsWebGPUEnv(context.target_env) &&
  277. !vstate->IsFunctionCallDefined(called_id)) {
  278. return vstate->diag(SPV_ERROR_INVALID_LAYOUT, &instruction)
  279. << "For WebGPU, functions need to be defined before being "
  280. "called.";
  281. }
  282. vstate->AddFunctionCallTarget(called_id);
  283. }
  284. if (vstate->in_function_body()) {
  285. inst->set_function(&(vstate->current_function()));
  286. inst->set_block(vstate->current_function().current_block());
  287. if (vstate->in_block() && spvOpcodeIsBlockTerminator(inst->opcode())) {
  288. vstate->current_function().current_block()->set_terminator(inst);
  289. }
  290. }
  291. if (auto error = IdPass(*vstate, inst)) return error;
  292. }
  293. if (auto error = CapabilityPass(*vstate, &instruction)) return error;
  294. if (auto error = ModuleLayoutPass(*vstate, &instruction)) return error;
  295. if (auto error = CfgPass(*vstate, &instruction)) return error;
  296. if (auto error = InstructionPass(*vstate, &instruction)) return error;
  297. // Now that all of the checks are done, update the state.
  298. {
  299. Instruction* inst = const_cast<Instruction*>(&instruction);
  300. vstate->RegisterInstruction(inst);
  301. if (inst->opcode() == SpvOpTypeForwardPointer) {
  302. vstate->RegisterForwardPointer(inst->GetOperandAs<uint32_t>(0));
  303. }
  304. }
  305. }
  306. if (!vstate->has_memory_model_specified())
  307. return vstate->diag(SPV_ERROR_INVALID_LAYOUT, nullptr)
  308. << "Missing required OpMemoryModel instruction.";
  309. if (vstate->in_function_body())
  310. return vstate->diag(SPV_ERROR_INVALID_LAYOUT, nullptr)
  311. << "Missing OpFunctionEnd at end of module.";
  312. // Catch undefined forward references before performing further checks.
  313. if (auto error = ValidateForwardDecls(*vstate)) return error;
  314. // ID usage needs be handled in its own iteration of the instructions,
  315. // between the two others. It depends on the first loop to have been
  316. // finished, so that all instructions have been registered. And the following
  317. // loop depends on all of the usage data being populated. Thus it cannot live
  318. // in either of those iterations.
  319. // It should also live after the forward declaration check, since it will
  320. // have problems with missing forward declarations, but give less useful error
  321. // messages.
  322. for (size_t i = 0; i < vstate->ordered_instructions().size(); ++i) {
  323. auto& instruction = vstate->ordered_instructions()[i];
  324. if (auto error = UpdateIdUse(*vstate, &instruction)) return error;
  325. }
  326. // Validate individual opcodes.
  327. for (size_t i = 0; i < vstate->ordered_instructions().size(); ++i) {
  328. auto& instruction = vstate->ordered_instructions()[i];
  329. // Keep these passes in the order they appear in the SPIR-V specification
  330. // sections to maintain test consistency.
  331. if (auto error = MiscPass(*vstate, &instruction)) return error;
  332. if (auto error = DebugPass(*vstate, &instruction)) return error;
  333. if (auto error = AnnotationPass(*vstate, &instruction)) return error;
  334. if (auto error = ExtensionPass(*vstate, &instruction)) return error;
  335. if (auto error = ModeSettingPass(*vstate, &instruction)) return error;
  336. if (auto error = TypePass(*vstate, &instruction)) return error;
  337. if (auto error = ConstantPass(*vstate, &instruction)) return error;
  338. if (auto error = MemoryPass(*vstate, &instruction)) return error;
  339. if (auto error = FunctionPass(*vstate, &instruction)) return error;
  340. if (auto error = ImagePass(*vstate, &instruction)) return error;
  341. if (auto error = ConversionPass(*vstate, &instruction)) return error;
  342. if (auto error = CompositesPass(*vstate, &instruction)) return error;
  343. if (auto error = ArithmeticsPass(*vstate, &instruction)) return error;
  344. if (auto error = BitwisePass(*vstate, &instruction)) return error;
  345. if (auto error = LogicalsPass(*vstate, &instruction)) return error;
  346. if (auto error = ControlFlowPass(*vstate, &instruction)) return error;
  347. if (auto error = DerivativesPass(*vstate, &instruction)) return error;
  348. if (auto error = AtomicsPass(*vstate, &instruction)) return error;
  349. if (auto error = PrimitivesPass(*vstate, &instruction)) return error;
  350. if (auto error = BarriersPass(*vstate, &instruction)) return error;
  351. // Group
  352. // Device-Side Enqueue
  353. // Pipe
  354. if (auto error = NonUniformPass(*vstate, &instruction)) return error;
  355. if (auto error = LiteralsPass(*vstate, &instruction)) return error;
  356. }
  357. // Validate the preconditions involving adjacent instructions. e.g. SpvOpPhi
  358. // must only be preceeded by SpvOpLabel, SpvOpPhi, or SpvOpLine.
  359. if (auto error = ValidateAdjacency(*vstate)) return error;
  360. if (auto error = ValidateEntryPoints(*vstate)) return error;
  361. // CFG checks are performed after the binary has been parsed
  362. // and the CFGPass has collected information about the control flow
  363. if (auto error = PerformCfgChecks(*vstate)) return error;
  364. if (auto error = CheckIdDefinitionDominateUse(*vstate)) return error;
  365. if (auto error = ValidateDecorations(*vstate)) return error;
  366. if (auto error = ValidateInterfaces(*vstate)) return error;
  367. // TODO(dsinclair): Restructure ValidateBuiltins so we can move into the
  368. // for() above as it loops over all ordered_instructions internally.
  369. if (auto error = ValidateBuiltIns(*vstate)) return error;
  370. // These checks must be performed after individual opcode checks because
  371. // those checks register the limitation checked here.
  372. for (const auto inst : vstate->ordered_instructions()) {
  373. if (auto error = ValidateExecutionLimitations(*vstate, &inst)) return error;
  374. if (auto error = ValidateSmallTypeUses(*vstate, &inst)) return error;
  375. }
  376. return SPV_SUCCESS;
  377. }
  378. } // namespace
  379. spv_result_t ValidateBinaryAndKeepValidationState(
  380. const spv_const_context context, spv_const_validator_options options,
  381. const uint32_t* words, const size_t num_words, spv_diagnostic* pDiagnostic,
  382. std::unique_ptr<ValidationState_t>* vstate) {
  383. spv_context_t hijack_context = *context;
  384. if (pDiagnostic) {
  385. *pDiagnostic = nullptr;
  386. UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
  387. }
  388. vstate->reset(new ValidationState_t(&hijack_context, options, words,
  389. num_words, kDefaultMaxNumOfWarnings));
  390. return ValidateBinaryUsingContextAndValidationState(
  391. hijack_context, words, num_words, pDiagnostic, vstate->get());
  392. }
  393. } // namespace val
  394. } // namespace spvtools
  395. spv_result_t spvValidate(const spv_const_context context,
  396. const spv_const_binary binary,
  397. spv_diagnostic* pDiagnostic) {
  398. return spvValidateBinary(context, binary->code, binary->wordCount,
  399. pDiagnostic);
  400. }
  401. spv_result_t spvValidateBinary(const spv_const_context context,
  402. const uint32_t* words, const size_t num_words,
  403. spv_diagnostic* pDiagnostic) {
  404. spv_context_t hijack_context = *context;
  405. if (pDiagnostic) {
  406. *pDiagnostic = nullptr;
  407. spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
  408. }
  409. // This interface is used for default command line options.
  410. spv_validator_options default_options = spvValidatorOptionsCreate();
  411. // Create the ValidationState using the context and default options.
  412. spvtools::val::ValidationState_t vstate(&hijack_context, default_options,
  413. words, num_words,
  414. kDefaultMaxNumOfWarnings);
  415. spv_result_t result =
  416. spvtools::val::ValidateBinaryUsingContextAndValidationState(
  417. hijack_context, words, num_words, pDiagnostic, &vstate);
  418. spvValidatorOptionsDestroy(default_options);
  419. return result;
  420. }
  421. spv_result_t spvValidateWithOptions(const spv_const_context context,
  422. spv_const_validator_options options,
  423. const spv_const_binary binary,
  424. spv_diagnostic* pDiagnostic) {
  425. spv_context_t hijack_context = *context;
  426. if (pDiagnostic) {
  427. *pDiagnostic = nullptr;
  428. spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
  429. }
  430. // Create the ValidationState using the context.
  431. spvtools::val::ValidationState_t vstate(&hijack_context, options,
  432. binary->code, binary->wordCount,
  433. kDefaultMaxNumOfWarnings);
  434. return spvtools::val::ValidateBinaryUsingContextAndValidationState(
  435. hijack_context, binary->code, binary->wordCount, pDiagnostic, &vstate);
  436. }