Coverage Report

Created: 2022-01-22 13:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/include/clang/Lex/Preprocessor.h
Line
Count
Source (jump to first uncovered line)
1
//===- Preprocessor.h - C Language Family Preprocessor ----------*- C++ -*-===//
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
/// \file
10
/// Defines the clang::Preprocessor interface.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#ifndef LLVM_CLANG_LEX_PREPROCESSOR_H
15
#define LLVM_CLANG_LEX_PREPROCESSOR_H
16
17
#include "clang/Basic/Diagnostic.h"
18
#include "clang/Basic/DiagnosticIDs.h"
19
#include "clang/Basic/IdentifierTable.h"
20
#include "clang/Basic/LLVM.h"
21
#include "clang/Basic/LangOptions.h"
22
#include "clang/Basic/Module.h"
23
#include "clang/Basic/SourceLocation.h"
24
#include "clang/Basic/SourceManager.h"
25
#include "clang/Basic/TokenKinds.h"
26
#include "clang/Lex/Lexer.h"
27
#include "clang/Lex/MacroInfo.h"
28
#include "clang/Lex/ModuleLoader.h"
29
#include "clang/Lex/ModuleMap.h"
30
#include "clang/Lex/PPCallbacks.h"
31
#include "clang/Lex/PreprocessorExcludedConditionalDirectiveSkipMapping.h"
32
#include "clang/Lex/Token.h"
33
#include "clang/Lex/TokenLexer.h"
34
#include "llvm/ADT/ArrayRef.h"
35
#include "llvm/ADT/DenseMap.h"
36
#include "llvm/ADT/FoldingSet.h"
37
#include "llvm/ADT/FunctionExtras.h"
38
#include "llvm/ADT/None.h"
39
#include "llvm/ADT/Optional.h"
40
#include "llvm/ADT/PointerUnion.h"
41
#include "llvm/ADT/STLExtras.h"
42
#include "llvm/ADT/SmallPtrSet.h"
43
#include "llvm/ADT/SmallVector.h"
44
#include "llvm/ADT/StringRef.h"
45
#include "llvm/ADT/TinyPtrVector.h"
46
#include "llvm/ADT/iterator_range.h"
47
#include "llvm/Support/Allocator.h"
48
#include "llvm/Support/Casting.h"
49
#include "llvm/Support/Registry.h"
50
#include <cassert>
51
#include <cstddef>
52
#include <cstdint>
53
#include <map>
54
#include <memory>
55
#include <string>
56
#include <utility>
57
#include <vector>
58
59
namespace llvm {
60
61
template<unsigned InternalLen> class SmallString;
62
63
} // namespace llvm
64
65
namespace clang {
66
67
class CodeCompletionHandler;
68
class CommentHandler;
69
class DirectoryEntry;
70
class DirectoryLookup;
71
class EmptylineHandler;
72
class ExternalPreprocessorSource;
73
class FileEntry;
74
class FileManager;
75
class HeaderSearch;
76
class MacroArgs;
77
class PragmaHandler;
78
class PragmaNamespace;
79
class PreprocessingRecord;
80
class PreprocessorLexer;
81
class PreprocessorOptions;
82
class ScratchBuffer;
83
class TargetInfo;
84
85
namespace Builtin {
86
class Context;
87
}
88
89
/// Stores token information for comparing actual tokens with
90
/// predefined values.  Only handles simple tokens and identifiers.
91
class TokenValue {
92
  tok::TokenKind Kind;
93
  IdentifierInfo *II;
94
95
public:
96
1.33k
  TokenValue(tok::TokenKind Kind) : Kind(Kind), II(nullptr) {
97
1.33k
    assert(Kind != tok::raw_identifier && "Raw identifiers are not supported.");
98
0
    assert(Kind != tok::identifier &&
99
1.33k
           "Identifiers should be created by TokenValue(IdentifierInfo *)");
100
0
    assert(!tok::isLiteral(Kind) && "Literals are not supported.");
101
0
    assert(!tok::isAnnotation(Kind) && "Annotations are not supported.");
102
1.33k
  }
103
104
373
  TokenValue(IdentifierInfo *II) : Kind(tok::identifier), II(II) {}
105
106
13.5k
  bool operator==(const Token &Tok) const {
107
13.5k
    return Tok.getKind() == Kind &&
108
13.5k
        
(924
!II924
||
II == Tok.getIdentifierInfo()221
);
109
13.5k
  }
110
};
111
112
/// Context in which macro name is used.
113
enum MacroUse {
114
  // other than #define or #undef
115
  MU_Other  = 0,
116
117
  // macro name specified in #define
118
  MU_Define = 1,
119
120
  // macro name specified in #undef
121
  MU_Undef  = 2
122
};
123
124
/// Engages in a tight little dance with the lexer to efficiently
125
/// preprocess tokens.
126
///
127
/// Lexers know only about tokens within a single source file, and don't
128
/// know anything about preprocessor-level issues like the \#include stack,
129
/// token expansion, etc.
130
class Preprocessor {
131
  friend class VAOptDefinitionContext;
132
  friend class VariadicMacroScopeGuard;
133
134
  llvm::unique_function<void(const clang::Token &)> OnToken;
135
  std::shared_ptr<PreprocessorOptions> PPOpts;
136
  DiagnosticsEngine        *Diags;
137
  LangOptions       &LangOpts;
138
  const TargetInfo *Target = nullptr;
139
  const TargetInfo *AuxTarget = nullptr;
140
  FileManager       &FileMgr;
141
  SourceManager     &SourceMgr;
142
  std::unique_ptr<ScratchBuffer> ScratchBuf;
143
  HeaderSearch      &HeaderInfo;
144
  ModuleLoader      &TheModuleLoader;
145
146
  /// External source of macros.
147
  ExternalPreprocessorSource *ExternalSource;
148
149
  /// A BumpPtrAllocator object used to quickly allocate and release
150
  /// objects internal to the Preprocessor.
151
  llvm::BumpPtrAllocator BP;
152
153
  /// Identifiers for builtin macros and other builtins.
154
  IdentifierInfo *Ident__LINE__, *Ident__FILE__;   // __LINE__, __FILE__
155
  IdentifierInfo *Ident__DATE__, *Ident__TIME__;   // __DATE__, __TIME__
156
  IdentifierInfo *Ident__INCLUDE_LEVEL__;          // __INCLUDE_LEVEL__
157
  IdentifierInfo *Ident__BASE_FILE__;              // __BASE_FILE__
158
  IdentifierInfo *Ident__FILE_NAME__;              // __FILE_NAME__
159
  IdentifierInfo *Ident__TIMESTAMP__;              // __TIMESTAMP__
160
  IdentifierInfo *Ident__COUNTER__;                // __COUNTER__
161
  IdentifierInfo *Ident_Pragma, *Ident__pragma;    // _Pragma, __pragma
162
  IdentifierInfo *Ident__identifier;               // __identifier
163
  IdentifierInfo *Ident__VA_ARGS__;                // __VA_ARGS__
164
  IdentifierInfo *Ident__VA_OPT__;                 // __VA_OPT__
165
  IdentifierInfo *Ident__has_feature;              // __has_feature
166
  IdentifierInfo *Ident__has_extension;            // __has_extension
167
  IdentifierInfo *Ident__has_builtin;              // __has_builtin
168
  IdentifierInfo *Ident__has_attribute;            // __has_attribute
169
  IdentifierInfo *Ident__has_include;              // __has_include
170
  IdentifierInfo *Ident__has_include_next;         // __has_include_next
171
  IdentifierInfo *Ident__has_warning;              // __has_warning
172
  IdentifierInfo *Ident__is_identifier;            // __is_identifier
173
  IdentifierInfo *Ident__building_module;          // __building_module
174
  IdentifierInfo *Ident__MODULE__;                 // __MODULE__
175
  IdentifierInfo *Ident__has_cpp_attribute;        // __has_cpp_attribute
176
  IdentifierInfo *Ident__has_c_attribute;          // __has_c_attribute
177
  IdentifierInfo *Ident__has_declspec;             // __has_declspec_attribute
178
  IdentifierInfo *Ident__is_target_arch;           // __is_target_arch
179
  IdentifierInfo *Ident__is_target_vendor;         // __is_target_vendor
180
  IdentifierInfo *Ident__is_target_os;             // __is_target_os
181
  IdentifierInfo *Ident__is_target_environment;    // __is_target_environment
182
183
  // Weak, only valid (and set) while InMacroArgs is true.
184
  Token* ArgMacro;
185
186
  SourceLocation DATELoc, TIMELoc;
187
188
  // Next __COUNTER__ value, starts at 0.
189
  unsigned CounterValue = 0;
190
191
  enum {
192
    /// Maximum depth of \#includes.
193
    MaxAllowedIncludeStackDepth = 200
194
  };
195
196
  // State that is set before the preprocessor begins.
197
  bool KeepComments : 1;
198
  bool KeepMacroComments : 1;
199
  bool SuppressIncludeNotFoundError : 1;
200
201
  // State that changes while the preprocessor runs:
202
  bool InMacroArgs : 1;            // True if parsing fn macro invocation args.
203
204
  /// Whether the preprocessor owns the header search object.
205
  bool OwnsHeaderSearch : 1;
206
207
  /// True if macro expansion is disabled.
208
  bool DisableMacroExpansion : 1;
209
210
  /// Temporarily disables DisableMacroExpansion (i.e. enables expansion)
211
  /// when parsing preprocessor directives.
212
  bool MacroExpansionInDirectivesOverride : 1;
213
214
  class ResetMacroExpansionHelper;
215
216
  /// Whether we have already loaded macros from the external source.
217
  mutable bool ReadMacrosFromExternalSource : 1;
218
219
  /// True if pragmas are enabled.
220
  bool PragmasEnabled : 1;
221
222
  /// True if the current build action is a preprocessing action.
223
  bool PreprocessedOutput : 1;
224
225
  /// True if we are currently preprocessing a #if or #elif directive
226
  bool ParsingIfOrElifDirective;
227
228
  /// True if we are pre-expanding macro arguments.
229
  bool InMacroArgPreExpansion;
230
231
  /// Mapping/lookup information for all identifiers in
232
  /// the program, including program keywords.
233
  mutable IdentifierTable Identifiers;
234
235
  /// This table contains all the selectors in the program.
236
  ///
237
  /// Unlike IdentifierTable above, this table *isn't* populated by the
238
  /// preprocessor. It is declared/expanded here because its role/lifetime is
239
  /// conceptually similar to the IdentifierTable. In addition, the current
240
  /// control flow (in clang::ParseAST()), make it convenient to put here.
241
  ///
242
  /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to
243
  /// the lifetime of the preprocessor.
244
  SelectorTable Selectors;
245
246
  /// Information about builtins.
247
  std::unique_ptr<Builtin::Context> BuiltinInfo;
248
249
  /// Tracks all of the pragmas that the client registered
250
  /// with this preprocessor.
251
  std::unique_ptr<PragmaNamespace> PragmaHandlers;
252
253
  /// Pragma handlers of the original source is stored here during the
254
  /// parsing of a model file.
255
  std::unique_ptr<PragmaNamespace> PragmaHandlersBackup;
256
257
  /// Tracks all of the comment handlers that the client registered
258
  /// with this preprocessor.
259
  std::vector<CommentHandler *> CommentHandlers;
260
261
  /// Empty line handler.
262
  EmptylineHandler *Emptyline = nullptr;
263
264
  /// True if we want to ignore EOF token and continue later on (thus
265
  /// avoid tearing the Lexer and etc. down).
266
  bool IncrementalProcessing = false;
267
268
public:
269
  /// The kind of translation unit we are processing.
270
  const TranslationUnitKind TUKind;
271
272
private:
273
  /// The code-completion handler.
274
  CodeCompletionHandler *CodeComplete = nullptr;
275
276
  /// The file that we're performing code-completion for, if any.
277
  const FileEntry *CodeCompletionFile = nullptr;
278
279
  /// The offset in file for the code-completion point.
280
  unsigned CodeCompletionOffset = 0;
281
282
  /// The location for the code-completion point. This gets instantiated
283
  /// when the CodeCompletionFile gets \#include'ed for preprocessing.
284
  SourceLocation CodeCompletionLoc;
285
286
  /// The start location for the file of the code-completion point.
287
  ///
288
  /// This gets instantiated when the CodeCompletionFile gets \#include'ed
289
  /// for preprocessing.
290
  SourceLocation CodeCompletionFileLoc;
291
292
  /// The source location of the \c import contextual keyword we just
293
  /// lexed, if any.
294
  SourceLocation ModuleImportLoc;
295
296
  /// The module import path that we're currently processing.
297
  SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> ModuleImportPath;
298
299
  /// Whether the last token we lexed was an '@'.
300
  bool LastTokenWasAt = false;
301
302
  /// A position within a C++20 import-seq.
303
  class ImportSeq {
304
  public:
305
    enum State : int {
306
      // Positive values represent a number of unclosed brackets.
307
      AtTopLevel = 0,
308
      AfterTopLevelTokenSeq = -1,
309
      AfterExport = -2,
310
      AfterImportSeq = -3,
311
    };
312
313
87.9k
    ImportSeq(State S) : S(S) {}
314
315
    /// Saw any kind of open bracket.
316
115k
    void handleOpenBracket() {
317
115k
      S = static_cast<State>(std::max<int>(S, 0) + 1);
318
115k
    }
319
    /// Saw any kind of close bracket other than '}'.
320
115k
    void handleCloseBracket() {
321
115k
      S = static_cast<State>(std::max<int>(S, 1) - 1);
322
115k
    }
323
    /// Saw a close brace.
324
26.5k
    void handleCloseBrace() {
325
26.5k
      handleCloseBracket();
326
26.5k
      if (S == AtTopLevel && 
!AfterHeaderName9.99k
)
327
9.99k
        S = AfterTopLevelTokenSeq;
328
26.5k
    }
329
    /// Saw a semicolon.
330
60.8k
    void handleSemi() {
331
60.8k
      if (atTopLevel()) {
332
8.62k
        S = AfterTopLevelTokenSeq;
333
8.62k
        AfterHeaderName = false;
334
8.62k
      }
335
60.8k
    }
336
337
    /// Saw an 'export' identifier.
338
118
    void handleExport() {
339
118
      if (S == AfterTopLevelTokenSeq)
340
107
        S = AfterExport;
341
11
      else if (S <= 0)
342
2
        S = AtTopLevel;
343
118
    }
344
    /// Saw an 'import' identifier.
345
59
    void handleImport() {
346
59
      if (S == AfterTopLevelTokenSeq || 
S == AfterExport20
)
347
41
        S = AfterImportSeq;
348
18
      else if (S <= 0)
349
13
        S = AtTopLevel;
350
59
    }
351
352
    /// Saw a 'header-name' token; do not recognize any more 'import' tokens
353
    /// until we reach a top-level semicolon.
354
24
    void handleHeaderName() {
355
24
      if (S == AfterImportSeq)
356
24
        AfterHeaderName = true;
357
24
      handleMisc();
358
24
    }
359
360
    /// Saw any other token.
361
473k
    void handleMisc() {
362
473k
      if (S <= 0)
363
57.0k
        S = AtTopLevel;
364
473k
    }
365
366
60.8k
    bool atTopLevel() { return S <= 0; }
367
59
    bool afterImportSeq() { return S == AfterImportSeq; }
368
369
  private:
370
    State S;
371
    /// Whether we're in the pp-import-suffix following the header-name in a
372
    /// pp-import. If so, a close-brace is not sufficient to end the
373
    /// top-level-token-seq of an import-seq.
374
    bool AfterHeaderName = false;
375
  };
376
377
  /// Our current position within a C++20 import-seq.
378
  ImportSeq ImportSeqState = ImportSeq::AfterTopLevelTokenSeq;
379
380
  /// Whether the module import expects an identifier next. Otherwise,
381
  /// it expects a '.' or ';'.
382
  bool ModuleImportExpectsIdentifier = false;
383
384
  /// The identifier and source location of the currently-active
385
  /// \#pragma clang arc_cf_code_audited begin.
386
  std::pair<IdentifierInfo *, SourceLocation> PragmaARCCFCodeAuditedInfo;
387
388
  /// The source location of the currently-active
389
  /// \#pragma clang assume_nonnull begin.
390
  SourceLocation PragmaAssumeNonNullLoc;
391
392
  /// True if we hit the code-completion point.
393
  bool CodeCompletionReached = false;
394
395
  /// The code completion token containing the information
396
  /// on the stem that is to be code completed.
397
  IdentifierInfo *CodeCompletionII = nullptr;
398
399
  /// Range for the code completion token.
400
  SourceRange CodeCompletionTokenRange;
401
402
  /// The directory that the main file should be considered to occupy,
403
  /// if it does not correspond to a real file (as happens when building a
404
  /// module).
405
  const DirectoryEntry *MainFileDir = nullptr;
406
407
  /// The number of bytes that we will initially skip when entering the
408
  /// main file, along with a flag that indicates whether skipping this number
409
  /// of bytes will place the lexer at the start of a line.
410
  ///
411
  /// This is used when loading a precompiled preamble.
412
  std::pair<int, bool> SkipMainFilePreamble;
413
414
  /// Whether we hit an error due to reaching max allowed include depth. Allows
415
  /// to avoid hitting the same error over and over again.
416
  bool HasReachedMaxIncludeDepth = false;
417
418
  /// The number of currently-active calls to Lex.
419
  ///
420
  /// Lex is reentrant, and asking for an (end-of-phase-4) token can often
421
  /// require asking for multiple additional tokens. This counter makes it
422
  /// possible for Lex to detect whether it's producing a token for the end
423
  /// of phase 4 of translation or for some other situation.
424
  unsigned LexLevel = 0;
425
426
  /// The number of (LexLevel 0) preprocessor tokens.
427
  unsigned TokenCount = 0;
428
429
  /// Preprocess every token regardless of LexLevel.
430
  bool PreprocessToken = false;
431
432
  /// The maximum number of (LexLevel 0) tokens before issuing a -Wmax-tokens
433
  /// warning, or zero for unlimited.
434
  unsigned MaxTokens = 0;
435
  SourceLocation MaxTokensOverrideLoc;
436
437
public:
438
  struct PreambleSkipInfo {
439
    SourceLocation HashTokenLoc;
440
    SourceLocation IfTokenLoc;
441
    bool FoundNonSkipPortion;
442
    bool FoundElse;
443
    SourceLocation ElseLoc;
444
445
    PreambleSkipInfo(SourceLocation HashTokenLoc, SourceLocation IfTokenLoc,
446
                     bool FoundNonSkipPortion, bool FoundElse,
447
                     SourceLocation ElseLoc)
448
        : HashTokenLoc(HashTokenLoc), IfTokenLoc(IfTokenLoc),
449
          FoundNonSkipPortion(FoundNonSkipPortion), FoundElse(FoundElse),
450
23
          ElseLoc(ElseLoc) {}
451
  };
452
453
private:
454
  friend class ASTReader;
455
  friend class MacroArgs;
456
457
  class PreambleConditionalStackStore {
458
    enum State {
459
      Off = 0,
460
      Recording = 1,
461
      Replaying = 2,
462
    };
463
464
  public:
465
87.9k
    PreambleConditionalStackStore() = default;
466
467
91
    void startRecording() { ConditionalStackState = Recording; }
468
28
    void startReplaying() { ConditionalStackState = Replaying; }
469
1.71M
    bool isRecording() const { return ConditionalStackState == Recording; }
470
87.6k
    bool isReplaying() const { return ConditionalStackState == Replaying; }
471
472
35
    ArrayRef<PPConditionalInfo> getStack() const {
473
35
      return ConditionalStack;
474
35
    }
475
476
28
    void doneReplaying() {
477
28
      ConditionalStack.clear();
478
28
      ConditionalStackState = Off;
479
28
    }
480
481
119
    void setStack(ArrayRef<PPConditionalInfo> s) {
482
119
      if (!isRecording() && 
!isReplaying()28
)
483
0
        return;
484
119
      ConditionalStack.clear();
485
119
      ConditionalStack.append(s.begin(), s.end());
486
119
    }
487
488
91
    bool hasRecordedPreamble() const { return !ConditionalStack.empty(); }
489
490
2.80M
    bool reachedEOFWhileSkipping() const { return SkipInfo.hasValue(); }
491
492
18
    void clearSkipInfo() { SkipInfo.reset(); }
493
494
    llvm::Optional<PreambleSkipInfo> SkipInfo;
495
496
  private:
497
    SmallVector<PPConditionalInfo, 4> ConditionalStack;
498
    State ConditionalStackState = Off;
499
  } PreambleConditionalStack;
500
501
  /// The current top of the stack that we're lexing from if
502
  /// not expanding a macro and we are lexing directly from source code.
503
  ///
504
  /// Only one of CurLexer, or CurTokenLexer will be non-null.
505
  std::unique_ptr<Lexer> CurLexer;
506
507
  /// The current top of the stack what we're lexing from
508
  /// if not expanding a macro.
509
  ///
510
  /// This is an alias for CurLexer.
511
  PreprocessorLexer *CurPPLexer = nullptr;
512
513
  /// Used to find the current FileEntry, if CurLexer is non-null
514
  /// and if applicable.
515
  ///
516
  /// This allows us to implement \#include_next and find directory-specific
517
  /// properties.
518
  const DirectoryLookup *CurDirLookup = nullptr;
519
520
  /// The current macro we are expanding, if we are expanding a macro.
521
  ///
522
  /// One of CurLexer and CurTokenLexer must be null.
523
  std::unique_ptr<TokenLexer> CurTokenLexer;
524
525
  /// The kind of lexer we're currently working with.
526
  enum CurLexerKind {
527
    CLK_Lexer,
528
    CLK_TokenLexer,
529
    CLK_CachingLexer,
530
    CLK_LexAfterModuleImport
531
  } CurLexerKind = CLK_Lexer;
532
533
  /// If the current lexer is for a submodule that is being built, this
534
  /// is that submodule.
535
  Module *CurLexerSubmodule = nullptr;
536
537
  /// Keeps track of the stack of files currently
538
  /// \#included, and macros currently being expanded from, not counting
539
  /// CurLexer/CurTokenLexer.
540
  struct IncludeStackInfo {
541
    enum CurLexerKind           CurLexerKind;
542
    Module                     *TheSubmodule;
543
    std::unique_ptr<Lexer>      TheLexer;
544
    PreprocessorLexer          *ThePPLexer;
545
    std::unique_ptr<TokenLexer> TheTokenLexer;
546
    const DirectoryLookup      *TheDirLookup;
547
548
    // The following constructors are completely useless copies of the default
549
    // versions, only needed to pacify MSVC.
550
    IncludeStackInfo(enum CurLexerKind CurLexerKind, Module *TheSubmodule,
551
                     std::unique_ptr<Lexer> &&TheLexer,
552
                     PreprocessorLexer *ThePPLexer,
553
                     std::unique_ptr<TokenLexer> &&TheTokenLexer,
554
                     const DirectoryLookup *TheDirLookup)
555
        : CurLexerKind(std::move(CurLexerKind)),
556
          TheSubmodule(std::move(TheSubmodule)), TheLexer(std::move(TheLexer)),
557
          ThePPLexer(std::move(ThePPLexer)),
558
          TheTokenLexer(std::move(TheTokenLexer)),
559
186M
          TheDirLookup(std::move(TheDirLookup)) {}
560
  };
561
  std::vector<IncludeStackInfo> IncludeMacroStack;
562
563
  /// Actions invoked when some preprocessor activity is
564
  /// encountered (e.g. a file is \#included, etc).
565
  std::unique_ptr<PPCallbacks> Callbacks;
566
567
  struct MacroExpandsInfo {
568
    Token Tok;
569
    MacroDefinition MD;
570
    SourceRange Range;
571
572
    MacroExpandsInfo(Token Tok, MacroDefinition MD, SourceRange Range)
573
6
        : Tok(Tok), MD(MD), Range(Range) {}
574
  };
575
  SmallVector<MacroExpandsInfo, 2> DelayedMacroExpandsCallbacks;
576
577
  /// Information about a name that has been used to define a module macro.
578
  struct ModuleMacroInfo {
579
    /// The most recent macro directive for this identifier.
580
    MacroDirective *MD;
581
582
    /// The active module macros for this identifier.
583
    llvm::TinyPtrVector<ModuleMacro *> ActiveModuleMacros;
584
585
    /// The generation number at which we last updated ActiveModuleMacros.
586
    /// \see Preprocessor::VisibleModules.
587
    unsigned ActiveModuleMacrosGeneration = 0;
588
589
    /// Whether this macro name is ambiguous.
590
    bool IsAmbiguous = false;
591
592
    /// The module macros that are overridden by this macro.
593
    llvm::TinyPtrVector<ModuleMacro *> OverriddenMacros;
594
595
94.6k
    ModuleMacroInfo(MacroDirective *MD) : MD(MD) {}
596
  };
597
598
  /// The state of a macro for an identifier.
599
  class MacroState {
600
    mutable llvm::PointerUnion<MacroDirective *, ModuleMacroInfo *> State;
601
602
    ModuleMacroInfo *getModuleInfo(Preprocessor &PP,
603
376M
                                   const IdentifierInfo *II) const {
604
376M
      if (II->isOutOfDate())
605
953
        PP.updateOutOfDateIdentifier(const_cast<IdentifierInfo&>(*II));
606
      // FIXME: Find a spare bit on IdentifierInfo and store a
607
      //        HasModuleMacros flag.
608
376M
      if (!II->hasMacroDefinition() ||
609
376M
          
(332M
!PP.getLangOpts().Modules332M
&&
610
332M
           
!PP.getLangOpts().ModulesLocalVisibility325M
) ||
611
376M
          
!PP.CurSubmoduleState->VisibleModules.getGeneration()7.59M
)
612
368M
        return nullptr;
613
614
7.48M
      auto *Info = State.dyn_cast<ModuleMacroInfo*>();
615
7.48M
      if (!Info) {
616
94.6k
        Info = new (PP.getPreprocessorAllocator())
617
94.6k
            ModuleMacroInfo(State.get<MacroDirective *>());
618
94.6k
        State = Info;
619
94.6k
      }
620
621
7.48M
      if (PP.CurSubmoduleState->VisibleModules.getGeneration() !=
622
7.48M
          Info->ActiveModuleMacrosGeneration)
623
331k
        PP.updateModuleMacroInfo(II, *Info);
624
7.48M
      return Info;
625
376M
    }
626
627
  public:
628
48.4M
    MacroState() : MacroState(nullptr) {}
Unexecuted instantiation: clang::Preprocessor::MacroState::MacroState()
clang::Preprocessor::MacroState::MacroState()
Line
Count
Source
628
48.4M
    MacroState() : MacroState(nullptr) {}
629
48.5M
    MacroState(MacroDirective *MD) : State(MD) {}
630
631
78.5M
    MacroState(MacroState &&O) noexcept : State(O.State) {
632
78.5M
      O.State = (MacroDirective *)nullptr;
633
78.5M
    }
634
635
45.1k
    MacroState &operator=(MacroState &&O) noexcept {
636
45.1k
      auto S = O.State;
637
45.1k
      O.State = (MacroDirective *)nullptr;
638
45.1k
      State = S;
639
45.1k
      return *this;
640
45.1k
    }
641
642
120M
    ~MacroState() {
643
120M
      if (auto *Info = State.dyn_cast<ModuleMacroInfo*>())
644
93.2k
        Info->~ModuleMacroInfo();
645
120M
    }
646
647
213M
    MacroDirective *getLatest() const {
648
213M
      if (auto *Info = State.dyn_cast<ModuleMacroInfo*>())
649
3.79M
        return Info->MD;
650
210M
      return State.get<MacroDirective*>();
651
213M
    }
652
653
44.3M
    void setLatest(MacroDirective *MD) {
654
44.3M
      if (auto *Info = State.dyn_cast<ModuleMacroInfo*>())
655
77.7k
        Info->MD = MD;
656
44.2M
      else
657
44.2M
        State = MD;
658
44.3M
    }
659
660
166M
    bool isAmbiguous(Preprocessor &PP, const IdentifierInfo *II) const {
661
166M
      auto *Info = getModuleInfo(PP, II);
662
166M
      return Info ? 
Info->IsAmbiguous3.73M
:
false162M
;
663
166M
    }
664
665
    ArrayRef<ModuleMacro *>
666
166M
    getActiveModuleMacros(Preprocessor &PP, const IdentifierInfo *II) const {
667
166M
      if (auto *Info = getModuleInfo(PP, II))
668
3.73M
        return Info->ActiveModuleMacros;
669
162M
      return None;
670
166M
    }
671
672
    MacroDirective::DefInfo findDirectiveAtLoc(SourceLocation Loc,
673
119k
                                               SourceManager &SourceMgr) const {
674
      // FIXME: Incorporate module macros into the result of this.
675
119k
      if (auto *Latest = getLatest())
676
119k
        return Latest->findDirectiveAtLoc(Loc, SourceMgr);
677
1
      return {};
678
119k
    }
679
680
44.0M
    void overrideActiveModuleMacros(Preprocessor &PP, IdentifierInfo *II) {
681
44.0M
      if (auto *Info = getModuleInfo(PP, II)) {
682
10.3k
        Info->OverriddenMacros.insert(Info->OverriddenMacros.end(),
683
10.3k
                                      Info->ActiveModuleMacros.begin(),
684
10.3k
                                      Info->ActiveModuleMacros.end());
685
10.3k
        Info->ActiveModuleMacros.clear();
686
10.3k
        Info->IsAmbiguous = false;
687
10.3k
      }
688
44.0M
    }
689
690
426k
    ArrayRef<ModuleMacro*> getOverriddenMacros() const {
691
426k
      if (auto *Info = State.dyn_cast<ModuleMacroInfo*>())
692
65.2k
        return Info->OverriddenMacros;
693
361k
      return None;
694
426k
    }
695
696
    void setOverriddenMacros(Preprocessor &PP,
697
425k
                             ArrayRef<ModuleMacro *> Overrides) {
698
425k
      auto *Info = State.dyn_cast<ModuleMacroInfo*>();
699
425k
      if (!Info) {
700
361k
        if (Overrides.empty())
701
361k
          return;
702
0
        Info = new (PP.getPreprocessorAllocator())
703
0
            ModuleMacroInfo(State.get<MacroDirective *>());
704
0
        State = Info;
705
0
      }
706
64.7k
      Info->OverriddenMacros.clear();
707
64.7k
      Info->OverriddenMacros.insert(Info->OverriddenMacros.end(),
708
64.7k
                                    Overrides.begin(), Overrides.end());
709
64.7k
      Info->ActiveModuleMacrosGeneration = 0;
710
64.7k
    }
711
  };
712
713
  /// For each IdentifierInfo that was associated with a macro, we
714
  /// keep a mapping to the history of all macro definitions and #undefs in
715
  /// the reverse order (the latest one is in the head of the list).
716
  ///
717
  /// This mapping lives within the \p CurSubmoduleState.
718
  using MacroMap = llvm::DenseMap<const IdentifierInfo *, MacroState>;
719
720
  struct SubmoduleState;
721
722
  /// Information about a submodule that we're currently building.
723
  struct BuildingSubmoduleInfo {
724
    /// The module that we are building.
725
    Module *M;
726
727
    /// The location at which the module was included.
728
    SourceLocation ImportLoc;
729
730
    /// Whether we entered this submodule via a pragma.
731
    bool IsPragma;
732
733
    /// The previous SubmoduleState.
734
    SubmoduleState *OuterSubmoduleState;
735
736
    /// The number of pending module macro names when we started building this.
737
    unsigned OuterPendingModuleMacroNames;
738
739
    BuildingSubmoduleInfo(Module *M, SourceLocation ImportLoc, bool IsPragma,
740
                          SubmoduleState *OuterSubmoduleState,
741
                          unsigned OuterPendingModuleMacroNames)
742
        : M(M), ImportLoc(ImportLoc), IsPragma(IsPragma),
743
          OuterSubmoduleState(OuterSubmoduleState),
744
80.3k
          OuterPendingModuleMacroNames(OuterPendingModuleMacroNames) {}
745
  };
746
  SmallVector<BuildingSubmoduleInfo, 8> BuildingSubmoduleStack;
747
748
  /// Information about a submodule's preprocessor state.
749
  struct SubmoduleState {
750
    /// The macros for the submodule.
751
    MacroMap Macros;
752
753
    /// The set of modules that are visible within the submodule.
754
    VisibleModuleSet VisibleModules;
755
756
    // FIXME: CounterValue?
757
    // FIXME: PragmaPushMacroInfo?
758
  };
759
  std::map<Module *, SubmoduleState> Submodules;
760
761
  /// The preprocessor state for preprocessing outside of any submodule.
762
  SubmoduleState NullSubmoduleState;
763
764
  /// The current submodule state. Will be \p NullSubmoduleState if we're not
765
  /// in a submodule.
766
  SubmoduleState *CurSubmoduleState;
767
768
  /// The set of known macros exported from modules.
769
  llvm::FoldingSet<ModuleMacro> ModuleMacros;
770
771
  /// The names of potential module macros that we've not yet processed.
772
  llvm::SmallVector<const IdentifierInfo *, 32> PendingModuleMacroNames;
773
774
  /// The list of module macros, for each identifier, that are not overridden by
775
  /// any other module macro.
776
  llvm::DenseMap<const IdentifierInfo *, llvm::TinyPtrVector<ModuleMacro *>>
777
      LeafModuleMacros;
778
779
  /// Macros that we want to warn because they are not used at the end
780
  /// of the translation unit.
781
  ///
782
  /// We store just their SourceLocations instead of
783
  /// something like MacroInfo*. The benefit of this is that when we are
784
  /// deserializing from PCH, we don't need to deserialize identifier & macros
785
  /// just so that we can report that they are unused, we just warn using
786
  /// the SourceLocations of this set (that will be filled by the ASTReader).
787
  using WarnUnusedMacroLocsTy = llvm::SmallDenseSet<SourceLocation, 32>;
788
  WarnUnusedMacroLocsTy WarnUnusedMacroLocs;
789
790
  /// This is a pair of an optional message and source location used for pragmas
791
  /// that annotate macros like pragma clang restrict_expansion and pragma clang
792
  /// deprecated. This pair stores the optional message and the location of the
793
  /// annotation pragma for use producing diagnostics and notes.
794
  using MsgLocationPair = std::pair<std::string, SourceLocation>;
795
796
  struct MacroAnnotationInfo {
797
    SourceLocation Location;
798
    std::string Message;
799
  };
800
801
  struct MacroAnnotations {
802
    llvm::Optional<MacroAnnotationInfo> DeprecationInfo;
803
    llvm::Optional<MacroAnnotationInfo> RestrictExpansionInfo;
804
    llvm::Optional<SourceLocation> FinalAnnotationLoc;
805
806
    static MacroAnnotations makeDeprecation(SourceLocation Loc,
807
22
                                            std::string Msg) {
808
22
      return MacroAnnotations{MacroAnnotationInfo{Loc, std::move(Msg)},
809
22
                              llvm::None, llvm::None};
810
22
    }
811
812
    static MacroAnnotations makeRestrictExpansion(SourceLocation Loc,
813
3
                                                  std::string Msg) {
814
3
      return MacroAnnotations{
815
3
          llvm::None, MacroAnnotationInfo{Loc, std::move(Msg)}, llvm::None};
816
3
    }
817
818
3
    static MacroAnnotations makeFinal(SourceLocation Loc) {
819
3
      return MacroAnnotations{llvm::None, llvm::None, Loc};
820
3
    }
821
  };
822
823
  /// Warning information for macro annotations.
824
  llvm::DenseMap<const IdentifierInfo *, MacroAnnotations> AnnotationInfos;
825
826
  /// A "freelist" of MacroArg objects that can be
827
  /// reused for quick allocation.
828
  MacroArgs *MacroArgCache = nullptr;
829
830
  /// For each IdentifierInfo used in a \#pragma push_macro directive,
831
  /// we keep a MacroInfo stack used to restore the previous macro value.
832
  llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>
833
      PragmaPushMacroInfo;
834
835
  // Various statistics we track for performance analysis.
836
  unsigned NumDirectives = 0;
837
  unsigned NumDefined = 0;
838
  unsigned NumUndefined = 0;
839
  unsigned NumPragma = 0;
840
  unsigned NumIf = 0;
841
  unsigned NumElse = 0;
842
  unsigned NumEndif = 0;
843
  unsigned NumEnteredSourceFiles = 0;
844
  unsigned MaxIncludeStackDepth = 0;
845
  unsigned NumMacroExpanded = 0;
846
  unsigned NumFnMacroExpanded = 0;
847
  unsigned NumBuiltinMacroExpanded = 0;
848
  unsigned NumFastMacroExpanded = 0;
849
  unsigned NumTokenPaste = 0;
850
  unsigned NumFastTokenPaste = 0;
851
  unsigned NumSkipped = 0;
852
853
  /// The predefined macros that preprocessor should use from the
854
  /// command line etc.
855
  std::string Predefines;
856
857
  /// The file ID for the preprocessor predefines.
858
  FileID PredefinesFileID;
859
860
  /// The file ID for the PCH through header.
861
  FileID PCHThroughHeaderFileID;
862
863
  /// Whether tokens are being skipped until a #pragma hdrstop is seen.
864
  bool SkippingUntilPragmaHdrStop = false;
865
866
  /// Whether tokens are being skipped until the through header is seen.
867
  bool SkippingUntilPCHThroughHeader = false;
868
869
  /// \{
870
  /// Cache of macro expanders to reduce malloc traffic.
871
  enum { TokenLexerCacheSize = 8 };
872
  unsigned NumCachedTokenLexers;
873
  std::unique_ptr<TokenLexer> TokenLexerCache[TokenLexerCacheSize];
874
  /// \}
875
876
  /// Keeps macro expanded tokens for TokenLexers.
877
  //
878
  /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
879
  /// going to lex in the cache and when it finishes the tokens are removed
880
  /// from the end of the cache.
881
  SmallVector<Token, 16> MacroExpandedTokens;
882
  std::vector<std::pair<TokenLexer *, size_t>> MacroExpandingLexersStack;
883
884
  /// A record of the macro definitions and expansions that
885
  /// occurred during preprocessing.
886
  ///
887
  /// This is an optional side structure that can be enabled with
888
  /// \c createPreprocessingRecord() prior to preprocessing.
889
  PreprocessingRecord *Record = nullptr;
890
891
  /// Cached tokens state.
892
  using CachedTokensTy = SmallVector<Token, 1>;
893
894
  /// Cached tokens are stored here when we do backtracking or
895
  /// lookahead. They are "lexed" by the CachingLex() method.
896
  CachedTokensTy CachedTokens;
897
898
  /// The position of the cached token that CachingLex() should
899
  /// "lex" next.
900
  ///
901
  /// If it points beyond the CachedTokens vector, it means that a normal
902
  /// Lex() should be invoked.
903
  CachedTokensTy::size_type CachedLexPos = 0;
904
905
  /// Stack of backtrack positions, allowing nested backtracks.
906
  ///
907
  /// The EnableBacktrackAtThisPos() method pushes a position to
908
  /// indicate where CachedLexPos should be set when the BackTrack() method is
909
  /// invoked (at which point the last position is popped).
910
  std::vector<CachedTokensTy::size_type> BacktrackPositions;
911
912
  struct MacroInfoChain {
913
    MacroInfo MI;
914
    MacroInfoChain *Next;
915
  };
916
917
  /// MacroInfos are managed as a chain for easy disposal.  This is the head
918
  /// of that list.
919
  MacroInfoChain *MIChainHead = nullptr;
920
921
  void updateOutOfDateIdentifier(IdentifierInfo &II) const;
922
923
public:
924
  Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
925
               DiagnosticsEngine &diags, LangOptions &opts, SourceManager &SM,
926
               HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
927
               IdentifierInfoLookup *IILookup = nullptr,
928
               bool OwnsHeaderSearch = false,
929
               TranslationUnitKind TUKind = TU_Complete);
930
931
  ~Preprocessor();
932
933
  /// Initialize the preprocessor using information about the target.
934
  ///
935
  /// \param Target is owned by the caller and must remain valid for the
936
  /// lifetime of the preprocessor.
937
  /// \param AuxTarget is owned by the caller and must remain valid for
938
  /// the lifetime of the preprocessor.
939
  void Initialize(const TargetInfo &Target,
940
                  const TargetInfo *AuxTarget = nullptr);
941
942
  /// Initialize the preprocessor to parse a model file
943
  ///
944
  /// To parse model files the preprocessor of the original source is reused to
945
  /// preserver the identifier table. However to avoid some duplicate
946
  /// information in the preprocessor some cleanup is needed before it is used
947
  /// to parse model files. This method does that cleanup.
948
  void InitializeForModelFile();
949
950
  /// Cleanup after model file parsing
951
  void FinalizeForModelFile();
952
953
  /// Retrieve the preprocessor options used to initialize this
954
  /// preprocessor.
955
139k
  PreprocessorOptions &getPreprocessorOpts() const { return *PPOpts; }
956
957
33.7M
  DiagnosticsEngine &getDiagnostics() const { return *Diags; }
958
234
  void setDiagnostics(DiagnosticsEngine &D) { Diags = &D; }
959
960
5.77G
  const LangOptions &getLangOpts() const { return LangOpts; }
961
17.5M
  const TargetInfo &getTargetInfo() const { return *Target; }
962
1.23k
  const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
963
203k
  FileManager &getFileManager() const { return FileMgr; }
964
1.32G
  SourceManager &getSourceManager() const { return SourceMgr; }
965
2.54M
  HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; }
