1 //===- Preprocess.cpp - C Language Family Preprocessor Implementation -----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Preprocessor interface. 11 // 12 //===----------------------------------------------------------------------===// 13 // 14 // Options to support: 15 // -H - Print the name of each header file used. 16 // -d[DNI] - Dump various things. 17 // -fworking-directory - #line's with preprocessor's working dir. 18 // -fpreprocessed 19 // -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD 20 // -W* 21 // -w 22 // 23 // Messages to emit: 24 // "Multiple include guards may be useful for:\n" 25 // 26 //===----------------------------------------------------------------------===// 27 28 #include "clang/Lex/Preprocessor.h" 29 #include "clang/Basic/FileManager.h" 30 #include "clang/Basic/FileSystemStatCache.h" 31 #include "clang/Basic/IdentifierTable.h" 32 #include "clang/Basic/LLVM.h" 33 #include "clang/Basic/LangOptions.h" 34 #include "clang/Basic/Module.h" 35 #include "clang/Basic/SourceLocation.h" 36 #include "clang/Basic/SourceManager.h" 37 #include "clang/Basic/TargetInfo.h" 38 #include "clang/Lex/CodeCompletionHandler.h" 39 #include "clang/Lex/ExternalPreprocessorSource.h" 40 #include "clang/Lex/HeaderSearch.h" 41 #include "clang/Lex/LexDiagnostic.h" 42 #include "clang/Lex/Lexer.h" 43 #include "clang/Lex/LiteralSupport.h" 44 #include "clang/Lex/MacroArgs.h" 45 #include "clang/Lex/MacroInfo.h" 46 #include "clang/Lex/ModuleLoader.h" 47 #include "clang/Lex/PTHLexer.h" 48 #include "clang/Lex/PTHManager.h" 49 #include "clang/Lex/Pragma.h" 50 #include "clang/Lex/PreprocessingRecord.h" 51 #include "clang/Lex/PreprocessorLexer.h" 52 #include "clang/Lex/PreprocessorOptions.h" 53 #include "clang/Lex/ScratchBuffer.h" 54 #include "clang/Lex/Token.h" 55 #include "clang/Lex/TokenLexer.h" 56 #include "llvm/ADT/APInt.h" 57 #include "llvm/ADT/ArrayRef.h" 58 #include "llvm/ADT/DenseMap.h" 59 #include "llvm/ADT/SmallString.h" 60 #include "llvm/ADT/SmallVector.h" 61 #include "llvm/ADT/STLExtras.h" 62 #include "llvm/ADT/StringRef.h" 63 #include "llvm/ADT/StringSwitch.h" 64 #include "llvm/Support/Capacity.h" 65 #include "llvm/Support/ErrorHandling.h" 66 #include "llvm/Support/MemoryBuffer.h" 67 #include "llvm/Support/raw_ostream.h" 68 #include <algorithm> 69 #include <cassert> 70 #include <memory> 71 #include <string> 72 #include <utility> 73 #include <vector> 74 75 using namespace clang; 76 77 LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry) 78 79 ExternalPreprocessorSource::~ExternalPreprocessorSource() = default; 80 81 Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts, 82 DiagnosticsEngine &diags, LangOptions &opts, 83 SourceManager &SM, MemoryBufferCache &PCMCache, 84 HeaderSearch &Headers, ModuleLoader &TheModuleLoader, 85 IdentifierInfoLookup *IILookup, bool OwnsHeaders, 86 TranslationUnitKind TUKind) 87 : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts), 88 FileMgr(Headers.getFileMgr()), SourceMgr(SM), PCMCache(PCMCache), 89 ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers), 90 TheModuleLoader(TheModuleLoader), ExternalSource(nullptr), 91 // As the language options may have not been loaded yet (when 92 // deserializing an ASTUnit), adding keywords to the identifier table is 93 // deferred to Preprocessor::Initialize(). 94 Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())), 95 TUKind(TUKind), SkipMainFilePreamble(0, true), 96 CurSubmoduleState(&NullSubmoduleState) { 97 OwnsHeaderSearch = OwnsHeaders; 98 99 // Default to discarding comments. 100 KeepComments = false; 101 KeepMacroComments = false; 102 SuppressIncludeNotFoundError = false; 103 104 // Macro expansion is enabled. 105 DisableMacroExpansion = false; 106 MacroExpansionInDirectivesOverride = false; 107 InMacroArgs = false; 108 InMacroArgPreExpansion = false; 109 NumCachedTokenLexers = 0; 110 PragmasEnabled = true; 111 ParsingIfOrElifDirective = false; 112 PreprocessedOutput = false; 113 114 // We haven't read anything from the external source. 115 ReadMacrosFromExternalSource = false; 116 117 // "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of 118 // a macro. They get unpoisoned where it is allowed. 119 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned(); 120 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use); 121 if (getLangOpts().CPlusPlus2a) { 122 (Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned(); 123 SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use); 124 } else { 125 Ident__VA_OPT__ = nullptr; 126 } 127 128 // Initialize the pragma handlers. 129 RegisterBuiltinPragmas(); 130 131 // Initialize builtin macros like __LINE__ and friends. 132 RegisterBuiltinMacros(); 133 134 if(LangOpts.Borland) { 135 Ident__exception_info = getIdentifierInfo("_exception_info"); 136 Ident___exception_info = getIdentifierInfo("__exception_info"); 137 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation"); 138 Ident__exception_code = getIdentifierInfo("_exception_code"); 139 Ident___exception_code = getIdentifierInfo("__exception_code"); 140 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode"); 141 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination"); 142 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination"); 143 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination"); 144 } else { 145 Ident__exception_info = Ident__exception_code = nullptr; 146 Ident__abnormal_termination = Ident___exception_info = nullptr; 147 Ident___exception_code = Ident___abnormal_termination = nullptr; 148 Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr; 149 Ident_AbnormalTermination = nullptr; 150 } 151 152 // If using a PCH with a through header, start skipping tokens. 153 if (!this->PPOpts->PCHThroughHeader.empty() && 154 !this->PPOpts->ImplicitPCHInclude.empty()) 155 SkippingUntilPCHThroughHeader = true; 156 157 if (this->PPOpts->GeneratePreamble) 158 PreambleConditionalStack.startRecording(); 159 } 160 161 Preprocessor::~Preprocessor() { 162 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!"); 163 164 IncludeMacroStack.clear(); 165 166 // Destroy any macro definitions. 167 while (MacroInfoChain *I = MIChainHead) { 168 MIChainHead = I->Next; 169 I->~MacroInfoChain(); 170 } 171 172 // Free any cached macro expanders. 173 // This populates MacroArgCache, so all TokenLexers need to be destroyed 174 // before the code below that frees up the MacroArgCache list. 175 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr); 176 CurTokenLexer.reset(); 177 178 // Free any cached MacroArgs. 179 for (MacroArgs *ArgList = MacroArgCache; ArgList;) 180 ArgList = ArgList->deallocate(); 181 182 // Delete the header search info, if we own it. 183 if (OwnsHeaderSearch) 184 delete &HeaderInfo; 185 } 186 187 void Preprocessor::Initialize(const TargetInfo &Target, 188 const TargetInfo *AuxTarget) { 189 assert((!this->Target || this->Target == &Target) && 190 "Invalid override of target information"); 191 this->Target = &Target; 192 193 assert((!this->AuxTarget || this->AuxTarget == AuxTarget) && 194 "Invalid override of aux target information."); 195 this->AuxTarget = AuxTarget; 196 197 // Initialize information about built-ins. 198 BuiltinInfo.InitializeTarget(Target, AuxTarget); 199 HeaderInfo.setTarget(Target); 200 201 // Populate the identifier table with info about keywords for the current language. 202 Identifiers.AddKeywords(LangOpts); 203 } 204 205 void Preprocessor::InitializeForModelFile() { 206 NumEnteredSourceFiles = 0; 207 208 // Reset pragmas 209 PragmaHandlersBackup = std::move(PragmaHandlers); 210 PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef()); 211 RegisterBuiltinPragmas(); 212 213 // Reset PredefinesFileID 214 PredefinesFileID = FileID(); 215 } 216 217 void Preprocessor::FinalizeForModelFile() { 218 NumEnteredSourceFiles = 1; 219 220 PragmaHandlers = std::move(PragmaHandlersBackup); 221 } 222 223 void Preprocessor::setPTHManager(PTHManager* pm) { 224 PTH.reset(pm); 225 FileMgr.addStatCache(PTH->createStatCache()); 226 } 227 228 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const { 229 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '" 230 << getSpelling(Tok) << "'"; 231 232 if (!DumpFlags) return; 233 234 llvm::errs() << "\t"; 235 if (Tok.isAtStartOfLine()) 236 llvm::errs() << " [StartOfLine]"; 237 if (Tok.hasLeadingSpace()) 238 llvm::errs() << " [LeadingSpace]"; 239 if (Tok.isExpandDisabled()) 240 llvm::errs() << " [ExpandDisabled]"; 241 if (Tok.needsCleaning()) { 242 const char *Start = SourceMgr.getCharacterData(Tok.getLocation()); 243 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength()) 244 << "']"; 245 } 246 247 llvm::errs() << "\tLoc=<"; 248 DumpLocation(Tok.getLocation()); 249 llvm::errs() << ">"; 250 } 251 252 void Preprocessor::DumpLocation(SourceLocation Loc) const { 253 Loc.dump(SourceMgr); 254 } 255 256 void Preprocessor::DumpMacro(const MacroInfo &MI) const { 257 llvm::errs() << "MACRO: "; 258 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) { 259 DumpToken(MI.getReplacementToken(i)); 260 llvm::errs() << " "; 261 } 262 llvm::errs() << "\n"; 263 } 264 265 void Preprocessor::PrintStats() { 266 llvm::errs() << "\n*** Preprocessor Stats:\n"; 267 llvm::errs() << NumDirectives << " directives found:\n"; 268 llvm::errs() << " " << NumDefined << " #define.\n"; 269 llvm::errs() << " " << NumUndefined << " #undef.\n"; 270 llvm::errs() << " #include/#include_next/#import:\n"; 271 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n"; 272 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n"; 273 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n"; 274 llvm::errs() << " " << NumElse << " #else/#elif.\n"; 275 llvm::errs() << " " << NumEndif << " #endif.\n"; 276 llvm::errs() << " " << NumPragma << " #pragma.\n"; 277 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n"; 278 279 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/" 280 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, " 281 << NumFastMacroExpanded << " on the fast path.\n"; 282 llvm::errs() << (NumFastTokenPaste+NumTokenPaste) 283 << " token paste (##) operations performed, " 284 << NumFastTokenPaste << " on the fast path.\n"; 285 286 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total"; 287 288 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory(); 289 llvm::errs() << "\n Macro Expanded Tokens: " 290 << llvm::capacity_in_bytes(MacroExpandedTokens); 291 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity(); 292 // FIXME: List information for all submodules. 293 llvm::errs() << "\n Macros: " 294 << llvm::capacity_in_bytes(CurSubmoduleState->Macros); 295 llvm::errs() << "\n #pragma push_macro Info: " 296 << llvm::capacity_in_bytes(PragmaPushMacroInfo); 297 llvm::errs() << "\n Poison Reasons: " 298 << llvm::capacity_in_bytes(PoisonReasons); 299 llvm::errs() << "\n Comment Handlers: " 300 << llvm::capacity_in_bytes(CommentHandlers) << "\n"; 301 } 302 303 Preprocessor::macro_iterator 304 Preprocessor::macro_begin(bool IncludeExternalMacros) const { 305 if (IncludeExternalMacros && ExternalSource && 306 !ReadMacrosFromExternalSource) { 307 ReadMacrosFromExternalSource = true; 308 ExternalSource->ReadDefinedMacros(); 309 } 310 311 // Make sure we cover all macros in visible modules. 312 for (const ModuleMacro &Macro : ModuleMacros) 313 CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState())); 314 315 return CurSubmoduleState->Macros.begin(); 316 } 317 318 size_t Preprocessor::getTotalMemory() const { 319 return BP.getTotalMemory() 320 + llvm::capacity_in_bytes(MacroExpandedTokens) 321 + Predefines.capacity() /* Predefines buffer. */ 322 // FIXME: Include sizes from all submodules, and include MacroInfo sizes, 323 // and ModuleMacros. 324 + llvm::capacity_in_bytes(CurSubmoduleState->Macros) 325 + llvm::capacity_in_bytes(PragmaPushMacroInfo) 326 + llvm::capacity_in_bytes(PoisonReasons) 327 + llvm::capacity_in_bytes(CommentHandlers); 328 } 329 330 Preprocessor::macro_iterator 331 Preprocessor::macro_end(bool IncludeExternalMacros) const { 332 if (IncludeExternalMacros && ExternalSource && 333 !ReadMacrosFromExternalSource) { 334 ReadMacrosFromExternalSource = true; 335 ExternalSource->ReadDefinedMacros(); 336 } 337 338 return CurSubmoduleState->Macros.end(); 339 } 340 341 /// Compares macro tokens with a specified token value sequence. 342 static bool MacroDefinitionEquals(const MacroInfo *MI, 343 ArrayRef<TokenValue> Tokens) { 344 return Tokens.size() == MI->getNumTokens() && 345 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin()); 346 } 347 348 StringRef Preprocessor::getLastMacroWithSpelling( 349 SourceLocation Loc, 350 ArrayRef<TokenValue> Tokens) const { 351 SourceLocation BestLocation; 352 StringRef BestSpelling; 353 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end(); 354 I != E; ++I) { 355 const MacroDirective::DefInfo 356 Def = I->second.findDirectiveAtLoc(Loc, SourceMgr); 357 if (!Def || !Def.getMacroInfo()) 358 continue; 359 if (!Def.getMacroInfo()->isObjectLike()) 360 continue; 361 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens)) 362 continue; 363 SourceLocation Location = Def.getLocation(); 364 // Choose the macro defined latest. 365 if (BestLocation.isInvalid() || 366 (Location.isValid() && 367 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) { 368 BestLocation = Location; 369 BestSpelling = I->first->getName(); 370 } 371 } 372 return BestSpelling; 373 } 374 375 void Preprocessor::recomputeCurLexerKind() { 376 if (CurLexer) 377 CurLexerKind = CLK_Lexer; 378 else if (CurPTHLexer) 379 CurLexerKind = CLK_PTHLexer; 380 else if (CurTokenLexer) 381 CurLexerKind = CLK_TokenLexer; 382 else 383 CurLexerKind = CLK_CachingLexer; 384 } 385 386 bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File, 387 unsigned CompleteLine, 388 unsigned CompleteColumn) { 389 assert(File); 390 assert(CompleteLine && CompleteColumn && "Starts from 1:1"); 391 assert(!CodeCompletionFile && "Already set"); 392 393 using llvm::MemoryBuffer; 394 395 // Load the actual file's contents. 396 bool Invalid = false; 397 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid); 398 if (Invalid) 399 return true; 400 401 // Find the byte position of the truncation point. 402 const char *Position = Buffer->getBufferStart(); 403 for (unsigned Line = 1; Line < CompleteLine; ++Line) { 404 for (; *Position; ++Position) { 405 if (*Position != '\r' && *Position != '\n') 406 continue; 407 408 // Eat \r\n or \n\r as a single line. 409 if ((Position[1] == '\r' || Position[1] == '\n') && 410 Position[0] != Position[1]) 411 ++Position; 412 ++Position; 413 break; 414 } 415 } 416 417 Position += CompleteColumn - 1; 418 419 // If pointing inside the preamble, adjust the position at the beginning of 420 // the file after the preamble. 421 if (SkipMainFilePreamble.first && 422 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) { 423 if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first) 424 Position = Buffer->getBufferStart() + SkipMainFilePreamble.first; 425 } 426 427 if (Position > Buffer->getBufferEnd()) 428 Position = Buffer->getBufferEnd(); 429 430 CodeCompletionFile = File; 431 CodeCompletionOffset = Position - Buffer->getBufferStart(); 432 433 auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer( 434 Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier()); 435 char *NewBuf = NewBuffer->getBufferStart(); 436 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf); 437 *NewPos = '\0'; 438 std::copy(Position, Buffer->getBufferEnd(), NewPos+1); 439 SourceMgr.overrideFileContents(File, std::move(NewBuffer)); 440 441 return false; 442 } 443 444 void Preprocessor::CodeCompleteNaturalLanguage() { 445 if (CodeComplete) 446 CodeComplete->CodeCompleteNaturalLanguage(); 447 setCodeCompletionReached(); 448 } 449 450 /// getSpelling - This method is used to get the spelling of a token into a 451 /// SmallVector. Note that the returned StringRef may not point to the 452 /// supplied buffer if a copy can be avoided. 453 StringRef Preprocessor::getSpelling(const Token &Tok, 454 SmallVectorImpl<char> &Buffer, 455 bool *Invalid) const { 456 // NOTE: this has to be checked *before* testing for an IdentifierInfo. 457 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) { 458 // Try the fast path. 459 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) 460 return II->getName(); 461 } 462 463 // Resize the buffer if we need to copy into it. 464 if (Tok.needsCleaning()) 465 Buffer.resize(Tok.getLength()); 466 467 const char *Ptr = Buffer.data(); 468 unsigned Len = getSpelling(Tok, Ptr, Invalid); 469 return StringRef(Ptr, Len); 470 } 471 472 /// CreateString - Plop the specified string into a scratch buffer and return a 473 /// location for it. If specified, the source location provides a source 474 /// location for the token. 475 void Preprocessor::CreateString(StringRef Str, Token &Tok, 476 SourceLocation ExpansionLocStart, 477 SourceLocation ExpansionLocEnd) { 478 Tok.setLength(Str.size()); 479 480 const char *DestPtr; 481 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr); 482 483 if (ExpansionLocStart.isValid()) 484 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart, 485 ExpansionLocEnd, Str.size()); 486 Tok.setLocation(Loc); 487 488 // If this is a raw identifier or a literal token, set the pointer data. 489 if (Tok.is(tok::raw_identifier)) 490 Tok.setRawIdentifierData(DestPtr); 491 else if (Tok.isLiteral()) 492 Tok.setLiteralData(DestPtr); 493 } 494 495 SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) { 496 auto &SM = getSourceManager(); 497 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc); 498 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc); 499 bool Invalid = false; 500 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 501 if (Invalid) 502 return SourceLocation(); 503 504 // FIXME: We could consider re-using spelling for tokens we see repeatedly. 505 const char *DestPtr; 506 SourceLocation Spelling = 507 ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr); 508 return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length)); 509 } 510 511 Module *Preprocessor::getCurrentModule() { 512 if (!getLangOpts().isCompilingModule()) 513 return nullptr; 514 515 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule); 516 } 517 518 //===----------------------------------------------------------------------===// 519 // Preprocessor Initialization Methods 520 //===----------------------------------------------------------------------===// 521 522 /// EnterMainSourceFile - Enter the specified FileID as the main source file, 523 /// which implicitly adds the builtin defines etc. 524 void Preprocessor::EnterMainSourceFile() { 525 // We do not allow the preprocessor to reenter the main file. Doing so will 526 // cause FileID's to accumulate information from both runs (e.g. #line 527 // information) and predefined macros aren't guaranteed to be set properly. 528 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!"); 529 FileID MainFileID = SourceMgr.getMainFileID(); 530 531 // If MainFileID is loaded it means we loaded an AST file, no need to enter 532 // a main file. 533 if (!SourceMgr.isLoadedFileID(MainFileID)) { 534 // Enter the main file source buffer. 535 EnterSourceFile(MainFileID, nullptr, SourceLocation()); 536 537 // If we've been asked to skip bytes in the main file (e.g., as part of a 538 // precompiled preamble), do so now. 539 if (SkipMainFilePreamble.first > 0) 540 CurLexer->SetByteOffset(SkipMainFilePreamble.first, 541 SkipMainFilePreamble.second); 542 543 // Tell the header info that the main file was entered. If the file is later 544 // #imported, it won't be re-entered. 545 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID)) 546 HeaderInfo.IncrementIncludeCount(FE); 547 } 548 549 // Preprocess Predefines to populate the initial preprocessor state. 550 std::unique_ptr<llvm::MemoryBuffer> SB = 551 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>"); 552 assert(SB && "Cannot create predefined source buffer"); 553 FileID FID = SourceMgr.createFileID(std::move(SB)); 554 assert(FID.isValid() && "Could not create FileID for predefines?"); 555 setPredefinesFileID(FID); 556 557 // Start parsing the predefines. 558 EnterSourceFile(FID, nullptr, SourceLocation()); 559 560 if (!PPOpts->PCHThroughHeader.empty()) { 561 // Lookup and save the FileID for the through header. If it isn't found 562 // in the search path, it's a fatal error. 563 const DirectoryLookup *CurDir; 564 const FileEntry *File = LookupFile( 565 SourceLocation(), PPOpts->PCHThroughHeader, 566 /*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr, CurDir, 567 /*SearchPath=*/nullptr, /*RelativePath=*/nullptr, 568 /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr); 569 if (!File) { 570 Diag(SourceLocation(), diag::err_pp_through_header_not_found) 571 << PPOpts->PCHThroughHeader; 572 return; 573 } 574 setPCHThroughHeaderFileID( 575 SourceMgr.createFileID(File, SourceLocation(), SrcMgr::C_User)); 576 } 577 578 // Skip tokens from the Predefines and if needed the main file. 579 if (usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) 580 SkipTokensUntilPCHThroughHeader(); 581 } 582 583 void Preprocessor::setPCHThroughHeaderFileID(FileID FID) { 584 assert(PCHThroughHeaderFileID.isInvalid() && 585 "PCHThroughHeaderFileID already set!"); 586 PCHThroughHeaderFileID = FID; 587 } 588 589 bool Preprocessor::isPCHThroughHeader(const FileEntry *FE) { 590 assert(PCHThroughHeaderFileID.isValid() && 591 "Invalid PCH through header FileID"); 592 return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID); 593 } 594 595 bool Preprocessor::creatingPCHWithThroughHeader() { 596 return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() && 597 PCHThroughHeaderFileID.isValid(); 598 } 599 600 bool Preprocessor::usingPCHWithThroughHeader() { 601 return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() && 602 PCHThroughHeaderFileID.isValid(); 603 } 604 605 /// Skip tokens until after the #include of the through header. 606 /// Tokens in the predefines file and the main file may be skipped. If the end 607 /// of the predefines file is reached, skipping continues into the main file. 608 /// If the end of the main file is reached, it's a fatal error. 609 void Preprocessor::SkipTokensUntilPCHThroughHeader() { 610 bool ReachedMainFileEOF = false; 611 Token Tok; 612 while (true) { 613 bool InPredefines = (CurLexer->getFileID() == getPredefinesFileID()); 614 CurLexer->Lex(Tok); 615 if (Tok.is(tok::eof) && !InPredefines) { 616 ReachedMainFileEOF = true; 617 break; 618 } 619 if (!SkippingUntilPCHThroughHeader) 620 break; 621 } 622 if (ReachedMainFileEOF) 623 Diag(SourceLocation(), diag::err_pp_through_header_not_seen) 624 << PPOpts->PCHThroughHeader << 1; 625 } 626 627 void Preprocessor::replayPreambleConditionalStack() { 628 // Restore the conditional stack from the preamble, if there is one. 629 if (PreambleConditionalStack.isReplaying()) { 630 assert(CurPPLexer && 631 "CurPPLexer is null when calling replayPreambleConditionalStack."); 632 CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack()); 633 PreambleConditionalStack.doneReplaying(); 634 if (PreambleConditionalStack.reachedEOFWhileSkipping()) 635 SkipExcludedConditionalBlock( 636 PreambleConditionalStack.SkipInfo->HashTokenLoc, 637 PreambleConditionalStack.SkipInfo->IfTokenLoc, 638 PreambleConditionalStack.SkipInfo->FoundNonSkipPortion, 639 PreambleConditionalStack.SkipInfo->FoundElse, 640 PreambleConditionalStack.SkipInfo->ElseLoc); 641 } 642 } 643 644 void Preprocessor::EndSourceFile() { 645 // Notify the client that we reached the end of the source file. 646 if (Callbacks) 647 Callbacks->EndOfMainFile(); 648 } 649 650 //===----------------------------------------------------------------------===// 651 // Lexer Event Handling. 652 //===----------------------------------------------------------------------===// 653 654 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the 655 /// identifier information for the token and install it into the token, 656 /// updating the token kind accordingly. 657 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const { 658 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!"); 659 660 // Look up this token, see if it is a macro, or if it is a language keyword. 661 IdentifierInfo *II; 662 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) { 663 // No cleaning needed, just use the characters from the lexed buffer. 664 II = getIdentifierInfo(Identifier.getRawIdentifier()); 665 } else { 666 // Cleaning needed, alloca a buffer, clean into it, then use the buffer. 667 SmallString<64> IdentifierBuffer; 668 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer); 669 670 if (Identifier.hasUCN()) { 671 SmallString<64> UCNIdentifierBuffer; 672 expandUCNs(UCNIdentifierBuffer, CleanedStr); 673 II = getIdentifierInfo(UCNIdentifierBuffer); 674 } else { 675 II = getIdentifierInfo(CleanedStr); 676 } 677 } 678 679 // Update the token info (identifier info and appropriate token kind). 680 Identifier.setIdentifierInfo(II); 681 if (getLangOpts().MSVCCompat && II->isCPlusPlusOperatorKeyword() && 682 getSourceManager().isInSystemHeader(Identifier.getLocation())) 683 Identifier.setKind(tok::identifier); 684 else 685 Identifier.setKind(II->getTokenID()); 686 687 return II; 688 } 689 690 void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) { 691 PoisonReasons[II] = DiagID; 692 } 693 694 void Preprocessor::PoisonSEHIdentifiers(bool Poison) { 695 assert(Ident__exception_code && Ident__exception_info); 696 assert(Ident___exception_code && Ident___exception_info); 697 Ident__exception_code->setIsPoisoned(Poison); 698 Ident___exception_code->setIsPoisoned(Poison); 699 Ident_GetExceptionCode->setIsPoisoned(Poison); 700 Ident__exception_info->setIsPoisoned(Poison); 701 Ident___exception_info->setIsPoisoned(Poison); 702 Ident_GetExceptionInfo->setIsPoisoned(Poison); 703 Ident__abnormal_termination->setIsPoisoned(Poison); 704 Ident___abnormal_termination->setIsPoisoned(Poison); 705 Ident_AbnormalTermination->setIsPoisoned(Poison); 706 } 707 708 void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) { 709 assert(Identifier.getIdentifierInfo() && 710 "Can't handle identifiers without identifier info!"); 711 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it = 712 PoisonReasons.find(Identifier.getIdentifierInfo()); 713 if(it == PoisonReasons.end()) 714 Diag(Identifier, diag::err_pp_used_poisoned_id); 715 else 716 Diag(Identifier,it->second) << Identifier.getIdentifierInfo(); 717 } 718 719 /// Returns a diagnostic message kind for reporting a future keyword as 720 /// appropriate for the identifier and specified language. 721 static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II, 722 const LangOptions &LangOpts) { 723 assert(II.isFutureCompatKeyword() && "diagnostic should not be needed"); 724 725 if (LangOpts.CPlusPlus) 726 return llvm::StringSwitch<diag::kind>(II.getName()) 727 #define CXX11_KEYWORD(NAME, FLAGS) \ 728 .Case(#NAME, diag::warn_cxx11_keyword) 729 #define CXX2A_KEYWORD(NAME, FLAGS) \ 730 .Case(#NAME, diag::warn_cxx2a_keyword) 731 #include "clang/Basic/TokenKinds.def" 732 ; 733 734 llvm_unreachable( 735 "Keyword not known to come from a newer Standard or proposed Standard"); 736 } 737 738 void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const { 739 assert(II.isOutOfDate() && "not out of date"); 740 getExternalSource()->updateOutOfDateIdentifier(II); 741 } 742 743 /// HandleIdentifier - This callback is invoked when the lexer reads an 744 /// identifier. This callback looks up the identifier in the map and/or 745 /// potentially macro expands it or turns it into a named token (like 'for'). 746 /// 747 /// Note that callers of this method are guarded by checking the 748 /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the 749 /// IdentifierInfo methods that compute these properties will need to change to 750 /// match. 751 bool Preprocessor::HandleIdentifier(Token &Identifier) { 752 assert(Identifier.getIdentifierInfo() && 753 "Can't handle identifiers without identifier info!"); 754 755 IdentifierInfo &II = *Identifier.getIdentifierInfo(); 756 757 // If the information about this identifier is out of date, update it from 758 // the external source. 759 // We have to treat __VA_ARGS__ in a special way, since it gets 760 // serialized with isPoisoned = true, but our preprocessor may have 761 // unpoisoned it if we're defining a C99 macro. 762 if (II.isOutOfDate()) { 763 bool CurrentIsPoisoned = false; 764 const bool IsSpecialVariadicMacro = 765 &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__; 766 if (IsSpecialVariadicMacro) 767 CurrentIsPoisoned = II.isPoisoned(); 768 769 updateOutOfDateIdentifier(II); 770 Identifier.setKind(II.getTokenID()); 771 772 if (IsSpecialVariadicMacro) 773 II.setIsPoisoned(CurrentIsPoisoned); 774 } 775 776 // If this identifier was poisoned, and if it was not produced from a macro 777 // expansion, emit an error. 778 if (II.isPoisoned() && CurPPLexer) { 779 HandlePoisonedIdentifier(Identifier); 780 } 781 782 // If this is a macro to be expanded, do it. 783 if (MacroDefinition MD = getMacroDefinition(&II)) { 784 auto *MI = MD.getMacroInfo(); 785 assert(MI && "macro definition with no macro info?"); 786 if (!DisableMacroExpansion) { 787 if (!Identifier.isExpandDisabled() && MI->isEnabled()) { 788 // C99 6.10.3p10: If the preprocessing token immediately after the 789 // macro name isn't a '(', this macro should not be expanded. 790 if (!MI->isFunctionLike() || isNextPPTokenLParen()) 791 return HandleMacroExpandedIdentifier(Identifier, MD); 792 } else { 793 // C99 6.10.3.4p2 says that a disabled macro may never again be 794 // expanded, even if it's in a context where it could be expanded in the 795 // future. 796 Identifier.setFlag(Token::DisableExpand); 797 if (MI->isObjectLike() || isNextPPTokenLParen()) 798 Diag(Identifier, diag::pp_disabled_macro_expansion); 799 } 800 } 801 } 802 803 // If this identifier is a keyword in a newer Standard or proposed Standard, 804 // produce a warning. Don't warn if we're not considering macro expansion, 805 // since this identifier might be the name of a macro. 806 // FIXME: This warning is disabled in cases where it shouldn't be, like 807 // "#define constexpr constexpr", "int constexpr;" 808 if (II.isFutureCompatKeyword() && !DisableMacroExpansion) { 809 Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts())) 810 << II.getName(); 811 // Don't diagnose this keyword again in this translation unit. 812 II.setIsFutureCompatKeyword(false); 813 } 814 815 // If this is an extension token, diagnose its use. 816 // We avoid diagnosing tokens that originate from macro definitions. 817 // FIXME: This warning is disabled in cases where it shouldn't be, 818 // like "#define TY typeof", "TY(1) x". 819 if (II.isExtensionToken() && !DisableMacroExpansion) 820 Diag(Identifier, diag::ext_token_used); 821 822 // If this is the 'import' contextual keyword following an '@', note 823 // that the next token indicates a module name. 824 // 825 // Note that we do not treat 'import' as a contextual 826 // keyword when we're in a caching lexer, because caching lexers only get 827 // used in contexts where import declarations are disallowed. 828 // 829 // Likewise if this is the C++ Modules TS import keyword. 830 if (((LastTokenWasAt && II.isModulesImport()) || 831 Identifier.is(tok::kw_import)) && 832 !InMacroArgs && !DisableMacroExpansion && 833 (getLangOpts().Modules || getLangOpts().DebuggerSupport) && 834 CurLexerKind != CLK_CachingLexer) { 835 ModuleImportLoc = Identifier.getLocation(); 836 ModuleImportPath.clear(); 837 ModuleImportExpectsIdentifier = true; 838 CurLexerKind = CLK_LexAfterModuleImport; 839 } 840 return true; 841 } 842 843 void Preprocessor::Lex(Token &Result) { 844 // We loop here until a lex function returns a token; this avoids recursion. 845 bool ReturnedToken; 846 do { 847 switch (CurLexerKind) { 848 case CLK_Lexer: 849 ReturnedToken = CurLexer->Lex(Result); 850 break; 851 case CLK_PTHLexer: 852 ReturnedToken = CurPTHLexer->Lex(Result); 853 break; 854 case CLK_TokenLexer: 855 ReturnedToken = CurTokenLexer->Lex(Result); 856 break; 857 case CLK_CachingLexer: 858 CachingLex(Result); 859 ReturnedToken = true; 860 break; 861 case CLK_LexAfterModuleImport: 862 LexAfterModuleImport(Result); 863 ReturnedToken = true; 864 break; 865 } 866 } while (!ReturnedToken); 867 868 if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) { 869 // Remember the identifier before code completion token. 870 setCodeCompletionIdentifierInfo(Result.getIdentifierInfo()); 871 // Set IdenfitierInfo to null to avoid confusing code that handles both 872 // identifiers and completion tokens. 873 Result.setIdentifierInfo(nullptr); 874 } 875 876 LastTokenWasAt = Result.is(tok::at); 877 } 878 879 /// Lex a token following the 'import' contextual keyword. 880 /// 881 void Preprocessor::LexAfterModuleImport(Token &Result) { 882 // Figure out what kind of lexer we actually have. 883 recomputeCurLexerKind(); 884 885 // Lex the next token. 886 Lex(Result); 887 888 // The token sequence 889 // 890 // import identifier (. identifier)* 891 // 892 // indicates a module import directive. We already saw the 'import' 893 // contextual keyword, so now we're looking for the identifiers. 894 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) { 895 // We expected to see an identifier here, and we did; continue handling 896 // identifiers. 897 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(), 898 Result.getLocation())); 899 ModuleImportExpectsIdentifier = false; 900 CurLexerKind = CLK_LexAfterModuleImport; 901 return; 902 } 903 904 // If we're expecting a '.' or a ';', and we got a '.', then wait until we 905 // see the next identifier. (We can also see a '[[' that begins an 906 // attribute-specifier-seq here under the C++ Modules TS.) 907 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) { 908 ModuleImportExpectsIdentifier = true; 909 CurLexerKind = CLK_LexAfterModuleImport; 910 return; 911 } 912 913 // If we have a non-empty module path, load the named module. 914 if (!ModuleImportPath.empty()) { 915 // Under the Modules TS, the dot is just part of the module name, and not 916 // a real hierarachy separator. Flatten such module names now. 917 // 918 // FIXME: Is this the right level to be performing this transformation? 919 std::string FlatModuleName; 920 if (getLangOpts().ModulesTS) { 921 for (auto &Piece : ModuleImportPath) { 922 if (!FlatModuleName.empty()) 923 FlatModuleName += "."; 924 FlatModuleName += Piece.first->getName(); 925 } 926 SourceLocation FirstPathLoc = ModuleImportPath[0].second; 927 ModuleImportPath.clear(); 928 ModuleImportPath.push_back( 929 std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc)); 930 } 931 932 Module *Imported = nullptr; 933 if (getLangOpts().Modules) { 934 Imported = TheModuleLoader.loadModule(ModuleImportLoc, 935 ModuleImportPath, 936 Module::Hidden, 937 /*IsIncludeDirective=*/false); 938 if (Imported) 939 makeModuleVisible(Imported, ModuleImportLoc); 940 } 941 if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport)) 942 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported); 943 } 944 } 945 946 void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) { 947 CurSubmoduleState->VisibleModules.setVisible( 948 M, Loc, [](Module *) {}, 949 [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) { 950 // FIXME: Include the path in the diagnostic. 951 // FIXME: Include the import location for the conflicting module. 952 Diag(ModuleImportLoc, diag::warn_module_conflict) 953 << Path[0]->getFullModuleName() 954 << Conflict->getFullModuleName() 955 << Message; 956 }); 957 958 // Add this module to the imports list of the currently-built submodule. 959 if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M) 960 BuildingSubmoduleStack.back().M->Imports.insert(M); 961 } 962 963 bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String, 964 const char *DiagnosticTag, 965 bool AllowMacroExpansion) { 966 // We need at least one string literal. 967 if (Result.isNot(tok::string_literal)) { 968 Diag(Result, diag::err_expected_string_literal) 969 << /*Source='in...'*/0 << DiagnosticTag; 970 return false; 971 } 972 973 // Lex string literal tokens, optionally with macro expansion. 974 SmallVector<Token, 4> StrToks; 975 do { 976 StrToks.push_back(Result); 977 978 if (Result.hasUDSuffix()) 979 Diag(Result, diag::err_invalid_string_udl); 980 981 if (AllowMacroExpansion) 982 Lex(Result); 983 else 984 LexUnexpandedToken(Result); 985 } while (Result.is(tok::string_literal)); 986 987 // Concatenate and parse the strings. 988 StringLiteralParser Literal(StrToks, *this); 989 assert(Literal.isAscii() && "Didn't allow wide strings in"); 990 991 if (Literal.hadError) 992 return false; 993 994 if (Literal.Pascal) { 995 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal) 996 << /*Source='in...'*/0 << DiagnosticTag; 997 return false; 998 } 999 1000 String = Literal.GetString(); 1001 return true; 1002 } 1003 1004 bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) { 1005 assert(Tok.is(tok::numeric_constant)); 1006 SmallString<8> IntegerBuffer; 1007 bool NumberInvalid = false; 1008 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid); 1009 if (NumberInvalid) 1010 return false; 1011 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this); 1012 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix()) 1013 return false; 1014 llvm::APInt APVal(64, 0); 1015 if (Literal.GetIntegerValue(APVal)) 1016 return false; 1017 Lex(Tok); 1018 Value = APVal.getLimitedValue(); 1019 return true; 1020 } 1021 1022 void Preprocessor::addCommentHandler(CommentHandler *Handler) { 1023 assert(Handler && "NULL comment handler"); 1024 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) == 1025 CommentHandlers.end() && "Comment handler already registered"); 1026 CommentHandlers.push_back(Handler); 1027 } 1028 1029 void Preprocessor::removeCommentHandler(CommentHandler *Handler) { 1030 std::vector<CommentHandler *>::iterator Pos = 1031 std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler); 1032 assert(Pos != CommentHandlers.end() && "Comment handler not registered"); 1033 CommentHandlers.erase(Pos); 1034 } 1035 1036 bool Preprocessor::HandleComment(Token &result, SourceRange Comment) { 1037 bool AnyPendingTokens = false; 1038 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(), 1039 HEnd = CommentHandlers.end(); 1040 H != HEnd; ++H) { 1041 if ((*H)->HandleComment(*this, Comment)) 1042 AnyPendingTokens = true; 1043 } 1044 if (!AnyPendingTokens || getCommentRetentionState()) 1045 return false; 1046 Lex(result); 1047 return true; 1048 } 1049 1050 ModuleLoader::~ModuleLoader() = default; 1051 1052 CommentHandler::~CommentHandler() = default; 1053 1054 CodeCompletionHandler::~CodeCompletionHandler() = default; 1055 1056 void Preprocessor::createPreprocessingRecord() { 1057 if (Record) 1058 return; 1059 1060 Record = new PreprocessingRecord(getSourceManager()); 1061 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record)); 1062 } 1063