blob: 5c21e7fed5247b4f4d5aee0a190ab2f10df9bf71 [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"
31#include "opcode.h"
32#include "operand.h"
33
34#include <assert.h>
35#include <string.h>
36
37#include <sstream>
38
39// Binary API
40
41enum {
42 I32_ENDIAN_LITTLE = 0x03020100ul,
43 I32_ENDIAN_BIG = 0x00010203ul,
44};
45
46static const union {
47 unsigned char bytes[4];
48 uint32_t value;
49} o32_host_order = {{0, 1, 2, 3}};
50
51#define I32_ENDIAN_HOST (o32_host_order.value)
52
53spv_result_t spvBinaryEndianness(const spv_binary binary,
54 spv_endianness_t *pEndian) {
Lei Zhang40056702015-09-11 14:31:27 -040055 if (!binary->code || !binary->wordCount) return SPV_ERROR_INVALID_BINARY;
56 if (!pEndian) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010057
58 uint8_t bytes[4];
59 memcpy(bytes, binary->code, sizeof(uint32_t));
60
61 if (0x03 == bytes[0] && 0x02 == bytes[1] && 0x23 == bytes[2] &&
62 0x07 == bytes[3]) {
63 *pEndian = SPV_ENDIANNESS_LITTLE;
64 return SPV_SUCCESS;
65 }
66
67 if (0x07 == bytes[0] && 0x23 == bytes[1] && 0x02 == bytes[2] &&
68 0x03 == bytes[3]) {
69 *pEndian = SPV_ENDIANNESS_BIG;
70 return SPV_SUCCESS;
71 }
72
73 return SPV_ERROR_INVALID_BINARY;
74}
75
76uint32_t spvFixWord(const uint32_t word, const spv_endianness_t endian) {
77 if ((SPV_ENDIANNESS_LITTLE == endian && I32_ENDIAN_HOST == I32_ENDIAN_BIG) ||
78 (SPV_ENDIANNESS_BIG == endian && I32_ENDIAN_HOST == I32_ENDIAN_LITTLE)) {
79 return (word & 0x000000ff) << 24 | (word & 0x0000ff00) << 8 |
80 (word & 0x00ff0000) >> 8 | (word & 0xff000000) >> 24;
81 }
82
83 return word;
84}
85
Lei Zhangb41d1502015-09-14 15:22:23 -040086uint64_t spvFixDoubleWord(const uint32_t low, const uint32_t high,
87 const spv_endianness_t endian) {
88 return (uint64_t(spvFixWord(high, endian)) << 32) | spvFixWord(low, endian);
89}
90
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010091spv_result_t spvBinaryHeaderGet(const spv_binary binary,
92 const spv_endianness_t endian,
93 spv_header_t *pHeader) {
Lei Zhang40056702015-09-11 14:31:27 -040094 if (!binary->code || !binary->wordCount) return SPV_ERROR_INVALID_BINARY;
95 if (!pHeader) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010096
97 // TODO: Validation checking?
98 pHeader->magic = spvFixWord(binary->code[SPV_INDEX_MAGIC_NUMBER], endian);
99 pHeader->version = spvFixWord(binary->code[SPV_INDEX_VERSION_NUMBER], endian);
100 pHeader->generator =
101 spvFixWord(binary->code[SPV_INDEX_GENERATOR_NUMBER], endian);
102 pHeader->bound = spvFixWord(binary->code[SPV_INDEX_BOUND], endian);
103 pHeader->schema = spvFixWord(binary->code[SPV_INDEX_SCHEMA], endian);
104 pHeader->instructions = &binary->code[SPV_INDEX_INSTRUCTION];
105
106 return SPV_SUCCESS;
107}
108
109spv_result_t spvBinaryHeaderSet(spv_binary_t *binary, const uint32_t bound) {
Lei Zhang40056702015-09-11 14:31:27 -0400110 if (!binary) return SPV_ERROR_INVALID_BINARY;
111 if (!binary->code || !binary->wordCount) return SPV_ERROR_INVALID_BINARY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100112
113 binary->code[SPV_INDEX_MAGIC_NUMBER] = SPV_MAGIC_NUMBER;
114 binary->code[SPV_INDEX_VERSION_NUMBER] = SPV_VERSION_NUMBER;
Kenneth Benzie (Benie)81d7d492015-06-01 09:50:46 -0700115 binary->code[SPV_INDEX_GENERATOR_NUMBER] = SPV_GENERATOR_KHRONOS;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100116 binary->code[SPV_INDEX_BOUND] = bound;
117 binary->code[SPV_INDEX_SCHEMA] = 0; // NOTE: Reserved
118
119 return SPV_SUCCESS;
120}
121
122spv_result_t spvBinaryEncodeU32(const uint32_t value, spv_instruction_t *pInst,
123 const spv_position position,
124 spv_diagnostic *pDiagnostic) {
Lei Zhang40056702015-09-11 14:31:27 -0400125 if (pInst->wordCount + 1 > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
126 DIAGNOSTIC << "Instruction word count '"
127 << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX << "' exceeded.";
128 return SPV_ERROR_INVALID_TEXT;
129 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100130
131 pInst->words[pInst->wordCount++] = (uint32_t)value;
132 return SPV_SUCCESS;
133}
134
135spv_result_t spvBinaryEncodeU64(const uint64_t value, spv_instruction_t *pInst,
136 const spv_position position,
137 spv_diagnostic *pDiagnostic) {
Lei Zhang40056702015-09-11 14:31:27 -0400138 if (pInst->wordCount + 2 > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
139 DIAGNOSTIC << "Instruction word count '"
140 << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX << "' exceeded.";
141 return SPV_ERROR_INVALID_TEXT;
142 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100143
144 uint32_t low = (uint32_t)(0x00000000ffffffff & value);
145 uint32_t high = (uint32_t)((0xffffffff00000000 & value) >> 32);
146 pInst->words[pInst->wordCount++] = low;
147 pInst->words[pInst->wordCount++] = high;
148 return SPV_SUCCESS;
149}
150
151spv_result_t spvBinaryEncodeString(const char *str, spv_instruction_t *pInst,
152 const spv_position position,
153 spv_diagnostic *pDiagnostic) {
154 size_t length = strlen(str);
155 size_t wordCount = (length / 4) + 1;
Lei Zhang40056702015-09-11 14:31:27 -0400156 if ((sizeof(uint32_t) * pInst->wordCount) + length >
157 sizeof(uint32_t) * SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
158 DIAGNOSTIC << "Instruction word count '"
159 << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX << "'exceeded.";
160 return SPV_ERROR_INVALID_TEXT;
161 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100162
163 char *dest = (char *)&pInst->words[pInst->wordCount];
164 strncpy(dest, str, length);
165 pInst->wordCount += (uint16_t)wordCount;
166
167 return SPV_SUCCESS;
168}
169
David Neto78c3b432015-08-27 13:03:52 -0400170// TODO(dneto): This API is not powerful enough in the case that the
171// number and type of operands are not known until partway through parsing
172// the operation. This happens when enum operands might have different number
173// of operands, or with extended instructions.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100174spv_operand_type_t spvBinaryOperandInfo(const uint32_t word,
175 const uint16_t operandIndex,
176 const spv_opcode_desc opcodeEntry,
177 const spv_operand_table operandTable,
178 spv_operand_desc *pOperandEntry) {
179 spv_operand_type_t type;
David Neto78c3b432015-08-27 13:03:52 -0400180 if (operandIndex < opcodeEntry->numTypes) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100181 // NOTE: Do operand table lookup to set operandEntry if successful
182 uint16_t index = operandIndex - 1;
183 type = opcodeEntry->operandTypes[index];
184 spv_operand_desc entry = nullptr;
185 if (!spvOperandTableValueLookup(operandTable, type, word, &entry)) {
186 if (SPV_OPERAND_TYPE_NONE != entry->operandTypes[0]) {
187 *pOperandEntry = entry;
188 }
189 }
190 } else if (*pOperandEntry) {
191 // NOTE: Use specified operand entry operand type for this word
David Neto78c3b432015-08-27 13:03:52 -0400192 uint16_t index = operandIndex - opcodeEntry->numTypes;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100193 type = (*pOperandEntry)->operandTypes[index];
194 } else if (OpSwitch == opcodeEntry->opcode) {
195 // NOTE: OpSwitch is a special case which expects a list of paired extra
196 // operands
197 assert(0 &&
198 "This case is previously untested, remove this assert and ensure it "
199 "is behaving correctly!");
David Neto78c3b432015-08-27 13:03:52 -0400200 uint16_t lastIndex = opcodeEntry->numTypes - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100201 uint16_t index = lastIndex + ((operandIndex - lastIndex) % 2);
202 type = opcodeEntry->operandTypes[index];
203 } else {
204 // NOTE: Default to last operand type in opcode entry
David Neto78c3b432015-08-27 13:03:52 -0400205 uint16_t index = opcodeEntry->numTypes - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100206 type = opcodeEntry->operandTypes[index];
207 }
208 return type;
209}
210
211spv_result_t spvBinaryDecodeOperand(
212 const Op opcode, const spv_operand_type_t type, const uint32_t *words,
Lei Zhangb41d1502015-09-14 15:22:23 -0400213 uint16_t numWords, const spv_endianness_t endian, const uint32_t options,
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100214 const spv_operand_table operandTable, const spv_ext_inst_table extInstTable,
David Neto78c3b432015-08-27 13:03:52 -0400215 spv_operand_pattern_t *pExpectedOperands, spv_ext_inst_type_t *pExtInstType,
216 out_stream &stream, spv_position position, spv_diagnostic *pDiagnostic) {
Lei Zhang40056702015-09-11 14:31:27 -0400217 if (!words || !position) return SPV_ERROR_INVALID_POINTER;
218 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100219
220 bool print = spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options);
221 bool color =
222 print && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COLOR, options);
223
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100224 switch (type) {
David Neto78c3b432015-08-27 13:03:52 -0400225 case SPV_OPERAND_TYPE_ID:
226 case SPV_OPERAND_TYPE_RESULT_ID:
227 case SPV_OPERAND_TYPE_OPTIONAL_ID:
228 case SPV_OPERAND_TYPE_ID_IN_OPTIONAL_TUPLE: {
229 if (color) {
Pyry Haulos26b3b002015-09-09 13:35:53 -0700230 if (type == SPV_OPERAND_TYPE_RESULT_ID) {
231 stream.get() << clr::blue();
232 } else {
233 stream.get() << clr::yellow();
234 }
David Neto78c3b432015-08-27 13:03:52 -0400235 }
Lei Zhang97afd5c2015-09-14 15:26:12 -0400236 stream.get() << "%" << spvFixWord(words[0], endian);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100237 stream.get() << ((color) ? clr::reset() : "");
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100238 position->index++;
239 } break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100240 case SPV_OPERAND_TYPE_LITERAL_NUMBER: {
241 // NOTE: Special case for extended instruction use
242 if (OpExtInst == opcode) {
243 spv_ext_inst_desc extInst;
Lei Zhang40056702015-09-11 14:31:27 -0400244 if (spvExtInstTableValueLookup(extInstTable, *pExtInstType, words[0],
245 &extInst)) {
246 DIAGNOSTIC << "Invalid extended instruction '" << words[0] << "'.";
247 return SPV_ERROR_INVALID_BINARY;
248 }
David Neto78c3b432015-08-27 13:03:52 -0400249 spvPrependOperandTypes(extInst->operandTypes, pExpectedOperands);
Andrew Woloszyn0d350b52015-08-21 14:23:42 -0400250 stream.get() << (color ? clr::red() : "");
251 stream.get() << extInst->name;
252 stream.get() << (color ? clr::reset() : "");
Lei Zhang41bf0732015-09-14 12:26:15 -0400253 position->index++;
254 break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100255 }
Lei Zhang41bf0732015-09-14 12:26:15 -0400256 } // Fall through for the general case.
Lei Zhangb41d1502015-09-14 15:22:23 -0400257 case SPV_OPERAND_TYPE_MULTIWORD_LITERAL_NUMBER:
Lei Zhang41bf0732015-09-14 12:26:15 -0400258 case SPV_OPERAND_TYPE_LITERAL:
259 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL:
260 case SPV_OPERAND_TYPE_LITERAL_IN_OPTIONAL_TUPLE: {
261 // TODO: Need to support multiple word literals
262 stream.get() << (color ? clr::red() : "");
Lei Zhangb41d1502015-09-14 15:22:23 -0400263 if (numWords > 2) {
264 DIAGNOSTIC << "Literal numbers larger than 64-bit not supported yet.";
265 return SPV_UNSUPPORTED;
266 } else if (numWords == 2) {
267 stream.get() << spvFixDoubleWord(words[0], words[1], endian);
268 position->index += 2;
269 } else {
270 stream.get() << spvFixWord(words[0], endian);
271 position->index++;
272 }
Lei Zhang41bf0732015-09-14 12:26:15 -0400273 stream.get() << (color ? clr::reset() : "");
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100274 } break;
David Neto78c3b432015-08-27 13:03:52 -0400275 case SPV_OPERAND_TYPE_LITERAL_STRING:
276 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
Lei Zhang97afd5c2015-09-14 15:26:12 -0400277 const char *string = (const char *)words;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100278 uint64_t stringOperandCount = (strlen(string) / 4) + 1;
279
280 // NOTE: Special case for extended instruction import
281 if (OpExtInstImport == opcode) {
282 *pExtInstType = spvExtInstImportTypeGet(string);
Lei Zhang40056702015-09-11 14:31:27 -0400283 if (SPV_EXT_INST_TYPE_NONE == *pExtInstType) {
284 DIAGNOSTIC << "Invalid extended instruction import'" << string
285 << "'.";
286 return SPV_ERROR_INVALID_BINARY;
287 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100288 }
289
290 stream.get() << "\"";
291 stream.get() << (color ? clr::green() : "");
292 stream.get() << string;
293 stream.get() << (color ? clr::reset() : "");
294 stream.get() << "\"";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100295 position->index += stringOperandCount;
296 } break;
297 case SPV_OPERAND_TYPE_CAPABILITY:
298 case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
299 case SPV_OPERAND_TYPE_EXECUTION_MODEL:
300 case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
301 case SPV_OPERAND_TYPE_MEMORY_MODEL:
302 case SPV_OPERAND_TYPE_EXECUTION_MODE:
David Neto78c3b432015-08-27 13:03:52 -0400303 case SPV_OPERAND_TYPE_OPTIONAL_EXECUTION_MODE:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100304 case SPV_OPERAND_TYPE_STORAGE_CLASS:
305 case SPV_OPERAND_TYPE_DIMENSIONALITY:
306 case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
307 case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100308 case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
309 case SPV_OPERAND_TYPE_LINKAGE_TYPE:
310 case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
311 case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
312 case SPV_OPERAND_TYPE_DECORATION:
313 case SPV_OPERAND_TYPE_BUILT_IN:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100314 case SPV_OPERAND_TYPE_MEMORY_SEMANTICS:
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100315 case SPV_OPERAND_TYPE_EXECUTION_SCOPE:
316 case SPV_OPERAND_TYPE_GROUP_OPERATION:
317 case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
David Neto47994822015-08-27 13:11:01 -0400318 case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO: {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100319 spv_operand_desc entry;
Lei Zhang97afd5c2015-09-14 15:26:12 -0400320 if (spvOperandTableValueLookup(operandTable, type,
321 spvFixWord(words[0], endian), &entry)) {
Lei Zhang40056702015-09-11 14:31:27 -0400322 DIAGNOSTIC << "Invalid " << spvOperandTypeStr(type) << " operand '"
Lei Zhang97afd5c2015-09-14 15:26:12 -0400323 << words[0] << "'.";
David Neto619db262015-09-25 12:43:37 -0400324 return SPV_ERROR_INVALID_TEXT; // TODO(dneto): Surely this is invalid binary.
Lei Zhang40056702015-09-11 14:31:27 -0400325 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100326 stream.get() << entry->name;
David Neto78c3b432015-08-27 13:03:52 -0400327 // Prepare to accept operands to this operand, if needed.
328 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100329 position->index++;
330 } break;
David Neto619db262015-09-25 12:43:37 -0400331 case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
332 case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
333 case SPV_OPERAND_TYPE_LOOP_CONTROL:
334 case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
335 case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
336 case SPV_OPERAND_TYPE_SELECTION_CONTROL: {
337 // This operand is a mask.
338 // Scan it from least significant bit to most significant bit. For each
339 // set bit, emit the name of that bit and prepare to parse its operands,
340 // if any.
341 uint32_t remaining_word = spvFixWord(words[0], endian);
342 uint32_t mask;
343 int num_emitted = 0;
344 for (mask = 1; remaining_word; mask <<= 1) {
345 if (remaining_word & mask) {
346 remaining_word ^= mask;
347 spv_operand_desc entry;
348 if (spvOperandTableValueLookup(operandTable, type, mask, &entry)) {
349 DIAGNOSTIC << "Invalid " << spvOperandTypeStr(type) << " operand '"
350 << words[0] << "'.";
351 return SPV_ERROR_INVALID_BINARY;
352 }
353 if (num_emitted) stream.get() << "|";
354 stream.get() << entry->name;
355 num_emitted++;
356 }
357 }
358 if (!num_emitted) {
359 // An operand value of 0 was provided, so represent it by the name
360 // of the 0 value. In many cases, that's "None".
361 spv_operand_desc entry;
362 if (SPV_SUCCESS ==
363 spvOperandTableValueLookup(operandTable, type, 0, &entry)) {
364 stream.get() << entry->name;
365 // Prepare for its operands, if any.
366 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
367 }
368 }
369 // Prepare for subsequent operands, if any.
370 // Scan from MSB to LSB since we can only prepend operands to a pattern.
371 remaining_word = spvFixWord(words[0], endian);
372 for (mask = (1u << 31); remaining_word; mask >>= 1) {
373 if (remaining_word & mask) {
374 remaining_word ^= mask;
375 spv_operand_desc entry;
376 if (SPV_SUCCESS ==
377 spvOperandTableValueLookup(operandTable, type, mask, &entry)) {
378 spvPrependOperandTypes(entry->operandTypes, pExpectedOperands);
379 }
380 }
381 }
382 position->index++;
383 } break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100384 default: {
385 DIAGNOSTIC << "Invalid binary operand '" << type << "'";
386 return SPV_ERROR_INVALID_BINARY;
387 }
388 }
389
390 return SPV_SUCCESS;
391}
392
393spv_result_t spvBinaryDecodeOpcode(
394 spv_instruction_t *pInst, const spv_endianness_t endian,
395 const uint32_t options, const spv_opcode_table opcodeTable,
396 const spv_operand_table operandTable, const spv_ext_inst_table extInstTable,
Lei Zhang29e667e2015-09-11 11:01:59 -0400397 spv_assembly_syntax_format_t format, out_stream &stream,
398 spv_position position, spv_diagnostic *pDiagnostic) {
Lei Zhang40056702015-09-11 14:31:27 -0400399 if (!pInst || !position) return SPV_ERROR_INVALID_POINTER;
400 if (!opcodeTable || !operandTable || !extInstTable)
401 return SPV_ERROR_INVALID_TABLE;
402 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100403
David Neto78c3b432015-08-27 13:03:52 -0400404 spv_position_t instructionStart = *position;
405
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100406 uint16_t wordCount;
407 Op opcode;
408 spvOpcodeSplit(spvFixWord(pInst->words[0], endian), &wordCount, &opcode);
409
410 spv_opcode_desc opcodeEntry;
Lei Zhang40056702015-09-11 14:31:27 -0400411 if (spvOpcodeTableValueLookup(opcodeTable, opcode, &opcodeEntry)) {
412 DIAGNOSTIC << "Invalid Opcode '" << opcode << "'.";
413 return SPV_ERROR_INVALID_BINARY;
414 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100415
David Neto78c3b432015-08-27 13:03:52 -0400416 // See if there are enough required words.
417 // Some operands in the operand types are optional or could be zero length.
418 // The optional and zero length opeands must be at the end of the list.
419 if (opcodeEntry->numTypes > wordCount &&
420 !spvOperandIsOptional(opcodeEntry->operandTypes[wordCount])) {
421 uint16_t numRequired;
Lei Zhange78a7c12015-09-10 17:07:21 -0400422 for (numRequired = 0;
423 numRequired < opcodeEntry->numTypes &&
424 !spvOperandIsOptional(opcodeEntry->operandTypes[numRequired]);
425 numRequired++)
David Neto78c3b432015-08-27 13:03:52 -0400426 ;
427 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
Lei Zhange78a7c12015-09-10 17:07:21 -0400428 << " word count '" << wordCount << "', expected at least '"
429 << numRequired << "'.";
David Neto78c3b432015-08-27 13:03:52 -0400430 return SPV_ERROR_INVALID_BINARY;
431 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100432
Lei Zhang29e667e2015-09-11 11:01:59 -0400433 const bool isAssigmentFormat =
434 SPV_ASSEMBLY_SYNTAX_FORMAT_ASSIGNMENT == format;
435
436 // For Canonical Assembly Format, all words are written to stream in order.
437 // For Assignment Assembly Format, <result-id> and the equal sign are written
438 // to stream first, while the rest are written to no_result_id_stream. After
439 // processing all words, all words in no_result_id_stream are transcribed to
440 // stream.
441
Lei Zhang8a375202015-08-24 15:52:26 -0400442 std::stringstream no_result_id_strstream;
443 out_stream no_result_id_stream(no_result_id_strstream);
Lei Zhang29e667e2015-09-11 11:01:59 -0400444 (isAssigmentFormat ? no_result_id_stream.get() : stream.get())
445 << "Op" << opcodeEntry->name;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100446
Lei Zhang29e667e2015-09-11 11:01:59 -0400447 const int16_t result_id_index = spvOpcodeResultIdIndex(opcodeEntry);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100448 position->index++;
449
David Neto78c3b432015-08-27 13:03:52 -0400450 // Maintains the ordered list of expected operand types.
451 // For many instructions we only need the {numTypes, operandTypes}
452 // entries in opcodeEntry. However, sometimes we need to modify
453 // the list as we parse the operands. This occurs when an operand
454 // has its own logical operands (such as the LocalSize operand for
455 // ExecutionMode), or for extended instructions that may have their
456 // own operands depending on the selected extended instruction.
457 spv_operand_pattern_t expectedOperands(
458 opcodeEntry->operandTypes,
459 opcodeEntry->operandTypes + opcodeEntry->numTypes);
460
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100461 for (uint16_t index = 1; index < wordCount; ++index) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100462 const uint64_t currentPosIndex = position->index;
Lei Zhang29e667e2015-09-11 11:01:59 -0400463 const bool currentIsResultId = result_id_index == index - 1;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100464
Lei Zhang40056702015-09-11 14:31:27 -0400465 if (expectedOperands.empty()) {
466 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
467 << " starting at word " << instructionStart.index
468 << ": expected no more operands after " << index
469 << " words, but word count is " << wordCount << ".";
470 return SPV_ERROR_INVALID_BINARY;
471 }
David Neto78c3b432015-08-27 13:03:52 -0400472
473 spv_operand_type_t type = spvTakeFirstMatchableOperand(&expectedOperands);
474
Lei Zhang29e667e2015-09-11 11:01:59 -0400475 if (isAssigmentFormat) {
476 if (!currentIsResultId) no_result_id_stream.get() << " ";
477 } else {
478 stream.get() << " ";
479 }
Lei Zhangb41d1502015-09-14 15:22:23 -0400480
481 uint16_t numWords = 1;
482 if (type == SPV_OPERAND_TYPE_MULTIWORD_LITERAL_NUMBER) {
483 // Make sure this is the last operand for this instruction.
484 if (expectedOperands.empty()) {
485 numWords = wordCount - index;
486 } else {
487 // TODO(antiagainst): This may not be an error. The exact design has not
488 // been settled yet.
489 DIAGNOSTIC << "Multiple word literal numbers can only appear as the "
490 "last operand of an instruction.";
491 return SPV_ERROR_INVALID_BINARY;
492 }
493 }
494
Lei Zhang40056702015-09-11 14:31:27 -0400495 if (spvBinaryDecodeOperand(
Lei Zhangb41d1502015-09-14 15:22:23 -0400496 opcodeEntry->opcode, type, pInst->words + index, numWords, endian,
497 options, operandTable, extInstTable, &expectedOperands,
498 &pInst->extInstType,
Lei Zhang29e667e2015-09-11 11:01:59 -0400499 (isAssigmentFormat && !currentIsResultId ? no_result_id_stream
500 : stream),
Lei Zhang40056702015-09-11 14:31:27 -0400501 position, pDiagnostic)) {
502 DIAGNOSTIC << "UNEXPLAINED ERROR";
503 return SPV_ERROR_INVALID_BINARY;
504 }
Lei Zhang29e667e2015-09-11 11:01:59 -0400505 if (isAssigmentFormat && currentIsResultId) stream.get() << " = ";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100506 index += (uint16_t)(position->index - currentPosIndex - 1);
507 }
David Neto78c3b432015-08-27 13:03:52 -0400508 // TODO(dneto): There's an opportunity for a more informative message.
Lei Zhang40056702015-09-11 14:31:27 -0400509 if (!expectedOperands.empty() &&
510 !spvOperandIsOptional(expectedOperands.front())) {
511 DIAGNOSTIC << "Invalid instruction Op" << opcodeEntry->name
512 << " starting at word " << instructionStart.index
513 << ": expected more operands after " << wordCount << " words.";
514 return SPV_ERROR_INVALID_BINARY;
515 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100516
Lei Zhang8a375202015-08-24 15:52:26 -0400517 stream.get() << no_result_id_strstream.str();
518
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100519 return SPV_SUCCESS;
520}
521
Lei Zhange78a7c12015-09-10 17:07:21 -0400522spv_result_t spvBinaryToText(uint32_t *code, const uint64_t wordCount,
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400523 const uint32_t options,
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100524 const spv_opcode_table opcodeTable,
525 const spv_operand_table operandTable,
526 const spv_ext_inst_table extInstTable,
527 spv_text *pText, spv_diagnostic *pDiagnostic) {
Lei Zhang29e667e2015-09-11 11:01:59 -0400528 return spvBinaryToTextWithFormat(
529 code, wordCount, options, opcodeTable, operandTable, extInstTable,
530 SPV_ASSEMBLY_SYNTAX_FORMAT_DEFAULT, pText, pDiagnostic);
531}
532
533spv_result_t spvBinaryToTextWithFormat(
534 uint32_t *code, const uint64_t wordCount, const uint32_t options,
535 const spv_opcode_table opcodeTable, const spv_operand_table operandTable,
536 const spv_ext_inst_table extInstTable, spv_assembly_syntax_format_t format,
537 spv_text *pText, spv_diagnostic *pDiagnostic) {
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400538 spv_binary_t binary = {code, wordCount};
539
Andrew Woloszyn4b4acde2015-09-10 10:28:22 -0400540 spv_position_t position = {};
Lei Zhang40056702015-09-11 14:31:27 -0400541 if (!binary.code || !binary.wordCount) {
542 DIAGNOSTIC << "Binary stream is empty.";
543 return SPV_ERROR_INVALID_BINARY;
544 }
545 if (!opcodeTable || !operandTable || !extInstTable)
546 return SPV_ERROR_INVALID_TABLE;
547 if (pText && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options))
548 return SPV_ERROR_INVALID_POINTER;
549 if (!pText && !spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options))
550 return SPV_ERROR_INVALID_POINTER;
551 if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100552
553 spv_endianness_t endian;
Lei Zhang40056702015-09-11 14:31:27 -0400554 if (spvBinaryEndianness(&binary, &endian)) {
555 DIAGNOSTIC << "Invalid SPIR-V magic number '" << std::hex << binary.code[0]
556 << "'.";
557 return SPV_ERROR_INVALID_BINARY;
558 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100559
560 spv_header_t header;
Lei Zhang40056702015-09-11 14:31:27 -0400561 if (spvBinaryHeaderGet(&binary, endian, &header)) {
562 DIAGNOSTIC << "Invalid SPIR-V header.";
563 return SPV_ERROR_INVALID_BINARY;
564 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100565
566 bool print = spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options);
567 bool color =
568 print && spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COLOR, options);
569
570 std::stringstream sstream;
571 out_stream stream(sstream);
572 if (print) {
573 stream = out_stream();
574 }
575
576 if (color) {
577 stream.get() << clr::grey();
578 }
579 stream.get() << "; SPIR-V\n"
580 << "; Version: " << header.version << "\n"
581 << "; Generator: " << spvGeneratorStr(header.generator) << "\n"
582 << "; Bound: " << header.bound << "\n"
583 << "; Schema: " << header.schema << "\n";
584 if (color) {
585 stream.get() << clr::reset();
586 }
587
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400588 const uint32_t *words = binary.code;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100589 position.index = SPV_INDEX_INSTRUCTION;
590 spv_ext_inst_type_t extInstType = SPV_EXT_INST_TYPE_NONE;
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400591 while (position.index < binary.wordCount) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100592 uint64_t index = position.index;
593 uint16_t wordCount;
594 Op opcode;
595 spvOpcodeSplit(spvFixWord(words[position.index], endian), &wordCount,
596 &opcode);
597
598 spv_instruction_t inst = {};
599 inst.extInstType = extInstType;
600 spvInstructionCopy(&words[position.index], opcode, wordCount, endian,
601 &inst);
602
Lei Zhang40056702015-09-11 14:31:27 -0400603 if (spvBinaryDecodeOpcode(&inst, endian, options, opcodeTable, operandTable,
604 extInstTable, format, stream, &position,
605 pDiagnostic))
606 return SPV_ERROR_INVALID_BINARY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100607 extInstType = inst.extInstType;
608
Lei Zhang40056702015-09-11 14:31:27 -0400609 if ((index + wordCount) != position.index) {
610 DIAGNOSTIC << "Invalid word count.";
611 return SPV_ERROR_INVALID_BINARY;
612 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100613
614 stream.get() << "\n";
615 }
616
617 if (!print) {
618 size_t length = sstream.str().size();
619 char *str = new char[length + 1];
Lei Zhang40056702015-09-11 14:31:27 -0400620 if (!str) return SPV_ERROR_OUT_OF_MEMORY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100621 strncpy(str, sstream.str().c_str(), length + 1);
622 spv_text text = new spv_text_t();
Lei Zhang40056702015-09-11 14:31:27 -0400623 if (!text) return SPV_ERROR_OUT_OF_MEMORY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100624 text->str = str;
625 text->length = length;
626 *pText = text;
627 }
628
629 return SPV_SUCCESS;
630}
631
632void spvBinaryDestroy(spv_binary binary) {
Lei Zhang40056702015-09-11 14:31:27 -0400633 if (!binary) return;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100634 if (binary->code) {
635 delete[] binary->code;
636 }
637 delete binary;
638}