1 //===- MILexer.cpp - Machine instructions lexer implementation ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the lexing of machine instructions.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "MILexer.h"
14 #include "llvm/ADT/None.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Twine.h"
18 #include <algorithm>
19 #include <cassert>
20 #include <cctype>
21 #include <string>
22
23 using namespace llvm;
24
25 namespace {
26
27 using ErrorCallbackType =
28 function_ref<void(StringRef::iterator Loc, const Twine &)>;
29
30 /// This class provides a way to iterate and get characters from the source
31 /// string.
32 class Cursor {
33 const char *Ptr = nullptr;
34 const char *End = nullptr;
35
36 public:
Cursor(NoneType)37 Cursor(NoneType) {}
38
Cursor(StringRef Str)39 explicit Cursor(StringRef Str) {
40 Ptr = Str.data();
41 End = Ptr + Str.size();
42 }
43
isEOF() const44 bool isEOF() const { return Ptr == End; }
45
peek(int I=0) const46 char peek(int I = 0) const { return End - Ptr <= I ? 0 : Ptr[I]; }
47
advance(unsigned I=1)48 void advance(unsigned I = 1) { Ptr += I; }
49
remaining() const50 StringRef remaining() const { return StringRef(Ptr, End - Ptr); }
51
upto(Cursor C) const52 StringRef upto(Cursor C) const {
53 assert(C.Ptr >= Ptr && C.Ptr <= End);
54 return StringRef(Ptr, C.Ptr - Ptr);
55 }
56
location() const57 StringRef::iterator location() const { return Ptr; }
58
operator bool() const59 operator bool() const { return Ptr != nullptr; }
60 };
61
62 } // end anonymous namespace
63
reset(TokenKind Kind,StringRef Range)64 MIToken &MIToken::reset(TokenKind Kind, StringRef Range) {
65 this->Kind = Kind;
66 this->Range = Range;
67 return *this;
68 }
69
setStringValue(StringRef StrVal)70 MIToken &MIToken::setStringValue(StringRef StrVal) {
71 StringValue = StrVal;
72 return *this;
73 }
74
setOwnedStringValue(std::string StrVal)75 MIToken &MIToken::setOwnedStringValue(std::string StrVal) {
76 StringValueStorage = std::move(StrVal);
77 StringValue = StringValueStorage;
78 return *this;
79 }
80
setIntegerValue(APSInt IntVal)81 MIToken &MIToken::setIntegerValue(APSInt IntVal) {
82 this->IntVal = std::move(IntVal);
83 return *this;
84 }
85
86 /// Skip the leading whitespace characters and return the updated cursor.
skipWhitespace(Cursor C)87 static Cursor skipWhitespace(Cursor C) {
88 while (isblank(C.peek()))
89 C.advance();
90 return C;
91 }
92
isNewlineChar(char C)93 static bool isNewlineChar(char C) { return C == '\n' || C == '\r'; }
94
95 /// Skip a line comment and return the updated cursor.
skipComment(Cursor C)96 static Cursor skipComment(Cursor C) {
97 if (C.peek() != ';')
98 return C;
99 while (!isNewlineChar(C.peek()) && !C.isEOF())
100 C.advance();
101 return C;
102 }
103
104 /// Machine operands can have comments, enclosed between /* and */.
105 /// This eats up all tokens, including /* and */.
skipMachineOperandComment(Cursor C)106 static Cursor skipMachineOperandComment(Cursor C) {
107 if (C.peek() != '/' || C.peek(1) != '*')
108 return C;
109
110 while (C.peek() != '*' || C.peek(1) != '/')
111 C.advance();
112
113 C.advance();
114 C.advance();
115 return C;
116 }
117
118 /// Return true if the given character satisfies the following regular
119 /// expression: [-a-zA-Z$._0-9]
isIdentifierChar(char C)120 static bool isIdentifierChar(char C) {
121 return isalpha(C) || isdigit(C) || C == '_' || C == '-' || C == '.' ||
122 C == '$';
123 }
124
125 /// Unescapes the given string value.
126 ///
127 /// Expects the string value to be quoted.
unescapeQuotedString(StringRef Value)128 static std::string unescapeQuotedString(StringRef Value) {
129 assert(Value.front() == '"' && Value.back() == '"');
130 Cursor C = Cursor(Value.substr(1, Value.size() - 2));
131
132 std::string Str;
133 Str.reserve(C.remaining().size());
134 while (!C.isEOF()) {
135 char Char = C.peek();
136 if (Char == '\\') {
137 if (C.peek(1) == '\\') {
138 // Two '\' become one
139 Str += '\\';
140 C.advance(2);
141 continue;
142 }
143 if (isxdigit(C.peek(1)) && isxdigit(C.peek(2))) {
144 Str += hexDigitValue(C.peek(1)) * 16 + hexDigitValue(C.peek(2));
145 C.advance(3);
146 continue;
147 }
148 }
149 Str += Char;
150 C.advance();
151 }
152 return Str;
153 }
154
155 /// Lex a string constant using the following regular expression: \"[^\"]*\"
lexStringConstant(Cursor C,ErrorCallbackType ErrorCallback)156 static Cursor lexStringConstant(Cursor C, ErrorCallbackType ErrorCallback) {
157 assert(C.peek() == '"');
158 for (C.advance(); C.peek() != '"'; C.advance()) {
159 if (C.isEOF() || isNewlineChar(C.peek())) {
160 ErrorCallback(
161 C.location(),
162 "end of machine instruction reached before the closing '\"'");
163 return None;
164 }
165 }
166 C.advance();
167 return C;
168 }
169
lexName(Cursor C,MIToken & Token,MIToken::TokenKind Type,unsigned PrefixLength,ErrorCallbackType ErrorCallback)170 static Cursor lexName(Cursor C, MIToken &Token, MIToken::TokenKind Type,
171 unsigned PrefixLength, ErrorCallbackType ErrorCallback) {
172 auto Range = C;
173 C.advance(PrefixLength);
174 if (C.peek() == '"') {
175 if (Cursor R = lexStringConstant(C, ErrorCallback)) {
176 StringRef String = Range.upto(R);
177 Token.reset(Type, String)
178 .setOwnedStringValue(
179 unescapeQuotedString(String.drop_front(PrefixLength)));
180 return R;
181 }
182 Token.reset(MIToken::Error, Range.remaining());
183 return Range;
184 }
185 while (isIdentifierChar(C.peek()))
186 C.advance();
187 Token.reset(Type, Range.upto(C))
188 .setStringValue(Range.upto(C).drop_front(PrefixLength));
189 return C;
190 }
191
getIdentifierKind(StringRef Identifier)192 static MIToken::TokenKind getIdentifierKind(StringRef Identifier) {
193 return StringSwitch<MIToken::TokenKind>(Identifier)
194 .Case("_", MIToken::underscore)
195 .Case("implicit", MIToken::kw_implicit)
196 .Case("implicit-def", MIToken::kw_implicit_define)
197 .Case("def", MIToken::kw_def)
198 .Case("dead", MIToken::kw_dead)
199 .Case("killed", MIToken::kw_killed)
200 .Case("undef", MIToken::kw_undef)
201 .Case("internal", MIToken::kw_internal)
202 .Case("early-clobber", MIToken::kw_early_clobber)
203 .Case("debug-use", MIToken::kw_debug_use)
204 .Case("renamable", MIToken::kw_renamable)
205 .Case("tied-def", MIToken::kw_tied_def)
206 .Case("frame-setup", MIToken::kw_frame_setup)
207 .Case("frame-destroy", MIToken::kw_frame_destroy)
208 .Case("nnan", MIToken::kw_nnan)
209 .Case("ninf", MIToken::kw_ninf)
210 .Case("nsz", MIToken::kw_nsz)
211 .Case("arcp", MIToken::kw_arcp)
212 .Case("contract", MIToken::kw_contract)
213 .Case("afn", MIToken::kw_afn)
214 .Case("reassoc", MIToken::kw_reassoc)
215 .Case("nuw", MIToken::kw_nuw)
216 .Case("nsw", MIToken::kw_nsw)
217 .Case("exact", MIToken::kw_exact)
218 .Case("nofpexcept", MIToken::kw_nofpexcept)
219 .Case("debug-location", MIToken::kw_debug_location)
220 .Case("debug-instr-number", MIToken::kw_debug_instr_number)
221 .Case("same_value", MIToken::kw_cfi_same_value)
222 .Case("offset", MIToken::kw_cfi_offset)
223 .Case("rel_offset", MIToken::kw_cfi_rel_offset)
224 .Case("def_cfa_register", MIToken::kw_cfi_def_cfa_register)
225 .Case("def_cfa_offset", MIToken::kw_cfi_def_cfa_offset)
226 .Case("adjust_cfa_offset", MIToken::kw_cfi_adjust_cfa_offset)
227 .Case("escape", MIToken::kw_cfi_escape)
228 .Case("def_cfa", MIToken::kw_cfi_def_cfa)
229 .Case("remember_state", MIToken::kw_cfi_remember_state)
230 .Case("restore", MIToken::kw_cfi_restore)
231 .Case("restore_state", MIToken::kw_cfi_restore_state)
232 .Case("undefined", MIToken::kw_cfi_undefined)
233 .Case("register", MIToken::kw_cfi_register)
234 .Case("window_save", MIToken::kw_cfi_window_save)
235 .Case("negate_ra_sign_state",
236 MIToken::kw_cfi_aarch64_negate_ra_sign_state)
237 .Case("blockaddress", MIToken::kw_blockaddress)
238 .Case("intrinsic", MIToken::kw_intrinsic)
239 .Case("target-index", MIToken::kw_target_index)
240 .Case("half", MIToken::kw_half)
241 .Case("float", MIToken::kw_float)
242 .Case("double", MIToken::kw_double)
243 .Case("x86_fp80", MIToken::kw_x86_fp80)
244 .Case("fp128", MIToken::kw_fp128)
245 .Case("ppc_fp128", MIToken::kw_ppc_fp128)
246 .Case("target-flags", MIToken::kw_target_flags)
247 .Case("volatile", MIToken::kw_volatile)
248 .Case("non-temporal", MIToken::kw_non_temporal)
249 .Case("dereferenceable", MIToken::kw_dereferenceable)
250 .Case("invariant", MIToken::kw_invariant)
251 .Case("align", MIToken::kw_align)
252 .Case("basealign", MIToken::kw_align)
253 .Case("addrspace", MIToken::kw_addrspace)
254 .Case("stack", MIToken::kw_stack)
255 .Case("got", MIToken::kw_got)
256 .Case("jump-table", MIToken::kw_jump_table)
257 .Case("constant-pool", MIToken::kw_constant_pool)
258 .Case("call-entry", MIToken::kw_call_entry)
259 .Case("custom", MIToken::kw_custom)
260 .Case("liveout", MIToken::kw_liveout)
261 .Case("address-taken", MIToken::kw_address_taken)
262 .Case("landing-pad", MIToken::kw_landing_pad)
263 .Case("ehfunclet-entry", MIToken::kw_ehfunclet_entry)
264 .Case("liveins", MIToken::kw_liveins)
265 .Case("successors", MIToken::kw_successors)
266 .Case("floatpred", MIToken::kw_floatpred)
267 .Case("intpred", MIToken::kw_intpred)
268 .Case("shufflemask", MIToken::kw_shufflemask)
269 .Case("pre-instr-symbol", MIToken::kw_pre_instr_symbol)
270 .Case("post-instr-symbol", MIToken::kw_post_instr_symbol)
271 .Case("heap-alloc-marker", MIToken::kw_heap_alloc_marker)
272 .Case("bbsections", MIToken::kw_bbsections)
273 .Case("unknown-size", MIToken::kw_unknown_size)
274 .Case("unknown-address", MIToken::kw_unknown_address)
275 .Default(MIToken::Identifier);
276 }
277
maybeLexIdentifier(Cursor C,MIToken & Token)278 static Cursor maybeLexIdentifier(Cursor C, MIToken &Token) {
279 if (!isalpha(C.peek()) && C.peek() != '_')
280 return None;
281 auto Range = C;
282 while (isIdentifierChar(C.peek()))
283 C.advance();
284 auto Identifier = Range.upto(C);
285 Token.reset(getIdentifierKind(Identifier), Identifier)
286 .setStringValue(Identifier);
287 return C;
288 }
289
maybeLexMachineBasicBlock(Cursor C,MIToken & Token,ErrorCallbackType ErrorCallback)290 static Cursor maybeLexMachineBasicBlock(Cursor C, MIToken &Token,
291 ErrorCallbackType ErrorCallback) {
292 bool IsReference = C.remaining().startswith("%bb.");
293 if (!IsReference && !C.remaining().startswith("bb."))
294 return None;
295 auto Range = C;
296 unsigned PrefixLength = IsReference ? 4 : 3;
297 C.advance(PrefixLength); // Skip '%bb.' or 'bb.'
298 if (!isdigit(C.peek())) {
299 Token.reset(MIToken::Error, C.remaining());
300 ErrorCallback(C.location(), "expected a number after '%bb.'");
301 return C;
302 }
303 auto NumberRange = C;
304 while (isdigit(C.peek()))
305 C.advance();
306 StringRef Number = NumberRange.upto(C);
307 unsigned StringOffset = PrefixLength + Number.size(); // Drop '%bb.<id>'
308 // TODO: The format bb.<id>.<irname> is supported only when it's not a
309 // reference. Once we deprecate the format where the irname shows up, we
310 // should only lex forward if it is a reference.
311 if (C.peek() == '.') {
312 C.advance(); // Skip '.'
313 ++StringOffset;
314 while (isIdentifierChar(C.peek()))
315 C.advance();
316 }
317 Token.reset(IsReference ? MIToken::MachineBasicBlock
318 : MIToken::MachineBasicBlockLabel,
319 Range.upto(C))
320 .setIntegerValue(APSInt(Number))
321 .setStringValue(Range.upto(C).drop_front(StringOffset));
322 return C;
323 }
324
maybeLexIndex(Cursor C,MIToken & Token,StringRef Rule,MIToken::TokenKind Kind)325 static Cursor maybeLexIndex(Cursor C, MIToken &Token, StringRef Rule,
326 MIToken::TokenKind Kind) {
327 if (!C.remaining().startswith(Rule) || !isdigit(C.peek(Rule.size())))
328 return None;
329 auto Range = C;
330 C.advance(Rule.size());
331 auto NumberRange = C;
332 while (isdigit(C.peek()))
333 C.advance();
334 Token.reset(Kind, Range.upto(C)).setIntegerValue(APSInt(NumberRange.upto(C)));
335 return C;
336 }
337
maybeLexIndexAndName(Cursor C,MIToken & Token,StringRef Rule,MIToken::TokenKind Kind)338 static Cursor maybeLexIndexAndName(Cursor C, MIToken &Token, StringRef Rule,
339 MIToken::TokenKind Kind) {
340 if (!C.remaining().startswith(Rule) || !isdigit(C.peek(Rule.size())))
341 return None;
342 auto Range = C;
343 C.advance(Rule.size());
344 auto NumberRange = C;
345 while (isdigit(C.peek()))
346 C.advance();
347 StringRef Number = NumberRange.upto(C);
348 unsigned StringOffset = Rule.size() + Number.size();
349 if (C.peek() == '.') {
350 C.advance();
351 ++StringOffset;
352 while (isIdentifierChar(C.peek()))
353 C.advance();
354 }
355 Token.reset(Kind, Range.upto(C))
356 .setIntegerValue(APSInt(Number))
357 .setStringValue(Range.upto(C).drop_front(StringOffset));
358 return C;
359 }
360
maybeLexJumpTableIndex(Cursor C,MIToken & Token)361 static Cursor maybeLexJumpTableIndex(Cursor C, MIToken &Token) {
362 return maybeLexIndex(C, Token, "%jump-table.", MIToken::JumpTableIndex);
363 }
364
maybeLexStackObject(Cursor C,MIToken & Token)365 static Cursor maybeLexStackObject(Cursor C, MIToken &Token) {
366 return maybeLexIndexAndName(C, Token, "%stack.", MIToken::StackObject);
367 }
368
maybeLexFixedStackObject(Cursor C,MIToken & Token)369 static Cursor maybeLexFixedStackObject(Cursor C, MIToken &Token) {
370 return maybeLexIndex(C, Token, "%fixed-stack.", MIToken::FixedStackObject);
371 }
372
maybeLexConstantPoolItem(Cursor C,MIToken & Token)373 static Cursor maybeLexConstantPoolItem(Cursor C, MIToken &Token) {
374 return maybeLexIndex(C, Token, "%const.", MIToken::ConstantPoolItem);
375 }
376
maybeLexSubRegisterIndex(Cursor C,MIToken & Token,ErrorCallbackType ErrorCallback)377 static Cursor maybeLexSubRegisterIndex(Cursor C, MIToken &Token,
378 ErrorCallbackType ErrorCallback) {
379 const StringRef Rule = "%subreg.";
380 if (!C.remaining().startswith(Rule))
381 return None;
382 return lexName(C, Token, MIToken::SubRegisterIndex, Rule.size(),
383 ErrorCallback);
384 }
385
maybeLexIRBlock(Cursor C,MIToken & Token,ErrorCallbackType ErrorCallback)386 static Cursor maybeLexIRBlock(Cursor C, MIToken &Token,
387 ErrorCallbackType ErrorCallback) {
388 const StringRef Rule = "%ir-block.";
389 if (!C.remaining().startswith(Rule))
390 return None;
391 if (isdigit(C.peek(Rule.size())))
392 return maybeLexIndex(C, Token, Rule, MIToken::IRBlock);
393 return lexName(C, Token, MIToken::NamedIRBlock, Rule.size(), ErrorCallback);
394 }
395
maybeLexIRValue(Cursor C,MIToken & Token,ErrorCallbackType ErrorCallback)396 static Cursor maybeLexIRValue(Cursor C, MIToken &Token,
397 ErrorCallbackType ErrorCallback) {
398 const StringRef Rule = "%ir.";
399 if (!C.remaining().startswith(Rule))
400 return None;
401 if (isdigit(C.peek(Rule.size())))
402 return maybeLexIndex(C, Token, Rule, MIToken::IRValue);
403 return lexName(C, Token, MIToken::NamedIRValue, Rule.size(), ErrorCallback);
404 }
405
maybeLexStringConstant(Cursor C,MIToken & Token,ErrorCallbackType ErrorCallback)406 static Cursor maybeLexStringConstant(Cursor C, MIToken &Token,
407 ErrorCallbackType ErrorCallback) {
408 if (C.peek() != '"')
409 return None;
410 return lexName(C, Token, MIToken::StringConstant, /*PrefixLength=*/0,
411 ErrorCallback);
412 }
413
lexVirtualRegister(Cursor C,MIToken & Token)414 static Cursor lexVirtualRegister(Cursor C, MIToken &Token) {
415 auto Range = C;
416 C.advance(); // Skip '%'
417 auto NumberRange = C;
418 while (isdigit(C.peek()))
419 C.advance();
420 Token.reset(MIToken::VirtualRegister, Range.upto(C))
421 .setIntegerValue(APSInt(NumberRange.upto(C)));
422 return C;
423 }
424
425 /// Returns true for a character allowed in a register name.
isRegisterChar(char C)426 static bool isRegisterChar(char C) {
427 return isIdentifierChar(C) && C != '.';
428 }
429
lexNamedVirtualRegister(Cursor C,MIToken & Token)430 static Cursor lexNamedVirtualRegister(Cursor C, MIToken &Token) {
431 Cursor Range = C;
432 C.advance(); // Skip '%'
433 while (isRegisterChar(C.peek()))
434 C.advance();
435 Token.reset(MIToken::NamedVirtualRegister, Range.upto(C))
436 .setStringValue(Range.upto(C).drop_front(1)); // Drop the '%'
437 return C;
438 }
439
maybeLexRegister(Cursor C,MIToken & Token,ErrorCallbackType ErrorCallback)440 static Cursor maybeLexRegister(Cursor C, MIToken &Token,
441 ErrorCallbackType ErrorCallback) {
442 if (C.peek() != '%' && C.peek() != '$')
443 return None;
444
445 if (C.peek() == '%') {
446 if (isdigit(C.peek(1)))
447 return lexVirtualRegister(C, Token);
448
449 if (isRegisterChar(C.peek(1)))
450 return lexNamedVirtualRegister(C, Token);
451
452 return None;
453 }
454
455 assert(C.peek() == '$');
456 auto Range = C;
457 C.advance(); // Skip '$'
458 while (isRegisterChar(C.peek()))
459 C.advance();
460 Token.reset(MIToken::NamedRegister, Range.upto(C))
461 .setStringValue(Range.upto(C).drop_front(1)); // Drop the '$'
462 return C;
463 }
464
maybeLexGlobalValue(Cursor C,MIToken & Token,ErrorCallbackType ErrorCallback)465 static Cursor maybeLexGlobalValue(Cursor C, MIToken &Token,
466 ErrorCallbackType ErrorCallback) {
467 if (C.peek() != '@')
468 return None;
469 if (!isdigit(C.peek(1)))
470 return lexName(C, Token, MIToken::NamedGlobalValue, /*PrefixLength=*/1,
471 ErrorCallback);
472 auto Range = C;
473 C.advance(1); // Skip the '@'
474 auto NumberRange = C;
475 while (isdigit(C.peek()))
476 C.advance();
477 Token.reset(MIToken::GlobalValue, Range.upto(C))
478 .setIntegerValue(APSInt(NumberRange.upto(C)));
479 return C;
480 }
481
maybeLexExternalSymbol(Cursor C,MIToken & Token,ErrorCallbackType ErrorCallback)482 static Cursor maybeLexExternalSymbol(Cursor C, MIToken &Token,
483 ErrorCallbackType ErrorCallback) {
484 if (C.peek() != '&')
485 return None;
486 return lexName(C, Token, MIToken::ExternalSymbol, /*PrefixLength=*/1,
487 ErrorCallback);
488 }
489
maybeLexMCSymbol(Cursor C,MIToken & Token,ErrorCallbackType ErrorCallback)490 static Cursor maybeLexMCSymbol(Cursor C, MIToken &Token,
491 ErrorCallbackType ErrorCallback) {
492 const StringRef Rule = "<mcsymbol ";
493 if (!C.remaining().startswith(Rule))
494 return None;
495 auto Start = C;
496 C.advance(Rule.size());
497
498 // Try a simple unquoted name.
499 if (C.peek() != '"') {
500 while (isIdentifierChar(C.peek()))
501 C.advance();
502 StringRef String = Start.upto(C).drop_front(Rule.size());
503 if (C.peek() != '>') {
504 ErrorCallback(C.location(),
505 "expected the '<mcsymbol ...' to be closed by a '>'");
506 Token.reset(MIToken::Error, Start.remaining());
507 return Start;
508 }
509 C.advance();
510
511 Token.reset(MIToken::MCSymbol, Start.upto(C)).setStringValue(String);
512 return C;
513 }
514
515 // Otherwise lex out a quoted name.
516 Cursor R = lexStringConstant(C, ErrorCallback);
517 if (!R) {
518 ErrorCallback(C.location(),
519 "unable to parse quoted string from opening quote");
520 Token.reset(MIToken::Error, Start.remaining());
521 return Start;
522 }
523 StringRef String = Start.upto(R).drop_front(Rule.size());
524 if (R.peek() != '>') {
525 ErrorCallback(R.location(),
526 "expected the '<mcsymbol ...' to be closed by a '>'");
527 Token.reset(MIToken::Error, Start.remaining());
528 return Start;
529 }
530 R.advance();
531
532 Token.reset(MIToken::MCSymbol, Start.upto(R))
533 .setOwnedStringValue(unescapeQuotedString(String));
534 return R;
535 }
536
isValidHexFloatingPointPrefix(char C)537 static bool isValidHexFloatingPointPrefix(char C) {
538 return C == 'H' || C == 'K' || C == 'L' || C == 'M' || C == 'R';
539 }
540
lexFloatingPointLiteral(Cursor Range,Cursor C,MIToken & Token)541 static Cursor lexFloatingPointLiteral(Cursor Range, Cursor C, MIToken &Token) {
542 C.advance();
543 // Skip over [0-9]*([eE][-+]?[0-9]+)?
544 while (isdigit(C.peek()))
545 C.advance();
546 if ((C.peek() == 'e' || C.peek() == 'E') &&
547 (isdigit(C.peek(1)) ||
548 ((C.peek(1) == '-' || C.peek(1) == '+') && isdigit(C.peek(2))))) {
549 C.advance(2);
550 while (isdigit(C.peek()))
551 C.advance();
552 }
553 Token.reset(MIToken::FloatingPointLiteral, Range.upto(C));
554 return C;
555 }
556
maybeLexHexadecimalLiteral(Cursor C,MIToken & Token)557 static Cursor maybeLexHexadecimalLiteral(Cursor C, MIToken &Token) {
558 if (C.peek() != '0' || (C.peek(1) != 'x' && C.peek(1) != 'X'))
559 return None;
560 Cursor Range = C;
561 C.advance(2);
562 unsigned PrefLen = 2;
563 if (isValidHexFloatingPointPrefix(C.peek())) {
564 C.advance();
565 PrefLen++;
566 }
567 while (isxdigit(C.peek()))
568 C.advance();
569 StringRef StrVal = Range.upto(C);
570 if (StrVal.size() <= PrefLen)
571 return None;
572 if (PrefLen == 2)
573 Token.reset(MIToken::HexLiteral, Range.upto(C));
574 else // It must be 3, which means that there was a floating-point prefix.
575 Token.reset(MIToken::FloatingPointLiteral, Range.upto(C));
576 return C;
577 }
578
maybeLexNumericalLiteral(Cursor C,MIToken & Token)579 static Cursor maybeLexNumericalLiteral(Cursor C, MIToken &Token) {
580 if (!isdigit(C.peek()) && (C.peek() != '-' || !isdigit(C.peek(1))))
581 return None;
582 auto Range = C;
583 C.advance();
584 while (isdigit(C.peek()))
585 C.advance();
586 if (C.peek() == '.')
587 return lexFloatingPointLiteral(Range, C, Token);
588 StringRef StrVal = Range.upto(C);
589 Token.reset(MIToken::IntegerLiteral, StrVal).setIntegerValue(APSInt(StrVal));
590 return C;
591 }
592
getMetadataKeywordKind(StringRef Identifier)593 static MIToken::TokenKind getMetadataKeywordKind(StringRef Identifier) {
594 return StringSwitch<MIToken::TokenKind>(Identifier)
595 .Case("!tbaa", MIToken::md_tbaa)
596 .Case("!alias.scope", MIToken::md_alias_scope)
597 .Case("!noalias", MIToken::md_noalias)
598 .Case("!range", MIToken::md_range)
599 .Case("!DIExpression", MIToken::md_diexpr)
600 .Case("!DILocation", MIToken::md_dilocation)
601 .Default(MIToken::Error);
602 }
603
maybeLexExclaim(Cursor C,MIToken & Token,ErrorCallbackType ErrorCallback)604 static Cursor maybeLexExclaim(Cursor C, MIToken &Token,
605 ErrorCallbackType ErrorCallback) {
606 if (C.peek() != '!')
607 return None;
608 auto Range = C;
609 C.advance(1);
610 if (isdigit(C.peek()) || !isIdentifierChar(C.peek())) {
611 Token.reset(MIToken::exclaim, Range.upto(C));
612 return C;
613 }
614 while (isIdentifierChar(C.peek()))
615 C.advance();
616 StringRef StrVal = Range.upto(C);
617 Token.reset(getMetadataKeywordKind(StrVal), StrVal);
618 if (Token.isError())
619 ErrorCallback(Token.location(),
620 "use of unknown metadata keyword '" + StrVal + "'");
621 return C;
622 }
623
symbolToken(char C)624 static MIToken::TokenKind symbolToken(char C) {
625 switch (C) {
626 case ',':
627 return MIToken::comma;
628 case '.':
629 return MIToken::dot;
630 case '=':
631 return MIToken::equal;
632 case ':':
633 return MIToken::colon;
634 case '(':
635 return MIToken::lparen;
636 case ')':
637 return MIToken::rparen;
638 case '{':
639 return MIToken::lbrace;
640 case '}':
641 return MIToken::rbrace;
642 case '+':
643 return MIToken::plus;
644 case '-':
645 return MIToken::minus;
646 case '<':
647 return MIToken::less;
648 case '>':
649 return MIToken::greater;
650 default:
651 return MIToken::Error;
652 }
653 }
654
maybeLexSymbol(Cursor C,MIToken & Token)655 static Cursor maybeLexSymbol(Cursor C, MIToken &Token) {
656 MIToken::TokenKind Kind;
657 unsigned Length = 1;
658 if (C.peek() == ':' && C.peek(1) == ':') {
659 Kind = MIToken::coloncolon;
660 Length = 2;
661 } else
662 Kind = symbolToken(C.peek());
663 if (Kind == MIToken::Error)
664 return None;
665 auto Range = C;
666 C.advance(Length);
667 Token.reset(Kind, Range.upto(C));
668 return C;
669 }
670
maybeLexNewline(Cursor C,MIToken & Token)671 static Cursor maybeLexNewline(Cursor C, MIToken &Token) {
672 if (!isNewlineChar(C.peek()))
673 return None;
674 auto Range = C;
675 C.advance();
676 Token.reset(MIToken::Newline, Range.upto(C));
677 return C;
678 }
679
maybeLexEscapedIRValue(Cursor C,MIToken & Token,ErrorCallbackType ErrorCallback)680 static Cursor maybeLexEscapedIRValue(Cursor C, MIToken &Token,
681 ErrorCallbackType ErrorCallback) {
682 if (C.peek() != '`')
683 return None;
684 auto Range = C;
685 C.advance();
686 auto StrRange = C;
687 while (C.peek() != '`') {
688 if (C.isEOF() || isNewlineChar(C.peek())) {
689 ErrorCallback(
690 C.location(),
691 "end of machine instruction reached before the closing '`'");
692 Token.reset(MIToken::Error, Range.remaining());
693 return C;
694 }
695 C.advance();
696 }
697 StringRef Value = StrRange.upto(C);
698 C.advance();
699 Token.reset(MIToken::QuotedIRValue, Range.upto(C)).setStringValue(Value);
700 return C;
701 }
702
lexMIToken(StringRef Source,MIToken & Token,ErrorCallbackType ErrorCallback)703 StringRef llvm::lexMIToken(StringRef Source, MIToken &Token,
704 ErrorCallbackType ErrorCallback) {
705 auto C = skipComment(skipWhitespace(Cursor(Source)));
706 if (C.isEOF()) {
707 Token.reset(MIToken::Eof, C.remaining());
708 return C.remaining();
709 }
710
711 C = skipMachineOperandComment(C);
712
713 if (Cursor R = maybeLexMachineBasicBlock(C, Token, ErrorCallback))
714 return R.remaining();
715 if (Cursor R = maybeLexIdentifier(C, Token))
716 return R.remaining();
717 if (Cursor R = maybeLexJumpTableIndex(C, Token))
718 return R.remaining();
719 if (Cursor R = maybeLexStackObject(C, Token))
720 return R.remaining();
721 if (Cursor R = maybeLexFixedStackObject(C, Token))
722 return R.remaining();
723 if (Cursor R = maybeLexConstantPoolItem(C, Token))
724 return R.remaining();
725 if (Cursor R = maybeLexSubRegisterIndex(C, Token, ErrorCallback))
726 return R.remaining();
727 if (Cursor R = maybeLexIRBlock(C, Token, ErrorCallback))
728 return R.remaining();
729 if (Cursor R = maybeLexIRValue(C, Token, ErrorCallback))
730 return R.remaining();
731 if (Cursor R = maybeLexRegister(C, Token, ErrorCallback))
732 return R.remaining();
733 if (Cursor R = maybeLexGlobalValue(C, Token, ErrorCallback))
734 return R.remaining();
735 if (Cursor R = maybeLexExternalSymbol(C, Token, ErrorCallback))
736 return R.remaining();
737 if (Cursor R = maybeLexMCSymbol(C, Token, ErrorCallback))
738 return R.remaining();
739 if (Cursor R = maybeLexHexadecimalLiteral(C, Token))
740 return R.remaining();
741 if (Cursor R = maybeLexNumericalLiteral(C, Token))
742 return R.remaining();
743 if (Cursor R = maybeLexExclaim(C, Token, ErrorCallback))
744 return R.remaining();
745 if (Cursor R = maybeLexSymbol(C, Token))
746 return R.remaining();
747 if (Cursor R = maybeLexNewline(C, Token))
748 return R.remaining();
749 if (Cursor R = maybeLexEscapedIRValue(C, Token, ErrorCallback))
750 return R.remaining();
751 if (Cursor R = maybeLexStringConstant(C, Token, ErrorCallback))
752 return R.remaining();
753
754 Token.reset(MIToken::Error, C.remaining());
755 ErrorCallback(C.location(),
756 Twine("unexpected character '") + Twine(C.peek()) + "'");
757 return C.remaining();
758 }
759