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