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