966
967
25.4M
  IdentifierTable &getIdentifierTable() { return Identifiers; }
968
5.38k
  const IdentifierTable &getIdentifierTable() const { return Identifiers; }
969
1.45M
  SelectorTable &getSelectorTable() { return Selectors; }
970
169k
  Builtin::Context &getBuiltinInfo() { return *BuiltinInfo; }
971
2.91M
  llvm::BumpPtrAllocator &getPreprocessorAllocator() { return BP; }
972
973
7.24k
  void setExternalSource(ExternalPreprocessorSource *Source) {
974
7.24k
    ExternalSource = Source;
975
7.24k
  }
976
977
1.46M
  ExternalPreprocessorSource *getExternalSource() const {
978
1.46M
    return ExternalSource;
979
1.46M
  }
980
981
  /// Retrieve the module loader associated with this preprocessor.
982
110k
  ModuleLoader &getModuleLoader() const { return TheModuleLoader; }
983
984
60.0M
  bool hadModuleLoaderFatalFailure() const {
985
60.0M
    return TheModuleLoader.HadFatalFailure;
986
60.0M
  }
987
988
  /// Retrieve the number of Directives that have been processed by the
989
  /// Preprocessor.
990
824k
  unsigned getNumDirectives() const {
991
824k
    return NumDirectives;
992
824k
  }
