blob: 8c48814b056650a0dd31e80040ca099937986b3a [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"
Lei Zhang7a222e42015-11-11 12:40:25 -050039#include "table.h"
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040040#include "text_handler.h"
Andrew Woloszynf731cbf2015-10-23 09:53:58 -040041#include "util/bitutils.h"
qining1773b952016-09-01 14:27:04 -040042#include "util/parse_number.h"
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010043
Andrew Woloszyn13804e52015-09-22 15:50:33 -040044bool spvIsValidIDCharacter(const char value) {
45 return value == '_' || 0 != ::isalnum(value);
46}
47
48// Returns true if the given string represents a valid ID name.
Dejan Mircevski14c4b102015-09-29 17:07:21 -040049bool spvIsValidID(const char* textValue) {
50 const char* c = textValue;
Andrew Woloszyn13804e52015-09-22 15:50:33 -040051 for (; *c != '\0'; ++c) {
52 if (!spvIsValidIDCharacter(*c)) {
53 return false;
54 }
55 }
56 // If the string was empty, then the ID also is not valid.
57 return c != textValue;
58}
59
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040060// Text API
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010061
Dejan Mircevski903f9d62015-09-28 17:04:39 -040062spv_result_t spvTextToLiteral(const char* textValue, spv_literal_t* pLiteral) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010063 bool isSigned = false;
David Netoaffa6962015-08-24 15:33:14 -040064 int numPeriods = 0;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010065 bool isString = false;
66
David Netoaffa6962015-08-24 15:33:14 -040067 const size_t len = strlen(textValue);
David Neto98290a22015-08-24 16:27:02 -040068 if (len == 0) return SPV_FAILED_MATCH;
69
David Netoaffa6962015-08-24 15:33:14 -040070 for (uint64_t index = 0; index < len; ++index) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010071 switch (textValue[index]) {
72 case '0':
73 case '1':
74 case '2':
75 case '3':
76 case '4':
77 case '5':
78 case '6':
79 case '7':
80 case '8':
81 case '9':
82 break;
83 case '.':
David Netoaffa6962015-08-24 15:33:14 -040084 numPeriods++;
85 break;
86 case '-':
87 if (index == 0) {
88 isSigned = true;
89 } else {
90 isString = true;
91 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010092 break;
93 default:
94 isString = true;
Lei Zhange78a7c12015-09-10 17:07:21 -040095 index = len; // break out of the loop too.
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +010096 break;
97 }
98 }
99
David Netoaffa6962015-08-24 15:33:14 -0400100 pLiteral->type = spv_literal_type_t(99);
101
Lei Zhange78a7c12015-09-10 17:07:21 -0400102 if (isString || numPeriods > 1 || (isSigned && len == 1)) {
David Neto98290a22015-08-24 16:27:02 -0400103 if (len < 2 || textValue[0] != '"' || textValue[len - 1] != '"')
104 return SPV_FAILED_MATCH;
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400105 bool escaping = false;
Lei Zhang6483bd72015-10-14 17:02:39 -0400106 for (const char* val = textValue + 1; val != textValue + len - 1; ++val) {
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400107 if ((*val == '\\') && (!escaping)) {
108 escaping = true;
109 } else {
110 // Have to save space for the null-terminator
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500111 if (pLiteral->str.size() >= SPV_LIMIT_LITERAL_STRING_BYTES_MAX)
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400112 return SPV_ERROR_OUT_OF_MEMORY;
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500113 pLiteral->str.push_back(*val);
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400114 escaping = false;
Andrew Woloszyn3e69cd12015-10-14 12:44:19 -0400115 }
116 }
117
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100118 pLiteral->type = SPV_LITERAL_TYPE_STRING;
David Netoaffa6962015-08-24 15:33:14 -0400119 } else if (numPeriods == 1) {
120 double d = std::strtod(textValue, nullptr);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100121 float f = (float)d;
122 if (d == (double)f) {
123 pLiteral->type = SPV_LITERAL_TYPE_FLOAT_32;
124 pLiteral->value.f = f;
125 } else {
126 pLiteral->type = SPV_LITERAL_TYPE_FLOAT_64;
127 pLiteral->value.d = d;
128 }
129 } else if (isSigned) {
130 int64_t i64 = strtoll(textValue, nullptr, 10);
131 int32_t i32 = (int32_t)i64;
132 if (i64 == (int64_t)i32) {
133 pLiteral->type = SPV_LITERAL_TYPE_INT_32;
134 pLiteral->value.i32 = i32;
135 } else {
136 pLiteral->type = SPV_LITERAL_TYPE_INT_64;
137 pLiteral->value.i64 = i64;
138 }
139 } else {
140 uint64_t u64 = strtoull(textValue, nullptr, 10);
141 uint32_t u32 = (uint32_t)u64;
142 if (u64 == (uint64_t)u32) {
143 pLiteral->type = SPV_LITERAL_TYPE_UINT_32;
144 pLiteral->value.u32 = u32;
145 } else {
146 pLiteral->type = SPV_LITERAL_TYPE_UINT_64;
147 pLiteral->value.u64 = u64;
148 }
149 }
150
151 return SPV_SUCCESS;
152}
153
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400154namespace {
155
156/// Parses an immediate integer from text, guarding against overflow. If
157/// successful, adds the parsed value to pInst, advances the context past it,
158/// and returns SPV_SUCCESS. Otherwise, leaves pInst alone, emits diagnostics,
159/// and returns SPV_ERROR_INVALID_TEXT.
160spv_result_t encodeImmediate(libspirv::AssemblyContext* context,
161 const char* text, spv_instruction_t* pInst) {
162 assert(*text == '!');
David Neto78e677b2015-10-05 13:28:46 -0400163 uint32_t parse_result;
qining1773b952016-09-01 14:27:04 -0400164 if (!spvutils::ParseNumber(text + 1, &parse_result)) {
165 return context->diagnostic(SPV_ERROR_INVALID_TEXT)
166 << "Invalid immediate integer: !" << text + 1;
167 }
David Neto78e677b2015-10-05 13:28:46 -0400168 context->binaryEncodeU32(parse_result, pInst);
Ben Vanik01c8d7a2015-11-22 08:32:53 -0800169 context->seekForward(static_cast<uint32_t>(strlen(text)));
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400170 return SPV_SUCCESS;
171}
172
173} // anonymous namespace
174
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400175/// @brief Translate an Opcode operand to binary form
176///
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400177/// @param[in] grammar the grammar to use for compilation
178/// @param[in, out] context the dynamic compilation info
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400179/// @param[in] type of the operand
180/// @param[in] textValue word of text to be parsed
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400181/// @param[out] pInst return binary Opcode
182/// @param[in,out] pExpectedOperands the operand types expected
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400183///
184/// @return result code
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400185spv_result_t spvTextEncodeOperand(const libspirv::AssemblyGrammar& grammar,
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400186 libspirv::AssemblyContext* context,
187 const spv_operand_type_t type,
188 const char* textValue,
189 spv_instruction_t* pInst,
190 spv_operand_pattern_t* pExpectedOperands) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100191 // NOTE: Handle immediate int in the stream
192 if ('!' == textValue[0]) {
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400193 if (auto error = encodeImmediate(context, textValue, pInst)) {
194 return error;
Lei Zhang40056702015-09-11 14:31:27 -0400195 }
Dejan Mircevski897bff92015-09-29 10:38:18 -0400196 *pExpectedOperands =
197 spvAlternatePatternFollowingImmediate(*pExpectedOperands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100198 return SPV_SUCCESS;
199 }
200
David Neto51013d12015-10-14 11:31:51 -0400201 // Optional literal operands can fail to parse. In that case use
202 // SPV_FAILED_MATCH to avoid emitting a diagostic. Use the following
203 // for those situations.
204 spv_result_t error_code_for_literals =
205 spvOperandIsOptional(type) ? SPV_FAILED_MATCH : SPV_ERROR_INVALID_TEXT;
206
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100207 switch (type) {
David Netoe3f70b92015-08-27 13:50:05 -0400208 case SPV_OPERAND_TYPE_ID:
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400209 case SPV_OPERAND_TYPE_TYPE_ID:
David Neto201caf72015-11-04 17:38:17 -0500210 case SPV_OPERAND_TYPE_RESULT_ID:
211 case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
212 case SPV_OPERAND_TYPE_SCOPE_ID:
213 case SPV_OPERAND_TYPE_OPTIONAL_ID: {
Lei Zhangabafd5e2015-08-21 11:52:29 -0400214 if ('%' == textValue[0]) {
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100215 textValue++;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100216 } else {
David Netoac508b02015-10-09 15:48:09 -0400217 return context->diagnostic() << "Expected id to start with %.";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100218 }
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400219 if (!spvIsValidID(textValue)) {
David Netoac508b02015-10-09 15:48:09 -0400220 return context->diagnostic() << "Invalid ID " << textValue;
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400221 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400222 const uint32_t id = context->spvNamedIdAssignOrGet(textValue);
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400223 if (type == SPV_OPERAND_TYPE_TYPE_ID) pInst->resultTypeId = id;
David Netob5dc8fc2015-10-06 16:22:00 -0400224 spvInstructionAddWord(pInst, id);
David Neto2ae4a682015-11-09 18:55:42 -0500225
226 // Set the extended instruction type.
227 // The import set id is the 3rd operand of OpExtInst.
228 if (pInst->opcode == SpvOpExtInst && pInst->words.size() == 4) {
229 auto ext_inst_type = context->getExtInstTypeForId(pInst->words[3]);
230 if (ext_inst_type == SPV_EXT_INST_TYPE_NONE) {
231 return context->diagnostic()
232 << "Invalid extended instruction import Id "
233 << pInst->words[2];
234 }
235 pInst->extInstType = ext_inst_type;
236 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100237 } break;
David Neto201caf72015-11-04 17:38:17 -0500238
David Neto445ce442015-10-15 15:22:06 -0400239 case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
240 // The assembler accepts the symbolic name for an extended instruction,
241 // and emits its corresponding number.
242 spv_ext_inst_desc extInst;
243 if (grammar.lookupExtInst(pInst->extInstType, textValue, &extInst)) {
244 return context->diagnostic() << "Invalid extended instruction name '"
245 << textValue << "'.";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100246 }
David Neto445ce442015-10-15 15:22:06 -0400247 spvInstructionAddWord(pInst, extInst->ext_inst);
248
249 // Prepare to parse the operands for the extended instructions.
Chris Forbes78338d52017-06-27 16:28:22 -0700250 spvPushOperandTypes(extInst->operandTypes, pExpectedOperands);
David Neto0f166be2015-11-11 01:56:49 -0500251 } break;
David Neto445ce442015-10-15 15:22:06 -0400252
David Neto0f166be2015-11-11 01:56:49 -0500253 case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: {
254 // The assembler accepts the symbolic name for the opcode, but without
255 // the "Op" prefix. For example, "IAdd" is accepted. The number
256 // of the opcode is emitted.
257 SpvOp opcode;
258 if (grammar.lookupSpecConstantOpcode(textValue, &opcode)) {
259 return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
260 << " '" << textValue << "'.";
261 }
262 spv_opcode_desc opcodeEntry = nullptr;
263 if (grammar.lookupOpcode(opcode, &opcodeEntry)) {
264 return context->diagnostic(SPV_ERROR_INTERNAL)
265 << "OpSpecConstant opcode table out of sync";
266 }
267 spvInstructionAddWord(pInst, uint32_t(opcodeEntry->opcode));
268
269 // Prepare to parse the operands for the opcode. Except skip the
270 // type Id and result Id, since they've already been processed.
271 assert(opcodeEntry->hasType);
272 assert(opcodeEntry->hasResult);
273 assert(opcodeEntry->numTypes >= 2);
Chris Forbes78338d52017-06-27 16:28:22 -0700274 spvPushOperandTypes(opcodeEntry->operandTypes + 2, pExpectedOperands);
David Neto445ce442015-10-15 15:22:06 -0400275 } break;
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400276
David Neto201caf72015-11-04 17:38:17 -0500277 case SPV_OPERAND_TYPE_LITERAL_INTEGER:
278 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER: {
279 // The current operand is an *unsigned* 32-bit integer.
280 // That's just how the grammar works.
281 libspirv::IdType expected_type = {
282 32, false, libspirv::IdTypeClass::kScalarIntegerType};
David Neto78e677b2015-10-05 13:28:46 -0400283 if (auto error = context->binaryEncodeNumericLiteral(
David Neto51013d12015-10-14 11:31:51 -0400284 textValue, error_code_for_literals, expected_type, pInst)) {
David Neto78e677b2015-10-05 13:28:46 -0400285 return error;
David Neto51013d12015-10-14 11:31:51 -0400286 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100287 } break;
David Neto201caf72015-11-04 17:38:17 -0500288
289 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_NUMBER:
290 // This is a context-independent literal number which can be a 32-bit
291 // number of floating point value.
292 if (auto error = context->binaryEncodeNumericLiteral(
293 textValue, error_code_for_literals, libspirv::kUnknownType,
294 pInst)) {
295 return error;
296 }
297 break;
298
299 case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER:
300 case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER: {
301 libspirv::IdType expected_type = libspirv::kUnknownType;
302 // The encoding for OpConstant, OpSpecConstant and OpSwitch all
303 // depend on either their own result-id or the result-id of
304 // one of their parameters.
305 if (SpvOpConstant == pInst->opcode ||
306 SpvOpSpecConstant == pInst->opcode) {
307 // The type of the literal is determined by the type Id of the
308 // instruction.
309 expected_type =
310 context->getTypeOfTypeGeneratingValue(pInst->resultTypeId);
311 if (!libspirv::isScalarFloating(expected_type) &&
312 !libspirv::isScalarIntegral(expected_type)) {
313 spv_opcode_desc d;
314 const char* opcode_name = "opcode";
315 if (SPV_SUCCESS == grammar.lookupOpcode(pInst->opcode, &d)) {
316 opcode_name = d->name;
317 }
318 return context->diagnostic()
319 << "Type for " << opcode_name
320 << " must be a scalar floating point or integer type";
321 }
322 } else if (pInst->opcode == SpvOpSwitch) {
323 // The type of the literal is the same as the type of the selector.
324 expected_type = context->getTypeOfValueInstruction(pInst->words[1]);
325 if (!libspirv::isScalarIntegral(expected_type)) {
326 return context->diagnostic()
327 << "The selector operand for OpSwitch must be the result"
328 " of an instruction that generates an integer scalar";
329 }
330 }
331 if (auto error = context->binaryEncodeNumericLiteral(
332 textValue, error_code_for_literals, expected_type, pInst)) {
333 return error;
334 }
335 } break;
336
David Neto78c3b432015-08-27 13:03:52 -0400337 case SPV_OPERAND_TYPE_LITERAL_STRING:
338 case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
Lei Zhang6d415812015-09-15 13:36:21 -0400339 spv_literal_t literal = {};
340 spv_result_t error = spvTextToLiteral(textValue, &literal);
341 if (error != SPV_SUCCESS) {
342 if (error == SPV_ERROR_OUT_OF_MEMORY) return error;
David Neto51013d12015-10-14 11:31:51 -0400343 return context->diagnostic(error_code_for_literals)
344 << "Invalid literal string '" << textValue << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400345 }
Lei Zhang6d415812015-09-15 13:36:21 -0400346 if (literal.type != SPV_LITERAL_TYPE_STRING) {
David Neto51013d12015-10-14 11:31:51 -0400347 return context->diagnostic()
David Netoac508b02015-10-09 15:48:09 -0400348 << "Expected literal string, found literal number '" << textValue
349 << "'.";
Lei Zhang6d415812015-09-15 13:36:21 -0400350 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100351
352 // NOTE: Special case for extended instruction library import
Lei Zhangb36e7042015-10-28 13:40:52 -0400353 if (SpvOpExtInstImport == pInst->opcode) {
David Neto2ae4a682015-11-09 18:55:42 -0500354 const spv_ext_inst_type_t ext_inst_type =
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500355 spvExtInstImportTypeGet(literal.str.c_str());
David Neto2ae4a682015-11-09 18:55:42 -0500356 if (SPV_EXT_INST_TYPE_NONE == ext_inst_type) {
357 return context->diagnostic()
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500358 << "Invalid extended instruction import '" << literal.str
David Neto2ae4a682015-11-09 18:55:42 -0500359 << "'";
360 }
David Neto677e0c72016-01-05 14:56:02 -0500361 if ((error = context->recordIdAsExtInstImport(pInst->words[1],
362 ext_inst_type)))
David Neto2ae4a682015-11-09 18:55:42 -0500363 return error;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100364 }
365
Lei Zhang16f3ddf2015-11-11 15:37:01 -0500366 if (context->binaryEncodeString(literal.str.c_str(), pInst))
Lei Zhang40056702015-09-11 14:31:27 -0400367 return SPV_ERROR_INVALID_TEXT;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100368 } break;
David Neto36b0c0f2015-09-16 18:32:54 -0400369 case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
370 case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
371 case SPV_OPERAND_TYPE_LOOP_CONTROL:
David Neto2889a0c2016-02-15 13:50:00 -0500372 case SPV_OPERAND_TYPE_IMAGE:
David Netoee1b3bb2015-09-18 11:19:18 -0400373 case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
David Neto5bf88fc2015-09-17 17:06:10 -0400374 case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
David Neto36b0c0f2015-09-16 18:32:54 -0400375 case SPV_OPERAND_TYPE_SELECTION_CONTROL: {
376 uint32_t value;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400377 if (grammar.parseMaskOperand(type, textValue, &value)) {
David Netoac508b02015-10-09 15:48:09 -0400378 return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
David Netod9ad0502015-11-24 18:37:24 -0500379 << " operand '" << textValue << "'.";
David Neto36b0c0f2015-09-16 18:32:54 -0400380 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400381 if (auto error = context->binaryEncodeU32(value, pInst)) return error;
David Neto5bf88fc2015-09-17 17:06:10 -0400382 // Prepare to parse the operands for this logical operand.
Chris Forbes78338d52017-06-27 16:28:22 -0700383 grammar.pushOperandTypesForMask(type, value, pExpectedOperands);
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400384 } break;
385 case SPV_OPERAND_TYPE_OPTIONAL_CIV: {
386 auto error = spvTextEncodeOperand(
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400387 grammar, context, SPV_OPERAND_TYPE_OPTIONAL_LITERAL_NUMBER, textValue,
388 pInst, pExpectedOperands);
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400389 if (error == SPV_FAILED_MATCH) {
390 // It's not a literal number -- is it a literal string?
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400391 error = spvTextEncodeOperand(grammar, context,
392 SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING,
393 textValue, pInst, pExpectedOperands);
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400394 }
395 if (error == SPV_FAILED_MATCH) {
396 // It's not a literal -- is it an ID?
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400397 error =
398 spvTextEncodeOperand(grammar, context, SPV_OPERAND_TYPE_OPTIONAL_ID,
399 textValue, pInst, pExpectedOperands);
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400400 }
401 if (error) {
David Netoac508b02015-10-09 15:48:09 -0400402 return context->diagnostic(error)
403 << "Invalid word following !<integer>: " << textValue;
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400404 }
405 if (pExpectedOperands->empty()) {
406 pExpectedOperands->push_back(SPV_OPERAND_TYPE_OPTIONAL_CIV);
407 }
David Neto36b0c0f2015-09-16 18:32:54 -0400408 } break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100409 default: {
410 // NOTE: All non literal operands are handled here using the operand
411 // table.
412 spv_operand_desc entry;
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400413 if (grammar.lookupOperand(type, textValue, strlen(textValue), &entry)) {
David Netoac508b02015-10-09 15:48:09 -0400414 return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
415 << " '" << textValue << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400416 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400417 if (context->binaryEncodeU32(entry->value, pInst)) {
David Netoac508b02015-10-09 15:48:09 -0400418 return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
419 << " '" << textValue << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400420 }
David Neto78c3b432015-08-27 13:03:52 -0400421
422 // Prepare to parse the operands for this logical operand.
Chris Forbes78338d52017-06-27 16:28:22 -0700423 spvPushOperandTypes(entry->operandTypes, pExpectedOperands);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100424 } break;
425 }
426 return SPV_SUCCESS;
427}
428
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400429namespace {
430
431/// Encodes an instruction started by !<integer> at the given position in text.
432///
433/// Puts the encoded words into *pInst. If successful, moves position past the
434/// instruction and returns SPV_SUCCESS. Otherwise, returns an error code and
435/// leaves position pointing to the error in text.
436spv_result_t encodeInstructionStartingWithImmediate(
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400437 const libspirv::AssemblyGrammar& grammar,
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400438 libspirv::AssemblyContext* context, spv_instruction_t* pInst) {
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400439 std::string firstWord;
440 spv_position_t nextPosition = {};
Lei Zhang6032b982016-03-15 16:52:40 -0400441 auto error = context->getWord(&firstWord, &nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400442 if (error) return context->diagnostic(error) << "Internal Error";
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400443
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400444 if ((error = encodeImmediate(context, firstWord.c_str(), pInst))) {
445 return error;
Lei Zhang40056702015-09-11 14:31:27 -0400446 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400447 while (context->advance() != SPV_END_OF_STREAM) {
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400448 // A beginning of a new instruction means we're done.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400449 if (context->isStartOfNewInst()) return SPV_SUCCESS;
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400450
451 // Otherwise, there must be an operand that's either a literal, an ID, or
452 // an immediate.
453 std::string operandValue;
Lei Zhang6032b982016-03-15 16:52:40 -0400454 if ((error = context->getWord(&operandValue, &nextPosition)))
David Netoac508b02015-10-09 15:48:09 -0400455 return context->diagnostic(error) << "Internal Error";
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400456
David Netoac508b02015-10-09 15:48:09 -0400457 if (operandValue == "=")
458 return context->diagnostic() << firstWord << " not allowed before =.";
Dejan Mircevskie3a19c02015-09-11 15:03:54 -0400459
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400460 // Needed to pass to spvTextEncodeOpcode(), but it shouldn't ever be
461 // expanded.
462 spv_operand_pattern_t dummyExpectedOperands;
463 error = spvTextEncodeOperand(
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400464 grammar, context, SPV_OPERAND_TYPE_OPTIONAL_CIV, operandValue.c_str(),
465 pInst, &dummyExpectedOperands);
Lei Zhang40056702015-09-11 14:31:27 -0400466 if (error) return error;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400467 context->setPosition(nextPosition);
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400468 }
469 return SPV_SUCCESS;
470}
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400471
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400472/// @brief Translate single Opcode and operands to binary form
473///
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400474/// @param[in] grammar the grammar to use for compilation
475/// @param[in, out] context the dynamic compilation info
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400476/// @param[in] text stream to translate
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400477/// @param[out] pInst returned binary Opcode
478/// @param[in,out] pPosition in the text stream
Andrew Woloszyn13804e52015-09-22 15:50:33 -0400479///
480/// @return result code
Dejan Mircevski14c4b102015-09-29 17:07:21 -0400481spv_result_t spvTextEncodeOpcode(const libspirv::AssemblyGrammar& grammar,
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400482 libspirv::AssemblyContext* context,
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400483 spv_instruction_t* pInst) {
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400484 // Check for !<integer> first.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400485 if ('!' == context->peek()) {
486 return encodeInstructionStartingWithImmediate(grammar, context, pInst);
Dejan Mircevskif79519c2015-09-11 00:43:11 -0400487 }
488
Lei Zhang06efdc52015-09-10 14:00:00 -0400489 std::string firstWord;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100490 spv_position_t nextPosition = {};
Lei Zhang6032b982016-03-15 16:52:40 -0400491 spv_result_t error = context->getWord(&firstWord, &nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400492 if (error) return context->diagnostic() << "Internal Error";
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100493
Lei Zhang06efdc52015-09-10 14:00:00 -0400494 std::string opcodeName;
Lei Zhangdfc50082015-08-21 11:50:55 -0400495 std::string result_id;
496 spv_position_t result_id_position = {};
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400497 if (context->startsWithOp()) {
Lei Zhang06efdc52015-09-10 14:00:00 -0400498 opcodeName = firstWord;
499 } else {
Lei Zhang06efdc52015-09-10 14:00:00 -0400500 result_id = firstWord;
Lei Zhang40056702015-09-11 14:31:27 -0400501 if ('%' != result_id.front()) {
David Netoac508b02015-10-09 15:48:09 -0400502 return context->diagnostic()
503 << "Expected <opcode> or <result-id> at the beginning "
504 "of an instruction, found '"
505 << result_id << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400506 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400507 result_id_position = context->position();
Lei Zhang06efdc52015-09-10 14:00:00 -0400508
509 // The '=' sign.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400510 context->setPosition(nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400511 if (context->advance())
512 return context->diagnostic() << "Expected '=', found end of stream.";
Lei Zhangdfc50082015-08-21 11:50:55 -0400513 std::string equal_sign;
Lei Zhang6032b982016-03-15 16:52:40 -0400514 error = context->getWord(&equal_sign, &nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400515 if ("=" != equal_sign)
516 return context->diagnostic() << "'=' expected after result id.";
Lei Zhangdfc50082015-08-21 11:50:55 -0400517
518 // The <opcode> after the '=' sign.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400519 context->setPosition(nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400520 if (context->advance())
521 return context->diagnostic() << "Expected opcode, found end of stream.";
Lei Zhang6032b982016-03-15 16:52:40 -0400522 error = context->getWord(&opcodeName, &nextPosition);
Lei Zhang6483bd72015-10-14 17:02:39 -0400523 if (error) return context->diagnostic(error) << "Internal Error";
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400524 if (!context->startsWithOp()) {
David Netoac508b02015-10-09 15:48:09 -0400525 return context->diagnostic() << "Invalid Opcode prefix '" << opcodeName
526 << "'.";
Lei Zhang40056702015-09-11 14:31:27 -0400527 }
Lei Zhangdfc50082015-08-21 11:50:55 -0400528 }
529
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100530 // NOTE: The table contains Opcode names without the "Op" prefix.
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400531 const char* pInstName = opcodeName.data() + 2;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100532
533 spv_opcode_desc opcodeEntry;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400534 error = grammar.lookupOpcode(pInstName, &opcodeEntry);
Lei Zhang40056702015-09-11 14:31:27 -0400535 if (error) {
Lei Zhang6032b982016-03-15 16:52:40 -0400536 return context->diagnostic(error) << "Invalid Opcode name '" << opcodeName
537 << "'";
Lei Zhang40056702015-09-11 14:31:27 -0400538 }
Lei Zhang9042f402015-11-05 17:45:09 -0500539 if (opcodeEntry->hasResult && result_id.empty()) {
540 return context->diagnostic()
541 << "Expected <result-id> at the beginning of an instruction, found '"
542 << firstWord << "'.";
Lei Zhang06efdc52015-09-10 14:00:00 -0400543 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100544 pInst->opcode = opcodeEntry->opcode;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400545 context->setPosition(nextPosition);
David Netob5dc8fc2015-10-06 16:22:00 -0400546 // Reserve the first word for the instruction.
547 spvInstructionAddWord(pInst, 0);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100548
David Neto78c3b432015-08-27 13:03:52 -0400549 // Maintains the ordered list of expected operand types.
550 // For many instructions we only need the {numTypes, operandTypes}
551 // entries in opcodeEntry. However, sometimes we need to modify
552 // the list as we parse the operands. This occurs when an operand
553 // has its own logical operands (such as the LocalSize operand for
554 // ExecutionMode), or for extended instructions that may have their
555 // own operands depending on the selected extended instruction.
Chris Forbes78338d52017-06-27 16:28:22 -0700556 spv_operand_pattern_t expectedOperands;
557 expectedOperands.reserve(opcodeEntry->numTypes);
558 for (auto i = 0; i < opcodeEntry->numTypes; i++)
559 expectedOperands.push_back(opcodeEntry->operandTypes[opcodeEntry->numTypes - i - 1]);
Lei Zhangdfc50082015-08-21 11:50:55 -0400560
David Neto78c3b432015-08-27 13:03:52 -0400561 while (!expectedOperands.empty()) {
Chris Forbes78338d52017-06-27 16:28:22 -0700562 const spv_operand_type_t type = expectedOperands.back();
563 expectedOperands.pop_back();
David Neto78c3b432015-08-27 13:03:52 -0400564
565 // Expand optional tuples lazily.
Lei Zhange78a7c12015-09-10 17:07:21 -0400566 if (spvExpandOperandSequenceOnce(type, &expectedOperands)) continue;
David Neto78c3b432015-08-27 13:03:52 -0400567
568 if (type == SPV_OPERAND_TYPE_RESULT_ID && !result_id.empty()) {
569 // Handle the <result-id> for value generating instructions.
570 // We've already consumed it from the text stream. Here
571 // we inject its words into the instruction.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400572 spv_position_t temp_pos = context->position();
573 error = spvTextEncodeOperand(grammar, context, SPV_OPERAND_TYPE_RESULT_ID,
574 result_id.c_str(), pInst, nullptr);
575 result_id_position = context->position();
576 // Because we are injecting we have to reset the position afterwards.
577 context->setPosition(temp_pos);
Lei Zhang40056702015-09-11 14:31:27 -0400578 if (error) return error;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100579 } else {
David Neto78c3b432015-08-27 13:03:52 -0400580 // Find the next word.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400581 error = context->advance();
David Neto78c3b432015-08-27 13:03:52 -0400582 if (error == SPV_END_OF_STREAM) {
583 if (spvOperandIsOptional(type)) {
Lei Zhange78a7c12015-09-10 17:07:21 -0400584 // This would have been the last potential operand for the
585 // instruction,
David Neto78c3b432015-08-27 13:03:52 -0400586 // and we didn't find one. We're finished parsing this instruction.
587 break;
588 } else {
David Netoac508b02015-10-09 15:48:09 -0400589 return context->diagnostic()
590 << "Expected operand, found end of stream.";
David Neto78c3b432015-08-27 13:03:52 -0400591 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100592 }
David Neto78c3b432015-08-27 13:03:52 -0400593 assert(error == SPV_SUCCESS && "Somebody added another way to fail");
594
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400595 if (context->isStartOfNewInst()) {
David Neto78c3b432015-08-27 13:03:52 -0400596 if (spvOperandIsOptional(type)) {
597 break;
598 } else {
David Netoac508b02015-10-09 15:48:09 -0400599 return context->diagnostic()
600 << "Expected operand, found next instruction instead.";
David Neto78c3b432015-08-27 13:03:52 -0400601 }
602 }
603
604 std::string operandValue;
Lei Zhang6032b982016-03-15 16:52:40 -0400605 error = context->getWord(&operandValue, &nextPosition);
David Netoac508b02015-10-09 15:48:09 -0400606 if (error) return context->diagnostic(error) << "Internal Error";
David Neto78c3b432015-08-27 13:03:52 -0400607
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400608 error = spvTextEncodeOperand(grammar, context, type, operandValue.c_str(),
609 pInst, &expectedOperands);
David Neto78c3b432015-08-27 13:03:52 -0400610
611 if (error == SPV_FAILED_MATCH && spvOperandIsOptional(type))
612 return SPV_SUCCESS;
613
Lei Zhang40056702015-09-11 14:31:27 -0400614 if (error) return error;
David Neto78c3b432015-08-27 13:03:52 -0400615
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400616 context->setPosition(nextPosition);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100617 }
618 }
619
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400620 if (spvOpcodeGeneratesType(pInst->opcode)) {
621 if (context->recordTypeDefinition(pInst) != SPV_SUCCESS) {
622 return SPV_ERROR_INVALID_TEXT;
623 }
624 } else if (opcodeEntry->hasType) {
625 // SPIR-V dictates that if an instruction has both a return value and a
626 // type ID then the type id is first, and the return value is second.
627 assert(opcodeEntry->hasResult &&
628 "Unknown opcode: has a type but no result.");
629 context->recordTypeIdForValue(pInst->words[2], pInst->words[1]);
630 }
631
David Netob5dc8fc2015-10-06 16:22:00 -0400632 if (pInst->words.size() > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
David Netoac508b02015-10-09 15:48:09 -0400633 return context->diagnostic()
634 << "Instruction too long: " << pInst->words.size()
635 << " words, but the limit is "
636 << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX;
David Netob5dc8fc2015-10-06 16:22:00 -0400637 }
638
David Netod9ad0502015-11-24 18:37:24 -0500639 pInst->words[0] =
640 spvOpcodeMake(uint16_t(pInst->words.size()), opcodeEntry->opcode);
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100641
642 return SPV_SUCCESS;
643}
644
David Netod9ad0502015-11-24 18:37:24 -0500645enum { kAssemblerVersion = 0 };
David Neto14b93e42015-11-12 18:33:47 -0500646
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400647// Populates a binary stream's |header|. The target environment is specified via
648// |env| and Id bound is via |bound|.
649spv_result_t SetHeader(spv_target_env env, const uint32_t bound,
650 uint32_t* header) {
651 if (!header) return SPV_ERROR_INVALID_BINARY;
David Neto0b981682015-10-27 15:51:34 -0400652
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400653 header[SPV_INDEX_MAGIC_NUMBER] = SpvMagicNumber;
654 header[SPV_INDEX_VERSION_NUMBER] = spvVersionForTargetEnv(env);
655 header[SPV_INDEX_GENERATOR_NUMBER] =
David Neto14b93e42015-11-12 18:33:47 -0500656 SPV_GENERATOR_WORD(SPV_GENERATOR_KHRONOS_ASSEMBLER, kAssemblerVersion);
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400657 header[SPV_INDEX_BOUND] = bound;
658 header[SPV_INDEX_SCHEMA] = 0; // NOTE: Reserved
David Neto0b981682015-10-27 15:51:34 -0400659
660 return SPV_SUCCESS;
661}
662
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400663// Collects all numeric ids in the module source into |numeric_ids|.
664// This function is essentially a dry-run of spvTextToBinary.
665spv_result_t GetNumericIds(const libspirv::AssemblyGrammar& grammar,
666 const spvtools::MessageConsumer& consumer,
667 const spv_text text,
668 std::set<uint32_t>* numeric_ids) {
669 libspirv::AssemblyContext context(text, consumer);
670
671 if (!text->str) return context.diagnostic() << "Missing assembly text.";
672
673 if (!grammar.isValid()) {
674 return SPV_ERROR_INVALID_TABLE;
675 }
676
677 // Skip past whitespace and comments.
678 context.advance();
679
680 while (context.hasText()) {
681 spv_instruction_t inst;
682
683 if (spvTextEncodeOpcode(grammar, &context, &inst)) {
684 return SPV_ERROR_INVALID_TEXT;
685 }
686
687 if (context.advance()) break;
688 }
689
690 *numeric_ids = context.GetNumericIds();
691 return SPV_SUCCESS;
692}
693
David Netoc9786432015-09-01 18:05:14 -0400694// Translates a given assembly language module into binary form.
695// If a diagnostic is generated, it is not yet marked as being
696// for a text-based input.
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400697spv_result_t spvTextToBinaryInternal(
698 const libspirv::AssemblyGrammar& grammar,
699 const spvtools::MessageConsumer& consumer, const spv_text text,
700 const uint32_t options, spv_binary* pBinary) {
701 // The ids in this set will have the same values both in source and binary.
702 // All other ids will be generated by filling in the gaps.
703 std::set<uint32_t> ids_to_preserve;
704
705 if (options & SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS) {
706 // Collect all numeric ids from the source into ids_to_preserve.
707 const spv_result_t result =
708 GetNumericIds(grammar, consumer, text, &ids_to_preserve);
709 if (result != SPV_SUCCESS) return result;
710 }
711
712 libspirv::AssemblyContext context(text, consumer, std::move(ids_to_preserve));
713
David Neto201caf72015-11-04 17:38:17 -0500714 if (!text->str) return context.diagnostic() << "Missing assembly text.";
David Netoac508b02015-10-09 15:48:09 -0400715
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400716 if (!grammar.isValid()) {
Lei Zhang40056702015-09-11 14:31:27 -0400717 return SPV_ERROR_INVALID_TABLE;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400718 }
Lei Zhang40056702015-09-11 14:31:27 -0400719 if (!pBinary) return SPV_ERROR_INVALID_POINTER;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100720
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100721 std::vector<spv_instruction_t> instructions;
722
David Netoea633a62015-11-02 11:40:59 -0500723 // Skip past whitespace and comments.
724 context.advance();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100725
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400726 while (context.hasText()) {
David Netob5dc8fc2015-10-06 16:22:00 -0400727 instructions.push_back({});
728 spv_instruction_t& inst = instructions.back();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100729
Lei Zhang9042f402015-11-05 17:45:09 -0500730 if (spvTextEncodeOpcode(grammar, &context, &inst)) {
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400731 return SPV_ERROR_INVALID_TEXT;
Lei Zhang40056702015-09-11 14:31:27 -0400732 }
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400733
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400734 if (context.advance()) break;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100735 }
736
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100737 size_t totalSize = SPV_INDEX_INSTRUCTION;
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400738 for (auto& inst : instructions) {
David Netob5dc8fc2015-10-06 16:22:00 -0400739 totalSize += inst.words.size();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100740 }
741
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400742 uint32_t* data = new uint32_t[totalSize];
Lei Zhang40056702015-09-11 14:31:27 -0400743 if (!data) return SPV_ERROR_OUT_OF_MEMORY;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100744 uint64_t currentIndex = SPV_INDEX_INSTRUCTION;
Dejan Mircevski903f9d62015-09-28 17:04:39 -0400745 for (auto& inst : instructions) {
Lei Zhang6483bd72015-10-14 17:02:39 -0400746 memcpy(data + currentIndex, inst.words.data(),
747 sizeof(uint32_t) * inst.words.size());
David Netob5dc8fc2015-10-06 16:22:00 -0400748 currentIndex += inst.words.size();
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100749 }
750
Lei Zhang6fa3f8a2016-03-31 17:26:31 -0400751 if (auto error = SetHeader(grammar.target_env(), context.getBound(), data))
752 return error;
David Netoe4945de2015-10-28 13:50:32 -0400753
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100754 spv_binary binary = new spv_binary_t();
Lei Zhang40056702015-09-11 14:31:27 -0400755 if (!binary) {
756 delete[] data;
757 return SPV_ERROR_OUT_OF_MEMORY;
758 }
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100759 binary->code = data;
760 binary->wordCount = totalSize;
761
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100762 *pBinary = binary;
763
764 return SPV_SUCCESS;
765}
766
Lei Zhange78a7c12015-09-10 17:07:21 -0400767} // anonymous namespace
David Netoc9786432015-09-01 18:05:14 -0400768
Lei Zhang972788b2015-11-12 13:48:30 -0500769spv_result_t spvTextToBinary(const spv_const_context context,
770 const char* input_text,
Lei Zhangdf920ec2015-11-11 11:33:26 -0500771 const size_t input_text_size, spv_binary* pBinary,
772 spv_diagnostic* pDiagnostic) {
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400773 return spvTextToBinaryWithOptions(
774 context, input_text, input_text_size, SPV_BINARY_TO_TEXT_OPTION_NONE,
775 pBinary, pDiagnostic);
776}
777
778spv_result_t spvTextToBinaryWithOptions(
779 const spv_const_context context, const char* input_text,
780 const size_t input_text_size, const uint32_t options, spv_binary* pBinary,
781 spv_diagnostic* pDiagnostic) {
Lei Zhang755f97f2016-09-02 18:06:18 -0400782 spv_context_t hijack_context = *context;
783 if (pDiagnostic) {
784 *pDiagnostic = nullptr;
785 libspirv::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
786 }
787
Andrew Woloszyncfeac482015-09-09 13:04:32 -0400788 spv_text_t text = {input_text, input_text_size};
Lei Zhang755f97f2016-09-02 18:06:18 -0400789 libspirv::AssemblyGrammar grammar(&hijack_context);
Lei Zhang9042f402015-11-05 17:45:09 -0500790
Andrey Tuganovb173d1c2017-04-11 19:46:15 -0400791 spv_result_t result = spvTextToBinaryInternal(
792 grammar, hijack_context.consumer, &text, options, pBinary);
David Netoc9786432015-09-01 18:05:14 -0400793 if (pDiagnostic && *pDiagnostic) (*pDiagnostic)->isTextSource = true;
794
795 return result;
796}
797
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100798void spvTextDestroy(spv_text text) {
Lei Zhang40056702015-09-11 14:31:27 -0400799 if (!text) return;
Eric Engestromeb6ae972016-02-18 23:41:16 +0000800 delete[] text->str;
Kenneth Benzie (Benie)83e5a292015-05-22 18:26:19 +0100801 delete text;
802}