binary.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. // Copyright (c) 2015-2020 The Khronos Group Inc.
  2. // Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights
  3. // reserved.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. #include "source/binary.h"
  17. #include <algorithm>
  18. #include <cassert>
  19. #include <cstring>
  20. #include <iterator>
  21. #include <limits>
  22. #include <string>
  23. #include <unordered_map>
  24. #include <vector>
  25. #include "source/assembly_grammar.h"
  26. #include "source/diagnostic.h"
  27. #include "source/ext_inst.h"
  28. #include "source/latest_version_spirv_header.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/table2.h"
  34. #include "source/util/string_utils.h"
  35. spv_result_t spvBinaryHeaderGet(const spv_const_binary binary,
  36. const spv_endianness_t endian,
  37. spv_header_t* pHeader) {
  38. if (!binary->code) return SPV_ERROR_INVALID_BINARY;
  39. if (binary->wordCount < SPV_INDEX_INSTRUCTION)
  40. return SPV_ERROR_INVALID_BINARY;
  41. if (!pHeader) return SPV_ERROR_INVALID_POINTER;
  42. // TODO: Validation checking?
  43. pHeader->magic = spvFixWord(binary->code[SPV_INDEX_MAGIC_NUMBER], endian);
  44. pHeader->version = spvFixWord(binary->code[SPV_INDEX_VERSION_NUMBER], endian);
  45. // Per 2.3.1 version's high and low bytes are 0
  46. if ((pHeader->version & 0x000000ff) || pHeader->version & 0xff000000)
  47. return SPV_ERROR_INVALID_BINARY;
  48. // Minimum version was 1.0 and max version is defined by SPV_VERSION.
  49. if (pHeader->version < SPV_SPIRV_VERSION_WORD(1, 0) ||
  50. pHeader->version > SPV_VERSION)
  51. return SPV_ERROR_INVALID_BINARY;
  52. pHeader->generator =
  53. spvFixWord(binary->code[SPV_INDEX_GENERATOR_NUMBER], endian);
  54. pHeader->bound = spvFixWord(binary->code[SPV_INDEX_BOUND], endian);
  55. pHeader->schema = spvFixWord(binary->code[SPV_INDEX_SCHEMA], endian);
  56. pHeader->instructions = &binary->code[SPV_INDEX_INSTRUCTION];
  57. return SPV_SUCCESS;
  58. }
  59. std::string spvDecodeLiteralStringOperand(const spv_parsed_instruction_t& inst,
  60. const uint16_t operand_index) {
  61. assert(operand_index < inst.num_operands);
  62. const spv_parsed_operand_t& operand = inst.operands[operand_index];
  63. return spvtools::utils::MakeString(inst.words + operand.offset,
  64. operand.num_words);
  65. }
  66. namespace {
  67. // A SPIR-V binary parser. A parser instance communicates detailed parse
  68. // results via callbacks.
  69. class Parser {
  70. public:
  71. // The user_data value is provided to the callbacks as context.
  72. Parser(const spv_const_context context, void* user_data,
  73. spv_parsed_header_fn_t parsed_header_fn,
  74. spv_parsed_instruction_fn_t parsed_instruction_fn)
  75. : grammar_(context),
  76. consumer_(context->consumer),
  77. user_data_(user_data),
  78. parsed_header_fn_(parsed_header_fn),
  79. parsed_instruction_fn_(parsed_instruction_fn) {}
  80. // Parses the specified binary SPIR-V module, issuing callbacks on a parsed
  81. // header and for each parsed instruction. Returns SPV_SUCCESS on success.
  82. // Otherwise returns an error code and issues a diagnostic.
  83. spv_result_t parse(const uint32_t* words, size_t num_words,
  84. spv_diagnostic* diagnostic);
  85. private:
  86. // All remaining methods work on the current module parse state.
  87. // Like the parse method, but works on the current module parse state.
  88. spv_result_t parseModule();
  89. // Parses an instruction at the current position of the binary. Assumes
  90. // the header has been parsed, the endian has been set, and the word index is
  91. // still in range. Advances the parsing position past the instruction, and
  92. // updates other parsing state for the current module.
  93. // On success, returns SPV_SUCCESS and issues the parsed-instruction callback.
  94. // On failure, returns an error code and issues a diagnostic.
  95. spv_result_t parseInstruction();
  96. // Parses an instruction operand with the given type, for an instruction
  97. // starting at inst_offset words into the SPIR-V binary.
  98. // If the SPIR-V binary is the same endianness as the host, then the
  99. // endian_converted_inst_words parameter is ignored. Otherwise, this method
  100. // appends the words for this operand, converted to host native endianness,
  101. // to the end of endian_converted_inst_words. This method also updates the
  102. // expected_operands parameter, and the scalar members of the inst parameter.
  103. // On success, returns SPV_SUCCESS, advances past the operand, and pushes a
  104. // new entry on to the operands vector. Otherwise returns an error code and
  105. // issues a diagnostic.
  106. spv_result_t parseOperand(size_t inst_offset, spv_parsed_instruction_t* inst,
  107. const spv_operand_type_t type,
  108. std::vector<uint32_t>* endian_converted_inst_words,
  109. std::vector<spv_parsed_operand_t>* operands,
  110. spv_operand_pattern_t* expected_operands);
  111. // Records the numeric type for an operand according to the type information
  112. // associated with the given non-zero type Id. This can fail if the type Id
  113. // is not a type Id, or if the type Id does not reference a scalar numeric
  114. // type. On success, return SPV_SUCCESS and populates the num_words,
  115. // number_kind, and number_bit_width fields of parsed_operand.
  116. spv_result_t setNumericTypeInfoForType(spv_parsed_operand_t* parsed_operand,
  117. uint32_t type_id);
  118. // Records the number type for an instruction at the given offset, if that
  119. // instruction generates a type. For types that aren't scalar numbers,
  120. // record something with number kind SPV_NUMBER_NONE.
  121. void recordNumberType(size_t inst_offset,
  122. const spv_parsed_instruction_t* inst);
  123. // Returns a diagnostic stream object initialized with current position in
  124. // the input stream, and for the given error code. Any data written to the
  125. // returned object will be propagated to the current parse's diagnostic
  126. // object.
  127. spvtools::DiagnosticStream diagnostic(spv_result_t error) {
  128. return spvtools::DiagnosticStream({0, 0, _.instruction_count}, consumer_,
  129. "", error);
  130. }
  131. // Returns a diagnostic stream object with the default parse error code.
  132. spvtools::DiagnosticStream diagnostic() {
  133. // The default failure for parsing is invalid binary.
  134. return diagnostic(SPV_ERROR_INVALID_BINARY);
  135. }
  136. // Issues a diagnostic describing an exhaustion of input condition when
  137. // trying to decode an instruction operand, and returns
  138. // SPV_ERROR_INVALID_BINARY.
  139. spv_result_t exhaustedInputDiagnostic(size_t inst_offset, spv::Op opcode,
  140. spv_operand_type_t type) {
  141. return diagnostic() << "End of input reached while decoding Op"
  142. << spvOpcodeString(opcode) << " starting at word "
  143. << inst_offset
  144. << ((_.word_index < _.num_words) ? ": truncated "
  145. : ": missing ")
  146. << spvOperandTypeStr(type) << " operand at word offset "
  147. << _.word_index - inst_offset << ".";
  148. }
  149. // Returns the endian-corrected word at the current position.
  150. uint32_t peek() const { return peekAt(_.word_index); }
  151. // Returns the endian-corrected word at the given position.
  152. uint32_t peekAt(size_t index) const {
  153. assert(index < _.num_words);
  154. return spvFixWord(_.words[index], _.endian);
  155. }
  156. // Data members
  157. const spvtools::AssemblyGrammar grammar_; // SPIR-V syntax utility.
  158. const spvtools::MessageConsumer& consumer_; // Message consumer callback.
  159. void* const user_data_; // Context for the callbacks
  160. const spv_parsed_header_fn_t parsed_header_fn_; // Parsed header callback
  161. const spv_parsed_instruction_fn_t
  162. parsed_instruction_fn_; // Parsed instruction callback
  163. // Describes the format of a typed literal number.
  164. struct NumberType {
  165. spv_number_kind_t type;
  166. uint32_t bit_width;
  167. };
  168. // The state used to parse a single SPIR-V binary module.
  169. struct State {
  170. State(const uint32_t* words_arg, size_t num_words_arg,
  171. spv_diagnostic* diagnostic_arg)
  172. : words(words_arg),
  173. num_words(num_words_arg),
  174. diagnostic(diagnostic_arg),
  175. word_index(0),
  176. instruction_count(0),
  177. endian(),
  178. requires_endian_conversion(false) {
  179. // Temporary storage for parser state within a single instruction.
  180. // Most instructions require fewer than 25 words or operands.
  181. operands.reserve(25);
  182. endian_converted_words.reserve(25);
  183. expected_operands.reserve(25);
  184. }
  185. State() : State(0, 0, nullptr) {}
  186. const uint32_t* words; // Words in the binary SPIR-V module.
  187. size_t num_words; // Number of words in the module.
  188. spv_diagnostic* diagnostic; // Where diagnostics go.
  189. size_t word_index; // The current position in words.
  190. size_t instruction_count; // The count of processed instructions
  191. spv_endianness_t endian; // The endianness of the binary.
  192. // Is the SPIR-V binary in a different endianness from the host native
  193. // endianness?
  194. bool requires_endian_conversion;
  195. // Maps a result ID to its type ID. By convention:
  196. // - a result ID that is a type definition maps to itself.
  197. // - a result ID without a type maps to 0. (E.g. for OpLabel)
  198. std::unordered_map<uint32_t, uint32_t> id_to_type_id;
  199. // Maps a type ID to its number type description.
  200. std::unordered_map<uint32_t, NumberType> type_id_to_number_type_info;
  201. // Maps an ExtInstImport id to the extended instruction type.
  202. std::unordered_map<uint32_t, spv_ext_inst_type_t>
  203. import_id_to_ext_inst_type;
  204. // Used by parseOperand
  205. std::vector<spv_parsed_operand_t> operands;
  206. std::vector<uint32_t> endian_converted_words;
  207. spv_operand_pattern_t expected_operands;
  208. } _;
  209. };
  210. spv_result_t Parser::parse(const uint32_t* words, size_t num_words,
  211. spv_diagnostic* diagnostic_arg) {
  212. _ = State(words, num_words, diagnostic_arg);
  213. const spv_result_t result = parseModule();
  214. // Clear the module state. The tables might be big.
  215. _ = State();
  216. return result;
  217. }
  218. spv_result_t Parser::parseModule() {
  219. if (!_.words) return diagnostic() << "Missing module.";
  220. if (_.num_words < SPV_INDEX_INSTRUCTION)
  221. return diagnostic() << "Module has incomplete header: only " << _.num_words
  222. << " words instead of " << SPV_INDEX_INSTRUCTION;
  223. // Check the magic number and detect the module's endianness.
  224. spv_const_binary_t binary{_.words, _.num_words};
  225. if (spvBinaryEndianness(&binary, &_.endian)) {
  226. return diagnostic() << "Invalid SPIR-V magic number '" << std::hex
  227. << _.words[0] << "'.";
  228. }
  229. _.requires_endian_conversion = !spvIsHostEndian(_.endian);
  230. // Process the header.
  231. spv_header_t header;
  232. if (spvBinaryHeaderGet(&binary, _.endian, &header)) {
  233. // It turns out there is no way to trigger this error since the only
  234. // failure cases are already handled above, with better messages.
  235. return diagnostic(SPV_ERROR_INTERNAL)
  236. << "Internal error: unhandled header parse failure";
  237. }
  238. if (parsed_header_fn_) {
  239. if (auto error = parsed_header_fn_(user_data_, _.endian, header.magic,
  240. header.version, header.generator,
  241. header.bound, header.schema)) {
  242. return error;
  243. }
  244. }
  245. // Process the instructions.
  246. _.word_index = SPV_INDEX_INSTRUCTION;
  247. while (_.word_index < _.num_words)
  248. if (auto error = parseInstruction()) return error;
  249. // Running off the end should already have been reported earlier.
  250. assert(_.word_index == _.num_words);
  251. return SPV_SUCCESS;
  252. }
  253. spv_result_t Parser::parseInstruction() {
  254. _.instruction_count++;
  255. // The zero values for all members except for opcode are the
  256. // correct initial values.
  257. spv_parsed_instruction_t inst = {};
  258. const uint32_t first_word = peek();
  259. // If the module's endianness is different from the host native endianness,
  260. // then converted_words contains the endian-translated words in the
  261. // instruction.
  262. _.endian_converted_words.clear();
  263. _.endian_converted_words.push_back(first_word);
  264. // After a successful parse of the instruction, the inst.operands member
  265. // will point to this vector's storage.
  266. _.operands.clear();
  267. assert(_.word_index < _.num_words);
  268. // Decompose and check the first word.
  269. uint16_t inst_word_count = 0;
  270. spvOpcodeSplit(first_word, &inst_word_count, &inst.opcode);
  271. if (inst_word_count < 1) {
  272. return diagnostic() << "Invalid instruction word count: "
  273. << inst_word_count;
  274. }
  275. const spvtools::InstructionDesc* opcode_desc = nullptr;
  276. if (spvtools::LookupOpcode(static_cast<spv::Op>(inst.opcode), &opcode_desc))
  277. return diagnostic() << "Invalid opcode: " << inst.opcode;
  278. // Advance past the opcode word. But remember the of the start
  279. // of the instruction.
  280. const size_t inst_offset = _.word_index;
  281. _.word_index++;
  282. // Maintains the ordered list of expected operand types.
  283. // For many instructions we only need the {numTypes, operandTypes}
  284. // entries in opcode_desc. However, sometimes we need to modify
  285. // the list as we parse the operands. This occurs when an operand
  286. // has its own logical operands (such as the LocalSize operand for
  287. // ExecutionMode), or for extended instructions that may have their
  288. // own operands depending on the selected extended instruction.
  289. _.expected_operands.clear();
  290. spvPushOperandTypes(opcode_desc->operands(), &_.expected_operands);
  291. while (_.word_index < inst_offset + inst_word_count) {
  292. const uint16_t inst_word_index = uint16_t(_.word_index - inst_offset);
  293. if (_.expected_operands.empty()) {
  294. return diagnostic() << "Invalid instruction Op"
  295. << opcode_desc->name().data() << " starting at word "
  296. << inst_offset << ": expected no more operands after "
  297. << inst_word_index
  298. << " words, but stated word count is "
  299. << inst_word_count << ".";
  300. }
  301. spv_operand_type_t type =
  302. spvTakeFirstMatchableOperand(&_.expected_operands);
  303. if (auto error =
  304. parseOperand(inst_offset, &inst, type, &_.endian_converted_words,
  305. &_.operands, &_.expected_operands)) {
  306. return error;
  307. }
  308. }
  309. if (!_.expected_operands.empty() &&
  310. !spvOperandIsOptional(_.expected_operands.back())) {
  311. return diagnostic() << "End of input reached while decoding Op"
  312. << opcode_desc->name().data() << " starting at word "
  313. << inst_offset << ": expected more operands after "
  314. << inst_word_count << " words.";
  315. }
  316. if ((inst_offset + inst_word_count) != _.word_index) {
  317. return diagnostic() << "Invalid word count: Op"
  318. << opcode_desc->name().data() << " starting at word "
  319. << inst_offset << " says it has " << inst_word_count
  320. << " words, but found " << _.word_index - inst_offset
  321. << " words instead.";
  322. }
  323. // Check the computed length of the endian-converted words vector against
  324. // the declared number of words in the instruction. If endian conversion
  325. // is required, then they should match. If no endian conversion was
  326. // performed, then the vector only contains the initial opcode/word-count
  327. // word.
  328. assert(!_.requires_endian_conversion ||
  329. (inst_word_count == _.endian_converted_words.size()));
  330. assert(_.requires_endian_conversion ||
  331. (_.endian_converted_words.size() == 1));
  332. recordNumberType(inst_offset, &inst);
  333. if (_.requires_endian_conversion) {
  334. // We must wait until here to set this pointer, because the vector might
  335. // have been be resized while we accumulated its elements.
  336. inst.words = _.endian_converted_words.data();
  337. } else {
  338. // If no conversion is required, then just point to the underlying binary.
  339. // This saves time and space.
  340. inst.words = _.words + inst_offset;
  341. }
  342. inst.num_words = inst_word_count;
  343. // We must wait until here to set this pointer, because the vector might
  344. // have been be resized while we accumulated its elements.
  345. inst.operands = _.operands.data();
  346. inst.num_operands = uint16_t(_.operands.size());
  347. // Issue the callback. The callee should know that all the storage in inst
  348. // is transient, and will disappear immediately afterward.
  349. if (parsed_instruction_fn_) {
  350. if (auto error = parsed_instruction_fn_(user_data_, &inst)) return error;
  351. }
  352. return SPV_SUCCESS;
  353. }
  354. spv_result_t Parser::parseOperand(size_t inst_offset,
  355. spv_parsed_instruction_t* inst,
  356. const spv_operand_type_t type,
  357. std::vector<uint32_t>* words,
  358. std::vector<spv_parsed_operand_t>* operands,
  359. spv_operand_pattern_t* expected_operands) {
  360. const spv::Op opcode = static_cast<spv::Op>(inst->opcode);
  361. // We'll fill in this result as we go along.
  362. spv_parsed_operand_t parsed_operand;
  363. parsed_operand.offset = uint16_t(_.word_index - inst_offset);
  364. // Most operands occupy one word. This might be be adjusted later.
  365. parsed_operand.num_words = 1;
  366. // The type argument is the one used by the grammar to parse the instruction.
  367. // But it can exposes internal parser details such as whether an operand is
  368. // optional or actually represents a variable-length sequence of operands.
  369. // The resulting type should be adjusted to avoid those internal details.
  370. // In most cases, the resulting operand type is the same as the grammar type.
  371. parsed_operand.type = type;
  372. // Assume non-numeric values. This will be updated for literal numbers.
  373. parsed_operand.number_kind = SPV_NUMBER_NONE;
  374. parsed_operand.number_bit_width = 0;
  375. if (_.word_index >= _.num_words)
  376. return exhaustedInputDiagnostic(inst_offset, opcode, type);
  377. const uint32_t word = peek();
  378. // Do the words in this operand have to be converted to native endianness?
  379. // True for all but literal strings.
  380. bool convert_operand_endianness = true;
  381. switch (type) {
  382. case SPV_OPERAND_TYPE_TYPE_ID:
  383. if (!word)
  384. return diagnostic(SPV_ERROR_INVALID_ID) << "Error: Type Id is 0";
  385. inst->type_id = word;
  386. break;
  387. case SPV_OPERAND_TYPE_RESULT_ID:
  388. if (!word)
  389. return diagnostic(SPV_ERROR_INVALID_ID) << "Error: Result Id is 0";
  390. inst->result_id = word;
  391. // Save the result ID to type ID mapping.
  392. // In the grammar, type ID always appears before result ID.
  393. if (_.id_to_type_id.find(inst->result_id) != _.id_to_type_id.end())
  394. return diagnostic(SPV_ERROR_INVALID_ID)
  395. << "Id " << inst->result_id << " is defined more than once";
  396. // Record it.
  397. // A regular value maps to its type. Some instructions (e.g. OpLabel)
  398. // have no type Id, and will map to 0. The result Id for a
  399. // type-generating instruction (e.g. OpTypeInt) maps to itself.
  400. _.id_to_type_id[inst->result_id] =
  401. spvOpcodeGeneratesType(opcode) ? inst->result_id : inst->type_id;
  402. break;
  403. case SPV_OPERAND_TYPE_ID:
  404. case SPV_OPERAND_TYPE_OPTIONAL_ID:
  405. if (!word) return diagnostic(SPV_ERROR_INVALID_ID) << "Id is 0";
  406. parsed_operand.type = SPV_OPERAND_TYPE_ID;
  407. if (spvIsExtendedInstruction(opcode) && parsed_operand.offset == 3) {
  408. // The current word is the extended instruction set Id.
  409. // Set the extended instruction set type for the current instruction.
  410. auto ext_inst_type_iter = _.import_id_to_ext_inst_type.find(word);
  411. if (ext_inst_type_iter == _.import_id_to_ext_inst_type.end()) {
  412. return diagnostic(SPV_ERROR_INVALID_ID)
  413. << "OpExtInst set Id " << word
  414. << " does not reference an OpExtInstImport result Id";
  415. }
  416. inst->ext_inst_type = ext_inst_type_iter->second;
  417. }
  418. break;
  419. case SPV_OPERAND_TYPE_SCOPE_ID:
  420. case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
  421. // Check for trivially invalid values. The operand descriptions already
  422. // have the word "ID" in them.
  423. if (!word) return diagnostic() << spvOperandTypeStr(type) << " is 0";
  424. break;
  425. case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
  426. assert(spvIsExtendedInstruction(opcode));
  427. assert(inst->ext_inst_type != SPV_EXT_INST_TYPE_NONE);
  428. const spvtools::ExtInstDesc* desc = nullptr;
  429. if (spvtools::LookupExtInst(inst->ext_inst_type, word, &desc) ==
  430. SPV_SUCCESS) {
  431. // if we know about this ext inst, push the expected operands
  432. spvPushOperandTypes(desc->operands(), expected_operands);
  433. } else {
  434. // if we don't know this extended instruction and the set isn't
  435. // non-semantic, we cannot process further
  436. if (!spvExtInstIsNonSemantic(inst->ext_inst_type)) {
  437. return diagnostic()
  438. << "Invalid extended instruction number: " << word;
  439. } else {
  440. // for non-semantic instruction sets, we know the form of all such
  441. // extended instructions contains a series of IDs as parameters
  442. expected_operands->push_back(SPV_OPERAND_TYPE_VARIABLE_ID);
  443. }
  444. }
  445. } break;
  446. case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: {
  447. assert(spv::Op::OpSpecConstantOp == opcode);
  448. if (word > static_cast<uint32_t>(spv::Op::Max) ||
  449. grammar_.lookupSpecConstantOpcode(spv::Op(word))) {
  450. return diagnostic()
  451. << "Invalid " << spvOperandTypeStr(type) << ": " << word;
  452. }
  453. const spvtools::InstructionDesc* opcode_entry = nullptr;
  454. if (spvtools::LookupOpcode(spv::Op(word), &opcode_entry)) {
  455. return diagnostic(SPV_ERROR_INTERNAL)
  456. << "OpSpecConstant opcode table out of sync";
  457. }
  458. // OpSpecConstant opcodes must have a type and result. We've already
  459. // processed them, so skip them when preparing to parse the other
  460. // operants for the opcode.
  461. assert(opcode_entry->hasType);
  462. assert(opcode_entry->hasResult);
  463. assert(opcode_entry->operands().size() >= 2);
  464. spvPushOperandTypes(opcode_entry->operands().subspan(2),
  465. expected_operands);
  466. } break;
  467. case SPV_OPERAND_TYPE_LITERAL_INTEGER:
  468. case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER:
  469. // These are regular single-word literal integer operands.
  470. // Post-parsing validation should check the range of the parsed value.
  471. parsed_operand.type = SPV_OPERAND_TYPE_LITERAL_INTEGER;
  472. // It turns out they are always unsigned integers!
  473. parsed_operand.number_kind = SPV_NUMBER_UNSIGNED_INT;
  474. parsed_operand.number_bit_width = 32;
  475. break;
  476. case SPV_OPERAND_TYPE_LITERAL_FLOAT:
  477. // These are regular single-word literal float operands.
  478. parsed_operand.type = SPV_OPERAND_TYPE_LITERAL_FLOAT;
  479. parsed_operand.number_kind = SPV_NUMBER_FLOATING;
  480. parsed_operand.number_bit_width = 32;
  481. break;
  482. case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER:
  483. case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER:
  484. parsed_operand.type = SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER;
  485. if (opcode == spv::Op::OpSwitch) {
  486. // The literal operands have the same type as the value
  487. // referenced by the selector Id.
  488. const uint32_t selector_id = peekAt(inst_offset + 1);
  489. const auto type_id_iter = _.id_to_type_id.find(selector_id);
  490. if (type_id_iter == _.id_to_type_id.end() ||
  491. type_id_iter->second == 0) {
  492. return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
  493. << " has no type";
  494. }
  495. uint32_t type_id = type_id_iter->second;
  496. if (selector_id == type_id) {
  497. // Recall that by convention, a result ID that is a type definition
  498. // maps to itself.
  499. return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
  500. << " is a type, not a value";
  501. }
  502. if (auto error = setNumericTypeInfoForType(&parsed_operand, type_id))
  503. return error;
  504. if (parsed_operand.number_kind != SPV_NUMBER_UNSIGNED_INT &&
  505. parsed_operand.number_kind != SPV_NUMBER_SIGNED_INT) {
  506. return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
  507. << " is not a scalar integer";
  508. }
  509. } else {
  510. assert(opcode == spv::Op::OpConstant ||
  511. opcode == spv::Op::OpSpecConstant);
  512. // The literal number type is determined by the type Id for the
  513. // constant.
  514. assert(inst->type_id);
  515. if (auto error =
  516. setNumericTypeInfoForType(&parsed_operand, inst->type_id))
  517. return error;
  518. }
  519. break;
  520. case SPV_OPERAND_TYPE_LITERAL_STRING:
  521. case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
  522. const size_t max_words = _.num_words - _.word_index;
  523. std::string string =
  524. spvtools::utils::MakeString(_.words + _.word_index, max_words, false);
  525. if (string.length() == max_words * 4)
  526. return exhaustedInputDiagnostic(inst_offset, opcode, type);
  527. // Make sure we can record the word count without overflow.
  528. //
  529. // This error can't currently be triggered because of validity
  530. // checks elsewhere.
  531. const size_t string_num_words = string.length() / 4 + 1;
  532. if (string_num_words > std::numeric_limits<uint16_t>::max()) {
  533. return diagnostic() << "Literal string is longer than "
  534. << std::numeric_limits<uint16_t>::max()
  535. << " words: " << string_num_words << " words long";
  536. }
  537. parsed_operand.num_words = uint16_t(string_num_words);
  538. parsed_operand.type = SPV_OPERAND_TYPE_LITERAL_STRING;
  539. if (spv::Op::OpExtInstImport == opcode) {
  540. // Record the extended instruction type for the ID for this import.
  541. // There is only one string literal argument to OpExtInstImport,
  542. // so it's sufficient to guard this just on the opcode.
  543. const spv_ext_inst_type_t ext_inst_type =
  544. spvExtInstImportTypeGet(string.c_str());
  545. if (SPV_EXT_INST_TYPE_NONE == ext_inst_type) {
  546. return diagnostic()
  547. << "Invalid extended instruction import '" << string << "'";
  548. }
  549. // We must have parsed a valid result ID. It's a condition
  550. // of the grammar, and we only accept non-zero result Ids.
  551. assert(inst->result_id);
  552. _.import_id_to_ext_inst_type[inst->result_id] = ext_inst_type;
  553. }
  554. } break;
  555. case SPV_OPERAND_TYPE_CAPABILITY:
  556. case SPV_OPERAND_TYPE_EXECUTION_MODEL:
  557. case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
  558. case SPV_OPERAND_TYPE_MEMORY_MODEL:
  559. case SPV_OPERAND_TYPE_EXECUTION_MODE:
  560. case SPV_OPERAND_TYPE_STORAGE_CLASS:
  561. case SPV_OPERAND_TYPE_DIMENSIONALITY:
  562. case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
  563. case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
  564. case SPV_OPERAND_TYPE_SAMPLER_IMAGE_FORMAT:
  565. case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
  566. case SPV_OPERAND_TYPE_LINKAGE_TYPE:
  567. case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
  568. case SPV_OPERAND_TYPE_OPTIONAL_ACCESS_QUALIFIER:
  569. case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
  570. case SPV_OPERAND_TYPE_DECORATION:
  571. case SPV_OPERAND_TYPE_BUILT_IN:
  572. case SPV_OPERAND_TYPE_GROUP_OPERATION:
  573. case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
  574. case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO:
  575. case SPV_OPERAND_TYPE_RAY_FLAGS:
  576. case SPV_OPERAND_TYPE_RAY_QUERY_INTERSECTION:
  577. case SPV_OPERAND_TYPE_RAY_QUERY_COMMITTED_INTERSECTION_TYPE:
  578. case SPV_OPERAND_TYPE_RAY_QUERY_CANDIDATE_INTERSECTION_TYPE:
  579. case SPV_OPERAND_TYPE_DEBUG_BASE_TYPE_ATTRIBUTE_ENCODING:
  580. case SPV_OPERAND_TYPE_DEBUG_COMPOSITE_TYPE:
  581. case SPV_OPERAND_TYPE_DEBUG_TYPE_QUALIFIER:
  582. case SPV_OPERAND_TYPE_DEBUG_OPERATION:
  583. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_BASE_TYPE_ATTRIBUTE_ENCODING:
  584. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_COMPOSITE_TYPE:
  585. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_TYPE_QUALIFIER:
  586. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_OPERATION:
  587. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_IMPORTED_ENTITY:
  588. case SPV_OPERAND_TYPE_FPDENORM_MODE:
  589. case SPV_OPERAND_TYPE_FPOPERATION_MODE:
  590. case SPV_OPERAND_TYPE_QUANTIZATION_MODES:
  591. case SPV_OPERAND_TYPE_OVERFLOW_MODES:
  592. case SPV_OPERAND_TYPE_PACKED_VECTOR_FORMAT:
  593. case SPV_OPERAND_TYPE_OPTIONAL_PACKED_VECTOR_FORMAT:
  594. case SPV_OPERAND_TYPE_FPENCODING:
  595. case SPV_OPERAND_TYPE_OPTIONAL_FPENCODING:
  596. case SPV_OPERAND_TYPE_HOST_ACCESS_QUALIFIER:
  597. case SPV_OPERAND_TYPE_LOAD_CACHE_CONTROL:
  598. case SPV_OPERAND_TYPE_STORE_CACHE_CONTROL:
  599. case SPV_OPERAND_TYPE_NAMED_MAXIMUM_NUMBER_OF_REGISTERS: {
  600. // A single word that is a plain enum value.
  601. // Map an optional operand type to its corresponding concrete type.
  602. if (type == SPV_OPERAND_TYPE_OPTIONAL_ACCESS_QUALIFIER)
  603. parsed_operand.type = SPV_OPERAND_TYPE_ACCESS_QUALIFIER;
  604. if (type == SPV_OPERAND_TYPE_OPTIONAL_PACKED_VECTOR_FORMAT)
  605. parsed_operand.type = SPV_OPERAND_TYPE_PACKED_VECTOR_FORMAT;
  606. if (type == SPV_OPERAND_TYPE_OPTIONAL_FPENCODING)
  607. parsed_operand.type = SPV_OPERAND_TYPE_FPENCODING;
  608. const spvtools::OperandDesc* entry = nullptr;
  609. if (spvtools::LookupOperand(type, word, &entry)) {
  610. return diagnostic()
  611. << "Invalid " << spvOperandTypeStr(parsed_operand.type)
  612. << " operand: " << word;
  613. }
  614. // Prepare to accept operands to this operand, if needed.
  615. spvPushOperandTypes(entry->operands(), expected_operands);
  616. } break;
  617. case SPV_OPERAND_TYPE_SOURCE_LANGUAGE: {
  618. const spvtools::OperandDesc* entry = nullptr;
  619. if (spvtools::LookupOperand(type, word, &entry)) {
  620. return diagnostic()
  621. << "Invalid " << spvOperandTypeStr(parsed_operand.type)
  622. << " operand: " << word
  623. << ", if you are creating a new source language please use "
  624. "value 0 "
  625. "(Unknown) and when ready, add your source language to "
  626. "SPIRV-Headers";
  627. }
  628. // Prepare to accept operands to this operand, if needed.
  629. spvPushOperandTypes(entry->operands(), expected_operands);
  630. } break;
  631. case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
  632. case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
  633. case SPV_OPERAND_TYPE_LOOP_CONTROL:
  634. case SPV_OPERAND_TYPE_IMAGE:
  635. case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
  636. case SPV_OPERAND_TYPE_MEMORY_ACCESS:
  637. case SPV_OPERAND_TYPE_TENSOR_OPERANDS:
  638. case SPV_OPERAND_TYPE_OPTIONAL_TENSOR_OPERANDS:
  639. case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
  640. case SPV_OPERAND_TYPE_OPTIONAL_RAW_ACCESS_CHAIN_OPERANDS:
  641. case SPV_OPERAND_TYPE_SELECTION_CONTROL:
  642. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_INFO_FLAGS:
  643. case SPV_OPERAND_TYPE_DEBUG_INFO_FLAGS:
  644. case SPV_OPERAND_TYPE_COOPERATIVE_MATRIX_OPERANDS:
  645. case SPV_OPERAND_TYPE_OPTIONAL_COOPERATIVE_MATRIX_OPERANDS:
  646. case SPV_OPERAND_TYPE_COOPERATIVE_MATRIX_REDUCE:
  647. case SPV_OPERAND_TYPE_TENSOR_ADDRESSING_OPERANDS:
  648. case SPV_OPERAND_TYPE_MATRIX_MULTIPLY_ACCUMULATE_OPERANDS:
  649. case SPV_OPERAND_TYPE_OPTIONAL_MATRIX_MULTIPLY_ACCUMULATE_OPERANDS: {
  650. // This operand is a mask.
  651. // Map an optional operand type to its corresponding concrete type.
  652. if (type == SPV_OPERAND_TYPE_OPTIONAL_IMAGE)
  653. parsed_operand.type = SPV_OPERAND_TYPE_IMAGE;
  654. if (type == SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS)
  655. parsed_operand.type = SPV_OPERAND_TYPE_MEMORY_ACCESS;
  656. if (type == SPV_OPERAND_TYPE_OPTIONAL_COOPERATIVE_MATRIX_OPERANDS)
  657. parsed_operand.type = SPV_OPERAND_TYPE_COOPERATIVE_MATRIX_OPERANDS;
  658. if (type == SPV_OPERAND_TYPE_OPTIONAL_RAW_ACCESS_CHAIN_OPERANDS)
  659. parsed_operand.type = SPV_OPERAND_TYPE_RAW_ACCESS_CHAIN_OPERANDS;
  660. if (type == SPV_OPERAND_TYPE_OPTIONAL_MATRIX_MULTIPLY_ACCUMULATE_OPERANDS)
  661. parsed_operand.type =
  662. SPV_OPERAND_TYPE_MATRIX_MULTIPLY_ACCUMULATE_OPERANDS;
  663. if (type == SPV_OPERAND_TYPE_OPTIONAL_TENSOR_OPERANDS)
  664. parsed_operand.type = SPV_OPERAND_TYPE_TENSOR_OPERANDS;
  665. // Check validity of set mask bits. Also prepare for operands for those
  666. // masks if they have any. To get operand order correct, scan from
  667. // MSB to LSB since we can only prepend operands to a pattern.
  668. // The only case in the grammar where you have more than one mask bit
  669. // having an operand is for image operands. See SPIR-V 3.14 Image
  670. // Operands.
  671. uint32_t remaining_word = word;
  672. for (uint32_t mask = (1u << 31); remaining_word; mask >>= 1) {
  673. if (remaining_word & mask) {
  674. const spvtools::OperandDesc* entry = nullptr;
  675. if (spvtools::LookupOperand(type, mask, &entry)) {
  676. return diagnostic()
  677. << "Invalid " << spvOperandTypeStr(parsed_operand.type)
  678. << " operand: " << word << " has invalid mask component "
  679. << mask;
  680. }
  681. remaining_word ^= mask;
  682. spvPushOperandTypes(entry->operands(), expected_operands);
  683. }
  684. }
  685. if (word == 0) {
  686. // An all-zeroes mask *might* also be valid.
  687. const spvtools::OperandDesc* entry = nullptr;
  688. if (SPV_SUCCESS == spvtools::LookupOperand(type, 0, &entry)) {
  689. // Prepare for its operands, if any.
  690. spvPushOperandTypes(entry->operands(), expected_operands);
  691. }
  692. }
  693. } break;
  694. default:
  695. return diagnostic() << "Internal error: Unhandled operand type: " << type;
  696. }
  697. assert(spvOperandIsConcrete(parsed_operand.type));
  698. operands->push_back(parsed_operand);
  699. const size_t index_after_operand = _.word_index + parsed_operand.num_words;
  700. // Avoid buffer overrun for the cases where the operand has more than one
  701. // word, and where it isn't a string. (Those other cases have already been
  702. // handled earlier.) For example, this error can occur for a multi-word
  703. // argument to OpConstant, or a multi-word case literal operand for OpSwitch.
  704. if (_.num_words < index_after_operand)
  705. return exhaustedInputDiagnostic(inst_offset, opcode, type);
  706. if (_.requires_endian_conversion) {
  707. // Copy instruction words. Translate to native endianness as needed.
  708. if (convert_operand_endianness) {
  709. const spv_endianness_t endianness = _.endian;
  710. std::transform(_.words + _.word_index, _.words + index_after_operand,
  711. std::back_inserter(*words),
  712. [endianness](const uint32_t raw_word) {
  713. return spvFixWord(raw_word, endianness);
  714. });
  715. } else {
  716. words->insert(words->end(), _.words + _.word_index,
  717. _.words + index_after_operand);
  718. }
  719. }
  720. // Advance past the operand.
  721. _.word_index = index_after_operand;
  722. return SPV_SUCCESS;
  723. }
  724. spv_result_t Parser::setNumericTypeInfoForType(
  725. spv_parsed_operand_t* parsed_operand, uint32_t type_id) {
  726. assert(type_id != 0);
  727. auto type_info_iter = _.type_id_to_number_type_info.find(type_id);
  728. if (type_info_iter == _.type_id_to_number_type_info.end()) {
  729. return diagnostic() << "Type Id " << type_id << " is not a type";
  730. }
  731. const NumberType& info = type_info_iter->second;
  732. if (info.type == SPV_NUMBER_NONE) {
  733. // This is a valid type, but for something other than a scalar number.
  734. return diagnostic() << "Type Id " << type_id
  735. << " is not a scalar numeric type";
  736. }
  737. parsed_operand->number_kind = info.type;
  738. parsed_operand->number_bit_width = info.bit_width;
  739. // Round up the word count.
  740. parsed_operand->num_words = static_cast<uint16_t>((info.bit_width + 31) / 32);
  741. return SPV_SUCCESS;
  742. }
  743. void Parser::recordNumberType(size_t inst_offset,
  744. const spv_parsed_instruction_t* inst) {
  745. const spv::Op opcode = static_cast<spv::Op>(inst->opcode);
  746. if (spvOpcodeGeneratesType(opcode)) {
  747. NumberType info = {SPV_NUMBER_NONE, 0};
  748. if (spv::Op::OpTypeInt == opcode) {
  749. const bool is_signed = peekAt(inst_offset + 3) != 0;
  750. info.type = is_signed ? SPV_NUMBER_SIGNED_INT : SPV_NUMBER_UNSIGNED_INT;
  751. info.bit_width = peekAt(inst_offset + 2);
  752. } else if (spv::Op::OpTypeFloat == opcode) {
  753. info.type = SPV_NUMBER_FLOATING;
  754. info.bit_width = peekAt(inst_offset + 2);
  755. }
  756. // The *result* Id of a type generating instruction is the type Id.
  757. _.type_id_to_number_type_info[inst->result_id] = info;
  758. }
  759. }
  760. } // anonymous namespace
  761. spv_result_t spvBinaryParse(const spv_const_context context, void* user_data,
  762. const uint32_t* code, const size_t num_words,
  763. spv_parsed_header_fn_t parsed_header,
  764. spv_parsed_instruction_fn_t parsed_instruction,
  765. spv_diagnostic* diagnostic) {
  766. spv_context_t hijack_context = *context;
  767. if (diagnostic) {
  768. *diagnostic = nullptr;
  769. spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, diagnostic);
  770. }
  771. Parser parser(&hijack_context, user_data, parsed_header, parsed_instruction);
  772. return parser.parse(code, num_words, diagnostic);
  773. }
  774. // TODO(dneto): This probably belongs in text.cpp since that's the only place
  775. // that a spv_binary_t value is created.
  776. void spvBinaryDestroy(spv_binary binary) {
  777. if (binary) {
  778. if (binary->code) delete[] binary->code;
  779. delete binary;
  780. }
  781. }
  782. size_t spv_strnlen_s(const char* str, size_t strsz) {
  783. if (!str) return 0;
  784. for (size_t i = 0; i < strsz; i++) {
  785. if (!str[i]) return i;
  786. }
  787. return strsz;
  788. }