AsmParser: Don't crash on short hex constants for fp128 types
[oota-llvm.git] / lib / AsmParser / LLLexer.cpp
1 //===- LLLexer.cpp - Lexer for .ll Files ----------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implement the Lexer for .ll files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LLLexer.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/AsmParser/Parser.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Instruction.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <cctype>
27 #include <cstdio>
28 #include <cstdlib>
29 #include <cstring>
30 using namespace llvm;
31
32 bool LLLexer::Error(LocTy ErrorLoc, const Twine &Msg) const {
33   ErrorInfo = SM.GetMessage(ErrorLoc, SourceMgr::DK_Error, Msg);
34   return true;
35 }
36
37 void LLLexer::Warning(LocTy WarningLoc, const Twine &Msg) const {
38   SM.PrintMessage(WarningLoc, SourceMgr::DK_Warning, Msg);
39 }
40
41 //===----------------------------------------------------------------------===//
42 // Helper functions.
43 //===----------------------------------------------------------------------===//
44
45 // atoull - Convert an ascii string of decimal digits into the unsigned long
46 // long representation... this does not have to do input error checking,
47 // because we know that the input will be matched by a suitable regex...
48 //
49 uint64_t LLLexer::atoull(const char *Buffer, const char *End) {
50   uint64_t Result = 0;
51   for (; Buffer != End; Buffer++) {
52     uint64_t OldRes = Result;
53     Result *= 10;
54     Result += *Buffer-'0';
55     if (Result < OldRes) {  // Uh, oh, overflow detected!!!
56       Error("constant bigger than 64 bits detected!");
57       return 0;
58     }
59   }
60   return Result;
61 }
62
63 uint64_t LLLexer::HexIntToVal(const char *Buffer, const char *End) {
64   uint64_t Result = 0;
65   for (; Buffer != End; ++Buffer) {
66     uint64_t OldRes = Result;
67     Result *= 16;
68     Result += hexDigitValue(*Buffer);
69
70     if (Result < OldRes) {   // Uh, oh, overflow detected!!!
71       Error("constant bigger than 64 bits detected!");
72       return 0;
73     }
74   }
75   return Result;
76 }
77
78 void LLLexer::HexToIntPair(const char *Buffer, const char *End,
79                            uint64_t Pair[2]) {
80   Pair[0] = 0;
81   if (End - Buffer >= 16) {
82     for (int i = 0; i < 16; i++, Buffer++) {
83       assert(Buffer != End);
84       Pair[0] *= 16;
85       Pair[0] += hexDigitValue(*Buffer);
86     }
87   }
88   Pair[1] = 0;
89   for (int i = 0; i < 16 && Buffer != End; i++, Buffer++) {
90     Pair[1] *= 16;
91     Pair[1] += hexDigitValue(*Buffer);
92   }
93   if (Buffer != End)
94     Error("constant bigger than 128 bits detected!");
95 }
96
97 /// FP80HexToIntPair - translate an 80 bit FP80 number (20 hexits) into
98 /// { low64, high16 } as usual for an APInt.
99 void LLLexer::FP80HexToIntPair(const char *Buffer, const char *End,
100                            uint64_t Pair[2]) {
101   Pair[1] = 0;
102   for (int i=0; i<4 && Buffer != End; i++, Buffer++) {
103     assert(Buffer != End);
104     Pair[1] *= 16;
105     Pair[1] += hexDigitValue(*Buffer);
106   }
107   Pair[0] = 0;
108   for (int i=0; i<16; i++, Buffer++) {
109     Pair[0] *= 16;
110     Pair[0] += hexDigitValue(*Buffer);
111   }
112   if (Buffer != End)
113     Error("constant bigger than 128 bits detected!");
114 }
115
116 // UnEscapeLexed - Run through the specified buffer and change \xx codes to the
117 // appropriate character.
118 static void UnEscapeLexed(std::string &Str) {
119   if (Str.empty()) return;
120
121   char *Buffer = &Str[0], *EndBuffer = Buffer+Str.size();
122   char *BOut = Buffer;
123   for (char *BIn = Buffer; BIn != EndBuffer; ) {
124     if (BIn[0] == '\\') {
125       if (BIn < EndBuffer-1 && BIn[1] == '\\') {
126         *BOut++ = '\\'; // Two \ becomes one
127         BIn += 2;
128       } else if (BIn < EndBuffer-2 &&
129                  isxdigit(static_cast<unsigned char>(BIn[1])) &&
130                  isxdigit(static_cast<unsigned char>(BIn[2]))) {
131         *BOut = hexDigitValue(BIn[1]) * 16 + hexDigitValue(BIn[2]);
132         BIn += 3;                           // Skip over handled chars
133         ++BOut;
134       } else {
135         *BOut++ = *BIn++;
136       }
137     } else {
138       *BOut++ = *BIn++;
139     }
140   }
141   Str.resize(BOut-Buffer);
142 }
143
144 /// isLabelChar - Return true for [-a-zA-Z$._0-9].
145 static bool isLabelChar(char C) {
146   return isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
147          C == '.' || C == '_';
148 }
149
150
151 /// isLabelTail - Return true if this pointer points to a valid end of a label.
152 static const char *isLabelTail(const char *CurPtr) {
153   while (1) {
154     if (CurPtr[0] == ':') return CurPtr+1;
155     if (!isLabelChar(CurPtr[0])) return nullptr;
156     ++CurPtr;
157   }
158 }
159
160
161
162 //===----------------------------------------------------------------------===//
163 // Lexer definition.
164 //===----------------------------------------------------------------------===//
165
166 LLLexer::LLLexer(StringRef StartBuf, SourceMgr &sm, SMDiagnostic &Err,
167                  LLVMContext &C)
168   : CurBuf(StartBuf), ErrorInfo(Err), SM(sm), Context(C), APFloatVal(0.0) {
169   CurPtr = CurBuf.begin();
170 }
171
172 int LLLexer::getNextChar() {
173   char CurChar = *CurPtr++;
174   switch (CurChar) {
175   default: return (unsigned char)CurChar;
176   case 0:
177     // A nul character in the stream is either the end of the current buffer or
178     // a random nul in the file.  Disambiguate that here.
179     if (CurPtr-1 != CurBuf.end())
180       return 0;  // Just whitespace.
181
182     // Otherwise, return end of file.
183     --CurPtr;  // Another call to lex will return EOF again.
184     return EOF;
185   }
186 }
187
188
189 lltok::Kind LLLexer::LexToken() {
190   TokStart = CurPtr;
191
192   int CurChar = getNextChar();
193   switch (CurChar) {
194   default:
195     // Handle letters: [a-zA-Z_]
196     if (isalpha(static_cast<unsigned char>(CurChar)) || CurChar == '_')
197       return LexIdentifier();
198
199     return lltok::Error;
200   case EOF: return lltok::Eof;
201   case 0:
202   case ' ':
203   case '\t':
204   case '\n':
205   case '\r':
206     // Ignore whitespace.
207     return LexToken();
208   case '+': return LexPositive();
209   case '@': return LexAt();
210   case '$': return LexDollar();
211   case '%': return LexPercent();
212   case '"': return LexQuote();
213   case '.':
214     if (const char *Ptr = isLabelTail(CurPtr)) {
215       CurPtr = Ptr;
216       StrVal.assign(TokStart, CurPtr-1);
217       return lltok::LabelStr;
218     }
219     if (CurPtr[0] == '.' && CurPtr[1] == '.') {
220       CurPtr += 2;
221       return lltok::dotdotdot;
222     }
223     return lltok::Error;
224   case ';':
225     SkipLineComment();
226     return LexToken();
227   case '!': return LexExclaim();
228   case '#': return LexHash();
229   case '0': case '1': case '2': case '3': case '4':
230   case '5': case '6': case '7': case '8': case '9':
231   case '-':
232     return LexDigitOrNegative();
233   case '=': return lltok::equal;
234   case '[': return lltok::lsquare;
235   case ']': return lltok::rsquare;
236   case '{': return lltok::lbrace;
237   case '}': return lltok::rbrace;
238   case '<': return lltok::less;
239   case '>': return lltok::greater;
240   case '(': return lltok::lparen;
241   case ')': return lltok::rparen;
242   case ',': return lltok::comma;
243   case '*': return lltok::star;
244   case '\\': return lltok::backslash;
245   }
246 }
247
248 void LLLexer::SkipLineComment() {
249   while (1) {
250     if (CurPtr[0] == '\n' || CurPtr[0] == '\r' || getNextChar() == EOF)
251       return;
252   }
253 }
254
255 /// LexAt - Lex all tokens that start with an @ character:
256 ///   GlobalVar   @\"[^\"]*\"
257 ///   GlobalVar   @[-a-zA-Z$._][-a-zA-Z$._0-9]*
258 ///   GlobalVarID @[0-9]+
259 lltok::Kind LLLexer::LexAt() {
260   // Handle AtStringConstant: @\"[^\"]*\"
261   if (CurPtr[0] == '"') {
262     ++CurPtr;
263
264     while (1) {
265       int CurChar = getNextChar();
266
267       if (CurChar == EOF) {
268         Error("end of file in global variable name");
269         return lltok::Error;
270       }
271       if (CurChar == '"') {
272         StrVal.assign(TokStart+2, CurPtr-1);
273         UnEscapeLexed(StrVal);
274         if (StringRef(StrVal).find_first_of(0) != StringRef::npos) {
275           Error("Null bytes are not allowed in names");
276           return lltok::Error;
277         }
278         return lltok::GlobalVar;
279       }
280     }
281   }
282
283   // Handle GlobalVarName: @[-a-zA-Z$._][-a-zA-Z$._0-9]*
284   if (ReadVarName())
285     return lltok::GlobalVar;
286
287   // Handle GlobalVarID: @[0-9]+
288   if (isdigit(static_cast<unsigned char>(CurPtr[0]))) {
289     for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
290       /*empty*/;
291
292     uint64_t Val = atoull(TokStart+1, CurPtr);
293     if ((unsigned)Val != Val)
294       Error("invalid value number (too large)!");
295     UIntVal = unsigned(Val);
296     return lltok::GlobalID;
297   }
298
299   return lltok::Error;
300 }
301
302 lltok::Kind LLLexer::LexDollar() {
303   if (const char *Ptr = isLabelTail(TokStart)) {
304     CurPtr = Ptr;
305     StrVal.assign(TokStart, CurPtr - 1);
306     return lltok::LabelStr;
307   }
308
309   // Handle DollarStringConstant: $\"[^\"]*\"
310   if (CurPtr[0] == '"') {
311     ++CurPtr;
312
313     while (1) {
314       int CurChar = getNextChar();
315
316       if (CurChar == EOF) {
317         Error("end of file in COMDAT variable name");
318         return lltok::Error;
319       }
320       if (CurChar == '"') {
321         StrVal.assign(TokStart + 2, CurPtr - 1);
322         UnEscapeLexed(StrVal);
323         if (StringRef(StrVal).find_first_of(0) != StringRef::npos) {
324           Error("Null bytes are not allowed in names");
325           return lltok::Error;
326         }
327         return lltok::ComdatVar;
328       }
329     }
330   }
331
332   // Handle ComdatVarName: $[-a-zA-Z$._][-a-zA-Z$._0-9]*
333   if (ReadVarName())
334     return lltok::ComdatVar;
335
336   return lltok::Error;
337 }
338
339 /// ReadString - Read a string until the closing quote.
340 lltok::Kind LLLexer::ReadString(lltok::Kind kind) {
341   const char *Start = CurPtr;
342   while (1) {
343     int CurChar = getNextChar();
344
345     if (CurChar == EOF) {
346       Error("end of file in string constant");
347       return lltok::Error;
348     }
349     if (CurChar == '"') {
350       StrVal.assign(Start, CurPtr-1);
351       UnEscapeLexed(StrVal);
352       return kind;
353     }
354   }
355 }
356
357 /// ReadVarName - Read the rest of a token containing a variable name.
358 bool LLLexer::ReadVarName() {
359   const char *NameStart = CurPtr;
360   if (isalpha(static_cast<unsigned char>(CurPtr[0])) ||
361       CurPtr[0] == '-' || CurPtr[0] == '$' ||
362       CurPtr[0] == '.' || CurPtr[0] == '_') {
363     ++CurPtr;
364     while (isalnum(static_cast<unsigned char>(CurPtr[0])) ||
365            CurPtr[0] == '-' || CurPtr[0] == '$' ||
366            CurPtr[0] == '.' || CurPtr[0] == '_')
367       ++CurPtr;
368
369     StrVal.assign(NameStart, CurPtr);
370     return true;
371   }
372   return false;
373 }
374
375 /// LexPercent - Lex all tokens that start with a % character:
376 ///   LocalVar   ::= %\"[^\"]*\"
377 ///   LocalVar   ::= %[-a-zA-Z$._][-a-zA-Z$._0-9]*
378 ///   LocalVarID ::= %[0-9]+
379 lltok::Kind LLLexer::LexPercent() {
380   // Handle LocalVarName: %\"[^\"]*\"
381   if (CurPtr[0] == '"') {
382     ++CurPtr;
383     return ReadString(lltok::LocalVar);
384   }
385
386   // Handle LocalVarName: %[-a-zA-Z$._][-a-zA-Z$._0-9]*
387   if (ReadVarName())
388     return lltok::LocalVar;
389
390   // Handle LocalVarID: %[0-9]+
391   if (isdigit(static_cast<unsigned char>(CurPtr[0]))) {
392     for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
393       /*empty*/;
394
395     uint64_t Val = atoull(TokStart+1, CurPtr);
396     if ((unsigned)Val != Val)
397       Error("invalid value number (too large)!");
398     UIntVal = unsigned(Val);
399     return lltok::LocalVarID;
400   }
401
402   return lltok::Error;
403 }
404
405 /// LexQuote - Lex all tokens that start with a " character:
406 ///   QuoteLabel        "[^"]+":
407 ///   StringConstant    "[^"]*"
408 lltok::Kind LLLexer::LexQuote() {
409   lltok::Kind kind = ReadString(lltok::StringConstant);
410   if (kind == lltok::Error || kind == lltok::Eof)
411     return kind;
412
413   if (CurPtr[0] == ':') {
414     ++CurPtr;
415     kind = lltok::LabelStr;
416   }
417
418   return kind;
419 }
420
421 /// LexExclaim:
422 ///    !foo
423 ///    !
424 lltok::Kind LLLexer::LexExclaim() {
425   // Lex a metadata name as a MetadataVar.
426   if (isalpha(static_cast<unsigned char>(CurPtr[0])) ||
427       CurPtr[0] == '-' || CurPtr[0] == '$' ||
428       CurPtr[0] == '.' || CurPtr[0] == '_' || CurPtr[0] == '\\') {
429     ++CurPtr;
430     while (isalnum(static_cast<unsigned char>(CurPtr[0])) ||
431            CurPtr[0] == '-' || CurPtr[0] == '$' ||
432            CurPtr[0] == '.' || CurPtr[0] == '_' || CurPtr[0] == '\\')
433       ++CurPtr;
434
435     StrVal.assign(TokStart+1, CurPtr);   // Skip !
436     UnEscapeLexed(StrVal);
437     return lltok::MetadataVar;
438   }
439   return lltok::exclaim;
440 }
441
442 /// LexHash - Lex all tokens that start with a # character:
443 ///    AttrGrpID ::= #[0-9]+
444 lltok::Kind LLLexer::LexHash() {
445   // Handle AttrGrpID: #[0-9]+
446   if (isdigit(static_cast<unsigned char>(CurPtr[0]))) {
447     for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
448       /*empty*/;
449
450     uint64_t Val = atoull(TokStart+1, CurPtr);
451     if ((unsigned)Val != Val)
452       Error("invalid value number (too large)!");
453     UIntVal = unsigned(Val);
454     return lltok::AttrGrpID;
455   }
456
457   return lltok::Error;
458 }
459
460 /// LexIdentifier: Handle several related productions:
461 ///    Label           [-a-zA-Z$._0-9]+:
462 ///    IntegerType     i[0-9]+
463 ///    Keyword         sdiv, float, ...
464 ///    HexIntConstant  [us]0x[0-9A-Fa-f]+
465 lltok::Kind LLLexer::LexIdentifier() {
466   const char *StartChar = CurPtr;
467   const char *IntEnd = CurPtr[-1] == 'i' ? nullptr : StartChar;
468   const char *KeywordEnd = nullptr;
469
470   for (; isLabelChar(*CurPtr); ++CurPtr) {
471     // If we decide this is an integer, remember the end of the sequence.
472     if (!IntEnd && !isdigit(static_cast<unsigned char>(*CurPtr)))
473       IntEnd = CurPtr;
474     if (!KeywordEnd && !isalnum(static_cast<unsigned char>(*CurPtr)) &&
475         *CurPtr != '_')
476       KeywordEnd = CurPtr;
477   }
478
479   // If we stopped due to a colon, this really is a label.
480   if (*CurPtr == ':') {
481     StrVal.assign(StartChar-1, CurPtr++);
482     return lltok::LabelStr;
483   }
484
485   // Otherwise, this wasn't a label.  If this was valid as an integer type,
486   // return it.
487   if (!IntEnd) IntEnd = CurPtr;
488   if (IntEnd != StartChar) {
489     CurPtr = IntEnd;
490     uint64_t NumBits = atoull(StartChar, CurPtr);
491     if (NumBits < IntegerType::MIN_INT_BITS ||
492         NumBits > IntegerType::MAX_INT_BITS) {
493       Error("bitwidth for integer type out of range!");
494       return lltok::Error;
495     }
496     TyVal = IntegerType::get(Context, NumBits);
497     return lltok::Type;
498   }
499
500   // Otherwise, this was a letter sequence.  See which keyword this is.
501   if (!KeywordEnd) KeywordEnd = CurPtr;
502   CurPtr = KeywordEnd;
503   --StartChar;
504   unsigned Len = CurPtr-StartChar;
505 #define KEYWORD(STR)                                                    \
506   do {                                                                  \
507     if (Len == strlen(#STR) && !memcmp(StartChar, #STR, strlen(#STR)))  \
508       return lltok::kw_##STR;                                           \
509   } while (0)
510
511   KEYWORD(true);    KEYWORD(false);
512   KEYWORD(declare); KEYWORD(define);
513   KEYWORD(global);  KEYWORD(constant);
514
515   KEYWORD(private);
516   KEYWORD(internal);
517   KEYWORD(available_externally);
518   KEYWORD(linkonce);
519   KEYWORD(linkonce_odr);
520   KEYWORD(weak); // Use as a linkage, and a modifier for "cmpxchg".
521   KEYWORD(weak_odr);
522   KEYWORD(appending);
523   KEYWORD(dllimport);
524   KEYWORD(dllexport);
525   KEYWORD(common);
526   KEYWORD(default);
527   KEYWORD(hidden);
528   KEYWORD(protected);
529   KEYWORD(unnamed_addr);
530   KEYWORD(externally_initialized);
531   KEYWORD(extern_weak);
532   KEYWORD(external);
533   KEYWORD(thread_local);
534   KEYWORD(localdynamic);
535   KEYWORD(initialexec);
536   KEYWORD(localexec);
537   KEYWORD(zeroinitializer);
538   KEYWORD(undef);
539   KEYWORD(null);
540   KEYWORD(to);
541   KEYWORD(tail);
542   KEYWORD(musttail);
543   KEYWORD(target);
544   KEYWORD(triple);
545   KEYWORD(unwind);
546   KEYWORD(deplibs);             // FIXME: Remove in 4.0.
547   KEYWORD(datalayout);
548   KEYWORD(volatile);
549   KEYWORD(atomic);
550   KEYWORD(unordered);
551   KEYWORD(monotonic);
552   KEYWORD(acquire);
553   KEYWORD(release);
554   KEYWORD(acq_rel);
555   KEYWORD(seq_cst);
556   KEYWORD(singlethread);
557
558   KEYWORD(nnan);
559   KEYWORD(ninf);
560   KEYWORD(nsz);
561   KEYWORD(arcp);
562   KEYWORD(fast);
563   KEYWORD(nuw);
564   KEYWORD(nsw);
565   KEYWORD(exact);
566   KEYWORD(inbounds);
567   KEYWORD(align);
568   KEYWORD(addrspace);
569   KEYWORD(section);
570   KEYWORD(alias);
571   KEYWORD(module);
572   KEYWORD(asm);
573   KEYWORD(sideeffect);
574   KEYWORD(alignstack);
575   KEYWORD(inteldialect);
576   KEYWORD(gc);
577   KEYWORD(prefix);
578   KEYWORD(prologue);
579
580   KEYWORD(ccc);
581   KEYWORD(fastcc);
582   KEYWORD(coldcc);
583   KEYWORD(x86_stdcallcc);
584   KEYWORD(x86_fastcallcc);
585   KEYWORD(x86_thiscallcc);
586   KEYWORD(x86_vectorcallcc);
587   KEYWORD(arm_apcscc);
588   KEYWORD(arm_aapcscc);
589   KEYWORD(arm_aapcs_vfpcc);
590   KEYWORD(msp430_intrcc);
591   KEYWORD(ptx_kernel);
592   KEYWORD(ptx_device);
593   KEYWORD(spir_kernel);
594   KEYWORD(spir_func);
595   KEYWORD(intel_ocl_bicc);
596   KEYWORD(x86_64_sysvcc);
597   KEYWORD(x86_64_win64cc);
598   KEYWORD(webkit_jscc);
599   KEYWORD(anyregcc);
600   KEYWORD(preserve_mostcc);
601   KEYWORD(preserve_allcc);
602   KEYWORD(ghccc);
603
604   KEYWORD(cc);
605   KEYWORD(c);
606
607   KEYWORD(attributes);
608
609   KEYWORD(alwaysinline);
610   KEYWORD(builtin);
611   KEYWORD(byval);
612   KEYWORD(inalloca);
613   KEYWORD(cold);
614   KEYWORD(dereferenceable);
615   KEYWORD(inlinehint);
616   KEYWORD(inreg);
617   KEYWORD(jumptable);
618   KEYWORD(minsize);
619   KEYWORD(naked);
620   KEYWORD(nest);
621   KEYWORD(noalias);
622   KEYWORD(nobuiltin);
623   KEYWORD(nocapture);
624   KEYWORD(noduplicate);
625   KEYWORD(noimplicitfloat);
626   KEYWORD(noinline);
627   KEYWORD(nonlazybind);
628   KEYWORD(nonnull);
629   KEYWORD(noredzone);
630   KEYWORD(noreturn);
631   KEYWORD(nounwind);
632   KEYWORD(optnone);
633   KEYWORD(optsize);
634   KEYWORD(readnone);
635   KEYWORD(readonly);
636   KEYWORD(returned);
637   KEYWORD(returns_twice);
638   KEYWORD(signext);
639   KEYWORD(sret);
640   KEYWORD(ssp);
641   KEYWORD(sspreq);
642   KEYWORD(sspstrong);
643   KEYWORD(sanitize_address);
644   KEYWORD(sanitize_thread);
645   KEYWORD(sanitize_memory);
646   KEYWORD(uwtable);
647   KEYWORD(zeroext);
648
649   KEYWORD(type);
650   KEYWORD(opaque);
651
652   KEYWORD(comdat);
653
654   // Comdat types
655   KEYWORD(any);
656   KEYWORD(exactmatch);
657   KEYWORD(largest);
658   KEYWORD(noduplicates);
659   KEYWORD(samesize);
660
661   KEYWORD(eq); KEYWORD(ne); KEYWORD(slt); KEYWORD(sgt); KEYWORD(sle);
662   KEYWORD(sge); KEYWORD(ult); KEYWORD(ugt); KEYWORD(ule); KEYWORD(uge);
663   KEYWORD(oeq); KEYWORD(one); KEYWORD(olt); KEYWORD(ogt); KEYWORD(ole);
664   KEYWORD(oge); KEYWORD(ord); KEYWORD(uno); KEYWORD(ueq); KEYWORD(une);
665
666   KEYWORD(xchg); KEYWORD(nand); KEYWORD(max); KEYWORD(min); KEYWORD(umax);
667   KEYWORD(umin);
668
669   KEYWORD(x);
670   KEYWORD(blockaddress);
671
672   // Use-list order directives.
673   KEYWORD(uselistorder);
674   KEYWORD(uselistorder_bb);
675
676   KEYWORD(personality);
677   KEYWORD(cleanup);
678   KEYWORD(catch);
679   KEYWORD(filter);
680 #undef KEYWORD
681
682   // Keywords for types.
683 #define TYPEKEYWORD(STR, LLVMTY) \
684   if (Len == strlen(STR) && !memcmp(StartChar, STR, strlen(STR))) { \
685     TyVal = LLVMTY; return lltok::Type; }
686   TYPEKEYWORD("void",      Type::getVoidTy(Context));
687   TYPEKEYWORD("half",      Type::getHalfTy(Context));
688   TYPEKEYWORD("float",     Type::getFloatTy(Context));
689   TYPEKEYWORD("double",    Type::getDoubleTy(Context));
690   TYPEKEYWORD("x86_fp80",  Type::getX86_FP80Ty(Context));
691   TYPEKEYWORD("fp128",     Type::getFP128Ty(Context));
692   TYPEKEYWORD("ppc_fp128", Type::getPPC_FP128Ty(Context));
693   TYPEKEYWORD("label",     Type::getLabelTy(Context));
694   TYPEKEYWORD("metadata",  Type::getMetadataTy(Context));
695   TYPEKEYWORD("x86_mmx",   Type::getX86_MMXTy(Context));
696 #undef TYPEKEYWORD
697
698   // Keywords for instructions.
699 #define INSTKEYWORD(STR, Enum) \
700   if (Len == strlen(#STR) && !memcmp(StartChar, #STR, strlen(#STR))) { \
701     UIntVal = Instruction::Enum; return lltok::kw_##STR; }
702
703   INSTKEYWORD(add,   Add);  INSTKEYWORD(fadd,   FAdd);
704   INSTKEYWORD(sub,   Sub);  INSTKEYWORD(fsub,   FSub);
705   INSTKEYWORD(mul,   Mul);  INSTKEYWORD(fmul,   FMul);
706   INSTKEYWORD(udiv,  UDiv); INSTKEYWORD(sdiv,  SDiv); INSTKEYWORD(fdiv,  FDiv);
707   INSTKEYWORD(urem,  URem); INSTKEYWORD(srem,  SRem); INSTKEYWORD(frem,  FRem);
708   INSTKEYWORD(shl,   Shl);  INSTKEYWORD(lshr,  LShr); INSTKEYWORD(ashr,  AShr);
709   INSTKEYWORD(and,   And);  INSTKEYWORD(or,    Or);   INSTKEYWORD(xor,   Xor);
710   INSTKEYWORD(icmp,  ICmp); INSTKEYWORD(fcmp,  FCmp);
711
712   INSTKEYWORD(phi,         PHI);
713   INSTKEYWORD(call,        Call);
714   INSTKEYWORD(trunc,       Trunc);
715   INSTKEYWORD(zext,        ZExt);
716   INSTKEYWORD(sext,        SExt);
717   INSTKEYWORD(fptrunc,     FPTrunc);
718   INSTKEYWORD(fpext,       FPExt);
719   INSTKEYWORD(uitofp,      UIToFP);
720   INSTKEYWORD(sitofp,      SIToFP);
721   INSTKEYWORD(fptoui,      FPToUI);
722   INSTKEYWORD(fptosi,      FPToSI);
723   INSTKEYWORD(inttoptr,    IntToPtr);
724   INSTKEYWORD(ptrtoint,    PtrToInt);
725   INSTKEYWORD(bitcast,     BitCast);
726   INSTKEYWORD(addrspacecast, AddrSpaceCast);
727   INSTKEYWORD(select,      Select);
728   INSTKEYWORD(va_arg,      VAArg);
729   INSTKEYWORD(ret,         Ret);
730   INSTKEYWORD(br,          Br);
731   INSTKEYWORD(switch,      Switch);
732   INSTKEYWORD(indirectbr,  IndirectBr);
733   INSTKEYWORD(invoke,      Invoke);
734   INSTKEYWORD(resume,      Resume);
735   INSTKEYWORD(unreachable, Unreachable);
736
737   INSTKEYWORD(alloca,      Alloca);
738   INSTKEYWORD(load,        Load);
739   INSTKEYWORD(store,       Store);
740   INSTKEYWORD(cmpxchg,     AtomicCmpXchg);
741   INSTKEYWORD(atomicrmw,   AtomicRMW);
742   INSTKEYWORD(fence,       Fence);
743   INSTKEYWORD(getelementptr, GetElementPtr);
744
745   INSTKEYWORD(extractelement, ExtractElement);
746   INSTKEYWORD(insertelement,  InsertElement);
747   INSTKEYWORD(shufflevector,  ShuffleVector);
748   INSTKEYWORD(extractvalue,   ExtractValue);
749   INSTKEYWORD(insertvalue,    InsertValue);
750   INSTKEYWORD(landingpad,     LandingPad);
751 #undef INSTKEYWORD
752
753   // Check for [us]0x[0-9A-Fa-f]+ which are Hexadecimal constant generated by
754   // the CFE to avoid forcing it to deal with 64-bit numbers.
755   if ((TokStart[0] == 'u' || TokStart[0] == 's') &&
756       TokStart[1] == '0' && TokStart[2] == 'x' &&
757       isxdigit(static_cast<unsigned char>(TokStart[3]))) {
758     int len = CurPtr-TokStart-3;
759     uint32_t bits = len * 4;
760     APInt Tmp(bits, StringRef(TokStart+3, len), 16);
761     uint32_t activeBits = Tmp.getActiveBits();
762     if (activeBits > 0 && activeBits < bits)
763       Tmp = Tmp.trunc(activeBits);
764     APSIntVal = APSInt(Tmp, TokStart[0] == 'u');
765     return lltok::APSInt;
766   }
767
768   // If this is "cc1234", return this as just "cc".
769   if (TokStart[0] == 'c' && TokStart[1] == 'c') {
770     CurPtr = TokStart+2;
771     return lltok::kw_cc;
772   }
773
774   // Finally, if this isn't known, return an error.
775   CurPtr = TokStart+1;
776   return lltok::Error;
777 }
778
779
780 /// Lex0x: Handle productions that start with 0x, knowing that it matches and
781 /// that this is not a label:
782 ///    HexFPConstant     0x[0-9A-Fa-f]+
783 ///    HexFP80Constant   0xK[0-9A-Fa-f]+
784 ///    HexFP128Constant  0xL[0-9A-Fa-f]+
785 ///    HexPPC128Constant 0xM[0-9A-Fa-f]+
786 ///    HexHalfConstant   0xH[0-9A-Fa-f]+
787 lltok::Kind LLLexer::Lex0x() {
788   CurPtr = TokStart + 2;
789
790   char Kind;
791   if ((CurPtr[0] >= 'K' && CurPtr[0] <= 'M') || CurPtr[0] == 'H') {
792     Kind = *CurPtr++;
793   } else {
794     Kind = 'J';
795   }
796
797   if (!isxdigit(static_cast<unsigned char>(CurPtr[0]))) {
798     // Bad token, return it as an error.
799     CurPtr = TokStart+1;
800     return lltok::Error;
801   }
802
803   while (isxdigit(static_cast<unsigned char>(CurPtr[0])))
804     ++CurPtr;
805
806   if (Kind == 'J') {
807     // HexFPConstant - Floating point constant represented in IEEE format as a
808     // hexadecimal number for when exponential notation is not precise enough.
809     // Half, Float, and double only.
810     APFloatVal = APFloat(BitsToDouble(HexIntToVal(TokStart+2, CurPtr)));
811     return lltok::APFloat;
812   }
813
814   uint64_t Pair[2];
815   switch (Kind) {
816   default: llvm_unreachable("Unknown kind!");
817   case 'K':
818     // F80HexFPConstant - x87 long double in hexadecimal format (10 bytes)
819     FP80HexToIntPair(TokStart+3, CurPtr, Pair);
820     APFloatVal = APFloat(APFloat::x87DoubleExtended, APInt(80, Pair));
821     return lltok::APFloat;
822   case 'L':
823     // F128HexFPConstant - IEEE 128-bit in hexadecimal format (16 bytes)
824     HexToIntPair(TokStart+3, CurPtr, Pair);
825     APFloatVal = APFloat(APFloat::IEEEquad, APInt(128, Pair));
826     return lltok::APFloat;
827   case 'M':
828     // PPC128HexFPConstant - PowerPC 128-bit in hexadecimal format (16 bytes)
829     HexToIntPair(TokStart+3, CurPtr, Pair);
830     APFloatVal = APFloat(APFloat::PPCDoubleDouble, APInt(128, Pair));
831     return lltok::APFloat;
832   case 'H':
833     APFloatVal = APFloat(APFloat::IEEEhalf,
834                          APInt(16,HexIntToVal(TokStart+3, CurPtr)));
835     return lltok::APFloat;
836   }
837 }
838
839 /// LexIdentifier: Handle several related productions:
840 ///    Label             [-a-zA-Z$._0-9]+:
841 ///    NInteger          -[0-9]+
842 ///    FPConstant        [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
843 ///    PInteger          [0-9]+
844 ///    HexFPConstant     0x[0-9A-Fa-f]+
845 ///    HexFP80Constant   0xK[0-9A-Fa-f]+
846 ///    HexFP128Constant  0xL[0-9A-Fa-f]+
847 ///    HexPPC128Constant 0xM[0-9A-Fa-f]+
848 lltok::Kind LLLexer::LexDigitOrNegative() {
849   // If the letter after the negative is not a number, this is probably a label.
850   if (!isdigit(static_cast<unsigned char>(TokStart[0])) &&
851       !isdigit(static_cast<unsigned char>(CurPtr[0]))) {
852     // Okay, this is not a number after the -, it's probably a label.
853     if (const char *End = isLabelTail(CurPtr)) {
854       StrVal.assign(TokStart, End-1);
855       CurPtr = End;
856       return lltok::LabelStr;
857     }
858
859     return lltok::Error;
860   }
861
862   // At this point, it is either a label, int or fp constant.
863
864   // Skip digits, we have at least one.
865   for (; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
866     /*empty*/;
867
868   // Check to see if this really is a label afterall, e.g. "-1:".
869   if (isLabelChar(CurPtr[0]) || CurPtr[0] == ':') {
870     if (const char *End = isLabelTail(CurPtr)) {
871       StrVal.assign(TokStart, End-1);
872       CurPtr = End;
873       return lltok::LabelStr;
874     }
875   }
876
877   // If the next character is a '.', then it is a fp value, otherwise its
878   // integer.
879   if (CurPtr[0] != '.') {
880     if (TokStart[0] == '0' && TokStart[1] == 'x')
881       return Lex0x();
882     unsigned Len = CurPtr-TokStart;
883     uint32_t numBits = ((Len * 64) / 19) + 2;
884     APInt Tmp(numBits, StringRef(TokStart, Len), 10);
885     if (TokStart[0] == '-') {
886       uint32_t minBits = Tmp.getMinSignedBits();
887       if (minBits > 0 && minBits < numBits)
888         Tmp = Tmp.trunc(minBits);
889       APSIntVal = APSInt(Tmp, false);
890     } else {
891       uint32_t activeBits = Tmp.getActiveBits();
892       if (activeBits > 0 && activeBits < numBits)
893         Tmp = Tmp.trunc(activeBits);
894       APSIntVal = APSInt(Tmp, true);
895     }
896     return lltok::APSInt;
897   }
898
899   ++CurPtr;
900
901   // Skip over [0-9]*([eE][-+]?[0-9]+)?
902   while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
903
904   if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
905     if (isdigit(static_cast<unsigned char>(CurPtr[1])) ||
906         ((CurPtr[1] == '-' || CurPtr[1] == '+') &&
907           isdigit(static_cast<unsigned char>(CurPtr[2])))) {
908       CurPtr += 2;
909       while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
910     }
911   }
912
913   APFloatVal = APFloat(std::atof(TokStart));
914   return lltok::APFloat;
915 }
916
917 ///    FPConstant  [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
918 lltok::Kind LLLexer::LexPositive() {
919   // If the letter after the negative is a number, this is probably not a
920   // label.
921   if (!isdigit(static_cast<unsigned char>(CurPtr[0])))
922     return lltok::Error;
923
924   // Skip digits.
925   for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
926     /*empty*/;
927
928   // At this point, we need a '.'.
929   if (CurPtr[0] != '.') {
930     CurPtr = TokStart+1;
931     return lltok::Error;
932   }
933
934   ++CurPtr;
935
936   // Skip over [0-9]*([eE][-+]?[0-9]+)?
937   while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
938
939   if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
940     if (isdigit(static_cast<unsigned char>(CurPtr[1])) ||
941         ((CurPtr[1] == '-' || CurPtr[1] == '+') &&
942         isdigit(static_cast<unsigned char>(CurPtr[2])))) {
943       CurPtr += 2;
944       while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
945     }
946   }
947
948   APFloatVal = APFloat(std::atof(TokStart));
949   return lltok::APFloat;
950 }