993
994
  /// True if we are currently preprocessing a #if or #elif directive
995
15.3k
  bool isParsingIfOrElifDirective() const {
996
15.3k
    return ParsingIfOrElifDirective;
997
15.3k
  }
998
999
  /// Control whether the preprocessor retains comments in output.
1000
668
  void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) {
1001
668
    this->KeepComments = KeepComments | KeepMacroComments;
1002
668
    this->KeepMacroComments = KeepMacroComments;
1003
668
  }
1004
1005
85.8M
  bool getCommentRetentionState() const { return KeepComments; }
1006
1007
234
  void setPragmasEnabled(bool Enabled) { PragmasEnabled = Enabled; }
1008
117
  bool getPragmasEnabled() const { return PragmasEnabled; }
1009
1010
4
  void SetSuppressIncludeNotFoundError(bool Suppress) {
1011
4
    SuppressIncludeNotFoundError = Suppress;
1012
4
  }
1013
1014
0
  bool GetSuppressIncludeNotFoundError() {
1015
0
    return SuppressIncludeNotFoundError;
1016
0
  }
1017
1018
  /// Sets whether the preprocessor is responsible for producing output or if
1019
  /// it is producing tokens to be consumed by Parse and Sema.
1020
87.7k
  void setPreprocessedOutput(bool IsPreprocessedOutput) {
1021
87.7k
    PreprocessedOutput = IsPreprocessedOutput;
1022
87.7k
  }
