Coverage Report

Created: 2020-09-19 12:23

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