/src/shaderc/third_party/spirv-tools/source/text.cpp
Line  | Count  | Source  | 
1  |  | // Copyright (c) 2015-2016 The Khronos Group Inc.  | 
2  |  | //  | 
3  |  | // 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  | 
6  |  | //  | 
7  |  | //     http://www.apache.org/licenses/LICENSE-2.0  | 
8  |  | //  | 
9  |  | // 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.  | 
14  |  |  | 
15  |  | #include "source/text.h"  | 
16  |  |  | 
17  |  | #include <algorithm>  | 
18  |  | #include <cassert>  | 
19  |  | #include <cctype>  | 
20  |  | #include <cstdio>  | 
21  |  | #include <cstdlib>  | 
22  |  | #include <cstring>  | 
23  |  | #include <memory>  | 
24  |  | #include <set>  | 
25  |  | #include <sstream>  | 
26  |  | #include <string>  | 
27  |  | #include <unordered_map>  | 
28  |  | #include <utility>  | 
29  |  | #include <vector>  | 
30  |  |  | 
31  |  | #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"  | 
36  |  | #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/table2.h"  | 
42  |  | #include "source/text_handler.h"  | 
43  |  | #include "source/util/bitutils.h"  | 
44  |  | #include "source/util/parse_number.h"  | 
45  |  | #include "spirv-tools/libspirv.h"  | 
46  |  |  | 
47  | 0  | bool spvIsValidIDCharacter(const char value) { | 
48  | 0  |   return value == '_' || 0 != ::isalnum(value);  | 
49  | 0  | }  | 
50  |  |  | 
51  |  | // Returns true if the given string represents a valid ID name.  | 
52  | 0  | bool spvIsValidID(const char* textValue) { | 
53  | 0  |   const char* c = textValue;  | 
54  | 0  |   for (; *c != '\0'; ++c) { | 
55  | 0  |     if (!spvIsValidIDCharacter(*c)) { | 
56  | 0  |       return false;  | 
57  | 0  |     }  | 
58  | 0  |   }  | 
59  |  |   // If the string was empty, then the ID also is not valid.  | 
60  | 0  |   return c != textValue;  | 
61  | 0  | }  | 
62  |  |  | 
63  |  | // Text API  | 
64  |  |  | 
65  | 0  | spv_result_t spvTextToLiteral(const char* textValue, spv_literal_t* pLiteral) { | 
66  | 0  |   bool isSigned = false;  | 
67  | 0  |   int numPeriods = 0;  | 
68  | 0  |   bool isString = false;  | 
69  |  | 
  | 
70  | 0  |   const size_t len = strlen(textValue);  | 
71  | 0  |   if (len == 0) return SPV_FAILED_MATCH;  | 
72  |  |  | 
73  | 0  |   for (uint64_t index = 0; index < len; ++index) { | 
74  | 0  |     switch (textValue[index]) { | 
75  | 0  |       case '0':  | 
76  | 0  |       case '1':  | 
77  | 0  |       case '2':  | 
78  | 0  |       case '3':  | 
79  | 0  |       case '4':  | 
80  | 0  |       case '5':  | 
81  | 0  |       case '6':  | 
82  | 0  |       case '7':  | 
83  | 0  |       case '8':  | 
84  | 0  |       case '9':  | 
85  | 0  |         break;  | 
86  | 0  |       case '.':  | 
87  | 0  |         numPeriods++;  | 
88  | 0  |         break;  | 
89  | 0  |       case '-':  | 
90  | 0  |         if (index == 0) { | 
91  | 0  |           isSigned = true;  | 
92  | 0  |         } else { | 
93  | 0  |           isString = true;  | 
94  | 0  |         }  | 
95  | 0  |         break;  | 
96  | 0  |       default:  | 
97  | 0  |         isString = true;  | 
98  | 0  |         index = len;  // break out of the loop too.  | 
99  | 0  |         break;  | 
100  | 0  |     }  | 
101  | 0  |   }  | 
102  |  |  | 
103  | 0  |   pLiteral->type = spv_literal_type_t(99);  | 
104  |  | 
  | 
105  | 0  |   if (isString || numPeriods > 1 || (isSigned && len == 1)) { | 
106  | 0  |     if (len < 2 || textValue[0] != '"' || textValue[len - 1] != '"')  | 
107  | 0  |       return SPV_FAILED_MATCH;  | 
108  | 0  |     bool escaping = false;  | 
109  | 0  |     for (const char* val = textValue + 1; val != textValue + len - 1; ++val) { | 
110  | 0  |       if ((*val == '\\') && (!escaping)) { | 
111  | 0  |         escaping = true;  | 
112  | 0  |       } else { | 
113  |  |         // Have to save space for the null-terminator  | 
114  | 0  |         if (pLiteral->str.size() >= SPV_LIMIT_LITERAL_STRING_BYTES_MAX)  | 
115  | 0  |           return SPV_ERROR_OUT_OF_MEMORY;  | 
116  | 0  |         pLiteral->str.push_back(*val);  | 
117  | 0  |         escaping = false;  | 
118  | 0  |       }  | 
119  | 0  |     }  | 
120  |  |  | 
121  | 0  |     pLiteral->type = SPV_LITERAL_TYPE_STRING;  | 
122  | 0  |   } else if (numPeriods == 1) { | 
123  | 0  |     double d = std::strtod(textValue, nullptr);  | 
124  | 0  |     float f = (float)d;  | 
125  | 0  |     if (d == (double)f) { | 
126  | 0  |       pLiteral->type = SPV_LITERAL_TYPE_FLOAT_32;  | 
127  | 0  |       pLiteral->value.f = f;  | 
128  | 0  |     } else { | 
129  | 0  |       pLiteral->type = SPV_LITERAL_TYPE_FLOAT_64;  | 
130  | 0  |       pLiteral->value.d = d;  | 
131  | 0  |     }  | 
132  | 0  |   } else if (isSigned) { | 
133  | 0  |     int64_t i64 = strtoll(textValue, nullptr, 10);  | 
134  | 0  |     int32_t i32 = (int32_t)i64;  | 
135  | 0  |     if (i64 == (int64_t)i32) { | 
136  | 0  |       pLiteral->type = SPV_LITERAL_TYPE_INT_32;  | 
137  | 0  |       pLiteral->value.i32 = i32;  | 
138  | 0  |     } else { | 
139  | 0  |       pLiteral->type = SPV_LITERAL_TYPE_INT_64;  | 
140  | 0  |       pLiteral->value.i64 = i64;  | 
141  | 0  |     }  | 
142  | 0  |   } else { | 
143  | 0  |     uint64_t u64 = strtoull(textValue, nullptr, 10);  | 
144  | 0  |     uint32_t u32 = (uint32_t)u64;  | 
145  | 0  |     if (u64 == (uint64_t)u32) { | 
146  | 0  |       pLiteral->type = SPV_LITERAL_TYPE_UINT_32;  | 
147  | 0  |       pLiteral->value.u32 = u32;  | 
148  | 0  |     } else { | 
149  | 0  |       pLiteral->type = SPV_LITERAL_TYPE_UINT_64;  | 
150  | 0  |       pLiteral->value.u64 = u64;  | 
151  | 0  |     }  | 
152  | 0  |   }  | 
153  |  |  | 
154  | 0  |   return SPV_SUCCESS;  | 
155  | 0  | }  | 
156  |  |  | 
157  |  | namespace { | 
158  |  |  | 
159  |  | /// Parses an immediate integer from text, guarding against overflow.  If  | 
160  |  | /// successful, adds the parsed value to pInst, advances the context past it,  | 
161  |  | /// and returns SPV_SUCCESS.  Otherwise, leaves pInst alone, emits diagnostics,  | 
162  |  | /// and returns SPV_ERROR_INVALID_TEXT.  | 
163  |  | spv_result_t encodeImmediate(spvtools::AssemblyContext* context,  | 
164  | 0  |                              const char* text, spv_instruction_t* pInst) { | 
165  | 0  |   assert(*text == '!');  | 
166  | 0  |   uint32_t parse_result;  | 
167  | 0  |   if (!spvtools::utils::ParseNumber(text + 1, &parse_result)) { | 
168  | 0  |     return context->diagnostic(SPV_ERROR_INVALID_TEXT)  | 
169  | 0  |            << "Invalid immediate integer: !" << text + 1;  | 
170  | 0  |   }  | 
171  | 0  |   context->binaryEncodeU32(parse_result, pInst);  | 
172  | 0  |   context->seekForward(static_cast<uint32_t>(strlen(text)));  | 
173  | 0  |   return SPV_SUCCESS;  | 
174  | 0  | }  | 
175  |  |  | 
176  |  | }  // anonymous namespace  | 
177  |  |  | 
178  |  | /// @brief Translate an Opcode operand to binary form  | 
179  |  | ///  | 
180  |  | /// @param[in] grammar the grammar to use for compilation  | 
181  |  | /// @param[in, out] context the dynamic compilation info  | 
182  |  | /// @param[in] type of the operand  | 
183  |  | /// @param[in] textValue word of text to be parsed  | 
184  |  | /// @param[out] pInst return binary Opcode  | 
185  |  | /// @param[in,out] pExpectedOperands the operand types expected  | 
186  |  | ///  | 
187  |  | /// @return result code  | 
188  |  | spv_result_t spvTextEncodeOperand(const spvtools::AssemblyGrammar& grammar,  | 
189  |  |                                   spvtools::AssemblyContext* context,  | 
190  |  |                                   const spv_operand_type_t type,  | 
191  |  |                                   const char* textValue,  | 
192  |  |                                   spv_instruction_t* pInst,  | 
193  | 0  |                                   spv_operand_pattern_t* pExpectedOperands) { | 
194  |  |   // NOTE: Handle immediate int in the stream  | 
195  | 0  |   if ('!' == textValue[0]) { | 
196  | 0  |     if (auto error = encodeImmediate(context, textValue, pInst)) { | 
197  | 0  |       return error;  | 
198  | 0  |     }  | 
199  | 0  |     *pExpectedOperands =  | 
200  | 0  |         spvAlternatePatternFollowingImmediate(*pExpectedOperands);  | 
201  | 0  |     return SPV_SUCCESS;  | 
202  | 0  |   }  | 
203  |  |  | 
204  |  |   // Optional literal operands can fail to parse. In that case use  | 
205  |  |   // SPV_FAILED_MATCH to avoid emitting a diagnostic.  Use the following  | 
206  |  |   // for those situations.  | 
207  | 0  |   spv_result_t error_code_for_literals =  | 
208  | 0  |       spvOperandIsOptional(type) ? SPV_FAILED_MATCH : SPV_ERROR_INVALID_TEXT;  | 
209  |  | 
  | 
210  | 0  |   switch (type) { | 
211  | 0  |     case SPV_OPERAND_TYPE_ID:  | 
212  | 0  |     case SPV_OPERAND_TYPE_TYPE_ID:  | 
213  | 0  |     case SPV_OPERAND_TYPE_RESULT_ID:  | 
214  | 0  |     case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:  | 
215  | 0  |     case SPV_OPERAND_TYPE_SCOPE_ID:  | 
216  | 0  |     case SPV_OPERAND_TYPE_OPTIONAL_ID: { | 
217  | 0  |       if ('%' == textValue[0]) { | 
218  | 0  |         textValue++;  | 
219  | 0  |       } else { | 
220  | 0  |         return context->diagnostic() << "Expected id to start with %.";  | 
221  | 0  |       }  | 
222  | 0  |       if (!spvIsValidID(textValue)) { | 
223  | 0  |         return context->diagnostic() << "Invalid ID " << textValue;  | 
224  | 0  |       }  | 
225  | 0  |       const uint32_t id = context->spvNamedIdAssignOrGet(textValue);  | 
226  | 0  |       if (type == SPV_OPERAND_TYPE_TYPE_ID) pInst->resultTypeId = id;  | 
227  | 0  |       spvInstructionAddWord(pInst, id);  | 
228  |  |  | 
229  |  |       // Set the extended instruction type.  | 
230  |  |       // The import set id is the 3rd operand of OpExtInst.  | 
231  | 0  |       if (spvIsExtendedInstruction(pInst->opcode) && pInst->words.size() == 4) { | 
232  | 0  |         auto ext_inst_type = context->getExtInstTypeForId(pInst->words[3]);  | 
233  | 0  |         if (ext_inst_type == SPV_EXT_INST_TYPE_NONE) { | 
234  | 0  |           return context->diagnostic()  | 
235  | 0  |                  << "Invalid extended instruction import Id "  | 
236  | 0  |                  << pInst->words[2];  | 
237  | 0  |         }  | 
238  | 0  |         pInst->extInstType = ext_inst_type;  | 
239  | 0  |       }  | 
240  | 0  |     } break;  | 
241  |  |  | 
242  | 0  |     case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: { | 
243  |  |       // The assembler accepts the symbolic name for an extended instruction,  | 
244  |  |       // and emits its corresponding number.  | 
245  | 0  |       const spvtools::ExtInstDesc* desc = nullptr;  | 
246  | 0  |       if (spvtools::LookupExtInst(pInst->extInstType, textValue, &desc) ==  | 
247  | 0  |           SPV_SUCCESS) { | 
248  |  |         // if we know about this extended instruction, push the numeric value  | 
249  | 0  |         spvInstructionAddWord(pInst, desc->value);  | 
250  |  |  | 
251  |  |         // Prepare to parse the operands for the extended instructions.  | 
252  | 0  |         spvPushOperandTypes(desc->operands(), pExpectedOperands);  | 
253  | 0  |       } else { | 
254  |  |         // if we don't know this extended instruction and the set isn't  | 
255  |  |         // non-semantic, we cannot process further  | 
256  | 0  |         if (!spvExtInstIsNonSemantic(pInst->extInstType)) { | 
257  | 0  |           return context->diagnostic()  | 
258  | 0  |                  << "Invalid extended instruction name '" << textValue << "'.";  | 
259  | 0  |         } else { | 
260  |  |           // for non-semantic instruction sets, as long as the text name is an  | 
261  |  |           // integer value we can encode it since we know the form of all such  | 
262  |  |           // extended instructions  | 
263  | 0  |           spv_literal_t extInstValue;  | 
264  | 0  |           if (spvTextToLiteral(textValue, &extInstValue) ||  | 
265  | 0  |               extInstValue.type != SPV_LITERAL_TYPE_UINT_32) { | 
266  | 0  |             return context->diagnostic()  | 
267  | 0  |                    << "Couldn't translate unknown extended instruction name '"  | 
268  | 0  |                    << textValue << "' to unsigned integer.";  | 
269  | 0  |           }  | 
270  |  |  | 
271  | 0  |           spvInstructionAddWord(pInst, extInstValue.value.u32);  | 
272  |  |  | 
273  |  |           // opcode contains an unknown number of IDs.  | 
274  | 0  |           pExpectedOperands->push_back(SPV_OPERAND_TYPE_VARIABLE_ID);  | 
275  | 0  |         }  | 
276  | 0  |       }  | 
277  | 0  |     } break;  | 
278  |  |  | 
279  | 0  |     case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: { | 
280  |  |       // The assembler accepts the symbolic name for the opcode, but without  | 
281  |  |       // the "Op" prefix.  For example, "IAdd" is accepted.  The number  | 
282  |  |       // of the opcode is emitted.  | 
283  | 0  |       spv::Op opcode;  | 
284  | 0  |       if (grammar.lookupSpecConstantOpcode(textValue, &opcode)) { | 
285  | 0  |         return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)  | 
286  | 0  |                                      << " '" << textValue << "'.";  | 
287  | 0  |       }  | 
288  | 0  |       const spvtools::InstructionDesc* opcodeEntry = nullptr;  | 
289  | 0  |       if (LookupOpcodeForEnv(grammar.target_env(), opcode, &opcodeEntry)) { | 
290  | 0  |         return context->diagnostic(SPV_ERROR_INTERNAL)  | 
291  | 0  |                << "OpSpecConstant opcode table out of sync";  | 
292  | 0  |       }  | 
293  | 0  |       spvInstructionAddWord(pInst, uint32_t(opcodeEntry->opcode));  | 
294  |  |  | 
295  |  |       // Prepare to parse the operands for the opcode.  Except skip the  | 
296  |  |       // type Id and result Id, since they've already been processed.  | 
297  | 0  |       assert(opcodeEntry->hasType);  | 
298  | 0  |       assert(opcodeEntry->hasResult);  | 
299  | 0  |       assert(opcodeEntry->operands().size() >= 2);  | 
300  | 0  |       spvPushOperandTypes(opcodeEntry->operands().subspan(2),  | 
301  | 0  |                           pExpectedOperands);  | 
302  | 0  |     } break;  | 
303  |  |  | 
304  | 0  |     case SPV_OPERAND_TYPE_LITERAL_INTEGER:  | 
305  | 0  |     case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER: { | 
306  |  |       // The current operand is an *unsigned* 32-bit integer.  | 
307  |  |       // That's just how the grammar works.  | 
308  | 0  |       spvtools::IdType expected_type = { | 
309  | 0  |           32, false, spvtools::IdTypeClass::kScalarIntegerType};  | 
310  | 0  |       if (auto error = context->binaryEncodeNumericLiteral(  | 
311  | 0  |               textValue, error_code_for_literals, expected_type, pInst)) { | 
312  | 0  |         return error;  | 
313  | 0  |       }  | 
314  | 0  |     } break;  | 
315  |  |  | 
316  | 0  |     case SPV_OPERAND_TYPE_LITERAL_FLOAT: { | 
317  |  |       // The current operand is a 32-bit float.  | 
318  |  |       // That's just how the grammar works.  | 
319  | 0  |       spvtools::IdType expected_type = { | 
320  | 0  |           32, false, spvtools::IdTypeClass::kScalarFloatType};  | 
321  | 0  |       if (auto error = context->binaryEncodeNumericLiteral(  | 
322  | 0  |               textValue, error_code_for_literals, expected_type, pInst)) { | 
323  | 0  |         return error;  | 
324  | 0  |       }  | 
325  | 0  |     } break;  | 
326  |  |  | 
327  | 0  |     case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_NUMBER:  | 
328  |  |       // This is a context-independent literal number which can be a 32-bit  | 
329  |  |       // number of floating point value.  | 
330  | 0  |       if (auto error = context->binaryEncodeNumericLiteral(  | 
331  | 0  |               textValue, error_code_for_literals, spvtools::kUnknownType,  | 
332  | 0  |               pInst)) { | 
333  | 0  |         return error;  | 
334  | 0  |       }  | 
335  | 0  |       break;  | 
336  |  |  | 
337  | 0  |     case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER:  | 
338  | 0  |     case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER: { | 
339  | 0  |       spvtools::IdType expected_type = spvtools::kUnknownType;  | 
340  |  |       // The encoding for OpConstant, OpSpecConstant and OpSwitch all  | 
341  |  |       // depend on either their own result-id or the result-id of  | 
342  |  |       // one of their parameters.  | 
343  | 0  |       if (spv::Op::OpConstant == pInst->opcode ||  | 
344  | 0  |           spv::Op::OpSpecConstant == pInst->opcode) { | 
345  |  |         // The type of the literal is determined by the type Id of the  | 
346  |  |         // instruction.  | 
347  | 0  |         expected_type =  | 
348  | 0  |             context->getTypeOfTypeGeneratingValue(pInst->resultTypeId);  | 
349  | 0  |         if (!spvtools::isScalarFloating(expected_type) &&  | 
350  | 0  |             !spvtools::isScalarIntegral(expected_type)) { | 
351  | 0  |           const spvtools::InstructionDesc* opcodeEntry = nullptr;  | 
352  | 0  |           const char* opcode_name = "opcode";  | 
353  | 0  |           if (SPV_SUCCESS == LookupOpcode(pInst->opcode, &opcodeEntry)) { | 
354  | 0  |             opcode_name =  | 
355  | 0  |                 opcodeEntry->name().data();  // assumes it's null-terminated  | 
356  | 0  |           }  | 
357  | 0  |           return context->diagnostic()  | 
358  | 0  |                  << "Type for " << opcode_name  | 
359  | 0  |                  << " must be a scalar floating point or integer type";  | 
360  | 0  |         }  | 
361  | 0  |       } else if (pInst->opcode == spv::Op::OpSwitch) { | 
362  |  |         // The type of the literal is the same as the type of the selector.  | 
363  | 0  |         expected_type = context->getTypeOfValueInstruction(pInst->words[1]);  | 
364  | 0  |         if (!spvtools::isScalarIntegral(expected_type)) { | 
365  | 0  |           return context->diagnostic()  | 
366  | 0  |                  << "The selector operand for OpSwitch must be the result"  | 
367  | 0  |                     " of an instruction that generates an integer scalar";  | 
368  | 0  |         }  | 
369  | 0  |       }  | 
370  | 0  |       if (auto error = context->binaryEncodeNumericLiteral(  | 
371  | 0  |               textValue, error_code_for_literals, expected_type, pInst)) { | 
372  | 0  |         return error;  | 
373  | 0  |       }  | 
374  | 0  |     } break;  | 
375  |  |  | 
376  | 0  |     case SPV_OPERAND_TYPE_LITERAL_STRING:  | 
377  | 0  |     case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: { | 
378  | 0  |       spv_literal_t literal = {}; | 
379  | 0  |       spv_result_t error = spvTextToLiteral(textValue, &literal);  | 
380  | 0  |       if (error != SPV_SUCCESS) { | 
381  | 0  |         if (error == SPV_ERROR_OUT_OF_MEMORY) return error;  | 
382  | 0  |         return context->diagnostic(error_code_for_literals)  | 
383  | 0  |                << "Invalid literal string '" << textValue << "'.";  | 
384  | 0  |       }  | 
385  | 0  |       if (literal.type != SPV_LITERAL_TYPE_STRING) { | 
386  | 0  |         return context->diagnostic()  | 
387  | 0  |                << "Expected literal string, found literal number '" << textValue  | 
388  | 0  |                << "'.";  | 
389  | 0  |       }  | 
390  |  |  | 
391  |  |       // NOTE: Special case for extended instruction library import  | 
392  | 0  |       if (spv::Op::OpExtInstImport == pInst->opcode) { | 
393  | 0  |         const spv_ext_inst_type_t ext_inst_type =  | 
394  | 0  |             spvExtInstImportTypeGet(literal.str.c_str());  | 
395  | 0  |         if (SPV_EXT_INST_TYPE_NONE == ext_inst_type) { | 
396  | 0  |           return context->diagnostic()  | 
397  | 0  |                  << "Invalid extended instruction import '" << literal.str  | 
398  | 0  |                  << "'";  | 
399  | 0  |         }  | 
400  | 0  |         if ((error = context->recordIdAsExtInstImport(pInst->words[1],  | 
401  | 0  |                                                       ext_inst_type)))  | 
402  | 0  |           return error;  | 
403  | 0  |       }  | 
404  |  |  | 
405  | 0  |       if (context->binaryEncodeString(literal.str.c_str(), pInst))  | 
406  | 0  |         return SPV_ERROR_INVALID_TEXT;  | 
407  | 0  |     } break;  | 
408  |  |  | 
409  |  |     // Masks.  | 
410  | 0  |     case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:  | 
411  | 0  |     case SPV_OPERAND_TYPE_FUNCTION_CONTROL:  | 
412  | 0  |     case SPV_OPERAND_TYPE_LOOP_CONTROL:  | 
413  | 0  |     case SPV_OPERAND_TYPE_IMAGE:  | 
414  | 0  |     case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:  | 
415  | 0  |     case SPV_OPERAND_TYPE_TENSOR_OPERANDS:  | 
416  | 0  |     case SPV_OPERAND_TYPE_OPTIONAL_TENSOR_OPERANDS:  | 
417  | 0  |     case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:  | 
418  | 0  |     case SPV_OPERAND_TYPE_OPTIONAL_RAW_ACCESS_CHAIN_OPERANDS:  | 
419  | 0  |     case SPV_OPERAND_TYPE_SELECTION_CONTROL:  | 
420  | 0  |     case SPV_OPERAND_TYPE_DEBUG_INFO_FLAGS:  | 
421  | 0  |     case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_INFO_FLAGS:  | 
422  | 0  |     case SPV_OPERAND_TYPE_OPTIONAL_COOPERATIVE_MATRIX_OPERANDS:  | 
423  | 0  |     case SPV_OPERAND_TYPE_TENSOR_ADDRESSING_OPERANDS:  | 
424  | 0  |     case SPV_OPERAND_TYPE_COOPERATIVE_MATRIX_REDUCE:  | 
425  | 0  |     case SPV_OPERAND_TYPE_OPTIONAL_MATRIX_MULTIPLY_ACCUMULATE_OPERANDS: { | 
426  | 0  |       uint32_t value;  | 
427  | 0  |       if (auto error = grammar.parseMaskOperand(type, textValue, &value)) { | 
428  | 0  |         return context->diagnostic(error)  | 
429  | 0  |                << "Invalid " << spvOperandTypeStr(type) << " operand '"  | 
430  | 0  |                << textValue << "'.";  | 
431  | 0  |       }  | 
432  | 0  |       if (auto error = context->binaryEncodeU32(value, pInst)) return error;  | 
433  |  |       // Prepare to parse the operands for this logical operand.  | 
434  | 0  |       grammar.pushOperandTypesForMask(type, value, pExpectedOperands);  | 
435  | 0  |     } break;  | 
436  | 0  |     case SPV_OPERAND_TYPE_OPTIONAL_CIV: { | 
437  | 0  |       auto error = spvTextEncodeOperand(  | 
438  | 0  |           grammar, context, SPV_OPERAND_TYPE_OPTIONAL_LITERAL_NUMBER, textValue,  | 
439  | 0  |           pInst, pExpectedOperands);  | 
440  | 0  |       if (error == SPV_FAILED_MATCH) { | 
441  |  |         // It's not a literal number -- is it a literal string?  | 
442  | 0  |         error = spvTextEncodeOperand(grammar, context,  | 
443  | 0  |                                      SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING,  | 
444  | 0  |                                      textValue, pInst, pExpectedOperands);  | 
445  | 0  |       }  | 
446  | 0  |       if (error == SPV_FAILED_MATCH) { | 
447  |  |         // It's not a literal -- is it an ID?  | 
448  | 0  |         error =  | 
449  | 0  |             spvTextEncodeOperand(grammar, context, SPV_OPERAND_TYPE_OPTIONAL_ID,  | 
450  | 0  |                                  textValue, pInst, pExpectedOperands);  | 
451  | 0  |       }  | 
452  | 0  |       if (error) { | 
453  | 0  |         return context->diagnostic(error)  | 
454  | 0  |                << "Invalid word following !<integer>: " << textValue;  | 
455  | 0  |       }  | 
456  | 0  |       if (pExpectedOperands->empty()) { | 
457  | 0  |         pExpectedOperands->push_back(SPV_OPERAND_TYPE_OPTIONAL_CIV);  | 
458  | 0  |       }  | 
459  | 0  |     } break;  | 
460  | 0  |     default: { | 
461  |  |       // NOTE: All non literal operands are handled here using the operand  | 
462  |  |       // table.  | 
463  | 0  |       const spvtools::OperandDesc* entry = nullptr;  | 
464  | 0  |       if (spvtools::LookupOperand(type, textValue, strlen(textValue), &entry)) { | 
465  | 0  |         return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)  | 
466  | 0  |                                      << " '" << textValue << "'.";  | 
467  | 0  |       }  | 
468  | 0  |       if (context->binaryEncodeU32(entry->value, pInst)) { | 
469  | 0  |         return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)  | 
470  | 0  |                                      << " '" << textValue << "'.";  | 
471  | 0  |       }  | 
472  |  |  | 
473  |  |       // Prepare to parse the operands for this logical operand.  | 
474  | 0  |       spvPushOperandTypes(entry->operands(), pExpectedOperands);  | 
475  | 0  |     } break;  | 
476  | 0  |   }  | 
477  | 0  |   return SPV_SUCCESS;  | 
478  | 0  | }  | 
479  |  |  | 
480  |  | namespace { | 
481  |  |  | 
482  |  | /// Encodes an instruction started by !<integer> at the given position in text.  | 
483  |  | ///  | 
484  |  | /// Puts the encoded words into *pInst.  If successful, moves position past the  | 
485  |  | /// instruction and returns SPV_SUCCESS.  Otherwise, returns an error code and  | 
486  |  | /// leaves position pointing to the error in text.  | 
487  |  | spv_result_t encodeInstructionStartingWithImmediate(  | 
488  |  |     const spvtools::AssemblyGrammar& grammar,  | 
489  | 0  |     spvtools::AssemblyContext* context, spv_instruction_t* pInst) { | 
490  | 0  |   std::string firstWord;  | 
491  | 0  |   spv_position_t nextPosition = {}; | 
492  | 0  |   auto error = context->getWord(&firstWord, &nextPosition);  | 
493  | 0  |   if (error) return context->diagnostic(error) << "Internal Error";  | 
494  |  |  | 
495  | 0  |   if ((error = encodeImmediate(context, firstWord.c_str(), pInst))) { | 
496  | 0  |     return error;  | 
497  | 0  |   }  | 
498  | 0  |   while (context->advance() != SPV_END_OF_STREAM) { | 
499  |  |     // A beginning of a new instruction means we're done.  | 
500  | 0  |     if (context->isStartOfNewInst()) return SPV_SUCCESS;  | 
501  |  |  | 
502  |  |     // Otherwise, there must be an operand that's either a literal, an ID, or  | 
503  |  |     // an immediate.  | 
504  | 0  |     std::string operandValue;  | 
505  | 0  |     if ((error = context->getWord(&operandValue, &nextPosition)))  | 
506  | 0  |       return context->diagnostic(error) << "Internal Error";  | 
507  |  |  | 
508  | 0  |     if (operandValue == "=")  | 
509  | 0  |       return context->diagnostic() << firstWord << " not allowed before =.";  | 
510  |  |  | 
511  |  |     // Needed to pass to spvTextEncodeOperand(), but it shouldn't ever be  | 
512  |  |     // expanded.  | 
513  | 0  |     spv_operand_pattern_t dummyExpectedOperands;  | 
514  | 0  |     error = spvTextEncodeOperand(  | 
515  | 0  |         grammar, context, SPV_OPERAND_TYPE_OPTIONAL_CIV, operandValue.c_str(),  | 
516  | 0  |         pInst, &dummyExpectedOperands);  | 
517  | 0  |     if (error) return error;  | 
518  | 0  |     context->setPosition(nextPosition);  | 
519  | 0  |   }  | 
520  | 0  |   return SPV_SUCCESS;  | 
521  | 0  | }  | 
522  |  |  | 
523  |  | /// @brief Translate an instruction started by OpUnknown and the following  | 
524  |  | /// operands to binary form  | 
525  |  | ///  | 
526  |  | /// @param[in] grammar the grammar to use for compilation  | 
527  |  | /// @param[in, out] context the dynamic compilation info  | 
528  |  | /// @param[out] pInst returned binary Opcode  | 
529  |  | ///  | 
530  |  | /// @return result code  | 
531  |  | spv_result_t encodeInstructionStartingWithOpUnknown(  | 
532  |  |     const spvtools::AssemblyGrammar& grammar,  | 
533  | 0  |     spvtools::AssemblyContext* context, spv_instruction_t* pInst) { | 
534  | 0  |   spv_position_t nextPosition = {}; | 
535  |  | 
  | 
536  | 0  |   uint16_t opcode;  | 
537  | 0  |   uint16_t wordCount;  | 
538  |  |  | 
539  |  |   // The '(' character. | 
540  | 0  |   if (context->advance())  | 
541  | 0  |     return context->diagnostic() << "Expected '(', found end of stream."; | 
542  | 0  |   if ('(' != context->peek()) { | 
543  | 0  |     return context->diagnostic() << "'(' expected after OpUnknown but found '" | 
544  | 0  |                                  << context->peek() << "'.";  | 
545  | 0  |   }  | 
546  | 0  |   context->seekForward(1);  | 
547  |  |  | 
548  |  |   // The opcode enumerant.  | 
549  | 0  |   if (context->advance())  | 
550  | 0  |     return context->diagnostic()  | 
551  | 0  |            << "Expected opcode enumerant, found end of stream.";  | 
552  | 0  |   std::string opcodeString;  | 
553  | 0  |   spv_result_t error = context->getWord(&opcodeString, &nextPosition);  | 
554  | 0  |   if (error) return context->diagnostic(error) << "Internal Error";  | 
555  |  |  | 
556  | 0  |   if (!spvtools::utils::ParseNumber(opcodeString.c_str(), &opcode)) { | 
557  | 0  |     return context->diagnostic()  | 
558  | 0  |            << "Invalid opcode enumerant: \"" << opcodeString << "\".";  | 
559  | 0  |   }  | 
560  |  |  | 
561  | 0  |   context->setPosition(nextPosition);  | 
562  |  |  | 
563  |  |   // The ',' character.  | 
564  | 0  |   if (context->advance())  | 
565  | 0  |     return context->diagnostic() << "Expected ',', found end of stream.";  | 
566  | 0  |   if (',' != context->peek()) { | 
567  | 0  |     return context->diagnostic()  | 
568  | 0  |            << "',' expected after opcode enumerant but found '"  | 
569  | 0  |            << context->peek() << "'.";  | 
570  | 0  |   }  | 
571  | 0  |   context->seekForward(1);  | 
572  |  |  | 
573  |  |   // The number of words.  | 
574  | 0  |   if (context->advance())  | 
575  | 0  |     return context->diagnostic()  | 
576  | 0  |            << "Expected number of words, found end of stream.";  | 
577  | 0  |   std::string wordCountString;  | 
578  | 0  |   error = context->getWord(&wordCountString, &nextPosition);  | 
579  | 0  |   if (error) return context->diagnostic(error) << "Internal Error";  | 
580  |  |  | 
581  | 0  |   if (!spvtools::utils::ParseNumber(wordCountString.c_str(), &wordCount)) { | 
582  | 0  |     return context->diagnostic()  | 
583  | 0  |            << "Invalid number of words: \"" << wordCountString << "\".";  | 
584  | 0  |   }  | 
585  |  |  | 
586  | 0  |   if (wordCount == 0) { | 
587  | 0  |     return context->diagnostic() << "Number of words (which includes the "  | 
588  | 0  |                                     "opcode) must be greater than zero.";  | 
589  | 0  |   }  | 
590  |  |  | 
591  | 0  |   context->setPosition(nextPosition);  | 
592  |  |  | 
593  |  |   // The ')' character.  | 
594  | 0  |   if (context->advance())  | 
595  | 0  |     return context->diagnostic() << "Expected ')', found end of stream.";  | 
596  | 0  |   if (')' != context->peek()) { | 
597  | 0  |     return context->diagnostic()  | 
598  | 0  |            << "')' expected after number of words but found '"  | 
599  | 0  |            << context->peek() << "'.";  | 
600  | 0  |   }  | 
601  | 0  |   context->seekForward(1);  | 
602  |  | 
  | 
603  | 0  |   pInst->opcode = static_cast<spv::Op>(opcode);  | 
604  | 0  |   context->binaryEncodeU32(spvOpcodeMake(wordCount, pInst->opcode), pInst);  | 
605  |  | 
  | 
606  | 0  |   wordCount--;  // Subtract the opcode from the number of words left to read.  | 
607  |  | 
  | 
608  | 0  |   while (wordCount-- > 0) { | 
609  | 0  |     if (context->advance() == SPV_END_OF_STREAM) { | 
610  | 0  |       return context->diagnostic() << "Expected " << wordCount + 1  | 
611  | 0  |                                    << " more operands, found end of stream.";  | 
612  | 0  |     }  | 
613  | 0  |     if (context->isStartOfNewInst()) { | 
614  | 0  |       std::string invalid;  | 
615  | 0  |       context->getWord(&invalid, &nextPosition);  | 
616  | 0  |       return context->diagnostic()  | 
617  | 0  |              << "Unexpected start of new instruction: \"" << invalid  | 
618  | 0  |              << "\". Expected " << wordCount + 1 << " more operands";  | 
619  | 0  |     }  | 
620  |  |  | 
621  | 0  |     std::string operandValue;  | 
622  | 0  |     if ((error = context->getWord(&operandValue, &nextPosition)))  | 
623  | 0  |       return context->diagnostic(error) << "Internal Error";  | 
624  |  |  | 
625  | 0  |     if (operandValue == "=")  | 
626  | 0  |       return context->diagnostic() << "OpUnknown not allowed before =.";  | 
627  |  |  | 
628  |  |     // Needed to pass to spvTextEncodeOperand(), but it shouldn't ever be  | 
629  |  |     // expanded.  | 
630  | 0  |     spv_operand_pattern_t dummyExpectedOperands;  | 
631  | 0  |     error = spvTextEncodeOperand(  | 
632  | 0  |         grammar, context, SPV_OPERAND_TYPE_OPTIONAL_CIV, operandValue.c_str(),  | 
633  | 0  |         pInst, &dummyExpectedOperands);  | 
634  | 0  |     if (error) return error;  | 
635  | 0  |     context->setPosition(nextPosition);  | 
636  | 0  |   }  | 
637  |  |  | 
638  | 0  |   return SPV_SUCCESS;  | 
639  | 0  | }  | 
640  |  |  | 
641  |  | /// @brief Translate single Opcode and operands to binary form  | 
642  |  | ///  | 
643  |  | /// @param[in] grammar the grammar to use for compilation  | 
644  |  | /// @param[in, out] context the dynamic compilation info  | 
645  |  | /// @param[in] text stream to translate  | 
646  |  | /// @param[out] pInst returned binary Opcode  | 
647  |  | /// @param[in,out] pPosition in the text stream  | 
648  |  | ///  | 
649  |  | /// @return result code  | 
650  |  | spv_result_t spvTextEncodeOpcode(const spvtools::AssemblyGrammar& grammar,  | 
651  |  |                                  spvtools::AssemblyContext* context,  | 
652  | 0  |                                  spv_instruction_t* pInst) { | 
653  |  |   // Check for !<integer> first.  | 
654  | 0  |   if ('!' == context->peek()) { | 
655  | 0  |     return encodeInstructionStartingWithImmediate(grammar, context, pInst);  | 
656  | 0  |   }  | 
657  |  |  | 
658  | 0  |   std::string firstWord;  | 
659  | 0  |   spv_position_t nextPosition = {}; | 
660  | 0  |   spv_result_t error = context->getWord(&firstWord, &nextPosition);  | 
661  | 0  |   if (error) return context->diagnostic() << "Internal Error";  | 
662  |  |  | 
663  | 0  |   std::string opcodeName;  | 
664  | 0  |   std::string result_id;  | 
665  | 0  |   spv_position_t result_id_position = {}; | 
666  | 0  |   if (context->startsWithOp()) { | 
667  | 0  |     opcodeName = firstWord;  | 
668  | 0  |   } else { | 
669  | 0  |     result_id = firstWord;  | 
670  | 0  |     if ('%' != result_id.front()) { | 
671  | 0  |       return context->diagnostic()  | 
672  | 0  |              << "Expected <opcode> or <result-id> at the beginning "  | 
673  | 0  |                 "of an instruction, found '"  | 
674  | 0  |              << result_id << "'.";  | 
675  | 0  |     }  | 
676  | 0  |     result_id_position = context->position();  | 
677  |  |  | 
678  |  |     // The '=' sign.  | 
679  | 0  |     context->setPosition(nextPosition);  | 
680  | 0  |     if (context->advance())  | 
681  | 0  |       return context->diagnostic() << "Expected '=', found end of stream.";  | 
682  | 0  |     std::string equal_sign;  | 
683  | 0  |     error = context->getWord(&equal_sign, &nextPosition);  | 
684  | 0  |     if ("=" != equal_sign) | 
685  | 0  |       return context->diagnostic() << "'=' expected after result id but found '"  | 
686  | 0  |                                    << equal_sign << "'.";  | 
687  |  |  | 
688  |  |     // The <opcode> after the '=' sign.  | 
689  | 0  |     context->setPosition(nextPosition);  | 
690  | 0  |     if (context->advance())  | 
691  | 0  |       return context->diagnostic() << "Expected opcode, found end of stream.";  | 
692  | 0  |     error = context->getWord(&opcodeName, &nextPosition);  | 
693  | 0  |     if (error) return context->diagnostic(error) << "Internal Error";  | 
694  | 0  |     if (!context->startsWithOp()) { | 
695  | 0  |       return context->diagnostic()  | 
696  | 0  |              << "Invalid Opcode prefix '" << opcodeName << "'.";  | 
697  | 0  |     }  | 
698  | 0  |   }  | 
699  |  |  | 
700  | 0  |   if (opcodeName == "OpUnknown") { | 
701  | 0  |     if (!result_id.empty()) { | 
702  | 0  |       return context->diagnostic()  | 
703  | 0  |              << "OpUnknown not allowed in assignment. Use an explicit result "  | 
704  | 0  |                 "id operand instead.";  | 
705  | 0  |     }  | 
706  | 0  |     context->setPosition(nextPosition);  | 
707  | 0  |     return encodeInstructionStartingWithOpUnknown(grammar, context, pInst);  | 
708  | 0  |   }  | 
709  |  |  | 
710  |  |   // NOTE: The table contains Opcode names without the "Op" prefix.  | 
711  | 0  |   const char* pInstName = opcodeName.data() + 2;  | 
712  |  | 
  | 
713  | 0  |   const spvtools::InstructionDesc* opcodeEntry = nullptr;  | 
714  | 0  |   error = LookupOpcodeForEnv(grammar.target_env(), pInstName, &opcodeEntry);  | 
715  | 0  |   if (error) { | 
716  | 0  |     return context->diagnostic(error)  | 
717  | 0  |            << "Invalid Opcode name '" << opcodeName << "'";  | 
718  | 0  |   }  | 
719  | 0  |   if (opcodeEntry->hasResult && result_id.empty()) { | 
720  | 0  |     return context->diagnostic()  | 
721  | 0  |            << "Expected <result-id> at the beginning of an instruction, found '"  | 
722  | 0  |            << firstWord << "'.";  | 
723  | 0  |   }  | 
724  | 0  |   if (!opcodeEntry->hasResult && !result_id.empty()) { | 
725  | 0  |     return context->diagnostic()  | 
726  | 0  |            << "Cannot set ID " << result_id << " because " << opcodeName  | 
727  | 0  |            << " does not produce a result ID.";  | 
728  | 0  |   }  | 
729  | 0  |   pInst->opcode = opcodeEntry->opcode;  | 
730  | 0  |   context->setPosition(nextPosition);  | 
731  |  |   // Reserve the first word for the instruction.  | 
732  | 0  |   spvInstructionAddWord(pInst, 0);  | 
733  |  |  | 
734  |  |   // Maintains the ordered list of expected operand types.  | 
735  |  |   // For many instructions we only need the {numTypes, operandTypes} | 
736  |  |   // entries in opcodeEntry.  However, sometimes we need to modify  | 
737  |  |   // the list as we parse the operands. This occurs when an operand  | 
738  |  |   // has its own logical operands (such as the LocalSize operand for  | 
739  |  |   // ExecutionMode), or for extended instructions that may have their  | 
740  |  |   // own operands depending on the selected extended instruction.  | 
741  | 0  |   spv_operand_pattern_t expectedOperands;  | 
742  | 0  |   { | 
743  | 0  |     const auto operands = opcodeEntry->operands();  | 
744  | 0  |     const auto n = operands.size();  | 
745  | 0  |     expectedOperands.reserve(n);  | 
746  | 0  |     for (auto i = 0u; i < n; i++) { | 
747  | 0  |       auto ty = operands[n - i - 1];  | 
748  | 0  |       expectedOperands.push_back(ty);  | 
749  | 0  |     }  | 
750  | 0  |   }  | 
751  |  | 
  | 
752  | 0  |   while (!expectedOperands.empty()) { | 
753  | 0  |     const spv_operand_type_t type = expectedOperands.back();  | 
754  | 0  |     expectedOperands.pop_back();  | 
755  |  |  | 
756  |  |     // Expand optional tuples lazily.  | 
757  | 0  |     if (spvExpandOperandSequenceOnce(type, &expectedOperands)) continue;  | 
758  |  |  | 
759  | 0  |     if (type == SPV_OPERAND_TYPE_RESULT_ID && !result_id.empty()) { | 
760  |  |       // Handle the <result-id> for value generating instructions.  | 
761  |  |       // We've already consumed it from the text stream.  Here  | 
762  |  |       // we inject its words into the instruction.  | 
763  | 0  |       spv_position_t temp_pos = context->position();  | 
764  | 0  |       error = spvTextEncodeOperand(grammar, context, SPV_OPERAND_TYPE_RESULT_ID,  | 
765  | 0  |                                    result_id.c_str(), pInst, nullptr);  | 
766  | 0  |       result_id_position = context->position();  | 
767  |  |       // Because we are injecting we have to reset the position afterwards.  | 
768  | 0  |       context->setPosition(temp_pos);  | 
769  | 0  |       if (error) return error;  | 
770  | 0  |     } else { | 
771  |  |       // Find the next word.  | 
772  | 0  |       error = context->advance();  | 
773  | 0  |       if (error == SPV_END_OF_STREAM) { | 
774  | 0  |         if (spvOperandIsOptional(type)) { | 
775  |  |           // This would have been the last potential operand for the  | 
776  |  |           // instruction,  | 
777  |  |           // and we didn't find one.  We're finished parsing this instruction.  | 
778  | 0  |           break;  | 
779  | 0  |         } else { | 
780  | 0  |           return context->diagnostic()  | 
781  | 0  |                  << "Expected operand for " << opcodeName  | 
782  | 0  |                  << " instruction, but found the end of the stream.";  | 
783  | 0  |         }  | 
784  | 0  |       }  | 
785  | 0  |       assert(error == SPV_SUCCESS && "Somebody added another way to fail");  | 
786  |  | 
  | 
787  | 0  |       if (context->isStartOfNewInst()) { | 
788  | 0  |         if (spvOperandIsOptional(type)) { | 
789  | 0  |           break;  | 
790  | 0  |         } else { | 
791  | 0  |           return context->diagnostic()  | 
792  | 0  |                  << "Expected operand for " << opcodeName  | 
793  | 0  |                  << " instruction, but found the next instruction instead.";  | 
794  | 0  |         }  | 
795  | 0  |       }  | 
796  |  |  | 
797  | 0  |       std::string operandValue;  | 
798  | 0  |       error = context->getWord(&operandValue, &nextPosition);  | 
799  | 0  |       if (error) return context->diagnostic(error) << "Internal Error";  | 
800  |  |  | 
801  | 0  |       error = spvTextEncodeOperand(grammar, context, type, operandValue.c_str(),  | 
802  | 0  |                                    pInst, &expectedOperands);  | 
803  |  | 
  | 
804  | 0  |       if (error == SPV_FAILED_MATCH && spvOperandIsOptional(type))  | 
805  | 0  |         return SPV_SUCCESS;  | 
806  |  |  | 
807  | 0  |       if (error) return error;  | 
808  |  |  | 
809  | 0  |       context->setPosition(nextPosition);  | 
810  | 0  |     }  | 
811  | 0  |   }  | 
812  |  |  | 
813  | 0  |   if (spvOpcodeGeneratesType(pInst->opcode)) { | 
814  | 0  |     if (context->recordTypeDefinition(pInst) != SPV_SUCCESS) { | 
815  | 0  |       return SPV_ERROR_INVALID_TEXT;  | 
816  | 0  |     }  | 
817  | 0  |   } else if (opcodeEntry->hasType) { | 
818  |  |     // SPIR-V dictates that if an instruction has both a return value and a  | 
819  |  |     // type ID then the type id is first, and the return value is second.  | 
820  | 0  |     assert(opcodeEntry->hasResult &&  | 
821  | 0  |            "Unknown opcode: has a type but no result.");  | 
822  | 0  |     context->recordTypeIdForValue(pInst->words[2], pInst->words[1]);  | 
823  | 0  |   }  | 
824  |  |  | 
825  | 0  |   if (pInst->words.size() > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) { | 
826  | 0  |     return context->diagnostic()  | 
827  | 0  |            << opcodeName << " Instruction too long: " << pInst->words.size()  | 
828  | 0  |            << " words, but the limit is "  | 
829  | 0  |            << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX;  | 
830  | 0  |   }  | 
831  |  |  | 
832  | 0  |   pInst->words[0] =  | 
833  | 0  |       spvOpcodeMake(uint16_t(pInst->words.size()), opcodeEntry->opcode);  | 
834  |  | 
  | 
835  | 0  |   return SPV_SUCCESS;  | 
836  | 0  | }  | 
837  |  |  | 
838  |  | enum { kAssemblerVersion = 0 }; | 
839  |  |  | 
840  |  | // Populates a binary stream's |header|. The target environment is specified via  | 
841  |  | // |env| and Id bound is via |bound|.  | 
842  |  | spv_result_t SetHeader(spv_target_env env, const uint32_t bound,  | 
843  | 0  |                        uint32_t* header) { | 
844  | 0  |   if (!header) return SPV_ERROR_INVALID_BINARY;  | 
845  |  |  | 
846  | 0  |   header[SPV_INDEX_MAGIC_NUMBER] = spv::MagicNumber;  | 
847  | 0  |   header[SPV_INDEX_VERSION_NUMBER] = spvVersionForTargetEnv(env);  | 
848  | 0  |   header[SPV_INDEX_GENERATOR_NUMBER] =  | 
849  | 0  |       SPV_GENERATOR_WORD(SPV_GENERATOR_KHRONOS_ASSEMBLER, kAssemblerVersion);  | 
850  | 0  |   header[SPV_INDEX_BOUND] = bound;  | 
851  | 0  |   header[SPV_INDEX_SCHEMA] = 0;  // NOTE: Reserved  | 
852  |  | 
  | 
853  | 0  |   return SPV_SUCCESS;  | 
854  | 0  | }  | 
855  |  |  | 
856  |  | // Collects all numeric ids in the module source into |numeric_ids|.  | 
857  |  | // This function is essentially a dry-run of spvTextToBinary.  | 
858  |  | spv_result_t GetNumericIds(const spvtools::AssemblyGrammar& grammar,  | 
859  |  |                            const spvtools::MessageConsumer& consumer,  | 
860  |  |                            const spv_text text,  | 
861  | 0  |                            std::set<uint32_t>* numeric_ids) { | 
862  | 0  |   spvtools::AssemblyContext context(text, consumer);  | 
863  |  | 
  | 
864  | 0  |   if (!text->str) return context.diagnostic() << "Missing assembly text.";  | 
865  |  |  | 
866  |  |   // Skip past whitespace and comments.  | 
867  | 0  |   context.advance();  | 
868  |  | 
  | 
869  | 0  |   while (context.hasText()) { | 
870  | 0  |     spv_instruction_t inst;  | 
871  |  |  | 
872  |  |     // Operand parsing sometimes involves knowing the opcode of the instruction  | 
873  |  |     // being parsed. A malformed input might feature such an operand *before*  | 
874  |  |     // the opcode is known. To guard against accessing an uninitialized opcode,  | 
875  |  |     // the instruction's opcode is initialized to a default value.  | 
876  | 0  |     inst.opcode = spv::Op::Max;  | 
877  |  | 
  | 
878  | 0  |     if (spvTextEncodeOpcode(grammar, &context, &inst)) { | 
879  | 0  |       return SPV_ERROR_INVALID_TEXT;  | 
880  | 0  |     }  | 
881  |  |  | 
882  | 0  |     if (context.advance()) break;  | 
883  | 0  |   }  | 
884  |  |  | 
885  | 0  |   *numeric_ids = context.GetNumericIds();  | 
886  | 0  |   return SPV_SUCCESS;  | 
887  | 0  | }  | 
888  |  |  | 
889  |  | // Translates a given assembly language module into binary form.  | 
890  |  | // If a diagnostic is generated, it is not yet marked as being  | 
891  |  | // for a text-based input.  | 
892  |  | spv_result_t spvTextToBinaryInternal(const spvtools::AssemblyGrammar& grammar,  | 
893  |  |                                      const spvtools::MessageConsumer& consumer,  | 
894  |  |                                      const spv_text text,  | 
895  |  |                                      const uint32_t options,  | 
896  | 0  |                                      spv_binary* pBinary) { | 
897  |  |   // The ids in this set will have the same values both in source and binary.  | 
898  |  |   // All other ids will be generated by filling in the gaps.  | 
899  | 0  |   std::set<uint32_t> ids_to_preserve;  | 
900  |  | 
  | 
901  | 0  |   if (options & SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS) { | 
902  |  |     // Collect all numeric ids from the source into ids_to_preserve.  | 
903  | 0  |     const spv_result_t result =  | 
904  | 0  |         GetNumericIds(grammar, consumer, text, &ids_to_preserve);  | 
905  | 0  |     if (result != SPV_SUCCESS) return result;  | 
906  | 0  |   }  | 
907  |  |  | 
908  | 0  |   spvtools::AssemblyContext context(text, consumer, std::move(ids_to_preserve));  | 
909  |  | 
  | 
910  | 0  |   if (!text->str) return context.diagnostic() << "Missing assembly text.";  | 
911  | 0  |   if (!pBinary) return SPV_ERROR_INVALID_POINTER;  | 
912  |  |  | 
913  | 0  |   std::vector<spv_instruction_t> instructions;  | 
914  |  |  | 
915  |  |   // Skip past whitespace and comments.  | 
916  | 0  |   context.advance();  | 
917  |  | 
  | 
918  | 0  |   while (context.hasText()) { | 
919  | 0  |     instructions.push_back({}); | 
920  | 0  |     spv_instruction_t& inst = instructions.back();  | 
921  |  | 
  | 
922  | 0  |     if (auto error = spvTextEncodeOpcode(grammar, &context, &inst)) { | 
923  | 0  |       return error;  | 
924  | 0  |     }  | 
925  |  |  | 
926  | 0  |     if (context.advance()) break;  | 
927  | 0  |   }  | 
928  |  |  | 
929  | 0  |   size_t totalSize = SPV_INDEX_INSTRUCTION;  | 
930  | 0  |   for (auto& inst : instructions) { | 
931  | 0  |     totalSize += inst.words.size();  | 
932  | 0  |   }  | 
933  |  | 
  | 
934  | 0  |   uint32_t* data = new uint32_t[totalSize];  | 
935  | 0  |   if (!data) return SPV_ERROR_OUT_OF_MEMORY;  | 
936  | 0  |   uint64_t currentIndex = SPV_INDEX_INSTRUCTION;  | 
937  | 0  |   for (auto& inst : instructions) { | 
938  | 0  |     memcpy(data + currentIndex, inst.words.data(),  | 
939  | 0  |            sizeof(uint32_t) * inst.words.size());  | 
940  | 0  |     currentIndex += inst.words.size();  | 
941  | 0  |   }  | 
942  |  | 
  | 
943  | 0  |   if (auto error = SetHeader(grammar.target_env(), context.getBound(), data))  | 
944  | 0  |     return error;  | 
945  |  |  | 
946  | 0  |   spv_binary binary = new spv_binary_t();  | 
947  | 0  |   if (!binary) { | 
948  | 0  |     delete[] data;  | 
949  | 0  |     return SPV_ERROR_OUT_OF_MEMORY;  | 
950  | 0  |   }  | 
951  | 0  |   binary->code = data;  | 
952  | 0  |   binary->wordCount = totalSize;  | 
953  |  | 
  | 
954  | 0  |   *pBinary = binary;  | 
955  |  | 
  | 
956  | 0  |   return SPV_SUCCESS;  | 
957  | 0  | }  | 
958  |  |  | 
959  |  | }  // anonymous namespace  | 
960  |  |  | 
961  |  | spv_result_t spvTextToBinary(const spv_const_context context,  | 
962  |  |                              const char* input_text,  | 
963  |  |                              const size_t input_text_size, spv_binary* pBinary,  | 
964  | 0  |                              spv_diagnostic* pDiagnostic) { | 
965  | 0  |   return spvTextToBinaryWithOptions(context, input_text, input_text_size,  | 
966  | 0  |                                     SPV_TEXT_TO_BINARY_OPTION_NONE, pBinary,  | 
967  | 0  |                                     pDiagnostic);  | 
968  | 0  | }  | 
969  |  |  | 
970  |  | spv_result_t spvTextToBinaryWithOptions(const spv_const_context context,  | 
971  |  |                                         const char* input_text,  | 
972  |  |                                         const size_t input_text_size,  | 
973  |  |                                         const uint32_t options,  | 
974  |  |                                         spv_binary* pBinary,  | 
975  | 0  |                                         spv_diagnostic* pDiagnostic) { | 
976  | 0  |   spv_context_t hijack_context = *context;  | 
977  | 0  |   if (pDiagnostic) { | 
978  | 0  |     *pDiagnostic = nullptr;  | 
979  | 0  |     spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);  | 
980  | 0  |   }  | 
981  |  | 
  | 
982  | 0  |   spv_text_t text = {input_text, input_text_size}; | 
983  | 0  |   spvtools::AssemblyGrammar grammar(&hijack_context);  | 
984  |  | 
  | 
985  | 0  |   spv_result_t result = spvTextToBinaryInternal(  | 
986  | 0  |       grammar, hijack_context.consumer, &text, options, pBinary);  | 
987  | 0  |   if (pDiagnostic && *pDiagnostic) (*pDiagnostic)->isTextSource = true;  | 
988  |  | 
  | 
989  | 0  |   return result;  | 
990  | 0  | }  | 
991  |  |  | 
992  | 815  | void spvTextDestroy(spv_text text) { | 
993  | 815  |   if (text) { | 
994  | 814  |     if (text->str) delete[] text->str;  | 
995  | 814  |     delete text;  | 
996  | 814  |   }  | 
997  | 815  | }  |