Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Lex/PPLexerChange.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
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 pieces of the Preprocessor interface that manage the
10
// current lexer stack.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Basic/FileManager.h"
15
#include "clang/Basic/SourceLocation.h"
16
#include "clang/Basic/SourceManager.h"
17
#include "clang/Lex/HeaderSearch.h"
18
#include "clang/Lex/LexDiagnostic.h"
19
#include "clang/Lex/MacroInfo.h"
20
#include "clang/Lex/Preprocessor.h"
21
#include "clang/Lex/PreprocessorOptions.h"
22
#include "llvm/ADT/StringSwitch.h"
23
#include "llvm/Support/FileSystem.h"
24
#include "llvm/Support/MemoryBufferRef.h"
25
#include "llvm/Support/Path.h"
26
27
using namespace clang;
28
29
//===----------------------------------------------------------------------===//
30
// Miscellaneous Methods.
31
//===----------------------------------------------------------------------===//
32
33
/// isInPrimaryFile - Return true if we're in the top-level file, not in a
34
/// \#include.  This looks through macro expansions and active _Pragma lexers.
35
144k
bool Preprocessor::isInPrimaryFile() const {
36
144k
  if (IsFileLexer())
37
144k
    return IncludeMacroStack.empty();
38
39
  // If there are any stacked lexers, we're in a #include.
40
1
  assert(IsFileLexer(IncludeMacroStack[0]) &&
41
1
         "Top level include stack isn't our primary lexer?");
42
0
  return std::none_of(
43
1
      IncludeMacroStack.begin() + 1, IncludeMacroStack.end(),
44
1
      [&](const IncludeStackInfo &ISI) -> bool 
{ return IsFileLexer(ISI); }0
);
45
144k
}
46
47
/// getCurrentLexer - Return the current file lexer being lexed from.  Note
48
/// that this ignores any potentially active macro expansions and _Pragma
49
/// expansions going on at the time.
50
1.72M
PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
51
1.72M
  if (IsFileLexer())
52
1.72M
    return CurPPLexer;
53
54
  // Look for a stacked lexer.
55
18
  
for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack))17
{
56
18
    if (IsFileLexer(ISI))
57
17
      return ISI.ThePPLexer;
58
18
  }
59
0
  return nullptr;
60
17
}
61
62
63
//===----------------------------------------------------------------------===//
64
// Methods for Entering and Callbacks for leaving various contexts
65
//===----------------------------------------------------------------------===//
66
67
/// EnterSourceFile - Add a source file to the top of the include stack and
68
/// start lexing tokens from it instead of the current buffer.
69
bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
70
819k
                                   SourceLocation Loc) {
71
819k
  assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
72
0
  ++NumEnteredSourceFiles;
73
74
819k
  if (MaxIncludeStackDepth < IncludeMacroStack.size())
75
25.3k
    MaxIncludeStackDepth = IncludeMacroStack.size();
76
77
  // Get the MemoryBuffer for this FID, if it fails, we fail.
78
819k
  llvm::Optional<llvm::MemoryBufferRef> InputFile =
79
819k
      getSourceManager().getBufferOrNone(FID, Loc);
80
819k
  if (!InputFile) {
81
2
    SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
82
2
    Diag(Loc, diag::err_pp_error_opening_file)
83
2
        << std::string(SourceMgr.getBufferName(FileStart)) << "";
84
2
    return true;
85
2
  }
86
87
819k
  if (isCodeCompletionEnabled() &&
88
819k
      
SourceMgr.getFileEntryForID(FID) == CodeCompletionFile2.54k
) {
89
1.25k
    CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
90
1.25k
    CodeCompletionLoc =
91
1.25k
        CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
92
1.25k
  }
93
94
819k
  EnterSourceFileWithLexer(new Lexer(FID, *InputFile, *this), CurDir);
95
819k
  return false;
96
819k
}
97
98
/// EnterSourceFileWithLexer - Add a source file to the top of the include stack
99
///  and start lexing tokens from it instead of the current buffer.
100
void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
101
1.42M
                                            const DirectoryLookup *CurDir) {
102
103
  // Add the current lexer to the include stack.
104
1.42M
  if (CurPPLexer || 
CurTokenLexer694k
)
105
1.32M
    PushIncludeMacroStack();
106
107
1.42M
  CurLexer.reset(TheLexer);
108
1.42M
  CurPPLexer = TheLexer;
109
1.42M
  CurDirLookup = CurDir;
110
1.42M
  CurLexerSubmodule = nullptr;
111
1.42M
  if (CurLexerKind != CLK_LexAfterModuleImport)
112
1.42M
    CurLexerKind = CLK_Lexer;
113
114
  // Notify the client, if desired, that we are in a new source file.
115
1.42M
  if (Callbacks && 
!CurLexer->Is_PragmaLexer1.41M
) {
116
815k
    SrcMgr::CharacteristicKind FileType =
117
815k
       SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
118
119
815k
    Callbacks->FileChanged(CurLexer->getFileLoc(),
120
815k
                           PPCallbacks::EnterFile, FileType);
121
815k
  }
122
1.42M
}
123
124
/// EnterMacro - Add a Macro to the top of the include stack and start lexing
125
/// tokens from it instead of the current buffer.
126
void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
127
56.3M
                              MacroInfo *Macro, MacroArgs *Args) {
128
56.3M
  std::unique_ptr<TokenLexer> TokLexer;
129
56.3M
  if (NumCachedTokenLexers == 0) {
130
55.4k
    TokLexer = std::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this);
131
56.3M
  } else {
132
56.3M
    TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
133
56.3M
    TokLexer->Init(Tok, ILEnd, Macro, Args);
134
56.3M
  }
