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