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/DeclObjC.h"
18 #include "clang/AST/DeclarationName.h"
19 #include "clang/AST/TemplateBase.h"
20 #include "clang/AST/TemplateName.h"
21 #include "clang/AST/Type.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/FileSystemOptions.h"
25 #include "clang/Basic/IdentifierTable.h"
26 #include "clang/Basic/Module.h"
27 #include "clang/Basic/OpenCLOptions.h"
28 #include "clang/Basic/SourceLocation.h"
29 #include "clang/Basic/Version.h"
30 #include "clang/Basic/VersionTuple.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"
79 class ASTDeserializationListener;
81 class ASTRecordReader;
82 class CXXBaseSpecifier;
83 class CXXConstructorDecl;
84 class CXXCtorInitializer;
94 class FileSystemOptions;
96 class GlobalModuleIndex;
97 struct HeaderFileInfo;
98 class HeaderSearchOptions;
100 class LazyASTUnresolvedSet;
102 class MemoryBufferCache;
105 class NestedNameSpecifier;
106 class ObjCCategoryDecl;
107 class ObjCInterfaceDecl;
108 class PCHContainerReader;
110 class PreprocessorOptions;
111 struct QualifierInfo;
117 class TemplateParameterList;
118 class TypedefNameDecl;
119 class TypeSourceInfo;
123 /// \brief Abstract interface for callback invocations by the ASTReader.
125 /// While reading an AST file, the ASTReader will call the methods of the
126 /// listener to pass on specific information. Some of the listener methods can
127 /// return true to indicate to the ASTReader that the information (and
128 /// consequently the AST file) is invalid.
129 class ASTReaderListener {
131 virtual ~ASTReaderListener();
133 /// \brief Receives the full Clang version information.
135 /// \returns true to indicate that the version is invalid. Subclasses should
136 /// generally defer to this implementation.
137 virtual bool ReadFullVersionInformation(StringRef FullVersion) {
138 return FullVersion != getClangFullRepositoryVersion();
141 virtual void ReadModuleName(StringRef ModuleName) {}
142 virtual void ReadModuleMapFile(StringRef ModuleMapPath) {}
144 /// \brief Receives the language options.
146 /// \returns true to indicate the options are invalid or false otherwise.
147 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
149 bool AllowCompatibleDifferences) {
153 /// \brief Receives the target options.
155 /// \returns true to indicate the target options are invalid, or false
157 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
158 bool AllowCompatibleDifferences) {
162 /// \brief Receives the diagnostic options.
164 /// \returns true to indicate the diagnostic options are invalid, or false
167 ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
172 /// \brief Receives the file system options.
174 /// \returns true to indicate the file system options are invalid, or false
176 virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
181 /// \brief Receives the header search options.
183 /// \returns true to indicate the header search options are invalid, or false
185 virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
186 StringRef SpecificModuleCachePath,
191 /// \brief Receives the preprocessor options.
193 /// \param SuggestedPredefines Can be filled in with the set of predefines
194 /// that are suggested by the preprocessor options. Typically only used when
195 /// loading a precompiled header.
197 /// \returns true to indicate the preprocessor options are invalid, or false
199 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
201 std::string &SuggestedPredefines) {
205 /// \brief Receives __COUNTER__ value.
206 virtual void ReadCounter(const serialization::ModuleFile &M,
209 /// This is called for each AST file loaded.
210 virtual void visitModuleFile(StringRef Filename,
211 serialization::ModuleKind Kind) {}
213 /// \brief Returns true if this \c ASTReaderListener wants to receive the
214 /// input files of the AST file via \c visitInputFile, false otherwise.
215 virtual bool needsInputFileVisitation() { return false; }
217 /// \brief Returns true if this \c ASTReaderListener wants to receive the
218 /// system input files of the AST file via \c visitInputFile, false otherwise.
219 virtual bool needsSystemInputFileVisitation() { return false; }
221 /// \brief if \c needsInputFileVisitation returns true, this is called for
222 /// each non-system input file of the AST File. If
223 /// \c needsSystemInputFileVisitation is true, then it is called for all
224 /// system input files as well.
226 /// \returns true to continue receiving the next input file, false to stop.
227 virtual bool visitInputFile(StringRef Filename, bool isSystem,
228 bool isOverridden, bool isExplicitModule) {
232 /// \brief Returns true if this \c ASTReaderListener wants to receive the
233 /// imports of the AST file via \c visitImport, false otherwise.
234 virtual bool needsImportVisitation() const { return false; }
236 /// \brief If needsImportVisitation returns \c true, this is called for each
237 /// AST file imported by this AST file.
238 virtual void visitImport(StringRef Filename) {}
240 /// Indicates that a particular module file extension has been read.
241 virtual void readModuleFileExtension(
242 const ModuleFileExtensionMetadata &Metadata) {}
245 /// \brief Simple wrapper class for chaining listeners.
246 class ChainedASTReaderListener : public ASTReaderListener {
247 std::unique_ptr<ASTReaderListener> First;
248 std::unique_ptr<ASTReaderListener> Second;
251 /// Takes ownership of \p First and \p Second.
252 ChainedASTReaderListener(std::unique_ptr<ASTReaderListener> First,
253 std::unique_ptr<ASTReaderListener> Second)
254 : First(std::move(First)), Second(std::move(Second)) {}
256 std::unique_ptr<ASTReaderListener> takeFirst() { return std::move(First); }
257 std::unique_ptr<ASTReaderListener> takeSecond() { return std::move(Second); }
259 bool ReadFullVersionInformation(StringRef FullVersion) override;
260 void ReadModuleName(StringRef ModuleName) override;
261 void ReadModuleMapFile(StringRef ModuleMapPath) override;
262 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
263 bool AllowCompatibleDifferences) override;
264 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
265 bool AllowCompatibleDifferences) override;
266 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
267 bool Complain) override;
268 bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
269 bool Complain) override;
271 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
272 StringRef SpecificModuleCachePath,
273 bool Complain) override;
274 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
276 std::string &SuggestedPredefines) override;
278 void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
279 bool needsInputFileVisitation() override;
280 bool needsSystemInputFileVisitation() override;
281 void visitModuleFile(StringRef Filename,
282 serialization::ModuleKind Kind) override;
283 bool visitInputFile(StringRef Filename, bool isSystem,
284 bool isOverridden, bool isExplicitModule) override;
285 void readModuleFileExtension(
286 const ModuleFileExtensionMetadata &Metadata) override;
289 /// \brief ASTReaderListener implementation to validate the information of
290 /// the PCH file against an initialized Preprocessor.
291 class PCHValidator : public ASTReaderListener {
296 PCHValidator(Preprocessor &PP, ASTReader &Reader)
297 : PP(PP), Reader(Reader) {}
299 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
300 bool AllowCompatibleDifferences) override;
301 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
302 bool AllowCompatibleDifferences) override;
303 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
304 bool Complain) override;
305 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
306 std::string &SuggestedPredefines) override;
307 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
308 StringRef SpecificModuleCachePath,
309 bool Complain) override;
310 void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
313 void Error(const char *Msg);
316 /// \brief ASTReaderListenter implementation to set SuggestedPredefines of
317 /// ASTReader which is required to use a pch file. This is the replacement
318 /// of PCHValidator or SimplePCHValidator when using a pch file without
320 class SimpleASTReaderListener : public ASTReaderListener {
324 SimpleASTReaderListener(Preprocessor &PP)
327 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
328 std::string &SuggestedPredefines) override;
331 namespace serialization {
333 class ReadMethodPoolVisitor;
337 class ASTIdentifierLookupTrait;
339 /// \brief The on-disk hash table(s) used for DeclContext name lookup.
340 struct DeclContextLookupTable;
342 } // namespace reader
344 } // namespace serialization
346 /// \brief Reads an AST files chain containing the contents of a translation
349 /// The ASTReader class reads bitstreams (produced by the ASTWriter
350 /// class) containing the serialized representation of a given
351 /// abstract syntax tree and its supporting data structures. An
352 /// instance of the ASTReader can be attached to an ASTContext object,
353 /// which will provide access to the contents of the AST files.
355 /// The AST reader provides lazy de-serialization of declarations, as
356 /// required when traversing the AST. Only those AST nodes that are
357 /// actually required will be de-serialized.
359 : public ExternalPreprocessorSource,
360 public ExternalPreprocessingRecordSource,
361 public ExternalHeaderFileInfoSource,
362 public ExternalSemaSource,
363 public IdentifierInfoLookup,
364 public ExternalSLocEntrySource
367 /// \brief Types of AST files.
368 friend class ASTDeclReader;
369 friend class ASTIdentifierIterator;
370 friend class ASTRecordReader;
371 friend class ASTStmtReader;
372 friend class ASTUnit; // ASTUnit needs to remap source locations.
373 friend class ASTWriter;
374 friend class PCHValidator;
375 friend class serialization::reader::ASTIdentifierLookupTrait;
376 friend class serialization::ReadMethodPoolVisitor;
377 friend class TypeLocReader;
379 using RecordData = SmallVector<uint64_t, 64>;
380 using RecordDataImpl = SmallVectorImpl<uint64_t>;
382 /// \brief The result of reading the control block of an AST file, which
383 /// can fail for various reasons.
385 /// \brief The control block was read successfully. Aside from failures,
386 /// the AST file is safe to read into the current context.
389 /// \brief The AST file itself appears corrupted.
392 /// \brief The AST file was missing.
395 /// \brief The AST file is out-of-date relative to its input files,
396 /// and needs to be regenerated.
399 /// \brief The AST file was written by a different version of Clang.
402 /// \brief The AST file was writtten with a different language/target
404 ConfigurationMismatch,
406 /// \brief The AST file has errors.
410 using ModuleFile = serialization::ModuleFile;
411 using ModuleKind = serialization::ModuleKind;
412 using ModuleManager = serialization::ModuleManager;
413 using ModuleIterator = ModuleManager::ModuleIterator;
414 using ModuleConstIterator = ModuleManager::ModuleConstIterator;
415 using ModuleReverseIterator = ModuleManager::ModuleReverseIterator;
418 /// \brief The receiver of some callbacks invoked by ASTReader.
419 std::unique_ptr<ASTReaderListener> Listener;
421 /// \brief The receiver of deserialization events.
422 ASTDeserializationListener *DeserializationListener = nullptr;
424 bool OwnsDeserializationListener = false;
426 SourceManager &SourceMgr;
427 FileManager &FileMgr;
428 const PCHContainerReader &PCHContainerRdr;
429 DiagnosticsEngine &Diags;
431 /// \brief The semantic analysis object that will be processing the
432 /// AST files and the translation unit that uses it.
433 Sema *SemaObj = nullptr;
435 /// \brief The preprocessor that will be loading the source file.
438 /// \brief The AST context into which we'll read the AST files.
439 ASTContext *ContextObj = nullptr;
441 /// \brief The AST consumer.
442 ASTConsumer *Consumer = nullptr;
444 /// \brief The module manager which manages modules and their dependencies
445 ModuleManager ModuleMgr;
447 /// The cache that manages memory buffers for PCM files.
448 MemoryBufferCache &PCMCache;
450 /// \brief A dummy identifier resolver used to merge TU-scope declarations in
451 /// C, for the cases where we don't have a Sema object to provide a real
452 /// identifier resolver.
453 IdentifierResolver DummyIdResolver;
455 /// A mapping from extension block names to module file extensions.
456 llvm::StringMap<std::shared_ptr<ModuleFileExtension>> ModuleFileExtensions;
458 /// \brief A timer used to track the time spent deserializing.
459 std::unique_ptr<llvm::Timer> ReadTimer;
461 /// \brief The location where the module file will be considered as
462 /// imported from. For non-module AST types it should be invalid.
463 SourceLocation CurrentImportLoc;
465 /// \brief The global module index, if loaded.
466 std::unique_ptr<GlobalModuleIndex> GlobalIndex;
468 /// \brief A map of global bit offsets to the module that stores entities
469 /// at those bit offsets.
470 ContinuousRangeMap<uint64_t, ModuleFile*, 4> GlobalBitOffsetsMap;
472 /// \brief A map of negated SLocEntryIDs to the modules containing them.
473 ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocEntryMap;
475 using GlobalSLocOffsetMapType =
476 ContinuousRangeMap<unsigned, ModuleFile *, 64>;
478 /// \brief A map of reversed (SourceManager::MaxLoadedOffset - SLocOffset)
479 /// SourceLocation offsets to the modules containing them.
480 GlobalSLocOffsetMapType GlobalSLocOffsetMap;
482 /// \brief Types that have already been loaded from the chain.
484 /// When the pointer at index I is non-NULL, the type with
485 /// ID = (I + 1) << FastQual::Width has already been loaded
486 std::vector<QualType> TypesLoaded;
488 using GlobalTypeMapType =
489 ContinuousRangeMap<serialization::TypeID, ModuleFile *, 4>;
491 /// \brief Mapping from global type IDs to the module in which the
492 /// type resides along with the offset that should be added to the
493 /// global type ID to produce a local ID.
494 GlobalTypeMapType GlobalTypeMap;
496 /// \brief Declarations that have already been loaded from the chain.
498 /// When the pointer at index I is non-NULL, the declaration with ID
499 /// = I + 1 has already been loaded.
500 std::vector<Decl *> DeclsLoaded;
502 using GlobalDeclMapType =
503 ContinuousRangeMap<serialization::DeclID, ModuleFile *, 4>;
505 /// \brief Mapping from global declaration IDs to the module in which the
506 /// declaration resides.
507 GlobalDeclMapType GlobalDeclMap;
509 using FileOffset = std::pair<ModuleFile *, uint64_t>;
510 using FileOffsetsTy = SmallVector<FileOffset, 2>;
511 using DeclUpdateOffsetsMap =
512 llvm::DenseMap<serialization::DeclID, FileOffsetsTy>;
514 /// \brief Declarations that have modifications residing in a later file
516 DeclUpdateOffsetsMap DeclUpdateOffsets;
518 struct PendingUpdateRecord {
520 serialization::GlobalDeclID ID;
522 // Whether the declaration was just deserialized.
525 PendingUpdateRecord(serialization::GlobalDeclID ID, Decl *D,
527 : D(D), ID(ID), JustLoaded(JustLoaded) {}
530 /// \brief Declaration updates for already-loaded declarations that we need
531 /// to apply once we finish processing an import.
532 llvm::SmallVector<PendingUpdateRecord, 16> PendingUpdateRecords;
534 enum class PendingFakeDefinitionKind { NotFake, Fake, FakeLoaded };
536 /// \brief The DefinitionData pointers that we faked up for class definitions
537 /// that we needed but hadn't loaded yet.
538 llvm::DenseMap<void *, PendingFakeDefinitionKind> PendingFakeDefinitionData;
540 /// \brief Exception specification updates that have been loaded but not yet
541 /// propagated across the relevant redeclaration chain. The map key is the
542 /// canonical declaration (used only for deduplication) and the value is a
543 /// declaration that has an exception specification.
544 llvm::SmallMapVector<Decl *, FunctionDecl *, 4> PendingExceptionSpecUpdates;
546 /// \brief Declarations that have been imported and have typedef names for
547 /// linkage purposes.
548 llvm::DenseMap<std::pair<DeclContext *, IdentifierInfo *>, NamedDecl *>
549 ImportedTypedefNamesForLinkage;
551 /// \brief Mergeable declaration contexts that have anonymous declarations
552 /// within them, and those anonymous declarations.
553 llvm::DenseMap<DeclContext*, llvm::SmallVector<NamedDecl*, 2>>
554 AnonymousDeclarationsForMerging;
556 struct FileDeclsInfo {
557 ModuleFile *Mod = nullptr;
558 ArrayRef<serialization::LocalDeclID> Decls;
560 FileDeclsInfo() = default;
561 FileDeclsInfo(ModuleFile *Mod, ArrayRef<serialization::LocalDeclID> Decls)
562 : Mod(Mod), Decls(Decls) {}
565 /// \brief Map from a FileID to the file-level declarations that it contains.
566 llvm::DenseMap<FileID, FileDeclsInfo> FileDeclIDs;
568 /// \brief An array of lexical contents of a declaration context, as a sequence of
569 /// Decl::Kind, DeclID pairs.
570 using LexicalContents = ArrayRef<llvm::support::unaligned_uint32_t>;
572 /// \brief Map from a DeclContext to its lexical contents.
573 llvm::DenseMap<const DeclContext*, std::pair<ModuleFile*, LexicalContents>>
576 /// \brief Map from the TU to its lexical contents from each module file.
577 std::vector<std::pair<ModuleFile*, LexicalContents>> TULexicalDecls;
579 /// \brief Map from a DeclContext to its lookup tables.
580 llvm::DenseMap<const DeclContext *,
581 serialization::reader::DeclContextLookupTable> Lookups;
583 // Updates for visible decls can occur for other contexts than just the
584 // TU, and when we read those update records, the actual context may not
585 // be available yet, so have this pending map using the ID as a key. It
586 // will be realized when the context is actually loaded.
587 struct PendingVisibleUpdate {
589 const unsigned char *Data;
591 using DeclContextVisibleUpdates = SmallVector<PendingVisibleUpdate, 1>;
593 /// \brief Updates to the visible declarations of declaration contexts that
594 /// haven't been loaded yet.
595 llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates>
596 PendingVisibleUpdates;
598 /// \brief The set of C++ or Objective-C classes that have forward
599 /// declarations that have not yet been linked to their definitions.
600 llvm::SmallPtrSet<Decl *, 4> PendingDefinitions;
602 using PendingBodiesMap =
603 llvm::MapVector<Decl *, uint64_t,
604 llvm::SmallDenseMap<Decl *, unsigned, 4>,
605 SmallVector<std::pair<Decl *, uint64_t>, 4>>;
607 /// \brief Functions or methods that have bodies that will be attached.
608 PendingBodiesMap PendingBodies;
610 /// \brief Definitions for which we have added merged definitions but not yet
611 /// performed deduplication.
612 llvm::SetVector<NamedDecl *> PendingMergedDefinitionsToDeduplicate;
614 /// \brief Read the record that describes the lexical contents of a DC.
615 bool ReadLexicalDeclContextStorage(ModuleFile &M,
616 llvm::BitstreamCursor &Cursor,
617 uint64_t Offset, DeclContext *DC);
619 /// \brief Read the record that describes the visible contents of a DC.
620 bool ReadVisibleDeclContextStorage(ModuleFile &M,
621 llvm::BitstreamCursor &Cursor,
622 uint64_t Offset, serialization::DeclID ID);
624 /// \brief A vector containing identifiers that have already been
627 /// If the pointer at index I is non-NULL, then it refers to the
628 /// IdentifierInfo for the identifier with ID=I+1 that has already
630 std::vector<IdentifierInfo *> IdentifiersLoaded;
632 using GlobalIdentifierMapType =
633 ContinuousRangeMap<serialization::IdentID, ModuleFile *, 4>;
635 /// \brief Mapping from global identifier IDs to the module in which the
636 /// identifier resides along with the offset that should be added to the
637 /// global identifier ID to produce a local ID.
638 GlobalIdentifierMapType GlobalIdentifierMap;
640 /// \brief A vector containing macros that have already been
643 /// If the pointer at index I is non-NULL, then it refers to the
644 /// MacroInfo for the identifier with ID=I+1 that has already
646 std::vector<MacroInfo *> MacrosLoaded;
648 using LoadedMacroInfo =
649 std::pair<IdentifierInfo *, serialization::SubmoduleID>;
651 /// \brief A set of #undef directives that we have loaded; used to
652 /// deduplicate the same #undef information coming from multiple module
654 llvm::DenseSet<LoadedMacroInfo> LoadedUndefs;
656 using GlobalMacroMapType =
657 ContinuousRangeMap<serialization::MacroID, ModuleFile *, 4>;
659 /// \brief Mapping from global macro IDs to the module in which the
660 /// macro resides along with the offset that should be added to the
661 /// global macro ID to produce a local ID.
662 GlobalMacroMapType GlobalMacroMap;
664 /// \brief A vector containing submodules that have already been loaded.
666 /// This vector is indexed by the Submodule ID (-1). NULL submodule entries
667 /// indicate that the particular submodule ID has not yet been loaded.
668 SmallVector<Module *, 2> SubmodulesLoaded;
670 using GlobalSubmoduleMapType =
671 ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4>;
673 /// \brief Mapping from global submodule IDs to the module file in which the
674 /// submodule resides along with the offset that should be added to the
675 /// global submodule ID to produce a local ID.
676 GlobalSubmoduleMapType GlobalSubmoduleMap;
678 /// \brief A set of hidden declarations.
679 using HiddenNames = SmallVector<Decl *, 2>;
680 using HiddenNamesMapType = llvm::DenseMap<Module *, HiddenNames>;
682 /// \brief A mapping from each of the hidden submodules to the deserialized
683 /// declarations in that submodule that could be made visible.
684 HiddenNamesMapType HiddenNamesMap;
686 /// \brief A module import, export, or conflict that hasn't yet been resolved.
687 struct UnresolvedModuleRef {
688 /// \brief The file in which this module resides.
691 /// \brief The module that is importing or exporting.
694 /// \brief The kind of module reference.
695 enum { Import, Export, Conflict } Kind;
697 /// \brief The local ID of the module that is being exported.
700 /// \brief Whether this is a wildcard export.
701 unsigned IsWildcard : 1;
703 /// \brief String data.
707 /// \brief The set of module imports and exports that still need to be
709 SmallVector<UnresolvedModuleRef, 2> UnresolvedModuleRefs;
711 /// \brief A vector containing selectors that have already been loaded.
713 /// This vector is indexed by the Selector ID (-1). NULL selector
714 /// entries indicate that the particular selector ID has not yet
716 SmallVector<Selector, 16> SelectorsLoaded;
718 using GlobalSelectorMapType =
719 ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4>;
721 /// \brief Mapping from global selector IDs to the module in which the
722 /// global selector ID to produce a local ID.
723 GlobalSelectorMapType GlobalSelectorMap;
725 /// \brief The generation number of the last time we loaded data from the
726 /// global method pool for this selector.
727 llvm::DenseMap<Selector, unsigned> SelectorGeneration;
729 /// Whether a selector is out of date. We mark a selector as out of date
730 /// if we load another module after the method pool entry was pulled in.
731 llvm::DenseMap<Selector, bool> SelectorOutOfDate;
733 struct PendingMacroInfo {
735 uint64_t MacroDirectivesOffset;
737 PendingMacroInfo(ModuleFile *M, uint64_t MacroDirectivesOffset)
738 : M(M), MacroDirectivesOffset(MacroDirectivesOffset) {}
741 using PendingMacroIDsMap =
742 llvm::MapVector<IdentifierInfo *, SmallVector<PendingMacroInfo, 2>>;
744 /// \brief Mapping from identifiers that have a macro history to the global
745 /// IDs have not yet been deserialized to the global IDs of those macros.
746 PendingMacroIDsMap PendingMacroIDs;
748 using GlobalPreprocessedEntityMapType =
749 ContinuousRangeMap<unsigned, ModuleFile *, 4>;
751 /// \brief Mapping from global preprocessing entity IDs to the module in
752 /// which the preprocessed entity resides along with the offset that should be
753 /// added to the global preprocessing entity ID to produce a local ID.
754 GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap;
756 /// \name CodeGen-relevant special data
757 /// \brief Fields containing data that is relevant to CodeGen.
760 /// \brief The IDs of all declarations that fulfill the criteria of
761 /// "interesting" decls.
763 /// This contains the data loaded from all EAGERLY_DESERIALIZED_DECLS blocks
764 /// in the chain. The referenced declarations are deserialized and passed to
765 /// the consumer eagerly.
766 SmallVector<uint64_t, 16> EagerlyDeserializedDecls;
768 /// \brief The IDs of all tentative definitions stored in the chain.
770 /// Sema keeps track of all tentative definitions in a TU because it has to
771 /// complete them and pass them on to CodeGen. Thus, tentative definitions in
772 /// the PCH chain must be eagerly deserialized.
773 SmallVector<uint64_t, 16> TentativeDefinitions;
775 /// \brief The IDs of all CXXRecordDecls stored in the chain whose VTables are
778 /// CodeGen has to emit VTables for these records, so they have to be eagerly
780 SmallVector<uint64_t, 64> VTableUses;
782 /// \brief A snapshot of the pending instantiations in the chain.
784 /// This record tracks the instantiations that Sema has to perform at the
785 /// end of the TU. It consists of a pair of values for every pending
786 /// instantiation where the first value is the ID of the decl and the second
787 /// is the instantiation location.
788 SmallVector<uint64_t, 64> PendingInstantiations;
792 /// \name DiagnosticsEngine-relevant special data
793 /// \brief Fields containing data that is used for generating diagnostics
796 /// \brief A snapshot of Sema's unused file-scoped variable tracking, for
797 /// generating warnings.
798 SmallVector<uint64_t, 16> UnusedFileScopedDecls;
800 /// \brief A list of all the delegating constructors we've seen, to diagnose
802 SmallVector<uint64_t, 4> DelegatingCtorDecls;
804 /// \brief Method selectors used in a @selector expression. Used for
805 /// implementation of -Wselector.
806 SmallVector<uint64_t, 64> ReferencedSelectorsData;
808 /// \brief A snapshot of Sema's weak undeclared identifier tracking, for
809 /// generating warnings.
810 SmallVector<uint64_t, 64> WeakUndeclaredIdentifiers;
812 /// \brief The IDs of type aliases for ext_vectors that exist in the chain.
814 /// Used by Sema for finding sugared names for ext_vectors in diagnostics.
815 SmallVector<uint64_t, 4> ExtVectorDecls;
819 /// \name Sema-relevant special data
820 /// \brief Fields containing data that is used for semantic analysis
823 /// \brief The IDs of all potentially unused typedef names in the chain.
825 /// Sema tracks these to emit warnings.
826 SmallVector<uint64_t, 16> UnusedLocalTypedefNameCandidates;
828 /// \brief Our current depth in #pragma cuda force_host_device begin/end
830 unsigned ForceCUDAHostDeviceDepth = 0;
832 /// \brief The IDs of the declarations Sema stores directly.
834 /// Sema tracks a few important decls, such as namespace std, directly.
835 SmallVector<uint64_t, 4> SemaDeclRefs;
837 /// \brief The IDs of the types ASTContext stores directly.
839 /// The AST context tracks a few important types, such as va_list, directly.
840 SmallVector<uint64_t, 16> SpecialTypes;
842 /// \brief The IDs of CUDA-specific declarations ASTContext stores directly.
844 /// The AST context tracks a few important decls, currently cudaConfigureCall,
846 SmallVector<uint64_t, 2> CUDASpecialDeclRefs;
848 /// \brief The floating point pragma option settings.
849 SmallVector<uint64_t, 1> FPPragmaOptions;
851 /// \brief The pragma clang optimize location (if the pragma state is "off").
852 SourceLocation OptimizeOffPragmaLocation;
854 /// \brief The PragmaMSStructKind pragma ms_struct state if set, or -1.
855 int PragmaMSStructState = -1;
857 /// \brief The PragmaMSPointersToMembersKind pragma pointers_to_members state.
858 int PragmaMSPointersToMembersState = -1;
859 SourceLocation PointersToMembersPragmaLocation;
861 /// \brief The pragma pack state.
862 Optional<unsigned> PragmaPackCurrentValue;
863 SourceLocation PragmaPackCurrentLocation;
864 struct PragmaPackStackEntry {
866 SourceLocation Location;
867 SourceLocation PushLocation;
870 llvm::SmallVector<PragmaPackStackEntry, 2> PragmaPackStack;
871 llvm::SmallVector<std::string, 2> PragmaPackStrings;
873 /// \brief The OpenCL extension settings.
874 OpenCLOptions OpenCLExtensions;
876 /// \brief Extensions required by an OpenCL type.
877 llvm::DenseMap<const Type *, std::set<std::string>> OpenCLTypeExtMap;
879 /// \brief Extensions required by an OpenCL declaration.
880 llvm::DenseMap<const Decl *, std::set<std::string>> OpenCLDeclExtMap;
882 /// \brief A list of the namespaces we've seen.
883 SmallVector<uint64_t, 4> KnownNamespaces;
885 /// \brief A list of undefined decls with internal linkage followed by the
886 /// SourceLocation of a matching ODR-use.
887 SmallVector<uint64_t, 8> UndefinedButUsed;
889 /// \brief Delete expressions to analyze at the end of translation unit.
890 SmallVector<uint64_t, 8> DelayedDeleteExprs;
892 // \brief A list of late parsed template function data.
893 SmallVector<uint64_t, 1> LateParsedTemplates;
896 struct ImportedSubmodule {
897 serialization::SubmoduleID ID;
898 SourceLocation ImportLoc;
900 ImportedSubmodule(serialization::SubmoduleID ID, SourceLocation ImportLoc)
901 : ID(ID), ImportLoc(ImportLoc) {}
905 /// \brief A list of modules that were imported by precompiled headers or
906 /// any other non-module AST file.
907 SmallVector<ImportedSubmodule, 2> ImportedModules;
910 /// \brief The system include root to be used when loading the
911 /// precompiled header.
912 std::string isysroot;
914 /// \brief Whether to disable the normal validation performed on precompiled
915 /// headers when they are loaded.
916 bool DisableValidation;
918 /// \brief Whether to accept an AST file with compiler errors.
919 bool AllowASTWithCompilerErrors;
921 /// \brief Whether to accept an AST file that has a different configuration
922 /// from the current compiler instance.
923 bool AllowConfigurationMismatch;
925 /// \brief Whether validate system input files.
926 bool ValidateSystemInputs;
928 /// \brief Whether we are allowed to use the global module index.
931 /// \brief Whether we have tried loading the global module index yet.
932 bool TriedLoadingGlobalIndex = false;
934 ///\brief Whether we are currently processing update records.
935 bool ProcessingUpdateRecords = false;
937 using SwitchCaseMapTy = llvm::DenseMap<unsigned, SwitchCase *>;
939 /// \brief Mapping from switch-case IDs in the chain to switch-case statements
941 /// Statements usually don't have IDs, but switch cases need them, so that the
942 /// switch statement can refer to them.
943 SwitchCaseMapTy SwitchCaseStmts;
945 SwitchCaseMapTy *CurrSwitchCaseStmts;
947 /// \brief The number of source location entries de-serialized from
949 unsigned NumSLocEntriesRead = 0;
951 /// \brief The number of source location entries in the chain.
952 unsigned TotalNumSLocEntries = 0;
954 /// \brief The number of statements (and expressions) de-serialized
956 unsigned NumStatementsRead = 0;
958 /// \brief The total number of statements (and expressions) stored
960 unsigned TotalNumStatements = 0;
962 /// \brief The number of macros de-serialized from the chain.
963 unsigned NumMacrosRead = 0;
965 /// \brief The total number of macros stored in the chain.
966 unsigned TotalNumMacros = 0;
968 /// \brief The number of lookups into identifier tables.
969 unsigned NumIdentifierLookups = 0;
971 /// \brief The number of lookups into identifier tables that succeed.
972 unsigned NumIdentifierLookupHits = 0;
974 /// \brief The number of selectors that have been read.
975 unsigned NumSelectorsRead = 0;
977 /// \brief The number of method pool entries that have been read.
978 unsigned NumMethodPoolEntriesRead = 0;
980 /// \brief The number of times we have looked up a selector in the method
982 unsigned NumMethodPoolLookups = 0;
984 /// \brief The number of times we have looked up a selector in the method
985 /// pool and found something.
986 unsigned NumMethodPoolHits = 0;
988 /// \brief The number of times we have looked up a selector in the method
989 /// pool within a specific module.
990 unsigned NumMethodPoolTableLookups = 0;
992 /// \brief The number of times we have looked up a selector in the method
993 /// pool within a specific module and found something.
994 unsigned NumMethodPoolTableHits = 0;
996 /// \brief The total number of method pool entries in the selector table.
997 unsigned TotalNumMethodPoolEntries = 0;
999 /// Number of lexical decl contexts read/total.
1000 unsigned NumLexicalDeclContextsRead = 0, TotalLexicalDeclContexts = 0;
1002 /// Number of visible decl contexts read/total.
1003 unsigned NumVisibleDeclContextsRead = 0, TotalVisibleDeclContexts = 0;
1005 /// Total size of modules, in bits, currently loaded
1006 uint64_t TotalModulesSizeInBits = 0;
1008 /// \brief Number of Decl/types that are currently deserializing.
1009 unsigned NumCurrentElementsDeserializing = 0;
1011 /// \brief Set true while we are in the process of passing deserialized
1012 /// "interesting" decls to consumer inside FinishedDeserializing().
1013 /// This is used as a guard to avoid recursively repeating the process of
1014 /// passing decls to consumer.
1015 bool PassingDeclsToConsumer = false;
1017 /// \brief The set of identifiers that were read while the AST reader was
1018 /// (recursively) loading declarations.
1020 /// The declarations on the identifier chain for these identifiers will be
1021 /// loaded once the recursive loading has completed.
1022 llvm::MapVector<IdentifierInfo *, SmallVector<uint32_t, 4>>
1023 PendingIdentifierInfos;
1025 /// \brief The set of lookup results that we have faked in order to support
1026 /// merging of partially deserialized decls but that we have not yet removed.
1027 llvm::SmallMapVector<IdentifierInfo *, SmallVector<NamedDecl*, 2>, 16>
1028 PendingFakeLookupResults;
1030 /// \brief The generation number of each identifier, which keeps track of
1031 /// the last time we loaded information about this identifier.
1032 llvm::DenseMap<IdentifierInfo *, unsigned> IdentifierGeneration;
1034 class InterestingDecl {
1036 bool DeclHasPendingBody;
1039 InterestingDecl(Decl *D, bool HasBody)
1040 : D(D), DeclHasPendingBody(HasBody) {}
1042 Decl *getDecl() { return D; }
1044 /// Whether the declaration has a pending body.
1045 bool hasPendingBody() { return DeclHasPendingBody; }
1048 /// \brief Contains declarations and definitions that could be
1049 /// "interesting" to the ASTConsumer, when we get that AST consumer.
1051 /// "Interesting" declarations are those that have data that may
1052 /// need to be emitted, such as inline function definitions or
1053 /// Objective-C protocols.
1054 std::deque<InterestingDecl> PotentiallyInterestingDecls;
1056 /// \brief The list of redeclaration chains that still need to be
1057 /// reconstructed, and the local offset to the corresponding list
1058 /// of redeclarations.
1059 SmallVector<std::pair<Decl *, uint64_t>, 16> PendingDeclChains;
1061 /// \brief The list of canonical declarations whose redeclaration chains
1062 /// need to be marked as incomplete once we're done deserializing things.
1063 SmallVector<Decl *, 16> PendingIncompleteDeclChains;
1065 /// \brief The Decl IDs for the Sema/Lexical DeclContext of a Decl that has
1066 /// been loaded but its DeclContext was not set yet.
1067 struct PendingDeclContextInfo {
1069 serialization::GlobalDeclID SemaDC;
1070 serialization::GlobalDeclID LexicalDC;
1073 /// \brief The set of Decls that have been loaded but their DeclContexts are
1076 /// The DeclContexts for these Decls will be set once recursive loading has
1078 std::deque<PendingDeclContextInfo> PendingDeclContextInfos;
1080 /// \brief The set of NamedDecls that have been loaded, but are members of a
1081 /// context that has been merged into another context where the corresponding
1082 /// declaration is either missing or has not yet been loaded.
1084 /// We will check whether the corresponding declaration is in fact missing
1085 /// once recursing loading has been completed.
1086 llvm::SmallVector<NamedDecl *, 16> PendingOdrMergeChecks;
1088 using DataPointers =
1089 std::pair<CXXRecordDecl *, struct CXXRecordDecl::DefinitionData *>;
1091 /// \brief Record definitions in which we found an ODR violation.
1092 llvm::SmallDenseMap<CXXRecordDecl *, llvm::SmallVector<DataPointers, 2>, 2>
1093 PendingOdrMergeFailures;
1095 /// \brief Function definitions in which we found an ODR violation.
1096 llvm::SmallDenseMap<FunctionDecl *, llvm::SmallVector<FunctionDecl *, 2>, 2>
1097 PendingFunctionOdrMergeFailures;
1099 /// \brief DeclContexts in which we have diagnosed an ODR violation.
1100 llvm::SmallPtrSet<DeclContext*, 2> DiagnosedOdrMergeFailures;
1102 /// \brief The set of Objective-C categories that have been deserialized
1103 /// since the last time the declaration chains were linked.
1104 llvm::SmallPtrSet<ObjCCategoryDecl *, 16> CategoriesDeserialized;
1106 /// \brief The set of Objective-C class definitions that have already been
1107 /// loaded, for which we will need to check for categories whenever a new
1108 /// module is loaded.
1109 SmallVector<ObjCInterfaceDecl *, 16> ObjCClassesLoaded;
1112 llvm::DenseMap<Decl *, SmallVector<serialization::DeclID, 2>>;
1114 /// \brief A mapping from canonical declarations to the set of global
1115 /// declaration IDs for key declaration that have been merged with that
1116 /// canonical declaration. A key declaration is a formerly-canonical
1117 /// declaration whose module did not import any other key declaration for that
1118 /// entity. These are the IDs that we use as keys when finding redecl chains.
1119 KeyDeclsMap KeyDecls;
1121 /// \brief A mapping from DeclContexts to the semantic DeclContext that we
1122 /// are treating as the definition of the entity. This is used, for instance,
1123 /// when merging implicit instantiations of class templates across modules.
1124 llvm::DenseMap<DeclContext *, DeclContext *> MergedDeclContexts;
1126 /// \brief A mapping from canonical declarations of enums to their canonical
1127 /// definitions. Only populated when using modules in C++.
1128 llvm::DenseMap<EnumDecl *, EnumDecl *> EnumDefinitions;
1130 /// \brief When reading a Stmt tree, Stmt operands are placed in this stack.
1131 SmallVector<Stmt *, 16> StmtStack;
1133 /// \brief What kind of records we are reading.
1135 Read_None, Read_Decl, Read_Type, Read_Stmt
1138 /// \brief What kind of records we are reading.
1139 ReadingKind ReadingKind = Read_None;
1141 /// \brief RAII object to change the reading kind.
1142 class ReadingKindTracker {
1144 enum ReadingKind PrevKind;
1147 ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
1148 : Reader(reader), PrevKind(Reader.ReadingKind) {
1149 Reader.ReadingKind = newKind;
1152 ReadingKindTracker(const ReadingKindTracker &) = delete;
1153 ReadingKindTracker &operator=(const ReadingKindTracker &) = delete;
1154 ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; }
1157 /// \brief RAII object to mark the start of processing updates.
1158 class ProcessingUpdatesRAIIObj {
1163 ProcessingUpdatesRAIIObj(ASTReader &reader)
1164 : Reader(reader), PrevState(Reader.ProcessingUpdateRecords) {
1165 Reader.ProcessingUpdateRecords = true;
1168 ProcessingUpdatesRAIIObj(const ProcessingUpdatesRAIIObj &) = delete;
1169 ProcessingUpdatesRAIIObj &
1170 operator=(const ProcessingUpdatesRAIIObj &) = delete;
1171 ~ProcessingUpdatesRAIIObj() { Reader.ProcessingUpdateRecords = PrevState; }
1174 /// \brief Suggested contents of the predefines buffer, after this
1175 /// PCH file has been processed.
1177 /// In most cases, this string will be empty, because the predefines
1178 /// buffer computed to build the PCH file will be identical to the
1179 /// predefines buffer computed from the command line. However, when
1180 /// there are differences that the PCH reader can work around, this
1181 /// predefines buffer may contain additional definitions.
1182 std::string SuggestedPredefines;
1184 llvm::DenseMap<const Decl *, bool> DefinitionSource;
1186 /// \brief Reads a statement from the specified cursor.
1187 Stmt *ReadStmtFromStream(ModuleFile &F);
1189 struct InputFileInfo {
1190 std::string Filename;
1195 bool TopLevelModuleMap;
1198 /// \brief Reads the stored information about an input file.
1199 InputFileInfo readInputFileInfo(ModuleFile &F, unsigned ID);
1201 /// \brief Retrieve the file entry and 'overridden' bit for an input
1202 /// file in the given module file.
1203 serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
1204 bool Complain = true);
1207 void ResolveImportedPath(ModuleFile &M, std::string &Filename);
1208 static void ResolveImportedPath(std::string &Filename, StringRef Prefix);
1210 /// \brief Returns the first key declaration for the given declaration. This
1211 /// is one that is formerly-canonical (or still canonical) and whose module
1212 /// did not import any other key declaration of the entity.
1213 Decl *getKeyDeclaration(Decl *D) {
1214 D = D->getCanonicalDecl();
1215 if (D->isFromASTFile())
1218 auto I = KeyDecls.find(D);
1219 if (I == KeyDecls.end() || I->second.empty())
1221 return GetExistingDecl(I->second[0]);
1223 const Decl *getKeyDeclaration(const Decl *D) {
1224 return getKeyDeclaration(const_cast<Decl*>(D));
1227 /// \brief Run a callback on each imported key declaration of \p D.
1228 template <typename Fn>
1229 void forEachImportedKeyDecl(const Decl *D, Fn Visit) {
1230 D = D->getCanonicalDecl();
1231 if (D->isFromASTFile())
1234 auto It = KeyDecls.find(const_cast<Decl*>(D));
1235 if (It != KeyDecls.end())
1236 for (auto ID : It->second)
1237 Visit(GetExistingDecl(ID));
1240 /// \brief Get the loaded lookup tables for \p Primary, if any.
1241 const serialization::reader::DeclContextLookupTable *
1242 getLoadedLookupTables(DeclContext *Primary) const;
1245 struct ImportedModule {
1247 ModuleFile *ImportedBy;
1248 SourceLocation ImportLoc;
1250 ImportedModule(ModuleFile *Mod,
1251 ModuleFile *ImportedBy,
1252 SourceLocation ImportLoc)
1253 : Mod(Mod), ImportedBy(ImportedBy), ImportLoc(ImportLoc) {}
1256 ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
1257 SourceLocation ImportLoc, ModuleFile *ImportedBy,
1258 SmallVectorImpl<ImportedModule> &Loaded,
1259 off_t ExpectedSize, time_t ExpectedModTime,
1260 ASTFileSignature ExpectedSignature,
1261 unsigned ClientLoadCapabilities);
1262 ASTReadResult ReadControlBlock(ModuleFile &F,
1263 SmallVectorImpl<ImportedModule> &Loaded,
1264 const ModuleFile *ImportedBy,
1265 unsigned ClientLoadCapabilities);
1266 static ASTReadResult ReadOptionsBlock(
1267 llvm::BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
1268 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
1269 std::string &SuggestedPredefines);
1271 /// Read the unhashed control block.
1273 /// This has no effect on \c F.Stream, instead creating a fresh cursor from
1274 /// \c F.Data and reading ahead.
1275 ASTReadResult readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
1276 unsigned ClientLoadCapabilities);
1278 static ASTReadResult
1279 readUnhashedControlBlockImpl(ModuleFile *F, llvm::StringRef StreamData,
1280 unsigned ClientLoadCapabilities,
1281 bool AllowCompatibleConfigurationMismatch,
1282 ASTReaderListener *Listener,
1283 bool ValidateDiagnosticOptions);
1285 ASTReadResult ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities);
1286 ASTReadResult ReadExtensionBlock(ModuleFile &F);
1287 void ReadModuleOffsetMap(ModuleFile &F) const;
1288 bool ParseLineTable(ModuleFile &F, const RecordData &Record);
1289 bool ReadSourceManagerBlock(ModuleFile &F);
1290 llvm::BitstreamCursor &SLocCursorForID(int ID);
1291 SourceLocation getImportLocation(ModuleFile *F);
1292 ASTReadResult ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
1293 const ModuleFile *ImportedBy,
1294 unsigned ClientLoadCapabilities);
1295 ASTReadResult ReadSubmoduleBlock(ModuleFile &F,
1296 unsigned ClientLoadCapabilities);
1297 static bool ParseLanguageOptions(const RecordData &Record, bool Complain,
1298 ASTReaderListener &Listener,
1299 bool AllowCompatibleDifferences);
1300 static bool ParseTargetOptions(const RecordData &Record, bool Complain,
1301 ASTReaderListener &Listener,
1302 bool AllowCompatibleDifferences);
1303 static bool ParseDiagnosticOptions(const RecordData &Record, bool Complain,
1304 ASTReaderListener &Listener);
1305 static bool ParseFileSystemOptions(const RecordData &Record, bool Complain,
1306 ASTReaderListener &Listener);
1307 static bool ParseHeaderSearchOptions(const RecordData &Record, bool Complain,
1308 ASTReaderListener &Listener);
1309 static bool ParsePreprocessorOptions(const RecordData &Record, bool Complain,
1310 ASTReaderListener &Listener,
1311 std::string &SuggestedPredefines);
1313 struct RecordLocation {
1317 RecordLocation(ModuleFile *M, uint64_t O)
1318 : F(M), Offset(O) {}
1321 QualType readTypeRecord(unsigned Index);
1322 void readExceptionSpec(ModuleFile &ModuleFile,
1323 SmallVectorImpl<QualType> &ExceptionStorage,
1324 FunctionProtoType::ExceptionSpecInfo &ESI,
1325 const RecordData &Record, unsigned &Index);
1326 RecordLocation TypeCursorForIndex(unsigned Index);
1327 void LoadedDecl(unsigned Index, Decl *D);
1328 Decl *ReadDeclRecord(serialization::DeclID ID);
1329 void markIncompleteDeclChain(Decl *Canon);
1331 /// \brief Returns the most recent declaration of a declaration (which must be
1332 /// of a redeclarable kind) that is either local or has already been loaded
1333 /// merged into its redecl chain.
1334 Decl *getMostRecentExistingDecl(Decl *D);
1336 RecordLocation DeclCursorForID(serialization::DeclID ID,
1337 SourceLocation &Location);
1338 void loadDeclUpdateRecords(PendingUpdateRecord &Record);
1339 void loadPendingDeclChain(Decl *D, uint64_t LocalOffset);
1340 void loadObjCCategories(serialization::GlobalDeclID ID, ObjCInterfaceDecl *D,
1341 unsigned PreviousGeneration = 0);
1343 RecordLocation getLocalBitOffset(uint64_t GlobalOffset);
1344 uint64_t getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset);
1346 /// \brief Returns the first preprocessed entity ID that begins or ends after
1348 serialization::PreprocessedEntityID
1349 findPreprocessedEntity(SourceLocation Loc, bool EndsAfter) const;
1351 /// \brief Find the next module that contains entities and return the ID
1352 /// of the first entry.
1354 /// \param SLocMapI points at a chunk of a module that contains no
1355 /// preprocessed entities or the entities it contains are not the
1356 /// ones we are looking for.
1357 serialization::PreprocessedEntityID
1358 findNextPreprocessedEntity(
1359 GlobalSLocOffsetMapType::const_iterator SLocMapI) const;
1361 /// \brief Returns (ModuleFile, Local index) pair for \p GlobalIndex of a
1362 /// preprocessed entity.
1363 std::pair<ModuleFile *, unsigned>
1364 getModulePreprocessedEntity(unsigned GlobalIndex);
1366 /// \brief Returns (begin, end) pair for the preprocessed entities of a
1367 /// particular module.
1368 llvm::iterator_range<PreprocessingRecord::iterator>
1369 getModulePreprocessedEntities(ModuleFile &Mod) const;
1372 class ModuleDeclIterator
1373 : public llvm::iterator_adaptor_base<
1374 ModuleDeclIterator, const serialization::LocalDeclID *,
1375 std::random_access_iterator_tag, const Decl *, ptrdiff_t,
1376 const Decl *, const Decl *> {
1377 ASTReader *Reader = nullptr;
1378 ModuleFile *Mod = nullptr;
1381 ModuleDeclIterator() : iterator_adaptor_base(nullptr) {}
1383 ModuleDeclIterator(ASTReader *Reader, ModuleFile *Mod,
1384 const serialization::LocalDeclID *Pos)
1385 : iterator_adaptor_base(Pos), Reader(Reader), Mod(Mod) {}
1387 value_type operator*() const {
1388 return Reader->GetDecl(Reader->getGlobalDeclID(*Mod, *I));
1391 value_type operator->() const { return **this; }
1393 bool operator==(const ModuleDeclIterator &RHS) const {
1394 assert(Reader == RHS.Reader && Mod == RHS.Mod);
1399 llvm::iterator_range<ModuleDeclIterator>
1400 getModuleFileLevelDecls(ModuleFile &Mod);
1403 void PassInterestingDeclsToConsumer();
1404 void PassInterestingDeclToConsumer(Decl *D);
1406 void finishPendingActions();
1407 void diagnoseOdrViolations();
1409 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
1411 void addPendingDeclContextInfo(Decl *D,
1412 serialization::GlobalDeclID SemaDC,
1413 serialization::GlobalDeclID LexicalDC) {
1415 PendingDeclContextInfo Info = { D, SemaDC, LexicalDC };
1416 PendingDeclContextInfos.push_back(Info);
1419 /// \brief Produce an error diagnostic and return true.
1421 /// This routine should only be used for fatal errors that have to
1422 /// do with non-routine failures (e.g., corrupted AST file).
1423 void Error(StringRef Msg) const;
1424 void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
1425 StringRef Arg2 = StringRef()) const;
1428 /// \brief Load the AST file and validate its contents against the given
1431 /// \param PP the preprocessor associated with the context in which this
1432 /// precompiled header will be loaded.
1434 /// \param Context the AST context that this precompiled header will be
1435 /// loaded into, if any.
1437 /// \param PCHContainerRdr the PCHContainerOperations to use for loading and
1438 /// creating modules.
1440 /// \param Extensions the list of module file extensions that can be loaded
1441 /// from the AST files.
1443 /// \param isysroot If non-NULL, the system include path specified by the
1444 /// user. This is only used with relocatable PCH files. If non-NULL,
1445 /// a relocatable PCH file will use the default path "/".
1447 /// \param DisableValidation If true, the AST reader will suppress most
1448 /// of its regular consistency checking, allowing the use of precompiled
1449 /// headers that cannot be determined to be compatible.
1451 /// \param AllowASTWithCompilerErrors If true, the AST reader will accept an
1452 /// AST file the was created out of an AST with compiler errors,
1453 /// otherwise it will reject it.
1455 /// \param AllowConfigurationMismatch If true, the AST reader will not check
1456 /// for configuration differences between the AST file and the invocation.
1458 /// \param ValidateSystemInputs If true, the AST reader will validate
1459 /// system input files in addition to user input files. This is only
1460 /// meaningful if \p DisableValidation is false.
1462 /// \param UseGlobalIndex If true, the AST reader will try to load and use
1463 /// the global module index.
1465 /// \param ReadTimer If non-null, a timer used to track the time spent
1467 ASTReader(Preprocessor &PP, ASTContext *Context,
1468 const PCHContainerReader &PCHContainerRdr,
1469 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
1470 StringRef isysroot = "", bool DisableValidation = false,
1471 bool AllowASTWithCompilerErrors = false,
1472 bool AllowConfigurationMismatch = false,
1473 bool ValidateSystemInputs = false, bool UseGlobalIndex = true,
1474 std::unique_ptr<llvm::Timer> ReadTimer = {});
1475 ASTReader(const ASTReader &) = delete;
1476 ASTReader &operator=(const ASTReader &) = delete;
1477 ~ASTReader() override;
1479 SourceManager &getSourceManager() const { return SourceMgr; }
1480 FileManager &getFileManager() const { return FileMgr; }
1481 DiagnosticsEngine &getDiags() const { return Diags; }
1483 /// \brief Flags that indicate what kind of AST loading failures the client
1484 /// of the AST reader can directly handle.
1486 /// When a client states that it can handle a particular kind of failure,
1487 /// the AST reader will not emit errors when producing that kind of failure.
1488 enum LoadFailureCapabilities {
1489 /// \brief The client can't handle any AST loading failures.
1492 /// \brief The client can handle an AST file that cannot load because it
1496 /// \brief The client can handle an AST file that cannot load because it
1497 /// is out-of-date relative to its input files.
1498 ARR_OutOfDate = 0x2,
1500 /// \brief The client can handle an AST file that cannot load because it
1501 /// was built with a different version of Clang.
1502 ARR_VersionMismatch = 0x4,
1504 /// \brief The client can handle an AST file that cannot load because it's
1505 /// compiled configuration doesn't match that of the context it was
1507 ARR_ConfigurationMismatch = 0x8
1510 /// \brief Load the AST file designated by the given file name.
1512 /// \param FileName The name of the AST file to load.
1514 /// \param Type The kind of AST being loaded, e.g., PCH, module, main file,
1517 /// \param ImportLoc the location where the module file will be considered as
1518 /// imported from. For non-module AST types it should be invalid.
1520 /// \param ClientLoadCapabilities The set of client load-failure
1521 /// capabilities, represented as a bitset of the enumerators of
1522 /// LoadFailureCapabilities.
1524 /// \param Imported optional out-parameter to append the list of modules
1525 /// that were imported by precompiled headers or any other non-module AST file
1526 ASTReadResult ReadAST(StringRef FileName, ModuleKind Type,
1527 SourceLocation ImportLoc,
1528 unsigned ClientLoadCapabilities,
1529 SmallVectorImpl<ImportedSubmodule> *Imported = nullptr);
1531 /// \brief Make the entities in the given module and any of its (non-explicit)
1532 /// submodules visible to name lookup.
1534 /// \param Mod The module whose names should be made visible.
1536 /// \param NameVisibility The level of visibility to give the names in the
1537 /// module. Visibility can only be increased over time.
1539 /// \param ImportLoc The location at which the import occurs.
1540 void makeModuleVisible(Module *Mod,
1541 Module::NameVisibilityKind NameVisibility,
1542 SourceLocation ImportLoc);
1544 /// \brief Make the names within this set of hidden names visible.
1545 void makeNamesVisible(const HiddenNames &Names, Module *Owner);
1547 /// \brief Note that MergedDef is a redefinition of the canonical definition
1548 /// Def, so Def should be visible whenever MergedDef is.
1549 void mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef);
1551 /// \brief Take the AST callbacks listener.
1552 std::unique_ptr<ASTReaderListener> takeListener() {
1553 return std::move(Listener);
1556 /// \brief Set the AST callbacks listener.
1557 void setListener(std::unique_ptr<ASTReaderListener> Listener) {
1558 this->Listener = std::move(Listener);
1561 /// \brief Add an AST callback listener.
1563 /// Takes ownership of \p L.
1564 void addListener(std::unique_ptr<ASTReaderListener> L) {
1566 L = llvm::make_unique<ChainedASTReaderListener>(std::move(L),
1567 std::move(Listener));
1568 Listener = std::move(L);
1571 /// RAII object to temporarily add an AST callback listener.
1572 class ListenerScope {
1574 bool Chained = false;
1577 ListenerScope(ASTReader &Reader, std::unique_ptr<ASTReaderListener> L)
1579 auto Old = Reader.takeListener();
1582 L = llvm::make_unique<ChainedASTReaderListener>(std::move(L),
1585 Reader.setListener(std::move(L));
1589 auto New = Reader.takeListener();
1591 Reader.setListener(static_cast<ChainedASTReaderListener *>(New.get())
1596 /// \brief Set the AST deserialization listener.
1597 void setDeserializationListener(ASTDeserializationListener *Listener,
1598 bool TakeOwnership = false);
1600 /// \brief Determine whether this AST reader has a global index.
1601 bool hasGlobalIndex() const { return (bool)GlobalIndex; }
1603 /// \brief Return global module index.
1604 GlobalModuleIndex *getGlobalIndex() { return GlobalIndex.get(); }
1606 /// \brief Reset reader for a reload try.
1607 void resetForReload() { TriedLoadingGlobalIndex = false; }
1609 /// \brief Attempts to load the global index.
1611 /// \returns true if loading the global index has failed for any reason.
1612 bool loadGlobalIndex();
1614 /// \brief Determine whether we tried to load the global index, but failed,
1615 /// e.g., because it is out-of-date or does not exist.
1616 bool isGlobalIndexUnavailable() const;
1618 /// \brief Initializes the ASTContext
1619 void InitializeContext();
1621 /// \brief Update the state of Sema after loading some additional modules.
1624 /// \brief Add in-memory (virtual file) buffer.
1625 void addInMemoryBuffer(StringRef &FileName,
1626 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
1627 ModuleMgr.addInMemoryBuffer(FileName, std::move(Buffer));
1630 /// \brief Finalizes the AST reader's state before writing an AST file to
1633 /// This operation may undo temporary state in the AST that should not be
1635 void finalizeForWriting();
1637 /// \brief Retrieve the module manager.
1638 ModuleManager &getModuleManager() { return ModuleMgr; }
1640 /// \brief Retrieve the preprocessor.
1641 Preprocessor &getPreprocessor() const { return PP; }
1643 /// \brief Retrieve the name of the original source file name for the primary
1645 StringRef getOriginalSourceFile() {
1646 return ModuleMgr.getPrimaryModule().OriginalSourceFileName;
1649 /// \brief Retrieve the name of the original source file name directly from
1650 /// the AST file, without actually loading the AST file.
1652 getOriginalSourceFile(const std::string &ASTFileName, FileManager &FileMgr,
1653 const PCHContainerReader &PCHContainerRdr,
1654 DiagnosticsEngine &Diags);
1656 /// \brief Read the control block for the named AST file.
1658 /// \returns true if an error occurred, false otherwise.
1660 readASTFileControlBlock(StringRef Filename, FileManager &FileMgr,
1661 const PCHContainerReader &PCHContainerRdr,
1662 bool FindModuleFileExtensions,
1663 ASTReaderListener &Listener,
1664 bool ValidateDiagnosticOptions);
1666 /// \brief Determine whether the given AST file is acceptable to load into a
1667 /// translation unit with the given language and target options.
1668 static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
1669 const PCHContainerReader &PCHContainerRdr,
1670 const LangOptions &LangOpts,
1671 const TargetOptions &TargetOpts,
1672 const PreprocessorOptions &PPOpts,
1673 StringRef ExistingModuleCachePath);
1675 /// \brief Returns the suggested contents of the predefines buffer,
1676 /// which contains a (typically-empty) subset of the predefines
1677 /// build prior to including the precompiled header.
1678 const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
1680 /// \brief Read a preallocated preprocessed entity from the external source.
1682 /// \returns null if an error occurred that prevented the preprocessed
1683 /// entity from being loaded.
1684 PreprocessedEntity *ReadPreprocessedEntity(unsigned Index) override;
1686 /// \brief Returns a pair of [Begin, End) indices of preallocated
1687 /// preprocessed entities that \p Range encompasses.
1688 std::pair<unsigned, unsigned>
1689 findPreprocessedEntitiesInRange(SourceRange Range) override;
1691 /// \brief Optionally returns true or false if the preallocated preprocessed
1692 /// entity with index \p Index came from file \p FID.
1693 Optional<bool> isPreprocessedEntityInFileID(unsigned Index,
1694 FileID FID) override;
1696 /// \brief Read the header file information for the given file entry.
1697 HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) override;
1699 void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag);
1701 /// \brief Returns the number of source locations found in the chain.
1702 unsigned getTotalNumSLocs() const {
1703 return TotalNumSLocEntries;
1706 /// \brief Returns the number of identifiers found in the chain.
1707 unsigned getTotalNumIdentifiers() const {
1708 return static_cast<unsigned>(IdentifiersLoaded.size());
1711 /// \brief Returns the number of macros found in the chain.
1712 unsigned getTotalNumMacros() const {
1713 return static_cast<unsigned>(MacrosLoaded.size());
1716 /// \brief Returns the number of types found in the chain.
1717 unsigned getTotalNumTypes() const {
1718 return static_cast<unsigned>(TypesLoaded.size());
1721 /// \brief Returns the number of declarations found in the chain.
1722 unsigned getTotalNumDecls() const {
1723 return static_cast<unsigned>(DeclsLoaded.size());
1726 /// \brief Returns the number of submodules known.
1727 unsigned getTotalNumSubmodules() const {
1728 return static_cast<unsigned>(SubmodulesLoaded.size());
1731 /// \brief Returns the number of selectors found in the chain.
1732 unsigned getTotalNumSelectors() const {
1733 return static_cast<unsigned>(SelectorsLoaded.size());
1736 /// \brief Returns the number of preprocessed entities known to the AST
1738 unsigned getTotalNumPreprocessedEntities() const {
1739 unsigned Result = 0;
1740 for (const auto &M : ModuleMgr)
1741 Result += M.NumPreprocessedEntities;
1745 /// \brief Reads a TemplateArgumentLocInfo appropriate for the
1746 /// given TemplateArgument kind.
1747 TemplateArgumentLocInfo
1748 GetTemplateArgumentLocInfo(ModuleFile &F, TemplateArgument::ArgKind Kind,
1749 const RecordData &Record, unsigned &Idx);
1751 /// \brief Reads a TemplateArgumentLoc.
1753 ReadTemplateArgumentLoc(ModuleFile &F,
1754 const RecordData &Record, unsigned &Idx);
1756 const ASTTemplateArgumentListInfo*
1757 ReadASTTemplateArgumentListInfo(ModuleFile &F,
1758 const RecordData &Record, unsigned &Index);
1760 /// \brief Reads a declarator info from the given record.
1761 TypeSourceInfo *GetTypeSourceInfo(ModuleFile &F,
1762 const RecordData &Record, unsigned &Idx);
1764 /// \brief Resolve a type ID into a type, potentially building a new
1766 QualType GetType(serialization::TypeID ID);
1768 /// \brief Resolve a local type ID within a given AST file into a type.
1769 QualType getLocalType(ModuleFile &F, unsigned LocalID);
1771 /// \brief Map a local type ID within a given AST file into a global type ID.
1772 serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const;
1774 /// \brief Read a type from the current position in the given record, which
1775 /// was read from the given AST file.
1776 QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) {
1777 if (Idx >= Record.size())
1780 return getLocalType(F, Record[Idx++]);
1783 /// \brief Map from a local declaration ID within a given module to a
1784 /// global declaration ID.
1785 serialization::DeclID getGlobalDeclID(ModuleFile &F,
1786 serialization::LocalDeclID LocalID) const;
1788 /// \brief Returns true if global DeclID \p ID originated from module \p M.
1789 bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const;
1791 /// \brief Retrieve the module file that owns the given declaration, or NULL
1792 /// if the declaration is not from a module file.
1793 ModuleFile *getOwningModuleFile(const Decl *D);
1795 /// \brief Get the best name we know for the module that owns the given
1796 /// declaration, or an empty string if the declaration is not from a module.
1797 std::string getOwningModuleNameForDiagnostic(const Decl *D);
1799 /// \brief Returns the source location for the decl \p ID.
1800 SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID);
1802 /// \brief Resolve a declaration ID into a declaration, potentially
1803 /// building a new declaration.
1804 Decl *GetDecl(serialization::DeclID ID);
1805 Decl *GetExternalDecl(uint32_t ID) override;
1807 /// \brief Resolve a declaration ID into a declaration. Return 0 if it's not
1808 /// been loaded yet.
1809 Decl *GetExistingDecl(serialization::DeclID ID);
1811 /// \brief Reads a declaration with the given local ID in the given module.
1812 Decl *GetLocalDecl(ModuleFile &F, uint32_t LocalID) {
1813 return GetDecl(getGlobalDeclID(F, LocalID));
1816 /// \brief Reads a declaration with the given local ID in the given module.
1818 /// \returns The requested declaration, casted to the given return type.
1819 template<typename T>
1820 T *GetLocalDeclAs(ModuleFile &F, uint32_t LocalID) {
1821 return cast_or_null<T>(GetLocalDecl(F, LocalID));
1824 /// \brief Map a global declaration ID into the declaration ID used to
1825 /// refer to this declaration within the given module fule.
1827 /// \returns the global ID of the given declaration as known in the given
1829 serialization::DeclID
1830 mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
1831 serialization::DeclID GlobalID);
1833 /// \brief Reads a declaration ID from the given position in a record in the
1836 /// \returns The declaration ID read from the record, adjusted to a global ID.
1837 serialization::DeclID ReadDeclID(ModuleFile &F, const RecordData &Record,
1840 /// \brief Reads a declaration from the given position in a record in the
1842 Decl *ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I) {
1843 return GetDecl(ReadDeclID(F, R, I));
1846 /// \brief Reads a declaration from the given position in a record in the
1849 /// \returns The declaration read from this location, casted to the given
1851 template<typename T>
1852 T *ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I) {
1853 return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
1856 /// \brief If any redeclarations of \p D have been imported since it was
1857 /// last checked, this digs out those redeclarations and adds them to the
1858 /// redeclaration chain for \p D.
1859 void CompleteRedeclChain(const Decl *D) override;
1861 CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override;
1863 /// \brief Resolve the offset of a statement into a statement.
1865 /// This operation will read a new statement from the external
1866 /// source each time it is called, and is meant to be used via a
1867 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1868 Stmt *GetExternalDeclStmt(uint64_t Offset) override;
1870 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1871 /// specified cursor. Read the abbreviations that are at the top of the block
1872 /// and then leave the cursor pointing into the block.
1873 static bool ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID);
1875 /// \brief Finds all the visible declarations with a given name.
1876 /// The current implementation of this method just loads the entire
1877 /// lookup table as unmaterialized references.
1878 bool FindExternalVisibleDeclsByName(const DeclContext *DC,
1879 DeclarationName Name) override;
1881 /// \brief Read all of the declarations lexically stored in a
1882 /// declaration context.
1884 /// \param DC The declaration context whose declarations will be
1887 /// \param IsKindWeWant A predicate indicating which declaration kinds
1888 /// we are interested in.
1890 /// \param Decls Vector that will contain the declarations loaded
1891 /// from the external source. The caller is responsible for merging
1892 /// these declarations with any declarations already stored in the
1893 /// declaration context.
1895 FindExternalLexicalDecls(const DeclContext *DC,
1896 llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
1897 SmallVectorImpl<Decl *> &Decls) override;
1899 /// \brief Get the decls that are contained in a file in the Offset/Length
1900 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
1902 void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
1903 SmallVectorImpl<Decl *> &Decls) override;
1905 /// \brief Notify ASTReader that we started deserialization of
1906 /// a decl or type so until FinishedDeserializing is called there may be
1907 /// decls that are initializing. Must be paired with FinishedDeserializing.
1908 void StartedDeserializing() override;
1910 /// \brief Notify ASTReader that we finished the deserialization of
1911 /// a decl or type. Must be paired with StartedDeserializing.
1912 void FinishedDeserializing() override;
1914 /// \brief Function that will be invoked when we begin parsing a new
1915 /// translation unit involving this external AST source.
1917 /// This function will provide all of the external definitions to
1918 /// the ASTConsumer.
1919 void StartTranslationUnit(ASTConsumer *Consumer) override;
1921 /// \brief Print some statistics about AST usage.
1922 void PrintStats() override;
1924 /// \brief Dump information about the AST reader to standard error.
1927 /// Return the amount of memory used by memory buffers, breaking down
1928 /// by heap-backed versus mmap'ed memory.
1929 void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override;
1931 /// \brief Initialize the semantic source with the Sema instance
1932 /// being used to perform semantic analysis on the abstract syntax
1934 void InitializeSema(Sema &S) override;
1936 /// \brief Inform the semantic consumer that Sema is no longer available.
1937 void ForgetSema() override { SemaObj = nullptr; }
1939 /// \brief Retrieve the IdentifierInfo for the named identifier.
1941 /// This routine builds a new IdentifierInfo for the given identifier. If any
1942 /// declarations with this name are visible from translation unit scope, their
1943 /// declarations will be deserialized and introduced into the declaration
1944 /// chain of the identifier.
1945 IdentifierInfo *get(StringRef Name) override;
1947 /// \brief Retrieve an iterator into the set of all identifiers
1948 /// in all loaded AST files.
1949 IdentifierIterator *getIdentifiers() override;
1951 /// \brief Load the contents of the global method pool for a given
1953 void ReadMethodPool(Selector Sel) override;
1955 /// Load the contents of the global method pool for a given
1956 /// selector if necessary.
1957 void updateOutOfDateSelector(Selector Sel) override;
1959 /// \brief Load the set of namespaces that are known to the external source,
1960 /// which will be used during typo correction.
1961 void ReadKnownNamespaces(
1962 SmallVectorImpl<NamespaceDecl *> &Namespaces) override;
1964 void ReadUndefinedButUsed(
1965 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) override;
1967 void ReadMismatchingDeleteExpressions(llvm::MapVector<
1968 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
1971 void ReadTentativeDefinitions(
1972 SmallVectorImpl<VarDecl *> &TentativeDefs) override;
1974 void ReadUnusedFileScopedDecls(
1975 SmallVectorImpl<const DeclaratorDecl *> &Decls) override;
1977 void ReadDelegatingConstructors(
1978 SmallVectorImpl<CXXConstructorDecl *> &Decls) override;
1980 void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) override;
1982 void ReadUnusedLocalTypedefNameCandidates(
1983 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) override;
1985 void ReadReferencedSelectors(
1986 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) override;
1988 void ReadWeakUndeclaredIdentifiers(
1989 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WI) override;
1991 void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) override;
1993 void ReadPendingInstantiations(
1994 SmallVectorImpl<std::pair<ValueDecl *,
1995 SourceLocation>> &Pending) override;
1997 void ReadLateParsedTemplates(
1998 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
2001 /// \brief Load a selector from disk, registering its ID if it exists.
2002 void LoadSelector(Selector Sel);
2004 void SetIdentifierInfo(unsigned ID, IdentifierInfo *II);
2005 void SetGloballyVisibleDecls(IdentifierInfo *II,
2006 const SmallVectorImpl<uint32_t> &DeclIDs,
2007 SmallVectorImpl<Decl *> *Decls = nullptr);
2009 /// \brief Report a diagnostic.
2010 DiagnosticBuilder Diag(unsigned DiagID) const;
2012 /// \brief Report a diagnostic.
2013 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const;
2015 IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID);
2017 IdentifierInfo *GetIdentifierInfo(ModuleFile &M, const RecordData &Record,
2019 return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++]));
2022 IdentifierInfo *GetIdentifier(serialization::IdentifierID ID) override {
2023 // Note that we are loading an identifier.
2024 Deserializing AnIdentifier(this);
2026 return DecodeIdentifierInfo(ID);
2029 IdentifierInfo *getLocalIdentifier(ModuleFile &M, unsigned LocalID);
2031 serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M,
2034 void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo);
2036 /// \brief Retrieve the macro with the given ID.
2037 MacroInfo *getMacro(serialization::MacroID ID);
2039 /// \brief Retrieve the global macro ID corresponding to the given local
2040 /// ID within the given module file.
2041 serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID);
2043 /// \brief Read the source location entry with index ID.
2044 bool ReadSLocEntry(int ID) override;
2046 /// \brief Retrieve the module import location and module name for the
2047 /// given source manager entry ID.
2048 std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) override;
2050 /// \brief Retrieve the global submodule ID given a module and its local ID
2052 serialization::SubmoduleID
2053 getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID);
2055 /// \brief Retrieve the submodule that corresponds to a global submodule ID.
2057 Module *getSubmodule(serialization::SubmoduleID GlobalID);
2059 /// \brief Retrieve the module that corresponds to the given module ID.
2061 /// Note: overrides method in ExternalASTSource
2062 Module *getModule(unsigned ID) override;
2064 /// \brief Retrieve the module file with a given local ID within the specified
2066 ModuleFile *getLocalModuleFile(ModuleFile &M, unsigned ID);
2068 /// \brief Get an ID for the given module file.
2069 unsigned getModuleFileID(ModuleFile *M);
2071 /// \brief Return a descriptor for the corresponding module.
2072 llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID) override;
2074 ExtKind hasExternalDefinitions(const Decl *D) override;
2076 /// \brief Retrieve a selector from the given module with its local ID
2078 Selector getLocalSelector(ModuleFile &M, unsigned LocalID);
2080 Selector DecodeSelector(serialization::SelectorID Idx);
2082 Selector GetExternalSelector(serialization::SelectorID ID) override;
2083 uint32_t GetNumExternalSelectors() override;
2085 Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) {
2086 return getLocalSelector(M, Record[Idx++]);
2089 /// \brief Retrieve the global selector ID that corresponds to this
2090 /// the local selector ID in a given module.
2091 serialization::SelectorID getGlobalSelectorID(ModuleFile &F,
2092 unsigned LocalID) const;
2094 /// \brief Read a declaration name.
2095 DeclarationName ReadDeclarationName(ModuleFile &F,
2096 const RecordData &Record, unsigned &Idx);
2097 void ReadDeclarationNameLoc(ModuleFile &F,
2098 DeclarationNameLoc &DNLoc, DeclarationName Name,
2099 const RecordData &Record, unsigned &Idx);
2100 void ReadDeclarationNameInfo(ModuleFile &F, DeclarationNameInfo &NameInfo,
2101 const RecordData &Record, unsigned &Idx);
2103 void ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
2104 const RecordData &Record, unsigned &Idx);
2106 NestedNameSpecifier *ReadNestedNameSpecifier(ModuleFile &F,
2107 const RecordData &Record,
2110 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(ModuleFile &F,
2111 const RecordData &Record,
2114 /// \brief Read a template name.
2115 TemplateName ReadTemplateName(ModuleFile &F, const RecordData &Record,
2118 /// \brief Read a template argument.
2119 TemplateArgument ReadTemplateArgument(ModuleFile &F, const RecordData &Record,
2121 bool Canonicalize = false);
2123 /// \brief Read a template parameter list.
2124 TemplateParameterList *ReadTemplateParameterList(ModuleFile &F,
2125 const RecordData &Record,
2128 /// \brief Read a template argument array.
2129 void ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
2130 ModuleFile &F, const RecordData &Record,
2131 unsigned &Idx, bool Canonicalize = false);
2133 /// \brief Read a UnresolvedSet structure.
2134 void ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
2135 const RecordData &Record, unsigned &Idx);
2137 /// \brief Read a C++ base specifier.
2138 CXXBaseSpecifier ReadCXXBaseSpecifier(ModuleFile &F,
2139 const RecordData &Record,unsigned &Idx);
2141 /// \brief Read a CXXCtorInitializer array.
2142 CXXCtorInitializer **
2143 ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
2146 /// \brief Read the contents of a CXXCtorInitializer array.
2147 CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset) override;
2149 /// \brief Read a source location from raw form and return it in its
2150 /// originating module file's source location space.
2151 SourceLocation ReadUntranslatedSourceLocation(uint32_t Raw) const {
2152 return SourceLocation::getFromRawEncoding((Raw >> 1) | (Raw << 31));
2155 /// \brief Read a source location from raw form.
2156 SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, uint32_t Raw) const {
2157 SourceLocation Loc = ReadUntranslatedSourceLocation(Raw);
2158 return TranslateSourceLocation(ModuleFile, Loc);
2161 /// \brief Translate a source location from another module file's source
2162 /// location space into ours.
2163 SourceLocation TranslateSourceLocation(ModuleFile &ModuleFile,
2164 SourceLocation Loc) const {
2165 if (!ModuleFile.ModuleOffsetMap.empty())
2166 ReadModuleOffsetMap(ModuleFile);
2167 assert(ModuleFile.SLocRemap.find(Loc.getOffset()) !=
2168 ModuleFile.SLocRemap.end() &&
2169 "Cannot find offset to remap.");
2170 int Remap = ModuleFile.SLocRemap.find(Loc.getOffset())->second;
2171 return Loc.getLocWithOffset(Remap);
2174 /// \brief Read a source location.
2175 SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
2176 const RecordDataImpl &Record,
2178 return ReadSourceLocation(ModuleFile, Record[Idx++]);
2181 /// \brief Read a source range.
2182 SourceRange ReadSourceRange(ModuleFile &F,
2183 const RecordData &Record, unsigned &Idx);
2185 /// \brief Read an integral value
2186 llvm::APInt ReadAPInt(const RecordData &Record, unsigned &Idx);
2188 /// \brief Read a signed integral value
2189 llvm::APSInt ReadAPSInt(const RecordData &Record, unsigned &Idx);
2191 /// \brief Read a floating-point value
2192 llvm::APFloat ReadAPFloat(const RecordData &Record,
2193 const llvm::fltSemantics &Sem, unsigned &Idx);
2195 // \brief Read a string
2196 static std::string ReadString(const RecordData &Record, unsigned &Idx);
2198 // \brief Skip a string
2199 static void SkipString(const RecordData &Record, unsigned &Idx) {
2200 Idx += Record[Idx] + 1;
2203 // \brief Read a path
2204 std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx);
2206 // \brief Skip a path
2207 static void SkipPath(const RecordData &Record, unsigned &Idx) {
2208 SkipString(Record, Idx);
2211 /// \brief Read a version tuple.
2212 static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
2214 CXXTemporary *ReadCXXTemporary(ModuleFile &F, const RecordData &Record,
2217 /// \brief Reads attributes from the current stream position.
2218 void ReadAttributes(ASTRecordReader &Record, AttrVec &Attrs);
2220 /// \brief Reads a statement.
2221 Stmt *ReadStmt(ModuleFile &F);
2223 /// \brief Reads an expression.
2224 Expr *ReadExpr(ModuleFile &F);
2226 /// \brief Reads a sub-statement operand during statement reading.
2227 Stmt *ReadSubStmt() {
2228 assert(ReadingKind == Read_Stmt &&
2229 "Should be called only during statement reading!");
2230 // Subexpressions are stored from last to first, so the next Stmt we need
2231 // is at the back of the stack.
2232 assert(!StmtStack.empty() && "Read too many sub-statements!");
2233 return StmtStack.pop_back_val();
2236 /// \brief Reads a sub-expression operand during statement reading.
2237 Expr *ReadSubExpr();
2239 /// \brief Reads a token out of a record.
2240 Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx);
2242 /// \brief Reads the macro record located at the given offset.
2243 MacroInfo *ReadMacroRecord(ModuleFile &F, uint64_t Offset);
2245 /// \brief Determine the global preprocessed entity ID that corresponds to
2246 /// the given local ID within the given module.
2247 serialization::PreprocessedEntityID
2248 getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const;
2250 /// \brief Add a macro to deserialize its macro directive history.
2252 /// \param II The name of the macro.
2253 /// \param M The module file.
2254 /// \param MacroDirectivesOffset Offset of the serialized macro directive
2256 void addPendingMacro(IdentifierInfo *II, ModuleFile *M,
2257 uint64_t MacroDirectivesOffset);
2259 /// \brief Read the set of macros defined by this external macro source.
2260 void ReadDefinedMacros() override;
2262 /// \brief Update an out-of-date identifier.
2263 void updateOutOfDateIdentifier(IdentifierInfo &II) override;
2265 /// \brief Note that this identifier is up-to-date.
2266 void markIdentifierUpToDate(IdentifierInfo *II);
2268 /// \brief Load all external visible decls in the given DeclContext.
2269 void completeVisibleDeclsMap(const DeclContext *DC) override;
2271 /// \brief Retrieve the AST context that this AST reader supplements.
2272 ASTContext &getContext() {
2273 assert(ContextObj && "requested AST context when not loading AST");
2277 // \brief Contains the IDs for declarations that were requested before we have
2278 // access to a Sema object.
2279 SmallVector<uint64_t, 16> PreloadedDeclIDs;
2281 /// \brief Retrieve the semantic analysis object used to analyze the
2282 /// translation unit in which the precompiled header is being
2284 Sema *getSema() { return SemaObj; }
2286 /// \brief Get the identifier resolver used for name lookup / updates
2287 /// in the translation unit scope. We have one of these even if we don't
2288 /// have a Sema object.
2289 IdentifierResolver &getIdResolver();
2291 /// \brief Retrieve the identifier table associated with the
2293 IdentifierTable &getIdentifierTable();
2295 /// \brief Record that the given ID maps to the given switch-case
2297 void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
2299 /// \brief Retrieve the switch-case statement with the given ID.
2300 SwitchCase *getSwitchCaseWithID(unsigned ID);
2302 void ClearSwitchCaseIDs();
2304 /// \brief Cursors for comments blocks.
2305 SmallVector<std::pair<llvm::BitstreamCursor,
2306 serialization::ModuleFile *>, 8> CommentsCursors;
2308 /// \brief Loads comments ranges.
2309 void ReadComments() override;
2311 /// Visit all the input files of the given module file.
2312 void visitInputFiles(serialization::ModuleFile &MF,
2313 bool IncludeSystem, bool Complain,
2314 llvm::function_ref<void(const serialization::InputFile &IF,
2315 bool isSystem)> Visitor);
2317 /// Visit all the top-level module maps loaded when building the given module
2319 void visitTopLevelModuleMaps(serialization::ModuleFile &MF,
2321 void(const FileEntry *)> Visitor);
2323 bool isProcessingUpdateRecords() { return ProcessingUpdateRecords; }
2326 /// \brief An object for streaming information from a record.
2327 class ASTRecordReader {
2328 using ModuleFile = serialization::ModuleFile;
2333 ASTReader::RecordData Record;
2335 using RecordData = ASTReader::RecordData;
2336 using RecordDataImpl = ASTReader::RecordDataImpl;
2339 /// Construct an ASTRecordReader that uses the default encoding scheme.
2340 ASTRecordReader(ASTReader &Reader, ModuleFile &F) : Reader(&Reader), F(&F) {}
2342 /// \brief Reads a record with id AbbrevID from Cursor, resetting the
2344 unsigned readRecord(llvm::BitstreamCursor &Cursor, unsigned AbbrevID);
2346 /// \brief Is this a module file for a module (rather than a PCH or similar).
2347 bool isModule() const { return F->isModule(); }
2349 /// \brief Retrieve the AST context that this AST reader supplements.
2350 ASTContext &getContext() { return Reader->getContext(); }
2352 /// \brief The current position in this record.
2353 unsigned getIdx() const { return Idx; }
2355 /// \brief The length of this record.
2356 size_t size() const { return Record.size(); }
2358 /// \brief An arbitrary index in this record.
2359 const uint64_t &operator[](size_t N) { return Record[N]; }
2361 /// \brief The last element in this record.
2362 const uint64_t &back() const { return Record.back(); }
2364 /// \brief Returns the current value in this record, and advances to the
2366 const uint64_t &readInt() { return Record[Idx++]; }
2368 /// \brief Returns the current value in this record, without advancing.
2369 const uint64_t &peekInt() { return Record[Idx]; }
2371 /// \brief Skips the specified number of values.
2372 void skipInts(unsigned N) { Idx += N; }
2374 /// \brief Retrieve the global submodule ID its local ID number.
2375 serialization::SubmoduleID
2376 getGlobalSubmoduleID(unsigned LocalID) {
2377 return Reader->getGlobalSubmoduleID(*F, LocalID);
2380 /// \brief Retrieve the submodule that corresponds to a global submodule ID.
2381 Module *getSubmodule(serialization::SubmoduleID GlobalID) {
2382 return Reader->getSubmodule(GlobalID);
2385 /// \brief Read the record that describes the lexical contents of a DC.
2386 bool readLexicalDeclContextStorage(uint64_t Offset, DeclContext *DC) {
2387 return Reader->ReadLexicalDeclContextStorage(*F, F->DeclsCursor, Offset,
2391 /// \brief Read the record that describes the visible contents of a DC.
2392 bool readVisibleDeclContextStorage(uint64_t Offset,
2393 serialization::DeclID ID) {
2394 return Reader->ReadVisibleDeclContextStorage(*F, F->DeclsCursor, Offset,
2398 void readExceptionSpec(SmallVectorImpl<QualType> &ExceptionStorage,
2399 FunctionProtoType::ExceptionSpecInfo &ESI) {
2400 return Reader->readExceptionSpec(*F, ExceptionStorage, ESI, Record, Idx);
2403 /// \brief Get the global offset corresponding to a local offset.
2404 uint64_t getGlobalBitOffset(uint32_t LocalOffset) {
2405 return Reader->getGlobalBitOffset(*F, LocalOffset);
2408 /// \brief Reads a statement.
2409 Stmt *readStmt() { return Reader->ReadStmt(*F); }
2411 /// \brief Reads an expression.
2412 Expr *readExpr() { return Reader->ReadExpr(*F); }
2414 /// \brief Reads a sub-statement operand during statement reading.
2415 Stmt *readSubStmt() { return Reader->ReadSubStmt(); }
2417 /// \brief Reads a sub-expression operand during statement reading.
2418 Expr *readSubExpr() { return Reader->ReadSubExpr(); }
2420 /// \brief Reads a declaration with the given local ID in the given module.
2422 /// \returns The requested declaration, casted to the given return type.
2423 template<typename T>
2424 T *GetLocalDeclAs(uint32_t LocalID) {
2425 return cast_or_null<T>(Reader->GetLocalDecl(*F, LocalID));
2428 /// \brief Reads a TemplateArgumentLocInfo appropriate for the
2429 /// given TemplateArgument kind, advancing Idx.
2430 TemplateArgumentLocInfo
2431 getTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
2432 return Reader->GetTemplateArgumentLocInfo(*F, Kind, Record, Idx);
2435 /// \brief Reads a TemplateArgumentLoc, advancing Idx.
2437 readTemplateArgumentLoc() {
2438 return Reader->ReadTemplateArgumentLoc(*F, Record, Idx);
2441 const ASTTemplateArgumentListInfo*
2442 readASTTemplateArgumentListInfo() {
2443 return Reader->ReadASTTemplateArgumentListInfo(*F, Record, Idx);
2446 /// \brief Reads a declarator info from the given record, advancing Idx.
2447 TypeSourceInfo *getTypeSourceInfo() {
2448 return Reader->GetTypeSourceInfo(*F, Record, Idx);
2451 /// \brief Map a local type ID within a given AST file to a global type ID.
2452 serialization::TypeID getGlobalTypeID(unsigned LocalID) const {
2453 return Reader->getGlobalTypeID(*F, LocalID);
2456 /// \brief Read a type from the current position in the record.
2457 QualType readType() {
2458 return Reader->readType(*F, Record, Idx);
2461 /// \brief Reads a declaration ID from the given position in this record.
2463 /// \returns The declaration ID read from the record, adjusted to a global ID.
2464 serialization::DeclID readDeclID() {
2465 return Reader->ReadDeclID(*F, Record, Idx);
2468 /// \brief Reads a declaration from the given position in a record in the
2469 /// given module, advancing Idx.
2471 return Reader->ReadDecl(*F, Record, Idx);
2474 /// \brief Reads a declaration from the given position in the record,
2477 /// \returns The declaration read from this location, casted to the given
2479 template<typename T>
2481 return Reader->ReadDeclAs<T>(*F, Record, Idx);
2484 IdentifierInfo *getIdentifierInfo() {
2485 return Reader->GetIdentifierInfo(*F, Record, Idx);
2488 /// \brief Read a selector from the Record, advancing Idx.
2489 Selector readSelector() {
2490 return Reader->ReadSelector(*F, Record, Idx);
2493 /// \brief Read a declaration name, advancing Idx.
2494 DeclarationName readDeclarationName() {
2495 return Reader->ReadDeclarationName(*F, Record, Idx);
2497 void readDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name) {
2498 return Reader->ReadDeclarationNameLoc(*F, DNLoc, Name, Record, Idx);
2500 void readDeclarationNameInfo(DeclarationNameInfo &NameInfo) {
2501 return Reader->ReadDeclarationNameInfo(*F, NameInfo, Record, Idx);
2504 void readQualifierInfo(QualifierInfo &Info) {
2505 return Reader->ReadQualifierInfo(*F, Info, Record, Idx);
2508 NestedNameSpecifier *readNestedNameSpecifier() {
2509 return Reader->ReadNestedNameSpecifier(*F, Record, Idx);
2512 NestedNameSpecifierLoc readNestedNameSpecifierLoc() {
2513 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
2516 /// \brief Read a template name, advancing Idx.
2517 TemplateName readTemplateName() {
2518 return Reader->ReadTemplateName(*F, Record, Idx);
2521 /// \brief Read a template argument, advancing Idx.
2522 TemplateArgument readTemplateArgument(bool Canonicalize = false) {
2523 return Reader->ReadTemplateArgument(*F, Record, Idx, Canonicalize);
2526 /// \brief Read a template parameter list, advancing Idx.
2527 TemplateParameterList *readTemplateParameterList() {
2528 return Reader->ReadTemplateParameterList(*F, Record, Idx);
2531 /// \brief Read a template argument array, advancing Idx.
2532 void readTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
2533 bool Canonicalize = false) {
2534 return Reader->ReadTemplateArgumentList(TemplArgs, *F, Record, Idx,
2538 /// \brief Read a UnresolvedSet structure, advancing Idx.
2539 void readUnresolvedSet(LazyASTUnresolvedSet &Set) {
2540 return Reader->ReadUnresolvedSet(*F, Set, Record, Idx);
2543 /// \brief Read a C++ base specifier, advancing Idx.
2544 CXXBaseSpecifier readCXXBaseSpecifier() {
2545 return Reader->ReadCXXBaseSpecifier(*F, Record, Idx);
2548 /// \brief Read a CXXCtorInitializer array, advancing Idx.
2549 CXXCtorInitializer **readCXXCtorInitializers() {
2550 return Reader->ReadCXXCtorInitializers(*F, Record, Idx);
2553 CXXTemporary *readCXXTemporary() {
2554 return Reader->ReadCXXTemporary(*F, Record, Idx);
2557 /// \brief Read a source location, advancing Idx.
2558 SourceLocation readSourceLocation() {
2559 return Reader->ReadSourceLocation(*F, Record, Idx);
2562 /// \brief Read a source range, advancing Idx.
2563 SourceRange readSourceRange() {
2564 return Reader->ReadSourceRange(*F, Record, Idx);
2567 /// \brief Read an integral value, advancing Idx.
2568 llvm::APInt readAPInt() {
2569 return Reader->ReadAPInt(Record, Idx);
2572 /// \brief Read a signed integral value, advancing Idx.
2573 llvm::APSInt readAPSInt() {
2574 return Reader->ReadAPSInt(Record, Idx);
2577 /// \brief Read a floating-point value, advancing Idx.
2578 llvm::APFloat readAPFloat(const llvm::fltSemantics &Sem) {
2579 return Reader->ReadAPFloat(Record, Sem,Idx);
2582 /// \brief Read a string, advancing Idx.
2583 std::string readString() {
2584 return Reader->ReadString(Record, Idx);
2587 /// \brief Read a path, advancing Idx.
2588 std::string readPath() {
2589 return Reader->ReadPath(*F, Record, Idx);
2592 /// \brief Read a version tuple, advancing Idx.
2593 VersionTuple readVersionTuple() {
2594 return ASTReader::ReadVersionTuple(Record, Idx);
2597 /// \brief Reads attributes from the current stream position, advancing Idx.
2598 void readAttributes(AttrVec &Attrs) {
2599 return Reader->ReadAttributes(*this, Attrs);
2602 /// \brief Reads a token out of a record, advancing Idx.
2604 return Reader->ReadToken(*F, Record, Idx);
2607 void recordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2608 Reader->RecordSwitchCaseID(SC, ID);
2611 /// \brief Retrieve the switch-case statement with the given ID.
2612 SwitchCase *getSwitchCaseWithID(unsigned ID) {
2613 return Reader->getSwitchCaseWithID(ID);
2617 /// \brief Helper class that saves the current stream position and
2618 /// then restores it when destroyed.
2619 struct SavedStreamPosition {
2620 explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor)
2621 : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) {}
2623 ~SavedStreamPosition() {
2624 Cursor.JumpToBit(Offset);
2628 llvm::BitstreamCursor &Cursor;
2632 inline void PCHValidator::Error(const char *Msg) {
2636 } // namespace clang
2638 #endif // LLVM_CLANG_SERIALIZATION_ASTREADER_H