ASTReader.h revision 21cf08b7e0c03266f37f436c2afd8521c643b31a
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/Serialization/ASTBitCodes.h"
18#include "clang/Serialization/ContinuousRangeMap.h"
19#include "clang/Serialization/Module.h"
20#include "clang/Serialization/ModuleManager.h"
21#include "clang/Sema/ExternalSemaSource.h"
22#include "clang/AST/DeclarationName.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/TemplateBase.h"
25#include "clang/Lex/ExternalPreprocessorSource.h"
26#include "clang/Lex/HeaderSearch.h"
27#include "clang/Lex/PreprocessingRecord.h"
28#include "clang/Basic/Diagnostic.h"
29#include "clang/Basic/FileManager.h"
30#include "clang/Basic/FileSystemOptions.h"
31#include "clang/Basic/IdentifierTable.h"
32#include "clang/Basic/SourceManager.h"
33#include "llvm/ADT/APFloat.h"
34#include "llvm/ADT/APInt.h"
35#include "llvm/ADT/APSInt.h"
36#include "llvm/ADT/OwningPtr.h"
37#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/StringRef.h"
39#include "llvm/ADT/DenseSet.h"
40#include "llvm/Bitcode/BitstreamReader.h"
41#include "llvm/Support/DataTypes.h"
42#include <deque>
43#include <map>
44#include <string>
45#include <utility>
46#include <vector>
47
48namespace llvm {
49  class MemoryBuffer;
50}
51
52namespace clang {
53
54class AddrLabelExpr;
55class ASTConsumer;
56class ASTContext;
57class ASTIdentifierIterator;
58class ASTUnit; // FIXME: Layering violation and egregious hack.
59class Attr;
60class Decl;
61class DeclContext;
62class NestedNameSpecifier;
63class CXXBaseSpecifier;
64class CXXConstructorDecl;
65class CXXCtorInitializer;
66class GotoStmt;
67class MacroDefinition;
68class NamedDecl;
69class OpaqueValueExpr;
70class Preprocessor;
71class Sema;
72class SwitchCase;
73class ASTDeserializationListener;
74class ASTWriter;
75class ASTReader;
76class ASTDeclReader;
77class ASTStmtReader;
78class TypeLocReader;
79struct HeaderFileInfo;
80class VersionTuple;
81
82struct PCHPredefinesBlock {
83  /// \brief The file ID for this predefines buffer in a PCH file.
84  FileID BufferID;
85
86  /// \brief This predefines buffer in a PCH file.
87  StringRef Data;
88};
89typedef SmallVector<PCHPredefinesBlock, 2> PCHPredefinesBlocks;
90
91/// \brief Abstract interface for callback invocations by the ASTReader.
92///
93/// While reading an AST file, the ASTReader will call the methods of the
94/// listener to pass on specific information. Some of the listener methods can
95/// return true to indicate to the ASTReader that the information (and
96/// consequently the AST file) is invalid.
97class ASTReaderListener {
98public:
99  virtual ~ASTReaderListener();
100
101  /// \brief Receives the language options.
102  ///
103  /// \returns true to indicate the options are invalid or false otherwise.
104  virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
105    return false;
106  }
107
108  /// \brief Receives the target triple.
109  ///
110  /// \returns true to indicate the target triple is invalid or false otherwise.
111  virtual bool ReadTargetTriple(StringRef Triple) {
112    return false;
113  }
114
115  /// \brief Receives the contents of the predefines buffer.
116  ///
117  /// \param Buffers Information about the predefines buffers.
118  ///
119  /// \param OriginalFileName The original file name for the AST file, which
120  /// will appear as an entry in the predefines buffer.
121  ///
122  /// \param SuggestedPredefines If necessary, additional definitions are added
123  /// here.
124  ///
125  /// \returns true to indicate the predefines are invalid or false otherwise.
126  virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
127                                    StringRef OriginalFileName,
128                                    std::string &SuggestedPredefines,
129                                    FileManager &FileMgr) {
130    return false;
131  }
132
133  /// \brief Receives a HeaderFileInfo entry.
134  virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {}
135
136  /// \brief Receives __COUNTER__ value.
137  virtual void ReadCounter(unsigned Value) {}
138};
139
140/// \brief ASTReaderListener implementation to validate the information of
141/// the PCH file against an initialized Preprocessor.
142class PCHValidator : public ASTReaderListener {
143  Preprocessor &PP;
144  ASTReader &Reader;
145
146  unsigned NumHeaderInfos;
147
148public:
149  PCHValidator(Preprocessor &PP, ASTReader &Reader)
150    : PP(PP), Reader(Reader), NumHeaderInfos(0) {}
151
152  virtual bool ReadLanguageOptions(const LangOptions &LangOpts);
153  virtual bool ReadTargetTriple(StringRef Triple);
154  virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
155                                    StringRef OriginalFileName,
156                                    std::string &SuggestedPredefines,
157                                    FileManager &FileMgr);
158  virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID);
159  virtual void ReadCounter(unsigned Value);
160
161private:
162  void Error(const char *Msg);
163};
164
165namespace serialization {
166
167class ReadMethodPoolVisitor;
168
169namespace reader {
170  class ASTIdentifierLookupTrait;
171}
172
173} // end namespace serialization
174
175/// \brief Reads an AST files chain containing the contents of a translation
176/// unit.
177///
178/// The ASTReader class reads bitstreams (produced by the ASTWriter
179/// class) containing the serialized representation of a given
180/// abstract syntax tree and its supporting data structures. An
181/// instance of the ASTReader can be attached to an ASTContext object,
182/// which will provide access to the contents of the AST files.
183///
184/// The AST reader provides lazy de-serialization of declarations, as
185/// required when traversing the AST. Only those AST nodes that are
186/// actually required will be de-serialized.
187class ASTReader
188  : public ExternalPreprocessorSource,
189    public ExternalPreprocessingRecordSource,
190    public ExternalHeaderFileInfoSource,
191    public ExternalSemaSource,
192    public IdentifierInfoLookup,
193    public ExternalIdentifierLookup,
194    public ExternalSLocEntrySource
195{
196public:
197  enum ASTReadResult { Success, Failure, IgnorePCH };
198  /// \brief Types of AST files.
199  friend class PCHValidator;
200  friend class ASTDeclReader;
201  friend class ASTStmtReader;
202  friend class ASTIdentifierIterator;
203  friend class serialization::reader::ASTIdentifierLookupTrait;
204  friend class TypeLocReader;
205  friend class ASTWriter;
206  friend class ASTUnit; // ASTUnit needs to remap source locations.
207  friend class serialization::ReadMethodPoolVisitor;
208
209  typedef serialization::ModuleFile ModuleFile;
210  typedef serialization::ModuleKind ModuleKind;
211  typedef serialization::ModuleManager ModuleManager;
212
213  typedef ModuleManager::ModuleIterator ModuleIterator;
214  typedef ModuleManager::ModuleConstIterator ModuleConstIterator;
215  typedef ModuleManager::ModuleReverseIterator ModuleReverseIterator;
216
217private:
218  /// \brief The receiver of some callbacks invoked by ASTReader.
219  llvm::OwningPtr<ASTReaderListener> Listener;
220
221  /// \brief The receiver of deserialization events.
222  ASTDeserializationListener *DeserializationListener;
223
224  SourceManager &SourceMgr;
225  FileManager &FileMgr;
226  DiagnosticsEngine &Diags;
227
228  /// \brief The semantic analysis object that will be processing the
229  /// AST files and the translation unit that uses it.
230  Sema *SemaObj;
231
232  /// \brief The preprocessor that will be loading the source file.
233  Preprocessor &PP;
234
235  /// \brief The AST context into which we'll read the AST files.
236  ASTContext &Context;
237
238  /// \brief The AST consumer.
239  ASTConsumer *Consumer;
240
241  /// \brief The module manager which manages modules and their dependencies
242  ModuleManager ModuleMgr;
243
244  /// \brief A map of global bit offsets to the module that stores entities
245  /// at those bit offsets.
246  ContinuousRangeMap<uint64_t, ModuleFile*, 4> GlobalBitOffsetsMap;
247
248  /// \brief A map of negated SLocEntryIDs to the modules containing them.
249  ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocEntryMap;
250
251  typedef ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocOffsetMapType;
252
253  /// \brief A map of reversed (SourceManager::MaxLoadedOffset - SLocOffset)
254  /// SourceLocation offsets to the modules containing them.
255  GlobalSLocOffsetMapType GlobalSLocOffsetMap;
256
257  /// \brief Types that have already been loaded from the chain.
258  ///
259  /// When the pointer at index I is non-NULL, the type with
260  /// ID = (I + 1) << FastQual::Width has already been loaded
261  std::vector<QualType> TypesLoaded;
262
263  typedef ContinuousRangeMap<serialization::TypeID, ModuleFile *, 4>
264    GlobalTypeMapType;
265
266  /// \brief Mapping from global type IDs to the module in which the
267  /// type resides along with the offset that should be added to the
268  /// global type ID to produce a local ID.
269  GlobalTypeMapType GlobalTypeMap;
270
271  /// \brief Declarations that have already been loaded from the chain.
272  ///
273  /// When the pointer at index I is non-NULL, the declaration with ID
274  /// = I + 1 has already been loaded.
275  std::vector<Decl *> DeclsLoaded;
276
277  typedef ContinuousRangeMap<serialization::DeclID, ModuleFile *, 4>
278    GlobalDeclMapType;
279
280  /// \brief Mapping from global declaration IDs to the module in which the
281  /// declaration resides.
282  GlobalDeclMapType GlobalDeclMap;
283
284  typedef std::pair<ModuleFile *, uint64_t> FileOffset;
285  typedef SmallVector<FileOffset, 2> FileOffsetsTy;
286  typedef llvm::DenseMap<serialization::DeclID, FileOffsetsTy>
287      DeclUpdateOffsetsMap;
288
289  /// \brief Declarations that have modifications residing in a later file
290  /// in the chain.
291  DeclUpdateOffsetsMap DeclUpdateOffsets;
292
293  struct ReplacedDeclInfo {
294    ModuleFile *Mod;
295    uint64_t Offset;
296    unsigned RawLoc;
297
298    ReplacedDeclInfo() : Mod(0), Offset(0), RawLoc(0) {}
299    ReplacedDeclInfo(ModuleFile *Mod, uint64_t Offset, unsigned RawLoc)
300      : Mod(Mod), Offset(Offset), RawLoc(RawLoc) {}
301  };
302
303  typedef llvm::DenseMap<serialization::DeclID, ReplacedDeclInfo>
304      DeclReplacementMap;
305  /// \brief Declarations that have been replaced in a later file in the chain.
306  DeclReplacementMap ReplacedDecls;
307
308  struct FileDeclsInfo {
309    ModuleFile *Mod;
310    ArrayRef<serialization::LocalDeclID> Decls;
311
312    FileDeclsInfo() : Mod(0) {}
313    FileDeclsInfo(ModuleFile *Mod, ArrayRef<serialization::LocalDeclID> Decls)
314      : Mod(Mod), Decls(Decls) {}
315  };
316
317  /// \brief Map from a FileID to the file-level declarations that it contains.
318  llvm::DenseMap<FileID, FileDeclsInfo> FileDeclIDs;
319
320  // Updates for visible decls can occur for other contexts than just the
321  // TU, and when we read those update records, the actual context will not
322  // be available yet (unless it's the TU), so have this pending map using the
323  // ID as a key. It will be realized when the context is actually loaded.
324  typedef SmallVector<std::pair<void *, ModuleFile*>, 1> DeclContextVisibleUpdates;
325  typedef llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates>
326      DeclContextVisibleUpdatesPending;
327
328  /// \brief Updates to the visible declarations of declaration contexts that
329  /// haven't been loaded yet.
330  DeclContextVisibleUpdatesPending PendingVisibleUpdates;
331
332  /// \brief The set of C++ or Objective-C classes that have forward
333  /// declarations that have not yet been linked to their definitions.
334  llvm::SmallPtrSet<Decl *, 4> PendingDefinitions;
335
336  typedef llvm::DenseMap<serialization::DeclID, serialization::DeclID>
337      FirstLatestDeclIDMap;
338  /// \brief Map of first declarations from a chained PCH that point to the
339  /// most recent declarations in another AST file.
340  FirstLatestDeclIDMap FirstLatestDeclIDs;
341
342  /// \brief Set of ObjC interfaces that have categories chained to them in
343  /// other modules.
344  llvm::DenseSet<serialization::GlobalDeclID> ObjCChainedCategoriesInterfaces;
345
346  /// \brief Read the records that describe the contents of declcontexts.
347  bool ReadDeclContextStorage(ModuleFile &M,
348                              llvm::BitstreamCursor &Cursor,
349                              const std::pair<uint64_t, uint64_t> &Offsets,
350                              serialization::DeclContextInfo &Info);
351
352  /// \brief A vector containing identifiers that have already been
353  /// loaded.
354  ///
355  /// If the pointer at index I is non-NULL, then it refers to the
356  /// IdentifierInfo for the identifier with ID=I+1 that has already
357  /// been loaded.
358  std::vector<IdentifierInfo *> IdentifiersLoaded;
359
360  typedef ContinuousRangeMap<serialization::IdentID, ModuleFile *, 4>
361    GlobalIdentifierMapType;
362
363  /// \brief Mapping from global identifer IDs to the module in which the
364  /// identifier resides along with the offset that should be added to the
365  /// global identifier ID to produce a local ID.
366  GlobalIdentifierMapType GlobalIdentifierMap;
367
368  /// \brief A vector containing submodules that have already been loaded.
369  ///
370  /// This vector is indexed by the Submodule ID (-1). NULL submodule entries
371  /// indicate that the particular submodule ID has not yet been loaded.
372  SmallVector<Module *, 2> SubmodulesLoaded;
373
374  typedef ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4>
375    GlobalSubmoduleMapType;
376
377  /// \brief Mapping from global submodule IDs to the module file in which the
378  /// submodule resides along with the offset that should be added to the
379  /// global submodule ID to produce a local ID.
380  GlobalSubmoduleMapType GlobalSubmoduleMap;
381
382  /// \brief A set of hidden declarations.
383  typedef llvm::SmallVector<llvm::PointerUnion<Decl *, IdentifierInfo *>, 2>
384    HiddenNames;
385
386  typedef llvm::DenseMap<Module *, HiddenNames> HiddenNamesMapType;
387
388  /// \brief A mapping from each of the hidden submodules to the deserialized
389  /// declarations in that submodule that could be made visible.
390  HiddenNamesMapType HiddenNamesMap;
391
392
393  /// \brief A module import or export that hasn't yet been resolved.
394  struct UnresolvedModuleImportExport {
395    /// \brief The file in which this module resides.
396    ModuleFile *File;
397
398    /// \brief The module that is importing or exporting.
399    Module *Mod;
400
401    /// \brief The local ID of the module that is being exported.
402    unsigned ID;
403
404    /// \brief Whether this is an import (vs. an export).
405    unsigned IsImport : 1;
406
407    /// \brief Whether this is a wildcard export.
408    unsigned IsWildcard : 1;
409  };
410
411  /// \brief The set of module imports and exports that still need to be
412  /// resolved.
413  llvm::SmallVector<UnresolvedModuleImportExport, 2>
414    UnresolvedModuleImportExports;
415
416  /// \brief A vector containing selectors that have already been loaded.
417  ///
418  /// This vector is indexed by the Selector ID (-1). NULL selector
419  /// entries indicate that the particular selector ID has not yet
420  /// been loaded.
421  SmallVector<Selector, 16> SelectorsLoaded;
422
423  typedef ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4>
424    GlobalSelectorMapType;
425
426  /// \brief Mapping from global selector IDs to the module in which the
427  /// selector resides along with the offset that should be added to the
428  /// global selector ID to produce a local ID.
429  GlobalSelectorMapType GlobalSelectorMap;
430
431  /// \brief Mapping from identifiers that represent macros whose definitions
432  /// have not yet been deserialized to the global offset where the macro
433  /// record resides.
434  llvm::DenseMap<IdentifierInfo *, uint64_t> UnreadMacroRecordOffsets;
435
436  typedef ContinuousRangeMap<unsigned, ModuleFile *, 4>
437    GlobalPreprocessedEntityMapType;
438
439  /// \brief Mapping from global preprocessing entity IDs to the module in
440  /// which the preprocessed entity resides along with the offset that should be
441  /// added to the global preprocessing entitiy ID to produce a local ID.
442  GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap;
443
444  /// \name CodeGen-relevant special data
445  /// \brief Fields containing data that is relevant to CodeGen.
446  //@{
447
448  /// \brief The IDs of all declarations that fulfill the criteria of
449  /// "interesting" decls.
450  ///
451  /// This contains the data loaded from all EXTERNAL_DEFINITIONS blocks in the
452  /// chain. The referenced declarations are deserialized and passed to the
453  /// consumer eagerly.
454  SmallVector<uint64_t, 16> ExternalDefinitions;
455
456  /// \brief The IDs of all tentative definitions stored in the the chain.
457  ///
458  /// Sema keeps track of all tentative definitions in a TU because it has to
459  /// complete them and pass them on to CodeGen. Thus, tentative definitions in
460  /// the PCH chain must be eagerly deserialized.
461  SmallVector<uint64_t, 16> TentativeDefinitions;
462
463  /// \brief The IDs of all CXXRecordDecls stored in the chain whose VTables are
464  /// used.
465  ///
466  /// CodeGen has to emit VTables for these records, so they have to be eagerly
467  /// deserialized.
468  SmallVector<uint64_t, 64> VTableUses;
469
470  /// \brief A snapshot of the pending instantiations in the chain.
471  ///
472  /// This record tracks the instantiations that Sema has to perform at the
473  /// end of the TU. It consists of a pair of values for every pending
474  /// instantiation where the first value is the ID of the decl and the second
475  /// is the instantiation location.
476  SmallVector<uint64_t, 64> PendingInstantiations;
477
478  //@}
479
480  /// \name DiagnosticsEngine-relevant special data
481  /// \brief Fields containing data that is used for generating diagnostics
482  //@{
483
484  /// \brief A snapshot of Sema's unused file-scoped variable tracking, for
485  /// generating warnings.
486  SmallVector<uint64_t, 16> UnusedFileScopedDecls;
487
488  /// \brief A list of all the delegating constructors we've seen, to diagnose
489  /// cycles.
490  SmallVector<uint64_t, 4> DelegatingCtorDecls;
491
492  /// \brief Method selectors used in a @selector expression. Used for
493  /// implementation of -Wselector.
494  SmallVector<uint64_t, 64> ReferencedSelectorsData;
495
496  /// \brief A snapshot of Sema's weak undeclared identifier tracking, for
497  /// generating warnings.
498  SmallVector<uint64_t, 64> WeakUndeclaredIdentifiers;
499
500  /// \brief The IDs of type aliases for ext_vectors that exist in the chain.
501  ///
502  /// Used by Sema for finding sugared names for ext_vectors in diagnostics.
503  SmallVector<uint64_t, 4> ExtVectorDecls;
504
505  //@}
506
507  /// \name Sema-relevant special data
508  /// \brief Fields containing data that is used for semantic analysis
509  //@{
510
511  /// \brief The IDs of all locally scoped external decls in the chain.
512  ///
513  /// Sema tracks these to validate that the types are consistent across all
514  /// local external declarations.
515  SmallVector<uint64_t, 16> LocallyScopedExternalDecls;
516
517  /// \brief The IDs of all dynamic class declarations in the chain.
518  ///
519  /// Sema tracks these because it checks for the key functions being defined
520  /// at the end of the TU, in which case it directs CodeGen to emit the VTable.
521  SmallVector<uint64_t, 16> DynamicClasses;
522
523  /// \brief The IDs of the declarations Sema stores directly.
524  ///
525  /// Sema tracks a few important decls, such as namespace std, directly.
526  SmallVector<uint64_t, 4> SemaDeclRefs;
527
528  /// \brief The IDs of the types ASTContext stores directly.
529  ///
530  /// The AST context tracks a few important types, such as va_list, directly.
531  SmallVector<uint64_t, 16> SpecialTypes;
532
533  /// \brief The IDs of CUDA-specific declarations ASTContext stores directly.
534  ///
535  /// The AST context tracks a few important decls, currently cudaConfigureCall,
536  /// directly.
537  SmallVector<uint64_t, 2> CUDASpecialDeclRefs;
538
539  /// \brief The floating point pragma option settings.
540  SmallVector<uint64_t, 1> FPPragmaOptions;
541
542  /// \brief The OpenCL extension settings.
543  SmallVector<uint64_t, 1> OpenCLExtensions;
544
545  /// \brief A list of the namespaces we've seen.
546  SmallVector<uint64_t, 4> KnownNamespaces;
547
548  /// \brief A list of modules that were imported by precompiled headers or
549  /// any other non-module AST file.
550  SmallVector<serialization::SubmoduleID, 2> ImportedModules;
551  //@}
552
553  /// \brief The original file name that was used to build the primary AST file,
554  /// which may have been modified for relocatable-pch support.
555  std::string OriginalFileName;
556
557  /// \brief The actual original file name that was used to build the primary
558  /// AST file.
559  std::string ActualOriginalFileName;
560
561  /// \brief The file ID for the original file that was used to build the
562  /// primary AST file.
563  FileID OriginalFileID;
564
565  /// \brief The directory that the PCH was originally created in. Used to
566  /// allow resolving headers even after headers+PCH was moved to a new path.
567  std::string OriginalDir;
568
569  /// \brief The directory that the PCH we are reading is stored in.
570  std::string CurrentDir;
571
572  /// \brief Whether this precompiled header is a relocatable PCH file.
573  bool RelocatablePCH;
574
575  /// \brief The system include root to be used when loading the
576  /// precompiled header.
577  std::string isysroot;
578
579  /// \brief Whether to disable the normal validation performed on precompiled
580  /// headers when they are loaded.
581  bool DisableValidation;
582
583  /// \brief Whether to disable the use of stat caches in AST files.
584  bool DisableStatCache;
585
586  /// \brief Mapping from switch-case IDs in the chain to switch-case statements
587  ///
588  /// Statements usually don't have IDs, but switch cases need them, so that the
589  /// switch statement can refer to them.
590  std::map<unsigned, SwitchCase *> SwitchCaseStmts;
591
592  /// \brief The number of stat() calls that hit/missed the stat
593  /// cache.
594  unsigned NumStatHits, NumStatMisses;
595
596  /// \brief The number of source location entries de-serialized from
597  /// the PCH file.
598  unsigned NumSLocEntriesRead;
599
600  /// \brief The number of source location entries in the chain.
601  unsigned TotalNumSLocEntries;
602
603  /// \brief The number of statements (and expressions) de-serialized
604  /// from the chain.
605  unsigned NumStatementsRead;
606
607  /// \brief The total number of statements (and expressions) stored
608  /// in the chain.
609  unsigned TotalNumStatements;
610
611  /// \brief The number of macros de-serialized from the chain.
612  unsigned NumMacrosRead;
613
614  /// \brief The total number of macros stored in the chain.
615  unsigned TotalNumMacros;
616
617  /// \brief The number of selectors that have been read.
618  unsigned NumSelectorsRead;
619
620  /// \brief The number of method pool entries that have been read.
621  unsigned NumMethodPoolEntriesRead;
622
623  /// \brief The number of times we have looked up a selector in the method
624  /// pool and not found anything interesting.
625  unsigned NumMethodPoolMisses;
626
627  /// \brief The total number of method pool entries in the selector table.
628  unsigned TotalNumMethodPoolEntries;
629
630  /// Number of lexical decl contexts read/total.
631  unsigned NumLexicalDeclContextsRead, TotalLexicalDeclContexts;
632
633  /// Number of visible decl contexts read/total.
634  unsigned NumVisibleDeclContextsRead, TotalVisibleDeclContexts;
635
636  /// Total size of modules, in bits, currently loaded
637  uint64_t TotalModulesSizeInBits;
638
639  /// \brief Number of Decl/types that are currently deserializing.
640  unsigned NumCurrentElementsDeserializing;
641
642  /// Number of CXX base specifiers currently loaded
643  unsigned NumCXXBaseSpecifiersLoaded;
644
645  /// \brief An IdentifierInfo that has been loaded but whose top-level
646  /// declarations of the same name have not (yet) been loaded.
647  struct PendingIdentifierInfo {
648    IdentifierInfo *II;
649    SmallVector<uint32_t, 4> DeclIDs;
650  };
651
652  /// \brief The set of identifiers that were read while the AST reader was
653  /// (recursively) loading declarations.
654  ///
655  /// The declarations on the identifier chain for these identifiers will be
656  /// loaded once the recursive loading has completed.
657  std::deque<PendingIdentifierInfo> PendingIdentifierInfos;
658
659  /// \brief Contains declarations and definitions that will be
660  /// "interesting" to the ASTConsumer, when we get that AST consumer.
661  ///
662  /// "Interesting" declarations are those that have data that may
663  /// need to be emitted, such as inline function definitions or
664  /// Objective-C protocols.
665  std::deque<Decl *> InterestingDecls;
666
667  /// \brief We delay loading of the previous declaration chain to avoid
668  /// deeply nested calls when there are many redeclarations.
669  std::deque<std::pair<Decl *, serialization::DeclID> > PendingPreviousDecls;
670
671  /// \brief The list of redeclaration chains that still need to be
672  /// reconstructed.
673  ///
674  /// Each element is the global declaration ID of the first declaration in
675  /// the chain. Elements in this vector should be unique; use
676  /// PendingDeclChainsKnown to ensure uniqueness.
677  llvm::SmallVector<serialization::DeclID, 16> PendingDeclChains;
678
679  /// \brief Keeps track of the elements added to PendingDeclChains.
680  llvm::SmallSet<serialization::DeclID, 16> PendingDeclChainsKnown;
681
682  /// \brief We delay loading the chain of objc categories after recursive
683  /// loading of declarations is finished.
684  std::vector<std::pair<ObjCInterfaceDecl *, serialization::DeclID> >
685    PendingChainedObjCCategories;
686
687  /// \brief Ready to load the previous declaration of the given Decl.
688  void loadAndAttachPreviousDecl(Decl *D, serialization::DeclID ID);
689
690  /// \brief When reading a Stmt tree, Stmt operands are placed in this stack.
691  SmallVector<Stmt *, 16> StmtStack;
692
693  /// \brief What kind of records we are reading.
694  enum ReadingKind {
695    Read_Decl, Read_Type, Read_Stmt
696  };
697
698  /// \brief What kind of records we are reading.
699  ReadingKind ReadingKind;
700
701  /// \brief RAII object to change the reading kind.
702  class ReadingKindTracker {
703    ASTReader &Reader;
704    enum ReadingKind PrevKind;
705
706    ReadingKindTracker(const ReadingKindTracker&); // do not implement
707    ReadingKindTracker &operator=(const ReadingKindTracker&);// do not implement
708
709  public:
710    ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
711      : Reader(reader), PrevKind(Reader.ReadingKind) {
712      Reader.ReadingKind = newKind;
713    }
714
715    ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; }
716  };
717
718  /// \brief All predefines buffers in the chain, to be treated as if
719  /// concatenated.
720  PCHPredefinesBlocks PCHPredefinesBuffers;
721
722  /// \brief Suggested contents of the predefines buffer, after this
723  /// PCH file has been processed.
724  ///
725  /// In most cases, this string will be empty, because the predefines
726  /// buffer computed to build the PCH file will be identical to the
727  /// predefines buffer computed from the command line. However, when
728  /// there are differences that the PCH reader can work around, this
729  /// predefines buffer may contain additional definitions.
730  std::string SuggestedPredefines;
731
732  /// \brief Reads a statement from the specified cursor.
733  Stmt *ReadStmtFromStream(ModuleFile &F);
734
735  /// \brief Get a FileEntry out of stored-in-PCH filename, making sure we take
736  /// into account all the necessary relocations.
737  const FileEntry *getFileEntry(StringRef filename);
738
739  void MaybeAddSystemRootToFilename(std::string &Filename);
740
741  ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
742                            ModuleFile *ImportedBy);
743  ASTReadResult ReadASTBlock(ModuleFile &F);
744  bool CheckPredefinesBuffers();
745  bool ParseLineTable(ModuleFile &F, SmallVectorImpl<uint64_t> &Record);
746  ASTReadResult ReadSourceManagerBlock(ModuleFile &F);
747  ASTReadResult ReadSLocEntryRecord(int ID);
748  llvm::BitstreamCursor &SLocCursorForID(int ID);
749  SourceLocation getImportLocation(ModuleFile *F);
750  ASTReadResult ReadSubmoduleBlock(ModuleFile &F);
751  bool ParseLanguageOptions(const SmallVectorImpl<uint64_t> &Record);
752
753  struct RecordLocation {
754    RecordLocation(ModuleFile *M, uint64_t O)
755      : F(M), Offset(O) {}
756    ModuleFile *F;
757    uint64_t Offset;
758  };
759
760  QualType readTypeRecord(unsigned Index);
761  RecordLocation TypeCursorForIndex(unsigned Index);
762  void LoadedDecl(unsigned Index, Decl *D);
763  Decl *ReadDeclRecord(serialization::DeclID ID);
764  RecordLocation DeclCursorForID(serialization::DeclID ID,
765                                 unsigned &RawLocation);
766  void loadDeclUpdateRecords(serialization::DeclID ID, Decl *D);
767  void loadPendingDeclChain(serialization::GlobalDeclID ID);
768  void loadObjCChainedCategories(serialization::GlobalDeclID ID,
769                                 ObjCInterfaceDecl *D);
770
771  RecordLocation getLocalBitOffset(uint64_t GlobalOffset);
772  uint64_t getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset);
773
774  /// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
775  serialization::PreprocessedEntityID
776    findBeginPreprocessedEntity(SourceLocation BLoc) const;
777
778  /// \brief Returns the first preprocessed entity ID that begins after \arg
779  /// ELoc.
780  serialization::PreprocessedEntityID
781    findEndPreprocessedEntity(SourceLocation ELoc) const;
782
783  /// \brief \arg SLocMapI points at a chunk of a module that contains no
784  /// preprocessed entities or the entities it contains are not the ones we are
785  /// looking for. Find the next module that contains entities and return the ID
786  /// of the first entry.
787  serialization::PreprocessedEntityID
788    findNextPreprocessedEntity(
789                        GlobalSLocOffsetMapType::const_iterator SLocMapI) const;
790
791  /// \brief Returns (ModuleFile, Local index) pair for \arg GlobalIndex of a
792  /// preprocessed entity.
793  std::pair<ModuleFile *, unsigned>
794    getModulePreprocessedEntity(unsigned GlobalIndex);
795
796  void PassInterestingDeclsToConsumer();
797  void PassInterestingDeclToConsumer(Decl *D);
798
799  void finishPendingActions();
800
801  /// \brief Produce an error diagnostic and return true.
802  ///
803  /// This routine should only be used for fatal errors that have to
804  /// do with non-routine failures (e.g., corrupted AST file).
805  void Error(StringRef Msg);
806  void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
807             StringRef Arg2 = StringRef());
808
809  ASTReader(const ASTReader&); // do not implement
810  ASTReader &operator=(const ASTReader &); // do not implement
811public:
812  typedef SmallVector<uint64_t, 64> RecordData;
813
814  /// \brief Load the AST file and validate its contents against the given
815  /// Preprocessor.
816  ///
817  /// \param PP the preprocessor associated with the context in which this
818  /// precompiled header will be loaded.
819  ///
820  /// \param Context the AST context that this precompiled header will be
821  /// loaded into.
822  ///
823  /// \param isysroot If non-NULL, the system include path specified by the
824  /// user. This is only used with relocatable PCH files. If non-NULL,
825  /// a relocatable PCH file will use the default path "/".
826  ///
827  /// \param DisableValidation If true, the AST reader will suppress most
828  /// of its regular consistency checking, allowing the use of precompiled
829  /// headers that cannot be determined to be compatible.
830  ///
831  /// \param DisableStatCache If true, the AST reader will ignore the
832  /// stat cache in the AST files. This performance pessimization can
833  /// help when an AST file is being used in cases where the
834  /// underlying files in the file system may have changed, but
835  /// parsing should still continue.
836  ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot = "",
837            bool DisableValidation = false, bool DisableStatCache = false);
838
839  ~ASTReader();
840
841  SourceManager &getSourceManager() const { return SourceMgr; }
842
843  /// \brief Load the AST file designated by the given file name.
844  ASTReadResult ReadAST(const std::string &FileName, ModuleKind Type);
845
846  /// \brief Checks that no file that is stored in PCH is out-of-sync with
847  /// the actual file in the file system.
848  ASTReadResult validateFileEntries(ModuleFile &M);
849
850  /// \brief Make the entities in the given module and any of its (non-explicit)
851  /// submodules visible to name lookup.
852  ///
853  /// \param Mod The module whose names should be made visible.
854  ///
855  /// \param Visibility The level of visibility to give the names in the module.
856  /// Visibility can only be increased over time.
857  void makeModuleVisible(Module *Mod,
858                         Module::NameVisibilityKind NameVisibility);
859
860  /// \brief Make the names within this set of hidden names visible.
861  void makeNamesVisible(const HiddenNames &Names);
862
863  /// \brief Set the AST callbacks listener.
864  void setListener(ASTReaderListener *listener) {
865    Listener.reset(listener);
866  }
867
868  /// \brief Set the AST deserialization listener.
869  void setDeserializationListener(ASTDeserializationListener *Listener);
870
871  /// \brief Initializes the ASTContext
872  void InitializeContext();
873
874  /// \brief Add in-memory (virtual file) buffer.
875  void addInMemoryBuffer(StringRef &FileName, llvm::MemoryBuffer *Buffer) {
876    ModuleMgr.addInMemoryBuffer(FileName, Buffer);
877  }
878
879  /// \brief Finalizes the AST reader's state before writing an AST file to
880  /// disk.
881  ///
882  /// This operation may undo temporary state in the AST that should not be
883  /// emitted.
884  void finalizeForWriting();
885
886  /// \brief Retrieve the module manager.
887  ModuleManager &getModuleManager() { return ModuleMgr; }
888
889  /// \brief Retrieve the preprocessor.
890  Preprocessor &getPreprocessor() const { return PP; }
891
892  /// \brief Retrieve the name of the original source file name
893  const std::string &getOriginalSourceFile() { return OriginalFileName; }
894
895  /// \brief Retrieve the name of the original source file name directly from
896  /// the AST file, without actually loading the AST file.
897  static std::string getOriginalSourceFile(const std::string &ASTFileName,
898                                           FileManager &FileMgr,
899                                           DiagnosticsEngine &Diags);
900
901  /// \brief Returns the suggested contents of the predefines buffer,
902  /// which contains a (typically-empty) subset of the predefines
903  /// build prior to including the precompiled header.
904  const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
905
906  /// \brief Read a preallocated preprocessed entity from the external source.
907  ///
908  /// \returns null if an error occurred that prevented the preprocessed
909  /// entity from being loaded.
910  virtual PreprocessedEntity *ReadPreprocessedEntity(unsigned Index);
911
912  /// \brief Returns a pair of [Begin, End) indices of preallocated
913  /// preprocessed entities that \arg Range encompasses.
914  virtual std::pair<unsigned, unsigned>
915      findPreprocessedEntitiesInRange(SourceRange Range);
916
917  /// \brief Optionally returns true or false if the preallocated preprocessed
918  /// entity with index \arg Index came from file \arg FID.
919  virtual llvm::Optional<bool> isPreprocessedEntityInFileID(unsigned Index,
920                                                            FileID FID);
921
922  /// \brief Read the header file information for the given file entry.
923  virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE);
924
925  void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag);
926
927  /// \brief Returns the number of source locations found in the chain.
928  unsigned getTotalNumSLocs() const {
929    return TotalNumSLocEntries;
930  }
931
932  /// \brief Returns the number of identifiers found in the chain.
933  unsigned getTotalNumIdentifiers() const {
934    return static_cast<unsigned>(IdentifiersLoaded.size());
935  }
936
937  /// \brief Returns the number of types found in the chain.
938  unsigned getTotalNumTypes() const {
939    return static_cast<unsigned>(TypesLoaded.size());
940  }
941
942  /// \brief Returns the number of declarations found in the chain.
943  unsigned getTotalNumDecls() const {
944    return static_cast<unsigned>(DeclsLoaded.size());
945  }
946
947  /// \brief Returns the number of submodules known.
948  unsigned getTotalNumSubmodules() const {
949    return static_cast<unsigned>(SubmodulesLoaded.size());
950  }
951
952  /// \brief Returns the number of selectors found in the chain.
953  unsigned getTotalNumSelectors() const {
954    return static_cast<unsigned>(SelectorsLoaded.size());
955  }
956
957  /// \brief Returns the number of preprocessed entities known to the AST
958  /// reader.
959  unsigned getTotalNumPreprocessedEntities() const {
960    unsigned Result = 0;
961    for (ModuleConstIterator I = ModuleMgr.begin(),
962        E = ModuleMgr.end(); I != E; ++I) {
963      Result += (*I)->NumPreprocessedEntities;
964    }
965
966    return Result;
967  }
968
969  /// \brief Returns the number of C++ base specifiers found in the chain.
970  unsigned getTotalNumCXXBaseSpecifiers() const {
971    return NumCXXBaseSpecifiersLoaded;
972  }
973
974  /// \brief Reads a TemplateArgumentLocInfo appropriate for the
975  /// given TemplateArgument kind.
976  TemplateArgumentLocInfo
977  GetTemplateArgumentLocInfo(ModuleFile &F, TemplateArgument::ArgKind Kind,
978                             const RecordData &Record, unsigned &Idx);
979
980  /// \brief Reads a TemplateArgumentLoc.
981  TemplateArgumentLoc
982  ReadTemplateArgumentLoc(ModuleFile &F,
983                          const RecordData &Record, unsigned &Idx);
984
985  /// \brief Reads a declarator info from the given record.
986  TypeSourceInfo *GetTypeSourceInfo(ModuleFile &F,
987                                    const RecordData &Record, unsigned &Idx);
988
989  /// \brief Resolve a type ID into a type, potentially building a new
990  /// type.
991  QualType GetType(serialization::TypeID ID);
992
993  /// \brief Resolve a local type ID within a given AST file into a type.
994  QualType getLocalType(ModuleFile &F, unsigned LocalID);
995
996  /// \brief Map a local type ID within a given AST file into a global type ID.
997  serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const;
998
999  /// \brief Read a type from the current position in the given record, which
1000  /// was read from the given AST file.
1001  QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) {
1002    if (Idx >= Record.size())
1003      return QualType();
1004
1005    return getLocalType(F, Record[Idx++]);
1006  }
1007
1008  /// \brief Map from a local declaration ID within a given module to a
1009  /// global declaration ID.
1010  serialization::DeclID getGlobalDeclID(ModuleFile &F, unsigned LocalID) const;
1011
1012  /// \brief Returns true if global DeclID \arg ID originated from module
1013  /// \arg M.
1014  bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const;
1015
1016  /// \brief Returns the source location for the decl \arg ID.
1017  SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID);
1018
1019  /// \brief Resolve a declaration ID into a declaration, potentially
1020  /// building a new declaration.
1021  Decl *GetDecl(serialization::DeclID ID);
1022  virtual Decl *GetExternalDecl(uint32_t ID);
1023
1024  /// \brief Reads a declaration with the given local ID in the given module.
1025  Decl *GetLocalDecl(ModuleFile &F, uint32_t LocalID) {
1026    return GetDecl(getGlobalDeclID(F, LocalID));
1027  }
1028
1029  /// \brief Reads a declaration with the given local ID in the given module.
1030  ///
1031  /// \returns The requested declaration, casted to the given return type.
1032  template<typename T>
1033  T *GetLocalDeclAs(ModuleFile &F, uint32_t LocalID) {
1034    return cast_or_null<T>(GetLocalDecl(F, LocalID));
1035  }
1036
1037  /// \brief Map a global declaration ID into the declaration ID used to
1038  /// refer to this declaration within the given module fule.
1039  ///
1040  /// \returns the global ID of the given declaration as known in the given
1041  /// module file.
1042  serialization::DeclID
1043  mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
1044                                  serialization::DeclID GlobalID);
1045
1046  /// \brief Reads a declaration ID from the given position in a record in the
1047  /// given module.
1048  ///
1049  /// \returns The declaration ID read from the record, adjusted to a global ID.
1050  serialization::DeclID ReadDeclID(ModuleFile &F, const RecordData &Record,
1051                                   unsigned &Idx);
1052
1053  /// \brief Reads a declaration from the given position in a record in the
1054  /// given module.
1055  Decl *ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I) {
1056    return GetDecl(ReadDeclID(F, R, I));
1057  }
1058
1059  /// \brief Reads a declaration from the given position in a record in the
1060  /// given module.
1061  ///
1062  /// \returns The declaration read from this location, casted to the given
1063  /// result type.
1064  template<typename T>
1065  T *ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I) {
1066    return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
1067  }
1068
1069  /// \brief Read a CXXBaseSpecifiers ID form the given record and
1070  /// return its global bit offset.
1071  uint64_t readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
1072                                 unsigned &Idx);
1073
1074  virtual CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset);
1075
1076  /// \brief Resolve the offset of a statement into a statement.
1077  ///
1078  /// This operation will read a new statement from the external
1079  /// source each time it is called, and is meant to be used via a
1080  /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1081  virtual Stmt *GetExternalDeclStmt(uint64_t Offset);
1082
1083  /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1084  /// specified cursor.  Read the abbreviations that are at the top of the block
1085  /// and then leave the cursor pointing into the block.
1086  bool ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID);
1087
1088  /// \brief Finds all the visible declarations with a given name.
1089  /// The current implementation of this method just loads the entire
1090  /// lookup table as unmaterialized references.
1091  virtual DeclContext::lookup_result
1092  FindExternalVisibleDeclsByName(const DeclContext *DC,
1093                                 DeclarationName Name);
1094
1095  /// \brief Read all of the declarations lexically stored in a
1096  /// declaration context.
1097  ///
1098  /// \param DC The declaration context whose declarations will be
1099  /// read.
1100  ///
1101  /// \param Decls Vector that will contain the declarations loaded
1102  /// from the external source. The caller is responsible for merging
1103  /// these declarations with any declarations already stored in the
1104  /// declaration context.
1105  ///
1106  /// \returns true if there was an error while reading the
1107  /// declarations for this declaration context.
1108  virtual ExternalLoadResult FindExternalLexicalDecls(const DeclContext *DC,
1109                                        bool (*isKindWeWant)(Decl::Kind),
1110                                        SmallVectorImpl<Decl*> &Decls);
1111
1112  /// \brief Get the decls that are contained in a file in the Offset/Length
1113  /// range. \arg Length can be 0 to indicate a point at \arg Offset instead of
1114  /// a range.
1115  virtual void FindFileRegionDecls(FileID File, unsigned Offset,unsigned Length,
1116                                   SmallVectorImpl<Decl *> &Decls);
1117
1118  /// \brief Notify ASTReader that we started deserialization of
1119  /// a decl or type so until FinishedDeserializing is called there may be
1120  /// decls that are initializing. Must be paired with FinishedDeserializing.
1121  virtual void StartedDeserializing() { ++NumCurrentElementsDeserializing; }
1122
1123  /// \brief Notify ASTReader that we finished the deserialization of
1124  /// a decl or type. Must be paired with StartedDeserializing.
1125  virtual void FinishedDeserializing();
1126
1127  /// \brief Function that will be invoked when we begin parsing a new
1128  /// translation unit involving this external AST source.
1129  ///
1130  /// This function will provide all of the external definitions to
1131  /// the ASTConsumer.
1132  virtual void StartTranslationUnit(ASTConsumer *Consumer);
1133
1134  /// \brief Print some statistics about AST usage.
1135  virtual void PrintStats();
1136
1137  /// \brief Dump information about the AST reader to standard error.
1138  void dump();
1139
1140  /// Return the amount of memory used by memory buffers, breaking down
1141  /// by heap-backed versus mmap'ed memory.
1142  virtual void getMemoryBufferSizes(MemoryBufferSizes &sizes) const;
1143
1144  /// \brief Initialize the semantic source with the Sema instance
1145  /// being used to perform semantic analysis on the abstract syntax
1146  /// tree.
1147  virtual void InitializeSema(Sema &S);
1148
1149  /// \brief Inform the semantic consumer that Sema is no longer available.
1150  virtual void ForgetSema() { SemaObj = 0; }
1151
1152  /// \brief Retrieve the IdentifierInfo for the named identifier.
1153  ///
1154  /// This routine builds a new IdentifierInfo for the given identifier. If any
1155  /// declarations with this name are visible from translation unit scope, their
1156  /// declarations will be deserialized and introduced into the declaration
1157  /// chain of the identifier.
1158  virtual IdentifierInfo *get(const char *NameStart, const char *NameEnd);
1159  IdentifierInfo *get(StringRef Name) {
1160    return get(Name.begin(), Name.end());
1161  }
1162
1163  /// \brief Retrieve an iterator into the set of all identifiers
1164  /// in all loaded AST files.
1165  virtual IdentifierIterator *getIdentifiers() const;
1166
1167  /// \brief Load the contents of the global method pool for a given
1168  /// selector.
1169  ///
1170  /// \returns a pair of Objective-C methods lists containing the
1171  /// instance and factory methods, respectively, with this selector.
1172  virtual std::pair<ObjCMethodList, ObjCMethodList>
1173    ReadMethodPool(Selector Sel);
1174
1175  /// \brief Load the set of namespaces that are known to the external source,
1176  /// which will be used during typo correction.
1177  virtual void ReadKnownNamespaces(
1178                           SmallVectorImpl<NamespaceDecl *> &Namespaces);
1179
1180  virtual void ReadTentativeDefinitions(
1181                 SmallVectorImpl<VarDecl *> &TentativeDefs);
1182
1183  virtual void ReadUnusedFileScopedDecls(
1184                 SmallVectorImpl<const DeclaratorDecl *> &Decls);
1185
1186  virtual void ReadDelegatingConstructors(
1187                 SmallVectorImpl<CXXConstructorDecl *> &Decls);
1188
1189  virtual void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls);
1190
1191  virtual void ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls);
1192
1193  virtual void ReadLocallyScopedExternalDecls(
1194                 SmallVectorImpl<NamedDecl *> &Decls);
1195
1196  virtual void ReadReferencedSelectors(
1197                 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels);
1198
1199  virtual void ReadWeakUndeclaredIdentifiers(
1200                 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WI);
1201
1202  virtual void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables);
1203
1204  virtual void ReadPendingInstantiations(
1205                 SmallVectorImpl<std::pair<ValueDecl *,
1206                                           SourceLocation> > &Pending);
1207
1208  /// \brief Load a selector from disk, registering its ID if it exists.
1209  void LoadSelector(Selector Sel);
1210
1211  void SetIdentifierInfo(unsigned ID, IdentifierInfo *II);
1212  void SetGloballyVisibleDecls(IdentifierInfo *II,
1213                               const SmallVectorImpl<uint32_t> &DeclIDs,
1214                               bool Nonrecursive = false);
1215
1216  /// \brief Report a diagnostic.
1217  DiagnosticBuilder Diag(unsigned DiagID);
1218
1219  /// \brief Report a diagnostic.
1220  DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
1221
1222  IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID);
1223
1224  IdentifierInfo *GetIdentifierInfo(ModuleFile &M, const RecordData &Record,
1225                                    unsigned &Idx) {
1226    return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++]));
1227  }
1228
1229  virtual IdentifierInfo *GetIdentifier(serialization::IdentifierID ID) {
1230    return DecodeIdentifierInfo(ID);
1231  }
1232
1233  IdentifierInfo *getLocalIdentifier(ModuleFile &M, unsigned LocalID);
1234
1235  serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M,
1236                                                    unsigned LocalID);
1237
1238  /// \brief Read the source location entry with index ID.
1239  virtual bool ReadSLocEntry(int ID);
1240
1241  /// \brief Retrieve the global submodule ID given a module and its local ID
1242  /// number.
1243  serialization::SubmoduleID
1244  getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID);
1245
1246  /// \brief Retrieve the submodule that corresponds to a global submodule ID.
1247  ///
1248  Module *getSubmodule(serialization::SubmoduleID GlobalID);
1249
1250  /// \brief Retrieve a selector from the given module with its local ID
1251  /// number.
1252  Selector getLocalSelector(ModuleFile &M, unsigned LocalID);
1253
1254  Selector DecodeSelector(serialization::SelectorID Idx);
1255
1256  virtual Selector GetExternalSelector(serialization::SelectorID ID);
1257  uint32_t GetNumExternalSelectors();
1258
1259  Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) {
1260    return getLocalSelector(M, Record[Idx++]);
1261  }
1262
1263  /// \brief Retrieve the global selector ID that corresponds to this
1264  /// the local selector ID in a given module.
1265  serialization::SelectorID getGlobalSelectorID(ModuleFile &F,
1266                                                unsigned LocalID) const;
1267
1268  /// \brief Read a declaration name.
1269  DeclarationName ReadDeclarationName(ModuleFile &F,
1270                                      const RecordData &Record, unsigned &Idx);
1271  void ReadDeclarationNameLoc(ModuleFile &F,
1272                              DeclarationNameLoc &DNLoc, DeclarationName Name,
1273                              const RecordData &Record, unsigned &Idx);
1274  void ReadDeclarationNameInfo(ModuleFile &F, DeclarationNameInfo &NameInfo,
1275                               const RecordData &Record, unsigned &Idx);
1276
1277  void ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
1278                         const RecordData &Record, unsigned &Idx);
1279
1280  NestedNameSpecifier *ReadNestedNameSpecifier(ModuleFile &F,
1281                                               const RecordData &Record,
1282                                               unsigned &Idx);
1283
1284  NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(ModuleFile &F,
1285                                                    const RecordData &Record,
1286                                                    unsigned &Idx);
1287
1288  /// \brief Read a template name.
1289  TemplateName ReadTemplateName(ModuleFile &F, const RecordData &Record,
1290                                unsigned &Idx);
1291
1292  /// \brief Read a template argument.
1293  TemplateArgument ReadTemplateArgument(ModuleFile &F,
1294                                        const RecordData &Record,unsigned &Idx);
1295
1296  /// \brief Read a template parameter list.
1297  TemplateParameterList *ReadTemplateParameterList(ModuleFile &F,
1298                                                   const RecordData &Record,
1299                                                   unsigned &Idx);
1300
1301  /// \brief Read a template argument array.
1302  void
1303  ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
1304                           ModuleFile &F, const RecordData &Record,
1305                           unsigned &Idx);
1306
1307  /// \brief Read a UnresolvedSet structure.
1308  void ReadUnresolvedSet(ModuleFile &F, UnresolvedSetImpl &Set,
1309                         const RecordData &Record, unsigned &Idx);
1310
1311  /// \brief Read a C++ base specifier.
1312  CXXBaseSpecifier ReadCXXBaseSpecifier(ModuleFile &F,
1313                                        const RecordData &Record,unsigned &Idx);
1314
1315  /// \brief Read a CXXCtorInitializer array.
1316  std::pair<CXXCtorInitializer **, unsigned>
1317  ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
1318                          unsigned &Idx);
1319
1320  /// \brief Read a source location from raw form.
1321  SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, unsigned Raw) const {
1322    SourceLocation Loc = SourceLocation::getFromRawEncoding(Raw);
1323    assert(ModuleFile.SLocRemap.find(Loc.getOffset()) != ModuleFile.SLocRemap.end() &&
1324           "Cannot find offset to remap.");
1325    int Remap = ModuleFile.SLocRemap.find(Loc.getOffset())->second;
1326    return Loc.getLocWithOffset(Remap);
1327  }
1328
1329  /// \brief Read a source location.
1330  SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
1331                                    const RecordData &Record, unsigned& Idx) {
1332    return ReadSourceLocation(ModuleFile, Record[Idx++]);
1333  }
1334
1335  /// \brief Read a source range.
1336  SourceRange ReadSourceRange(ModuleFile &F,
1337                              const RecordData &Record, unsigned& Idx);
1338
1339  /// \brief Read an integral value
1340  llvm::APInt ReadAPInt(const RecordData &Record, unsigned &Idx);
1341
1342  /// \brief Read a signed integral value
1343  llvm::APSInt ReadAPSInt(const RecordData &Record, unsigned &Idx);
1344
1345  /// \brief Read a floating-point value
1346  llvm::APFloat ReadAPFloat(const RecordData &Record, unsigned &Idx);
1347
1348  // \brief Read a string
1349  std::string ReadString(const RecordData &Record, unsigned &Idx);
1350
1351  /// \brief Read a version tuple.
1352  VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
1353
1354  CXXTemporary *ReadCXXTemporary(ModuleFile &F, const RecordData &Record,
1355                                 unsigned &Idx);
1356
1357  /// \brief Reads attributes from the current stream position.
1358  void ReadAttributes(ModuleFile &F, AttrVec &Attrs,
1359                      const RecordData &Record, unsigned &Idx);
1360
1361  /// \brief Reads a statement.
1362  Stmt *ReadStmt(ModuleFile &F);
1363
1364  /// \brief Reads an expression.
1365  Expr *ReadExpr(ModuleFile &F);
1366
1367  /// \brief Reads a sub-statement operand during statement reading.
1368  Stmt *ReadSubStmt() {
1369    assert(ReadingKind == Read_Stmt &&
1370           "Should be called only during statement reading!");
1371    // Subexpressions are stored from last to first, so the next Stmt we need
1372    // is at the back of the stack.
1373    assert(!StmtStack.empty() && "Read too many sub statements!");
1374    return StmtStack.pop_back_val();
1375  }
1376
1377  /// \brief Reads a sub-expression operand during statement reading.
1378  Expr *ReadSubExpr();
1379
1380  /// \brief Reads the macro record located at the given offset.
1381  void ReadMacroRecord(ModuleFile &F, uint64_t Offset);
1382
1383  /// \brief Determine the global preprocessed entity ID that corresponds to
1384  /// the given local ID within the given module.
1385  serialization::PreprocessedEntityID
1386  getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const;
1387
1388  /// \brief Note that the identifier is a macro whose record will be loaded
1389  /// from the given AST file at the given (file-local) offset.
1390  ///
1391  /// \param II The name of the macro.
1392  ///
1393  /// \param F The module file from which the macro definition was deserialized.
1394  ///
1395  /// \param Offset The offset into the module file at which the macro
1396  /// definition is located.
1397  ///
1398  /// \param Visible Whether the macro should be made visible.
1399  void setIdentifierIsMacro(IdentifierInfo *II, ModuleFile &F,
1400                            uint64_t Offset, bool Visible);
1401
1402  /// \brief Read the set of macros defined by this external macro source.
1403  virtual void ReadDefinedMacros();
1404
1405  /// \brief Read the macro definition for this identifier.
1406  virtual void LoadMacroDefinition(IdentifierInfo *II);
1407
1408  /// \brief Update an out-of-date identifier.
1409  virtual void updateOutOfDateIdentifier(IdentifierInfo &II);
1410
1411  /// \brief Read the macro definition corresponding to this iterator
1412  /// into the unread macro record offsets table.
1413  void LoadMacroDefinition(
1414                     llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos);
1415
1416  /// \brief Retrieve the AST context that this AST reader supplements.
1417  ASTContext &getContext() { return Context; }
1418
1419  // \brief Contains declarations that were loaded before we have
1420  // access to a Sema object.
1421  SmallVector<NamedDecl *, 16> PreloadedDecls;
1422
1423  /// \brief Retrieve the semantic analysis object used to analyze the
1424  /// translation unit in which the precompiled header is being
1425  /// imported.
1426  Sema *getSema() { return SemaObj; }
1427
1428  /// \brief Retrieve the identifier table associated with the
1429  /// preprocessor.
1430  IdentifierTable &getIdentifierTable();
1431
1432  /// \brief Record that the given ID maps to the given switch-case
1433  /// statement.
1434  void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
1435
1436  /// \brief Retrieve the switch-case statement with the given ID.
1437  SwitchCase *getSwitchCaseWithID(unsigned ID);
1438
1439  void ClearSwitchCaseIDs();
1440};
1441
1442/// \brief Helper class that saves the current stream position and
1443/// then restores it when destroyed.
1444struct SavedStreamPosition {
1445  explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor)
1446  : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) { }
1447
1448  ~SavedStreamPosition() {
1449    Cursor.JumpToBit(Offset);
1450  }
1451
1452private:
1453  llvm::BitstreamCursor &Cursor;
1454  uint64_t Offset;
1455};
1456
1457inline void PCHValidator::Error(const char *Msg) {
1458  Reader.Error(Msg);
1459}
1460
1461} // end namespace clang
1462
1463#endif
1464