Coverage Report

Created: 2021-01-19 06:58

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