c854031bca4948bb43d35a60fee4f21225a3c5b5
[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/DerivedTypes.h"
16 #include "llvm/Instruction.h"
17 #include "llvm/LLVMContext.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/MemoryBuffer.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/SourceMgr.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Assembly/Parser.h"
24 #include <cstdlib>
25 #include <cstring>
26 using namespace llvm;
27
28 bool LLLexer::Error(LocTy ErrorLoc, const std::string &Msg) const {
29   ErrorInfo = SM.GetMessage(ErrorLoc, Msg, "error");
30   return true;
31 }
32
33 //===----------------------------------------------------------------------===//
34 // Helper functions.
35 //===----------------------------------------------------------------------===//
36
37 // atoull - Convert an ascii string of decimal digits into the unsigned long
38 // long representation... this does not have to do input error checking,
39 // because we know that the input will be matched by a suitable regex...
40 //
41 uint64_t LLLexer::atoull(const char *Buffer, const char *End) {
42   uint64_t Result = 0;
43   for (; Buffer != End; Buffer++) {
44     uint64_t OldRes = Result;
45     Result *= 10;
46     Result += *Buffer-'0';
47     if (Result < OldRes) {  // Uh, oh, overflow detected!!!
48       Error("constant bigger than 64 bits detected!");
49       return 0;
50     }
51   }
52   return Result;
53 }
54
55 uint64_t LLLexer::HexIntToVal(const char *Buffer, const char *End) {
56   uint64_t Result = 0;
57   for (; Buffer != End; ++Buffer) {
58     uint64_t OldRes = Result;
59     Result *= 16;
60     char C = *Buffer;
61     if (C >= '0' && C <= '9')
62       Result += C-'0';
63     else if (C >= 'A' && C <= 'F')
64       Result += C-'A'+10;
65     else if (C >= 'a' && C <= 'f')
66       Result += C-'a'+10;
67
68     if (Result < OldRes) {   // Uh, oh, overflow detected!!!
69       Error("constant bigger than 64 bits detected!");
70       return 0;
71     }
72   }
73   return Result;
74 }
75
76 void LLLexer::HexToIntPair(const char *Buffer, const char *End,
77                            uint64_t Pair[2]) {
78   Pair[0] = 0;
79   for (int i=0; i<16; i++, Buffer++) {
80     assert(Buffer != End);
81     Pair[0] *= 16;
82     char C = *Buffer;
83     if (C >= '0' && C <= '9')
84       Pair[0] += C-'0';
85     else if (C >= 'A' && C <= 'F')
86       Pair[0] += C-'A'+10;
87     else if (C >= 'a' && C <= 'f')
88       Pair[0] += C-'a'+10;
89   }
90   Pair[1] = 0;
91   for (int i=0; i<16 && Buffer != End; i++, Buffer++) {
92     Pair[1] *= 16;
93     char C = *Buffer;
94     if (C >= '0' && C <= '9')
95       Pair[1] += C-'0';
96     else if (C >= 'A' && C <= 'F')
97       Pair[1] += C-'A'+10;
98     else if (C >= 'a' && C <= 'f')
99       Pair[1] += C-'a'+10;
100   }
101   if (Buffer != End)
102     Error("constant bigger than 128 bits detected!");
103 }
104
105 /// FP80HexToIntPair - translate an 80 bit FP80 number (20 hexits) into
106 /// { low64, high16 } as usual for an APInt.
107 void LLLexer::FP80HexToIntPair(const char *Buffer, const char *End,
108                            uint64_t Pair[2]) {
109   Pair[1] = 0;
110   for (int i=0; i<4 && Buffer != End; i++, Buffer++) {
111     assert(Buffer != End);
112     Pair[1] *= 16;
113     char C = *Buffer;
114     if (C >= '0' && C <= '9')
115       Pair[1] += C-'0';
116     else if (C >= 'A' && C <= 'F')
117       Pair[1] += C-'A'+10;
118     else if (C >= 'a' && C <= 'f')
119       Pair[1] += C-'a'+10;
120   }
121   Pair[0] = 0;
122   for (int i=0; i<16; i++, Buffer++) {
123     Pair[0] *= 16;
124     char C = *Buffer;
125     if (C >= '0' && C <= '9')
126       Pair[0] += C-'0';
127     else if (C >= 'A' && C <= 'F')
128       Pair[0] += C-'A'+10;
129     else if (C >= 'a' && C <= 'f')
130       Pair[0] += C-'a'+10;
131   }
132   if (Buffer != End)
133     Error("constant bigger than 128 bits detected!");
134 }
135
136 // UnEscapeLexed - Run through the specified buffer and change \xx codes to the
137 // appropriate character.
138 static void UnEscapeLexed(std::string &Str) {
139   if (Str.empty()) return;
140
141   char *Buffer = &Str[0], *EndBuffer = Buffer+Str.size();
142   char *BOut = Buffer;
143   for (char *BIn = Buffer; BIn != EndBuffer; ) {
144     if (BIn[0] == '\\') {
145       if (BIn < EndBuffer-1 && BIn[1] == '\\') {
146         *BOut++ = '\\'; // Two \ becomes one
147         BIn += 2;
148       } else if (BIn < EndBuffer-2 && isxdigit(BIn[1]) && isxdigit(BIn[2])) {
149         char Tmp = BIn[3]; BIn[3] = 0;      // Terminate string
150         *BOut = (char)strtol(BIn+1, 0, 16); // Convert to number
151         BIn[3] = Tmp;                       // Restore character
152         BIn += 3;                           // Skip over handled chars
153         ++BOut;
154       } else {
155         *BOut++ = *BIn++;
156       }
157     } else {
158       *BOut++ = *BIn++;
159     }
160   }
161   Str.resize(BOut-Buffer);
162 }
163
164 /// isLabelChar - Return true for [-a-zA-Z$._0-9].
165 static bool isLabelChar(char C) {
166   return isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_';
167 }
168
169
170 /// isLabelTail - Return true if this pointer points to a valid end of a label.
171 static const char *isLabelTail(const char *CurPtr) {
172   while (1) {
173     if (CurPtr[0] == ':') return CurPtr+1;
174     if (!isLabelChar(CurPtr[0])) return 0;
175     ++CurPtr;
176   }
177 }
178
179
180
181 //===----------------------------------------------------------------------===//
182 // Lexer definition.
183 //===----------------------------------------------------------------------===//
184
185 LLLexer::LLLexer(MemoryBuffer *StartBuf, SourceMgr &sm, SMDiagnostic &Err,
186                  LLVMContext &C)
187   : CurBuf(StartBuf), ErrorInfo(Err), SM(sm), Context(C), APFloatVal(0.0) {
188   CurPtr = CurBuf->getBufferStart();
189 }
190
191 std::string LLLexer::getFilename() const {
192   return CurBuf->getBufferIdentifier();
193 }
194
195 int LLLexer::getNextChar() {
196   char CurChar = *CurPtr++;
197   switch (CurChar) {
198   default: return (unsigned char)CurChar;
199   case 0:
200     // A nul character in the stream is either the end of the current buffer or
201     // a random nul in the file.  Disambiguate that here.
202     if (CurPtr-1 != CurBuf->getBufferEnd())
203       return 0;  // Just whitespace.
204
205     // Otherwise, return end of file.
206     --CurPtr;  // Another call to lex will return EOF again.
207     return EOF;
208   }
209 }
210
211
212 lltok::Kind LLLexer::LexToken() {
213   TokStart = CurPtr;
214
215   int CurChar = getNextChar();
216   switch (CurChar) {
217   default:
218     // Handle letters: [a-zA-Z_]
219     if (isalpha(CurChar) || CurChar == '_')
220       return LexIdentifier();
221
222     return lltok::Error;
223   case EOF: return lltok::Eof;
224   case 0:
225   case ' ':
226   case '\t':
227   case '\n':
228   case '\r':
229     // Ignore whitespace.
230     return LexToken();
231   case '+': return LexPositive();
232   case '@': return LexAt();
233   case '%': return LexPercent();
234   case '"': return LexQuote();
235   case '.':
236     if (const char *Ptr = isLabelTail(CurPtr)) {
237       CurPtr = Ptr;
238       StrVal.assign(TokStart, CurPtr-1);
239       return lltok::LabelStr;
240     }
241     if (CurPtr[0] == '.' && CurPtr[1] == '.') {
242       CurPtr += 2;
243       return lltok::dotdotdot;
244     }
245     return lltok::Error;
246   case '$':
247     if (const char *Ptr = isLabelTail(CurPtr)) {
248       CurPtr = Ptr;
249       StrVal.assign(TokStart, CurPtr-1);
250       return lltok::LabelStr;
251     }
252     return lltok::Error;
253   case ';':
254     SkipLineComment();
255     return LexToken();
256   case '!': return lltok::Metadata;
257   case '0': case '1': case '2': case '3': case '4':
258   case '5': case '6': case '7': case '8': case '9':
259   case '-':
260     return LexDigitOrNegative();
261   case '=': return lltok::equal;
262   case '[': return lltok::lsquare;
263   case ']': return lltok::rsquare;
264   case '{': return lltok::lbrace;
265   case '}': return lltok::rbrace;
266   case '<': return lltok::less;
267   case '>': return lltok::greater;
268   case '(': return lltok::lparen;
269   case ')': return lltok::rparen;
270   case ',': return lltok::comma;
271   case '*': return lltok::star;
272   case '\\': return lltok::backslash;
273   }
274 }
275
276 void LLLexer::SkipLineComment() {
277   while (1) {
278     if (CurPtr[0] == '\n' || CurPtr[0] == '\r' || getNextChar() == EOF)
279       return;
280   }
281 }
282
283 /// LexAt - Lex all tokens that start with an @ character:
284 ///   GlobalVar   @\"[^\"]*\"
285 ///   GlobalVar   @[-a-zA-Z$._][-a-zA-Z$._0-9]*
286 ///   GlobalVarID @[0-9]+
287 lltok::Kind LLLexer::LexAt() {
288   // Handle AtStringConstant: @\"[^\"]*\"
289   if (CurPtr[0] == '"') {
290     ++CurPtr;
291
292     while (1) {
293       int CurChar = getNextChar();
294
295       if (CurChar == EOF) {
296         Error("end of file in global variable name");
297         return lltok::Error;
298       }
299       if (CurChar == '"') {
300         StrVal.assign(TokStart+2, CurPtr-1);
301         UnEscapeLexed(StrVal);
302         return lltok::GlobalVar;
303       }
304     }
305   }
306
307   // Handle GlobalVarName: @[-a-zA-Z$._][-a-zA-Z$._0-9]*
308   if (isalpha(CurPtr[0]) || CurPtr[0] == '-' || CurPtr[0] == '$' ||
309       CurPtr[0] == '.' || CurPtr[0] == '_') {
310     ++CurPtr;
311     while (isalnum(CurPtr[0]) || CurPtr[0] == '-' || CurPtr[0] == '$' ||
312            CurPtr[0] == '.' || CurPtr[0] == '_')
313       ++CurPtr;
314
315     StrVal.assign(TokStart+1, CurPtr);   // Skip @
316     return lltok::GlobalVar;
317   }
318
319   // Handle GlobalVarID: @[0-9]+
320   if (isdigit(CurPtr[0])) {
321     for (++CurPtr; isdigit(CurPtr[0]); ++CurPtr)
322       /*empty*/;
323
324     uint64_t Val = atoull(TokStart+1, CurPtr);
325     if ((unsigned)Val != Val)
326       Error("invalid value number (too large)!");
327     UIntVal = unsigned(Val);
328     return lltok::GlobalID;
329   }
330
331   return lltok::Error;
332 }
333
334
335 /// LexPercent - Lex all tokens that start with a % character:
336 ///   LocalVar   ::= %\"[^\"]*\"
337 ///   LocalVar   ::= %[-a-zA-Z$._][-a-zA-Z$._0-9]*
338 ///   LocalVarID ::= %[0-9]+
339 lltok::Kind LLLexer::LexPercent() {
340   // Handle LocalVarName: %\"[^\"]*\"
341   if (CurPtr[0] == '"') {
342     ++CurPtr;
343
344     while (1) {
345       int CurChar = getNextChar();
346
347       if (CurChar == EOF) {
348         Error("end of file in string constant");
349         return lltok::Error;
350       }
351       if (CurChar == '"') {
352         StrVal.assign(TokStart+2, CurPtr-1);
353         UnEscapeLexed(StrVal);
354         return lltok::LocalVar;
355       }
356     }
357   }
358
359   // Handle LocalVarName: %[-a-zA-Z$._][-a-zA-Z$._0-9]*
360   if (isalpha(CurPtr[0]) || CurPtr[0] == '-' || CurPtr[0] == '$' ||
361       CurPtr[0] == '.' || CurPtr[0] == '_') {
362     ++CurPtr;
363     while (isalnum(CurPtr[0]) || CurPtr[0] == '-' || CurPtr[0] == '$' ||
364            CurPtr[0] == '.' || CurPtr[0] == '_')
365       ++CurPtr;
366
367     StrVal.assign(TokStart+1, CurPtr);   // Skip %
368     return lltok::LocalVar;
369   }
370
371   // Handle LocalVarID: %[0-9]+
372   if (isdigit(CurPtr[0])) {
373     for (++CurPtr; isdigit(CurPtr[0]); ++CurPtr)
374       /*empty*/;
375
376     uint64_t Val = atoull(TokStart+1, CurPtr);
377     if ((unsigned)Val != Val)
378       Error("invalid value number (too large)!");
379     UIntVal = unsigned(Val);
380     return lltok::LocalVarID;
381   }
382
383   return lltok::Error;
384 }
385
386 /// LexQuote - Lex all tokens that start with a " character:
387 ///   QuoteLabel        "[^"]+":
388 ///   StringConstant    "[^"]*"
389 lltok::Kind LLLexer::LexQuote() {
390   while (1) {
391     int CurChar = getNextChar();
392
393     if (CurChar == EOF) {
394       Error("end of file in quoted string");
395       return lltok::Error;
396     }
397
398     if (CurChar != '"') continue;
399
400     if (CurPtr[0] != ':') {
401       StrVal.assign(TokStart+1, CurPtr-1);
402       UnEscapeLexed(StrVal);
403       return lltok::StringConstant;
404     }
405
406     ++CurPtr;
407     StrVal.assign(TokStart+1, CurPtr-2);
408     UnEscapeLexed(StrVal);
409     return lltok::LabelStr;
410   }
411 }
412
413 static bool JustWhitespaceNewLine(const char *&Ptr) {
414   const char *ThisPtr = Ptr;
415   while (*ThisPtr == ' ' || *ThisPtr == '\t')
416     ++ThisPtr;
417   if (*ThisPtr == '\n' || *ThisPtr == '\r') {
418     Ptr = ThisPtr;
419     return true;
420   }
421   return false;
422 }
423
424
425 /// LexIdentifier: Handle several related productions:
426 ///    Label           [-a-zA-Z$._0-9]+:
427 ///    IntegerType     i[0-9]+
428 ///    Keyword         sdiv, float, ...
429 ///    HexIntConstant  [us]0x[0-9A-Fa-f]+
430 lltok::Kind LLLexer::LexIdentifier() {
431   const char *StartChar = CurPtr;
432   const char *IntEnd = CurPtr[-1] == 'i' ? 0 : StartChar;
433   const char *KeywordEnd = 0;
434
435   for (; isLabelChar(*CurPtr); ++CurPtr) {
436     // If we decide this is an integer, remember the end of the sequence.
437     if (!IntEnd && !isdigit(*CurPtr)) IntEnd = CurPtr;
438     if (!KeywordEnd && !isalnum(*CurPtr) && *CurPtr != '_') KeywordEnd = CurPtr;
439   }
440
441   // If we stopped due to a colon, this really is a label.
442   if (*CurPtr == ':') {
443     StrVal.assign(StartChar-1, CurPtr++);
444     return lltok::LabelStr;
445   }
446
447   // Otherwise, this wasn't a label.  If this was valid as an integer type,
448   // return it.
449   if (IntEnd == 0) IntEnd = CurPtr;
450   if (IntEnd != StartChar) {
451     CurPtr = IntEnd;
452     uint64_t NumBits = atoull(StartChar, CurPtr);
453     if (NumBits < IntegerType::MIN_INT_BITS ||
454         NumBits > IntegerType::MAX_INT_BITS) {
455       Error("bitwidth for integer type out of range!");
456       return lltok::Error;
457     }
458     TyVal = Context.getIntegerType(NumBits);
459     return lltok::Type;
460   }
461
462   // Otherwise, this was a letter sequence.  See which keyword this is.
463   if (KeywordEnd == 0) KeywordEnd = CurPtr;
464   CurPtr = KeywordEnd;
465   --StartChar;
466   unsigned Len = CurPtr-StartChar;
467 #define KEYWORD(STR) \
468   if (Len == strlen(#STR) && !memcmp(StartChar, #STR, strlen(#STR))) \
469     return lltok::kw_##STR;
470
471   KEYWORD(begin);   KEYWORD(end);
472   KEYWORD(true);    KEYWORD(false);
473   KEYWORD(declare); KEYWORD(define);
474   KEYWORD(global);  KEYWORD(constant);
475
476   KEYWORD(private);
477   KEYWORD(internal);
478   KEYWORD(available_externally);
479   KEYWORD(linkonce);
480   KEYWORD(linkonce_odr);
481   KEYWORD(weak);
482   KEYWORD(weak_odr);
483   KEYWORD(appending);
484   KEYWORD(dllimport);
485   KEYWORD(dllexport);
486   KEYWORD(common);
487   KEYWORD(default);
488   KEYWORD(hidden);
489   KEYWORD(protected);
490   KEYWORD(extern_weak);
491   KEYWORD(external);
492   KEYWORD(thread_local);
493   KEYWORD(zeroinitializer);
494   KEYWORD(undef);
495   KEYWORD(null);
496   KEYWORD(to);
497   KEYWORD(tail);
498   KEYWORD(target);
499   KEYWORD(triple);
500   KEYWORD(deplibs);
501   KEYWORD(datalayout);
502   KEYWORD(volatile);
503   KEYWORD(align);
504   KEYWORD(addrspace);
505   KEYWORD(section);
506   KEYWORD(alias);
507   KEYWORD(module);
508   KEYWORD(asm);
509   KEYWORD(sideeffect);
510   KEYWORD(gc);
511
512   KEYWORD(ccc);
513   KEYWORD(fastcc);
514   KEYWORD(coldcc);
515   KEYWORD(x86_stdcallcc);
516   KEYWORD(x86_fastcallcc);
517   KEYWORD(arm_apcscc);
518   KEYWORD(arm_aapcscc);
519   KEYWORD(arm_aapcs_vfpcc);
520
521   KEYWORD(cc);
522   KEYWORD(c);
523
524   KEYWORD(signext);
525   KEYWORD(zeroext);
526   KEYWORD(inreg);
527   KEYWORD(sret);
528   KEYWORD(nounwind);
529   KEYWORD(noreturn);
530   KEYWORD(noalias);
531   KEYWORD(nocapture);
532   KEYWORD(byval);
533   KEYWORD(nest);
534   KEYWORD(readnone);
535   KEYWORD(readonly);
536
537   KEYWORD(noinline);
538   KEYWORD(alwaysinline);
539   KEYWORD(optsize);
540   KEYWORD(ssp);
541   KEYWORD(sspreq);
542   KEYWORD(noredzone);
543   KEYWORD(noimplicitfloat);
544
545   KEYWORD(type);
546   KEYWORD(opaque);
547
548   KEYWORD(eq); KEYWORD(ne); KEYWORD(slt); KEYWORD(sgt); KEYWORD(sle);
549   KEYWORD(sge); KEYWORD(ult); KEYWORD(ugt); KEYWORD(ule); KEYWORD(uge);
550   KEYWORD(oeq); KEYWORD(one); KEYWORD(olt); KEYWORD(ogt); KEYWORD(ole);
551   KEYWORD(oge); KEYWORD(ord); KEYWORD(uno); KEYWORD(ueq); KEYWORD(une);
552
553   KEYWORD(x);
554 #undef KEYWORD
555
556   // Keywords for types.
557 #define TYPEKEYWORD(STR, LLVMTY) \
558   if (Len == strlen(STR) && !memcmp(StartChar, STR, strlen(STR))) { \
559     TyVal = LLVMTY; return lltok::Type; }
560   TYPEKEYWORD("void",      Type::VoidTy);
561   TYPEKEYWORD("float",     Type::FloatTy);
562   TYPEKEYWORD("double",    Type::DoubleTy);
563   TYPEKEYWORD("x86_fp80",  Type::X86_FP80Ty);
564   TYPEKEYWORD("fp128",     Type::FP128Ty);
565   TYPEKEYWORD("ppc_fp128", Type::PPC_FP128Ty);
566   TYPEKEYWORD("label",     Type::LabelTy);
567   TYPEKEYWORD("metadata",  Type::MetadataTy);
568 #undef TYPEKEYWORD
569
570   // Handle special forms for autoupgrading.  Drop these in LLVM 3.0.  This is
571   // to avoid conflicting with the sext/zext instructions, below.
572   if (Len == 4 && !memcmp(StartChar, "sext", 4)) {
573     // Scan CurPtr ahead, seeing if there is just whitespace before the newline.
574     if (JustWhitespaceNewLine(CurPtr))
575       return lltok::kw_signext;
576   } else if (Len == 4 && !memcmp(StartChar, "zext", 4)) {
577     // Scan CurPtr ahead, seeing if there is just whitespace before the newline.
578     if (JustWhitespaceNewLine(CurPtr))
579       return lltok::kw_zeroext;
580   }
581
582   // Keywords for instructions.
583 #define INSTKEYWORD(STR, Enum) \
584   if (Len == strlen(#STR) && !memcmp(StartChar, #STR, strlen(#STR))) { \
585     UIntVal = Instruction::Enum; return lltok::kw_##STR; }
586
587   INSTKEYWORD(add,   Add);  INSTKEYWORD(fadd,   FAdd);
588   INSTKEYWORD(sub,   Sub);  INSTKEYWORD(fsub,   FSub);
589   INSTKEYWORD(mul,   Mul);  INSTKEYWORD(fmul,   FMul);
590   INSTKEYWORD(udiv,  UDiv); INSTKEYWORD(sdiv,  SDiv); INSTKEYWORD(fdiv,  FDiv);
591   INSTKEYWORD(urem,  URem); INSTKEYWORD(srem,  SRem); INSTKEYWORD(frem,  FRem);
592   INSTKEYWORD(shl,   Shl);  INSTKEYWORD(lshr,  LShr); INSTKEYWORD(ashr,  AShr);
593   INSTKEYWORD(and,   And);  INSTKEYWORD(or,    Or);   INSTKEYWORD(xor,   Xor);
594   INSTKEYWORD(icmp,  ICmp); INSTKEYWORD(fcmp,  FCmp);
595
596   INSTKEYWORD(phi,         PHI);
597   INSTKEYWORD(call,        Call);
598   INSTKEYWORD(trunc,       Trunc);
599   INSTKEYWORD(zext,        ZExt);
600   INSTKEYWORD(sext,        SExt);
601   INSTKEYWORD(fptrunc,     FPTrunc);
602   INSTKEYWORD(fpext,       FPExt);
603   INSTKEYWORD(uitofp,      UIToFP);
604   INSTKEYWORD(sitofp,      SIToFP);
605   INSTKEYWORD(fptoui,      FPToUI);
606   INSTKEYWORD(fptosi,      FPToSI);
607   INSTKEYWORD(inttoptr,    IntToPtr);
608   INSTKEYWORD(ptrtoint,    PtrToInt);
609   INSTKEYWORD(bitcast,     BitCast);
610   INSTKEYWORD(select,      Select);
611   INSTKEYWORD(va_arg,      VAArg);
612   INSTKEYWORD(ret,         Ret);
613   INSTKEYWORD(br,          Br);
614   INSTKEYWORD(switch,      Switch);
615   INSTKEYWORD(invoke,      Invoke);
616   INSTKEYWORD(unwind,      Unwind);
617   INSTKEYWORD(unreachable, Unreachable);
618
619   INSTKEYWORD(malloc,      Malloc);
620   INSTKEYWORD(alloca,      Alloca);
621   INSTKEYWORD(free,        Free);
622   INSTKEYWORD(load,        Load);
623   INSTKEYWORD(store,       Store);
624   INSTKEYWORD(getelementptr, GetElementPtr);
625
626   INSTKEYWORD(extractelement, ExtractElement);
627   INSTKEYWORD(insertelement,  InsertElement);
628   INSTKEYWORD(shufflevector,  ShuffleVector);
629   INSTKEYWORD(getresult,      ExtractValue);
630   INSTKEYWORD(extractvalue,   ExtractValue);
631   INSTKEYWORD(insertvalue,    InsertValue);
632 #undef INSTKEYWORD
633
634   // Check for [us]0x[0-9A-Fa-f]+ which are Hexadecimal constant generated by
635   // the CFE to avoid forcing it to deal with 64-bit numbers.
636   if ((TokStart[0] == 'u' || TokStart[0] == 's') &&
637       TokStart[1] == '0' && TokStart[2] == 'x' && isxdigit(TokStart[3])) {
638     int len = CurPtr-TokStart-3;
639     uint32_t bits = len * 4;
640     APInt Tmp(bits, TokStart+3, len, 16);
641     uint32_t activeBits = Tmp.getActiveBits();
642     if (activeBits > 0 && activeBits < bits)
643       Tmp.trunc(activeBits);
644     APSIntVal = APSInt(Tmp, TokStart[0] == 'u');
645     return lltok::APSInt;
646   }
647
648   // If this is "cc1234", return this as just "cc".
649   if (TokStart[0] == 'c' && TokStart[1] == 'c') {
650     CurPtr = TokStart+2;
651     return lltok::kw_cc;
652   }
653
654   // If this starts with "call", return it as CALL.  This is to support old
655   // broken .ll files.  FIXME: remove this with LLVM 3.0.
656   if (CurPtr-TokStart > 4 && !memcmp(TokStart, "call", 4)) {
657     CurPtr = TokStart+4;
658     UIntVal = Instruction::Call;
659     return lltok::kw_call;
660   }
661
662   // Finally, if this isn't known, return an error.
663   CurPtr = TokStart+1;
664   return lltok::Error;
665 }
666
667
668 /// Lex0x: Handle productions that start with 0x, knowing that it matches and
669 /// that this is not a label:
670 ///    HexFPConstant     0x[0-9A-Fa-f]+
671 ///    HexFP80Constant   0xK[0-9A-Fa-f]+
672 ///    HexFP128Constant  0xL[0-9A-Fa-f]+
673 ///    HexPPC128Constant 0xM[0-9A-Fa-f]+
674 lltok::Kind LLLexer::Lex0x() {
675   CurPtr = TokStart + 2;
676
677   char Kind;
678   if (CurPtr[0] >= 'K' && CurPtr[0] <= 'M') {
679     Kind = *CurPtr++;
680   } else {
681     Kind = 'J';
682   }
683
684   if (!isxdigit(CurPtr[0])) {
685     // Bad token, return it as an error.
686     CurPtr = TokStart+1;
687     return lltok::Error;
688   }
689
690   while (isxdigit(CurPtr[0]))
691     ++CurPtr;
692
693   if (Kind == 'J') {
694     // HexFPConstant - Floating point constant represented in IEEE format as a
695     // hexadecimal number for when exponential notation is not precise enough.
696     // Float and double only.
697     APFloatVal = APFloat(BitsToDouble(HexIntToVal(TokStart+2, CurPtr)));
698     return lltok::APFloat;
699   }
700
701   uint64_t Pair[2];
702   switch (Kind) {
703   default: LLVM_UNREACHABLE("Unknown kind!");
704   case 'K':
705     // F80HexFPConstant - x87 long double in hexadecimal format (10 bytes)
706     FP80HexToIntPair(TokStart+3, CurPtr, Pair);
707     APFloatVal = APFloat(APInt(80, 2, Pair));
708     return lltok::APFloat;
709   case 'L':
710     // F128HexFPConstant - IEEE 128-bit in hexadecimal format (16 bytes)
711     HexToIntPair(TokStart+3, CurPtr, Pair);
712     APFloatVal = APFloat(APInt(128, 2, Pair), true);
713     return lltok::APFloat;
714   case 'M':
715     // PPC128HexFPConstant - PowerPC 128-bit in hexadecimal format (16 bytes)
716     HexToIntPair(TokStart+3, CurPtr, Pair);
717     APFloatVal = APFloat(APInt(128, 2, Pair));
718     return lltok::APFloat;
719   }
720 }
721
722 /// LexIdentifier: Handle several related productions:
723 ///    Label             [-a-zA-Z$._0-9]+:
724 ///    NInteger          -[0-9]+
725 ///    FPConstant        [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
726 ///    PInteger          [0-9]+
727 ///    HexFPConstant     0x[0-9A-Fa-f]+
728 ///    HexFP80Constant   0xK[0-9A-Fa-f]+
729 ///    HexFP128Constant  0xL[0-9A-Fa-f]+
730 ///    HexPPC128Constant 0xM[0-9A-Fa-f]+
731 lltok::Kind LLLexer::LexDigitOrNegative() {
732   // If the letter after the negative is a number, this is probably a label.
733   if (!isdigit(TokStart[0]) && !isdigit(CurPtr[0])) {
734     // Okay, this is not a number after the -, it's probably a label.
735     if (const char *End = isLabelTail(CurPtr)) {
736       StrVal.assign(TokStart, End-1);
737       CurPtr = End;
738       return lltok::LabelStr;
739     }
740
741     return lltok::Error;
742   }
743
744   // At this point, it is either a label, int or fp constant.
745
746   // Skip digits, we have at least one.
747   for (; isdigit(CurPtr[0]); ++CurPtr)
748     /*empty*/;
749
750   // Check to see if this really is a label afterall, e.g. "-1:".
751   if (isLabelChar(CurPtr[0]) || CurPtr[0] == ':') {
752     if (const char *End = isLabelTail(CurPtr)) {
753       StrVal.assign(TokStart, End-1);
754       CurPtr = End;
755       return lltok::LabelStr;
756     }
757   }
758
759   // If the next character is a '.', then it is a fp value, otherwise its
760   // integer.
761   if (CurPtr[0] != '.') {
762     if (TokStart[0] == '0' && TokStart[1] == 'x')
763       return Lex0x();
764     unsigned Len = CurPtr-TokStart;
765     uint32_t numBits = ((Len * 64) / 19) + 2;
766     APInt Tmp(numBits, TokStart, Len, 10);
767     if (TokStart[0] == '-') {
768       uint32_t minBits = Tmp.getMinSignedBits();
769       if (minBits > 0 && minBits < numBits)
770         Tmp.trunc(minBits);
771       APSIntVal = APSInt(Tmp, false);
772     } else {
773       uint32_t activeBits = Tmp.getActiveBits();
774       if (activeBits > 0 && activeBits < numBits)
775         Tmp.trunc(activeBits);
776       APSIntVal = APSInt(Tmp, true);
777     }
778     return lltok::APSInt;
779   }
780
781   ++CurPtr;
782
783   // Skip over [0-9]*([eE][-+]?[0-9]+)?
784   while (isdigit(CurPtr[0])) ++CurPtr;
785
786   if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
787     if (isdigit(CurPtr[1]) ||
788         ((CurPtr[1] == '-' || CurPtr[1] == '+') && isdigit(CurPtr[2]))) {
789       CurPtr += 2;
790       while (isdigit(CurPtr[0])) ++CurPtr;
791     }
792   }
793
794   APFloatVal = APFloat(atof(TokStart));
795   return lltok::APFloat;
796 }
797
798 ///    FPConstant  [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
799 lltok::Kind LLLexer::LexPositive() {
800   // If the letter after the negative is a number, this is probably not a
801   // label.
802   if (!isdigit(CurPtr[0]))
803     return lltok::Error;
804
805   // Skip digits.
806   for (++CurPtr; isdigit(CurPtr[0]); ++CurPtr)
807     /*empty*/;
808
809   // At this point, we need a '.'.
810   if (CurPtr[0] != '.') {
811     CurPtr = TokStart+1;
812     return lltok::Error;
813   }
814
815   ++CurPtr;
816
817   // Skip over [0-9]*([eE][-+]?[0-9]+)?
818   while (isdigit(CurPtr[0])) ++CurPtr;
819
820   if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
821     if (isdigit(CurPtr[1]) ||
822         ((CurPtr[1] == '-' || CurPtr[1] == '+') && isdigit(CurPtr[2]))) {
823       CurPtr += 2;
824       while (isdigit(CurPtr[0])) ++CurPtr;
825     }
826   }
827
828   APFloatVal = APFloat(atof(TokStart));
829   return lltok::APFloat;
830 }