1023
1024
  /// Returns true if the preprocessor is responsible for generating output,
1025
  /// false if it is producing tokens to be consumed by Parse and Sema.
1026
7.66k
  bool isPreprocessedOutput() const { return PreprocessedOutput; }
1027
1028
  /// Return true if we are lexing directly from the specified lexer.
1029
0
  bool isCurrentLexer(const PreprocessorLexer *L) const {
1030
0
    return CurPPLexer == L;
1031
0
  }
1032
1033
  /// Return the current lexer being lexed from.
1034
  ///
1035
  /// Note that this ignores any potentially active macro expansions and _Pragma
1036
  /// expansions going on at the time.
1037
84.3k
  PreprocessorLexer *getCurrentLexer() const { return CurPPLexer; }
1038
1039
  /// Return the current file lexer being lexed from.
1040
  ///
1041
  /// Note that this ignores any potentially active macro expansions and _Pragma
1042
  /// expansions going on at the time.
1043
  PreprocessorLexer *getCurrentFileLexer() const;
1044
1045
  /// Return the submodule owning the file being lexed. This may not be
1046
  /// the current module if we have changed modules since entering the file.
1047
5.33k
  Module *getCurrentLexerSubmodule() const { return CurLexerSubmodule; }
1048
1049
  /// Returns the FileID for the preprocessor predefines.
1050
728k
  FileID getPredefinesFileID() const { return PredefinesFileID; }
1051
1052
  /// \{
1053
  /// Accessors for preprocessor callbacks.
1054
  ///
1055
  /// Note that this class takes ownership of any PPCallbacks object given to
1056
  /// it.
1057
1.74M
  PPCallbacks *getPPCallbacks() const { return Callbacks.get(); }
1058
136k
  void addPPCallbacks(std::unique_ptr<PPCallbacks> C) {
1059
136k
    if (Callbacks)
1060
49.8k
      C = std::make_unique<PPChainedCallbacks>(std::move(C),
1061
49.8k
                                                std::move(Callbacks));
1062
136k
    Callbacks = std::move(C);
1063
136k
  }
1064
  /// \}
1065
1066
  /// Get the number of tokens processed so far.
1067
10
  unsigned getTokenCount() const { return TokenCount; }
1068
1069
  /// Get the max number of tokens before issuing a -Wmax-tokens warning.
1070
85.4k
  unsigned getMaxTokens() const { return MaxTokens; }
1071
1072
1
  void overrideMaxTokens(unsigned Value, SourceLocation Loc) {
1073
1
    MaxTokens = Value;
1074
1
    MaxTokensOverrideLoc = Loc;
1075
1
  };
1076
1077
2
  SourceLocation getMaxTokensOverrideLoc() const { return MaxTokensOverrideLoc; }
1078
1079
  /// Register a function that would be called on each token in the final
1080
  /// expanded token stream.
1081
  /// This also reports annotation tokens produced by the parser.
1082
4.45k
  void setTokenWatcher(llvm::unique_function<void(const clang::Token &)> F) {
1083
4.45k
    OnToken = std::move(F);
1084
4.45k
  }
1085
1086
24
  void setPreprocessToken(bool Preprocess) { PreprocessToken = Preprocess; }
1087
1088
97.3k
  bool isMacroDefined(StringRef Id) {
1089
97.3k
    return isMacroDefined(&Identifiers.get(Id));
1090
97.3k
  }
1091
1.41M
  bool isMacroDefined(const IdentifierInfo *II) {
1092
1.41M
    return II->hasMacroDefinition() &&
1093
1.41M
           
(1.41M
!getLangOpts().Modules1.41M
||
(bool)getMacroDefinition(II)19.3k
);
1094
1.41M
  }
1095
1096
  /// Determine whether II is defined as a macro within the module M,
1097
  /// if that is a module that we've already preprocessed. Does not check for
1098
  /// macros imported into M.
1099
55.8k
  bool isMacroDefinedInLocalModule(const IdentifierInfo *II, Module *M) {
1100
55.8k
    if (!II->hasMacroDefinition())
1101
97
      return false;
1102
55.7k
    auto I = Submodules.find(M);
1103
55.7k
    if (I == Submodules.end())
1104
55.7k
      return false;
1105
18
    auto J = I->second.Macros.find(II);
1106
18
    if (J == I->second.Macros.end())
1107
0
      return false;
1108
18
    auto *MD = J->second.getLatest();
1109
18
    return MD && MD->isDefined();
1110
18
  }
1111
1112
172M
  MacroDefinition getMacroDefinition(const IdentifierInfo *II) {
1113
172M
    if (!II->hasMacroDefinition())
1114
6.24M
      return {};
1115
1116
166M
    MacroState &S = CurSubmoduleState->Macros[II];
1117
166M
    auto *MD = S.getLatest();
1118
166M
    while (MD && 
isa<VisibilityMacroDirective>(MD)162M
)
1119
133
      MD = MD->getPrevious();
1120
166M
    return MacroDefinition(dyn_cast_or_null<DefMacroDirective>(MD),
1121
166M
                           S.getActiveModuleMacros(*this, II),
1122
166M
                           S.isAmbiguous(*this, II));
1123
172M
  }
1124
1125
  MacroDefinition getMacroDefinitionAtLoc(const IdentifierInfo *II,
1126
29
                                          SourceLocation Loc) {
1127
29
    if (!II->hadMacroDefinition())
1128
10
      return {};
1129
1130
19
    MacroState &S = CurSubmoduleState->Macros[II];
1131
19
    MacroDirective::DefInfo DI;
1132
19
    if (auto *MD = S.getLatest())
1133
19
      DI = MD->findDirectiveAtLoc(Loc, getSourceManager());
1134
    // FIXME: Compute the set of active module macros at the specified location.
1135
19
    return MacroDefinition(DI.getDirective(),
1136
19
                           S.getActiveModuleMacros(*this, II),
1137
19
                           S.isAmbiguous(*this, II));
1138
29
  }
1139
1140
  /// Given an identifier, return its latest non-imported MacroDirective
1141
  /// if it is \#define'd and not \#undef'd, or null if it isn't \#define'd.
1142
197
  MacroDirective *getLocalMacroDirective(const IdentifierInfo *II) const {
1143
197
    if (!II->hasMacroDefinition())
1144
9
      return nullptr;
1145
1146
188
    auto *MD = getLocalMacroDirectiveHistory(II);
1147
188
    if (!MD || MD->getDefinition().isUndefined())
1148
0
      return nullptr;
1149
1150
188
    return MD;
1151
188
  }
1152
1153
76.5M
  const MacroInfo *getMacroInfo(const IdentifierInfo *II) const {
1154
76.5M
    return const_cast<Preprocessor*>(this)->getMacroInfo(II);
1155
76.5M
  }
1156
1157
169M
  MacroInfo *getMacroInfo(const IdentifierInfo *II) {
1158
169M
    if (!II->hasMacroDefinition())
1159
89.1M
      return nullptr;
1160
80.8M
    if (auto MD = getMacroDefinition(II))
1161
80.8M
      return MD.getMacroInfo();
1162
17.2k
    return nullptr;
1163
80.8M
  }
1164
1165
  /// Given an identifier, return the latest non-imported macro
1166
  /// directive for that identifier.
1167
  ///
1168
  /// One can iterate over all previous macro directives from the most recent
1169
  /// one.
1170
  MacroDirective *getLocalMacroDirectiveHistory(const IdentifierInfo *II) const;
1171
1172
  /// Add a directive to the macro directive history for this identifier.
1173
  void appendMacroDirective(IdentifierInfo *II, MacroDirective *MD);
1174
  DefMacroDirective *appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI,
1175
43.9M
                                             SourceLocation Loc) {
1176
43.9M
    DefMacroDirective *MD = AllocateDefMacroDirective(MI, Loc);
1177
43.9M
    appendMacroDirective(II, MD);
1178
43.9M
    return MD;
1179
43.9M
  }
1180
  DefMacroDirective *appendDefMacroDirective(IdentifierInfo *II,
1181
43.9M
                                             MacroInfo *MI) {
1182
43.9M
    return appendDefMacroDirective(II, MI, MI->getDefinitionLoc());
1183
43.9M
  }
1184
1185
  /// Set a MacroDirective that was loaded from a PCH file.
1186
  void setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *ED,
1187
                               MacroDirective *MD);
1188
1189
  /// Register an exported macro for a module and identifier.
1190
  ModuleMacro *addModuleMacro(Module *Mod, IdentifierInfo *II, MacroInfo *Macro,
1191
                              ArrayRef<ModuleMacro *> Overrides, bool &IsNew);
1192
  ModuleMacro *getModuleMacro(Module *Mod, const IdentifierInfo *II);
1193
1194
  /// Get the list of leaf (non-overridden) module macros for a name.
1195
7.44M
  ArrayRef<ModuleMacro*> getLeafModuleMacros(const IdentifierInfo *II) const {
1196
7.44M
    if (II->isOutOfDate())
1197
85
      updateOutOfDateIdentifier(const_cast<IdentifierInfo&>(*II));
1198
7.44M
    auto I = LeafModuleMacros.find(II);
1199
7.44M
    if (I != LeafModuleMacros.end())
1200
5.23M
      return I->second;
1201
2.21M
    return None;
1202
7.44M
  }
1203
1204
  /// Get the list of submodules that we're currently building.
1205
0
  ArrayRef<BuildingSubmoduleInfo> getBuildingSubmodules() const {
1206
0
    return BuildingSubmoduleStack;
1207
0
  }
1208
1209
  /// \{
1210
  /// Iterators for the macro history table. Currently defined macros have
1211
  /// IdentifierInfo::hasMacroDefinition() set and an empty
1212
  /// MacroInfo::getUndefLoc() at the head of the list.
1213
  using macro_iterator = MacroMap::const_iterator;
1214
1215
  macro_iterator macro_begin(bool IncludeExternalMacros = true) const;
1216
  macro_iterator macro_end(bool IncludeExternalMacros = true) const;
1217
1218
  llvm::iterator_range<macro_iterator>
1219
8
  macros(bool IncludeExternalMacros = true) const {
1220
8
    macro_iterator begin = macro_begin(IncludeExternalMacros);
1221
8
    macro_iterator end = macro_end(IncludeExternalMacros);
1222
8
    return llvm::make_range(begin, end);
1223
8
  }
1224
1225
  /// \}
1226
1227
  /// Return the name of the macro defined before \p Loc that has
1228
  /// spelling \p Tokens.  If there are multiple macros with same spelling,
1229
  /// return the last one defined.
1230
  StringRef getLastMacroWithSpelling(SourceLocation Loc,
1231
                                     ArrayRef<TokenValue> Tokens) const;
1232
1233
0
  const std::string &getPredefines() const { return Predefines; }
1234
1235
  /// Set the predefines for this Preprocessor.
1236
  ///
1237
  /// These predefines are automatically injected when parsing the main file.
1238
  void setPredefines(const char *P) { Predefines = P; }
1239
91.4k
  void setPredefines(StringRef P) { Predefines = std::string(P); }
1240
1241
  /// Return information about the specified preprocessor
1242
  /// identifier token.
1243
503M
  IdentifierInfo *getIdentifierInfo(StringRef Name) const {
1244
503M
    return &Identifiers.get(Name);
1245
503M
  }
1246
1247
  /// Add the specified pragma handler to this preprocessor.
1248
  ///
1249
  /// If \p Namespace is non-null, then it is a token required to exist on the
1250
  /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
1251
  void AddPragmaHandler(StringRef Namespace, PragmaHandler *Handler);
1252
1.96M
  void AddPragmaHandler(PragmaHandler *Handler) {
1253
1.96M
    AddPragmaHandler(StringRef(), Handler);
1254
1.96M
  }
1255
1256
  /// Remove the specific pragma handler from this preprocessor.
1257
  ///
1258
  /// If \p Namespace is non-null, then it should be the namespace that
1259
  /// \p Handler was added to. It is an error to remove a handler that
1260
  /// has not been registered.
1261
  void RemovePragmaHandler(StringRef Namespace, PragmaHandler *Handler);
1262
1.29M
  void RemovePragmaHandler(PragmaHandler *Handler) {
1263
1.29M
    RemovePragmaHandler(StringRef(), Handler);
1264
1.29M
  }
1265
1266
  /// Install empty handlers for all pragmas (making them ignored).
1267
  void IgnorePragmas();
1268
1269
  /// Set empty line handler.
1270
24
  void setEmptylineHandler(EmptylineHandler *Handler) { Emptyline = Handler; }
1271
1272
19.7M
  EmptylineHandler *getEmptylineHandler() const { return Emptyline; }
1273
1274
  /// Add the specified comment handler to the preprocessor.
1275
  void addCommentHandler(CommentHandler *Handler);
1276
1277
  /// Remove the specified comment handler.
1278
  ///
1279
  /// It is an error to remove a handler that has not been registered.
1280
  void removeCommentHandler(CommentHandler *Handler);
1281
1282
  /// Set the code completion handler to the given object.
1283
85.4k
  void setCodeCompletionHandler(CodeCompletionHandler &Handler) {
1284
85.4k
    CodeComplete = &Handler;
1285
85.4k
  }
1286
1287
  /// Retrieve the current code-completion handler.
1288
20
  CodeCompletionHandler *getCodeCompletionHandler() const {
1289
20
    return CodeComplete;
1290
20
  }
1291
1292
  /// Clear out the code completion handler.
1293
85.3k
  void clearCodeCompletionHandler() {
1294
85.3k
    CodeComplete = nullptr;
1295
85.3k
  }
1296
1297
  /// Hook used by the lexer to invoke the "included file" code
1298
  /// completion point.
1299
  void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
1300
1301
  /// Hook used by the lexer to invoke the "natural language" code
1302
  /// completion point.
1303
  void CodeCompleteNaturalLanguage();
1304
1305
  /// Set the code completion token for filtering purposes.
1306
99
  void setCodeCompletionIdentifierInfo(IdentifierInfo *Filter) {
1307
99
    CodeCompletionII = Filter;
1308
99
  }
