1 //===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===// 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 top level handling of macro expasion for the 11 // preprocessor. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Lex/Preprocessor.h" 16 #include "MacroArgs.h" 17 #include "clang/Lex/MacroInfo.h" 18 #include "clang/Basic/SourceManager.h" 19 #include "clang/Basic/FileManager.h" 20 #include "clang/Basic/TargetInfo.h" 21 #include "clang/Lex/LexDiagnostic.h" 22 #include "clang/Lex/CodeCompletionHandler.h" 23 #include "clang/Lex/ExternalPreprocessorSource.h" 24 #include "llvm/ADT/StringSwitch.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/Config/config.h" 27 #include "llvm/Support/raw_ostream.h" 28 #include "llvm/Support/ErrorHandling.h" 29 #include <cstdio> 30 #include <ctime> 31 using namespace clang; 32 33 MacroInfo *Preprocessor::getInfoForMacro(IdentifierInfo *II) const { 34 assert(II->hasMacroDefinition() && "Identifier is not a macro!"); 35 36 llvm::DenseMap<IdentifierInfo*, MacroInfo*>::const_iterator Pos 37 = Macros.find(II); 38 if (Pos == Macros.end()) { 39 // Load this macro from the external source. 40 getExternalSource()->LoadMacroDefinition(II); 41 Pos = Macros.find(II); 42 } 43 assert(Pos != Macros.end() && "Identifier macro info is missing!"); 44 return Pos->second; 45 } 46 47 /// setMacroInfo - Specify a macro for this identifier. 48 /// 49 void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) { 50 if (MI) { 51 Macros[II] = MI; 52 II->setHasMacroDefinition(true); 53 } else if (II->hasMacroDefinition()) { 54 Macros.erase(II); 55 II->setHasMacroDefinition(false); 56 } 57 } 58 59 /// RegisterBuiltinMacro - Register the specified identifier in the identifier 60 /// table and mark it as a builtin macro to be expanded. 61 static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){ 62 // Get the identifier. 63 IdentifierInfo *Id = PP.getIdentifierInfo(Name); 64 65 // Mark it as being a macro that is builtin. 66 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation()); 67 MI->setIsBuiltinMacro(); 68 PP.setMacroInfo(Id, MI); 69 return Id; 70 } 71 72 73 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the 74 /// identifier table. 75 void Preprocessor::RegisterBuiltinMacros() { 76 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__"); 77 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__"); 78 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__"); 79 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__"); 80 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__"); 81 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma"); 82 83 // GCC Extensions. 84 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__"); 85 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__"); 86 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__"); 87 88 // Clang Extensions. 89 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature"); 90 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension"); 91 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin"); 92 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute"); 93 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include"); 94 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next"); 95 96 // Microsoft Extensions. 97 if (Features.MicrosoftExt) 98 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma"); 99 else 100 Ident__pragma = 0; 101 } 102 103 /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token 104 /// in its expansion, currently expands to that token literally. 105 static bool isTrivialSingleTokenExpansion(const MacroInfo *MI, 106 const IdentifierInfo *MacroIdent, 107 Preprocessor &PP) { 108 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo(); 109 110 // If the token isn't an identifier, it's always literally expanded. 111 if (II == 0) return true; 112 113 // If the identifier is a macro, and if that macro is enabled, it may be 114 // expanded so it's not a trivial expansion. 115 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() && 116 // Fast expanding "#define X X" is ok, because X would be disabled. 117 II != MacroIdent) 118 return false; 119 120 // If this is an object-like macro invocation, it is safe to trivially expand 121 // it. 122 if (MI->isObjectLike()) return true; 123 124 // If this is a function-like macro invocation, it's safe to trivially expand 125 // as long as the identifier is not a macro argument. 126 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end(); 127 I != E; ++I) 128 if (*I == II) 129 return false; // Identifier is a macro argument. 130 131 return true; 132 } 133 134 135 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be 136 /// lexed is a '('. If so, consume the token and return true, if not, this 137 /// method should have no observable side-effect on the lexed tokens. 138 bool Preprocessor::isNextPPTokenLParen() { 139 // Do some quick tests for rejection cases. 140 unsigned Val; 141 if (CurLexer) 142 Val = CurLexer->isNextPPTokenLParen(); 143 else if (CurPTHLexer) 144 Val = CurPTHLexer->isNextPPTokenLParen(); 145 else 146 Val = CurTokenLexer->isNextTokenLParen(); 147 148 if (Val == 2) { 149 // We have run off the end. If it's a source file we don't 150 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the 151 // macro stack. 152 if (CurPPLexer) 153 return false; 154 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) { 155 IncludeStackInfo &Entry = IncludeMacroStack[i-1]; 156 if (Entry.TheLexer) 157 Val = Entry.TheLexer->isNextPPTokenLParen(); 158 else if (Entry.ThePTHLexer) 159 Val = Entry.ThePTHLexer->isNextPPTokenLParen(); 160 else 161 Val = Entry.TheTokenLexer->isNextTokenLParen(); 162 163 if (Val != 2) 164 break; 165 166 // Ran off the end of a source file? 167 if (Entry.ThePPLexer) 168 return false; 169 } 170 } 171 172 // Okay, if we know that the token is a '(', lex it and return. Otherwise we 173 // have found something that isn't a '(' or we found the end of the 174 // translation unit. In either case, return false. 175 return Val == 1; 176 } 177 178 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be 179 /// expanded as a macro, handle it and return the next token as 'Identifier'. 180 bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier, 181 MacroInfo *MI) { 182 // If this is a macro expansion in the "#if !defined(x)" line for the file, 183 // then the macro could expand to different things in other contexts, we need 184 // to disable the optimization in this case. 185 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro(); 186 187 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially. 188 if (MI->isBuiltinMacro()) { 189 if (Callbacks) Callbacks->MacroExpands(Identifier, MI, 190 Identifier.getLocation()); 191 ExpandBuiltinMacro(Identifier); 192 return false; 193 } 194 195 /// Args - If this is a function-like macro expansion, this contains, 196 /// for each macro argument, the list of tokens that were provided to the 197 /// invocation. 198 MacroArgs *Args = 0; 199 200 // Remember where the end of the expansion occurred. For an object-like 201 // macro, this is the identifier. For a function-like macro, this is the ')'. 202 SourceLocation ExpansionEnd = Identifier.getLocation(); 203 204 // If this is a function-like macro, read the arguments. 205 if (MI->isFunctionLike()) { 206 // C99 6.10.3p10: If the preprocessing token immediately after the the macro 207 // name isn't a '(', this macro should not be expanded. 208 if (!isNextPPTokenLParen()) 209 return true; 210 211 // Remember that we are now parsing the arguments to a macro invocation. 212 // Preprocessor directives used inside macro arguments are not portable, and 213 // this enables the warning. 214 InMacroArgs = true; 215 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd); 216 217 // Finished parsing args. 218 InMacroArgs = false; 219 220 // If there was an error parsing the arguments, bail out. 221 if (Args == 0) return false; 222 223 ++NumFnMacroExpanded; 224 } else { 225 ++NumMacroExpanded; 226 } 227 228 // Notice that this macro has been used. 229 markMacroAsUsed(MI); 230 231 // Remember where the token is expanded. 232 SourceLocation ExpandLoc = Identifier.getLocation(); 233 234 if (Callbacks) Callbacks->MacroExpands(Identifier, MI, 235 SourceRange(ExpandLoc, ExpansionEnd)); 236 237 // If we started lexing a macro, enter the macro expansion body. 238 239 // If this macro expands to no tokens, don't bother to push it onto the 240 // expansion stack, only to take it right back off. 241 if (MI->getNumTokens() == 0) { 242 // No need for arg info. 243 if (Args) Args->destroy(*this); 244 245 // Ignore this macro use, just return the next token in the current 246 // buffer. 247 bool HadLeadingSpace = Identifier.hasLeadingSpace(); 248 bool IsAtStartOfLine = Identifier.isAtStartOfLine(); 249 250 Lex(Identifier); 251 252 // If the identifier isn't on some OTHER line, inherit the leading 253 // whitespace/first-on-a-line property of this token. This handles 254 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is 255 // empty. 256 if (!Identifier.isAtStartOfLine()) { 257 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine); 258 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace); 259 } 260 Identifier.setFlag(Token::LeadingEmptyMacro); 261 ++NumFastMacroExpanded; 262 return false; 263 264 } else if (MI->getNumTokens() == 1 && 265 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(), 266 *this)) { 267 // Otherwise, if this macro expands into a single trivially-expanded 268 // token: expand it now. This handles common cases like 269 // "#define VAL 42". 270 271 // No need for arg info. 272 if (Args) Args->destroy(*this); 273 274 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro 275 // identifier to the expanded token. 276 bool isAtStartOfLine = Identifier.isAtStartOfLine(); 277 bool hasLeadingSpace = Identifier.hasLeadingSpace(); 278 279 // Replace the result token. 280 Identifier = MI->getReplacementToken(0); 281 282 // Restore the StartOfLine/LeadingSpace markers. 283 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine); 284 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace); 285 286 // Update the tokens location to include both its expansion and physical 287 // locations. 288 SourceLocation Loc = 289 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc, 290 ExpansionEnd,Identifier.getLength()); 291 Identifier.setLocation(Loc); 292 293 // If this is a disabled macro or #define X X, we must mark the result as 294 // unexpandable. 295 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) { 296 if (MacroInfo *NewMI = getMacroInfo(NewII)) 297 if (!NewMI->isEnabled() || NewMI == MI) 298 Identifier.setFlag(Token::DisableExpand); 299 } 300 301 // Since this is not an identifier token, it can't be macro expanded, so 302 // we're done. 303 ++NumFastMacroExpanded; 304 return false; 305 } 306 307 // Start expanding the macro. 308 EnterMacro(Identifier, ExpansionEnd, Args); 309 310 // Now that the macro is at the top of the include stack, ask the 311 // preprocessor to read the next token from it. 312 Lex(Identifier); 313 return false; 314 } 315 316 /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next 317 /// token is the '(' of the macro, this method is invoked to read all of the 318 /// actual arguments specified for the macro invocation. This returns null on 319 /// error. 320 MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, 321 MacroInfo *MI, 322 SourceLocation &MacroEnd) { 323 // The number of fixed arguments to parse. 324 unsigned NumFixedArgsLeft = MI->getNumArgs(); 325 bool isVariadic = MI->isVariadic(); 326 327 // Outer loop, while there are more arguments, keep reading them. 328 Token Tok; 329 330 // Read arguments as unexpanded tokens. This avoids issues, e.g., where 331 // an argument value in a macro could expand to ',' or '(' or ')'. 332 LexUnexpandedToken(Tok); 333 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?"); 334 335 // ArgTokens - Build up a list of tokens that make up each argument. Each 336 // argument is separated by an EOF token. Use a SmallVector so we can avoid 337 // heap allocations in the common case. 338 SmallVector<Token, 64> ArgTokens; 339 340 unsigned NumActuals = 0; 341 while (Tok.isNot(tok::r_paren)) { 342 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) && 343 "only expect argument separators here"); 344 345 unsigned ArgTokenStart = ArgTokens.size(); 346 SourceLocation ArgStartLoc = Tok.getLocation(); 347 348 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note 349 // that we already consumed the first one. 350 unsigned NumParens = 0; 351 352 while (1) { 353 // Read arguments as unexpanded tokens. This avoids issues, e.g., where 354 // an argument value in a macro could expand to ',' or '(' or ')'. 355 LexUnexpandedToken(Tok); 356 357 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n" 358 Diag(MacroName, diag::err_unterm_macro_invoc); 359 // Do not lose the EOF/EOD. Return it to the client. 360 MacroName = Tok; 361 return 0; 362 } else if (Tok.is(tok::r_paren)) { 363 // If we found the ) token, the macro arg list is done. 364 if (NumParens-- == 0) { 365 MacroEnd = Tok.getLocation(); 366 break; 367 } 368 } else if (Tok.is(tok::l_paren)) { 369 ++NumParens; 370 } else if (Tok.is(tok::comma) && NumParens == 0) { 371 // Comma ends this argument if there are more fixed arguments expected. 372 // However, if this is a variadic macro, and this is part of the 373 // variadic part, then the comma is just an argument token. 374 if (!isVariadic) break; 375 if (NumFixedArgsLeft > 1) 376 break; 377 } else if (Tok.is(tok::comment) && !KeepMacroComments) { 378 // If this is a comment token in the argument list and we're just in 379 // -C mode (not -CC mode), discard the comment. 380 continue; 381 } else if (Tok.getIdentifierInfo() != 0) { 382 // Reading macro arguments can cause macros that we are currently 383 // expanding from to be popped off the expansion stack. Doing so causes 384 // them to be reenabled for expansion. Here we record whether any 385 // identifiers we lex as macro arguments correspond to disabled macros. 386 // If so, we mark the token as noexpand. This is a subtle aspect of 387 // C99 6.10.3.4p2. 388 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo())) 389 if (!MI->isEnabled()) 390 Tok.setFlag(Token::DisableExpand); 391 } else if (Tok.is(tok::code_completion)) { 392 if (CodeComplete) 393 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(), 394 MI, NumActuals); 395 // Don't mark that we reached the code-completion point because the 396 // parser is going to handle the token and there will be another 397 // code-completion callback. 398 } 399 400 ArgTokens.push_back(Tok); 401 } 402 403 // If this was an empty argument list foo(), don't add this as an empty 404 // argument. 405 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren) 406 break; 407 408 // If this is not a variadic macro, and too many args were specified, emit 409 // an error. 410 if (!isVariadic && NumFixedArgsLeft == 0) { 411 if (ArgTokens.size() != ArgTokenStart) 412 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation(); 413 414 // Emit the diagnostic at the macro name in case there is a missing ). 415 // Emitting it at the , could be far away from the macro name. 416 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc); 417 return 0; 418 } 419 420 // Empty arguments are standard in C99 and C++0x, and are supported as an extension in 421 // other modes. 422 if (ArgTokens.size() == ArgTokenStart && !Features.C99 && !Features.CPlusPlus0x) 423 Diag(Tok, diag::ext_empty_fnmacro_arg); 424 425 // Add a marker EOF token to the end of the token list for this argument. 426 Token EOFTok; 427 EOFTok.startToken(); 428 EOFTok.setKind(tok::eof); 429 EOFTok.setLocation(Tok.getLocation()); 430 EOFTok.setLength(0); 431 ArgTokens.push_back(EOFTok); 432 ++NumActuals; 433 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed"); 434 --NumFixedArgsLeft; 435 } 436 437 // Okay, we either found the r_paren. Check to see if we parsed too few 438 // arguments. 439 unsigned MinArgsExpected = MI->getNumArgs(); 440 441 // See MacroArgs instance var for description of this. 442 bool isVarargsElided = false; 443 444 if (NumActuals < MinArgsExpected) { 445 // There are several cases where too few arguments is ok, handle them now. 446 if (NumActuals == 0 && MinArgsExpected == 1) { 447 // #define A(X) or #define A(...) ---> A() 448 449 // If there is exactly one argument, and that argument is missing, 450 // then we have an empty "()" argument empty list. This is fine, even if 451 // the macro expects one argument (the argument is just empty). 452 isVarargsElided = MI->isVariadic(); 453 } else if (MI->isVariadic() && 454 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X) 455 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A() 456 // Varargs where the named vararg parameter is missing: ok as extension. 457 // #define A(x, ...) 458 // A("blah") 459 Diag(Tok, diag::ext_missing_varargs_arg); 460 461 // Remember this occurred, allowing us to elide the comma when used for 462 // cases like: 463 // #define A(x, foo...) blah(a, ## foo) 464 // #define B(x, ...) blah(a, ## __VA_ARGS__) 465 // #define C(...) blah(a, ## __VA_ARGS__) 466 // A(x) B(x) C() 467 isVarargsElided = true; 468 } else { 469 // Otherwise, emit the error. 470 Diag(Tok, diag::err_too_few_args_in_macro_invoc); 471 return 0; 472 } 473 474 // Add a marker EOF token to the end of the token list for this argument. 475 SourceLocation EndLoc = Tok.getLocation(); 476 Tok.startToken(); 477 Tok.setKind(tok::eof); 478 Tok.setLocation(EndLoc); 479 Tok.setLength(0); 480 ArgTokens.push_back(Tok); 481 482 // If we expect two arguments, add both as empty. 483 if (NumActuals == 0 && MinArgsExpected == 2) 484 ArgTokens.push_back(Tok); 485 486 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) { 487 // Emit the diagnostic at the macro name in case there is a missing ). 488 // Emitting it at the , could be far away from the macro name. 489 Diag(MacroName, diag::err_too_many_args_in_macro_invoc); 490 return 0; 491 } 492 493 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this); 494 } 495 496 /// \brief Keeps macro expanded tokens for TokenLexers. 497 // 498 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is 499 /// going to lex in the cache and when it finishes the tokens are removed 500 /// from the end of the cache. 501 Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer, 502 ArrayRef<Token> tokens) { 503 assert(tokLexer); 504 if (tokens.empty()) 505 return 0; 506 507 size_t newIndex = MacroExpandedTokens.size(); 508 bool cacheNeedsToGrow = tokens.size() > 509 MacroExpandedTokens.capacity()-MacroExpandedTokens.size(); 510 MacroExpandedTokens.append(tokens.begin(), tokens.end()); 511 512 if (cacheNeedsToGrow) { 513 // Go through all the TokenLexers whose 'Tokens' pointer points in the 514 // buffer and update the pointers to the (potential) new buffer array. 515 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) { 516 TokenLexer *prevLexer; 517 size_t tokIndex; 518 llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i]; 519 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex; 520 } 521 } 522 523 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex)); 524 return MacroExpandedTokens.data() + newIndex; 525 } 526 527 void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() { 528 assert(!MacroExpandingLexersStack.empty()); 529 size_t tokIndex = MacroExpandingLexersStack.back().second; 530 assert(tokIndex < MacroExpandedTokens.size()); 531 // Pop the cached macro expanded tokens from the end. 532 MacroExpandedTokens.resize(tokIndex); 533 MacroExpandingLexersStack.pop_back(); 534 } 535 536 /// ComputeDATE_TIME - Compute the current time, enter it into the specified 537 /// scratch buffer, then return DATELoc/TIMELoc locations with the position of 538 /// the identifier tokens inserted. 539 static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc, 540 Preprocessor &PP) { 541 time_t TT = time(0); 542 struct tm *TM = localtime(&TT); 543 544 static const char * const Months[] = { 545 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" 546 }; 547 548 char TmpBuffer[32]; 549 #ifdef LLVM_ON_WIN32 550 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday, 551 TM->tm_year+1900); 552 #else 553 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday, 554 TM->tm_year+1900); 555 #endif 556 557 Token TmpTok; 558 TmpTok.startToken(); 559 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok); 560 DATELoc = TmpTok.getLocation(); 561 562 #ifdef LLVM_ON_WIN32 563 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec); 564 #else 565 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec); 566 #endif 567 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok); 568 TIMELoc = TmpTok.getLocation(); 569 } 570 571 572 /// HasFeature - Return true if we recognize and implement the feature 573 /// specified by the identifier as a standard language feature. 574 static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) { 575 const LangOptions &LangOpts = PP.getLangOptions(); 576 577 return llvm::StringSwitch<bool>(II->getName()) 578 .Case("attribute_analyzer_noreturn", true) 579 .Case("attribute_availability", true) 580 .Case("attribute_cf_returns_not_retained", true) 581 .Case("attribute_cf_returns_retained", true) 582 .Case("attribute_deprecated_with_message", true) 583 .Case("attribute_ext_vector_type", true) 584 .Case("attribute_ns_returns_not_retained", true) 585 .Case("attribute_ns_returns_retained", true) 586 .Case("attribute_ns_consumes_self", true) 587 .Case("attribute_ns_consumed", true) 588 .Case("attribute_cf_consumed", true) 589 .Case("attribute_objc_ivar_unused", true) 590 .Case("attribute_objc_method_family", true) 591 .Case("attribute_overloadable", true) 592 .Case("attribute_unavailable_with_message", true) 593 .Case("blocks", LangOpts.Blocks) 594 .Case("cxx_exceptions", LangOpts.Exceptions) 595 .Case("cxx_rtti", LangOpts.RTTI) 596 .Case("enumerator_attributes", true) 597 // Objective-C features 598 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE? 599 .Case("objc_arc", LangOpts.ObjCAutoRefCount) 600 .Case("objc_arc_weak", LangOpts.ObjCAutoRefCount && 601 LangOpts.ObjCRuntimeHasWeak) 602 .Case("objc_fixed_enum", LangOpts.ObjC2) 603 .Case("objc_instancetype", LangOpts.ObjC2) 604 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI) 605 .Case("objc_weak_class", LangOpts.ObjCNonFragileABI) 606 .Case("ownership_holds", true) 607 .Case("ownership_returns", true) 608 .Case("ownership_takes", true) 609 // C1X features 610 .Case("c_generic_selections", LangOpts.C1X) 611 .Case("c_static_assert", LangOpts.C1X) 612 // C++0x features 613 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus0x) 614 .Case("cxx_alias_templates", LangOpts.CPlusPlus0x) 615 .Case("cxx_attributes", LangOpts.CPlusPlus0x) 616 .Case("cxx_auto_type", LangOpts.CPlusPlus0x) 617 //.Case("cxx_constexpr", false); 618 .Case("cxx_decltype", LangOpts.CPlusPlus0x) 619 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus0x) 620 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus0x) 621 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x) 622 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus0x) 623 //.Case("cxx_generalized_initializers", LangOpts.CPlusPlus0x) 624 .Case("cxx_implicit_moves", LangOpts.CPlusPlus0x) 625 //.Case("cxx_inheriting_constructors", false) 626 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus0x) 627 //.Case("cxx_lambdas", false) 628 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus0x) 629 .Case("cxx_noexcept", LangOpts.CPlusPlus0x) 630 .Case("cxx_nullptr", LangOpts.CPlusPlus0x) 631 .Case("cxx_override_control", LangOpts.CPlusPlus0x) 632 .Case("cxx_range_for", LangOpts.CPlusPlus0x) 633 //.Case("cxx_raw_string_literals", false) 634 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus0x) 635 .Case("cxx_rvalue_references", LangOpts.CPlusPlus0x) 636 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x) 637 .Case("cxx_static_assert", LangOpts.CPlusPlus0x) 638 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x) 639 //.Case("cxx_unicode_literals", false) 640 //.Case("cxx_unrestricted_unions", false) 641 //.Case("cxx_user_literals", false) 642 .Case("cxx_variadic_templates", LangOpts.CPlusPlus0x) 643 // Type traits 644 .Case("has_nothrow_assign", LangOpts.CPlusPlus) 645 .Case("has_nothrow_copy", LangOpts.CPlusPlus) 646 .Case("has_nothrow_constructor", LangOpts.CPlusPlus) 647 .Case("has_trivial_assign", LangOpts.CPlusPlus) 648 .Case("has_trivial_copy", LangOpts.CPlusPlus) 649 .Case("has_trivial_constructor", LangOpts.CPlusPlus) 650 .Case("has_trivial_destructor", LangOpts.CPlusPlus) 651 .Case("has_virtual_destructor", LangOpts.CPlusPlus) 652 .Case("is_abstract", LangOpts.CPlusPlus) 653 .Case("is_base_of", LangOpts.CPlusPlus) 654 .Case("is_class", LangOpts.CPlusPlus) 655 .Case("is_convertible_to", LangOpts.CPlusPlus) 656 // __is_empty is available only if the horrible 657 // "struct __is_empty" parsing hack hasn't been needed in this 658 // translation unit. If it has, __is_empty reverts to a normal 659 // identifier and __has_feature(is_empty) evaluates false. 660 .Case("is_empty", 661 LangOpts.CPlusPlus && 662 PP.getIdentifierInfo("__is_empty")->getTokenID() 663 != tok::identifier) 664 .Case("is_enum", LangOpts.CPlusPlus) 665 .Case("is_literal", LangOpts.CPlusPlus) 666 .Case("is_standard_layout", LangOpts.CPlusPlus) 667 // __is_pod is available only if the horrible 668 // "struct __is_pod" parsing hack hasn't been needed in this 669 // translation unit. If it has, __is_pod reverts to a normal 670 // identifier and __has_feature(is_pod) evaluates false. 671 .Case("is_pod", 672 LangOpts.CPlusPlus && 673 PP.getIdentifierInfo("__is_pod")->getTokenID() 674 != tok::identifier) 675 .Case("is_polymorphic", LangOpts.CPlusPlus) 676 .Case("is_trivial", LangOpts.CPlusPlus) 677 .Case("is_trivially_copyable", LangOpts.CPlusPlus) 678 .Case("is_union", LangOpts.CPlusPlus) 679 .Case("tls", PP.getTargetInfo().isTLSSupported()) 680 .Case("underlying_type", LangOpts.CPlusPlus) 681 .Default(false); 682 } 683 684 /// HasExtension - Return true if we recognize and implement the feature 685 /// specified by the identifier, either as an extension or a standard language 686 /// feature. 687 static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) { 688 if (HasFeature(PP, II)) 689 return true; 690 691 // If the use of an extension results in an error diagnostic, extensions are 692 // effectively unavailable, so just return false here. 693 if (PP.getDiagnostics().getExtensionHandlingBehavior() == 694 DiagnosticsEngine::Ext_Error) 695 return false; 696 697 const LangOptions &LangOpts = PP.getLangOptions(); 698 699 // Because we inherit the feature list from HasFeature, this string switch 700 // must be less restrictive than HasFeature's. 701 return llvm::StringSwitch<bool>(II->getName()) 702 // C1X features supported by other languages as extensions. 703 .Case("c_generic_selections", true) 704 .Case("c_static_assert", true) 705 // C++0x features supported by other languages as extensions. 706 .Case("cxx_deleted_functions", LangOpts.CPlusPlus) 707 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus) 708 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus) 709 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus) 710 .Case("cxx_override_control", LangOpts.CPlusPlus) 711 .Case("cxx_range_for", LangOpts.CPlusPlus) 712 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus) 713 .Case("cxx_rvalue_references", LangOpts.CPlusPlus) 714 .Default(false); 715 } 716 717 /// HasAttribute - Return true if we recognize and implement the attribute 718 /// specified by the given identifier. 719 static bool HasAttribute(const IdentifierInfo *II) { 720 return llvm::StringSwitch<bool>(II->getName()) 721 #include "clang/Lex/AttrSpellings.inc" 722 .Default(false); 723 } 724 725 /// EvaluateHasIncludeCommon - Process a '__has_include("path")' 726 /// or '__has_include_next("path")' expression. 727 /// Returns true if successful. 728 static bool EvaluateHasIncludeCommon(Token &Tok, 729 IdentifierInfo *II, Preprocessor &PP, 730 const DirectoryLookup *LookupFrom) { 731 SourceLocation LParenLoc; 732 733 // Get '('. 734 PP.LexNonComment(Tok); 735 736 // Ensure we have a '('. 737 if (Tok.isNot(tok::l_paren)) { 738 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName(); 739 return false; 740 } 741 742 // Save '(' location for possible missing ')' message. 743 LParenLoc = Tok.getLocation(); 744 745 // Get the file name. 746 PP.getCurrentLexer()->LexIncludeFilename(Tok); 747 748 // Reserve a buffer to get the spelling. 749 llvm::SmallString<128> FilenameBuffer; 750 StringRef Filename; 751 SourceLocation EndLoc; 752 753 switch (Tok.getKind()) { 754 case tok::eod: 755 // If the token kind is EOD, the error has already been diagnosed. 756 return false; 757 758 case tok::angle_string_literal: 759 case tok::string_literal: { 760 bool Invalid = false; 761 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid); 762 if (Invalid) 763 return false; 764 break; 765 } 766 767 case tok::less: 768 // This could be a <foo/bar.h> file coming from a macro expansion. In this 769 // case, glue the tokens together into FilenameBuffer and interpret those. 770 FilenameBuffer.push_back('<'); 771 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) 772 return false; // Found <eod> but no ">"? Diagnostic already emitted. 773 Filename = FilenameBuffer.str(); 774 break; 775 default: 776 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename); 777 return false; 778 } 779 780 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename); 781 // If GetIncludeFilenameSpelling set the start ptr to null, there was an 782 // error. 783 if (Filename.empty()) 784 return false; 785 786 // Search include directories. 787 const DirectoryLookup *CurDir; 788 const FileEntry *File = 789 PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL); 790 791 // Get the result value. Result = true means the file exists. 792 bool Result = File != 0; 793 794 // Get ')'. 795 PP.LexNonComment(Tok); 796 797 // Ensure we have a trailing ). 798 if (Tok.isNot(tok::r_paren)) { 799 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName(); 800 PP.Diag(LParenLoc, diag::note_matching) << "("; 801 return false; 802 } 803 804 return Result; 805 } 806 807 /// EvaluateHasInclude - Process a '__has_include("path")' expression. 808 /// Returns true if successful. 809 static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II, 810 Preprocessor &PP) { 811 return EvaluateHasIncludeCommon(Tok, II, PP, NULL); 812 } 813 814 /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression. 815 /// Returns true if successful. 816 static bool EvaluateHasIncludeNext(Token &Tok, 817 IdentifierInfo *II, Preprocessor &PP) { 818 // __has_include_next is like __has_include, except that we start 819 // searching after the current found directory. If we can't do this, 820 // issue a diagnostic. 821 const DirectoryLookup *Lookup = PP.GetCurDirLookup(); 822 if (PP.isInPrimaryFile()) { 823 Lookup = 0; 824 PP.Diag(Tok, diag::pp_include_next_in_primary); 825 } else if (Lookup == 0) { 826 PP.Diag(Tok, diag::pp_include_next_absolute_path); 827 } else { 828 // Start looking up in the next directory. 829 ++Lookup; 830 } 831 832 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup); 833 } 834 835 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded 836 /// as a builtin macro, handle it and return the next token as 'Tok'. 837 void Preprocessor::ExpandBuiltinMacro(Token &Tok) { 838 // Figure out which token this is. 839 IdentifierInfo *II = Tok.getIdentifierInfo(); 840 assert(II && "Can't be a macro without id info!"); 841 842 // If this is an _Pragma or Microsoft __pragma directive, expand it, 843 // invoke the pragma handler, then lex the token after it. 844 if (II == Ident_Pragma) 845 return Handle_Pragma(Tok); 846 else if (II == Ident__pragma) // in non-MS mode this is null 847 return HandleMicrosoft__pragma(Tok); 848 849 ++NumBuiltinMacroExpanded; 850 851 llvm::SmallString<128> TmpBuffer; 852 llvm::raw_svector_ostream OS(TmpBuffer); 853 854 // Set up the return result. 855 Tok.setIdentifierInfo(0); 856 Tok.clearFlag(Token::NeedsCleaning); 857 858 if (II == Ident__LINE__) { 859 // C99 6.10.8: "__LINE__: The presumed line number (within the current 860 // source file) of the current source line (an integer constant)". This can 861 // be affected by #line. 862 SourceLocation Loc = Tok.getLocation(); 863 864 // Advance to the location of the first _, this might not be the first byte 865 // of the token if it starts with an escaped newline. 866 Loc = AdvanceToTokenCharacter(Loc, 0); 867 868 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of 869 // a macro expansion. This doesn't matter for object-like macros, but 870 // can matter for a function-like macro that expands to contain __LINE__. 871 // Skip down through expansion points until we find a file loc for the 872 // end of the expansion history. 873 Loc = SourceMgr.getExpansionRange(Loc).second; 874 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc); 875 876 // __LINE__ expands to a simple numeric value. 877 OS << (PLoc.isValid()? PLoc.getLine() : 1); 878 Tok.setKind(tok::numeric_constant); 879 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) { 880 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a 881 // character string literal)". This can be affected by #line. 882 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); 883 884 // __BASE_FILE__ is a GNU extension that returns the top of the presumed 885 // #include stack instead of the current file. 886 if (II == Ident__BASE_FILE__ && PLoc.isValid()) { 887 SourceLocation NextLoc = PLoc.getIncludeLoc(); 888 while (NextLoc.isValid()) { 889 PLoc = SourceMgr.getPresumedLoc(NextLoc); 890 if (PLoc.isInvalid()) 891 break; 892 893 NextLoc = PLoc.getIncludeLoc(); 894 } 895 } 896 897 // Escape this filename. Turn '\' -> '\\' '"' -> '\"' 898 llvm::SmallString<128> FN; 899 if (PLoc.isValid()) { 900 FN += PLoc.getFilename(); 901 Lexer::Stringify(FN); 902 OS << '"' << FN.str() << '"'; 903 } 904 Tok.setKind(tok::string_literal); 905 } else if (II == Ident__DATE__) { 906 if (!DATELoc.isValid()) 907 ComputeDATE_TIME(DATELoc, TIMELoc, *this); 908 Tok.setKind(tok::string_literal); 909 Tok.setLength(strlen("\"Mmm dd yyyy\"")); 910 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(), 911 Tok.getLocation(), 912 Tok.getLength())); 913 return; 914 } else if (II == Ident__TIME__) { 915 if (!TIMELoc.isValid()) 916 ComputeDATE_TIME(DATELoc, TIMELoc, *this); 917 Tok.setKind(tok::string_literal); 918 Tok.setLength(strlen("\"hh:mm:ss\"")); 919 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(), 920 Tok.getLocation(), 921 Tok.getLength())); 922 return; 923 } else if (II == Ident__INCLUDE_LEVEL__) { 924 // Compute the presumed include depth of this token. This can be affected 925 // by GNU line markers. 926 unsigned Depth = 0; 927 928 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); 929 if (PLoc.isValid()) { 930 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); 931 for (; PLoc.isValid(); ++Depth) 932 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); 933 } 934 935 // __INCLUDE_LEVEL__ expands to a simple numeric value. 936 OS << Depth; 937 Tok.setKind(tok::numeric_constant); 938 } else if (II == Ident__TIMESTAMP__) { 939 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be 940 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime. 941 942 // Get the file that we are lexing out of. If we're currently lexing from 943 // a macro, dig into the include stack. 944 const FileEntry *CurFile = 0; 945 PreprocessorLexer *TheLexer = getCurrentFileLexer(); 946 947 if (TheLexer) 948 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID()); 949 950 const char *Result; 951 if (CurFile) { 952 time_t TT = CurFile->getModificationTime(); 953 struct tm *TM = localtime(&TT); 954 Result = asctime(TM); 955 } else { 956 Result = "??? ??? ?? ??:??:?? ????\n"; 957 } 958 // Surround the string with " and strip the trailing newline. 959 OS << '"' << StringRef(Result, strlen(Result)-1) << '"'; 960 Tok.setKind(tok::string_literal); 961 } else if (II == Ident__COUNTER__) { 962 // __COUNTER__ expands to a simple numeric value. 963 OS << CounterValue++; 964 Tok.setKind(tok::numeric_constant); 965 } else if (II == Ident__has_feature || 966 II == Ident__has_extension || 967 II == Ident__has_builtin || 968 II == Ident__has_attribute) { 969 // The argument to these builtins should be a parenthesized identifier. 970 SourceLocation StartLoc = Tok.getLocation(); 971 972 bool IsValid = false; 973 IdentifierInfo *FeatureII = 0; 974 975 // Read the '('. 976 Lex(Tok); 977 if (Tok.is(tok::l_paren)) { 978 // Read the identifier 979 Lex(Tok); 980 if (Tok.is(tok::identifier)) { 981 FeatureII = Tok.getIdentifierInfo(); 982 983 // Read the ')'. 984 Lex(Tok); 985 if (Tok.is(tok::r_paren)) 986 IsValid = true; 987 } 988 } 989 990 bool Value = false; 991 if (!IsValid) 992 Diag(StartLoc, diag::err_feature_check_malformed); 993 else if (II == Ident__has_builtin) { 994 // Check for a builtin is trivial. 995 Value = FeatureII->getBuiltinID() != 0; 996 } else if (II == Ident__has_attribute) 997 Value = HasAttribute(FeatureII); 998 else if (II == Ident__has_extension) 999 Value = HasExtension(*this, FeatureII); 1000 else { 1001 assert(II == Ident__has_feature && "Must be feature check"); 1002 Value = HasFeature(*this, FeatureII); 1003 } 1004 1005 OS << (int)Value; 1006 Tok.setKind(tok::numeric_constant); 1007 } else if (II == Ident__has_include || 1008 II == Ident__has_include_next) { 1009 // The argument to these two builtins should be a parenthesized 1010 // file name string literal using angle brackets (<>) or 1011 // double-quotes (""). 1012 bool Value; 1013 if (II == Ident__has_include) 1014 Value = EvaluateHasInclude(Tok, II, *this); 1015 else 1016 Value = EvaluateHasIncludeNext(Tok, II, *this); 1017 OS << (int)Value; 1018 Tok.setKind(tok::numeric_constant); 1019 } else { 1020 llvm_unreachable("Unknown identifier!"); 1021 } 1022 CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation()); 1023 } 1024 1025 void Preprocessor::markMacroAsUsed(MacroInfo *MI) { 1026 // If the 'used' status changed, and the macro requires 'unused' warning, 1027 // remove its SourceLocation from the warn-for-unused-macro locations. 1028 if (MI->isWarnIfUnused() && !MI->isUsed()) 1029 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); 1030 MI->setIsUsed(true); 1031 } 1032