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