text.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  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_LITERAL_FLOAT: {
  288. // The current operand is a 32-bit float.
  289. // That's just how the grammar works.
  290. spvtools::IdType expected_type = {
  291. 32, false, spvtools::IdTypeClass::kScalarFloatType};
  292. if (auto error = context->binaryEncodeNumericLiteral(
  293. textValue, error_code_for_literals, expected_type, pInst)) {
  294. return error;
  295. }
  296. } break;
  297. case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_NUMBER:
  298. // This is a context-independent literal number which can be a 32-bit
  299. // number of floating point value.
  300. if (auto error = context->binaryEncodeNumericLiteral(
  301. textValue, error_code_for_literals, spvtools::kUnknownType,
  302. pInst)) {
  303. return error;
  304. }
  305. break;
  306. case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER:
  307. case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER: {
  308. spvtools::IdType expected_type = spvtools::kUnknownType;
  309. // The encoding for OpConstant, OpSpecConstant and OpSwitch all
  310. // depend on either their own result-id or the result-id of
  311. // one of their parameters.
  312. if (spv::Op::OpConstant == pInst->opcode ||
  313. spv::Op::OpSpecConstant == pInst->opcode) {
  314. // The type of the literal is determined by the type Id of the
  315. // instruction.
  316. expected_type =
  317. context->getTypeOfTypeGeneratingValue(pInst->resultTypeId);
  318. if (!spvtools::isScalarFloating(expected_type) &&
  319. !spvtools::isScalarIntegral(expected_type)) {
  320. spv_opcode_desc d;
  321. const char* opcode_name = "opcode";
  322. if (SPV_SUCCESS == grammar.lookupOpcode(pInst->opcode, &d)) {
  323. opcode_name = d->name;
  324. }
  325. return context->diagnostic()
  326. << "Type for " << opcode_name
  327. << " must be a scalar floating point or integer type";
  328. }
  329. } else if (pInst->opcode == spv::Op::OpSwitch) {
  330. // The type of the literal is the same as the type of the selector.
  331. expected_type = context->getTypeOfValueInstruction(pInst->words[1]);
  332. if (!spvtools::isScalarIntegral(expected_type)) {
  333. return context->diagnostic()
  334. << "The selector operand for OpSwitch must be the result"
  335. " of an instruction that generates an integer scalar";
  336. }
  337. }
  338. if (auto error = context->binaryEncodeNumericLiteral(
  339. textValue, error_code_for_literals, expected_type, pInst)) {
  340. return error;
  341. }
  342. } break;
  343. case SPV_OPERAND_TYPE_LITERAL_STRING:
  344. case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
  345. spv_literal_t literal = {};
  346. spv_result_t error = spvTextToLiteral(textValue, &literal);
  347. if (error != SPV_SUCCESS) {
  348. if (error == SPV_ERROR_OUT_OF_MEMORY) return error;
  349. return context->diagnostic(error_code_for_literals)
  350. << "Invalid literal string '" << textValue << "'.";
  351. }
  352. if (literal.type != SPV_LITERAL_TYPE_STRING) {
  353. return context->diagnostic()
  354. << "Expected literal string, found literal number '" << textValue
  355. << "'.";
  356. }
  357. // NOTE: Special case for extended instruction library import
  358. if (spv::Op::OpExtInstImport == pInst->opcode) {
  359. const spv_ext_inst_type_t ext_inst_type =
  360. spvExtInstImportTypeGet(literal.str.c_str());
  361. if (SPV_EXT_INST_TYPE_NONE == ext_inst_type) {
  362. return context->diagnostic()
  363. << "Invalid extended instruction import '" << literal.str
  364. << "'";
  365. }
  366. if ((error = context->recordIdAsExtInstImport(pInst->words[1],
  367. ext_inst_type)))
  368. return error;
  369. }
  370. if (context->binaryEncodeString(literal.str.c_str(), pInst))
  371. return SPV_ERROR_INVALID_TEXT;
  372. } break;
  373. // Masks.
  374. case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
  375. case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
  376. case SPV_OPERAND_TYPE_LOOP_CONTROL:
  377. case SPV_OPERAND_TYPE_IMAGE:
  378. case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
  379. case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
  380. case SPV_OPERAND_TYPE_OPTIONAL_RAW_ACCESS_CHAIN_OPERANDS:
  381. case SPV_OPERAND_TYPE_SELECTION_CONTROL:
  382. case SPV_OPERAND_TYPE_DEBUG_INFO_FLAGS:
  383. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_INFO_FLAGS:
  384. case SPV_OPERAND_TYPE_OPTIONAL_COOPERATIVE_MATRIX_OPERANDS: {
  385. uint32_t value;
  386. if (auto error = grammar.parseMaskOperand(type, textValue, &value)) {
  387. return context->diagnostic(error)
  388. << "Invalid " << spvOperandTypeStr(type) << " operand '"
  389. << textValue << "'.";
  390. }
  391. if (auto error = context->binaryEncodeU32(value, pInst)) return error;
  392. // Prepare to parse the operands for this logical operand.
  393. grammar.pushOperandTypesForMask(type, value, pExpectedOperands);
  394. } break;
  395. case SPV_OPERAND_TYPE_OPTIONAL_CIV: {
  396. auto error = spvTextEncodeOperand(
  397. grammar, context, SPV_OPERAND_TYPE_OPTIONAL_LITERAL_NUMBER, textValue,
  398. pInst, pExpectedOperands);
  399. if (error == SPV_FAILED_MATCH) {
  400. // It's not a literal number -- is it a literal string?
  401. error = spvTextEncodeOperand(grammar, context,
  402. SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING,
  403. textValue, pInst, pExpectedOperands);
  404. }
  405. if (error == SPV_FAILED_MATCH) {
  406. // It's not a literal -- is it an ID?
  407. error =
  408. spvTextEncodeOperand(grammar, context, SPV_OPERAND_TYPE_OPTIONAL_ID,
  409. textValue, pInst, pExpectedOperands);
  410. }
  411. if (error) {
  412. return context->diagnostic(error)
  413. << "Invalid word following !<integer>: " << textValue;
  414. }
  415. if (pExpectedOperands->empty()) {
  416. pExpectedOperands->push_back(SPV_OPERAND_TYPE_OPTIONAL_CIV);
  417. }
  418. } break;
  419. default: {
  420. // NOTE: All non literal operands are handled here using the operand
  421. // table.
  422. spv_operand_desc entry;
  423. if (grammar.lookupOperand(type, textValue, strlen(textValue), &entry)) {
  424. return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
  425. << " '" << textValue << "'.";
  426. }
  427. if (context->binaryEncodeU32(entry->value, pInst)) {
  428. return context->diagnostic() << "Invalid " << spvOperandTypeStr(type)
  429. << " '" << textValue << "'.";
  430. }
  431. // Prepare to parse the operands for this logical operand.
  432. spvPushOperandTypes(entry->operandTypes, pExpectedOperands);
  433. } break;
  434. }
  435. return SPV_SUCCESS;
  436. }
  437. namespace {
  438. /// Encodes an instruction started by !<integer> at the given position in text.
  439. ///
  440. /// Puts the encoded words into *pInst. If successful, moves position past the
  441. /// instruction and returns SPV_SUCCESS. Otherwise, returns an error code and
  442. /// leaves position pointing to the error in text.
  443. spv_result_t encodeInstructionStartingWithImmediate(
  444. const spvtools::AssemblyGrammar& grammar,
  445. spvtools::AssemblyContext* context, spv_instruction_t* pInst) {
  446. std::string firstWord;
  447. spv_position_t nextPosition = {};
  448. auto error = context->getWord(&firstWord, &nextPosition);
  449. if (error) return context->diagnostic(error) << "Internal Error";
  450. if ((error = encodeImmediate(context, firstWord.c_str(), pInst))) {
  451. return error;
  452. }
  453. while (context->advance() != SPV_END_OF_STREAM) {
  454. // A beginning of a new instruction means we're done.
  455. if (context->isStartOfNewInst()) return SPV_SUCCESS;
  456. // Otherwise, there must be an operand that's either a literal, an ID, or
  457. // an immediate.
  458. std::string operandValue;
  459. if ((error = context->getWord(&operandValue, &nextPosition)))
  460. return context->diagnostic(error) << "Internal Error";
  461. if (operandValue == "=")
  462. return context->diagnostic() << firstWord << " not allowed before =.";
  463. // Needed to pass to spvTextEncodeOpcode(), but it shouldn't ever be
  464. // expanded.
  465. spv_operand_pattern_t dummyExpectedOperands;
  466. error = spvTextEncodeOperand(
  467. grammar, context, SPV_OPERAND_TYPE_OPTIONAL_CIV, operandValue.c_str(),
  468. pInst, &dummyExpectedOperands);
  469. if (error) return error;
  470. context->setPosition(nextPosition);
  471. }
  472. return SPV_SUCCESS;
  473. }
  474. /// @brief Translate single Opcode and operands to binary form
  475. ///
  476. /// @param[in] grammar the grammar to use for compilation
  477. /// @param[in, out] context the dynamic compilation info
  478. /// @param[in] text stream to translate
  479. /// @param[out] pInst returned binary Opcode
  480. /// @param[in,out] pPosition in the text stream
  481. ///
  482. /// @return result code
  483. spv_result_t spvTextEncodeOpcode(const spvtools::AssemblyGrammar& grammar,
  484. spvtools::AssemblyContext* context,
  485. spv_instruction_t* pInst) {
  486. // Check for !<integer> first.
  487. if ('!' == context->peek()) {
  488. return encodeInstructionStartingWithImmediate(grammar, context, pInst);
  489. }
  490. std::string firstWord;
  491. spv_position_t nextPosition = {};
  492. spv_result_t error = context->getWord(&firstWord, &nextPosition);
  493. if (error) return context->diagnostic() << "Internal Error";
  494. std::string opcodeName;
  495. std::string result_id;
  496. spv_position_t result_id_position = {};
  497. if (context->startsWithOp()) {
  498. opcodeName = firstWord;
  499. } else {
  500. result_id = firstWord;
  501. if ('%' != result_id.front()) {
  502. return context->diagnostic()
  503. << "Expected <opcode> or <result-id> at the beginning "
  504. "of an instruction, found '"
  505. << result_id << "'.";
  506. }
  507. result_id_position = context->position();
  508. // The '=' sign.
  509. context->setPosition(nextPosition);
  510. if (context->advance())
  511. return context->diagnostic() << "Expected '=', found end of stream.";
  512. std::string equal_sign;
  513. error = context->getWord(&equal_sign, &nextPosition);
  514. if ("=" != equal_sign)
  515. return context->diagnostic() << "'=' expected after result id but found '"
  516. << equal_sign << "'.";
  517. // The <opcode> after the '=' sign.
  518. context->setPosition(nextPosition);
  519. if (context->advance())
  520. return context->diagnostic() << "Expected opcode, found end of stream.";
  521. error = context->getWord(&opcodeName, &nextPosition);
  522. if (error) return context->diagnostic(error) << "Internal Error";
  523. if (!context->startsWithOp()) {
  524. return context->diagnostic()
  525. << "Invalid Opcode prefix '" << opcodeName << "'.";
  526. }
  527. }
  528. // NOTE: The table contains Opcode names without the "Op" prefix.
  529. const char* pInstName = opcodeName.data() + 2;
  530. spv_opcode_desc opcodeEntry;
  531. error = grammar.lookupOpcode(pInstName, &opcodeEntry);
  532. if (error) {
  533. return context->diagnostic(error)
  534. << "Invalid Opcode name '" << opcodeName << "'";
  535. }
  536. if (opcodeEntry->hasResult && result_id.empty()) {
  537. return context->diagnostic()
  538. << "Expected <result-id> at the beginning of an instruction, found '"
  539. << firstWord << "'.";
  540. }
  541. if (!opcodeEntry->hasResult && !result_id.empty()) {
  542. return context->diagnostic()
  543. << "Cannot set ID " << result_id << " because " << opcodeName
  544. << " does not produce a result ID.";
  545. }
  546. pInst->opcode = opcodeEntry->opcode;
  547. context->setPosition(nextPosition);
  548. // Reserve the first word for the instruction.
  549. spvInstructionAddWord(pInst, 0);
  550. // Maintains the ordered list of expected operand types.
  551. // For many instructions we only need the {numTypes, operandTypes}
  552. // entries in opcodeEntry. However, sometimes we need to modify
  553. // the list as we parse the operands. This occurs when an operand
  554. // has its own logical operands (such as the LocalSize operand for
  555. // ExecutionMode), or for extended instructions that may have their
  556. // own operands depending on the selected extended instruction.
  557. spv_operand_pattern_t expectedOperands;
  558. expectedOperands.reserve(opcodeEntry->numTypes);
  559. for (auto i = 0; i < opcodeEntry->numTypes; i++)
  560. expectedOperands.push_back(
  561. opcodeEntry->operandTypes[opcodeEntry->numTypes - i - 1]);
  562. while (!expectedOperands.empty()) {
  563. const spv_operand_type_t type = expectedOperands.back();
  564. expectedOperands.pop_back();
  565. // Expand optional tuples lazily.
  566. if (spvExpandOperandSequenceOnce(type, &expectedOperands)) continue;
  567. if (type == SPV_OPERAND_TYPE_RESULT_ID && !result_id.empty()) {
  568. // Handle the <result-id> for value generating instructions.
  569. // We've already consumed it from the text stream. Here
  570. // we inject its words into the instruction.
  571. spv_position_t temp_pos = context->position();
  572. error = spvTextEncodeOperand(grammar, context, SPV_OPERAND_TYPE_RESULT_ID,
  573. result_id.c_str(), pInst, nullptr);
  574. result_id_position = context->position();
  575. // Because we are injecting we have to reset the position afterwards.
  576. context->setPosition(temp_pos);
  577. if (error) return error;
  578. } else {
  579. // Find the next word.
  580. error = context->advance();
  581. if (error == SPV_END_OF_STREAM) {
  582. if (spvOperandIsOptional(type)) {
  583. // This would have been the last potential operand for the
  584. // instruction,
  585. // and we didn't find one. We're finished parsing this instruction.
  586. break;
  587. } else {
  588. return context->diagnostic()
  589. << "Expected operand for " << opcodeName
  590. << " instruction, but found the end of the stream.";
  591. }
  592. }
  593. assert(error == SPV_SUCCESS && "Somebody added another way to fail");
  594. if (context->isStartOfNewInst()) {
  595. if (spvOperandIsOptional(type)) {
  596. break;
  597. } else {
  598. return context->diagnostic()
  599. << "Expected operand for " << opcodeName
  600. << " instruction, but found the next instruction instead.";
  601. }
  602. }
  603. std::string operandValue;
  604. error = context->getWord(&operandValue, &nextPosition);
  605. if (error) return context->diagnostic(error) << "Internal Error";
  606. error = spvTextEncodeOperand(grammar, context, type, operandValue.c_str(),
  607. pInst, &expectedOperands);
  608. if (error == SPV_FAILED_MATCH && spvOperandIsOptional(type))
  609. return SPV_SUCCESS;
  610. if (error) return error;
  611. context->setPosition(nextPosition);
  612. }
  613. }
  614. if (spvOpcodeGeneratesType(pInst->opcode)) {
  615. if (context->recordTypeDefinition(pInst) != SPV_SUCCESS) {
  616. return SPV_ERROR_INVALID_TEXT;
  617. }
  618. } else if (opcodeEntry->hasType) {
  619. // SPIR-V dictates that if an instruction has both a return value and a
  620. // type ID then the type id is first, and the return value is second.
  621. assert(opcodeEntry->hasResult &&
  622. "Unknown opcode: has a type but no result.");
  623. context->recordTypeIdForValue(pInst->words[2], pInst->words[1]);
  624. }
  625. if (pInst->words.size() > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
  626. return context->diagnostic()
  627. << opcodeName << " Instruction too long: " << pInst->words.size()
  628. << " words, but the limit is "
  629. << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX;
  630. }
  631. pInst->words[0] =
  632. spvOpcodeMake(uint16_t(pInst->words.size()), opcodeEntry->opcode);
  633. return SPV_SUCCESS;
  634. }
  635. enum { kAssemblerVersion = 0 };
  636. // Populates a binary stream's |header|. The target environment is specified via
  637. // |env| and Id bound is via |bound|.
  638. spv_result_t SetHeader(spv_target_env env, const uint32_t bound,
  639. uint32_t* header) {
  640. if (!header) return SPV_ERROR_INVALID_BINARY;
  641. header[SPV_INDEX_MAGIC_NUMBER] = spv::MagicNumber;
  642. header[SPV_INDEX_VERSION_NUMBER] = spvVersionForTargetEnv(env);
  643. header[SPV_INDEX_GENERATOR_NUMBER] =
  644. SPV_GENERATOR_WORD(SPV_GENERATOR_KHRONOS_ASSEMBLER, kAssemblerVersion);
  645. header[SPV_INDEX_BOUND] = bound;
  646. header[SPV_INDEX_SCHEMA] = 0; // NOTE: Reserved
  647. return SPV_SUCCESS;
  648. }
  649. // Collects all numeric ids in the module source into |numeric_ids|.
  650. // This function is essentially a dry-run of spvTextToBinary.
  651. spv_result_t GetNumericIds(const spvtools::AssemblyGrammar& grammar,
  652. const spvtools::MessageConsumer& consumer,
  653. const spv_text text,
  654. std::set<uint32_t>* numeric_ids) {
  655. spvtools::AssemblyContext context(text, consumer);
  656. if (!text->str) return context.diagnostic() << "Missing assembly text.";
  657. if (!grammar.isValid()) {
  658. return SPV_ERROR_INVALID_TABLE;
  659. }
  660. // Skip past whitespace and comments.
  661. context.advance();
  662. while (context.hasText()) {
  663. spv_instruction_t inst;
  664. // Operand parsing sometimes involves knowing the opcode of the instruction
  665. // being parsed. A malformed input might feature such an operand *before*
  666. // the opcode is known. To guard against accessing an uninitialized opcode,
  667. // the instruction's opcode is initialized to a default value.
  668. inst.opcode = spv::Op::Max;
  669. if (spvTextEncodeOpcode(grammar, &context, &inst)) {
  670. return SPV_ERROR_INVALID_TEXT;
  671. }
  672. if (context.advance()) break;
  673. }
  674. *numeric_ids = context.GetNumericIds();
  675. return SPV_SUCCESS;
  676. }
  677. // Translates a given assembly language module into binary form.
  678. // If a diagnostic is generated, it is not yet marked as being
  679. // for a text-based input.
  680. spv_result_t spvTextToBinaryInternal(const spvtools::AssemblyGrammar& grammar,
  681. const spvtools::MessageConsumer& consumer,
  682. const spv_text text,
  683. const uint32_t options,
  684. spv_binary* pBinary) {
  685. // The ids in this set will have the same values both in source and binary.
  686. // All other ids will be generated by filling in the gaps.
  687. std::set<uint32_t> ids_to_preserve;
  688. if (options & SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS) {
  689. // Collect all numeric ids from the source into ids_to_preserve.
  690. const spv_result_t result =
  691. GetNumericIds(grammar, consumer, text, &ids_to_preserve);
  692. if (result != SPV_SUCCESS) return result;
  693. }
  694. spvtools::AssemblyContext context(text, consumer, std::move(ids_to_preserve));
  695. if (!text->str) return context.diagnostic() << "Missing assembly text.";
  696. if (!grammar.isValid()) {
  697. return SPV_ERROR_INVALID_TABLE;
  698. }
  699. if (!pBinary) return SPV_ERROR_INVALID_POINTER;
  700. std::vector<spv_instruction_t> instructions;
  701. // Skip past whitespace and comments.
  702. context.advance();
  703. while (context.hasText()) {
  704. instructions.push_back({});
  705. spv_instruction_t& inst = instructions.back();
  706. if (auto error = spvTextEncodeOpcode(grammar, &context, &inst)) {
  707. return error;
  708. }
  709. if (context.advance()) break;
  710. }
  711. size_t totalSize = SPV_INDEX_INSTRUCTION;
  712. for (auto& inst : instructions) {
  713. totalSize += inst.words.size();
  714. }
  715. uint32_t* data = new uint32_t[totalSize];
  716. if (!data) return SPV_ERROR_OUT_OF_MEMORY;
  717. uint64_t currentIndex = SPV_INDEX_INSTRUCTION;
  718. for (auto& inst : instructions) {
  719. memcpy(data + currentIndex, inst.words.data(),
  720. sizeof(uint32_t) * inst.words.size());
  721. currentIndex += inst.words.size();
  722. }
  723. if (auto error = SetHeader(grammar.target_env(), context.getBound(), data))
  724. return error;
  725. spv_binary binary = new spv_binary_t();
  726. if (!binary) {
  727. delete[] data;
  728. return SPV_ERROR_OUT_OF_MEMORY;
  729. }
  730. binary->code = data;
  731. binary->wordCount = totalSize;
  732. *pBinary = binary;
  733. return SPV_SUCCESS;
  734. }
  735. } // anonymous namespace
  736. spv_result_t spvTextToBinary(const spv_const_context context,
  737. const char* input_text,
  738. const size_t input_text_size, spv_binary* pBinary,
  739. spv_diagnostic* pDiagnostic) {
  740. return spvTextToBinaryWithOptions(context, input_text, input_text_size,
  741. SPV_TEXT_TO_BINARY_OPTION_NONE, pBinary,
  742. pDiagnostic);
  743. }
  744. spv_result_t spvTextToBinaryWithOptions(const spv_const_context context,
  745. const char* input_text,
  746. const size_t input_text_size,
  747. const uint32_t options,
  748. spv_binary* pBinary,
  749. spv_diagnostic* pDiagnostic) {
  750. spv_context_t hijack_context = *context;
  751. if (pDiagnostic) {
  752. *pDiagnostic = nullptr;
  753. spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
  754. }
  755. spv_text_t text = {input_text, input_text_size};
  756. spvtools::AssemblyGrammar grammar(&hijack_context);
  757. spv_result_t result = spvTextToBinaryInternal(
  758. grammar, hijack_context.consumer, &text, options, pBinary);
  759. if (pDiagnostic && *pDiagnostic) (*pDiagnostic)->isTextSource = true;
  760. return result;
  761. }
  762. void spvTextDestroy(spv_text text) {
  763. if (text) {
  764. if (text->str) delete[] text->str;
  765. delete text;
  766. }
  767. }