xref: /llvm-project/clang/lib/Lex/Preprocessor.cpp (revision e77a01d79a48e15c94c89e4aa4bd27424a96b49b)
1 //===- Preprocessor.cpp - C Language Family Preprocessor Implementation ---===//
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 Preprocessor interface.
10 //
11 //===----------------------------------------------------------------------===//
12 //
13 // Options to support:
14 //   -H       - Print the name of each header file used.
15 //   -d[DNI] - Dump various things.
16 //   -fworking-directory - #line's with preprocessor's working dir.
17 //   -fpreprocessed
18 //   -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
19 //   -W*
20 //   -w
21 //
22 // Messages to emit:
23 //   "Multiple include guards may be useful for:\n"
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Basic/Builtins.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/Pragma.h"
48 #include "clang/Lex/PreprocessingRecord.h"
49 #include "clang/Lex/PreprocessorLexer.h"
50 #include "clang/Lex/PreprocessorOptions.h"
51 #include "clang/Lex/ScratchBuffer.h"
52 #include "clang/Lex/Token.h"
53 #include "clang/Lex/TokenLexer.h"
54 #include "llvm/ADT/APInt.h"
55 #include "llvm/ADT/ArrayRef.h"
56 #include "llvm/ADT/DenseMap.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include "llvm/ADT/SmallString.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/StringRef.h"
61 #include "llvm/ADT/iterator_range.h"
62 #include "llvm/Support/Capacity.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/MemoryBuffer.h"
65 #include "llvm/Support/raw_ostream.h"
66 #include <algorithm>
67 #include <cassert>
68 #include <memory>
69 #include <optional>
70 #include <string>
71 #include <utility>
72 #include <vector>
73 
74 using namespace clang;
75 
76 /// Minimum distance between two check points, in tokens.
77 static constexpr unsigned CheckPointStepSize = 1024;
78 
79 LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
80 
81 ExternalPreprocessorSource::~ExternalPreprocessorSource() = default;
82 
83 Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
84                            DiagnosticsEngine &diags, const LangOptions &opts,
85                            SourceManager &SM, HeaderSearch &Headers,
86                            ModuleLoader &TheModuleLoader,
87                            IdentifierInfoLookup *IILookup, bool OwnsHeaders,
88                            TranslationUnitKind TUKind)
89     : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),
90       FileMgr(Headers.getFileMgr()), SourceMgr(SM),
91       ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
92       TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
93       // As the language options may have not been loaded yet (when
94       // deserializing an ASTUnit), adding keywords to the identifier table is
95       // deferred to Preprocessor::Initialize().
96       Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
97       TUKind(TUKind), SkipMainFilePreamble(0, true),
98       CurSubmoduleState(&NullSubmoduleState) {
99   OwnsHeaderSearch = OwnsHeaders;
100 
101   // Default to discarding comments.
102   KeepComments = false;
103   KeepMacroComments = false;
104   SuppressIncludeNotFoundError = false;
105 
106   // Macro expansion is enabled.
107   DisableMacroExpansion = false;
108   MacroExpansionInDirectivesOverride = false;
109   InMacroArgs = false;
110   ArgMacro = nullptr;
111   InMacroArgPreExpansion = false;
112   NumCachedTokenLexers = 0;
113   PragmasEnabled = true;
114   ParsingIfOrElifDirective = false;
115   PreprocessedOutput = false;
116 
117   // We haven't read anything from the external source.
118   ReadMacrosFromExternalSource = false;
119 
120   BuiltinInfo = std::make_unique<Builtin::Context>();
121 
122   // "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of
123   // a macro. They get unpoisoned where it is allowed.
124   (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
125   SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
126   (Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
127   SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);
128 
129   // Initialize the pragma handlers.
130   RegisterBuiltinPragmas();
131 
132   // Initialize builtin macros like __LINE__ and friends.
133   RegisterBuiltinMacros();
134 
135   if(LangOpts.Borland) {
136     Ident__exception_info        = getIdentifierInfo("_exception_info");
137     Ident___exception_info       = getIdentifierInfo("__exception_info");
138     Ident_GetExceptionInfo       = getIdentifierInfo("GetExceptionInformation");
139     Ident__exception_code        = getIdentifierInfo("_exception_code");
140     Ident___exception_code       = getIdentifierInfo("__exception_code");
141     Ident_GetExceptionCode       = getIdentifierInfo("GetExceptionCode");
142     Ident__abnormal_termination  = getIdentifierInfo("_abnormal_termination");
143     Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
144     Ident_AbnormalTermination    = getIdentifierInfo("AbnormalTermination");
145   } else {
146     Ident__exception_info = Ident__exception_code = nullptr;
147     Ident__abnormal_termination = Ident___exception_info = nullptr;
148     Ident___exception_code = Ident___abnormal_termination = nullptr;
149     Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
150     Ident_AbnormalTermination = nullptr;
151   }
152 
153   // Default incremental processing to -fincremental-extensions, clients can
154   // override with `enableIncrementalProcessing` if desired.
155   IncrementalProcessing = LangOpts.IncrementalExtensions;
156 
157   // If using a PCH where a #pragma hdrstop is expected, start skipping tokens.
158   if (usingPCHWithPragmaHdrStop())
159     SkippingUntilPragmaHdrStop = true;
160 
161   // If using a PCH with a through header, start skipping tokens.
162   if (!this->PPOpts->PCHThroughHeader.empty() &&
163       !this->PPOpts->ImplicitPCHInclude.empty())
164     SkippingUntilPCHThroughHeader = true;
165 
166   if (this->PPOpts->GeneratePreamble)
167     PreambleConditionalStack.startRecording();
168 
169   MaxTokens = LangOpts.MaxTokens;
170 }
171 
172 Preprocessor::~Preprocessor() {
173   assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
174 
175   IncludeMacroStack.clear();
176 
177   // Free any cached macro expanders.
178   // This populates MacroArgCache, so all TokenLexers need to be destroyed
179   // before the code below that frees up the MacroArgCache list.
180   std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
181   CurTokenLexer.reset();
182 
183   // Free any cached MacroArgs.
184   for (MacroArgs *ArgList = MacroArgCache; ArgList;)
185     ArgList = ArgList->deallocate();
186 
187   // Delete the header search info, if we own it.
188   if (OwnsHeaderSearch)
189     delete &HeaderInfo;
190 }
191 
192 void Preprocessor::Initialize(const TargetInfo &Target,
193                               const TargetInfo *AuxTarget) {
194   assert((!this->Target || this->Target == &Target) &&
195          "Invalid override of target information");
196   this->Target = &Target;
197 
198   assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
199          "Invalid override of aux target information.");
200   this->AuxTarget = AuxTarget;
201 
202   // Initialize information about built-ins.
203   BuiltinInfo->InitializeTarget(Target, AuxTarget);
204   HeaderInfo.setTarget(Target);
205 
206   // Populate the identifier table with info about keywords for the current language.
207   Identifiers.AddKeywords(LangOpts);
208 
209   // Initialize the __FTL_EVAL_METHOD__ macro to the TargetInfo.
210   setTUFPEvalMethod(getTargetInfo().getFPEvalMethod());
211 
212   if (getLangOpts().getFPEvalMethod() == LangOptions::FEM_UnsetOnCommandLine)
213     // Use setting from TargetInfo.
214     setCurrentFPEvalMethod(SourceLocation(), Target.getFPEvalMethod());
215   else
216     // Set initial value of __FLT_EVAL_METHOD__ from the command line.
217     setCurrentFPEvalMethod(SourceLocation(), getLangOpts().getFPEvalMethod());
218 }
219 
220 void Preprocessor::InitializeForModelFile() {
221   NumEnteredSourceFiles = 0;
222 
223   // Reset pragmas
224   PragmaHandlersBackup = std::move(PragmaHandlers);
225   PragmaHandlers = std::make_unique<PragmaNamespace>(StringRef());
226   RegisterBuiltinPragmas();
227 
228   // Reset PredefinesFileID
229   PredefinesFileID = FileID();
230 }
231 
232 void Preprocessor::FinalizeForModelFile() {
233   NumEnteredSourceFiles = 1;
234 
235   PragmaHandlers = std::move(PragmaHandlersBackup);
236 }
237 
238 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
239   llvm::errs() << tok::getTokenName(Tok.getKind());
240 
241   if (!Tok.isAnnotation())
242     llvm::errs() << " '" << getSpelling(Tok) << "'";
243 
244   if (!DumpFlags) return;
245 
246   llvm::errs() << "\t";
247   if (Tok.isAtStartOfLine())
248     llvm::errs() << " [StartOfLine]";
249   if (Tok.hasLeadingSpace())
250     llvm::errs() << " [LeadingSpace]";
251   if (Tok.isExpandDisabled())
252     llvm::errs() << " [ExpandDisabled]";
253   if (Tok.needsCleaning()) {
254     const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
255     llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
256                  << "']";
257   }
258 
259   llvm::errs() << "\tLoc=<";
260   DumpLocation(Tok.getLocation());
261   llvm::errs() << ">";
262 }
263 
264 void Preprocessor::DumpLocation(SourceLocation Loc) const {
265   Loc.print(llvm::errs(), SourceMgr);
266 }
267 
268 void Preprocessor::DumpMacro(const MacroInfo &MI) const {
269   llvm::errs() << "MACRO: ";
270   for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
271     DumpToken(MI.getReplacementToken(i));
272     llvm::errs() << "  ";
273   }
274   llvm::errs() << "\n";
275 }
276 
277 void Preprocessor::PrintStats() {
278   llvm::errs() << "\n*** Preprocessor Stats:\n";
279   llvm::errs() << NumDirectives << " directives found:\n";
280   llvm::errs() << "  " << NumDefined << " #define.\n";
281   llvm::errs() << "  " << NumUndefined << " #undef.\n";
282   llvm::errs() << "  #include/#include_next/#import:\n";
283   llvm::errs() << "    " << NumEnteredSourceFiles << " source files entered.\n";
284   llvm::errs() << "    " << MaxIncludeStackDepth << " max include stack depth\n";
285   llvm::errs() << "  " << NumIf << " #if/#ifndef/#ifdef.\n";
286   llvm::errs() << "  " << NumElse << " #else/#elif/#elifdef/#elifndef.\n";
287   llvm::errs() << "  " << NumEndif << " #endif.\n";
288   llvm::errs() << "  " << NumPragma << " #pragma.\n";
289   llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
290 
291   llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
292              << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
293              << NumFastMacroExpanded << " on the fast path.\n";
294   llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
295              << " token paste (##) operations performed, "
296              << NumFastTokenPaste << " on the fast path.\n";
297 
298   llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
299 
300   llvm::errs() << "\n  BumpPtr: " << BP.getTotalMemory();
301   llvm::errs() << "\n  Macro Expanded Tokens: "
302                << llvm::capacity_in_bytes(MacroExpandedTokens);
303   llvm::errs() << "\n  Predefines Buffer: " << Predefines.capacity();
304   // FIXME: List information for all submodules.
305   llvm::errs() << "\n  Macros: "
306                << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
307   llvm::errs() << "\n  #pragma push_macro Info: "
308                << llvm::capacity_in_bytes(PragmaPushMacroInfo);
309   llvm::errs() << "\n  Poison Reasons: "
310                << llvm::capacity_in_bytes(PoisonReasons);
311   llvm::errs() << "\n  Comment Handlers: "
312                << llvm::capacity_in_bytes(CommentHandlers) << "\n";
313 }
314 
315 Preprocessor::macro_iterator
316 Preprocessor::macro_begin(bool IncludeExternalMacros) const {
317   if (IncludeExternalMacros && ExternalSource &&
318       !ReadMacrosFromExternalSource) {
319     ReadMacrosFromExternalSource = true;
320     ExternalSource->ReadDefinedMacros();
321   }
322 
323   // Make sure we cover all macros in visible modules.
324   for (const ModuleMacro &Macro : ModuleMacros)
325     CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
326 
327   return CurSubmoduleState->Macros.begin();
328 }
329 
330 size_t Preprocessor::getTotalMemory() const {
331   return BP.getTotalMemory()
332     + llvm::capacity_in_bytes(MacroExpandedTokens)
333     + Predefines.capacity() /* Predefines buffer. */
334     // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
335     // and ModuleMacros.
336     + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
337     + llvm::capacity_in_bytes(PragmaPushMacroInfo)
338     + llvm::capacity_in_bytes(PoisonReasons)
339     + llvm::capacity_in_bytes(CommentHandlers);
340 }
341 
342 Preprocessor::macro_iterator
343 Preprocessor::macro_end(bool IncludeExternalMacros) const {
344   if (IncludeExternalMacros && ExternalSource &&
345       !ReadMacrosFromExternalSource) {
346     ReadMacrosFromExternalSource = true;
347     ExternalSource->ReadDefinedMacros();
348   }
349 
350   return CurSubmoduleState->Macros.end();
351 }
352 
353 /// Compares macro tokens with a specified token value sequence.
354 static bool MacroDefinitionEquals(const MacroInfo *MI,
355                                   ArrayRef<TokenValue> Tokens) {
356   return Tokens.size() == MI->getNumTokens() &&
357       std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
358 }
359 
360 StringRef Preprocessor::getLastMacroWithSpelling(
361                                     SourceLocation Loc,
362                                     ArrayRef<TokenValue> Tokens) const {
363   SourceLocation BestLocation;
364   StringRef BestSpelling;
365   for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
366        I != E; ++I) {
367     const MacroDirective::DefInfo
368       Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
369     if (!Def || !Def.getMacroInfo())
370       continue;
371     if (!Def.getMacroInfo()->isObjectLike())
372       continue;
373     if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
374       continue;
375     SourceLocation Location = Def.getLocation();
376     // Choose the macro defined latest.
377     if (BestLocation.isInvalid() ||
378         (Location.isValid() &&
379          SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
380       BestLocation = Location;
381       BestSpelling = I->first->getName();
382     }
383   }
384   return BestSpelling;
385 }
386 
387 void Preprocessor::recomputeCurLexerKind() {
388   if (CurLexer)
389     CurLexerCallback = CurLexer->isDependencyDirectivesLexer()
390                            ? CLK_DependencyDirectivesLexer
391                            : CLK_Lexer;
392   else if (CurTokenLexer)
393     CurLexerCallback = CLK_TokenLexer;
394   else
395     CurLexerCallback = CLK_CachingLexer;
396 }
397 
398 bool Preprocessor::SetCodeCompletionPoint(FileEntryRef File,
399                                           unsigned CompleteLine,
400                                           unsigned CompleteColumn) {
401   assert(CompleteLine && CompleteColumn && "Starts from 1:1");
402   assert(!CodeCompletionFile && "Already set");
403 
404   // Load the actual file's contents.
405   std::optional<llvm::MemoryBufferRef> Buffer =
406       SourceMgr.getMemoryBufferForFileOrNone(File);
407   if (!Buffer)
408     return true;
409 
410   // Find the byte position of the truncation point.
411   const char *Position = Buffer->getBufferStart();
412   for (unsigned Line = 1; Line < CompleteLine; ++Line) {
413     for (; *Position; ++Position) {
414       if (*Position != '\r' && *Position != '\n')
415         continue;
416 
417       // Eat \r\n or \n\r as a single line.
418       if ((Position[1] == '\r' || Position[1] == '\n') &&
419           Position[0] != Position[1])
420         ++Position;
421       ++Position;
422       break;
423     }
424   }
425 
426   Position += CompleteColumn - 1;
427 
428   // If pointing inside the preamble, adjust the position at the beginning of
429   // the file after the preamble.
430   if (SkipMainFilePreamble.first &&
431       SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
432     if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
433       Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
434   }
435 
436   if (Position > Buffer->getBufferEnd())
437     Position = Buffer->getBufferEnd();
438 
439   CodeCompletionFile = File;
440   CodeCompletionOffset = Position - Buffer->getBufferStart();
441 
442   auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
443       Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
444   char *NewBuf = NewBuffer->getBufferStart();
445   char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
446   *NewPos = '\0';
447   std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
448   SourceMgr.overrideFileContents(File, std::move(NewBuffer));
449 
450   return false;
451 }
452 
453 void Preprocessor::CodeCompleteIncludedFile(llvm::StringRef Dir,
454                                             bool IsAngled) {
455   setCodeCompletionReached();
456   if (CodeComplete)
457     CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled);
458 }
459 
460 void Preprocessor::CodeCompleteNaturalLanguage() {
461   setCodeCompletionReached();
462   if (CodeComplete)
463     CodeComplete->CodeCompleteNaturalLanguage();
464 }
465 
466 /// getSpelling - This method is used to get the spelling of a token into a
467 /// SmallVector. Note that the returned StringRef may not point to the
468 /// supplied buffer if a copy can be avoided.
469 StringRef Preprocessor::getSpelling(const Token &Tok,
470                                           SmallVectorImpl<char> &Buffer,
471                                           bool *Invalid) const {
472   // NOTE: this has to be checked *before* testing for an IdentifierInfo.
473   if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
474     // Try the fast path.
475     if (const IdentifierInfo *II = Tok.getIdentifierInfo())
476       return II->getName();
477   }
478 
479   // Resize the buffer if we need to copy into it.
480   if (Tok.needsCleaning())
481     Buffer.resize(Tok.getLength());
482 
483   const char *Ptr = Buffer.data();
484   unsigned Len = getSpelling(Tok, Ptr, Invalid);
485   return StringRef(Ptr, Len);
486 }
487 
488 /// CreateString - Plop the specified string into a scratch buffer and return a
489 /// location for it.  If specified, the source location provides a source
490 /// location for the token.
491 void Preprocessor::CreateString(StringRef Str, Token &Tok,
492                                 SourceLocation ExpansionLocStart,
493                                 SourceLocation ExpansionLocEnd) {
494   Tok.setLength(Str.size());
495 
496   const char *DestPtr;
497   SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
498 
499   if (ExpansionLocStart.isValid())
500     Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
501                                        ExpansionLocEnd, Str.size());
502   Tok.setLocation(Loc);
503 
504   // If this is a raw identifier or a literal token, set the pointer data.
505   if (Tok.is(tok::raw_identifier))
506     Tok.setRawIdentifierData(DestPtr);
507   else if (Tok.isLiteral())
508     Tok.setLiteralData(DestPtr);
509 }
510 
511 SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) {
512   auto &SM = getSourceManager();
513   SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
514   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc);
515   bool Invalid = false;
516   StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
517   if (Invalid)
518     return SourceLocation();
519 
520   // FIXME: We could consider re-using spelling for tokens we see repeatedly.
521   const char *DestPtr;
522   SourceLocation Spelling =
523       ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
524   return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
525 }
526 
527 Module *Preprocessor::getCurrentModule() {
528   if (!getLangOpts().isCompilingModule())
529     return nullptr;
530 
531   return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
532 }
533 
534 Module *Preprocessor::getCurrentModuleImplementation() {
535   if (!getLangOpts().isCompilingModuleImplementation())
536     return nullptr;
537 
538   return getHeaderSearchInfo().lookupModule(getLangOpts().ModuleName);
539 }
540 
541 //===----------------------------------------------------------------------===//
542 // Preprocessor Initialization Methods
543 //===----------------------------------------------------------------------===//
544 
545 /// EnterMainSourceFile - Enter the specified FileID as the main source file,
546 /// which implicitly adds the builtin defines etc.
547 void Preprocessor::EnterMainSourceFile() {
548   // We do not allow the preprocessor to reenter the main file.  Doing so will
549   // cause FileID's to accumulate information from both runs (e.g. #line
550   // information) and predefined macros aren't guaranteed to be set properly.
551   assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
552   FileID MainFileID = SourceMgr.getMainFileID();
553 
554   // If MainFileID is loaded it means we loaded an AST file, no need to enter
555   // a main file.
556   if (!SourceMgr.isLoadedFileID(MainFileID)) {
557     // Enter the main file source buffer.
558     EnterSourceFile(MainFileID, nullptr, SourceLocation());
559 
560     // If we've been asked to skip bytes in the main file (e.g., as part of a
561     // precompiled preamble), do so now.
562     if (SkipMainFilePreamble.first > 0)
563       CurLexer->SetByteOffset(SkipMainFilePreamble.first,
564                               SkipMainFilePreamble.second);
565 
566     // Tell the header info that the main file was entered.  If the file is later
567     // #imported, it won't be re-entered.
568     if (OptionalFileEntryRef FE = SourceMgr.getFileEntryRefForID(MainFileID))
569       markIncluded(*FE);
570   }
571 
572   // Preprocess Predefines to populate the initial preprocessor state.
573   std::unique_ptr<llvm::MemoryBuffer> SB =
574     llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
575   assert(SB && "Cannot create predefined source buffer");
576   FileID FID = SourceMgr.createFileID(std::move(SB));
577   assert(FID.isValid() && "Could not create FileID for predefines?");
578   setPredefinesFileID(FID);
579 
580   // Start parsing the predefines.
581   EnterSourceFile(FID, nullptr, SourceLocation());
582 
583   if (!PPOpts->PCHThroughHeader.empty()) {
584     // Lookup and save the FileID for the through header. If it isn't found
585     // in the search path, it's a fatal error.
586     OptionalFileEntryRef File = LookupFile(
587         SourceLocation(), PPOpts->PCHThroughHeader,
588         /*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr,
589         /*CurDir=*/nullptr, /*SearchPath=*/nullptr, /*RelativePath=*/nullptr,
590         /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr,
591         /*IsFrameworkFound=*/nullptr);
592     if (!File) {
593       Diag(SourceLocation(), diag::err_pp_through_header_not_found)
594           << PPOpts->PCHThroughHeader;
595       return;
596     }
597     setPCHThroughHeaderFileID(
598         SourceMgr.createFileID(*File, SourceLocation(), SrcMgr::C_User));
599   }
600 
601   // Skip tokens from the Predefines and if needed the main file.
602   if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) ||
603       (usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop))
604     SkipTokensWhileUsingPCH();
605 }
606 
607 void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {
608   assert(PCHThroughHeaderFileID.isInvalid() &&
609          "PCHThroughHeaderFileID already set!");
610   PCHThroughHeaderFileID = FID;
611 }
612 
613 bool Preprocessor::isPCHThroughHeader(const FileEntry *FE) {
614   assert(PCHThroughHeaderFileID.isValid() &&
615          "Invalid PCH through header FileID");
616   return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
617 }
618 
619 bool Preprocessor::creatingPCHWithThroughHeader() {
620   return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
621          PCHThroughHeaderFileID.isValid();
622 }
623 
624 bool Preprocessor::usingPCHWithThroughHeader() {
625   return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
626          PCHThroughHeaderFileID.isValid();
627 }
628 
629 bool Preprocessor::creatingPCHWithPragmaHdrStop() {
630   return TUKind == TU_Prefix && PPOpts->PCHWithHdrStop;
631 }
632 
633 bool Preprocessor::usingPCHWithPragmaHdrStop() {
634   return TUKind != TU_Prefix && PPOpts->PCHWithHdrStop;
635 }
636 
637 /// Skip tokens until after the #include of the through header or
638 /// until after a #pragma hdrstop is seen. Tokens in the predefines file
639 /// and the main file may be skipped. If the end of the predefines file
640 /// is reached, skipping continues into the main file. If the end of the
641 /// main file is reached, it's a fatal error.
642 void Preprocessor::SkipTokensWhileUsingPCH() {
643   bool ReachedMainFileEOF = false;
644   bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader;
645   bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop;
646   Token Tok;
647   while (true) {
648     bool InPredefines =
649         (CurLexer && CurLexer->getFileID() == getPredefinesFileID());
650     CurLexerCallback(*this, Tok);
651     if (Tok.is(tok::eof) && !InPredefines) {
652       ReachedMainFileEOF = true;
653       break;
654     }
655     if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader)
656       break;
657     if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop)
658       break;
659   }
660   if (ReachedMainFileEOF) {
661     if (UsingPCHThroughHeader)
662       Diag(SourceLocation(), diag::err_pp_through_header_not_seen)
663           << PPOpts->PCHThroughHeader << 1;
664     else if (!PPOpts->PCHWithHdrStopCreate)
665       Diag(SourceLocation(), diag::err_pp_pragma_hdrstop_not_seen);
666   }
667 }
668 
669 void Preprocessor::replayPreambleConditionalStack() {
670   // Restore the conditional stack from the preamble, if there is one.
671   if (PreambleConditionalStack.isReplaying()) {
672     assert(CurPPLexer &&
673            "CurPPLexer is null when calling replayPreambleConditionalStack.");
674     CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
675     PreambleConditionalStack.doneReplaying();
676     if (PreambleConditionalStack.reachedEOFWhileSkipping())
677       SkipExcludedConditionalBlock(
678           PreambleConditionalStack.SkipInfo->HashTokenLoc,
679           PreambleConditionalStack.SkipInfo->IfTokenLoc,
680           PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
681           PreambleConditionalStack.SkipInfo->FoundElse,
682           PreambleConditionalStack.SkipInfo->ElseLoc);
683   }
684 }
685 
686 void Preprocessor::EndSourceFile() {
687   // Notify the client that we reached the end of the source file.
688   if (Callbacks)
689     Callbacks->EndOfMainFile();
690 }
691 
692 //===----------------------------------------------------------------------===//
693 // Lexer Event Handling.
694 //===----------------------------------------------------------------------===//
695 
696 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
697 /// identifier information for the token and install it into the token,
698 /// updating the token kind accordingly.
699 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
700   assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
701 
702   // Look up this token, see if it is a macro, or if it is a language keyword.
703   IdentifierInfo *II;
704   if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
705     // No cleaning needed, just use the characters from the lexed buffer.
706     II = getIdentifierInfo(Identifier.getRawIdentifier());
707   } else {
708     // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
709     SmallString<64> IdentifierBuffer;
710     StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
711 
712     if (Identifier.hasUCN()) {
713       SmallString<64> UCNIdentifierBuffer;
714       expandUCNs(UCNIdentifierBuffer, CleanedStr);
715       II = getIdentifierInfo(UCNIdentifierBuffer);
716     } else {
717       II = getIdentifierInfo(CleanedStr);
718     }
719   }
720 
721   // Update the token info (identifier info and appropriate token kind).
722   // FIXME: the raw_identifier may contain leading whitespace which is removed
723   // from the cleaned identifier token. The SourceLocation should be updated to
724   // refer to the non-whitespace character. For instance, the text "\\\nB" (a
725   // line continuation before 'B') is parsed as a single tok::raw_identifier and
726   // is cleaned to tok::identifier "B". After cleaning the token's length is
727   // still 3 and the SourceLocation refers to the location of the backslash.
728   Identifier.setIdentifierInfo(II);
729   Identifier.setKind(II->getTokenID());
730 
731   return II;
732 }
733 
734 void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
735   PoisonReasons[II] = DiagID;
736 }
737 
738 void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
739   assert(Ident__exception_code && Ident__exception_info);
740   assert(Ident___exception_code && Ident___exception_info);
741   Ident__exception_code->setIsPoisoned(Poison);
742   Ident___exception_code->setIsPoisoned(Poison);
743   Ident_GetExceptionCode->setIsPoisoned(Poison);
744   Ident__exception_info->setIsPoisoned(Poison);
745   Ident___exception_info->setIsPoisoned(Poison);
746   Ident_GetExceptionInfo->setIsPoisoned(Poison);
747   Ident__abnormal_termination->setIsPoisoned(Poison);
748   Ident___abnormal_termination->setIsPoisoned(Poison);
749   Ident_AbnormalTermination->setIsPoisoned(Poison);
750 }
751 
752 void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
753   assert(Identifier.getIdentifierInfo() &&
754          "Can't handle identifiers without identifier info!");
755   llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
756     PoisonReasons.find(Identifier.getIdentifierInfo());
757   if(it == PoisonReasons.end())
758     Diag(Identifier, diag::err_pp_used_poisoned_id);
759   else
760     Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
761 }
762 
763 void Preprocessor::updateOutOfDateIdentifier(const IdentifierInfo &II) const {
764   assert(II.isOutOfDate() && "not out of date");
765   getExternalSource()->updateOutOfDateIdentifier(II);
766 }
767 
768 /// HandleIdentifier - This callback is invoked when the lexer reads an
769 /// identifier.  This callback looks up the identifier in the map and/or
770 /// potentially macro expands it or turns it into a named token (like 'for').
771 ///
772 /// Note that callers of this method are guarded by checking the
773 /// IdentifierInfo's 'isHandleIdentifierCase' bit.  If this method changes, the
774 /// IdentifierInfo methods that compute these properties will need to change to
775 /// match.
776 bool Preprocessor::HandleIdentifier(Token &Identifier) {
777   assert(Identifier.getIdentifierInfo() &&
778          "Can't handle identifiers without identifier info!");
779 
780   IdentifierInfo &II = *Identifier.getIdentifierInfo();
781 
782   // If the information about this identifier is out of date, update it from
783   // the external source.
784   // We have to treat __VA_ARGS__ in a special way, since it gets
785   // serialized with isPoisoned = true, but our preprocessor may have
786   // unpoisoned it if we're defining a C99 macro.
787   if (II.isOutOfDate()) {
788     bool CurrentIsPoisoned = false;
789     const bool IsSpecialVariadicMacro =
790         &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
791     if (IsSpecialVariadicMacro)
792       CurrentIsPoisoned = II.isPoisoned();
793 
794     updateOutOfDateIdentifier(II);
795     Identifier.setKind(II.getTokenID());
796 
797     if (IsSpecialVariadicMacro)
798       II.setIsPoisoned(CurrentIsPoisoned);
799   }
800 
801   // If this identifier was poisoned, and if it was not produced from a macro
802   // expansion, emit an error.
803   if (II.isPoisoned() && CurPPLexer) {
804     HandlePoisonedIdentifier(Identifier);
805   }
806 
807   // If this is a macro to be expanded, do it.
808   if (const MacroDefinition MD = getMacroDefinition(&II)) {
809     const auto *MI = MD.getMacroInfo();
810     assert(MI && "macro definition with no macro info?");
811     if (!DisableMacroExpansion) {
812       if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
813         // C99 6.10.3p10: If the preprocessing token immediately after the
814         // macro name isn't a '(', this macro should not be expanded.
815         if (!MI->isFunctionLike() || isNextPPTokenLParen())
816           return HandleMacroExpandedIdentifier(Identifier, MD);
817       } else {
818         // C99 6.10.3.4p2 says that a disabled macro may never again be
819         // expanded, even if it's in a context where it could be expanded in the
820         // future.
821         Identifier.setFlag(Token::DisableExpand);
822         if (MI->isObjectLike() || isNextPPTokenLParen())
823           Diag(Identifier, diag::pp_disabled_macro_expansion);
824       }
825     }
826   }
827 
828   // If this identifier is a keyword in a newer Standard or proposed Standard,
829   // produce a warning. Don't warn if we're not considering macro expansion,
830   // since this identifier might be the name of a macro.
831   // FIXME: This warning is disabled in cases where it shouldn't be, like
832   //   "#define constexpr constexpr", "int constexpr;"
833   if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
834     Diag(Identifier, getIdentifierTable().getFutureCompatDiagKind(II, getLangOpts()))
835         << II.getName();
836     // Don't diagnose this keyword again in this translation unit.
837     II.setIsFutureCompatKeyword(false);
838   }
839 
840   // If this is an extension token, diagnose its use.
841   // We avoid diagnosing tokens that originate from macro definitions.
842   // FIXME: This warning is disabled in cases where it shouldn't be,
843   // like "#define TY typeof", "TY(1) x".
844   if (II.isExtensionToken() && !DisableMacroExpansion)
845     Diag(Identifier, diag::ext_token_used);
846 
847   // If this is the 'import' contextual keyword following an '@', note
848   // that the next token indicates a module name.
849   //
850   // Note that we do not treat 'import' as a contextual
851   // keyword when we're in a caching lexer, because caching lexers only get
852   // used in contexts where import declarations are disallowed.
853   //
854   // Likewise if this is the standard C++ import keyword.
855   if (((LastTokenWasAt && II.isModulesImport()) ||
856        Identifier.is(tok::kw_import)) &&
857       !InMacroArgs && !DisableMacroExpansion &&
858       (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
859       CurLexerCallback != CLK_CachingLexer) {
860     ModuleImportLoc = Identifier.getLocation();
861     NamedModuleImportPath.clear();
862     IsAtImport = true;
863     CurLexerCallback = CLK_LexAfterModuleImport;
864   }
865 
866   if ((II.isModulesDeclaration() || Identifier.is(tok::kw_module)) &&
867       !InMacroArgs && !DisableMacroExpansion &&
868       (getLangOpts().CPlusPlusModules || getLangOpts().DebuggerSupport) &&
869       CurLexerCallback != CLK_CachingLexer) {
870     CurLexerCallback = CLK_LexAfterModuleDecl;
871   }
872   return true;
873 }
874 
875 void Preprocessor::Lex(Token &Result) {
876   ++LexLevel;
877 
878   // We loop here until a lex function returns a token; this avoids recursion.
879   while (!CurLexerCallback(*this, Result))
880     ;
881 
882   if (Result.is(tok::unknown) && TheModuleLoader.HadFatalFailure)
883     return;
884 
885   if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
886     // Remember the identifier before code completion token.
887     setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
888     setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc());
889     // Set IdenfitierInfo to null to avoid confusing code that handles both
890     // identifiers and completion tokens.
891     Result.setIdentifierInfo(nullptr);
892   }
893 
894   // Update StdCXXImportSeqState to track our position within a C++20 import-seq
895   // if this token is being produced as a result of phase 4 of translation.
896   // Update TrackGMFState to decide if we are currently in a Global Module
897   // Fragment. GMF state updates should precede StdCXXImportSeq ones, since GMF state
898   // depends on the prevailing StdCXXImportSeq state in two cases.
899   if (getLangOpts().CPlusPlusModules && LexLevel == 1 &&
900       !Result.getFlag(Token::IsReinjected)) {
901     switch (Result.getKind()) {
902     case tok::l_paren: case tok::l_square: case tok::l_brace:
903       StdCXXImportSeqState.handleOpenBracket();
904       break;
905     case tok::r_paren: case tok::r_square:
906       StdCXXImportSeqState.handleCloseBracket();
907       break;
908     case tok::r_brace:
909       StdCXXImportSeqState.handleCloseBrace();
910       break;
911     // This token is injected to represent the translation of '#include "a.h"'
912     // into "import a.h;". Mimic the notional ';'.
913     case tok::annot_module_include:
914     case tok::annot_repl_input_end:
915     case tok::semi:
916       TrackGMFState.handleSemi();
917       StdCXXImportSeqState.handleSemi();
918       ModuleDeclState.handleSemi();
919       break;
920     case tok::header_name:
921     case tok::annot_header_unit:
922       StdCXXImportSeqState.handleHeaderName();
923       break;
924     case tok::kw_export:
925       TrackGMFState.handleExport();
926       StdCXXImportSeqState.handleExport();
927       ModuleDeclState.handleExport();
928       break;
929     case tok::annot_module_name: {
930       auto *Info = static_cast<ModuleNameInfo *>(Result.getAnnotationValue());
931       for (const auto &Tok : Info->getTokens()) {
932         switch (Tok.getKind()) {
933         case tok::identifier:
934           ModuleDeclState.handleIdentifier(Tok.getIdentifierInfo());
935           break;
936         case tok::period:
937           ModuleDeclState.handlePeriod();
938           break;
939         case tok::colon:
940           ModuleDeclState.handleColon();
941           break;
942         default:
943           llvm_unreachable("Unexpected token in module name");
944         }
945       }
946       if (ModuleDeclState.isModuleCandidate())
947         break;
948       TrackGMFState.handleMisc();
949       StdCXXImportSeqState.handleMisc();
950       ModuleDeclState.handleMisc();
951       break;
952     }
953     case tok::identifier:
954       // Check "import" and "module" when there is no open bracket. The two
955       // identifiers are not meaningful with open brackets.
956       if (StdCXXImportSeqState.atTopLevel()) {
957         if (Result.getIdentifierInfo()->isModulesImport()) {
958           TrackGMFState.handleImport(StdCXXImportSeqState.afterTopLevelSeq());
959           StdCXXImportSeqState.handleImport();
960           if (StdCXXImportSeqState.afterImportSeq()) {
961             ModuleImportLoc = Result.getLocation();
962             NamedModuleImportPath.clear();
963             IsAtImport = false;
964             CurLexerCallback = CLK_LexAfterModuleImport;
965           }
966           break;
967         }
968         if (Result.getIdentifierInfo()->isModulesDeclaration()) {
969           TrackGMFState.handleModule(StdCXXImportSeqState.afterTopLevelSeq());
970           ModuleDeclState.handleModule();
971           CurLexerCallback = CLK_LexAfterModuleDecl;
972           break;
973         }
974       }
975       if (ModuleDeclState.isModuleCandidate())
976         break;
977       [[fallthrough]];
978     default:
979       TrackGMFState.handleMisc();
980       StdCXXImportSeqState.handleMisc();
981       ModuleDeclState.handleMisc();
982       break;
983     }
984   }
985 
986   if (CurLexer && ++CheckPointCounter == CheckPointStepSize) {
987     CheckPoints[CurLexer->getFileID()].push_back(CurLexer->BufferPtr);
988     CheckPointCounter = 0;
989   }
990 
991   LastTokenWasAt = Result.is(tok::at);
992   --LexLevel;
993 
994   if ((LexLevel == 0 || PreprocessToken) &&
995       !Result.getFlag(Token::IsReinjected)) {
996     if (LexLevel == 0)
997       ++TokenCount;
998     if (OnToken)
999       OnToken(Result);
1000   }
1001 }
1002 
1003 void Preprocessor::LexTokensUntilEOF(std::vector<Token> *Tokens) {
1004   while (1) {
1005     Token Tok;
1006     Lex(Tok);
1007     if (Tok.isOneOf(tok::unknown, tok::eof, tok::eod,
1008                     tok::annot_repl_input_end))
1009       break;
1010     if (Tokens != nullptr)
1011       Tokens->push_back(Tok);
1012   }
1013 }
1014 
1015 /// Lex a header-name token (including one formed from header-name-tokens if
1016 /// \p AllowMacroExpansion is \c true).
1017 ///
1018 /// \param FilenameTok Filled in with the next token. On success, this will
1019 ///        be either a header_name token. On failure, it will be whatever other
1020 ///        token was found instead.
1021 /// \param AllowMacroExpansion If \c true, allow the header name to be formed
1022 ///        by macro expansion (concatenating tokens as necessary if the first
1023 ///        token is a '<').
1024 /// \return \c true if we reached EOD or EOF while looking for a > token in
1025 ///         a concatenated header name and diagnosed it. \c false otherwise.
1026 bool Preprocessor::LexHeaderName(Token &FilenameTok, bool AllowMacroExpansion) {
1027   // Lex using header-name tokenization rules if tokens are being lexed from
1028   // a file. Just grab a token normally if we're in a macro expansion.
1029   if (CurPPLexer)
1030     CurPPLexer->LexIncludeFilename(FilenameTok);
1031   else
1032     Lex(FilenameTok);
1033 
1034   // This could be a <foo/bar.h> file coming from a macro expansion.  In this
1035   // case, glue the tokens together into an angle_string_literal token.
1036   SmallString<128> FilenameBuffer;
1037   if (FilenameTok.is(tok::less) && AllowMacroExpansion) {
1038     bool StartOfLine = FilenameTok.isAtStartOfLine();
1039     bool LeadingSpace = FilenameTok.hasLeadingSpace();
1040     bool LeadingEmptyMacro = FilenameTok.hasLeadingEmptyMacro();
1041 
1042     SourceLocation Start = FilenameTok.getLocation();
1043     SourceLocation End;
1044     FilenameBuffer.push_back('<');
1045 
1046     // Consume tokens until we find a '>'.
1047     // FIXME: A header-name could be formed starting or ending with an
1048     // alternative token. It's not clear whether that's ill-formed in all
1049     // cases.
1050     while (FilenameTok.isNot(tok::greater)) {
1051       Lex(FilenameTok);
1052       if (FilenameTok.isOneOf(tok::eod, tok::eof)) {
1053         Diag(FilenameTok.getLocation(), diag::err_expected) << tok::greater;
1054         Diag(Start, diag::note_matching) << tok::less;
1055         return true;
1056       }
1057 
1058       End = FilenameTok.getLocation();
1059 
1060       // FIXME: Provide code completion for #includes.
1061       if (FilenameTok.is(tok::code_completion)) {
1062         setCodeCompletionReached();
1063         Lex(FilenameTok);
1064         continue;
1065       }
1066 
1067       // Append the spelling of this token to the buffer. If there was a space
1068       // before it, add it now.
1069       if (FilenameTok.hasLeadingSpace())
1070         FilenameBuffer.push_back(' ');
1071 
1072       // Get the spelling of the token, directly into FilenameBuffer if
1073       // possible.
1074       size_t PreAppendSize = FilenameBuffer.size();
1075       FilenameBuffer.resize(PreAppendSize + FilenameTok.getLength());
1076 
1077       const char *BufPtr = &FilenameBuffer[PreAppendSize];
1078       unsigned ActualLen = getSpelling(FilenameTok, BufPtr);
1079 
1080       // If the token was spelled somewhere else, copy it into FilenameBuffer.
1081       if (BufPtr != &FilenameBuffer[PreAppendSize])
1082         memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1083 
1084       // Resize FilenameBuffer to the correct size.
1085       if (FilenameTok.getLength() != ActualLen)
1086         FilenameBuffer.resize(PreAppendSize + ActualLen);
1087     }
1088 
1089     FilenameTok.startToken();
1090     FilenameTok.setKind(tok::header_name);
1091     FilenameTok.setFlagValue(Token::StartOfLine, StartOfLine);
1092     FilenameTok.setFlagValue(Token::LeadingSpace, LeadingSpace);
1093     FilenameTok.setFlagValue(Token::LeadingEmptyMacro, LeadingEmptyMacro);
1094     CreateString(FilenameBuffer, FilenameTok, Start, End);
1095   } else if (FilenameTok.is(tok::string_literal) && AllowMacroExpansion) {
1096     // Convert a string-literal token of the form " h-char-sequence "
1097     // (produced by macro expansion) into a header-name token.
1098     //
1099     // The rules for header-names don't quite match the rules for
1100     // string-literals, but all the places where they differ result in
1101     // undefined behavior, so we can and do treat them the same.
1102     //
1103     // A string-literal with a prefix or suffix is not translated into a
1104     // header-name. This could theoretically be observable via the C++20
1105     // context-sensitive header-name formation rules.
1106     StringRef Str = getSpelling(FilenameTok, FilenameBuffer);
1107     if (Str.size() >= 2 && Str.front() == '"' && Str.back() == '"')
1108       FilenameTok.setKind(tok::header_name);
1109   }
1110 
1111   return false;
1112 }
1113 
1114 /// Collect the tokens of a C++20 pp-import-suffix.
1115 void Preprocessor::CollectPpImportSuffix(SmallVectorImpl<Token> &Toks) {
1116   // FIXME: For error recovery, consider recognizing attribute syntax here
1117   // and terminating / diagnosing a missing semicolon if we find anything
1118   // else? (Can we leave that to the parser?)
1119   unsigned BracketDepth = 0;
1120   while (true) {
1121     Toks.emplace_back();
1122     Lex(Toks.back());
1123 
1124     switch (Toks.back().getKind()) {
1125     case tok::l_paren: case tok::l_square: case tok::l_brace:
1126       ++BracketDepth;
1127       break;
1128 
1129     case tok::r_paren: case tok::r_square: case tok::r_brace:
1130       if (BracketDepth == 0)
1131         return;
1132       --BracketDepth;
1133       break;
1134 
1135     case tok::semi:
1136       if (BracketDepth == 0)
1137         return;
1138     break;
1139 
1140     case tok::eof:
1141       return;
1142 
1143     default:
1144       break;
1145     }
1146   }
1147 }
1148 
1149 ModuleNameInfo::ModuleNameInfo(ArrayRef<Token> AnnotToks,
1150                                std::optional<unsigned> ColonIndex) {
1151   assert(!AnnotToks.empty() && "Named module token cannot be empty.");
1152   if (!ColonIndex.has_value())
1153     ColonIndex = AnnotToks.size();
1154   ModuleName = ArrayRef(AnnotToks.begin(), AnnotToks.begin() + *ColonIndex);
1155   PartitionName = ArrayRef(AnnotToks.begin() + *ColonIndex, AnnotToks.end());
1156   assert(ModuleName.end() == PartitionName.begin());
1157 }
1158 
1159 std::string ModuleNameInfo::getFlatName() const {
1160   std::string FlatModuleName;
1161   for (auto &Tok : getTokens()) {
1162     switch (Tok.getKind()) {
1163     case tok::identifier:
1164       FlatModuleName += Tok.getIdentifierInfo()->getName();
1165       break;
1166     case tok::period:
1167       FlatModuleName += '.';
1168       break;
1169     case tok::colon:
1170       FlatModuleName += ':';
1171       break;
1172     default:
1173       llvm_unreachable("Unexpected token in module name");
1174     }
1175   }
1176   return FlatModuleName;
1177 }
1178 
1179 void ModuleNameInfo::getModuleIdPath(
1180     SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path) const {
1181   return getModuleIdPath(getTokens(), Path);
1182 }
1183 
1184 void ModuleNameInfo::getModuleIdPath(
1185     ArrayRef<Token> ModuleName,
1186     SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path) {
1187   for (const auto &Tok : ModuleName) {
1188     if (Tok.is(tok::identifier))
1189       Path.push_back(
1190           std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
1191   }
1192 }
1193 
1194 /// Lex a module name or a partition name.
1195 ///
1196 ///     module-name:
1197 ///           module-name-qualifier[opt] identifier
1198 ///
1199 ///     partition-name: [C++20]
1200 ///           : module-name-qualifier[opt] identifier
1201 ///
1202 ///     module-name-qualifier
1203 ///           module-name-qualifier[opt] identifier .
1204 bool Preprocessor::LexModuleName(Token &Result, bool IsImport) {
1205   bool ExpectsIdentifier = true, IsLexingPartition = false;
1206   SmallVector<Token, 8> ModuleName;
1207   std::optional<unsigned> ColonTokIndex;
1208   auto LexNextToken = [&](Token &Tok) {
1209     if (IsImport)
1210       Lex(Tok);
1211     else
1212       LexUnexpandedToken(Tok);
1213   };
1214 
1215   while (true) {
1216     LexNextToken(Result);
1217     if (ExpectsIdentifier && Result.is(tok::identifier)) {
1218       auto *MI = getMacroInfo(Result.getIdentifierInfo());
1219       if (getLangOpts().CPlusPlusModules && !IsImport && MI &&
1220           MI->isObjectLike()) {
1221         Diag(Result, diag::err_module_decl_cannot_be_macros)
1222             << Result.getLocation() << IsLexingPartition
1223             << Result.getIdentifierInfo();
1224       }
1225       ModuleName.push_back(Result);
1226       ExpectsIdentifier = false;
1227       continue;
1228     }
1229 
1230     if (!ExpectsIdentifier && Result.is(tok::period)) {
1231       ModuleName.push_back(Result);
1232       ExpectsIdentifier = true;
1233       continue;
1234     }
1235 
1236     // Module partition only allowed in C++20 Modules.
1237     if (getLangOpts().CPlusPlusModules && Result.is(tok::colon)) {
1238       // Handle the form like: import :P;
1239       // If the token after ':' is not an identifier, this is a invalid module
1240       // name.
1241       if (ModuleName.empty()) {
1242         Token Tmp;
1243         LexNextToken(Tmp);
1244         EnterToken(Tmp, /*IsReiject=*/false);
1245         // A private-module-fragment:
1246         // export module :private;
1247         if (!IsImport && Tmp.is(tok::kw_private))
1248           return true;
1249         // import :N;
1250         if (IsImport && Tmp.isNot(tok::identifier))
1251           return false;
1252       } else if (!ExpectsIdentifier) {
1253         ExpectsIdentifier = true;
1254       }
1255       IsLexingPartition = true;
1256       ColonTokIndex = ModuleName.size();
1257       ModuleName.push_back(Result);
1258       continue;
1259     }
1260 
1261     // [cpp.module]/p2: where the pp-tokens (if any) shall not begin with a (
1262     // preprocessing token [...]
1263     //
1264     // We only emit diagnostic in the preprocessor, and in the parser we skip
1265     // invalid tokens and recover from errors.
1266     if (getLangOpts().CPlusPlusModules && !ExpectsIdentifier &&
1267         Result.is(tok::l_paren))
1268       Diag(Result, diag::err_unxepected_paren_in_module_decl)
1269           << IsLexingPartition;
1270     break;
1271   }
1272 
1273   // Put the last token back to stream, it's not a valid part of module name.
1274   // We lexed it unexpanded but it might be a valid macro expansion
1275   Result.clearFlag(Token::DisableExpand);
1276   auto ToksCopy = std::make_unique<Token[]>(1);
1277   *ToksCopy.get() = Result;
1278   EnterTokenStream(std::move(ToksCopy), 1,
1279                    /*DisableMacroExpansion=*/false,
1280                    /*IsReinject=*/false);
1281 
1282   if (ModuleName.empty())
1283     return false;
1284   Result.startToken();
1285   Result.setKind(tok::annot_module_name);
1286   Result.setLocation(ModuleName.front().getLocation());
1287   Result.setAnnotationEndLoc(ModuleName.back().getLocation());
1288   auto AnnotToks = ArrayRef(ModuleName).copy(getPreprocessorAllocator());
1289   ModuleNameInfo *Info =
1290       new (getPreprocessorAllocator()) ModuleNameInfo(AnnotToks, ColonTokIndex);
1291   Result.setAnnotationValue(static_cast<void *>(Info));
1292   return true;
1293 }
1294 
1295 /// Lex a token following the 'import' contextual keyword.
1296 ///
1297 ///     pp-import: [C++20]
1298 ///           import header-name pp-import-suffix[opt] ;
1299 ///           import header-name-tokens pp-import-suffix[opt] ;
1300 /// [ObjC]    @ import module-name ;
1301 /// [Clang]   import module-name ;
1302 ///
1303 ///     header-name-tokens:
1304 ///           string-literal
1305 ///           < [any sequence of preprocessing-tokens other than >] >
1306 ///
1307 ///     module-name:
1308 ///           module-name-qualifier[opt] identifier
1309 ///
1310 ///     module-name-qualifier
1311 ///           module-name-qualifier[opt] identifier .
1312 ///
1313 /// We respond to a pp-import by importing macros from the named module.
1314 bool Preprocessor::LexAfterModuleImport(Token &Result) {
1315   // Figure out what kind of lexer we actually have.
1316   recomputeCurLexerKind();
1317 
1318   // Allocate a holding buffer for a sequence of tokens and introduce it into
1319   // the token stream.
1320   auto EnterTokens = [this](ArrayRef<Token> Toks) {
1321     auto ToksCopy = std::make_unique<Token[]>(Toks.size());
1322     std::copy(Toks.begin(), Toks.end(), ToksCopy.get());
1323     EnterTokenStream(std::move(ToksCopy), Toks.size(),
1324                      /*DisableMacroExpansion*/ true, /*IsReinject*/ false);
1325   };
1326 
1327   SmallVector<Token, 32> Suffix;
1328 
1329   // Lex the next token. The header-name lexing rules are used at the start of
1330   // a pp-import.
1331   //
1332   // For now, we only support header-name imports in C++20 mode.
1333   // FIXME: Should we allow this in all language modes that support an import
1334   // declaration as an extension?
1335   if (NamedModuleImportPath.empty() && getLangOpts().CPlusPlusModules) {
1336     if (LexHeaderName(Result))
1337       return true;
1338 
1339     // Check for a header-name.
1340     if (Result.is(tok::header_name)) {
1341       // Enter the header-name token into the token stream; a Lex action cannot
1342       // both return a token and cache tokens (doing so would corrupt the token
1343       // cache if the call to Lex comes from CachingLex / PeekAhead).
1344       Suffix.push_back(Result);
1345 
1346       // Consume the pp-import-suffix and expand any macros in it now. We'll add
1347       // it back into the token stream later.
1348       CollectPpImportSuffix(Suffix);
1349       if (Suffix.back().isNot(tok::semi)) {
1350         // This is not a pp-import after all.
1351         EnterTokens(Suffix);
1352         return false;
1353       }
1354 
1355       // C++2a [cpp.module]p1:
1356       //   The ';' preprocessing-token terminating a pp-import shall not have
1357       //   been produced by macro replacement.
1358       SourceLocation SemiLoc = Suffix.back().getLocation();
1359       if (SemiLoc.isMacroID())
1360         Diag(SemiLoc, diag::err_header_import_semi_in_macro);
1361 
1362       // Reconstitute the import token.
1363       Token ImportTok;
1364       ImportTok.startToken();
1365       ImportTok.setKind(tok::kw_import);
1366       ImportTok.setLocation(ModuleImportLoc);
1367       ImportTok.setIdentifierInfo(getIdentifierInfo("import"));
1368       ImportTok.setLength(6);
1369 
1370       auto Action = HandleHeaderIncludeOrImport(
1371           /*HashLoc*/ SourceLocation(), ImportTok, Suffix.front(), SemiLoc);
1372       switch (Action.Kind) {
1373       case ImportAction::None:
1374         break;
1375 
1376       case ImportAction::ModuleBegin:
1377         // Let the parser know we're textually entering the module.
1378         Suffix.emplace_back();
1379         Suffix.back().startToken();
1380         Suffix.back().setKind(tok::annot_module_begin);
1381         Suffix.back().setLocation(SemiLoc);
1382         Suffix.back().setAnnotationEndLoc(SemiLoc);
1383         Suffix.back().setAnnotationValue(Action.ModuleForHeader);
1384         [[fallthrough]];
1385 
1386       case ImportAction::ModuleImport:
1387       case ImportAction::HeaderUnitImport:
1388       case ImportAction::SkippedModuleImport:
1389         // We chose to import (or textually enter) the file. Convert the
1390         // header-name token into a header unit annotation token.
1391         Suffix[0].setKind(tok::annot_header_unit);
1392         Suffix[0].setAnnotationEndLoc(Suffix[0].getLocation());
1393         Suffix[0].setAnnotationValue(Action.ModuleForHeader);
1394         // FIXME: Call the moduleImport callback?
1395         break;
1396       case ImportAction::Failure:
1397         assert(TheModuleLoader.HadFatalFailure &&
1398                "This should be an early exit only to a fatal error");
1399         Result.setKind(tok::eof);
1400         CurLexer->cutOffLexing();
1401         EnterTokens(Suffix);
1402         return true;
1403       }
1404 
1405       EnterTokens(Suffix);
1406       return false;
1407     }
1408   } else {
1409     Lex(Result);
1410   }
1411 
1412   if (Result.isOneOf(tok::identifier, tok::colon)) {
1413     EnterToken(Result, /*IsReinject=*/false);
1414     if (!LexModuleName(Result, /*IsImport=*/true))
1415       return true;
1416     auto *Info = Result.getAnnotationValueAs<ModuleNameInfo *>();
1417     if (getLangOpts().CPlusPlusModules) {
1418       // Under the standard C++ Modules, the dot is just part of the module
1419       // name, and not a real hierarchy separator. Flatten such module names
1420       // now.
1421       //
1422       // FIXME: Is this the right level to be performing this transformation?
1423       std::string FlatModuleName;
1424       if (Info->getTokens().front().is(tok::colon)) {
1425         // Import a module partition allowed in C++20 Modules.
1426         // We can import a partition in named module TU.
1427         if (NamedModuleImportPath.empty() && ModuleDeclState.isNamedModule())
1428           FlatModuleName = llvm::Twine(ModuleDeclState.getPrimaryName())
1429                                .concat(Info->getFlatName())
1430                                .str();
1431         else
1432           return true;
1433       } else {
1434         FlatModuleName = Info->getFlatName();
1435       }
1436       NamedModuleImportPath.emplace_back(getIdentifierInfo(FlatModuleName),
1437                                          Result.getLocation());
1438     } else {
1439       Info->getModuleIdPath(NamedModuleImportPath);
1440     }
1441   }
1442 
1443   // If we didn't recognize a module name at all, this is not a (valid) import.
1444   if (NamedModuleImportPath.empty() || Result.is(tok::eof))
1445     return true;
1446 
1447   // Consume the pp-import-suffix and expand any macros in it now, if we're not
1448   // at the semicolon already.
1449   SourceLocation SemiLoc = Result.getLocation();
1450   if (Result.isNot(tok::semi)) {
1451     Suffix.push_back(Result);
1452     CollectPpImportSuffix(Suffix);
1453     if (Suffix.back().isNot(tok::semi)) {
1454       // This is not an import after all.
1455       EnterTokens(Suffix);
1456       return false;
1457     }
1458     SemiLoc = Suffix.back().getLocation();
1459   }
1460 
1461   Module *Imported = nullptr;
1462   // We don't/shouldn't load the standard c++20 modules when preprocessing.
1463   if (getLangOpts().Modules && !isInImportingCXXNamedModules()) {
1464     Imported = TheModuleLoader.loadModule(ModuleImportLoc,
1465                                           NamedModuleImportPath,
1466                                           Module::Hidden,
1467                                           /*IsInclusionDirective=*/false);
1468     if (Imported)
1469       makeModuleVisible(Imported, SemiLoc);
1470   }
1471 
1472   if (Callbacks)
1473     Callbacks->moduleImport(ModuleImportLoc, NamedModuleImportPath, Imported);
1474 
1475   if (!Suffix.empty()) {
1476     EnterTokens(Suffix);
1477     return false;
1478   }
1479   return true;
1480 }
1481 
1482 /// Lex a token following the 'module' contextual keyword.
1483 ///
1484 /// [cpp.module]/p2:
1485 /// The pp-tokens, if any, of a pp-module shall be of the form:
1486 ///       pp-module-name pp-module-partition[opt] pp-tokens[opt]
1487 ///
1488 /// where the pp-tokens (if any) shall not begin with a ( preprocessing token
1489 /// and the grammar non-terminals are defined as:
1490 ///       pp-module-name:
1491 ///             pp-module-name-qualifierp[opt] identifier
1492 ///       pp-module-partition:
1493 ///             : pp-module-name-qualifier[opt] identifier
1494 ///       pp-module-name-qualifier:
1495 ///             identifier .
1496 ///             pp-module-name-qualifier identifier .
1497 /// No identifier in the pp-module-name or pp-module-partition shall currently
1498 /// be defined as an object-like macro.
1499 ///
1500 /// [cpp.module]/p3:
1501 /// Any preprocessing tokens after the module preprocessing token in the module
1502 /// directive are processed just as in normal text.
1503 bool Preprocessor::LexAfterModuleDecl(Token &Result) {
1504   // Figure out what kind of lexer we actually have.
1505   recomputeCurLexerKind();
1506   return LexModuleName(Result, /*IsImport=*/false);
1507 }
1508 
1509 void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
1510   CurSubmoduleState->VisibleModules.setVisible(
1511       M, Loc, [](Module *) {},
1512       [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
1513         // FIXME: Include the path in the diagnostic.
1514         // FIXME: Include the import location for the conflicting module.
1515         Diag(ModuleImportLoc, diag::warn_module_conflict)
1516             << Path[0]->getFullModuleName()
1517             << Conflict->getFullModuleName()
1518             << Message;
1519       });
1520 
1521   // Add this module to the imports list of the currently-built submodule.
1522   if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
1523     BuildingSubmoduleStack.back().M->Imports.insert(M);
1524 }
1525 
1526 bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
1527                                           const char *DiagnosticTag,
1528                                           bool AllowMacroExpansion) {
1529   // We need at least one string literal.
1530   if (Result.isNot(tok::string_literal)) {
1531     Diag(Result, diag::err_expected_string_literal)
1532       << /*Source='in...'*/0 << DiagnosticTag;
1533     return false;
1534   }
1535 
1536   // Lex string literal tokens, optionally with macro expansion.
1537   SmallVector<Token, 4> StrToks;
1538   do {
1539     StrToks.push_back(Result);
1540 
1541     if (Result.hasUDSuffix())
1542       Diag(Result, diag::err_invalid_string_udl);
1543 
1544     if (AllowMacroExpansion)
1545       Lex(Result);
1546     else
1547       LexUnexpandedToken(Result);
1548   } while (Result.is(tok::string_literal));
1549 
1550   // Concatenate and parse the strings.
1551   StringLiteralParser Literal(StrToks, *this);
1552   assert(Literal.isOrdinary() && "Didn't allow wide strings in");
1553 
1554   if (Literal.hadError)
1555     return false;
1556 
1557   if (Literal.Pascal) {
1558     Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
1559       << /*Source='in...'*/0 << DiagnosticTag;
1560     return false;
1561   }
1562 
1563   String = std::string(Literal.GetString());
1564   return true;
1565 }
1566 
1567 bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
1568   assert(Tok.is(tok::numeric_constant));
1569   SmallString<8> IntegerBuffer;
1570   bool NumberInvalid = false;
1571   StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
1572   if (NumberInvalid)
1573     return false;
1574   NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(),
1575                                getLangOpts(), getTargetInfo(),
1576                                getDiagnostics());
1577   if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
1578     return false;
1579   llvm::APInt APVal(64, 0);
1580   if (Literal.GetIntegerValue(APVal))
1581     return false;
1582   Lex(Tok);
1583   Value = APVal.getLimitedValue();
1584   return true;
1585 }
1586 
1587 void Preprocessor::addCommentHandler(CommentHandler *Handler) {
1588   assert(Handler && "NULL comment handler");
1589   assert(!llvm::is_contained(CommentHandlers, Handler) &&
1590          "Comment handler already registered");
1591   CommentHandlers.push_back(Handler);
1592 }
1593 
1594 void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
1595   std::vector<CommentHandler *>::iterator Pos =
1596       llvm::find(CommentHandlers, Handler);
1597   assert(Pos != CommentHandlers.end() && "Comment handler not registered");
1598   CommentHandlers.erase(Pos);
1599 }
1600 
1601 bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
1602   bool AnyPendingTokens = false;
1603   for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
1604        HEnd = CommentHandlers.end();
1605        H != HEnd; ++H) {
1606     if ((*H)->HandleComment(*this, Comment))
1607       AnyPendingTokens = true;
1608   }
1609   if (!AnyPendingTokens || getCommentRetentionState())
1610     return false;
1611   Lex(result);
1612   return true;
1613 }
1614 
1615 void Preprocessor::emitMacroDeprecationWarning(const Token &Identifier) const {
1616   const MacroAnnotations &A =
1617       getMacroAnnotations(Identifier.getIdentifierInfo());
1618   assert(A.DeprecationInfo &&
1619          "Macro deprecation warning without recorded annotation!");
1620   const MacroAnnotationInfo &Info = *A.DeprecationInfo;
1621   if (Info.Message.empty())
1622     Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1623         << Identifier.getIdentifierInfo() << 0;
1624   else
1625     Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1626         << Identifier.getIdentifierInfo() << 1 << Info.Message;
1627   Diag(Info.Location, diag::note_pp_macro_annotation) << 0;
1628 }
1629 
1630 void Preprocessor::emitRestrictExpansionWarning(const Token &Identifier) const {
1631   const MacroAnnotations &A =
1632       getMacroAnnotations(Identifier.getIdentifierInfo());
1633   assert(A.RestrictExpansionInfo &&
1634          "Macro restricted expansion warning without recorded annotation!");
1635   const MacroAnnotationInfo &Info = *A.RestrictExpansionInfo;
1636   if (Info.Message.empty())
1637     Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1638         << Identifier.getIdentifierInfo() << 0;
1639   else
1640     Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1641         << Identifier.getIdentifierInfo() << 1 << Info.Message;
1642   Diag(Info.Location, diag::note_pp_macro_annotation) << 1;
1643 }
1644 
1645 void Preprocessor::emitRestrictInfNaNWarning(const Token &Identifier,
1646                                              unsigned DiagSelection) const {
1647   Diag(Identifier, diag::warn_fp_nan_inf_when_disabled) << DiagSelection << 1;
1648 }
1649 
1650 void Preprocessor::emitFinalMacroWarning(const Token &Identifier,
1651                                          bool IsUndef) const {
1652   const MacroAnnotations &A =
1653       getMacroAnnotations(Identifier.getIdentifierInfo());
1654   assert(A.FinalAnnotationLoc &&
1655          "Final macro warning without recorded annotation!");
1656 
1657   Diag(Identifier, diag::warn_pragma_final_macro)
1658       << Identifier.getIdentifierInfo() << (IsUndef ? 0 : 1);
1659   Diag(*A.FinalAnnotationLoc, diag::note_pp_macro_annotation) << 2;
1660 }
1661 
1662 bool Preprocessor::isSafeBufferOptOut(const SourceManager &SourceMgr,
1663                                       const SourceLocation &Loc) const {
1664   // The lambda that tests if a `Loc` is in an opt-out region given one opt-out
1665   // region map:
1666   auto TestInMap = [&SourceMgr](const SafeBufferOptOutRegionsTy &Map,
1667                                 const SourceLocation &Loc) -> bool {
1668     // Try to find a region in `SafeBufferOptOutMap` where `Loc` is in:
1669     auto FirstRegionEndingAfterLoc = llvm::partition_point(
1670         Map, [&SourceMgr,
1671               &Loc](const std::pair<SourceLocation, SourceLocation> &Region) {
1672           return SourceMgr.isBeforeInTranslationUnit(Region.second, Loc);
1673         });
1674 
1675     if (FirstRegionEndingAfterLoc != Map.end()) {
1676       // To test if the start location of the found region precedes `Loc`:
1677       return SourceMgr.isBeforeInTranslationUnit(
1678           FirstRegionEndingAfterLoc->first, Loc);
1679     }
1680     // If we do not find a region whose end location passes `Loc`, we want to
1681     // check if the current region is still open:
1682     if (!Map.empty() && Map.back().first == Map.back().second)
1683       return SourceMgr.isBeforeInTranslationUnit(Map.back().first, Loc);
1684     return false;
1685   };
1686 
1687   // What the following does:
1688   //
1689   // If `Loc` belongs to the local TU, we just look up `SafeBufferOptOutMap`.
1690   // Otherwise, `Loc` is from a loaded AST.  We look up the
1691   // `LoadedSafeBufferOptOutMap` first to get the opt-out region map of the
1692   // loaded AST where `Loc` is at.  Then we find if `Loc` is in an opt-out
1693   // region w.r.t. the region map.  If the region map is absent, it means there
1694   // is no opt-out pragma in that loaded AST.
1695   //
1696   // Opt-out pragmas in the local TU or a loaded AST is not visible to another
1697   // one of them.  That means if you put the pragmas around a `#include
1698   // "module.h"`, where module.h is a module, it is not actually suppressing
1699   // warnings in module.h.  This is fine because warnings in module.h will be
1700   // reported when module.h is compiled in isolation and nothing in module.h
1701   // will be analyzed ever again.  So you will not see warnings from the file
1702   // that imports module.h anyway. And you can't even do the same thing for PCHs
1703   //  because they can only be included from the command line.
1704 
1705   if (SourceMgr.isLocalSourceLocation(Loc))
1706     return TestInMap(SafeBufferOptOutMap, Loc);
1707 
1708   const SafeBufferOptOutRegionsTy *LoadedRegions =
1709       LoadedSafeBufferOptOutMap.lookupLoadedOptOutMap(Loc, SourceMgr);
1710 
1711   if (LoadedRegions)
1712     return TestInMap(*LoadedRegions, Loc);
1713   return false;
1714 }
1715 
1716 bool Preprocessor::enterOrExitSafeBufferOptOutRegion(
1717     bool isEnter, const SourceLocation &Loc) {
1718   if (isEnter) {
1719     if (isPPInSafeBufferOptOutRegion())
1720       return true; // invalid enter action
1721     InSafeBufferOptOutRegion = true;
1722     CurrentSafeBufferOptOutStart = Loc;
1723 
1724     // To set the start location of a new region:
1725 
1726     if (!SafeBufferOptOutMap.empty()) {
1727       [[maybe_unused]] auto *PrevRegion = &SafeBufferOptOutMap.back();
1728       assert(PrevRegion->first != PrevRegion->second &&
1729              "Shall not begin a safe buffer opt-out region before closing the "
1730              "previous one.");
1731     }
1732     // If the start location equals to the end location, we call the region a
1733     // open region or a unclosed region (i.e., end location has not been set
1734     // yet).
1735     SafeBufferOptOutMap.emplace_back(Loc, Loc);
1736   } else {
1737     if (!isPPInSafeBufferOptOutRegion())
1738       return true; // invalid enter action
1739     InSafeBufferOptOutRegion = false;
1740 
1741     // To set the end location of the current open region:
1742 
1743     assert(!SafeBufferOptOutMap.empty() &&
1744            "Misordered safe buffer opt-out regions");
1745     auto *CurrRegion = &SafeBufferOptOutMap.back();
1746     assert(CurrRegion->first == CurrRegion->second &&
1747            "Set end location to a closed safe buffer opt-out region");
1748     CurrRegion->second = Loc;
1749   }
1750   return false;
1751 }
1752 
1753 bool Preprocessor::isPPInSafeBufferOptOutRegion() {
1754   return InSafeBufferOptOutRegion;
1755 }
1756 bool Preprocessor::isPPInSafeBufferOptOutRegion(SourceLocation &StartLoc) {
1757   StartLoc = CurrentSafeBufferOptOutStart;
1758   return InSafeBufferOptOutRegion;
1759 }
1760 
1761 SmallVector<SourceLocation, 64>
1762 Preprocessor::serializeSafeBufferOptOutMap() const {
1763   assert(!InSafeBufferOptOutRegion &&
1764          "Attempt to serialize safe buffer opt-out regions before file being "
1765          "completely preprocessed");
1766 
1767   SmallVector<SourceLocation, 64> SrcSeq;
1768 
1769   for (const auto &[begin, end] : SafeBufferOptOutMap) {
1770     SrcSeq.push_back(begin);
1771     SrcSeq.push_back(end);
1772   }
1773   // Only `SafeBufferOptOutMap` gets serialized. No need to serialize
1774   // `LoadedSafeBufferOptOutMap` because if this TU loads a pch/module, every
1775   // pch/module in the pch-chain/module-DAG will be loaded one by one in order.
1776   // It means that for each loading pch/module m, it just needs to load m's own
1777   // `SafeBufferOptOutMap`.
1778   return SrcSeq;
1779 }
1780 
1781 bool Preprocessor::setDeserializedSafeBufferOptOutMap(
1782     const SmallVectorImpl<SourceLocation> &SourceLocations) {
1783   if (SourceLocations.size() == 0)
1784     return false;
1785 
1786   assert(SourceLocations.size() % 2 == 0 &&
1787          "ill-formed SourceLocation sequence");
1788 
1789   auto It = SourceLocations.begin();
1790   SafeBufferOptOutRegionsTy &Regions =
1791       LoadedSafeBufferOptOutMap.findAndConsLoadedOptOutMap(*It, SourceMgr);
1792 
1793   do {
1794     SourceLocation Begin = *It++;
1795     SourceLocation End = *It++;
1796 
1797     Regions.emplace_back(Begin, End);
1798   } while (It != SourceLocations.end());
1799   return true;
1800 }
1801 
1802 ModuleLoader::~ModuleLoader() = default;
1803 
1804 CommentHandler::~CommentHandler() = default;
1805 
1806 EmptylineHandler::~EmptylineHandler() = default;
1807 
1808 CodeCompletionHandler::~CodeCompletionHandler() = default;
1809 
1810 void Preprocessor::createPreprocessingRecord() {
1811   if (Record)
1812     return;
1813 
1814   Record = new PreprocessingRecord(getSourceManager());
1815   addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
1816 }
1817 
1818 const char *Preprocessor::getCheckPoint(FileID FID, const char *Start) const {
1819   if (auto It = CheckPoints.find(FID); It != CheckPoints.end()) {
1820     const SmallVector<const char *> &FileCheckPoints = It->second;
1821     const char *Last = nullptr;
1822     // FIXME: Do better than a linear search.
1823     for (const char *P : FileCheckPoints) {
1824       if (P > Start)
1825         break;
1826       Last = P;
1827     }
1828     return Last;
1829   }
1830 
1831   return nullptr;
1832 }
1833