1309
1310
  /// Set the code completion token range for detecting replacement range later
1311
  /// on.
1312
  void setCodeCompletionTokenRange(const SourceLocation Start,
1313
99
                                   const SourceLocation End) {
1314
99
    CodeCompletionTokenRange = {Start, End};
1315
99
  }
1316
0
  SourceRange getCodeCompletionTokenRange() const {
1317
0
    return CodeCompletionTokenRange;
1318
0
  }
1319
1320
  /// Get the code completion token for filtering purposes.
1321
387
  StringRef getCodeCompletionFilter() {
1322
387
    if (CodeCompletionII)
1323
77
      return CodeCompletionII->getName();
1324
310
    return {};
1325
387
  }
1326
1327
  /// Retrieve the preprocessing record, or NULL if there is no
1328
  /// preprocessing record.
1329
222k
  PreprocessingRecord *getPreprocessingRecord() const { return Record; }
1330
1331
  /// Create a new preprocessing record, which will keep track of
1332
  /// all macro expansions, macro definitions, etc.
1333
  void createPreprocessingRecord();
1334
1335
  /// Returns true if the FileEntry is the PCH through header.
1336
  bool isPCHThroughHeader(const FileEntry *FE);
1337
1338
  /// True if creating a PCH with a through header.
1339
  bool creatingPCHWithThroughHeader();
1340
1341
  /// True if using a PCH with a through header.
1342
  bool usingPCHWithThroughHeader();
1343
1344
  /// True if creating a PCH with a #pragma hdrstop.
1345
  bool creatingPCHWithPragmaHdrStop();
1346
1347
  /// True if using a PCH with a #pragma hdrstop.
1348
  bool usingPCHWithPragmaHdrStop();
1349
1350
  /// Skip tokens until after the #include of the through header or
1351
  /// until after a #pragma hdrstop.
1352
  void SkipTokensWhileUsingPCH();
1353
1354
  /// Process directives while skipping until the through header or
1355
  /// #pragma hdrstop is found.
1356
  void HandleSkippedDirectiveWhileUsingPCH(Token &Result,
1357
                                           SourceLocation HashLoc);
1358
1359
  /// Enter the specified FileID as the main source file,
1360
  /// which implicitly adds the builtin defines etc.
1361
  void EnterMainSourceFile();
1362
1363
  /// Inform the preprocessor callbacks that processing is complete.
1364
  void EndSourceFile();
1365
1366
  /// Add a source file to the top of the include stack and
1367
  /// start lexing tokens from it instead of the current buffer.
1368
  ///
1369
  /// Emits a diagnostic, doesn't enter the file, and returns true on error.
1370
  bool EnterSourceFile(FileID FID, const DirectoryLookup *Dir,
1371
                       SourceLocation Loc, bool IsFirstIncludeOfFile = true);
1372
1373
  /// Add a Macro to the top of the include stack and start lexing
1374
  /// tokens from it instead of the current buffer.
1375
  ///
1376
  /// \param Args specifies the tokens input to a function-like macro.
1377
  /// \param ILEnd specifies the location of the ')' for a function-like macro
1378
  /// or the identifier for an object-like macro.
1379
  void EnterMacro(Token &Tok, SourceLocation ILEnd, MacroInfo *Macro,
1380
                  MacroArgs *Args);
1381
1382
private:
1383
  /// Add a "macro" context to the top of the include stack,
1384
  /// which will cause the lexer to start returning the specified tokens.
1385
  ///
1386
  /// If \p DisableMacroExpansion is true, tokens lexed from the token stream
1387
  /// will not be subject to further macro expansion. Otherwise, these tokens
1388
  /// will be re-macro-expanded when/if expansion is enabled.
1389
  ///
1390
  /// If \p OwnsTokens is false, this method assumes that the specified stream
1391
  /// of tokens has a permanent owner somewhere, so they do not need to be
1392
  /// copied. If it is true, it assumes the array of tokens is allocated with
1393
  /// \c new[] and the Preprocessor will delete[] it.
1394
  ///
1395
  /// If \p IsReinject the resulting tokens will have Token::IsReinjected flag
1396
  /// set, see the flag documentation for details.
1397
  void EnterTokenStream(const Token *Toks, unsigned NumToks,
1398
                        bool DisableMacroExpansion, bool OwnsTokens,
1399
                        bool IsReinject);
1400
1401
public:
1402
  void EnterTokenStream(std::unique_ptr<Token[]> Toks, unsigned NumToks,
1403
347k
                        bool DisableMacroExpansion, bool IsReinject) {
1404
347k
    EnterTokenStream(Toks.release(), NumToks, DisableMacroExpansion, true,
1405
347k
                     IsReinject);
1406
347k
  }
1407
1408
  void EnterTokenStream(ArrayRef<Token> Toks, bool DisableMacroExpansion,
1409
1.04M
                        bool IsReinject) {
1410
1.04M
    EnterTokenStream(Toks.data(), Toks.size(), DisableMacroExpansion, false,
1411
1.04M
                     IsReinject);
1412
1.04M
  }
1413
1414
  /// Pop the current lexer/macro exp off the top of the lexer stack.
1415
  ///
1416
  /// This should only be used in situations where the current state of the
1417
  /// top-of-stack lexer is known.
1418
  void RemoveTopOfLexerStack();
1419
1420
  /// From the point that this method is called, and until
1421
  /// CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor
1422
  /// keeps track of the lexed tokens so that a subsequent Backtrack() call will
1423
  /// make the Preprocessor re-lex the same tokens.
1424
  ///
1425
  /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can
1426
  /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will
1427
  /// be combined with the EnableBacktrackAtThisPos calls in reverse order.
1428
  ///
1429
  /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack
1430
  /// at some point after EnableBacktrackAtThisPos. If you don't, caching of
1431
  /// tokens will continue indefinitely.
1432
  ///
1433
  void EnableBacktrackAtThisPos();
1434
1435
  /// Disable the last EnableBacktrackAtThisPos call.
1436
  void CommitBacktrackedTokens();
1437
1438
  /// Make Preprocessor re-lex the tokens that were lexed since
1439
  /// EnableBacktrackAtThisPos() was previously called.
1440
  void Backtrack();
1441
1442
  /// True if EnableBacktrackAtThisPos() was called and
1443
  /// caching of tokens is on.
1444
114M
  bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); }
1445
1446
  /// Lex the next token for this preprocessor.
1447
  void Lex(Token &Result);
1448
1449
  /// Lex a token, forming a header-name token if possible.
1450
  bool LexHeaderName(Token &Result, bool AllowMacroExpansion = true);
1451
1452
  bool LexAfterModuleImport(Token &Result);
1453
  void CollectPpImportSuffix(SmallVectorImpl<Token> &Toks);
1454
1455
  void makeModuleVisible(Module *M, SourceLocation Loc);
1456
1457
66
  SourceLocation getModuleImportLoc(Module *M) const {
1458
66
    return CurSubmoduleState->VisibleModules.getImportLoc(M);
1459
66
  }
1460
1461
  /// Lex a string literal, which may be the concatenation of multiple
1462
  /// string literals and may even come from macro expansion.
1463
  /// \returns true on success, false if a error diagnostic has been generated.
1464
  bool LexStringLiteral(Token &Result, std::string &String,
1465
183
                        const char *DiagnosticTag, bool AllowMacroExpansion) {
1466
183
    if (AllowMacroExpansion)
1467
90
      Lex(Result);
1468
93
    else
1469
93
      LexUnexpandedToken(Result);
1470
183
    return FinishLexStringLiteral(Result, String, DiagnosticTag,
1471
183
                                  AllowMacroExpansion);
1472
183
  }
1473
1474
  /// Complete the lexing of a string literal where the first token has
1475
  /// already been lexed (see LexStringLiteral).
1476
  bool FinishLexStringLiteral(Token &Result, std::string &String,
1477
                              const char *DiagnosticTag,
1478
                              bool AllowMacroExpansion);
1479
1480
  /// Lex a token.  If it's a comment, keep lexing until we get
1481
  /// something not a comment.
1482
  ///
1483
  /// This is useful in -E -C mode where comments would foul up preprocessor
1484
  /// directive handling.
1485
8.34M
  void LexNonComment(Token &Result) {
1486
8.34M
    do
1487
8.34M
      Lex(Result);
1488
8.34M
    while (Result.getKind() == tok::comment);
1489
8.34M
  }
1490
1491
  /// Just like Lex, but disables macro expansion of identifier tokens.
1492
517M
  void LexUnexpandedToken(Token &Result) {
1493
    // Disable macro expansion.
1494
517M
    bool OldVal = DisableMacroExpansion;
1495
517M
    DisableMacroExpansion = true;
1496
    // Lex the token.
1497
517M
    Lex(Result);
1498
1499
    // Reenable it.
1500
517M
    DisableMacroExpansion = OldVal;
1501
517M
  }
1502
1503
  /// Like LexNonComment, but this disables macro expansion of
1504
  /// identifier tokens.
1505
4.35M
  void LexUnexpandedNonComment(Token &Result) {
1506
4.35M
    do
1507
4.35M
      LexUnexpandedToken(Result);
1508
4.35M
    while (Result.getKind() == tok::comment);
1509
4.35M
  }
1510
1511
  /// Parses a simple integer literal to get its numeric value.  Floating
1512
  /// point literals and user defined literals are rejected.  Used primarily to
1513
  /// handle pragmas that accept integer arguments.
1514
  bool parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value);
1515
1516
  /// Disables macro expansion everywhere except for preprocessor directives.
1517
60
  void SetMacroExpansionOnlyInDirectives() {
1518
60
    DisableMacroExpansion = true;
1519
60
    MacroExpansionInDirectivesOverride = true;
1520
60
  }
1521
1522
  /// Peeks ahead N tokens and returns that token without consuming any
1523
  /// tokens.
1524
  ///
1525
  /// LookAhead(0) returns the next token that would be returned by Lex(),
1526
  /// LookAhead(1) returns the token after it, etc.  This returns normal
1527
  /// tokens after phase 5.  As such, it is equivalent to using
1528
  /// 'Lex', not 'LexUnexpandedToken'.
1529
228M
  const Token &LookAhead(unsigned N) {
1530
228M
    assert(LexLevel == 0 && "cannot use lookahead while lexing");
1531
228M
    if (CachedLexPos + N < CachedTokens.size())
1532
110M
      return CachedTokens[CachedLexPos+N];
1533
117M
    else
1534
117M
      return PeekAhead(N+1);
1535
228M
  }
1536
1537
  /// When backtracking is enabled and tokens are cached,
1538
  /// this allows to revert a specific number of tokens.
1539
  ///
1540
  /// Note that the number of tokens being reverted should be up to the last
1541
  /// backtrack position, not more.
1542
33.0k
  void RevertCachedTokens(unsigned N) {
1543
33.0k
    assert(isBacktrackEnabled() &&
1544
33.0k
           "Should only be called when tokens are cached for backtracking");
1545
0
    assert(signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back())
1546
33.0k
         && "Should revert tokens up to the last backtrack position, not more");
1547
0
    assert(signed(CachedLexPos) - signed(N) >= 0 &&
1548
33.0k
           "Corrupted backtrack positions ?");
1549
0
    CachedLexPos -= N;
1550
33.0k
  }
1551
1552
  /// Enters a token in the token stream to be lexed next.
1553
  ///
1554
  /// If BackTrack() is called afterwards, the token will remain at the
1555
  /// insertion point.
1556
  /// If \p IsReinject is true, resulting token will have Token::IsReinjected
1557
  /// flag set. See the flag documentation for details.
1558
2.97M
  void EnterToken(const Token &Tok, bool IsReinject) {
1559
2.97M
    if (LexLevel) {
1560
      // It's not correct in general to enter caching lex mode while in the
1561
      // middle of a nested lexing action.
1562
249
      auto TokCopy = std::make_unique<Token[]>(1);
1563
249
      TokCopy[0] = Tok;
1564
249
      EnterTokenStream(std::move(TokCopy), 1, true, IsReinject);
1565
2.97M
    } else {
1566
2.97M
      EnterCachingLexMode();
1567
2.97M
      assert(IsReinject && "new tokens in the middle of cached stream");
1568
0
      CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok);
1569
2.97M
    }
1570
2.97M
  }
1571
1572
  /// We notify the Preprocessor that if it is caching tokens (because
1573
  /// backtrack is enabled) it should replace the most recent cached tokens
1574
  /// with the given annotation token. This function has no effect if
1575
  /// backtracking is not enabled.
1576
  ///
1577
  /// Note that the use of this function is just for optimization, so that the
1578
  /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is
1579
  /// invoked.
1580
42.8M
  void AnnotateCachedTokens(const Token &Tok) {
1581
42.8M
    assert(Tok.isAnnotation() && "Expected annotation token");
1582
42.8M
    if (CachedLexPos != 0 && 
isBacktrackEnabled()12.8M
)
1583
8.34M
      AnnotatePreviousCachedTokens(Tok);
1584
42.8M
  }
1585
1586
  /// Get the location of the last cached token, suitable for setting the end
1587
  /// location of an annotation token.
1588
11.2k
  SourceLocation getLastCachedTokenLocation() const {
1589
11.2k
    assert(CachedLexPos != 0);
1590
0
    return CachedTokens[CachedLexPos-1].getLastLoc();
1591
11.2k
  }
1592
1593
  /// Whether \p Tok is the most recent token (`CachedLexPos - 1`) in
1594
  /// CachedTokens.
1595
  bool IsPreviousCachedToken(const Token &Tok) const;
1596
1597
  /// Replace token in `CachedLexPos - 1` in CachedTokens by the tokens
1598
  /// in \p NewToks.
1599
  ///
1600
  /// Useful when a token needs to be split in smaller ones and CachedTokens
1601
  /// most recent token must to be updated to reflect that.
1602
  void ReplacePreviousCachedToken(ArrayRef<Token> NewToks);
1603
1604
  /// Replace the last token with an annotation token.
1605
  ///
1606
  /// Like AnnotateCachedTokens(), this routine replaces an
1607
  /// already-parsed (and resolved) token with an annotation
1608
  /// token. However, this routine only replaces the last token with
1609
  /// the annotation token; it does not affect any other cached
1610
  /// tokens. This function has no effect if backtracking is not
1611
  /// enabled.
1612
0
  void ReplaceLastTokenWithAnnotation(const Token &Tok) {
1613
0
    assert(Tok.isAnnotation() && "Expected annotation token");
1614
0
    if (CachedLexPos != 0 && isBacktrackEnabled())
1615
0
      CachedTokens[CachedLexPos-1] = Tok;
1616
0
  }
1617
1618
  /// Enter an annotation token into the token stream.
