Preprocessor.cpp revision 7e0fbb2561fadf8c1fce5fdb588f5db2f3cae51f
1//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===// 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// This file implements the Preprocessor interface. 11// 12//===----------------------------------------------------------------------===// 13// 14// Options to support: 15// -H - Print the name of each header file used. 16// -d[MDNI] - Dump various things. 17// -fworking-directory - #line's with preprocessor's working dir. 18// -fpreprocessed 19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD 20// -W* 21// -w 22// 23// Messages to emit: 24// "Multiple include guards may be useful for:\n" 25// 26//===----------------------------------------------------------------------===// 27 28#include "clang/Lex/Preprocessor.h" 29#include "clang/Lex/HeaderSearch.h" 30#include "clang/Lex/MacroInfo.h" 31#include "clang/Lex/Pragma.h" 32#include "clang/Lex/ScratchBuffer.h" 33#include "clang/Basic/Diagnostic.h" 34#include "clang/Basic/SourceManager.h" 35#include "clang/Basic/TargetInfo.h" 36#include "llvm/ADT/APFloat.h" 37#include "llvm/ADT/SmallVector.h" 38#include "llvm/Support/MemoryBuffer.h" 39#include "llvm/Support/Streams.h" 40using namespace clang; 41 42//===----------------------------------------------------------------------===// 43 44PreprocessorFactory::~PreprocessorFactory() {} 45 46Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts, 47 TargetInfo &target, SourceManager &SM, 48 HeaderSearch &Headers) 49 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()), 50 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts), 51 CurPPLexer(0), CurDirLookup(0), Callbacks(0) { 52 ScratchBuf = new ScratchBuffer(SourceMgr); 53 54 // Clear stats. 55 NumDirectives = NumDefined = NumUndefined = NumPragma = 0; 56 NumIf = NumElse = NumEndif = 0; 57 NumEnteredSourceFiles = 0; 58 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0; 59 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0; 60 MaxIncludeStackDepth = 0; 61 NumSkipped = 0; 62 63 // Default to discarding comments. 64 KeepComments = false; 65 KeepMacroComments = false; 66 67 // Macro expansion is enabled. 68 DisableMacroExpansion = false; 69 InMacroArgs = false; 70 NumCachedTokenLexers = 0; 71 72 CachedLexPos = 0; 73 74 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro. 75 // This gets unpoisoned where it is allowed. 76 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned(); 77 78 // Initialize the pragma handlers. 79 PragmaHandlers = new PragmaNamespace(0); 80 RegisterBuiltinPragmas(); 81 82 // Initialize builtin macros like __LINE__ and friends. 83 RegisterBuiltinMacros(); 84} 85 86Preprocessor::~Preprocessor() { 87 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!"); 88 89 while (!IncludeMacroStack.empty()) { 90 delete IncludeMacroStack.back().TheLexer; 91 delete IncludeMacroStack.back().TheTokenLexer; 92 IncludeMacroStack.pop_back(); 93 } 94 95 // Free any macro definitions. 96 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I = 97 Macros.begin(), E = Macros.end(); I != E; ++I) { 98 // We don't need to free the MacroInfo objects directly. These 99 // will be released when the BumpPtrAllocator 'BP' object gets 100 // destroyed. 101 I->first->setHasMacroDefinition(false); 102 } 103 104 // Free any cached macro expanders. 105 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i) 106 delete TokenLexerCache[i]; 107 108 // Release pragma information. 109 delete PragmaHandlers; 110 111 // Delete the scratch buffer info. 112 delete ScratchBuf; 113 114 delete Callbacks; 115} 116 117void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const { 118 llvm::cerr << tok::getTokenName(Tok.getKind()) << " '" 119 << getSpelling(Tok) << "'"; 120 121 if (!DumpFlags) return; 122 123 llvm::cerr << "\t"; 124 if (Tok.isAtStartOfLine()) 125 llvm::cerr << " [StartOfLine]"; 126 if (Tok.hasLeadingSpace()) 127 llvm::cerr << " [LeadingSpace]"; 128 if (Tok.isExpandDisabled()) 129 llvm::cerr << " [ExpandDisabled]"; 130 if (Tok.needsCleaning()) { 131 const char *Start = SourceMgr.getCharacterData(Tok.getLocation()); 132 llvm::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength()) 133 << "']"; 134 } 135 136 llvm::cerr << "\tLoc=<"; 137 DumpLocation(Tok.getLocation()); 138 llvm::cerr << ">"; 139} 140 141void Preprocessor::DumpLocation(SourceLocation Loc) const { 142 SourceLocation LogLoc = SourceMgr.getLogicalLoc(Loc); 143 llvm::cerr << SourceMgr.getSourceName(LogLoc) << ':' 144 << SourceMgr.getLineNumber(LogLoc) << ':' 145 << SourceMgr.getColumnNumber(LogLoc); 146 147 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(Loc); 148 if (PhysLoc != LogLoc) { 149 llvm::cerr << " <PhysLoc="; 150 DumpLocation(PhysLoc); 151 llvm::cerr << ">"; 152 } 153} 154 155void Preprocessor::DumpMacro(const MacroInfo &MI) const { 156 llvm::cerr << "MACRO: "; 157 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) { 158 DumpToken(MI.getReplacementToken(i)); 159 llvm::cerr << " "; 160 } 161 llvm::cerr << "\n"; 162} 163 164void Preprocessor::PrintStats() { 165 llvm::cerr << "\n*** Preprocessor Stats:\n"; 166 llvm::cerr << NumDirectives << " directives found:\n"; 167 llvm::cerr << " " << NumDefined << " #define.\n"; 168 llvm::cerr << " " << NumUndefined << " #undef.\n"; 169 llvm::cerr << " #include/#include_next/#import:\n"; 170 llvm::cerr << " " << NumEnteredSourceFiles << " source files entered.\n"; 171 llvm::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n"; 172 llvm::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n"; 173 llvm::cerr << " " << NumElse << " #else/#elif.\n"; 174 llvm::cerr << " " << NumEndif << " #endif.\n"; 175 llvm::cerr << " " << NumPragma << " #pragma.\n"; 176 llvm::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n"; 177 178 llvm::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/" 179 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, " 180 << NumFastMacroExpanded << " on the fast path.\n"; 181 llvm::cerr << (NumFastTokenPaste+NumTokenPaste) 182 << " token paste (##) operations performed, " 183 << NumFastTokenPaste << " on the fast path.\n"; 184} 185 186//===----------------------------------------------------------------------===// 187// Token Spelling 188//===----------------------------------------------------------------------===// 189 190 191/// getSpelling() - Return the 'spelling' of this token. The spelling of a 192/// token are the characters used to represent the token in the source file 193/// after trigraph expansion and escaped-newline folding. In particular, this 194/// wants to get the true, uncanonicalized, spelling of things like digraphs 195/// UCNs, etc. 196std::string Preprocessor::getSpelling(const Token &Tok) const { 197 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!"); 198 199 // If this token contains nothing interesting, return it directly. 200 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation()); 201 if (!Tok.needsCleaning()) 202 return std::string(TokStart, TokStart+Tok.getLength()); 203 204 std::string Result; 205 Result.reserve(Tok.getLength()); 206 207 // Otherwise, hard case, relex the characters into the string. 208 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength(); 209 Ptr != End; ) { 210 unsigned CharSize; 211 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features)); 212 Ptr += CharSize; 213 } 214 assert(Result.size() != unsigned(Tok.getLength()) && 215 "NeedsCleaning flag set on something that didn't need cleaning!"); 216 return Result; 217} 218 219/// getSpelling - This method is used to get the spelling of a token into a 220/// preallocated buffer, instead of as an std::string. The caller is required 221/// to allocate enough space for the token, which is guaranteed to be at least 222/// Tok.getLength() bytes long. The actual length of the token is returned. 223/// 224/// Note that this method may do two possible things: it may either fill in 225/// the buffer specified with characters, or it may *change the input pointer* 226/// to point to a constant buffer with the data already in it (avoiding a 227/// copy). The caller is not allowed to modify the returned buffer pointer 228/// if an internal buffer is returned. 229unsigned Preprocessor::getSpelling(const Token &Tok, 230 const char *&Buffer) const { 231 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!"); 232 233 // If this token is an identifier, just return the string from the identifier 234 // table, which is very quick. 235 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) { 236 Buffer = II->getName(); 237 238 // Return the length of the token. If the token needed cleaning, don't 239 // include the size of the newlines or trigraphs in it. 240 if (!Tok.needsCleaning()) 241 return Tok.getLength(); 242 else 243 return strlen(Buffer); 244 } 245 246 // Otherwise, compute the start of the token in the input lexer buffer. 247 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation()); 248 249 // If this token contains nothing interesting, return it directly. 250 if (!Tok.needsCleaning()) { 251 Buffer = TokStart; 252 return Tok.getLength(); 253 } 254 // Otherwise, hard case, relex the characters into the string. 255 char *OutBuf = const_cast<char*>(Buffer); 256 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength(); 257 Ptr != End; ) { 258 unsigned CharSize; 259 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features); 260 Ptr += CharSize; 261 } 262 assert(unsigned(OutBuf-Buffer) != Tok.getLength() && 263 "NeedsCleaning flag set on something that didn't need cleaning!"); 264 265 return OutBuf-Buffer; 266} 267 268 269/// CreateString - Plop the specified string into a scratch buffer and return a 270/// location for it. If specified, the source location provides a source 271/// location for the token. 272SourceLocation Preprocessor:: 273CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) { 274 if (SLoc.isValid()) 275 return ScratchBuf->getToken(Buf, Len, SLoc); 276 return ScratchBuf->getToken(Buf, Len); 277} 278 279 280/// AdvanceToTokenCharacter - Given a location that specifies the start of a 281/// token, return a new location that specifies a character within the token. 282SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart, 283 unsigned CharNo) { 284 // If they request the first char of the token, we're trivially done. If this 285 // is a macro expansion, it doesn't make sense to point to a character within 286 // the instantiation point (the name). We could point to the source 287 // character, but without also pointing to instantiation info, this is 288 // confusing. 289 if (CharNo == 0 || TokStart.isMacroID()) return TokStart; 290 291 // Figure out how many physical characters away the specified logical 292 // character is. This needs to take into consideration newlines and 293 // trigraphs. 294 const char *TokPtr = SourceMgr.getCharacterData(TokStart); 295 unsigned PhysOffset = 0; 296 297 // The usual case is that tokens don't contain anything interesting. Skip 298 // over the uninteresting characters. If a token only consists of simple 299 // chars, this method is extremely fast. 300 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr)) 301 ++TokPtr, --CharNo, ++PhysOffset; 302 303 // If we have a character that may be a trigraph or escaped newline, create a 304 // lexer to parse it correctly. 305 if (CharNo != 0) { 306 // Create a lexer starting at this token position. 307 Lexer TheLexer(TokStart, *this, TokPtr); 308 Token Tok; 309 // Skip over characters the remaining characters. 310 const char *TokStartPtr = TokPtr; 311 for (; CharNo; --CharNo) 312 TheLexer.getAndAdvanceChar(TokPtr, Tok); 313 314 PhysOffset += TokPtr-TokStartPtr; 315 } 316 317 return TokStart.getFileLocWithOffset(PhysOffset); 318} 319 320 321//===----------------------------------------------------------------------===// 322// Preprocessor Initialization Methods 323//===----------------------------------------------------------------------===// 324 325// Append a #define line to Buf for Macro. Macro should be of the form XXX, 326// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit 327// "#define XXX Y z W". To get a #define with no value, use "XXX=". 328static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro, 329 const char *Command = "#define ") { 330 Buf.insert(Buf.end(), Command, Command+strlen(Command)); 331 if (const char *Equal = strchr(Macro, '=')) { 332 // Turn the = into ' '. 333 Buf.insert(Buf.end(), Macro, Equal); 334 Buf.push_back(' '); 335 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal)); 336 } else { 337 // Push "macroname 1". 338 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro)); 339 Buf.push_back(' '); 340 Buf.push_back('1'); 341 } 342 Buf.push_back('\n'); 343} 344 345/// PickFP - This is used to pick a value based on the FP semantics of the 346/// specified FP model. 347template <typename T> 348static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal, 349 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal) { 350 if (Sem == &llvm::APFloat::IEEEsingle) 351 return IEEESingleVal; 352 if (Sem == &llvm::APFloat::IEEEdouble) 353 return IEEEDoubleVal; 354 if (Sem == &llvm::APFloat::x87DoubleExtended) 355 return X87DoubleExtendedVal; 356 assert(Sem == &llvm::APFloat::PPCDoubleDouble); 357 return PPCDoubleDoubleVal; 358} 359 360static void DefineFloatMacros(std::vector<char> &Buf, const char *Prefix, 361 const llvm::fltSemantics *Sem) { 362 const char *DenormMin, *Epsilon, *Max, *Min; 363 DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324", 364 "3.64519953188247460253e-4951L", 365 "4.94065645841246544176568792868221e-324L"); 366 int Digits = PickFP(Sem, 6, 15, 18, 31); 367 Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16", 368 "1.08420217248550443401e-19L", 369 "4.94065645841246544176568792868221e-324L"); 370 int HasInifinity = 1, HasQuietNaN = 1; 371 int MantissaDigits = PickFP(Sem, 24, 53, 64, 106); 372 int Min10Exp = PickFP(Sem, -37, -307, -4931, -291); 373 int Max10Exp = PickFP(Sem, 38, 308, 4932, 308); 374 int MinExp = PickFP(Sem, -125, -1021, -16381, -968); 375 int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024); 376 Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308", 377 "3.36210314311209350626e-4932L", 378 "2.00416836000897277799610805135016e-292L"); 379 Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308", 380 "1.18973149535723176502e+4932L", 381 "1.79769313486231580793728971405301e+308L"); 382 383 char MacroBuf[60]; 384 sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin); 385 DefineBuiltinMacro(Buf, MacroBuf); 386 sprintf(MacroBuf, "__%s_DIG__=%d", Prefix, Digits); 387 DefineBuiltinMacro(Buf, MacroBuf); 388 sprintf(MacroBuf, "__%s_EPSILON__=%s", Prefix, Epsilon); 389 DefineBuiltinMacro(Buf, MacroBuf); 390 sprintf(MacroBuf, "__%s_HAS_INFINITY__=%d", Prefix, HasInifinity); 391 DefineBuiltinMacro(Buf, MacroBuf); 392 sprintf(MacroBuf, "__%s_HAS_QUIET_NAN__=%d", Prefix, HasQuietNaN); 393 DefineBuiltinMacro(Buf, MacroBuf); 394 sprintf(MacroBuf, "__%s_MANT_DIG__=%d", Prefix, MantissaDigits); 395 DefineBuiltinMacro(Buf, MacroBuf); 396 sprintf(MacroBuf, "__%s_MAX_10_EXP__=%d", Prefix, Max10Exp); 397 DefineBuiltinMacro(Buf, MacroBuf); 398 sprintf(MacroBuf, "__%s_MAX_EXP__=%d", Prefix, MaxExp); 399 DefineBuiltinMacro(Buf, MacroBuf); 400 sprintf(MacroBuf, "__%s_MAX__=%s", Prefix, Max); 401 DefineBuiltinMacro(Buf, MacroBuf); 402 sprintf(MacroBuf, "__%s_MIN_10_EXP__=(%d)", Prefix, Min10Exp); 403 DefineBuiltinMacro(Buf, MacroBuf); 404 sprintf(MacroBuf, "__%s_MIN_EXP__=(%d)", Prefix, MinExp); 405 DefineBuiltinMacro(Buf, MacroBuf); 406 sprintf(MacroBuf, "__%s_MIN__=%s", Prefix, Min); 407 DefineBuiltinMacro(Buf, MacroBuf); 408} 409 410 411static void InitializePredefinedMacros(Preprocessor &PP, 412 std::vector<char> &Buf) { 413 // Compiler version introspection macros. 414 DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend 415 DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend 416 417 // Currently claim to be compatible with GCC 4.2.1-5621. 418 DefineBuiltinMacro(Buf, "__APPLE_CC__=5621"); 419 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2"); 420 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1"); 421 DefineBuiltinMacro(Buf, "__GNUC__=4"); 422 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002"); 423 DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 (Apple Computer, Inc. " 424 "build 5621) (dot 3)\""); 425 426 427 // Initialize language-specific preprocessor defines. 428 429 // FIXME: Implement magic like cpp_init_builtins for things like __STDC__ 430 // and __DATE__ etc. 431 // These should all be defined in the preprocessor according to the 432 // current language configuration. 433 if (!PP.getLangOptions().Microsoft) 434 DefineBuiltinMacro(Buf, "__STDC__=1"); 435 if (PP.getLangOptions().AsmPreprocessor) 436 DefineBuiltinMacro(Buf, "__ASSEMBLER__=1"); 437 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus) 438 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L"); 439 else if (0) // STDC94 ? 440 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L"); 441 442 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1"); 443 if (PP.getLangOptions().ObjC1) { 444 DefineBuiltinMacro(Buf, "__OBJC__=1"); 445 446 if (PP.getLangOptions().getGCMode() == LangOptions::NonGC) { 447 DefineBuiltinMacro(Buf, "__weak="); 448 DefineBuiltinMacro(Buf, "__strong="); 449 } else { 450 DefineBuiltinMacro(Buf, "__weak=__attribute__((objc_gc(weak)))"); 451 DefineBuiltinMacro(Buf, "__strong=__attribute__((objc_gc(strong)))"); 452 DefineBuiltinMacro(Buf, "__OBJC_GC__=1"); 453 } 454 455 if (PP.getLangOptions().NeXTRuntime) 456 DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1"); 457 } 458 459 // darwin_constant_cfstrings controls this. This is also dependent 460 // on other things like the runtime I believe. This is set even for C code. 461 DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1"); 462 463 if (PP.getLangOptions().ObjC2) 464 DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES"); 465 466 if (PP.getLangOptions().PascalStrings) 467 DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__"); 468 469 if (PP.getLangOptions().Blocks) { 470 DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))"); 471 DefineBuiltinMacro(Buf, "__BLOCKS__=1"); 472 } 473 474 if (PP.getLangOptions().CPlusPlus) { 475 DefineBuiltinMacro(Buf, "__DEPRECATED=1"); 476 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1"); 477 DefineBuiltinMacro(Buf, "__GNUG__=4"); 478 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1"); 479 DefineBuiltinMacro(Buf, "__cplusplus=1"); 480 DefineBuiltinMacro(Buf, "__private_extern__=extern"); 481 } 482 483 // Filter out some microsoft extensions when trying to parse in ms-compat 484 // mode. 485 if (PP.getLangOptions().Microsoft) { 486 DefineBuiltinMacro(Buf, "__stdcall="); 487 DefineBuiltinMacro(Buf, "__cdecl="); 488 DefineBuiltinMacro(Buf, "_cdecl="); 489 DefineBuiltinMacro(Buf, "__ptr64="); 490 DefineBuiltinMacro(Buf, "__w64="); 491 DefineBuiltinMacro(Buf, "__forceinline="); 492 DefineBuiltinMacro(Buf, "__int8=char"); 493 DefineBuiltinMacro(Buf, "__int16=short"); 494 DefineBuiltinMacro(Buf, "__int32=int"); 495 DefineBuiltinMacro(Buf, "__int64=long long"); 496 DefineBuiltinMacro(Buf, "__declspec(X)="); 497 } 498 499 500 // Initialize target-specific preprocessor defines. 501 const TargetInfo &TI = PP.getTargetInfo(); 502 503 // Define type sizing macros based on the target properties. 504 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far"); 505 DefineBuiltinMacro(Buf, "__CHAR_BIT__=8"); 506 DefineBuiltinMacro(Buf, "__SCHAR_MAX__=127"); 507 508 assert(TI.getWCharWidth() == 32 && "Only support 32-bit wchar so far"); 509 DefineBuiltinMacro(Buf, "__WCHAR_MAX__=2147483647"); 510 DefineBuiltinMacro(Buf, "__WCHAR_TYPE__=int"); 511 DefineBuiltinMacro(Buf, "__WINT_TYPE__=int"); 512 513 assert(TI.getShortWidth() == 16 && "Only support 16-bit short so far"); 514 DefineBuiltinMacro(Buf, "__SHRT_MAX__=32767"); 515 516 if (TI.getIntWidth() == 32) 517 DefineBuiltinMacro(Buf, "__INT_MAX__=2147483647"); 518 else if (TI.getIntWidth() == 16) 519 DefineBuiltinMacro(Buf, "__INT_MAX__=32767"); 520 else 521 assert(0 && "Unknown integer size"); 522 523 if (TI.getLongLongWidth() == 64) 524 DefineBuiltinMacro(Buf, "__LONG_LONG_MAX__=9223372036854775807LL"); 525 else if (TI.getLongLongWidth() == 32) 526 DefineBuiltinMacro(Buf, "__LONG_LONG_MAX__=2147483647L"); 527 528 if (TI.getLongWidth() == 32) 529 DefineBuiltinMacro(Buf, "__LONG_MAX__=2147483647L"); 530 else if (TI.getLongWidth() == 64) 531 DefineBuiltinMacro(Buf, "__LONG_MAX__=9223372036854775807L"); 532 else if (TI.getLongWidth() == 16) 533 DefineBuiltinMacro(Buf, "__LONG_MAX__=32767L"); 534 else 535 assert(0 && "Unknown long size"); 536 char MacroBuf[60]; 537 sprintf(MacroBuf, "__INTMAX_MAX__=%lld", 538 (TI.getIntMaxType() == TargetInfo::UnsignedLongLong? 539 (1LL << (TI.getLongLongWidth() - 1)) : 540 ((1LL << (TI.getLongLongWidth() - 2)) - 1))); 541 DefineBuiltinMacro(Buf, MacroBuf); 542 543 if (TI.getIntMaxType() == TargetInfo::UnsignedLongLong) 544 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned long long int"); 545 else if (TI.getIntMaxType() == TargetInfo::SignedLongLong) 546 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=long long int"); 547 else if (TI.getIntMaxType() == TargetInfo::UnsignedLong) 548 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned long int"); 549 else if (TI.getIntMaxType() == TargetInfo::SignedLong) 550 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=long int"); 551 else if (TI.getIntMaxType() == TargetInfo::UnsignedInt) 552 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned int"); 553 else 554 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=int"); 555 556 if (TI.getUIntMaxType() == TargetInfo::UnsignedLongLong) 557 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned long long int"); 558 else if (TI.getUIntMaxType() == TargetInfo::SignedLongLong) 559 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=long long int"); 560 else if (TI.getUIntMaxType() == TargetInfo::UnsignedLong) 561 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned long int"); 562 else if (TI.getUIntMaxType() == TargetInfo::SignedLong) 563 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=long int"); 564 else if (TI.getUIntMaxType() == TargetInfo::UnsignedInt) 565 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned int"); 566 else 567 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=int"); 568 569 if (TI.getPtrDiffType(0) == TargetInfo::UnsignedLongLong) 570 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned long long int"); 571 else if (TI.getPtrDiffType(0) == TargetInfo::SignedLongLong) 572 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=long long int"); 573 else if (TI.getPtrDiffType(0) == TargetInfo::UnsignedLong) 574 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned long int"); 575 else if (TI.getPtrDiffType(0) == TargetInfo::SignedLong) 576 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=long int"); 577 else if (TI.getPtrDiffType(0) == TargetInfo::UnsignedInt) 578 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned int"); 579 else 580 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=int"); 581 582 if (TI.getSizeType() == TargetInfo::UnsignedLongLong) 583 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned long long int"); 584 else if (TI.getSizeType() == TargetInfo::SignedLongLong) 585 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=long long int"); 586 else if (TI.getSizeType() == TargetInfo::UnsignedLong) 587 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned long int"); 588 else if (TI.getSizeType() == TargetInfo::SignedLong) 589 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=long int"); 590 else if (TI.getSizeType() == TargetInfo::UnsignedInt) 591 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned int"); 592 else if (TI.getSizeType() == TargetInfo::SignedInt) 593 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=int"); 594 else 595 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned short"); 596 597 DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat()); 598 DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat()); 599 DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat()); 600 601 602 // Add __builtin_va_list typedef. 603 { 604 const char *VAList = TI.getVAListDeclaration(); 605 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList)); 606 Buf.push_back('\n'); 607 } 608 609 if (const char *Prefix = TI.getUserLabelPrefix()) { 610 sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix); 611 DefineBuiltinMacro(Buf, MacroBuf); 612 } 613 614 // Build configuration options. FIXME: these should be controlled by 615 // command line options or something. 616 DefineBuiltinMacro(Buf, "__DYNAMIC__=1"); 617 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0"); 618 DefineBuiltinMacro(Buf, "__NO_INLINE__=1"); 619 DefineBuiltinMacro(Buf, "__PIC__=1"); 620 621 // Macros to control C99 numerics and <float.h> 622 DefineBuiltinMacro(Buf, "__FLT_EVAL_METHOD__=0"); 623 DefineBuiltinMacro(Buf, "__FLT_RADIX__=2"); 624 sprintf(MacroBuf, "__DECIMAL_DIG__=%d", 625 PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33)); 626 DefineBuiltinMacro(Buf, MacroBuf); 627 628 // Get other target #defines. 629 TI.getTargetDefines(Buf); 630 631 // FIXME: Should emit a #line directive here. 632} 633 634 635/// EnterMainSourceFile - Enter the specified FileID as the main source file, 636/// which implicitly adds the builtin defines etc. 637void Preprocessor::EnterMainSourceFile() { 638 639 unsigned MainFileID = SourceMgr.getMainFileID(); 640 641 // Enter the main file source buffer. 642 EnterSourceFile(MainFileID, 0); 643 644 // Tell the header info that the main file was entered. If the file is later 645 // #imported, it won't be re-entered. 646 if (const FileEntry *FE = 647 SourceMgr.getFileEntryForLoc(SourceLocation::getFileLoc(MainFileID, 0))) 648 HeaderInfo.IncrementIncludeCount(FE); 649 650 std::vector<char> PrologFile; 651 PrologFile.reserve(4080); 652 653 // Install things like __POWERPC__, __GNUC__, etc into the macro table. 654 InitializePredefinedMacros(*this, PrologFile); 655 656 // Add on the predefines from the driver. 657 PrologFile.insert(PrologFile.end(), Predefines.begin(), Predefines.end()); 658 659 // Memory buffer must end with a null byte! 660 PrologFile.push_back(0); 661 662 // Now that we have emitted the predefined macros, #includes, etc into 663 // PrologFile, preprocess it to populate the initial preprocessor state. 664 llvm::MemoryBuffer *SB = 665 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(), 666 "<predefines>"); 667 assert(SB && "Cannot fail to create predefined source buffer"); 668 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB); 669 assert(FileID && "Could not create FileID for predefines?"); 670 671 // Start parsing the predefines. 672 EnterSourceFile(FileID, 0); 673} 674 675 676//===----------------------------------------------------------------------===// 677// Lexer Event Handling. 678//===----------------------------------------------------------------------===// 679 680/// LookUpIdentifierInfo - Given a tok::identifier token, look up the 681/// identifier information for the token and install it into the token. 682IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier, 683 const char *BufPtr) { 684 assert(Identifier.is(tok::identifier) && "Not an identifier!"); 685 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!"); 686 687 // Look up this token, see if it is a macro, or if it is a language keyword. 688 IdentifierInfo *II; 689 if (BufPtr && !Identifier.needsCleaning()) { 690 // No cleaning needed, just use the characters from the lexed buffer. 691 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength()); 692 } else { 693 // Cleaning needed, alloca a buffer, clean into it, then use the buffer. 694 llvm::SmallVector<char, 64> IdentifierBuffer; 695 IdentifierBuffer.resize(Identifier.getLength()); 696 const char *TmpBuf = &IdentifierBuffer[0]; 697 unsigned Size = getSpelling(Identifier, TmpBuf); 698 II = getIdentifierInfo(TmpBuf, TmpBuf+Size); 699 } 700 Identifier.setIdentifierInfo(II); 701 return II; 702} 703 704 705/// HandleIdentifier - This callback is invoked when the lexer reads an 706/// identifier. This callback looks up the identifier in the map and/or 707/// potentially macro expands it or turns it into a named token (like 'for'). 708void Preprocessor::HandleIdentifier(Token &Identifier) { 709 assert(Identifier.getIdentifierInfo() && 710 "Can't handle identifiers without identifier info!"); 711 712 IdentifierInfo &II = *Identifier.getIdentifierInfo(); 713 714 // If this identifier was poisoned, and if it was not produced from a macro 715 // expansion, emit an error. 716 if (II.isPoisoned() && CurPPLexer) { 717 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning. 718 Diag(Identifier, diag::err_pp_used_poisoned_id); 719 else 720 Diag(Identifier, diag::ext_pp_bad_vaargs_use); 721 } 722 723 // If this is a macro to be expanded, do it. 724 if (MacroInfo *MI = getMacroInfo(&II)) { 725 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) { 726 if (MI->isEnabled()) { 727 if (!HandleMacroExpandedIdentifier(Identifier, MI)) 728 return; 729 } else { 730 // C99 6.10.3.4p2 says that a disabled macro may never again be 731 // expanded, even if it's in a context where it could be expanded in the 732 // future. 733 Identifier.setFlag(Token::DisableExpand); 734 } 735 } 736 } 737 738 // C++ 2.11p2: If this is an alternative representation of a C++ operator, 739 // then we act as if it is the actual operator and not the textual 740 // representation of it. 741 if (II.isCPlusPlusOperatorKeyword()) 742 Identifier.setIdentifierInfo(0); 743 744 // Change the kind of this identifier to the appropriate token kind, e.g. 745 // turning "for" into a keyword. 746 Identifier.setKind(II.getTokenID()); 747 748 // If this is an extension token, diagnose its use. 749 // We avoid diagnosing tokens that originate from macro definitions. 750 if (II.isExtensionToken() && Features.C99 && !DisableMacroExpansion) 751 Diag(Identifier, diag::ext_token_used); 752} 753