blob: 9df80d32d01f0ad02631fec0119dd10e425736c3 [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>
Andrew Woloszyn157e41b2015-10-16 15:11:00 -040040#include <unordered_map>
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010041
42// Binary API
43
44enum {
45 I32_ENDIAN_LITTLE = 0x03020100ul,
46 I32_ENDIAN_BIG = 0x00010203ul,
47};
48
49static const union {
50 unsigned char bytes[4];
51 uint32_t value;
52} o32_host_order = {{0, 1, 2, 3}};
53
Andrew Woloszyn157e41b2015-10-16 15:11:00 -040054using id_to_type_id_map = std::unordered_map<uint32_t, uint32_t>;
55using type_id_to_type_map = std::unordered_map<uint32_t, libspirv::IdType>;
56
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010057#define I32_ENDIAN_HOST (o32_host_order.value)
58
59spv_result_t spvBinaryEndianness(const spv_binary binary,
60 spv_endianness_t *pEndian) {
Lei Zhang40056702015-09-11 14:31:27 -040061 if (!binary->code || !binary->wordCount) return SPV_ERROR_INVALID_BINARY;
62 if (!pEndian) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010063
64 uint8_t bytes[4];
65 memcpy(bytes, binary->code, sizeof(uint32_t));
66
67 if (0x03 == bytes[0] && 0x02 == bytes[1] && 0x23 == bytes[2] &&
68 0x07 == bytes[3]) {
69 *pEndian = SPV_ENDIANNESS_LITTLE;
70 return SPV_SUCCESS;
71 }
72
73 if (0x07 == bytes[0] && 0x23 == bytes[1] && 0x02 == bytes[2] &&
74 0x03 == bytes[3]) {
75 *pEndian = SPV_ENDIANNESS_BIG;
76 return SPV_SUCCESS;
77 }
78
79 return SPV_ERROR_INVALID_BINARY;
80}
81
82uint32_t spvFixWord(const uint32_t word, const spv_endianness_t endian) {
83 if ((SPV_ENDIANNESS_LITTLE == endian && I32_ENDIAN_HOST == I32_ENDIAN_BIG) ||
84 (SPV_ENDIANNESS_BIG == endian && I32_ENDIAN_HOST == I32_ENDIAN_LITTLE)) {
85 return (word & 0x000000ff) << 24 | (word & 0x0000ff00) << 8 |
86 (word & 0x00ff0000) >> 8 | (word & 0xff000000) >> 24;
87 }
88
89 return word;
90}
91
Lei Zhangb41d1502015-09-14 15:22:23 -040092uint64_t spvFixDoubleWord(const uint32_t low, const uint32_t high,
93 const spv_endianness_t endian) {
94 return (uint64_t(spvFixWord(high, endian)) << 32) | spvFixWord(low, endian);
95}
96
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010097spv_result_t spvBinaryHeaderGet(const spv_binary binary,
98 const spv_endianness_t endian,
99 spv_header_t *pHeader) {
Lei Zhang40056702015-09-11 14:31:27 -0400100 if (!binary->code || !binary->wordCount) return SPV_ERROR_INVALID_BINARY;
101 if (!pHeader) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100102
103 // TODO: Validation checking?
104 pHeader->magic = spvFixWord(binary->code[SPV_INDEX_MAGIC_NUMBER], endian);
105 pHeader->version = spvFixWord(binary->code[SPV_INDEX_VERSION_NUMBER], endian);
106 pHeader->generator =
107 spvFixWord(binary->code[SPV_INDEX_GENERATOR_NUMBER], endian);
108 pHeader->bound = spvFixWord(binary->code[SPV_INDEX_BOUND], endian);
109 pHeader->schema = spvFixWord(binary->code[SPV_INDEX_SCHEMA], endian);
110 pHeader->instructions = &binary->code[SPV_INDEX_INSTRUCTION];
111
112 return SPV_SUCCESS;
113}
114
115spv_result_t spvBinaryHeaderSet(spv_binary_t *binary, const uint32_t bound) {
Lei Zhang40056702015-09-11 14:31:27 -0400116 if (!binary) return SPV_ERROR_INVALID_BINARY;
117 if (!binary->code || !binary->wordCount) return SPV_ERROR_INVALID_BINARY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100118
119 binary->code[SPV_INDEX_MAGIC_NUMBER] = SPV_MAGIC_NUMBER;
120 binary->code[SPV_INDEX_VERSION_NUMBER] = SPV_VERSION_NUMBER;
Kenneth Benzie (Benie)81d7d492015-06-01 09:50:46 -0700121 binary->code[SPV_INDEX_GENERATOR_NUMBER] = SPV_GENERATOR_KHRONOS;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100122 binary->code[SPV_INDEX_BOUND] = bound;
123 binary->code[SPV_INDEX_SCHEMA] = 0; // NOTE: Reserved
124
125 return SPV_SUCCESS;
126}
127
David Neto78c3b432015-08-27 13:03:52 -0400128// TODO(dneto): This API is not powerful enough in the case that the
129// number and type of operands are not known until partway through parsing
130// the operation. This happens when enum operands might have different number
131// of operands, or with extended instructions.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100132spv_operand_type_t spvBinaryOperandInfo(const uint32_t word,
133 const uint16_t operandIndex,
134 const spv_opcode_desc opcodeEntry,
135 const spv_operand_table operandTable,
136 spv_operand_desc *pOperandEntry) {
137 spv_operand_type_t type;
David Neto78c3b432015-08-27 13:03:52 -0400138 if (operandIndex < opcodeEntry->numTypes) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100139 // NOTE: Do operand table lookup to set operandEntry if successful
140 uint16_t index = operandIndex - 1;
141 type = opcodeEntry->operandTypes[index];
142 spv_operand_desc entry = nullptr;
143 if (!spvOperandTableValueLookup(operandTable, type, word, &entry)) {
144 if (SPV_OPERAND_TYPE_NONE != entry->operandTypes[0]) {
145 *pOperandEntry = entry;
146 }
147 }
148 } else if (*pOperandEntry) {
149 // NOTE: Use specified operand entry operand type for this word
David Neto78c3b432015-08-27 13:03:52 -0400150 uint16_t index = operandIndex - opcodeEntry->numTypes;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100151 type = (*pOperandEntry)->operandTypes[index];
152 } else if (OpSwitch == opcodeEntry->opcode) {
153 // NOTE: OpSwitch is a special case which expects a list of paired extra
154 // operands
155 assert(0 &&
156 "This case is previously untested, remove this assert and ensure it "
157 "is behaving correctly!");
David Neto78c3b432015-08-27 13:03:52 -0400158 uint16_t lastIndex = opcodeEntry->numTypes - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100159 uint16_t index = lastIndex + ((operandIndex - lastIndex) % 2);
160 type = opcodeEntry->operandTypes[index];
161 } else {
162 // NOTE: Default to last operand type in opcode entry
David Neto78c3b432015-08-27 13:03:52 -0400163 uint16_t index = opcodeEntry->numTypes - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100164 type = opcodeEntry->operandTypes[index];
165 }
166 return type;
167}
168
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400169
170/// @brief Translate a binary operand to the textual form
171///
172/// @param[in] opcode of the current instruction
173/// @param[in] type type of the operand to decode
174/// @param[in] words the binary stream of words
175/// @param[in] endian the endianness of the stream
176/// @param[in] options bitfield of spv_binary_to_text_options_t values
177/// @param[in] grammar the AssemblyGrammar to when decoding this operand
178/// @param[in,out] stream the text output stream
179/// @param[in,out] position position in the binary stream
180/// @param[out] pDiag return diagnostic on error
181///
182/// @return result code
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100183spv_result_t spvBinaryDecodeOperand(
184 const Op opcode, const spv_operand_type_t type, const uint32_t *words,
Lei Zhangb41d1502015-09-14 15:22:23 -0400185 uint16_t numWords, const spv_endianness_t endian, const uint32_t options,
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400186 const libspirv::AssemblyGrammar& grammar,
David Neto78c3b432015-08-27 13:03:52 -0400187 spv_operand_pattern_t *pExpectedOperands, spv_ext_inst_type_t *pExtInstType,
188 out_stream &stream, spv_position position, spv_diagnostic *pDiagnostic) {
Lei Zhang40056702015-09-11 14:31:27 -0400189 if (!words || !position) return SPV_ERROR_INVALID_POINTER;
190 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100191
192 bool print = spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options);
193 bool color =
194 print && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COLOR, options);
195
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100196 switch (type) {
David Netob14a7272015-09-25 13:56:09 -0400197 case SPV_OPERAND_TYPE_EXECUTION_SCOPE:
David Neto78c3b432015-08-27 13:03:52 -0400198 case SPV_OPERAND_TYPE_ID:
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400199 case SPV_OPERAND_TYPE_TYPE_ID:
David Netob14a7272015-09-25 13:56:09 -0400200 case SPV_OPERAND_TYPE_ID_IN_OPTIONAL_TUPLE:
David Neto78c3b432015-08-27 13:03:52 -0400201 case SPV_OPERAND_TYPE_OPTIONAL_ID:
David Netob14a7272015-09-25 13:56:09 -0400202 case SPV_OPERAND_TYPE_MEMORY_SEMANTICS:
203 case SPV_OPERAND_TYPE_RESULT_ID: {
David Neto78c3b432015-08-27 13:03:52 -0400204 if (color) {
Pyry Haulos26b3b002015-09-09 13:35:53 -0700205 if (type == SPV_OPERAND_TYPE_RESULT_ID) {
206 stream.get() << clr::blue();
207 } else {
208 stream.get() << clr::yellow();
209 }
David Neto78c3b432015-08-27 13:03:52 -0400210 }
Lei Zhang97afd5c2015-09-14 15:26:12 -0400211 stream.get() << "%" << spvFixWord(words[0], endian);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100212 stream.get() << ((color) ? clr::reset() : "");
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100213 position->index++;
214 } break;
David Neto445ce442015-10-15 15:22:06 -0400215 case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100216 if (OpExtInst == opcode) {
217 spv_ext_inst_desc extInst;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400218 if (grammar.lookupExtInst(*pExtInstType, words[0], &extInst)) {
Lei Zhang40056702015-09-11 14:31:27 -0400219 DIAGNOSTIC << "Invalid extended instruction '" << words[0] << "'.";
220 return SPV_ERROR_INVALID_BINARY;
221 }
David Neto78c3b432015-08-27 13:03:52 -0400222 spvPrependOperandTypes(extInst->operandTypes, pExpectedOperands);
Andrew Woloszyn0d350b52015-08-21 14:23:42 -0400223 stream.get() << (color ? clr::red() : "");
224 stream.get() << extInst->name;
225 stream.get() << (color ? clr::reset() : "");
Lei Zhang41bf0732015-09-14 12:26:15 -0400226 position->index++;
David Neto445ce442015-10-15 15:22:06 -0400227 } else {
228 DIAGNOSTIC << "Internal error: grammar thinks we need an "
229 "extension instruction number for opcode "
230 << opcode;
231 return SPV_ERROR_INTERNAL;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100232 }
David Neto445ce442015-10-15 15:22:06 -0400233 } break;
234 case SPV_OPERAND_TYPE_LITERAL_INTEGER:
Lei Zhangb41d1502015-09-14 15:22:23 -0400235 case SPV_OPERAND_TYPE_MULTIWORD_LITERAL_NUMBER:
Lei Zhang6483bd72015-10-14 17:02:39 -0400236 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER:
237 case SPV_OPERAND_TYPE_LITERAL_INTEGER_IN_OPTIONAL_TUPLE: {
Lei Zhang41bf0732015-09-14 12:26:15 -0400238 // TODO: Need to support multiple word literals
239 stream.get() << (color ? clr::red() : "");
Lei Zhangb41d1502015-09-14 15:22:23 -0400240 if (numWords > 2) {
241 DIAGNOSTIC << "Literal numbers larger than 64-bit not supported yet.";
242 return SPV_UNSUPPORTED;
243 } else if (numWords == 2) {
244 stream.get() << spvFixDoubleWord(words[0], words[1], endian);
245 position->index += 2;
246 } else {
247 stream.get() << spvFixWord(words[0], endian);
248 position->index++;
249 }
Lei Zhang41bf0732015-09-14 12:26:15 -0400250 stream.get() << (color ? clr::reset() : "");
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100251 } break;
David Neto78c3b432015-08-27 13:03:52 -0400252 case SPV_OPERAND_TYPE_LITERAL_STRING:
253 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
Lei Zhang97afd5c2015-09-14 15:26:12 -0400254 const char *string = (const char *)words;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100255 uint64_t stringOperandCount = (strlen(string) / 4) + 1;
256
257 // NOTE: Special case for extended instruction import
258 if (OpExtInstImport == opcode) {
259 *pExtInstType = spvExtInstImportTypeGet(string);
Lei Zhang40056702015-09-11 14:31:27 -0400260 if (SPV_EXT_INST_TYPE_NONE == *pExtInstType) {
261 DIAGNOSTIC << "Invalid extended instruction import'" << string
262 << "'.";
263 return SPV_ERROR_INVALID_BINARY;
264 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100265 }
266
267 stream.get() << "\"";
268 stream.get() << (color ? clr::green() : "");
David Neto980b7cb2015-10-15 16:40:04 -0400269 for (const char* p = string; *p; ++p) {
270 if(*p == '"' || *p == '\\') {
Andrew Woloszyne59e6b72015-10-14 14:18:43 -0400271 stream.get() << '\\';
272 }
David Neto980b7cb2015-10-15 16:40:04 -0400273 stream.get() << *p;
Andrew Woloszyne59e6b72015-10-14 14:18:43 -0400274 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100275 stream.get() << (color ? clr::reset() : "");
276 stream.get() << "\"";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100277 position->index += stringOperandCount;
278 } break;
279 case SPV_OPERAND_TYPE_CAPABILITY:
280 case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
281 case SPV_OPERAND_TYPE_EXECUTION_MODEL:
282 case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
283 case SPV_OPERAND_TYPE_MEMORY_MODEL:
284 case SPV_OPERAND_TYPE_EXECUTION_MODE:
David Neto78c3b432015-08-27 13:03:52 -0400285 case SPV_OPERAND_TYPE_OPTIONAL_EXECUTION_MODE:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100286 case SPV_OPERAND_TYPE_STORAGE_CLASS:
287 case SPV_OPERAND_TYPE_DIMENSIONALITY:
288 case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
289 case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100290 case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
291 case SPV_OPERAND_TYPE_LINKAGE_TYPE:
292 case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
293 case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
294 case SPV_OPERAND_TYPE_DECORATION:
295 case SPV_OPERAND_TYPE_BUILT_IN:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100296 case SPV_OPERAND_TYPE_GROUP_OPERATION:
297 case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
David Neto47994822015-08-27 13:11:01 -0400298 case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO: {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100299 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400300 if (grammar.lookupOperand(type, spvFixWord(words[0], endian), &entry)) {
Lei Zhang40056702015-09-11 14:31:27 -0400301 DIAGNOSTIC << "Invalid " << spvOperandTypeStr(type) << " operand '"
Lei Zhang97afd5c2015-09-14 15:26:12 -0400302 << words[0] << "'.";
David Neto619db262015-09-25 12:43:37 -0400303 return SPV_ERROR_INVALID_TEXT; // TODO(dneto): Surely this is invalid binary.
Lei Zhang40056702015-09-11 14:31:27 -0400304 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100305 stream.get() << entry->name;
David Neto78c3b432015-08-27 13:03:52 -0400306 // Prepare to accept operands to this operand, if needed.
307 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100308 position->index++;
309 } break;
David Neto619db262015-09-25 12:43:37 -0400310 case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
311 case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
312 case SPV_OPERAND_TYPE_LOOP_CONTROL:
313 case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
314 case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
315 case SPV_OPERAND_TYPE_SELECTION_CONTROL: {
316 // This operand is a mask.
317 // Scan it from least significant bit to most significant bit. For each
318 // set bit, emit the name of that bit and prepare to parse its operands,
319 // if any.
320 uint32_t remaining_word = spvFixWord(words[0], endian);
321 uint32_t mask;
322 int num_emitted = 0;
323 for (mask = 1; remaining_word; mask <<= 1) {
324 if (remaining_word & mask) {
325 remaining_word ^= mask;
326 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400327 if (grammar.lookupOperand(type, mask, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400328 DIAGNOSTIC << "Invalid " << spvOperandTypeStr(type) << " operand '"
329 << words[0] << "'.";
330 return SPV_ERROR_INVALID_BINARY;
331 }
332 if (num_emitted) stream.get() << "|";
333 stream.get() << entry->name;
334 num_emitted++;
335 }
336 }
337 if (!num_emitted) {
338 // An operand value of 0 was provided, so represent it by the name
339 // of the 0 value. In many cases, that's "None".
340 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400341 if (SPV_SUCCESS == grammar.lookupOperand(type, 0, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400342 stream.get() << entry->name;
343 // Prepare for its operands, if any.
344 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
345 }
346 }
347 // Prepare for subsequent operands, if any.
348 // Scan from MSB to LSB since we can only prepend operands to a pattern.
349 remaining_word = spvFixWord(words[0], endian);
350 for (mask = (1u << 31); remaining_word; mask >>= 1) {
351 if (remaining_word & mask) {
352 remaining_word ^= mask;
353 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400354 if (SPV_SUCCESS == grammar.lookupOperand(type, mask, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400355 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
356 }
357 }
358 }
359 position->index++;
360 } break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100361 default: {
362 DIAGNOSTIC << "Invalid binary operand '" << type << "'";
363 return SPV_ERROR_INVALID_BINARY;
364 }
365 }
366
367 return SPV_SUCCESS;
368}
369
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400370
371
372/// @brief Regsiters the given instruction with the type and id tracking
373/// tables.
374///
375/// @param[in] pInst the Opcode instruction stream
376/// @param[in] pOpcodeEntry the Opcode Entry describing the instruction
377/// @param[in, out] type_map the map of Ids to Types to be filled in
378/// @param[in, out] id_map the map of Ids to type Ids to be filled in
379/// @param[in, out] position position in the stream
380/// @param[out] pDiag return diagnostic on error
381///
382/// @return result code
383spv_result_t spvRegisterIdForOpcode(const spv_instruction_t* pInst,
384 const spv_opcode_desc_t* pOpcodeEntry,
385 type_id_to_type_map* type_map,
386 id_to_type_id_map* id_map,
387 spv_position position,
388 spv_diagnostic* pDiagnostic) {
389 libspirv::IdType detected_type = libspirv::kUnknownType;
390 if (spvOpcodeIsType(pOpcodeEntry->opcode)) {
391 if (spv::OpTypeInt == pOpcodeEntry->opcode) {
392 detected_type.type_class = libspirv::IdTypeClass::kScalarIntegerType;
393 detected_type.bitwidth = pInst->words[2];
394 detected_type.isSigned = (pInst->words[3] != 0);
395 } else if (spv::OpTypeFloat == pOpcodeEntry->opcode) {
396 detected_type.type_class = libspirv::IdTypeClass::kScalarIntegerType;
397 detected_type.bitwidth = pInst->words[2];
398 detected_type.isSigned = true;
399 } else {
400 detected_type.type_class = libspirv::IdTypeClass::kOtherType;
401 }
402 }
403
404 // We do not use else-if here so that we can still catch the case where an
405 // OpType* instruction shares the same ID as a non OpType* instruction.
406 if (pOpcodeEntry->hasResult) {
407 uint32_t value_id =
408 pOpcodeEntry->hasType ? pInst->words[2] : pInst->words[1];
409 if (id_map->find(value_id) != id_map->end()) {
410 DIAGNOSTIC << "Id " << value_id << " is defined more than once";
411 return SPV_ERROR_INVALID_BINARY;
412 }
413
414 (*id_map)[value_id] = pOpcodeEntry->hasType ? pInst->words[1] : 0;
415 }
416
417 if (detected_type != libspirv::kUnknownType) {
418 // This defines a new type.
419 uint32_t id = pInst->words[1];
420 (*type_map)[id] = detected_type;
421 }
422
423 return SPV_SUCCESS;
424}
425
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400426/// @brief Translate binary Opcode stream to textual form
427///
428/// @param[in] pInst the Opcode instruction stream
429/// @param[in] endian the endianness of the stream
430/// @param[in] options bitfield of spv_binary_to_text_options_t values
431/// @param[in] grammar the AssemblyGrammar to when decoding this operand
432/// @param[in] format the assembly syntax format to decode into
433/// @param[out] stream output text stream
434/// @param[in,out] position position in the stream
435/// @param[out] pDiag return diagnostic on error
436///
437/// @return result code
438spv_result_t spvBinaryDecodeOpcode(spv_instruction_t* pInst,
439 const spv_endianness_t endian,
440 const uint32_t options,
441 const libspirv::AssemblyGrammar& grammar,
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400442 type_id_to_type_map* type_map,
443 id_to_type_id_map* id_map,
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400444 spv_assembly_syntax_format_t format,
445 out_stream &stream, spv_position position,
446 spv_diagnostic *pDiagnostic) {
Lei Zhang40056702015-09-11 14:31:27 -0400447 if (!pInst || !position) return SPV_ERROR_INVALID_POINTER;
Lei Zhang40056702015-09-11 14:31:27 -0400448 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100449
David Neto78c3b432015-08-27 13:03:52 -0400450 spv_position_t instructionStart = *position;
451
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100452 uint16_t wordCount;
453 Op opcode;
454 spvOpcodeSplit(spvFixWord(pInst->words[0], endian), &wordCount, &opcode);
455
456 spv_opcode_desc opcodeEntry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400457 if (grammar.lookupOpcode(opcode, &opcodeEntry)) {
Lei Zhang40056702015-09-11 14:31:27 -0400458 DIAGNOSTIC << "Invalid Opcode '" << opcode << "'.";
459 return SPV_ERROR_INVALID_BINARY;
460 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100461
David Neto78c3b432015-08-27 13:03:52 -0400462 // See if there are enough required words.
463 // Some operands in the operand types are optional or could be zero length.
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400464 // The optional and zero length operands must be at the end of the list.
David Neto78c3b432015-08-27 13:03:52 -0400465 if (opcodeEntry->numTypes > wordCount &&
466 !spvOperandIsOptional(opcodeEntry->operandTypes[wordCount])) {
467 uint16_t numRequired;
Lei Zhange78a7c12015-09-10 17:07:21 -0400468 for (numRequired = 0;
469 numRequired < opcodeEntry->numTypes &&
470 !spvOperandIsOptional(opcodeEntry->operandTypes[numRequired]);
471 numRequired++)
David Neto78c3b432015-08-27 13:03:52 -0400472 ;
473 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
Lei Zhange78a7c12015-09-10 17:07:21 -0400474 << " word count '" << wordCount << "', expected at least '"
475 << numRequired << "'.";
David Neto78c3b432015-08-27 13:03:52 -0400476 return SPV_ERROR_INVALID_BINARY;
477 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100478
Lei Zhang29e667e2015-09-11 11:01:59 -0400479 const bool isAssigmentFormat =
480 SPV_ASSEMBLY_SYNTAX_FORMAT_ASSIGNMENT == format;
481
482 // For Canonical Assembly Format, all words are written to stream in order.
483 // For Assignment Assembly Format, <result-id> and the equal sign are written
484 // to stream first, while the rest are written to no_result_id_stream. After
485 // processing all words, all words in no_result_id_stream are transcribed to
486 // stream.
487
Lei Zhang8a375202015-08-24 15:52:26 -0400488 std::stringstream no_result_id_strstream;
489 out_stream no_result_id_stream(no_result_id_strstream);
Lei Zhang29e667e2015-09-11 11:01:59 -0400490 (isAssigmentFormat ? no_result_id_stream.get() : stream.get())
491 << "Op" << opcodeEntry->name;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100492
Lei Zhang29e667e2015-09-11 11:01:59 -0400493 const int16_t result_id_index = spvOpcodeResultIdIndex(opcodeEntry);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100494 position->index++;
495
David Neto78c3b432015-08-27 13:03:52 -0400496 // Maintains the ordered list of expected operand types.
497 // For many instructions we only need the {numTypes, operandTypes}
498 // entries in opcodeEntry. However, sometimes we need to modify
499 // the list as we parse the operands. This occurs when an operand
500 // has its own logical operands (such as the LocalSize operand for
501 // ExecutionMode), or for extended instructions that may have their
502 // own operands depending on the selected extended instruction.
503 spv_operand_pattern_t expectedOperands(
504 opcodeEntry->operandTypes,
505 opcodeEntry->operandTypes + opcodeEntry->numTypes);
506
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100507 for (uint16_t index = 1; index < wordCount; ++index) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100508 const uint64_t currentPosIndex = position->index;
Lei Zhang29e667e2015-09-11 11:01:59 -0400509 const bool currentIsResultId = result_id_index == index - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100510
Lei Zhang40056702015-09-11 14:31:27 -0400511 if (expectedOperands.empty()) {
512 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
513 << " starting at word " << instructionStart.index
514 << ": expected no more operands after " << index
515 << " words, but word count is " << wordCount << ".";
516 return SPV_ERROR_INVALID_BINARY;
517 }
David Neto78c3b432015-08-27 13:03:52 -0400518
519 spv_operand_type_t type = spvTakeFirstMatchableOperand(&expectedOperands);
520
Lei Zhang29e667e2015-09-11 11:01:59 -0400521 if (isAssigmentFormat) {
522 if (!currentIsResultId) no_result_id_stream.get() << " ";
523 } else {
524 stream.get() << " ";
525 }
Lei Zhangb41d1502015-09-14 15:22:23 -0400526
527 uint16_t numWords = 1;
528 if (type == SPV_OPERAND_TYPE_MULTIWORD_LITERAL_NUMBER) {
529 // Make sure this is the last operand for this instruction.
530 if (expectedOperands.empty()) {
531 numWords = wordCount - index;
532 } else {
533 // TODO(antiagainst): This may not be an error. The exact design has not
534 // been settled yet.
535 DIAGNOSTIC << "Multiple word literal numbers can only appear as the "
536 "last operand of an instruction.";
537 return SPV_ERROR_INVALID_BINARY;
538 }
539 }
540
Lei Zhang40056702015-09-11 14:31:27 -0400541 if (spvBinaryDecodeOperand(
David Netob5dc8fc2015-10-06 16:22:00 -0400542 opcodeEntry->opcode, type, &pInst->words[index], numWords, endian,
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400543 options, grammar, &expectedOperands,
Lei Zhangb41d1502015-09-14 15:22:23 -0400544 &pInst->extInstType,
Lei Zhang29e667e2015-09-11 11:01:59 -0400545 (isAssigmentFormat && !currentIsResultId ? no_result_id_stream
546 : stream),
Lei Zhang40056702015-09-11 14:31:27 -0400547 position, pDiagnostic)) {
548 DIAGNOSTIC << "UNEXPLAINED ERROR";
549 return SPV_ERROR_INVALID_BINARY;
550 }
Lei Zhang29e667e2015-09-11 11:01:59 -0400551 if (isAssigmentFormat && currentIsResultId) stream.get() << " = ";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100552 index += (uint16_t)(position->index - currentPosIndex - 1);
553 }
David Neto78c3b432015-08-27 13:03:52 -0400554 // TODO(dneto): There's an opportunity for a more informative message.
Lei Zhang40056702015-09-11 14:31:27 -0400555 if (!expectedOperands.empty() &&
556 !spvOperandIsOptional(expectedOperands.front())) {
557 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
558 << " starting at word " << instructionStart.index
559 << ": expected more operands after " << wordCount << " words.";
560 return SPV_ERROR_INVALID_BINARY;
561 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100562
Lei Zhang8a375202015-08-24 15:52:26 -0400563 stream.get() << no_result_id_strstream.str();
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400564 if (spv_result_t error = spvRegisterIdForOpcode(
565 pInst, opcodeEntry, type_map, id_map, position, pDiagnostic)) {
566 return error;
567 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100568 return SPV_SUCCESS;
569}
570
Lei Zhange78a7c12015-09-10 17:07:21 -0400571spv_result_t spvBinaryToText(uint32_t *code, const uint64_t wordCount,
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400572 const uint32_t options,
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100573 const spv_opcode_table opcodeTable,
574 const spv_operand_table operandTable,
575 const spv_ext_inst_table extInstTable,
576 spv_text *pText, spv_diagnostic *pDiagnostic) {
Lei Zhang29e667e2015-09-11 11:01:59 -0400577 return spvBinaryToTextWithFormat(
578 code, wordCount, options, opcodeTable, operandTable, extInstTable,
579 SPV_ASSEMBLY_SYNTAX_FORMAT_DEFAULT, pText, pDiagnostic);
580}
581
582spv_result_t spvBinaryToTextWithFormat(
583 uint32_t *code, const uint64_t wordCount, const uint32_t options,
584 const spv_opcode_table opcodeTable, const spv_operand_table operandTable,
585 const spv_ext_inst_table extInstTable, spv_assembly_syntax_format_t format,
586 spv_text *pText, spv_diagnostic *pDiagnostic) {
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400587 spv_binary_t binary = {code, wordCount};
588
Andrew Woloszyn4b4acde2015-09-10 10:28:22 -0400589 spv_position_t position = {};
Lei Zhang40056702015-09-11 14:31:27 -0400590 if (!binary.code || !binary.wordCount) {
591 DIAGNOSTIC << "Binary stream is empty.";
592 return SPV_ERROR_INVALID_BINARY;
593 }
594 if (!opcodeTable || !operandTable || !extInstTable)
595 return SPV_ERROR_INVALID_TABLE;
596 if (pText && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options))
597 return SPV_ERROR_INVALID_POINTER;
598 if (!pText && !spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options))
599 return SPV_ERROR_INVALID_POINTER;
600 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100601
602 spv_endianness_t endian;
Lei Zhang40056702015-09-11 14:31:27 -0400603 if (spvBinaryEndianness(&binary, &endian)) {
604 DIAGNOSTIC << "Invalid SPIR-V magic number '" << std::hex << binary.code[0]
605 << "'.";
606 return SPV_ERROR_INVALID_BINARY;
607 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100608
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400609 libspirv::AssemblyGrammar grammar(operandTable, opcodeTable, extInstTable);
610
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100611 spv_header_t header;
Lei Zhang40056702015-09-11 14:31:27 -0400612 if (spvBinaryHeaderGet(&binary, endian, &header)) {
613 DIAGNOSTIC << "Invalid SPIR-V header.";
614 return SPV_ERROR_INVALID_BINARY;
615 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100616
617 bool print = spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options);
618 bool color =
619 print && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COLOR, options);
620
621 std::stringstream sstream;
622 out_stream stream(sstream);
623 if (print) {
624 stream = out_stream();
625 }
626
627 if (color) {
628 stream.get() << clr::grey();
629 }
630 stream.get() << "; SPIR-V\n"
631 << "; Version: " << header.version << "\n"
632 << "; Generator: " << spvGeneratorStr(header.generator) << "\n"
633 << "; Bound: " << header.bound << "\n"
634 << "; Schema: " << header.schema << "\n";
635 if (color) {
636 stream.get() << clr::reset();
637 }
638
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400639 const uint32_t *words = binary.code;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100640 position.index = SPV_INDEX_INSTRUCTION;
641 spv_ext_inst_type_t extInstType = SPV_EXT_INST_TYPE_NONE;
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400642
643 id_to_type_id_map id_map;
644 type_id_to_type_map type_map;
645
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400646 while (position.index < binary.wordCount) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100647 uint64_t index = position.index;
648 uint16_t wordCount;
649 Op opcode;
650 spvOpcodeSplit(spvFixWord(words[position.index], endian), &wordCount,
651 &opcode);
652
653 spv_instruction_t inst = {};
654 inst.extInstType = extInstType;
655 spvInstructionCopy(&words[position.index], opcode, wordCount, endian,
656 &inst);
657
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400658 if (spvBinaryDecodeOpcode(&inst, endian, options, grammar, &type_map,
659 &id_map, format, stream, &position, pDiagnostic))
Lei Zhang40056702015-09-11 14:31:27 -0400660 return SPV_ERROR_INVALID_BINARY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100661 extInstType = inst.extInstType;
662
Lei Zhang40056702015-09-11 14:31:27 -0400663 if ((index + wordCount) != position.index) {
664 DIAGNOSTIC << "Invalid word count.";
665 return SPV_ERROR_INVALID_BINARY;
666 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100667
668 stream.get() << "\n";
669 }
670
671 if (!print) {
672 size_t length = sstream.str().size();
673 char *str = new char[length + 1];
Lei Zhang40056702015-09-11 14:31:27 -0400674 if (!str) return SPV_ERROR_OUT_OF_MEMORY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100675 strncpy(str, sstream.str().c_str(), length + 1);
676 spv_text text = new spv_text_t();
Lei Zhang40056702015-09-11 14:31:27 -0400677 if (!text) return SPV_ERROR_OUT_OF_MEMORY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100678 text->str = str;
679 text->length = length;
680 *pText = text;
681 }
682
683 return SPV_SUCCESS;
684}
685
686void spvBinaryDestroy(spv_binary binary) {
Lei Zhang40056702015-09-11 14:31:27 -0400687 if (!binary) return;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100688 if (binary->code) {
689 delete[] binary->code;
690 }
691 delete binary;
692}