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