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