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 expansion for the 11 // preprocessor. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Lex/Preprocessor.h" 16 #include "clang/Basic/Attributes.h" 17 #include "clang/Basic/FileManager.h" 18 #include "clang/Basic/SourceManager.h" 19 #include "clang/Basic/TargetInfo.h" 20 #include "clang/Lex/CodeCompletionHandler.h" 21 #include "clang/Lex/ExternalPreprocessorSource.h" 22 #include "clang/Lex/LexDiagnostic.h" 23 #include "clang/Lex/MacroArgs.h" 24 #include "clang/Lex/MacroInfo.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SmallString.h" 27 #include "llvm/ADT/StringSwitch.h" 28 #include "llvm/Config/llvm-config.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/Format.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include <cstdio> 33 #include <ctime> 34 using namespace clang; 35 36 MacroDirective * 37 Preprocessor::getLocalMacroDirectiveHistory(const IdentifierInfo *II) const { 38 if (!II->hadMacroDefinition()) 39 return nullptr; 40 auto Pos = CurSubmoduleState->Macros.find(II); 41 return Pos == CurSubmoduleState->Macros.end() ? nullptr 42 : Pos->second.getLatest(); 43 } 44 45 void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){ 46 assert(MD && "MacroDirective should be non-zero!"); 47 assert(!MD->getPrevious() && "Already attached to a MacroDirective history."); 48 49 MacroState &StoredMD = CurSubmoduleState->Macros[II]; 50 auto *OldMD = StoredMD.getLatest(); 51 MD->setPrevious(OldMD); 52 StoredMD.setLatest(MD); 53 StoredMD.overrideActiveModuleMacros(*this, II); 54 55 // Set up the identifier as having associated macro history. 56 II->setHasMacroDefinition(true); 57 if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end()) 58 II->setHasMacroDefinition(false); 59 if (II->isFromAST()) 60 II->setChangedSinceDeserialization(); 61 } 62 63 void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II, 64 MacroDirective *MD) { 65 assert(II && MD); 66 MacroState &StoredMD = CurSubmoduleState->Macros[II]; 67 assert(!StoredMD.getLatest() && 68 "the macro history was modified before initializing it from a pch"); 69 StoredMD = MD; 70 // Setup the identifier as having associated macro history. 71 II->setHasMacroDefinition(true); 72 if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end()) 73 II->setHasMacroDefinition(false); 74 } 75 76 ModuleMacro *Preprocessor::addModuleMacro(Module *Mod, IdentifierInfo *II, 77 MacroInfo *Macro, 78 ArrayRef<ModuleMacro *> Overrides, 79 bool &New) { 80 llvm::FoldingSetNodeID ID; 81 ModuleMacro::Profile(ID, Mod, II); 82 83 void *InsertPos; 84 if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) { 85 New = false; 86 return MM; 87 } 88 89 auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides); 90 ModuleMacros.InsertNode(MM, InsertPos); 91 92 // Each overridden macro is now overridden by one more macro. 93 bool HidAny = false; 94 for (auto *O : Overrides) { 95 HidAny |= (O->NumOverriddenBy == 0); 96 ++O->NumOverriddenBy; 97 } 98 99 // If we were the first overrider for any macro, it's no longer a leaf. 100 auto &LeafMacros = LeafModuleMacros[II]; 101 if (HidAny) { 102 LeafMacros.erase(std::remove_if(LeafMacros.begin(), LeafMacros.end(), 103 [](ModuleMacro *MM) { 104 return MM->NumOverriddenBy != 0; 105 }), 106 LeafMacros.end()); 107 } 108 109 // The new macro is always a leaf macro. 110 LeafMacros.push_back(MM); 111 // The identifier now has defined macros (that may or may not be visible). 112 II->setHasMacroDefinition(true); 113 114 New = true; 115 return MM; 116 } 117 118 ModuleMacro *Preprocessor::getModuleMacro(Module *Mod, IdentifierInfo *II) { 119 llvm::FoldingSetNodeID ID; 120 ModuleMacro::Profile(ID, Mod, II); 121 122 void *InsertPos; 123 return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos); 124 } 125 126 void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II, 127 ModuleMacroInfo &Info) { 128 assert(Info.ActiveModuleMacrosGeneration != 129 CurSubmoduleState->VisibleModules.getGeneration() && 130 "don't need to update this macro name info"); 131 Info.ActiveModuleMacrosGeneration = 132 CurSubmoduleState->VisibleModules.getGeneration(); 133 134 auto Leaf = LeafModuleMacros.find(II); 135 if (Leaf == LeafModuleMacros.end()) { 136 // No imported macros at all: nothing to do. 137 return; 138 } 139 140 Info.ActiveModuleMacros.clear(); 141 142 // Every macro that's locally overridden is overridden by a visible macro. 143 llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides; 144 for (auto *O : Info.OverriddenMacros) 145 NumHiddenOverrides[O] = -1; 146 147 // Collect all macros that are not overridden by a visible macro. 148 llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf->second.begin(), 149 Leaf->second.end()); 150 while (!Worklist.empty()) { 151 auto *MM = Worklist.pop_back_val(); 152 if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) { 153 // We only care about collecting definitions; undefinitions only act 154 // to override other definitions. 155 if (MM->getMacroInfo()) 156 Info.ActiveModuleMacros.push_back(MM); 157 } else { 158 for (auto *O : MM->overrides()) 159 if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros()) 160 Worklist.push_back(O); 161 } 162 } 163 // Our reverse postorder walk found the macros in reverse order. 164 std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end()); 165 166 // Determine whether the macro name is ambiguous. 167 MacroInfo *MI = nullptr; 168 bool IsSystemMacro = true; 169 bool IsAmbiguous = false; 170 if (auto *MD = Info.MD) { 171 while (MD && isa<VisibilityMacroDirective>(MD)) 172 MD = MD->getPrevious(); 173 if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) { 174 MI = DMD->getInfo(); 175 IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation()); 176 } 177 } 178 for (auto *Active : Info.ActiveModuleMacros) { 179 auto *NewMI = Active->getMacroInfo(); 180 181 // Before marking the macro as ambiguous, check if this is a case where 182 // both macros are in system headers. If so, we trust that the system 183 // did not get it wrong. This also handles cases where Clang's own 184 // headers have a different spelling of certain system macros: 185 // #define LONG_MAX __LONG_MAX__ (clang's limits.h) 186 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h) 187 // 188 // FIXME: Remove the defined-in-system-headers check. clang's limits.h 189 // overrides the system limits.h's macros, so there's no conflict here. 190 if (MI && NewMI != MI && 191 !MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true)) 192 IsAmbiguous = true; 193 IsSystemMacro &= Active->getOwningModule()->IsSystem || 194 SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc()); 195 MI = NewMI; 196 } 197 Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro; 198 } 199 200 void Preprocessor::dumpMacroInfo(const IdentifierInfo *II) { 201 ArrayRef<ModuleMacro*> Leaf; 202 auto LeafIt = LeafModuleMacros.find(II); 203 if (LeafIt != LeafModuleMacros.end()) 204 Leaf = LeafIt->second; 205 const MacroState *State = nullptr; 206 auto Pos = CurSubmoduleState->Macros.find(II); 207 if (Pos != CurSubmoduleState->Macros.end()) 208 State = &Pos->second; 209 210 llvm::errs() << "MacroState " << State << " " << II->getNameStart(); 211 if (State && State->isAmbiguous(*this, II)) 212 llvm::errs() << " ambiguous"; 213 if (State && !State->getOverriddenMacros().empty()) { 214 llvm::errs() << " overrides"; 215 for (auto *O : State->getOverriddenMacros()) 216 llvm::errs() << " " << O->getOwningModule()->getFullModuleName(); 217 } 218 llvm::errs() << "\n"; 219 220 // Dump local macro directives. 221 for (auto *MD = State ? State->getLatest() : nullptr; MD; 222 MD = MD->getPrevious()) { 223 llvm::errs() << " "; 224 MD->dump(); 225 } 226 227 // Dump module macros. 228 llvm::DenseSet<ModuleMacro*> Active; 229 for (auto *MM : State ? State->getActiveModuleMacros(*this, II) : None) 230 Active.insert(MM); 231 llvm::DenseSet<ModuleMacro*> Visited; 232 llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf.begin(), Leaf.end()); 233 while (!Worklist.empty()) { 234 auto *MM = Worklist.pop_back_val(); 235 llvm::errs() << " ModuleMacro " << MM << " " 236 << MM->getOwningModule()->getFullModuleName(); 237 if (!MM->getMacroInfo()) 238 llvm::errs() << " undef"; 239 240 if (Active.count(MM)) 241 llvm::errs() << " active"; 242 else if (!CurSubmoduleState->VisibleModules.isVisible( 243 MM->getOwningModule())) 244 llvm::errs() << " hidden"; 245 else if (MM->getMacroInfo()) 246 llvm::errs() << " overridden"; 247 248 if (!MM->overrides().empty()) { 249 llvm::errs() << " overrides"; 250 for (auto *O : MM->overrides()) { 251 llvm::errs() << " " << O->getOwningModule()->getFullModuleName(); 252 if (Visited.insert(O).second) 253 Worklist.push_back(O); 254 } 255 } 256 llvm::errs() << "\n"; 257 if (auto *MI = MM->getMacroInfo()) { 258 llvm::errs() << " "; 259 MI->dump(); 260 llvm::errs() << "\n"; 261 } 262 } 263 } 264 265 /// RegisterBuiltinMacro - Register the specified identifier in the identifier 266 /// table and mark it as a builtin macro to be expanded. 267 static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){ 268 // Get the identifier. 269 IdentifierInfo *Id = PP.getIdentifierInfo(Name); 270 271 // Mark it as being a macro that is builtin. 272 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation()); 273 MI->setIsBuiltinMacro(); 274 PP.appendDefMacroDirective(Id, MI); 275 return Id; 276 } 277 278 279 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the 280 /// identifier table. 281 void Preprocessor::RegisterBuiltinMacros() { 282 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__"); 283 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__"); 284 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__"); 285 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__"); 286 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__"); 287 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma"); 288 289 // C++ Standing Document Extensions. 290 if (LangOpts.CPlusPlus) 291 Ident__has_cpp_attribute = 292 RegisterBuiltinMacro(*this, "__has_cpp_attribute"); 293 else 294 Ident__has_cpp_attribute = nullptr; 295 296 // GCC Extensions. 297 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__"); 298 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__"); 299 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__"); 300 301 // Microsoft Extensions. 302 if (LangOpts.MicrosoftExt) { 303 Ident__identifier = RegisterBuiltinMacro(*this, "__identifier"); 304 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma"); 305 } else { 306 Ident__identifier = nullptr; 307 Ident__pragma = nullptr; 308 } 309 310 // Clang Extensions. 311 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature"); 312 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension"); 313 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin"); 314 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute"); 315 Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute"); 316 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include"); 317 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next"); 318 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning"); 319 Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier"); 320 321 // Modules. 322 if (LangOpts.Modules) { 323 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module"); 324 325 // __MODULE__ 326 if (!LangOpts.CurrentModule.empty()) 327 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__"); 328 else 329 Ident__MODULE__ = nullptr; 330 } else { 331 Ident__building_module = nullptr; 332 Ident__MODULE__ = nullptr; 333 } 334 } 335 336 /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token 337 /// in its expansion, currently expands to that token literally. 338 static bool isTrivialSingleTokenExpansion(const MacroInfo *MI, 339 const IdentifierInfo *MacroIdent, 340 Preprocessor &PP) { 341 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo(); 342 343 // If the token isn't an identifier, it's always literally expanded. 344 if (!II) return true; 345 346 // If the information about this identifier is out of date, update it from 347 // the external source. 348 if (II->isOutOfDate()) 349 PP.getExternalSource()->updateOutOfDateIdentifier(*II); 350 351 // If the identifier is a macro, and if that macro is enabled, it may be 352 // expanded so it's not a trivial expansion. 353 if (auto *ExpansionMI = PP.getMacroInfo(II)) 354 if (ExpansionMI->isEnabled() && 355 // Fast expanding "#define X X" is ok, because X would be disabled. 356 II != MacroIdent) 357 return false; 358 359 // If this is an object-like macro invocation, it is safe to trivially expand 360 // it. 361 if (MI->isObjectLike()) return true; 362 363 // If this is a function-like macro invocation, it's safe to trivially expand 364 // as long as the identifier is not a macro argument. 365 return std::find(MI->arg_begin(), MI->arg_end(), II) == MI->arg_end(); 366 367 } 368 369 370 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be 371 /// lexed is a '('. If so, consume the token and return true, if not, this 372 /// method should have no observable side-effect on the lexed tokens. 373 bool Preprocessor::isNextPPTokenLParen() { 374 // Do some quick tests for rejection cases. 375 unsigned Val; 376 if (CurLexer) 377 Val = CurLexer->isNextPPTokenLParen(); 378 else if (CurPTHLexer) 379 Val = CurPTHLexer->isNextPPTokenLParen(); 380 else 381 Val = CurTokenLexer->isNextTokenLParen(); 382 383 if (Val == 2) { 384 // We have run off the end. If it's a source file we don't 385 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the 386 // macro stack. 387 if (CurPPLexer) 388 return false; 389 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) { 390 IncludeStackInfo &Entry = IncludeMacroStack[i-1]; 391 if (Entry.TheLexer) 392 Val = Entry.TheLexer->isNextPPTokenLParen(); 393 else if (Entry.ThePTHLexer) 394 Val = Entry.ThePTHLexer->isNextPPTokenLParen(); 395 else 396 Val = Entry.TheTokenLexer->isNextTokenLParen(); 397 398 if (Val != 2) 399 break; 400 401 // Ran off the end of a source file? 402 if (Entry.ThePPLexer) 403 return false; 404 } 405 } 406 407 // Okay, if we know that the token is a '(', lex it and return. Otherwise we 408 // have found something that isn't a '(' or we found the end of the 409 // translation unit. In either case, return false. 410 return Val == 1; 411 } 412 413 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be 414 /// expanded as a macro, handle it and return the next token as 'Identifier'. 415 bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier, 416 const MacroDefinition &M) { 417 MacroInfo *MI = M.getMacroInfo(); 418 419 // If this is a macro expansion in the "#if !defined(x)" line for the file, 420 // then the macro could expand to different things in other contexts, we need 421 // to disable the optimization in this case. 422 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro(); 423 424 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially. 425 if (MI->isBuiltinMacro()) { 426 if (Callbacks) 427 Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(), 428 /*Args=*/nullptr); 429 ExpandBuiltinMacro(Identifier); 430 return true; 431 } 432 433 /// Args - If this is a function-like macro expansion, this contains, 434 /// for each macro argument, the list of tokens that were provided to the 435 /// invocation. 436 MacroArgs *Args = nullptr; 437 438 // Remember where the end of the expansion occurred. For an object-like 439 // macro, this is the identifier. For a function-like macro, this is the ')'. 440 SourceLocation ExpansionEnd = Identifier.getLocation(); 441 442 // If this is a function-like macro, read the arguments. 443 if (MI->isFunctionLike()) { 444 // Remember that we are now parsing the arguments to a macro invocation. 445 // Preprocessor directives used inside macro arguments are not portable, and 446 // this enables the warning. 447 InMacroArgs = true; 448 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd); 449 450 // Finished parsing args. 451 InMacroArgs = false; 452 453 // If there was an error parsing the arguments, bail out. 454 if (!Args) return true; 455 456 ++NumFnMacroExpanded; 457 } else { 458 ++NumMacroExpanded; 459 } 460 461 // Notice that this macro has been used. 462 markMacroAsUsed(MI); 463 464 // Remember where the token is expanded. 465 SourceLocation ExpandLoc = Identifier.getLocation(); 466 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd); 467 468 if (Callbacks) { 469 if (InMacroArgs) { 470 // We can have macro expansion inside a conditional directive while 471 // reading the function macro arguments. To ensure, in that case, that 472 // MacroExpands callbacks still happen in source order, queue this 473 // callback to have it happen after the function macro callback. 474 DelayedMacroExpandsCallbacks.push_back( 475 MacroExpandsInfo(Identifier, M, ExpansionRange)); 476 } else { 477 Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args); 478 if (!DelayedMacroExpandsCallbacks.empty()) { 479 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) { 480 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i]; 481 // FIXME: We lose macro args info with delayed callback. 482 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range, 483 /*Args=*/nullptr); 484 } 485 DelayedMacroExpandsCallbacks.clear(); 486 } 487 } 488 } 489 490 // If the macro definition is ambiguous, complain. 491 if (M.isAmbiguous()) { 492 Diag(Identifier, diag::warn_pp_ambiguous_macro) 493 << Identifier.getIdentifierInfo(); 494 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen) 495 << Identifier.getIdentifierInfo(); 496 M.forAllDefinitions([&](const MacroInfo *OtherMI) { 497 if (OtherMI != MI) 498 Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other) 499 << Identifier.getIdentifierInfo(); 500 }); 501 } 502 503 // If we started lexing a macro, enter the macro expansion body. 504 505 // If this macro expands to no tokens, don't bother to push it onto the 506 // expansion stack, only to take it right back off. 507 if (MI->getNumTokens() == 0) { 508 // No need for arg info. 509 if (Args) Args->destroy(*this); 510 511 // Propagate whitespace info as if we had pushed, then popped, 512 // a macro context. 513 Identifier.setFlag(Token::LeadingEmptyMacro); 514 PropagateLineStartLeadingSpaceInfo(Identifier); 515 ++NumFastMacroExpanded; 516 return false; 517 } else if (MI->getNumTokens() == 1 && 518 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(), 519 *this)) { 520 // Otherwise, if this macro expands into a single trivially-expanded 521 // token: expand it now. This handles common cases like 522 // "#define VAL 42". 523 524 // No need for arg info. 525 if (Args) Args->destroy(*this); 526 527 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro 528 // identifier to the expanded token. 529 bool isAtStartOfLine = Identifier.isAtStartOfLine(); 530 bool hasLeadingSpace = Identifier.hasLeadingSpace(); 531 532 // Replace the result token. 533 Identifier = MI->getReplacementToken(0); 534 535 // Restore the StartOfLine/LeadingSpace markers. 536 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine); 537 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace); 538 539 // Update the tokens location to include both its expansion and physical 540 // locations. 541 SourceLocation Loc = 542 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc, 543 ExpansionEnd,Identifier.getLength()); 544 Identifier.setLocation(Loc); 545 546 // If this is a disabled macro or #define X X, we must mark the result as 547 // unexpandable. 548 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) { 549 if (MacroInfo *NewMI = getMacroInfo(NewII)) 550 if (!NewMI->isEnabled() || NewMI == MI) { 551 Identifier.setFlag(Token::DisableExpand); 552 // Don't warn for "#define X X" like "#define bool bool" from 553 // stdbool.h. 554 if (NewMI != MI || MI->isFunctionLike()) 555 Diag(Identifier, diag::pp_disabled_macro_expansion); 556 } 557 } 558 559 // Since this is not an identifier token, it can't be macro expanded, so 560 // we're done. 561 ++NumFastMacroExpanded; 562 return true; 563 } 564 565 // Start expanding the macro. 566 EnterMacro(Identifier, ExpansionEnd, MI, Args); 567 return false; 568 } 569 570 enum Bracket { 571 Brace, 572 Paren 573 }; 574 575 /// CheckMatchedBrackets - Returns true if the braces and parentheses in the 576 /// token vector are properly nested. 577 static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) { 578 SmallVector<Bracket, 8> Brackets; 579 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(), 580 E = Tokens.end(); 581 I != E; ++I) { 582 if (I->is(tok::l_paren)) { 583 Brackets.push_back(Paren); 584 } else if (I->is(tok::r_paren)) { 585 if (Brackets.empty() || Brackets.back() == Brace) 586 return false; 587 Brackets.pop_back(); 588 } else if (I->is(tok::l_brace)) { 589 Brackets.push_back(Brace); 590 } else if (I->is(tok::r_brace)) { 591 if (Brackets.empty() || Brackets.back() == Paren) 592 return false; 593 Brackets.pop_back(); 594 } 595 } 596 if (!Brackets.empty()) 597 return false; 598 return true; 599 } 600 601 /// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new 602 /// vector of tokens in NewTokens. The new number of arguments will be placed 603 /// in NumArgs and the ranges which need to surrounded in parentheses will be 604 /// in ParenHints. 605 /// Returns false if the token stream cannot be changed. If this is because 606 /// of an initializer list starting a macro argument, the range of those 607 /// initializer lists will be place in InitLists. 608 static bool GenerateNewArgTokens(Preprocessor &PP, 609 SmallVectorImpl<Token> &OldTokens, 610 SmallVectorImpl<Token> &NewTokens, 611 unsigned &NumArgs, 612 SmallVectorImpl<SourceRange> &ParenHints, 613 SmallVectorImpl<SourceRange> &InitLists) { 614 if (!CheckMatchedBrackets(OldTokens)) 615 return false; 616 617 // Once it is known that the brackets are matched, only a simple count of the 618 // braces is needed. 619 unsigned Braces = 0; 620 621 // First token of a new macro argument. 622 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin(); 623 624 // First closing brace in a new macro argument. Used to generate 625 // SourceRanges for InitLists. 626 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end(); 627 NumArgs = 0; 628 Token TempToken; 629 // Set to true when a macro separator token is found inside a braced list. 630 // If true, the fixed argument spans multiple old arguments and ParenHints 631 // will be updated. 632 bool FoundSeparatorToken = false; 633 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(), 634 E = OldTokens.end(); 635 I != E; ++I) { 636 if (I->is(tok::l_brace)) { 637 ++Braces; 638 } else if (I->is(tok::r_brace)) { 639 --Braces; 640 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken) 641 ClosingBrace = I; 642 } else if (I->is(tok::eof)) { 643 // EOF token is used to separate macro arguments 644 if (Braces != 0) { 645 // Assume comma separator is actually braced list separator and change 646 // it back to a comma. 647 FoundSeparatorToken = true; 648 I->setKind(tok::comma); 649 I->setLength(1); 650 } else { // Braces == 0 651 // Separator token still separates arguments. 652 ++NumArgs; 653 654 // If the argument starts with a brace, it can't be fixed with 655 // parentheses. A different diagnostic will be given. 656 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) { 657 InitLists.push_back( 658 SourceRange(ArgStartIterator->getLocation(), 659 PP.getLocForEndOfToken(ClosingBrace->getLocation()))); 660 ClosingBrace = E; 661 } 662 663 // Add left paren 664 if (FoundSeparatorToken) { 665 TempToken.startToken(); 666 TempToken.setKind(tok::l_paren); 667 TempToken.setLocation(ArgStartIterator->getLocation()); 668 TempToken.setLength(0); 669 NewTokens.push_back(TempToken); 670 } 671 672 // Copy over argument tokens 673 NewTokens.insert(NewTokens.end(), ArgStartIterator, I); 674 675 // Add right paren and store the paren locations in ParenHints 676 if (FoundSeparatorToken) { 677 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation()); 678 TempToken.startToken(); 679 TempToken.setKind(tok::r_paren); 680 TempToken.setLocation(Loc); 681 TempToken.setLength(0); 682 NewTokens.push_back(TempToken); 683 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(), 684 Loc)); 685 } 686 687 // Copy separator token 688 NewTokens.push_back(*I); 689 690 // Reset values 691 ArgStartIterator = I + 1; 692 FoundSeparatorToken = false; 693 } 694 } 695 } 696 697 return !ParenHints.empty() && InitLists.empty(); 698 } 699 700 /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next 701 /// token is the '(' of the macro, this method is invoked to read all of the 702 /// actual arguments specified for the macro invocation. This returns null on 703 /// error. 704 MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, 705 MacroInfo *MI, 706 SourceLocation &MacroEnd) { 707 // The number of fixed arguments to parse. 708 unsigned NumFixedArgsLeft = MI->getNumArgs(); 709 bool isVariadic = MI->isVariadic(); 710 711 // Outer loop, while there are more arguments, keep reading them. 712 Token Tok; 713 714 // Read arguments as unexpanded tokens. This avoids issues, e.g., where 715 // an argument value in a macro could expand to ',' or '(' or ')'. 716 LexUnexpandedToken(Tok); 717 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?"); 718 719 // ArgTokens - Build up a list of tokens that make up each argument. Each 720 // argument is separated by an EOF token. Use a SmallVector so we can avoid 721 // heap allocations in the common case. 722 SmallVector<Token, 64> ArgTokens; 723 bool ContainsCodeCompletionTok = false; 724 725 SourceLocation TooManyArgsLoc; 726 727 unsigned NumActuals = 0; 728 while (Tok.isNot(tok::r_paren)) { 729 if (ContainsCodeCompletionTok && Tok.isOneOf(tok::eof, tok::eod)) 730 break; 731 732 assert(Tok.isOneOf(tok::l_paren, tok::comma) && 733 "only expect argument separators here"); 734 735 unsigned ArgTokenStart = ArgTokens.size(); 736 SourceLocation ArgStartLoc = Tok.getLocation(); 737 738 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note 739 // that we already consumed the first one. 740 unsigned NumParens = 0; 741 742 while (1) { 743 // Read arguments as unexpanded tokens. This avoids issues, e.g., where 744 // an argument value in a macro could expand to ',' or '(' or ')'. 745 LexUnexpandedToken(Tok); 746 747 if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n" 748 if (!ContainsCodeCompletionTok) { 749 Diag(MacroName, diag::err_unterm_macro_invoc); 750 Diag(MI->getDefinitionLoc(), diag::note_macro_here) 751 << MacroName.getIdentifierInfo(); 752 // Do not lose the EOF/EOD. Return it to the client. 753 MacroName = Tok; 754 return nullptr; 755 } else { 756 // Do not lose the EOF/EOD. 757 Token *Toks = new Token[1]; 758 Toks[0] = Tok; 759 EnterTokenStream(Toks, 1, true, true); 760 break; 761 } 762 } else if (Tok.is(tok::r_paren)) { 763 // If we found the ) token, the macro arg list is done. 764 if (NumParens-- == 0) { 765 MacroEnd = Tok.getLocation(); 766 break; 767 } 768 } else if (Tok.is(tok::l_paren)) { 769 ++NumParens; 770 } else if (Tok.is(tok::comma) && NumParens == 0 && 771 !(Tok.getFlags() & Token::IgnoredComma)) { 772 // In Microsoft-compatibility mode, single commas from nested macro 773 // expansions should not be considered as argument separators. We test 774 // for this with the IgnoredComma token flag above. 775 776 // Comma ends this argument if there are more fixed arguments expected. 777 // However, if this is a variadic macro, and this is part of the 778 // variadic part, then the comma is just an argument token. 779 if (!isVariadic) break; 780 if (NumFixedArgsLeft > 1) 781 break; 782 } else if (Tok.is(tok::comment) && !KeepMacroComments) { 783 // If this is a comment token in the argument list and we're just in 784 // -C mode (not -CC mode), discard the comment. 785 continue; 786 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) { 787 // Reading macro arguments can cause macros that we are currently 788 // expanding from to be popped off the expansion stack. Doing so causes 789 // them to be reenabled for expansion. Here we record whether any 790 // identifiers we lex as macro arguments correspond to disabled macros. 791 // If so, we mark the token as noexpand. This is a subtle aspect of 792 // C99 6.10.3.4p2. 793 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo())) 794 if (!MI->isEnabled()) 795 Tok.setFlag(Token::DisableExpand); 796 } else if (Tok.is(tok::code_completion)) { 797 ContainsCodeCompletionTok = true; 798 if (CodeComplete) 799 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(), 800 MI, NumActuals); 801 // Don't mark that we reached the code-completion point because the 802 // parser is going to handle the token and there will be another 803 // code-completion callback. 804 } 805 806 ArgTokens.push_back(Tok); 807 } 808 809 // If this was an empty argument list foo(), don't add this as an empty 810 // argument. 811 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren) 812 break; 813 814 // If this is not a variadic macro, and too many args were specified, emit 815 // an error. 816 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) { 817 if (ArgTokens.size() != ArgTokenStart) 818 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation(); 819 else 820 TooManyArgsLoc = ArgStartLoc; 821 } 822 823 // Empty arguments are standard in C99 and C++0x, and are supported as an 824 // extension in other modes. 825 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99) 826 Diag(Tok, LangOpts.CPlusPlus11 ? 827 diag::warn_cxx98_compat_empty_fnmacro_arg : 828 diag::ext_empty_fnmacro_arg); 829 830 // Add a marker EOF token to the end of the token list for this argument. 831 Token EOFTok; 832 EOFTok.startToken(); 833 EOFTok.setKind(tok::eof); 834 EOFTok.setLocation(Tok.getLocation()); 835 EOFTok.setLength(0); 836 ArgTokens.push_back(EOFTok); 837 ++NumActuals; 838 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0) 839 --NumFixedArgsLeft; 840 } 841 842 // Okay, we either found the r_paren. Check to see if we parsed too few 843 // arguments. 844 unsigned MinArgsExpected = MI->getNumArgs(); 845 846 // If this is not a variadic macro, and too many args were specified, emit 847 // an error. 848 if (!isVariadic && NumActuals > MinArgsExpected && 849 !ContainsCodeCompletionTok) { 850 // Emit the diagnostic at the macro name in case there is a missing ). 851 // Emitting it at the , could be far away from the macro name. 852 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc); 853 Diag(MI->getDefinitionLoc(), diag::note_macro_here) 854 << MacroName.getIdentifierInfo(); 855 856 // Commas from braced initializer lists will be treated as argument 857 // separators inside macros. Attempt to correct for this with parentheses. 858 // TODO: See if this can be generalized to angle brackets for templates 859 // inside macro arguments. 860 861 SmallVector<Token, 4> FixedArgTokens; 862 unsigned FixedNumArgs = 0; 863 SmallVector<SourceRange, 4> ParenHints, InitLists; 864 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs, 865 ParenHints, InitLists)) { 866 if (!InitLists.empty()) { 867 DiagnosticBuilder DB = 868 Diag(MacroName, 869 diag::note_init_list_at_beginning_of_macro_argument); 870 for (const SourceRange &Range : InitLists) 871 DB << Range; 872 } 873 return nullptr; 874 } 875 if (FixedNumArgs != MinArgsExpected) 876 return nullptr; 877 878 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro); 879 for (const SourceRange &ParenLocation : ParenHints) { 880 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "("); 881 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")"); 882 } 883 ArgTokens.swap(FixedArgTokens); 884 NumActuals = FixedNumArgs; 885 } 886 887 // See MacroArgs instance var for description of this. 888 bool isVarargsElided = false; 889 890 if (ContainsCodeCompletionTok) { 891 // Recover from not-fully-formed macro invocation during code-completion. 892 Token EOFTok; 893 EOFTok.startToken(); 894 EOFTok.setKind(tok::eof); 895 EOFTok.setLocation(Tok.getLocation()); 896 EOFTok.setLength(0); 897 for (; NumActuals < MinArgsExpected; ++NumActuals) 898 ArgTokens.push_back(EOFTok); 899 } 900 901 if (NumActuals < MinArgsExpected) { 902 // There are several cases where too few arguments is ok, handle them now. 903 if (NumActuals == 0 && MinArgsExpected == 1) { 904 // #define A(X) or #define A(...) ---> A() 905 906 // If there is exactly one argument, and that argument is missing, 907 // then we have an empty "()" argument empty list. This is fine, even if 908 // the macro expects one argument (the argument is just empty). 909 isVarargsElided = MI->isVariadic(); 910 } else if (MI->isVariadic() && 911 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X) 912 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A() 913 // Varargs where the named vararg parameter is missing: OK as extension. 914 // #define A(x, ...) 915 // A("blah") 916 // 917 // If the macro contains the comma pasting extension, the diagnostic 918 // is suppressed; we know we'll get another diagnostic later. 919 if (!MI->hasCommaPasting()) { 920 Diag(Tok, diag::ext_missing_varargs_arg); 921 Diag(MI->getDefinitionLoc(), diag::note_macro_here) 922 << MacroName.getIdentifierInfo(); 923 } 924 925 // Remember this occurred, allowing us to elide the comma when used for 926 // cases like: 927 // #define A(x, foo...) blah(a, ## foo) 928 // #define B(x, ...) blah(a, ## __VA_ARGS__) 929 // #define C(...) blah(a, ## __VA_ARGS__) 930 // A(x) B(x) C() 931 isVarargsElided = true; 932 } else if (!ContainsCodeCompletionTok) { 933 // Otherwise, emit the error. 934 Diag(Tok, diag::err_too_few_args_in_macro_invoc); 935 Diag(MI->getDefinitionLoc(), diag::note_macro_here) 936 << MacroName.getIdentifierInfo(); 937 return nullptr; 938 } 939 940 // Add a marker EOF token to the end of the token list for this argument. 941 SourceLocation EndLoc = Tok.getLocation(); 942 Tok.startToken(); 943 Tok.setKind(tok::eof); 944 Tok.setLocation(EndLoc); 945 Tok.setLength(0); 946 ArgTokens.push_back(Tok); 947 948 // If we expect two arguments, add both as empty. 949 if (NumActuals == 0 && MinArgsExpected == 2) 950 ArgTokens.push_back(Tok); 951 952 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() && 953 !ContainsCodeCompletionTok) { 954 // Emit the diagnostic at the macro name in case there is a missing ). 955 // Emitting it at the , could be far away from the macro name. 956 Diag(MacroName, diag::err_too_many_args_in_macro_invoc); 957 Diag(MI->getDefinitionLoc(), diag::note_macro_here) 958 << MacroName.getIdentifierInfo(); 959 return nullptr; 960 } 961 962 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this); 963 } 964 965 /// \brief Keeps macro expanded tokens for TokenLexers. 966 // 967 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is 968 /// going to lex in the cache and when it finishes the tokens are removed 969 /// from the end of the cache. 970 Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer, 971 ArrayRef<Token> tokens) { 972 assert(tokLexer); 973 if (tokens.empty()) 974 return nullptr; 975 976 size_t newIndex = MacroExpandedTokens.size(); 977 bool cacheNeedsToGrow = tokens.size() > 978 MacroExpandedTokens.capacity()-MacroExpandedTokens.size(); 979 MacroExpandedTokens.append(tokens.begin(), tokens.end()); 980 981 if (cacheNeedsToGrow) { 982 // Go through all the TokenLexers whose 'Tokens' pointer points in the 983 // buffer and update the pointers to the (potential) new buffer array. 984 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) { 985 TokenLexer *prevLexer; 986 size_t tokIndex; 987 std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i]; 988 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex; 989 } 990 } 991 992 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex)); 993 return MacroExpandedTokens.data() + newIndex; 994 } 995 996 void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() { 997 assert(!MacroExpandingLexersStack.empty()); 998 size_t tokIndex = MacroExpandingLexersStack.back().second; 999 assert(tokIndex < MacroExpandedTokens.size()); 1000 // Pop the cached macro expanded tokens from the end. 1001 MacroExpandedTokens.resize(tokIndex); 1002 MacroExpandingLexersStack.pop_back(); 1003 } 1004 1005 /// ComputeDATE_TIME - Compute the current time, enter it into the specified 1006 /// scratch buffer, then return DATELoc/TIMELoc locations with the position of 1007 /// the identifier tokens inserted. 1008 static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc, 1009 Preprocessor &PP) { 1010 time_t TT = time(nullptr); 1011 struct tm *TM = localtime(&TT); 1012 1013 static const char * const Months[] = { 1014 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" 1015 }; 1016 1017 { 1018 SmallString<32> TmpBuffer; 1019 llvm::raw_svector_ostream TmpStream(TmpBuffer); 1020 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon], 1021 TM->tm_mday, TM->tm_year + 1900); 1022 Token TmpTok; 1023 TmpTok.startToken(); 1024 PP.CreateString(TmpStream.str(), TmpTok); 1025 DATELoc = TmpTok.getLocation(); 1026 } 1027 1028 { 1029 SmallString<32> TmpBuffer; 1030 llvm::raw_svector_ostream TmpStream(TmpBuffer); 1031 TmpStream << llvm::format("\"%02d:%02d:%02d\"", 1032 TM->tm_hour, TM->tm_min, TM->tm_sec); 1033 Token TmpTok; 1034 TmpTok.startToken(); 1035 PP.CreateString(TmpStream.str(), TmpTok); 1036 TIMELoc = TmpTok.getLocation(); 1037 } 1038 } 1039 1040 1041 /// HasFeature - Return true if we recognize and implement the feature 1042 /// specified by the identifier as a standard language feature. 1043 static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) { 1044 const LangOptions &LangOpts = PP.getLangOpts(); 1045 StringRef Feature = II->getName(); 1046 1047 // Normalize the feature name, __foo__ becomes foo. 1048 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4) 1049 Feature = Feature.substr(2, Feature.size() - 4); 1050 1051 return llvm::StringSwitch<bool>(Feature) 1052 .Case("address_sanitizer", 1053 LangOpts.Sanitize.hasOneOf(SanitizerKind::Address | 1054 SanitizerKind::KernelAddress)) 1055 .Case("assume_nonnull", true) 1056 .Case("attribute_analyzer_noreturn", true) 1057 .Case("attribute_availability", true) 1058 .Case("attribute_availability_with_message", true) 1059 .Case("attribute_availability_app_extension", true) 1060 .Case("attribute_availability_with_version_underscores", true) 1061 .Case("attribute_cf_returns_not_retained", true) 1062 .Case("attribute_cf_returns_retained", true) 1063 .Case("attribute_cf_returns_on_parameters", true) 1064 .Case("attribute_deprecated_with_message", true) 1065 .Case("attribute_ext_vector_type", true) 1066 .Case("attribute_ns_returns_not_retained", true) 1067 .Case("attribute_ns_returns_retained", true) 1068 .Case("attribute_ns_consumes_self", true) 1069 .Case("attribute_ns_consumed", true) 1070 .Case("attribute_cf_consumed", true) 1071 .Case("attribute_objc_ivar_unused", true) 1072 .Case("attribute_objc_method_family", true) 1073 .Case("attribute_overloadable", true) 1074 .Case("attribute_unavailable_with_message", true) 1075 .Case("attribute_unused_on_fields", true) 1076 .Case("blocks", LangOpts.Blocks) 1077 .Case("c_thread_safety_attributes", true) 1078 .Case("cxx_exceptions", LangOpts.CXXExceptions) 1079 .Case("cxx_rtti", LangOpts.RTTI) 1080 .Case("enumerator_attributes", true) 1081 .Case("nullability", true) 1082 .Case("memory_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Memory)) 1083 .Case("thread_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Thread)) 1084 .Case("dataflow_sanitizer", LangOpts.Sanitize.has(SanitizerKind::DataFlow)) 1085 // Objective-C features 1086 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE? 1087 .Case("objc_arc", LangOpts.ObjCAutoRefCount) 1088 .Case("objc_arc_weak", LangOpts.ObjCARCWeak) 1089 .Case("objc_default_synthesize_properties", LangOpts.ObjC2) 1090 .Case("objc_fixed_enum", LangOpts.ObjC2) 1091 .Case("objc_instancetype", LangOpts.ObjC2) 1092 .Case("objc_kindof", LangOpts.ObjC2) 1093 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules) 1094 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile()) 1095 .Case("objc_property_explicit_atomic", 1096 true) // Does clang support explicit "atomic" keyword? 1097 .Case("objc_protocol_qualifier_mangling", true) 1098 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport()) 1099 .Case("ownership_holds", true) 1100 .Case("ownership_returns", true) 1101 .Case("ownership_takes", true) 1102 .Case("objc_bool", true) 1103 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile()) 1104 .Case("objc_array_literals", LangOpts.ObjC2) 1105 .Case("objc_dictionary_literals", LangOpts.ObjC2) 1106 .Case("objc_boxed_expressions", LangOpts.ObjC2) 1107 .Case("objc_boxed_nsvalue_expressions", LangOpts.ObjC2) 1108 .Case("arc_cf_code_audited", true) 1109 .Case("objc_bridge_id", true) 1110 .Case("objc_bridge_id_on_typedefs", true) 1111 .Case("objc_generics", LangOpts.ObjC2) 1112 .Case("objc_generics_variance", LangOpts.ObjC2) 1113 // C11 features 1114 .Case("c_alignas", LangOpts.C11) 1115 .Case("c_alignof", LangOpts.C11) 1116 .Case("c_atomic", LangOpts.C11) 1117 .Case("c_generic_selections", LangOpts.C11) 1118 .Case("c_static_assert", LangOpts.C11) 1119 .Case("c_thread_local", 1120 LangOpts.C11 && PP.getTargetInfo().isTLSSupported()) 1121 // C++11 features 1122 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11) 1123 .Case("cxx_alias_templates", LangOpts.CPlusPlus11) 1124 .Case("cxx_alignas", LangOpts.CPlusPlus11) 1125 .Case("cxx_alignof", LangOpts.CPlusPlus11) 1126 .Case("cxx_atomic", LangOpts.CPlusPlus11) 1127 .Case("cxx_attributes", LangOpts.CPlusPlus11) 1128 .Case("cxx_auto_type", LangOpts.CPlusPlus11) 1129 .Case("cxx_constexpr", LangOpts.CPlusPlus11) 1130 .Case("cxx_decltype", LangOpts.CPlusPlus11) 1131 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11) 1132 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11) 1133 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11) 1134 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11) 1135 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11) 1136 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11) 1137 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11) 1138 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11) 1139 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11) 1140 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11) 1141 .Case("cxx_lambdas", LangOpts.CPlusPlus11) 1142 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11) 1143 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11) 1144 .Case("cxx_noexcept", LangOpts.CPlusPlus11) 1145 .Case("cxx_nullptr", LangOpts.CPlusPlus11) 1146 .Case("cxx_override_control", LangOpts.CPlusPlus11) 1147 .Case("cxx_range_for", LangOpts.CPlusPlus11) 1148 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11) 1149 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11) 1150 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11) 1151 .Case("cxx_strong_enums", LangOpts.CPlusPlus11) 1152 .Case("cxx_static_assert", LangOpts.CPlusPlus11) 1153 .Case("cxx_thread_local", 1154 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported()) 1155 .Case("cxx_trailing_return", LangOpts.CPlusPlus11) 1156 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11) 1157 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11) 1158 .Case("cxx_user_literals", LangOpts.CPlusPlus11) 1159 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11) 1160 // C++1y features 1161 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus14) 1162 .Case("cxx_binary_literals", LangOpts.CPlusPlus14) 1163 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus14) 1164 .Case("cxx_decltype_auto", LangOpts.CPlusPlus14) 1165 .Case("cxx_generic_lambdas", LangOpts.CPlusPlus14) 1166 .Case("cxx_init_captures", LangOpts.CPlusPlus14) 1167 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus14) 1168 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus14) 1169 .Case("cxx_variable_templates", LangOpts.CPlusPlus14) 1170 // C++ TSes 1171 //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays) 1172 //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts) 1173 // FIXME: Should this be __has_feature or __has_extension? 1174 //.Case("raw_invocation_type", LangOpts.CPlusPlus) 1175 // Type traits 1176 .Case("has_nothrow_assign", LangOpts.CPlusPlus) 1177 .Case("has_nothrow_copy", LangOpts.CPlusPlus) 1178 .Case("has_nothrow_constructor", LangOpts.CPlusPlus) 1179 .Case("has_trivial_assign", LangOpts.CPlusPlus) 1180 .Case("has_trivial_copy", LangOpts.CPlusPlus) 1181 .Case("has_trivial_constructor", LangOpts.CPlusPlus) 1182 .Case("has_trivial_destructor", LangOpts.CPlusPlus) 1183 .Case("has_virtual_destructor", LangOpts.CPlusPlus) 1184 .Case("is_abstract", LangOpts.CPlusPlus) 1185 .Case("is_base_of", LangOpts.CPlusPlus) 1186 .Case("is_class", LangOpts.CPlusPlus) 1187 .Case("is_constructible", LangOpts.CPlusPlus) 1188 .Case("is_convertible_to", LangOpts.CPlusPlus) 1189 .Case("is_empty", LangOpts.CPlusPlus) 1190 .Case("is_enum", LangOpts.CPlusPlus) 1191 .Case("is_final", LangOpts.CPlusPlus) 1192 .Case("is_literal", LangOpts.CPlusPlus) 1193 .Case("is_standard_layout", LangOpts.CPlusPlus) 1194 .Case("is_pod", LangOpts.CPlusPlus) 1195 .Case("is_polymorphic", LangOpts.CPlusPlus) 1196 .Case("is_sealed", LangOpts.MicrosoftExt) 1197 .Case("is_trivial", LangOpts.CPlusPlus) 1198 .Case("is_trivially_assignable", LangOpts.CPlusPlus) 1199 .Case("is_trivially_constructible", LangOpts.CPlusPlus) 1200 .Case("is_trivially_copyable", LangOpts.CPlusPlus) 1201 .Case("is_union", LangOpts.CPlusPlus) 1202 .Case("modules", LangOpts.Modules) 1203 .Case("safe_stack", LangOpts.Sanitize.has(SanitizerKind::SafeStack)) 1204 .Case("tls", PP.getTargetInfo().isTLSSupported()) 1205 .Case("underlying_type", LangOpts.CPlusPlus) 1206 .Default(false); 1207 } 1208 1209 /// HasExtension - Return true if we recognize and implement the feature 1210 /// specified by the identifier, either as an extension or a standard language 1211 /// feature. 1212 static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) { 1213 if (HasFeature(PP, II)) 1214 return true; 1215 1216 // If the use of an extension results in an error diagnostic, extensions are 1217 // effectively unavailable, so just return false here. 1218 if (PP.getDiagnostics().getExtensionHandlingBehavior() >= 1219 diag::Severity::Error) 1220 return false; 1221 1222 const LangOptions &LangOpts = PP.getLangOpts(); 1223 StringRef Extension = II->getName(); 1224 1225 // Normalize the extension name, __foo__ becomes foo. 1226 if (Extension.startswith("__") && Extension.endswith("__") && 1227 Extension.size() >= 4) 1228 Extension = Extension.substr(2, Extension.size() - 4); 1229 1230 // Because we inherit the feature list from HasFeature, this string switch 1231 // must be less restrictive than HasFeature's. 1232 return llvm::StringSwitch<bool>(Extension) 1233 // C11 features supported by other languages as extensions. 1234 .Case("c_alignas", true) 1235 .Case("c_alignof", true) 1236 .Case("c_atomic", true) 1237 .Case("c_generic_selections", true) 1238 .Case("c_static_assert", true) 1239 .Case("c_thread_local", PP.getTargetInfo().isTLSSupported()) 1240 // C++11 features supported by other languages as extensions. 1241 .Case("cxx_atomic", LangOpts.CPlusPlus) 1242 .Case("cxx_deleted_functions", LangOpts.CPlusPlus) 1243 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus) 1244 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus) 1245 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus) 1246 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus) 1247 .Case("cxx_override_control", LangOpts.CPlusPlus) 1248 .Case("cxx_range_for", LangOpts.CPlusPlus) 1249 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus) 1250 .Case("cxx_rvalue_references", LangOpts.CPlusPlus) 1251 .Case("cxx_variadic_templates", LangOpts.CPlusPlus) 1252 // C++1y features supported by other languages as extensions. 1253 .Case("cxx_binary_literals", true) 1254 .Case("cxx_init_captures", LangOpts.CPlusPlus11) 1255 .Case("cxx_variable_templates", LangOpts.CPlusPlus) 1256 .Default(false); 1257 } 1258 1259 /// EvaluateHasIncludeCommon - Process a '__has_include("path")' 1260 /// or '__has_include_next("path")' expression. 1261 /// Returns true if successful. 1262 static bool EvaluateHasIncludeCommon(Token &Tok, 1263 IdentifierInfo *II, Preprocessor &PP, 1264 const DirectoryLookup *LookupFrom, 1265 const FileEntry *LookupFromFile) { 1266 // Save the location of the current token. If a '(' is later found, use 1267 // that location. If not, use the end of this location instead. 1268 SourceLocation LParenLoc = Tok.getLocation(); 1269 1270 // These expressions are only allowed within a preprocessor directive. 1271 if (!PP.isParsingIfOrElifDirective()) { 1272 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName(); 1273 // Return a valid identifier token. 1274 assert(Tok.is(tok::identifier)); 1275 Tok.setIdentifierInfo(II); 1276 return false; 1277 } 1278 1279 // Get '('. 1280 PP.LexNonComment(Tok); 1281 1282 // Ensure we have a '('. 1283 if (Tok.isNot(tok::l_paren)) { 1284 // No '(', use end of last token. 1285 LParenLoc = PP.getLocForEndOfToken(LParenLoc); 1286 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren; 1287 // If the next token looks like a filename or the start of one, 1288 // assume it is and process it as such. 1289 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) && 1290 !Tok.is(tok::less)) 1291 return false; 1292 } else { 1293 // Save '(' location for possible missing ')' message. 1294 LParenLoc = Tok.getLocation(); 1295 1296 if (PP.getCurrentLexer()) { 1297 // Get the file name. 1298 PP.getCurrentLexer()->LexIncludeFilename(Tok); 1299 } else { 1300 // We're in a macro, so we can't use LexIncludeFilename; just 1301 // grab the next token. 1302 PP.Lex(Tok); 1303 } 1304 } 1305 1306 // Reserve a buffer to get the spelling. 1307 SmallString<128> FilenameBuffer; 1308 StringRef Filename; 1309 SourceLocation EndLoc; 1310 1311 switch (Tok.getKind()) { 1312 case tok::eod: 1313 // If the token kind is EOD, the error has already been diagnosed. 1314 return false; 1315 1316 case tok::angle_string_literal: 1317 case tok::string_literal: { 1318 bool Invalid = false; 1319 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid); 1320 if (Invalid) 1321 return false; 1322 break; 1323 } 1324 1325 case tok::less: 1326 // This could be a <foo/bar.h> file coming from a macro expansion. In this 1327 // case, glue the tokens together into FilenameBuffer and interpret those. 1328 FilenameBuffer.push_back('<'); 1329 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) { 1330 // Let the caller know a <eod> was found by changing the Token kind. 1331 Tok.setKind(tok::eod); 1332 return false; // Found <eod> but no ">"? Diagnostic already emitted. 1333 } 1334 Filename = FilenameBuffer; 1335 break; 1336 default: 1337 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename); 1338 return false; 1339 } 1340 1341 SourceLocation FilenameLoc = Tok.getLocation(); 1342 1343 // Get ')'. 1344 PP.LexNonComment(Tok); 1345 1346 // Ensure we have a trailing ). 1347 if (Tok.isNot(tok::r_paren)) { 1348 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after) 1349 << II << tok::r_paren; 1350 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren; 1351 return false; 1352 } 1353 1354 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename); 1355 // If GetIncludeFilenameSpelling set the start ptr to null, there was an 1356 // error. 1357 if (Filename.empty()) 1358 return false; 1359 1360 // Search include directories. 1361 const DirectoryLookup *CurDir; 1362 const FileEntry *File = 1363 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile, 1364 CurDir, nullptr, nullptr, nullptr); 1365 1366 // Get the result value. A result of true means the file exists. 1367 return File != nullptr; 1368 } 1369 1370 /// EvaluateHasInclude - Process a '__has_include("path")' expression. 1371 /// Returns true if successful. 1372 static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II, 1373 Preprocessor &PP) { 1374 return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr); 1375 } 1376 1377 /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression. 1378 /// Returns true if successful. 1379 static bool EvaluateHasIncludeNext(Token &Tok, 1380 IdentifierInfo *II, Preprocessor &PP) { 1381 // __has_include_next is like __has_include, except that we start 1382 // searching after the current found directory. If we can't do this, 1383 // issue a diagnostic. 1384 // FIXME: Factor out duplication with 1385 // Preprocessor::HandleIncludeNextDirective. 1386 const DirectoryLookup *Lookup = PP.GetCurDirLookup(); 1387 const FileEntry *LookupFromFile = nullptr; 1388 if (PP.isInPrimaryFile()) { 1389 Lookup = nullptr; 1390 PP.Diag(Tok, diag::pp_include_next_in_primary); 1391 } else if (PP.getCurrentSubmodule()) { 1392 // Start looking up in the directory *after* the one in which the current 1393 // file would be found, if any. 1394 assert(PP.getCurrentLexer() && "#include_next directive in macro?"); 1395 LookupFromFile = PP.getCurrentLexer()->getFileEntry(); 1396 Lookup = nullptr; 1397 } else if (!Lookup) { 1398 PP.Diag(Tok, diag::pp_include_next_absolute_path); 1399 } else { 1400 // Start looking up in the next directory. 1401 ++Lookup; 1402 } 1403 1404 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile); 1405 } 1406 1407 /// \brief Process __building_module(identifier) expression. 1408 /// \returns true if we are building the named module, false otherwise. 1409 static bool EvaluateBuildingModule(Token &Tok, 1410 IdentifierInfo *II, Preprocessor &PP) { 1411 // Get '('. 1412 PP.LexNonComment(Tok); 1413 1414 // Ensure we have a '('. 1415 if (Tok.isNot(tok::l_paren)) { 1416 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II 1417 << tok::l_paren; 1418 return false; 1419 } 1420 1421 // Save '(' location for possible missing ')' message. 1422 SourceLocation LParenLoc = Tok.getLocation(); 1423 1424 // Get the module name. 1425 PP.LexNonComment(Tok); 1426 1427 // Ensure that we have an identifier. 1428 if (Tok.isNot(tok::identifier)) { 1429 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module); 1430 return false; 1431 } 1432 1433 bool Result 1434 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule; 1435 1436 // Get ')'. 1437 PP.LexNonComment(Tok); 1438 1439 // Ensure we have a trailing ). 1440 if (Tok.isNot(tok::r_paren)) { 1441 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II 1442 << tok::r_paren; 1443 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren; 1444 return false; 1445 } 1446 1447 return Result; 1448 } 1449 1450 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded 1451 /// as a builtin macro, handle it and return the next token as 'Tok'. 1452 void Preprocessor::ExpandBuiltinMacro(Token &Tok) { 1453 // Figure out which token this is. 1454 IdentifierInfo *II = Tok.getIdentifierInfo(); 1455 assert(II && "Can't be a macro without id info!"); 1456 1457 // If this is an _Pragma or Microsoft __pragma directive, expand it, 1458 // invoke the pragma handler, then lex the token after it. 1459 if (II == Ident_Pragma) 1460 return Handle_Pragma(Tok); 1461 else if (II == Ident__pragma) // in non-MS mode this is null 1462 return HandleMicrosoft__pragma(Tok); 1463 1464 ++NumBuiltinMacroExpanded; 1465 1466 SmallString<128> TmpBuffer; 1467 llvm::raw_svector_ostream OS(TmpBuffer); 1468 1469 // Set up the return result. 1470 Tok.setIdentifierInfo(nullptr); 1471 Tok.clearFlag(Token::NeedsCleaning); 1472 1473 if (II == Ident__LINE__) { 1474 // C99 6.10.8: "__LINE__: The presumed line number (within the current 1475 // source file) of the current source line (an integer constant)". This can 1476 // be affected by #line. 1477 SourceLocation Loc = Tok.getLocation(); 1478 1479 // Advance to the location of the first _, this might not be the first byte 1480 // of the token if it starts with an escaped newline. 1481 Loc = AdvanceToTokenCharacter(Loc, 0); 1482 1483 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of 1484 // a macro expansion. This doesn't matter for object-like macros, but 1485 // can matter for a function-like macro that expands to contain __LINE__. 1486 // Skip down through expansion points until we find a file loc for the 1487 // end of the expansion history. 1488 Loc = SourceMgr.getExpansionRange(Loc).second; 1489 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc); 1490 1491 // __LINE__ expands to a simple numeric value. 1492 OS << (PLoc.isValid()? PLoc.getLine() : 1); 1493 Tok.setKind(tok::numeric_constant); 1494 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) { 1495 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a 1496 // character string literal)". This can be affected by #line. 1497 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); 1498 1499 // __BASE_FILE__ is a GNU extension that returns the top of the presumed 1500 // #include stack instead of the current file. 1501 if (II == Ident__BASE_FILE__ && PLoc.isValid()) { 1502 SourceLocation NextLoc = PLoc.getIncludeLoc(); 1503 while (NextLoc.isValid()) { 1504 PLoc = SourceMgr.getPresumedLoc(NextLoc); 1505 if (PLoc.isInvalid()) 1506 break; 1507 1508 NextLoc = PLoc.getIncludeLoc(); 1509 } 1510 } 1511 1512 // Escape this filename. Turn '\' -> '\\' '"' -> '\"' 1513 SmallString<128> FN; 1514 if (PLoc.isValid()) { 1515 FN += PLoc.getFilename(); 1516 Lexer::Stringify(FN); 1517 OS << '"' << FN << '"'; 1518 } 1519 Tok.setKind(tok::string_literal); 1520 } else if (II == Ident__DATE__) { 1521 Diag(Tok.getLocation(), diag::warn_pp_date_time); 1522 if (!DATELoc.isValid()) 1523 ComputeDATE_TIME(DATELoc, TIMELoc, *this); 1524 Tok.setKind(tok::string_literal); 1525 Tok.setLength(strlen("\"Mmm dd yyyy\"")); 1526 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(), 1527 Tok.getLocation(), 1528 Tok.getLength())); 1529 return; 1530 } else if (II == Ident__TIME__) { 1531 Diag(Tok.getLocation(), diag::warn_pp_date_time); 1532 if (!TIMELoc.isValid()) 1533 ComputeDATE_TIME(DATELoc, TIMELoc, *this); 1534 Tok.setKind(tok::string_literal); 1535 Tok.setLength(strlen("\"hh:mm:ss\"")); 1536 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(), 1537 Tok.getLocation(), 1538 Tok.getLength())); 1539 return; 1540 } else if (II == Ident__INCLUDE_LEVEL__) { 1541 // Compute the presumed include depth of this token. This can be affected 1542 // by GNU line markers. 1543 unsigned Depth = 0; 1544 1545 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); 1546 if (PLoc.isValid()) { 1547 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); 1548 for (; PLoc.isValid(); ++Depth) 1549 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); 1550 } 1551 1552 // __INCLUDE_LEVEL__ expands to a simple numeric value. 1553 OS << Depth; 1554 Tok.setKind(tok::numeric_constant); 1555 } else if (II == Ident__TIMESTAMP__) { 1556 Diag(Tok.getLocation(), diag::warn_pp_date_time); 1557 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be 1558 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime. 1559 1560 // Get the file that we are lexing out of. If we're currently lexing from 1561 // a macro, dig into the include stack. 1562 const FileEntry *CurFile = nullptr; 1563 PreprocessorLexer *TheLexer = getCurrentFileLexer(); 1564 1565 if (TheLexer) 1566 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID()); 1567 1568 const char *Result; 1569 if (CurFile) { 1570 time_t TT = CurFile->getModificationTime(); 1571 struct tm *TM = localtime(&TT); 1572 Result = asctime(TM); 1573 } else { 1574 Result = "??? ??? ?? ??:??:?? ????\n"; 1575 } 1576 // Surround the string with " and strip the trailing newline. 1577 OS << '"' << StringRef(Result).drop_back() << '"'; 1578 Tok.setKind(tok::string_literal); 1579 } else if (II == Ident__COUNTER__) { 1580 // __COUNTER__ expands to a simple numeric value. 1581 OS << CounterValue++; 1582 Tok.setKind(tok::numeric_constant); 1583 } else if (II == Ident__has_feature || 1584 II == Ident__has_extension || 1585 II == Ident__has_builtin || 1586 II == Ident__is_identifier || 1587 II == Ident__has_attribute || 1588 II == Ident__has_declspec || 1589 II == Ident__has_cpp_attribute) { 1590 // The argument to these builtins should be a parenthesized identifier. 1591 SourceLocation StartLoc = Tok.getLocation(); 1592 1593 bool IsValid = false; 1594 IdentifierInfo *FeatureII = nullptr; 1595 IdentifierInfo *ScopeII = nullptr; 1596 1597 // Read the '('. 1598 LexUnexpandedToken(Tok); 1599 if (Tok.is(tok::l_paren)) { 1600 // Read the identifier 1601 LexUnexpandedToken(Tok); 1602 if ((FeatureII = Tok.getIdentifierInfo())) { 1603 // If we're checking __has_cpp_attribute, it is possible to receive a 1604 // scope token. Read the "::", if it's available. 1605 LexUnexpandedToken(Tok); 1606 bool IsScopeValid = true; 1607 if (II == Ident__has_cpp_attribute && Tok.is(tok::coloncolon)) { 1608 LexUnexpandedToken(Tok); 1609 // The first thing we read was not the feature, it was the scope. 1610 ScopeII = FeatureII; 1611 if ((FeatureII = Tok.getIdentifierInfo())) 1612 LexUnexpandedToken(Tok); 1613 else 1614 IsScopeValid = false; 1615 } 1616 // Read the closing paren. 1617 if (IsScopeValid && Tok.is(tok::r_paren)) 1618 IsValid = true; 1619 } 1620 // Eat tokens until ')'. 1621 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) && 1622 Tok.isNot(tok::eof)) 1623 LexUnexpandedToken(Tok); 1624 } 1625 1626 int Value = 0; 1627 if (!IsValid) 1628 Diag(StartLoc, diag::err_feature_check_malformed); 1629 else if (II == Ident__is_identifier) 1630 Value = FeatureII->getTokenID() == tok::identifier; 1631 else if (II == Ident__has_builtin) { 1632 // Check for a builtin is trivial. 1633 Value = FeatureII->getBuiltinID() != 0; 1634 } else if (II == Ident__has_attribute) 1635 Value = hasAttribute(AttrSyntax::GNU, nullptr, FeatureII, 1636 getTargetInfo(), getLangOpts()); 1637 else if (II == Ident__has_cpp_attribute) 1638 Value = hasAttribute(AttrSyntax::CXX, ScopeII, FeatureII, 1639 getTargetInfo(), getLangOpts()); 1640 else if (II == Ident__has_declspec) 1641 Value = hasAttribute(AttrSyntax::Declspec, nullptr, FeatureII, 1642 getTargetInfo(), getLangOpts()); 1643 else if (II == Ident__has_extension) 1644 Value = HasExtension(*this, FeatureII); 1645 else { 1646 assert(II == Ident__has_feature && "Must be feature check"); 1647 Value = HasFeature(*this, FeatureII); 1648 } 1649 1650 if (!IsValid) 1651 return; 1652 OS << Value; 1653 Tok.setKind(tok::numeric_constant); 1654 } else if (II == Ident__has_include || 1655 II == Ident__has_include_next) { 1656 // The argument to these two builtins should be a parenthesized 1657 // file name string literal using angle brackets (<>) or 1658 // double-quotes (""). 1659 bool Value; 1660 if (II == Ident__has_include) 1661 Value = EvaluateHasInclude(Tok, II, *this); 1662 else 1663 Value = EvaluateHasIncludeNext(Tok, II, *this); 1664 1665 if (Tok.isNot(tok::r_paren)) 1666 return; 1667 OS << (int)Value; 1668 Tok.setKind(tok::numeric_constant); 1669 } else if (II == Ident__has_warning) { 1670 // The argument should be a parenthesized string literal. 1671 // The argument to these builtins should be a parenthesized identifier. 1672 SourceLocation StartLoc = Tok.getLocation(); 1673 bool IsValid = false; 1674 bool Value = false; 1675 // Read the '('. 1676 LexUnexpandedToken(Tok); 1677 do { 1678 if (Tok.isNot(tok::l_paren)) { 1679 Diag(StartLoc, diag::err_warning_check_malformed); 1680 break; 1681 } 1682 1683 LexUnexpandedToken(Tok); 1684 std::string WarningName; 1685 SourceLocation StrStartLoc = Tok.getLocation(); 1686 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'", 1687 /*MacroExpansion=*/false)) { 1688 // Eat tokens until ')'. 1689 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) && 1690 Tok.isNot(tok::eof)) 1691 LexUnexpandedToken(Tok); 1692 break; 1693 } 1694 1695 // Is the end a ')'? 1696 if (!(IsValid = Tok.is(tok::r_paren))) { 1697 Diag(StartLoc, diag::err_warning_check_malformed); 1698 break; 1699 } 1700 1701 // FIXME: Should we accept "-R..." flags here, or should that be handled 1702 // by a separate __has_remark? 1703 if (WarningName.size() < 3 || WarningName[0] != '-' || 1704 WarningName[1] != 'W') { 1705 Diag(StrStartLoc, diag::warn_has_warning_invalid_option); 1706 break; 1707 } 1708 1709 // Finally, check if the warning flags maps to a diagnostic group. 1710 // We construct a SmallVector here to talk to getDiagnosticIDs(). 1711 // Although we don't use the result, this isn't a hot path, and not 1712 // worth special casing. 1713 SmallVector<diag::kind, 10> Diags; 1714 Value = !getDiagnostics().getDiagnosticIDs()-> 1715 getDiagnosticsInGroup(diag::Flavor::WarningOrError, 1716 WarningName.substr(2), Diags); 1717 } while (false); 1718 1719 if (!IsValid) 1720 return; 1721 OS << (int)Value; 1722 Tok.setKind(tok::numeric_constant); 1723 } else if (II == Ident__building_module) { 1724 // The argument to this builtin should be an identifier. The 1725 // builtin evaluates to 1 when that identifier names the module we are 1726 // currently building. 1727 OS << (int)EvaluateBuildingModule(Tok, II, *this); 1728 Tok.setKind(tok::numeric_constant); 1729 } else if (II == Ident__MODULE__) { 1730 // The current module as an identifier. 1731 OS << getLangOpts().CurrentModule; 1732 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule); 1733 Tok.setIdentifierInfo(ModuleII); 1734 Tok.setKind(ModuleII->getTokenID()); 1735 } else if (II == Ident__identifier) { 1736 SourceLocation Loc = Tok.getLocation(); 1737 1738 // We're expecting '__identifier' '(' identifier ')'. Try to recover 1739 // if the parens are missing. 1740 LexNonComment(Tok); 1741 if (Tok.isNot(tok::l_paren)) { 1742 // No '(', use end of last token. 1743 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after) 1744 << II << tok::l_paren; 1745 // If the next token isn't valid as our argument, we can't recover. 1746 if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) 1747 Tok.setKind(tok::identifier); 1748 return; 1749 } 1750 1751 SourceLocation LParenLoc = Tok.getLocation(); 1752 LexNonComment(Tok); 1753 1754 if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) 1755 Tok.setKind(tok::identifier); 1756 else { 1757 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier) 1758 << Tok.getKind(); 1759 // Don't walk past anything that's not a real token. 1760 if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation()) 1761 return; 1762 } 1763 1764 // Discard the ')', preserving 'Tok' as our result. 1765 Token RParen; 1766 LexNonComment(RParen); 1767 if (RParen.isNot(tok::r_paren)) { 1768 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after) 1769 << Tok.getKind() << tok::r_paren; 1770 Diag(LParenLoc, diag::note_matching) << tok::l_paren; 1771 } 1772 return; 1773 } else { 1774 llvm_unreachable("Unknown identifier!"); 1775 } 1776 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation()); 1777 } 1778 1779 void Preprocessor::markMacroAsUsed(MacroInfo *MI) { 1780 // If the 'used' status changed, and the macro requires 'unused' warning, 1781 // remove its SourceLocation from the warn-for-unused-macro locations. 1782 if (MI->isWarnIfUnused() && !MI->isUsed()) 1783 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); 1784 MI->setIsUsed(true); 1785 } 1786