1619
  void EnterAnnotationToken(SourceRange Range, tok::TokenKind Kind,
1620
                            void *AnnotationVal);
1621
1622
  /// Determine whether it's possible for a future call to Lex to produce an
1623
  /// annotation token created by a previous call to EnterAnnotationToken.
1624
2.11M
  bool mightHavePendingAnnotationTokens() {
1625
2.11M
    return CurLexerKind != CLK_Lexer;
1626
2.11M
  }
1627
1628
  /// Update the current token to represent the provided
1629
  /// identifier, in order to cache an action performed by typo correction.
1630
17
  void TypoCorrectToken(const Token &Tok) {
1631
17
    assert(Tok.getIdentifierInfo() && "Expected identifier token");
1632
17
    if (CachedLexPos != 0 && 
isBacktrackEnabled()10
)
1633
10
      CachedTokens[CachedLexPos-1] = Tok;
1634
17
  }
1635
1636
  /// Recompute the current lexer kind based on the CurLexer/
1637
  /// CurTokenLexer pointers.
1638
  void recomputeCurLexerKind();
1639
1640
  /// Returns true if incremental processing is enabled
1641
22.1M
  bool isIncrementalProcessingEnabled() const { return IncrementalProcessing; }
1642
1643
  /// Enables the incremental processing
1644
1.39k
  void enableIncrementalProcessing(bool value = true) {
1645
1.39k
    IncrementalProcessing = value;
1646
1.39k
  }
1647
1648
  /// Specify the point at which code-completion will be performed.
1649
  ///
1650
  /// \param File the file in which code completion should occur. If
1651
  /// this file is included multiple times, code-completion will
1652
  /// perform completion the first time it is included. If NULL, this
1653
  /// function clears out the code-completion point.
1654
  ///
1655
  /// \param Line the line at which code completion should occur
1656
  /// (1-based).
1657
  ///
1658
  /// \param Column the column at which code completion should occur
1659
  /// (1-based).
1660
  ///
1661
  /// \returns true if an error occurred, false otherwise.
1662
  bool SetCodeCompletionPoint(const FileEntry *File,
1663
                              unsigned Line, unsigned Column);
1664
1665
  /// Determine if we are performing code completion.
1666
541M
  bool isCodeCompletionEnabled() const { return CodeCompletionFile != nullptr; }
1667
1668
  /// Returns the location of the code-completion point.
1669
  ///
1670
  /// Returns an invalid location if code-completion is not enabled or the file
1671
  /// containing the code-completion point has not been lexed yet.
1672
1.11M
  SourceLocation getCodeCompletionLoc() const { return CodeCompletionLoc; }
1673
1674
  /// Returns the start location of the file of code-completion point.
1675
  ///
1676
  /// Returns an invalid location if code-completion is not enabled or the file
1677
  /// containing the code-completion point has not been lexed yet.
1678
37.6M
  SourceLocation getCodeCompletionFileLoc() const {
1679
37.6M
    return CodeCompletionFileLoc;
1680
37.6M
  }
1681
1682
  /// Returns true if code-completion is enabled and we have hit the
1683
  /// code-completion point.
1684
31.9M
  bool isCodeCompletionReached() const { return CodeCompletionReached; }
1685
1686
  /// Note that we hit the code-completion point.
1687
1.41k
  void setCodeCompletionReached() {
1688
1.41k
    assert(isCodeCompletionEnabled() && "Code-completion not enabled!");
1689
0
    CodeCompletionReached = true;
1690
    // Silence any diagnostics that occur after we hit the code-completion.
1691
1.41k
    getDiagnostics().setSuppressAllDiagnostics(true);
1692
1.41k
  }
1693
1694
  /// The location of the currently-active \#pragma clang
1695
  /// arc_cf_code_audited begin.
1696
  ///
1697
  /// Returns an invalid location if there is no such pragma active.
1698
  std::pair<IdentifierInfo *, SourceLocation>
1699
28.0M
  getPragmaARCCFCodeAuditedInfo() const {
1700
28.0M
    return PragmaARCCFCodeAuditedInfo;
1701
28.0M
  }
1702
1703
  /// Set the location of the currently-active \#pragma clang
1704
  /// arc_cf_code_audited begin.  An invalid location ends the pragma.
1705
  void setPragmaARCCFCodeAuditedInfo(IdentifierInfo *Ident,
1706
63.6k
                                     SourceLocation Loc) {
1707
63.6k
    PragmaARCCFCodeAuditedInfo = {Ident, Loc};
1708
63.6k
  }
1709
1710
  /// The location of the currently-active \#pragma clang
1711
  /// assume_nonnull begin.
1712
  ///
1713
  /// Returns an invalid location if there is no such pragma active.
1714
122M
  SourceLocation getPragmaAssumeNonNullLoc() const {
1715
122M
    return PragmaAssumeNonNullLoc;
1716
122M
  }
1717
1718
  /// Set the location of the currently-active \#pragma clang
1719
  /// assume_nonnull begin.  An invalid location ends the pragma.
1720
143k
  void setPragmaAssumeNonNullLoc(SourceLocation Loc) {
1721
143k
    PragmaAssumeNonNullLoc = Loc;
1722
143k
  }
1723
1724
  /// Set the directory in which the main file should be considered
1725
  /// to have been found, if it is not a real file.
1726
1.97k
  void setMainFileDir(const DirectoryEntry *Dir) {
1727
1.97k
    MainFileDir = Dir;
1728
1.97k
  }
1729
1730
  /// Instruct the preprocessor to skip part of the main source file.
1731
  ///
1732
  /// \param Bytes The number of bytes in the preamble to skip.
1733
  ///
1734
  /// \param StartOfLine Whether skipping these bytes puts the lexer at the
1735
  /// start of a line.
1736
87.8k
  void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine) {
1737
87.8k
    SkipMainFilePreamble.first = Bytes;
1738
87.8k
    SkipMainFilePreamble.second = StartOfLine;
1739
87.8k
  }
1740
1741
  /// Forwarding function for diagnostics.  This emits a diagnostic at
1742
  /// the specified Token's location, translating the token's start
1743
  /// position in the current buffer into a SourcePosition object for rendering.
1744
767k
  DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const {
1745
767k
    return Diags->Report(Loc, DiagID);
1746
767k
  }
1747
1748
1.18M
  DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) const {
1749
1.18M
    return Diags->Report(Tok.getLocation(), DiagID);
1750
1.18M
  }
1751
1752
  /// Return the 'spelling' of the token at the given
1753
  /// location; does not go up to the spelling location or down to the
1754
  /// expansion location.
1755
  ///
1756
  /// \param buffer A buffer which will be used only if the token requires
1757
  ///   "cleaning", e.g. if it contains trigraphs or escaped newlines
1758
  /// \param invalid If non-null, will be set \c true if an error occurs.
1759
  StringRef getSpelling(SourceLocation loc,
1760
                        SmallVectorImpl<char> &buffer,
1761
194
                        bool *invalid = nullptr) const {
1762
194
    return Lexer::getSpelling(loc, buffer, SourceMgr, LangOpts, invalid);
1763
194
  }
1764
1765
  /// Return the 'spelling' of the Tok token.
1766
  ///
1767
  /// The spelling of a token is the characters used to represent the token in
1768
  /// the source file after trigraph expansion and escaped-newline folding.  In
1769
  /// particular, this wants to get the true, uncanonicalized, spelling of
1770
  /// things like digraphs, UCNs, etc.
1771
  ///
1772
  /// \param Invalid If non-null, will be set \c true if an error occurs.
1773
2.50M
  std::string getSpelling(const Token &Tok, bool *Invalid = nullptr) const {
1774
2.50M
    return Lexer::getSpelling(Tok, SourceMgr, LangOpts, Invalid);
1775
2.50M
  }
1776
1777
  /// Get the spelling of a token into a preallocated buffer, instead
1778
  /// of as an std::string.
1779
  ///
1780
  /// The caller is required to allocate enough space for the token, which is
1781
  /// guaranteed to be at least Tok.getLength() bytes long. The length of the
1782
  /// actual result is returned.
1783
  ///
1784
  /// Note that this method may do two possible things: it may either fill in
1785
  /// the buffer specified with characters, or it may *change the input pointer*
1786
  /// to point to a constant buffer with the data already in it (avoiding a
1787
  /// copy).  The caller is not allowed to modify the returned buffer pointer
1788
  /// if an internal buffer is returned.
1789
  unsigned getSpelling(const Token &Tok, const char *&Buffer,
1790
29.7M
                       bool *Invalid = nullptr) const {
1791
29.7M
    return Lexer::getSpelling(Tok, Buffer, SourceMgr, LangOpts, Invalid);
1792
29.7M
  }
1793
1794
  /// Get the spelling of a token into a SmallVector.
1795
  ///
1796
  /// Note that the returned StringRef may not point to the
1797
  /// supplied buffer if a copy can be avoided.
1798
  StringRef getSpelling(const Token &Tok,
1799
                        SmallVectorImpl<char> &Buffer,
1800
                        bool *Invalid = nullptr) const;
1801
1802
  /// Relex the token at the specified location.
1803
  /// \returns true if there was a failure, false on success.
1804
  bool getRawToken(SourceLocation Loc, Token &Result,
1805
117
                   bool IgnoreWhiteSpace = false) {
1806
117
    return Lexer::getRawToken(Loc, Result, SourceMgr, LangOpts, IgnoreWhiteSpace);
1807
117
  }
1808
1809
  /// Given a Token \p Tok that is a numeric constant with length 1,
1810
  /// return the character.
1811
  char
1812
  getSpellingOfSingleCharacterNumericConstant(const Token &Tok,
1813
3.66M
                                              bool *Invalid = nullptr) const {
1814
3.66M
    assert(Tok.is(tok::numeric_constant) &&
1815
3.66M
           Tok.getLength() == 1 && "Called on unsupported token");
1816
0
    assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1");
1817
1818
    // If the token is carrying a literal data pointer, just use it.
1819
3.66M
    if (const char *D = Tok.getLiteralData())
1820
3.66M
      return *D;
1821
1822
    // Otherwise, fall back on getCharacterData, which is slower, but always
1823
    // works.
1824
1.85k
    return *SourceMgr.getCharacterData(Tok.getLocation(), Invalid);
1825
3.66M
  }
1826
1827
  /// Retrieve the name of the immediate macro expansion.
1828
  ///
1829
  /// This routine starts from a source location, and finds the name of the
1830
  /// macro responsible for its immediate expansion. It looks through any
1831
  /// intervening macro argument expansions to compute this. It returns a
1832
  /// StringRef that refers to the SourceManager-owned buffer of the source
1833
  /// where that macro name is spelled. Thus, the result shouldn't out-live
1834
  /// the SourceManager.
1835
32
  StringRef getImmediateMacroName(SourceLocation Loc) {
1836
32
    return Lexer::getImmediateMacroName(Loc, SourceMgr, getLangOpts());
1837
32
  }
1838
1839
  /// Plop the specified string into a scratch buffer and set the
1840
  /// specified token's location and length to it.
1841
  ///
1842
  /// If specified, the source location provides a location of the expansion
1843
  /// point of the token.
1844
  void CreateString(StringRef Str, Token &Tok,
1845
                    SourceLocation ExpansionLocStart = SourceLocation(),
1846
                    SourceLocation ExpansionLocEnd = SourceLocation());
1847
1848
  /// Split the first Length characters out of the token starting at TokLoc
1849
  /// and return a location pointing to the split token. Re-lexing from the
1850
  /// split token will return the split token rather than the original.
1851
  SourceLocation SplitToken(SourceLocation TokLoc, unsigned Length);
1852
1853
  /// Computes the source location just past the end of the
1854
  /// token at this source location.
1855
  ///
1856
  /// This routine can be used to produce a source location that
1857
  /// points just past the end of the token referenced by \p Loc, and
1858
  /// is generally used when a diagnostic needs to point just after a
1859
  /// token where it expected something different that it received. If
1860
  /// the returned source location would not be meaningful (e.g., if
1861
  /// it points into a macro), this routine returns an invalid
1862
  /// source location.
1863
  ///
1864
  /// \param Offset an offset from the end of the token, where the source
1865
  /// location should refer to. The default offset (0) produces a source
1866
  /// location pointing just past the end of the token; an offset of 1 produces
1867
  /// a source location pointing to the last character in the token, etc.
1868
8.50k
  SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0) {
1869
8.50k
    return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
1870
8.50k
  }
1871
1872
  /// Returns true if the given MacroID location points at the first
1873
  /// token of the macro expansion.
1874
  ///
1875
  /// \param MacroBegin If non-null and function returns true, it is set to
1876
  /// begin location of the macro.
1877
  bool isAtStartOfMacroExpansion(SourceLocation loc,
1878
29
                                 SourceLocation *MacroBegin = nullptr) const {
1879
29
    return Lexer::isAtStartOfMacroExpansion(loc, SourceMgr, LangOpts,
1880
29
                                            MacroBegin);
1881
29
  }
1882
1883
  /// Returns true if the given MacroID location points at the last
1884
  /// token of the macro expansion.
1885
  ///
1886
  /// \param MacroEnd If non-null and function returns true, it is set to
1887
  /// end location of the macro.
1888
  bool isAtEndOfMacroExpansion(SourceLocation loc,
1889
30
                               SourceLocation *MacroEnd = nullptr) const {
1890
30
    return Lexer::isAtEndOfMacroExpansion(loc, SourceMgr, LangOpts, MacroEnd);
1891
30
  }
1892
1893
  /// Print the token to stderr, used for debugging.
1894
  void DumpToken(const Token &Tok, bool DumpFlags = false) const;
1895
  void DumpLocation(SourceLocation Loc) const;
1896
  void DumpMacro(const MacroInfo &MI) const;
1897
  void dumpMacroInfo(const IdentifierInfo *II);
1898
1899
  /// Given a location that specifies the start of a
1900
  /// token, return a new location that specifies a character within the token.
1901
  SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,
1902
2.95k
                                         unsigned Char) const {
1903
2.95k
    return Lexer::AdvanceToTokenCharacter(TokStart, Char, SourceMgr, LangOpts);
1904
2.95k
  }
1905
1906
  /// Increment the counters for the number of token paste operations
1907
  /// performed.
1908
  ///
1909
  /// If fast was specified, this is a 'fast paste' case we handled.
1910
7.13M
  void IncrementPasteCounter(bool isFast) {
1911
7.13M
    if (isFast)
1912
6.55M
      ++NumFastTokenPaste;
1913
574k
    else
1914
574k
      ++NumTokenPaste;
1915
7.13M
  }
1916
1917
  void PrintStats();
1918
1919
  size_t getTotalMemory() const;
1920
1921
  /// When the macro expander pastes together a comment (/##/) in Microsoft
