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