1 //===- ASTReader.h - AST File Reader ----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ASTReader class, which reads AST files.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_SERIALIZATION_ASTREADER_H
15 #define LLVM_CLANG_SERIALIZATION_ASTREADER_H
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclarationName.h"
20 #include "clang/AST/NestedNameSpecifier.h"
21 #include "clang/AST/TemplateBase.h"
22 #include "clang/AST/TemplateName.h"
23 #include "clang/AST/Type.h"
24 #include "clang/Basic/Diagnostic.h"
25 #include "clang/Basic/DiagnosticOptions.h"
26 #include "clang/Basic/IdentifierTable.h"
27 #include "clang/Basic/Module.h"
28 #include "clang/Basic/OpenCLOptions.h"
29 #include "clang/Basic/SourceLocation.h"
30 #include "clang/Basic/Version.h"
31 #include "clang/Lex/ExternalPreprocessorSource.h"
32 #include "clang/Lex/HeaderSearch.h"
33 #include "clang/Lex/PreprocessingRecord.h"
34 #include "clang/Lex/Token.h"
35 #include "clang/Sema/ExternalSemaSource.h"
36 #include "clang/Sema/IdentifierResolver.h"
37 #include "clang/Serialization/ASTBitCodes.h"
38 #include "clang/Serialization/ContinuousRangeMap.h"
39 #include "clang/Serialization/Module.h"
40 #include "clang/Serialization/ModuleFileExtension.h"
41 #include "clang/Serialization/ModuleManager.h"
42 #include "llvm/ADT/APFloat.h"
43 #include "llvm/ADT/APInt.h"
44 #include "llvm/ADT/APSInt.h"
45 #include "llvm/ADT/ArrayRef.h"
46 #include "llvm/ADT/DenseMap.h"
47 #include "llvm/ADT/DenseSet.h"
48 #include "llvm/ADT/IntrusiveRefCntPtr.h"
49 #include "llvm/ADT/MapVector.h"
50 #include "llvm/ADT/Optional.h"
51 #include "llvm/ADT/STLExtras.h"
52 #include "llvm/ADT/SetVector.h"
53 #include "llvm/ADT/SmallPtrSet.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/StringMap.h"
56 #include "llvm/ADT/StringRef.h"
57 #include "llvm/ADT/iterator.h"
58 #include "llvm/ADT/iterator_range.h"
59 #include "llvm/Bitcode/BitstreamReader.h"
60 #include "llvm/Support/Casting.h"
61 #include "llvm/Support/Endian.h"
62 #include "llvm/Support/MemoryBuffer.h"
63 #include "llvm/Support/Timer.h"
64 #include "llvm/Support/VersionTuple.h"
80 class ASTDeserializationListener;
82 class ASTRecordReader;
92 class FileSystemOptions;
94 class GlobalModuleIndex;
95 struct HeaderFileInfo;
96 class HeaderSearchOptions;
98 class LazyASTUnresolvedSet;
100 class MemoryBufferCache;
103 class ObjCCategoryDecl;
104 class ObjCInterfaceDecl;
105 class PCHContainerReader;
107 class PreprocessorOptions;
108 struct QualifierInfo;
114 class TemplateParameterList;
115 class TypedefNameDecl;
116 class TypeSourceInfo;
120 /// Abstract interface for callback invocations by the ASTReader.
122 /// While reading an AST file, the ASTReader will call the methods of the
123 /// listener to pass on specific information. Some of the listener methods can
124 /// return true to indicate to the ASTReader that the information (and
125 /// consequently the AST file) is invalid.
126 class ASTReaderListener {
128 virtual ~ASTReaderListener();
130 /// Receives the full Clang version information.
132 /// \returns true to indicate that the version is invalid. Subclasses should
133 /// generally defer to this implementation.
134 virtual bool ReadFullVersionInformation(StringRef FullVersion) {
135 return FullVersion != getClangFullRepositoryVersion();
138 virtual void ReadModuleName(StringRef ModuleName) {}
139 virtual void ReadModuleMapFile(StringRef ModuleMapPath) {}
141 /// Receives the language options.
143 /// \returns true to indicate the options are invalid or false otherwise.
144 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
146 bool AllowCompatibleDifferences) {
150 /// Receives the target options.
152 /// \returns true to indicate the target options are invalid, or false
154 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
155 bool AllowCompatibleDifferences) {
159 /// Receives the diagnostic options.
161 /// \returns true to indicate the diagnostic options are invalid, or false
164 ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
169 /// Receives the file system options.
171 /// \returns true to indicate the file system options are invalid, or false
173 virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
178 /// Receives the header search options.
180 /// \returns true to indicate the header search options are invalid, or false
182 virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
183 StringRef SpecificModuleCachePath,
188 /// Receives the preprocessor options.
190 /// \param SuggestedPredefines Can be filled in with the set of predefines
191 /// that are suggested by the preprocessor options. Typically only used when
192 /// loading a precompiled header.
194 /// \returns true to indicate the preprocessor options are invalid, or false
196 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
198 std::string &SuggestedPredefines) {
202 /// Receives __COUNTER__ value.
203 virtual void ReadCounter(const serialization::ModuleFile &M,
206 /// This is called for each AST file loaded.
207 virtual void visitModuleFile(StringRef Filename,
208 serialization::ModuleKind Kind) {}
210 /// Returns true if this \c ASTReaderListener wants to receive the
211 /// input files of the AST file via \c visitInputFile, false otherwise.
212 virtual bool needsInputFileVisitation() { return false; }
214 /// Returns true if this \c ASTReaderListener wants to receive the
215 /// system input files of the AST file via \c visitInputFile, false otherwise.
216 virtual bool needsSystemInputFileVisitation() { return false; }
218 /// if \c needsInputFileVisitation returns true, this is called for
219 /// each non-system input file of the AST File. If
220 /// \c needsSystemInputFileVisitation is true, then it is called for all
221 /// system input files as well.
223 /// \returns true to continue receiving the next input file, false to stop.
224 virtual bool visitInputFile(StringRef Filename, bool isSystem,
225 bool isOverridden, bool isExplicitModule) {
229 /// Returns true if this \c ASTReaderListener wants to receive the
230 /// imports of the AST file via \c visitImport, false otherwise.
231 virtual bool needsImportVisitation() const { return false; }
233 /// If needsImportVisitation returns \c true, this is called for each
234 /// AST file imported by this AST file.
235 virtual void visitImport(StringRef Filename) {}
237 /// Indicates that a particular module file extension has been read.
238 virtual void readModuleFileExtension(
239 const ModuleFileExtensionMetadata &Metadata) {}
242 /// Simple wrapper class for chaining listeners.
243 class ChainedASTReaderListener : public ASTReaderListener {
244 std::unique_ptr<ASTReaderListener> First;
245 std::unique_ptr<ASTReaderListener> Second;
248 /// Takes ownership of \p First and \p Second.
249 ChainedASTReaderListener(std::unique_ptr<ASTReaderListener> First,
250 std::unique_ptr<ASTReaderListener> Second)
251 : First(std::move(First)), Second(std::move(Second)) {}
253 std::unique_ptr<ASTReaderListener> takeFirst() { return std::move(First); }
254 std::unique_ptr<ASTReaderListener> takeSecond() { return std::move(Second); }
256 bool ReadFullVersionInformation(StringRef FullVersion) override;
257 void ReadModuleName(StringRef ModuleName) override;
258 void ReadModuleMapFile(StringRef ModuleMapPath) override;
259 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
260 bool AllowCompatibleDifferences) override;
261 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
262 bool AllowCompatibleDifferences) override;
263 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
264 bool Complain) override;
265 bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
266 bool Complain) override;
268 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
269 StringRef SpecificModuleCachePath,
270 bool Complain) override;
271 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
273 std::string &SuggestedPredefines) override;
275 void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
276 bool needsInputFileVisitation() override;
277 bool needsSystemInputFileVisitation() override;
278 void visitModuleFile(StringRef Filename,
279 serialization::ModuleKind Kind) override;
280 bool visitInputFile(StringRef Filename, bool isSystem,
281 bool isOverridden, bool isExplicitModule) override;
282 void readModuleFileExtension(
283 const ModuleFileExtensionMetadata &Metadata) override;
286 /// ASTReaderListener implementation to validate the information of
287 /// the PCH file against an initialized Preprocessor.
288 class PCHValidator : public ASTReaderListener {
293 PCHValidator(Preprocessor &PP, ASTReader &Reader)
294 : PP(PP), Reader(Reader) {}
296 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
297 bool AllowCompatibleDifferences) override;
298 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
299 bool AllowCompatibleDifferences) override;
300 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
301 bool Complain) override;
302 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
303 std::string &SuggestedPredefines) override;
304 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
305 StringRef SpecificModuleCachePath,
306 bool Complain) override;
307 void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
310 void Error(const char *Msg);
313 /// ASTReaderListenter implementation to set SuggestedPredefines of
314 /// ASTReader which is required to use a pch file. This is the replacement
315 /// of PCHValidator or SimplePCHValidator when using a pch file without
317 class SimpleASTReaderListener : public ASTReaderListener {
321 SimpleASTReaderListener(Preprocessor &PP) : PP(PP) {}
323 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
324 std::string &SuggestedPredefines) override;
327 namespace serialization {
329 class ReadMethodPoolVisitor;
333 class ASTIdentifierLookupTrait;
335 /// The on-disk hash table(s) used for DeclContext name lookup.
336 struct DeclContextLookupTable;
338 } // namespace reader
340 } // namespace serialization
342 /// Reads an AST files chain containing the contents of a translation
345 /// The ASTReader class reads bitstreams (produced by the ASTWriter
346 /// class) containing the serialized representation of a given
347 /// abstract syntax tree and its supporting data structures. An
348 /// instance of the ASTReader can be attached to an ASTContext object,
349 /// which will provide access to the contents of the AST files.
351 /// The AST reader provides lazy de-serialization of declarations, as
352 /// required when traversing the AST. Only those AST nodes that are
353 /// actually required will be de-serialized.
355 : public ExternalPreprocessorSource,
356 public ExternalPreprocessingRecordSource,
357 public ExternalHeaderFileInfoSource,
358 public ExternalSemaSource,
359 public IdentifierInfoLookup,
360 public ExternalSLocEntrySource
363 /// Types of AST files.
364 friend class ASTDeclReader;
365 friend class ASTIdentifierIterator;
366 friend class ASTRecordReader;
367 friend class ASTStmtReader;
368 friend class ASTUnit; // ASTUnit needs to remap source locations.
369 friend class ASTWriter;
370 friend class PCHValidator;
371 friend class serialization::reader::ASTIdentifierLookupTrait;
372 friend class serialization::ReadMethodPoolVisitor;
373 friend class TypeLocReader;
375 using RecordData = SmallVector<uint64_t, 64>;
376 using RecordDataImpl = SmallVectorImpl<uint64_t>;
378 /// The result of reading the control block of an AST file, which
379 /// can fail for various reasons.
381 /// The control block was read successfully. Aside from failures,
382 /// the AST file is safe to read into the current context.
385 /// The AST file itself appears corrupted.
388 /// The AST file was missing.
391 /// The AST file is out-of-date relative to its input files,
392 /// and needs to be regenerated.
395 /// The AST file was written by a different version of Clang.
398 /// The AST file was writtten with a different language/target
400 ConfigurationMismatch,
402 /// The AST file has errors.
406 using ModuleFile = serialization::ModuleFile;
407 using ModuleKind = serialization::ModuleKind;
408 using ModuleManager = serialization::ModuleManager;
409 using ModuleIterator = ModuleManager::ModuleIterator;
410 using ModuleConstIterator = ModuleManager::ModuleConstIterator;
411 using ModuleReverseIterator = ModuleManager::ModuleReverseIterator;
414 /// The receiver of some callbacks invoked by ASTReader.
415 std::unique_ptr<ASTReaderListener> Listener;
417 /// The receiver of deserialization events.
418 ASTDeserializationListener *DeserializationListener = nullptr;
420 bool OwnsDeserializationListener = false;
422 SourceManager &SourceMgr;
423 FileManager &FileMgr;
424 const PCHContainerReader &PCHContainerRdr;
425 DiagnosticsEngine &Diags;
427 /// The semantic analysis object that will be processing the
428 /// AST files and the translation unit that uses it.
429 Sema *SemaObj = nullptr;
431 /// The preprocessor that will be loading the source file.
434 /// The AST context into which we'll read the AST files.
435 ASTContext *ContextObj = nullptr;
437 /// The AST consumer.
438 ASTConsumer *Consumer = nullptr;
440 /// The module manager which manages modules and their dependencies
441 ModuleManager ModuleMgr;
443 /// The cache that manages memory buffers for PCM files.
444 MemoryBufferCache &PCMCache;
446 /// A dummy identifier resolver used to merge TU-scope declarations in
447 /// C, for the cases where we don't have a Sema object to provide a real
448 /// identifier resolver.
449 IdentifierResolver DummyIdResolver;
451 /// A mapping from extension block names to module file extensions.
452 llvm::StringMap<std::shared_ptr<ModuleFileExtension>> ModuleFileExtensions;
454 /// A timer used to track the time spent deserializing.
455 std::unique_ptr<llvm::Timer> ReadTimer;
457 /// The location where the module file will be considered as
458 /// imported from. For non-module AST types it should be invalid.
459 SourceLocation CurrentImportLoc;
461 /// The global module index, if loaded.
462 std::unique_ptr<GlobalModuleIndex> GlobalIndex;
464 /// A map of global bit offsets to the module that stores entities
465 /// at those bit offsets.
466 ContinuousRangeMap<uint64_t, ModuleFile*, 4> GlobalBitOffsetsMap;
468 /// A map of negated SLocEntryIDs to the modules containing them.
469 ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocEntryMap;
471 using GlobalSLocOffsetMapType =
472 ContinuousRangeMap<unsigned, ModuleFile *, 64>;
474 /// A map of reversed (SourceManager::MaxLoadedOffset - SLocOffset)
475 /// SourceLocation offsets to the modules containing them.
476 GlobalSLocOffsetMapType GlobalSLocOffsetMap;
478 /// Types that have already been loaded from the chain.
480 /// When the pointer at index I is non-NULL, the type with
481 /// ID = (I + 1) << FastQual::Width has already been loaded
482 std::vector<QualType> TypesLoaded;
484 using GlobalTypeMapType =
485 ContinuousRangeMap<serialization::TypeID, ModuleFile *, 4>;
487 /// Mapping from global type IDs to the module in which the
488 /// type resides along with the offset that should be added to the
489 /// global type ID to produce a local ID.
490 GlobalTypeMapType GlobalTypeMap;
492 /// Declarations that have already been loaded from the chain.
494 /// When the pointer at index I is non-NULL, the declaration with ID
495 /// = I + 1 has already been loaded.
496 std::vector<Decl *> DeclsLoaded;
498 using GlobalDeclMapType =
499 ContinuousRangeMap<serialization::DeclID, ModuleFile *, 4>;
501 /// Mapping from global declaration IDs to the module in which the
502 /// declaration resides.
503 GlobalDeclMapType GlobalDeclMap;
505 using FileOffset = std::pair<ModuleFile *, uint64_t>;
506 using FileOffsetsTy = SmallVector<FileOffset, 2>;
507 using DeclUpdateOffsetsMap =
508 llvm::DenseMap<serialization::DeclID, FileOffsetsTy>;
510 /// Declarations that have modifications residing in a later file
512 DeclUpdateOffsetsMap DeclUpdateOffsets;
514 struct PendingUpdateRecord {
516 serialization::GlobalDeclID ID;
518 // Whether the declaration was just deserialized.
521 PendingUpdateRecord(serialization::GlobalDeclID ID, Decl *D,
523 : D(D), ID(ID), JustLoaded(JustLoaded) {}
526 /// Declaration updates for already-loaded declarations that we need
527 /// to apply once we finish processing an import.
528 llvm::SmallVector<PendingUpdateRecord, 16> PendingUpdateRecords;
530 enum class PendingFakeDefinitionKind { NotFake, Fake, FakeLoaded };
532 /// The DefinitionData pointers that we faked up for class definitions
533 /// that we needed but hadn't loaded yet.
534 llvm::DenseMap<void *, PendingFakeDefinitionKind> PendingFakeDefinitionData;
536 /// Exception specification updates that have been loaded but not yet
537 /// propagated across the relevant redeclaration chain. The map key is the
538 /// canonical declaration (used only for deduplication) and the value is a
539 /// declaration that has an exception specification.
540 llvm::SmallMapVector<Decl *, FunctionDecl *, 4> PendingExceptionSpecUpdates;
542 /// Declarations that have been imported and have typedef names for
543 /// linkage purposes.
544 llvm::DenseMap<std::pair<DeclContext *, IdentifierInfo *>, NamedDecl *>
545 ImportedTypedefNamesForLinkage;
547 /// Mergeable declaration contexts that have anonymous declarations
548 /// within them, and those anonymous declarations.
549 llvm::DenseMap<Decl*, llvm::SmallVector<NamedDecl*, 2>>
550 AnonymousDeclarationsForMerging;
552 struct FileDeclsInfo {
553 ModuleFile *Mod = nullptr;
554 ArrayRef<serialization::LocalDeclID> Decls;
556 FileDeclsInfo() = default;
557 FileDeclsInfo(ModuleFile *Mod, ArrayRef<serialization::LocalDeclID> Decls)
558 : Mod(Mod), Decls(Decls) {}
561 /// Map from a FileID to the file-level declarations that it contains.
562 llvm::DenseMap<FileID, FileDeclsInfo> FileDeclIDs;
564 /// An array of lexical contents of a declaration context, as a sequence of
565 /// Decl::Kind, DeclID pairs.
566 using LexicalContents = ArrayRef<llvm::support::unaligned_uint32_t>;
568 /// Map from a DeclContext to its lexical contents.
569 llvm::DenseMap<const DeclContext*, std::pair<ModuleFile*, LexicalContents>>
572 /// Map from the TU to its lexical contents from each module file.
573 std::vector<std::pair<ModuleFile*, LexicalContents>> TULexicalDecls;
575 /// Map from a DeclContext to its lookup tables.
576 llvm::DenseMap<const DeclContext *,
577 serialization::reader::DeclContextLookupTable> Lookups;
579 // Updates for visible decls can occur for other contexts than just the
580 // TU, and when we read those update records, the actual context may not
581 // be available yet, so have this pending map using the ID as a key. It
582 // will be realized when the context is actually loaded.
583 struct PendingVisibleUpdate {
585 const unsigned char *Data;
587 using DeclContextVisibleUpdates = SmallVector<PendingVisibleUpdate, 1>;
589 /// Updates to the visible declarations of declaration contexts that
590 /// haven't been loaded yet.
591 llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates>
592 PendingVisibleUpdates;
594 /// The set of C++ or Objective-C classes that have forward
595 /// declarations that have not yet been linked to their definitions.
596 llvm::SmallPtrSet<Decl *, 4> PendingDefinitions;
598 using PendingBodiesMap =
599 llvm::MapVector<Decl *, uint64_t,
600 llvm::SmallDenseMap<Decl *, unsigned, 4>,
601 SmallVector<std::pair<Decl *, uint64_t>, 4>>;
603 /// Functions or methods that have bodies that will be attached.
604 PendingBodiesMap PendingBodies;
606 /// Definitions for which we have added merged definitions but not yet
607 /// performed deduplication.
608 llvm::SetVector<NamedDecl *> PendingMergedDefinitionsToDeduplicate;
610 /// Read the record that describes the lexical contents of a DC.
611 bool ReadLexicalDeclContextStorage(ModuleFile &M,
612 llvm::BitstreamCursor &Cursor,
613 uint64_t Offset, DeclContext *DC);
615 /// Read the record that describes the visible contents of a DC.
616 bool ReadVisibleDeclContextStorage(ModuleFile &M,
617 llvm::BitstreamCursor &Cursor,
618 uint64_t Offset, serialization::DeclID ID);
620 /// A vector containing identifiers that have already been
623 /// If the pointer at index I is non-NULL, then it refers to the
624 /// IdentifierInfo for the identifier with ID=I+1 that has already
626 std::vector<IdentifierInfo *> IdentifiersLoaded;
628 using GlobalIdentifierMapType =
629 ContinuousRangeMap<serialization::IdentID, ModuleFile *, 4>;
631 /// Mapping from global identifier IDs to the module in which the
632 /// identifier resides along with the offset that should be added to the
633 /// global identifier ID to produce a local ID.
634 GlobalIdentifierMapType GlobalIdentifierMap;
636 /// A vector containing macros that have already been
639 /// If the pointer at index I is non-NULL, then it refers to the
640 /// MacroInfo for the identifier with ID=I+1 that has already
642 std::vector<MacroInfo *> MacrosLoaded;
644 using LoadedMacroInfo =
645 std::pair<IdentifierInfo *, serialization::SubmoduleID>;
647 /// A set of #undef directives that we have loaded; used to
648 /// deduplicate the same #undef information coming from multiple module
650 llvm::DenseSet<LoadedMacroInfo> LoadedUndefs;
652 using GlobalMacroMapType =
653 ContinuousRangeMap<serialization::MacroID, ModuleFile *, 4>;
655 /// Mapping from global macro IDs to the module in which the
656 /// macro resides along with the offset that should be added to the
657 /// global macro ID to produce a local ID.
658 GlobalMacroMapType GlobalMacroMap;
660 /// A vector containing submodules that have already been loaded.
662 /// This vector is indexed by the Submodule ID (-1). NULL submodule entries
663 /// indicate that the particular submodule ID has not yet been loaded.
664 SmallVector<Module *, 2> SubmodulesLoaded;
666 using GlobalSubmoduleMapType =
667 ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4>;
669 /// Mapping from global submodule IDs to the module file in which the
670 /// submodule resides along with the offset that should be added to the
671 /// global submodule ID to produce a local ID.
672 GlobalSubmoduleMapType GlobalSubmoduleMap;
674 /// A set of hidden declarations.
675 using HiddenNames = SmallVector<Decl *, 2>;
676 using HiddenNamesMapType = llvm::DenseMap<Module *, HiddenNames>;
678 /// A mapping from each of the hidden submodules to the deserialized
679 /// declarations in that submodule that could be made visible.
680 HiddenNamesMapType HiddenNamesMap;
682 /// A module import, export, or conflict that hasn't yet been resolved.
683 struct UnresolvedModuleRef {
684 /// The file in which this module resides.
687 /// The module that is importing or exporting.
690 /// The kind of module reference.
691 enum { Import, Export, Conflict } Kind;
693 /// The local ID of the module that is being exported.
696 /// Whether this is a wildcard export.
697 unsigned IsWildcard : 1;
703 /// The set of module imports and exports that still need to be
705 SmallVector<UnresolvedModuleRef, 2> UnresolvedModuleRefs;
707 /// A vector containing selectors that have already been loaded.
709 /// This vector is indexed by the Selector ID (-1). NULL selector
710 /// entries indicate that the particular selector ID has not yet
712 SmallVector<Selector, 16> SelectorsLoaded;
714 using GlobalSelectorMapType =
715 ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4>;
717 /// Mapping from global selector IDs to the module in which the
718 /// global selector ID to produce a local ID.
719 GlobalSelectorMapType GlobalSelectorMap;
721 /// The generation number of the last time we loaded data from the
722 /// global method pool for this selector.
723 llvm::DenseMap<Selector, unsigned> SelectorGeneration;
725 /// Whether a selector is out of date. We mark a selector as out of date
726 /// if we load another module after the method pool entry was pulled in.
727 llvm::DenseMap<Selector, bool> SelectorOutOfDate;
729 struct PendingMacroInfo {
731 uint64_t MacroDirectivesOffset;
733 PendingMacroInfo(ModuleFile *M, uint64_t MacroDirectivesOffset)
734 : M(M), MacroDirectivesOffset(MacroDirectivesOffset) {}
737 using PendingMacroIDsMap =
738 llvm::MapVector<IdentifierInfo *, SmallVector<PendingMacroInfo, 2>>;
740 /// Mapping from identifiers that have a macro history to the global
741 /// IDs have not yet been deserialized to the global IDs of those macros.
742 PendingMacroIDsMap PendingMacroIDs;
744 using GlobalPreprocessedEntityMapType =
745 ContinuousRangeMap<unsigned, ModuleFile *, 4>;
747 /// Mapping from global preprocessing entity IDs to the module in
748 /// which the preprocessed entity resides along with the offset that should be
749 /// added to the global preprocessing entity ID to produce a local ID.
750 GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap;
752 using GlobalSkippedRangeMapType =
753 ContinuousRangeMap<unsigned, ModuleFile *, 4>;
755 /// Mapping from global skipped range base IDs to the module in which
756 /// the skipped ranges reside.
757 GlobalSkippedRangeMapType GlobalSkippedRangeMap;
759 /// \name CodeGen-relevant special data
760 /// Fields containing data that is relevant to CodeGen.
763 /// The IDs of all declarations that fulfill the criteria of
764 /// "interesting" decls.
766 /// This contains the data loaded from all EAGERLY_DESERIALIZED_DECLS blocks
767 /// in the chain. The referenced declarations are deserialized and passed to
768 /// the consumer eagerly.
769 SmallVector<uint64_t, 16> EagerlyDeserializedDecls;
771 /// The IDs of all tentative definitions stored in the chain.
773 /// Sema keeps track of all tentative definitions in a TU because it has to
774 /// complete them and pass them on to CodeGen. Thus, tentative definitions in
775 /// the PCH chain must be eagerly deserialized.
776 SmallVector<uint64_t, 16> TentativeDefinitions;
778 /// The IDs of all CXXRecordDecls stored in the chain whose VTables are
781 /// CodeGen has to emit VTables for these records, so they have to be eagerly
783 SmallVector<uint64_t, 64> VTableUses;
785 /// A snapshot of the pending instantiations in the chain.
787 /// This record tracks the instantiations that Sema has to perform at the
788 /// end of the TU. It consists of a pair of values for every pending
789 /// instantiation where the first value is the ID of the decl and the second
790 /// is the instantiation location.
791 SmallVector<uint64_t, 64> PendingInstantiations;
795 /// \name DiagnosticsEngine-relevant special data
796 /// Fields containing data that is used for generating diagnostics
799 /// A snapshot of Sema's unused file-scoped variable tracking, for
800 /// generating warnings.
801 SmallVector<uint64_t, 16> UnusedFileScopedDecls;
803 /// A list of all the delegating constructors we've seen, to diagnose
805 SmallVector<uint64_t, 4> DelegatingCtorDecls;
807 /// Method selectors used in a @selector expression. Used for
808 /// implementation of -Wselector.
809 SmallVector<uint64_t, 64> ReferencedSelectorsData;
811 /// A snapshot of Sema's weak undeclared identifier tracking, for
812 /// generating warnings.
813 SmallVector<uint64_t, 64> WeakUndeclaredIdentifiers;
815 /// The IDs of type aliases for ext_vectors that exist in the chain.
817 /// Used by Sema for finding sugared names for ext_vectors in diagnostics.
818 SmallVector<uint64_t, 4> ExtVectorDecls;
822 /// \name Sema-relevant special data
823 /// Fields containing data that is used for semantic analysis
826 /// The IDs of all potentially unused typedef names in the chain.
828 /// Sema tracks these to emit warnings.
829 SmallVector<uint64_t, 16> UnusedLocalTypedefNameCandidates;
831 /// Our current depth in #pragma cuda force_host_device begin/end
833 unsigned ForceCUDAHostDeviceDepth = 0;
835 /// The IDs of the declarations Sema stores directly.
837 /// Sema tracks a few important decls, such as namespace std, directly.
838 SmallVector<uint64_t, 4> SemaDeclRefs;
840 /// The IDs of the types ASTContext stores directly.
842 /// The AST context tracks a few important types, such as va_list, directly.
843 SmallVector<uint64_t, 16> SpecialTypes;
845 /// The IDs of CUDA-specific declarations ASTContext stores directly.
847 /// The AST context tracks a few important decls, currently cudaConfigureCall,
849 SmallVector<uint64_t, 2> CUDASpecialDeclRefs;
851 /// The floating point pragma option settings.
852 SmallVector<uint64_t, 1> FPPragmaOptions;
854 /// The pragma clang optimize location (if the pragma state is "off").
855 SourceLocation OptimizeOffPragmaLocation;
857 /// The PragmaMSStructKind pragma ms_struct state if set, or -1.
858 int PragmaMSStructState = -1;
860 /// The PragmaMSPointersToMembersKind pragma pointers_to_members state.
861 int PragmaMSPointersToMembersState = -1;
862 SourceLocation PointersToMembersPragmaLocation;
864 /// The pragma pack state.
865 Optional<unsigned> PragmaPackCurrentValue;
866 SourceLocation PragmaPackCurrentLocation;
867 struct PragmaPackStackEntry {
869 SourceLocation Location;
870 SourceLocation PushLocation;
873 llvm::SmallVector<PragmaPackStackEntry, 2> PragmaPackStack;
874 llvm::SmallVector<std::string, 2> PragmaPackStrings;
876 /// The OpenCL extension settings.
877 OpenCLOptions OpenCLExtensions;
879 /// Extensions required by an OpenCL type.
880 llvm::DenseMap<const Type *, std::set<std::string>> OpenCLTypeExtMap;
882 /// Extensions required by an OpenCL declaration.
883 llvm::DenseMap<const Decl *, std::set<std::string>> OpenCLDeclExtMap;
885 /// A list of the namespaces we've seen.
886 SmallVector<uint64_t, 4> KnownNamespaces;
888 /// A list of undefined decls with internal linkage followed by the
889 /// SourceLocation of a matching ODR-use.
890 SmallVector<uint64_t, 8> UndefinedButUsed;
892 /// Delete expressions to analyze at the end of translation unit.
893 SmallVector<uint64_t, 8> DelayedDeleteExprs;
895 // A list of late parsed template function data.
896 SmallVector<uint64_t, 1> LateParsedTemplates;
899 struct ImportedSubmodule {
900 serialization::SubmoduleID ID;
901 SourceLocation ImportLoc;
903 ImportedSubmodule(serialization::SubmoduleID ID, SourceLocation ImportLoc)
904 : ID(ID), ImportLoc(ImportLoc) {}
908 /// A list of modules that were imported by precompiled headers or
909 /// any other non-module AST file.
910 SmallVector<ImportedSubmodule, 2> ImportedModules;
913 /// The system include root to be used when loading the
914 /// precompiled header.
915 std::string isysroot;
917 /// Whether to disable the normal validation performed on precompiled
918 /// headers when they are loaded.
919 bool DisableValidation;
921 /// Whether to accept an AST file with compiler errors.
922 bool AllowASTWithCompilerErrors;
924 /// Whether to accept an AST file that has a different configuration
925 /// from the current compiler instance.
926 bool AllowConfigurationMismatch;
928 /// Whether validate system input files.
929 bool ValidateSystemInputs;
931 /// Whether we are allowed to use the global module index.
934 /// Whether we have tried loading the global module index yet.
935 bool TriedLoadingGlobalIndex = false;
937 ///Whether we are currently processing update records.
938 bool ProcessingUpdateRecords = false;
940 using SwitchCaseMapTy = llvm::DenseMap<unsigned, SwitchCase *>;
942 /// Mapping from switch-case IDs in the chain to switch-case statements
944 /// Statements usually don't have IDs, but switch cases need them, so that the
945 /// switch statement can refer to them.
946 SwitchCaseMapTy SwitchCaseStmts;
948 SwitchCaseMapTy *CurrSwitchCaseStmts;
950 /// The number of source location entries de-serialized from
952 unsigned NumSLocEntriesRead = 0;
954 /// The number of source location entries in the chain.
955 unsigned TotalNumSLocEntries = 0;
957 /// The number of statements (and expressions) de-serialized
959 unsigned NumStatementsRead = 0;
961 /// The total number of statements (and expressions) stored
963 unsigned TotalNumStatements = 0;
965 /// The number of macros de-serialized from the chain.
966 unsigned NumMacrosRead = 0;
968 /// The total number of macros stored in the chain.
969 unsigned TotalNumMacros = 0;
971 /// The number of lookups into identifier tables.
972 unsigned NumIdentifierLookups = 0;
974 /// The number of lookups into identifier tables that succeed.
975 unsigned NumIdentifierLookupHits = 0;
977 /// The number of selectors that have been read.
978 unsigned NumSelectorsRead = 0;
980 /// The number of method pool entries that have been read.
981 unsigned NumMethodPoolEntriesRead = 0;
983 /// The number of times we have looked up a selector in the method
985 unsigned NumMethodPoolLookups = 0;
987 /// The number of times we have looked up a selector in the method
988 /// pool and found something.
989 unsigned NumMethodPoolHits = 0;
991 /// The number of times we have looked up a selector in the method
992 /// pool within a specific module.
993 unsigned NumMethodPoolTableLookups = 0;
995 /// The number of times we have looked up a selector in the method
996 /// pool within a specific module and found something.
997 unsigned NumMethodPoolTableHits = 0;
999 /// The total number of method pool entries in the selector table.
1000 unsigned TotalNumMethodPoolEntries = 0;
1002 /// Number of lexical decl contexts read/total.
1003 unsigned NumLexicalDeclContextsRead = 0, TotalLexicalDeclContexts = 0;
1005 /// Number of visible decl contexts read/total.
1006 unsigned NumVisibleDeclContextsRead = 0, TotalVisibleDeclContexts = 0;
1008 /// Total size of modules, in bits, currently loaded
1009 uint64_t TotalModulesSizeInBits = 0;
1011 /// Number of Decl/types that are currently deserializing.
1012 unsigned NumCurrentElementsDeserializing = 0;
1014 /// Set true while we are in the process of passing deserialized
1015 /// "interesting" decls to consumer inside FinishedDeserializing().
1016 /// This is used as a guard to avoid recursively repeating the process of
1017 /// passing decls to consumer.
1018 bool PassingDeclsToConsumer = false;
1020 /// The set of identifiers that were read while the AST reader was
1021 /// (recursively) loading declarations.
1023 /// The declarations on the identifier chain for these identifiers will be
1024 /// loaded once the recursive loading has completed.
1025 llvm::MapVector<IdentifierInfo *, SmallVector<uint32_t, 4>>
1026 PendingIdentifierInfos;
1028 /// The set of lookup results that we have faked in order to support
1029 /// merging of partially deserialized decls but that we have not yet removed.
1030 llvm::SmallMapVector<IdentifierInfo *, SmallVector<NamedDecl*, 2>, 16>
1031 PendingFakeLookupResults;
1033 /// The generation number of each identifier, which keeps track of
1034 /// the last time we loaded information about this identifier.
1035 llvm::DenseMap<IdentifierInfo *, unsigned> IdentifierGeneration;
1037 class InterestingDecl {
1039 bool DeclHasPendingBody;
1042 InterestingDecl(Decl *D, bool HasBody)
1043 : D(D), DeclHasPendingBody(HasBody) {}
1045 Decl *getDecl() { return D; }
1047 /// Whether the declaration has a pending body.
1048 bool hasPendingBody() { return DeclHasPendingBody; }
1051 /// Contains declarations and definitions that could be
1052 /// "interesting" to the ASTConsumer, when we get that AST consumer.
1054 /// "Interesting" declarations are those that have data that may
1055 /// need to be emitted, such as inline function definitions or
1056 /// Objective-C protocols.
1057 std::deque<InterestingDecl> PotentiallyInterestingDecls;
1059 /// The list of redeclaration chains that still need to be
1060 /// reconstructed, and the local offset to the corresponding list
1061 /// of redeclarations.
1062 SmallVector<std::pair<Decl *, uint64_t>, 16> PendingDeclChains;
1064 /// The list of canonical declarations whose redeclaration chains
1065 /// need to be marked as incomplete once we're done deserializing things.
1066 SmallVector<Decl *, 16> PendingIncompleteDeclChains;
1068 /// The Decl IDs for the Sema/Lexical DeclContext of a Decl that has
1069 /// been loaded but its DeclContext was not set yet.
1070 struct PendingDeclContextInfo {
1072 serialization::GlobalDeclID SemaDC;
1073 serialization::GlobalDeclID LexicalDC;
1076 /// The set of Decls that have been loaded but their DeclContexts are
1079 /// The DeclContexts for these Decls will be set once recursive loading has
1081 std::deque<PendingDeclContextInfo> PendingDeclContextInfos;
1083 /// The set of NamedDecls that have been loaded, but are members of a
1084 /// context that has been merged into another context where the corresponding
1085 /// declaration is either missing or has not yet been loaded.
1087 /// We will check whether the corresponding declaration is in fact missing
1088 /// once recursing loading has been completed.
1089 llvm::SmallVector<NamedDecl *, 16> PendingOdrMergeChecks;
1091 using DataPointers =
1092 std::pair<CXXRecordDecl *, struct CXXRecordDecl::DefinitionData *>;
1094 /// Record definitions in which we found an ODR violation.
1095 llvm::SmallDenseMap<CXXRecordDecl *, llvm::SmallVector<DataPointers, 2>, 2>
1096 PendingOdrMergeFailures;
1098 /// Function definitions in which we found an ODR violation.
1099 llvm::SmallDenseMap<FunctionDecl *, llvm::SmallVector<FunctionDecl *, 2>, 2>
1100 PendingFunctionOdrMergeFailures;
1102 /// Enum definitions in which we found an ODR violation.
1103 llvm::SmallDenseMap<EnumDecl *, llvm::SmallVector<EnumDecl *, 2>, 2>
1104 PendingEnumOdrMergeFailures;
1106 /// DeclContexts in which we have diagnosed an ODR violation.
1107 llvm::SmallPtrSet<DeclContext*, 2> DiagnosedOdrMergeFailures;
1109 /// The set of Objective-C categories that have been deserialized
1110 /// since the last time the declaration chains were linked.
1111 llvm::SmallPtrSet<ObjCCategoryDecl *, 16> CategoriesDeserialized;
1113 /// The set of Objective-C class definitions that have already been
1114 /// loaded, for which we will need to check for categories whenever a new
1115 /// module is loaded.
1116 SmallVector<ObjCInterfaceDecl *, 16> ObjCClassesLoaded;
1119 llvm::DenseMap<Decl *, SmallVector<serialization::DeclID, 2>>;
1121 /// A mapping from canonical declarations to the set of global
1122 /// declaration IDs for key declaration that have been merged with that
1123 /// canonical declaration. A key declaration is a formerly-canonical
1124 /// declaration whose module did not import any other key declaration for that
1125 /// entity. These are the IDs that we use as keys when finding redecl chains.
1126 KeyDeclsMap KeyDecls;
1128 /// A mapping from DeclContexts to the semantic DeclContext that we
1129 /// are treating as the definition of the entity. This is used, for instance,
1130 /// when merging implicit instantiations of class templates across modules.
1131 llvm::DenseMap<DeclContext *, DeclContext *> MergedDeclContexts;
1133 /// A mapping from canonical declarations of enums to their canonical
1134 /// definitions. Only populated when using modules in C++.
1135 llvm::DenseMap<EnumDecl *, EnumDecl *> EnumDefinitions;
1137 /// When reading a Stmt tree, Stmt operands are placed in this stack.
1138 SmallVector<Stmt *, 16> StmtStack;
1140 /// What kind of records we are reading.
1142 Read_None, Read_Decl, Read_Type, Read_Stmt
1145 /// What kind of records we are reading.
1146 ReadingKind ReadingKind = Read_None;
1148 /// RAII object to change the reading kind.
1149 class ReadingKindTracker {
1151 enum ReadingKind PrevKind;
1154 ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
1155 : Reader(reader), PrevKind(Reader.ReadingKind) {
1156 Reader.ReadingKind = newKind;
1159 ReadingKindTracker(const ReadingKindTracker &) = delete;
1160 ReadingKindTracker &operator=(const ReadingKindTracker &) = delete;
1161 ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; }
1164 /// RAII object to mark the start of processing updates.
1165 class ProcessingUpdatesRAIIObj {
1170 ProcessingUpdatesRAIIObj(ASTReader &reader)
1171 : Reader(reader), PrevState(Reader.ProcessingUpdateRecords) {
1172 Reader.ProcessingUpdateRecords = true;
1175 ProcessingUpdatesRAIIObj(const ProcessingUpdatesRAIIObj &) = delete;
1176 ProcessingUpdatesRAIIObj &
1177 operator=(const ProcessingUpdatesRAIIObj &) = delete;
1178 ~ProcessingUpdatesRAIIObj() { Reader.ProcessingUpdateRecords = PrevState; }
1181 /// Suggested contents of the predefines buffer, after this
1182 /// PCH file has been processed.
1184 /// In most cases, this string will be empty, because the predefines
1185 /// buffer computed to build the PCH file will be identical to the
1186 /// predefines buffer computed from the command line. However, when
1187 /// there are differences that the PCH reader can work around, this
1188 /// predefines buffer may contain additional definitions.
1189 std::string SuggestedPredefines;
1191 llvm::DenseMap<const Decl *, bool> DefinitionSource;
1193 /// Reads a statement from the specified cursor.
1194 Stmt *ReadStmtFromStream(ModuleFile &F);
1196 struct InputFileInfo {
1197 std::string Filename;
1202 bool TopLevelModuleMap;
1205 /// Reads the stored information about an input file.
1206 InputFileInfo readInputFileInfo(ModuleFile &F, unsigned ID);
1208 /// Retrieve the file entry and 'overridden' bit for an input
1209 /// file in the given module file.
1210 serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
1211 bool Complain = true);
1214 void ResolveImportedPath(ModuleFile &M, std::string &Filename);
1215 static void ResolveImportedPath(std::string &Filename, StringRef Prefix);
1217 /// Returns the first key declaration for the given declaration. This
1218 /// is one that is formerly-canonical (or still canonical) and whose module
1219 /// did not import any other key declaration of the entity.
1220 Decl *getKeyDeclaration(Decl *D) {
1221 D = D->getCanonicalDecl();
1222 if (D->isFromASTFile())
1225 auto I = KeyDecls.find(D);
1226 if (I == KeyDecls.end() || I->second.empty())
1228 return GetExistingDecl(I->second[0]);
1230 const Decl *getKeyDeclaration(const Decl *D) {
1231 return getKeyDeclaration(const_cast<Decl*>(D));
1234 /// Run a callback on each imported key declaration of \p D.
1235 template <typename Fn>
1236 void forEachImportedKeyDecl(const Decl *D, Fn Visit) {
1237 D = D->getCanonicalDecl();
1238 if (D->isFromASTFile())
1241 auto It = KeyDecls.find(const_cast<Decl*>(D));
1242 if (It != KeyDecls.end())
1243 for (auto ID : It->second)
1244 Visit(GetExistingDecl(ID));
1247 /// Get the loaded lookup tables for \p Primary, if any.
1248 const serialization::reader::DeclContextLookupTable *
1249 getLoadedLookupTables(DeclContext *Primary) const;
1252 struct ImportedModule {
1254 ModuleFile *ImportedBy;
1255 SourceLocation ImportLoc;
1257 ImportedModule(ModuleFile *Mod,
1258 ModuleFile *ImportedBy,
1259 SourceLocation ImportLoc)
1260 : Mod(Mod), ImportedBy(ImportedBy), ImportLoc(ImportLoc) {}
1263 ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
1264 SourceLocation ImportLoc, ModuleFile *ImportedBy,
1265 SmallVectorImpl<ImportedModule> &Loaded,
1266 off_t ExpectedSize, time_t ExpectedModTime,
1267 ASTFileSignature ExpectedSignature,
1268 unsigned ClientLoadCapabilities);
1269 ASTReadResult ReadControlBlock(ModuleFile &F,
1270 SmallVectorImpl<ImportedModule> &Loaded,
1271 const ModuleFile *ImportedBy,
1272 unsigned ClientLoadCapabilities);
1273 static ASTReadResult ReadOptionsBlock(
1274 llvm::BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
1275 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
1276 std::string &SuggestedPredefines);
1278 /// Read the unhashed control block.
1280 /// This has no effect on \c F.Stream, instead creating a fresh cursor from
1281 /// \c F.Data and reading ahead.
1282 ASTReadResult readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
1283 unsigned ClientLoadCapabilities);
1285 static ASTReadResult
1286 readUnhashedControlBlockImpl(ModuleFile *F, llvm::StringRef StreamData,
1287 unsigned ClientLoadCapabilities,
1288 bool AllowCompatibleConfigurationMismatch,
1289 ASTReaderListener *Listener,
1290 bool ValidateDiagnosticOptions);
1292 ASTReadResult ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities);
1293 ASTReadResult ReadExtensionBlock(ModuleFile &F);
1294 void ReadModuleOffsetMap(ModuleFile &F) const;
1295 bool ParseLineTable(ModuleFile &F, const RecordData &Record);
1296 bool ReadSourceManagerBlock(ModuleFile &F);
1297 llvm::BitstreamCursor &SLocCursorForID(int ID);
1298 SourceLocation getImportLocation(ModuleFile *F);
1299 ASTReadResult ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
1300 const ModuleFile *ImportedBy,
1301 unsigned ClientLoadCapabilities);
1302 ASTReadResult ReadSubmoduleBlock(ModuleFile &F,
1303 unsigned ClientLoadCapabilities);
1304 static bool ParseLanguageOptions(const RecordData &Record, bool Complain,
1305 ASTReaderListener &Listener,
1306 bool AllowCompatibleDifferences);
1307 static bool ParseTargetOptions(const RecordData &Record, bool Complain,
1308 ASTReaderListener &Listener,
1309 bool AllowCompatibleDifferences);
1310 static bool ParseDiagnosticOptions(const RecordData &Record, bool Complain,
1311 ASTReaderListener &Listener);
1312 static bool ParseFileSystemOptions(const RecordData &Record, bool Complain,
1313 ASTReaderListener &Listener);
1314 static bool ParseHeaderSearchOptions(const RecordData &Record, bool Complain,
1315 ASTReaderListener &Listener);
1316 static bool ParsePreprocessorOptions(const RecordData &Record, bool Complain,
1317 ASTReaderListener &Listener,
1318 std::string &SuggestedPredefines);
1320 struct RecordLocation {
1324 RecordLocation(ModuleFile *M, uint64_t O) : F(M), Offset(O) {}
1327 QualType readTypeRecord(unsigned Index);
1328 void readExceptionSpec(ModuleFile &ModuleFile,
1329 SmallVectorImpl<QualType> &ExceptionStorage,
1330 FunctionProtoType::ExceptionSpecInfo &ESI,
1331 const RecordData &Record, unsigned &Index);
1332 RecordLocation TypeCursorForIndex(unsigned Index);
1333 void LoadedDecl(unsigned Index, Decl *D);
1334 Decl *ReadDeclRecord(serialization::DeclID ID);
1335 void markIncompleteDeclChain(Decl *Canon);
1337 /// Returns the most recent declaration of a declaration (which must be
1338 /// of a redeclarable kind) that is either local or has already been loaded
1339 /// merged into its redecl chain.
1340 Decl *getMostRecentExistingDecl(Decl *D);
1342 RecordLocation DeclCursorForID(serialization::DeclID ID,
1343 SourceLocation &Location);
1344 void loadDeclUpdateRecords(PendingUpdateRecord &Record);
1345 void loadPendingDeclChain(Decl *D, uint64_t LocalOffset);
1346 void loadObjCCategories(serialization::GlobalDeclID ID, ObjCInterfaceDecl *D,
1347 unsigned PreviousGeneration = 0);
1349 RecordLocation getLocalBitOffset(uint64_t GlobalOffset);
1350 uint64_t getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset);
1352 /// Returns the first preprocessed entity ID that begins or ends after
1354 serialization::PreprocessedEntityID
1355 findPreprocessedEntity(SourceLocation Loc, bool EndsAfter) const;
1357 /// Find the next module that contains entities and return the ID
1358 /// of the first entry.
1360 /// \param SLocMapI points at a chunk of a module that contains no
1361 /// preprocessed entities or the entities it contains are not the
1362 /// ones we are looking for.
1363 serialization::PreprocessedEntityID
1364 findNextPreprocessedEntity(
1365 GlobalSLocOffsetMapType::const_iterator SLocMapI) const;
1367 /// Returns (ModuleFile, Local index) pair for \p GlobalIndex of a
1368 /// preprocessed entity.
1369 std::pair<ModuleFile *, unsigned>
1370 getModulePreprocessedEntity(unsigned GlobalIndex);
1372 /// Returns (begin, end) pair for the preprocessed entities of a
1373 /// particular module.
1374 llvm::iterator_range<PreprocessingRecord::iterator>
1375 getModulePreprocessedEntities(ModuleFile &Mod) const;
1378 class ModuleDeclIterator
1379 : public llvm::iterator_adaptor_base<
1380 ModuleDeclIterator, const serialization::LocalDeclID *,
1381 std::random_access_iterator_tag, const Decl *, ptrdiff_t,
1382 const Decl *, const Decl *> {
1383 ASTReader *Reader = nullptr;
1384 ModuleFile *Mod = nullptr;
1387 ModuleDeclIterator() : iterator_adaptor_base(nullptr) {}
1389 ModuleDeclIterator(ASTReader *Reader, ModuleFile *Mod,
1390 const serialization::LocalDeclID *Pos)
1391 : iterator_adaptor_base(Pos), Reader(Reader), Mod(Mod) {}
1393 value_type operator*() const {
1394 return Reader->GetDecl(Reader->getGlobalDeclID(*Mod, *I));
1397 value_type operator->() const { return **this; }
1399 bool operator==(const ModuleDeclIterator &RHS) const {
1400 assert(Reader == RHS.Reader && Mod == RHS.Mod);
1405 llvm::iterator_range<ModuleDeclIterator>
1406 getModuleFileLevelDecls(ModuleFile &Mod);
1409 void PassInterestingDeclsToConsumer();
1410 void PassInterestingDeclToConsumer(Decl *D);
1412 void finishPendingActions();
1413 void diagnoseOdrViolations();
1415 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
1417 void addPendingDeclContextInfo(Decl *D,
1418 serialization::GlobalDeclID SemaDC,
1419 serialization::GlobalDeclID LexicalDC) {
1421 PendingDeclContextInfo Info = { D, SemaDC, LexicalDC };
1422 PendingDeclContextInfos.push_back(Info);
1425 /// Produce an error diagnostic and return true.
1427 /// This routine should only be used for fatal errors that have to
1428 /// do with non-routine failures (e.g., corrupted AST file).
1429 void Error(StringRef Msg) const;
1430 void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
1431 StringRef Arg2 = StringRef()) const;
1434 /// Load the AST file and validate its contents against the given
1437 /// \param PP the preprocessor associated with the context in which this
1438 /// precompiled header will be loaded.
1440 /// \param Context the AST context that this precompiled header will be
1441 /// loaded into, if any.
1443 /// \param PCHContainerRdr the PCHContainerOperations to use for loading and
1444 /// creating modules.
1446 /// \param Extensions the list of module file extensions that can be loaded
1447 /// from the AST files.
1449 /// \param isysroot If non-NULL, the system include path specified by the
1450 /// user. This is only used with relocatable PCH files. If non-NULL,
1451 /// a relocatable PCH file will use the default path "/".
1453 /// \param DisableValidation If true, the AST reader will suppress most
1454 /// of its regular consistency checking, allowing the use of precompiled
1455 /// headers that cannot be determined to be compatible.
1457 /// \param AllowASTWithCompilerErrors If true, the AST reader will accept an
1458 /// AST file the was created out of an AST with compiler errors,
1459 /// otherwise it will reject it.
1461 /// \param AllowConfigurationMismatch If true, the AST reader will not check
1462 /// for configuration differences between the AST file and the invocation.
1464 /// \param ValidateSystemInputs If true, the AST reader will validate
1465 /// system input files in addition to user input files. This is only
1466 /// meaningful if \p DisableValidation is false.
1468 /// \param UseGlobalIndex If true, the AST reader will try to load and use
1469 /// the global module index.
1471 /// \param ReadTimer If non-null, a timer used to track the time spent
1473 ASTReader(Preprocessor &PP, ASTContext *Context,
1474 const PCHContainerReader &PCHContainerRdr,
1475 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
1476 StringRef isysroot = "", bool DisableValidation = false,
1477 bool AllowASTWithCompilerErrors = false,
1478 bool AllowConfigurationMismatch = false,
1479 bool ValidateSystemInputs = false, bool UseGlobalIndex = true,
1480 std::unique_ptr<llvm::Timer> ReadTimer = {});
1481 ASTReader(const ASTReader &) = delete;
1482 ASTReader &operator=(const ASTReader &) = delete;
1483 ~ASTReader() override;
1485 SourceManager &getSourceManager() const { return SourceMgr; }
1486 FileManager &getFileManager() const { return FileMgr; }
1487 DiagnosticsEngine &getDiags() const { return Diags; }
1489 /// Flags that indicate what kind of AST loading failures the client
1490 /// of the AST reader can directly handle.
1492 /// When a client states that it can handle a particular kind of failure,
1493 /// the AST reader will not emit errors when producing that kind of failure.
1494 enum LoadFailureCapabilities {
1495 /// The client can't handle any AST loading failures.
1498 /// The client can handle an AST file that cannot load because it
1502 /// The client can handle an AST file that cannot load because it
1503 /// is out-of-date relative to its input files.
1504 ARR_OutOfDate = 0x2,
1506 /// The client can handle an AST file that cannot load because it
1507 /// was built with a different version of Clang.
1508 ARR_VersionMismatch = 0x4,
1510 /// The client can handle an AST file that cannot load because it's
1511 /// compiled configuration doesn't match that of the context it was
1513 ARR_ConfigurationMismatch = 0x8
1516 /// Load the AST file designated by the given file name.
1518 /// \param FileName The name of the AST file to load.
1520 /// \param Type The kind of AST being loaded, e.g., PCH, module, main file,
1523 /// \param ImportLoc the location where the module file will be considered as
1524 /// imported from. For non-module AST types it should be invalid.
1526 /// \param ClientLoadCapabilities The set of client load-failure
1527 /// capabilities, represented as a bitset of the enumerators of
1528 /// LoadFailureCapabilities.
1530 /// \param Imported optional out-parameter to append the list of modules
1531 /// that were imported by precompiled headers or any other non-module AST file
1532 ASTReadResult ReadAST(StringRef FileName, ModuleKind Type,
1533 SourceLocation ImportLoc,
1534 unsigned ClientLoadCapabilities,
1535 SmallVectorImpl<ImportedSubmodule> *Imported = nullptr);
1537 /// Make the entities in the given module and any of its (non-explicit)
1538 /// submodules visible to name lookup.
1540 /// \param Mod The module whose names should be made visible.
1542 /// \param NameVisibility The level of visibility to give the names in the
1543 /// module. Visibility can only be increased over time.
1545 /// \param ImportLoc The location at which the import occurs.
1546 void makeModuleVisible(Module *Mod,
1547 Module::NameVisibilityKind NameVisibility,
1548 SourceLocation ImportLoc);
1550 /// Make the names within this set of hidden names visible.
1551 void makeNamesVisible(const HiddenNames &Names, Module *Owner);
1553 /// Note that MergedDef is a redefinition of the canonical definition
1554 /// Def, so Def should be visible whenever MergedDef is.
1555 void mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef);
1557 /// Take the AST callbacks listener.
1558 std::unique_ptr<ASTReaderListener> takeListener() {
1559 return std::move(Listener);
1562 /// Set the AST callbacks listener.
1563 void setListener(std::unique_ptr<ASTReaderListener> Listener) {
1564 this->Listener = std::move(Listener);
1567 /// Add an AST callback listener.
1569 /// Takes ownership of \p L.
1570 void addListener(std::unique_ptr<ASTReaderListener> L) {
1572 L = llvm::make_unique<ChainedASTReaderListener>(std::move(L),
1573 std::move(Listener));
1574 Listener = std::move(L);
1577 /// RAII object to temporarily add an AST callback listener.
1578 class ListenerScope {
1580 bool Chained = false;
1583 ListenerScope(ASTReader &Reader, std::unique_ptr<ASTReaderListener> L)
1585 auto Old = Reader.takeListener();
1588 L = llvm::make_unique<ChainedASTReaderListener>(std::move(L),
1591 Reader.setListener(std::move(L));
1595 auto New = Reader.takeListener();
1597 Reader.setListener(static_cast<ChainedASTReaderListener *>(New.get())
1602 /// Set the AST deserialization listener.
1603 void setDeserializationListener(ASTDeserializationListener *Listener,
1604 bool TakeOwnership = false);
1606 /// Get the AST deserialization listener.
1607 ASTDeserializationListener *getDeserializationListener() {
1608 return DeserializationListener;
1611 /// Determine whether this AST reader has a global index.
1612 bool hasGlobalIndex() const { return (bool)GlobalIndex; }
1614 /// Return global module index.
1615 GlobalModuleIndex *getGlobalIndex() { return GlobalIndex.get(); }
1617 /// Reset reader for a reload try.
1618 void resetForReload() { TriedLoadingGlobalIndex = false; }
1620 /// Attempts to load the global index.
1622 /// \returns true if loading the global index has failed for any reason.
1623 bool loadGlobalIndex();
1625 /// Determine whether we tried to load the global index, but failed,
1626 /// e.g., because it is out-of-date or does not exist.
1627 bool isGlobalIndexUnavailable() const;
1629 /// Initializes the ASTContext
1630 void InitializeContext();
1632 /// Update the state of Sema after loading some additional modules.
1635 /// Add in-memory (virtual file) buffer.
1636 void addInMemoryBuffer(StringRef &FileName,
1637 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
1638 ModuleMgr.addInMemoryBuffer(FileName, std::move(Buffer));
1641 /// Finalizes the AST reader's state before writing an AST file to
1644 /// This operation may undo temporary state in the AST that should not be
1646 void finalizeForWriting();
1648 /// Retrieve the module manager.
1649 ModuleManager &getModuleManager() { return ModuleMgr; }
1651 /// Retrieve the preprocessor.
1652 Preprocessor &getPreprocessor() const { return PP; }
1654 /// Retrieve the name of the original source file name for the primary
1656 StringRef getOriginalSourceFile() {
1657 return ModuleMgr.getPrimaryModule().OriginalSourceFileName;
1660 /// Retrieve the name of the original source file name directly from
1661 /// the AST file, without actually loading the AST file.
1663 getOriginalSourceFile(const std::string &ASTFileName, FileManager &FileMgr,
1664 const PCHContainerReader &PCHContainerRdr,
1665 DiagnosticsEngine &Diags);
1667 /// Read the control block for the named AST file.
1669 /// \returns true if an error occurred, false otherwise.
1671 readASTFileControlBlock(StringRef Filename, FileManager &FileMgr,
1672 const PCHContainerReader &PCHContainerRdr,
1673 bool FindModuleFileExtensions,
1674 ASTReaderListener &Listener,
1675 bool ValidateDiagnosticOptions);
1677 /// Determine whether the given AST file is acceptable to load into a
1678 /// translation unit with the given language and target options.
1679 static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
1680 const PCHContainerReader &PCHContainerRdr,
1681 const LangOptions &LangOpts,
1682 const TargetOptions &TargetOpts,
1683 const PreprocessorOptions &PPOpts,
1684 StringRef ExistingModuleCachePath);
1686 /// Returns the suggested contents of the predefines buffer,
1687 /// which contains a (typically-empty) subset of the predefines
1688 /// build prior to including the precompiled header.
1689 const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
1691 /// Read a preallocated preprocessed entity from the external source.
1693 /// \returns null if an error occurred that prevented the preprocessed
1694 /// entity from being loaded.
1695 PreprocessedEntity *ReadPreprocessedEntity(unsigned Index) override;
1697 /// Returns a pair of [Begin, End) indices of preallocated
1698 /// preprocessed entities that \p Range encompasses.
1699 std::pair<unsigned, unsigned>
1700 findPreprocessedEntitiesInRange(SourceRange Range) override;
1702 /// Optionally returns true or false if the preallocated preprocessed
1703 /// entity with index \p Index came from file \p FID.
1704 Optional<bool> isPreprocessedEntityInFileID(unsigned Index,
1705 FileID FID) override;
1707 /// Read a preallocated skipped range from the external source.
1708 SourceRange ReadSkippedRange(unsigned Index) override;
1710 /// Read the header file information for the given file entry.
1711 HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) override;
1713 void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag);
1715 /// Returns the number of source locations found in the chain.
1716 unsigned getTotalNumSLocs() const {
1717 return TotalNumSLocEntries;
1720 /// Returns the number of identifiers found in the chain.
1721 unsigned getTotalNumIdentifiers() const {
1722 return static_cast<unsigned>(IdentifiersLoaded.size());
1725 /// Returns the number of macros found in the chain.
1726 unsigned getTotalNumMacros() const {
1727 return static_cast<unsigned>(MacrosLoaded.size());
1730 /// Returns the number of types found in the chain.
1731 unsigned getTotalNumTypes() const {
1732 return static_cast<unsigned>(TypesLoaded.size());
1735 /// Returns the number of declarations found in the chain.
1736 unsigned getTotalNumDecls() const {
1737 return static_cast<unsigned>(DeclsLoaded.size());
1740 /// Returns the number of submodules known.
1741 unsigned getTotalNumSubmodules() const {
1742 return static_cast<unsigned>(SubmodulesLoaded.size());
1745 /// Returns the number of selectors found in the chain.
1746 unsigned getTotalNumSelectors() const {
1747 return static_cast<unsigned>(SelectorsLoaded.size());
1750 /// Returns the number of preprocessed entities known to the AST
1752 unsigned getTotalNumPreprocessedEntities() const {
1753 unsigned Result = 0;
1754 for (const auto &M : ModuleMgr)
1755 Result += M.NumPreprocessedEntities;
1759 /// Reads a TemplateArgumentLocInfo appropriate for the
1760 /// given TemplateArgument kind.
1761 TemplateArgumentLocInfo
1762 GetTemplateArgumentLocInfo(ModuleFile &F, TemplateArgument::ArgKind Kind,
1763 const RecordData &Record, unsigned &Idx);
1765 /// Reads a TemplateArgumentLoc.
1767 ReadTemplateArgumentLoc(ModuleFile &F,
1768 const RecordData &Record, unsigned &Idx);
1770 const ASTTemplateArgumentListInfo*
1771 ReadASTTemplateArgumentListInfo(ModuleFile &F,
1772 const RecordData &Record, unsigned &Index);
1774 /// Reads a declarator info from the given record.
1775 TypeSourceInfo *GetTypeSourceInfo(ModuleFile &F,
1776 const RecordData &Record, unsigned &Idx);
1778 /// Raad the type locations for the given TInfo.
1779 void ReadTypeLoc(ModuleFile &F, const RecordData &Record, unsigned &Idx,
1782 /// Resolve a type ID into a type, potentially building a new
1784 QualType GetType(serialization::TypeID ID);
1786 /// Resolve a local type ID within a given AST file into a type.
1787 QualType getLocalType(ModuleFile &F, unsigned LocalID);
1789 /// Map a local type ID within a given AST file into a global type ID.
1790 serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const;
1792 /// Read a type from the current position in the given record, which
1793 /// was read from the given AST file.
1794 QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) {
1795 if (Idx >= Record.size())
1798 return getLocalType(F, Record[Idx++]);
1801 /// Map from a local declaration ID within a given module to a
1802 /// global declaration ID.
1803 serialization::DeclID getGlobalDeclID(ModuleFile &F,
1804 serialization::LocalDeclID LocalID) const;
1806 /// Returns true if global DeclID \p ID originated from module \p M.
1807 bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const;
1809 /// Retrieve the module file that owns the given declaration, or NULL
1810 /// if the declaration is not from a module file.
1811 ModuleFile *getOwningModuleFile(const Decl *D);
1813 /// Get the best name we know for the module that owns the given
1814 /// declaration, or an empty string if the declaration is not from a module.
1815 std::string getOwningModuleNameForDiagnostic(const Decl *D);
1817 /// Returns the source location for the decl \p ID.
1818 SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID);
1820 /// Resolve a declaration ID into a declaration, potentially
1821 /// building a new declaration.
1822 Decl *GetDecl(serialization::DeclID ID);
1823 Decl *GetExternalDecl(uint32_t ID) override;
1825 /// Resolve a declaration ID into a declaration. Return 0 if it's not
1826 /// been loaded yet.
1827 Decl *GetExistingDecl(serialization::DeclID ID);
1829 /// Reads a declaration with the given local ID in the given module.
1830 Decl *GetLocalDecl(ModuleFile &F, uint32_t LocalID) {
1831 return GetDecl(getGlobalDeclID(F, LocalID));
1834 /// Reads a declaration with the given local ID in the given module.
1836 /// \returns The requested declaration, casted to the given return type.
1837 template<typename T>
1838 T *GetLocalDeclAs(ModuleFile &F, uint32_t LocalID) {
1839 return cast_or_null<T>(GetLocalDecl(F, LocalID));
1842 /// Map a global declaration ID into the declaration ID used to
1843 /// refer to this declaration within the given module fule.
1845 /// \returns the global ID of the given declaration as known in the given
1847 serialization::DeclID
1848 mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
1849 serialization::DeclID GlobalID);
1851 /// Reads a declaration ID from the given position in a record in the
1854 /// \returns The declaration ID read from the record, adjusted to a global ID.
1855 serialization::DeclID ReadDeclID(ModuleFile &F, const RecordData &Record,
1858 /// Reads a declaration from the given position in a record in the
1860 Decl *ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I) {
1861 return GetDecl(ReadDeclID(F, R, I));
1864 /// Reads a declaration from the given position in a record in the
1867 /// \returns The declaration read from this location, casted to the given
1869 template<typename T>
1870 T *ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I) {
1871 return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
1874 /// If any redeclarations of \p D have been imported since it was
1875 /// last checked, this digs out those redeclarations and adds them to the
1876 /// redeclaration chain for \p D.
1877 void CompleteRedeclChain(const Decl *D) override;
1879 CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override;
1881 /// Resolve the offset of a statement into a statement.
1883 /// This operation will read a new statement from the external
1884 /// source each time it is called, and is meant to be used via a
1885 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1886 Stmt *GetExternalDeclStmt(uint64_t Offset) override;
1888 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1889 /// specified cursor. Read the abbreviations that are at the top of the block
1890 /// and then leave the cursor pointing into the block.
1891 static bool ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID);
1893 /// Finds all the visible declarations with a given name.
1894 /// The current implementation of this method just loads the entire
1895 /// lookup table as unmaterialized references.
1896 bool FindExternalVisibleDeclsByName(const DeclContext *DC,
1897 DeclarationName Name) override;
1899 /// Read all of the declarations lexically stored in a
1900 /// declaration context.
1902 /// \param DC The declaration context whose declarations will be
1905 /// \param IsKindWeWant A predicate indicating which declaration kinds
1906 /// we are interested in.
1908 /// \param Decls Vector that will contain the declarations loaded
1909 /// from the external source. The caller is responsible for merging
1910 /// these declarations with any declarations already stored in the
1911 /// declaration context.
1913 FindExternalLexicalDecls(const DeclContext *DC,
1914 llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
1915 SmallVectorImpl<Decl *> &Decls) override;
1917 /// Get the decls that are contained in a file in the Offset/Length
1918 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
1920 void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
1921 SmallVectorImpl<Decl *> &Decls) override;
1923 /// Notify ASTReader that we started deserialization of
1924 /// a decl or type so until FinishedDeserializing is called there may be
1925 /// decls that are initializing. Must be paired with FinishedDeserializing.
1926 void StartedDeserializing() override;
1928 /// Notify ASTReader that we finished the deserialization of
1929 /// a decl or type. Must be paired with StartedDeserializing.
1930 void FinishedDeserializing() override;
1932 /// Function that will be invoked when we begin parsing a new
1933 /// translation unit involving this external AST source.
1935 /// This function will provide all of the external definitions to
1936 /// the ASTConsumer.
1937 void StartTranslationUnit(ASTConsumer *Consumer) override;
1939 /// Print some statistics about AST usage.
1940 void PrintStats() override;
1942 /// Dump information about the AST reader to standard error.
1945 /// Return the amount of memory used by memory buffers, breaking down
1946 /// by heap-backed versus mmap'ed memory.
1947 void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override;
1949 /// Initialize the semantic source with the Sema instance
1950 /// being used to perform semantic analysis on the abstract syntax
1952 void InitializeSema(Sema &S) override;
1954 /// Inform the semantic consumer that Sema is no longer available.
1955 void ForgetSema() override { SemaObj = nullptr; }
1957 /// Retrieve the IdentifierInfo for the named identifier.
1959 /// This routine builds a new IdentifierInfo for the given identifier. If any
1960 /// declarations with this name are visible from translation unit scope, their
1961 /// declarations will be deserialized and introduced into the declaration
1962 /// chain of the identifier.
1963 IdentifierInfo *get(StringRef Name) override;
1965 /// Retrieve an iterator into the set of all identifiers
1966 /// in all loaded AST files.
1967 IdentifierIterator *getIdentifiers() override;
1969 /// Load the contents of the global method pool for a given
1971 void ReadMethodPool(Selector Sel) override;
1973 /// Load the contents of the global method pool for a given
1974 /// selector if necessary.
1975 void updateOutOfDateSelector(Selector Sel) override;
1977 /// Load the set of namespaces that are known to the external source,
1978 /// which will be used during typo correction.
1979 void ReadKnownNamespaces(
1980 SmallVectorImpl<NamespaceDecl *> &Namespaces) override;
1982 void ReadUndefinedButUsed(
1983 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) override;
1985 void ReadMismatchingDeleteExpressions(llvm::MapVector<
1986 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
1989 void ReadTentativeDefinitions(
1990 SmallVectorImpl<VarDecl *> &TentativeDefs) override;
1992 void ReadUnusedFileScopedDecls(
1993 SmallVectorImpl<const DeclaratorDecl *> &Decls) override;
1995 void ReadDelegatingConstructors(
1996 SmallVectorImpl<CXXConstructorDecl *> &Decls) override;
1998 void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) override;
2000 void ReadUnusedLocalTypedefNameCandidates(
2001 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) override;
2003 void ReadReferencedSelectors(
2004 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) override;
2006 void ReadWeakUndeclaredIdentifiers(
2007 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WI) override;
2009 void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) override;
2011 void ReadPendingInstantiations(
2012 SmallVectorImpl<std::pair<ValueDecl *,
2013 SourceLocation>> &Pending) override;
2015 void ReadLateParsedTemplates(
2016 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
2019 /// Load a selector from disk, registering its ID if it exists.
2020 void LoadSelector(Selector Sel);
2022 void SetIdentifierInfo(unsigned ID, IdentifierInfo *II);
2023 void SetGloballyVisibleDecls(IdentifierInfo *II,
2024 const SmallVectorImpl<uint32_t> &DeclIDs,
2025 SmallVectorImpl<Decl *> *Decls = nullptr);
2027 /// Report a diagnostic.
2028 DiagnosticBuilder Diag(unsigned DiagID) const;
2030 /// Report a diagnostic.
2031 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const;
2033 IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID);
2035 IdentifierInfo *GetIdentifierInfo(ModuleFile &M, const RecordData &Record,
2037 return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++]));
2040 IdentifierInfo *GetIdentifier(serialization::IdentifierID ID) override {
2041 // Note that we are loading an identifier.
2042 Deserializing AnIdentifier(this);
2044 return DecodeIdentifierInfo(ID);
2047 IdentifierInfo *getLocalIdentifier(ModuleFile &M, unsigned LocalID);
2049 serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M,
2052 void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo);
2054 /// Retrieve the macro with the given ID.
2055 MacroInfo *getMacro(serialization::MacroID ID);
2057 /// Retrieve the global macro ID corresponding to the given local
2058 /// ID within the given module file.
2059 serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID);
2061 /// Read the source location entry with index ID.
2062 bool ReadSLocEntry(int ID) override;
2064 /// Retrieve the module import location and module name for the
2065 /// given source manager entry ID.
2066 std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) override;
2068 /// Retrieve the global submodule ID given a module and its local ID
2070 serialization::SubmoduleID
2071 getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID);
2073 /// Retrieve the submodule that corresponds to a global submodule ID.
2075 Module *getSubmodule(serialization::SubmoduleID GlobalID);
2077 /// Retrieve the module that corresponds to the given module ID.
2079 /// Note: overrides method in ExternalASTSource
2080 Module *getModule(unsigned ID) override;
2082 bool DeclIsFromPCHWithObjectFile(const Decl *D) override;
2084 /// Retrieve the module file with a given local ID within the specified
2086 ModuleFile *getLocalModuleFile(ModuleFile &M, unsigned ID);
2088 /// Get an ID for the given module file.
2089 unsigned getModuleFileID(ModuleFile *M);
2091 /// Return a descriptor for the corresponding module.
2092 llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID) override;
2094 ExtKind hasExternalDefinitions(const Decl *D) override;
2096 /// Retrieve a selector from the given module with its local ID
2098 Selector getLocalSelector(ModuleFile &M, unsigned LocalID);
2100 Selector DecodeSelector(serialization::SelectorID Idx);
2102 Selector GetExternalSelector(serialization::SelectorID ID) override;
2103 uint32_t GetNumExternalSelectors() override;
2105 Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) {
2106 return getLocalSelector(M, Record[Idx++]);
2109 /// Retrieve the global selector ID that corresponds to this
2110 /// the local selector ID in a given module.
2111 serialization::SelectorID getGlobalSelectorID(ModuleFile &F,
2112 unsigned LocalID) const;
2114 /// Read a declaration name.
2115 DeclarationName ReadDeclarationName(ModuleFile &F,
2116 const RecordData &Record, unsigned &Idx);
2117 void ReadDeclarationNameLoc(ModuleFile &F,
2118 DeclarationNameLoc &DNLoc, DeclarationName Name,
2119 const RecordData &Record, unsigned &Idx);
2120 void ReadDeclarationNameInfo(ModuleFile &F, DeclarationNameInfo &NameInfo,
2121 const RecordData &Record, unsigned &Idx);
2123 void ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
2124 const RecordData &Record, unsigned &Idx);
2126 NestedNameSpecifier *ReadNestedNameSpecifier(ModuleFile &F,
2127 const RecordData &Record,
2130 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(ModuleFile &F,
2131 const RecordData &Record,
2134 /// Read a template name.
2135 TemplateName ReadTemplateName(ModuleFile &F, const RecordData &Record,
2138 /// Read a template argument.
2139 TemplateArgument ReadTemplateArgument(ModuleFile &F, const RecordData &Record,
2141 bool Canonicalize = false);
2143 /// Read a template parameter list.
2144 TemplateParameterList *ReadTemplateParameterList(ModuleFile &F,
2145 const RecordData &Record,
2148 /// Read a template argument array.
2149 void ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
2150 ModuleFile &F, const RecordData &Record,
2151 unsigned &Idx, bool Canonicalize = false);
2153 /// Read a UnresolvedSet structure.
2154 void ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
2155 const RecordData &Record, unsigned &Idx);
2157 /// Read a C++ base specifier.
2158 CXXBaseSpecifier ReadCXXBaseSpecifier(ModuleFile &F,
2159 const RecordData &Record,unsigned &Idx);
2161 /// Read a CXXCtorInitializer array.
2162 CXXCtorInitializer **
2163 ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
2166 /// Read the contents of a CXXCtorInitializer array.
2167 CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset) override;
2169 /// Read a source location from raw form and return it in its
2170 /// originating module file's source location space.
2171 SourceLocation ReadUntranslatedSourceLocation(uint32_t Raw) const {
2172 return SourceLocation::getFromRawEncoding((Raw >> 1) | (Raw << 31));
2175 /// Read a source location from raw form.
2176 SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, uint32_t Raw) const {
2177 SourceLocation Loc = ReadUntranslatedSourceLocation(Raw);
2178 return TranslateSourceLocation(ModuleFile, Loc);
2181 /// Translate a source location from another module file's source
2182 /// location space into ours.
2183 SourceLocation TranslateSourceLocation(ModuleFile &ModuleFile,
2184 SourceLocation Loc) const {
2185 if (!ModuleFile.ModuleOffsetMap.empty())
2186 ReadModuleOffsetMap(ModuleFile);
2187 assert(ModuleFile.SLocRemap.find(Loc.getOffset()) !=
2188 ModuleFile.SLocRemap.end() &&
2189 "Cannot find offset to remap.");
2190 int Remap = ModuleFile.SLocRemap.find(Loc.getOffset())->second;
2191 return Loc.getLocWithOffset(Remap);
2194 /// Read a source location.
2195 SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
2196 const RecordDataImpl &Record,
2198 return ReadSourceLocation(ModuleFile, Record[Idx++]);
2201 /// Read a source range.
2202 SourceRange ReadSourceRange(ModuleFile &F,
2203 const RecordData &Record, unsigned &Idx);
2205 /// Read an integral value
2206 llvm::APInt ReadAPInt(const RecordData &Record, unsigned &Idx);
2208 /// Read a signed integral value
2209 llvm::APSInt ReadAPSInt(const RecordData &Record, unsigned &Idx);
2211 /// Read a floating-point value
2212 llvm::APFloat ReadAPFloat(const RecordData &Record,
2213 const llvm::fltSemantics &Sem, unsigned &Idx);
2216 static std::string ReadString(const RecordData &Record, unsigned &Idx);
2219 static void SkipString(const RecordData &Record, unsigned &Idx) {
2220 Idx += Record[Idx] + 1;
2224 std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx);
2227 static void SkipPath(const RecordData &Record, unsigned &Idx) {
2228 SkipString(Record, Idx);
2231 /// Read a version tuple.
2232 static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
2234 CXXTemporary *ReadCXXTemporary(ModuleFile &F, const RecordData &Record,
2237 /// Reads attributes from the current stream position.
2238 void ReadAttributes(ASTRecordReader &Record, AttrVec &Attrs);
2240 /// Reads a statement.
2241 Stmt *ReadStmt(ModuleFile &F);
2243 /// Reads an expression.
2244 Expr *ReadExpr(ModuleFile &F);
2246 /// Reads a sub-statement operand during statement reading.
2247 Stmt *ReadSubStmt() {
2248 assert(ReadingKind == Read_Stmt &&
2249 "Should be called only during statement reading!");
2250 // Subexpressions are stored from last to first, so the next Stmt we need
2251 // is at the back of the stack.
2252 assert(!StmtStack.empty() && "Read too many sub-statements!");
2253 return StmtStack.pop_back_val();
2256 /// Reads a sub-expression operand during statement reading.
2257 Expr *ReadSubExpr();
2259 /// Reads a token out of a record.
2260 Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx);
2262 /// Reads the macro record located at the given offset.
2263 MacroInfo *ReadMacroRecord(ModuleFile &F, uint64_t Offset);
2265 /// Determine the global preprocessed entity ID that corresponds to
2266 /// the given local ID within the given module.
2267 serialization::PreprocessedEntityID
2268 getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const;
2270 /// Add a macro to deserialize its macro directive history.
2272 /// \param II The name of the macro.
2273 /// \param M The module file.
2274 /// \param MacroDirectivesOffset Offset of the serialized macro directive
2276 void addPendingMacro(IdentifierInfo *II, ModuleFile *M,
2277 uint64_t MacroDirectivesOffset);
2279 /// Read the set of macros defined by this external macro source.
2280 void ReadDefinedMacros() override;
2282 /// Update an out-of-date identifier.
2283 void updateOutOfDateIdentifier(IdentifierInfo &II) override;
2285 /// Note that this identifier is up-to-date.
2286 void markIdentifierUpToDate(IdentifierInfo *II);
2288 /// Load all external visible decls in the given DeclContext.
2289 void completeVisibleDeclsMap(const DeclContext *DC) override;
2291 /// Retrieve the AST context that this AST reader supplements.
2292 ASTContext &getContext() {
2293 assert(ContextObj && "requested AST context when not loading AST");
2297 // Contains the IDs for declarations that were requested before we have
2298 // access to a Sema object.
2299 SmallVector<uint64_t, 16> PreloadedDeclIDs;
2301 /// Retrieve the semantic analysis object used to analyze the
2302 /// translation unit in which the precompiled header is being
2304 Sema *getSema() { return SemaObj; }
2306 /// Get the identifier resolver used for name lookup / updates
2307 /// in the translation unit scope. We have one of these even if we don't
2308 /// have a Sema object.
2309 IdentifierResolver &getIdResolver();
2311 /// Retrieve the identifier table associated with the
2313 IdentifierTable &getIdentifierTable();
2315 /// Record that the given ID maps to the given switch-case
2317 void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
2319 /// Retrieve the switch-case statement with the given ID.
2320 SwitchCase *getSwitchCaseWithID(unsigned ID);
2322 void ClearSwitchCaseIDs();
2324 /// Cursors for comments blocks.
2325 SmallVector<std::pair<llvm::BitstreamCursor,
2326 serialization::ModuleFile *>, 8> CommentsCursors;
2328 /// Loads comments ranges.
2329 void ReadComments() override;
2331 /// Visit all the input files of the given module file.
2332 void visitInputFiles(serialization::ModuleFile &MF,
2333 bool IncludeSystem, bool Complain,
2334 llvm::function_ref<void(const serialization::InputFile &IF,
2335 bool isSystem)> Visitor);
2337 /// Visit all the top-level module maps loaded when building the given module
2339 void visitTopLevelModuleMaps(serialization::ModuleFile &MF,
2341 void(const FileEntry *)> Visitor);
2343 bool isProcessingUpdateRecords() { return ProcessingUpdateRecords; }
2346 /// An object for streaming information from a record.
2347 class ASTRecordReader {
2348 using ModuleFile = serialization::ModuleFile;
2353 ASTReader::RecordData Record;
2355 using RecordData = ASTReader::RecordData;
2356 using RecordDataImpl = ASTReader::RecordDataImpl;
2359 /// Construct an ASTRecordReader that uses the default encoding scheme.
2360 ASTRecordReader(ASTReader &Reader, ModuleFile &F) : Reader(&Reader), F(&F) {}
2362 /// Reads a record with id AbbrevID from Cursor, resetting the
2364 unsigned readRecord(llvm::BitstreamCursor &Cursor, unsigned AbbrevID);
2366 /// Is this a module file for a module (rather than a PCH or similar).
2367 bool isModule() const { return F->isModule(); }
2369 /// Retrieve the AST context that this AST reader supplements.
2370 ASTContext &getContext() { return Reader->getContext(); }
2372 /// The current position in this record.
2373 unsigned getIdx() const { return Idx; }
2375 /// The length of this record.
2376 size_t size() const { return Record.size(); }
2378 /// An arbitrary index in this record.
2379 const uint64_t &operator[](size_t N) { return Record[N]; }
2381 /// The last element in this record.
2382 const uint64_t &back() const { return Record.back(); }
2384 /// Returns the current value in this record, and advances to the
2386 const uint64_t &readInt() { return Record[Idx++]; }
2388 /// Returns the current value in this record, without advancing.
2389 const uint64_t &peekInt() { return Record[Idx]; }
2391 /// Skips the specified number of values.
2392 void skipInts(unsigned N) { Idx += N; }
2394 /// Retrieve the global submodule ID its local ID number.
2395 serialization::SubmoduleID
2396 getGlobalSubmoduleID(unsigned LocalID) {
2397 return Reader->getGlobalSubmoduleID(*F, LocalID);
2400 /// Retrieve the submodule that corresponds to a global submodule ID.
2401 Module *getSubmodule(serialization::SubmoduleID GlobalID) {
2402 return Reader->getSubmodule(GlobalID);
2405 /// Read the record that describes the lexical contents of a DC.
2406 bool readLexicalDeclContextStorage(uint64_t Offset, DeclContext *DC) {
2407 return Reader->ReadLexicalDeclContextStorage(*F, F->DeclsCursor, Offset,
2411 /// Read the record that describes the visible contents of a DC.
2412 bool readVisibleDeclContextStorage(uint64_t Offset,
2413 serialization::DeclID ID) {
2414 return Reader->ReadVisibleDeclContextStorage(*F, F->DeclsCursor, Offset,
2418 void readExceptionSpec(SmallVectorImpl<QualType> &ExceptionStorage,
2419 FunctionProtoType::ExceptionSpecInfo &ESI) {
2420 return Reader->readExceptionSpec(*F, ExceptionStorage, ESI, Record, Idx);
2423 /// Get the global offset corresponding to a local offset.
2424 uint64_t getGlobalBitOffset(uint32_t LocalOffset) {
2425 return Reader->getGlobalBitOffset(*F, LocalOffset);
2428 /// Reads a statement.
2429 Stmt *readStmt() { return Reader->ReadStmt(*F); }
2431 /// Reads an expression.
2432 Expr *readExpr() { return Reader->ReadExpr(*F); }
2434 /// Reads a sub-statement operand during statement reading.
2435 Stmt *readSubStmt() { return Reader->ReadSubStmt(); }
2437 /// Reads a sub-expression operand during statement reading.
2438 Expr *readSubExpr() { return Reader->ReadSubExpr(); }
2440 /// Reads a declaration with the given local ID in the given module.
2442 /// \returns The requested declaration, casted to the given return type.
2443 template<typename T>
2444 T *GetLocalDeclAs(uint32_t LocalID) {
2445 return cast_or_null<T>(Reader->GetLocalDecl(*F, LocalID));
2448 /// Reads a TemplateArgumentLocInfo appropriate for the
2449 /// given TemplateArgument kind, advancing Idx.
2450 TemplateArgumentLocInfo
2451 getTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
2452 return Reader->GetTemplateArgumentLocInfo(*F, Kind, Record, Idx);
2455 /// Reads a TemplateArgumentLoc, advancing Idx.
2457 readTemplateArgumentLoc() {
2458 return Reader->ReadTemplateArgumentLoc(*F, Record, Idx);
2461 const ASTTemplateArgumentListInfo*
2462 readASTTemplateArgumentListInfo() {
2463 return Reader->ReadASTTemplateArgumentListInfo(*F, Record, Idx);
2466 /// Reads a declarator info from the given record, advancing Idx.
2467 TypeSourceInfo *getTypeSourceInfo() {
2468 return Reader->GetTypeSourceInfo(*F, Record, Idx);
2471 /// Reads the location information for a type.
2472 void readTypeLoc(TypeLoc TL) {
2473 return Reader->ReadTypeLoc(*F, Record, Idx, TL);
2476 /// Map a local type ID within a given AST file to a global type ID.
2477 serialization::TypeID getGlobalTypeID(unsigned LocalID) const {
2478 return Reader->getGlobalTypeID(*F, LocalID);
2481 /// Read a type from the current position in the record.
2482 QualType readType() {
2483 return Reader->readType(*F, Record, Idx);
2486 /// Reads a declaration ID from the given position in this record.
2488 /// \returns The declaration ID read from the record, adjusted to a global ID.
2489 serialization::DeclID readDeclID() {
2490 return Reader->ReadDeclID(*F, Record, Idx);
2493 /// Reads a declaration from the given position in a record in the
2494 /// given module, advancing Idx.
2496 return Reader->ReadDecl(*F, Record, Idx);
2499 /// Reads a declaration from the given position in the record,
2502 /// \returns The declaration read from this location, casted to the given
2504 template<typename T>
2506 return Reader->ReadDeclAs<T>(*F, Record, Idx);
2509 IdentifierInfo *getIdentifierInfo() {
2510 return Reader->GetIdentifierInfo(*F, Record, Idx);
2513 /// Read a selector from the Record, advancing Idx.
2514 Selector readSelector() {
2515 return Reader->ReadSelector(*F, Record, Idx);
2518 /// Read a declaration name, advancing Idx.
2519 DeclarationName readDeclarationName() {
2520 return Reader->ReadDeclarationName(*F, Record, Idx);
2522 void readDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name) {
2523 return Reader->ReadDeclarationNameLoc(*F, DNLoc, Name, Record, Idx);
2525 void readDeclarationNameInfo(DeclarationNameInfo &NameInfo) {
2526 return Reader->ReadDeclarationNameInfo(*F, NameInfo, Record, Idx);
2529 void readQualifierInfo(QualifierInfo &Info) {
2530 return Reader->ReadQualifierInfo(*F, Info, Record, Idx);
2533 NestedNameSpecifier *readNestedNameSpecifier() {
2534 return Reader->ReadNestedNameSpecifier(*F, Record, Idx);
2537 NestedNameSpecifierLoc readNestedNameSpecifierLoc() {
2538 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
2541 /// Read a template name, advancing Idx.
2542 TemplateName readTemplateName() {
2543 return Reader->ReadTemplateName(*F, Record, Idx);
2546 /// Read a template argument, advancing Idx.
2547 TemplateArgument readTemplateArgument(bool Canonicalize = false) {
2548 return Reader->ReadTemplateArgument(*F, Record, Idx, Canonicalize);
2551 /// Read a template parameter list, advancing Idx.
2552 TemplateParameterList *readTemplateParameterList() {
2553 return Reader->ReadTemplateParameterList(*F, Record, Idx);
2556 /// Read a template argument array, advancing Idx.
2557 void readTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
2558 bool Canonicalize = false) {
2559 return Reader->ReadTemplateArgumentList(TemplArgs, *F, Record, Idx,
2563 /// Read a UnresolvedSet structure, advancing Idx.
2564 void readUnresolvedSet(LazyASTUnresolvedSet &Set) {
2565 return Reader->ReadUnresolvedSet(*F, Set, Record, Idx);
2568 /// Read a C++ base specifier, advancing Idx.
2569 CXXBaseSpecifier readCXXBaseSpecifier() {
2570 return Reader->ReadCXXBaseSpecifier(*F, Record, Idx);
2573 /// Read a CXXCtorInitializer array, advancing Idx.
2574 CXXCtorInitializer **readCXXCtorInitializers() {
2575 return Reader->ReadCXXCtorInitializers(*F, Record, Idx);
2578 CXXTemporary *readCXXTemporary() {
2579 return Reader->ReadCXXTemporary(*F, Record, Idx);
2582 /// Read a source location, advancing Idx.
2583 SourceLocation readSourceLocation() {
2584 return Reader->ReadSourceLocation(*F, Record, Idx);
2587 /// Read a source range, advancing Idx.
2588 SourceRange readSourceRange() {
2589 return Reader->ReadSourceRange(*F, Record, Idx);
2592 /// Read an integral value, advancing Idx.
2593 llvm::APInt readAPInt() {
2594 return Reader->ReadAPInt(Record, Idx);
2597 /// Read a signed integral value, advancing Idx.
2598 llvm::APSInt readAPSInt() {
2599 return Reader->ReadAPSInt(Record, Idx);
2602 /// Read a floating-point value, advancing Idx.
2603 llvm::APFloat readAPFloat(const llvm::fltSemantics &Sem) {
2604 return Reader->ReadAPFloat(Record, Sem,Idx);
2607 /// Read a string, advancing Idx.
2608 std::string readString() {
2609 return Reader->ReadString(Record, Idx);
2612 /// Read a path, advancing Idx.
2613 std::string readPath() {
2614 return Reader->ReadPath(*F, Record, Idx);
2617 /// Read a version tuple, advancing Idx.
2618 VersionTuple readVersionTuple() {
2619 return ASTReader::ReadVersionTuple(Record, Idx);
2622 /// Reads attributes from the current stream position, advancing Idx.
2623 void readAttributes(AttrVec &Attrs) {
2624 return Reader->ReadAttributes(*this, Attrs);
2627 /// Reads a token out of a record, advancing Idx.
2629 return Reader->ReadToken(*F, Record, Idx);
2632 void recordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2633 Reader->RecordSwitchCaseID(SC, ID);
2636 /// Retrieve the switch-case statement with the given ID.
2637 SwitchCase *getSwitchCaseWithID(unsigned ID) {
2638 return Reader->getSwitchCaseWithID(ID);
2642 /// Helper class that saves the current stream position and
2643 /// then restores it when destroyed.
2644 struct SavedStreamPosition {
2645 explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor)
2646 : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) {}
2648 ~SavedStreamPosition() {
2649 Cursor.JumpToBit(Offset);
2653 llvm::BitstreamCursor &Cursor;
2657 inline void PCHValidator::Error(const char *Msg) {
2661 } // namespace clang
2663 #endif // LLVM_CLANG_SERIALIZATION_ASTREADER_H