1922
  /// mode, this method handles updating the current state, returning the
1923
  /// token on the next source line.
1924
  void HandleMicrosoftCommentPaste(Token &Tok);
1925
1926
  //===--------------------------------------------------------------------===//
1927
  // Preprocessor callback methods.  These are invoked by a lexer as various
1928
  // directives and events are found.
1929
1930
  /// Given a tok::raw_identifier token, look up the
1931
  /// identifier information for the token and install it into the token,
1932
  /// updating the token kind accordingly.
1933
  IdentifierInfo *LookUpIdentifierInfo(Token &Identifier) const;
1934
1935
private:
1936
  llvm::DenseMap<IdentifierInfo*,unsigned> PoisonReasons;
1937
1938
public:
1939
  /// Specifies the reason for poisoning an identifier.
1940
  ///
1941
  /// If that identifier is accessed while poisoned, then this reason will be
1942
  /// used instead of the default "poisoned" diagnostic.
1943
  void SetPoisonReason(IdentifierInfo *II, unsigned DiagID);
1944
1945
  /// Display reason for poisoned identifier.
1946
  void HandlePoisonedIdentifier(Token & Identifier);
1947
1948
0
  void MaybeHandlePoisonedIdentifier(Token & Identifier) {
1949
0
    if(IdentifierInfo * II = Identifier.getIdentifierInfo()) {
1950
0
      if(II->isPoisoned()) {
1951
0
        HandlePoisonedIdentifier(Identifier);
1952
0
      }
1953
0
    }
1954
0
  }
1955
1956
private:
1957
  /// Identifiers used for SEH handling in Borland. These are only
1958
  /// allowed in particular circumstances
1959
  // __except block
1960
  IdentifierInfo *Ident__exception_code,
1961
                 *Ident___exception_code,
1962
                 *Ident_GetExceptionCode;
1963
  // __except filter expression
1964
  IdentifierInfo *Ident__exception_info,
1965
                 *Ident___exception_info,
1966
                 *Ident_GetExceptionInfo;
1967
  // __finally
1968
  IdentifierInfo *Ident__abnormal_termination,
1969
                 *Ident___abnormal_termination,
1970
                 *Ident_AbnormalTermination;
1971
1972
  const char *getCurLexerEndPos();
1973
  void diagnoseMissingHeaderInUmbrellaDir(const Module &Mod);
1974
1975
public:
1976
  void PoisonSEHIdentifiers(bool Poison = true); // Borland
1977
1978
  /// Callback invoked when the lexer reads an identifier and has
1979
  /// filled in the tokens IdentifierInfo member.
1980
  ///
1981
  /// This callback potentially macro expands it or turns it into a named
1982
  /// token (like 'for').
1983
  ///
1984
  /// \returns true if we actually computed a token, false if we need to
1985
  /// lex again.
1986
  bool HandleIdentifier(Token &Identifier);
1987
1988
  /// Callback invoked when the lexer hits the end of the current file.
1989
  ///
1990
  /// This either returns the EOF token and returns true, or
1991
  /// pops a level off the include stack and returns false, at which point the
1992
  /// client should call lex again.
1993
  bool HandleEndOfFile(Token &Result, SourceLocation Loc,
1994
                       bool isEndOfMacro = false);
1995
1996
  /// Callback invoked when the current TokenLexer hits the end of its
1997
  /// token stream.
1998
  bool HandleEndOfTokenLexer(Token &Result);
1999
2000
  /// Callback invoked when the lexer sees a # token at the start of a
2001
  /// line.
2002
  ///
2003
  /// This consumes the directive, modifies the lexer/preprocessor state, and
2004
  /// advances the lexer(s) so that the next token read is the correct one.
2005
  void HandleDirective(Token &Result);
2006
2007
  /// Ensure that the next token is a tok::eod token.
2008
  ///
2009
  /// If not, emit a diagnostic and consume up until the eod.
2010
  /// If \p EnableMacros is true, then we consider macros that expand to zero
2011
  /// tokens as being ok.
2012
  ///
2013
  /// \return The location of the end of the directive (the terminating
2014
  /// newline).
2015
  SourceLocation CheckEndOfDirective(const char *DirType,
2016
                                     bool EnableMacros = false);
2017
2018
  /// Read and discard all tokens remaining on the current line until
2019
  /// the tok::eod token is found. Returns the range of the skipped tokens.
2020
  SourceRange DiscardUntilEndOfDirective();
2021
2022
  /// Returns true if the preprocessor has seen a use of
2023
  /// __DATE__ or __TIME__ in the file so far.
2024
5.38k
  bool SawDateOrTime() const {
2025
5.38k
    return DATELoc != SourceLocation() || 
TIMELoc != SourceLocation()5.38k
;
2026
5.38k
  }
2027
5.38k
  unsigned getCounterValue() const { return CounterValue; }
2028
154
  void setCounterValue(unsigned V) { CounterValue = V; }
2029
2030
  /// Retrieves the module that we're currently building, if any.
2031
  Module *getCurrentModule();
2032
2033
  /// Allocate a new MacroInfo object with the provided SourceLocation.
2034
  MacroInfo *AllocateMacroInfo(SourceLocation L);
2035
2036
  /// Turn the specified lexer token into a fully checked and spelled
2037
  /// filename, e.g. as an operand of \#include.
2038
  ///
2039
  /// The caller is expected to provide a buffer that is large enough to hold
2040
  /// the spelling of the filename, but is also expected to handle the case
2041
  /// when this method decides to use a different buffer.
2042
  ///
2043
  /// \returns true if the input filename was in <>'s or false if it was
2044
  /// in ""'s.
2045
  bool GetIncludeFilenameSpelling(SourceLocation Loc,StringRef &Buffer);
2046
2047
  /// Given a "foo" or \<foo> reference, look up the indicated file.
2048
  ///
2049
  /// Returns None on failure.  \p isAngled indicates whether the file
2050
  /// reference is for system \#include's or not (i.e. using <> instead of "").
2051
  Optional<FileEntryRef>
2052
  LookupFile(SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
2053
             const DirectoryLookup *FromDir, const FileEntry *FromFile,
2054
             const DirectoryLookup **CurDir, SmallVectorImpl<char> *SearchPath,
2055
             SmallVectorImpl<char> *RelativePath,
2056
             ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped,
2057
             bool *IsFrameworkFound, bool SkipCache = false);
2058
2059
  /// Get the DirectoryLookup structure used to find the current
2060
  /// FileEntry, if CurLexer is non-null and if applicable.
2061
  ///
2062
  /// This allows us to implement \#include_next and find directory-specific
2063
  /// properties.
2064
5.34k
  const DirectoryLookup *GetCurDirLookup() { return CurDirLookup; }
2065
2066
  /// Return true if we're in the top-level file, not in a \#include.
2067
  bool isInPrimaryFile() const;
2068
2069
  /// Lex an on-off-switch (C99 6.10.6p2) and verify that it is
2070
  /// followed by EOD.  Return true if the token is not a valid on-off-switch.
2071
  bool LexOnOffSwitch(tok::OnOffSwitch &Result);
2072
2073
  bool CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
2074
                      bool *ShadowFlag = nullptr);
2075
2076
  void EnterSubmodule(Module *M, SourceLocation ImportLoc, bool ForPragma);
2077
  Module *LeaveSubmodule(bool ForPragma);
2078
2079
private:
2080
  friend void TokenLexer::ExpandFunctionArguments();
2081
2082
186M
  void PushIncludeMacroStack() {
2083
186M
    assert(CurLexerKind != CLK_CachingLexer && "cannot push a caching lexer");
2084
0
    IncludeMacroStack.emplace_back(CurLexerKind, CurLexerSubmodule,
2085
186M
                                   std::move(CurLexer), CurPPLexer,
2086
186M
                                   std::move(CurTokenLexer), CurDirLookup);
2087
186M
    CurPPLexer = nullptr;
2088
186M
  }
2089
2090
186M
  void PopIncludeMacroStack() {
2091
186M
    CurLexer = std::move(IncludeMacroStack.back().TheLexer);
2092
186M
    CurPPLexer = IncludeMacroStack.back().ThePPLexer;
2093
186M
    CurTokenLexer = std::move(IncludeMacroStack.back().TheTokenLexer);
2094
186M
    CurDirLookup  = IncludeMacroStack.back().TheDirLookup;
2095
186M
    CurLexerSubmodule = IncludeMacroStack.back().TheSubmodule;
2096
186M
    CurLexerKind = IncludeMacroStack.back().CurLexerKind;
2097
186M
    IncludeMacroStack.pop_back();
2098
186M
  }
2099
2100
  void PropagateLineStartLeadingSpaceInfo(Token &Result);
2101
2102
  /// Determine whether we need to create module macros for #defines in the
2103
  /// current context.
2104
  bool needModuleMacros() const;
2105
2106
  /// Update the set of active module macros and ambiguity flag for a module
2107
  /// macro name.
2108
  void updateModuleMacroInfo(const IdentifierInfo *II, ModuleMacroInfo &Info);
2109
2110
  DefMacroDirective *AllocateDefMacroDirective(MacroInfo *MI,
2111
                                               SourceLocation Loc);
2112
  UndefMacroDirective *AllocateUndefMacroDirective(SourceLocation UndefLoc);
2113
  VisibilityMacroDirective *AllocateVisibilityMacroDirective(SourceLocation Loc,
2114
                                                             bool isPublic);
2115
2116
  /// Lex and validate a macro name, which occurs after a
2117
  /// \#define or \#undef.
2118
  ///
2119
  /// \param MacroNameTok Token that represents the name defined or undefined.
2120
  /// \param IsDefineUndef Kind if preprocessor directive.
2121
  /// \param ShadowFlag Points to flag that is set if macro name shadows
2122
  ///                   a keyword.
2123
  ///
2124
  /// This emits a diagnostic, sets the token kind to eod,
2125
  /// and discards the rest of the macro line if the macro name is invalid.
2126
  void ReadMacroName(Token &MacroNameTok, MacroUse IsDefineUndef = MU_Other,
2127
                     bool *ShadowFlag = nullptr);
2128
2129
  /// ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
2130
  /// entire line) of the macro's tokens and adds them to MacroInfo, and while
2131
  /// doing so performs certain validity checks including (but not limited to):
2132
  ///   - # (stringization) is followed by a macro parameter
2133
  /// \param MacroNameTok - Token that represents the macro name
2134
  /// \param ImmediatelyAfterHeaderGuard - Macro follows an #ifdef header guard
2135
  ///
2136
  ///  Either returns a pointer to a MacroInfo object OR emits a diagnostic and
2137
  ///  returns a nullptr if an invalid sequence of tokens is encountered.
2138
  MacroInfo *ReadOptionalMacroParameterListAndBody(
2139
      const Token &MacroNameTok, bool ImmediatelyAfterHeaderGuard);
2140
2141
  /// The ( starting an argument list of a macro definition has just been read.
2142
  /// Lex the rest of the parameters and the closing ), updating \p MI with
2143
  /// what we learn and saving in \p LastTok the last token read.
2144
  /// Return true if an error occurs parsing the arg list.
2145
  bool ReadMacroParameterList(MacroInfo *MI, Token& LastTok);
2146
2147
  /// We just read a \#if or related directive and decided that the
2148
  /// subsequent tokens are in the \#if'd out portion of the
2149
  /// file.  Lex the rest of the file, until we see an \#endif.  If \p
2150
  /// FoundNonSkipPortion is true, then we have already emitted code for part of
2151
  /// this \#if directive, so \#else/\#elif blocks should never be entered. If
2152
  /// \p FoundElse is false, then \#else directives are ok, if not, then we have
2153
  /// already seen one so a \#else directive is a duplicate.  When this returns,
2154
  /// the caller can lex the first valid token.
2155
  void SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
2156
                                    SourceLocation IfTokenLoc,
2157
                                    bool FoundNonSkipPortion, bool FoundElse,
2158
                                    SourceLocation ElseLoc = SourceLocation());
2159
2160
  /// Information about the result for evaluating an expression for a
2161
  /// preprocessor directive.
2162
  struct DirectiveEvalResult {
2163
    /// Whether the expression was evaluated as true or not.
2164
    bool Conditional;
2165
2166
    /// True if the expression contained identifiers that were undefined.
2167
    bool IncludedUndefinedIds;
2168
2169
    /// The source range for the expression.
2170
    SourceRange ExprRange;
2171
  };
2172
2173
  /// Evaluate an integer constant expression that may occur after a
2174
  /// \#if or \#elif directive and return a \p DirectiveEvalResult object.
2175
  ///
2176
  /// If the expression is equivalent to "!defined(X)" return X in IfNDefMacro.
2177
  DirectiveEvalResult EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro);
2178
2179
  /// Install the standard preprocessor pragmas:
2180
  /// \#pragma GCC poison/system_header/dependency and \#pragma once.
2181
  void RegisterBuiltinPragmas();
2182
2183
  /// Register builtin macros such as __LINE__ with the identifier table.
2184
  void RegisterBuiltinMacros();
2185
2186
  /// If an identifier token is read that is to be expanded as a macro, handle
2187
  /// it and return the next token as 'Tok'.  If we lexed a token, return true;
2188
  /// otherwise the caller should lex again.
2189
  bool HandleMacroExpandedIdentifier(Token &Identifier, const MacroDefinition &MD);
2190
2191
  /// Cache macro expanded tokens for TokenLexers.
2192
  //
2193
  /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
2194
  /// going to lex in the cache and when it finishes the tokens are removed
2195
  /// from the end of the cache.
2196
  Token *cacheMacroExpandedTokens(TokenLexer *tokLexer,
2197
                                  ArrayRef<Token> tokens);
2198
2199
  void removeCachedMacroExpandedTokensOfLastLexer();
2200
2201
  /// Determine whether the next preprocessor token to be
2202
  /// lexed is a '('.  If so, consume the token and return true, if not, this
2203
  /// method should have no observable side-effect on the lexed tokens.
2204
  bool isNextPPTokenLParen();
2205
2206
  /// After reading "MACRO(", this method is invoked to read all of the formal
2207
  /// arguments specified for the macro invocation.  Returns null on error.
2208
  MacroArgs *ReadMacroCallArgumentList(Token &MacroName, MacroInfo *MI,
2209
                                       SourceLocation &MacroEnd);
2210
2211
  /// If an identifier token is read that is to be expanded
2212
  /// as a builtin macro, handle it and return the next token as 'Tok'.
2213
  void ExpandBuiltinMacro(Token &Tok);
2214
2215
  /// Read a \c _Pragma directive, slice it up, process it, then
2216
  /// return the first token after the directive.
2217
  /// This assumes that the \c _Pragma token has just been read into \p Tok.