135
136
56.3M
  PushIncludeMacroStack();
137
56.3M
  CurDirLookup = nullptr;
138
56.3M
  CurTokenLexer = std::move(TokLexer);
139
56.3M
  if (CurLexerKind != CLK_LexAfterModuleImport)
140
56.3M
    CurLexerKind = CLK_TokenLexer;
141
56.3M
}
142
143
/// EnterTokenStream - Add a "macro" context to the top of the include stack,
144
/// which will cause the lexer to start returning the specified tokens.
145
///
146
/// If DisableMacroExpansion is true, tokens lexed from the token stream will
147
/// not be subject to further macro expansion.  Otherwise, these tokens will
148
/// be re-macro-expanded when/if expansion is enabled.
149
///
150
/// If OwnsTokens is false, this method assumes that the specified stream of
151
/// tokens has a permanent owner somewhere, so they do not need to be copied.
152
/// If it is true, it assumes the array of tokens is allocated with new[] and
153
/// must be freed.
154
///
155
void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
156
                                    bool DisableMacroExpansion, bool OwnsTokens,
157
4.26M
                                    bool IsReinject) {
158
4.26M
  if (CurLexerKind == CLK_CachingLexer) {
159
3.44k
    if (CachedLexPos < CachedTokens.size()) {
160
3.05k
      assert(IsReinject && "new tokens in the middle of cached stream");
161
      // We're entering tokens into the middle of our cached token stream. We
162
      // can't represent that, so just insert the tokens into the buffer.
163
0
      CachedTokens.insert(CachedTokens.begin() + CachedLexPos,
164
3.05k
                          Toks, Toks + NumToks);
165
3.05k
      if (OwnsTokens)
166
0
        delete [] Toks;
167
3.05k
      return;
168
3.05k
    }
169
170
    // New tokens are at the end of the cached token sequnece; insert the
171
    // token stream underneath the caching lexer.
172
395
    ExitCachingLexMode();
173
395
    EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens,
174
395
                     IsReinject);
175
395
    EnterCachingLexMode();
176
395
    return;
177
3.44k
  }
178
179
  // Create a macro expander to expand from the specified token stream.
180
4.26M
  std::unique_ptr<TokenLexer> TokLexer;
181
4.26M
  if (NumCachedTokenLexers == 0) {
182
334k
    TokLexer = std::make_unique<TokenLexer>(
183
334k
        Toks, NumToks, DisableMacroExpansion, OwnsTokens, IsReinject, *this);
184
3.92M
  } else {
185
3.92M
    TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
186
3.92M
    TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens,
187
3.92M
                   IsReinject);
188
3.92M
  }
189
190
  // Save our current state.
191
4.26M
  PushIncludeMacroStack();
192
4.26M
  CurDirLookup = nullptr;
193
4.26M
  CurTokenLexer = std::move(TokLexer);
194
4.26M
  if (CurLexerKind != CLK_LexAfterModuleImport)
195
4.26M
    CurLexerKind = CLK_TokenLexer;
196
4.26M
}
197
198
/// Compute the relative path that names the given file relative to
199
/// the given directory.
200
static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
201
                                const FileEntry *File,
202
52
                                SmallString<128> &Result) {
203
52
  Result.clear();
204
205
52
  StringRef FilePath = File->getDir()->getName();
206
52
  StringRef Path = FilePath;
207
52
  while (!Path.empty()) {
208
52
    if (auto CurDir = FM.getDirectory(Path)) {
209
52
      if (*CurDir == Dir) {
210
52
        Result = FilePath.substr(Path.size());
211
52
        llvm::sys::path::append(Result,
212
52
                                llvm::sys::path::filename(File->getName()));
213
52
        return;
214
52
      }
215
52
    }
216
217
0
    Path = llvm::sys::path::parent_path(Path);
218
0
  }
219
220
0
  Result = File->getName();
221
0
}
222
223
59.9M
void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
224
59.9M
  if (CurTokenLexer) {
225
23.2M
    CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
226
23.2M
    return;
227
23.2M
  }
228
36.7M
  if (CurLexer) {
229
36.7M
    CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
230
36.7M
    return;
231
36.7M
  }
232
  // FIXME: Handle other kinds of lexers?  It generally shouldn't matter,
233
  // but it might if they're empty?
