blob: 4213bea160854d442061f89ce2e1894c49bf0406 [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
David Neto78c3b432015-08-27 13:03:52 -0400116// TODO(dneto): This API is not powerful enough in the case that the
117// number and type of operands are not known until partway through parsing
118// the operation. This happens when enum operands might have different number
119// of operands, or with extended instructions.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100120spv_operand_type_t spvBinaryOperandInfo(const uint32_t word,
121 const uint16_t operandIndex,
122 const spv_opcode_desc opcodeEntry,
123 const spv_operand_table operandTable,
124 spv_operand_desc *pOperandEntry) {
125 spv_operand_type_t type;
David Neto78c3b432015-08-27 13:03:52 -0400126 if (operandIndex < opcodeEntry->numTypes) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100127 // NOTE: Do operand table lookup to set operandEntry if successful
128 uint16_t index = operandIndex - 1;
129 type = opcodeEntry->operandTypes[index];
130 spv_operand_desc entry = nullptr;
131 if (!spvOperandTableValueLookup(operandTable, type, word, &entry)) {
132 if (SPV_OPERAND_TYPE_NONE != entry->operandTypes[0]) {
133 *pOperandEntry = entry;
134 }
135 }
136 } else if (*pOperandEntry) {
137 // NOTE: Use specified operand entry operand type for this word
David Neto78c3b432015-08-27 13:03:52 -0400138 uint16_t index = operandIndex - opcodeEntry->numTypes;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100139 type = (*pOperandEntry)->operandTypes[index];
140 } else if (OpSwitch == opcodeEntry->opcode) {
141 // NOTE: OpSwitch is a special case which expects a list of paired extra
142 // operands
143 assert(0 &&
144 "This case is previously untested, remove this assert and ensure it "
145 "is behaving correctly!");
David Neto78c3b432015-08-27 13:03:52 -0400146 uint16_t lastIndex = opcodeEntry->numTypes - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100147 uint16_t index = lastIndex + ((operandIndex - lastIndex) % 2);
148 type = opcodeEntry->operandTypes[index];
149 } else {
150 // NOTE: Default to last operand type in opcode entry
David Neto78c3b432015-08-27 13:03:52 -0400151 uint16_t index = opcodeEntry->numTypes - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100152 type = opcodeEntry->operandTypes[index];
153 }
154 return type;
155}
156
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400157
158/// @brief Translate a binary operand to the textual form
159///
160/// @param[in] opcode of the current instruction
161/// @param[in] type type of the operand to decode
162/// @param[in] words the binary stream of words
163/// @param[in] endian the endianness of the stream
164/// @param[in] options bitfield of spv_binary_to_text_options_t values
165/// @param[in] grammar the AssemblyGrammar to when decoding this operand
166/// @param[in,out] stream the text output stream
167/// @param[in,out] position position in the binary stream
168/// @param[out] pDiag return diagnostic on error
169///
170/// @return result code
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100171spv_result_t spvBinaryDecodeOperand(
172 const Op opcode, const spv_operand_type_t type, const uint32_t *words,
Lei Zhangb41d1502015-09-14 15:22:23 -0400173 uint16_t numWords, const spv_endianness_t endian, const uint32_t options,
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400174 const libspirv::AssemblyGrammar& grammar,
David Neto78c3b432015-08-27 13:03:52 -0400175 spv_operand_pattern_t *pExpectedOperands, spv_ext_inst_type_t *pExtInstType,
176 out_stream &stream, spv_position position, spv_diagnostic *pDiagnostic) {
Lei Zhang40056702015-09-11 14:31:27 -0400177 if (!words || !position) return SPV_ERROR_INVALID_POINTER;
178 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100179
180 bool print = spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options);
181 bool color =
182 print && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COLOR, options);
183
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100184 switch (type) {
David Netob14a7272015-09-25 13:56:09 -0400185 case SPV_OPERAND_TYPE_EXECUTION_SCOPE:
David Neto78c3b432015-08-27 13:03:52 -0400186 case SPV_OPERAND_TYPE_ID:
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400187 case SPV_OPERAND_TYPE_TYPE_ID:
David Netob14a7272015-09-25 13:56:09 -0400188 case SPV_OPERAND_TYPE_ID_IN_OPTIONAL_TUPLE:
David Neto78c3b432015-08-27 13:03:52 -0400189 case SPV_OPERAND_TYPE_OPTIONAL_ID:
David Netob14a7272015-09-25 13:56:09 -0400190 case SPV_OPERAND_TYPE_MEMORY_SEMANTICS:
191 case SPV_OPERAND_TYPE_RESULT_ID: {
David Neto78c3b432015-08-27 13:03:52 -0400192 if (color) {
Pyry Haulos26b3b002015-09-09 13:35:53 -0700193 if (type == SPV_OPERAND_TYPE_RESULT_ID) {
194 stream.get() << clr::blue();
195 } else {
196 stream.get() << clr::yellow();
197 }
David Neto78c3b432015-08-27 13:03:52 -0400198 }
Lei Zhang97afd5c2015-09-14 15:26:12 -0400199 stream.get() << "%" << spvFixWord(words[0], endian);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100200 stream.get() << ((color) ? clr::reset() : "");
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100201 position->index++;
202 } break;
David Neto445ce442015-10-15 15:22:06 -0400203 case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100204 if (OpExtInst == opcode) {
205 spv_ext_inst_desc extInst;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400206 if (grammar.lookupExtInst(*pExtInstType, words[0], &extInst)) {
Lei Zhang40056702015-09-11 14:31:27 -0400207 DIAGNOSTIC << "Invalid extended instruction '" << words[0] << "'.";
208 return SPV_ERROR_INVALID_BINARY;
209 }
David Neto78c3b432015-08-27 13:03:52 -0400210 spvPrependOperandTypes(extInst->operandTypes, pExpectedOperands);
Andrew Woloszyn0d350b52015-08-21 14:23:42 -0400211 stream.get() << (color ? clr::red() : "");
212 stream.get() << extInst->name;
213 stream.get() << (color ? clr::reset() : "");
Lei Zhang41bf0732015-09-14 12:26:15 -0400214 position->index++;
David Neto445ce442015-10-15 15:22:06 -0400215 } else {
216 DIAGNOSTIC << "Internal error: grammar thinks we need an "
217 "extension instruction number for opcode "
218 << opcode;
219 return SPV_ERROR_INTERNAL;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100220 }
David Neto445ce442015-10-15 15:22:06 -0400221 } break;
222 case SPV_OPERAND_TYPE_LITERAL_INTEGER:
Lei Zhangb41d1502015-09-14 15:22:23 -0400223 case SPV_OPERAND_TYPE_MULTIWORD_LITERAL_NUMBER:
Lei Zhang6483bd72015-10-14 17:02:39 -0400224 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER:
225 case SPV_OPERAND_TYPE_LITERAL_INTEGER_IN_OPTIONAL_TUPLE: {
Lei Zhang41bf0732015-09-14 12:26:15 -0400226 // TODO: Need to support multiple word literals
227 stream.get() << (color ? clr::red() : "");
Lei Zhangb41d1502015-09-14 15:22:23 -0400228 if (numWords > 2) {
229 DIAGNOSTIC << "Literal numbers larger than 64-bit not supported yet.";
230 return SPV_UNSUPPORTED;
231 } else if (numWords == 2) {
232 stream.get() << spvFixDoubleWord(words[0], words[1], endian);
233 position->index += 2;
234 } else {
235 stream.get() << spvFixWord(words[0], endian);
236 position->index++;
237 }
Lei Zhang41bf0732015-09-14 12:26:15 -0400238 stream.get() << (color ? clr::reset() : "");
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100239 } break;
David Neto78c3b432015-08-27 13:03:52 -0400240 case SPV_OPERAND_TYPE_LITERAL_STRING:
241 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
Lei Zhang97afd5c2015-09-14 15:26:12 -0400242 const char *string = (const char *)words;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100243 uint64_t stringOperandCount = (strlen(string) / 4) + 1;
244
245 // NOTE: Special case for extended instruction import
246 if (OpExtInstImport == opcode) {
247 *pExtInstType = spvExtInstImportTypeGet(string);
Lei Zhang40056702015-09-11 14:31:27 -0400248 if (SPV_EXT_INST_TYPE_NONE == *pExtInstType) {
249 DIAGNOSTIC << "Invalid extended instruction import'" << string
250 << "'.";
251 return SPV_ERROR_INVALID_BINARY;
252 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100253 }
254
255 stream.get() << "\"";
256 stream.get() << (color ? clr::green() : "");
David Neto980b7cb2015-10-15 16:40:04 -0400257 for (const char* p = string; *p; ++p) {
258 if(*p == '"' || *p == '\\') {
Andrew Woloszyne59e6b72015-10-14 14:18:43 -0400259 stream.get() << '\\';
260 }
David Neto980b7cb2015-10-15 16:40:04 -0400261 stream.get() << *p;
Andrew Woloszyne59e6b72015-10-14 14:18:43 -0400262 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100263 stream.get() << (color ? clr::reset() : "");
264 stream.get() << "\"";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100265 position->index += stringOperandCount;
266 } break;
267 case SPV_OPERAND_TYPE_CAPABILITY:
268 case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
269 case SPV_OPERAND_TYPE_EXECUTION_MODEL:
270 case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
271 case SPV_OPERAND_TYPE_MEMORY_MODEL:
272 case SPV_OPERAND_TYPE_EXECUTION_MODE:
David Neto78c3b432015-08-27 13:03:52 -0400273 case SPV_OPERAND_TYPE_OPTIONAL_EXECUTION_MODE:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100274 case SPV_OPERAND_TYPE_STORAGE_CLASS:
275 case SPV_OPERAND_TYPE_DIMENSIONALITY:
276 case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
277 case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100278 case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
279 case SPV_OPERAND_TYPE_LINKAGE_TYPE:
280 case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
281 case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
282 case SPV_OPERAND_TYPE_DECORATION:
283 case SPV_OPERAND_TYPE_BUILT_IN:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100284 case SPV_OPERAND_TYPE_GROUP_OPERATION:
285 case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
David Neto47994822015-08-27 13:11:01 -0400286 case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO: {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100287 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400288 if (grammar.lookupOperand(type, spvFixWord(words[0], endian), &entry)) {
Lei Zhang40056702015-09-11 14:31:27 -0400289 DIAGNOSTIC << "Invalid " << spvOperandTypeStr(type) << " operand '"
Lei Zhang97afd5c2015-09-14 15:26:12 -0400290 << words[0] << "'.";
David Neto619db262015-09-25 12:43:37 -0400291 return SPV_ERROR_INVALID_TEXT; // TODO(dneto): Surely this is invalid binary.
Lei Zhang40056702015-09-11 14:31:27 -0400292 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100293 stream.get() << entry->name;
David Neto78c3b432015-08-27 13:03:52 -0400294 // Prepare to accept operands to this operand, if needed.
295 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100296 position->index++;
297 } break;
David Neto619db262015-09-25 12:43:37 -0400298 case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
299 case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
300 case SPV_OPERAND_TYPE_LOOP_CONTROL:
301 case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
302 case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
303 case SPV_OPERAND_TYPE_SELECTION_CONTROL: {
304 // This operand is a mask.
305 // Scan it from least significant bit to most significant bit. For each
306 // set bit, emit the name of that bit and prepare to parse its operands,
307 // if any.
308 uint32_t remaining_word = spvFixWord(words[0], endian);
309 uint32_t mask;
310 int num_emitted = 0;
311 for (mask = 1; remaining_word; mask <<= 1) {
312 if (remaining_word & mask) {
313 remaining_word ^= mask;
314 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400315 if (grammar.lookupOperand(type, mask, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400316 DIAGNOSTIC << "Invalid " << spvOperandTypeStr(type) << " operand '"
317 << words[0] << "'.";
318 return SPV_ERROR_INVALID_BINARY;
319 }
320 if (num_emitted) stream.get() << "|";
321 stream.get() << entry->name;
322 num_emitted++;
323 }
324 }
325 if (!num_emitted) {
326 // An operand value of 0 was provided, so represent it by the name
327 // of the 0 value. In many cases, that's "None".
328 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400329 if (SPV_SUCCESS == grammar.lookupOperand(type, 0, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400330 stream.get() << entry->name;
331 // Prepare for its operands, if any.
332 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
333 }
334 }
335 // Prepare for subsequent operands, if any.
336 // Scan from MSB to LSB since we can only prepend operands to a pattern.
337 remaining_word = spvFixWord(words[0], endian);
338 for (mask = (1u << 31); remaining_word; mask >>= 1) {
339 if (remaining_word & mask) {
340 remaining_word ^= mask;
341 spv_operand_desc entry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400342 if (SPV_SUCCESS == grammar.lookupOperand(type, mask, &entry)) {
David Neto619db262015-09-25 12:43:37 -0400343 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
344 }
345 }
346 }
347 position->index++;
348 } break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100349 default: {
350 DIAGNOSTIC << "Invalid binary operand '" << type << "'";
351 return SPV_ERROR_INVALID_BINARY;
352 }
353 }
354
355 return SPV_SUCCESS;
356}
357
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400358
359
360/// @brief Regsiters the given instruction with the type and id tracking
361/// tables.
362///
363/// @param[in] pInst the Opcode instruction stream
364/// @param[in] pOpcodeEntry the Opcode Entry describing the instruction
365/// @param[in, out] type_map the map of Ids to Types to be filled in
366/// @param[in, out] id_map the map of Ids to type Ids to be filled in
367/// @param[in, out] position position in the stream
368/// @param[out] pDiag return diagnostic on error
369///
370/// @return result code
371spv_result_t spvRegisterIdForOpcode(const spv_instruction_t* pInst,
372 const spv_opcode_desc_t* pOpcodeEntry,
373 type_id_to_type_map* type_map,
374 id_to_type_id_map* id_map,
375 spv_position position,
376 spv_diagnostic* pDiagnostic) {
377 libspirv::IdType detected_type = libspirv::kUnknownType;
378 if (spvOpcodeIsType(pOpcodeEntry->opcode)) {
379 if (spv::OpTypeInt == pOpcodeEntry->opcode) {
380 detected_type.type_class = libspirv::IdTypeClass::kScalarIntegerType;
381 detected_type.bitwidth = pInst->words[2];
382 detected_type.isSigned = (pInst->words[3] != 0);
383 } else if (spv::OpTypeFloat == pOpcodeEntry->opcode) {
384 detected_type.type_class = libspirv::IdTypeClass::kScalarIntegerType;
385 detected_type.bitwidth = pInst->words[2];
386 detected_type.isSigned = true;
387 } else {
388 detected_type.type_class = libspirv::IdTypeClass::kOtherType;
389 }
390 }
391
392 // We do not use else-if here so that we can still catch the case where an
393 // OpType* instruction shares the same ID as a non OpType* instruction.
394 if (pOpcodeEntry->hasResult) {
395 uint32_t value_id =
396 pOpcodeEntry->hasType ? pInst->words[2] : pInst->words[1];
397 if (id_map->find(value_id) != id_map->end()) {
398 DIAGNOSTIC << "Id " << value_id << " is defined more than once";
399 return SPV_ERROR_INVALID_BINARY;
400 }
401
402 (*id_map)[value_id] = pOpcodeEntry->hasType ? pInst->words[1] : 0;
403 }
404
405 if (detected_type != libspirv::kUnknownType) {
406 // This defines a new type.
407 uint32_t id = pInst->words[1];
408 (*type_map)[id] = detected_type;
409 }
410
411 return SPV_SUCCESS;
412}
413
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400414/// @brief Translate binary Opcode stream to textual form
415///
416/// @param[in] pInst the Opcode instruction stream
417/// @param[in] endian the endianness of the stream
418/// @param[in] options bitfield of spv_binary_to_text_options_t values
419/// @param[in] grammar the AssemblyGrammar to when decoding this operand
420/// @param[in] format the assembly syntax format to decode into
421/// @param[out] stream output text stream
422/// @param[in,out] position position in the stream
423/// @param[out] pDiag return diagnostic on error
424///
425/// @return result code
426spv_result_t spvBinaryDecodeOpcode(spv_instruction_t* pInst,
427 const spv_endianness_t endian,
428 const uint32_t options,
429 const libspirv::AssemblyGrammar& grammar,
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400430 type_id_to_type_map* type_map,
431 id_to_type_id_map* id_map,
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400432 spv_assembly_syntax_format_t format,
433 out_stream &stream, spv_position position,
434 spv_diagnostic *pDiagnostic) {
Lei Zhang40056702015-09-11 14:31:27 -0400435 if (!pInst || !position) return SPV_ERROR_INVALID_POINTER;
Lei Zhang40056702015-09-11 14:31:27 -0400436 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100437
David Neto78c3b432015-08-27 13:03:52 -0400438 spv_position_t instructionStart = *position;
439
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100440 uint16_t wordCount;
441 Op opcode;
442 spvOpcodeSplit(spvFixWord(pInst->words[0], endian), &wordCount, &opcode);
443
444 spv_opcode_desc opcodeEntry;
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400445 if (grammar.lookupOpcode(opcode, &opcodeEntry)) {
Lei Zhang40056702015-09-11 14:31:27 -0400446 DIAGNOSTIC << "Invalid Opcode '" << opcode << "'.";
447 return SPV_ERROR_INVALID_BINARY;
448 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100449
David Neto78c3b432015-08-27 13:03:52 -0400450 // See if there are enough required words.
451 // Some operands in the operand types are optional or could be zero length.
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400452 // The optional and zero length operands must be at the end of the list.
David Neto78c3b432015-08-27 13:03:52 -0400453 if (opcodeEntry->numTypes > wordCount &&
454 !spvOperandIsOptional(opcodeEntry->operandTypes[wordCount])) {
455 uint16_t numRequired;
Lei Zhange78a7c12015-09-10 17:07:21 -0400456 for (numRequired = 0;
457 numRequired < opcodeEntry->numTypes &&
458 !spvOperandIsOptional(opcodeEntry->operandTypes[numRequired]);
459 numRequired++)
David Neto78c3b432015-08-27 13:03:52 -0400460 ;
461 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
Lei Zhange78a7c12015-09-10 17:07:21 -0400462 << " word count '" << wordCount << "', expected at least '"
463 << numRequired << "'.";
David Neto78c3b432015-08-27 13:03:52 -0400464 return SPV_ERROR_INVALID_BINARY;
465 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100466
Lei Zhang29e667e2015-09-11 11:01:59 -0400467 const bool isAssigmentFormat =
468 SPV_ASSEMBLY_SYNTAX_FORMAT_ASSIGNMENT == format;
469
470 // For Canonical Assembly Format, all words are written to stream in order.
471 // For Assignment Assembly Format, <result-id> and the equal sign are written
472 // to stream first, while the rest are written to no_result_id_stream. After
473 // processing all words, all words in no_result_id_stream are transcribed to
474 // stream.
475
Lei Zhang8a375202015-08-24 15:52:26 -0400476 std::stringstream no_result_id_strstream;
477 out_stream no_result_id_stream(no_result_id_strstream);
Lei Zhang29e667e2015-09-11 11:01:59 -0400478 (isAssigmentFormat ? no_result_id_stream.get() : stream.get())
479 << "Op" << opcodeEntry->name;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100480
Lei Zhang29e667e2015-09-11 11:01:59 -0400481 const int16_t result_id_index = spvOpcodeResultIdIndex(opcodeEntry);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100482 position->index++;
483
David Neto78c3b432015-08-27 13:03:52 -0400484 // Maintains the ordered list of expected operand types.
485 // For many instructions we only need the {numTypes, operandTypes}
486 // entries in opcodeEntry. However, sometimes we need to modify
487 // the list as we parse the operands. This occurs when an operand
488 // has its own logical operands (such as the LocalSize operand for
489 // ExecutionMode), or for extended instructions that may have their
490 // own operands depending on the selected extended instruction.
491 spv_operand_pattern_t expectedOperands(
492 opcodeEntry->operandTypes,
493 opcodeEntry->operandTypes + opcodeEntry->numTypes);
494
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100495 for (uint16_t index = 1; index < wordCount; ++index) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100496 const uint64_t currentPosIndex = position->index;
Lei Zhang29e667e2015-09-11 11:01:59 -0400497 const bool currentIsResultId = result_id_index == index - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100498
Lei Zhang40056702015-09-11 14:31:27 -0400499 if (expectedOperands.empty()) {
500 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
501 << " starting at word " << instructionStart.index
502 << ": expected no more operands after " << index
503 << " words, but word count is " << wordCount << ".";
504 return SPV_ERROR_INVALID_BINARY;
505 }
David Neto78c3b432015-08-27 13:03:52 -0400506
507 spv_operand_type_t type = spvTakeFirstMatchableOperand(&expectedOperands);
508
Lei Zhang29e667e2015-09-11 11:01:59 -0400509 if (isAssigmentFormat) {
510 if (!currentIsResultId) no_result_id_stream.get() << " ";
511 } else {
512 stream.get() << " ";
513 }
Lei Zhangb41d1502015-09-14 15:22:23 -0400514
515 uint16_t numWords = 1;
516 if (type == SPV_OPERAND_TYPE_MULTIWORD_LITERAL_NUMBER) {
517 // Make sure this is the last operand for this instruction.
518 if (expectedOperands.empty()) {
519 numWords = wordCount - index;
520 } else {
521 // TODO(antiagainst): This may not be an error. The exact design has not
522 // been settled yet.
523 DIAGNOSTIC << "Multiple word literal numbers can only appear as the "
524 "last operand of an instruction.";
525 return SPV_ERROR_INVALID_BINARY;
526 }
527 }
528
Lei Zhang40056702015-09-11 14:31:27 -0400529 if (spvBinaryDecodeOperand(
David Netob5dc8fc2015-10-06 16:22:00 -0400530 opcodeEntry->opcode, type, &pInst->words[index], numWords, endian,
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400531 options, grammar, &expectedOperands,
Lei Zhangb41d1502015-09-14 15:22:23 -0400532 &pInst->extInstType,
Lei Zhang29e667e2015-09-11 11:01:59 -0400533 (isAssigmentFormat && !currentIsResultId ? no_result_id_stream
534 : stream),
Lei Zhang40056702015-09-11 14:31:27 -0400535 position, pDiagnostic)) {
536 DIAGNOSTIC << "UNEXPLAINED ERROR";
537 return SPV_ERROR_INVALID_BINARY;
538 }
Lei Zhang29e667e2015-09-11 11:01:59 -0400539 if (isAssigmentFormat && currentIsResultId) stream.get() << " = ";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100540 index += (uint16_t)(position->index - currentPosIndex - 1);
541 }
David Neto78c3b432015-08-27 13:03:52 -0400542 // TODO(dneto): There's an opportunity for a more informative message.
Lei Zhang40056702015-09-11 14:31:27 -0400543 if (!expectedOperands.empty() &&
544 !spvOperandIsOptional(expectedOperands.front())) {
545 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
546 << " starting at word " << instructionStart.index
547 << ": expected more operands after " << wordCount << " words.";
548 return SPV_ERROR_INVALID_BINARY;
549 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100550
Lei Zhang8a375202015-08-24 15:52:26 -0400551 stream.get() << no_result_id_strstream.str();
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400552 if (spv_result_t error = spvRegisterIdForOpcode(
553 pInst, opcodeEntry, type_map, id_map, position, pDiagnostic)) {
554 return error;
555 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100556 return SPV_SUCCESS;
557}
558
Lei Zhange78a7c12015-09-10 17:07:21 -0400559spv_result_t spvBinaryToText(uint32_t *code, const uint64_t wordCount,
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400560 const uint32_t options,
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100561 const spv_opcode_table opcodeTable,
562 const spv_operand_table operandTable,
563 const spv_ext_inst_table extInstTable,
564 spv_text *pText, spv_diagnostic *pDiagnostic) {
Lei Zhang29e667e2015-09-11 11:01:59 -0400565 return spvBinaryToTextWithFormat(
566 code, wordCount, options, opcodeTable, operandTable, extInstTable,
567 SPV_ASSEMBLY_SYNTAX_FORMAT_DEFAULT, pText, pDiagnostic);
568}
569
570spv_result_t spvBinaryToTextWithFormat(
571 uint32_t *code, const uint64_t wordCount, const uint32_t options,
572 const spv_opcode_table opcodeTable, const spv_operand_table operandTable,
573 const spv_ext_inst_table extInstTable, spv_assembly_syntax_format_t format,
574 spv_text *pText, spv_diagnostic *pDiagnostic) {
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400575 spv_binary_t binary = {code, wordCount};
576
Andrew Woloszyn4b4acde2015-09-10 10:28:22 -0400577 spv_position_t position = {};
Lei Zhang40056702015-09-11 14:31:27 -0400578 if (!binary.code || !binary.wordCount) {
579 DIAGNOSTIC << "Binary stream is empty.";
580 return SPV_ERROR_INVALID_BINARY;
581 }
582 if (!opcodeTable || !operandTable || !extInstTable)
583 return SPV_ERROR_INVALID_TABLE;
584 if (pText && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options))
585 return SPV_ERROR_INVALID_POINTER;
586 if (!pText && !spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options))
587 return SPV_ERROR_INVALID_POINTER;
588 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100589
590 spv_endianness_t endian;
Lei Zhang40056702015-09-11 14:31:27 -0400591 if (spvBinaryEndianness(&binary, &endian)) {
592 DIAGNOSTIC << "Invalid SPIR-V magic number '" << std::hex << binary.code[0]
593 << "'.";
594 return SPV_ERROR_INVALID_BINARY;
595 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100596
Andrew Woloszynccc210b2015-10-16 10:23:42 -0400597 libspirv::AssemblyGrammar grammar(operandTable, opcodeTable, extInstTable);
598
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100599 spv_header_t header;
Lei Zhang40056702015-09-11 14:31:27 -0400600 if (spvBinaryHeaderGet(&binary, endian, &header)) {
601 DIAGNOSTIC << "Invalid SPIR-V header.";
602 return SPV_ERROR_INVALID_BINARY;
603 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100604
605 bool print = spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options);
606 bool color =
607 print && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COLOR, options);
608
609 std::stringstream sstream;
610 out_stream stream(sstream);
611 if (print) {
612 stream = out_stream();
613 }
614
615 if (color) {
616 stream.get() << clr::grey();
617 }
618 stream.get() << "; SPIR-V\n"
619 << "; Version: " << header.version << "\n"
620 << "; Generator: " << spvGeneratorStr(header.generator) << "\n"
621 << "; Bound: " << header.bound << "\n"
622 << "; Schema: " << header.schema << "\n";
623 if (color) {
624 stream.get() << clr::reset();
625 }
626
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400627 const uint32_t *words = binary.code;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100628 position.index = SPV_INDEX_INSTRUCTION;
629 spv_ext_inst_type_t extInstType = SPV_EXT_INST_TYPE_NONE;
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400630
631 id_to_type_id_map id_map;
632 type_id_to_type_map type_map;
633
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400634 while (position.index < binary.wordCount) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100635 uint64_t index = position.index;
636 uint16_t wordCount;
637 Op opcode;
638 spvOpcodeSplit(spvFixWord(words[position.index], endian), &wordCount,
639 &opcode);
640
641 spv_instruction_t inst = {};
642 inst.extInstType = extInstType;
643 spvInstructionCopy(&words[position.index], opcode, wordCount, endian,
644 &inst);
645
Andrew Woloszyn157e41b2015-10-16 15:11:00 -0400646 if (spvBinaryDecodeOpcode(&inst, endian, options, grammar, &type_map,
647 &id_map, format, stream, &position, pDiagnostic))
Lei Zhang40056702015-09-11 14:31:27 -0400648 return SPV_ERROR_INVALID_BINARY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100649 extInstType = inst.extInstType;
650
Lei Zhang40056702015-09-11 14:31:27 -0400651 if ((index + wordCount) != position.index) {
652 DIAGNOSTIC << "Invalid word count.";
653 return SPV_ERROR_INVALID_BINARY;
654 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100655
656 stream.get() << "\n";
657 }
658
659 if (!print) {
660 size_t length = sstream.str().size();
661 char *str = new char[length + 1];
Lei Zhang40056702015-09-11 14:31:27 -0400662 if (!str) return SPV_ERROR_OUT_OF_MEMORY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100663 strncpy(str, sstream.str().c_str(), length + 1);
664 spv_text text = new spv_text_t();
Lei Zhang40056702015-09-11 14:31:27 -0400665 if (!text) return SPV_ERROR_OUT_OF_MEMORY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100666 text->str = str;
667 text->length = length;
668 *pText = text;
669 }
670
671 return SPV_SUCCESS;
672}
673
674void spvBinaryDestroy(spv_binary binary) {
Lei Zhang40056702015-09-11 14:31:27 -0400675 if (!binary) return;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100676 if (binary->code) {
677 delete[] binary->code;
678 }
679 delete binary;
680}