blob: d16e2f47a5b1dfe8396b1d1e1d55d6b625c6dc66 [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
David Neto36b0c0f2015-09-16 18:32:54 -040015#include "text.h"
16
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>
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040024#include <sstream>
David Neto201caf72015-11-04 17:38:17 -050025#include <string>
David Neto36b0c0f2015-09-16 18:32:54 -040026#include <unordered_map>
27#include <vector>
Dejan Mircevskiba569fb2015-09-11 16:34:49 -040028
David Netofcc7d582015-10-27 15:31:10 -040029#include "assembly_grammar.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010030#include "binary.h"
31#include "diagnostic.h"
32#include "ext_inst.h"
David Netob5dc8fc2015-10-06 16:22:00 -040033#include "instruction.h"
Lei Zhang755f97f2016-09-02 18:06:18 -040034#include "message.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010035#include "opcode.h"
36#include "operand.h"
David Neto5a703352016-02-17 14:44:00 -050037#include "spirv-tools/libspirv.h"
Lei Zhangaa056cd2015-11-11 14:24:04 -050038#include "spirv_constant.h"
Alan Baker42840d12018-04-06 14:15:27 -040039#include "spirv_target_env.h"
Lei Zhang7a222e42015-11-11 12:40:25 -050040#include "table.h"
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040041#include "text_handler.h"
Andrew Woloszynf731cbf2015-10-23 09:53:58 -040042#include "util/bitutils.h"
qining1773b952016-09-01 14:27:04 -040043#include "util/parse_number.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010044
Andrew Woloszyn13804e52015-09-22 15:50:33 -040045bool spvIsValidIDCharacter(const char value) {
46 return value == '_' || 0 != ::isalnum(value);
47}
48
49// Returns true if the given string represents a valid ID name.
Dejan Mircevski14c4b102015-09-29 17:07:21 -040050bool spvIsValidID(const char* textValue) {
51 const char* c = textValue;
Andrew Woloszyn13804e52015-09-22 15:50:33 -040052 for (; *c != '\0'; ++c) {
53 if (!spvIsValidIDCharacter(*c)) {
54 return false;
55 }
56 }
57 // If the string was empty, then the ID also is not valid.
58 return c != textValue;
59}
60
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040061// Text API
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010062
Dejan Mircevski903f9d62015-09-28 17:04:39 -040063spv_result_t spvTextToLiteral(const char* textValue, spv_literal_t* pLiteral) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010064 bool isSigned = false;
David Netoaffa6962015-08-24 15:33:14 -040065 int numPeriods = 0;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010066 bool isString = false;
67
David Netoaffa6962015-08-24 15:33:14 -040068 const size_t len = strlen(textValue);
David Neto98290a22015-08-24 16:27:02 -040069 if (len == 0) return SPV_FAILED_MATCH;
70
David Netoaffa6962015-08-24 15:33:14 -040071 for (uint64_t index = 0; index < len; ++index) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010072 switch (textValue[index]) {
73 case '0':
74 case '1':
75 case '2':
76 case '3':
77 case '4':
78 case '5':
79 case '6':
80 case '7':
81 case '8':
82 case '9':
83 break;
84 case '.':
David Netoaffa6962015-08-24 15:33:14 -040085 numPeriods++;
86 break;
87 case '-':
88 if (index == 0) {
89 isSigned = true;
90 } else {
91 isString = true;
92 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010093 break;
94 default:
95 isString = true;
Lei Zhange78a7c12015-09-10 17:07:21 -040096 index = len; // break out of the loop too.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010097 break;
98 }
99 }
100
David Netoaffa6962015-08-24 15:33:14 -0400101 pLiteral->type = spv_literal_type_t(99);
102
Lei Zhange78a7c12015-09-10 17:07:21 -0400103 if (isString || numPeriods > 1 || (isSigned && len == 1)) {
David Neto98290a22015-08-24 16:27:02 -0400104 if (len < 2 || textValue[0] != '"' || textValue[len - 1] != '"')
105 return SPV_FAILED_MATCH;
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400106 bool escaping = false;
Lei Zhang6483bd72015-10-14 17:02:39 -0400107 for (const char* val = textValue + 1; val != textValue + len - 1; ++val) {
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400108 if ((*val == '\\') && (!escaping)) {
109 escaping = true;
110 } else {
111 // Have to save space for the null-terminator
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500112 if (pLiteral->str.size() >= SPV_LIMIT_LITERAL_STRING_BYTES_MAX)
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400113 return SPV_ERROR_OUT_OF_MEMORY;
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500114 pLiteral->str.push_back(*val);
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400115 escaping = false;
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400116 }
117 }
118
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100119 pLiteral->type = SPV_LITERAL_TYPE_STRING;
David Netoaffa6962015-08-24 15:33:14 -0400120 } else if (numPeriods == 1) {
121 double d = std::strtod(textValue, nullptr);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100122 float f = (float)d;
123 if (d == (double)f) {
124 pLiteral->type = SPV_LITERAL_TYPE_FLOAT_32;
125 pLiteral->value.f = f;
126 } else {
127 pLiteral->type = SPV_LITERAL_TYPE_FLOAT_64;
128 pLiteral->value.d = d;
129 }
130 } else if (isSigned) {
131 int64_t i64 = strtoll(textValue, nullptr, 10);
132 int32_t i32 = (int32_t)i64;
133 if (i64 == (int64_t)i32) {
134 pLiteral->type = SPV_LITERAL_TYPE_INT_32;
135 pLiteral->value.i32 = i32;
136 } else {
137 pLiteral->type = SPV_LITERAL_TYPE_INT_64;
138 pLiteral->value.i64 = i64;
139 }
140 } else {
141 uint64_t u64 = strtoull(textValue, nullptr, 10);
142 uint32_t u32 = (uint32_t)u64;
143 if (u64 == (uint64_t)u32) {
144 pLiteral->type = SPV_LITERAL_TYPE_UINT_32;
145 pLiteral->value.u32 = u32;
146 } else {
147 pLiteral->type = SPV_LITERAL_TYPE_UINT_64;
148 pLiteral->value.u64 = u64;
149 }
150 }
151
152 return SPV_SUCCESS;
153}
154
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400155namespace {
156
157/// Parses an immediate integer from text, guarding against overflow. If
158/// successful, adds the parsed value to pInst, advances the context past it,
159/// and returns SPV_SUCCESS. Otherwise, leaves pInst alone, emits diagnostics,
160/// and returns SPV_ERROR_INVALID_TEXT.
dan sinclair3dad1cd2018-07-07 09:38:00 -0400161spv_result_t encodeImmediate(spvtools::AssemblyContext* context,
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400162 const char* text, spv_instruction_t* pInst) {
163 assert(*text == '!');
David Neto78e677b2015-10-05 13:28:46 -0400164 uint32_t parse_result;
dan sinclair76e0bde2018-07-06 13:25:17 -0400165 if (!spvtools::utils::ParseNumber(text + 1, &parse_result)) {
qining1773b952016-09-01 14:27:04 -0400166 return context->diagnostic(SPV_ERROR_INVALID_TEXT)
167 << "Invalid immediate integer: !" << text + 1;
168 }
David Neto78e677b2015-10-05 13:28:46 -0400169 context->binaryEncodeU32(parse_result, pInst);
Ben Vanik01c8d7a2015-11-22 08:32:53 -0800170 context->seekForward(static_cast<uint32_t>(strlen(text)));
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400171 return SPV_SUCCESS;
172}
173
174} // anonymous namespace
175
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400176/// @brief Translate an Opcode operand to binary form
177///
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400178/// @param[in] grammar the grammar to use for compilation
179/// @param[in, out] context the dynamic compilation info
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400180/// @param[in] type of the operand
181/// @param[in] textValue word of text to be parsed
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400182/// @param[out] pInst return binary Opcode
183/// @param[in,out] pExpectedOperands the operand types expected
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400184///
185/// @return result code
dan sinclair3dad1cd2018-07-07 09:38:00 -0400186spv_result_t spvTextEncodeOperand(const spvtools::AssemblyGrammar& grammar,
187 spvtools::AssemblyContext* context,
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400188 const spv_operand_type_t type,
189 const char* textValue,
190 spv_instruction_t* pInst,
191 spv_operand_pattern_t* pExpectedOperands) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100192 // NOTE: Handle immediate int in the stream
193 if ('!' == textValue[0]) {
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400194 if (auto error = encodeImmediate(context, textValue, pInst)) {
195 return error;
Lei Zhang40056702015-09-11 14:31:27 -0400196 }
Dejan Mircevski897bff92015-09-29 10:38:18 -0400197 *pExpectedOperands =
198 spvAlternatePatternFollowingImmediate(*pExpectedOperands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100199 return SPV_SUCCESS;
200 }
201
David Neto51013d12015-10-14 11:31:51 -0400202 // Optional literal operands can fail to parse. In that case use
203 // SPV_FAILED_MATCH to avoid emitting a diagostic. Use the following
204 // for those situations.
205 spv_result_t error_code_for_literals =
206 spvOperandIsOptional(type) ? SPV_FAILED_MATCH : SPV_ERROR_INVALID_TEXT;
207
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100208 switch (type) {
David Netoe3f70b92015-08-27 13:50:05 -0400209 case SPV_OPERAND_TYPE_ID:
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400210 case SPV_OPERAND_TYPE_TYPE_ID:
David Neto201caf72015-11-04 17:38:17 -0500211 case SPV_OPERAND_TYPE_RESULT_ID:
212 case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
213 case SPV_OPERAND_TYPE_SCOPE_ID:
214 case SPV_OPERAND_TYPE_OPTIONAL_ID: {
Lei Zhangabafd5e2015-08-21 11:52:29 -0400215 if ('%' == textValue[0]) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100216 textValue++;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100217 } else {
David Netoac508b02015-10-09 15:48:09 -0400218 return context->diagnostic() << "Expected id to start with %.";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100219 }
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400220 if (!spvIsValidID(textValue)) {
David Netoac508b02015-10-09 15:48:09 -0400221 return context->diagnostic() << "Invalid ID " << textValue;
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400222 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400223 const uint32_t id = context->spvNamedIdAssignOrGet(textValue);
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400224 if (type == SPV_OPERAND_TYPE_TYPE_ID) pInst->resultTypeId = id;
David Netob5dc8fc2015-10-06 16:22:00 -0400225 spvInstructionAddWord(pInst, id);
David Neto2ae4a682015-11-09 18:55:42 -0500226
227 // Set the extended instruction type.
228 // The import set id is the 3rd operand of OpExtInst.
229 if (pInst->opcode == SpvOpExtInst && pInst->words.size() == 4) {
230 auto ext_inst_type = context->getExtInstTypeForId(pInst->words[3]);
231 if (ext_inst_type == SPV_EXT_INST_TYPE_NONE) {
232 return context->diagnostic()
233 << "Invalid extended instruction import Id "
234 << pInst->words[2];
235 }
236 pInst->extInstType = ext_inst_type;
237 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100238 } break;
David Neto201caf72015-11-04 17:38:17 -0500239
David Neto445ce442015-10-15 15:22:06 -0400240 case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
241 // The assembler accepts the symbolic name for an extended instruction,
242 // and emits its corresponding number.
243 spv_ext_inst_desc extInst;
244 if (grammar.lookupExtInst(pInst->extInstType, textValue, &extInst)) {
Diego Novillod2938e42017-11-08 12:40:02 -0500245 return context->diagnostic()
246 << "Invalid extended instruction name '" << textValue << "'.";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100247 }
David Neto445ce442015-10-15 15:22:06 -0400248 spvInstructionAddWord(pInst, extInst->ext_inst);
249
250 // Prepare to parse the operands for the extended instructions.
Chris Forbes78338d52017-06-27 16:28:22 -0700251 spvPushOperandTypes(extInst->operandTypes, pExpectedOperands);
David Neto0f166be2015-11-11 01:56:49 -0500252 } break;
David Neto445ce442015-10-15 15:22:06 -0400253
David Neto0f166be2015-11-11 01:56:49 -0500254 case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: {
255 // The assembler accepts the symbolic name for the opcode, but without
256 // the "Op" prefix. For example, "IAdd" is accepted. The number
257 // of the opcode is emitted.
258 SpvOp opcode;
259 if (grammar.lookupSpecConstantOpcode(textValue, &opcode)) {
260 return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
261 << " '" << textValue << "'.";
262 }
263 spv_opcode_desc opcodeEntry = nullptr;
264 if (grammar.lookupOpcode(opcode, &opcodeEntry)) {
265 return context->diagnostic(SPV_ERROR_INTERNAL)
266 << "OpSpecConstant opcode table out of sync";
267 }
268 spvInstructionAddWord(pInst, uint32_t(opcodeEntry->opcode));
269
270 // Prepare to parse the operands for the opcode. Except skip the
271 // type Id and result Id, since they've already been processed.
272 assert(opcodeEntry->hasType);
273 assert(opcodeEntry->hasResult);
274 assert(opcodeEntry->numTypes >= 2);
Chris Forbes78338d52017-06-27 16:28:22 -0700275 spvPushOperandTypes(opcodeEntry->operandTypes + 2, pExpectedOperands);
David Neto445ce442015-10-15 15:22:06 -0400276 } break;
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400277
David Neto201caf72015-11-04 17:38:17 -0500278 case SPV_OPERAND_TYPE_LITERAL_INTEGER:
279 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER: {
280 // The current operand is an *unsigned* 32-bit integer.
281 // That's just how the grammar works.
dan sinclair3dad1cd2018-07-07 09:38:00 -0400282 spvtools::IdType expected_type = {
283 32, false, spvtools::IdTypeClass::kScalarIntegerType};
David Neto78e677b2015-10-05 13:28:46 -0400284 if (auto error = context->binaryEncodeNumericLiteral(
David Neto51013d12015-10-14 11:31:51 -0400285 textValue, error_code_for_literals, expected_type, pInst)) {
David Neto78e677b2015-10-05 13:28:46 -0400286 return error;
David Neto51013d12015-10-14 11:31:51 -0400287 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100288 } break;
David Neto201caf72015-11-04 17:38:17 -0500289
290 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_NUMBER:
291 // This is a context-independent literal number which can be a 32-bit
292 // number of floating point value.
293 if (auto error = context->binaryEncodeNumericLiteral(
dan sinclair3dad1cd2018-07-07 09:38:00 -0400294 textValue, error_code_for_literals, spvtools::kUnknownType,
David Neto201caf72015-11-04 17:38:17 -0500295 pInst)) {
296 return error;
297 }
298 break;
299
300 case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER:
301 case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER: {
dan sinclair3dad1cd2018-07-07 09:38:00 -0400302 spvtools::IdType expected_type = spvtools::kUnknownType;
David Neto201caf72015-11-04 17:38:17 -0500303 // The encoding for OpConstant, OpSpecConstant and OpSwitch all
304 // depend on either their own result-id or the result-id of
305 // one of their parameters.
306 if (SpvOpConstant == pInst->opcode ||
307 SpvOpSpecConstant == pInst->opcode) {
308 // The type of the literal is determined by the type Id of the
309 // instruction.
310 expected_type =
311 context->getTypeOfTypeGeneratingValue(pInst->resultTypeId);
dan sinclair3dad1cd2018-07-07 09:38:00 -0400312 if (!spvtools::isScalarFloating(expected_type) &&
313 !spvtools::isScalarIntegral(expected_type)) {
David Neto201caf72015-11-04 17:38:17 -0500314 spv_opcode_desc d;
315 const char* opcode_name = "opcode";
316 if (SPV_SUCCESS == grammar.lookupOpcode(pInst->opcode, &d)) {
317 opcode_name = d->name;
318 }
319 return context->diagnostic()
320 << "Type for " << opcode_name
321 << " must be a scalar floating point or integer type";
322 }
323 } else if (pInst->opcode == SpvOpSwitch) {
324 // The type of the literal is the same as the type of the selector.
325 expected_type = context->getTypeOfValueInstruction(pInst->words[1]);
dan sinclair3dad1cd2018-07-07 09:38:00 -0400326 if (!spvtools::isScalarIntegral(expected_type)) {
David Neto201caf72015-11-04 17:38:17 -0500327 return context->diagnostic()
328 << "The selector operand for OpSwitch must be the result"
329 " of an instruction that generates an integer scalar";
330 }
331 }
332 if (auto error = context->binaryEncodeNumericLiteral(
333 textValue, error_code_for_literals, expected_type, pInst)) {
334 return error;
335 }
336 } break;
337
David Neto78c3b432015-08-27 13:03:52 -0400338 case SPV_OPERAND_TYPE_LITERAL_STRING:
339 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
Lei Zhang6d415812015-09-15 13:36:21 -0400340 spv_literal_t literal = {};
341 spv_result_t error = spvTextToLiteral(textValue, &literal);
342 if (error != SPV_SUCCESS) {
343 if (error == SPV_ERROR_OUT_OF_MEMORY) return error;
David Neto51013d12015-10-14 11:31:51 -0400344 return context->diagnostic(error_code_for_literals)
345 << "Invalid literal string '" << textValue << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400346 }
Lei Zhang6d415812015-09-15 13:36:21 -0400347 if (literal.type != SPV_LITERAL_TYPE_STRING) {
David Neto51013d12015-10-14 11:31:51 -0400348 return context->diagnostic()
David Netoac508b02015-10-09 15:48:09 -0400349 << "Expected literal string, found literal number '" << textValue
350 << "'.";
Lei Zhang6d415812015-09-15 13:36:21 -0400351 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100352
353 // NOTE: Special case for extended instruction library import
Lei Zhangb36e7042015-10-28 13:40:52 -0400354 if (SpvOpExtInstImport == pInst->opcode) {
David Neto2ae4a682015-11-09 18:55:42 -0500355 const spv_ext_inst_type_t ext_inst_type =
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500356 spvExtInstImportTypeGet(literal.str.c_str());
David Neto2ae4a682015-11-09 18:55:42 -0500357 if (SPV_EXT_INST_TYPE_NONE == ext_inst_type) {
358 return context->diagnostic()
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500359 << "Invalid extended instruction import '" << literal.str
David Neto2ae4a682015-11-09 18:55:42 -0500360 << "'";
361 }
David Neto677e0c72016-01-05 14:56:02 -0500362 if ((error = context->recordIdAsExtInstImport(pInst->words[1],
363 ext_inst_type)))
David Neto2ae4a682015-11-09 18:55:42 -0500364 return error;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100365 }
366
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500367 if (context->binaryEncodeString(literal.str.c_str(), pInst))
Lei Zhang40056702015-09-11 14:31:27 -0400368 return SPV_ERROR_INVALID_TEXT;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100369 } break;
David Neto59de6102017-12-03 12:30:08 -0500370
371 // Masks.
David Neto36b0c0f2015-09-16 18:32:54 -0400372 case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
373 case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
374 case SPV_OPERAND_TYPE_LOOP_CONTROL:
David Neto2889a0c2016-02-15 13:50:00 -0500375 case SPV_OPERAND_TYPE_IMAGE:
David Netoee1b3bb2015-09-18 11:19:18 -0400376 case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
David Neto5bf88fc2015-09-17 17:06:10 -0400377 case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
David Neto59de6102017-12-03 12:30:08 -0500378 case SPV_OPERAND_TYPE_SELECTION_CONTROL:
379 case SPV_OPERAND_TYPE_DEBUG_INFO_FLAGS: {
David Neto36b0c0f2015-09-16 18:32:54 -0400380 uint32_t value;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400381 if (grammar.parseMaskOperand(type, textValue, &value)) {
David Netoac508b02015-10-09 15:48:09 -0400382 return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
David Netod9ad0502015-11-24 18:37:24 -0500383 << " operand '" << textValue << "'.";
David Neto36b0c0f2015-09-16 18:32:54 -0400384 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400385 if (auto error = context->binaryEncodeU32(value, pInst)) return error;
David Neto5bf88fc2015-09-17 17:06:10 -0400386 // Prepare to parse the operands for this logical operand.
Chris Forbes78338d52017-06-27 16:28:22 -0700387 grammar.pushOperandTypesForMask(type, value, pExpectedOperands);
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400388 } break;
389 case SPV_OPERAND_TYPE_OPTIONAL_CIV: {
390 auto error = spvTextEncodeOperand(
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400391 grammar, context, SPV_OPERAND_TYPE_OPTIONAL_LITERAL_NUMBER, textValue,
392 pInst, pExpectedOperands);
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400393 if (error == SPV_FAILED_MATCH) {
394 // It's not a literal number -- is it a literal string?
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400395 error = spvTextEncodeOperand(grammar, context,
396 SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING,
397 textValue, pInst, pExpectedOperands);
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400398 }
399 if (error == SPV_FAILED_MATCH) {
400 // It's not a literal -- is it an ID?
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400401 error =
402 spvTextEncodeOperand(grammar, context, SPV_OPERAND_TYPE_OPTIONAL_ID,
403 textValue, pInst, pExpectedOperands);
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400404 }
405 if (error) {
David Netoac508b02015-10-09 15:48:09 -0400406 return context->diagnostic(error)
407 << "Invalid word following !<integer>: " << textValue;
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400408 }
409 if (pExpectedOperands->empty()) {
410 pExpectedOperands->push_back(SPV_OPERAND_TYPE_OPTIONAL_CIV);
411 }
David Neto36b0c0f2015-09-16 18:32:54 -0400412 } break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100413 default: {
414 // NOTE: All non literal operands are handled here using the operand
415 // table.
416 spv_operand_desc entry;
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400417 if (grammar.lookupOperand(type, textValue, strlen(textValue), &entry)) {
David Netoac508b02015-10-09 15:48:09 -0400418 return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
419 << " '" << textValue << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400420 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400421 if (context->binaryEncodeU32(entry->value, pInst)) {
David Netoac508b02015-10-09 15:48:09 -0400422 return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
423 << " '" << textValue << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400424 }
David Neto78c3b432015-08-27 13:03:52 -0400425
426 // Prepare to parse the operands for this logical operand.
Chris Forbes78338d52017-06-27 16:28:22 -0700427 spvPushOperandTypes(entry->operandTypes, pExpectedOperands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100428 } break;
429 }
430 return SPV_SUCCESS;
431}
432
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400433namespace {
434
435/// Encodes an instruction started by !<integer> at the given position in text.
436///
437/// Puts the encoded words into *pInst. If successful, moves position past the
438/// instruction and returns SPV_SUCCESS. Otherwise, returns an error code and
439/// leaves position pointing to the error in text.
440spv_result_t encodeInstructionStartingWithImmediate(
dan sinclair3dad1cd2018-07-07 09:38:00 -0400441 const spvtools::AssemblyGrammar& grammar,
442 spvtools::AssemblyContext* context, spv_instruction_t* pInst) {
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400443 std::string firstWord;
444 spv_position_t nextPosition = {};
Lei Zhang6032b982016-03-15 16:52:40 -0400445 auto error = context->getWord(&firstWord, &nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400446 if (error) return context->diagnostic(error) << "Internal Error";
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400447
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400448 if ((error = encodeImmediate(context, firstWord.c_str(), pInst))) {
449 return error;
Lei Zhang40056702015-09-11 14:31:27 -0400450 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400451 while (context->advance() != SPV_END_OF_STREAM) {
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400452 // A beginning of a new instruction means we're done.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400453 if (context->isStartOfNewInst()) return SPV_SUCCESS;
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400454
455 // Otherwise, there must be an operand that's either a literal, an ID, or
456 // an immediate.
457 std::string operandValue;
Lei Zhang6032b982016-03-15 16:52:40 -0400458 if ((error = context->getWord(&operandValue, &nextPosition)))
David Netoac508b02015-10-09 15:48:09 -0400459 return context->diagnostic(error) << "Internal Error";
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400460
David Netoac508b02015-10-09 15:48:09 -0400461 if (operandValue == "=")
462 return context->diagnostic() << firstWord << " not allowed before =.";
Dejan Mircevskie3a19c02015-09-11 15:03:54 -0400463
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400464 // Needed to pass to spvTextEncodeOpcode(), but it shouldn't ever be
465 // expanded.
466 spv_operand_pattern_t dummyExpectedOperands;
467 error = spvTextEncodeOperand(
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400468 grammar, context, SPV_OPERAND_TYPE_OPTIONAL_CIV, operandValue.c_str(),
469 pInst, &dummyExpectedOperands);
Lei Zhang40056702015-09-11 14:31:27 -0400470 if (error) return error;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400471 context->setPosition(nextPosition);
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400472 }
473 return SPV_SUCCESS;
474}
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400475
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400476/// @brief Translate single Opcode and operands to binary form
477///
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400478/// @param[in] grammar the grammar to use for compilation
479/// @param[in, out] context the dynamic compilation info
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400480/// @param[in] text stream to translate
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400481/// @param[out] pInst returned binary Opcode
482/// @param[in,out] pPosition in the text stream
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400483///
484/// @return result code
dan sinclair3dad1cd2018-07-07 09:38:00 -0400485spv_result_t spvTextEncodeOpcode(const spvtools::AssemblyGrammar& grammar,
486 spvtools::AssemblyContext* context,
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400487 spv_instruction_t* pInst) {
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400488 // Check for !<integer> first.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400489 if ('!' == context->peek()) {
490 return encodeInstructionStartingWithImmediate(grammar, context, pInst);
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400491 }
492
Lei Zhang06efdc52015-09-10 14:00:00 -0400493 std::string firstWord;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100494 spv_position_t nextPosition = {};
Lei Zhang6032b982016-03-15 16:52:40 -0400495 spv_result_t error = context->getWord(&firstWord, &nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400496 if (error) return context->diagnostic() << "Internal Error";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100497
Lei Zhang06efdc52015-09-10 14:00:00 -0400498 std::string opcodeName;
Lei Zhangdfc50082015-08-21 11:50:55 -0400499 std::string result_id;
500 spv_position_t result_id_position = {};
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400501 if (context->startsWithOp()) {
Lei Zhang06efdc52015-09-10 14:00:00 -0400502 opcodeName = firstWord;
503 } else {
Lei Zhang06efdc52015-09-10 14:00:00 -0400504 result_id = firstWord;
Lei Zhang40056702015-09-11 14:31:27 -0400505 if ('%' != result_id.front()) {
David Netoac508b02015-10-09 15:48:09 -0400506 return context->diagnostic()
507 << "Expected <opcode> or <result-id> at the beginning "
508 "of an instruction, found '"
509 << result_id << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400510 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400511 result_id_position = context->position();
Lei Zhang06efdc52015-09-10 14:00:00 -0400512
513 // The '=' sign.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400514 context->setPosition(nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400515 if (context->advance())
516 return context->diagnostic() << "Expected '=', found end of stream.";
Lei Zhangdfc50082015-08-21 11:50:55 -0400517 std::string equal_sign;
Lei Zhang6032b982016-03-15 16:52:40 -0400518 error = context->getWord(&equal_sign, &nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400519 if ("=" != equal_sign)
520 return context->diagnostic() << "'=' expected after result id.";
Lei Zhangdfc50082015-08-21 11:50:55 -0400521
522 // The <opcode> after the '=' sign.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400523 context->setPosition(nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400524 if (context->advance())
525 return context->diagnostic() << "Expected opcode, found end of stream.";
Lei Zhang6032b982016-03-15 16:52:40 -0400526 error = context->getWord(&opcodeName, &nextPosition);
Lei Zhang6483bd72015-10-14 17:02:39 -0400527 if (error) return context->diagnostic(error) << "Internal Error";
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400528 if (!context->startsWithOp()) {
Diego Novillod2938e42017-11-08 12:40:02 -0500529 return context->diagnostic()
530 << "Invalid Opcode prefix '" << opcodeName << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400531 }
Lei Zhangdfc50082015-08-21 11:50:55 -0400532 }
533
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100534 // NOTE: The table contains Opcode names without the "Op" prefix.
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400535 const char* pInstName = opcodeName.data() + 2;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100536
537 spv_opcode_desc opcodeEntry;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400538 error = grammar.lookupOpcode(pInstName, &opcodeEntry);
Lei Zhang40056702015-09-11 14:31:27 -0400539 if (error) {
Diego Novillod2938e42017-11-08 12:40:02 -0500540 return context->diagnostic(error)
541 << "Invalid Opcode name '" << opcodeName << "'";
Lei Zhang40056702015-09-11 14:31:27 -0400542 }
Lei Zhang9042f402015-11-05 17:45:09 -0500543 if (opcodeEntry->hasResult && result_id.empty()) {
544 return context->diagnostic()
545 << "Expected <result-id> at the beginning of an instruction, found '"
546 << firstWord << "'.";
Lei Zhang06efdc52015-09-10 14:00:00 -0400547 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100548 pInst->opcode = opcodeEntry->opcode;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400549 context->setPosition(nextPosition);
David Netob5dc8fc2015-10-06 16:22:00 -0400550 // Reserve the first word for the instruction.
551 spvInstructionAddWord(pInst, 0);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100552
David Neto78c3b432015-08-27 13:03:52 -0400553 // Maintains the ordered list of expected operand types.
554 // For many instructions we only need the {numTypes, operandTypes}
555 // entries in opcodeEntry. However, sometimes we need to modify
556 // the list as we parse the operands. This occurs when an operand
557 // has its own logical operands (such as the LocalSize operand for
558 // ExecutionMode), or for extended instructions that may have their
559 // own operands depending on the selected extended instruction.
Chris Forbes78338d52017-06-27 16:28:22 -0700560 spv_operand_pattern_t expectedOperands;
561 expectedOperands.reserve(opcodeEntry->numTypes);
562 for (auto i = 0; i < opcodeEntry->numTypes; i++)
Diego Novillod2938e42017-11-08 12:40:02 -0500563 expectedOperands.push_back(
564 opcodeEntry->operandTypes[opcodeEntry->numTypes - i - 1]);
Lei Zhangdfc50082015-08-21 11:50:55 -0400565
David Neto78c3b432015-08-27 13:03:52 -0400566 while (!expectedOperands.empty()) {
Chris Forbes78338d52017-06-27 16:28:22 -0700567 const spv_operand_type_t type = expectedOperands.back();
568 expectedOperands.pop_back();
David Neto78c3b432015-08-27 13:03:52 -0400569
570 // Expand optional tuples lazily.
Lei Zhange78a7c12015-09-10 17:07:21 -0400571 if (spvExpandOperandSequenceOnce(type, &expectedOperands)) continue;
David Neto78c3b432015-08-27 13:03:52 -0400572
573 if (type == SPV_OPERAND_TYPE_RESULT_ID && !result_id.empty()) {
574 // Handle the <result-id> for value generating instructions.
575 // We've already consumed it from the text stream. Here
576 // we inject its words into the instruction.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400577 spv_position_t temp_pos = context->position();
578 error = spvTextEncodeOperand(grammar, context, SPV_OPERAND_TYPE_RESULT_ID,
579 result_id.c_str(), pInst, nullptr);
580 result_id_position = context->position();
581 // Because we are injecting we have to reset the position afterwards.
582 context->setPosition(temp_pos);
Lei Zhang40056702015-09-11 14:31:27 -0400583 if (error) return error;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100584 } else {
David Neto78c3b432015-08-27 13:03:52 -0400585 // Find the next word.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400586 error = context->advance();
David Neto78c3b432015-08-27 13:03:52 -0400587 if (error == SPV_END_OF_STREAM) {
588 if (spvOperandIsOptional(type)) {
Lei Zhange78a7c12015-09-10 17:07:21 -0400589 // This would have been the last potential operand for the
590 // instruction,
David Neto78c3b432015-08-27 13:03:52 -0400591 // and we didn't find one. We're finished parsing this instruction.
592 break;
593 } else {
David Netoac508b02015-10-09 15:48:09 -0400594 return context->diagnostic()
595 << "Expected operand, found end of stream.";
David Neto78c3b432015-08-27 13:03:52 -0400596 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100597 }
David Neto78c3b432015-08-27 13:03:52 -0400598 assert(error == SPV_SUCCESS && "Somebody added another way to fail");
599
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400600 if (context->isStartOfNewInst()) {
David Neto78c3b432015-08-27 13:03:52 -0400601 if (spvOperandIsOptional(type)) {
602 break;
603 } else {
David Netoac508b02015-10-09 15:48:09 -0400604 return context->diagnostic()
605 << "Expected operand, found next instruction instead.";
David Neto78c3b432015-08-27 13:03:52 -0400606 }
607 }
608
609 std::string operandValue;
Lei Zhang6032b982016-03-15 16:52:40 -0400610 error = context->getWord(&operandValue, &nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400611 if (error) return context->diagnostic(error) << "Internal Error";
David Neto78c3b432015-08-27 13:03:52 -0400612
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400613 error = spvTextEncodeOperand(grammar, context, type, operandValue.c_str(),
614 pInst, &expectedOperands);
David Neto78c3b432015-08-27 13:03:52 -0400615
616 if (error == SPV_FAILED_MATCH && spvOperandIsOptional(type))
617 return SPV_SUCCESS;
618
Lei Zhang40056702015-09-11 14:31:27 -0400619 if (error) return error;
David Neto78c3b432015-08-27 13:03:52 -0400620
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400621 context->setPosition(nextPosition);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100622 }
623 }
624
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400625 if (spvOpcodeGeneratesType(pInst->opcode)) {
626 if (context->recordTypeDefinition(pInst) != SPV_SUCCESS) {
627 return SPV_ERROR_INVALID_TEXT;
628 }
629 } else if (opcodeEntry->hasType) {
630 // SPIR-V dictates that if an instruction has both a return value and a
631 // type ID then the type id is first, and the return value is second.
632 assert(opcodeEntry->hasResult &&
633 "Unknown opcode: has a type but no result.");
634 context->recordTypeIdForValue(pInst->words[2], pInst->words[1]);
635 }
636
David Netob5dc8fc2015-10-06 16:22:00 -0400637 if (pInst->words.size() > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
David Netoac508b02015-10-09 15:48:09 -0400638 return context->diagnostic()
639 << "Instruction too long: " << pInst->words.size()
640 << " words, but the limit is "
641 << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX;
David Netob5dc8fc2015-10-06 16:22:00 -0400642 }
643
David Netod9ad0502015-11-24 18:37:24 -0500644 pInst->words[0] =
645 spvOpcodeMake(uint16_t(pInst->words.size()), opcodeEntry->opcode);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100646
647 return SPV_SUCCESS;
648}
649
David Netod9ad0502015-11-24 18:37:24 -0500650enum { kAssemblerVersion = 0 };
David Neto14b93e42015-11-12 18:33:47 -0500651
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400652// Populates a binary stream's |header|. The target environment is specified via
653// |env| and Id bound is via |bound|.
654spv_result_t SetHeader(spv_target_env env, const uint32_t bound,
655 uint32_t* header) {
656 if (!header) return SPV_ERROR_INVALID_BINARY;
David Neto0b981682015-10-27 15:51:34 -0400657
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400658 header[SPV_INDEX_MAGIC_NUMBER] = SpvMagicNumber;
659 header[SPV_INDEX_VERSION_NUMBER] = spvVersionForTargetEnv(env);
660 header[SPV_INDEX_GENERATOR_NUMBER] =
David Neto14b93e42015-11-12 18:33:47 -0500661 SPV_GENERATOR_WORD(SPV_GENERATOR_KHRONOS_ASSEMBLER, kAssemblerVersion);
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400662 header[SPV_INDEX_BOUND] = bound;
663 header[SPV_INDEX_SCHEMA] = 0; // NOTE: Reserved
David Neto0b981682015-10-27 15:51:34 -0400664
665 return SPV_SUCCESS;
666}
667
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400668// Collects all numeric ids in the module source into |numeric_ids|.
669// This function is essentially a dry-run of spvTextToBinary.
dan sinclair3dad1cd2018-07-07 09:38:00 -0400670spv_result_t GetNumericIds(const spvtools::AssemblyGrammar& grammar,
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400671 const spvtools::MessageConsumer& consumer,
672 const spv_text text,
673 std::set<uint32_t>* numeric_ids) {
dan sinclair3dad1cd2018-07-07 09:38:00 -0400674 spvtools::AssemblyContext context(text, consumer);
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400675
676 if (!text->str) return context.diagnostic() << "Missing assembly text.";
677
678 if (!grammar.isValid()) {
679 return SPV_ERROR_INVALID_TABLE;
680 }
681
682 // Skip past whitespace and comments.
683 context.advance();
684
685 while (context.hasText()) {
686 spv_instruction_t inst;
687
688 if (spvTextEncodeOpcode(grammar, &context, &inst)) {
689 return SPV_ERROR_INVALID_TEXT;
690 }
691
692 if (context.advance()) break;
693 }
694
695 *numeric_ids = context.GetNumericIds();
696 return SPV_SUCCESS;
697}
698
David Netoc9786432015-09-01 18:05:14 -0400699// Translates a given assembly language module into binary form.
700// If a diagnostic is generated, it is not yet marked as being
701// for a text-based input.
dan sinclair3dad1cd2018-07-07 09:38:00 -0400702spv_result_t spvTextToBinaryInternal(const spvtools::AssemblyGrammar& grammar,
Diego Novillod2938e42017-11-08 12:40:02 -0500703 const spvtools::MessageConsumer& consumer,
704 const spv_text text,
705 const uint32_t options,
706 spv_binary* pBinary) {
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400707 // The ids in this set will have the same values both in source and binary.
708 // All other ids will be generated by filling in the gaps.
709 std::set<uint32_t> ids_to_preserve;
710
711 if (options & SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS) {
712 // Collect all numeric ids from the source into ids_to_preserve.
713 const spv_result_t result =
714 GetNumericIds(grammar, consumer, text, &ids_to_preserve);
715 if (result != SPV_SUCCESS) return result;
716 }
717
dan sinclair3dad1cd2018-07-07 09:38:00 -0400718 spvtools::AssemblyContext context(text, consumer, std::move(ids_to_preserve));
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400719
David Neto201caf72015-11-04 17:38:17 -0500720 if (!text->str) return context.diagnostic() << "Missing assembly text.";
David Netoac508b02015-10-09 15:48:09 -0400721
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400722 if (!grammar.isValid()) {
Lei Zhang40056702015-09-11 14:31:27 -0400723 return SPV_ERROR_INVALID_TABLE;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400724 }
Lei Zhang40056702015-09-11 14:31:27 -0400725 if (!pBinary) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100726
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100727 std::vector<spv_instruction_t> instructions;
728
David Netoea633a62015-11-02 11:40:59 -0500729 // Skip past whitespace and comments.
730 context.advance();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100731
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400732 while (context.hasText()) {
David Netob5dc8fc2015-10-06 16:22:00 -0400733 instructions.push_back({});
734 spv_instruction_t& inst = instructions.back();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100735
Lei Zhang9042f402015-11-05 17:45:09 -0500736 if (spvTextEncodeOpcode(grammar, &context, &inst)) {
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400737 return SPV_ERROR_INVALID_TEXT;
Lei Zhang40056702015-09-11 14:31:27 -0400738 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400739
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400740 if (context.advance()) break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100741 }
742
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100743 size_t totalSize = SPV_INDEX_INSTRUCTION;
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400744 for (auto& inst : instructions) {
David Netob5dc8fc2015-10-06 16:22:00 -0400745 totalSize += inst.words.size();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100746 }
747
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400748 uint32_t* data = new uint32_t[totalSize];
Lei Zhang40056702015-09-11 14:31:27 -0400749 if (!data) return SPV_ERROR_OUT_OF_MEMORY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100750 uint64_t currentIndex = SPV_INDEX_INSTRUCTION;
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400751 for (auto& inst : instructions) {
Lei Zhang6483bd72015-10-14 17:02:39 -0400752 memcpy(data + currentIndex, inst.words.data(),
753 sizeof(uint32_t) * inst.words.size());
David Netob5dc8fc2015-10-06 16:22:00 -0400754 currentIndex += inst.words.size();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100755 }
756
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400757 if (auto error = SetHeader(grammar.target_env(), context.getBound(), data))
758 return error;
David Netoe4945de2015-10-28 13:50:32 -0400759
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100760 spv_binary binary = new spv_binary_t();
Lei Zhang40056702015-09-11 14:31:27 -0400761 if (!binary) {
762 delete[] data;
763 return SPV_ERROR_OUT_OF_MEMORY;
764 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100765 binary->code = data;
766 binary->wordCount = totalSize;
767
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100768 *pBinary = binary;
769
770 return SPV_SUCCESS;
771}
772
Lei Zhange78a7c12015-09-10 17:07:21 -0400773} // anonymous namespace
David Netoc9786432015-09-01 18:05:14 -0400774
Lei Zhang972788b2015-11-12 13:48:30 -0500775spv_result_t spvTextToBinary(const spv_const_context context,
776 const char* input_text,
Lei Zhangdf920ec2015-11-11 11:33:26 -0500777 const size_t input_text_size, spv_binary* pBinary,
778 spv_diagnostic* pDiagnostic) {
Diego Novillod2938e42017-11-08 12:40:02 -0500779 return spvTextToBinaryWithOptions(context, input_text, input_text_size,
780 SPV_BINARY_TO_TEXT_OPTION_NONE, pBinary,
781 pDiagnostic);
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400782}
783
Diego Novillod2938e42017-11-08 12:40:02 -0500784spv_result_t spvTextToBinaryWithOptions(const spv_const_context context,
785 const char* input_text,
786 const size_t input_text_size,
787 const uint32_t options,
788 spv_binary* pBinary,
789 spv_diagnostic* pDiagnostic) {
Lei Zhang755f97f2016-09-02 18:06:18 -0400790 spv_context_t hijack_context = *context;
791 if (pDiagnostic) {
792 *pDiagnostic = nullptr;
dan sinclair3dad1cd2018-07-07 09:38:00 -0400793 spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
Lei Zhang755f97f2016-09-02 18:06:18 -0400794 }
795
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400796 spv_text_t text = {input_text, input_text_size};
dan sinclair3dad1cd2018-07-07 09:38:00 -0400797 spvtools::AssemblyGrammar grammar(&hijack_context);
Lei Zhang9042f402015-11-05 17:45:09 -0500798
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400799 spv_result_t result = spvTextToBinaryInternal(
800 grammar, hijack_context.consumer, &text, options, pBinary);
David Netoc9786432015-09-01 18:05:14 -0400801 if (pDiagnostic && *pDiagnostic) (*pDiagnostic)->isTextSource = true;
802
803 return result;
804}
805
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100806void spvTextDestroy(spv_text text) {
Lei Zhang40056702015-09-11 14:31:27 -0400807 if (!text) return;
Eric Engestromeb6ae972016-02-18 23:41:16 +0000808 delete[] text->str;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100809 delete text;
810}