234
36.7M
}
235
236
/// Determine the location to use as the end of the buffer for a lexer.
237
///
238
/// If the file ends with a newline, form the EOF token on the newline itself,
239
/// rather than "on the line following it", which doesn't exist.  This makes
240
/// diagnostics relating to the end of file include the last file that the user
241
/// actually typed, which is goodness.
242
173k
const char *Preprocessor::getCurLexerEndPos() {
243
173k
  const char *EndPos = CurLexer->BufferEnd;
244
173k
  if (EndPos != CurLexer->BufferStart &&
245
173k
      
(171k
EndPos[-1] == '\n'171k
||
EndPos[-1] == '\r'25.3k
)) {
246
145k
    --EndPos;
247
248
    // Handle \n\r and \r\n:
249
145k
    if (EndPos != CurLexer->BufferStart &&
250
145k
        
(145k
EndPos[-1] == '\n'145k
||
EndPos[-1] == '\r'137k
) &&
251
145k
        
EndPos[-1] != EndPos[0]8.40k
)
252
59
      --EndPos;
253
145k
  }
254
255
173k
  return EndPos;
256
173k
}
257
258
static void collectAllSubModulesWithUmbrellaHeader(
259
23.1k
    const Module &Mod, SmallVectorImpl<const Module *> &SubMods) {
260
23.1k
  if (Mod.getUmbrellaHeader())
261
485
    SubMods.push_back(&Mod);
262
23.1k
  for (auto *M : Mod.submodules())
263
21.1k
    collectAllSubModulesWithUmbrellaHeader(*M, SubMods);
264
23.1k
}
265
266
485
void Preprocessor::diagnoseMissingHeaderInUmbrellaDir(const Module &Mod) {
267
485
  const Module::Header &UmbrellaHeader = Mod.getUmbrellaHeader();
268
485
  assert(UmbrellaHeader.Entry && "Module must use umbrella header");
269
0
  const FileID &File = SourceMgr.translateFile(UmbrellaHeader.Entry);
270
485
  SourceLocation ExpectedHeadersLoc = SourceMgr.getLocForEndOfFile(File);
271
485
  if (getDiagnostics().isIgnored(diag::warn_uncovered_module_header,
272
485
                                 ExpectedHeadersLoc))
273
244
    return;
274
275
241
  ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
276
241
  const DirectoryEntry *Dir = Mod.getUmbrellaDir().Entry;
277
241
  llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
278
241
  std::error_code EC;
279
241
  for (llvm::vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC),
280
241
       End;
281
953
       Entry != End && 
!EC712
;
Entry.increment(EC)712
) {
282
712
    using llvm::StringSwitch;
283
284
    // Check whether this entry has an extension typically associated with
285
    // headers.
286
712
    if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()))
287
712
             .Cases(".h", ".H", ".hh", ".hpp", true)
288
712
             .Default(false))
289
51
      continue;
290
291
661
    if (auto Header = getFileManager().getFile(Entry->path()))
292
661
      if (!getSourceManager().hasFileInfo(*Header)) {
293
133
        if (!ModMap.isHeaderInUnavailableModule(*Header)) {
294
          // Find the relative path that would access this header.
295
52
          SmallString<128> RelativePath;
296
52
          computeRelativePath(FileMgr, Dir, *Header, RelativePath);
297
52
          Diag(ExpectedHeadersLoc, diag::warn_uncovered_module_header)
298
52
              << Mod.getFullModuleName() << RelativePath;
299
52
        }
300
133
      }
301
661
  }
