blob: 38034653918e8c7b7f212f2b4fcf9d728c22a607 [file] [log] [blame]
Dejan Mircevskib6fe02f2016-01-07 13:44:22 -05001// Copyright (c) 2015-2016 The Khronos Group Inc.
Andrew Woloszyn71fc0552015-09-24 10:26:51 -04002//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and/or associated documentation files (the
5// "Materials"), to deal in the Materials without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Materials, and to
8// permit persons to whom the Materials are furnished to do so, subject to
9// the following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Materials.
13//
14// MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS
15// KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS
16// SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT
17// https://www.khronos.org/registry/
18//
19// THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
23// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25// MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
26
27#include "text_handler.h"
28
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040029#include <cassert>
David Neto78e677b2015-10-05 13:28:46 -040030#include <cstdlib>
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040031#include <cstring>
Andrew Woloszyn537e7762015-09-29 11:28:34 -040032#include <tuple>
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040033
David Netofcc7d582015-10-27 15:31:10 -040034#include "assembly_grammar.h"
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040035#include "binary.h"
36#include "ext_inst.h"
David Netob5dc8fc2015-10-06 16:22:00 -040037#include "instruction.h"
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040038#include "opcode.h"
39#include "text.h"
Andrew Woloszynf731cbf2015-10-23 09:53:58 -040040#include "util/bitutils.h"
David Neto9e545d72015-11-06 18:08:49 -050041#include "util/hex_float.h"
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040042
43namespace {
44
David Neto78e677b2015-10-05 13:28:46 -040045using spvutils::BitwiseCast;
David Neto9e545d72015-11-06 18:08:49 -050046using spvutils::FloatProxy;
47using spvutils::HexFloat;
David Neto78e677b2015-10-05 13:28:46 -040048
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040049/// @brief Advance text to the start of the next line
50///
51/// @param[in] text to be parsed
52/// @param[in,out] position position text has been advanced to
53///
54/// @return result code
55spv_result_t advanceLine(spv_text text, spv_position position) {
56 while (true) {
57 switch (text->str[position->index]) {
58 case '\0':
59 return SPV_END_OF_STREAM;
60 case '\n':
61 position->column = 0;
62 position->line++;
63 position->index++;
64 return SPV_SUCCESS;
65 default:
66 position->column++;
67 position->index++;
68 break;
69 }
70 }
71}
72
73/// @brief Advance text to first non white space character
74/// If a null terminator is found during the text advance SPV_END_OF_STREAM is
75/// returned, SPV_SUCCESS otherwise. No error checking is performed on the
76/// parameters, its the users responsibility to ensure these are non null.
77///
78/// @param[in] text to be parsed
79/// @param[in,out] position text has been advanced to
80///
81/// @return result code
82spv_result_t advance(spv_text text, spv_position position) {
83 // NOTE: Consume white space, otherwise don't advance.
Lei Zhang8f6ba142015-11-06 15:09:04 -050084 if (position->index >= text->length) return SPV_END_OF_STREAM;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040085 switch (text->str[position->index]) {
86 case '\0':
87 return SPV_END_OF_STREAM;
88 case ';':
89 if (spv_result_t error = advanceLine(text, position)) return error;
90 return advance(text, position);
91 case ' ':
92 case '\t':
Dejan Mircevskia1de2b32016-04-01 00:47:02 -040093 case '\r':
Andrew Woloszyn71fc0552015-09-24 10:26:51 -040094 position->column++;
95 position->index++;
96 return advance(text, position);
97 case '\n':
98 position->column = 0;
99 position->line++;
100 position->index++;
101 return advance(text, position);
102 default:
103 break;
104 }
105 return SPV_SUCCESS;
106}
107
Lei Zhang6032b982016-03-15 16:52:40 -0400108// Fetches the next word from the given text stream starting from the given
109// *position. On success, writes the decoded word into *word and updates
110// *position to the location past the returned word.
111//
112// A word ends at the next comment or whitespace. However, double-quoted
113// strings remain intact, and a backslash always escapes the next character.
114spv_result_t getWord(spv_text text, spv_position position, std::string* word) {
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400115 if (!text->str || !text->length) return SPV_ERROR_INVALID_TEXT;
Lei Zhang6032b982016-03-15 16:52:40 -0400116 if (!position) return SPV_ERROR_INVALID_POINTER;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400117
Lei Zhang6032b982016-03-15 16:52:40 -0400118 const size_t start_index = position->index;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400119
120 bool quoting = false;
121 bool escaping = false;
122
123 // NOTE: Assumes first character is not white space!
124 while (true) {
Lei Zhang6032b982016-03-15 16:52:40 -0400125 if (position->index >= text->length) {
126 word->assign(text->str + start_index, text->str + position->index);
Lei Zhang9413fbb2016-02-22 17:17:25 -0500127 return SPV_SUCCESS;
128 }
Lei Zhang6032b982016-03-15 16:52:40 -0400129 const char ch = text->str[position->index];
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400130 if (ch == '\\')
131 escaping = !escaping;
132 else {
133 switch (ch) {
134 case '"':
135 if (!escaping) quoting = !quoting;
136 break;
137 case ' ':
138 case ';':
139 case '\t':
140 case '\n':
Dejan Mircevskia1de2b32016-04-01 00:47:02 -0400141 case '\r':
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400142 if (escaping || quoting) break;
143 // Fall through.
144 case '\0': { // NOTE: End of word found!
Lei Zhang6032b982016-03-15 16:52:40 -0400145 word->assign(text->str + start_index, text->str + position->index);
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400146 return SPV_SUCCESS;
147 }
148 default:
149 break;
150 }
151 escaping = false;
152 }
153
Lei Zhang6032b982016-03-15 16:52:40 -0400154 position->column++;
155 position->index++;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400156 }
157}
158
159// Returns true if the characters in the text as position represent
160// the start of an Opcode.
161bool startsWithOp(spv_text text, spv_position position) {
162 if (text->length < position->index + 3) return false;
163 char ch0 = text->str[position->index];
164 char ch1 = text->str[position->index + 1];
165 char ch2 = text->str[position->index + 2];
166 return ('O' == ch0 && 'p' == ch1 && ('A' <= ch2 && ch2 <= 'Z'));
167}
168
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400169} // anonymous namespace
170
171namespace libspirv {
172
David Neto78e677b2015-10-05 13:28:46 -0400173const IdType kUnknownType = {0, false, IdTypeClass::kBottom};
174
David Neto78e677b2015-10-05 13:28:46 -0400175// TODO(dneto): Reorder AssemblyContext definitions to match declaration order.
176
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400177// This represents all of the data that is only valid for the duration of
178// a single compilation.
Lei Zhang1a0334e2015-11-02 09:41:20 -0500179uint32_t AssemblyContext::spvNamedIdAssignOrGet(const char* textValue) {
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400180 if (named_ids_.end() == named_ids_.find(textValue)) {
181 named_ids_[std::string(textValue)] = bound_++;
182 }
183 return named_ids_[textValue];
184}
185uint32_t AssemblyContext::getBound() const { return bound_; }
186
187spv_result_t AssemblyContext::advance() {
188 return ::advance(text_, &current_position_);
189}
190
Lei Zhang6032b982016-03-15 16:52:40 -0400191spv_result_t AssemblyContext::getWord(std::string* word,
192 spv_position next_position) {
193 *next_position = current_position_;
194 return ::getWord(text_, next_position, word);
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400195}
196
197bool AssemblyContext::startsWithOp() {
198 return ::startsWithOp(text_, &current_position_);
199}
200
201bool AssemblyContext::isStartOfNewInst() {
Lei Zhang6032b982016-03-15 16:52:40 -0400202 spv_position_t pos = current_position_;
203 if (::advance(text_, &pos)) return false;
204 if (::startsWithOp(text_, &pos)) return true;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400205
206 std::string word;
Lei Zhang6032b982016-03-15 16:52:40 -0400207 pos = current_position_;
208 if (::getWord(text_, &pos, &word)) return false;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400209 if ('%' != word.front()) return false;
210
Lei Zhang6032b982016-03-15 16:52:40 -0400211 if (::advance(text_, &pos)) return false;
212 if (::getWord(text_, &pos, &word)) return false;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400213 if ("=" != word) return false;
214
Lei Zhang6032b982016-03-15 16:52:40 -0400215 if (::advance(text_, &pos)) return false;
216 if (::startsWithOp(text_, &pos)) return true;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400217 return false;
218}
Andrew Woloszyn4274f932015-10-20 09:12:32 -0400219
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400220char AssemblyContext::peek() const {
221 return text_->str[current_position_.index];
222}
223
224bool AssemblyContext::hasText() const {
225 return text_->length > current_position_.index;
226}
Andrew Woloszyn4274f932015-10-20 09:12:32 -0400227
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400228void AssemblyContext::seekForward(uint32_t size) {
229 current_position_.index += size;
230 current_position_.column += size;
231}
232
233spv_result_t AssemblyContext::binaryEncodeU32(const uint32_t value,
Lei Zhang1a0334e2015-11-02 09:41:20 -0500234 spv_instruction_t* pInst) {
Andrew Woloszyn4ddb4312016-02-17 13:00:23 -0500235 pInst->words.insert(pInst->words.end(), value);
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400236 return SPV_SUCCESS;
237}
238
239spv_result_t AssemblyContext::binaryEncodeU64(const uint64_t value,
Lei Zhang1a0334e2015-11-02 09:41:20 -0500240 spv_instruction_t* pInst) {
David Neto78e677b2015-10-05 13:28:46 -0400241 uint32_t low = uint32_t(0x00000000ffffffff & value);
242 uint32_t high = uint32_t((0xffffffff00000000 & value) >> 32);
David Netoac508b02015-10-09 15:48:09 -0400243 binaryEncodeU32(low, pInst);
244 binaryEncodeU32(high, pInst);
245 return SPV_SUCCESS;
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400246}
247
David Neto78e677b2015-10-05 13:28:46 -0400248spv_result_t AssemblyContext::binaryEncodeNumericLiteral(
Lei Zhang1a0334e2015-11-02 09:41:20 -0500249 const char* val, spv_result_t error_code, const IdType& type,
250 spv_instruction_t* pInst) {
David Neto78e677b2015-10-05 13:28:46 -0400251 const bool is_bottom = type.type_class == libspirv::IdTypeClass::kBottom;
252 const bool is_floating = libspirv::isScalarFloating(type);
253 const bool is_integer = libspirv::isScalarIntegral(type);
254
255 if (!is_bottom && !is_floating && !is_integer) {
256 return diagnostic(SPV_ERROR_INTERNAL)
257 << "The expected type is not a scalar integer or float type";
258 }
259
260 // If this is bottom, but looks like a float, we should treat it like a
261 // float.
262 const bool looks_like_float = is_bottom && strchr(val, '.');
263
264 // If we explicitly expect a floating-point number, we should handle that
265 // first.
266 if (is_floating || looks_like_float)
David Neto51013d12015-10-14 11:31:51 -0400267 return binaryEncodeFloatingPointLiteral(val, error_code, type, pInst);
David Neto78e677b2015-10-05 13:28:46 -0400268
David Neto51013d12015-10-14 11:31:51 -0400269 return binaryEncodeIntegerLiteral(val, error_code, type, pInst);
David Neto78e677b2015-10-05 13:28:46 -0400270}
271
Lei Zhang1a0334e2015-11-02 09:41:20 -0500272spv_result_t AssemblyContext::binaryEncodeString(const char* value,
273 spv_instruction_t* pInst) {
David Netob5dc8fc2015-10-06 16:22:00 -0400274 const size_t length = strlen(value);
275 const size_t wordCount = (length / 4) + 1;
276 const size_t oldWordCount = pInst->words.size();
277 const size_t newWordCount = oldWordCount + wordCount;
278
279 // TODO(dneto): We can just defer this check until later.
280 if (newWordCount > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
David Neto78e677b2015-10-05 13:28:46 -0400281 return diagnostic() << "Instruction too long: more than "
282 << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX << " words.";
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400283 }
284
David Netob5dc8fc2015-10-06 16:22:00 -0400285 pInst->words.resize(newWordCount);
286
287 // Make sure all the bytes in the last word are 0, in case we only
288 // write a partial word at the end.
289 pInst->words.back() = 0;
290
Lei Zhang1a0334e2015-11-02 09:41:20 -0500291 char* dest = (char*)&pInst->words[oldWordCount];
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400292 strncpy(dest, value, length);
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400293
294 return SPV_SUCCESS;
295}
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400296
297spv_result_t AssemblyContext::recordTypeDefinition(
Lei Zhang1a0334e2015-11-02 09:41:20 -0500298 const spv_instruction_t* pInst) {
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400299 uint32_t value = pInst->words[1];
300 if (types_.find(value) != types_.end()) {
Lei Zhang1a0334e2015-11-02 09:41:20 -0500301 return diagnostic() << "Value " << value
302 << " has already been used to generate a type";
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400303 }
304
Lei Zhangb36e7042015-10-28 13:40:52 -0400305 if (pInst->opcode == SpvOpTypeInt) {
David Neto78e677b2015-10-05 13:28:46 -0400306 if (pInst->words.size() != 4)
307 return diagnostic() << "Invalid OpTypeInt instruction";
308 types_[value] = {pInst->words[2], pInst->words[3] != 0,
309 IdTypeClass::kScalarIntegerType};
Lei Zhangb36e7042015-10-28 13:40:52 -0400310 } else if (pInst->opcode == SpvOpTypeFloat) {
David Neto78e677b2015-10-05 13:28:46 -0400311 if (pInst->words.size() != 3)
312 return diagnostic() << "Invalid OpTypeFloat instruction";
313 types_[value] = {pInst->words[2], false, IdTypeClass::kScalarFloatType};
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400314 } else {
David Neto78e677b2015-10-05 13:28:46 -0400315 types_[value] = {0, false, IdTypeClass::kOtherType};
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400316 }
317 return SPV_SUCCESS;
318}
319
320IdType AssemblyContext::getTypeOfTypeGeneratingValue(uint32_t value) const {
321 auto type = types_.find(value);
322 if (type == types_.end()) {
David Neto78e677b2015-10-05 13:28:46 -0400323 return kUnknownType;
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400324 }
325 return std::get<1>(*type);
326}
327
328IdType AssemblyContext::getTypeOfValueInstruction(uint32_t value) const {
329 auto type_value = value_types_.find(value);
330 if (type_value == value_types_.end()) {
Lei Zhang1a0334e2015-11-02 09:41:20 -0500331 return {0, false, IdTypeClass::kBottom};
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400332 }
333 return getTypeOfTypeGeneratingValue(std::get<1>(*type_value));
334}
335
336spv_result_t AssemblyContext::recordTypeIdForValue(uint32_t value,
337 uint32_t type) {
338 bool successfully_inserted = false;
339 std::tie(std::ignore, successfully_inserted) =
340 value_types_.insert(std::make_pair(value, type));
David Neto78e677b2015-10-05 13:28:46 -0400341 if (!successfully_inserted)
342 return diagnostic() << "Value is being defined a second time";
Andrew Woloszyn537e7762015-09-29 11:28:34 -0400343 return SPV_SUCCESS;
344}
345
David Neto2ae4a682015-11-09 18:55:42 -0500346spv_result_t AssemblyContext::recordIdAsExtInstImport(
347 uint32_t id, spv_ext_inst_type_t type) {
348 bool successfully_inserted = false;
349 std::tie(std::ignore, successfully_inserted) =
350 import_id_to_ext_inst_type_.insert(std::make_pair(id, type));
351 if (!successfully_inserted)
352 return diagnostic() << "Import Id is being defined a second time";
353 return SPV_SUCCESS;
354}
355
356spv_ext_inst_type_t AssemblyContext::getExtInstTypeForId(uint32_t id) const {
357 auto type = import_id_to_ext_inst_type_.find(id);
358 if (type == import_id_to_ext_inst_type_.end()) {
359 return SPV_EXT_INST_TYPE_NONE;
360 }
361 return std::get<1>(*type);
362}
363
David Neto78e677b2015-10-05 13:28:46 -0400364spv_result_t AssemblyContext::binaryEncodeFloatingPointLiteral(
Lei Zhang1a0334e2015-11-02 09:41:20 -0500365 const char* val, spv_result_t error_code, const IdType& type,
366 spv_instruction_t* pInst) {
David Neto78e677b2015-10-05 13:28:46 -0400367 const auto bit_width = assumedBitWidth(type);
368 switch (bit_width) {
Andrew Woloszyn43401d22016-01-08 09:54:42 -0500369 case 16: {
370 spvutils::HexFloat<FloatProxy<spvutils::Float16>> hVal(0);
371 if (auto error = parseNumber(val, error_code, &hVal,
372 "Invalid 16-bit float literal: "))
373 return error;
374 // getAsFloat will return the spvutils::Float16 value, and get_value
375 // will return a uint16_t representing the bits of the float.
376 // The encoding is therefore correct from the perspective of the SPIR-V
377 // spec since the top 16 bits will be 0.
378 return binaryEncodeU32(
379 static_cast<uint32_t>(hVal.value().getAsFloat().get_value()), pInst);
380 } break;
David Neto78e677b2015-10-05 13:28:46 -0400381 case 32: {
David Neto9e545d72015-11-06 18:08:49 -0500382 spvutils::HexFloat<FloatProxy<float>> fVal(0.0f);
David Neto51013d12015-10-14 11:31:51 -0400383 if (auto error = parseNumber(val, error_code, &fVal,
David Neto78e677b2015-10-05 13:28:46 -0400384 "Invalid 32-bit float literal: "))
385 return error;
386 return binaryEncodeU32(BitwiseCast<uint32_t>(fVal), pInst);
387 } break;
388 case 64: {
David Neto9e545d72015-11-06 18:08:49 -0500389 spvutils::HexFloat<FloatProxy<double>> dVal(0.0);
David Neto51013d12015-10-14 11:31:51 -0400390 if (auto error = parseNumber(val, error_code, &dVal,
David Neto78e677b2015-10-05 13:28:46 -0400391 "Invalid 64-bit float literal: "))
392 return error;
393 return binaryEncodeU64(BitwiseCast<uint64_t>(dVal), pInst);
394 } break;
395 default:
396 break;
397 }
398 return diagnostic() << "Unsupported " << bit_width << "-bit float literals";
Andrew Woloszyn71fc0552015-09-24 10:26:51 -0400399}
400
Andrew Woloszyn4ddb4312016-02-17 13:00:23 -0500401// Returns SPV_SUCCESS if the given value fits within the target scalar
402// integral type. The target type may have an unusual bit width.
403// If the value was originally specified as a hexadecimal number, then
404// the overflow bits should be zero. If it was hex and the target type is
405// signed, then return the sign-extended value through the
406// updated_value_for_hex pointer argument.
407// On failure, return the given error code and emit a diagnostic if that error
408// code is not SPV_FAILED_MATCH.
David Neto78e677b2015-10-05 13:28:46 -0400409template <typename T>
Andrew Woloszyn4ddb4312016-02-17 13:00:23 -0500410spv_result_t checkRangeAndIfHexThenSignExtend(T value, spv_result_t error_code,
411 const IdType& type, bool is_hex,
412 T* updated_value_for_hex) {
David Neto78e677b2015-10-05 13:28:46 -0400413 // The encoded result has three regions of bits that are of interest, from
414 // least to most significant:
415 // - magnitude bits, where the magnitude of the number would be stored if
416 // we were using a signed-magnitude representation.
417 // - an optional sign bit
418 // - overflow bits, up to bit 63 of a 64-bit number
419 // For example:
420 // Type Overflow Sign Magnitude
421 // --------------- -------- ---- ---------
422 // unsigned 8 bit 8-63 n/a 0-7
423 // signed 8 bit 8-63 7 0-6
424 // unsigned 16 bit 16-63 n/a 0-15
425 // signed 16 bit 16-63 15 0-14
426
427 // We'll use masks to define the three regions.
428 // At first we'll assume the number is unsigned.
429 const uint32_t bit_width = assumedBitWidth(type);
430 uint64_t magnitude_mask =
431 (bit_width == 64) ? -1 : ((uint64_t(1) << bit_width) - 1);
432 uint64_t sign_mask = 0;
433 uint64_t overflow_mask = ~magnitude_mask;
434
435 if (value < 0 || type.isSigned) {
436 // Accommodate the sign bit.
437 magnitude_mask >>= 1;
438 sign_mask = magnitude_mask + 1;
439 }
440
441 bool failed = false;
442 if (value < 0) {
443 // The top bits must all be 1 for a negative signed value.
444 failed = ((value & overflow_mask) != overflow_mask) ||
445 ((value & sign_mask) != sign_mask);
446 } else {
447 if (is_hex) {
448 // Hex values are a bit special. They decode as unsigned values, but
449 // may represent a negative number. In this case, the overflow bits
450 // should be zero.
Ben Vanik01c8d7a2015-11-22 08:32:53 -0800451 failed = (value & overflow_mask) != 0;
David Neto78e677b2015-10-05 13:28:46 -0400452 } else {
Lei Zhang8bd75d62015-11-18 09:22:10 -0500453 const uint64_t value_as_u64 = static_cast<uint64_t>(value);
David Neto78e677b2015-10-05 13:28:46 -0400454 // Check overflow in the ordinary case.
Lei Zhang8bd75d62015-11-18 09:22:10 -0500455 failed = (value_as_u64 & magnitude_mask) != value_as_u64;
David Neto78e677b2015-10-05 13:28:46 -0400456 }
457 }
458
459 if (failed) {
Andrew Woloszyn4ddb4312016-02-17 13:00:23 -0500460 return error_code;
David Neto78e677b2015-10-05 13:28:46 -0400461 }
462
463 // Sign extend hex the number.
464 if (is_hex && (value & sign_mask))
465 *updated_value_for_hex = (value | overflow_mask);
466
467 return SPV_SUCCESS;
468}
Andrew Woloszyn4ddb4312016-02-17 13:00:23 -0500469
470spv_result_t AssemblyContext::binaryEncodeIntegerLiteral(
471 const char* val, spv_result_t error_code, const IdType& type,
472 spv_instruction_t* pInst) {
473 const bool is_bottom = type.type_class == libspirv::IdTypeClass::kBottom;
474 const uint32_t bit_width = assumedBitWidth(type);
475
476 if (bit_width > 64)
477 return diagnostic(SPV_ERROR_INTERNAL) << "Unsupported " << bit_width
478 << "-bit integer literals";
479
480 // Either we are expecting anything or integer.
481 bool is_negative = val[0] == '-';
482 bool can_be_signed = is_bottom || type.isSigned;
483
484 if (is_negative && !can_be_signed) {
485 return diagnostic()
486 << "Cannot put a negative number in an unsigned literal";
487 }
488
489 const bool is_hex = val[0] == '0' && (val[1] == 'x' || val[1] == 'X');
490
491 uint64_t decoded_bits;
492 if (is_negative) {
493 int64_t decoded_signed = 0;
494
495 if (auto error = parseNumber(val, error_code, &decoded_signed,
496 "Invalid signed integer literal: "))
497 return error;
498 if (auto error = checkRangeAndIfHexThenSignExtend(
499 decoded_signed, error_code, type, is_hex, &decoded_signed)) {
500 diagnostic(error_code)
501 << "Integer " << (is_hex ? std::hex : std::dec) << std::showbase
502 << decoded_signed << " does not fit in a " << std::dec << bit_width
503 << "-bit " << (type.isSigned ? "signed" : "unsigned") << " integer";
504 return error;
505 }
506 decoded_bits = decoded_signed;
507 } else {
508 // There's no leading minus sign, so parse it as an unsigned integer.
509 if (auto error = parseNumber(val, error_code, &decoded_bits,
510 "Invalid unsigned integer literal: "))
511 return error;
512 if (auto error = checkRangeAndIfHexThenSignExtend(
513 decoded_bits, error_code, type, is_hex, &decoded_bits)) {
514 diagnostic(error_code)
515 << "Integer " << (is_hex ? std::hex : std::dec) << std::showbase
516 << decoded_bits << " does not fit in a " << std::dec << bit_width
517 << "-bit " << (type.isSigned ? "signed" : "unsigned") << " integer";
518 return error;
519 }
520 }
521 if (bit_width > 32) {
522 return binaryEncodeU64(decoded_bits, pInst);
523 } else {
524 return binaryEncodeU32(uint32_t(decoded_bits), pInst);
525 }
526}
Lei Zhang1a0334e2015-11-02 09:41:20 -0500527} // namespace libspirv