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