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