1 //===- ASTReader.h - AST File Reader ----------------------------*- 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 //  This file defines the ASTReader class, which reads AST files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_SERIALIZATION_ASTREADER_H
14 #define LLVM_CLANG_SERIALIZATION_ASTREADER_H
15 
16 #include "clang/AST/Type.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/DiagnosticOptions.h"
19 #include "clang/Basic/IdentifierTable.h"
20 #include "clang/Basic/OpenCLOptions.h"
21 #include "clang/Basic/SourceLocation.h"
22 #include "clang/Basic/Version.h"
23 #include "clang/Lex/ExternalPreprocessorSource.h"
24 #include "clang/Lex/HeaderSearch.h"
25 #include "clang/Lex/PreprocessingRecord.h"
26 #include "clang/Sema/ExternalSemaSource.h"
27 #include "clang/Sema/IdentifierResolver.h"
28 #include "clang/Serialization/ASTBitCodes.h"
29 #include "clang/Serialization/ContinuousRangeMap.h"
30 #include "clang/Serialization/ModuleFile.h"
31 #include "clang/Serialization/ModuleFileExtension.h"
32 #include "clang/Serialization/ModuleManager.h"
33 #include "llvm/ADT/ArrayRef.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/DenseSet.h"
36 #include "llvm/ADT/IntrusiveRefCntPtr.h"
37 #include "llvm/ADT/MapVector.h"
38 #include "llvm/ADT/Optional.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/ADT/SetVector.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/StringMap.h"
44 #include "llvm/ADT/StringRef.h"
45 #include "llvm/ADT/iterator.h"
46 #include "llvm/ADT/iterator_range.h"
47 #include "llvm/Bitstream/BitstreamReader.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/Timer.h"
50 #include "llvm/Support/VersionTuple.h"
51 #include <cassert>
52 #include <cstddef>
53 #include <cstdint>
54 #include <ctime>
55 #include <deque>
56 #include <memory>
57 #include <set>
58 #include <string>
59 #include <utility>
60 #include <vector>
61 
62 namespace clang {
63 
64 class ASTConsumer;
65 class ASTContext;
66 class ASTDeserializationListener;
67 class ASTReader;
68 class ASTRecordReader;
69 class CXXTemporary;
70 class Decl;
71 class DeclarationName;
72 class DeclaratorDecl;
73 class DeclContext;
74 class EnumDecl;
75 class Expr;
76 class FieldDecl;
77 class FileEntry;
78 class FileManager;
79 class FileSystemOptions;
80 class FunctionDecl;
81 class GlobalModuleIndex;
82 struct HeaderFileInfo;
83 class HeaderSearchOptions;
84 class LangOptions;
85 class LazyASTUnresolvedSet;
86 class MacroInfo;
87 class InMemoryModuleCache;
88 class NamedDecl;
89 class NamespaceDecl;
90 class ObjCCategoryDecl;
91 class ObjCInterfaceDecl;
92 class PCHContainerReader;
93 class Preprocessor;
94 class PreprocessorOptions;
95 struct QualifierInfo;
96 class Sema;
97 class SourceManager;
98 class Stmt;
99 class SwitchCase;
100 class TargetOptions;
101 class Token;
102 class TypedefNameDecl;
103 class ValueDecl;
104 class VarDecl;
105 
106 /// Abstract interface for callback invocations by the ASTReader.
107 ///
108 /// While reading an AST file, the ASTReader will call the methods of the
109 /// listener to pass on specific information. Some of the listener methods can
110 /// return true to indicate to the ASTReader that the information (and
111 /// consequently the AST file) is invalid.
112 class ASTReaderListener {
113 public:
114   virtual ~ASTReaderListener();
115 
116   /// Receives the full Clang version information.
117   ///
118   /// \returns true to indicate that the version is invalid. Subclasses should
119   /// generally defer to this implementation.
ReadFullVersionInformation(StringRef FullVersion)120   virtual bool ReadFullVersionInformation(StringRef FullVersion) {
121     return FullVersion != getClangFullRepositoryVersion();
122   }
123 
ReadModuleName(StringRef ModuleName)124   virtual void ReadModuleName(StringRef ModuleName) {}
ReadModuleMapFile(StringRef ModuleMapPath)125   virtual void ReadModuleMapFile(StringRef ModuleMapPath) {}
126 
127   /// Receives the language options.
128   ///
129   /// \returns true to indicate the options are invalid or false otherwise.
ReadLanguageOptions(const LangOptions & LangOpts,bool Complain,bool AllowCompatibleDifferences)130   virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
131                                    bool Complain,
132                                    bool AllowCompatibleDifferences) {
133     return false;
134   }
135 
136   /// Receives the target options.
137   ///
138   /// \returns true to indicate the target options are invalid, or false
139   /// otherwise.
ReadTargetOptions(const TargetOptions & TargetOpts,bool Complain,bool AllowCompatibleDifferences)140   virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
141                                  bool AllowCompatibleDifferences) {
142     return false;
143   }
144 
145   /// Receives the diagnostic options.
146   ///
147   /// \returns true to indicate the diagnostic options are invalid, or false
148   /// otherwise.
149   virtual bool
ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,bool Complain)150   ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
151                         bool Complain) {
152     return false;
153   }
154 
155   /// Receives the file system options.
156   ///
157   /// \returns true to indicate the file system options are invalid, or false
158   /// otherwise.
ReadFileSystemOptions(const FileSystemOptions & FSOpts,bool Complain)159   virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
160                                      bool Complain) {
161     return false;
162   }
163 
164   /// Receives the header search options.
165   ///
166   /// \returns true to indicate the header search options are invalid, or false
167   /// otherwise.
ReadHeaderSearchOptions(const HeaderSearchOptions & HSOpts,StringRef SpecificModuleCachePath,bool Complain)168   virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
169                                        StringRef SpecificModuleCachePath,
170                                        bool Complain) {
171     return false;
172   }
173 
174   /// Receives the preprocessor options.
175   ///
176   /// \param SuggestedPredefines Can be filled in with the set of predefines
177   /// that are suggested by the preprocessor options. Typically only used when
178   /// loading a precompiled header.
179   ///
180   /// \returns true to indicate the preprocessor options are invalid, or false
181   /// otherwise.
ReadPreprocessorOptions(const PreprocessorOptions & PPOpts,bool Complain,std::string & SuggestedPredefines)182   virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
183                                        bool Complain,
184                                        std::string &SuggestedPredefines) {
185     return false;
186   }
187 
188   /// Receives __COUNTER__ value.
ReadCounter(const serialization::ModuleFile & M,unsigned Value)189   virtual void ReadCounter(const serialization::ModuleFile &M,
190                            unsigned Value) {}
191 
192   /// This is called for each AST file loaded.
visitModuleFile(StringRef Filename,serialization::ModuleKind Kind)193   virtual void visitModuleFile(StringRef Filename,
194                                serialization::ModuleKind Kind) {}
195 
196   /// Returns true if this \c ASTReaderListener wants to receive the
197   /// input files of the AST file via \c visitInputFile, false otherwise.
needsInputFileVisitation()198   virtual bool needsInputFileVisitation() { return false; }
199 
200   /// Returns true if this \c ASTReaderListener wants to receive the
201   /// system input files of the AST file via \c visitInputFile, false otherwise.
needsSystemInputFileVisitation()202   virtual bool needsSystemInputFileVisitation() { return false; }
203 
204   /// if \c needsInputFileVisitation returns true, this is called for
205   /// each non-system input file of the AST File. If
206   /// \c needsSystemInputFileVisitation is true, then it is called for all
207   /// system input files as well.
208   ///
209   /// \returns true to continue receiving the next input file, false to stop.
visitInputFile(StringRef Filename,bool isSystem,bool isOverridden,bool isExplicitModule)210   virtual bool visitInputFile(StringRef Filename, bool isSystem,
211                               bool isOverridden, bool isExplicitModule) {
212     return true;
213   }
214 
215   /// Returns true if this \c ASTReaderListener wants to receive the
216   /// imports of the AST file via \c visitImport, false otherwise.
needsImportVisitation()217   virtual bool needsImportVisitation() const { return false; }
218 
219   /// If needsImportVisitation returns \c true, this is called for each
220   /// AST file imported by this AST file.
visitImport(StringRef ModuleName,StringRef Filename)221   virtual void visitImport(StringRef ModuleName, StringRef Filename) {}
222 
223   /// Indicates that a particular module file extension has been read.
readModuleFileExtension(const ModuleFileExtensionMetadata & Metadata)224   virtual void readModuleFileExtension(
225                  const ModuleFileExtensionMetadata &Metadata) {}
226 };
227 
228 /// Simple wrapper class for chaining listeners.
229 class ChainedASTReaderListener : public ASTReaderListener {
230   std::unique_ptr<ASTReaderListener> First;
231   std::unique_ptr<ASTReaderListener> Second;
232 
233 public:
234   /// Takes ownership of \p First and \p Second.
ChainedASTReaderListener(std::unique_ptr<ASTReaderListener> First,std::unique_ptr<ASTReaderListener> Second)235   ChainedASTReaderListener(std::unique_ptr<ASTReaderListener> First,
236                            std::unique_ptr<ASTReaderListener> Second)
237       : First(std::move(First)), Second(std::move(Second)) {}
238 
takeFirst()239   std::unique_ptr<ASTReaderListener> takeFirst() { return std::move(First); }
takeSecond()240   std::unique_ptr<ASTReaderListener> takeSecond() { return std::move(Second); }
241 
242   bool ReadFullVersionInformation(StringRef FullVersion) override;
243   void ReadModuleName(StringRef ModuleName) override;
244   void ReadModuleMapFile(StringRef ModuleMapPath) override;
245   bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
246                            bool AllowCompatibleDifferences) override;
247   bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
248                          bool AllowCompatibleDifferences) override;
249   bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
250                              bool Complain) override;
251   bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
252                              bool Complain) override;
253 
254   bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
255                                StringRef SpecificModuleCachePath,
256                                bool Complain) override;
257   bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
258                                bool Complain,
259                                std::string &SuggestedPredefines) override;
260 
261   void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
262   bool needsInputFileVisitation() override;
263   bool needsSystemInputFileVisitation() override;
264   void visitModuleFile(StringRef Filename,
265                        serialization::ModuleKind Kind) override;
266   bool visitInputFile(StringRef Filename, bool isSystem,
267                       bool isOverridden, bool isExplicitModule) override;
268   void readModuleFileExtension(
269          const ModuleFileExtensionMetadata &Metadata) override;
270 };
271 
272 /// ASTReaderListener implementation to validate the information of
273 /// the PCH file against an initialized Preprocessor.
274 class PCHValidator : public ASTReaderListener {
275   Preprocessor &PP;
276   ASTReader &Reader;
277 
278 public:
PCHValidator(Preprocessor & PP,ASTReader & Reader)279   PCHValidator(Preprocessor &PP, ASTReader &Reader)
280       : PP(PP), Reader(Reader) {}
281 
282   bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
283                            bool AllowCompatibleDifferences) override;
284   bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
285                          bool AllowCompatibleDifferences) override;
286   bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
287                              bool Complain) override;
288   bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
289                                std::string &SuggestedPredefines) override;
290   bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
291                                StringRef SpecificModuleCachePath,
292                                bool Complain) override;
293   void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
294 
295 private:
296   void Error(const char *Msg);
297 };
298 
299 /// ASTReaderListenter implementation to set SuggestedPredefines of
300 /// ASTReader which is required to use a pch file. This is the replacement
301 /// of PCHValidator or SimplePCHValidator when using a pch file without
302 /// validating it.
303 class SimpleASTReaderListener : public ASTReaderListener {
304   Preprocessor &PP;
305 
306 public:
SimpleASTReaderListener(Preprocessor & PP)307   SimpleASTReaderListener(Preprocessor &PP) : PP(PP) {}
308 
309   bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
310                                std::string &SuggestedPredefines) override;
311 };
312 
313 namespace serialization {
314 
315 class ReadMethodPoolVisitor;
316 
317 namespace reader {
318 
319 class ASTIdentifierLookupTrait;
320 
321 /// The on-disk hash table(s) used for DeclContext name lookup.
322 struct DeclContextLookupTable;
323 
324 } // namespace reader
325 
326 } // namespace serialization
327 
328 /// Reads an AST files chain containing the contents of a translation
329 /// unit.
330 ///
331 /// The ASTReader class reads bitstreams (produced by the ASTWriter
332 /// class) containing the serialized representation of a given
333 /// abstract syntax tree and its supporting data structures. An
334 /// instance of the ASTReader can be attached to an ASTContext object,
335 /// which will provide access to the contents of the AST files.
336 ///
337 /// The AST reader provides lazy de-serialization of declarations, as
338 /// required when traversing the AST. Only those AST nodes that are
339 /// actually required will be de-serialized.
340 class ASTReader
341   : public ExternalPreprocessorSource,
342     public ExternalPreprocessingRecordSource,
343     public ExternalHeaderFileInfoSource,
344     public ExternalSemaSource,
345     public IdentifierInfoLookup,
346     public ExternalSLocEntrySource
347 {
348 public:
349   /// Types of AST files.
350   friend class ASTDeclReader;
351   friend class ASTIdentifierIterator;
352   friend class ASTRecordReader;
353   friend class ASTUnit; // ASTUnit needs to remap source locations.
354   friend class ASTWriter;
355   friend class PCHValidator;
356   friend class serialization::reader::ASTIdentifierLookupTrait;
357   friend class serialization::ReadMethodPoolVisitor;
358   friend class TypeLocReader;
359 
360   using RecordData = SmallVector<uint64_t, 64>;
361   using RecordDataImpl = SmallVectorImpl<uint64_t>;
362 
363   /// The result of reading the control block of an AST file, which
364   /// can fail for various reasons.
365   enum ASTReadResult {
366     /// The control block was read successfully. Aside from failures,
367     /// the AST file is safe to read into the current context.
368     Success,
369 
370     /// The AST file itself appears corrupted.
371     Failure,
372 
373     /// The AST file was missing.
374     Missing,
375 
376     /// The AST file is out-of-date relative to its input files,
377     /// and needs to be regenerated.
378     OutOfDate,
379 
380     /// The AST file was written by a different version of Clang.
381     VersionMismatch,
382 
383     /// The AST file was writtten with a different language/target
384     /// configuration.
385     ConfigurationMismatch,
386 
387     /// The AST file has errors.
388     HadErrors
389   };
390 
391   using ModuleFile = serialization::ModuleFile;
392   using ModuleKind = serialization::ModuleKind;
393   using ModuleManager = serialization::ModuleManager;
394   using ModuleIterator = ModuleManager::ModuleIterator;
395   using ModuleConstIterator = ModuleManager::ModuleConstIterator;
396   using ModuleReverseIterator = ModuleManager::ModuleReverseIterator;
397 
398 private:
399   /// The receiver of some callbacks invoked by ASTReader.
400   std::unique_ptr<ASTReaderListener> Listener;
401 
402   /// The receiver of deserialization events.
403   ASTDeserializationListener *DeserializationListener = nullptr;
404 
405   bool OwnsDeserializationListener = false;
406 
407   SourceManager &SourceMgr;
408   FileManager &FileMgr;
409   const PCHContainerReader &PCHContainerRdr;
410   DiagnosticsEngine &Diags;
411 
412   /// The semantic analysis object that will be processing the
413   /// AST files and the translation unit that uses it.
414   Sema *SemaObj = nullptr;
415 
416   /// The preprocessor that will be loading the source file.
417   Preprocessor &PP;
418 
419   /// The AST context into which we'll read the AST files.
420   ASTContext *ContextObj = nullptr;
421 
422   /// The AST consumer.
423   ASTConsumer *Consumer = nullptr;
424 
425   /// The module manager which manages modules and their dependencies
426   ModuleManager ModuleMgr;
427 
428   /// A dummy identifier resolver used to merge TU-scope declarations in
429   /// C, for the cases where we don't have a Sema object to provide a real
430   /// identifier resolver.
431   IdentifierResolver DummyIdResolver;
432 
433   /// A mapping from extension block names to module file extensions.
434   llvm::StringMap<std::shared_ptr<ModuleFileExtension>> ModuleFileExtensions;
435 
436   /// A timer used to track the time spent deserializing.
437   std::unique_ptr<llvm::Timer> ReadTimer;
438 
439   /// The location where the module file will be considered as
440   /// imported from. For non-module AST types it should be invalid.
441   SourceLocation CurrentImportLoc;
442 
443   /// The global module index, if loaded.
444   std::unique_ptr<GlobalModuleIndex> GlobalIndex;
445 
446   /// A map of global bit offsets to the module that stores entities
447   /// at those bit offsets.
448   ContinuousRangeMap<uint64_t, ModuleFile*, 4> GlobalBitOffsetsMap;
449 
450   /// A map of negated SLocEntryIDs to the modules containing them.
451   ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocEntryMap;
452 
453   using GlobalSLocOffsetMapType =
454       ContinuousRangeMap<unsigned, ModuleFile *, 64>;
455 
456   /// A map of reversed (SourceManager::MaxLoadedOffset - SLocOffset)
457   /// SourceLocation offsets to the modules containing them.
458   GlobalSLocOffsetMapType GlobalSLocOffsetMap;
459 
460   /// Types that have already been loaded from the chain.
461   ///
462   /// When the pointer at index I is non-NULL, the type with
463   /// ID = (I + 1) << FastQual::Width has already been loaded
464   std::vector<QualType> TypesLoaded;
465 
466   using GlobalTypeMapType =
467       ContinuousRangeMap<serialization::TypeID, ModuleFile *, 4>;
468 
469   /// Mapping from global type IDs to the module in which the
470   /// type resides along with the offset that should be added to the
471   /// global type ID to produce a local ID.
472   GlobalTypeMapType GlobalTypeMap;
473 
474   /// Declarations that have already been loaded from the chain.
475   ///
476   /// When the pointer at index I is non-NULL, the declaration with ID
477   /// = I + 1 has already been loaded.
478   std::vector<Decl *> DeclsLoaded;
479 
480   using GlobalDeclMapType =
481       ContinuousRangeMap<serialization::DeclID, ModuleFile *, 4>;
482 
483   /// Mapping from global declaration IDs to the module in which the
484   /// declaration resides.
485   GlobalDeclMapType GlobalDeclMap;
486 
487   using FileOffset = std::pair<ModuleFile *, uint64_t>;
488   using FileOffsetsTy = SmallVector<FileOffset, 2>;
489   using DeclUpdateOffsetsMap =
490       llvm::DenseMap<serialization::DeclID, FileOffsetsTy>;
491 
492   /// Declarations that have modifications residing in a later file
493   /// in the chain.
494   DeclUpdateOffsetsMap DeclUpdateOffsets;
495 
496   struct PendingUpdateRecord {
497     Decl *D;
498     serialization::GlobalDeclID ID;
499 
500     // Whether the declaration was just deserialized.
501     bool JustLoaded;
502 
PendingUpdateRecordPendingUpdateRecord503     PendingUpdateRecord(serialization::GlobalDeclID ID, Decl *D,
504                         bool JustLoaded)
505         : D(D), ID(ID), JustLoaded(JustLoaded) {}
506   };
507 
508   /// Declaration updates for already-loaded declarations that we need
509   /// to apply once we finish processing an import.
510   llvm::SmallVector<PendingUpdateRecord, 16> PendingUpdateRecords;
511 
512   enum class PendingFakeDefinitionKind { NotFake, Fake, FakeLoaded };
513 
514   /// The DefinitionData pointers that we faked up for class definitions
515   /// that we needed but hadn't loaded yet.
516   llvm::DenseMap<void *, PendingFakeDefinitionKind> PendingFakeDefinitionData;
517 
518   /// Exception specification updates that have been loaded but not yet
519   /// propagated across the relevant redeclaration chain. The map key is the
520   /// canonical declaration (used only for deduplication) and the value is a
521   /// declaration that has an exception specification.
522   llvm::SmallMapVector<Decl *, FunctionDecl *, 4> PendingExceptionSpecUpdates;
523 
524   /// Deduced return type updates that have been loaded but not yet propagated
525   /// across the relevant redeclaration chain. The map key is the canonical
526   /// declaration and the value is the deduced return type.
527   llvm::SmallMapVector<FunctionDecl *, QualType, 4> PendingDeducedTypeUpdates;
528 
529   /// Declarations that have been imported and have typedef names for
530   /// linkage purposes.
531   llvm::DenseMap<std::pair<DeclContext *, IdentifierInfo *>, NamedDecl *>
532       ImportedTypedefNamesForLinkage;
533 
534   /// Mergeable declaration contexts that have anonymous declarations
535   /// within them, and those anonymous declarations.
536   llvm::DenseMap<Decl*, llvm::SmallVector<NamedDecl*, 2>>
537     AnonymousDeclarationsForMerging;
538 
539   /// Key used to identify LifetimeExtendedTemporaryDecl for merging,
540   /// containing the lifetime-extending declaration and the mangling number.
541   using LETemporaryKey = std::pair<Decl *, unsigned>;
542 
543   /// Map of already deserialiazed temporaries.
544   llvm::DenseMap<LETemporaryKey, LifetimeExtendedTemporaryDecl *>
545       LETemporaryForMerging;
546 
547   struct FileDeclsInfo {
548     ModuleFile *Mod = nullptr;
549     ArrayRef<serialization::LocalDeclID> Decls;
550 
551     FileDeclsInfo() = default;
FileDeclsInfoFileDeclsInfo552     FileDeclsInfo(ModuleFile *Mod, ArrayRef<serialization::LocalDeclID> Decls)
553         : Mod(Mod), Decls(Decls) {}
554   };
555 
556   /// Map from a FileID to the file-level declarations that it contains.
557   llvm::DenseMap<FileID, FileDeclsInfo> FileDeclIDs;
558 
559   /// An array of lexical contents of a declaration context, as a sequence of
560   /// Decl::Kind, DeclID pairs.
561   using LexicalContents = ArrayRef<llvm::support::unaligned_uint32_t>;
562 
563   /// Map from a DeclContext to its lexical contents.
564   llvm::DenseMap<const DeclContext*, std::pair<ModuleFile*, LexicalContents>>
565       LexicalDecls;
566 
567   /// Map from the TU to its lexical contents from each module file.
568   std::vector<std::pair<ModuleFile*, LexicalContents>> TULexicalDecls;
569 
570   /// Map from a DeclContext to its lookup tables.
571   llvm::DenseMap<const DeclContext *,
572                  serialization::reader::DeclContextLookupTable> Lookups;
573 
574   // Updates for visible decls can occur for other contexts than just the
575   // TU, and when we read those update records, the actual context may not
576   // be available yet, so have this pending map using the ID as a key. It
577   // will be realized when the context is actually loaded.
578   struct PendingVisibleUpdate {
579     ModuleFile *Mod;
580     const unsigned char *Data;
581   };
582   using DeclContextVisibleUpdates = SmallVector<PendingVisibleUpdate, 1>;
583 
584   /// Updates to the visible declarations of declaration contexts that
585   /// haven't been loaded yet.
586   llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates>
587       PendingVisibleUpdates;
588 
589   /// The set of C++ or Objective-C classes that have forward
590   /// declarations that have not yet been linked to their definitions.
591   llvm::SmallPtrSet<Decl *, 4> PendingDefinitions;
592 
593   using PendingBodiesMap =
594       llvm::MapVector<Decl *, uint64_t,
595                       llvm::SmallDenseMap<Decl *, unsigned, 4>,
596                       SmallVector<std::pair<Decl *, uint64_t>, 4>>;
597 
598   /// Functions or methods that have bodies that will be attached.
599   PendingBodiesMap PendingBodies;
600 
601   /// Definitions for which we have added merged definitions but not yet
602   /// performed deduplication.
603   llvm::SetVector<NamedDecl *> PendingMergedDefinitionsToDeduplicate;
604 
605   /// Read the record that describes the lexical contents of a DC.
606   bool ReadLexicalDeclContextStorage(ModuleFile &M,
607                                      llvm::BitstreamCursor &Cursor,
608                                      uint64_t Offset, DeclContext *DC);
609 
610   /// Read the record that describes the visible contents of a DC.
611   bool ReadVisibleDeclContextStorage(ModuleFile &M,
612                                      llvm::BitstreamCursor &Cursor,
613                                      uint64_t Offset, serialization::DeclID ID);
614 
615   /// A vector containing identifiers that have already been
616   /// loaded.
617   ///
618   /// If the pointer at index I is non-NULL, then it refers to the
619   /// IdentifierInfo for the identifier with ID=I+1 that has already
620   /// been loaded.
621   std::vector<IdentifierInfo *> IdentifiersLoaded;
622 
623   using GlobalIdentifierMapType =
624       ContinuousRangeMap<serialization::IdentID, ModuleFile *, 4>;
625 
626   /// Mapping from global identifier IDs to the module in which the
627   /// identifier resides along with the offset that should be added to the
628   /// global identifier ID to produce a local ID.
629   GlobalIdentifierMapType GlobalIdentifierMap;
630 
631   /// A vector containing macros that have already been
632   /// loaded.
633   ///
634   /// If the pointer at index I is non-NULL, then it refers to the
635   /// MacroInfo for the identifier with ID=I+1 that has already
636   /// been loaded.
637   std::vector<MacroInfo *> MacrosLoaded;
638 
639   using LoadedMacroInfo =
640       std::pair<IdentifierInfo *, serialization::SubmoduleID>;
641 
642   /// A set of #undef directives that we have loaded; used to
643   /// deduplicate the same #undef information coming from multiple module
644   /// files.
645   llvm::DenseSet<LoadedMacroInfo> LoadedUndefs;
646 
647   using GlobalMacroMapType =
648       ContinuousRangeMap<serialization::MacroID, ModuleFile *, 4>;
649 
650   /// Mapping from global macro IDs to the module in which the
651   /// macro resides along with the offset that should be added to the
652   /// global macro ID to produce a local ID.
653   GlobalMacroMapType GlobalMacroMap;
654 
655   /// A vector containing submodules that have already been loaded.
656   ///
657   /// This vector is indexed by the Submodule ID (-1). NULL submodule entries
658   /// indicate that the particular submodule ID has not yet been loaded.
659   SmallVector<Module *, 2> SubmodulesLoaded;
660 
661   using GlobalSubmoduleMapType =
662       ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4>;
663 
664   /// Mapping from global submodule IDs to the module file in which the
665   /// submodule resides along with the offset that should be added to the
666   /// global submodule ID to produce a local ID.
667   GlobalSubmoduleMapType GlobalSubmoduleMap;
668 
669   /// A set of hidden declarations.
670   using HiddenNames = SmallVector<Decl *, 2>;
671   using HiddenNamesMapType = llvm::DenseMap<Module *, HiddenNames>;
672 
673   /// A mapping from each of the hidden submodules to the deserialized
674   /// declarations in that submodule that could be made visible.
675   HiddenNamesMapType HiddenNamesMap;
676 
677   /// A module import, export, or conflict that hasn't yet been resolved.
678   struct UnresolvedModuleRef {
679     /// The file in which this module resides.
680     ModuleFile *File;
681 
682     /// The module that is importing or exporting.
683     Module *Mod;
684 
685     /// The kind of module reference.
686     enum { Import, Export, Conflict } Kind;
687 
688     /// The local ID of the module that is being exported.
689     unsigned ID;
690 
691     /// Whether this is a wildcard export.
692     unsigned IsWildcard : 1;
693 
694     /// String data.
695     StringRef String;
696   };
697 
698   /// The set of module imports and exports that still need to be
699   /// resolved.
700   SmallVector<UnresolvedModuleRef, 2> UnresolvedModuleRefs;
701 
702   /// A vector containing selectors that have already been loaded.
703   ///
704   /// This vector is indexed by the Selector ID (-1). NULL selector
705   /// entries indicate that the particular selector ID has not yet
706   /// been loaded.
707   SmallVector<Selector, 16> SelectorsLoaded;
708 
709   using GlobalSelectorMapType =
710       ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4>;
711 
712   /// Mapping from global selector IDs to the module in which the
713   /// global selector ID to produce a local ID.
714   GlobalSelectorMapType GlobalSelectorMap;
715 
716   /// The generation number of the last time we loaded data from the
717   /// global method pool for this selector.
718   llvm::DenseMap<Selector, unsigned> SelectorGeneration;
719 
720   /// Whether a selector is out of date. We mark a selector as out of date
721   /// if we load another module after the method pool entry was pulled in.
722   llvm::DenseMap<Selector, bool> SelectorOutOfDate;
723 
724   struct PendingMacroInfo {
725     ModuleFile *M;
726     /// Offset relative to ModuleFile::MacroOffsetsBase.
727     uint32_t MacroDirectivesOffset;
728 
PendingMacroInfoPendingMacroInfo729     PendingMacroInfo(ModuleFile *M, uint32_t MacroDirectivesOffset)
730         : M(M), MacroDirectivesOffset(MacroDirectivesOffset) {}
731   };
732 
733   using PendingMacroIDsMap =
734       llvm::MapVector<IdentifierInfo *, SmallVector<PendingMacroInfo, 2>>;
735 
736   /// Mapping from identifiers that have a macro history to the global
737   /// IDs have not yet been deserialized to the global IDs of those macros.
738   PendingMacroIDsMap PendingMacroIDs;
739 
740   using GlobalPreprocessedEntityMapType =
741       ContinuousRangeMap<unsigned, ModuleFile *, 4>;
742 
743   /// Mapping from global preprocessing entity IDs to the module in
744   /// which the preprocessed entity resides along with the offset that should be
745   /// added to the global preprocessing entity ID to produce a local ID.
746   GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap;
747 
748   using GlobalSkippedRangeMapType =
749       ContinuousRangeMap<unsigned, ModuleFile *, 4>;
750 
751   /// Mapping from global skipped range base IDs to the module in which
752   /// the skipped ranges reside.
753   GlobalSkippedRangeMapType GlobalSkippedRangeMap;
754 
755   /// \name CodeGen-relevant special data
756   /// Fields containing data that is relevant to CodeGen.
757   //@{
758 
759   /// The IDs of all declarations that fulfill the criteria of
760   /// "interesting" decls.
761   ///
762   /// This contains the data loaded from all EAGERLY_DESERIALIZED_DECLS blocks
763   /// in the chain. The referenced declarations are deserialized and passed to
764   /// the consumer eagerly.
765   SmallVector<uint64_t, 16> EagerlyDeserializedDecls;
766 
767   /// The IDs of all tentative definitions stored in the chain.
768   ///
769   /// Sema keeps track of all tentative definitions in a TU because it has to
770   /// complete them and pass them on to CodeGen. Thus, tentative definitions in
771   /// the PCH chain must be eagerly deserialized.
772   SmallVector<uint64_t, 16> TentativeDefinitions;
773 
774   /// The IDs of all CXXRecordDecls stored in the chain whose VTables are
775   /// used.
776   ///
777   /// CodeGen has to emit VTables for these records, so they have to be eagerly
778   /// deserialized.
779   SmallVector<uint64_t, 64> VTableUses;
780 
781   /// A snapshot of the pending instantiations in the chain.
782   ///
783   /// This record tracks the instantiations that Sema has to perform at the
784   /// end of the TU. It consists of a pair of values for every pending
785   /// instantiation where the first value is the ID of the decl and the second
786   /// is the instantiation location.
787   SmallVector<uint64_t, 64> PendingInstantiations;
788 
789   //@}
790 
791   /// \name DiagnosticsEngine-relevant special data
792   /// Fields containing data that is used for generating diagnostics
793   //@{
794 
795   /// A snapshot of Sema's unused file-scoped variable tracking, for
796   /// generating warnings.
797   SmallVector<uint64_t, 16> UnusedFileScopedDecls;
798 
799   /// A list of all the delegating constructors we've seen, to diagnose
800   /// cycles.
801   SmallVector<uint64_t, 4> DelegatingCtorDecls;
802 
803   /// Method selectors used in a @selector expression. Used for
804   /// implementation of -Wselector.
805   SmallVector<uint64_t, 64> ReferencedSelectorsData;
806 
807   /// A snapshot of Sema's weak undeclared identifier tracking, for
808   /// generating warnings.
809   SmallVector<uint64_t, 64> WeakUndeclaredIdentifiers;
810 
811   /// The IDs of type aliases for ext_vectors that exist in the chain.
812   ///
813   /// Used by Sema for finding sugared names for ext_vectors in diagnostics.
814   SmallVector<uint64_t, 4> ExtVectorDecls;
815 
816   //@}
817 
818   /// \name Sema-relevant special data
819   /// Fields containing data that is used for semantic analysis
820   //@{
821 
822   /// The IDs of all potentially unused typedef names in the chain.
823   ///
824   /// Sema tracks these to emit warnings.
825   SmallVector<uint64_t, 16> UnusedLocalTypedefNameCandidates;
826 
827   /// Our current depth in #pragma cuda force_host_device begin/end
828   /// macros.
829   unsigned ForceCUDAHostDeviceDepth = 0;
830 
831   /// The IDs of the declarations Sema stores directly.
832   ///
833   /// Sema tracks a few important decls, such as namespace std, directly.
834   SmallVector<uint64_t, 4> SemaDeclRefs;
835 
836   /// The IDs of the types ASTContext stores directly.
837   ///
838   /// The AST context tracks a few important types, such as va_list, directly.
839   SmallVector<uint64_t, 16> SpecialTypes;
840 
841   /// The IDs of CUDA-specific declarations ASTContext stores directly.
842   ///
843   /// The AST context tracks a few important decls, currently cudaConfigureCall,
844   /// directly.
845   SmallVector<uint64_t, 2> CUDASpecialDeclRefs;
846 
847   /// The floating point pragma option settings.
848   SmallVector<uint64_t, 1> FPPragmaOptions;
849 
850   /// The pragma clang optimize location (if the pragma state is "off").
851   SourceLocation OptimizeOffPragmaLocation;
852 
853   /// The PragmaMSStructKind pragma ms_struct state if set, or -1.
854   int PragmaMSStructState = -1;
855 
856   /// The PragmaMSPointersToMembersKind pragma pointers_to_members state.
857   int PragmaMSPointersToMembersState = -1;
858   SourceLocation PointersToMembersPragmaLocation;
859 
860   /// The pragma float_control state.
861   Optional<unsigned> FpPragmaCurrentValue;
862   SourceLocation FpPragmaCurrentLocation;
863   struct FpPragmaStackEntry {
864     unsigned Value;
865     SourceLocation Location;
866     SourceLocation PushLocation;
867     StringRef SlotLabel;
868   };
869   llvm::SmallVector<FpPragmaStackEntry, 2> FpPragmaStack;
870   llvm::SmallVector<std::string, 2> FpPragmaStrings;
871 
872   /// The pragma pack state.
873   Optional<unsigned> PragmaPackCurrentValue;
874   SourceLocation PragmaPackCurrentLocation;
875   struct PragmaPackStackEntry {
876     unsigned Value;
877     SourceLocation Location;
878     SourceLocation PushLocation;
879     StringRef SlotLabel;
880   };
881   llvm::SmallVector<PragmaPackStackEntry, 2> PragmaPackStack;
882   llvm::SmallVector<std::string, 2> PragmaPackStrings;
883 
884   /// The OpenCL extension settings.
885   OpenCLOptions OpenCLExtensions;
886 
887   /// Extensions required by an OpenCL type.
888   llvm::DenseMap<const Type *, std::set<std::string>> OpenCLTypeExtMap;
889 
890   /// Extensions required by an OpenCL declaration.
891   llvm::DenseMap<const Decl *, std::set<std::string>> OpenCLDeclExtMap;
892 
893   /// A list of the namespaces we've seen.
894   SmallVector<uint64_t, 4> KnownNamespaces;
895 
896   /// A list of undefined decls with internal linkage followed by the
897   /// SourceLocation of a matching ODR-use.
898   SmallVector<uint64_t, 8> UndefinedButUsed;
899 
900   /// Delete expressions to analyze at the end of translation unit.
901   SmallVector<uint64_t, 8> DelayedDeleteExprs;
902 
903   // A list of late parsed template function data.
904   SmallVector<uint64_t, 1> LateParsedTemplates;
905 
906   /// The IDs of all decls to be checked for deferred diags.
907   ///
908   /// Sema tracks these to emit deferred diags.
909   SmallVector<uint64_t, 4> DeclsToCheckForDeferredDiags;
910 
911 
912 public:
913   struct ImportedSubmodule {
914     serialization::SubmoduleID ID;
915     SourceLocation ImportLoc;
916 
ImportedSubmoduleImportedSubmodule917     ImportedSubmodule(serialization::SubmoduleID ID, SourceLocation ImportLoc)
918         : ID(ID), ImportLoc(ImportLoc) {}
919   };
920 
921 private:
922   /// A list of modules that were imported by precompiled headers or
923   /// any other non-module AST file.
924   SmallVector<ImportedSubmodule, 2> ImportedModules;
925   //@}
926 
927   /// The system include root to be used when loading the
928   /// precompiled header.
929   std::string isysroot;
930 
931   /// Whether to disable the normal validation performed on precompiled
932   /// headers when they are loaded.
933   bool DisableValidation;
934 
935   /// Whether to accept an AST file with compiler errors.
936   bool AllowASTWithCompilerErrors;
937 
938   /// Whether to accept an AST file that has a different configuration
939   /// from the current compiler instance.
940   bool AllowConfigurationMismatch;
941 
942   /// Whether validate system input files.
943   bool ValidateSystemInputs;
944 
945   /// Whether validate headers and module maps using hash based on contents.
946   bool ValidateASTInputFilesContent;
947 
948   /// Whether we are allowed to use the global module index.
949   bool UseGlobalIndex;
950 
951   /// Whether we have tried loading the global module index yet.
952   bool TriedLoadingGlobalIndex = false;
953 
954   ///Whether we are currently processing update records.
955   bool ProcessingUpdateRecords = false;
956 
957   using SwitchCaseMapTy = llvm::DenseMap<unsigned, SwitchCase *>;
958 
959   /// Mapping from switch-case IDs in the chain to switch-case statements
960   ///
961   /// Statements usually don't have IDs, but switch cases need them, so that the
962   /// switch statement can refer to them.
963   SwitchCaseMapTy SwitchCaseStmts;
964 
965   SwitchCaseMapTy *CurrSwitchCaseStmts;
966 
967   /// The number of source location entries de-serialized from
968   /// the PCH file.
969   unsigned NumSLocEntriesRead = 0;
970 
971   /// The number of source location entries in the chain.
972   unsigned TotalNumSLocEntries = 0;
973 
974   /// The number of statements (and expressions) de-serialized
975   /// from the chain.
976   unsigned NumStatementsRead = 0;
977 
978   /// The total number of statements (and expressions) stored
979   /// in the chain.
980   unsigned TotalNumStatements = 0;
981 
982   /// The number of macros de-serialized from the chain.
983   unsigned NumMacrosRead = 0;
984 
985   /// The total number of macros stored in the chain.
986   unsigned TotalNumMacros = 0;
987 
988   /// The number of lookups into identifier tables.
989   unsigned NumIdentifierLookups = 0;
990 
991   /// The number of lookups into identifier tables that succeed.
992   unsigned NumIdentifierLookupHits = 0;
993 
994   /// The number of selectors that have been read.
995   unsigned NumSelectorsRead = 0;
996 
997   /// The number of method pool entries that have been read.
998   unsigned NumMethodPoolEntriesRead = 0;
999 
1000   /// The number of times we have looked up a selector in the method
1001   /// pool.
1002   unsigned NumMethodPoolLookups = 0;
1003 
1004   /// The number of times we have looked up a selector in the method
1005   /// pool and found something.
1006   unsigned NumMethodPoolHits = 0;
1007 
1008   /// The number of times we have looked up a selector in the method
1009   /// pool within a specific module.
1010   unsigned NumMethodPoolTableLookups = 0;
1011 
1012   /// The number of times we have looked up a selector in the method
1013   /// pool within a specific module and found something.
1014   unsigned NumMethodPoolTableHits = 0;
1015 
1016   /// The total number of method pool entries in the selector table.
1017   unsigned TotalNumMethodPoolEntries = 0;
1018 
1019   /// Number of lexical decl contexts read/total.
1020   unsigned NumLexicalDeclContextsRead = 0, TotalLexicalDeclContexts = 0;
1021 
1022   /// Number of visible decl contexts read/total.
1023   unsigned NumVisibleDeclContextsRead = 0, TotalVisibleDeclContexts = 0;
1024 
1025   /// Total size of modules, in bits, currently loaded
1026   uint64_t TotalModulesSizeInBits = 0;
1027 
1028   /// Number of Decl/types that are currently deserializing.
1029   unsigned NumCurrentElementsDeserializing = 0;
1030 
1031   /// Set true while we are in the process of passing deserialized
1032   /// "interesting" decls to consumer inside FinishedDeserializing().
1033   /// This is used as a guard to avoid recursively repeating the process of
1034   /// passing decls to consumer.
1035   bool PassingDeclsToConsumer = false;
1036 
1037   /// The set of identifiers that were read while the AST reader was
1038   /// (recursively) loading declarations.
1039   ///
1040   /// The declarations on the identifier chain for these identifiers will be
1041   /// loaded once the recursive loading has completed.
1042   llvm::MapVector<IdentifierInfo *, SmallVector<uint32_t, 4>>
1043     PendingIdentifierInfos;
1044 
1045   /// The set of lookup results that we have faked in order to support
1046   /// merging of partially deserialized decls but that we have not yet removed.
1047   llvm::SmallMapVector<IdentifierInfo *, SmallVector<NamedDecl*, 2>, 16>
1048     PendingFakeLookupResults;
1049 
1050   /// The generation number of each identifier, which keeps track of
1051   /// the last time we loaded information about this identifier.
1052   llvm::DenseMap<IdentifierInfo *, unsigned> IdentifierGeneration;
1053 
1054   class InterestingDecl {
1055     Decl *D;
1056     bool DeclHasPendingBody;
1057 
1058   public:
InterestingDecl(Decl * D,bool HasBody)1059     InterestingDecl(Decl *D, bool HasBody)
1060         : D(D), DeclHasPendingBody(HasBody) {}
1061 
getDecl()1062     Decl *getDecl() { return D; }
1063 
1064     /// Whether the declaration has a pending body.
hasPendingBody()1065     bool hasPendingBody() { return DeclHasPendingBody; }
1066   };
1067 
1068   /// Contains declarations and definitions that could be
1069   /// "interesting" to the ASTConsumer, when we get that AST consumer.
1070   ///
1071   /// "Interesting" declarations are those that have data that may
1072   /// need to be emitted, such as inline function definitions or
1073   /// Objective-C protocols.
1074   std::deque<InterestingDecl> PotentiallyInterestingDecls;
1075 
1076   /// The list of deduced function types that we have not yet read, because
1077   /// they might contain a deduced return type that refers to a local type
1078   /// declared within the function.
1079   SmallVector<std::pair<FunctionDecl *, serialization::TypeID>, 16>
1080       PendingFunctionTypes;
1081 
1082   /// The list of redeclaration chains that still need to be
1083   /// reconstructed, and the local offset to the corresponding list
1084   /// of redeclarations.
1085   SmallVector<std::pair<Decl *, uint64_t>, 16> PendingDeclChains;
1086 
1087   /// The list of canonical declarations whose redeclaration chains
1088   /// need to be marked as incomplete once we're done deserializing things.
1089   SmallVector<Decl *, 16> PendingIncompleteDeclChains;
1090 
1091   /// The Decl IDs for the Sema/Lexical DeclContext of a Decl that has
1092   /// been loaded but its DeclContext was not set yet.
1093   struct PendingDeclContextInfo {
1094     Decl *D;
1095     serialization::GlobalDeclID SemaDC;
1096     serialization::GlobalDeclID LexicalDC;
1097   };
1098 
1099   /// The set of Decls that have been loaded but their DeclContexts are
1100   /// not set yet.
1101   ///
1102   /// The DeclContexts for these Decls will be set once recursive loading has
1103   /// been completed.
1104   std::deque<PendingDeclContextInfo> PendingDeclContextInfos;
1105 
1106   /// The set of NamedDecls that have been loaded, but are members of a
1107   /// context that has been merged into another context where the corresponding
1108   /// declaration is either missing or has not yet been loaded.
1109   ///
1110   /// We will check whether the corresponding declaration is in fact missing
1111   /// once recursing loading has been completed.
1112   llvm::SmallVector<NamedDecl *, 16> PendingOdrMergeChecks;
1113 
1114   using DataPointers =
1115       std::pair<CXXRecordDecl *, struct CXXRecordDecl::DefinitionData *>;
1116 
1117   /// Record definitions in which we found an ODR violation.
1118   llvm::SmallDenseMap<CXXRecordDecl *, llvm::SmallVector<DataPointers, 2>, 2>
1119       PendingOdrMergeFailures;
1120 
1121   /// Function definitions in which we found an ODR violation.
1122   llvm::SmallDenseMap<FunctionDecl *, llvm::SmallVector<FunctionDecl *, 2>, 2>
1123       PendingFunctionOdrMergeFailures;
1124 
1125   /// Enum definitions in which we found an ODR violation.
1126   llvm::SmallDenseMap<EnumDecl *, llvm::SmallVector<EnumDecl *, 2>, 2>
1127       PendingEnumOdrMergeFailures;
1128 
1129   /// DeclContexts in which we have diagnosed an ODR violation.
1130   llvm::SmallPtrSet<DeclContext*, 2> DiagnosedOdrMergeFailures;
1131 
1132   /// The set of Objective-C categories that have been deserialized
1133   /// since the last time the declaration chains were linked.
1134   llvm::SmallPtrSet<ObjCCategoryDecl *, 16> CategoriesDeserialized;
1135 
1136   /// The set of Objective-C class definitions that have already been
1137   /// loaded, for which we will need to check for categories whenever a new
1138   /// module is loaded.
1139   SmallVector<ObjCInterfaceDecl *, 16> ObjCClassesLoaded;
1140 
1141   using KeyDeclsMap =
1142       llvm::DenseMap<Decl *, SmallVector<serialization::DeclID, 2>>;
1143 
1144   /// A mapping from canonical declarations to the set of global
1145   /// declaration IDs for key declaration that have been merged with that
1146   /// canonical declaration. A key declaration is a formerly-canonical
1147   /// declaration whose module did not import any other key declaration for that
1148   /// entity. These are the IDs that we use as keys when finding redecl chains.
1149   KeyDeclsMap KeyDecls;
1150 
1151   /// A mapping from DeclContexts to the semantic DeclContext that we
1152   /// are treating as the definition of the entity. This is used, for instance,
1153   /// when merging implicit instantiations of class templates across modules.
1154   llvm::DenseMap<DeclContext *, DeclContext *> MergedDeclContexts;
1155 
1156   /// A mapping from canonical declarations of enums to their canonical
1157   /// definitions. Only populated when using modules in C++.
1158   llvm::DenseMap<EnumDecl *, EnumDecl *> EnumDefinitions;
1159 
1160   /// When reading a Stmt tree, Stmt operands are placed in this stack.
1161   SmallVector<Stmt *, 16> StmtStack;
1162 
1163   /// What kind of records we are reading.
1164   enum ReadingKind {
1165     Read_None, Read_Decl, Read_Type, Read_Stmt
1166   };
1167 
1168   /// What kind of records we are reading.
1169   ReadingKind ReadingKind = Read_None;
1170 
1171   /// RAII object to change the reading kind.
1172   class ReadingKindTracker {
1173     ASTReader &Reader;
1174     enum ReadingKind PrevKind;
1175 
1176   public:
ReadingKindTracker(enum ReadingKind newKind,ASTReader & reader)1177     ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
1178         : Reader(reader), PrevKind(Reader.ReadingKind) {
1179       Reader.ReadingKind = newKind;
1180     }
1181 
1182     ReadingKindTracker(const ReadingKindTracker &) = delete;
1183     ReadingKindTracker &operator=(const ReadingKindTracker &) = delete;
~ReadingKindTracker()1184     ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; }
1185   };
1186 
1187   /// RAII object to mark the start of processing updates.
1188   class ProcessingUpdatesRAIIObj {
1189     ASTReader &Reader;
1190     bool PrevState;
1191 
1192   public:
ProcessingUpdatesRAIIObj(ASTReader & reader)1193     ProcessingUpdatesRAIIObj(ASTReader &reader)
1194         : Reader(reader), PrevState(Reader.ProcessingUpdateRecords) {
1195       Reader.ProcessingUpdateRecords = true;
1196     }
1197 
1198     ProcessingUpdatesRAIIObj(const ProcessingUpdatesRAIIObj &) = delete;
1199     ProcessingUpdatesRAIIObj &
1200     operator=(const ProcessingUpdatesRAIIObj &) = delete;
~ProcessingUpdatesRAIIObj()1201     ~ProcessingUpdatesRAIIObj() { Reader.ProcessingUpdateRecords = PrevState; }
1202   };
1203 
1204   /// Suggested contents of the predefines buffer, after this
1205   /// PCH file has been processed.
1206   ///
1207   /// In most cases, this string will be empty, because the predefines
1208   /// buffer computed to build the PCH file will be identical to the
1209   /// predefines buffer computed from the command line. However, when
1210   /// there are differences that the PCH reader can work around, this
1211   /// predefines buffer may contain additional definitions.
1212   std::string SuggestedPredefines;
1213 
1214   llvm::DenseMap<const Decl *, bool> DefinitionSource;
1215 
1216   /// Reads a statement from the specified cursor.
1217   Stmt *ReadStmtFromStream(ModuleFile &F);
1218 
1219   struct InputFileInfo {
1220     std::string Filename;
1221     uint64_t ContentHash;
1222     off_t StoredSize;
1223     time_t StoredTime;
1224     bool Overridden;
1225     bool Transient;
1226     bool TopLevelModuleMap;
1227   };
1228 
1229   /// Reads the stored information about an input file.
1230   InputFileInfo readInputFileInfo(ModuleFile &F, unsigned ID);
1231 
1232   /// Retrieve the file entry and 'overridden' bit for an input
1233   /// file in the given module file.
1234   serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
1235                                         bool Complain = true);
1236 
1237 public:
1238   void ResolveImportedPath(ModuleFile &M, std::string &Filename);
1239   static void ResolveImportedPath(std::string &Filename, StringRef Prefix);
1240 
1241   /// Returns the first key declaration for the given declaration. This
1242   /// is one that is formerly-canonical (or still canonical) and whose module
1243   /// did not import any other key declaration of the entity.
getKeyDeclaration(Decl * D)1244   Decl *getKeyDeclaration(Decl *D) {
1245     D = D->getCanonicalDecl();
1246     if (D->isFromASTFile())
1247       return D;
1248 
1249     auto I = KeyDecls.find(D);
1250     if (I == KeyDecls.end() || I->second.empty())
1251       return D;
1252     return GetExistingDecl(I->second[0]);
1253   }
getKeyDeclaration(const Decl * D)1254   const Decl *getKeyDeclaration(const Decl *D) {
1255     return getKeyDeclaration(const_cast<Decl*>(D));
1256   }
1257 
1258   /// Run a callback on each imported key declaration of \p D.
1259   template <typename Fn>
forEachImportedKeyDecl(const Decl * D,Fn Visit)1260   void forEachImportedKeyDecl(const Decl *D, Fn Visit) {
1261     D = D->getCanonicalDecl();
1262     if (D->isFromASTFile())
1263       Visit(D);
1264 
1265     auto It = KeyDecls.find(const_cast<Decl*>(D));
1266     if (It != KeyDecls.end())
1267       for (auto ID : It->second)
1268         Visit(GetExistingDecl(ID));
1269   }
1270 
1271   /// Get the loaded lookup tables for \p Primary, if any.
1272   const serialization::reader::DeclContextLookupTable *
1273   getLoadedLookupTables(DeclContext *Primary) const;
1274 
1275 private:
1276   struct ImportedModule {
1277     ModuleFile *Mod;
1278     ModuleFile *ImportedBy;
1279     SourceLocation ImportLoc;
1280 
ImportedModuleImportedModule1281     ImportedModule(ModuleFile *Mod,
1282                    ModuleFile *ImportedBy,
1283                    SourceLocation ImportLoc)
1284         : Mod(Mod), ImportedBy(ImportedBy), ImportLoc(ImportLoc) {}
1285   };
1286 
1287   ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
1288                             SourceLocation ImportLoc, ModuleFile *ImportedBy,
1289                             SmallVectorImpl<ImportedModule> &Loaded,
1290                             off_t ExpectedSize, time_t ExpectedModTime,
1291                             ASTFileSignature ExpectedSignature,
1292                             unsigned ClientLoadCapabilities);
1293   ASTReadResult ReadControlBlock(ModuleFile &F,
1294                                  SmallVectorImpl<ImportedModule> &Loaded,
1295                                  const ModuleFile *ImportedBy,
1296                                  unsigned ClientLoadCapabilities);
1297   static ASTReadResult ReadOptionsBlock(
1298       llvm::BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
1299       bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
1300       std::string &SuggestedPredefines);
1301 
1302   /// Read the unhashed control block.
1303   ///
1304   /// This has no effect on \c F.Stream, instead creating a fresh cursor from
1305   /// \c F.Data and reading ahead.
1306   ASTReadResult readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
1307                                          unsigned ClientLoadCapabilities);
1308 
1309   static ASTReadResult
1310   readUnhashedControlBlockImpl(ModuleFile *F, llvm::StringRef StreamData,
1311                                unsigned ClientLoadCapabilities,
1312                                bool AllowCompatibleConfigurationMismatch,
1313                                ASTReaderListener *Listener,
1314                                bool ValidateDiagnosticOptions);
1315 
1316   ASTReadResult ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities);
1317   ASTReadResult ReadExtensionBlock(ModuleFile &F);
1318   void ReadModuleOffsetMap(ModuleFile &F) const;
1319   bool ParseLineTable(ModuleFile &F, const RecordData &Record);
1320   bool ReadSourceManagerBlock(ModuleFile &F);
1321   llvm::BitstreamCursor &SLocCursorForID(int ID);
1322   SourceLocation getImportLocation(ModuleFile *F);
1323   ASTReadResult ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
1324                                        const ModuleFile *ImportedBy,
1325                                        unsigned ClientLoadCapabilities);
1326   ASTReadResult ReadSubmoduleBlock(ModuleFile &F,
1327                                    unsigned ClientLoadCapabilities);
1328   static bool ParseLanguageOptions(const RecordData &Record, bool Complain,
1329                                    ASTReaderListener &Listener,
1330                                    bool AllowCompatibleDifferences);
1331   static bool ParseTargetOptions(const RecordData &Record, bool Complain,
1332                                  ASTReaderListener &Listener,
1333                                  bool AllowCompatibleDifferences);
1334   static bool ParseDiagnosticOptions(const RecordData &Record, bool Complain,
1335                                      ASTReaderListener &Listener);
1336   static bool ParseFileSystemOptions(const RecordData &Record, bool Complain,
1337                                      ASTReaderListener &Listener);
1338   static bool ParseHeaderSearchOptions(const RecordData &Record, bool Complain,
1339                                        ASTReaderListener &Listener);
1340   static bool ParsePreprocessorOptions(const RecordData &Record, bool Complain,
1341                                        ASTReaderListener &Listener,
1342                                        std::string &SuggestedPredefines);
1343 
1344   struct RecordLocation {
1345     ModuleFile *F;
1346     uint64_t Offset;
1347 
RecordLocationRecordLocation1348     RecordLocation(ModuleFile *M, uint64_t O) : F(M), Offset(O) {}
1349   };
1350 
1351   QualType readTypeRecord(unsigned Index);
1352   RecordLocation TypeCursorForIndex(unsigned Index);
1353   void LoadedDecl(unsigned Index, Decl *D);
1354   Decl *ReadDeclRecord(serialization::DeclID ID);
1355   void markIncompleteDeclChain(Decl *Canon);
1356 
1357   /// Returns the most recent declaration of a declaration (which must be
1358   /// of a redeclarable kind) that is either local or has already been loaded
1359   /// merged into its redecl chain.
1360   Decl *getMostRecentExistingDecl(Decl *D);
1361 
1362   RecordLocation DeclCursorForID(serialization::DeclID ID,
1363                                  SourceLocation &Location);
1364   void loadDeclUpdateRecords(PendingUpdateRecord &Record);
1365   void loadPendingDeclChain(Decl *D, uint64_t LocalOffset);
1366   void loadObjCCategories(serialization::GlobalDeclID ID, ObjCInterfaceDecl *D,
1367                           unsigned PreviousGeneration = 0);
1368 
1369   RecordLocation getLocalBitOffset(uint64_t GlobalOffset);
1370   uint64_t getGlobalBitOffset(ModuleFile &M, uint64_t LocalOffset);
1371 
1372   /// Returns the first preprocessed entity ID that begins or ends after
1373   /// \arg Loc.
1374   serialization::PreprocessedEntityID
1375   findPreprocessedEntity(SourceLocation Loc, bool EndsAfter) const;
1376 
1377   /// Find the next module that contains entities and return the ID
1378   /// of the first entry.
1379   ///
1380   /// \param SLocMapI points at a chunk of a module that contains no
1381   /// preprocessed entities or the entities it contains are not the
1382   /// ones we are looking for.
1383   serialization::PreprocessedEntityID
1384     findNextPreprocessedEntity(
1385                         GlobalSLocOffsetMapType::const_iterator SLocMapI) const;
1386 
1387   /// Returns (ModuleFile, Local index) pair for \p GlobalIndex of a
1388   /// preprocessed entity.
1389   std::pair<ModuleFile *, unsigned>
1390     getModulePreprocessedEntity(unsigned GlobalIndex);
1391 
1392   /// Returns (begin, end) pair for the preprocessed entities of a
1393   /// particular module.
1394   llvm::iterator_range<PreprocessingRecord::iterator>
1395   getModulePreprocessedEntities(ModuleFile &Mod) const;
1396 
1397 public:
1398   class ModuleDeclIterator
1399       : public llvm::iterator_adaptor_base<
1400             ModuleDeclIterator, const serialization::LocalDeclID *,
1401             std::random_access_iterator_tag, const Decl *, ptrdiff_t,
1402             const Decl *, const Decl *> {
1403     ASTReader *Reader = nullptr;
1404     ModuleFile *Mod = nullptr;
1405 
1406   public:
ModuleDeclIterator()1407     ModuleDeclIterator() : iterator_adaptor_base(nullptr) {}
1408 
ModuleDeclIterator(ASTReader * Reader,ModuleFile * Mod,const serialization::LocalDeclID * Pos)1409     ModuleDeclIterator(ASTReader *Reader, ModuleFile *Mod,
1410                        const serialization::LocalDeclID *Pos)
1411         : iterator_adaptor_base(Pos), Reader(Reader), Mod(Mod) {}
1412 
1413     value_type operator*() const {
1414       return Reader->GetDecl(Reader->getGlobalDeclID(*Mod, *I));
1415     }
1416 
1417     value_type operator->() const { return **this; }
1418 
1419     bool operator==(const ModuleDeclIterator &RHS) const {
1420       assert(Reader == RHS.Reader && Mod == RHS.Mod);
1421       return I == RHS.I;
1422     }
1423   };
1424 
1425   llvm::iterator_range<ModuleDeclIterator>
1426   getModuleFileLevelDecls(ModuleFile &Mod);
1427 
1428 private:
1429   void PassInterestingDeclsToConsumer();
1430   void PassInterestingDeclToConsumer(Decl *D);
1431 
1432   void finishPendingActions();
1433   void diagnoseOdrViolations();
1434 
1435   void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
1436 
addPendingDeclContextInfo(Decl * D,serialization::GlobalDeclID SemaDC,serialization::GlobalDeclID LexicalDC)1437   void addPendingDeclContextInfo(Decl *D,
1438                                  serialization::GlobalDeclID SemaDC,
1439                                  serialization::GlobalDeclID LexicalDC) {
1440     assert(D);
1441     PendingDeclContextInfo Info = { D, SemaDC, LexicalDC };
1442     PendingDeclContextInfos.push_back(Info);
1443   }
1444 
1445   /// Produce an error diagnostic and return true.
1446   ///
1447   /// This routine should only be used for fatal errors that have to
1448   /// do with non-routine failures (e.g., corrupted AST file).
1449   void Error(StringRef Msg) const;
1450   void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
1451              StringRef Arg2 = StringRef(), StringRef Arg3 = StringRef()) const;
1452   void Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1453              unsigned Select) const;
1454   void Error(llvm::Error &&Err) const;
1455 
1456 public:
1457   /// Load the AST file and validate its contents against the given
1458   /// Preprocessor.
1459   ///
1460   /// \param PP the preprocessor associated with the context in which this
1461   /// precompiled header will be loaded.
1462   ///
1463   /// \param Context the AST context that this precompiled header will be
1464   /// loaded into, if any.
1465   ///
1466   /// \param PCHContainerRdr the PCHContainerOperations to use for loading and
1467   /// creating modules.
1468   ///
1469   /// \param Extensions the list of module file extensions that can be loaded
1470   /// from the AST files.
1471   ///
1472   /// \param isysroot If non-NULL, the system include path specified by the
1473   /// user. This is only used with relocatable PCH files. If non-NULL,
1474   /// a relocatable PCH file will use the default path "/".
1475   ///
1476   /// \param DisableValidation If true, the AST reader will suppress most
1477   /// of its regular consistency checking, allowing the use of precompiled
1478   /// headers that cannot be determined to be compatible.
1479   ///
1480   /// \param AllowASTWithCompilerErrors If true, the AST reader will accept an
1481   /// AST file the was created out of an AST with compiler errors,
1482   /// otherwise it will reject it.
1483   ///
1484   /// \param AllowConfigurationMismatch If true, the AST reader will not check
1485   /// for configuration differences between the AST file and the invocation.
1486   ///
1487   /// \param ValidateSystemInputs If true, the AST reader will validate
1488   /// system input files in addition to user input files. This is only
1489   /// meaningful if \p DisableValidation is false.
1490   ///
1491   /// \param UseGlobalIndex If true, the AST reader will try to load and use
1492   /// the global module index.
1493   ///
1494   /// \param ReadTimer If non-null, a timer used to track the time spent
1495   /// deserializing.
1496   ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
1497             ASTContext *Context, const PCHContainerReader &PCHContainerRdr,
1498             ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
1499             StringRef isysroot = "", bool DisableValidation = false,
1500             bool AllowASTWithCompilerErrors = false,
1501             bool AllowConfigurationMismatch = false,
1502             bool ValidateSystemInputs = false,
1503             bool ValidateASTInputFilesContent = false,
1504             bool UseGlobalIndex = true,
1505             std::unique_ptr<llvm::Timer> ReadTimer = {});
1506   ASTReader(const ASTReader &) = delete;
1507   ASTReader &operator=(const ASTReader &) = delete;
1508   ~ASTReader() override;
1509 
getSourceManager()1510   SourceManager &getSourceManager() const { return SourceMgr; }
getFileManager()1511   FileManager &getFileManager() const { return FileMgr; }
getDiags()1512   DiagnosticsEngine &getDiags() const { return Diags; }
1513 
1514   /// Flags that indicate what kind of AST loading failures the client
1515   /// of the AST reader can directly handle.
1516   ///
1517   /// When a client states that it can handle a particular kind of failure,
1518   /// the AST reader will not emit errors when producing that kind of failure.
1519   enum LoadFailureCapabilities {
1520     /// The client can't handle any AST loading failures.
1521     ARR_None = 0,
1522 
1523     /// The client can handle an AST file that cannot load because it
1524     /// is missing.
1525     ARR_Missing = 0x1,
1526 
1527     /// The client can handle an AST file that cannot load because it
1528     /// is out-of-date relative to its input files.
1529     ARR_OutOfDate = 0x2,
1530 
1531     /// The client can handle an AST file that cannot load because it
1532     /// was built with a different version of Clang.
1533     ARR_VersionMismatch = 0x4,
1534 
1535     /// The client can handle an AST file that cannot load because it's
1536     /// compiled configuration doesn't match that of the context it was
1537     /// loaded into.
1538     ARR_ConfigurationMismatch = 0x8
1539   };
1540 
1541   /// Load the AST file designated by the given file name.
1542   ///
1543   /// \param FileName The name of the AST file to load.
1544   ///
1545   /// \param Type The kind of AST being loaded, e.g., PCH, module, main file,
1546   /// or preamble.
1547   ///
1548   /// \param ImportLoc the location where the module file will be considered as
1549   /// imported from. For non-module AST types it should be invalid.
1550   ///
1551   /// \param ClientLoadCapabilities The set of client load-failure
1552   /// capabilities, represented as a bitset of the enumerators of
1553   /// LoadFailureCapabilities.
1554   ///
1555   /// \param Imported optional out-parameter to append the list of modules
1556   /// that were imported by precompiled headers or any other non-module AST file
1557   ASTReadResult ReadAST(StringRef FileName, ModuleKind Type,
1558                         SourceLocation ImportLoc,
1559                         unsigned ClientLoadCapabilities,
1560                         SmallVectorImpl<ImportedSubmodule> *Imported = nullptr);
1561 
1562   /// Make the entities in the given module and any of its (non-explicit)
1563   /// submodules visible to name lookup.
1564   ///
1565   /// \param Mod The module whose names should be made visible.
1566   ///
1567   /// \param NameVisibility The level of visibility to give the names in the
1568   /// module.  Visibility can only be increased over time.
1569   ///
1570   /// \param ImportLoc The location at which the import occurs.
1571   void makeModuleVisible(Module *Mod,
1572                          Module::NameVisibilityKind NameVisibility,
1573                          SourceLocation ImportLoc);
1574 
1575   /// Make the names within this set of hidden names visible.
1576   void makeNamesVisible(const HiddenNames &Names, Module *Owner);
1577 
1578   /// Note that MergedDef is a redefinition of the canonical definition
1579   /// Def, so Def should be visible whenever MergedDef is.
1580   void mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef);
1581 
1582   /// Take the AST callbacks listener.
takeListener()1583   std::unique_ptr<ASTReaderListener> takeListener() {
1584     return std::move(Listener);
1585   }
1586 
1587   /// Set the AST callbacks listener.
setListener(std::unique_ptr<ASTReaderListener> Listener)1588   void setListener(std::unique_ptr<ASTReaderListener> Listener) {
1589     this->Listener = std::move(Listener);
1590   }
1591 
1592   /// Add an AST callback listener.
1593   ///
1594   /// Takes ownership of \p L.
addListener(std::unique_ptr<ASTReaderListener> L)1595   void addListener(std::unique_ptr<ASTReaderListener> L) {
1596     if (Listener)
1597       L = std::make_unique<ChainedASTReaderListener>(std::move(L),
1598                                                       std::move(Listener));
1599     Listener = std::move(L);
1600   }
1601 
1602   /// RAII object to temporarily add an AST callback listener.
1603   class ListenerScope {
1604     ASTReader &Reader;
1605     bool Chained = false;
1606 
1607   public:
ListenerScope(ASTReader & Reader,std::unique_ptr<ASTReaderListener> L)1608     ListenerScope(ASTReader &Reader, std::unique_ptr<ASTReaderListener> L)
1609         : Reader(Reader) {
1610       auto Old = Reader.takeListener();
1611       if (Old) {
1612         Chained = true;
1613         L = std::make_unique<ChainedASTReaderListener>(std::move(L),
1614                                                         std::move(Old));
1615       }
1616       Reader.setListener(std::move(L));
1617     }
1618 
~ListenerScope()1619     ~ListenerScope() {
1620       auto New = Reader.takeListener();
1621       if (Chained)
1622         Reader.setListener(static_cast<ChainedASTReaderListener *>(New.get())
1623                                ->takeSecond());
1624     }
1625   };
1626 
1627   /// Set the AST deserialization listener.
1628   void setDeserializationListener(ASTDeserializationListener *Listener,
1629                                   bool TakeOwnership = false);
1630 
1631   /// Get the AST deserialization listener.
getDeserializationListener()1632   ASTDeserializationListener *getDeserializationListener() {
1633     return DeserializationListener;
1634   }
1635 
1636   /// Determine whether this AST reader has a global index.
hasGlobalIndex()1637   bool hasGlobalIndex() const { return (bool)GlobalIndex; }
1638 
1639   /// Return global module index.
getGlobalIndex()1640   GlobalModuleIndex *getGlobalIndex() { return GlobalIndex.get(); }
1641 
1642   /// Reset reader for a reload try.
resetForReload()1643   void resetForReload() { TriedLoadingGlobalIndex = false; }
1644 
1645   /// Attempts to load the global index.
1646   ///
1647   /// \returns true if loading the global index has failed for any reason.
1648   bool loadGlobalIndex();
1649 
1650   /// Determine whether we tried to load the global index, but failed,
1651   /// e.g., because it is out-of-date or does not exist.
1652   bool isGlobalIndexUnavailable() const;
1653 
1654   /// Initializes the ASTContext
1655   void InitializeContext();
1656 
1657   /// Update the state of Sema after loading some additional modules.
1658   void UpdateSema();
1659 
1660   /// Add in-memory (virtual file) buffer.
addInMemoryBuffer(StringRef & FileName,std::unique_ptr<llvm::MemoryBuffer> Buffer)1661   void addInMemoryBuffer(StringRef &FileName,
1662                          std::unique_ptr<llvm::MemoryBuffer> Buffer) {
1663     ModuleMgr.addInMemoryBuffer(FileName, std::move(Buffer));
1664   }
1665 
1666   /// Finalizes the AST reader's state before writing an AST file to
1667   /// disk.
1668   ///
1669   /// This operation may undo temporary state in the AST that should not be
1670   /// emitted.
1671   void finalizeForWriting();
1672 
1673   /// Retrieve the module manager.
getModuleManager()1674   ModuleManager &getModuleManager() { return ModuleMgr; }
1675 
1676   /// Retrieve the preprocessor.
getPreprocessor()1677   Preprocessor &getPreprocessor() const { return PP; }
1678 
1679   /// Retrieve the name of the original source file name for the primary
1680   /// module file.
getOriginalSourceFile()1681   StringRef getOriginalSourceFile() {
1682     return ModuleMgr.getPrimaryModule().OriginalSourceFileName;
1683   }
1684 
1685   /// Retrieve the name of the original source file name directly from
1686   /// the AST file, without actually loading the AST file.
1687   static std::string
1688   getOriginalSourceFile(const std::string &ASTFileName, FileManager &FileMgr,
1689                         const PCHContainerReader &PCHContainerRdr,
1690                         DiagnosticsEngine &Diags);
1691 
1692   /// Read the control block for the named AST file.
1693   ///
1694   /// \returns true if an error occurred, false otherwise.
1695   static bool
1696   readASTFileControlBlock(StringRef Filename, FileManager &FileMgr,
1697                           const PCHContainerReader &PCHContainerRdr,
1698                           bool FindModuleFileExtensions,
1699                           ASTReaderListener &Listener,
1700                           bool ValidateDiagnosticOptions);
1701 
1702   /// Determine whether the given AST file is acceptable to load into a
1703   /// translation unit with the given language and target options.
1704   static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
1705                                   const PCHContainerReader &PCHContainerRdr,
1706                                   const LangOptions &LangOpts,
1707                                   const TargetOptions &TargetOpts,
1708                                   const PreprocessorOptions &PPOpts,
1709                                   StringRef ExistingModuleCachePath);
1710 
1711   /// Returns the suggested contents of the predefines buffer,
1712   /// which contains a (typically-empty) subset of the predefines
1713   /// build prior to including the precompiled header.
getSuggestedPredefines()1714   const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
1715 
1716   /// Read a preallocated preprocessed entity from the external source.
1717   ///
1718   /// \returns null if an error occurred that prevented the preprocessed
1719   /// entity from being loaded.
1720   PreprocessedEntity *ReadPreprocessedEntity(unsigned Index) override;
1721 
1722   /// Returns a pair of [Begin, End) indices of preallocated
1723   /// preprocessed entities that \p Range encompasses.
1724   std::pair<unsigned, unsigned>
1725       findPreprocessedEntitiesInRange(SourceRange Range) override;
1726 
1727   /// Optionally returns true or false if the preallocated preprocessed
1728   /// entity with index \p Index came from file \p FID.
1729   Optional<bool> isPreprocessedEntityInFileID(unsigned Index,
1730                                               FileID FID) override;
1731 
1732   /// Read a preallocated skipped range from the external source.
1733   SourceRange ReadSkippedRange(unsigned Index) override;
1734 
1735   /// Read the header file information for the given file entry.
1736   HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) override;
1737 
1738   void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag);
1739 
1740   /// Returns the number of source locations found in the chain.
getTotalNumSLocs()1741   unsigned getTotalNumSLocs() const {
1742     return TotalNumSLocEntries;
1743   }
1744 
1745   /// Returns the number of identifiers found in the chain.
getTotalNumIdentifiers()1746   unsigned getTotalNumIdentifiers() const {
1747     return static_cast<unsigned>(IdentifiersLoaded.size());
1748   }
1749 
1750   /// Returns the number of macros found in the chain.
getTotalNumMacros()1751   unsigned getTotalNumMacros() const {
1752     return static_cast<unsigned>(MacrosLoaded.size());
1753   }
1754 
1755   /// Returns the number of types found in the chain.
getTotalNumTypes()1756   unsigned getTotalNumTypes() const {
1757     return static_cast<unsigned>(TypesLoaded.size());
1758   }
1759 
1760   /// Returns the number of declarations found in the chain.
getTotalNumDecls()1761   unsigned getTotalNumDecls() const {
1762     return static_cast<unsigned>(DeclsLoaded.size());
1763   }
1764 
1765   /// Returns the number of submodules known.
getTotalNumSubmodules()1766   unsigned getTotalNumSubmodules() const {
1767     return static_cast<unsigned>(SubmodulesLoaded.size());
1768   }
1769 
1770   /// Returns the number of selectors found in the chain.
getTotalNumSelectors()1771   unsigned getTotalNumSelectors() const {
1772     return static_cast<unsigned>(SelectorsLoaded.size());
1773   }
1774 
1775   /// Returns the number of preprocessed entities known to the AST
1776   /// reader.
getTotalNumPreprocessedEntities()1777   unsigned getTotalNumPreprocessedEntities() const {
1778     unsigned Result = 0;
1779     for (const auto &M : ModuleMgr)
1780       Result += M.NumPreprocessedEntities;
1781     return Result;
1782   }
1783 
1784   /// Resolve a type ID into a type, potentially building a new
1785   /// type.
1786   QualType GetType(serialization::TypeID ID);
1787 
1788   /// Resolve a local type ID within a given AST file into a type.
1789   QualType getLocalType(ModuleFile &F, unsigned LocalID);
1790 
1791   /// Map a local type ID within a given AST file into a global type ID.
1792   serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const;
1793 
1794   /// Read a type from the current position in the given record, which
1795   /// was read from the given AST file.
readType(ModuleFile & F,const RecordData & Record,unsigned & Idx)1796   QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) {
1797     if (Idx >= Record.size())
1798       return {};
1799 
1800     return getLocalType(F, Record[Idx++]);
1801   }
1802 
1803   /// Map from a local declaration ID within a given module to a
1804   /// global declaration ID.
1805   serialization::DeclID getGlobalDeclID(ModuleFile &F,
1806                                       serialization::LocalDeclID LocalID) const;
1807 
1808   /// Returns true if global DeclID \p ID originated from module \p M.
1809   bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const;
1810 
1811   /// Retrieve the module file that owns the given declaration, or NULL
1812   /// if the declaration is not from a module file.
1813   ModuleFile *getOwningModuleFile(const Decl *D);
1814 
1815   /// Get the best name we know for the module that owns the given
1816   /// declaration, or an empty string if the declaration is not from a module.
1817   std::string getOwningModuleNameForDiagnostic(const Decl *D);
1818 
1819   /// Returns the source location for the decl \p ID.
1820   SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID);
1821 
1822   /// Resolve a declaration ID into a declaration, potentially
1823   /// building a new declaration.
1824   Decl *GetDecl(serialization::DeclID ID);
1825   Decl *GetExternalDecl(uint32_t ID) override;
1826 
1827   /// Resolve a declaration ID into a declaration. Return 0 if it's not
1828   /// been loaded yet.
1829   Decl *GetExistingDecl(serialization::DeclID ID);
1830 
1831   /// Reads a declaration with the given local ID in the given module.
GetLocalDecl(ModuleFile & F,uint32_t LocalID)1832   Decl *GetLocalDecl(ModuleFile &F, uint32_t LocalID) {
1833     return GetDecl(getGlobalDeclID(F, LocalID));
1834   }
1835 
1836   /// Reads a declaration with the given local ID in the given module.
1837   ///
1838   /// \returns The requested declaration, casted to the given return type.
1839   template<typename T>
GetLocalDeclAs(ModuleFile & F,uint32_t LocalID)1840   T *GetLocalDeclAs(ModuleFile &F, uint32_t LocalID) {
1841     return cast_or_null<T>(GetLocalDecl(F, LocalID));
1842   }
1843 
1844   /// Map a global declaration ID into the declaration ID used to
1845   /// refer to this declaration within the given module fule.
1846   ///
1847   /// \returns the global ID of the given declaration as known in the given
1848   /// module file.
1849   serialization::DeclID
1850   mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
1851                                   serialization::DeclID GlobalID);
1852 
1853   /// Reads a declaration ID from the given position in a record in the
1854   /// given module.
1855   ///
1856   /// \returns The declaration ID read from the record, adjusted to a global ID.
1857   serialization::DeclID ReadDeclID(ModuleFile &F, const RecordData &Record,
1858                                    unsigned &Idx);
1859 
1860   /// Reads a declaration from the given position in a record in the
1861   /// given module.
ReadDecl(ModuleFile & F,const RecordData & R,unsigned & I)1862   Decl *ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I) {
1863     return GetDecl(ReadDeclID(F, R, I));
1864   }
1865 
1866   /// Reads a declaration from the given position in a record in the
1867   /// given module.
1868   ///
1869   /// \returns The declaration read from this location, casted to the given
1870   /// result type.
1871   template<typename T>
ReadDeclAs(ModuleFile & F,const RecordData & R,unsigned & I)1872   T *ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I) {
1873     return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
1874   }
1875 
1876   /// If any redeclarations of \p D have been imported since it was
1877   /// last checked, this digs out those redeclarations and adds them to the
1878   /// redeclaration chain for \p D.
1879   void CompleteRedeclChain(const Decl *D) override;
1880 
1881   CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override;
1882 
1883   /// Resolve the offset of a statement into a statement.
1884   ///
1885   /// This operation will read a new statement from the external
1886   /// source each time it is called, and is meant to be used via a
1887   /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1888   Stmt *GetExternalDeclStmt(uint64_t Offset) override;
1889 
1890   /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1891   /// specified cursor.  Read the abbreviations that are at the top of the block
1892   /// and then leave the cursor pointing into the block.
1893   static bool ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID,
1894                                uint64_t *StartOfBlockOffset = nullptr);
1895 
1896   /// Finds all the visible declarations with a given name.
1897   /// The current implementation of this method just loads the entire
1898   /// lookup table as unmaterialized references.
1899   bool FindExternalVisibleDeclsByName(const DeclContext *DC,
1900                                       DeclarationName Name) override;
1901 
1902   /// Read all of the declarations lexically stored in a
1903   /// declaration context.
1904   ///
1905   /// \param DC The declaration context whose declarations will be
1906   /// read.
1907   ///
1908   /// \param IsKindWeWant A predicate indicating which declaration kinds
1909   /// we are interested in.
1910   ///
1911   /// \param Decls Vector that will contain the declarations loaded
1912   /// from the external source. The caller is responsible for merging
1913   /// these declarations with any declarations already stored in the
1914   /// declaration context.
1915   void
1916   FindExternalLexicalDecls(const DeclContext *DC,
1917                            llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
1918                            SmallVectorImpl<Decl *> &Decls) override;
1919 
1920   /// Get the decls that are contained in a file in the Offset/Length
1921   /// range. \p Length can be 0 to indicate a point at \p Offset instead of
1922   /// a range.
1923   void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
1924                            SmallVectorImpl<Decl *> &Decls) override;
1925 
1926   /// Notify ASTReader that we started deserialization of
1927   /// a decl or type so until FinishedDeserializing is called there may be
1928   /// decls that are initializing. Must be paired with FinishedDeserializing.
1929   void StartedDeserializing() override;
1930 
1931   /// Notify ASTReader that we finished the deserialization of
1932   /// a decl or type. Must be paired with StartedDeserializing.
1933   void FinishedDeserializing() override;
1934 
1935   /// Function that will be invoked when we begin parsing a new
1936   /// translation unit involving this external AST source.
1937   ///
1938   /// This function will provide all of the external definitions to
1939   /// the ASTConsumer.
1940   void StartTranslationUnit(ASTConsumer *Consumer) override;
1941 
1942   /// Print some statistics about AST usage.
1943   void PrintStats() override;
1944 
1945   /// Dump information about the AST reader to standard error.
1946   void dump();
1947 
1948   /// Return the amount of memory used by memory buffers, breaking down
1949   /// by heap-backed versus mmap'ed memory.
1950   void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override;
1951 
1952   /// Initialize the semantic source with the Sema instance
1953   /// being used to perform semantic analysis on the abstract syntax
1954   /// tree.
1955   void InitializeSema(Sema &S) override;
1956 
1957   /// Inform the semantic consumer that Sema is no longer available.
ForgetSema()1958   void ForgetSema() override { SemaObj = nullptr; }
1959 
1960   /// Retrieve the IdentifierInfo for the named identifier.
1961   ///
1962   /// This routine builds a new IdentifierInfo for the given identifier. If any
1963   /// declarations with this name are visible from translation unit scope, their
1964   /// declarations will be deserialized and introduced into the declaration
1965   /// chain of the identifier.
1966   IdentifierInfo *get(StringRef Name) override;
1967 
1968   /// Retrieve an iterator into the set of all identifiers
1969   /// in all loaded AST files.
1970   IdentifierIterator *getIdentifiers() override;
1971 
1972   /// Load the contents of the global method pool for a given
1973   /// selector.
1974   void ReadMethodPool(Selector Sel) override;
1975 
1976   /// Load the contents of the global method pool for a given
1977   /// selector if necessary.
1978   void updateOutOfDateSelector(Selector Sel) override;
1979 
1980   /// Load the set of namespaces that are known to the external source,
1981   /// which will be used during typo correction.
1982   void ReadKnownNamespaces(
1983                          SmallVectorImpl<NamespaceDecl *> &Namespaces) override;
1984 
1985   void ReadUndefinedButUsed(
1986       llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) override;
1987 
1988   void ReadMismatchingDeleteExpressions(llvm::MapVector<
1989       FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
1990                                             Exprs) override;
1991 
1992   void ReadTentativeDefinitions(
1993                             SmallVectorImpl<VarDecl *> &TentativeDefs) override;
1994 
1995   void ReadUnusedFileScopedDecls(
1996                        SmallVectorImpl<const DeclaratorDecl *> &Decls) override;
1997 
1998   void ReadDelegatingConstructors(
1999                          SmallVectorImpl<CXXConstructorDecl *> &Decls) override;
2000 
2001   void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) override;
2002 
2003   void ReadUnusedLocalTypedefNameCandidates(
2004       llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) override;
2005 
2006   void ReadDeclsToCheckForDeferredDiags(
2007       llvm::SmallVector<Decl *, 4> &Decls) override;
2008 
2009   void ReadReferencedSelectors(
2010            SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) override;
2011 
2012   void ReadWeakUndeclaredIdentifiers(
2013            SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WI) override;
2014 
2015   void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) override;
2016 
2017   void ReadPendingInstantiations(
2018                   SmallVectorImpl<std::pair<ValueDecl *,
2019                                             SourceLocation>> &Pending) override;
2020 
2021   void ReadLateParsedTemplates(
2022       llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
2023           &LPTMap) override;
2024 
2025   /// Load a selector from disk, registering its ID if it exists.
2026   void LoadSelector(Selector Sel);
2027 
2028   void SetIdentifierInfo(unsigned ID, IdentifierInfo *II);
2029   void SetGloballyVisibleDecls(IdentifierInfo *II,
2030                                const SmallVectorImpl<uint32_t> &DeclIDs,
2031                                SmallVectorImpl<Decl *> *Decls = nullptr);
2032 
2033   /// Report a diagnostic.
2034   DiagnosticBuilder Diag(unsigned DiagID) const;
2035 
2036   /// Report a diagnostic.
2037   DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const;
2038 
2039   IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID);
2040 
readIdentifier(ModuleFile & M,const RecordData & Record,unsigned & Idx)2041   IdentifierInfo *readIdentifier(ModuleFile &M, const RecordData &Record,
2042                                  unsigned &Idx) {
2043     return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++]));
2044   }
2045 
GetIdentifier(serialization::IdentifierID ID)2046   IdentifierInfo *GetIdentifier(serialization::IdentifierID ID) override {
2047     // Note that we are loading an identifier.
2048     Deserializing AnIdentifier(this);
2049 
2050     return DecodeIdentifierInfo(ID);
2051   }
2052 
2053   IdentifierInfo *getLocalIdentifier(ModuleFile &M, unsigned LocalID);
2054 
2055   serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M,
2056                                                     unsigned LocalID);
2057 
2058   void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo);
2059 
2060   /// Retrieve the macro with the given ID.
2061   MacroInfo *getMacro(serialization::MacroID ID);
2062 
2063   /// Retrieve the global macro ID corresponding to the given local
2064   /// ID within the given module file.
2065   serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID);
2066 
2067   /// Read the source location entry with index ID.
2068   bool ReadSLocEntry(int ID) override;
2069 
2070   /// Retrieve the module import location and module name for the
2071   /// given source manager entry ID.
2072   std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) override;
2073 
2074   /// Retrieve the global submodule ID given a module and its local ID
2075   /// number.
2076   serialization::SubmoduleID
2077   getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID);
2078 
2079   /// Retrieve the submodule that corresponds to a global submodule ID.
2080   ///
2081   Module *getSubmodule(serialization::SubmoduleID GlobalID);
2082 
2083   /// Retrieve the module that corresponds to the given module ID.
2084   ///
2085   /// Note: overrides method in ExternalASTSource
2086   Module *getModule(unsigned ID) override;
2087 
2088   bool DeclIsFromPCHWithObjectFile(const Decl *D) override;
2089 
2090   /// Retrieve the module file with a given local ID within the specified
2091   /// ModuleFile.
2092   ModuleFile *getLocalModuleFile(ModuleFile &M, unsigned ID);
2093 
2094   /// Get an ID for the given module file.
2095   unsigned getModuleFileID(ModuleFile *M);
2096 
2097   /// Return a descriptor for the corresponding module.
2098   llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID) override;
2099 
2100   ExtKind hasExternalDefinitions(const Decl *D) override;
2101 
2102   /// Retrieve a selector from the given module with its local ID
2103   /// number.
2104   Selector getLocalSelector(ModuleFile &M, unsigned LocalID);
2105 
2106   Selector DecodeSelector(serialization::SelectorID Idx);
2107 
2108   Selector GetExternalSelector(serialization::SelectorID ID) override;
2109   uint32_t GetNumExternalSelectors() override;
2110 
ReadSelector(ModuleFile & M,const RecordData & Record,unsigned & Idx)2111   Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) {
2112     return getLocalSelector(M, Record[Idx++]);
2113   }
2114 
2115   /// Retrieve the global selector ID that corresponds to this
2116   /// the local selector ID in a given module.
2117   serialization::SelectorID getGlobalSelectorID(ModuleFile &F,
2118                                                 unsigned LocalID) const;
2119 
2120   /// Read the contents of a CXXCtorInitializer array.
2121   CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset) override;
2122 
2123   /// Read a source location from raw form and return it in its
2124   /// originating module file's source location space.
ReadUntranslatedSourceLocation(uint32_t Raw)2125   SourceLocation ReadUntranslatedSourceLocation(uint32_t Raw) const {
2126     return SourceLocation::getFromRawEncoding((Raw >> 1) | (Raw << 31));
2127   }
2128 
2129   /// Read a source location from raw form.
ReadSourceLocation(ModuleFile & ModuleFile,uint32_t Raw)2130   SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, uint32_t Raw) const {
2131     SourceLocation Loc = ReadUntranslatedSourceLocation(Raw);
2132     return TranslateSourceLocation(ModuleFile, Loc);
2133   }
2134 
2135   /// Translate a source location from another module file's source
2136   /// location space into ours.
TranslateSourceLocation(ModuleFile & ModuleFile,SourceLocation Loc)2137   SourceLocation TranslateSourceLocation(ModuleFile &ModuleFile,
2138                                          SourceLocation Loc) const {
2139     if (!ModuleFile.ModuleOffsetMap.empty())
2140       ReadModuleOffsetMap(ModuleFile);
2141     assert(ModuleFile.SLocRemap.find(Loc.getOffset()) !=
2142                ModuleFile.SLocRemap.end() &&
2143            "Cannot find offset to remap.");
2144     int Remap = ModuleFile.SLocRemap.find(Loc.getOffset())->second;
2145     return Loc.getLocWithOffset(Remap);
2146   }
2147 
2148   /// Read a source location.
ReadSourceLocation(ModuleFile & ModuleFile,const RecordDataImpl & Record,unsigned & Idx)2149   SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
2150                                     const RecordDataImpl &Record,
2151                                     unsigned &Idx) {
2152     return ReadSourceLocation(ModuleFile, Record[Idx++]);
2153   }
2154 
2155   /// Read a source range.
2156   SourceRange ReadSourceRange(ModuleFile &F,
2157                               const RecordData &Record, unsigned &Idx);
2158 
2159   // Read a string
2160   static std::string ReadString(const RecordData &Record, unsigned &Idx);
2161 
2162   // Skip a string
SkipString(const RecordData & Record,unsigned & Idx)2163   static void SkipString(const RecordData &Record, unsigned &Idx) {
2164     Idx += Record[Idx] + 1;
2165   }
2166 
2167   // Read a path
2168   std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx);
2169 
2170   // Read a path
2171   std::string ReadPath(StringRef BaseDirectory, const RecordData &Record,
2172                        unsigned &Idx);
2173 
2174   // Skip a path
SkipPath(const RecordData & Record,unsigned & Idx)2175   static void SkipPath(const RecordData &Record, unsigned &Idx) {
2176     SkipString(Record, Idx);
2177   }
2178 
2179   /// Read a version tuple.
2180   static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
2181 
2182   CXXTemporary *ReadCXXTemporary(ModuleFile &F, const RecordData &Record,
2183                                  unsigned &Idx);
2184 
2185   /// Reads a statement.
2186   Stmt *ReadStmt(ModuleFile &F);
2187 
2188   /// Reads an expression.
2189   Expr *ReadExpr(ModuleFile &F);
2190 
2191   /// Reads a sub-statement operand during statement reading.
ReadSubStmt()2192   Stmt *ReadSubStmt() {
2193     assert(ReadingKind == Read_Stmt &&
2194            "Should be called only during statement reading!");
2195     // Subexpressions are stored from last to first, so the next Stmt we need
2196     // is at the back of the stack.
2197     assert(!StmtStack.empty() && "Read too many sub-statements!");
2198     return StmtStack.pop_back_val();
2199   }
2200 
2201   /// Reads a sub-expression operand during statement reading.
2202   Expr *ReadSubExpr();
2203 
2204   /// Reads a token out of a record.
2205   Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx);
2206 
2207   /// Reads the macro record located at the given offset.
2208   MacroInfo *ReadMacroRecord(ModuleFile &F, uint64_t Offset);
2209 
2210   /// Determine the global preprocessed entity ID that corresponds to
2211   /// the given local ID within the given module.
2212   serialization::PreprocessedEntityID
2213   getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const;
2214 
2215   /// Add a macro to deserialize its macro directive history.
2216   ///
2217   /// \param II The name of the macro.
2218   /// \param M The module file.
2219   /// \param MacroDirectivesOffset Offset of the serialized macro directive
2220   /// history.
2221   void addPendingMacro(IdentifierInfo *II, ModuleFile *M,
2222                        uint32_t MacroDirectivesOffset);
2223 
2224   /// Read the set of macros defined by this external macro source.
2225   void ReadDefinedMacros() override;
2226 
2227   /// Update an out-of-date identifier.
2228   void updateOutOfDateIdentifier(IdentifierInfo &II) override;
2229 
2230   /// Note that this identifier is up-to-date.
2231   void markIdentifierUpToDate(IdentifierInfo *II);
2232 
2233   /// Load all external visible decls in the given DeclContext.
2234   void completeVisibleDeclsMap(const DeclContext *DC) override;
2235 
2236   /// Retrieve the AST context that this AST reader supplements.
getContext()2237   ASTContext &getContext() {
2238     assert(ContextObj && "requested AST context when not loading AST");
2239     return *ContextObj;
2240   }
2241 
2242   // Contains the IDs for declarations that were requested before we have
2243   // access to a Sema object.
2244   SmallVector<uint64_t, 16> PreloadedDeclIDs;
2245 
2246   /// Retrieve the semantic analysis object used to analyze the
2247   /// translation unit in which the precompiled header is being
2248   /// imported.
getSema()2249   Sema *getSema() { return SemaObj; }
2250 
2251   /// Get the identifier resolver used for name lookup / updates
2252   /// in the translation unit scope. We have one of these even if we don't
2253   /// have a Sema object.
2254   IdentifierResolver &getIdResolver();
2255 
2256   /// Retrieve the identifier table associated with the
2257   /// preprocessor.
2258   IdentifierTable &getIdentifierTable();
2259 
2260   /// Record that the given ID maps to the given switch-case
2261   /// statement.
2262   void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
2263 
2264   /// Retrieve the switch-case statement with the given ID.
2265   SwitchCase *getSwitchCaseWithID(unsigned ID);
2266 
2267   void ClearSwitchCaseIDs();
2268 
2269   /// Cursors for comments blocks.
2270   SmallVector<std::pair<llvm::BitstreamCursor,
2271                         serialization::ModuleFile *>, 8> CommentsCursors;
2272 
2273   /// Loads comments ranges.
2274   void ReadComments() override;
2275 
2276   /// Visit all the input files of the given module file.
2277   void visitInputFiles(serialization::ModuleFile &MF,
2278                        bool IncludeSystem, bool Complain,
2279           llvm::function_ref<void(const serialization::InputFile &IF,
2280                                   bool isSystem)> Visitor);
2281 
2282   /// Visit all the top-level module maps loaded when building the given module
2283   /// file.
2284   void visitTopLevelModuleMaps(serialization::ModuleFile &MF,
2285                                llvm::function_ref<
2286                                    void(const FileEntry *)> Visitor);
2287 
isProcessingUpdateRecords()2288   bool isProcessingUpdateRecords() { return ProcessingUpdateRecords; }
2289 };
2290 
2291 } // namespace clang
2292 
2293 #endif // LLVM_CLANG_SERIALIZATION_ASTREADER_H
2294