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