blob: de291061a3937691678e4174efe0d80994aa4ebb [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
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010027#include "binary.h"
David Netofcc7d582015-10-27 15:31:10 -040028
29#include <cassert>
30#include <cstring>
31#include <sstream>
32#include <unordered_map>
33
34#include <libspirv/libspirv.h>
35#include "assembly_grammar.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010036#include "diagnostic.h"
37#include "ext_inst.h"
David Netob5dc8fc2015-10-06 16:22:00 -040038#include "instruction.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010039#include "opcode.h"
40#include "operand.h"
Andrew Woloszynccc210b2015-10-16 10:23:42 -040041#include "text_handler.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010042
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010043// Binary API
44
45enum {
46 I32_ENDIAN_LITTLE = 0x03020100ul,
47 I32_ENDIAN_BIG = 0x00010203ul,
48};
49
50static const union {
51 unsigned char bytes[4];
52 uint32_t value;
53} o32_host_order = {{0, 1, 2, 3}};
54
Andrew Woloszyn157e41b2015-10-16 15:11:00 -040055using id_to_type_id_map = std::unordered_map<uint32_t, uint32_t>;
56using type_id_to_type_map = std::unordered_map<uint32_t, libspirv::IdType>;
57
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010058#define I32_ENDIAN_HOST (o32_host_order.value)
59
60spv_result_t spvBinaryEndianness(const spv_binary binary,
61 spv_endianness_t *pEndian) {
Lei Zhang40056702015-09-11 14:31:27 -040062 if (!binary->code || !binary->wordCount) return SPV_ERROR_INVALID_BINARY;
63 if (!pEndian) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010064
65 uint8_t bytes[4];
66 memcpy(bytes, binary->code, sizeof(uint32_t));
67
68 if (0x03 == bytes[0] && 0x02 == bytes[1] && 0x23 == bytes[2] &&
69 0x07 == bytes[3]) {
70 *pEndian = SPV_ENDIANNESS_LITTLE;
71 return SPV_SUCCESS;
72 }
73
74 if (0x07 == bytes[0] && 0x23 == bytes[1] && 0x02 == bytes[2] &&
75 0x03 == bytes[3]) {
76 *pEndian = SPV_ENDIANNESS_BIG;
77 return SPV_SUCCESS;
78 }
79
80 return SPV_ERROR_INVALID_BINARY;
81}
82
83uint32_t spvFixWord(const uint32_t word, const spv_endianness_t endian) {
84 if ((SPV_ENDIANNESS_LITTLE == endian && I32_ENDIAN_HOST == I32_ENDIAN_BIG) ||
85 (SPV_ENDIANNESS_BIG == endian && I32_ENDIAN_HOST == I32_ENDIAN_LITTLE)) {
86 return (word & 0x000000ff) << 24 | (word & 0x0000ff00) << 8 |
87 (word & 0x00ff0000) >> 8 | (word & 0xff000000) >> 24;
88 }
89
90 return word;
91}
92
Lei Zhangb41d1502015-09-14 15:22:23 -040093uint64_t spvFixDoubleWord(const uint32_t low, const uint32_t high,
94 const spv_endianness_t endian) {
95 return (uint64_t(spvFixWord(high, endian)) << 32) | spvFixWord(low, endian);
96}
97
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010098spv_result_t spvBinaryHeaderGet(const spv_binary binary,
99 const spv_endianness_t endian,
100 spv_header_t *pHeader) {
Lei Zhang40056702015-09-11 14:31:27 -0400101 if (!binary->code || !binary->wordCount) return SPV_ERROR_INVALID_BINARY;
102 if (!pHeader) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100103
104 // TODO: Validation checking?
105 pHeader->magic = spvFixWord(binary->code[SPV_INDEX_MAGIC_NUMBER], endian);
106 pHeader->version = spvFixWord(binary->code[SPV_INDEX_VERSION_NUMBER], endian);
107 pHeader->generator =
108 spvFixWord(binary->code[SPV_INDEX_GENERATOR_NUMBER], endian);
109 pHeader->bound = spvFixWord(binary->code[SPV_INDEX_BOUND], endian);
110 pHeader->schema = spvFixWord(binary->code[SPV_INDEX_SCHEMA], endian);
111 pHeader->instructions = &binary->code[SPV_INDEX_INSTRUCTION];
112
113 return SPV_SUCCESS;
114}
115
116spv_result_t spvBinaryHeaderSet(spv_binary_t *binary, const uint32_t bound) {
Lei Zhang40056702015-09-11 14:31:27 -0400117 if (!binary) return SPV_ERROR_INVALID_BINARY;
118 if (!binary->code || !binary->wordCount) return SPV_ERROR_INVALID_BINARY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100119
120 binary->code[SPV_INDEX_MAGIC_NUMBER] = SPV_MAGIC_NUMBER;
121 binary->code[SPV_INDEX_VERSION_NUMBER] = SPV_VERSION_NUMBER;
Kenneth Benzie (Benie)81d7d492015-06-01 09:50:46 -0700122 binary->code[SPV_INDEX_GENERATOR_NUMBER] = SPV_GENERATOR_KHRONOS;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100123 binary->code[SPV_INDEX_BOUND] = bound;
124 binary->code[SPV_INDEX_SCHEMA] = 0; // NOTE: Reserved
125
126 return SPV_SUCCESS;
127}
128
David Neto78c3b432015-08-27 13:03:52 -0400129// TODO(dneto): This API is not powerful enough in the case that the
130// number and type of operands are not known until partway through parsing
131// the operation. This happens when enum operands might have different number
132// of operands, or with extended instructions.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100133spv_operand_type_t spvBinaryOperandInfo(const uint32_t word,
134 const uint16_t operandIndex,
135 const spv_opcode_desc opcodeEntry,
136 const spv_operand_table operandTable,
137 spv_operand_desc *pOperandEntry) {
138 spv_operand_type_t type;
David Neto78c3b432015-08-27 13:03:52 -0400139 if (operandIndex < opcodeEntry->numTypes) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100140 // NOTE: Do operand table lookup to set operandEntry if successful
141 uint16_t index = operandIndex - 1;
142 type = opcodeEntry->operandTypes[index];
143 spv_operand_desc entry = nullptr;
144 if (!spvOperandTableValueLookup(operandTable, type, word, &entry)) {
145 if (SPV_OPERAND_TYPE_NONE != entry->operandTypes[0]) {
146 *pOperandEntry = entry;
147 }
148 }
149 } else if (*pOperandEntry) {
150 // NOTE: Use specified operand entry operand type for this word
David Neto78c3b432015-08-27 13:03:52 -0400151 uint16_t index = operandIndex - opcodeEntry->numTypes;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100152 type = (*pOperandEntry)->operandTypes[index];
153 } else if (OpSwitch == opcodeEntry->opcode) {
154 // NOTE: OpSwitch is a special case which expects a list of paired extra
155 // operands
156 assert(0 &&
157 "This case is previously untested, remove this assert and ensure it "
158 "is behaving correctly!");
David Neto78c3b432015-08-27 13:03:52 -0400159 uint16_t lastIndex = opcodeEntry->numTypes - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100160 uint16_t index = lastIndex + ((operandIndex - lastIndex) % 2);
161 type = opcodeEntry->operandTypes[index];
162 } else {
163 // NOTE: Default to last operand type in opcode entry
David Neto78c3b432015-08-27 13:03:52 -0400164 uint16_t index = opcodeEntry->numTypes - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100165 type = opcodeEntry->operandTypes[index];
166 }
167 return type;
168}
169
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400170
171/// @brief Translate a binary operand to the textual form
172///
173/// @param[in] opcode of the current instruction
174/// @param[in] type type of the operand to decode
175/// @param[in] words the binary stream of words
176/// @param[in] endian the endianness of the stream
177/// @param[in] options bitfield of spv_binary_to_text_options_t values
178/// @param[in] grammar the AssemblyGrammar to when decoding this operand
179/// @param[in,out] stream the text output stream
180/// @param[in,out] position position in the binary stream
181/// @param[out] pDiag return diagnostic on error
182///
183/// @return result code
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100184spv_result_t spvBinaryDecodeOperand(
185 const Op opcode, const spv_operand_type_t type, const uint32_t *words,
Lei Zhangb41d1502015-09-14 15:22:23 -0400186 uint16_t numWords, const spv_endianness_t endian, const uint32_t options,
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400187 const libspirv::AssemblyGrammar& grammar,
David Neto78c3b432015-08-27 13:03:52 -0400188 spv_operand_pattern_t *pExpectedOperands, spv_ext_inst_type_t *pExtInstType,
189 out_stream &stream, spv_position position, spv_diagnostic *pDiagnostic) {
Lei Zhang40056702015-09-11 14:31:27 -0400190 if (!words || !position) return SPV_ERROR_INVALID_POINTER;
191 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100192
193 bool print = spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options);
194 bool color =
195 print && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COLOR, options);
196
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100197 switch (type) {
David Netob14a7272015-09-25 13:56:09 -0400198 case SPV_OPERAND_TYPE_EXECUTION_SCOPE:
David Neto78c3b432015-08-27 13:03:52 -0400199 case SPV_OPERAND_TYPE_ID:
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400200 case SPV_OPERAND_TYPE_TYPE_ID:
David Netob14a7272015-09-25 13:56:09 -0400201 case SPV_OPERAND_TYPE_ID_IN_OPTIONAL_TUPLE:
David Neto78c3b432015-08-27 13:03:52 -0400202 case SPV_OPERAND_TYPE_OPTIONAL_ID:
David Netob14a7272015-09-25 13:56:09 -0400203 case SPV_OPERAND_TYPE_MEMORY_SEMANTICS:
204 case SPV_OPERAND_TYPE_RESULT_ID: {
David Neto78c3b432015-08-27 13:03:52 -0400205 if (color) {
Pyry Haulos26b3b002015-09-09 13:35:53 -0700206 if (type == SPV_OPERAND_TYPE_RESULT_ID) {
207 stream.get() << clr::blue();
208 } else {
209 stream.get() << clr::yellow();
210 }
David Neto78c3b432015-08-27 13:03:52 -0400211 }
Lei Zhang97afd5c2015-09-14 15:26:12 -0400212 stream.get() << "%" << spvFixWord(words[0], endian);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100213 stream.get() << ((color) ? clr::reset() : "");
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100214 position->index++;
215 } break;
David Neto445ce442015-10-15 15:22:06 -0400216 case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100217 if (OpExtInst == opcode) {
218 spv_ext_inst_desc extInst;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400219 if (grammar.lookupExtInst(*pExtInstType, words[0], &extInst)) {
Lei Zhang40056702015-09-11 14:31:27 -0400220 DIAGNOSTIC << "Invalid extended instruction '" << words[0] << "'.";
221 return SPV_ERROR_INVALID_BINARY;
222 }
David Neto78c3b432015-08-27 13:03:52 -0400223 spvPrependOperandTypes(extInst->operandTypes, pExpectedOperands);
Andrew Woloszyn0d350b52015-08-21 14:23:42 -0400224 stream.get() << (color ? clr::red() : "");
225 stream.get() << extInst->name;
226 stream.get() << (color ? clr::reset() : "");
Lei Zhang41bf0732015-09-14 12:26:15 -0400227 position->index++;
David Neto445ce442015-10-15 15:22:06 -0400228 } else {
229 DIAGNOSTIC << "Internal error: grammar thinks we need an "
230 "extension instruction number for opcode "
231 << opcode;
232 return SPV_ERROR_INTERNAL;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100233 }
David Neto445ce442015-10-15 15:22:06 -0400234 } break;
235 case SPV_OPERAND_TYPE_LITERAL_INTEGER:
Lei Zhangb41d1502015-09-14 15:22:23 -0400236 case SPV_OPERAND_TYPE_MULTIWORD_LITERAL_NUMBER:
Lei Zhang6483bd72015-10-14 17:02:39 -0400237 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER:
238 case SPV_OPERAND_TYPE_LITERAL_INTEGER_IN_OPTIONAL_TUPLE: {
Lei Zhang41bf0732015-09-14 12:26:15 -0400239 // TODO: Need to support multiple word literals
240 stream.get() << (color ? clr::red() : "");
Lei Zhangb41d1502015-09-14 15:22:23 -0400241 if (numWords > 2) {
242 DIAGNOSTIC << "Literal numbers larger than 64-bit not supported yet.";
243 return SPV_UNSUPPORTED;
244 } else if (numWords == 2) {
245 stream.get() << spvFixDoubleWord(words[0], words[1], endian);
246 position->index += 2;
247 } else {
248 stream.get() << spvFixWord(words[0], endian);
249 position->index++;
250 }
Lei Zhang41bf0732015-09-14 12:26:15 -0400251 stream.get() << (color ? clr::reset() : "");
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100252 } break;
David Neto78c3b432015-08-27 13:03:52 -0400253 case SPV_OPERAND_TYPE_LITERAL_STRING:
254 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
Lei Zhang97afd5c2015-09-14 15:26:12 -0400255 const char *string = (const char *)words;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100256 uint64_t stringOperandCount = (strlen(string) / 4) + 1;
257
258 // NOTE: Special case for extended instruction import
259 if (OpExtInstImport == opcode) {
260 *pExtInstType = spvExtInstImportTypeGet(string);
Lei Zhang40056702015-09-11 14:31:27 -0400261 if (SPV_EXT_INST_TYPE_NONE == *pExtInstType) {
262 DIAGNOSTIC << "Invalid extended instruction import'" << string
263 << "'.";
264 return SPV_ERROR_INVALID_BINARY;
265 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100266 }
267
268 stream.get() << "\"";
269 stream.get() << (color ? clr::green() : "");
David Neto980b7cb2015-10-15 16:40:04 -0400270 for (const char* p = string; *p; ++p) {
271 if(*p == '"' || *p == '\\') {
Andrew Woloszyne59e6b72015-10-14 14:18:43 -0400272 stream.get() << '\\';
273 }
David Neto980b7cb2015-10-15 16:40:04 -0400274 stream.get() << *p;
Andrew Woloszyne59e6b72015-10-14 14:18:43 -0400275 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100276 stream.get() << (color ? clr::reset() : "");
277 stream.get() << "\"";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100278 position->index += stringOperandCount;
279 } break;
280 case SPV_OPERAND_TYPE_CAPABILITY:
281 case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
282 case SPV_OPERAND_TYPE_EXECUTION_MODEL:
283 case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
284 case SPV_OPERAND_TYPE_MEMORY_MODEL:
285 case SPV_OPERAND_TYPE_EXECUTION_MODE:
David Neto78c3b432015-08-27 13:03:52 -0400286 case SPV_OPERAND_TYPE_OPTIONAL_EXECUTION_MODE:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100287 case SPV_OPERAND_TYPE_STORAGE_CLASS:
288 case SPV_OPERAND_TYPE_DIMENSIONALITY:
289 case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
290 case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100291 case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
292 case SPV_OPERAND_TYPE_LINKAGE_TYPE:
293 case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
294 case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
295 case SPV_OPERAND_TYPE_DECORATION:
296 case SPV_OPERAND_TYPE_BUILT_IN:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100297 case SPV_OPERAND_TYPE_GROUP_OPERATION:
298 case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
David Neto47994822015-08-27 13:11:01 -0400299 case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO: {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100300 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400301 if (grammar.lookupOperand(type, spvFixWord(words[0], endian), &entry)) {
Lei Zhang40056702015-09-11 14:31:27 -0400302 DIAGNOSTIC << "Invalid " << spvOperandTypeStr(type) << " operand '"
Lei Zhang97afd5c2015-09-14 15:26:12 -0400303 << words[0] << "'.";
David Neto619db262015-09-25 12:43:37 -0400304 return SPV_ERROR_INVALID_TEXT; // TODO(dneto): Surely this is invalid binary.
Lei Zhang40056702015-09-11 14:31:27 -0400305 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100306 stream.get() << entry->name;
David Neto78c3b432015-08-27 13:03:52 -0400307 // Prepare to accept operands to this operand, if needed.
308 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100309 position->index++;
310 } break;
David Neto619db262015-09-25 12:43:37 -0400311 case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
312 case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
313 case SPV_OPERAND_TYPE_LOOP_CONTROL:
314 case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
315 case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
316 case SPV_OPERAND_TYPE_SELECTION_CONTROL: {
317 // This operand is a mask.
318 // Scan it from least significant bit to most significant bit. For each
319 // set bit, emit the name of that bit and prepare to parse its operands,
320 // if any.
321 uint32_t remaining_word = spvFixWord(words[0], endian);
322 uint32_t mask;
323 int num_emitted = 0;
324 for (mask = 1; remaining_word; mask <<= 1) {
325 if (remaining_word & mask) {
326 remaining_word ^= mask;
327 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400328 if (grammar.lookupOperand(type, mask, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400329 DIAGNOSTIC << "Invalid " << spvOperandTypeStr(type) << " operand '"
330 << words[0] << "'.";
331 return SPV_ERROR_INVALID_BINARY;
332 }
333 if (num_emitted) stream.get() << "|";
334 stream.get() << entry->name;
335 num_emitted++;
336 }
337 }
338 if (!num_emitted) {
339 // An operand value of 0 was provided, so represent it by the name
340 // of the 0 value. In many cases, that's "None".
341 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400342 if (SPV_SUCCESS == grammar.lookupOperand(type, 0, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400343 stream.get() << entry->name;
344 // Prepare for its operands, if any.
345 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
346 }
347 }
348 // Prepare for subsequent operands, if any.
349 // Scan from MSB to LSB since we can only prepend operands to a pattern.
350 remaining_word = spvFixWord(words[0], endian);
351 for (mask = (1u << 31); remaining_word; mask >>= 1) {
352 if (remaining_word & mask) {
353 remaining_word ^= mask;
354 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400355 if (SPV_SUCCESS == grammar.lookupOperand(type, mask, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400356 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
357 }
358 }
359 }
360 position->index++;
361 } break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100362 default: {
363 DIAGNOSTIC << "Invalid binary operand '" << type << "'";
364 return SPV_ERROR_INVALID_BINARY;
365 }
366 }
367
368 return SPV_SUCCESS;
369}
370
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400371
372
373/// @brief Regsiters the given instruction with the type and id tracking
374/// tables.
375///
376/// @param[in] pInst the Opcode instruction stream
377/// @param[in] pOpcodeEntry the Opcode Entry describing the instruction
378/// @param[in, out] type_map the map of Ids to Types to be filled in
379/// @param[in, out] id_map the map of Ids to type Ids to be filled in
380/// @param[in, out] position position in the stream
381/// @param[out] pDiag return diagnostic on error
382///
383/// @return result code
384spv_result_t spvRegisterIdForOpcode(const spv_instruction_t* pInst,
385 const spv_opcode_desc_t* pOpcodeEntry,
386 type_id_to_type_map* type_map,
387 id_to_type_id_map* id_map,
388 spv_position position,
389 spv_diagnostic* pDiagnostic) {
390 libspirv::IdType detected_type = libspirv::kUnknownType;
391 if (spvOpcodeIsType(pOpcodeEntry->opcode)) {
392 if (spv::OpTypeInt == pOpcodeEntry->opcode) {
393 detected_type.type_class = libspirv::IdTypeClass::kScalarIntegerType;
394 detected_type.bitwidth = pInst->words[2];
395 detected_type.isSigned = (pInst->words[3] != 0);
396 } else if (spv::OpTypeFloat == pOpcodeEntry->opcode) {
397 detected_type.type_class = libspirv::IdTypeClass::kScalarIntegerType;
398 detected_type.bitwidth = pInst->words[2];
399 detected_type.isSigned = true;
400 } else {
401 detected_type.type_class = libspirv::IdTypeClass::kOtherType;
402 }
403 }
404
405 // We do not use else-if here so that we can still catch the case where an
406 // OpType* instruction shares the same ID as a non OpType* instruction.
407 if (pOpcodeEntry->hasResult) {
408 uint32_t value_id =
409 pOpcodeEntry->hasType ? pInst->words[2] : pInst->words[1];
410 if (id_map->find(value_id) != id_map->end()) {
411 DIAGNOSTIC << "Id " << value_id << " is defined more than once";
412 return SPV_ERROR_INVALID_BINARY;
413 }
414
415 (*id_map)[value_id] = pOpcodeEntry->hasType ? pInst->words[1] : 0;
416 }
417
418 if (detected_type != libspirv::kUnknownType) {
419 // This defines a new type.
420 uint32_t id = pInst->words[1];
421 (*type_map)[id] = detected_type;
422 }
423
424 return SPV_SUCCESS;
425}
426
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400427/// @brief Translate binary Opcode stream to textual form
428///
429/// @param[in] pInst the Opcode instruction stream
430/// @param[in] endian the endianness of the stream
431/// @param[in] options bitfield of spv_binary_to_text_options_t values
432/// @param[in] grammar the AssemblyGrammar to when decoding this operand
433/// @param[in] format the assembly syntax format to decode into
434/// @param[out] stream output text stream
435/// @param[in,out] position position in the stream
436/// @param[out] pDiag return diagnostic on error
437///
438/// @return result code
439spv_result_t spvBinaryDecodeOpcode(spv_instruction_t* pInst,
440 const spv_endianness_t endian,
441 const uint32_t options,
442 const libspirv::AssemblyGrammar& grammar,
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400443 type_id_to_type_map* type_map,
444 id_to_type_id_map* id_map,
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400445 spv_assembly_syntax_format_t format,
446 out_stream &stream, spv_position position,
447 spv_diagnostic *pDiagnostic) {
Lei Zhang40056702015-09-11 14:31:27 -0400448 if (!pInst || !position) return SPV_ERROR_INVALID_POINTER;
Lei Zhang40056702015-09-11 14:31:27 -0400449 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100450
David Neto78c3b432015-08-27 13:03:52 -0400451 spv_position_t instructionStart = *position;
452
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100453 uint16_t wordCount;
454 Op opcode;
455 spvOpcodeSplit(spvFixWord(pInst->words[0], endian), &wordCount, &opcode);
456
457 spv_opcode_desc opcodeEntry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400458 if (grammar.lookupOpcode(opcode, &opcodeEntry)) {
Lei Zhang40056702015-09-11 14:31:27 -0400459 DIAGNOSTIC << "Invalid Opcode '" << opcode << "'.";
460 return SPV_ERROR_INVALID_BINARY;
461 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100462
David Neto78c3b432015-08-27 13:03:52 -0400463 // See if there are enough required words.
464 // Some operands in the operand types are optional or could be zero length.
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400465 // The optional and zero length operands must be at the end of the list.
David Neto78c3b432015-08-27 13:03:52 -0400466 if (opcodeEntry->numTypes > wordCount &&
467 !spvOperandIsOptional(opcodeEntry->operandTypes[wordCount])) {
468 uint16_t numRequired;
Lei Zhange78a7c12015-09-10 17:07:21 -0400469 for (numRequired = 0;
470 numRequired < opcodeEntry->numTypes &&
471 !spvOperandIsOptional(opcodeEntry->operandTypes[numRequired]);
472 numRequired++)
David Neto78c3b432015-08-27 13:03:52 -0400473 ;
474 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
Lei Zhange78a7c12015-09-10 17:07:21 -0400475 << " word count '" << wordCount << "', expected at least '"
476 << numRequired << "'.";
David Neto78c3b432015-08-27 13:03:52 -0400477 return SPV_ERROR_INVALID_BINARY;
478 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100479
Lei Zhang29e667e2015-09-11 11:01:59 -0400480 const bool isAssigmentFormat =
481 SPV_ASSEMBLY_SYNTAX_FORMAT_ASSIGNMENT == format;
482
483 // For Canonical Assembly Format, all words are written to stream in order.
484 // For Assignment Assembly Format, <result-id> and the equal sign are written
485 // to stream first, while the rest are written to no_result_id_stream. After
486 // processing all words, all words in no_result_id_stream are transcribed to
487 // stream.
488
Lei Zhang8a375202015-08-24 15:52:26 -0400489 std::stringstream no_result_id_strstream;
490 out_stream no_result_id_stream(no_result_id_strstream);
Lei Zhang29e667e2015-09-11 11:01:59 -0400491 (isAssigmentFormat ? no_result_id_stream.get() : stream.get())
492 << "Op" << opcodeEntry->name;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100493
Lei Zhang29e667e2015-09-11 11:01:59 -0400494 const int16_t result_id_index = spvOpcodeResultIdIndex(opcodeEntry);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100495 position->index++;
496
David Neto78c3b432015-08-27 13:03:52 -0400497 // Maintains the ordered list of expected operand types.
498 // For many instructions we only need the {numTypes, operandTypes}
499 // entries in opcodeEntry. However, sometimes we need to modify
500 // the list as we parse the operands. This occurs when an operand
501 // has its own logical operands (such as the LocalSize operand for
502 // ExecutionMode), or for extended instructions that may have their
503 // own operands depending on the selected extended instruction.
504 spv_operand_pattern_t expectedOperands(
505 opcodeEntry->operandTypes,
506 opcodeEntry->operandTypes + opcodeEntry->numTypes);
507
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100508 for (uint16_t index = 1; index < wordCount; ++index) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100509 const uint64_t currentPosIndex = position->index;
Lei Zhang29e667e2015-09-11 11:01:59 -0400510 const bool currentIsResultId = result_id_index == index - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100511
Lei Zhang40056702015-09-11 14:31:27 -0400512 if (expectedOperands.empty()) {
513 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
514 << " starting at word " << instructionStart.index
515 << ": expected no more operands after " << index
516 << " words, but word count is " << wordCount << ".";
517 return SPV_ERROR_INVALID_BINARY;
518 }
David Neto78c3b432015-08-27 13:03:52 -0400519
520 spv_operand_type_t type = spvTakeFirstMatchableOperand(&expectedOperands);
521
Lei Zhang29e667e2015-09-11 11:01:59 -0400522 if (isAssigmentFormat) {
523 if (!currentIsResultId) no_result_id_stream.get() << " ";
524 } else {
525 stream.get() << " ";
526 }
Lei Zhangb41d1502015-09-14 15:22:23 -0400527
528 uint16_t numWords = 1;
529 if (type == SPV_OPERAND_TYPE_MULTIWORD_LITERAL_NUMBER) {
530 // Make sure this is the last operand for this instruction.
531 if (expectedOperands.empty()) {
532 numWords = wordCount - index;
533 } else {
534 // TODO(antiagainst): This may not be an error. The exact design has not
535 // been settled yet.
536 DIAGNOSTIC << "Multiple word literal numbers can only appear as the "
537 "last operand of an instruction.";
538 return SPV_ERROR_INVALID_BINARY;
539 }
540 }
541
Lei Zhang40056702015-09-11 14:31:27 -0400542 if (spvBinaryDecodeOperand(
David Netob5dc8fc2015-10-06 16:22:00 -0400543 opcodeEntry->opcode, type, &pInst->words[index], numWords, endian,
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400544 options, grammar, &expectedOperands,
Lei Zhangb41d1502015-09-14 15:22:23 -0400545 &pInst->extInstType,
Lei Zhang29e667e2015-09-11 11:01:59 -0400546 (isAssigmentFormat && !currentIsResultId ? no_result_id_stream
547 : stream),
Lei Zhang40056702015-09-11 14:31:27 -0400548 position, pDiagnostic)) {
549 DIAGNOSTIC << "UNEXPLAINED ERROR";
550 return SPV_ERROR_INVALID_BINARY;
551 }
Lei Zhang29e667e2015-09-11 11:01:59 -0400552 if (isAssigmentFormat && currentIsResultId) stream.get() << " = ";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100553 index += (uint16_t)(position->index - currentPosIndex - 1);
554 }
David Neto78c3b432015-08-27 13:03:52 -0400555 // TODO(dneto): There's an opportunity for a more informative message.
Lei Zhang40056702015-09-11 14:31:27 -0400556 if (!expectedOperands.empty() &&
557 !spvOperandIsOptional(expectedOperands.front())) {
558 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
559 << " starting at word " << instructionStart.index
560 << ": expected more operands after " << wordCount << " words.";
561 return SPV_ERROR_INVALID_BINARY;
562 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100563
Lei Zhang8a375202015-08-24 15:52:26 -0400564 stream.get() << no_result_id_strstream.str();
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400565 if (spv_result_t error = spvRegisterIdForOpcode(
566 pInst, opcodeEntry, type_map, id_map, position, pDiagnostic)) {
567 return error;
568 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100569 return SPV_SUCCESS;
570}
571
Lei Zhange78a7c12015-09-10 17:07:21 -0400572spv_result_t spvBinaryToText(uint32_t *code, const uint64_t wordCount,
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400573 const uint32_t options,
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100574 const spv_opcode_table opcodeTable,
575 const spv_operand_table operandTable,
576 const spv_ext_inst_table extInstTable,
577 spv_text *pText, spv_diagnostic *pDiagnostic) {
Lei Zhang29e667e2015-09-11 11:01:59 -0400578 return spvBinaryToTextWithFormat(
579 code, wordCount, options, opcodeTable, operandTable, extInstTable,
580 SPV_ASSEMBLY_SYNTAX_FORMAT_DEFAULT, pText, pDiagnostic);
581}
582
583spv_result_t spvBinaryToTextWithFormat(
584 uint32_t *code, const uint64_t wordCount, const uint32_t options,
585 const spv_opcode_table opcodeTable, const spv_operand_table operandTable,
586 const spv_ext_inst_table extInstTable, spv_assembly_syntax_format_t format,
587 spv_text *pText, spv_diagnostic *pDiagnostic) {
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400588 spv_binary_t binary = {code, wordCount};
589
Andrew Woloszyn4b4acde2015-09-10 10:28:22 -0400590 spv_position_t position = {};
Lei Zhang40056702015-09-11 14:31:27 -0400591 if (!binary.code || !binary.wordCount) {
592 DIAGNOSTIC << "Binary stream is empty.";
593 return SPV_ERROR_INVALID_BINARY;
594 }
595 if (!opcodeTable || !operandTable || !extInstTable)
596 return SPV_ERROR_INVALID_TABLE;
597 if (pText && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options))
598 return SPV_ERROR_INVALID_POINTER;
599 if (!pText && !spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options))
600 return SPV_ERROR_INVALID_POINTER;
601 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100602
603 spv_endianness_t endian;
Lei Zhang40056702015-09-11 14:31:27 -0400604 if (spvBinaryEndianness(&binary, &endian)) {
605 DIAGNOSTIC << "Invalid SPIR-V magic number '" << std::hex << binary.code[0]
606 << "'.";
607 return SPV_ERROR_INVALID_BINARY;
608 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100609
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400610 libspirv::AssemblyGrammar grammar(operandTable, opcodeTable, extInstTable);
611
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100612 spv_header_t header;
Lei Zhang40056702015-09-11 14:31:27 -0400613 if (spvBinaryHeaderGet(&binary, endian, &header)) {
614 DIAGNOSTIC << "Invalid SPIR-V header.";
615 return SPV_ERROR_INVALID_BINARY;
616 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100617
618 bool print = spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options);
619 bool color =
620 print && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COLOR, options);
621
622 std::stringstream sstream;
623 out_stream stream(sstream);
624 if (print) {
625 stream = out_stream();
626 }
627
628 if (color) {
629 stream.get() << clr::grey();
630 }
631 stream.get() << "; SPIR-V\n"
632 << "; Version: " << header.version << "\n"
633 << "; Generator: " << spvGeneratorStr(header.generator) << "\n"
634 << "; Bound: " << header.bound << "\n"
635 << "; Schema: " << header.schema << "\n";
636 if (color) {
637 stream.get() << clr::reset();
638 }
639
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400640 const uint32_t *words = binary.code;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100641 position.index = SPV_INDEX_INSTRUCTION;
642 spv_ext_inst_type_t extInstType = SPV_EXT_INST_TYPE_NONE;
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400643
644 id_to_type_id_map id_map;
645 type_id_to_type_map type_map;
646
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400647 while (position.index < binary.wordCount) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100648 uint64_t index = position.index;
649 uint16_t wordCount;
650 Op opcode;
651 spvOpcodeSplit(spvFixWord(words[position.index], endian), &wordCount,
652 &opcode);
653
654 spv_instruction_t inst = {};
655 inst.extInstType = extInstType;
656 spvInstructionCopy(&words[position.index], opcode, wordCount, endian,
657 &inst);
658
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400659 if (spvBinaryDecodeOpcode(&inst, endian, options, grammar, &type_map,
660 &id_map, format, stream, &position, pDiagnostic))
Lei Zhang40056702015-09-11 14:31:27 -0400661 return SPV_ERROR_INVALID_BINARY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100662 extInstType = inst.extInstType;
663
Lei Zhang40056702015-09-11 14:31:27 -0400664 if ((index + wordCount) != position.index) {
665 DIAGNOSTIC << "Invalid word count.";
666 return SPV_ERROR_INVALID_BINARY;
667 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100668
669 stream.get() << "\n";
670 }
671
672 if (!print) {
673 size_t length = sstream.str().size();
674 char *str = new char[length + 1];
Lei Zhang40056702015-09-11 14:31:27 -0400675 if (!str) return SPV_ERROR_OUT_OF_MEMORY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100676 strncpy(str, sstream.str().c_str(), length + 1);
677 spv_text text = new spv_text_t();
Lei Zhang40056702015-09-11 14:31:27 -0400678 if (!text) return SPV_ERROR_OUT_OF_MEMORY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100679 text->str = str;
680 text->length = length;
681 *pText = text;
682 }
683
684 return SPV_SUCCESS;
685}
686
687void spvBinaryDestroy(spv_binary binary) {
Lei Zhang40056702015-09-11 14:31:27 -0400688 if (!binary) return;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100689 if (binary->code) {
690 delete[] binary->code;
691 }
692 delete binary;
693}