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