1 //===- LLLexer.cpp - Lexer for .ll Files ----------------------------------===//
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 // Implement the Lexer for .ll files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/AsmParser/LLLexer.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Instruction.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/SourceMgr.h"
22 #include <cassert>
23 #include <cctype>
24 #include <cstdio>
25 
26 using namespace llvm;
27 
Error(LocTy ErrorLoc,const Twine & Msg) const28 bool LLLexer::Error(LocTy ErrorLoc, const Twine &Msg) const {
29   ErrorInfo = SM.GetMessage(ErrorLoc, SourceMgr::DK_Error, Msg);
30   return true;
31 }
32 
Warning(LocTy WarningLoc,const Twine & Msg) const33 void LLLexer::Warning(LocTy WarningLoc, const Twine &Msg) const {
34   SM.PrintMessage(WarningLoc, SourceMgr::DK_Warning, Msg);
35 }
36 
37 //===----------------------------------------------------------------------===//
38 // Helper functions.
39 //===----------------------------------------------------------------------===//
40 
41 // atoull - Convert an ascii string of decimal digits into the unsigned long
42 // long representation... this does not have to do input error checking,
43 // because we know that the input will be matched by a suitable regex...
44 //
atoull(const char * Buffer,const char * End)45 uint64_t LLLexer::atoull(const char *Buffer, const char *End) {
46   uint64_t Result = 0;
47   for (; Buffer != End; Buffer++) {
48     uint64_t OldRes = Result;
49     Result *= 10;
50     Result += *Buffer-'0';
51     if (Result < OldRes) {  // Uh, oh, overflow detected!!!
52       Error("constant bigger than 64 bits detected!");
53       return 0;
54     }
55   }
56   return Result;
57 }
58 
HexIntToVal(const char * Buffer,const char * End)59 uint64_t LLLexer::HexIntToVal(const char *Buffer, const char *End) {
60   uint64_t Result = 0;
61   for (; Buffer != End; ++Buffer) {
62     uint64_t OldRes = Result;
63     Result *= 16;
64     Result += hexDigitValue(*Buffer);
65 
66     if (Result < OldRes) {   // Uh, oh, overflow detected!!!
67       Error("constant bigger than 64 bits detected!");
68       return 0;
69     }
70   }
71   return Result;
72 }
73 
HexToIntPair(const char * Buffer,const char * End,uint64_t Pair[2])74 void LLLexer::HexToIntPair(const char *Buffer, const char *End,
75                            uint64_t Pair[2]) {
76   Pair[0] = 0;
77   if (End - Buffer >= 16) {
78     for (int i = 0; i < 16; i++, Buffer++) {
79       assert(Buffer != End);
80       Pair[0] *= 16;
81       Pair[0] += hexDigitValue(*Buffer);
82     }
83   }
84   Pair[1] = 0;
85   for (int i = 0; i < 16 && Buffer != End; i++, Buffer++) {
86     Pair[1] *= 16;
87     Pair[1] += hexDigitValue(*Buffer);
88   }
89   if (Buffer != End)
90     Error("constant bigger than 128 bits detected!");
91 }
92 
93 /// FP80HexToIntPair - translate an 80 bit FP80 number (20 hexits) into
94 /// { low64, high16 } as usual for an APInt.
FP80HexToIntPair(const char * Buffer,const char * End,uint64_t Pair[2])95 void LLLexer::FP80HexToIntPair(const char *Buffer, const char *End,
96                            uint64_t Pair[2]) {
97   Pair[1] = 0;
98   for (int i=0; i<4 && Buffer != End; i++, Buffer++) {
99     assert(Buffer != End);
100     Pair[1] *= 16;
101     Pair[1] += hexDigitValue(*Buffer);
102   }
103   Pair[0] = 0;
104   for (int i = 0; i < 16 && Buffer != End; i++, Buffer++) {
105     Pair[0] *= 16;
106     Pair[0] += hexDigitValue(*Buffer);
107   }
108   if (Buffer != End)
109     Error("constant bigger than 128 bits detected!");
110 }
111 
112 // UnEscapeLexed - Run through the specified buffer and change \xx codes to the
113 // appropriate character.
UnEscapeLexed(std::string & Str)114 static void UnEscapeLexed(std::string &Str) {
115   if (Str.empty()) return;
116 
117   char *Buffer = &Str[0], *EndBuffer = Buffer+Str.size();
118   char *BOut = Buffer;
119   for (char *BIn = Buffer; BIn != EndBuffer; ) {
120     if (BIn[0] == '\\') {
121       if (BIn < EndBuffer-1 && BIn[1] == '\\') {
122         *BOut++ = '\\'; // Two \ becomes one
123         BIn += 2;
124       } else if (BIn < EndBuffer-2 &&
125                  isxdigit(static_cast<unsigned char>(BIn[1])) &&
126                  isxdigit(static_cast<unsigned char>(BIn[2]))) {
127         *BOut = hexDigitValue(BIn[1]) * 16 + hexDigitValue(BIn[2]);
128         BIn += 3;                           // Skip over handled chars
129         ++BOut;
130       } else {
131         *BOut++ = *BIn++;
132       }
133     } else {
134       *BOut++ = *BIn++;
135     }
136   }
137   Str.resize(BOut-Buffer);
138 }
139 
140 /// isLabelChar - Return true for [-a-zA-Z$._0-9].
isLabelChar(char C)141 static bool isLabelChar(char C) {
142   return isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
143          C == '.' || C == '_';
144 }
145 
146 /// isLabelTail - Return true if this pointer points to a valid end of a label.
isLabelTail(const char * CurPtr)147 static const char *isLabelTail(const char *CurPtr) {
148   while (true) {
149     if (CurPtr[0] == ':') return CurPtr+1;
150     if (!isLabelChar(CurPtr[0])) return nullptr;
151     ++CurPtr;
152   }
153 }
154 
155 //===----------------------------------------------------------------------===//
156 // Lexer definition.
157 //===----------------------------------------------------------------------===//
158 
LLLexer(StringRef StartBuf,SourceMgr & SM,SMDiagnostic & Err,LLVMContext & C)159 LLLexer::LLLexer(StringRef StartBuf, SourceMgr &SM, SMDiagnostic &Err,
160                  LLVMContext &C)
161     : CurBuf(StartBuf), ErrorInfo(Err), SM(SM), Context(C) {
162   CurPtr = CurBuf.begin();
163 }
164 
getNextChar()165 int LLLexer::getNextChar() {
166   char CurChar = *CurPtr++;
167   switch (CurChar) {
168   default: return (unsigned char)CurChar;
169   case 0:
170     // A nul character in the stream is either the end of the current buffer or
171     // a random nul in the file.  Disambiguate that here.
172     if (CurPtr-1 != CurBuf.end())
173       return 0;  // Just whitespace.
174 
175     // Otherwise, return end of file.
176     --CurPtr;  // Another call to lex will return EOF again.
177     return EOF;
178   }
179 }
180 
LexToken()181 lltok::Kind LLLexer::LexToken() {
182   while (true) {
183     TokStart = CurPtr;
184 
185     int CurChar = getNextChar();
186     switch (CurChar) {
187     default:
188       // Handle letters: [a-zA-Z_]
189       if (isalpha(static_cast<unsigned char>(CurChar)) || CurChar == '_')
190         return LexIdentifier();
191 
192       return lltok::Error;
193     case EOF: return lltok::Eof;
194     case 0:
195     case ' ':
196     case '\t':
197     case '\n':
198     case '\r':
199       // Ignore whitespace.
200       continue;
201     case '+': return LexPositive();
202     case '@': return LexAt();
203     case '$': return LexDollar();
204     case '%': return LexPercent();
205     case '"': return LexQuote();
206     case '.':
207       if (const char *Ptr = isLabelTail(CurPtr)) {
208         CurPtr = Ptr;
209         StrVal.assign(TokStart, CurPtr-1);
210         return lltok::LabelStr;
211       }
212       if (CurPtr[0] == '.' && CurPtr[1] == '.') {
213         CurPtr += 2;
214         return lltok::dotdotdot;
215       }
216       return lltok::Error;
217     case ';':
218       SkipLineComment();
219       continue;
220     case '!': return LexExclaim();
221     case '^':
222       return LexCaret();
223     case ':':
224       return lltok::colon;
225     case '#': return LexHash();
226     case '0': case '1': case '2': case '3': case '4':
227     case '5': case '6': case '7': case '8': case '9':
228     case '-':
229       return LexDigitOrNegative();
230     case '=': return lltok::equal;
231     case '[': return lltok::lsquare;
232     case ']': return lltok::rsquare;
233     case '{': return lltok::lbrace;
234     case '}': return lltok::rbrace;
235     case '<': return lltok::less;
236     case '>': return lltok::greater;
237     case '(': return lltok::lparen;
238     case ')': return lltok::rparen;
239     case ',': return lltok::comma;
240     case '*': return lltok::star;
241     case '|': return lltok::bar;
242     }
243   }
244 }
245 
SkipLineComment()246 void LLLexer::SkipLineComment() {
247   while (true) {
248     if (CurPtr[0] == '\n' || CurPtr[0] == '\r' || getNextChar() == EOF)
249       return;
250   }
251 }
252 
253 /// Lex all tokens that start with an @ character.
254 ///   GlobalVar   @\"[^\"]*\"
255 ///   GlobalVar   @[-a-zA-Z$._][-a-zA-Z$._0-9]*
256 ///   GlobalVarID @[0-9]+
LexAt()257 lltok::Kind LLLexer::LexAt() {
258   return LexVar(lltok::GlobalVar, lltok::GlobalID);
259 }
260 
LexDollar()261 lltok::Kind LLLexer::LexDollar() {
262   if (const char *Ptr = isLabelTail(TokStart)) {
263     CurPtr = Ptr;
264     StrVal.assign(TokStart, CurPtr - 1);
265     return lltok::LabelStr;
266   }
267 
268   // Handle DollarStringConstant: $\"[^\"]*\"
269   if (CurPtr[0] == '"') {
270     ++CurPtr;
271 
272     while (true) {
273       int CurChar = getNextChar();
274 
275       if (CurChar == EOF) {
276         Error("end of file in COMDAT variable name");
277         return lltok::Error;
278       }
279       if (CurChar == '"') {
280         StrVal.assign(TokStart + 2, CurPtr - 1);
281         UnEscapeLexed(StrVal);
282         if (StringRef(StrVal).contains(0)) {
283           Error("Null bytes are not allowed in names");
284           return lltok::Error;
285         }
286         return lltok::ComdatVar;
287       }
288     }
289   }
290 
291   // Handle ComdatVarName: $[-a-zA-Z$._][-a-zA-Z$._0-9]*
292   if (ReadVarName())
293     return lltok::ComdatVar;
294 
295   return lltok::Error;
296 }
297 
298 /// ReadString - Read a string until the closing quote.
ReadString(lltok::Kind kind)299 lltok::Kind LLLexer::ReadString(lltok::Kind kind) {
300   const char *Start = CurPtr;
301   while (true) {
302     int CurChar = getNextChar();
303 
304     if (CurChar == EOF) {
305       Error("end of file in string constant");
306       return lltok::Error;
307     }
308     if (CurChar == '"') {
309       StrVal.assign(Start, CurPtr-1);
310       UnEscapeLexed(StrVal);
311       return kind;
312     }
313   }
314 }
315 
316 /// ReadVarName - Read the rest of a token containing a variable name.
ReadVarName()317 bool LLLexer::ReadVarName() {
318   const char *NameStart = CurPtr;
319   if (isalpha(static_cast<unsigned char>(CurPtr[0])) ||
320       CurPtr[0] == '-' || CurPtr[0] == '$' ||
321       CurPtr[0] == '.' || CurPtr[0] == '_') {
322     ++CurPtr;
323     while (isalnum(static_cast<unsigned char>(CurPtr[0])) ||
324            CurPtr[0] == '-' || CurPtr[0] == '$' ||
325            CurPtr[0] == '.' || CurPtr[0] == '_')
326       ++CurPtr;
327 
328     StrVal.assign(NameStart, CurPtr);
329     return true;
330   }
331   return false;
332 }
333 
334 // Lex an ID: [0-9]+. On success, the ID is stored in UIntVal and Token is
335 // returned, otherwise the Error token is returned.
LexUIntID(lltok::Kind Token)336 lltok::Kind LLLexer::LexUIntID(lltok::Kind Token) {
337   if (!isdigit(static_cast<unsigned char>(CurPtr[0])))
338     return lltok::Error;
339 
340   for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
341     /*empty*/;
342 
343   uint64_t Val = atoull(TokStart + 1, CurPtr);
344   if ((unsigned)Val != Val)
345     Error("invalid value number (too large)!");
346   UIntVal = unsigned(Val);
347   return Token;
348 }
349 
LexVar(lltok::Kind Var,lltok::Kind VarID)350 lltok::Kind LLLexer::LexVar(lltok::Kind Var, lltok::Kind VarID) {
351   // Handle StringConstant: \"[^\"]*\"
352   if (CurPtr[0] == '"') {
353     ++CurPtr;
354 
355     while (true) {
356       int CurChar = getNextChar();
357 
358       if (CurChar == EOF) {
359         Error("end of file in global variable name");
360         return lltok::Error;
361       }
362       if (CurChar == '"') {
363         StrVal.assign(TokStart+2, CurPtr-1);
364         UnEscapeLexed(StrVal);
365         if (StringRef(StrVal).contains(0)) {
366           Error("Null bytes are not allowed in names");
367           return lltok::Error;
368         }
369         return Var;
370       }
371     }
372   }
373 
374   // Handle VarName: [-a-zA-Z$._][-a-zA-Z$._0-9]*
375   if (ReadVarName())
376     return Var;
377 
378   // Handle VarID: [0-9]+
379   return LexUIntID(VarID);
380 }
381 
382 /// Lex all tokens that start with a % character.
383 ///   LocalVar   ::= %\"[^\"]*\"
384 ///   LocalVar   ::= %[-a-zA-Z$._][-a-zA-Z$._0-9]*
385 ///   LocalVarID ::= %[0-9]+
LexPercent()386 lltok::Kind LLLexer::LexPercent() {
387   return LexVar(lltok::LocalVar, lltok::LocalVarID);
388 }
389 
390 /// Lex all tokens that start with a " character.
391 ///   QuoteLabel        "[^"]+":
392 ///   StringConstant    "[^"]*"
LexQuote()393 lltok::Kind LLLexer::LexQuote() {
394   lltok::Kind kind = ReadString(lltok::StringConstant);
395   if (kind == lltok::Error || kind == lltok::Eof)
396     return kind;
397 
398   if (CurPtr[0] == ':') {
399     ++CurPtr;
400     if (StringRef(StrVal).contains(0)) {
401       Error("Null bytes are not allowed in names");
402       kind = lltok::Error;
403     } else {
404       kind = lltok::LabelStr;
405     }
406   }
407 
408   return kind;
409 }
410 
411 /// Lex all tokens that start with a ! character.
412 ///    !foo
413 ///    !
LexExclaim()414 lltok::Kind LLLexer::LexExclaim() {
415   // Lex a metadata name as a MetadataVar.
416   if (isalpha(static_cast<unsigned char>(CurPtr[0])) ||
417       CurPtr[0] == '-' || CurPtr[0] == '$' ||
418       CurPtr[0] == '.' || CurPtr[0] == '_' || CurPtr[0] == '\\') {
419     ++CurPtr;
420     while (isalnum(static_cast<unsigned char>(CurPtr[0])) ||
421            CurPtr[0] == '-' || CurPtr[0] == '$' ||
422            CurPtr[0] == '.' || CurPtr[0] == '_' || CurPtr[0] == '\\')
423       ++CurPtr;
424 
425     StrVal.assign(TokStart+1, CurPtr);   // Skip !
426     UnEscapeLexed(StrVal);
427     return lltok::MetadataVar;
428   }
429   return lltok::exclaim;
430 }
431 
432 /// Lex all tokens that start with a ^ character.
433 ///    SummaryID ::= ^[0-9]+
LexCaret()434 lltok::Kind LLLexer::LexCaret() {
435   // Handle SummaryID: ^[0-9]+
436   return LexUIntID(lltok::SummaryID);
437 }
438 
439 /// Lex all tokens that start with a # character.
440 ///    AttrGrpID ::= #[0-9]+
LexHash()441 lltok::Kind LLLexer::LexHash() {
442   // Handle AttrGrpID: #[0-9]+
443   return LexUIntID(lltok::AttrGrpID);
444 }
445 
446 /// Lex a label, integer type, keyword, or hexadecimal integer constant.
447 ///    Label           [-a-zA-Z$._0-9]+:
448 ///    IntegerType     i[0-9]+
449 ///    Keyword         sdiv, float, ...
450 ///    HexIntConstant  [us]0x[0-9A-Fa-f]+
LexIdentifier()451 lltok::Kind LLLexer::LexIdentifier() {
452   const char *StartChar = CurPtr;
453   const char *IntEnd = CurPtr[-1] == 'i' ? nullptr : StartChar;
454   const char *KeywordEnd = nullptr;
455 
456   for (; isLabelChar(*CurPtr); ++CurPtr) {
457     // If we decide this is an integer, remember the end of the sequence.
458     if (!IntEnd && !isdigit(static_cast<unsigned char>(*CurPtr)))
459       IntEnd = CurPtr;
460     if (!KeywordEnd && !isalnum(static_cast<unsigned char>(*CurPtr)) &&
461         *CurPtr != '_')
462       KeywordEnd = CurPtr;
463   }
464 
465   // If we stopped due to a colon, unless we were directed to ignore it,
466   // this really is a label.
467   if (!IgnoreColonInIdentifiers && *CurPtr == ':') {
468     StrVal.assign(StartChar-1, CurPtr++);
469     return lltok::LabelStr;
470   }
471 
472   // Otherwise, this wasn't a label.  If this was valid as an integer type,
473   // return it.
474   if (!IntEnd) IntEnd = CurPtr;
475   if (IntEnd != StartChar) {
476     CurPtr = IntEnd;
477     uint64_t NumBits = atoull(StartChar, CurPtr);
478     if (NumBits < IntegerType::MIN_INT_BITS ||
479         NumBits > IntegerType::MAX_INT_BITS) {
480       Error("bitwidth for integer type out of range!");
481       return lltok::Error;
482     }
483     TyVal = IntegerType::get(Context, NumBits);
484     return lltok::Type;
485   }
486 
487   // Otherwise, this was a letter sequence.  See which keyword this is.
488   if (!KeywordEnd) KeywordEnd = CurPtr;
489   CurPtr = KeywordEnd;
490   --StartChar;
491   StringRef Keyword(StartChar, CurPtr - StartChar);
492 
493 #define KEYWORD(STR)                                                           \
494   do {                                                                         \
495     if (Keyword == #STR)                                                       \
496       return lltok::kw_##STR;                                                  \
497   } while (false)
498 
499   KEYWORD(true);    KEYWORD(false);
500   KEYWORD(declare); KEYWORD(define);
501   KEYWORD(global);  KEYWORD(constant);
502 
503   KEYWORD(dso_local);
504   KEYWORD(dso_preemptable);
505 
506   KEYWORD(private);
507   KEYWORD(internal);
508   KEYWORD(available_externally);
509   KEYWORD(linkonce);
510   KEYWORD(linkonce_odr);
511   KEYWORD(weak); // Use as a linkage, and a modifier for "cmpxchg".
512   KEYWORD(weak_odr);
513   KEYWORD(appending);
514   KEYWORD(dllimport);
515   KEYWORD(dllexport);
516   KEYWORD(common);
517   KEYWORD(default);
518   KEYWORD(hidden);
519   KEYWORD(protected);
520   KEYWORD(unnamed_addr);
521   KEYWORD(local_unnamed_addr);
522   KEYWORD(externally_initialized);
523   KEYWORD(extern_weak);
524   KEYWORD(external);
525   KEYWORD(thread_local);
526   KEYWORD(localdynamic);
527   KEYWORD(initialexec);
528   KEYWORD(localexec);
529   KEYWORD(zeroinitializer);
530   KEYWORD(undef);
531   KEYWORD(null);
532   KEYWORD(none);
533   KEYWORD(poison);
534   KEYWORD(to);
535   KEYWORD(caller);
536   KEYWORD(within);
537   KEYWORD(from);
538   KEYWORD(tail);
539   KEYWORD(musttail);
540   KEYWORD(notail);
541   KEYWORD(target);
542   KEYWORD(triple);
543   KEYWORD(source_filename);
544   KEYWORD(unwind);
545   KEYWORD(datalayout);
546   KEYWORD(volatile);
547   KEYWORD(atomic);
548   KEYWORD(unordered);
549   KEYWORD(monotonic);
550   KEYWORD(acquire);
551   KEYWORD(release);
552   KEYWORD(acq_rel);
553   KEYWORD(seq_cst);
554   KEYWORD(syncscope);
555 
556   KEYWORD(nnan);
557   KEYWORD(ninf);
558   KEYWORD(nsz);
559   KEYWORD(arcp);
560   KEYWORD(contract);
561   KEYWORD(reassoc);
562   KEYWORD(afn);
563   KEYWORD(fast);
564   KEYWORD(nuw);
565   KEYWORD(nsw);
566   KEYWORD(exact);
567   KEYWORD(disjoint);
568   KEYWORD(inbounds);
569   KEYWORD(nneg);
570   KEYWORD(inrange);
571   KEYWORD(addrspace);
572   KEYWORD(section);
573   KEYWORD(partition);
574   KEYWORD(code_model);
575   KEYWORD(alias);
576   KEYWORD(ifunc);
577   KEYWORD(module);
578   KEYWORD(asm);
579   KEYWORD(sideeffect);
580   KEYWORD(inteldialect);
581   KEYWORD(gc);
582   KEYWORD(prefix);
583   KEYWORD(prologue);
584 
585   KEYWORD(no_sanitize_address);
586   KEYWORD(no_sanitize_hwaddress);
587   KEYWORD(sanitize_address_dyninit);
588 
589   KEYWORD(ccc);
590   KEYWORD(fastcc);
591   KEYWORD(coldcc);
592   KEYWORD(cfguard_checkcc);
593   KEYWORD(x86_stdcallcc);
594   KEYWORD(x86_fastcallcc);
595   KEYWORD(x86_thiscallcc);
596   KEYWORD(x86_vectorcallcc);
597   KEYWORD(arm_apcscc);
598   KEYWORD(arm_aapcscc);
599   KEYWORD(arm_aapcs_vfpcc);
600   KEYWORD(aarch64_vector_pcs);
601   KEYWORD(aarch64_sve_vector_pcs);
602   KEYWORD(aarch64_sme_preservemost_from_x0);
603   KEYWORD(aarch64_sme_preservemost_from_x2);
604   KEYWORD(msp430_intrcc);
605   KEYWORD(avr_intrcc);
606   KEYWORD(avr_signalcc);
607   KEYWORD(ptx_kernel);
608   KEYWORD(ptx_device);
609   KEYWORD(spir_kernel);
610   KEYWORD(spir_func);
611   KEYWORD(intel_ocl_bicc);
612   KEYWORD(x86_64_sysvcc);
613   KEYWORD(win64cc);
614   KEYWORD(x86_regcallcc);
615   KEYWORD(swiftcc);
616   KEYWORD(swifttailcc);
617   KEYWORD(anyregcc);
618   KEYWORD(preserve_mostcc);
619   KEYWORD(preserve_allcc);
620   KEYWORD(ghccc);
621   KEYWORD(x86_intrcc);
622   KEYWORD(hhvmcc);
623   KEYWORD(hhvm_ccc);
624   KEYWORD(cxx_fast_tlscc);
625   KEYWORD(amdgpu_vs);
626   KEYWORD(amdgpu_ls);
627   KEYWORD(amdgpu_hs);
628   KEYWORD(amdgpu_es);
629   KEYWORD(amdgpu_gs);
630   KEYWORD(amdgpu_ps);
631   KEYWORD(amdgpu_cs);
632   KEYWORD(amdgpu_cs_chain);
633   KEYWORD(amdgpu_cs_chain_preserve);
634   KEYWORD(amdgpu_kernel);
635   KEYWORD(amdgpu_gfx);
636   KEYWORD(tailcc);
637   KEYWORD(m68k_rtdcc);
638   KEYWORD(graalcc);
639 
640   KEYWORD(cc);
641   KEYWORD(c);
642 
643   KEYWORD(attributes);
644   KEYWORD(sync);
645   KEYWORD(async);
646 
647 #define GET_ATTR_NAMES
648 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
649   KEYWORD(DISPLAY_NAME);
650 #include "llvm/IR/Attributes.inc"
651 
652   KEYWORD(read);
653   KEYWORD(write);
654   KEYWORD(readwrite);
655   KEYWORD(argmem);
656   KEYWORD(inaccessiblemem);
657   KEYWORD(argmemonly);
658   KEYWORD(inaccessiblememonly);
659   KEYWORD(inaccessiblemem_or_argmemonly);
660 
661   // nofpclass attribute
662   KEYWORD(all);
663   KEYWORD(nan);
664   KEYWORD(snan);
665   KEYWORD(qnan);
666   KEYWORD(inf);
667   // ninf already a keyword
668   KEYWORD(pinf);
669   KEYWORD(norm);
670   KEYWORD(nnorm);
671   KEYWORD(pnorm);
672   // sub already a keyword
673   KEYWORD(nsub);
674   KEYWORD(psub);
675   KEYWORD(zero);
676   KEYWORD(nzero);
677   KEYWORD(pzero);
678 
679   KEYWORD(type);
680   KEYWORD(opaque);
681 
682   KEYWORD(comdat);
683 
684   // Comdat types
685   KEYWORD(any);
686   KEYWORD(exactmatch);
687   KEYWORD(largest);
688   KEYWORD(nodeduplicate);
689   KEYWORD(samesize);
690 
691   KEYWORD(eq); KEYWORD(ne); KEYWORD(slt); KEYWORD(sgt); KEYWORD(sle);
692   KEYWORD(sge); KEYWORD(ult); KEYWORD(ugt); KEYWORD(ule); KEYWORD(uge);
693   KEYWORD(oeq); KEYWORD(one); KEYWORD(olt); KEYWORD(ogt); KEYWORD(ole);
694   KEYWORD(oge); KEYWORD(ord); KEYWORD(uno); KEYWORD(ueq); KEYWORD(une);
695 
696   KEYWORD(xchg); KEYWORD(nand); KEYWORD(max); KEYWORD(min); KEYWORD(umax);
697   KEYWORD(umin); KEYWORD(fmax); KEYWORD(fmin);
698   KEYWORD(uinc_wrap);
699   KEYWORD(udec_wrap);
700 
701   KEYWORD(splat);
702   KEYWORD(vscale);
703   KEYWORD(x);
704   KEYWORD(blockaddress);
705   KEYWORD(dso_local_equivalent);
706   KEYWORD(no_cfi);
707 
708   // Metadata types.
709   KEYWORD(distinct);
710 
711   // Use-list order directives.
712   KEYWORD(uselistorder);
713   KEYWORD(uselistorder_bb);
714 
715   KEYWORD(personality);
716   KEYWORD(cleanup);
717   KEYWORD(catch);
718   KEYWORD(filter);
719 
720   // Summary index keywords.
721   KEYWORD(path);
722   KEYWORD(hash);
723   KEYWORD(gv);
724   KEYWORD(guid);
725   KEYWORD(name);
726   KEYWORD(summaries);
727   KEYWORD(flags);
728   KEYWORD(blockcount);
729   KEYWORD(linkage);
730   KEYWORD(visibility);
731   KEYWORD(notEligibleToImport);
732   KEYWORD(live);
733   KEYWORD(dsoLocal);
734   KEYWORD(canAutoHide);
735   KEYWORD(function);
736   KEYWORD(insts);
737   KEYWORD(funcFlags);
738   KEYWORD(readNone);
739   KEYWORD(readOnly);
740   KEYWORD(noRecurse);
741   KEYWORD(returnDoesNotAlias);
742   KEYWORD(noInline);
743   KEYWORD(alwaysInline);
744   KEYWORD(noUnwind);
745   KEYWORD(mayThrow);
746   KEYWORD(hasUnknownCall);
747   KEYWORD(mustBeUnreachable);
748   KEYWORD(calls);
749   KEYWORD(callee);
750   KEYWORD(params);
751   KEYWORD(param);
752   KEYWORD(hotness);
753   KEYWORD(unknown);
754   KEYWORD(critical);
755   KEYWORD(relbf);
756   KEYWORD(variable);
757   KEYWORD(vTableFuncs);
758   KEYWORD(virtFunc);
759   KEYWORD(aliasee);
760   KEYWORD(refs);
761   KEYWORD(typeIdInfo);
762   KEYWORD(typeTests);
763   KEYWORD(typeTestAssumeVCalls);
764   KEYWORD(typeCheckedLoadVCalls);
765   KEYWORD(typeTestAssumeConstVCalls);
766   KEYWORD(typeCheckedLoadConstVCalls);
767   KEYWORD(vFuncId);
768   KEYWORD(offset);
769   KEYWORD(args);
770   KEYWORD(typeid);
771   KEYWORD(typeidCompatibleVTable);
772   KEYWORD(summary);
773   KEYWORD(typeTestRes);
774   KEYWORD(kind);
775   KEYWORD(unsat);
776   KEYWORD(byteArray);
777   KEYWORD(inline);
778   KEYWORD(single);
779   KEYWORD(allOnes);
780   KEYWORD(sizeM1BitWidth);
781   KEYWORD(alignLog2);
782   KEYWORD(sizeM1);
783   KEYWORD(bitMask);
784   KEYWORD(inlineBits);
785   KEYWORD(vcall_visibility);
786   KEYWORD(wpdResolutions);
787   KEYWORD(wpdRes);
788   KEYWORD(indir);
789   KEYWORD(singleImpl);
790   KEYWORD(branchFunnel);
791   KEYWORD(singleImplName);
792   KEYWORD(resByArg);
793   KEYWORD(byArg);
794   KEYWORD(uniformRetVal);
795   KEYWORD(uniqueRetVal);
796   KEYWORD(virtualConstProp);
797   KEYWORD(info);
798   KEYWORD(byte);
799   KEYWORD(bit);
800   KEYWORD(varFlags);
801   KEYWORD(callsites);
802   KEYWORD(clones);
803   KEYWORD(stackIds);
804   KEYWORD(allocs);
805   KEYWORD(versions);
806   KEYWORD(memProf);
807   KEYWORD(notcold);
808 
809 #undef KEYWORD
810 
811   // Keywords for types.
812 #define TYPEKEYWORD(STR, LLVMTY)                                               \
813   do {                                                                         \
814     if (Keyword == STR) {                                                      \
815       TyVal = LLVMTY;                                                          \
816       return lltok::Type;                                                      \
817     }                                                                          \
818   } while (false)
819 
820   TYPEKEYWORD("void",      Type::getVoidTy(Context));
821   TYPEKEYWORD("half",      Type::getHalfTy(Context));
822   TYPEKEYWORD("bfloat",    Type::getBFloatTy(Context));
823   TYPEKEYWORD("float",     Type::getFloatTy(Context));
824   TYPEKEYWORD("double",    Type::getDoubleTy(Context));
825   TYPEKEYWORD("x86_fp80",  Type::getX86_FP80Ty(Context));
826   TYPEKEYWORD("fp128",     Type::getFP128Ty(Context));
827   TYPEKEYWORD("ppc_fp128", Type::getPPC_FP128Ty(Context));
828   TYPEKEYWORD("label",     Type::getLabelTy(Context));
829   TYPEKEYWORD("metadata",  Type::getMetadataTy(Context));
830   TYPEKEYWORD("x86_mmx",   Type::getX86_MMXTy(Context));
831   TYPEKEYWORD("x86_amx",   Type::getX86_AMXTy(Context));
832   TYPEKEYWORD("token",     Type::getTokenTy(Context));
833   TYPEKEYWORD("ptr",       PointerType::getUnqual(Context));
834 
835 #undef TYPEKEYWORD
836 
837   // Keywords for instructions.
838 #define INSTKEYWORD(STR, Enum)                                                 \
839   do {                                                                         \
840     if (Keyword == #STR) {                                                     \
841       UIntVal = Instruction::Enum;                                             \
842       return lltok::kw_##STR;                                                  \
843     }                                                                          \
844   } while (false)
845 
846   INSTKEYWORD(fneg,  FNeg);
847 
848   INSTKEYWORD(add,   Add);  INSTKEYWORD(fadd,   FAdd);
849   INSTKEYWORD(sub,   Sub);  INSTKEYWORD(fsub,   FSub);
850   INSTKEYWORD(mul,   Mul);  INSTKEYWORD(fmul,   FMul);
851   INSTKEYWORD(udiv,  UDiv); INSTKEYWORD(sdiv,  SDiv); INSTKEYWORD(fdiv,  FDiv);
852   INSTKEYWORD(urem,  URem); INSTKEYWORD(srem,  SRem); INSTKEYWORD(frem,  FRem);
853   INSTKEYWORD(shl,   Shl);  INSTKEYWORD(lshr,  LShr); INSTKEYWORD(ashr,  AShr);
854   INSTKEYWORD(and,   And);  INSTKEYWORD(or,    Or);   INSTKEYWORD(xor,   Xor);
855   INSTKEYWORD(icmp,  ICmp); INSTKEYWORD(fcmp,  FCmp);
856 
857   INSTKEYWORD(phi,         PHI);
858   INSTKEYWORD(call,        Call);
859   INSTKEYWORD(trunc,       Trunc);
860   INSTKEYWORD(zext,        ZExt);
861   INSTKEYWORD(sext,        SExt);
862   INSTKEYWORD(fptrunc,     FPTrunc);
863   INSTKEYWORD(fpext,       FPExt);
864   INSTKEYWORD(uitofp,      UIToFP);
865   INSTKEYWORD(sitofp,      SIToFP);
866   INSTKEYWORD(fptoui,      FPToUI);
867   INSTKEYWORD(fptosi,      FPToSI);
868   INSTKEYWORD(inttoptr,    IntToPtr);
869   INSTKEYWORD(ptrtoint,    PtrToInt);
870   INSTKEYWORD(bitcast,     BitCast);
871   INSTKEYWORD(addrspacecast, AddrSpaceCast);
872   INSTKEYWORD(select,      Select);
873   INSTKEYWORD(va_arg,      VAArg);
874   INSTKEYWORD(ret,         Ret);
875   INSTKEYWORD(br,          Br);
876   INSTKEYWORD(switch,      Switch);
877   INSTKEYWORD(indirectbr,  IndirectBr);
878   INSTKEYWORD(invoke,      Invoke);
879   INSTKEYWORD(resume,      Resume);
880   INSTKEYWORD(unreachable, Unreachable);
881   INSTKEYWORD(callbr,      CallBr);
882 
883   INSTKEYWORD(alloca,      Alloca);
884   INSTKEYWORD(load,        Load);
885   INSTKEYWORD(store,       Store);
886   INSTKEYWORD(cmpxchg,     AtomicCmpXchg);
887   INSTKEYWORD(atomicrmw,   AtomicRMW);
888   INSTKEYWORD(fence,       Fence);
889   INSTKEYWORD(getelementptr, GetElementPtr);
890 
891   INSTKEYWORD(extractelement, ExtractElement);
892   INSTKEYWORD(insertelement,  InsertElement);
893   INSTKEYWORD(shufflevector,  ShuffleVector);
894   INSTKEYWORD(extractvalue,   ExtractValue);
895   INSTKEYWORD(insertvalue,    InsertValue);
896   INSTKEYWORD(landingpad,     LandingPad);
897   INSTKEYWORD(cleanupret,     CleanupRet);
898   INSTKEYWORD(catchret,       CatchRet);
899   INSTKEYWORD(catchswitch,  CatchSwitch);
900   INSTKEYWORD(catchpad,     CatchPad);
901   INSTKEYWORD(cleanuppad,   CleanupPad);
902 
903   INSTKEYWORD(freeze,       Freeze);
904 
905 #undef INSTKEYWORD
906 
907 #define DWKEYWORD(TYPE, TOKEN)                                                 \
908   do {                                                                         \
909     if (Keyword.starts_with("DW_" #TYPE "_")) {                                \
910       StrVal.assign(Keyword.begin(), Keyword.end());                           \
911       return lltok::TOKEN;                                                     \
912     }                                                                          \
913   } while (false)
914 
915   DWKEYWORD(TAG, DwarfTag);
916   DWKEYWORD(ATE, DwarfAttEncoding);
917   DWKEYWORD(VIRTUALITY, DwarfVirtuality);
918   DWKEYWORD(LANG, DwarfLang);
919   DWKEYWORD(CC, DwarfCC);
920   DWKEYWORD(OP, DwarfOp);
921   DWKEYWORD(MACINFO, DwarfMacinfo);
922 
923 #undef DWKEYWORD
924 
925   if (Keyword.starts_with("DIFlag")) {
926     StrVal.assign(Keyword.begin(), Keyword.end());
927     return lltok::DIFlag;
928   }
929 
930   if (Keyword.starts_with("DISPFlag")) {
931     StrVal.assign(Keyword.begin(), Keyword.end());
932     return lltok::DISPFlag;
933   }
934 
935   if (Keyword.starts_with("CSK_")) {
936     StrVal.assign(Keyword.begin(), Keyword.end());
937     return lltok::ChecksumKind;
938   }
939 
940   if (Keyword == "NoDebug" || Keyword == "FullDebug" ||
941       Keyword == "LineTablesOnly" || Keyword == "DebugDirectivesOnly") {
942     StrVal.assign(Keyword.begin(), Keyword.end());
943     return lltok::EmissionKind;
944   }
945 
946   if (Keyword == "GNU" || Keyword == "Apple" || Keyword == "None" ||
947       Keyword == "Default") {
948     StrVal.assign(Keyword.begin(), Keyword.end());
949     return lltok::NameTableKind;
950   }
951 
952   // Check for [us]0x[0-9A-Fa-f]+ which are Hexadecimal constant generated by
953   // the CFE to avoid forcing it to deal with 64-bit numbers.
954   if ((TokStart[0] == 'u' || TokStart[0] == 's') &&
955       TokStart[1] == '0' && TokStart[2] == 'x' &&
956       isxdigit(static_cast<unsigned char>(TokStart[3]))) {
957     int len = CurPtr-TokStart-3;
958     uint32_t bits = len * 4;
959     StringRef HexStr(TokStart + 3, len);
960     if (!all_of(HexStr, isxdigit)) {
961       // Bad token, return it as an error.
962       CurPtr = TokStart+3;
963       return lltok::Error;
964     }
965     APInt Tmp(bits, HexStr, 16);
966     uint32_t activeBits = Tmp.getActiveBits();
967     if (activeBits > 0 && activeBits < bits)
968       Tmp = Tmp.trunc(activeBits);
969     APSIntVal = APSInt(Tmp, TokStart[0] == 'u');
970     return lltok::APSInt;
971   }
972 
973   // If this is "cc1234", return this as just "cc".
974   if (TokStart[0] == 'c' && TokStart[1] == 'c') {
975     CurPtr = TokStart+2;
976     return lltok::kw_cc;
977   }
978 
979   // Finally, if this isn't known, return an error.
980   CurPtr = TokStart+1;
981   return lltok::Error;
982 }
983 
984 /// Lex all tokens that start with a 0x prefix, knowing they match and are not
985 /// labels.
986 ///    HexFPConstant     0x[0-9A-Fa-f]+
987 ///    HexFP80Constant   0xK[0-9A-Fa-f]+
988 ///    HexFP128Constant  0xL[0-9A-Fa-f]+
989 ///    HexPPC128Constant 0xM[0-9A-Fa-f]+
990 ///    HexHalfConstant   0xH[0-9A-Fa-f]+
991 ///    HexBFloatConstant 0xR[0-9A-Fa-f]+
Lex0x()992 lltok::Kind LLLexer::Lex0x() {
993   CurPtr = TokStart + 2;
994 
995   char Kind;
996   if ((CurPtr[0] >= 'K' && CurPtr[0] <= 'M') || CurPtr[0] == 'H' ||
997       CurPtr[0] == 'R') {
998     Kind = *CurPtr++;
999   } else {
1000     Kind = 'J';
1001   }
1002 
1003   if (!isxdigit(static_cast<unsigned char>(CurPtr[0]))) {
1004     // Bad token, return it as an error.
1005     CurPtr = TokStart+1;
1006     return lltok::Error;
1007   }
1008 
1009   while (isxdigit(static_cast<unsigned char>(CurPtr[0])))
1010     ++CurPtr;
1011 
1012   if (Kind == 'J') {
1013     // HexFPConstant - Floating point constant represented in IEEE format as a
1014     // hexadecimal number for when exponential notation is not precise enough.
1015     // Half, BFloat, Float, and double only.
1016     APFloatVal = APFloat(APFloat::IEEEdouble(),
1017                          APInt(64, HexIntToVal(TokStart + 2, CurPtr)));
1018     return lltok::APFloat;
1019   }
1020 
1021   uint64_t Pair[2];
1022   switch (Kind) {
1023   default: llvm_unreachable("Unknown kind!");
1024   case 'K':
1025     // F80HexFPConstant - x87 long double in hexadecimal format (10 bytes)
1026     FP80HexToIntPair(TokStart+3, CurPtr, Pair);
1027     APFloatVal = APFloat(APFloat::x87DoubleExtended(), APInt(80, Pair));
1028     return lltok::APFloat;
1029   case 'L':
1030     // F128HexFPConstant - IEEE 128-bit in hexadecimal format (16 bytes)
1031     HexToIntPair(TokStart+3, CurPtr, Pair);
1032     APFloatVal = APFloat(APFloat::IEEEquad(), APInt(128, Pair));
1033     return lltok::APFloat;
1034   case 'M':
1035     // PPC128HexFPConstant - PowerPC 128-bit in hexadecimal format (16 bytes)
1036     HexToIntPair(TokStart+3, CurPtr, Pair);
1037     APFloatVal = APFloat(APFloat::PPCDoubleDouble(), APInt(128, Pair));
1038     return lltok::APFloat;
1039   case 'H':
1040     APFloatVal = APFloat(APFloat::IEEEhalf(),
1041                          APInt(16,HexIntToVal(TokStart+3, CurPtr)));
1042     return lltok::APFloat;
1043   case 'R':
1044     // Brain floating point
1045     APFloatVal = APFloat(APFloat::BFloat(),
1046                          APInt(16, HexIntToVal(TokStart + 3, CurPtr)));
1047     return lltok::APFloat;
1048   }
1049 }
1050 
1051 /// Lex tokens for a label or a numeric constant, possibly starting with -.
1052 ///    Label             [-a-zA-Z$._0-9]+:
1053 ///    NInteger          -[0-9]+
1054 ///    FPConstant        [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
1055 ///    PInteger          [0-9]+
1056 ///    HexFPConstant     0x[0-9A-Fa-f]+
1057 ///    HexFP80Constant   0xK[0-9A-Fa-f]+
1058 ///    HexFP128Constant  0xL[0-9A-Fa-f]+
1059 ///    HexPPC128Constant 0xM[0-9A-Fa-f]+
LexDigitOrNegative()1060 lltok::Kind LLLexer::LexDigitOrNegative() {
1061   // If the letter after the negative is not a number, this is probably a label.
1062   if (!isdigit(static_cast<unsigned char>(TokStart[0])) &&
1063       !isdigit(static_cast<unsigned char>(CurPtr[0]))) {
1064     // Okay, this is not a number after the -, it's probably a label.
1065     if (const char *End = isLabelTail(CurPtr)) {
1066       StrVal.assign(TokStart, End-1);
1067       CurPtr = End;
1068       return lltok::LabelStr;
1069     }
1070 
1071     return lltok::Error;
1072   }
1073 
1074   // At this point, it is either a label, int or fp constant.
1075 
1076   // Skip digits, we have at least one.
1077   for (; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
1078     /*empty*/;
1079 
1080   // Check if this is a fully-numeric label:
1081   if (isdigit(TokStart[0]) && CurPtr[0] == ':') {
1082     uint64_t Val = atoull(TokStart, CurPtr);
1083     ++CurPtr; // Skip the colon.
1084     if ((unsigned)Val != Val)
1085       Error("invalid value number (too large)!");
1086     UIntVal = unsigned(Val);
1087     return lltok::LabelID;
1088   }
1089 
1090   // Check to see if this really is a string label, e.g. "-1:".
1091   if (isLabelChar(CurPtr[0]) || CurPtr[0] == ':') {
1092     if (const char *End = isLabelTail(CurPtr)) {
1093       StrVal.assign(TokStart, End-1);
1094       CurPtr = End;
1095       return lltok::LabelStr;
1096     }
1097   }
1098 
1099   // If the next character is a '.', then it is a fp value, otherwise its
1100   // integer.
1101   if (CurPtr[0] != '.') {
1102     if (TokStart[0] == '0' && TokStart[1] == 'x')
1103       return Lex0x();
1104     APSIntVal = APSInt(StringRef(TokStart, CurPtr - TokStart));
1105     return lltok::APSInt;
1106   }
1107 
1108   ++CurPtr;
1109 
1110   // Skip over [0-9]*([eE][-+]?[0-9]+)?
1111   while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
1112 
1113   if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
1114     if (isdigit(static_cast<unsigned char>(CurPtr[1])) ||
1115         ((CurPtr[1] == '-' || CurPtr[1] == '+') &&
1116           isdigit(static_cast<unsigned char>(CurPtr[2])))) {
1117       CurPtr += 2;
1118       while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
1119     }
1120   }
1121 
1122   APFloatVal = APFloat(APFloat::IEEEdouble(),
1123                        StringRef(TokStart, CurPtr - TokStart));
1124   return lltok::APFloat;
1125 }
1126 
1127 /// Lex a floating point constant starting with +.
1128 ///    FPConstant  [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
LexPositive()1129 lltok::Kind LLLexer::LexPositive() {
1130   // If the letter after the negative is a number, this is probably not a
1131   // label.
1132   if (!isdigit(static_cast<unsigned char>(CurPtr[0])))
1133     return lltok::Error;
1134 
1135   // Skip digits.
1136   for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
1137     /*empty*/;
1138 
1139   // At this point, we need a '.'.
1140   if (CurPtr[0] != '.') {
1141     CurPtr = TokStart+1;
1142     return lltok::Error;
1143   }
1144 
1145   ++CurPtr;
1146 
1147   // Skip over [0-9]*([eE][-+]?[0-9]+)?
1148   while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
1149 
1150   if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
1151     if (isdigit(static_cast<unsigned char>(CurPtr[1])) ||
1152         ((CurPtr[1] == '-' || CurPtr[1] == '+') &&
1153         isdigit(static_cast<unsigned char>(CurPtr[2])))) {
1154       CurPtr += 2;
1155       while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
1156     }
1157   }
1158 
1159   APFloatVal = APFloat(APFloat::IEEEdouble(),
1160                        StringRef(TokStart, CurPtr - TokStart));
1161   return lltok::APFloat;
1162 }
1163