302
241
}
303
304
void Preprocessor::ResolvePragmaIncludeInstead(
305
1.42M
    const SourceLocation Location) const {
306
1.42M
  assert(Location.isValid());
307
1.42M
  if (CurLexer == nullptr)
308
0
    return;
309
310
1.42M
  if (SourceMgr.isInSystemHeader(Location))
311
1.19M
    return;
312
313
227k
  for (const auto &Include : CurLexer->getIncludeHistory()) {
314
27.5k
    StringRef Filename = Include.getKey();
315
27.5k
    const PreprocessorLexer::IncludeInfo &Info = Include.getValue();
316
27.5k
    ArrayRef<SmallString<32>> Aliases =
317
27.5k
        HeaderInfo.getFileInfo(Info.File).Aliases.getArrayRef();
318
319
27.5k
    if (Aliases.empty())
320
27.5k
      continue;
321
322
3
    switch (Aliases.size()) {
323
1
    case 1:
324
1
      Diag(Info.Location, diag::err_pragma_include_instead_system_reserved)
325
1
          << Filename << 0 << Aliases[0];
326
1
      continue;
327
1
    case 2:
328
1
      Diag(Info.Location, diag::err_pragma_include_instead_system_reserved)
329
1
          << Filename << 1 << Aliases[0] << Aliases[1];
330
1
      continue;
331
1
    default: {
332
1
      Diag(Info.Location, diag::err_pragma_include_instead_system_reserved)
333
1
          << Filename << 2 << ("{'" + llvm::join(Aliases, "', '") + "'}");
334
1
    }
335
3
    }
336
3
  }
337
227k
}
338
339
/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
340
/// the current file.  This either returns the EOF token or pops a level off
341
/// the include stack and keeps going.
342
bool Preprocessor::HandleEndOfFile(Token &Result, SourceLocation EndLoc,
343
59.1M
                                   bool isEndOfMacro) {
344
59.1M
  assert(!CurTokenLexer &&
345
59.1M
         "Ending a file when currently in a macro!");
346
347
  // If we have an unclosed module region from a pragma at the end of a
348
  // module, complain and close it now.
349
59.1M
  const bool LeavingSubmodule = CurLexer && 
CurLexerSubmodule1.42M
;
350
59.1M
  if ((LeavingSubmodule || 
IncludeMacroStack.empty()59.0M
) &&
351
59.1M
      
!BuildingSubmoduleStack.empty()173k
&&
352
59.1M
      
BuildingSubmoduleStack.back().IsPragma76.7k
) {
353
2
    Diag(BuildingSubmoduleStack.back().ImportLoc,
354
2
         diag::err_pp_module_begin_without_module_end);
355
2
    Module *M = LeaveSubmodule(/*ForPragma*/true);
356
357
2
    Result.startToken();
358
2
    const char *EndPos = getCurLexerEndPos();
359
2
    CurLexer->BufferPtr = EndPos;
360
2
    CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
361
2
    Result.setAnnotationEndLoc(Result.getLocation());
362
2
    Result.setAnnotationValue(M);
363
2
    return true;
364
2
  }
365
366
  // See if this file had a controlling macro.
367
59.1M
  if (CurPPLexer) {  // Not ending a macro, ignore it.
368
1.42M
    if (const IdentifierInfo *ControllingMacro =
369
1.42M
          CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
370
      // Okay, this has a controlling macro, remember in HeaderFileInfo.
371
385k
      if (const FileEntry *FE = CurPPLexer->getFileEntry()) {
372
385k
        HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
373
385k
        if (MacroInfo *MI =
374
385k
              getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro)))
375
384k
          MI->setUsedForHeaderGuard(true);
376
385k
        if (const IdentifierInfo *DefinedMacro =
377
385k
              CurPPLexer->MIOpt.GetDefinedMacro()) {
378
352k
          if (!isMacroDefined(ControllingMacro) &&
379
352k
              
DefinedMacro != ControllingMacro14
&&
380
352k
              
HeaderInfo.FirstTimeLexingFile(FE)14
) {
381
382
            // If the edit distance between the two macros is more than 50%,
383
            // DefinedMacro may not be header guard, or can be header guard of
384
            // another header file. Therefore, it maybe defining something
385
            // completely different. This can be observed in the wild when
386
            // handling feature macros or header guards in different files.
387
388
8
            const StringRef ControllingMacroName = ControllingMacro->getName();
389
8
            const StringRef DefinedMacroName = DefinedMacro->getName();
390
8
            const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
391
8
                                                  DefinedMacroName.size()) / 2;
392
8
            const unsigned ED = ControllingMacroName.edit_distance(
393
8
                DefinedMacroName, true, MaxHalfLength);
394
8
            if (ED <= MaxHalfLength) {
395
              // Emit a warning for a bad header guard.
396
6
              Diag(CurPPLexer->MIOpt.GetMacroLocation(),
397
6
                   diag::warn_header_guard)
398
6
                  << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
399
6
              Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
400
6
                   diag::note_header_guard)
401
6
                  << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
402
6
                  << ControllingMacro
403
6
                  << FixItHint::CreateReplacement(
404
6
                         CurPPLexer->MIOpt.GetDefinedLocation(),
405
6
                         ControllingMacro->getName());
406
6
            }
407
8
          }
408
352k
        }
409
385k
      }
410
385k
    }
411
1.42M
  }
412
413
59.1M
  if (EndLoc.isValid())
414
1.42M
    ResolvePragmaIncludeInstead(EndLoc);
415
416
  // Complain about reaching a true EOF within arc_cf_code_audited.
417
  // We don't want to complain about reaching the end of a macro
418
  // instantiation or a _Pragma.
419
59.1M
  if (PragmaARCCFCodeAuditedInfo.second.isValid() && 
!isEndOfMacro8.56M
&&
420
59.1M
      
!(2
CurLexer2
&&
CurLexer->Is_PragmaLexer2
)) {
421
2
    Diag(PragmaARCCFCodeAuditedInfo.second,
422
2
         diag::err_pp_eof_in_arc_cf_code_audited);
423
424
    // Recover by leaving immediately.
425
2
    PragmaARCCFCodeAuditedInfo = {nullptr, SourceLocation()};
426
2
  }
427
428
  // Complain about reaching a true EOF within assume_nonnull.
429
  // We don't want to complain about reaching the end of a macro
430
  // instantiation or a _Pragma.
431
59.1M
  if (PragmaAssumeNonNullLoc.isValid() &&
432
59.1M
      
!isEndOfMacro14.8M
&&
!(1
CurLexer1
&&
CurLexer->Is_PragmaLexer1
)) {
433
1
    Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
434
435
    // Recover by leaving immediately.
436
1
    PragmaAssumeNonNullLoc = SourceLocation();
437
1
  }
