blob: f16bf52275d02fedecdb1375607d35fe0deb683d [file] [log] [blame]
Daniel Koch5a97e3a2020-03-17 15:30:19 -04001// Copyright (c) 2015-2020 The Khronos Group Inc.
2// Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights
3// reserved.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +01004//
David Neto9fc86582016-09-01 15:33:59 -04005// 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
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +01008//
David Neto9fc86582016-09-01 15:33:59 -04009// http://www.apache.org/licenses/LICENSE-2.0
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010010//
David Neto9fc86582016-09-01 15:33:59 -040011// 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.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010016
dan sinclaireda2cfb2018-08-03 15:06:09 -040017#include "source/binary.h"
David Netofcc7d582015-10-27 15:31:10 -040018
David Neto7bff3eb2015-11-20 14:21:10 -050019#include <algorithm>
David Netofcc7d582015-10-27 15:31:10 -040020#include <cassert>
21#include <cstring>
Andrew Woloszyn7ffd8ff2016-01-11 16:22:34 -050022#include <iterator>
David Neto0ca6b592015-10-30 16:06:15 -040023#include <limits>
dan sinclaireda2cfb2018-08-03 15:06:09 -040024#include <string>
David Netofcc7d582015-10-27 15:31:10 -040025#include <unordered_map>
Lei Zhangdc6e4832016-09-21 17:16:31 -040026#include <vector>
David Netofcc7d582015-10-27 15:31:10 -040027
dan sinclaireda2cfb2018-08-03 15:06:09 -040028#include "source/assembly_grammar.h"
29#include "source/diagnostic.h"
30#include "source/ext_inst.h"
31#include "source/latest_version_spirv_header.h"
32#include "source/opcode.h"
33#include "source/operand.h"
34#include "source/spirv_constant.h"
35#include "source/spirv_endian.h"
Andrew Woloszyn157e41b2015-10-16 15:11:00 -040036
Andrew Woloszyn55ecc2e2015-11-11 11:05:07 -050037spv_result_t spvBinaryHeaderGet(const spv_const_binary binary,
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010038 const spv_endianness_t endian,
Lei Zhang1a0334e2015-11-02 09:41:20 -050039 spv_header_t* pHeader) {
David Neto0ca6b592015-10-30 16:06:15 -040040 if (!binary->code) return SPV_ERROR_INVALID_BINARY;
41 if (binary->wordCount < SPV_INDEX_INSTRUCTION)
42 return SPV_ERROR_INVALID_BINARY;
Lei Zhang40056702015-09-11 14:31:27 -040043 if (!pHeader) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010044
45 // TODO: Validation checking?
46 pHeader->magic = spvFixWord(binary->code[SPV_INDEX_MAGIC_NUMBER], endian);
47 pHeader->version = spvFixWord(binary->code[SPV_INDEX_VERSION_NUMBER], endian);
48 pHeader->generator =
49 spvFixWord(binary->code[SPV_INDEX_GENERATOR_NUMBER], endian);
50 pHeader->bound = spvFixWord(binary->code[SPV_INDEX_BOUND], endian);
51 pHeader->schema = spvFixWord(binary->code[SPV_INDEX_SCHEMA], endian);
52 pHeader->instructions = &binary->code[SPV_INDEX_INSTRUCTION];
53
54 return SPV_SUCCESS;
55}
56
David Neto0ca6b592015-10-30 16:06:15 -040057namespace {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010058
David Neto0ca6b592015-10-30 16:06:15 -040059// A SPIR-V binary parser. A parser instance communicates detailed parse
60// results via callbacks.
61class Parser {
62 public:
63 // The user_data value is provided to the callbacks as context.
Lei Zhang972788b2015-11-12 13:48:30 -050064 Parser(const spv_const_context context, void* user_data,
65 spv_parsed_header_fn_t parsed_header_fn,
David Neto0ca6b592015-10-30 16:06:15 -040066 spv_parsed_instruction_fn_t parsed_instruction_fn)
Lei Zhang972788b2015-11-12 13:48:30 -050067 : grammar_(context),
Lei Zhang755f97f2016-09-02 18:06:18 -040068 consumer_(context->consumer),
Lei Zhang972788b2015-11-12 13:48:30 -050069 user_data_(user_data),
David Neto0ca6b592015-10-30 16:06:15 -040070 parsed_header_fn_(parsed_header_fn),
71 parsed_instruction_fn_(parsed_instruction_fn) {}
72
73 // Parses the specified binary SPIR-V module, issuing callbacks on a parsed
74 // header and for each parsed instruction. Returns SPV_SUCCESS on success.
75 // Otherwise returns an error code and issues a diagnostic.
76 spv_result_t parse(const uint32_t* words, size_t num_words,
77 spv_diagnostic* diagnostic);
78
79 private:
80 // All remaining methods work on the current module parse state.
81
82 // Like the parse method, but works on the current module parse state.
83 spv_result_t parseModule();
84
85 // Parses an instruction at the current position of the binary. Assumes
86 // the header has been parsed, the endian has been set, and the word index is
87 // still in range. Advances the parsing position past the instruction, and
88 // updates other parsing state for the current module.
89 // On success, returns SPV_SUCCESS and issues the parsed-instruction callback.
90 // On failure, returns an error code and issues a diagnostic.
91 spv_result_t parseInstruction();
92
David Neto7bff3eb2015-11-20 14:21:10 -050093 // Parses an instruction operand with the given type, for an instruction
94 // starting at inst_offset words into the SPIR-V binary.
95 // If the SPIR-V binary is the same endianness as the host, then the
96 // endian_converted_inst_words parameter is ignored. Otherwise, this method
97 // appends the words for this operand, converted to host native endianness,
98 // to the end of endian_converted_inst_words. This method also updates the
99 // expected_operands parameter, and the scalar members of the inst parameter.
100 // On success, returns SPV_SUCCESS, advances past the operand, and pushes a
101 // new entry on to the operands vector. Otherwise returns an error code and
102 // issues a diagnostic.
103 spv_result_t parseOperand(size_t inst_offset, spv_parsed_instruction_t* inst,
David Neto0ca6b592015-10-30 16:06:15 -0400104 const spv_operand_type_t type,
David Neto7bff3eb2015-11-20 14:21:10 -0500105 std::vector<uint32_t>* endian_converted_inst_words,
David Neto0ca6b592015-10-30 16:06:15 -0400106 std::vector<spv_parsed_operand_t>* operands,
107 spv_operand_pattern_t* expected_operands);
108
109 // Records the numeric type for an operand according to the type information
110 // associated with the given non-zero type Id. This can fail if the type Id
111 // is not a type Id, or if the type Id does not reference a scalar numeric
112 // type. On success, return SPV_SUCCESS and populates the num_words,
113 // number_kind, and number_bit_width fields of parsed_operand.
114 spv_result_t setNumericTypeInfoForType(spv_parsed_operand_t* parsed_operand,
115 uint32_t type_id);
116
David Neto7bff3eb2015-11-20 14:21:10 -0500117 // Records the number type for an instruction at the given offset, if that
118 // instruction generates a type. For types that aren't scalar numbers,
119 // record something with number kind SPV_NUMBER_NONE.
120 void recordNumberType(size_t inst_offset,
121 const spv_parsed_instruction_t* inst);
David Neto0ca6b592015-10-30 16:06:15 -0400122
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.
dan sinclair3dad1cd2018-07-07 09:38:00 -0400127 spvtools::DiagnosticStream diagnostic(spv_result_t error) {
dan sinclair167f1272018-12-21 16:24:15 -0500128 return spvtools::DiagnosticStream({0, 0, _.instruction_count}, consumer_,
129 "", error);
David Neto0ca6b592015-10-30 16:06:15 -0400130 }
131
132 // Returns a diagnostic stream object with the default parse error code.
dan sinclair3dad1cd2018-07-07 09:38:00 -0400133 spvtools::DiagnosticStream diagnostic() {
David Neto0ca6b592015-10-30 16:06:15 -0400134 // The default failure for parsing is invalid binary.
135 return diagnostic(SPV_ERROR_INVALID_BINARY);
136 }
137
David Netod9ad0502015-11-24 18:37:24 -0500138 // Issues a diagnostic describing an exhaustion of input condition when
139 // trying to decode an instruction operand, and returns
140 // SPV_ERROR_INVALID_BINARY.
141 spv_result_t exhaustedInputDiagnostic(size_t inst_offset, SpvOp opcode,
142 spv_operand_type_t type) {
143 return diagnostic() << "End of input reached while decoding Op"
144 << spvOpcodeString(opcode) << " starting at word "
145 << inst_offset
146 << ((_.word_index < _.num_words) ? ": truncated "
147 : ": missing ")
148 << spvOperandTypeStr(type) << " operand at word offset "
149 << _.word_index - inst_offset << ".";
150 }
151
David Neto0ca6b592015-10-30 16:06:15 -0400152 // Returns the endian-corrected word at the current position.
153 uint32_t peek() const { return peekAt(_.word_index); }
154
155 // Returns the endian-corrected word at the given position.
156 uint32_t peekAt(size_t index) const {
157 assert(index < _.num_words);
158 return spvFixWord(_.words[index], _.endian);
159 }
160
161 // Data members
162
dan sinclair3dad1cd2018-07-07 09:38:00 -0400163 const spvtools::AssemblyGrammar grammar_; // SPIR-V syntax utility.
Lei Zhang755f97f2016-09-02 18:06:18 -0400164 const spvtools::MessageConsumer& consumer_; // Message consumer callback.
David Neto0ca6b592015-10-30 16:06:15 -0400165 void* const user_data_; // Context for the callbacks
166 const spv_parsed_header_fn_t parsed_header_fn_; // Parsed header callback
167 const spv_parsed_instruction_fn_t
168 parsed_instruction_fn_; // Parsed instruction callback
169
170 // Describes the format of a typed literal number.
171 struct NumberType {
172 spv_number_kind_t type;
173 uint32_t bit_width;
174 };
175
176 // The state used to parse a single SPIR-V binary module.
177 struct State {
178 State(const uint32_t* words_arg, size_t num_words_arg,
179 spv_diagnostic* diagnostic_arg)
180 : words(words_arg),
181 num_words(num_words_arg),
182 diagnostic(diagnostic_arg),
183 word_index(0),
dan sinclair167f1272018-12-21 16:24:15 -0500184 instruction_count(0),
Lei Zhang712bed02016-02-25 16:11:16 -0500185 endian(),
Chris Forbes78338d52017-06-27 16:28:22 -0700186 requires_endian_conversion(false) {
Diego Novillod2938e42017-11-08 12:40:02 -0500187 // Temporary storage for parser state within a single instruction.
188 // Most instructions require fewer than 25 words or operands.
189 operands.reserve(25);
190 endian_converted_words.reserve(25);
191 expected_operands.reserve(25);
Chris Forbes78338d52017-06-27 16:28:22 -0700192 }
David Neto0ca6b592015-10-30 16:06:15 -0400193 State() : State(0, 0, nullptr) {}
194 const uint32_t* words; // Words in the binary SPIR-V module.
195 size_t num_words; // Number of words in the module.
196 spv_diagnostic* diagnostic; // Where diagnostics go.
197 size_t word_index; // The current position in words.
dan sinclair167f1272018-12-21 16:24:15 -0500198 size_t instruction_count; // The count of processed instructions
David Neto0ca6b592015-10-30 16:06:15 -0400199 spv_endianness_t endian; // The endianness of the binary.
David Neto7bff3eb2015-11-20 14:21:10 -0500200 // Is the SPIR-V binary in a different endiannes from the host native
201 // endianness?
202 bool requires_endian_conversion;
David Neto0ca6b592015-10-30 16:06:15 -0400203
204 // Maps a result ID to its type ID. By convention:
205 // - a result ID that is a type definition maps to itself.
206 // - a result ID without a type maps to 0. (E.g. for OpLabel)
207 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
208 // Maps a type ID to its number type description.
209 std::unordered_map<uint32_t, NumberType> type_id_to_number_type_info;
210 // Maps an ExtInstImport id to the extended instruction type.
211 std::unordered_map<uint32_t, spv_ext_inst_type_t>
212 import_id_to_ext_inst_type;
Chris Forbesfcd991f2017-06-27 11:00:06 -0700213
214 // Used by parseOperand
215 std::vector<spv_parsed_operand_t> operands;
216 std::vector<uint32_t> endian_converted_words;
Chris Forbes78338d52017-06-27 16:28:22 -0700217 spv_operand_pattern_t expected_operands;
David Neto0ca6b592015-10-30 16:06:15 -0400218 } _;
219};
220
221spv_result_t Parser::parse(const uint32_t* words, size_t num_words,
222 spv_diagnostic* diagnostic_arg) {
223 _ = State(words, num_words, diagnostic_arg);
224
225 const spv_result_t result = parseModule();
226
227 // Clear the module state. The tables might be big.
228 _ = State();
229
230 return result;
231}
232
233spv_result_t Parser::parseModule() {
234 if (!_.words) return diagnostic() << "Missing module.";
235
236 if (_.num_words < SPV_INDEX_INSTRUCTION)
237 return diagnostic() << "Module has incomplete header: only " << _.num_words
238 << " words instead of " << SPV_INDEX_INSTRUCTION;
239
240 // Check the magic number and detect the module's endianness.
Andrew Woloszyn55ecc2e2015-11-11 11:05:07 -0500241 spv_const_binary_t binary{_.words, _.num_words};
David Neto0ca6b592015-10-30 16:06:15 -0400242 if (spvBinaryEndianness(&binary, &_.endian)) {
243 return diagnostic() << "Invalid SPIR-V magic number '" << std::hex
244 << _.words[0] << "'.";
245 }
David Neto7bff3eb2015-11-20 14:21:10 -0500246 _.requires_endian_conversion = !spvIsHostEndian(_.endian);
David Neto0ca6b592015-10-30 16:06:15 -0400247
248 // Process the header.
249 spv_header_t header;
250 if (spvBinaryHeaderGet(&binary, _.endian, &header)) {
251 // It turns out there is no way to trigger this error since the only
252 // failure cases are already handled above, with better messages.
253 return diagnostic(SPV_ERROR_INTERNAL)
254 << "Internal error: unhandled header parse failure";
255 }
256 if (parsed_header_fn_) {
257 if (auto error = parsed_header_fn_(user_data_, _.endian, header.magic,
258 header.version, header.generator,
259 header.bound, header.schema)) {
260 return error;
261 }
262 }
263
264 // Process the instructions.
265 _.word_index = SPV_INDEX_INSTRUCTION;
266 while (_.word_index < _.num_words)
267 if (auto error = parseInstruction()) return error;
268
269 // Running off the end should already have been reported earlier.
270 assert(_.word_index == _.num_words);
271
272 return SPV_SUCCESS;
273}
274
275spv_result_t Parser::parseInstruction() {
dan sinclair167f1272018-12-21 16:24:15 -0500276 _.instruction_count++;
277
David Neto0ca6b592015-10-30 16:06:15 -0400278 // The zero values for all members except for opcode are the
279 // correct initial values.
280 spv_parsed_instruction_t inst = {};
David Neto7bff3eb2015-11-20 14:21:10 -0500281
282 const uint32_t first_word = peek();
283
David Neto7bff3eb2015-11-20 14:21:10 -0500284 // If the module's endianness is different from the host native endianness,
285 // then converted_words contains the the endian-translated words in the
286 // instruction.
Chris Forbesfcd991f2017-06-27 11:00:06 -0700287 _.endian_converted_words.clear();
288 _.endian_converted_words.push_back(first_word);
David Neto0ca6b592015-10-30 16:06:15 -0400289
290 // After a successful parse of the instruction, the inst.operands member
291 // will point to this vector's storage.
Chris Forbesfcd991f2017-06-27 11:00:06 -0700292 _.operands.clear();
David Neto0ca6b592015-10-30 16:06:15 -0400293
294 assert(_.word_index < _.num_words);
295 // Decompose and check the first word.
296 uint16_t inst_word_count = 0;
David Neto7bff3eb2015-11-20 14:21:10 -0500297 spvOpcodeSplit(first_word, &inst_word_count, &inst.opcode);
David Neto0ca6b592015-10-30 16:06:15 -0400298 if (inst_word_count < 1) {
299 return diagnostic() << "Invalid instruction word count: "
300 << inst_word_count;
301 }
302 spv_opcode_desc opcode_desc;
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400303 if (grammar_.lookupOpcode(static_cast<SpvOp>(inst.opcode), &opcode_desc))
304 return diagnostic() << "Invalid opcode: " << inst.opcode;
David Neto0ca6b592015-10-30 16:06:15 -0400305
David Neto7bff3eb2015-11-20 14:21:10 -0500306 // Advance past the opcode word. But remember the of the start
307 // of the instruction.
308 const size_t inst_offset = _.word_index;
David Neto0ca6b592015-10-30 16:06:15 -0400309 _.word_index++;
310
311 // Maintains the ordered list of expected operand types.
312 // For many instructions we only need the {numTypes, operandTypes}
313 // entries in opcode_desc. However, sometimes we need to modify
314 // the list as we parse the operands. This occurs when an operand
315 // has its own logical operands (such as the LocalSize operand for
316 // ExecutionMode), or for extended instructions that may have their
317 // own operands depending on the selected extended instruction.
Chris Forbes78338d52017-06-27 16:28:22 -0700318 _.expected_operands.clear();
319 for (auto i = 0; i < opcode_desc->numTypes; i++)
Diego Novillod2938e42017-11-08 12:40:02 -0500320 _.expected_operands.push_back(
321 opcode_desc->operandTypes[opcode_desc->numTypes - i - 1]);
David Neto0ca6b592015-10-30 16:06:15 -0400322
David Neto7bff3eb2015-11-20 14:21:10 -0500323 while (_.word_index < inst_offset + inst_word_count) {
324 const uint16_t inst_word_index = uint16_t(_.word_index - inst_offset);
Chris Forbes78338d52017-06-27 16:28:22 -0700325 if (_.expected_operands.empty()) {
David Neto0ca6b592015-10-30 16:06:15 -0400326 return diagnostic() << "Invalid instruction Op" << opcode_desc->name
David Neto7bff3eb2015-11-20 14:21:10 -0500327 << " starting at word " << inst_offset
David Neto0ca6b592015-10-30 16:06:15 -0400328 << ": expected no more operands after "
329 << inst_word_index
330 << " words, but stated word count is "
331 << inst_word_count << ".";
332 }
333
Diego Novillod2938e42017-11-08 12:40:02 -0500334 spv_operand_type_t type =
335 spvTakeFirstMatchableOperand(&_.expected_operands);
David Neto0ca6b592015-10-30 16:06:15 -0400336
David Neto7bff3eb2015-11-20 14:21:10 -0500337 if (auto error =
Chris Forbesfcd991f2017-06-27 11:00:06 -0700338 parseOperand(inst_offset, &inst, type, &_.endian_converted_words,
Chris Forbes78338d52017-06-27 16:28:22 -0700339 &_.operands, &_.expected_operands)) {
David Neto0ca6b592015-10-30 16:06:15 -0400340 return error;
David Netod9ad0502015-11-24 18:37:24 -0500341 }
David Neto0ca6b592015-10-30 16:06:15 -0400342 }
343
Chris Forbes78338d52017-06-27 16:28:22 -0700344 if (!_.expected_operands.empty() &&
345 !spvOperandIsOptional(_.expected_operands.back())) {
David Neto0ca6b592015-10-30 16:06:15 -0400346 return diagnostic() << "End of input reached while decoding Op"
347 << opcode_desc->name << " starting at word "
David Neto7bff3eb2015-11-20 14:21:10 -0500348 << inst_offset << ": expected more operands after "
David Neto0ca6b592015-10-30 16:06:15 -0400349 << inst_word_count << " words.";
350 }
351
David Neto7bff3eb2015-11-20 14:21:10 -0500352 if ((inst_offset + inst_word_count) != _.word_index) {
David Netod9ad0502015-11-24 18:37:24 -0500353 return diagnostic() << "Invalid word count: Op" << opcode_desc->name
354 << " starting at word " << inst_offset
355 << " says it has " << inst_word_count
David Neto7bff3eb2015-11-20 14:21:10 -0500356 << " words, but found " << _.word_index - inst_offset
David Neto0ca6b592015-10-30 16:06:15 -0400357 << " words instead.";
358 }
David Neto15afbf92015-11-23 14:17:35 -0500359
360 // Check the computed length of the endian-converted words vector against
361 // the declared number of words in the instruction. If endian conversion
362 // is required, then they should match. If no endian conversion was
363 // performed, then the vector only contains the initial opcode/word-count
364 // word.
365 assert(!_.requires_endian_conversion ||
Chris Forbesfcd991f2017-06-27 11:00:06 -0700366 (inst_word_count == _.endian_converted_words.size()));
Diego Novillod2938e42017-11-08 12:40:02 -0500367 assert(_.requires_endian_conversion ||
368 (_.endian_converted_words.size() == 1));
David Neto0ca6b592015-10-30 16:06:15 -0400369
David Neto7bff3eb2015-11-20 14:21:10 -0500370 recordNumberType(inst_offset, &inst);
David Neto0ca6b592015-10-30 16:06:15 -0400371
David Neto7bff3eb2015-11-20 14:21:10 -0500372 if (_.requires_endian_conversion) {
373 // We must wait until here to set this pointer, because the vector might
374 // have been be resized while we accumulated its elements.
Chris Forbesfcd991f2017-06-27 11:00:06 -0700375 inst.words = _.endian_converted_words.data();
David Neto7bff3eb2015-11-20 14:21:10 -0500376 } else {
377 // If no conversion is required, then just point to the underlying binary.
378 // This saves time and space.
379 inst.words = _.words + inst_offset;
380 }
381 inst.num_words = inst_word_count;
382
383 // We must wait until here to set this pointer, because the vector might
384 // have been be resized while we accumulated its elements.
Chris Forbesfcd991f2017-06-27 11:00:06 -0700385 inst.operands = _.operands.data();
386 inst.num_operands = uint16_t(_.operands.size());
David Neto0ca6b592015-10-30 16:06:15 -0400387
388 // Issue the callback. The callee should know that all the storage in inst
389 // is transient, and will disappear immediately afterward.
390 if (parsed_instruction_fn_) {
391 if (auto error = parsed_instruction_fn_(user_data_, &inst)) return error;
392 }
393
394 return SPV_SUCCESS;
395}
396
David Neto7bff3eb2015-11-20 14:21:10 -0500397spv_result_t Parser::parseOperand(size_t inst_offset,
398 spv_parsed_instruction_t* inst,
David Neto0ca6b592015-10-30 16:06:15 -0400399 const spv_operand_type_t type,
David Neto7bff3eb2015-11-20 14:21:10 -0500400 std::vector<uint32_t>* words,
David Neto0ca6b592015-10-30 16:06:15 -0400401 std::vector<spv_parsed_operand_t>* operands,
402 spv_operand_pattern_t* expected_operands) {
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400403 const SpvOp opcode = static_cast<SpvOp>(inst->opcode);
David Neto0ca6b592015-10-30 16:06:15 -0400404 // We'll fill in this result as we go along.
405 spv_parsed_operand_t parsed_operand;
David Neto7bff3eb2015-11-20 14:21:10 -0500406 parsed_operand.offset = uint16_t(_.word_index - inst_offset);
David Neto0ca6b592015-10-30 16:06:15 -0400407 // Most operands occupy one word. This might be be adjusted later.
408 parsed_operand.num_words = 1;
409 // The type argument is the one used by the grammar to parse the instruction.
410 // But it can exposes internal parser details such as whether an operand is
411 // optional or actually represents a variable-length sequence of operands.
412 // The resulting type should be adjusted to avoid those internal details.
413 // In most cases, the resulting operand type is the same as the grammar type.
414 parsed_operand.type = type;
415
416 // Assume non-numeric values. This will be updated for literal numbers.
417 parsed_operand.number_kind = SPV_NUMBER_NONE;
418 parsed_operand.number_bit_width = 0;
419
David Netod9ad0502015-11-24 18:37:24 -0500420 if (_.word_index >= _.num_words)
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400421 return exhaustedInputDiagnostic(inst_offset, opcode, type);
David Netod9ad0502015-11-24 18:37:24 -0500422
David Neto0ca6b592015-10-30 16:06:15 -0400423 const uint32_t word = peek();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100424
David Neto7bff3eb2015-11-20 14:21:10 -0500425 // Do the words in this operand have to be converted to native endianness?
426 // True for all but literal strings.
427 bool convert_operand_endianness = true;
428
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100429 switch (type) {
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400430 case SPV_OPERAND_TYPE_TYPE_ID:
David Neto677e0c72016-01-05 14:56:02 -0500431 if (!word)
432 return diagnostic(SPV_ERROR_INVALID_ID) << "Error: Type Id is 0";
David Neto0ca6b592015-10-30 16:06:15 -0400433 inst->type_id = word;
434 break;
435
436 case SPV_OPERAND_TYPE_RESULT_ID:
David Neto677e0c72016-01-05 14:56:02 -0500437 if (!word)
438 return diagnostic(SPV_ERROR_INVALID_ID) << "Error: Result Id is 0";
David Neto0ca6b592015-10-30 16:06:15 -0400439 inst->result_id = word;
440 // Save the result ID to type ID mapping.
441 // In the grammar, type ID always appears before result ID.
442 if (_.id_to_type_id.find(inst->result_id) != _.id_to_type_id.end())
Diego Novillod2938e42017-11-08 12:40:02 -0500443 return diagnostic(SPV_ERROR_INVALID_ID)
444 << "Id " << inst->result_id << " is defined more than once";
David Neto0ca6b592015-10-30 16:06:15 -0400445 // Record it.
446 // A regular value maps to its type. Some instructions (e.g. OpLabel)
447 // have no type Id, and will map to 0. The result Id for a
448 // type-generating instruction (e.g. OpTypeInt) maps to itself.
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400449 _.id_to_type_id[inst->result_id] =
450 spvOpcodeGeneratesType(opcode) ? inst->result_id : inst->type_id;
David Neto0ca6b592015-10-30 16:06:15 -0400451 break;
452
453 case SPV_OPERAND_TYPE_ID:
David Neto78c3b432015-08-27 13:03:52 -0400454 case SPV_OPERAND_TYPE_OPTIONAL_ID:
Umar Arshadf76e0f52015-11-18 15:43:43 -0500455 if (!word) return diagnostic(SPV_ERROR_INVALID_ID) << "Id is 0";
David Neto0ca6b592015-10-30 16:06:15 -0400456 parsed_operand.type = SPV_OPERAND_TYPE_ID;
457
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400458 if (opcode == SpvOpExtInst && parsed_operand.offset == 3) {
David Neto0ca6b592015-10-30 16:06:15 -0400459 // The current word is the extended instruction set Id.
460 // Set the extended instruction set type for the current instruction.
461 auto ext_inst_type_iter = _.import_id_to_ext_inst_type.find(word);
462 if (ext_inst_type_iter == _.import_id_to_ext_inst_type.end()) {
Umar Arshadf76e0f52015-11-18 15:43:43 -0500463 return diagnostic(SPV_ERROR_INVALID_ID)
David Neto0ca6b592015-10-30 16:06:15 -0400464 << "OpExtInst set Id " << word
465 << " does not reference an OpExtInstImport result Id";
466 }
467 inst->ext_inst_type = ext_inst_type_iter->second;
468 }
469 break;
470
David Neto64a9be92015-11-18 15:48:32 -0500471 case SPV_OPERAND_TYPE_SCOPE_ID:
472 case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
David Netod9ad0502015-11-24 18:37:24 -0500473 // Check for trivially invalid values. The operand descriptions already
474 // have the word "ID" in them.
475 if (!word) return diagnostic() << spvOperandTypeStr(type) << " is 0";
David Neto0ca6b592015-10-30 16:06:15 -0400476 break;
477
David Neto445ce442015-10-15 15:22:06 -0400478 case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400479 assert(SpvOpExtInst == opcode);
David Neto0ca6b592015-10-30 16:06:15 -0400480 assert(inst->ext_inst_type != SPV_EXT_INST_TYPE_NONE);
481 spv_ext_inst_desc ext_inst;
David Netoe70b0092019-12-18 18:10:29 -0500482 if (grammar_.lookupExtInst(inst->ext_inst_type, word, &ext_inst) ==
483 SPV_SUCCESS) {
484 // if we know about this ext inst, push the expected operands
485 spvPushOperandTypes(ext_inst->operandTypes, expected_operands);
486 } else {
487 // if we don't know this extended instruction and the set isn't
488 // non-semantic, we cannot process further
489 if (!spvExtInstIsNonSemantic(inst->ext_inst_type)) {
490 return diagnostic()
491 << "Invalid extended instruction number: " << word;
492 } else {
493 // for non-semantic instruction sets, we know the form of all such
494 // extended instructions contains a series of IDs as parameters
495 expected_operands->push_back(SPV_OPERAND_TYPE_VARIABLE_ID);
496 }
497 }
David Neto445ce442015-10-15 15:22:06 -0400498 } break;
David Neto0ca6b592015-10-30 16:06:15 -0400499
David Neto21196942015-11-11 02:45:45 -0500500 case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: {
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400501 assert(SpvOpSpecConstantOp == opcode);
David Neto21196942015-11-11 02:45:45 -0500502 if (grammar_.lookupSpecConstantOpcode(SpvOp(word))) {
Diego Novillod2938e42017-11-08 12:40:02 -0500503 return diagnostic()
504 << "Invalid " << spvOperandTypeStr(type) << ": " << word;
David Neto21196942015-11-11 02:45:45 -0500505 }
506 spv_opcode_desc opcode_entry = nullptr;
507 if (grammar_.lookupOpcode(SpvOp(word), &opcode_entry)) {
508 return diagnostic(SPV_ERROR_INTERNAL)
509 << "OpSpecConstant opcode table out of sync";
510 }
511 // OpSpecConstant opcodes must have a type and result. We've already
512 // processed them, so skip them when preparing to parse the other
513 // operants for the opcode.
514 assert(opcode_entry->hasType);
515 assert(opcode_entry->hasResult);
516 assert(opcode_entry->numTypes >= 2);
Chris Forbes78338d52017-06-27 16:28:22 -0700517 spvPushOperandTypes(opcode_entry->operandTypes + 2, expected_operands);
David Neto21196942015-11-11 02:45:45 -0500518 } break;
519
David Neto445ce442015-10-15 15:22:06 -0400520 case SPV_OPERAND_TYPE_LITERAL_INTEGER:
Lei Zhang6483bd72015-10-14 17:02:39 -0400521 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER:
David Neto201caf72015-11-04 17:38:17 -0500522 // These are regular single-word literal integer operands.
523 // Post-parsing validation should check the range of the parsed value.
David Neto0ca6b592015-10-30 16:06:15 -0400524 parsed_operand.type = SPV_OPERAND_TYPE_LITERAL_INTEGER;
David Neto201caf72015-11-04 17:38:17 -0500525 // It turns out they are always unsigned integers!
526 parsed_operand.number_kind = SPV_NUMBER_UNSIGNED_INT;
527 parsed_operand.number_bit_width = 32;
528 break;
529
530 case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER:
531 case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER:
Lei Zhangaa3cd5a2015-11-10 14:29:35 -0500532 parsed_operand.type = SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER;
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400533 if (opcode == SpvOpSwitch) {
David Neto0ca6b592015-10-30 16:06:15 -0400534 // The literal operands have the same type as the value
535 // referenced by the selector Id.
David Neto7bff3eb2015-11-20 14:21:10 -0500536 const uint32_t selector_id = peekAt(inst_offset + 1);
David Neto3664bd52015-12-23 13:21:43 -0500537 const auto type_id_iter = _.id_to_type_id.find(selector_id);
538 if (type_id_iter == _.id_to_type_id.end() ||
539 type_id_iter->second == 0) {
David Neto0ca6b592015-10-30 16:06:15 -0400540 return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
541 << " has no type";
542 }
543 uint32_t type_id = type_id_iter->second;
544
545 if (selector_id == type_id) {
546 // Recall that by convention, a result ID that is a type definition
547 // maps to itself.
548 return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
549 << " is a type, not a value";
550 }
551 if (auto error = setNumericTypeInfoForType(&parsed_operand, type_id))
552 return error;
553 if (parsed_operand.number_kind != SPV_NUMBER_UNSIGNED_INT &&
554 parsed_operand.number_kind != SPV_NUMBER_SIGNED_INT) {
555 return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
556 << " is not a scalar integer";
557 }
Lei Zhangb41d1502015-09-14 15:22:23 -0400558 } else {
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400559 assert(opcode == SpvOpConstant || opcode == SpvOpSpecConstant);
David Neto201caf72015-11-04 17:38:17 -0500560 // The literal number type is determined by the type Id for the
561 // constant.
562 assert(inst->type_id);
563 if (auto error =
564 setNumericTypeInfoForType(&parsed_operand, inst->type_id))
565 return error;
Lei Zhangb41d1502015-09-14 15:22:23 -0400566 }
David Neto0ca6b592015-10-30 16:06:15 -0400567 break;
568
David Neto78c3b432015-08-27 13:03:52 -0400569 case SPV_OPERAND_TYPE_LITERAL_STRING:
570 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
David Neto7bff3eb2015-11-20 14:21:10 -0500571 convert_operand_endianness = false;
David Neto0ca6b592015-10-30 16:06:15 -0400572 const char* string =
573 reinterpret_cast<const char*>(_.words + _.word_index);
David Netod9ad0502015-11-24 18:37:24 -0500574 // Compute the length of the string, but make sure we don't run off the
575 // end of the input.
576 const size_t remaining_input_bytes =
577 sizeof(uint32_t) * (_.num_words - _.word_index);
578 const size_t string_num_content_bytes =
David Neto37422e92016-12-19 13:26:42 -0500579 spv_strnlen_s(string, remaining_input_bytes);
David Netod9ad0502015-11-24 18:37:24 -0500580 // If there was no terminating null byte, then that's an end-of-input
581 // error.
582 if (string_num_content_bytes == remaining_input_bytes)
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400583 return exhaustedInputDiagnostic(inst_offset, opcode, type);
David Netod9ad0502015-11-24 18:37:24 -0500584 // Account for null in the word length, so add 1 for null, then add 3 to
585 // make sure we round up. The following is equivalent to:
586 // (string_num_content_bytes + 1 + 3) / 4
587 const size_t string_num_words = string_num_content_bytes / 4 + 1;
David Neto0ca6b592015-10-30 16:06:15 -0400588 // Make sure we can record the word count without overflow.
David Netod9ad0502015-11-24 18:37:24 -0500589 //
590 // This error can't currently be triggered because of validity
591 // checks elsewhere.
David Neto0ca6b592015-10-30 16:06:15 -0400592 if (string_num_words > std::numeric_limits<uint16_t>::max()) {
593 return diagnostic() << "Literal string is longer than "
594 << std::numeric_limits<uint16_t>::max()
595 << " words: " << string_num_words << " words long";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100596 }
Andrew Woloszyn3a4bc7e2015-11-19 09:22:53 -0500597 parsed_operand.num_words = uint16_t(string_num_words);
David Neto0ca6b592015-10-30 16:06:15 -0400598 parsed_operand.type = SPV_OPERAND_TYPE_LITERAL_STRING;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100599
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400600 if (SpvOpExtInstImport == opcode) {
David Neto0ca6b592015-10-30 16:06:15 -0400601 // Record the extended instruction type for the ID for this import.
602 // There is only one string literal argument to OpExtInstImport,
603 // so it's sufficient to guard this just on the opcode.
604 const spv_ext_inst_type_t ext_inst_type =
605 spvExtInstImportTypeGet(string);
606 if (SPV_EXT_INST_TYPE_NONE == ext_inst_type) {
Diego Novillod2938e42017-11-08 12:40:02 -0500607 return diagnostic()
608 << "Invalid extended instruction import '" << string << "'";
Andrew Woloszyne59e6b72015-10-14 14:18:43 -0400609 }
David Neto0ca6b592015-10-30 16:06:15 -0400610 // We must have parsed a valid result ID. It's a condition
611 // of the grammar, and we only accept non-zero result Ids.
612 assert(inst->result_id);
613 _.import_id_to_ext_inst_type[inst->result_id] = ext_inst_type;
Andrew Woloszyne59e6b72015-10-14 14:18:43 -0400614 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100615 } break;
David Neto0ca6b592015-10-30 16:06:15 -0400616
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100617 case SPV_OPERAND_TYPE_CAPABILITY:
618 case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
619 case SPV_OPERAND_TYPE_EXECUTION_MODEL:
620 case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
621 case SPV_OPERAND_TYPE_MEMORY_MODEL:
622 case SPV_OPERAND_TYPE_EXECUTION_MODE:
623 case SPV_OPERAND_TYPE_STORAGE_CLASS:
624 case SPV_OPERAND_TYPE_DIMENSIONALITY:
625 case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
626 case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
David Netod9ad0502015-11-24 18:37:24 -0500627 case SPV_OPERAND_TYPE_SAMPLER_IMAGE_FORMAT:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100628 case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
629 case SPV_OPERAND_TYPE_LINKAGE_TYPE:
630 case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
David Neto2889a0c2016-02-15 13:50:00 -0500631 case SPV_OPERAND_TYPE_OPTIONAL_ACCESS_QUALIFIER:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100632 case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
633 case SPV_OPERAND_TYPE_DECORATION:
634 case SPV_OPERAND_TYPE_BUILT_IN:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100635 case SPV_OPERAND_TYPE_GROUP_OPERATION:
636 case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
David Neto59de6102017-12-03 12:30:08 -0500637 case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO:
Daniel Koch5a97e3a2020-03-17 15:30:19 -0400638 case SPV_OPERAND_TYPE_RAY_FLAGS:
639 case SPV_OPERAND_TYPE_RAY_QUERY_INTERSECTION:
640 case SPV_OPERAND_TYPE_RAY_QUERY_COMMITTED_INTERSECTION_TYPE:
641 case SPV_OPERAND_TYPE_RAY_QUERY_CANDIDATE_INTERSECTION_TYPE:
David Neto59de6102017-12-03 12:30:08 -0500642 case SPV_OPERAND_TYPE_DEBUG_BASE_TYPE_ATTRIBUTE_ENCODING:
643 case SPV_OPERAND_TYPE_DEBUG_COMPOSITE_TYPE:
644 case SPV_OPERAND_TYPE_DEBUG_TYPE_QUALIFIER:
David Neto64f36ea2019-12-19 17:16:26 -0500645 case SPV_OPERAND_TYPE_DEBUG_OPERATION:
646 case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_BASE_TYPE_ATTRIBUTE_ENCODING:
647 case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_COMPOSITE_TYPE:
648 case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_TYPE_QUALIFIER:
649 case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_OPERATION:
650 case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_IMPORTED_ENTITY: {
David Neto0ca6b592015-10-30 16:06:15 -0400651 // A single word that is a plain enum value.
David Neto2889a0c2016-02-15 13:50:00 -0500652
653 // Map an optional operand type to its corresponding concrete type.
654 if (type == SPV_OPERAND_TYPE_OPTIONAL_ACCESS_QUALIFIER)
655 parsed_operand.type = SPV_OPERAND_TYPE_ACCESS_QUALIFIER;
656
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100657 spv_operand_desc entry;
David Neto0ca6b592015-10-30 16:06:15 -0400658 if (grammar_.lookupOperand(type, word, &entry)) {
Diego Novillod2938e42017-11-08 12:40:02 -0500659 return diagnostic()
660 << "Invalid " << spvOperandTypeStr(parsed_operand.type)
661 << " operand: " << word;
Lei Zhang40056702015-09-11 14:31:27 -0400662 }
David Neto78c3b432015-08-27 13:03:52 -0400663 // Prepare to accept operands to this operand, if needed.
Chris Forbes78338d52017-06-27 16:28:22 -0700664 spvPushOperandTypes(entry->operandTypes, expected_operands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100665 } break;
David Neto0ca6b592015-10-30 16:06:15 -0400666
David Neto619db262015-09-25 12:43:37 -0400667 case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
668 case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
669 case SPV_OPERAND_TYPE_LOOP_CONTROL:
David Neto2889a0c2016-02-15 13:50:00 -0500670 case SPV_OPERAND_TYPE_IMAGE:
David Neto619db262015-09-25 12:43:37 -0400671 case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
672 case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
David Neto59de6102017-12-03 12:30:08 -0500673 case SPV_OPERAND_TYPE_SELECTION_CONTROL:
David Neto64f36ea2019-12-19 17:16:26 -0500674 case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_INFO_FLAGS:
David Neto59de6102017-12-03 12:30:08 -0500675 case SPV_OPERAND_TYPE_DEBUG_INFO_FLAGS: {
David Neto619db262015-09-25 12:43:37 -0400676 // This operand is a mask.
David Neto201caf72015-11-04 17:38:17 -0500677
678 // Map an optional operand type to its corresponding concrete type.
679 if (type == SPV_OPERAND_TYPE_OPTIONAL_IMAGE)
680 parsed_operand.type = SPV_OPERAND_TYPE_IMAGE;
681 else if (type == SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS)
682 parsed_operand.type = SPV_OPERAND_TYPE_MEMORY_ACCESS;
683
David Neto0ca6b592015-10-30 16:06:15 -0400684 // Check validity of set mask bits. Also prepare for operands for those
685 // masks if they have any. To get operand order correct, scan from
686 // MSB to LSB since we can only prepend operands to a pattern.
687 // The only case in the grammar where you have more than one mask bit
688 // having an operand is for image operands. See SPIR-V 3.14 Image
689 // Operands.
690 uint32_t remaining_word = word;
691 for (uint32_t mask = (1u << 31); remaining_word; mask >>= 1) {
David Neto619db262015-09-25 12:43:37 -0400692 if (remaining_word & mask) {
David Neto619db262015-09-25 12:43:37 -0400693 spv_operand_desc entry;
David Neto0ca6b592015-10-30 16:06:15 -0400694 if (grammar_.lookupOperand(type, mask, &entry)) {
David Neto201caf72015-11-04 17:38:17 -0500695 return diagnostic()
696 << "Invalid " << spvOperandTypeStr(parsed_operand.type)
697 << " operand: " << word << " has invalid mask component "
698 << mask;
David Neto619db262015-09-25 12:43:37 -0400699 }
David Neto0ca6b592015-10-30 16:06:15 -0400700 remaining_word ^= mask;
Chris Forbes78338d52017-06-27 16:28:22 -0700701 spvPushOperandTypes(entry->operandTypes, expected_operands);
David Neto619db262015-09-25 12:43:37 -0400702 }
703 }
David Neto0ca6b592015-10-30 16:06:15 -0400704 if (word == 0) {
705 // An all-zeroes mask *might* also be valid.
David Neto619db262015-09-25 12:43:37 -0400706 spv_operand_desc entry;
David Neto0ca6b592015-10-30 16:06:15 -0400707 if (SPV_SUCCESS == grammar_.lookupOperand(type, 0, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400708 // Prepare for its operands, if any.
Chris Forbes78338d52017-06-27 16:28:22 -0700709 spvPushOperandTypes(entry->operandTypes, expected_operands);
David Neto619db262015-09-25 12:43:37 -0400710 }
711 }
David Neto619db262015-09-25 12:43:37 -0400712 } break;
David Neto0ca6b592015-10-30 16:06:15 -0400713 default:
714 return diagnostic() << "Internal error: Unhandled operand type: " << type;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100715 }
716
David Neto0dbe1842017-12-03 14:26:16 -0500717 assert(spvOperandIsConcrete(parsed_operand.type));
David Neto0ca6b592015-10-30 16:06:15 -0400718
719 operands->push_back(parsed_operand);
720
David Neto7bff3eb2015-11-20 14:21:10 -0500721 const size_t index_after_operand = _.word_index + parsed_operand.num_words;
David Netod9ad0502015-11-24 18:37:24 -0500722
723 // Avoid buffer overrun for the cases where the operand has more than one
724 // word, and where it isn't a string. (Those other cases have already been
725 // handled earlier.) For example, this error can occur for a multi-word
726 // argument to OpConstant, or a multi-word case literal operand for OpSwitch.
727 if (_.num_words < index_after_operand)
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400728 return exhaustedInputDiagnostic(inst_offset, opcode, type);
David Netod9ad0502015-11-24 18:37:24 -0500729
David Neto7bff3eb2015-11-20 14:21:10 -0500730 if (_.requires_endian_conversion) {
731 // Copy instruction words. Translate to native endianness as needed.
732 if (convert_operand_endianness) {
733 const spv_endianness_t endianness = _.endian;
734 std::transform(_.words + _.word_index, _.words + index_after_operand,
Andrew Woloszyn3b69d052016-01-11 13:54:30 -0500735 std::back_inserter(*words),
736 [endianness](const uint32_t raw_word) {
David Neto677e0c72016-01-05 14:56:02 -0500737 return spvFixWord(raw_word, endianness);
David Neto7bff3eb2015-11-20 14:21:10 -0500738 });
739 } else {
740 words->insert(words->end(), _.words + _.word_index,
741 _.words + index_after_operand);
742 }
743 }
744
745 // Advance past the operand.
746 _.word_index = index_after_operand;
David Neto0ca6b592015-10-30 16:06:15 -0400747
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100748 return SPV_SUCCESS;
749}
750
David Neto0ca6b592015-10-30 16:06:15 -0400751spv_result_t Parser::setNumericTypeInfoForType(
752 spv_parsed_operand_t* parsed_operand, uint32_t type_id) {
David Neto201caf72015-11-04 17:38:17 -0500753 assert(type_id != 0);
David Neto0ca6b592015-10-30 16:06:15 -0400754 auto type_info_iter = _.type_id_to_number_type_info.find(type_id);
755 if (type_info_iter == _.type_id_to_number_type_info.end()) {
756 return diagnostic() << "Type Id " << type_id << " is not a type";
757 }
758 const NumberType& info = type_info_iter->second;
759 if (info.type == SPV_NUMBER_NONE) {
760 // This is a valid type, but for something other than a scalar number.
761 return diagnostic() << "Type Id " << type_id
762 << " is not a scalar numeric type";
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400763 }
764
David Neto0ca6b592015-10-30 16:06:15 -0400765 parsed_operand->number_kind = info.type;
766 parsed_operand->number_bit_width = info.bit_width;
David Neto066bd522016-01-05 14:57:58 -0500767 // Round up the word count.
768 parsed_operand->num_words = static_cast<uint16_t>((info.bit_width + 31) / 32);
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400769 return SPV_SUCCESS;
770}
771
David Neto7bff3eb2015-11-20 14:21:10 -0500772void Parser::recordNumberType(size_t inst_offset,
773 const spv_parsed_instruction_t* inst) {
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400774 const SpvOp opcode = static_cast<SpvOp>(inst->opcode);
775 if (spvOpcodeGeneratesType(opcode)) {
David Neto0ca6b592015-10-30 16:06:15 -0400776 NumberType info = {SPV_NUMBER_NONE, 0};
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400777 if (SpvOpTypeInt == opcode) {
David Neto7bff3eb2015-11-20 14:21:10 -0500778 const bool is_signed = peekAt(inst_offset + 3) != 0;
David Neto0ca6b592015-10-30 16:06:15 -0400779 info.type = is_signed ? SPV_NUMBER_SIGNED_INT : SPV_NUMBER_UNSIGNED_INT;
David Neto7bff3eb2015-11-20 14:21:10 -0500780 info.bit_width = peekAt(inst_offset + 2);
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400781 } else if (SpvOpTypeFloat == opcode) {
David Neto0ca6b592015-10-30 16:06:15 -0400782 info.type = SPV_NUMBER_FLOATING;
David Neto7bff3eb2015-11-20 14:21:10 -0500783 info.bit_width = peekAt(inst_offset + 2);
Lei Zhang40056702015-09-11 14:31:27 -0400784 }
David Neto0ca6b592015-10-30 16:06:15 -0400785 // The *result* Id of a type generating instruction is the type Id.
786 _.type_id_to_number_type_info[inst->result_id] = info;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100787 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100788}
789
David Neto0ca6b592015-10-30 16:06:15 -0400790} // anonymous namespace
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400791
Lei Zhang972788b2015-11-12 13:48:30 -0500792spv_result_t spvBinaryParse(const spv_const_context context, void* user_data,
793 const uint32_t* code, const size_t num_words,
David Neto0ca6b592015-10-30 16:06:15 -0400794 spv_parsed_header_fn_t parsed_header,
795 spv_parsed_instruction_fn_t parsed_instruction,
796 spv_diagnostic* diagnostic) {
Lei Zhang755f97f2016-09-02 18:06:18 -0400797 spv_context_t hijack_context = *context;
798 if (diagnostic) {
799 *diagnostic = nullptr;
dan sinclair3dad1cd2018-07-07 09:38:00 -0400800 spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, diagnostic);
Lei Zhang755f97f2016-09-02 18:06:18 -0400801 }
802 Parser parser(&hijack_context, user_data, parsed_header, parsed_instruction);
David Neto0ca6b592015-10-30 16:06:15 -0400803 return parser.parse(code, num_words, diagnostic);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100804}
805
David Neto0ca6b592015-10-30 16:06:15 -0400806// TODO(dneto): This probably belongs in text.cpp since that's the only place
807// that a spv_binary_t value is created.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100808void spvBinaryDestroy(spv_binary binary) {
Ryan Harrison024417d2019-10-17 12:30:15 -0400809 if (binary) {
810 if (binary->code) delete[] binary->code;
811 delete binary;
812 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100813}
David Neto37422e92016-12-19 13:26:42 -0500814
815size_t spv_strnlen_s(const char* str, size_t strsz) {
816 if (!str) return 0;
817 for (size_t i = 0; i < strsz; i++) {
818 if (!str[i]) return i;
819 }
820 return strsz;
821}