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:
37   Cursor(NoneType) {}
38 
39   explicit Cursor(StringRef Str) {
40     Ptr = Str.data();
41     End = Ptr + Str.size();
42   }
43 
44   bool isEOF() const { return Ptr == End; }
45 
46   char peek(int I = 0) const { return End - Ptr <= I ? 0 : Ptr[I]; }
47 
48   void advance(unsigned I = 1) { Ptr += I; }
49 
50   StringRef remaining() const { return StringRef(Ptr, End - Ptr); }
51 
52   StringRef upto(Cursor C) const {
53     assert(C.Ptr >= Ptr && C.Ptr <= End);
54     return StringRef(Ptr, C.Ptr - Ptr);
55   }
56 
57   StringRef::iterator location() const { return Ptr; }
58 
59   operator bool() const { return Ptr != nullptr; }
60 };
61 
62 } // end anonymous namespace
63 
64 MIToken &MIToken::reset(TokenKind Kind, StringRef Range) {
65   this->Kind = Kind;
66   this->Range = Range;
67   return *this;
68 }
69 
70 MIToken &MIToken::setStringValue(StringRef StrVal) {
71   StringValue = StrVal;
72   return *this;
73 }
74 
75 MIToken &MIToken::setOwnedStringValue(std::string StrVal) {
76   StringValueStorage = std::move(StrVal);
77   StringValue = StringValueStorage;
78   return *this;
79 }
80 
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.
87 static Cursor skipWhitespace(Cursor C) {
88   while (isblank(C.peek()))
89     C.advance();
90   return C;
91 }
92 
93 static bool isNewlineChar(char C) { return C == '\n' || C == '\r'; }
94 
95 /// Skip a line comment and return the updated cursor.
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 */.
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]
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.
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: \"[^\"]*\"
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 
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 
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("addrspace", MIToken::kw_addrspace)
253       .Case("stack", MIToken::kw_stack)
254       .Case("got", MIToken::kw_got)
255       .Case("jump-table", MIToken::kw_jump_table)
256       .Case("constant-pool", MIToken::kw_constant_pool)
257       .Case("call-entry", MIToken::kw_call_entry)
258       .Case("custom", MIToken::kw_custom)
259       .Case("liveout", MIToken::kw_liveout)
260       .Case("address-taken", MIToken::kw_address_taken)
261       .Case("landing-pad", MIToken::kw_landing_pad)
262       .Case("ehfunclet-entry", MIToken::kw_ehfunclet_entry)
263       .Case("liveins", MIToken::kw_liveins)
264       .Case("successors", MIToken::kw_successors)
265       .Case("floatpred", MIToken::kw_floatpred)
266       .Case("intpred", MIToken::kw_intpred)
267       .Case("shufflemask", MIToken::kw_shufflemask)
268       .Case("pre-instr-symbol", MIToken::kw_pre_instr_symbol)
269       .Case("post-instr-symbol", MIToken::kw_post_instr_symbol)
270       .Case("heap-alloc-marker", MIToken::kw_heap_alloc_marker)
271       .Case("bbsections", MIToken::kw_bbsections)
272       .Case("unknown-size", MIToken::kw_unknown_size)
273       .Default(MIToken::Identifier);
274 }
275 
276 static Cursor maybeLexIdentifier(Cursor C, MIToken &Token) {
277   if (!isalpha(C.peek()) && C.peek() != '_')
278     return None;
279   auto Range = C;
280   while (isIdentifierChar(C.peek()))
281     C.advance();
282   auto Identifier = Range.upto(C);
283   Token.reset(getIdentifierKind(Identifier), Identifier)
284       .setStringValue(Identifier);
285   return C;
286 }
287 
288 static Cursor maybeLexMachineBasicBlock(Cursor C, MIToken &Token,
289                                         ErrorCallbackType ErrorCallback) {
290   bool IsReference = C.remaining().startswith("%bb.");
291   if (!IsReference && !C.remaining().startswith("bb."))
292     return None;
293   auto Range = C;
294   unsigned PrefixLength = IsReference ? 4 : 3;
295   C.advance(PrefixLength); // Skip '%bb.' or 'bb.'
296   if (!isdigit(C.peek())) {
297     Token.reset(MIToken::Error, C.remaining());
298     ErrorCallback(C.location(), "expected a number after '%bb.'");
299     return C;
300   }
301   auto NumberRange = C;
302   while (isdigit(C.peek()))
303     C.advance();
304   StringRef Number = NumberRange.upto(C);
305   unsigned StringOffset = PrefixLength + Number.size(); // Drop '%bb.<id>'
306   // TODO: The format bb.<id>.<irname> is supported only when it's not a
307   // reference. Once we deprecate the format where the irname shows up, we
308   // should only lex forward if it is a reference.
309   if (C.peek() == '.') {
310     C.advance(); // Skip '.'
311     ++StringOffset;
312     while (isIdentifierChar(C.peek()))
313       C.advance();
314   }
315   Token.reset(IsReference ? MIToken::MachineBasicBlock
316                           : MIToken::MachineBasicBlockLabel,
317               Range.upto(C))
318       .setIntegerValue(APSInt(Number))
319       .setStringValue(Range.upto(C).drop_front(StringOffset));
320   return C;
321 }
322 
323 static Cursor maybeLexIndex(Cursor C, MIToken &Token, StringRef Rule,
324                             MIToken::TokenKind Kind) {
325   if (!C.remaining().startswith(Rule) || !isdigit(C.peek(Rule.size())))
326     return None;
327   auto Range = C;
328   C.advance(Rule.size());
329   auto NumberRange = C;
330   while (isdigit(C.peek()))
331     C.advance();
332   Token.reset(Kind, Range.upto(C)).setIntegerValue(APSInt(NumberRange.upto(C)));
333   return C;
334 }
335 
336 static Cursor maybeLexIndexAndName(Cursor C, MIToken &Token, StringRef Rule,
337                                    MIToken::TokenKind Kind) {
338   if (!C.remaining().startswith(Rule) || !isdigit(C.peek(Rule.size())))
339     return None;
340   auto Range = C;
341   C.advance(Rule.size());
342   auto NumberRange = C;
343   while (isdigit(C.peek()))
344     C.advance();
345   StringRef Number = NumberRange.upto(C);
346   unsigned StringOffset = Rule.size() + Number.size();
347   if (C.peek() == '.') {
348     C.advance();
349     ++StringOffset;
350     while (isIdentifierChar(C.peek()))
351       C.advance();
352   }
353   Token.reset(Kind, Range.upto(C))
354       .setIntegerValue(APSInt(Number))
355       .setStringValue(Range.upto(C).drop_front(StringOffset));
356   return C;
357 }
358 
359 static Cursor maybeLexJumpTableIndex(Cursor C, MIToken &Token) {
360   return maybeLexIndex(C, Token, "%jump-table.", MIToken::JumpTableIndex);
361 }
362 
363 static Cursor maybeLexStackObject(Cursor C, MIToken &Token) {
364   return maybeLexIndexAndName(C, Token, "%stack.", MIToken::StackObject);
365 }
366 
367 static Cursor maybeLexFixedStackObject(Cursor C, MIToken &Token) {
368   return maybeLexIndex(C, Token, "%fixed-stack.", MIToken::FixedStackObject);
369 }
370 
371 static Cursor maybeLexConstantPoolItem(Cursor C, MIToken &Token) {
372   return maybeLexIndex(C, Token, "%const.", MIToken::ConstantPoolItem);
373 }
374 
375 static Cursor maybeLexSubRegisterIndex(Cursor C, MIToken &Token,
376                                        ErrorCallbackType ErrorCallback) {
377   const StringRef Rule = "%subreg.";
378   if (!C.remaining().startswith(Rule))
379     return None;
380   return lexName(C, Token, MIToken::SubRegisterIndex, Rule.size(),
381                  ErrorCallback);
382 }
383 
384 static Cursor maybeLexIRBlock(Cursor C, MIToken &Token,
385                               ErrorCallbackType ErrorCallback) {
386   const StringRef Rule = "%ir-block.";
387   if (!C.remaining().startswith(Rule))
388     return None;
389   if (isdigit(C.peek(Rule.size())))
390     return maybeLexIndex(C, Token, Rule, MIToken::IRBlock);
391   return lexName(C, Token, MIToken::NamedIRBlock, Rule.size(), ErrorCallback);
392 }
393 
394 static Cursor maybeLexIRValue(Cursor C, MIToken &Token,
395                               ErrorCallbackType ErrorCallback) {
396   const StringRef Rule = "%ir.";
397   if (!C.remaining().startswith(Rule))
398     return None;
399   if (isdigit(C.peek(Rule.size())))
400     return maybeLexIndex(C, Token, Rule, MIToken::IRValue);
401   return lexName(C, Token, MIToken::NamedIRValue, Rule.size(), ErrorCallback);
402 }
403 
404 static Cursor maybeLexStringConstant(Cursor C, MIToken &Token,
405                                      ErrorCallbackType ErrorCallback) {
406   if (C.peek() != '"')
407     return None;
408   return lexName(C, Token, MIToken::StringConstant, /*PrefixLength=*/0,
409                  ErrorCallback);
410 }
411 
412 static Cursor lexVirtualRegister(Cursor C, MIToken &Token) {
413   auto Range = C;
414   C.advance(); // Skip '%'
415   auto NumberRange = C;
416   while (isdigit(C.peek()))
417     C.advance();
418   Token.reset(MIToken::VirtualRegister, Range.upto(C))
419       .setIntegerValue(APSInt(NumberRange.upto(C)));
420   return C;
421 }
422 
423 /// Returns true for a character allowed in a register name.
424 static bool isRegisterChar(char C) {
425   return isIdentifierChar(C) && C != '.';
426 }
427 
428 static Cursor lexNamedVirtualRegister(Cursor C, MIToken &Token) {
429   Cursor Range = C;
430   C.advance(); // Skip '%'
431   while (isRegisterChar(C.peek()))
432     C.advance();
433   Token.reset(MIToken::NamedVirtualRegister, Range.upto(C))
434       .setStringValue(Range.upto(C).drop_front(1)); // Drop the '%'
435   return C;
436 }
437 
438 static Cursor maybeLexRegister(Cursor C, MIToken &Token,
439                                ErrorCallbackType ErrorCallback) {
440   if (C.peek() != '%' && C.peek() != '$')
441     return None;
442 
443   if (C.peek() == '%') {
444     if (isdigit(C.peek(1)))
445       return lexVirtualRegister(C, Token);
446 
447     if (isRegisterChar(C.peek(1)))
448       return lexNamedVirtualRegister(C, Token);
449 
450     return None;
451   }
452 
453   assert(C.peek() == '$');
454   auto Range = C;
455   C.advance(); // Skip '$'
456   while (isRegisterChar(C.peek()))
457     C.advance();
458   Token.reset(MIToken::NamedRegister, Range.upto(C))
459       .setStringValue(Range.upto(C).drop_front(1)); // Drop the '$'
460   return C;
461 }
462 
463 static Cursor maybeLexGlobalValue(Cursor C, MIToken &Token,
464                                   ErrorCallbackType ErrorCallback) {
465   if (C.peek() != '@')
466     return None;
467   if (!isdigit(C.peek(1)))
468     return lexName(C, Token, MIToken::NamedGlobalValue, /*PrefixLength=*/1,
469                    ErrorCallback);
470   auto Range = C;
471   C.advance(1); // Skip the '@'
472   auto NumberRange = C;
473   while (isdigit(C.peek()))
474     C.advance();
475   Token.reset(MIToken::GlobalValue, Range.upto(C))
476       .setIntegerValue(APSInt(NumberRange.upto(C)));
477   return C;
478 }
479 
480 static Cursor maybeLexExternalSymbol(Cursor C, MIToken &Token,
481                                      ErrorCallbackType ErrorCallback) {
482   if (C.peek() != '&')
483     return None;
484   return lexName(C, Token, MIToken::ExternalSymbol, /*PrefixLength=*/1,
485                  ErrorCallback);
486 }
487 
488 static Cursor maybeLexMCSymbol(Cursor C, MIToken &Token,
489                                ErrorCallbackType ErrorCallback) {
490   const StringRef Rule = "<mcsymbol ";
491   if (!C.remaining().startswith(Rule))
492     return None;
493   auto Start = C;
494   C.advance(Rule.size());
495 
496   // Try a simple unquoted name.
497   if (C.peek() != '"') {
498     while (isIdentifierChar(C.peek()))
499       C.advance();
500     StringRef String = Start.upto(C).drop_front(Rule.size());
501     if (C.peek() != '>') {
502       ErrorCallback(C.location(),
503                     "expected the '<mcsymbol ...' to be closed by a '>'");
504       Token.reset(MIToken::Error, Start.remaining());
505       return Start;
506     }
507     C.advance();
508 
509     Token.reset(MIToken::MCSymbol, Start.upto(C)).setStringValue(String);
510     return C;
511   }
512 
513   // Otherwise lex out a quoted name.
514   Cursor R = lexStringConstant(C, ErrorCallback);
515   if (!R) {
516     ErrorCallback(C.location(),
517                   "unable to parse quoted string from opening quote");
518     Token.reset(MIToken::Error, Start.remaining());
519     return Start;
520   }
521   StringRef String = Start.upto(R).drop_front(Rule.size());
522   if (R.peek() != '>') {
523     ErrorCallback(R.location(),
524                   "expected the '<mcsymbol ...' to be closed by a '>'");
525     Token.reset(MIToken::Error, Start.remaining());
526     return Start;
527   }
528   R.advance();
529 
530   Token.reset(MIToken::MCSymbol, Start.upto(R))
531       .setOwnedStringValue(unescapeQuotedString(String));
532   return R;
533 }
534 
535 static bool isValidHexFloatingPointPrefix(char C) {
536   return C == 'H' || C == 'K' || C == 'L' || C == 'M' || C == 'R';
537 }
538 
539 static Cursor lexFloatingPointLiteral(Cursor Range, Cursor C, MIToken &Token) {
540   C.advance();
541   // Skip over [0-9]*([eE][-+]?[0-9]+)?
542   while (isdigit(C.peek()))
543     C.advance();
544   if ((C.peek() == 'e' || C.peek() == 'E') &&
545       (isdigit(C.peek(1)) ||
546        ((C.peek(1) == '-' || C.peek(1) == '+') && isdigit(C.peek(2))))) {
547     C.advance(2);
548     while (isdigit(C.peek()))
549       C.advance();
550   }
551   Token.reset(MIToken::FloatingPointLiteral, Range.upto(C));
552   return C;
553 }
554 
555 static Cursor maybeLexHexadecimalLiteral(Cursor C, MIToken &Token) {
556   if (C.peek() != '0' || (C.peek(1) != 'x' && C.peek(1) != 'X'))
557     return None;
558   Cursor Range = C;
559   C.advance(2);
560   unsigned PrefLen = 2;
561   if (isValidHexFloatingPointPrefix(C.peek())) {
562     C.advance();
563     PrefLen++;
564   }
565   while (isxdigit(C.peek()))
566     C.advance();
567   StringRef StrVal = Range.upto(C);
568   if (StrVal.size() <= PrefLen)
569     return None;
570   if (PrefLen == 2)
571     Token.reset(MIToken::HexLiteral, Range.upto(C));
572   else // It must be 3, which means that there was a floating-point prefix.
573     Token.reset(MIToken::FloatingPointLiteral, Range.upto(C));
574   return C;
575 }
576 
577 static Cursor maybeLexNumericalLiteral(Cursor C, MIToken &Token) {
578   if (!isdigit(C.peek()) && (C.peek() != '-' || !isdigit(C.peek(1))))
579     return None;
580   auto Range = C;
581   C.advance();
582   while (isdigit(C.peek()))
583     C.advance();
584   if (C.peek() == '.')
585     return lexFloatingPointLiteral(Range, C, Token);
586   StringRef StrVal = Range.upto(C);
587   Token.reset(MIToken::IntegerLiteral, StrVal).setIntegerValue(APSInt(StrVal));
588   return C;
589 }
590 
591 static MIToken::TokenKind getMetadataKeywordKind(StringRef Identifier) {
592   return StringSwitch<MIToken::TokenKind>(Identifier)
593       .Case("!tbaa", MIToken::md_tbaa)
594       .Case("!alias.scope", MIToken::md_alias_scope)
595       .Case("!noalias", MIToken::md_noalias)
596       .Case("!range", MIToken::md_range)
597       .Case("!DIExpression", MIToken::md_diexpr)
598       .Case("!DILocation", MIToken::md_dilocation)
599       .Default(MIToken::Error);
600 }
601 
602 static Cursor maybeLexExclaim(Cursor C, MIToken &Token,
603                               ErrorCallbackType ErrorCallback) {
604   if (C.peek() != '!')
605     return None;
606   auto Range = C;
607   C.advance(1);
608   if (isdigit(C.peek()) || !isIdentifierChar(C.peek())) {
609     Token.reset(MIToken::exclaim, Range.upto(C));
610     return C;
611   }
612   while (isIdentifierChar(C.peek()))
613     C.advance();
614   StringRef StrVal = Range.upto(C);
615   Token.reset(getMetadataKeywordKind(StrVal), StrVal);
616   if (Token.isError())
617     ErrorCallback(Token.location(),
618                   "use of unknown metadata keyword '" + StrVal + "'");
619   return C;
620 }
621 
622 static MIToken::TokenKind symbolToken(char C) {
623   switch (C) {
624   case ',':
625     return MIToken::comma;
626   case '.':
627     return MIToken::dot;
628   case '=':
629     return MIToken::equal;
630   case ':':
631     return MIToken::colon;
632   case '(':
633     return MIToken::lparen;
634   case ')':
635     return MIToken::rparen;
636   case '{':
637     return MIToken::lbrace;
638   case '}':
639     return MIToken::rbrace;
640   case '+':
641     return MIToken::plus;
642   case '-':
643     return MIToken::minus;
644   case '<':
645     return MIToken::less;
646   case '>':
647     return MIToken::greater;
648   default:
649     return MIToken::Error;
650   }
651 }
652 
653 static Cursor maybeLexSymbol(Cursor C, MIToken &Token) {
654   MIToken::TokenKind Kind;
655   unsigned Length = 1;
656   if (C.peek() == ':' && C.peek(1) == ':') {
657     Kind = MIToken::coloncolon;
658     Length = 2;
659   } else
660     Kind = symbolToken(C.peek());
661   if (Kind == MIToken::Error)
662     return None;
663   auto Range = C;
664   C.advance(Length);
665   Token.reset(Kind, Range.upto(C));
666   return C;
667 }
668 
669 static Cursor maybeLexNewline(Cursor C, MIToken &Token) {
670   if (!isNewlineChar(C.peek()))
671     return None;
672   auto Range = C;
673   C.advance();
674   Token.reset(MIToken::Newline, Range.upto(C));
675   return C;
676 }
677 
678 static Cursor maybeLexEscapedIRValue(Cursor C, MIToken &Token,
679                                      ErrorCallbackType ErrorCallback) {
680   if (C.peek() != '`')
681     return None;
682   auto Range = C;
683   C.advance();
684   auto StrRange = C;
685   while (C.peek() != '`') {
686     if (C.isEOF() || isNewlineChar(C.peek())) {
687       ErrorCallback(
688           C.location(),
689           "end of machine instruction reached before the closing '`'");
690       Token.reset(MIToken::Error, Range.remaining());
691       return C;
692     }
693     C.advance();
694   }
695   StringRef Value = StrRange.upto(C);
696   C.advance();
697   Token.reset(MIToken::QuotedIRValue, Range.upto(C)).setStringValue(Value);
698   return C;
699 }
700 
701 StringRef llvm::lexMIToken(StringRef Source, MIToken &Token,
702                            ErrorCallbackType ErrorCallback) {
703   auto C = skipComment(skipWhitespace(Cursor(Source)));
704   if (C.isEOF()) {
705     Token.reset(MIToken::Eof, C.remaining());
706     return C.remaining();
707   }
708 
709   C = skipMachineOperandComment(C);
710 
711   if (Cursor R = maybeLexMachineBasicBlock(C, Token, ErrorCallback))
712     return R.remaining();
713   if (Cursor R = maybeLexIdentifier(C, Token))
714     return R.remaining();
715   if (Cursor R = maybeLexJumpTableIndex(C, Token))
716     return R.remaining();
717   if (Cursor R = maybeLexStackObject(C, Token))
718     return R.remaining();
719   if (Cursor R = maybeLexFixedStackObject(C, Token))
720     return R.remaining();
721   if (Cursor R = maybeLexConstantPoolItem(C, Token))
722     return R.remaining();
723   if (Cursor R = maybeLexSubRegisterIndex(C, Token, ErrorCallback))
724     return R.remaining();
725   if (Cursor R = maybeLexIRBlock(C, Token, ErrorCallback))
726     return R.remaining();
727   if (Cursor R = maybeLexIRValue(C, Token, ErrorCallback))
728     return R.remaining();
729   if (Cursor R = maybeLexRegister(C, Token, ErrorCallback))
730     return R.remaining();
731   if (Cursor R = maybeLexGlobalValue(C, Token, ErrorCallback))
732     return R.remaining();
733   if (Cursor R = maybeLexExternalSymbol(C, Token, ErrorCallback))
734     return R.remaining();
735   if (Cursor R = maybeLexMCSymbol(C, Token, ErrorCallback))
736     return R.remaining();
737   if (Cursor R = maybeLexHexadecimalLiteral(C, Token))
738     return R.remaining();
739   if (Cursor R = maybeLexNumericalLiteral(C, Token))
740     return R.remaining();
741   if (Cursor R = maybeLexExclaim(C, Token, ErrorCallback))
742     return R.remaining();
743   if (Cursor R = maybeLexSymbol(C, Token))
744     return R.remaining();
745   if (Cursor R = maybeLexNewline(C, Token))
746     return R.remaining();
747   if (Cursor R = maybeLexEscapedIRValue(C, Token, ErrorCallback))
748     return R.remaining();
749   if (Cursor R = maybeLexStringConstant(C, Token, ErrorCallback))
750     return R.remaining();
751 
752   Token.reset(MIToken::Error, C.remaining());
753   ErrorCallback(C.location(),
754                 Twine("unexpected character '") + Twine(C.peek()) + "'");
755   return C.remaining();
756 }
757