438
439
59.1M
  bool LeavingPCHThroughHeader = false;
440
441
  // If this is a #include'd file, pop it off the include stack and continue
442
  // lexing the #includer file.
443
59.1M
  if (!IncludeMacroStack.empty()) {
444
445
    // If we lexed the code-completion file, act as if we reached EOF.
446
59.0M
    if (isCodeCompletionEnabled() && 
CurPPLexer2.14k
&&
447
59.0M
        SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
448
1.29k
            CodeCompletionFileLoc) {
449
1
      assert(CurLexer && "Got EOF but no current lexer set!");
450
0
      Result.startToken();
451
1
      CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
452
1
      CurLexer.reset();
453
454
1
      CurPPLexer = nullptr;
455
1
      recomputeCurLexerKind();
456
1
      return true;
457
1
    }
458
459
59.0M
    if (!isEndOfMacro && 
CurPPLexer722k
&&
460
59.0M
        
(722k
SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()722k
||
461
         // Predefines file doesn't have a valid include location.
462
722k
         
(96.7k
PredefinesFileID.isValid()96.7k
&&
463
722k
          
CurPPLexer->getFileID() == PredefinesFileID96.7k
))) {
464
      // Notify SourceManager to record the number of FileIDs that were created
465
      // during lexing of the #include'd file.
466
722k
      unsigned NumFIDs =
467
722k
          SourceMgr.local_sloc_entry_size() -
468
722k
          CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
469
722k
      SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
470
722k
    }
471
472
59.0M
    bool ExitedFromPredefinesFile = false;
473
59.0M
    FileID ExitedFID;
474
59.0M
    if (!isEndOfMacro && 
CurPPLexer722k
) {
475
722k
      ExitedFID = CurPPLexer->getFileID();
476
477
722k
      assert(PredefinesFileID.isValid() &&
478
722k
             "HandleEndOfFile is called before PredefinesFileId is set");
479
0
      ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);
480
722k
    }
481
482
59.0M
    if (LeavingSubmodule) {
483
      // We're done with this submodule.
484
76.7k
      Module *M = LeaveSubmodule(/*ForPragma*/false);
485
486
      // Notify the parser that we've left the module.
487
76.7k
      const char *EndPos = getCurLexerEndPos();
488
76.7k
      Result.startToken();
489
76.7k
      CurLexer->BufferPtr = EndPos;
490
76.7k
      CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
491
76.7k
      Result.setAnnotationEndLoc(Result.getLocation());
492
76.7k
      Result.setAnnotationValue(M);
493
76.7k
    }
494
495
59.0M
    bool FoundPCHThroughHeader = false;
496
59.0M
    if (CurPPLexer && 
creatingPCHWithThroughHeader()1.32M
&&
497
59.0M
        isPCHThroughHeader(
498
23
            SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
499
12
      FoundPCHThroughHeader = true;
500
501
    // We're done with the #included file.
502
59.0M
    RemoveTopOfLexerStack();
503
504
    // Propagate info about start-of-line/leading white-space/etc.
505
59.0M
    PropagateLineStartLeadingSpaceInfo(Result);
506
507
    // Notify the client, if desired, that we are in a new source file.
508
59.0M
    if (Callbacks && 
!isEndOfMacro59.0M
&&
CurPPLexer720k
) {
509
720k
      SrcMgr::CharacteristicKind FileType =
510
720k
        SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
511
720k
      Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
512
720k
                             PPCallbacks::ExitFile, FileType, ExitedFID);
513
720k
    }
514
515
    // Restore conditional stack from the preamble right after exiting from the
516
    // predefines file.
517
59.0M
    if (ExitedFromPredefinesFile)
518
96.7k
      replayPreambleConditionalStack();
519
520
59.0M
    if (!isEndOfMacro && 
CurPPLexer722k
&&
FoundPCHThroughHeader722k
&&
521
59.0M
        
(12
isInPrimaryFile()12
||
522
12
         
CurPPLexer->getFileID() == getPredefinesFileID()7
)) {
523
      // Leaving the through header. Continue directly to end of main file
524
      // processing.
525
12
      LeavingPCHThroughHeader = true;
526
59.0M
    } else {
527
      // Client should lex another token unless we generated an EOM.
528
59.0M
      return LeavingSubmodule;
529
59.0M
    }
530
59.0M
  }
531
532
  // If this is the end of the main file, form an EOF token.
533
97.0k
  assert(CurLexer && "Got EOF but no current lexer set!");
534
0
  const char *EndPos = getCurLexerEndPos();
535
97.0k
  Result.startToken();
536
97.0k
  CurLexer->BufferPtr = EndPos;
537
97.0k
  CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
538
539
97.0k
  if (isCodeCompletionEnabled()) {
540
    // Inserting the code-completion point increases the source buffer by 1,
541
    // but the main FileID was created before inserting the point.
542
    // Compensate by reducing the EOF location by 1, otherwise the location
543
    // will point to the next FileID.
544
    // FIXME: This is hacky, the code-completion point should probably be
545
    // inserted before the main FileID is created.
546
111
    if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
547
111
      Result.setLocation(Result.getLocation().getLocWithOffset(-1));
548
111
  }
