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/Basic/Diagnostic.h"
21 #include "clang/Basic/FileManager.h"
22 #include "clang/Basic/FileSystemOptions.h"
23 #include "clang/Basic/IdentifierTable.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/Version.h"
26 #include "clang/Lex/ExternalPreprocessorSource.h"
27 #include "clang/Lex/HeaderSearch.h"
28 #include "clang/Lex/PreprocessingRecord.h"
29 #include "clang/Sema/ExternalSemaSource.h"
30 #include "clang/Sema/IdentifierResolver.h"
31 #include "clang/Serialization/ASTBitCodes.h"
32 #include "clang/Serialization/ContinuousRangeMap.h"
33 #include "clang/Serialization/Module.h"
34 #include "clang/Serialization/ModuleFileExtension.h"
35 #include "clang/Serialization/ModuleManager.h"
36 #include "llvm/ADT/APFloat.h"
37 #include "llvm/ADT/APInt.h"
38 #include "llvm/ADT/APSInt.h"
39 #include "llvm/ADT/MapVector.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/SmallSet.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/StringMap.h"
44 #include "llvm/ADT/StringRef.h"
45 #include "llvm/ADT/TinyPtrVector.h"
46 #include "llvm/Bitcode/BitstreamReader.h"
47 #include "llvm/Support/DataTypes.h"
48 #include "llvm/Support/Timer.h"
65 class ASTIdentifierIterator;
66 class ASTUnit; // FIXME: Layering violation and egregious hack.
70 class DefMacroDirective;
71 class DiagnosticOptions;
72 class NestedNameSpecifier;
73 class CXXBaseSpecifier;
74 class CXXConstructorDecl;
75 class CXXCtorInitializer;
76 class GlobalModuleIndex;
78 class MacroDefinition;
82 class OpaqueValueExpr;
84 class PreprocessorOptions;
87 class ASTDeserializationListener;
93 struct HeaderFileInfo;
96 class LazyASTUnresolvedSet;
98 /// \brief Abstract interface for callback invocations by the ASTReader.
100 /// While reading an AST file, the ASTReader will call the methods of the
101 /// listener to pass on specific information. Some of the listener methods can
102 /// return true to indicate to the ASTReader that the information (and
103 /// consequently the AST file) is invalid.
104 class ASTReaderListener {
106 virtual ~ASTReaderListener();
108 /// \brief Receives the full Clang version information.
110 /// \returns true to indicate that the version is invalid. Subclasses should
111 /// generally defer to this implementation.
112 virtual bool ReadFullVersionInformation(StringRef FullVersion) {
113 return FullVersion != getClangFullRepositoryVersion();
116 virtual void ReadModuleName(StringRef ModuleName) {}
117 virtual void ReadModuleMapFile(StringRef ModuleMapPath) {}
119 /// \brief Receives the language options.
121 /// \returns true to indicate the options are invalid or false otherwise.
122 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
124 bool AllowCompatibleDifferences) {
128 /// \brief Receives the target options.
130 /// \returns true to indicate the target options are invalid, or false
132 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
133 bool AllowCompatibleDifferences) {
137 /// \brief Receives the diagnostic options.
139 /// \returns true to indicate the diagnostic options are invalid, or false
142 ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
147 /// \brief Receives the file system options.
149 /// \returns true to indicate the file system options are invalid, or false
151 virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
156 /// \brief Receives the header search options.
158 /// \returns true to indicate the header search options are invalid, or false
160 virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
161 StringRef SpecificModuleCachePath,
166 /// \brief Receives the preprocessor options.
168 /// \param SuggestedPredefines Can be filled in with the set of predefines
169 /// that are suggested by the preprocessor options. Typically only used when
170 /// loading a precompiled header.
172 /// \returns true to indicate the preprocessor options are invalid, or false
174 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
176 std::string &SuggestedPredefines) {
180 /// \brief Receives __COUNTER__ value.
181 virtual void ReadCounter(const serialization::ModuleFile &M,
184 /// This is called for each AST file loaded.
185 virtual void visitModuleFile(StringRef Filename,
186 serialization::ModuleKind Kind) {}
188 /// \brief Returns true if this \c ASTReaderListener wants to receive the
189 /// input files of the AST file via \c visitInputFile, false otherwise.
190 virtual bool needsInputFileVisitation() { return false; }
191 /// \brief Returns true if this \c ASTReaderListener wants to receive the
192 /// system input files of the AST file via \c visitInputFile, false otherwise.
193 virtual bool needsSystemInputFileVisitation() { return false; }
194 /// \brief if \c needsInputFileVisitation returns true, this is called for
195 /// each non-system input file of the AST File. If
196 /// \c needsSystemInputFileVisitation is true, then it is called for all
197 /// system input files as well.
199 /// \returns true to continue receiving the next input file, false to stop.
200 virtual bool visitInputFile(StringRef Filename, bool isSystem,
201 bool isOverridden, bool isExplicitModule) {
205 /// \brief Returns true if this \c ASTReaderListener wants to receive the
206 /// imports of the AST file via \c visitImport, false otherwise.
207 virtual bool needsImportVisitation() const { return false; }
208 /// \brief If needsImportVisitation returns \c true, this is called for each
209 /// AST file imported by this AST file.
210 virtual void visitImport(StringRef Filename) {}
212 /// Indicates that a particular module file extension has been read.
213 virtual void readModuleFileExtension(
214 const ModuleFileExtensionMetadata &Metadata) {}
217 /// \brief Simple wrapper class for chaining listeners.
218 class ChainedASTReaderListener : public ASTReaderListener {
219 std::unique_ptr<ASTReaderListener> First;
220 std::unique_ptr<ASTReaderListener> Second;
223 /// Takes ownership of \p First and \p Second.
224 ChainedASTReaderListener(std::unique_ptr<ASTReaderListener> First,
225 std::unique_ptr<ASTReaderListener> Second)
226 : First(std::move(First)), Second(std::move(Second)) {}
228 std::unique_ptr<ASTReaderListener> takeFirst() { return std::move(First); }
229 std::unique_ptr<ASTReaderListener> takeSecond() { return std::move(Second); }
231 bool ReadFullVersionInformation(StringRef FullVersion) override;
232 void ReadModuleName(StringRef ModuleName) override;
233 void ReadModuleMapFile(StringRef ModuleMapPath) override;
234 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
235 bool AllowCompatibleDifferences) override;
236 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
237 bool AllowCompatibleDifferences) override;
238 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
239 bool Complain) override;
240 bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
241 bool Complain) override;
243 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
244 StringRef SpecificModuleCachePath,
245 bool Complain) override;
246 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
248 std::string &SuggestedPredefines) override;
250 void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
251 bool needsInputFileVisitation() override;
252 bool needsSystemInputFileVisitation() override;
253 void visitModuleFile(StringRef Filename,
254 serialization::ModuleKind Kind) override;
255 bool visitInputFile(StringRef Filename, bool isSystem,
256 bool isOverridden, bool isExplicitModule) override;
257 void readModuleFileExtension(
258 const ModuleFileExtensionMetadata &Metadata) override;
261 /// \brief ASTReaderListener implementation to validate the information of
262 /// the PCH file against an initialized Preprocessor.
263 class PCHValidator : public ASTReaderListener {
268 PCHValidator(Preprocessor &PP, ASTReader &Reader)
269 : PP(PP), Reader(Reader) {}
271 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
272 bool AllowCompatibleDifferences) override;
273 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
274 bool AllowCompatibleDifferences) override;
275 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
276 bool Complain) override;
277 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
278 std::string &SuggestedPredefines) override;
279 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
280 StringRef SpecificModuleCachePath,
281 bool Complain) override;
282 void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
285 void Error(const char *Msg);
288 namespace serialization {
290 class ReadMethodPoolVisitor;
293 class ASTIdentifierLookupTrait;
294 /// \brief The on-disk hash table(s) used for DeclContext name lookup.
295 struct DeclContextLookupTable;
298 } // end namespace serialization
300 /// \brief Reads an AST files chain containing the contents of a translation
303 /// The ASTReader class reads bitstreams (produced by the ASTWriter
304 /// class) containing the serialized representation of a given
305 /// abstract syntax tree and its supporting data structures. An
306 /// instance of the ASTReader can be attached to an ASTContext object,
307 /// which will provide access to the contents of the AST files.
309 /// The AST reader provides lazy de-serialization of declarations, as
310 /// required when traversing the AST. Only those AST nodes that are
311 /// actually required will be de-serialized.
313 : public ExternalPreprocessorSource,
314 public ExternalPreprocessingRecordSource,
315 public ExternalHeaderFileInfoSource,
316 public ExternalSemaSource,
317 public IdentifierInfoLookup,
318 public ExternalSLocEntrySource
321 typedef SmallVector<uint64_t, 64> RecordData;
322 typedef SmallVectorImpl<uint64_t> RecordDataImpl;
324 /// \brief The result of reading the control block of an AST file, which
325 /// can fail for various reasons.
327 /// \brief The control block was read successfully. Aside from failures,
328 /// the AST file is safe to read into the current context.
330 /// \brief The AST file itself appears corrupted.
332 /// \brief The AST file was missing.
334 /// \brief The AST file is out-of-date relative to its input files,
335 /// and needs to be regenerated.
337 /// \brief The AST file was written by a different version of Clang.
339 /// \brief The AST file was writtten with a different language/target
341 ConfigurationMismatch,
342 /// \brief The AST file has errors.
346 /// \brief Types of AST files.
347 friend class PCHValidator;
348 friend class ASTDeclReader;
349 friend class ASTStmtReader;
350 friend class ASTIdentifierIterator;
351 friend class serialization::reader::ASTIdentifierLookupTrait;
352 friend class TypeLocReader;
353 friend class ASTWriter;
354 friend class ASTUnit; // ASTUnit needs to remap source locations.
355 friend class serialization::ReadMethodPoolVisitor;
357 typedef serialization::ModuleFile ModuleFile;
358 typedef serialization::ModuleKind ModuleKind;
359 typedef serialization::ModuleManager ModuleManager;
361 typedef ModuleManager::ModuleIterator ModuleIterator;
362 typedef ModuleManager::ModuleConstIterator ModuleConstIterator;
363 typedef ModuleManager::ModuleReverseIterator ModuleReverseIterator;
366 /// \brief The receiver of some callbacks invoked by ASTReader.
367 std::unique_ptr<ASTReaderListener> Listener;
369 /// \brief The receiver of deserialization events.
370 ASTDeserializationListener *DeserializationListener;
371 bool OwnsDeserializationListener;
373 SourceManager &SourceMgr;
374 FileManager &FileMgr;
375 const PCHContainerReader &PCHContainerRdr;
376 DiagnosticsEngine &Diags;
378 /// \brief The semantic analysis object that will be processing the
379 /// AST files and the translation unit that uses it.
382 /// \brief The preprocessor that will be loading the source file.
385 /// \brief The AST context into which we'll read the AST files.
388 /// \brief The AST consumer.
389 ASTConsumer *Consumer;
391 /// \brief The module manager which manages modules and their dependencies
392 ModuleManager ModuleMgr;
394 /// \brief A dummy identifier resolver used to merge TU-scope declarations in
395 /// C, for the cases where we don't have a Sema object to provide a real
396 /// identifier resolver.
397 IdentifierResolver DummyIdResolver;
399 /// A mapping from extension block names to module file extensions.
400 llvm::StringMap<IntrusiveRefCntPtr<ModuleFileExtension>> ModuleFileExtensions;
402 /// \brief A timer used to track the time spent deserializing.
403 std::unique_ptr<llvm::Timer> ReadTimer;
405 /// \brief The location where the module file will be considered as
406 /// imported from. For non-module AST types it should be invalid.
407 SourceLocation CurrentImportLoc;
409 /// \brief The global module index, if loaded.
410 std::unique_ptr<GlobalModuleIndex> GlobalIndex;
412 /// \brief A map of global bit offsets to the module that stores entities
413 /// at those bit offsets.
414 ContinuousRangeMap<uint64_t, ModuleFile*, 4> GlobalBitOffsetsMap;
416 /// \brief A map of negated SLocEntryIDs to the modules containing them.
417 ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocEntryMap;
419 typedef ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocOffsetMapType;
421 /// \brief A map of reversed (SourceManager::MaxLoadedOffset - SLocOffset)
422 /// SourceLocation offsets to the modules containing them.
423 GlobalSLocOffsetMapType GlobalSLocOffsetMap;
425 /// \brief Types that have already been loaded from the chain.
427 /// When the pointer at index I is non-NULL, the type with
428 /// ID = (I + 1) << FastQual::Width has already been loaded
429 std::vector<QualType> TypesLoaded;
431 typedef ContinuousRangeMap<serialization::TypeID, ModuleFile *, 4>
434 /// \brief Mapping from global type IDs to the module in which the
435 /// type resides along with the offset that should be added to the
436 /// global type ID to produce a local ID.
437 GlobalTypeMapType GlobalTypeMap;
439 /// \brief Declarations that have already been loaded from the chain.
441 /// When the pointer at index I is non-NULL, the declaration with ID
442 /// = I + 1 has already been loaded.
443 std::vector<Decl *> DeclsLoaded;
445 typedef ContinuousRangeMap<serialization::DeclID, ModuleFile *, 4>
448 /// \brief Mapping from global declaration IDs to the module in which the
449 /// declaration resides.
450 GlobalDeclMapType GlobalDeclMap;
452 typedef std::pair<ModuleFile *, uint64_t> FileOffset;
453 typedef SmallVector<FileOffset, 2> FileOffsetsTy;
454 typedef llvm::DenseMap<serialization::DeclID, FileOffsetsTy>
455 DeclUpdateOffsetsMap;
457 /// \brief Declarations that have modifications residing in a later file
459 DeclUpdateOffsetsMap DeclUpdateOffsets;
461 /// \brief Declaration updates for already-loaded declarations that we need
462 /// to apply once we finish processing an import.
463 llvm::SmallVector<std::pair<serialization::GlobalDeclID, Decl*>, 16>
464 PendingUpdateRecords;
466 enum class PendingFakeDefinitionKind { NotFake, Fake, FakeLoaded };
468 /// \brief The DefinitionData pointers that we faked up for class definitions
469 /// that we needed but hadn't loaded yet.
470 llvm::DenseMap<void *, PendingFakeDefinitionKind> PendingFakeDefinitionData;
472 /// \brief Exception specification updates that have been loaded but not yet
473 /// propagated across the relevant redeclaration chain. The map key is the
474 /// canonical declaration (used only for deduplication) and the value is a
475 /// declaration that has an exception specification.
476 llvm::SmallMapVector<Decl *, FunctionDecl *, 4> PendingExceptionSpecUpdates;
478 /// \brief Declarations that have been imported and have typedef names for
479 /// linkage purposes.
480 llvm::DenseMap<std::pair<DeclContext*, IdentifierInfo*>, NamedDecl*>
481 ImportedTypedefNamesForLinkage;
483 /// \brief Mergeable declaration contexts that have anonymous declarations
484 /// within them, and those anonymous declarations.
485 llvm::DenseMap<DeclContext*, llvm::SmallVector<NamedDecl*, 2>>
486 AnonymousDeclarationsForMerging;
488 struct FileDeclsInfo {
490 ArrayRef<serialization::LocalDeclID> Decls;
492 FileDeclsInfo() : Mod(nullptr) {}
493 FileDeclsInfo(ModuleFile *Mod, ArrayRef<serialization::LocalDeclID> Decls)
494 : Mod(Mod), Decls(Decls) {}
497 /// \brief Map from a FileID to the file-level declarations that it contains.
498 llvm::DenseMap<FileID, FileDeclsInfo> FileDeclIDs;
500 /// \brief An array of lexical contents of a declaration context, as a sequence of
501 /// Decl::Kind, DeclID pairs.
502 typedef ArrayRef<llvm::support::unaligned_uint32_t> LexicalContents;
504 /// \brief Map from a DeclContext to its lexical contents.
505 llvm::DenseMap<const DeclContext*, std::pair<ModuleFile*, LexicalContents>>
508 /// \brief Map from the TU to its lexical contents from each module file.
509 std::vector<std::pair<ModuleFile*, LexicalContents>> TULexicalDecls;
511 /// \brief Map from a DeclContext to its lookup tables.
512 llvm::DenseMap<const DeclContext *,
513 serialization::reader::DeclContextLookupTable> Lookups;
515 // Updates for visible decls can occur for other contexts than just the
516 // TU, and when we read those update records, the actual context may not
517 // be available yet, so have this pending map using the ID as a key. It
518 // will be realized when the context is actually loaded.
519 struct PendingVisibleUpdate {
521 const unsigned char *Data;
523 typedef SmallVector<PendingVisibleUpdate, 1> DeclContextVisibleUpdates;
525 /// \brief Updates to the visible declarations of declaration contexts that
526 /// haven't been loaded yet.
527 llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates>
528 PendingVisibleUpdates;
530 /// \brief The set of C++ or Objective-C classes that have forward
531 /// declarations that have not yet been linked to their definitions.
532 llvm::SmallPtrSet<Decl *, 4> PendingDefinitions;
534 typedef llvm::MapVector<Decl *, uint64_t,
535 llvm::SmallDenseMap<Decl *, unsigned, 4>,
536 SmallVector<std::pair<Decl *, uint64_t>, 4> >
539 /// \brief Functions or methods that have bodies that will be attached.
540 PendingBodiesMap PendingBodies;
542 /// \brief Definitions for which we have added merged definitions but not yet
543 /// performed deduplication.
544 llvm::SetVector<NamedDecl*> PendingMergedDefinitionsToDeduplicate;
546 /// \brief Read the record that describes the lexical contents of a DC.
547 bool ReadLexicalDeclContextStorage(ModuleFile &M,
548 llvm::BitstreamCursor &Cursor,
549 uint64_t Offset, DeclContext *DC);
550 /// \brief Read the record that describes the visible contents of a DC.
551 bool ReadVisibleDeclContextStorage(ModuleFile &M,
552 llvm::BitstreamCursor &Cursor,
553 uint64_t Offset, serialization::DeclID ID);
555 /// \brief A vector containing identifiers that have already been
558 /// If the pointer at index I is non-NULL, then it refers to the
559 /// IdentifierInfo for the identifier with ID=I+1 that has already
561 std::vector<IdentifierInfo *> IdentifiersLoaded;
563 typedef ContinuousRangeMap<serialization::IdentID, ModuleFile *, 4>
564 GlobalIdentifierMapType;
566 /// \brief Mapping from global identifier IDs to the module in which the
567 /// identifier resides along with the offset that should be added to the
568 /// global identifier ID to produce a local ID.
569 GlobalIdentifierMapType GlobalIdentifierMap;
571 /// \brief A vector containing macros that have already been
574 /// If the pointer at index I is non-NULL, then it refers to the
575 /// MacroInfo for the identifier with ID=I+1 that has already
577 std::vector<MacroInfo *> MacrosLoaded;
579 typedef std::pair<IdentifierInfo *, serialization::SubmoduleID>
582 /// \brief A set of #undef directives that we have loaded; used to
583 /// deduplicate the same #undef information coming from multiple module
585 llvm::DenseSet<LoadedMacroInfo> LoadedUndefs;
587 typedef ContinuousRangeMap<serialization::MacroID, ModuleFile *, 4>
590 /// \brief Mapping from global macro IDs to the module in which the
591 /// macro resides along with the offset that should be added to the
592 /// global macro ID to produce a local ID.
593 GlobalMacroMapType GlobalMacroMap;
595 /// \brief A vector containing submodules that have already been loaded.
597 /// This vector is indexed by the Submodule ID (-1). NULL submodule entries
598 /// indicate that the particular submodule ID has not yet been loaded.
599 SmallVector<Module *, 2> SubmodulesLoaded;
601 typedef ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4>
602 GlobalSubmoduleMapType;
604 /// \brief Mapping from global submodule IDs to the module file in which the
605 /// submodule resides along with the offset that should be added to the
606 /// global submodule ID to produce a local ID.
607 GlobalSubmoduleMapType GlobalSubmoduleMap;
609 /// \brief A set of hidden declarations.
610 typedef SmallVector<Decl*, 2> HiddenNames;
611 typedef llvm::DenseMap<Module *, HiddenNames> HiddenNamesMapType;
613 /// \brief A mapping from each of the hidden submodules to the deserialized
614 /// declarations in that submodule that could be made visible.
615 HiddenNamesMapType HiddenNamesMap;
618 /// \brief A module import, export, or conflict that hasn't yet been resolved.
619 struct UnresolvedModuleRef {
620 /// \brief The file in which this module resides.
623 /// \brief The module that is importing or exporting.
626 /// \brief The kind of module reference.
627 enum { Import, Export, Conflict } Kind;
629 /// \brief The local ID of the module that is being exported.
632 /// \brief Whether this is a wildcard export.
633 unsigned IsWildcard : 1;
635 /// \brief String data.
639 /// \brief The set of module imports and exports that still need to be
641 SmallVector<UnresolvedModuleRef, 2> UnresolvedModuleRefs;
643 /// \brief A vector containing selectors that have already been loaded.
645 /// This vector is indexed by the Selector ID (-1). NULL selector
646 /// entries indicate that the particular selector ID has not yet
648 SmallVector<Selector, 16> SelectorsLoaded;
650 typedef ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4>
651 GlobalSelectorMapType;
653 /// \brief Mapping from global selector IDs to the module in which the
655 /// global selector ID to produce a local ID.
656 GlobalSelectorMapType GlobalSelectorMap;
658 /// \brief The generation number of the last time we loaded data from the
659 /// global method pool for this selector.
660 llvm::DenseMap<Selector, unsigned> SelectorGeneration;
662 /// Whether a selector is out of date. We mark a selector as out of date
663 /// if we load another module after the method pool entry was pulled in.
664 llvm::DenseMap<Selector, bool> SelectorOutOfDate;
666 struct PendingMacroInfo {
668 uint64_t MacroDirectivesOffset;
670 PendingMacroInfo(ModuleFile *M, uint64_t MacroDirectivesOffset)
671 : M(M), MacroDirectivesOffset(MacroDirectivesOffset) {}
674 typedef llvm::MapVector<IdentifierInfo *, SmallVector<PendingMacroInfo, 2> >
677 /// \brief Mapping from identifiers that have a macro history to the global
678 /// IDs have not yet been deserialized to the global IDs of those macros.
679 PendingMacroIDsMap PendingMacroIDs;
681 typedef ContinuousRangeMap<unsigned, ModuleFile *, 4>
682 GlobalPreprocessedEntityMapType;
684 /// \brief Mapping from global preprocessing entity IDs to the module in
685 /// which the preprocessed entity resides along with the offset that should be
686 /// added to the global preprocessing entitiy ID to produce a local ID.
687 GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap;
689 /// \name CodeGen-relevant special data
690 /// \brief Fields containing data that is relevant to CodeGen.
693 /// \brief The IDs of all declarations that fulfill the criteria of
694 /// "interesting" decls.
696 /// This contains the data loaded from all EAGERLY_DESERIALIZED_DECLS blocks
697 /// in the chain. The referenced declarations are deserialized and passed to
698 /// the consumer eagerly.
699 SmallVector<uint64_t, 16> EagerlyDeserializedDecls;
701 /// \brief The IDs of all tentative definitions stored in the chain.
703 /// Sema keeps track of all tentative definitions in a TU because it has to
704 /// complete them and pass them on to CodeGen. Thus, tentative definitions in
705 /// the PCH chain must be eagerly deserialized.
706 SmallVector<uint64_t, 16> TentativeDefinitions;
708 /// \brief The IDs of all CXXRecordDecls stored in the chain whose VTables are
711 /// CodeGen has to emit VTables for these records, so they have to be eagerly
713 SmallVector<uint64_t, 64> VTableUses;
715 /// \brief A snapshot of the pending instantiations in the chain.
717 /// This record tracks the instantiations that Sema has to perform at the
718 /// end of the TU. It consists of a pair of values for every pending
719 /// instantiation where the first value is the ID of the decl and the second
720 /// is the instantiation location.
721 SmallVector<uint64_t, 64> PendingInstantiations;
725 /// \name DiagnosticsEngine-relevant special data
726 /// \brief Fields containing data that is used for generating diagnostics
729 /// \brief A snapshot of Sema's unused file-scoped variable tracking, for
730 /// generating warnings.
731 SmallVector<uint64_t, 16> UnusedFileScopedDecls;
733 /// \brief A list of all the delegating constructors we've seen, to diagnose
735 SmallVector<uint64_t, 4> DelegatingCtorDecls;
737 /// \brief Method selectors used in a @selector expression. Used for
738 /// implementation of -Wselector.
739 SmallVector<uint64_t, 64> ReferencedSelectorsData;
741 /// \brief A snapshot of Sema's weak undeclared identifier tracking, for
742 /// generating warnings.
743 SmallVector<uint64_t, 64> WeakUndeclaredIdentifiers;
745 /// \brief The IDs of type aliases for ext_vectors that exist in the chain.
747 /// Used by Sema for finding sugared names for ext_vectors in diagnostics.
748 SmallVector<uint64_t, 4> ExtVectorDecls;
752 /// \name Sema-relevant special data
753 /// \brief Fields containing data that is used for semantic analysis
756 /// \brief The IDs of all potentially unused typedef names in the chain.
758 /// Sema tracks these to emit warnings.
759 SmallVector<uint64_t, 16> UnusedLocalTypedefNameCandidates;
761 /// \brief The IDs of the declarations Sema stores directly.
763 /// Sema tracks a few important decls, such as namespace std, directly.
764 SmallVector<uint64_t, 4> SemaDeclRefs;
766 /// \brief The IDs of the types ASTContext stores directly.
768 /// The AST context tracks a few important types, such as va_list, directly.
769 SmallVector<uint64_t, 16> SpecialTypes;
771 /// \brief The IDs of CUDA-specific declarations ASTContext stores directly.
773 /// The AST context tracks a few important decls, currently cudaConfigureCall,
775 SmallVector<uint64_t, 2> CUDASpecialDeclRefs;
777 /// \brief The floating point pragma option settings.
778 SmallVector<uint64_t, 1> FPPragmaOptions;
780 /// \brief The pragma clang optimize location (if the pragma state is "off").
781 SourceLocation OptimizeOffPragmaLocation;
783 /// \brief The PragmaMSStructKind pragma ms_struct state if set, or -1.
784 int PragmaMSStructState;
786 /// \brief The PragmaMSPointersToMembersKind pragma pointers_to_members state.
787 int PragmaMSPointersToMembersState;
788 SourceLocation PointersToMembersPragmaLocation;
790 /// \brief The OpenCL extension settings.
791 SmallVector<uint64_t, 1> OpenCLExtensions;
793 /// \brief A list of the namespaces we've seen.
794 SmallVector<uint64_t, 4> KnownNamespaces;
796 /// \brief A list of undefined decls with internal linkage followed by the
797 /// SourceLocation of a matching ODR-use.
798 SmallVector<uint64_t, 8> UndefinedButUsed;
800 /// \brief Delete expressions to analyze at the end of translation unit.
801 SmallVector<uint64_t, 8> DelayedDeleteExprs;
803 // \brief A list of late parsed template function data.
804 SmallVector<uint64_t, 1> LateParsedTemplates;
806 struct ImportedSubmodule {
807 serialization::SubmoduleID ID;
808 SourceLocation ImportLoc;
810 ImportedSubmodule(serialization::SubmoduleID ID, SourceLocation ImportLoc)
811 : ID(ID), ImportLoc(ImportLoc) {}
814 /// \brief A list of modules that were imported by precompiled headers or
815 /// any other non-module AST file.
816 SmallVector<ImportedSubmodule, 2> ImportedModules;
819 /// \brief The directory that the PCH we are reading is stored in.
820 std::string CurrentDir;
822 /// \brief The system include root to be used when loading the
823 /// precompiled header.
824 std::string isysroot;
826 /// \brief Whether to disable the normal validation performed on precompiled
827 /// headers when they are loaded.
828 bool DisableValidation;
830 /// \brief Whether to accept an AST file with compiler errors.
831 bool AllowASTWithCompilerErrors;
833 /// \brief Whether to accept an AST file that has a different configuration
834 /// from the current compiler instance.
835 bool AllowConfigurationMismatch;
837 /// \brief Whether validate system input files.
838 bool ValidateSystemInputs;
840 /// \brief Whether we are allowed to use the global module index.
843 /// \brief Whether we have tried loading the global module index yet.
844 bool TriedLoadingGlobalIndex;
846 ///\brief Whether we are currently processing update records.
847 bool ProcessingUpdateRecords;
849 typedef llvm::DenseMap<unsigned, SwitchCase *> SwitchCaseMapTy;
850 /// \brief Mapping from switch-case IDs in the chain to switch-case statements
852 /// Statements usually don't have IDs, but switch cases need them, so that the
853 /// switch statement can refer to them.
854 SwitchCaseMapTy SwitchCaseStmts;
856 SwitchCaseMapTy *CurrSwitchCaseStmts;
858 /// \brief The number of source location entries de-serialized from
860 unsigned NumSLocEntriesRead;
862 /// \brief The number of source location entries in the chain.
863 unsigned TotalNumSLocEntries;
865 /// \brief The number of statements (and expressions) de-serialized
867 unsigned NumStatementsRead;
869 /// \brief The total number of statements (and expressions) stored
871 unsigned TotalNumStatements;
873 /// \brief The number of macros de-serialized from the chain.
874 unsigned NumMacrosRead;
876 /// \brief The total number of macros stored in the chain.
877 unsigned TotalNumMacros;
879 /// \brief The number of lookups into identifier tables.
880 unsigned NumIdentifierLookups;
882 /// \brief The number of lookups into identifier tables that succeed.
883 unsigned NumIdentifierLookupHits;
885 /// \brief The number of selectors that have been read.
886 unsigned NumSelectorsRead;
888 /// \brief The number of method pool entries that have been read.
889 unsigned NumMethodPoolEntriesRead;
891 /// \brief The number of times we have looked up a selector in the method
893 unsigned NumMethodPoolLookups;
895 /// \brief The number of times we have looked up a selector in the method
896 /// pool and found something.
897 unsigned NumMethodPoolHits;
899 /// \brief The number of times we have looked up a selector in the method
900 /// pool within a specific module.
901 unsigned NumMethodPoolTableLookups;
903 /// \brief The number of times we have looked up a selector in the method
904 /// pool within a specific module and found something.
905 unsigned NumMethodPoolTableHits;
907 /// \brief The total number of method pool entries in the selector table.
908 unsigned TotalNumMethodPoolEntries;
910 /// Number of lexical decl contexts read/total.
911 unsigned NumLexicalDeclContextsRead, TotalLexicalDeclContexts;
913 /// Number of visible decl contexts read/total.
914 unsigned NumVisibleDeclContextsRead, TotalVisibleDeclContexts;
916 /// Total size of modules, in bits, currently loaded
917 uint64_t TotalModulesSizeInBits;
919 /// \brief Number of Decl/types that are currently deserializing.
920 unsigned NumCurrentElementsDeserializing;
922 /// \brief Set true while we are in the process of passing deserialized
923 /// "interesting" decls to consumer inside FinishedDeserializing().
924 /// This is used as a guard to avoid recursively repeating the process of
925 /// passing decls to consumer.
926 bool PassingDeclsToConsumer;
928 /// \brief The set of identifiers that were read while the AST reader was
929 /// (recursively) loading declarations.
931 /// The declarations on the identifier chain for these identifiers will be
932 /// loaded once the recursive loading has completed.
933 llvm::MapVector<IdentifierInfo *, SmallVector<uint32_t, 4> >
934 PendingIdentifierInfos;
936 /// \brief The set of lookup results that we have faked in order to support
937 /// merging of partially deserialized decls but that we have not yet removed.
938 llvm::SmallMapVector<IdentifierInfo *, SmallVector<NamedDecl*, 2>, 16>
939 PendingFakeLookupResults;
941 /// \brief The generation number of each identifier, which keeps track of
942 /// the last time we loaded information about this identifier.
943 llvm::DenseMap<IdentifierInfo *, unsigned> IdentifierGeneration;
945 /// \brief Contains declarations and definitions that will be
946 /// "interesting" to the ASTConsumer, when we get that AST consumer.
948 /// "Interesting" declarations are those that have data that may
949 /// need to be emitted, such as inline function definitions or
950 /// Objective-C protocols.
951 std::deque<Decl *> InterestingDecls;
953 /// \brief The list of redeclaration chains that still need to be
954 /// reconstructed, and the local offset to the corresponding list
955 /// of redeclarations.
956 SmallVector<std::pair<Decl *, uint64_t>, 16> PendingDeclChains;
958 /// \brief The list of canonical declarations whose redeclaration chains
959 /// need to be marked as incomplete once we're done deserializing things.
960 SmallVector<Decl *, 16> PendingIncompleteDeclChains;
962 /// \brief The Decl IDs for the Sema/Lexical DeclContext of a Decl that has
963 /// been loaded but its DeclContext was not set yet.
964 struct PendingDeclContextInfo {
966 serialization::GlobalDeclID SemaDC;
967 serialization::GlobalDeclID LexicalDC;
970 /// \brief The set of Decls that have been loaded but their DeclContexts are
973 /// The DeclContexts for these Decls will be set once recursive loading has
975 std::deque<PendingDeclContextInfo> PendingDeclContextInfos;
977 /// \brief The set of NamedDecls that have been loaded, but are members of a
978 /// context that has been merged into another context where the corresponding
979 /// declaration is either missing or has not yet been loaded.
981 /// We will check whether the corresponding declaration is in fact missing
982 /// once recursing loading has been completed.
983 llvm::SmallVector<NamedDecl *, 16> PendingOdrMergeChecks;
985 /// \brief Record definitions in which we found an ODR violation.
986 llvm::SmallDenseMap<CXXRecordDecl *, llvm::TinyPtrVector<CXXRecordDecl *>, 2>
987 PendingOdrMergeFailures;
989 /// \brief DeclContexts in which we have diagnosed an ODR violation.
990 llvm::SmallPtrSet<DeclContext*, 2> DiagnosedOdrMergeFailures;
992 /// \brief The set of Objective-C categories that have been deserialized
993 /// since the last time the declaration chains were linked.
994 llvm::SmallPtrSet<ObjCCategoryDecl *, 16> CategoriesDeserialized;
996 /// \brief The set of Objective-C class definitions that have already been
997 /// loaded, for which we will need to check for categories whenever a new
998 /// module is loaded.
999 SmallVector<ObjCInterfaceDecl *, 16> ObjCClassesLoaded;
1001 typedef llvm::DenseMap<Decl *, SmallVector<serialization::DeclID, 2> >
1004 /// \brief A mapping from canonical declarations to the set of global
1005 /// declaration IDs for key declaration that have been merged with that
1006 /// canonical declaration. A key declaration is a formerly-canonical
1007 /// declaration whose module did not import any other key declaration for that
1008 /// entity. These are the IDs that we use as keys when finding redecl chains.
1009 KeyDeclsMap KeyDecls;
1011 /// \brief A mapping from DeclContexts to the semantic DeclContext that we
1012 /// are treating as the definition of the entity. This is used, for instance,
1013 /// when merging implicit instantiations of class templates across modules.
1014 llvm::DenseMap<DeclContext *, DeclContext *> MergedDeclContexts;
1016 /// \brief A mapping from canonical declarations of enums to their canonical
1017 /// definitions. Only populated when using modules in C++.
1018 llvm::DenseMap<EnumDecl *, EnumDecl *> EnumDefinitions;
1020 /// \brief When reading a Stmt tree, Stmt operands are placed in this stack.
1021 SmallVector<Stmt *, 16> StmtStack;
1023 /// \brief What kind of records we are reading.
1025 Read_None, Read_Decl, Read_Type, Read_Stmt
1028 /// \brief What kind of records we are reading.
1029 ReadingKind ReadingKind;
1031 /// \brief RAII object to change the reading kind.
1032 class ReadingKindTracker {
1034 enum ReadingKind PrevKind;
1036 ReadingKindTracker(const ReadingKindTracker &) = delete;
1037 void operator=(const ReadingKindTracker &) = delete;
1040 ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
1041 : Reader(reader), PrevKind(Reader.ReadingKind) {
1042 Reader.ReadingKind = newKind;
1045 ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; }
1048 /// \brief RAII object to mark the start of processing updates.
1049 class ProcessingUpdatesRAIIObj {
1053 ProcessingUpdatesRAIIObj(const ProcessingUpdatesRAIIObj &) = delete;
1054 void operator=(const ProcessingUpdatesRAIIObj &) = delete;
1057 ProcessingUpdatesRAIIObj(ASTReader &reader)
1058 : Reader(reader), PrevState(Reader.ProcessingUpdateRecords) {
1059 Reader.ProcessingUpdateRecords = true;
1062 ~ProcessingUpdatesRAIIObj() { Reader.ProcessingUpdateRecords = PrevState; }
1065 /// \brief Suggested contents of the predefines buffer, after this
1066 /// PCH file has been processed.
1068 /// In most cases, this string will be empty, because the predefines
1069 /// buffer computed to build the PCH file will be identical to the
1070 /// predefines buffer computed from the command line. However, when
1071 /// there are differences that the PCH reader can work around, this
1072 /// predefines buffer may contain additional definitions.
1073 std::string SuggestedPredefines;
1075 /// \brief Reads a statement from the specified cursor.
1076 Stmt *ReadStmtFromStream(ModuleFile &F);
1078 struct InputFileInfo {
1079 std::string Filename;
1086 /// \brief Reads the stored information about an input file.
1087 InputFileInfo readInputFileInfo(ModuleFile &F, unsigned ID);
1089 /// \brief Retrieve the file entry and 'overridden' bit for an input
1090 /// file in the given module file.
1091 serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
1092 bool Complain = true);
1095 void ResolveImportedPath(ModuleFile &M, std::string &Filename);
1096 static void ResolveImportedPath(std::string &Filename, StringRef Prefix);
1098 /// \brief Returns the first key declaration for the given declaration. This
1099 /// is one that is formerly-canonical (or still canonical) and whose module
1100 /// did not import any other key declaration of the entity.
1101 Decl *getKeyDeclaration(Decl *D) {
1102 D = D->getCanonicalDecl();
1103 if (D->isFromASTFile())
1106 auto I = KeyDecls.find(D);
1107 if (I == KeyDecls.end() || I->second.empty())
1109 return GetExistingDecl(I->second[0]);
1111 const Decl *getKeyDeclaration(const Decl *D) {
1112 return getKeyDeclaration(const_cast<Decl*>(D));
1115 /// \brief Run a callback on each imported key declaration of \p D.
1116 template <typename Fn>
1117 void forEachImportedKeyDecl(const Decl *D, Fn Visit) {
1118 D = D->getCanonicalDecl();
1119 if (D->isFromASTFile())
1122 auto It = KeyDecls.find(const_cast<Decl*>(D));
1123 if (It != KeyDecls.end())
1124 for (auto ID : It->second)
1125 Visit(GetExistingDecl(ID));
1128 /// \brief Get the loaded lookup tables for \p Primary, if any.
1129 const serialization::reader::DeclContextLookupTable *
1130 getLoadedLookupTables(DeclContext *Primary) const;
1133 struct ImportedModule {
1135 ModuleFile *ImportedBy;
1136 SourceLocation ImportLoc;
1138 ImportedModule(ModuleFile *Mod,
1139 ModuleFile *ImportedBy,
1140 SourceLocation ImportLoc)
1141 : Mod(Mod), ImportedBy(ImportedBy), ImportLoc(ImportLoc) { }
1144 ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
1145 SourceLocation ImportLoc, ModuleFile *ImportedBy,
1146 SmallVectorImpl<ImportedModule> &Loaded,
1147 off_t ExpectedSize, time_t ExpectedModTime,
1148 serialization::ASTFileSignature ExpectedSignature,
1149 unsigned ClientLoadCapabilities);
1150 ASTReadResult ReadControlBlock(ModuleFile &F,
1151 SmallVectorImpl<ImportedModule> &Loaded,
1152 const ModuleFile *ImportedBy,
1153 unsigned ClientLoadCapabilities);
1154 static ASTReadResult ReadOptionsBlock(
1155 llvm::BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
1156 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
1157 std::string &SuggestedPredefines);
1158 ASTReadResult ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities);
1159 ASTReadResult ReadExtensionBlock(ModuleFile &F);
1160 bool ParseLineTable(ModuleFile &F, const RecordData &Record);
1161 bool ReadSourceManagerBlock(ModuleFile &F);
1162 llvm::BitstreamCursor &SLocCursorForID(int ID);
1163 SourceLocation getImportLocation(ModuleFile *F);
1164 ASTReadResult ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
1165 const ModuleFile *ImportedBy,
1166 unsigned ClientLoadCapabilities);
1167 ASTReadResult ReadSubmoduleBlock(ModuleFile &F,
1168 unsigned ClientLoadCapabilities);
1169 static bool ParseLanguageOptions(const RecordData &Record, bool Complain,
1170 ASTReaderListener &Listener,
1171 bool AllowCompatibleDifferences);
1172 static bool ParseTargetOptions(const RecordData &Record, bool Complain,
1173 ASTReaderListener &Listener,
1174 bool AllowCompatibleDifferences);
1175 static bool ParseDiagnosticOptions(const RecordData &Record, bool Complain,
1176 ASTReaderListener &Listener);
1177 static bool ParseFileSystemOptions(const RecordData &Record, bool Complain,
1178 ASTReaderListener &Listener);
1179 static bool ParseHeaderSearchOptions(const RecordData &Record, bool Complain,
1180 ASTReaderListener &Listener);
1181 static bool ParsePreprocessorOptions(const RecordData &Record, bool Complain,
1182 ASTReaderListener &Listener,
1183 std::string &SuggestedPredefines);
1185 struct RecordLocation {
1186 RecordLocation(ModuleFile *M, uint64_t O)
1187 : F(M), Offset(O) {}
1192 QualType readTypeRecord(unsigned Index);
1193 void readExceptionSpec(ModuleFile &ModuleFile,
1194 SmallVectorImpl<QualType> &ExceptionStorage,
1195 FunctionProtoType::ExceptionSpecInfo &ESI,
1196 const RecordData &Record, unsigned &Index);
1197 RecordLocation TypeCursorForIndex(unsigned Index);
1198 void LoadedDecl(unsigned Index, Decl *D);
1199 Decl *ReadDeclRecord(serialization::DeclID ID);
1200 void markIncompleteDeclChain(Decl *Canon);
1202 /// \brief Returns the most recent declaration of a declaration (which must be
1203 /// of a redeclarable kind) that is either local or has already been loaded
1204 /// merged into its redecl chain.
1205 Decl *getMostRecentExistingDecl(Decl *D);
1207 RecordLocation DeclCursorForID(serialization::DeclID ID,
1208 SourceLocation &Location);
1209 void loadDeclUpdateRecords(serialization::DeclID ID, Decl *D);
1210 void loadPendingDeclChain(Decl *D, uint64_t LocalOffset);
1211 void loadObjCCategories(serialization::GlobalDeclID ID, ObjCInterfaceDecl *D,
1212 unsigned PreviousGeneration = 0);
1214 RecordLocation getLocalBitOffset(uint64_t GlobalOffset);
1215 uint64_t getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset);
1217 /// \brief Returns the first preprocessed entity ID that begins or ends after
1219 serialization::PreprocessedEntityID
1220 findPreprocessedEntity(SourceLocation Loc, bool EndsAfter) const;
1222 /// \brief Find the next module that contains entities and return the ID
1223 /// of the first entry.
1225 /// \param SLocMapI points at a chunk of a module that contains no
1226 /// preprocessed entities or the entities it contains are not the
1227 /// ones we are looking for.
1228 serialization::PreprocessedEntityID
1229 findNextPreprocessedEntity(
1230 GlobalSLocOffsetMapType::const_iterator SLocMapI) const;
1232 /// \brief Returns (ModuleFile, Local index) pair for \p GlobalIndex of a
1233 /// preprocessed entity.
1234 std::pair<ModuleFile *, unsigned>
1235 getModulePreprocessedEntity(unsigned GlobalIndex);
1237 /// \brief Returns (begin, end) pair for the preprocessed entities of a
1238 /// particular module.
1239 llvm::iterator_range<PreprocessingRecord::iterator>
1240 getModulePreprocessedEntities(ModuleFile &Mod) const;
1242 class ModuleDeclIterator
1243 : public llvm::iterator_adaptor_base<
1244 ModuleDeclIterator, const serialization::LocalDeclID *,
1245 std::random_access_iterator_tag, const Decl *, ptrdiff_t,
1246 const Decl *, const Decl *> {
1251 ModuleDeclIterator()
1252 : iterator_adaptor_base(nullptr), Reader(nullptr), Mod(nullptr) {}
1254 ModuleDeclIterator(ASTReader *Reader, ModuleFile *Mod,
1255 const serialization::LocalDeclID *Pos)
1256 : iterator_adaptor_base(Pos), Reader(Reader), Mod(Mod) {}
1258 value_type operator*() const {
1259 return Reader->GetDecl(Reader->getGlobalDeclID(*Mod, *I));
1261 value_type operator->() const { return **this; }
1263 bool operator==(const ModuleDeclIterator &RHS) const {
1264 assert(Reader == RHS.Reader && Mod == RHS.Mod);
1269 llvm::iterator_range<ModuleDeclIterator>
1270 getModuleFileLevelDecls(ModuleFile &Mod);
1272 void PassInterestingDeclsToConsumer();
1273 void PassInterestingDeclToConsumer(Decl *D);
1275 void finishPendingActions();
1276 void diagnoseOdrViolations();
1278 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
1280 void addPendingDeclContextInfo(Decl *D,
1281 serialization::GlobalDeclID SemaDC,
1282 serialization::GlobalDeclID LexicalDC) {
1284 PendingDeclContextInfo Info = { D, SemaDC, LexicalDC };
1285 PendingDeclContextInfos.push_back(Info);
1288 /// \brief Produce an error diagnostic and return true.
1290 /// This routine should only be used for fatal errors that have to
1291 /// do with non-routine failures (e.g., corrupted AST file).
1292 void Error(StringRef Msg);
1293 void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
1294 StringRef Arg2 = StringRef());
1296 ASTReader(const ASTReader &) = delete;
1297 void operator=(const ASTReader &) = delete;
1299 /// \brief Load the AST file and validate its contents against the given
1302 /// \param PP the preprocessor associated with the context in which this
1303 /// precompiled header will be loaded.
1305 /// \param Context the AST context that this precompiled header will be
1308 /// \param PCHContainerRdr the PCHContainerOperations to use for loading and
1309 /// creating modules.
1311 /// \param Extensions the list of module file extensions that can be loaded
1312 /// from the AST files.
1314 /// \param isysroot If non-NULL, the system include path specified by the
1315 /// user. This is only used with relocatable PCH files. If non-NULL,
1316 /// a relocatable PCH file will use the default path "/".
1318 /// \param DisableValidation If true, the AST reader will suppress most
1319 /// of its regular consistency checking, allowing the use of precompiled
1320 /// headers that cannot be determined to be compatible.
1322 /// \param AllowASTWithCompilerErrors If true, the AST reader will accept an
1323 /// AST file the was created out of an AST with compiler errors,
1324 /// otherwise it will reject it.
1326 /// \param AllowConfigurationMismatch If true, the AST reader will not check
1327 /// for configuration differences between the AST file and the invocation.
1329 /// \param ValidateSystemInputs If true, the AST reader will validate
1330 /// system input files in addition to user input files. This is only
1331 /// meaningful if \p DisableValidation is false.
1333 /// \param UseGlobalIndex If true, the AST reader will try to load and use
1334 /// the global module index.
1336 /// \param ReadTimer If non-null, a timer used to track the time spent
1338 ASTReader(Preprocessor &PP, ASTContext &Context,
1339 const PCHContainerReader &PCHContainerRdr,
1340 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
1341 StringRef isysroot = "", bool DisableValidation = false,
1342 bool AllowASTWithCompilerErrors = false,
1343 bool AllowConfigurationMismatch = false,
1344 bool ValidateSystemInputs = false, bool UseGlobalIndex = true,
1345 std::unique_ptr<llvm::Timer> ReadTimer = {});
1347 ~ASTReader() override;
1349 SourceManager &getSourceManager() const { return SourceMgr; }
1350 FileManager &getFileManager() const { return FileMgr; }
1351 DiagnosticsEngine &getDiags() const { return Diags; }
1353 /// \brief Flags that indicate what kind of AST loading failures the client
1354 /// of the AST reader can directly handle.
1356 /// When a client states that it can handle a particular kind of failure,
1357 /// the AST reader will not emit errors when producing that kind of failure.
1358 enum LoadFailureCapabilities {
1359 /// \brief The client can't handle any AST loading failures.
1361 /// \brief The client can handle an AST file that cannot load because it
1364 /// \brief The client can handle an AST file that cannot load because it
1365 /// is out-of-date relative to its input files.
1366 ARR_OutOfDate = 0x2,
1367 /// \brief The client can handle an AST file that cannot load because it
1368 /// was built with a different version of Clang.
1369 ARR_VersionMismatch = 0x4,
1370 /// \brief The client can handle an AST file that cannot load because it's
1371 /// compiled configuration doesn't match that of the context it was
1373 ARR_ConfigurationMismatch = 0x8
1376 /// \brief Load the AST file designated by the given file name.
1378 /// \param FileName The name of the AST file to load.
1380 /// \param Type The kind of AST being loaded, e.g., PCH, module, main file,
1383 /// \param ImportLoc the location where the module file will be considered as
1384 /// imported from. For non-module AST types it should be invalid.
1386 /// \param ClientLoadCapabilities The set of client load-failure
1387 /// capabilities, represented as a bitset of the enumerators of
1388 /// LoadFailureCapabilities.
1389 ASTReadResult ReadAST(StringRef FileName, ModuleKind Type,
1390 SourceLocation ImportLoc,
1391 unsigned ClientLoadCapabilities);
1393 /// \brief Make the entities in the given module and any of its (non-explicit)
1394 /// submodules visible to name lookup.
1396 /// \param Mod The module whose names should be made visible.
1398 /// \param NameVisibility The level of visibility to give the names in the
1399 /// module. Visibility can only be increased over time.
1401 /// \param ImportLoc The location at which the import occurs.
1402 void makeModuleVisible(Module *Mod,
1403 Module::NameVisibilityKind NameVisibility,
1404 SourceLocation ImportLoc);
1406 /// \brief Make the names within this set of hidden names visible.
1407 void makeNamesVisible(const HiddenNames &Names, Module *Owner);
1409 /// \brief Take the AST callbacks listener.
1410 std::unique_ptr<ASTReaderListener> takeListener() {
1411 return std::move(Listener);
1414 /// \brief Set the AST callbacks listener.
1415 void setListener(std::unique_ptr<ASTReaderListener> Listener) {
1416 this->Listener = std::move(Listener);
1419 /// \brief Add an AST callback listener.
1421 /// Takes ownership of \p L.
1422 void addListener(std::unique_ptr<ASTReaderListener> L) {
1424 L = llvm::make_unique<ChainedASTReaderListener>(std::move(L),
1425 std::move(Listener));
1426 Listener = std::move(L);
1429 /// RAII object to temporarily add an AST callback listener.
1430 class ListenerScope {
1435 ListenerScope(ASTReader &Reader, std::unique_ptr<ASTReaderListener> L)
1436 : Reader(Reader), Chained(false) {
1437 auto Old = Reader.takeListener();
1440 L = llvm::make_unique<ChainedASTReaderListener>(std::move(L),
1443 Reader.setListener(std::move(L));
1446 auto New = Reader.takeListener();
1448 Reader.setListener(static_cast<ChainedASTReaderListener *>(New.get())
1453 /// \brief Set the AST deserialization listener.
1454 void setDeserializationListener(ASTDeserializationListener *Listener,
1455 bool TakeOwnership = false);
1457 /// \brief Determine whether this AST reader has a global index.
1458 bool hasGlobalIndex() const { return (bool)GlobalIndex; }
1460 /// \brief Return global module index.
1461 GlobalModuleIndex *getGlobalIndex() { return GlobalIndex.get(); }
1463 /// \brief Reset reader for a reload try.
1464 void resetForReload() { TriedLoadingGlobalIndex = false; }
1466 /// \brief Attempts to load the global index.
1468 /// \returns true if loading the global index has failed for any reason.
1469 bool loadGlobalIndex();
1471 /// \brief Determine whether we tried to load the global index, but failed,
1472 /// e.g., because it is out-of-date or does not exist.
1473 bool isGlobalIndexUnavailable() const;
1475 /// \brief Initializes the ASTContext
1476 void InitializeContext();
1478 /// \brief Update the state of Sema after loading some additional modules.
1481 /// \brief Add in-memory (virtual file) buffer.
1482 void addInMemoryBuffer(StringRef &FileName,
1483 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
1484 ModuleMgr.addInMemoryBuffer(FileName, std::move(Buffer));
1487 /// \brief Finalizes the AST reader's state before writing an AST file to
1490 /// This operation may undo temporary state in the AST that should not be
1492 void finalizeForWriting();
1494 /// \brief Retrieve the module manager.
1495 ModuleManager &getModuleManager() { return ModuleMgr; }
1497 /// \brief Retrieve the preprocessor.
1498 Preprocessor &getPreprocessor() const { return PP; }
1500 /// \brief Retrieve the name of the original source file name for the primary
1502 StringRef getOriginalSourceFile() {
1503 return ModuleMgr.getPrimaryModule().OriginalSourceFileName;
1506 /// \brief Retrieve the name of the original source file name directly from
1507 /// the AST file, without actually loading the AST file.
1509 getOriginalSourceFile(const std::string &ASTFileName, FileManager &FileMgr,
1510 const PCHContainerReader &PCHContainerRdr,
1511 DiagnosticsEngine &Diags);
1513 /// \brief Read the control block for the named AST file.
1515 /// \returns true if an error occurred, false otherwise.
1517 readASTFileControlBlock(StringRef Filename, FileManager &FileMgr,
1518 const PCHContainerReader &PCHContainerRdr,
1519 bool FindModuleFileExtensions,
1520 ASTReaderListener &Listener);
1522 /// \brief Determine whether the given AST file is acceptable to load into a
1523 /// translation unit with the given language and target options.
1524 static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
1525 const PCHContainerReader &PCHContainerRdr,
1526 const LangOptions &LangOpts,
1527 const TargetOptions &TargetOpts,
1528 const PreprocessorOptions &PPOpts,
1529 std::string ExistingModuleCachePath);
1531 /// \brief Returns the suggested contents of the predefines buffer,
1532 /// which contains a (typically-empty) subset of the predefines
1533 /// build prior to including the precompiled header.
1534 const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
1536 /// \brief Read a preallocated preprocessed entity from the external source.
1538 /// \returns null if an error occurred that prevented the preprocessed
1539 /// entity from being loaded.
1540 PreprocessedEntity *ReadPreprocessedEntity(unsigned Index) override;
1542 /// \brief Returns a pair of [Begin, End) indices of preallocated
1543 /// preprocessed entities that \p Range encompasses.
1544 std::pair<unsigned, unsigned>
1545 findPreprocessedEntitiesInRange(SourceRange Range) override;
1547 /// \brief Optionally returns true or false if the preallocated preprocessed
1548 /// entity with index \p Index came from file \p FID.
1549 Optional<bool> isPreprocessedEntityInFileID(unsigned Index,
1550 FileID FID) override;
1552 /// \brief Read the header file information for the given file entry.
1553 HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) override;
1555 void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag);
1557 /// \brief Returns the number of source locations found in the chain.
1558 unsigned getTotalNumSLocs() const {
1559 return TotalNumSLocEntries;
1562 /// \brief Returns the number of identifiers found in the chain.
1563 unsigned getTotalNumIdentifiers() const {
1564 return static_cast<unsigned>(IdentifiersLoaded.size());
1567 /// \brief Returns the number of macros found in the chain.
1568 unsigned getTotalNumMacros() const {
1569 return static_cast<unsigned>(MacrosLoaded.size());
1572 /// \brief Returns the number of types found in the chain.
1573 unsigned getTotalNumTypes() const {
1574 return static_cast<unsigned>(TypesLoaded.size());
1577 /// \brief Returns the number of declarations found in the chain.
1578 unsigned getTotalNumDecls() const {
1579 return static_cast<unsigned>(DeclsLoaded.size());
1582 /// \brief Returns the number of submodules known.
1583 unsigned getTotalNumSubmodules() const {
1584 return static_cast<unsigned>(SubmodulesLoaded.size());
1587 /// \brief Returns the number of selectors found in the chain.
1588 unsigned getTotalNumSelectors() const {
1589 return static_cast<unsigned>(SelectorsLoaded.size());
1592 /// \brief Returns the number of preprocessed entities known to the AST
1594 unsigned getTotalNumPreprocessedEntities() const {
1595 unsigned Result = 0;
1596 for (ModuleConstIterator I = ModuleMgr.begin(),
1597 E = ModuleMgr.end(); I != E; ++I) {
1598 Result += (*I)->NumPreprocessedEntities;
1604 /// \brief Reads a TemplateArgumentLocInfo appropriate for the
1605 /// given TemplateArgument kind.
1606 TemplateArgumentLocInfo
1607 GetTemplateArgumentLocInfo(ModuleFile &F, TemplateArgument::ArgKind Kind,
1608 const RecordData &Record, unsigned &Idx);
1610 /// \brief Reads a TemplateArgumentLoc.
1612 ReadTemplateArgumentLoc(ModuleFile &F,
1613 const RecordData &Record, unsigned &Idx);
1615 const ASTTemplateArgumentListInfo*
1616 ReadASTTemplateArgumentListInfo(ModuleFile &F,
1617 const RecordData &Record, unsigned &Index);
1619 /// \brief Reads a declarator info from the given record.
1620 TypeSourceInfo *GetTypeSourceInfo(ModuleFile &F,
1621 const RecordData &Record, unsigned &Idx);
1623 /// \brief Resolve a type ID into a type, potentially building a new
1625 QualType GetType(serialization::TypeID ID);
1627 /// \brief Resolve a local type ID within a given AST file into a type.
1628 QualType getLocalType(ModuleFile &F, unsigned LocalID);
1630 /// \brief Map a local type ID within a given AST file into a global type ID.
1631 serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const;
1633 /// \brief Read a type from the current position in the given record, which
1634 /// was read from the given AST file.
1635 QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) {
1636 if (Idx >= Record.size())
1639 return getLocalType(F, Record[Idx++]);
1642 /// \brief Map from a local declaration ID within a given module to a
1643 /// global declaration ID.
1644 serialization::DeclID getGlobalDeclID(ModuleFile &F,
1645 serialization::LocalDeclID LocalID) const;
1647 /// \brief Returns true if global DeclID \p ID originated from module \p M.
1648 bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const;
1650 /// \brief Retrieve the module file that owns the given declaration, or NULL
1651 /// if the declaration is not from a module file.
1652 ModuleFile *getOwningModuleFile(const Decl *D);
1654 /// \brief Get the best name we know for the module that owns the given
1655 /// declaration, or an empty string if the declaration is not from a module.
1656 std::string getOwningModuleNameForDiagnostic(const Decl *D);
1658 /// \brief Returns the source location for the decl \p ID.
1659 SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID);
1661 /// \brief Resolve a declaration ID into a declaration, potentially
1662 /// building a new declaration.
1663 Decl *GetDecl(serialization::DeclID ID);
1664 Decl *GetExternalDecl(uint32_t ID) override;
1666 /// \brief Resolve a declaration ID into a declaration. Return 0 if it's not
1667 /// been loaded yet.
1668 Decl *GetExistingDecl(serialization::DeclID ID);
1670 /// \brief Reads a declaration with the given local ID in the given module.
1671 Decl *GetLocalDecl(ModuleFile &F, uint32_t LocalID) {
1672 return GetDecl(getGlobalDeclID(F, LocalID));
1675 /// \brief Reads a declaration with the given local ID in the given module.
1677 /// \returns The requested declaration, casted to the given return type.
1678 template<typename T>
1679 T *GetLocalDeclAs(ModuleFile &F, uint32_t LocalID) {
1680 return cast_or_null<T>(GetLocalDecl(F, LocalID));
1683 /// \brief Map a global declaration ID into the declaration ID used to
1684 /// refer to this declaration within the given module fule.
1686 /// \returns the global ID of the given declaration as known in the given
1688 serialization::DeclID
1689 mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
1690 serialization::DeclID GlobalID);
1692 /// \brief Reads a declaration ID from the given position in a record in the
1695 /// \returns The declaration ID read from the record, adjusted to a global ID.
1696 serialization::DeclID ReadDeclID(ModuleFile &F, const RecordData &Record,
1699 /// \brief Reads a declaration from the given position in a record in the
1701 Decl *ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I) {
1702 return GetDecl(ReadDeclID(F, R, I));
1705 /// \brief Reads a declaration from the given position in a record in the
1708 /// \returns The declaration read from this location, casted to the given
1710 template<typename T>
1711 T *ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I) {
1712 return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
1715 /// \brief If any redeclarations of \p D have been imported since it was
1716 /// last checked, this digs out those redeclarations and adds them to the
1717 /// redeclaration chain for \p D.
1718 void CompleteRedeclChain(const Decl *D) override;
1720 CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override;
1722 /// \brief Resolve the offset of a statement into a statement.
1724 /// This operation will read a new statement from the external
1725 /// source each time it is called, and is meant to be used via a
1726 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1727 Stmt *GetExternalDeclStmt(uint64_t Offset) override;
1729 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1730 /// specified cursor. Read the abbreviations that are at the top of the block
1731 /// and then leave the cursor pointing into the block.
1732 static bool ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID);
1734 /// \brief Finds all the visible declarations with a given name.
1735 /// The current implementation of this method just loads the entire
1736 /// lookup table as unmaterialized references.
1737 bool FindExternalVisibleDeclsByName(const DeclContext *DC,
1738 DeclarationName Name) override;
1740 /// \brief Read all of the declarations lexically stored in a
1741 /// declaration context.
1743 /// \param DC The declaration context whose declarations will be
1746 /// \param IsKindWeWant A predicate indicating which declaration kinds
1747 /// we are interested in.
1749 /// \param Decls Vector that will contain the declarations loaded
1750 /// from the external source. The caller is responsible for merging
1751 /// these declarations with any declarations already stored in the
1752 /// declaration context.
1754 FindExternalLexicalDecls(const DeclContext *DC,
1755 llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
1756 SmallVectorImpl<Decl *> &Decls) override;
1758 /// \brief Get the decls that are contained in a file in the Offset/Length
1759 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
1761 void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
1762 SmallVectorImpl<Decl *> &Decls) override;
1764 /// \brief Notify ASTReader that we started deserialization of
1765 /// a decl or type so until FinishedDeserializing is called there may be
1766 /// decls that are initializing. Must be paired with FinishedDeserializing.
1767 void StartedDeserializing() override;
1769 /// \brief Notify ASTReader that we finished the deserialization of
1770 /// a decl or type. Must be paired with StartedDeserializing.
1771 void FinishedDeserializing() override;
1773 /// \brief Function that will be invoked when we begin parsing a new
1774 /// translation unit involving this external AST source.
1776 /// This function will provide all of the external definitions to
1777 /// the ASTConsumer.
1778 void StartTranslationUnit(ASTConsumer *Consumer) override;
1780 /// \brief Print some statistics about AST usage.
1781 void PrintStats() override;
1783 /// \brief Dump information about the AST reader to standard error.
1786 /// Return the amount of memory used by memory buffers, breaking down
1787 /// by heap-backed versus mmap'ed memory.
1788 void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override;
1790 /// \brief Initialize the semantic source with the Sema instance
1791 /// being used to perform semantic analysis on the abstract syntax
1793 void InitializeSema(Sema &S) override;
1795 /// \brief Inform the semantic consumer that Sema is no longer available.
1796 void ForgetSema() override { SemaObj = nullptr; }
1798 /// \brief Retrieve the IdentifierInfo for the named identifier.
1800 /// This routine builds a new IdentifierInfo for the given identifier. If any
1801 /// declarations with this name are visible from translation unit scope, their
1802 /// declarations will be deserialized and introduced into the declaration
1803 /// chain of the identifier.
1804 IdentifierInfo *get(StringRef Name) override;
1806 /// \brief Retrieve an iterator into the set of all identifiers
1807 /// in all loaded AST files.
1808 IdentifierIterator *getIdentifiers() override;
1810 /// \brief Load the contents of the global method pool for a given
1812 void ReadMethodPool(Selector Sel) override;
1814 /// Load the contents of the global method pool for a given
1815 /// selector if necessary.
1816 void updateOutOfDateSelector(Selector Sel) override;
1818 /// \brief Load the set of namespaces that are known to the external source,
1819 /// which will be used during typo correction.
1820 void ReadKnownNamespaces(
1821 SmallVectorImpl<NamespaceDecl *> &Namespaces) override;
1823 void ReadUndefinedButUsed(
1824 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) override;
1826 void ReadMismatchingDeleteExpressions(llvm::MapVector<
1827 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
1830 void ReadTentativeDefinitions(
1831 SmallVectorImpl<VarDecl *> &TentativeDefs) override;
1833 void ReadUnusedFileScopedDecls(
1834 SmallVectorImpl<const DeclaratorDecl *> &Decls) override;
1836 void ReadDelegatingConstructors(
1837 SmallVectorImpl<CXXConstructorDecl *> &Decls) override;
1839 void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) override;
1841 void ReadUnusedLocalTypedefNameCandidates(
1842 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) override;
1844 void ReadReferencedSelectors(
1845 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) override;
1847 void ReadWeakUndeclaredIdentifiers(
1848 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WI) override;
1850 void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) override;
1852 void ReadPendingInstantiations(
1853 SmallVectorImpl<std::pair<ValueDecl *,
1854 SourceLocation> > &Pending) override;
1856 void ReadLateParsedTemplates(
1857 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap)
1860 /// \brief Load a selector from disk, registering its ID if it exists.
1861 void LoadSelector(Selector Sel);
1863 void SetIdentifierInfo(unsigned ID, IdentifierInfo *II);
1864 void SetGloballyVisibleDecls(IdentifierInfo *II,
1865 const SmallVectorImpl<uint32_t> &DeclIDs,
1866 SmallVectorImpl<Decl *> *Decls = nullptr);
1868 /// \brief Report a diagnostic.
1869 DiagnosticBuilder Diag(unsigned DiagID);
1871 /// \brief Report a diagnostic.
1872 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
1874 IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID);
1876 IdentifierInfo *GetIdentifierInfo(ModuleFile &M, const RecordData &Record,
1878 return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++]));
1881 IdentifierInfo *GetIdentifier(serialization::IdentifierID ID) override {
1882 // Note that we are loading an identifier.
1883 Deserializing AnIdentifier(this);
1885 return DecodeIdentifierInfo(ID);
1888 IdentifierInfo *getLocalIdentifier(ModuleFile &M, unsigned LocalID);
1890 serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M,
1893 void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo);
1895 /// \brief Retrieve the macro with the given ID.
1896 MacroInfo *getMacro(serialization::MacroID ID);
1898 /// \brief Retrieve the global macro ID corresponding to the given local
1899 /// ID within the given module file.
1900 serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID);
1902 /// \brief Read the source location entry with index ID.
1903 bool ReadSLocEntry(int ID) override;
1905 /// \brief Retrieve the module import location and module name for the
1906 /// given source manager entry ID.
1907 std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) override;
1909 /// \brief Retrieve the global submodule ID given a module and its local ID
1911 serialization::SubmoduleID
1912 getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID);
1914 /// \brief Retrieve the submodule that corresponds to a global submodule ID.
1916 Module *getSubmodule(serialization::SubmoduleID GlobalID);
1918 /// \brief Retrieve the module that corresponds to the given module ID.
1920 /// Note: overrides method in ExternalASTSource
1921 Module *getModule(unsigned ID) override;
1923 /// \brief Retrieve the module file with a given local ID within the specified
1925 ModuleFile *getLocalModuleFile(ModuleFile &M, unsigned ID);
1927 /// \brief Get an ID for the given module file.
1928 unsigned getModuleFileID(ModuleFile *M);
1930 /// \brief Return a descriptor for the corresponding module.
1931 llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID) override;
1933 /// \brief Retrieve a selector from the given module with its local ID
1935 Selector getLocalSelector(ModuleFile &M, unsigned LocalID);
1937 Selector DecodeSelector(serialization::SelectorID Idx);
1939 Selector GetExternalSelector(serialization::SelectorID ID) override;
1940 uint32_t GetNumExternalSelectors() override;
1942 Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) {
1943 return getLocalSelector(M, Record[Idx++]);
1946 /// \brief Retrieve the global selector ID that corresponds to this
1947 /// the local selector ID in a given module.
1948 serialization::SelectorID getGlobalSelectorID(ModuleFile &F,
1949 unsigned LocalID) const;
1951 /// \brief Read a declaration name.
1952 DeclarationName ReadDeclarationName(ModuleFile &F,
1953 const RecordData &Record, unsigned &Idx);
1954 void ReadDeclarationNameLoc(ModuleFile &F,
1955 DeclarationNameLoc &DNLoc, DeclarationName Name,
1956 const RecordData &Record, unsigned &Idx);
1957 void ReadDeclarationNameInfo(ModuleFile &F, DeclarationNameInfo &NameInfo,
1958 const RecordData &Record, unsigned &Idx);
1960 void ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
1961 const RecordData &Record, unsigned &Idx);
1963 NestedNameSpecifier *ReadNestedNameSpecifier(ModuleFile &F,
1964 const RecordData &Record,
1967 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(ModuleFile &F,
1968 const RecordData &Record,
1971 /// \brief Read a template name.
1972 TemplateName ReadTemplateName(ModuleFile &F, const RecordData &Record,
1975 /// \brief Read a template argument.
1976 TemplateArgument ReadTemplateArgument(ModuleFile &F, const RecordData &Record,
1978 bool Canonicalize = false);
1980 /// \brief Read a template parameter list.
1981 TemplateParameterList *ReadTemplateParameterList(ModuleFile &F,
1982 const RecordData &Record,
1985 /// \brief Read a template argument array.
1986 void ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
1987 ModuleFile &F, const RecordData &Record,
1988 unsigned &Idx, bool Canonicalize = false);
1990 /// \brief Read a UnresolvedSet structure.
1991 void ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
1992 const RecordData &Record, unsigned &Idx);
1994 /// \brief Read a C++ base specifier.
1995 CXXBaseSpecifier ReadCXXBaseSpecifier(ModuleFile &F,
1996 const RecordData &Record,unsigned &Idx);
1998 /// \brief Read a CXXCtorInitializer array.
1999 CXXCtorInitializer **
2000 ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
2003 /// \brief Read the contents of a CXXCtorInitializer array.
2004 CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset) override;
2006 /// \brief Read a source location from raw form and return it in its
2007 /// originating module file's source location space.
2008 SourceLocation ReadUntranslatedSourceLocation(uint32_t Raw) const {
2009 return SourceLocation::getFromRawEncoding((Raw >> 1) | (Raw << 31));
2012 /// \brief Read a source location from raw form.
2013 SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, uint32_t Raw) const {
2014 SourceLocation Loc = ReadUntranslatedSourceLocation(Raw);
2015 return TranslateSourceLocation(ModuleFile, Loc);
2018 /// \brief Translate a source location from another module file's source
2019 /// location space into ours.
2020 SourceLocation TranslateSourceLocation(ModuleFile &ModuleFile,
2021 SourceLocation Loc) const {
2022 assert(ModuleFile.SLocRemap.find(Loc.getOffset()) !=
2023 ModuleFile.SLocRemap.end() &&
2024 "Cannot find offset to remap.");
2025 int Remap = ModuleFile.SLocRemap.find(Loc.getOffset())->second;
2026 return Loc.getLocWithOffset(Remap);
2029 /// \brief Read a source location.
2030 SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
2031 const RecordDataImpl &Record,
2033 return ReadSourceLocation(ModuleFile, Record[Idx++]);
2036 /// \brief Read a source range.
2037 SourceRange ReadSourceRange(ModuleFile &F,
2038 const RecordData &Record, unsigned &Idx);
2040 /// \brief Read an integral value
2041 llvm::APInt ReadAPInt(const RecordData &Record, unsigned &Idx);
2043 /// \brief Read a signed integral value
2044 llvm::APSInt ReadAPSInt(const RecordData &Record, unsigned &Idx);
2046 /// \brief Read a floating-point value
2047 llvm::APFloat ReadAPFloat(const RecordData &Record,
2048 const llvm::fltSemantics &Sem, unsigned &Idx);
2050 // \brief Read a string
2051 static std::string ReadString(const RecordData &Record, unsigned &Idx);
2053 // \brief Read a path
2054 std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx);
2056 /// \brief Read a version tuple.
2057 static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
2059 CXXTemporary *ReadCXXTemporary(ModuleFile &F, const RecordData &Record,
2062 /// \brief Reads attributes from the current stream position.
2063 void ReadAttributes(ModuleFile &F, AttrVec &Attrs,
2064 const RecordData &Record, unsigned &Idx);
2066 /// \brief Reads a statement.
2067 Stmt *ReadStmt(ModuleFile &F);
2069 /// \brief Reads an expression.
2070 Expr *ReadExpr(ModuleFile &F);
2072 /// \brief Reads a sub-statement operand during statement reading.
2073 Stmt *ReadSubStmt() {
2074 assert(ReadingKind == Read_Stmt &&
2075 "Should be called only during statement reading!");
2076 // Subexpressions are stored from last to first, so the next Stmt we need
2077 // is at the back of the stack.
2078 assert(!StmtStack.empty() && "Read too many sub-statements!");
2079 return StmtStack.pop_back_val();
2082 /// \brief Reads a sub-expression operand during statement reading.
2083 Expr *ReadSubExpr();
2085 /// \brief Reads a token out of a record.
2086 Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx);
2088 /// \brief Reads the macro record located at the given offset.
2089 MacroInfo *ReadMacroRecord(ModuleFile &F, uint64_t Offset);
2091 /// \brief Determine the global preprocessed entity ID that corresponds to
2092 /// the given local ID within the given module.
2093 serialization::PreprocessedEntityID
2094 getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const;
2096 /// \brief Add a macro to deserialize its macro directive history.
2098 /// \param II The name of the macro.
2099 /// \param M The module file.
2100 /// \param MacroDirectivesOffset Offset of the serialized macro directive
2102 void addPendingMacro(IdentifierInfo *II, ModuleFile *M,
2103 uint64_t MacroDirectivesOffset);
2105 /// \brief Read the set of macros defined by this external macro source.
2106 void ReadDefinedMacros() override;
2108 /// \brief Update an out-of-date identifier.
2109 void updateOutOfDateIdentifier(IdentifierInfo &II) override;
2111 /// \brief Note that this identifier is up-to-date.
2112 void markIdentifierUpToDate(IdentifierInfo *II);
2114 /// \brief Load all external visible decls in the given DeclContext.
2115 void completeVisibleDeclsMap(const DeclContext *DC) override;
2117 /// \brief Retrieve the AST context that this AST reader supplements.
2118 ASTContext &getContext() { return Context; }
2120 // \brief Contains the IDs for declarations that were requested before we have
2121 // access to a Sema object.
2122 SmallVector<uint64_t, 16> PreloadedDeclIDs;
2124 /// \brief Retrieve the semantic analysis object used to analyze the
2125 /// translation unit in which the precompiled header is being
2127 Sema *getSema() { return SemaObj; }
2129 /// \brief Get the identifier resolver used for name lookup / updates
2130 /// in the translation unit scope. We have one of these even if we don't
2131 /// have a Sema object.
2132 IdentifierResolver &getIdResolver();
2134 /// \brief Retrieve the identifier table associated with the
2136 IdentifierTable &getIdentifierTable();
2138 /// \brief Record that the given ID maps to the given switch-case
2140 void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
2142 /// \brief Retrieve the switch-case statement with the given ID.
2143 SwitchCase *getSwitchCaseWithID(unsigned ID);
2145 void ClearSwitchCaseIDs();
2147 /// \brief Cursors for comments blocks.
2148 SmallVector<std::pair<llvm::BitstreamCursor,
2149 serialization::ModuleFile *>, 8> CommentsCursors;
2151 /// \brief Loads comments ranges.
2152 void ReadComments() override;
2154 bool isProcessingUpdateRecords() { return ProcessingUpdateRecords; }
2157 /// \brief Helper class that saves the current stream position and
2158 /// then restores it when destroyed.
2159 struct SavedStreamPosition {
2160 explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor)
2161 : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) { }
2163 ~SavedStreamPosition() {
2164 Cursor.JumpToBit(Offset);
2168 llvm::BitstreamCursor &Cursor;
2172 inline void PCHValidator::Error(const char *Msg) {
2176 } // end namespace clang