1 // Copyright (c) 2015-2016 The Khronos Group Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "source/text_handler.h"
16
17 #include <algorithm>
18 #include <cassert>
19 #include <cstdlib>
20 #include <cstring>
21 #include <tuple>
22
23 #include "source/assembly_grammar.h"
24 #include "source/binary.h"
25 #include "source/ext_inst.h"
26 #include "source/instruction.h"
27 #include "source/opcode.h"
28 #include "source/text.h"
29 #include "source/util/bitutils.h"
30 #include "source/util/hex_float.h"
31 #include "source/util/parse_number.h"
32 #include "source/util/string_utils.h"
33
34 namespace spvtools {
35 namespace {
36
37 // Advances |text| to the start of the next line and writes the new position to
38 // |position|.
advanceLine(spv_text text,spv_position position)39 spv_result_t advanceLine(spv_text text, spv_position position) {
40 while (true) {
41 if (position->index >= text->length) return SPV_END_OF_STREAM;
42 switch (text->str[position->index]) {
43 case '\0':
44 return SPV_END_OF_STREAM;
45 case '\n':
46 position->column = 0;
47 position->line++;
48 position->index++;
49 return SPV_SUCCESS;
50 default:
51 position->column++;
52 position->index++;
53 break;
54 }
55 }
56 }
57
58 // Advances |text| to first non white space character and writes the new
59 // position to |position|.
60 // If a null terminator is found during the text advance, SPV_END_OF_STREAM is
61 // returned, SPV_SUCCESS otherwise. No error checking is performed on the
62 // parameters, its the users responsibility to ensure these are non null.
advance(spv_text text,spv_position position)63 spv_result_t advance(spv_text text, spv_position position) {
64 // NOTE: Consume white space, otherwise don't advance.
65 if (position->index >= text->length) return SPV_END_OF_STREAM;
66 switch (text->str[position->index]) {
67 case '\0':
68 return SPV_END_OF_STREAM;
69 case ';':
70 if (spv_result_t error = advanceLine(text, position)) return error;
71 return advance(text, position);
72 case ' ':
73 case '\t':
74 case '\r':
75 position->column++;
76 position->index++;
77 return advance(text, position);
78 case '\n':
79 position->column = 0;
80 position->line++;
81 position->index++;
82 return advance(text, position);
83 default:
84 break;
85 }
86 return SPV_SUCCESS;
87 }
88
89 // Fetches the next word from the given text stream starting from the given
90 // *position. On success, writes the decoded word into *word and updates
91 // *position to the location past the returned word.
92 //
93 // A word ends at the next comment or whitespace. However, double-quoted
94 // strings remain intact, and a backslash always escapes the next character.
getWord(spv_text text,spv_position position,std::string * word)95 spv_result_t getWord(spv_text text, spv_position position, std::string* word) {
96 if (!text->str || !text->length) return SPV_ERROR_INVALID_TEXT;
97 if (!position) return SPV_ERROR_INVALID_POINTER;
98
99 const size_t start_index = position->index;
100
101 bool quoting = false;
102 bool escaping = false;
103
104 // NOTE: Assumes first character is not white space!
105 while (true) {
106 if (position->index >= text->length) {
107 word->assign(text->str + start_index, text->str + position->index);
108 return SPV_SUCCESS;
109 }
110 const char ch = text->str[position->index];
111 if (ch == '\\') {
112 escaping = !escaping;
113 } else {
114 switch (ch) {
115 case '"':
116 if (!escaping) quoting = !quoting;
117 break;
118 case ' ':
119 case ';':
120 case '\t':
121 case '\n':
122 case '\r':
123 if (escaping || quoting) break;
124 word->assign(text->str + start_index, text->str + position->index);
125 return SPV_SUCCESS;
126 case '\0': { // NOTE: End of word found!
127 word->assign(text->str + start_index, text->str + position->index);
128 return SPV_SUCCESS;
129 }
130 default:
131 break;
132 }
133 escaping = false;
134 }
135
136 position->column++;
137 position->index++;
138 }
139 }
140
141 // Returns true if the characters in the text as position represent
142 // the start of an Opcode.
startsWithOp(spv_text text,spv_position position)143 bool startsWithOp(spv_text text, spv_position position) {
144 if (text->length < position->index + 3) return false;
145 char ch0 = text->str[position->index];
146 char ch1 = text->str[position->index + 1];
147 char ch2 = text->str[position->index + 2];
148 return ('O' == ch0 && 'p' == ch1 && ('A' <= ch2 && ch2 <= 'Z'));
149 }
150
151 } // namespace
152
153 const IdType kUnknownType = {0, false, IdTypeClass::kBottom};
154
155 // TODO(dneto): Reorder AssemblyContext definitions to match declaration order.
156
157 // This represents all of the data that is only valid for the duration of
158 // a single compilation.
spvNamedIdAssignOrGet(const char * textValue)159 uint32_t AssemblyContext::spvNamedIdAssignOrGet(const char* textValue) {
160 if (!ids_to_preserve_.empty()) {
161 uint32_t id = 0;
162 if (spvtools::utils::ParseNumber(textValue, &id)) {
163 if (ids_to_preserve_.find(id) != ids_to_preserve_.end()) {
164 bound_ = std::max(bound_, id + 1);
165 return id;
166 }
167 }
168 }
169
170 const auto it = named_ids_.find(textValue);
171 if (it == named_ids_.end()) {
172 uint32_t id = next_id_++;
173 if (!ids_to_preserve_.empty()) {
174 while (ids_to_preserve_.find(id) != ids_to_preserve_.end()) {
175 id = next_id_++;
176 }
177 }
178
179 named_ids_.emplace(textValue, id);
180 bound_ = std::max(bound_, id + 1);
181 return id;
182 }
183
184 return it->second;
185 }
186
getBound() const187 uint32_t AssemblyContext::getBound() const { return bound_; }
188
advance()189 spv_result_t AssemblyContext::advance() {
190 return spvtools::advance(text_, ¤t_position_);
191 }
192
getWord(std::string * word,spv_position next_position)193 spv_result_t AssemblyContext::getWord(std::string* word,
194 spv_position next_position) {
195 *next_position = current_position_;
196 return spvtools::getWord(text_, next_position, word);
197 }
198
startsWithOp()199 bool AssemblyContext::startsWithOp() {
200 return spvtools::startsWithOp(text_, ¤t_position_);
201 }
202
isStartOfNewInst()203 bool AssemblyContext::isStartOfNewInst() {
204 spv_position_t pos = current_position_;
205 if (spvtools::advance(text_, &pos)) return false;
206 if (spvtools::startsWithOp(text_, &pos)) return true;
207
208 std::string word;
209 pos = current_position_;
210 if (spvtools::getWord(text_, &pos, &word)) return false;
211 if ('%' != word.front()) return false;
212
213 if (spvtools::advance(text_, &pos)) return false;
214 if (spvtools::getWord(text_, &pos, &word)) return false;
215 if ("=" != word) return false;
216
217 if (spvtools::advance(text_, &pos)) return false;
218 if (spvtools::startsWithOp(text_, &pos)) return true;
219 return false;
220 }
221
peek() const222 char AssemblyContext::peek() const {
223 return text_->str[current_position_.index];
224 }
225
hasText() const226 bool AssemblyContext::hasText() const {
227 return text_->length > current_position_.index;
228 }
229
seekForward(uint32_t size)230 void AssemblyContext::seekForward(uint32_t size) {
231 current_position_.index += size;
232 current_position_.column += size;
233 }
234
binaryEncodeU32(const uint32_t value,spv_instruction_t * pInst)235 spv_result_t AssemblyContext::binaryEncodeU32(const uint32_t value,
236 spv_instruction_t* pInst) {
237 pInst->words.insert(pInst->words.end(), value);
238 return SPV_SUCCESS;
239 }
240
binaryEncodeNumericLiteral(const char * val,spv_result_t error_code,const IdType & type,spv_instruction_t * pInst)241 spv_result_t AssemblyContext::binaryEncodeNumericLiteral(
242 const char* val, spv_result_t error_code, const IdType& type,
243 spv_instruction_t* pInst) {
244 using spvtools::utils::EncodeNumberStatus;
245 // Populate the NumberType from the IdType for parsing.
246 spvtools::utils::NumberType number_type;
247 switch (type.type_class) {
248 case IdTypeClass::kOtherType:
249 return diagnostic(SPV_ERROR_INTERNAL)
250 << "Unexpected numeric literal type";
251 case IdTypeClass::kScalarIntegerType:
252 if (type.isSigned) {
253 number_type = {type.bitwidth, SPV_NUMBER_SIGNED_INT};
254 } else {
255 number_type = {type.bitwidth, SPV_NUMBER_UNSIGNED_INT};
256 }
257 break;
258 case IdTypeClass::kScalarFloatType:
259 number_type = {type.bitwidth, SPV_NUMBER_FLOATING};
260 break;
261 case IdTypeClass::kBottom:
262 // kBottom means the type is unknown and we need to infer the type before
263 // parsing the number. The rule is: If there is a decimal point, treat
264 // the value as a floating point value, otherwise a integer value, then
265 // if the first char of the integer text is '-', treat the integer as a
266 // signed integer, otherwise an unsigned integer.
267 uint32_t bitwidth = static_cast<uint32_t>(assumedBitWidth(type));
268 if (strchr(val, '.')) {
269 number_type = {bitwidth, SPV_NUMBER_FLOATING};
270 } else if (type.isSigned || val[0] == '-') {
271 number_type = {bitwidth, SPV_NUMBER_SIGNED_INT};
272 } else {
273 number_type = {bitwidth, SPV_NUMBER_UNSIGNED_INT};
274 }
275 break;
276 }
277
278 std::string error_msg;
279 EncodeNumberStatus parse_status = ParseAndEncodeNumber(
280 val, number_type,
281 [this, pInst](uint32_t d) { this->binaryEncodeU32(d, pInst); },
282 &error_msg);
283 switch (parse_status) {
284 case EncodeNumberStatus::kSuccess:
285 return SPV_SUCCESS;
286 case EncodeNumberStatus::kInvalidText:
287 return diagnostic(error_code) << error_msg;
288 case EncodeNumberStatus::kUnsupported:
289 return diagnostic(SPV_ERROR_INTERNAL) << error_msg;
290 case EncodeNumberStatus::kInvalidUsage:
291 return diagnostic(SPV_ERROR_INVALID_TEXT) << error_msg;
292 }
293 // This line is not reachable, only added to satisfy the compiler.
294 return diagnostic(SPV_ERROR_INTERNAL)
295 << "Unexpected result code from ParseAndEncodeNumber()";
296 }
297
binaryEncodeString(const char * value,spv_instruction_t * pInst)298 spv_result_t AssemblyContext::binaryEncodeString(const char* value,
299 spv_instruction_t* pInst) {
300 const size_t length = strlen(value);
301 const size_t wordCount = (length / 4) + 1;
302 const size_t oldWordCount = pInst->words.size();
303 const size_t newWordCount = oldWordCount + wordCount;
304
305 // TODO(dneto): We can just defer this check until later.
306 if (newWordCount > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
307 return diagnostic() << "Instruction too long: more than "
308 << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX << " words.";
309 }
310
311 pInst->words.reserve(newWordCount);
312 spvtools::utils::AppendToVector(value, &pInst->words);
313
314 return SPV_SUCCESS;
315 }
316
recordTypeDefinition(const spv_instruction_t * pInst)317 spv_result_t AssemblyContext::recordTypeDefinition(
318 const spv_instruction_t* pInst) {
319 uint32_t value = pInst->words[1];
320 if (types_.find(value) != types_.end()) {
321 return diagnostic() << "Value " << value
322 << " has already been used to generate a type";
323 }
324
325 if (pInst->opcode == SpvOpTypeInt) {
326 if (pInst->words.size() != 4)
327 return diagnostic() << "Invalid OpTypeInt instruction";
328 types_[value] = {pInst->words[2], pInst->words[3] != 0,
329 IdTypeClass::kScalarIntegerType};
330 } else if (pInst->opcode == SpvOpTypeFloat) {
331 if (pInst->words.size() != 3)
332 return diagnostic() << "Invalid OpTypeFloat instruction";
333 types_[value] = {pInst->words[2], false, IdTypeClass::kScalarFloatType};
334 } else {
335 types_[value] = {0, false, IdTypeClass::kOtherType};
336 }
337 return SPV_SUCCESS;
338 }
339
getTypeOfTypeGeneratingValue(uint32_t value) const340 IdType AssemblyContext::getTypeOfTypeGeneratingValue(uint32_t value) const {
341 auto type = types_.find(value);
342 if (type == types_.end()) {
343 return kUnknownType;
344 }
345 return std::get<1>(*type);
346 }
347
getTypeOfValueInstruction(uint32_t value) const348 IdType AssemblyContext::getTypeOfValueInstruction(uint32_t value) const {
349 auto type_value = value_types_.find(value);
350 if (type_value == value_types_.end()) {
351 return {0, false, IdTypeClass::kBottom};
352 }
353 return getTypeOfTypeGeneratingValue(std::get<1>(*type_value));
354 }
355
recordTypeIdForValue(uint32_t value,uint32_t type)356 spv_result_t AssemblyContext::recordTypeIdForValue(uint32_t value,
357 uint32_t type) {
358 bool successfully_inserted = false;
359 std::tie(std::ignore, successfully_inserted) =
360 value_types_.insert(std::make_pair(value, type));
361 if (!successfully_inserted)
362 return diagnostic() << "Value is being defined a second time";
363 return SPV_SUCCESS;
364 }
365
recordIdAsExtInstImport(uint32_t id,spv_ext_inst_type_t type)366 spv_result_t AssemblyContext::recordIdAsExtInstImport(
367 uint32_t id, spv_ext_inst_type_t type) {
368 bool successfully_inserted = false;
369 std::tie(std::ignore, successfully_inserted) =
370 import_id_to_ext_inst_type_.insert(std::make_pair(id, type));
371 if (!successfully_inserted)
372 return diagnostic() << "Import Id is being defined a second time";
373 return SPV_SUCCESS;
374 }
375
getExtInstTypeForId(uint32_t id) const376 spv_ext_inst_type_t AssemblyContext::getExtInstTypeForId(uint32_t id) const {
377 auto type = import_id_to_ext_inst_type_.find(id);
378 if (type == import_id_to_ext_inst_type_.end()) {
379 return SPV_EXT_INST_TYPE_NONE;
380 }
381 return std::get<1>(*type);
382 }
383
GetNumericIds() const384 std::set<uint32_t> AssemblyContext::GetNumericIds() const {
385 std::set<uint32_t> ids;
386 for (const auto& kv : named_ids_) {
387 uint32_t id;
388 if (spvtools::utils::ParseNumber(kv.first.c_str(), &id)) ids.insert(id);
389 }
390 return ids;
391 }
392
393 } // namespace spvtools
394