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