text.cpp 31 KB

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