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