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