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