Coverage Report

Created: 2020-02-25 14:32

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