549
550
97.0k
  if (creatingPCHWithThroughHeader() && 
!LeavingPCHThroughHeader13
) {
551
    // Reached the end of the compilation without finding the through header.
552
1
    Diag(CurLexer->getFileLoc(), diag::err_pp_through_header_not_seen)
553
1
        << PPOpts->PCHThroughHeader << 0;
554
1
  }
555
556
97.0k
  if (!isIncrementalProcessingEnabled())
557
    // We're done with lexing.
558
94.1k
    CurLexer.reset();
559
560
97.0k
  if (!isIncrementalProcessingEnabled())
561
94.1k
    CurPPLexer = nullptr;
562
563
97.0k
  if (TUKind == TU_Complete) {
564
    // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
565
    // collected all macro locations that we need to warn because they are not
566
    // used.
567
91.5k
    for (WarnUnusedMacroLocsTy::iterator
568
91.5k
           I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
569
91.5k
           I!=E; 
++I8
)
570
8
      Diag(*I, diag::pp_macro_not_used);
571
91.5k
  }
572
573
  // If we are building a module that has an umbrella header, make sure that
574
  // each of the headers within the directory, including all submodules, is
575
  // covered by the umbrella header was actually included by the umbrella
576
  // header.
577
97.0k
  if (Module *Mod = getCurrentModule()) {
578
1.95k
    llvm::SmallVector<const Module *, 4> AllMods;
579
1.95k
    collectAllSubModulesWithUmbrellaHeader(*Mod, AllMods);
580
1.95k
    for (auto *M : AllMods)
581
485
      diagnoseMissingHeaderInUmbrellaDir(*M);
582
1.95k
  }
583
584
97.0k
  return true;
585
59.1M
}
586
587
/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
588
/// hits the end of its token stream.
589
57.7M
bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
590
57.7M
  assert(CurTokenLexer && !CurPPLexer &&
591
57.7M
         "Ending a macro when currently in a #include file!");
592
593
57.7M
  if (!MacroExpandingLexersStack.empty() &&
594
57.7M
      
MacroExpandingLexersStack.back().first == CurTokenLexer.get()21.5M
)
595
19.2M
    removeCachedMacroExpandedTokensOfLastLexer();
596
597
  // Delete or cache the now-dead macro expander.
598
57.7M
  if (NumCachedTokenLexers == TokenLexerCacheSize)
599
289k
    CurTokenLexer.reset();
600
57.4M
  else
601
57.4M
    TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
602
603
  // Handle this like a #include file being popped off the stack.
604
57.7M
  return HandleEndOfFile(Result, {}, true);
605
57.7M
}
606
607
/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
608
/// lexer stack.  This should only be used in situations where the current
609
/// state of the top-of-stack lexer is unknown.
610
192M
void Preprocessor::RemoveTopOfLexerStack() {
611
192M
  assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
612
613
192M
  if (CurTokenLexer) {
614
    // Delete or cache the now-dead macro expander.
615
2.90M
    if (NumCachedTokenLexers == TokenLexerCacheSize)
616
2.69k
      CurTokenLexer.reset();
617
2.89M
    else
618
2.89M
      TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
619
2.90M
  }
620
621
192M
  PopIncludeMacroStack();
622
192M
}
623
624
/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
625
/// comment (/##/) in microsoft mode, this method handles updating the current
626
/// state, returning the token on the next source line.
627
4
void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
628
4
  assert(CurTokenLexer && !CurPPLexer &&
629
4
         "Pasted comment can only be formed from macro");
630
  // We handle this by scanning for the closest real lexer, switching it to
631
  // raw mode and preprocessor mode.  This will cause it to return \n as an
632
  // explicit EOD token.
633
0
  PreprocessorLexer *FoundLexer = nullptr;
634
4
  bool LexerWasInPPMode = false;
635
6
  for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
636
6
    if (ISI.ThePPLexer == nullptr) 
continue2
; // Scan for a real lexer.
637
638
    // Once we find a real lexer, mark it as raw mode (disabling macro
639
    // expansions) and preprocessor mode (return EOD).  We know that the lexer
640
    // was *not* in raw mode before, because the macro that the comment came
641
    // from was expanded.  However, it could have already been in preprocessor
642
    // mode (#if COMMENT) in which case we have to return it to that mode and
643
    // return EOD.
644
4
    FoundLexer = ISI.ThePPLexer;
645
4
    FoundLexer->LexingRawMode = true;
646
4
    LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
647
4
    FoundLexer->ParsingPreprocessorDirective = true;
648
4
    break;
649
6
  }
650
651
  // Okay, we either found and switched over the lexer, or we didn't find a
652
  // lexer.  In either case, finish off the macro the comment came from, getting
653
  // the next token.
654
4
  if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
