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