blob: 5b51845c74c4c2c3c07723b2c5f5e5110d6294f6 [file] [log] [blame]
Dejan Mircevskib6fe02f2016-01-07 13:44:22 -05001// Copyright (c) 2015-2016 The Khronos Group Inc.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +01002//
David Neto9fc86582016-09-01 15:33:59 -04003// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +01006//
David Neto9fc86582016-09-01 15:33:59 -04007// http://www.apache.org/licenses/LICENSE-2.0
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +01008//
David Neto9fc86582016-09-01 15:33:59 -04009// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010014
dan sinclaireda2cfb2018-08-03 15:06:09 -040015#include "source/text.h"
David Neto36b0c0f2015-09-16 18:32:54 -040016
Dejan Mircevskiba569fb2015-09-11 16:34:49 -040017#include <algorithm>
18#include <cassert>
Andrew Woloszyn13804e52015-09-22 15:50:33 -040019#include <cctype>
Dejan Mircevskiba569fb2015-09-11 16:34:49 -040020#include <cstdio>
21#include <cstdlib>
David Neto36b0c0f2015-09-16 18:32:54 -040022#include <cstring>
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040023#include <memory>
dan sinclaireda2cfb2018-08-03 15:06:09 -040024#include <set>
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040025#include <sstream>
David Neto201caf72015-11-04 17:38:17 -050026#include <string>
David Neto36b0c0f2015-09-16 18:32:54 -040027#include <unordered_map>
dan sinclaireda2cfb2018-08-03 15:06:09 -040028#include <utility>
David Neto36b0c0f2015-09-16 18:32:54 -040029#include <vector>
Dejan Mircevskiba569fb2015-09-11 16:34:49 -040030
dan sinclaireda2cfb2018-08-03 15:06:09 -040031#include "source/assembly_grammar.h"
32#include "source/binary.h"
33#include "source/diagnostic.h"
34#include "source/ext_inst.h"
35#include "source/instruction.h"
dan sinclaireda2cfb2018-08-03 15:06:09 -040036#include "source/opcode.h"
37#include "source/operand.h"
38#include "source/spirv_constant.h"
39#include "source/spirv_target_env.h"
40#include "source/table.h"
41#include "source/text_handler.h"
42#include "source/util/bitutils.h"
43#include "source/util/parse_number.h"
David Neto5a703352016-02-17 14:44:00 -050044#include "spirv-tools/libspirv.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010045
Andrew Woloszyn13804e52015-09-22 15:50:33 -040046bool spvIsValidIDCharacter(const char value) {
47 return value == '_' || 0 != ::isalnum(value);
48}
49
50// Returns true if the given string represents a valid ID name.
Dejan Mircevski14c4b102015-09-29 17:07:21 -040051bool spvIsValidID(const char* textValue) {
52 const char* c = textValue;
Andrew Woloszyn13804e52015-09-22 15:50:33 -040053 for (; *c != '\0'; ++c) {
54 if (!spvIsValidIDCharacter(*c)) {
55 return false;
56 }
57 }
58 // If the string was empty, then the ID also is not valid.
59 return c != textValue;
60}
61
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040062// Text API
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010063
Dejan Mircevski903f9d62015-09-28 17:04:39 -040064spv_result_t spvTextToLiteral(const char* textValue, spv_literal_t* pLiteral) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010065 bool isSigned = false;
David Netoaffa6962015-08-24 15:33:14 -040066 int numPeriods = 0;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010067 bool isString = false;
68
David Netoaffa6962015-08-24 15:33:14 -040069 const size_t len = strlen(textValue);
David Neto98290a22015-08-24 16:27:02 -040070 if (len == 0) return SPV_FAILED_MATCH;
71
David Netoaffa6962015-08-24 15:33:14 -040072 for (uint64_t index = 0; index < len; ++index) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010073 switch (textValue[index]) {
74 case '0':
75 case '1':
76 case '2':
77 case '3':
78 case '4':
79 case '5':
80 case '6':
81 case '7':
82 case '8':
83 case '9':
84 break;
85 case '.':
David Netoaffa6962015-08-24 15:33:14 -040086 numPeriods++;
87 break;
88 case '-':
89 if (index == 0) {
90 isSigned = true;
91 } else {
92 isString = true;
93 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010094 break;
95 default:
96 isString = true;
Lei Zhange78a7c12015-09-10 17:07:21 -040097 index = len; // break out of the loop too.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010098 break;
99 }
100 }
101
David Netoaffa6962015-08-24 15:33:14 -0400102 pLiteral->type = spv_literal_type_t(99);
103
Lei Zhange78a7c12015-09-10 17:07:21 -0400104 if (isString || numPeriods > 1 || (isSigned && len == 1)) {
David Neto98290a22015-08-24 16:27:02 -0400105 if (len < 2 || textValue[0] != '"' || textValue[len - 1] != '"')
106 return SPV_FAILED_MATCH;
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400107 bool escaping = false;
Lei Zhang6483bd72015-10-14 17:02:39 -0400108 for (const char* val = textValue + 1; val != textValue + len - 1; ++val) {
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400109 if ((*val == '\\') && (!escaping)) {
110 escaping = true;
111 } else {
112 // Have to save space for the null-terminator
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500113 if (pLiteral->str.size() >= SPV_LIMIT_LITERAL_STRING_BYTES_MAX)
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400114 return SPV_ERROR_OUT_OF_MEMORY;
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500115 pLiteral->str.push_back(*val);
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400116 escaping = false;
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400117 }
118 }
119
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100120 pLiteral->type = SPV_LITERAL_TYPE_STRING;
David Netoaffa6962015-08-24 15:33:14 -0400121 } else if (numPeriods == 1) {
122 double d = std::strtod(textValue, nullptr);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100123 float f = (float)d;
124 if (d == (double)f) {
125 pLiteral->type = SPV_LITERAL_TYPE_FLOAT_32;
126 pLiteral->value.f = f;
127 } else {
128 pLiteral->type = SPV_LITERAL_TYPE_FLOAT_64;
129 pLiteral->value.d = d;
130 }
131 } else if (isSigned) {
132 int64_t i64 = strtoll(textValue, nullptr, 10);
133 int32_t i32 = (int32_t)i64;
134 if (i64 == (int64_t)i32) {
135 pLiteral->type = SPV_LITERAL_TYPE_INT_32;
136 pLiteral->value.i32 = i32;
137 } else {
138 pLiteral->type = SPV_LITERAL_TYPE_INT_64;
139 pLiteral->value.i64 = i64;
140 }
141 } else {
142 uint64_t u64 = strtoull(textValue, nullptr, 10);
143 uint32_t u32 = (uint32_t)u64;
144 if (u64 == (uint64_t)u32) {
145 pLiteral->type = SPV_LITERAL_TYPE_UINT_32;
146 pLiteral->value.u32 = u32;
147 } else {
148 pLiteral->type = SPV_LITERAL_TYPE_UINT_64;
149 pLiteral->value.u64 = u64;
150 }
151 }
152
153 return SPV_SUCCESS;
154}
155
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400156namespace {
157
158/// Parses an immediate integer from text, guarding against overflow. If
159/// successful, adds the parsed value to pInst, advances the context past it,
160/// and returns SPV_SUCCESS. Otherwise, leaves pInst alone, emits diagnostics,
161/// and returns SPV_ERROR_INVALID_TEXT.
dan sinclair3dad1cd2018-07-07 09:38:00 -0400162spv_result_t encodeImmediate(spvtools::AssemblyContext* context,
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400163 const char* text, spv_instruction_t* pInst) {
164 assert(*text == '!');
David Neto78e677b2015-10-05 13:28:46 -0400165 uint32_t parse_result;
dan sinclair76e0bde2018-07-06 13:25:17 -0400166 if (!spvtools::utils::ParseNumber(text + 1, &parse_result)) {
qining1773b952016-09-01 14:27:04 -0400167 return context->diagnostic(SPV_ERROR_INVALID_TEXT)
168 << "Invalid immediate integer: !" << text + 1;
169 }
David Neto78e677b2015-10-05 13:28:46 -0400170 context->binaryEncodeU32(parse_result, pInst);
Ben Vanik01c8d7a2015-11-22 08:32:53 -0800171 context->seekForward(static_cast<uint32_t>(strlen(text)));
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400172 return SPV_SUCCESS;
173}
174
175} // anonymous namespace
176
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400177/// @brief Translate an Opcode operand to binary form
178///
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400179/// @param[in] grammar the grammar to use for compilation
180/// @param[in, out] context the dynamic compilation info
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400181/// @param[in] type of the operand
182/// @param[in] textValue word of text to be parsed
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400183/// @param[out] pInst return binary Opcode
184/// @param[in,out] pExpectedOperands the operand types expected
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400185///
186/// @return result code
dan sinclair3dad1cd2018-07-07 09:38:00 -0400187spv_result_t spvTextEncodeOperand(const spvtools::AssemblyGrammar& grammar,
188 spvtools::AssemblyContext* context,
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400189 const spv_operand_type_t type,
190 const char* textValue,
191 spv_instruction_t* pInst,
192 spv_operand_pattern_t* pExpectedOperands) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100193 // NOTE: Handle immediate int in the stream
194 if ('!' == textValue[0]) {
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400195 if (auto error = encodeImmediate(context, textValue, pInst)) {
196 return error;
Lei Zhang40056702015-09-11 14:31:27 -0400197 }
Dejan Mircevski897bff92015-09-29 10:38:18 -0400198 *pExpectedOperands =
199 spvAlternatePatternFollowingImmediate(*pExpectedOperands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100200 return SPV_SUCCESS;
201 }
202
David Neto51013d12015-10-14 11:31:51 -0400203 // Optional literal operands can fail to parse. In that case use
204 // SPV_FAILED_MATCH to avoid emitting a diagostic. Use the following
205 // for those situations.
206 spv_result_t error_code_for_literals =
207 spvOperandIsOptional(type) ? SPV_FAILED_MATCH : SPV_ERROR_INVALID_TEXT;
208
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100209 switch (type) {
David Netoe3f70b92015-08-27 13:50:05 -0400210 case SPV_OPERAND_TYPE_ID:
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400211 case SPV_OPERAND_TYPE_TYPE_ID:
David Neto201caf72015-11-04 17:38:17 -0500212 case SPV_OPERAND_TYPE_RESULT_ID:
213 case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
214 case SPV_OPERAND_TYPE_SCOPE_ID:
215 case SPV_OPERAND_TYPE_OPTIONAL_ID: {
Lei Zhangabafd5e2015-08-21 11:52:29 -0400216 if ('%' == textValue[0]) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100217 textValue++;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100218 } else {
David Netoac508b02015-10-09 15:48:09 -0400219 return context->diagnostic() << "Expected id to start with %.";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100220 }
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400221 if (!spvIsValidID(textValue)) {
David Netoac508b02015-10-09 15:48:09 -0400222 return context->diagnostic() << "Invalid ID " << textValue;
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400223 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400224 const uint32_t id = context->spvNamedIdAssignOrGet(textValue);
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400225 if (type == SPV_OPERAND_TYPE_TYPE_ID) pInst->resultTypeId = id;
David Netob5dc8fc2015-10-06 16:22:00 -0400226 spvInstructionAddWord(pInst, id);
David Neto2ae4a682015-11-09 18:55:42 -0500227
228 // Set the extended instruction type.
229 // The import set id is the 3rd operand of OpExtInst.
230 if (pInst->opcode == SpvOpExtInst && pInst->words.size() == 4) {
231 auto ext_inst_type = context->getExtInstTypeForId(pInst->words[3]);
232 if (ext_inst_type == SPV_EXT_INST_TYPE_NONE) {
233 return context->diagnostic()
234 << "Invalid extended instruction import Id "
235 << pInst->words[2];
236 }
237 pInst->extInstType = ext_inst_type;
238 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100239 } break;
David Neto201caf72015-11-04 17:38:17 -0500240
David Neto445ce442015-10-15 15:22:06 -0400241 case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
242 // The assembler accepts the symbolic name for an extended instruction,
243 // and emits its corresponding number.
244 spv_ext_inst_desc extInst;
245 if (grammar.lookupExtInst(pInst->extInstType, textValue, &extInst)) {
Diego Novillod2938e42017-11-08 12:40:02 -0500246 return context->diagnostic()
247 << "Invalid extended instruction name '" << textValue << "'.";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100248 }
David Neto445ce442015-10-15 15:22:06 -0400249 spvInstructionAddWord(pInst, extInst->ext_inst);
250
251 // Prepare to parse the operands for the extended instructions.
Chris Forbes78338d52017-06-27 16:28:22 -0700252 spvPushOperandTypes(extInst->operandTypes, pExpectedOperands);
David Neto0f166be2015-11-11 01:56:49 -0500253 } break;
David Neto445ce442015-10-15 15:22:06 -0400254
David Neto0f166be2015-11-11 01:56:49 -0500255 case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: {
256 // The assembler accepts the symbolic name for the opcode, but without
257 // the "Op" prefix. For example, "IAdd" is accepted. The number
258 // of the opcode is emitted.
259 SpvOp opcode;
260 if (grammar.lookupSpecConstantOpcode(textValue, &opcode)) {
261 return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
262 << " '" << textValue << "'.";
263 }
264 spv_opcode_desc opcodeEntry = nullptr;
265 if (grammar.lookupOpcode(opcode, &opcodeEntry)) {
266 return context->diagnostic(SPV_ERROR_INTERNAL)
267 << "OpSpecConstant opcode table out of sync";
268 }
269 spvInstructionAddWord(pInst, uint32_t(opcodeEntry->opcode));
270
271 // Prepare to parse the operands for the opcode. Except skip the
272 // type Id and result Id, since they've already been processed.
273 assert(opcodeEntry->hasType);
274 assert(opcodeEntry->hasResult);
275 assert(opcodeEntry->numTypes >= 2);
Chris Forbes78338d52017-06-27 16:28:22 -0700276 spvPushOperandTypes(opcodeEntry->operandTypes + 2, pExpectedOperands);
David Neto445ce442015-10-15 15:22:06 -0400277 } break;
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400278
David Neto201caf72015-11-04 17:38:17 -0500279 case SPV_OPERAND_TYPE_LITERAL_INTEGER:
280 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER: {
281 // The current operand is an *unsigned* 32-bit integer.
282 // That's just how the grammar works.
dan sinclair3dad1cd2018-07-07 09:38:00 -0400283 spvtools::IdType expected_type = {
284 32, false, spvtools::IdTypeClass::kScalarIntegerType};
David Neto78e677b2015-10-05 13:28:46 -0400285 if (auto error = context->binaryEncodeNumericLiteral(
David Neto51013d12015-10-14 11:31:51 -0400286 textValue, error_code_for_literals, expected_type, pInst)) {
David Neto78e677b2015-10-05 13:28:46 -0400287 return error;
David Neto51013d12015-10-14 11:31:51 -0400288 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100289 } break;
David Neto201caf72015-11-04 17:38:17 -0500290
291 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_NUMBER:
292 // This is a context-independent literal number which can be a 32-bit
293 // number of floating point value.
294 if (auto error = context->binaryEncodeNumericLiteral(
dan sinclair3dad1cd2018-07-07 09:38:00 -0400295 textValue, error_code_for_literals, spvtools::kUnknownType,
David Neto201caf72015-11-04 17:38:17 -0500296 pInst)) {
297 return error;
298 }
299 break;
300
301 case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER:
302 case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER: {
dan sinclair3dad1cd2018-07-07 09:38:00 -0400303 spvtools::IdType expected_type = spvtools::kUnknownType;
David Neto201caf72015-11-04 17:38:17 -0500304 // The encoding for OpConstant, OpSpecConstant and OpSwitch all
305 // depend on either their own result-id or the result-id of
306 // one of their parameters.
307 if (SpvOpConstant == pInst->opcode ||
308 SpvOpSpecConstant == pInst->opcode) {
309 // The type of the literal is determined by the type Id of the
310 // instruction.
311 expected_type =
312 context->getTypeOfTypeGeneratingValue(pInst->resultTypeId);
dan sinclair3dad1cd2018-07-07 09:38:00 -0400313 if (!spvtools::isScalarFloating(expected_type) &&
314 !spvtools::isScalarIntegral(expected_type)) {
David Neto201caf72015-11-04 17:38:17 -0500315 spv_opcode_desc d;
316 const char* opcode_name = "opcode";
317 if (SPV_SUCCESS == grammar.lookupOpcode(pInst->opcode, &d)) {
318 opcode_name = d->name;
319 }
320 return context->diagnostic()
321 << "Type for " << opcode_name
322 << " must be a scalar floating point or integer type";
323 }
324 } else if (pInst->opcode == SpvOpSwitch) {
325 // The type of the literal is the same as the type of the selector.
326 expected_type = context->getTypeOfValueInstruction(pInst->words[1]);
dan sinclair3dad1cd2018-07-07 09:38:00 -0400327 if (!spvtools::isScalarIntegral(expected_type)) {
David Neto201caf72015-11-04 17:38:17 -0500328 return context->diagnostic()
329 << "The selector operand for OpSwitch must be the result"
330 " of an instruction that generates an integer scalar";
331 }
332 }
333 if (auto error = context->binaryEncodeNumericLiteral(
334 textValue, error_code_for_literals, expected_type, pInst)) {
335 return error;
336 }
337 } break;
338
David Neto78c3b432015-08-27 13:03:52 -0400339 case SPV_OPERAND_TYPE_LITERAL_STRING:
340 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
Lei Zhang6d415812015-09-15 13:36:21 -0400341 spv_literal_t literal = {};
342 spv_result_t error = spvTextToLiteral(textValue, &literal);
343 if (error != SPV_SUCCESS) {
344 if (error == SPV_ERROR_OUT_OF_MEMORY) return error;
David Neto51013d12015-10-14 11:31:51 -0400345 return context->diagnostic(error_code_for_literals)
346 << "Invalid literal string '" << textValue << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400347 }
Lei Zhang6d415812015-09-15 13:36:21 -0400348 if (literal.type != SPV_LITERAL_TYPE_STRING) {
David Neto51013d12015-10-14 11:31:51 -0400349 return context->diagnostic()
David Netoac508b02015-10-09 15:48:09 -0400350 << "Expected literal string, found literal number '" << textValue
351 << "'.";
Lei Zhang6d415812015-09-15 13:36:21 -0400352 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100353
354 // NOTE: Special case for extended instruction library import
Lei Zhangb36e7042015-10-28 13:40:52 -0400355 if (SpvOpExtInstImport == pInst->opcode) {
David Neto2ae4a682015-11-09 18:55:42 -0500356 const spv_ext_inst_type_t ext_inst_type =
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500357 spvExtInstImportTypeGet(literal.str.c_str());
David Neto2ae4a682015-11-09 18:55:42 -0500358 if (SPV_EXT_INST_TYPE_NONE == ext_inst_type) {
359 return context->diagnostic()
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500360 << "Invalid extended instruction import '" << literal.str
David Neto2ae4a682015-11-09 18:55:42 -0500361 << "'";
362 }
David Neto677e0c72016-01-05 14:56:02 -0500363 if ((error = context->recordIdAsExtInstImport(pInst->words[1],
364 ext_inst_type)))
David Neto2ae4a682015-11-09 18:55:42 -0500365 return error;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100366 }
367
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500368 if (context->binaryEncodeString(literal.str.c_str(), pInst))
Lei Zhang40056702015-09-11 14:31:27 -0400369 return SPV_ERROR_INVALID_TEXT;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100370 } break;
David Neto59de6102017-12-03 12:30:08 -0500371
372 // Masks.
David Neto36b0c0f2015-09-16 18:32:54 -0400373 case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
374 case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
375 case SPV_OPERAND_TYPE_LOOP_CONTROL:
David Neto2889a0c2016-02-15 13:50:00 -0500376 case SPV_OPERAND_TYPE_IMAGE:
David Netoee1b3bb2015-09-18 11:19:18 -0400377 case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
David Neto5bf88fc2015-09-17 17:06:10 -0400378 case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
David Neto59de6102017-12-03 12:30:08 -0500379 case SPV_OPERAND_TYPE_SELECTION_CONTROL:
380 case SPV_OPERAND_TYPE_DEBUG_INFO_FLAGS: {
David Neto36b0c0f2015-09-16 18:32:54 -0400381 uint32_t value;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400382 if (grammar.parseMaskOperand(type, textValue, &value)) {
David Netoac508b02015-10-09 15:48:09 -0400383 return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
David Netod9ad0502015-11-24 18:37:24 -0500384 << " operand '" << textValue << "'.";
David Neto36b0c0f2015-09-16 18:32:54 -0400385 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400386 if (auto error = context->binaryEncodeU32(value, pInst)) return error;
David Neto5bf88fc2015-09-17 17:06:10 -0400387 // Prepare to parse the operands for this logical operand.
Chris Forbes78338d52017-06-27 16:28:22 -0700388 grammar.pushOperandTypesForMask(type, value, pExpectedOperands);
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400389 } break;
390 case SPV_OPERAND_TYPE_OPTIONAL_CIV: {
391 auto error = spvTextEncodeOperand(
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400392 grammar, context, SPV_OPERAND_TYPE_OPTIONAL_LITERAL_NUMBER, textValue,
393 pInst, pExpectedOperands);
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400394 if (error == SPV_FAILED_MATCH) {
395 // It's not a literal number -- is it a literal string?
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400396 error = spvTextEncodeOperand(grammar, context,
397 SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING,
398 textValue, pInst, pExpectedOperands);
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400399 }
400 if (error == SPV_FAILED_MATCH) {
401 // It's not a literal -- is it an ID?
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400402 error =
403 spvTextEncodeOperand(grammar, context, SPV_OPERAND_TYPE_OPTIONAL_ID,
404 textValue, pInst, pExpectedOperands);
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400405 }
406 if (error) {
David Netoac508b02015-10-09 15:48:09 -0400407 return context->diagnostic(error)
408 << "Invalid word following !<integer>: " << textValue;
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400409 }
410 if (pExpectedOperands->empty()) {
411 pExpectedOperands->push_back(SPV_OPERAND_TYPE_OPTIONAL_CIV);
412 }
David Neto36b0c0f2015-09-16 18:32:54 -0400413 } break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100414 default: {
415 // NOTE: All non literal operands are handled here using the operand
416 // table.
417 spv_operand_desc entry;
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400418 if (grammar.lookupOperand(type, textValue, strlen(textValue), &entry)) {
David Netoac508b02015-10-09 15:48:09 -0400419 return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
420 << " '" << textValue << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400421 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400422 if (context->binaryEncodeU32(entry->value, pInst)) {
David Netoac508b02015-10-09 15:48:09 -0400423 return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
424 << " '" << textValue << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400425 }
David Neto78c3b432015-08-27 13:03:52 -0400426
427 // Prepare to parse the operands for this logical operand.
Chris Forbes78338d52017-06-27 16:28:22 -0700428 spvPushOperandTypes(entry->operandTypes, pExpectedOperands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100429 } break;
430 }
431 return SPV_SUCCESS;
432}
433
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400434namespace {
435
436/// Encodes an instruction started by !<integer> at the given position in text.
437///
438/// Puts the encoded words into *pInst. If successful, moves position past the
439/// instruction and returns SPV_SUCCESS. Otherwise, returns an error code and
440/// leaves position pointing to the error in text.
441spv_result_t encodeInstructionStartingWithImmediate(
dan sinclair3dad1cd2018-07-07 09:38:00 -0400442 const spvtools::AssemblyGrammar& grammar,
443 spvtools::AssemblyContext* context, spv_instruction_t* pInst) {
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400444 std::string firstWord;
445 spv_position_t nextPosition = {};
Lei Zhang6032b982016-03-15 16:52:40 -0400446 auto error = context->getWord(&firstWord, &nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400447 if (error) return context->diagnostic(error) << "Internal Error";
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400448
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400449 if ((error = encodeImmediate(context, firstWord.c_str(), pInst))) {
450 return error;
Lei Zhang40056702015-09-11 14:31:27 -0400451 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400452 while (context->advance() != SPV_END_OF_STREAM) {
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400453 // A beginning of a new instruction means we're done.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400454 if (context->isStartOfNewInst()) return SPV_SUCCESS;
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400455
456 // Otherwise, there must be an operand that's either a literal, an ID, or
457 // an immediate.
458 std::string operandValue;
Lei Zhang6032b982016-03-15 16:52:40 -0400459 if ((error = context->getWord(&operandValue, &nextPosition)))
David Netoac508b02015-10-09 15:48:09 -0400460 return context->diagnostic(error) << "Internal Error";
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400461
David Netoac508b02015-10-09 15:48:09 -0400462 if (operandValue == "=")
463 return context->diagnostic() << firstWord << " not allowed before =.";
Dejan Mircevskie3a19c02015-09-11 15:03:54 -0400464
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400465 // Needed to pass to spvTextEncodeOpcode(), but it shouldn't ever be
466 // expanded.
467 spv_operand_pattern_t dummyExpectedOperands;
468 error = spvTextEncodeOperand(
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400469 grammar, context, SPV_OPERAND_TYPE_OPTIONAL_CIV, operandValue.c_str(),
470 pInst, &dummyExpectedOperands);
Lei Zhang40056702015-09-11 14:31:27 -0400471 if (error) return error;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400472 context->setPosition(nextPosition);
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400473 }
474 return SPV_SUCCESS;
475}
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400476
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400477/// @brief Translate single Opcode and operands to binary form
478///
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400479/// @param[in] grammar the grammar to use for compilation
480/// @param[in, out] context the dynamic compilation info
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400481/// @param[in] text stream to translate
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400482/// @param[out] pInst returned binary Opcode
483/// @param[in,out] pPosition in the text stream
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400484///
485/// @return result code
dan sinclair3dad1cd2018-07-07 09:38:00 -0400486spv_result_t spvTextEncodeOpcode(const spvtools::AssemblyGrammar& grammar,
487 spvtools::AssemblyContext* context,
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400488 spv_instruction_t* pInst) {
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400489 // Check for !<integer> first.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400490 if ('!' == context->peek()) {
491 return encodeInstructionStartingWithImmediate(grammar, context, pInst);
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400492 }
493
Lei Zhang06efdc52015-09-10 14:00:00 -0400494 std::string firstWord;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100495 spv_position_t nextPosition = {};
Lei Zhang6032b982016-03-15 16:52:40 -0400496 spv_result_t error = context->getWord(&firstWord, &nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400497 if (error) return context->diagnostic() << "Internal Error";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100498
Lei Zhang06efdc52015-09-10 14:00:00 -0400499 std::string opcodeName;
Lei Zhangdfc50082015-08-21 11:50:55 -0400500 std::string result_id;
501 spv_position_t result_id_position = {};
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400502 if (context->startsWithOp()) {
Lei Zhang06efdc52015-09-10 14:00:00 -0400503 opcodeName = firstWord;
504 } else {
Lei Zhang06efdc52015-09-10 14:00:00 -0400505 result_id = firstWord;
Lei Zhang40056702015-09-11 14:31:27 -0400506 if ('%' != result_id.front()) {
David Netoac508b02015-10-09 15:48:09 -0400507 return context->diagnostic()
508 << "Expected <opcode> or <result-id> at the beginning "
509 "of an instruction, found '"
510 << result_id << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400511 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400512 result_id_position = context->position();
Lei Zhang06efdc52015-09-10 14:00:00 -0400513
514 // The '=' sign.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400515 context->setPosition(nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400516 if (context->advance())
517 return context->diagnostic() << "Expected '=', found end of stream.";
Lei Zhangdfc50082015-08-21 11:50:55 -0400518 std::string equal_sign;
Lei Zhang6032b982016-03-15 16:52:40 -0400519 error = context->getWord(&equal_sign, &nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400520 if ("=" != equal_sign)
521 return context->diagnostic() << "'=' expected after result id.";
Lei Zhangdfc50082015-08-21 11:50:55 -0400522
523 // The <opcode> after the '=' sign.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400524 context->setPosition(nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400525 if (context->advance())
526 return context->diagnostic() << "Expected opcode, found end of stream.";
Lei Zhang6032b982016-03-15 16:52:40 -0400527 error = context->getWord(&opcodeName, &nextPosition);
Lei Zhang6483bd72015-10-14 17:02:39 -0400528 if (error) return context->diagnostic(error) << "Internal Error";
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400529 if (!context->startsWithOp()) {
Diego Novillod2938e42017-11-08 12:40:02 -0500530 return context->diagnostic()
531 << "Invalid Opcode prefix '" << opcodeName << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400532 }
Lei Zhangdfc50082015-08-21 11:50:55 -0400533 }
534
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100535 // NOTE: The table contains Opcode names without the "Op" prefix.
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400536 const char* pInstName = opcodeName.data() + 2;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100537
538 spv_opcode_desc opcodeEntry;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400539 error = grammar.lookupOpcode(pInstName, &opcodeEntry);
Lei Zhang40056702015-09-11 14:31:27 -0400540 if (error) {
Diego Novillod2938e42017-11-08 12:40:02 -0500541 return context->diagnostic(error)
542 << "Invalid Opcode name '" << opcodeName << "'";
Lei Zhang40056702015-09-11 14:31:27 -0400543 }
Lei Zhang9042f402015-11-05 17:45:09 -0500544 if (opcodeEntry->hasResult && result_id.empty()) {
545 return context->diagnostic()
546 << "Expected <result-id> at the beginning of an instruction, found '"
547 << firstWord << "'.";
Lei Zhang06efdc52015-09-10 14:00:00 -0400548 }
David Neto9f188e32019-09-11 13:15:25 -0400549 if (!opcodeEntry->hasResult && !result_id.empty()) {
550 return context->diagnostic()
551 << "Cannot set ID " << result_id << " because " << opcodeName
552 << " does not produce a result ID.";
553 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100554 pInst->opcode = opcodeEntry->opcode;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400555 context->setPosition(nextPosition);
David Netob5dc8fc2015-10-06 16:22:00 -0400556 // Reserve the first word for the instruction.
557 spvInstructionAddWord(pInst, 0);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100558
David Neto78c3b432015-08-27 13:03:52 -0400559 // Maintains the ordered list of expected operand types.
560 // For many instructions we only need the {numTypes, operandTypes}
561 // entries in opcodeEntry. However, sometimes we need to modify
562 // the list as we parse the operands. This occurs when an operand
563 // has its own logical operands (such as the LocalSize operand for
564 // ExecutionMode), or for extended instructions that may have their
565 // own operands depending on the selected extended instruction.
Chris Forbes78338d52017-06-27 16:28:22 -0700566 spv_operand_pattern_t expectedOperands;
567 expectedOperands.reserve(opcodeEntry->numTypes);
568 for (auto i = 0; i < opcodeEntry->numTypes; i++)
Diego Novillod2938e42017-11-08 12:40:02 -0500569 expectedOperands.push_back(
570 opcodeEntry->operandTypes[opcodeEntry->numTypes - i - 1]);
Lei Zhangdfc50082015-08-21 11:50:55 -0400571
David Neto78c3b432015-08-27 13:03:52 -0400572 while (!expectedOperands.empty()) {
Chris Forbes78338d52017-06-27 16:28:22 -0700573 const spv_operand_type_t type = expectedOperands.back();
574 expectedOperands.pop_back();
David Neto78c3b432015-08-27 13:03:52 -0400575
576 // Expand optional tuples lazily.
Lei Zhange78a7c12015-09-10 17:07:21 -0400577 if (spvExpandOperandSequenceOnce(type, &expectedOperands)) continue;
David Neto78c3b432015-08-27 13:03:52 -0400578
579 if (type == SPV_OPERAND_TYPE_RESULT_ID && !result_id.empty()) {
580 // Handle the <result-id> for value generating instructions.
581 // We've already consumed it from the text stream. Here
582 // we inject its words into the instruction.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400583 spv_position_t temp_pos = context->position();
584 error = spvTextEncodeOperand(grammar, context, SPV_OPERAND_TYPE_RESULT_ID,
585 result_id.c_str(), pInst, nullptr);
586 result_id_position = context->position();
587 // Because we are injecting we have to reset the position afterwards.
588 context->setPosition(temp_pos);
Lei Zhang40056702015-09-11 14:31:27 -0400589 if (error) return error;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100590 } else {
David Neto78c3b432015-08-27 13:03:52 -0400591 // Find the next word.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400592 error = context->advance();
David Neto78c3b432015-08-27 13:03:52 -0400593 if (error == SPV_END_OF_STREAM) {
594 if (spvOperandIsOptional(type)) {
Lei Zhange78a7c12015-09-10 17:07:21 -0400595 // This would have been the last potential operand for the
596 // instruction,
David Neto78c3b432015-08-27 13:03:52 -0400597 // and we didn't find one. We're finished parsing this instruction.
598 break;
599 } else {
David Netoac508b02015-10-09 15:48:09 -0400600 return context->diagnostic()
601 << "Expected operand, found end of stream.";
David Neto78c3b432015-08-27 13:03:52 -0400602 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100603 }
David Neto78c3b432015-08-27 13:03:52 -0400604 assert(error == SPV_SUCCESS && "Somebody added another way to fail");
605
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400606 if (context->isStartOfNewInst()) {
David Neto78c3b432015-08-27 13:03:52 -0400607 if (spvOperandIsOptional(type)) {
608 break;
609 } else {
David Netoac508b02015-10-09 15:48:09 -0400610 return context->diagnostic()
611 << "Expected operand, found next instruction instead.";
David Neto78c3b432015-08-27 13:03:52 -0400612 }
613 }
614
615 std::string operandValue;
Lei Zhang6032b982016-03-15 16:52:40 -0400616 error = context->getWord(&operandValue, &nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400617 if (error) return context->diagnostic(error) << "Internal Error";
David Neto78c3b432015-08-27 13:03:52 -0400618
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400619 error = spvTextEncodeOperand(grammar, context, type, operandValue.c_str(),
620 pInst, &expectedOperands);
David Neto78c3b432015-08-27 13:03:52 -0400621
622 if (error == SPV_FAILED_MATCH && spvOperandIsOptional(type))
623 return SPV_SUCCESS;
624
Lei Zhang40056702015-09-11 14:31:27 -0400625 if (error) return error;
David Neto78c3b432015-08-27 13:03:52 -0400626
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400627 context->setPosition(nextPosition);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100628 }
629 }
630
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400631 if (spvOpcodeGeneratesType(pInst->opcode)) {
632 if (context->recordTypeDefinition(pInst) != SPV_SUCCESS) {
633 return SPV_ERROR_INVALID_TEXT;
634 }
635 } else if (opcodeEntry->hasType) {
636 // SPIR-V dictates that if an instruction has both a return value and a
637 // type ID then the type id is first, and the return value is second.
638 assert(opcodeEntry->hasResult &&
639 "Unknown opcode: has a type but no result.");
640 context->recordTypeIdForValue(pInst->words[2], pInst->words[1]);
641 }
642
David Netob5dc8fc2015-10-06 16:22:00 -0400643 if (pInst->words.size() > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
David Netoac508b02015-10-09 15:48:09 -0400644 return context->diagnostic()
645 << "Instruction too long: " << pInst->words.size()
646 << " words, but the limit is "
647 << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX;
David Netob5dc8fc2015-10-06 16:22:00 -0400648 }
649
David Netod9ad0502015-11-24 18:37:24 -0500650 pInst->words[0] =
651 spvOpcodeMake(uint16_t(pInst->words.size()), opcodeEntry->opcode);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100652
653 return SPV_SUCCESS;
654}
655
David Netod9ad0502015-11-24 18:37:24 -0500656enum { kAssemblerVersion = 0 };
David Neto14b93e42015-11-12 18:33:47 -0500657
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400658// Populates a binary stream's |header|. The target environment is specified via
659// |env| and Id bound is via |bound|.
660spv_result_t SetHeader(spv_target_env env, const uint32_t bound,
661 uint32_t* header) {
662 if (!header) return SPV_ERROR_INVALID_BINARY;
David Neto0b981682015-10-27 15:51:34 -0400663
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400664 header[SPV_INDEX_MAGIC_NUMBER] = SpvMagicNumber;
665 header[SPV_INDEX_VERSION_NUMBER] = spvVersionForTargetEnv(env);
666 header[SPV_INDEX_GENERATOR_NUMBER] =
David Neto14b93e42015-11-12 18:33:47 -0500667 SPV_GENERATOR_WORD(SPV_GENERATOR_KHRONOS_ASSEMBLER, kAssemblerVersion);
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400668 header[SPV_INDEX_BOUND] = bound;
669 header[SPV_INDEX_SCHEMA] = 0; // NOTE: Reserved
David Neto0b981682015-10-27 15:51:34 -0400670
671 return SPV_SUCCESS;
672}
673
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400674// Collects all numeric ids in the module source into |numeric_ids|.
675// This function is essentially a dry-run of spvTextToBinary.
dan sinclair3dad1cd2018-07-07 09:38:00 -0400676spv_result_t GetNumericIds(const spvtools::AssemblyGrammar& grammar,
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400677 const spvtools::MessageConsumer& consumer,
678 const spv_text text,
679 std::set<uint32_t>* numeric_ids) {
dan sinclair3dad1cd2018-07-07 09:38:00 -0400680 spvtools::AssemblyContext context(text, consumer);
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400681
682 if (!text->str) return context.diagnostic() << "Missing assembly text.";
683
684 if (!grammar.isValid()) {
685 return SPV_ERROR_INVALID_TABLE;
686 }
687
688 // Skip past whitespace and comments.
689 context.advance();
690
691 while (context.hasText()) {
692 spv_instruction_t inst;
693
694 if (spvTextEncodeOpcode(grammar, &context, &inst)) {
695 return SPV_ERROR_INVALID_TEXT;
696 }
697
698 if (context.advance()) break;
699 }
700
701 *numeric_ids = context.GetNumericIds();
702 return SPV_SUCCESS;
703}
704
David Netoc9786432015-09-01 18:05:14 -0400705// Translates a given assembly language module into binary form.
706// If a diagnostic is generated, it is not yet marked as being
707// for a text-based input.
dan sinclair3dad1cd2018-07-07 09:38:00 -0400708spv_result_t spvTextToBinaryInternal(const spvtools::AssemblyGrammar& grammar,
Diego Novillod2938e42017-11-08 12:40:02 -0500709 const spvtools::MessageConsumer& consumer,
710 const spv_text text,
711 const uint32_t options,
712 spv_binary* pBinary) {
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400713 // The ids in this set will have the same values both in source and binary.
714 // All other ids will be generated by filling in the gaps.
715 std::set<uint32_t> ids_to_preserve;
716
717 if (options & SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS) {
718 // Collect all numeric ids from the source into ids_to_preserve.
719 const spv_result_t result =
720 GetNumericIds(grammar, consumer, text, &ids_to_preserve);
721 if (result != SPV_SUCCESS) return result;
722 }
723
dan sinclair3dad1cd2018-07-07 09:38:00 -0400724 spvtools::AssemblyContext context(text, consumer, std::move(ids_to_preserve));
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400725
David Neto201caf72015-11-04 17:38:17 -0500726 if (!text->str) return context.diagnostic() << "Missing assembly text.";
David Netoac508b02015-10-09 15:48:09 -0400727
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400728 if (!grammar.isValid()) {
Lei Zhang40056702015-09-11 14:31:27 -0400729 return SPV_ERROR_INVALID_TABLE;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400730 }
Lei Zhang40056702015-09-11 14:31:27 -0400731 if (!pBinary) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100732
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100733 std::vector<spv_instruction_t> instructions;
734
David Netoea633a62015-11-02 11:40:59 -0500735 // Skip past whitespace and comments.
736 context.advance();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100737
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400738 while (context.hasText()) {
David Netob5dc8fc2015-10-06 16:22:00 -0400739 instructions.push_back({});
740 spv_instruction_t& inst = instructions.back();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100741
Lei Zhang9042f402015-11-05 17:45:09 -0500742 if (spvTextEncodeOpcode(grammar, &context, &inst)) {
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400743 return SPV_ERROR_INVALID_TEXT;
Lei Zhang40056702015-09-11 14:31:27 -0400744 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400745
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400746 if (context.advance()) break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100747 }
748
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100749 size_t totalSize = SPV_INDEX_INSTRUCTION;
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400750 for (auto& inst : instructions) {
David Netob5dc8fc2015-10-06 16:22:00 -0400751 totalSize += inst.words.size();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100752 }
753
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400754 uint32_t* data = new uint32_t[totalSize];
Lei Zhang40056702015-09-11 14:31:27 -0400755 if (!data) return SPV_ERROR_OUT_OF_MEMORY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100756 uint64_t currentIndex = SPV_INDEX_INSTRUCTION;
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400757 for (auto& inst : instructions) {
Lei Zhang6483bd72015-10-14 17:02:39 -0400758 memcpy(data + currentIndex, inst.words.data(),
759 sizeof(uint32_t) * inst.words.size());
David Netob5dc8fc2015-10-06 16:22:00 -0400760 currentIndex += inst.words.size();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100761 }
762
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400763 if (auto error = SetHeader(grammar.target_env(), context.getBound(), data))
764 return error;
David Netoe4945de2015-10-28 13:50:32 -0400765
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100766 spv_binary binary = new spv_binary_t();
Lei Zhang40056702015-09-11 14:31:27 -0400767 if (!binary) {
768 delete[] data;
769 return SPV_ERROR_OUT_OF_MEMORY;
770 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100771 binary->code = data;
772 binary->wordCount = totalSize;
773
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100774 *pBinary = binary;
775
776 return SPV_SUCCESS;
777}
778
Lei Zhange78a7c12015-09-10 17:07:21 -0400779} // anonymous namespace
David Netoc9786432015-09-01 18:05:14 -0400780
Lei Zhang972788b2015-11-12 13:48:30 -0500781spv_result_t spvTextToBinary(const spv_const_context context,
782 const char* input_text,
Lei Zhangdf920ec2015-11-11 11:33:26 -0500783 const size_t input_text_size, spv_binary* pBinary,
784 spv_diagnostic* pDiagnostic) {
Diego Novillod2938e42017-11-08 12:40:02 -0500785 return spvTextToBinaryWithOptions(context, input_text, input_text_size,
Steven Perron32b0f672019-02-26 16:52:33 -0500786 SPV_TEXT_TO_BINARY_OPTION_NONE, pBinary,
Diego Novillod2938e42017-11-08 12:40:02 -0500787 pDiagnostic);
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400788}
789
Diego Novillod2938e42017-11-08 12:40:02 -0500790spv_result_t spvTextToBinaryWithOptions(const spv_const_context context,
791 const char* input_text,
792 const size_t input_text_size,
793 const uint32_t options,
794 spv_binary* pBinary,
795 spv_diagnostic* pDiagnostic) {
Lei Zhang755f97f2016-09-02 18:06:18 -0400796 spv_context_t hijack_context = *context;
797 if (pDiagnostic) {
798 *pDiagnostic = nullptr;
dan sinclair3dad1cd2018-07-07 09:38:00 -0400799 spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
Lei Zhang755f97f2016-09-02 18:06:18 -0400800 }
801
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400802 spv_text_t text = {input_text, input_text_size};
dan sinclair3dad1cd2018-07-07 09:38:00 -0400803 spvtools::AssemblyGrammar grammar(&hijack_context);
Lei Zhang9042f402015-11-05 17:45:09 -0500804
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400805 spv_result_t result = spvTextToBinaryInternal(
806 grammar, hijack_context.consumer, &text, options, pBinary);
David Netoc9786432015-09-01 18:05:14 -0400807 if (pDiagnostic && *pDiagnostic) (*pDiagnostic)->isTextSource = true;
808
809 return result;
810}
811
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100812void spvTextDestroy(spv_text text) {
Lei Zhang40056702015-09-11 14:31:27 -0400813 if (!text) return;
Eric Engestromeb6ae972016-02-18 23:41:16 +0000814 delete[] text->str;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100815 delete text;
816}