655
656
  // Discarding comments as long as we don't have EOF or EOD.  This 'comments
657
  // out' the rest of the line, including any tokens that came from other macros
658
  // that were active, as in:
659
  //  #define submacro a COMMENT b
660
  //    submacro c
661
  // which should lex to 'a' only: 'b' and 'c' should be removed.
662
30
  while (Tok.isNot(tok::eod) && 
Tok.isNot(tok::eof)26
)
663
26
    Lex(Tok);
664
665
  // If we got an eod token, then we successfully found the end of the line.
666
4
  if (Tok.is(tok::eod)) {
667
4
    assert(FoundLexer && "Can't get end of line without an active lexer");
668
    // Restore the lexer back to normal mode instead of raw mode.
669
0
    FoundLexer->LexingRawMode = false;
670
671
    // If the lexer was already in preprocessor mode, just return the EOD token
672
    // to finish the preprocessor line.
673
4
    if (LexerWasInPPMode) 
return0
;
674
675
    // Otherwise, switch out of PP mode and return the next lexed token.
676
4
    FoundLexer->ParsingPreprocessorDirective = false;
677
4
    return Lex(Tok);
678
4
  }
679
680
  // If we got an EOF token, then we reached the end of the token stream but
681
  // didn't find an explicit \n.  This can only happen if there was no lexer
682
  // active (an active lexer would return EOD at EOF if there was no \n in
683
  // preprocessor directive mode), so just return EOF as our token.
684
0
  assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
685
0
}
686
687
void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc,
688
76.9k
                                  bool ForPragma) {
689
76.9k
  if (!getLangOpts().ModulesLocalVisibility) {
690
    // Just track that we entered this submodule.
691
76.5k
    BuildingSubmoduleStack.push_back(
692
76.5k
        BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
693
76.5k
                              PendingModuleMacroNames.size()));
694
76.5k
    if (Callbacks)
695
76.5k
      Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
696
76.5k
    return;
697
76.5k
  }
698
699
  // Resolve as much of the module definition as we can now, before we enter
700
  // one of its headers.
701
  // FIXME: Can we enable Complain here?
702
  // FIXME: Can we do this when local visibility is disabled?
703
306
  ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
704
306
  ModMap.resolveExports(M, /*Complain=*/false);
705
306
  ModMap.resolveUses(M, /*Complain=*/false);
706
306
  ModMap.resolveConflicts(M, /*Complain=*/false);
707
708
  // If this is the first time we've entered this module, set up its state.
709
306
  auto R = Submodules.insert(std::make_pair(M, SubmoduleState()));
710
306
  auto &State = R.first->second;
711
306
  bool FirstTime = R.second;
712
306
  if (FirstTime) {
713
    // Determine the set of starting macros for this submodule; take these
714
    // from the "null" module (the predefines buffer).
715
    //
716
    // FIXME: If we have local visibility but not modules enabled, the
717
    // NullSubmoduleState is polluted by #defines in the top-level source
718
    // file.
719
272
    auto &StartingMacros = NullSubmoduleState.Macros;
720
721
    // Restore to the starting state.
722
    // FIXME: Do this lazily, when each macro name is first referenced.
723
104k
    for (auto &Macro : StartingMacros) {
724
      // Skip uninteresting macros.
725
104k
      if (!Macro.second.getLatest() &&
726
104k
          
Macro.second.getOverriddenMacros().empty()4
)
727
4
        continue;
728
729
104k
      MacroState MS(Macro.second.getLatest());
730
104k
      MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros());
731
104k
      State.Macros.insert(std::make_pair(Macro.first, std::move(MS)));
732
104k
    }
733
272
  }
734
735
  // Track that we entered this module.
736
306
  BuildingSubmoduleStack.push_back(
737
306
      BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
738
306
                            PendingModuleMacroNames.size()));
739
740
306
  if (Callbacks)
741
306
    Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
742
743
  // Switch to this submodule as the current submodule.
744
306
  CurSubmoduleState = &State;
745
746
  // This module is visible to itself.
747
306
  if (FirstTime)
748
272
    makeModuleVisible(M, ImportLoc);
