blob: e7fc61db4b4d389712967b73bf30199f53e1ee55 [file] [log] [blame]
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +01001// Copyright (c) 2015 The Khronos Group Inc.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and/or associated documentation files (the
5// "Materials"), to deal in the Materials without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Materials, and to
8// permit persons to whom the Materials are furnished to do so, subject to
9// the following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Materials.
13//
14// MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS
15// KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS
16// SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT
17// https://www.khronos.org/registry/
18//
19// THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
23// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25// MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
26
27#include <libspirv/libspirv.h>
28#include "binary.h"
29#include "diagnostic.h"
30#include "ext_inst.h"
David Netob5dc8fc2015-10-06 16:22:00 -040031#include "instruction.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010032#include "opcode.h"
33#include "operand.h"
Andrew Woloszynccc210b2015-10-16 10:23:42 -040034#include "text_handler.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010035
36#include <assert.h>
37#include <string.h>
38
39#include <sstream>
40
41// Binary API
42
43enum {
44 I32_ENDIAN_LITTLE = 0x03020100ul,
45 I32_ENDIAN_BIG = 0x00010203ul,
46};
47
48static const union {
49 unsigned char bytes[4];
50 uint32_t value;
51} o32_host_order = {{0, 1, 2, 3}};
52
53#define I32_ENDIAN_HOST (o32_host_order.value)
54
55spv_result_t spvBinaryEndianness(const spv_binary binary,
56 spv_endianness_t *pEndian) {
Lei Zhang40056702015-09-11 14:31:27 -040057 if (!binary->code || !binary->wordCount) return SPV_ERROR_INVALID_BINARY;
58 if (!pEndian) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010059
60 uint8_t bytes[4];
61 memcpy(bytes, binary->code, sizeof(uint32_t));
62
63 if (0x03 == bytes[0] && 0x02 == bytes[1] && 0x23 == bytes[2] &&
64 0x07 == bytes[3]) {
65 *pEndian = SPV_ENDIANNESS_LITTLE;
66 return SPV_SUCCESS;
67 }
68
69 if (0x07 == bytes[0] && 0x23 == bytes[1] && 0x02 == bytes[2] &&
70 0x03 == bytes[3]) {
71 *pEndian = SPV_ENDIANNESS_BIG;
72 return SPV_SUCCESS;
73 }
74
75 return SPV_ERROR_INVALID_BINARY;
76}
77
78uint32_t spvFixWord(const uint32_t word, const spv_endianness_t endian) {
79 if ((SPV_ENDIANNESS_LITTLE == endian && I32_ENDIAN_HOST == I32_ENDIAN_BIG) ||
80 (SPV_ENDIANNESS_BIG == endian && I32_ENDIAN_HOST == I32_ENDIAN_LITTLE)) {
81 return (word & 0x000000ff) << 24 | (word & 0x0000ff00) << 8 |
82 (word & 0x00ff0000) >> 8 | (word & 0xff000000) >> 24;
83 }
84
85 return word;
86}
87
Lei Zhangb41d1502015-09-14 15:22:23 -040088uint64_t spvFixDoubleWord(const uint32_t low, const uint32_t high,
89 const spv_endianness_t endian) {
90 return (uint64_t(spvFixWord(high, endian)) << 32) | spvFixWord(low, endian);
91}
92
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010093spv_result_t spvBinaryHeaderGet(const spv_binary binary,
94 const spv_endianness_t endian,
95 spv_header_t *pHeader) {
Lei Zhang40056702015-09-11 14:31:27 -040096 if (!binary->code || !binary->wordCount) return SPV_ERROR_INVALID_BINARY;
97 if (!pHeader) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010098
99 // TODO: Validation checking?
100 pHeader->magic = spvFixWord(binary->code[SPV_INDEX_MAGIC_NUMBER], endian);
101 pHeader->version = spvFixWord(binary->code[SPV_INDEX_VERSION_NUMBER], endian);
102 pHeader->generator =
103 spvFixWord(binary->code[SPV_INDEX_GENERATOR_NUMBER], endian);
104 pHeader->bound = spvFixWord(binary->code[SPV_INDEX_BOUND], endian);
105 pHeader->schema = spvFixWord(binary->code[SPV_INDEX_SCHEMA], endian);
106 pHeader->instructions = &binary->code[SPV_INDEX_INSTRUCTION];
107
108 return SPV_SUCCESS;
109}
110
111spv_result_t spvBinaryHeaderSet(spv_binary_t *binary, const uint32_t bound) {
Lei Zhang40056702015-09-11 14:31:27 -0400112 if (!binary) return SPV_ERROR_INVALID_BINARY;
113 if (!binary->code || !binary->wordCount) return SPV_ERROR_INVALID_BINARY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100114
115 binary->code[SPV_INDEX_MAGIC_NUMBER] = SPV_MAGIC_NUMBER;
116 binary->code[SPV_INDEX_VERSION_NUMBER] = SPV_VERSION_NUMBER;
Kenneth Benzie (Benie)81d7d492015-06-01 09:50:46 -0700117 binary->code[SPV_INDEX_GENERATOR_NUMBER] = SPV_GENERATOR_KHRONOS;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100118 binary->code[SPV_INDEX_BOUND] = bound;
119 binary->code[SPV_INDEX_SCHEMA] = 0; // NOTE: Reserved
120
121 return SPV_SUCCESS;
122}
123
David Neto78c3b432015-08-27 13:03:52 -0400124// TODO(dneto): This API is not powerful enough in the case that the
125// number and type of operands are not known until partway through parsing
126// the operation. This happens when enum operands might have different number
127// of operands, or with extended instructions.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100128spv_operand_type_t spvBinaryOperandInfo(const uint32_t word,
129 const uint16_t operandIndex,
130 const spv_opcode_desc opcodeEntry,
131 const spv_operand_table operandTable,
132 spv_operand_desc *pOperandEntry) {
133 spv_operand_type_t type;
David Neto78c3b432015-08-27 13:03:52 -0400134 if (operandIndex < opcodeEntry->numTypes) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100135 // NOTE: Do operand table lookup to set operandEntry if successful
136 uint16_t index = operandIndex - 1;
137 type = opcodeEntry->operandTypes[index];
138 spv_operand_desc entry = nullptr;
139 if (!spvOperandTableValueLookup(operandTable, type, word, &entry)) {
140 if (SPV_OPERAND_TYPE_NONE != entry->operandTypes[0]) {
141 *pOperandEntry = entry;
142 }
143 }
144 } else if (*pOperandEntry) {
145 // NOTE: Use specified operand entry operand type for this word
David Neto78c3b432015-08-27 13:03:52 -0400146 uint16_t index = operandIndex - opcodeEntry->numTypes;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100147 type = (*pOperandEntry)->operandTypes[index];
148 } else if (OpSwitch == opcodeEntry->opcode) {
149 // NOTE: OpSwitch is a special case which expects a list of paired extra
150 // operands
151 assert(0 &&
152 "This case is previously untested, remove this assert and ensure it "
153 "is behaving correctly!");
David Neto78c3b432015-08-27 13:03:52 -0400154 uint16_t lastIndex = opcodeEntry->numTypes - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100155 uint16_t index = lastIndex + ((operandIndex - lastIndex) % 2);
156 type = opcodeEntry->operandTypes[index];
157 } else {
158 // NOTE: Default to last operand type in opcode entry
David Neto78c3b432015-08-27 13:03:52 -0400159 uint16_t index = opcodeEntry->numTypes - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100160 type = opcodeEntry->operandTypes[index];
161 }
162 return type;
163}
164
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400165
166/// @brief Translate a binary operand to the textual form
167///
168/// @param[in] opcode of the current instruction
169/// @param[in] type type of the operand to decode
170/// @param[in] words the binary stream of words
171/// @param[in] endian the endianness of the stream
172/// @param[in] options bitfield of spv_binary_to_text_options_t values
173/// @param[in] grammar the AssemblyGrammar to when decoding this operand
174/// @param[in,out] stream the text output stream
175/// @param[in,out] position position in the binary stream
176/// @param[out] pDiag return diagnostic on error
177///
178/// @return result code
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100179spv_result_t spvBinaryDecodeOperand(
180 const Op opcode, const spv_operand_type_t type, const uint32_t *words,
Lei Zhangb41d1502015-09-14 15:22:23 -0400181 uint16_t numWords, const spv_endianness_t endian, const uint32_t options,
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400182 const libspirv::AssemblyGrammar& grammar,
David Neto78c3b432015-08-27 13:03:52 -0400183 spv_operand_pattern_t *pExpectedOperands, spv_ext_inst_type_t *pExtInstType,
184 out_stream &stream, spv_position position, spv_diagnostic *pDiagnostic) {
Lei Zhang40056702015-09-11 14:31:27 -0400185 if (!words || !position) return SPV_ERROR_INVALID_POINTER;
186 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100187
188 bool print = spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options);
189 bool color =
190 print && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COLOR, options);
191
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100192 switch (type) {
David Netob14a7272015-09-25 13:56:09 -0400193 case SPV_OPERAND_TYPE_EXECUTION_SCOPE:
David Neto78c3b432015-08-27 13:03:52 -0400194 case SPV_OPERAND_TYPE_ID:
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400195 case SPV_OPERAND_TYPE_TYPE_ID:
David Netob14a7272015-09-25 13:56:09 -0400196 case SPV_OPERAND_TYPE_ID_IN_OPTIONAL_TUPLE:
David Neto78c3b432015-08-27 13:03:52 -0400197 case SPV_OPERAND_TYPE_OPTIONAL_ID:
David Netob14a7272015-09-25 13:56:09 -0400198 case SPV_OPERAND_TYPE_MEMORY_SEMANTICS:
199 case SPV_OPERAND_TYPE_RESULT_ID: {
David Neto78c3b432015-08-27 13:03:52 -0400200 if (color) {
Pyry Haulos26b3b002015-09-09 13:35:53 -0700201 if (type == SPV_OPERAND_TYPE_RESULT_ID) {
202 stream.get() << clr::blue();
203 } else {
204 stream.get() << clr::yellow();
205 }
David Neto78c3b432015-08-27 13:03:52 -0400206 }
Lei Zhang97afd5c2015-09-14 15:26:12 -0400207 stream.get() << "%" << spvFixWord(words[0], endian);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100208 stream.get() << ((color) ? clr::reset() : "");
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100209 position->index++;
210 } break;
David Neto445ce442015-10-15 15:22:06 -0400211 case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100212 if (OpExtInst == opcode) {
213 spv_ext_inst_desc extInst;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400214 if (grammar.lookupExtInst(*pExtInstType, words[0], &extInst)) {
Lei Zhang40056702015-09-11 14:31:27 -0400215 DIAGNOSTIC << "Invalid extended instruction '" << words[0] << "'.";
216 return SPV_ERROR_INVALID_BINARY;
217 }
David Neto78c3b432015-08-27 13:03:52 -0400218 spvPrependOperandTypes(extInst->operandTypes, pExpectedOperands);
Andrew Woloszyn0d350b52015-08-21 14:23:42 -0400219 stream.get() << (color ? clr::red() : "");
220 stream.get() << extInst->name;
221 stream.get() << (color ? clr::reset() : "");
Lei Zhang41bf0732015-09-14 12:26:15 -0400222 position->index++;
David Neto445ce442015-10-15 15:22:06 -0400223 } else {
224 DIAGNOSTIC << "Internal error: grammar thinks we need an "
225 "extension instruction number for opcode "
226 << opcode;
227 return SPV_ERROR_INTERNAL;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100228 }
David Neto445ce442015-10-15 15:22:06 -0400229 } break;
230 case SPV_OPERAND_TYPE_LITERAL_INTEGER:
Lei Zhangb41d1502015-09-14 15:22:23 -0400231 case SPV_OPERAND_TYPE_MULTIWORD_LITERAL_NUMBER:
Lei Zhang6483bd72015-10-14 17:02:39 -0400232 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER:
233 case SPV_OPERAND_TYPE_LITERAL_INTEGER_IN_OPTIONAL_TUPLE: {
Lei Zhang41bf0732015-09-14 12:26:15 -0400234 // TODO: Need to support multiple word literals
235 stream.get() << (color ? clr::red() : "");
Lei Zhangb41d1502015-09-14 15:22:23 -0400236 if (numWords > 2) {
237 DIAGNOSTIC << "Literal numbers larger than 64-bit not supported yet.";
238 return SPV_UNSUPPORTED;
239 } else if (numWords == 2) {
240 stream.get() << spvFixDoubleWord(words[0], words[1], endian);
241 position->index += 2;
242 } else {
243 stream.get() << spvFixWord(words[0], endian);
244 position->index++;
245 }
Lei Zhang41bf0732015-09-14 12:26:15 -0400246 stream.get() << (color ? clr::reset() : "");
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100247 } break;
David Neto78c3b432015-08-27 13:03:52 -0400248 case SPV_OPERAND_TYPE_LITERAL_STRING:
249 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
Lei Zhang97afd5c2015-09-14 15:26:12 -0400250 const char *string = (const char *)words;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100251 uint64_t stringOperandCount = (strlen(string) / 4) + 1;
252
253 // NOTE: Special case for extended instruction import
254 if (OpExtInstImport == opcode) {
255 *pExtInstType = spvExtInstImportTypeGet(string);
Lei Zhang40056702015-09-11 14:31:27 -0400256 if (SPV_EXT_INST_TYPE_NONE == *pExtInstType) {
257 DIAGNOSTIC << "Invalid extended instruction import'" << string
258 << "'.";
259 return SPV_ERROR_INVALID_BINARY;
260 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100261 }
262
263 stream.get() << "\"";
264 stream.get() << (color ? clr::green() : "");
David Neto980b7cb2015-10-15 16:40:04 -0400265 for (const char* p = string; *p; ++p) {
266 if(*p == '"' || *p == '\\') {
Andrew Woloszyne59e6b72015-10-14 14:18:43 -0400267 stream.get() << '\\';
268 }
David Neto980b7cb2015-10-15 16:40:04 -0400269 stream.get() << *p;
Andrew Woloszyne59e6b72015-10-14 14:18:43 -0400270 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100271 stream.get() << (color ? clr::reset() : "");
272 stream.get() << "\"";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100273 position->index += stringOperandCount;
274 } break;
275 case SPV_OPERAND_TYPE_CAPABILITY:
276 case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
277 case SPV_OPERAND_TYPE_EXECUTION_MODEL:
278 case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
279 case SPV_OPERAND_TYPE_MEMORY_MODEL:
280 case SPV_OPERAND_TYPE_EXECUTION_MODE:
David Neto78c3b432015-08-27 13:03:52 -0400281 case SPV_OPERAND_TYPE_OPTIONAL_EXECUTION_MODE:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100282 case SPV_OPERAND_TYPE_STORAGE_CLASS:
283 case SPV_OPERAND_TYPE_DIMENSIONALITY:
284 case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
285 case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100286 case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
287 case SPV_OPERAND_TYPE_LINKAGE_TYPE:
288 case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
289 case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
290 case SPV_OPERAND_TYPE_DECORATION:
291 case SPV_OPERAND_TYPE_BUILT_IN:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100292 case SPV_OPERAND_TYPE_GROUP_OPERATION:
293 case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
David Neto47994822015-08-27 13:11:01 -0400294 case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO: {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100295 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400296 if (grammar.lookupOperand(type, spvFixWord(words[0], endian), &entry)) {
Lei Zhang40056702015-09-11 14:31:27 -0400297 DIAGNOSTIC << "Invalid " << spvOperandTypeStr(type) << " operand '"
Lei Zhang97afd5c2015-09-14 15:26:12 -0400298 << words[0] << "'.";
David Neto619db262015-09-25 12:43:37 -0400299 return SPV_ERROR_INVALID_TEXT; // TODO(dneto): Surely this is invalid binary.
Lei Zhang40056702015-09-11 14:31:27 -0400300 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100301 stream.get() << entry->name;
David Neto78c3b432015-08-27 13:03:52 -0400302 // Prepare to accept operands to this operand, if needed.
303 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100304 position->index++;
305 } break;
David Neto619db262015-09-25 12:43:37 -0400306 case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
307 case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
308 case SPV_OPERAND_TYPE_LOOP_CONTROL:
309 case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
310 case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
311 case SPV_OPERAND_TYPE_SELECTION_CONTROL: {
312 // This operand is a mask.
313 // Scan it from least significant bit to most significant bit. For each
314 // set bit, emit the name of that bit and prepare to parse its operands,
315 // if any.
316 uint32_t remaining_word = spvFixWord(words[0], endian);
317 uint32_t mask;
318 int num_emitted = 0;
319 for (mask = 1; remaining_word; mask <<= 1) {
320 if (remaining_word & mask) {
321 remaining_word ^= mask;
322 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400323 if (grammar.lookupOperand(type, mask, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400324 DIAGNOSTIC << "Invalid " << spvOperandTypeStr(type) << " operand '"
325 << words[0] << "'.";
326 return SPV_ERROR_INVALID_BINARY;
327 }
328 if (num_emitted) stream.get() << "|";
329 stream.get() << entry->name;
330 num_emitted++;
331 }
332 }
333 if (!num_emitted) {
334 // An operand value of 0 was provided, so represent it by the name
335 // of the 0 value. In many cases, that's "None".
336 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400337 if (SPV_SUCCESS == grammar.lookupOperand(type, 0, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400338 stream.get() << entry->name;
339 // Prepare for its operands, if any.
340 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
341 }
342 }
343 // Prepare for subsequent operands, if any.
344 // Scan from MSB to LSB since we can only prepend operands to a pattern.
345 remaining_word = spvFixWord(words[0], endian);
346 for (mask = (1u << 31); remaining_word; mask >>= 1) {
347 if (remaining_word & mask) {
348 remaining_word ^= mask;
349 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400350 if (SPV_SUCCESS == grammar.lookupOperand(type, mask, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400351 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
352 }
353 }
354 }
355 position->index++;
356 } break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100357 default: {
358 DIAGNOSTIC << "Invalid binary operand '" << type << "'";
359 return SPV_ERROR_INVALID_BINARY;
360 }
361 }
362
363 return SPV_SUCCESS;
364}
365
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400366/// @brief Translate binary Opcode stream to textual form
367///
368/// @param[in] pInst the Opcode instruction stream
369/// @param[in] endian the endianness of the stream
370/// @param[in] options bitfield of spv_binary_to_text_options_t values
371/// @param[in] grammar the AssemblyGrammar to when decoding this operand
372/// @param[in] format the assembly syntax format to decode into
373/// @param[out] stream output text stream
374/// @param[in,out] position position in the stream
375/// @param[out] pDiag return diagnostic on error
376///
377/// @return result code
378spv_result_t spvBinaryDecodeOpcode(spv_instruction_t* pInst,
379 const spv_endianness_t endian,
380 const uint32_t options,
381 const libspirv::AssemblyGrammar& grammar,
382 spv_assembly_syntax_format_t format,
383 out_stream &stream, spv_position position,
384 spv_diagnostic *pDiagnostic) {
Lei Zhang40056702015-09-11 14:31:27 -0400385 if (!pInst || !position) return SPV_ERROR_INVALID_POINTER;
Lei Zhang40056702015-09-11 14:31:27 -0400386 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100387
David Neto78c3b432015-08-27 13:03:52 -0400388 spv_position_t instructionStart = *position;
389
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100390 uint16_t wordCount;
391 Op opcode;
392 spvOpcodeSplit(spvFixWord(pInst->words[0], endian), &wordCount, &opcode);
393
394 spv_opcode_desc opcodeEntry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400395 if (grammar.lookupOpcode(opcode, &opcodeEntry)) {
Lei Zhang40056702015-09-11 14:31:27 -0400396 DIAGNOSTIC << "Invalid Opcode '" << opcode << "'.";
397 return SPV_ERROR_INVALID_BINARY;
398 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100399
David Neto78c3b432015-08-27 13:03:52 -0400400 // See if there are enough required words.
401 // Some operands in the operand types are optional or could be zero length.
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400402 // The optional and zero length operands must be at the end of the list.
David Neto78c3b432015-08-27 13:03:52 -0400403 if (opcodeEntry->numTypes > wordCount &&
404 !spvOperandIsOptional(opcodeEntry->operandTypes[wordCount])) {
405 uint16_t numRequired;
Lei Zhange78a7c12015-09-10 17:07:21 -0400406 for (numRequired = 0;
407 numRequired < opcodeEntry->numTypes &&
408 !spvOperandIsOptional(opcodeEntry->operandTypes[numRequired]);
409 numRequired++)
David Neto78c3b432015-08-27 13:03:52 -0400410 ;
411 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
Lei Zhange78a7c12015-09-10 17:07:21 -0400412 << " word count '" << wordCount << "', expected at least '"
413 << numRequired << "'.";
David Neto78c3b432015-08-27 13:03:52 -0400414 return SPV_ERROR_INVALID_BINARY;
415 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100416
Lei Zhang29e667e2015-09-11 11:01:59 -0400417 const bool isAssigmentFormat =
418 SPV_ASSEMBLY_SYNTAX_FORMAT_ASSIGNMENT == format;
419
420 // For Canonical Assembly Format, all words are written to stream in order.
421 // For Assignment Assembly Format, <result-id> and the equal sign are written
422 // to stream first, while the rest are written to no_result_id_stream. After
423 // processing all words, all words in no_result_id_stream are transcribed to
424 // stream.
425
Lei Zhang8a375202015-08-24 15:52:26 -0400426 std::stringstream no_result_id_strstream;
427 out_stream no_result_id_stream(no_result_id_strstream);
Lei Zhang29e667e2015-09-11 11:01:59 -0400428 (isAssigmentFormat ? no_result_id_stream.get() : stream.get())
429 << "Op" << opcodeEntry->name;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100430
Lei Zhang29e667e2015-09-11 11:01:59 -0400431 const int16_t result_id_index = spvOpcodeResultIdIndex(opcodeEntry);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100432 position->index++;
433
David Neto78c3b432015-08-27 13:03:52 -0400434 // Maintains the ordered list of expected operand types.
435 // For many instructions we only need the {numTypes, operandTypes}
436 // entries in opcodeEntry. However, sometimes we need to modify
437 // the list as we parse the operands. This occurs when an operand
438 // has its own logical operands (such as the LocalSize operand for
439 // ExecutionMode), or for extended instructions that may have their
440 // own operands depending on the selected extended instruction.
441 spv_operand_pattern_t expectedOperands(
442 opcodeEntry->operandTypes,
443 opcodeEntry->operandTypes + opcodeEntry->numTypes);
444
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100445 for (uint16_t index = 1; index < wordCount; ++index) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100446 const uint64_t currentPosIndex = position->index;
Lei Zhang29e667e2015-09-11 11:01:59 -0400447 const bool currentIsResultId = result_id_index == index - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100448
Lei Zhang40056702015-09-11 14:31:27 -0400449 if (expectedOperands.empty()) {
450 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
451 << " starting at word " << instructionStart.index
452 << ": expected no more operands after " << index
453 << " words, but word count is " << wordCount << ".";
454 return SPV_ERROR_INVALID_BINARY;
455 }
David Neto78c3b432015-08-27 13:03:52 -0400456
457 spv_operand_type_t type = spvTakeFirstMatchableOperand(&expectedOperands);
458
Lei Zhang29e667e2015-09-11 11:01:59 -0400459 if (isAssigmentFormat) {
460 if (!currentIsResultId) no_result_id_stream.get() << " ";
461 } else {
462 stream.get() << " ";
463 }
Lei Zhangb41d1502015-09-14 15:22:23 -0400464
465 uint16_t numWords = 1;
466 if (type == SPV_OPERAND_TYPE_MULTIWORD_LITERAL_NUMBER) {
467 // Make sure this is the last operand for this instruction.
468 if (expectedOperands.empty()) {
469 numWords = wordCount - index;
470 } else {
471 // TODO(antiagainst): This may not be an error. The exact design has not
472 // been settled yet.
473 DIAGNOSTIC << "Multiple word literal numbers can only appear as the "
474 "last operand of an instruction.";
475 return SPV_ERROR_INVALID_BINARY;
476 }
477 }
478
Lei Zhang40056702015-09-11 14:31:27 -0400479 if (spvBinaryDecodeOperand(
David Netob5dc8fc2015-10-06 16:22:00 -0400480 opcodeEntry->opcode, type, &pInst->words[index], numWords, endian,
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400481 options, grammar, &expectedOperands,
Lei Zhangb41d1502015-09-14 15:22:23 -0400482 &pInst->extInstType,
Lei Zhang29e667e2015-09-11 11:01:59 -0400483 (isAssigmentFormat && !currentIsResultId ? no_result_id_stream
484 : stream),
Lei Zhang40056702015-09-11 14:31:27 -0400485 position, pDiagnostic)) {
486 DIAGNOSTIC << "UNEXPLAINED ERROR";
487 return SPV_ERROR_INVALID_BINARY;
488 }
Lei Zhang29e667e2015-09-11 11:01:59 -0400489 if (isAssigmentFormat && currentIsResultId) stream.get() << " = ";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100490 index += (uint16_t)(position->index - currentPosIndex - 1);
491 }
David Neto78c3b432015-08-27 13:03:52 -0400492 // TODO(dneto): There's an opportunity for a more informative message.
Lei Zhang40056702015-09-11 14:31:27 -0400493 if (!expectedOperands.empty() &&
494 !spvOperandIsOptional(expectedOperands.front())) {
495 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
496 << " starting at word " << instructionStart.index
497 << ": expected more operands after " << wordCount << " words.";
498 return SPV_ERROR_INVALID_BINARY;
499 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100500
Lei Zhang8a375202015-08-24 15:52:26 -0400501 stream.get() << no_result_id_strstream.str();
502
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100503 return SPV_SUCCESS;
504}
505
Lei Zhange78a7c12015-09-10 17:07:21 -0400506spv_result_t spvBinaryToText(uint32_t *code, const uint64_t wordCount,
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400507 const uint32_t options,
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100508 const spv_opcode_table opcodeTable,
509 const spv_operand_table operandTable,
510 const spv_ext_inst_table extInstTable,
511 spv_text *pText, spv_diagnostic *pDiagnostic) {
Lei Zhang29e667e2015-09-11 11:01:59 -0400512 return spvBinaryToTextWithFormat(
513 code, wordCount, options, opcodeTable, operandTable, extInstTable,
514 SPV_ASSEMBLY_SYNTAX_FORMAT_DEFAULT, pText, pDiagnostic);
515}
516
517spv_result_t spvBinaryToTextWithFormat(
518 uint32_t *code, const uint64_t wordCount, const uint32_t options,
519 const spv_opcode_table opcodeTable, const spv_operand_table operandTable,
520 const spv_ext_inst_table extInstTable, spv_assembly_syntax_format_t format,
521 spv_text *pText, spv_diagnostic *pDiagnostic) {
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400522 spv_binary_t binary = {code, wordCount};
523
Andrew Woloszyn4b4acde2015-09-10 10:28:22 -0400524 spv_position_t position = {};
Lei Zhang40056702015-09-11 14:31:27 -0400525 if (!binary.code || !binary.wordCount) {
526 DIAGNOSTIC << "Binary stream is empty.";
527 return SPV_ERROR_INVALID_BINARY;
528 }
529 if (!opcodeTable || !operandTable || !extInstTable)
530 return SPV_ERROR_INVALID_TABLE;
531 if (pText && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options))
532 return SPV_ERROR_INVALID_POINTER;
533 if (!pText && !spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options))
534 return SPV_ERROR_INVALID_POINTER;
535 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100536
537 spv_endianness_t endian;
Lei Zhang40056702015-09-11 14:31:27 -0400538 if (spvBinaryEndianness(&binary, &endian)) {
539 DIAGNOSTIC << "Invalid SPIR-V magic number '" << std::hex << binary.code[0]
540 << "'.";
541 return SPV_ERROR_INVALID_BINARY;
542 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100543
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400544 libspirv::AssemblyGrammar grammar(operandTable, opcodeTable, extInstTable);
545
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100546 spv_header_t header;
Lei Zhang40056702015-09-11 14:31:27 -0400547 if (spvBinaryHeaderGet(&binary, endian, &header)) {
548 DIAGNOSTIC << "Invalid SPIR-V header.";
549 return SPV_ERROR_INVALID_BINARY;
550 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100551
552 bool print = spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options);
553 bool color =
554 print && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COLOR, options);
555
556 std::stringstream sstream;
557 out_stream stream(sstream);
558 if (print) {
559 stream = out_stream();
560 }
561
562 if (color) {
563 stream.get() << clr::grey();
564 }
565 stream.get() << "; SPIR-V\n"
566 << "; Version: " << header.version << "\n"
567 << "; Generator: " << spvGeneratorStr(header.generator) << "\n"
568 << "; Bound: " << header.bound << "\n"
569 << "; Schema: " << header.schema << "\n";
570 if (color) {
571 stream.get() << clr::reset();
572 }
573
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400574 const uint32_t *words = binary.code;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100575 position.index = SPV_INDEX_INSTRUCTION;
576 spv_ext_inst_type_t extInstType = SPV_EXT_INST_TYPE_NONE;
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400577 while (position.index < binary.wordCount) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100578 uint64_t index = position.index;
579 uint16_t wordCount;
580 Op opcode;
581 spvOpcodeSplit(spvFixWord(words[position.index], endian), &wordCount,
582 &opcode);
583
584 spv_instruction_t inst = {};
585 inst.extInstType = extInstType;
586 spvInstructionCopy(&words[position.index], opcode, wordCount, endian,
587 &inst);
588
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400589 if (spvBinaryDecodeOpcode(&inst, endian, options, grammar, format, stream,
590 &position, pDiagnostic))
Lei Zhang40056702015-09-11 14:31:27 -0400591 return SPV_ERROR_INVALID_BINARY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100592 extInstType = inst.extInstType;
593
Lei Zhang40056702015-09-11 14:31:27 -0400594 if ((index + wordCount) != position.index) {
595 DIAGNOSTIC << "Invalid word count.";
596 return SPV_ERROR_INVALID_BINARY;
597 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100598
599 stream.get() << "\n";
600 }
601
602 if (!print) {
603 size_t length = sstream.str().size();
604 char *str = new char[length + 1];
Lei Zhang40056702015-09-11 14:31:27 -0400605 if (!str) return SPV_ERROR_OUT_OF_MEMORY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100606 strncpy(str, sstream.str().c_str(), length + 1);
607 spv_text text = new spv_text_t();
Lei Zhang40056702015-09-11 14:31:27 -0400608 if (!text) return SPV_ERROR_OUT_OF_MEMORY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100609 text->str = str;
610 text->length = length;
611 *pText = text;
612 }
613
614 return SPV_SUCCESS;
615}
616
617void spvBinaryDestroy(spv_binary binary) {
Lei Zhang40056702015-09-11 14:31:27 -0400618 if (!binary) return;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100619 if (binary->code) {
620 delete[] binary->code;
621 }
622 delete binary;
623}