Coverage Report

Created: 2021-08-24 07:12

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