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