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