2218
  void Handle_Pragma(Token &Tok);
2219
2220
  /// Like Handle_Pragma except the pragma text is not enclosed within
2221
  /// a string literal.
2222
  void HandleMicrosoft__pragma(Token &Tok);
2223
2224
  /// Add a lexer to the top of the include stack and
2225
  /// start lexing tokens from it instead of the current buffer.
2226
  void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir);
2227
2228
  /// Set the FileID for the preprocessor predefines.
2229
87.6k
  void setPredefinesFileID(FileID FID) {
2230
87.6k
    assert(PredefinesFileID.isInvalid() && "PredefinesFileID already set!");
2231
0
    PredefinesFileID = FID;
2232
87.6k
  }
2233
2234
  /// Set the FileID for the PCH through header.
2235
  void setPCHThroughHeaderFileID(FileID FID);
2236
2237
  /// Returns true if we are lexing from a file and not a
2238
  /// pragma or a macro.
2239
2.04M
  static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) {
2240
2.04M
    return L ? 
!L->isPragmaLexer()2.04M
:
P != nullptr19
;
2241
2.04M
  }
2242
2243
30.9k
  static bool IsFileLexer(const IncludeStackInfo& I) {
2244
30.9k
    return IsFileLexer(I.TheLexer.get(), I.ThePPLexer);
2245
30.9k
  }
2246
2247
2.00M
  bool IsFileLexer() const {
2248
2.00M
    return IsFileLexer(CurLexer.get(), CurPPLexer);
2249
2.00M
  }
2250
2251
  //===--------------------------------------------------------------------===//
2252
  // Caching stuff.
2253
  void CachingLex(Token &Result);
2254
2255
581M
  bool InCachingLexMode() const {
2256
    // If the Lexer pointers are 0 and IncludeMacroStack is empty, it means
2257
    // that we are past EOF, not that we are in CachingLex mode.
2258
581M
    return !CurPPLexer && 
!CurTokenLexer404M
&&
!IncludeMacroStack.empty()372M
;
2259
581M
  }
2260
2261
  void EnterCachingLexMode();
2262
  void EnterCachingLexModeUnchecked();
2263
2264
215M
  void ExitCachingLexMode() {
2265
215M
    if (InCachingLexMode())
2266
128M
      RemoveTopOfLexerStack();
2267
215M
  }
2268
2269
  const Token &PeekAhead(unsigned N);
2270
  void AnnotatePreviousCachedTokens(const Token &Tok);
2271
2272
  //===--------------------------------------------------------------------===//
2273
  /// Handle*Directive - implement the various preprocessor directives.  These
2274
  /// should side-effect the current preprocessor object so that the next call
2275
  /// to Lex() will return the appropriate token next.
2276
  void HandleLineDirective();
2277
  void HandleDigitDirective(Token &Tok);
2278
  void HandleUserDiagnosticDirective(Token &Tok, bool isWarning);
2279
  void HandleIdentSCCSDirective(Token &Tok);
2280
  void HandleMacroPublicDirective(Token &Tok);
2281
  void HandleMacroPrivateDirective();
2282
2283
  /// An additional notification that can be produced by a header inclusion or
2284
  /// import to tell the parser what happened.
2285
  struct ImportAction {
2286
    enum ActionKind {
2287
      None,
2288
      ModuleBegin,
2289
      ModuleImport,
2290
      SkippedModuleImport,
2291
      Failure,
2292
    } Kind;
2293
    Module *ModuleForHeader = nullptr;
2294
2295
    ImportAction(ActionKind AK, Module *Mod = nullptr)
2296
1.67M
        : Kind(AK), ModuleForHeader(Mod) {
2297
1.67M
      assert((AK == None || Mod || AK == Failure) &&
2298
1.67M
             "no module for module action");
2299
1.67M
    }
2300
  };
2301
2302
  Optional<FileEntryRef> LookupHeaderIncludeOrImport(
2303
      const DirectoryLookup **CurDir, StringRef &Filename,
2304
      SourceLocation FilenameLoc, CharSourceRange FilenameRange,
2305
      const Token &FilenameTok, bool &IsFrameworkFound, bool IsImportDecl,
2306
      bool &IsMapped, const DirectoryLookup *LookupFrom,
2307
      const FileEntry *LookupFromFile, StringRef &LookupFilename,
2308
      SmallVectorImpl<char> &RelativePath, SmallVectorImpl<char> &SearchPath,
2309
      ModuleMap::KnownHeader &SuggestedModule, bool isAngled);
2310
2311
  // File inclusion.
2312
  void HandleIncludeDirective(SourceLocation HashLoc, Token &Tok,
2313
                              const DirectoryLookup *LookupFrom = nullptr,
2314
                              const FileEntry *LookupFromFile = nullptr);
2315
  ImportAction
2316
  HandleHeaderIncludeOrImport(SourceLocation HashLoc, Token &IncludeTok,
2317
                              Token &FilenameTok, SourceLocation EndLoc,
2318
                              const DirectoryLookup *LookupFrom = nullptr,
2319
                              const FileEntry *LookupFromFile = nullptr);
2320
  void HandleIncludeNextDirective(SourceLocation HashLoc, Token &Tok);
2321
  void HandleIncludeMacrosDirective(SourceLocation HashLoc, Token &Tok);
2322
  void HandleImportDirective(SourceLocation HashLoc, Token &Tok);
2323
  void HandleMicrosoftImportDirective(Token &Tok);
2324
2325
public:
2326
  /// Check that the given module is available, producing a diagnostic if not.
2327
  /// \return \c true if the check failed (because the module is not available).
2328
  ///         \c false if the module appears to be usable.
2329
  static bool checkModuleIsAvailable(const LangOptions &LangOpts,
2330
                                     const TargetInfo &TargetInfo,
2331
                                     DiagnosticsEngine &Diags, Module *M);
2332
2333
  // Module inclusion testing.
2334
  /// Find the module that owns the source or header file that
2335
  /// \p Loc points to. If the location is in a file that was included
2336
  /// into a module, or is outside any module, returns nullptr.
2337
  Module *getModuleForLocation(SourceLocation Loc);
2338
2339
  /// We want to produce a diagnostic at location IncLoc concerning an
2340
  /// unreachable effect at location MLoc (eg, where a desired entity was
2341
  /// declared or defined). Determine whether the right way to make MLoc
2342
  /// reachable is by #include, and if so, what header should be included.
2343
  ///
2344
  /// This is not necessarily fast, and might load unexpected module maps, so
2345
  /// should only be called by code that intends to produce an error.
2346
  ///
2347
  /// \param IncLoc The location at which the missing effect was detected.
2348
  /// \param MLoc A location within an unimported module at which the desired
2349
  ///        effect occurred.
2350
  /// \return A file that can be #included to provide the desired effect. Null
2351
  ///         if no such file could be determined or if a #include is not
2352
  ///         appropriate (eg, if a module should be imported instead).
2353
  const FileEntry *getHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
2354
                                                    SourceLocation MLoc);
2355
2356
1.13M
  bool isRecordingPreamble() const {
2357
1.13M
    return PreambleConditionalStack.isRecording();
2358
1.13M
  }
2359
2360
91
  bool hasRecordedPreamble() const {
2361
91
    return PreambleConditionalStack.hasRecordedPreamble();
2362
91
  }
2363
2364
7
  ArrayRef<PPConditionalInfo> getPreambleConditionalStack() const {
2365
7
      return PreambleConditionalStack.getStack();
2366
7
  }
2367
2368
91
  void setRecordedPreambleConditionalStack(ArrayRef<PPConditionalInfo> s) {
2369
91
    PreambleConditionalStack.setStack(s);
2370
91
  }
2371
2372
  void setReplayablePreambleConditionalStack(ArrayRef<PPConditionalInfo> s,
2373
28
                                             llvm::Optional<PreambleSkipInfo> SkipInfo) {
2374
28
    PreambleConditionalStack.startReplaying();
2375
28
    PreambleConditionalStack.setStack(s);
2376
28
    PreambleConditionalStack.SkipInfo = SkipInfo;
2377
28
  }
2378
2379
7
  llvm::Optional<PreambleSkipInfo> getPreambleSkipInfo() const {
2380
7
    return PreambleConditionalStack.SkipInfo;
2381
7
  }
2382
2383
private:
2384
  /// After processing predefined file, initialize the conditional stack from
2385
  /// the preamble.
2386
  void replayPreambleConditionalStack();
2387
2388
  // Macro handling.
2389
  void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterHeaderGuard);
2390
  void HandleUndefDirective();
2391
2392
  // Conditional Inclusion.
2393
  void HandleIfdefDirective(Token &Result, const Token &HashToken,
2394
                            bool isIfndef, bool ReadAnyTokensBeforeDirective);
2395
  void HandleIfDirective(Token &IfToken, const Token &HashToken,
2396
                         bool ReadAnyTokensBeforeDirective);
2397
  void HandleEndifDirective(Token &EndifToken);
2398
  void HandleElseDirective(Token &Result, const Token &HashToken);
2399
  void HandleElifFamilyDirective(Token &ElifToken, const Token &HashToken,
2400
                                 tok::PPKeywordKind Kind);
2401
2402
  // Pragmas.
2403
  void HandlePragmaDirective(PragmaIntroducer Introducer);
2404
  void ResolvePragmaIncludeInstead(SourceLocation Location) const;
2405
2406
public:
2407
  void HandlePragmaOnce(Token &OnceTok);
2408
  void HandlePragmaMark(Token &MarkTok);
2409
  void HandlePragmaPoison();
2410
  void HandlePragmaSystemHeader(Token &SysHeaderTok);
2411
  void HandlePragmaIncludeInstead(Token &Tok);
2412
  void HandlePragmaDependency(Token &DependencyTok);
2413
  void HandlePragmaPushMacro(Token &Tok);
2414
  void HandlePragmaPopMacro(Token &Tok);
2415
  void HandlePragmaIncludeAlias(Token &Tok);
2416
  void HandlePragmaModuleBuild(Token &Tok);
2417
  void HandlePragmaHdrstop(Token &Tok);
2418
  IdentifierInfo *ParsePragmaPushOrPopMacro(Token &Tok);
2419
2420
  // Return true and store the first token only if any CommentHandler
2421
  // has inserted some tokens and getCommentRetentionState() is false.
2422
  bool HandleComment(Token &result, SourceRange Comment);
2423
2424
  /// A macro is used, update information about macros that need unused
2425
  /// warnings.
2426
  void markMacroAsUsed(MacroInfo *MI);
2427
2428
  void addMacroDeprecationMsg(const IdentifierInfo *II, std::string Msg,
2429
26
                              SourceLocation AnnotationLoc) {
2430
26
    auto Annotations = AnnotationInfos.find(II);
2431
26
    if (Annotations == AnnotationInfos.end())
2432
22
      AnnotationInfos.insert(std::make_pair(
2433
22
          II,
2434
22
          MacroAnnotations::makeDeprecation(AnnotationLoc, std::move(Msg))));
2435
4
    else
2436
4
      Annotations->second.DeprecationInfo =
2437
4
          MacroAnnotationInfo{AnnotationLoc, std::move(Msg)};
2438
26
  }
2439
2440
  void addRestrictExpansionMsg(const IdentifierInfo *II, std::string Msg,
2441
7
                               SourceLocation AnnotationLoc) {
2442
7
    auto Annotations = AnnotationInfos.find(II);
2443
7
    if (Annotations == AnnotationInfos.end())
2444
3
      AnnotationInfos.insert(
2445
3
          std::make_pair(II, MacroAnnotations::makeRestrictExpansion(
2446
3
                                 AnnotationLoc, std::move(Msg))));
2447
4
    else
2448
4
      Annotations->second.RestrictExpansionInfo =
2449
4
          MacroAnnotationInfo{AnnotationLoc, std::move(Msg)};
2450
7
  }
2451
2452
3
  void addFinalLoc(const IdentifierInfo *II, SourceLocation AnnotationLoc) {
2453
3
    auto Annotations = AnnotationInfos.find(II);
2454
3
    if (Annotations == AnnotationInfos.end())
2455
3
      AnnotationInfos.insert(
2456
3
          std::make_pair(II, MacroAnnotations::makeFinal(AnnotationLoc)));
2457
0
    else
2458
0
      Annotations->second.FinalAnnotationLoc = AnnotationLoc;
2459
3
  }
2460
2461
30
  const MacroAnnotations &getMacroAnnotations(const IdentifierInfo *II) const {
2462
30
    return AnnotationInfos.find(II)->second;
2463
30
  }
2464
2465
66.3M
  void emitMacroExpansionWarnings(const Token &Identifier) const {
2466
66.3M
    if (Identifier.getIdentifierInfo()->isDeprecatedMacro())
2467
14
      emitMacroDeprecationWarning(Identifier);
2468
2469
66.3M
    if (Identifier.getIdentifierInfo()->isRestrictExpansion() &&
2470
66.3M
        
!SourceMgr.isInMainFile(Identifier.getLocation())12
)
2471
10
      emitRestrictExpansionWarning(Identifier);
2472
66.3M
  }
2473
2474
private:
2475
  void emitMacroDeprecationWarning(const Token &Identifier) const;
2476
  void emitRestrictExpansionWarning(const Token &Identifier) const;
2477
  void emitFinalMacroWarning(const Token &Identifier, bool IsUndef) const;
2478
2479
  Optional<unsigned>
2480
  getSkippedRangeForExcludedConditionalBlock(SourceLocation HashLoc);
2481
2482
  /// Contains the currently active skipped range mappings for skipping excluded
2483
  /// conditional directives.
2484
  ExcludedPreprocessorDirectiveSkipMapping
2485
      *ExcludedConditionalDirectiveSkipMappings;
2486
};
2487
2488
/// Abstract base class that describes a handler that will receive
2489
/// source ranges for each of the comments encountered in the source file.
2490
class CommentHandler {
2491
public:
2492
  virtual ~CommentHandler();
2493
2494
  // The handler shall return true if it has pushed any tokens
2495
  // to be read using e.g. EnterToken or EnterTokenStream.
2496
  virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) = 0;
2497
};
2498
2499
/// Abstract base class that describes a handler that will receive
2500
/// source ranges for empty lines encountered in the source file.
2501
class EmptylineHandler {
2502
public:
2503
  virtual ~EmptylineHandler();
2504
2505
  // The handler handles empty lines.
2506
  virtual void HandleEmptyline(SourceRange Range) = 0;
2507
};
2508
2509
/// Registry of pragma handlers added by plugins
2510
using PragmaHandlerRegistry = llvm::Registry<PragmaHandler>;
2511
2512
} // namespace clang
2513
2514
#endif // LLVM_CLANG_LEX_PREPROCESSOR_H