749
306
}
750
751
51.2M
bool Preprocessor::needModuleMacros() const {
752
  // If we're not within a submodule, we never need to create ModuleMacros.
753
51.2M
  if (BuildingSubmoduleStack.empty())
754
50.8M
    return false;
755
  // If we are tracking module macro visibility even for textually-included
756
  // headers, we need ModuleMacros.
757
401k
  if (getLangOpts().ModulesLocalVisibility)
758
713
    return true;
759
  // Otherwise, we only need module macros if we're actually compiling a module
760
  // interface.
761
400k
  return getLangOpts().isCompilingModule();
762
401k
}
763
764
76.9k
Module *Preprocessor::LeaveSubmodule(bool ForPragma) {
765
76.9k
  if (BuildingSubmoduleStack.empty() ||
766
76.9k
      
BuildingSubmoduleStack.back().IsPragma != ForPragma76.8k
) {
767
3
    assert(ForPragma && "non-pragma module enter/leave mismatch");
768
0
    return nullptr;
769
3
  }
770
771
76.8k
  auto &Info = BuildingSubmoduleStack.back();
772
773
76.8k
  Module *LeavingMod = Info.M;
774
76.8k
  SourceLocation ImportLoc = Info.ImportLoc;
775
776
76.8k
  if (!needModuleMacros() ||
777
76.8k
      
(76.8k
!getLangOpts().ModulesLocalVisibility76.8k
&&
778
76.8k
       
LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule76.5k
)) {
779
    // If we don't need module macros, or this is not a module for which we
780
    // are tracking macro visibility, don't build any, and preserve the list
781
    // of pending names for the surrounding submodule.
782
91
    BuildingSubmoduleStack.pop_back();
783
784
91
    if (Callbacks)
785
89
      Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
786
787
91
    makeModuleVisible(LeavingMod, ImportLoc);
788
91
    return LeavingMod;
789
91
  }
790
791
  // Create ModuleMacros for any macros defined in this submodule.
792
76.8k
  llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros;
793
76.8k
  for (unsigned I = Info.OuterPendingModuleMacroNames;
794
401k
       I != PendingModuleMacroNames.size(); 
++I324k
) {
795
324k
    auto *II = const_cast<IdentifierInfo*>(PendingModuleMacroNames[I]);
796
324k
    if (!VisitedMacros.insert(II).second)
797
6.91k
      continue;
798
799
317k
    auto MacroIt = CurSubmoduleState->Macros.find(II);
800
317k
    if (MacroIt == CurSubmoduleState->Macros.end())
801
0
      continue;
802
317k
    auto &Macro = MacroIt->second;
803
804
    // Find the starting point for the MacroDirective chain in this submodule.
805
317k
    MacroDirective *OldMD = nullptr;
806
317k
    auto *OldState = Info.OuterSubmoduleState;
807
317k
    if (getLangOpts().ModulesLocalVisibility)
808
334
      OldState = &NullSubmoduleState;
809
317k
    if (OldState && OldState != CurSubmoduleState) {
810
      // FIXME: It'd be better to start at the state from when we most recently
811
      // entered this submodule, but it doesn't really matter.
812
334
      auto &OldMacros = OldState->Macros;
813
334
      auto OldMacroIt = OldMacros.find(II);
814
334
      if (OldMacroIt == OldMacros.end())
815
334
        OldMD = nullptr;
816
0
      else
817
0
        OldMD = OldMacroIt->second.getLatest();
818
334
    }
819
820
    // This module may have exported a new macro. If so, create a ModuleMacro
821
    // representing that fact.
822
317k
    bool ExplicitlyPublic = false;
823
317k
    for (auto *MD = Macro.getLatest(); MD != OldMD; 
MD = MD->getPrevious()12
) {
824
317k
      assert(MD && "broken macro directive chain");
825
826
317k
      if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
827
        // The latest visibility directive for a name in a submodule affects
828
        // all the directives that come before it.
829
182
        if (VisMD->isPublic())
830
12
          ExplicitlyPublic = true;
831
170
        else if (!ExplicitlyPublic)
832
          // Private with no following public directive: not exported.
833
170
          break;
834
317k
      } else {
835
317k
        MacroInfo *Def = nullptr;
836
317k
        if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
837
315k
          Def = DefMD->getInfo();
838
839
        // FIXME: Issue a warning if multiple headers for the same submodule
840
        // define a macro, rather than silently ignoring all but the first.
841
317k
        bool IsNew;
842
        // Don't bother creating a module macro if it would represent a #undef
843
        // that doesn't override anything.
844
317k
        if (Def || 
!Macro.getOverriddenMacros().empty()1.95k
)
845
315k
          addModuleMacro(LeavingMod, II, Def,
846
315k
                         Macro.getOverriddenMacros(), IsNew);
847
848
317k
        if (!getLangOpts().ModulesLocalVisibility) {
849
          // This macro is exposed to the rest of this compilation as a
850
          // ModuleMacro; we don't need to track its MacroDirective any more.
851
316k
          Macro.setLatest(nullptr);
852
316k
          Macro.setOverriddenMacros(*this, {});
853
316k
        }
854
317k
        break;
855
317k
      }
856
317k
    }
857
317k
  }
858
76.8k
  PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);
859
860
  // FIXME: Before we leave this submodule, we should parse all the other
861
  // headers within it. Otherwise, we're left with an inconsistent state
862
  // where we've made the module visible but don't yet have its complete
863
  // contents.
864
865
  // Put back the outer module's state, if we're tracking it.
866
76.8k
  if (getLangOpts().ModulesLocalVisibility)
867
306
    CurSubmoduleState = Info.OuterSubmoduleState;
868
869
76.8k
  BuildingSubmoduleStack.pop_back();
870
871
76.8k
  if (Callbacks)
872
76.8k
    Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
873
874
  // A nested #include makes the included submodule visible.
875
76.8k
  makeModuleVisible(LeavingMod, ImportLoc);
876
76.8k
  return LeavingMod;
877
76.8k
}