clang 20.0.0git
ASTReader.h
Go to the documentation of this file.
1//===- ASTReader.h - AST File Reader ----------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the ASTReader class, which reads AST files.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_SERIALIZATION_ASTREADER_H
14#define LLVM_CLANG_SERIALIZATION_ASTREADER_H
15
16#include "clang/AST/Type.h"
22#include "clang/Basic/Version.h"
29#include "clang/Sema/Sema.h"
36#include "llvm/ADT/ArrayRef.h"
37#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/DenseSet.h"
39#include "llvm/ADT/IntrusiveRefCntPtr.h"
40#include "llvm/ADT/MapVector.h"
41#include "llvm/ADT/PagedVector.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/SetVector.h"
44#include "llvm/ADT/SmallPtrSet.h"
45#include "llvm/ADT/SmallVector.h"
46#include "llvm/ADT/StringMap.h"
47#include "llvm/ADT/StringRef.h"
48#include "llvm/ADT/iterator.h"
49#include "llvm/ADT/iterator_range.h"
50#include "llvm/Bitstream/BitstreamReader.h"
51#include "llvm/Support/MemoryBuffer.h"
52#include "llvm/Support/Timer.h"
53#include "llvm/Support/VersionTuple.h"
54#include <cassert>
55#include <cstddef>
56#include <cstdint>
57#include <ctime>
58#include <deque>
59#include <memory>
60#include <optional>
61#include <set>
62#include <string>
63#include <utility>
64#include <vector>
65
66namespace clang {
67
68class ASTConsumer;
69class ASTContext;
70class ASTDeserializationListener;
71class ASTReader;
72class ASTRecordReader;
73class CXXTemporary;
74class Decl;
75class DeclarationName;
76class DeclaratorDecl;
77class DeclContext;
78class EnumDecl;
79class Expr;
80class FieldDecl;
81class FileEntry;
82class FileManager;
83class FileSystemOptions;
84class FunctionDecl;
85class GlobalModuleIndex;
86struct HeaderFileInfo;
87class HeaderSearchOptions;
88class LangOptions;
89class MacroInfo;
90class InMemoryModuleCache;
91class NamedDecl;
92class NamespaceDecl;
93class ObjCCategoryDecl;
94class ObjCInterfaceDecl;
95class PCHContainerReader;
96class Preprocessor;
97class PreprocessorOptions;
98class Sema;
99class SourceManager;
100class Stmt;
101class SwitchCase;
102class TargetOptions;
103class Token;
104class TypedefNameDecl;
105class ValueDecl;
106class VarDecl;
107
108/// Abstract interface for callback invocations by the ASTReader.
109///
110/// While reading an AST file, the ASTReader will call the methods of the
111/// listener to pass on specific information. Some of the listener methods can
112/// return true to indicate to the ASTReader that the information (and
113/// consequently the AST file) is invalid.
115public:
117
118 /// Receives the full Clang version information.
119 ///
120 /// \returns true to indicate that the version is invalid. Subclasses should
121 /// generally defer to this implementation.
122 virtual bool ReadFullVersionInformation(StringRef FullVersion) {
123 return FullVersion != getClangFullRepositoryVersion();
124 }
125
126 virtual void ReadModuleName(StringRef ModuleName) {}
127 virtual void ReadModuleMapFile(StringRef ModuleMapPath) {}
128
129 /// Receives the language options.
130 ///
131 /// \returns true to indicate the options are invalid or false otherwise.
132 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
133 bool Complain,
134 bool AllowCompatibleDifferences) {
135 return false;
136 }
137
138 /// Receives the target options.
139 ///
140 /// \returns true to indicate the target options are invalid, or false
141 /// otherwise.
142 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
143 bool AllowCompatibleDifferences) {
144 return false;
145 }
146
147 /// Receives the diagnostic options.
148 ///
149 /// \returns true to indicate the diagnostic options are invalid, or false
150 /// otherwise.
151 virtual bool
153 bool Complain) {
154 return false;
155 }
156
157 /// Receives the file system options.
158 ///
159 /// \returns true to indicate the file system options are invalid, or false
160 /// otherwise.
161 virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
162 bool Complain) {
163 return false;
164 }
165
166 /// Receives the header search options.
167 ///
168 /// \param HSOpts The read header search options. The following fields are
169 /// missing and are reported in ReadHeaderSearchPaths():
170 /// UserEntries, SystemHeaderPrefixes, VFSOverlayFiles.
171 ///
172 /// \returns true to indicate the header search options are invalid, or false
173 /// otherwise.
175 StringRef SpecificModuleCachePath,
176 bool Complain) {
177 return false;
178 }
179
180 /// Receives the header search paths.
181 ///
182 /// \param HSOpts The read header search paths. Only the following fields are
183 /// initialized: UserEntries, SystemHeaderPrefixes,
184 /// VFSOverlayFiles. The rest is reported in
185 /// ReadHeaderSearchOptions().
186 ///
187 /// \returns true to indicate the header search paths are invalid, or false
188 /// otherwise.
189 virtual bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts,
190 bool Complain) {
191 return false;
192 }
193
194 /// Receives the preprocessor options.
195 ///
196 /// \param SuggestedPredefines Can be filled in with the set of predefines
197 /// that are suggested by the preprocessor options. Typically only used when
198 /// loading a precompiled header.
199 ///
200 /// \returns true to indicate the preprocessor options are invalid, or false
201 /// otherwise.
203 bool ReadMacros, bool Complain,
204 std::string &SuggestedPredefines) {
205 return false;
206 }
207
208 /// Receives __COUNTER__ value.
210 unsigned Value) {}
211
212 /// This is called for each AST file loaded.
213 virtual void visitModuleFile(StringRef Filename,
215
216 /// Returns true if this \c ASTReaderListener wants to receive the
217 /// input files of the AST file via \c visitInputFile, false otherwise.
218 virtual bool needsInputFileVisitation() { return false; }
219
220 /// Returns true if this \c ASTReaderListener wants to receive the
221 /// system input files of the AST file via \c visitInputFile, false otherwise.
222 virtual bool needsSystemInputFileVisitation() { return false; }
223
224 /// if \c needsInputFileVisitation returns true, this is called for
225 /// each non-system input file of the AST File. If
226 /// \c needsSystemInputFileVisitation is true, then it is called for all
227 /// system input files as well.
228 ///
229 /// \returns true to continue receiving the next input file, false to stop.
230 virtual bool visitInputFile(StringRef Filename, bool isSystem,
231 bool isOverridden, bool isExplicitModule) {
232 return true;
233 }
234
235 /// Returns true if this \c ASTReaderListener wants to receive the
236 /// imports of the AST file via \c visitImport, false otherwise.
237 virtual bool needsImportVisitation() const { return false; }
238
239 /// If needsImportVisitation returns \c true, this is called for each
240 /// AST file imported by this AST file.
241 virtual void visitImport(StringRef ModuleName, StringRef Filename) {}
242
243 /// Indicates that a particular module file extension has been read.
245 const ModuleFileExtensionMetadata &Metadata) {}
246};
247
248/// Simple wrapper class for chaining listeners.
250 std::unique_ptr<ASTReaderListener> First;
251 std::unique_ptr<ASTReaderListener> Second;
252
253public:
254 /// Takes ownership of \p First and \p Second.
255 ChainedASTReaderListener(std::unique_ptr<ASTReaderListener> First,
256 std::unique_ptr<ASTReaderListener> Second)
257 : First(std::move(First)), Second(std::move(Second)) {}
258
259 std::unique_ptr<ASTReaderListener> takeFirst() { return std::move(First); }
260 std::unique_ptr<ASTReaderListener> takeSecond() { return std::move(Second); }
261
262 bool ReadFullVersionInformation(StringRef FullVersion) override;
263 void ReadModuleName(StringRef ModuleName) override;
264 void ReadModuleMapFile(StringRef ModuleMapPath) override;
265 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
266 bool AllowCompatibleDifferences) override;
267 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
268 bool AllowCompatibleDifferences) override;
270 bool Complain) override;
271 bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
272 bool Complain) override;
273
275 StringRef SpecificModuleCachePath,
276 bool Complain) override;
278 bool ReadMacros, bool Complain,
279 std::string &SuggestedPredefines) override;
280
281 void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
282 bool needsInputFileVisitation() override;
283 bool needsSystemInputFileVisitation() override;
284 void visitModuleFile(StringRef Filename,
286 bool visitInputFile(StringRef Filename, bool isSystem,
287 bool isOverridden, bool isExplicitModule) override;
289 const ModuleFileExtensionMetadata &Metadata) override;
290};
291
292/// ASTReaderListener implementation to validate the information of
293/// the PCH file against an initialized Preprocessor.
295 Preprocessor &PP;
296 ASTReader &Reader;
297
298public:
300 : PP(PP), Reader(Reader) {}
301
302 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
303 bool AllowCompatibleDifferences) override;
304 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
305 bool AllowCompatibleDifferences) override;
307 bool Complain) override;
309 bool ReadMacros, bool Complain,
310 std::string &SuggestedPredefines) override;
312 StringRef SpecificModuleCachePath,
313 bool Complain) override;
314 void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
315};
316
317/// ASTReaderListenter implementation to set SuggestedPredefines of
318/// ASTReader which is required to use a pch file. This is the replacement
319/// of PCHValidator or SimplePCHValidator when using a pch file without
320/// validating it.
322 Preprocessor &PP;
323
324public:
326
328 bool ReadMacros, bool Complain,
329 std::string &SuggestedPredefines) override;
330};
331
332namespace serialization {
333
334class ReadMethodPoolVisitor;
335
336namespace reader {
337
339
340/// The on-disk hash table(s) used for DeclContext name lookup.
342
343} // namespace reader
344
345} // namespace serialization
346
347/// Reads an AST files chain containing the contents of a translation
348/// unit.
349///
350/// The ASTReader class reads bitstreams (produced by the ASTWriter
351/// class) containing the serialized representation of a given
352/// abstract syntax tree and its supporting data structures. An
353/// instance of the ASTReader can be attached to an ASTContext object,
354/// which will provide access to the contents of the AST files.
355///
356/// The AST reader provides lazy de-serialization of declarations, as
357/// required when traversing the AST. Only those AST nodes that are
358/// actually required will be de-serialized.
363 public ExternalSemaSource,
366{
367public:
368 /// Types of AST files.
369 friend class ASTDeclReader;
371 friend class ASTRecordReader;
372 friend class ASTUnit; // ASTUnit needs to remap source locations.
373 friend class ASTWriter;
374 friend class PCHValidator;
377 friend class TypeLocReader;
378 friend class LocalDeclID;
379
382
383 /// The result of reading the control block of an AST file, which
384 /// can fail for various reasons.
386 /// The control block was read successfully. Aside from failures,
387 /// the AST file is safe to read into the current context.
389
390 /// The AST file itself appears corrupted.
392
393 /// The AST file was missing.
395
396 /// The AST file is out-of-date relative to its input files,
397 /// and needs to be regenerated.
399
400 /// The AST file was written by a different version of Clang.
402
403 /// The AST file was written with a different language/target
404 /// configuration.
406
407 /// The AST file has errors.
409 };
410
417
418private:
420
421 /// The receiver of some callbacks invoked by ASTReader.
422 std::unique_ptr<ASTReaderListener> Listener;
423
424 /// The receiver of deserialization events.
425 ASTDeserializationListener *DeserializationListener = nullptr;
426
427 bool OwnsDeserializationListener = false;
428
429 SourceManager &SourceMgr;
430 FileManager &FileMgr;
431 const PCHContainerReader &PCHContainerRdr;
432 DiagnosticsEngine &Diags;
433 // Sema has duplicate logic, but SemaObj can sometimes be null so ASTReader
434 // has its own version.
435 bool WarnedStackExhausted = false;
436
437 /// The semantic analysis object that will be processing the
438 /// AST files and the translation unit that uses it.
439 Sema *SemaObj = nullptr;
440
441 /// The preprocessor that will be loading the source file.
442 Preprocessor &PP;
443
444 /// The AST context into which we'll read the AST files.
445 ASTContext *ContextObj = nullptr;
446
447 /// The AST consumer.
448 ASTConsumer *Consumer = nullptr;
449
450 /// The module manager which manages modules and their dependencies
451 ModuleManager ModuleMgr;
452
453 /// A dummy identifier resolver used to merge TU-scope declarations in
454 /// C, for the cases where we don't have a Sema object to provide a real
455 /// identifier resolver.
456 IdentifierResolver DummyIdResolver;
457
458 /// A mapping from extension block names to module file extensions.
459 llvm::StringMap<std::shared_ptr<ModuleFileExtension>> ModuleFileExtensions;
460
461 /// A timer used to track the time spent deserializing.
462 std::unique_ptr<llvm::Timer> ReadTimer;
463
464 /// The location where the module file will be considered as
465 /// imported from. For non-module AST types it should be invalid.
466 SourceLocation CurrentImportLoc;
467
468 /// The module kind that is currently deserializing.
469 std::optional<ModuleKind> CurrentDeserializingModuleKind;
470
471 /// The global module index, if loaded.
472 std::unique_ptr<GlobalModuleIndex> GlobalIndex;
473
474 /// A map of global bit offsets to the module that stores entities
475 /// at those bit offsets.
477
478 /// A map of negated SLocEntryIDs to the modules containing them.
480
483
484 /// A map of reversed (SourceManager::MaxLoadedOffset - SLocOffset)
485 /// SourceLocation offsets to the modules containing them.
486 GlobalSLocOffsetMapType GlobalSLocOffsetMap;
487
488 /// Types that have already been loaded from the chain.
489 ///
490 /// When the pointer at index I is non-NULL, the type with
491 /// ID = (I + 1) << FastQual::Width has already been loaded
492 llvm::PagedVector<QualType> TypesLoaded;
493
494 /// Declarations that have already been loaded from the chain.
495 ///
496 /// When the pointer at index I is non-NULL, the declaration with ID
497 /// = I + 1 has already been loaded.
498 llvm::PagedVector<Decl *> DeclsLoaded;
499
500 using FileOffset = std::pair<ModuleFile *, uint64_t>;
502 using DeclUpdateOffsetsMap = llvm::DenseMap<GlobalDeclID, FileOffsetsTy>;
503
504 /// Declarations that have modifications residing in a later file
505 /// in the chain.
506 DeclUpdateOffsetsMap DeclUpdateOffsets;
507
508 using DelayedNamespaceOffsetMapTy =
509 llvm::DenseMap<GlobalDeclID, std::pair</*LexicalOffset*/ uint64_t,
510 /*VisibleOffset*/ uint64_t>>;
511
512 /// Mapping from global declaration IDs to the lexical and visible block
513 /// offset for delayed namespace in reduced BMI.
514 ///
515 /// We can't use the existing DeclUpdate mechanism since the DeclUpdate
516 /// may only be applied in an outer most read. However, we need to know
517 /// whether or not a DeclContext has external storage during the recursive
518 /// reading. So we need to apply the offset immediately after we read the
519 /// namespace as if it is not delayed.
520 DelayedNamespaceOffsetMapTy DelayedNamespaceOffsetMap;
521
522 struct PendingUpdateRecord {
523 Decl *D;
524 GlobalDeclID ID;
525
526 // Whether the declaration was just deserialized.
527 bool JustLoaded;
528
529 PendingUpdateRecord(GlobalDeclID ID, Decl *D, bool JustLoaded)
530 : D(D), ID(ID), JustLoaded(JustLoaded) {}
531 };
532
533 /// Declaration updates for already-loaded declarations that we need
534 /// to apply once we finish processing an import.
536
537 enum class PendingFakeDefinitionKind { NotFake, Fake, FakeLoaded };
538
539 /// The DefinitionData pointers that we faked up for class definitions
540 /// that we needed but hadn't loaded yet.
541 llvm::DenseMap<void *, PendingFakeDefinitionKind> PendingFakeDefinitionData;
542
543 /// Exception specification updates that have been loaded but not yet
544 /// propagated across the relevant redeclaration chain. The map key is the
545 /// canonical declaration (used only for deduplication) and the value is a
546 /// declaration that has an exception specification.
547 llvm::SmallMapVector<Decl *, FunctionDecl *, 4> PendingExceptionSpecUpdates;
548
549 /// Deduced return type updates that have been loaded but not yet propagated
550 /// across the relevant redeclaration chain. The map key is the canonical
551 /// declaration and the value is the deduced return type.
552 llvm::SmallMapVector<FunctionDecl *, QualType, 4> PendingDeducedTypeUpdates;
553
554 /// Functions has undededuced return type and we wish we can find the deduced
555 /// return type by iterating the redecls in other modules.
556 llvm::SmallVector<FunctionDecl *, 4> PendingUndeducedFunctionDecls;
557
558 /// Declarations that have been imported and have typedef names for
559 /// linkage purposes.
560 llvm::DenseMap<std::pair<DeclContext *, IdentifierInfo *>, NamedDecl *>
561 ImportedTypedefNamesForLinkage;
562
563 /// Mergeable declaration contexts that have anonymous declarations
564 /// within them, and those anonymous declarations.
565 llvm::DenseMap<Decl*, llvm::SmallVector<NamedDecl*, 2>>
566 AnonymousDeclarationsForMerging;
567
568 /// Map from numbering information for lambdas to the corresponding lambdas.
569 llvm::DenseMap<std::pair<const Decl *, unsigned>, NamedDecl *>
570 LambdaDeclarationsForMerging;
571
572 /// Key used to identify LifetimeExtendedTemporaryDecl for merging,
573 /// containing the lifetime-extending declaration and the mangling number.
574 using LETemporaryKey = std::pair<Decl *, unsigned>;
575
576 /// Map of already deserialiazed temporaries.
577 llvm::DenseMap<LETemporaryKey, LifetimeExtendedTemporaryDecl *>
578 LETemporaryForMerging;
579
580 struct FileDeclsInfo {
581 ModuleFile *Mod = nullptr;
582 ArrayRef<serialization::unaligned_decl_id_t> Decls;
583
584 FileDeclsInfo() = default;
585 FileDeclsInfo(ModuleFile *Mod,
586 ArrayRef<serialization::unaligned_decl_id_t> Decls)
587 : Mod(Mod), Decls(Decls) {}
588 };
589
590 /// Map from a FileID to the file-level declarations that it contains.
591 llvm::DenseMap<FileID, FileDeclsInfo> FileDeclIDs;
592
593 /// An array of lexical contents of a declaration context, as a sequence of
594 /// Decl::Kind, DeclID pairs.
595 using LexicalContents = ArrayRef<serialization::unaligned_decl_id_t>;
596
597 /// Map from a DeclContext to its lexical contents.
598 llvm::DenseMap<const DeclContext*, std::pair<ModuleFile*, LexicalContents>>
599 LexicalDecls;
600
601 /// Map from the TU to its lexical contents from each module file.
602 std::vector<std::pair<ModuleFile*, LexicalContents>> TULexicalDecls;
603
604 /// Map from a DeclContext to its lookup tables.
605 llvm::DenseMap<const DeclContext *,
606 serialization::reader::DeclContextLookupTable> Lookups;
607
608 // Updates for visible decls can occur for other contexts than just the
609 // TU, and when we read those update records, the actual context may not
610 // be available yet, so have this pending map using the ID as a key. It
611 // will be realized when the context is actually loaded.
612 struct PendingVisibleUpdate {
613 ModuleFile *Mod;
614 const unsigned char *Data;
615 };
616 using DeclContextVisibleUpdates = SmallVector<PendingVisibleUpdate, 1>;
617
618 /// Updates to the visible declarations of declaration contexts that
619 /// haven't been loaded yet.
620 llvm::DenseMap<GlobalDeclID, DeclContextVisibleUpdates> PendingVisibleUpdates;
621
622 /// The set of C++ or Objective-C classes that have forward
623 /// declarations that have not yet been linked to their definitions.
624 llvm::SmallPtrSet<Decl *, 4> PendingDefinitions;
625
626 using PendingBodiesMap =
627 llvm::MapVector<Decl *, uint64_t,
628 llvm::SmallDenseMap<Decl *, unsigned, 4>,
629 SmallVector<std::pair<Decl *, uint64_t>, 4>>;
630
631 /// Functions or methods that have bodies that will be attached.
632 PendingBodiesMap PendingBodies;
633
634 /// Definitions for which we have added merged definitions but not yet
635 /// performed deduplication.
636 llvm::SetVector<NamedDecl *> PendingMergedDefinitionsToDeduplicate;
637
638 /// Read the record that describes the lexical contents of a DC.
639 bool ReadLexicalDeclContextStorage(ModuleFile &M,
640 llvm::BitstreamCursor &Cursor,
641 uint64_t Offset, DeclContext *DC);
642
643 /// Read the record that describes the visible contents of a DC.
644 bool ReadVisibleDeclContextStorage(ModuleFile &M,
645 llvm::BitstreamCursor &Cursor,
646 uint64_t Offset, GlobalDeclID ID);
647
648 /// A vector containing identifiers that have already been
649 /// loaded.
650 ///
651 /// If the pointer at index I is non-NULL, then it refers to the
652 /// IdentifierInfo for the identifier with ID=I+1 that has already
653 /// been loaded.
654 std::vector<IdentifierInfo *> IdentifiersLoaded;
655
656 /// A vector containing macros that have already been
657 /// loaded.
658 ///
659 /// If the pointer at index I is non-NULL, then it refers to the
660 /// MacroInfo for the identifier with ID=I+1 that has already
661 /// been loaded.
662 std::vector<MacroInfo *> MacrosLoaded;
663
664 using LoadedMacroInfo =
665 std::pair<IdentifierInfo *, serialization::SubmoduleID>;
666
667 /// A set of #undef directives that we have loaded; used to
668 /// deduplicate the same #undef information coming from multiple module
669 /// files.
671
672 using GlobalMacroMapType =
673 ContinuousRangeMap<serialization::MacroID, ModuleFile *, 4>;
674
675 /// Mapping from global macro IDs to the module in which the
676 /// macro resides along with the offset that should be added to the
677 /// global macro ID to produce a local ID.
678 GlobalMacroMapType GlobalMacroMap;
679
680 /// A vector containing submodules that have already been loaded.
681 ///
682 /// This vector is indexed by the Submodule ID (-1). NULL submodule entries
683 /// indicate that the particular submodule ID has not yet been loaded.
684 SmallVector<Module *, 2> SubmodulesLoaded;
685
686 using GlobalSubmoduleMapType =
687 ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4>;
688
689 /// Mapping from global submodule IDs to the module file in which the
690 /// submodule resides along with the offset that should be added to the
691 /// global submodule ID to produce a local ID.
692 GlobalSubmoduleMapType GlobalSubmoduleMap;
693
694 /// A set of hidden declarations.
695 using HiddenNames = SmallVector<Decl *, 2>;
696 using HiddenNamesMapType = llvm::DenseMap<Module *, HiddenNames>;
697
698 /// A mapping from each of the hidden submodules to the deserialized
699 /// declarations in that submodule that could be made visible.
700 HiddenNamesMapType HiddenNamesMap;
701
702 /// A module import, export, or conflict that hasn't yet been resolved.
703 struct UnresolvedModuleRef {
704 /// The file in which this module resides.
706
707 /// The module that is importing or exporting.
708 Module *Mod;
709
710 /// The kind of module reference.
711 enum { Import, Export, Conflict, Affecting } Kind;
712
713 /// The local ID of the module that is being exported.
714 unsigned ID;
715
716 /// Whether this is a wildcard export.
717 LLVM_PREFERRED_TYPE(bool)
718 unsigned IsWildcard : 1;
719
720 /// String data.
721 StringRef String;
722 };
723
724 /// The set of module imports and exports that still need to be
725 /// resolved.
726 SmallVector<UnresolvedModuleRef, 2> UnresolvedModuleRefs;
727
728 /// A vector containing selectors that have already been loaded.
729 ///
730 /// This vector is indexed by the Selector ID (-1). NULL selector
731 /// entries indicate that the particular selector ID has not yet
732 /// been loaded.
733 SmallVector<Selector, 16> SelectorsLoaded;
734
735 using GlobalSelectorMapType =
736 ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4>;
737
738 /// Mapping from global selector IDs to the module in which the
739 /// global selector ID to produce a local ID.
740 GlobalSelectorMapType GlobalSelectorMap;
741
742 /// The generation number of the last time we loaded data from the
743 /// global method pool for this selector.
744 llvm::DenseMap<Selector, unsigned> SelectorGeneration;
745
746 /// Whether a selector is out of date. We mark a selector as out of date
747 /// if we load another module after the method pool entry was pulled in.
748 llvm::DenseMap<Selector, bool> SelectorOutOfDate;
749
750 struct PendingMacroInfo {
751 ModuleFile *M;
752 /// Offset relative to ModuleFile::MacroOffsetsBase.
753 uint32_t MacroDirectivesOffset;
754
755 PendingMacroInfo(ModuleFile *M, uint32_t MacroDirectivesOffset)
756 : M(M), MacroDirectivesOffset(MacroDirectivesOffset) {}
757 };
758
759 using PendingMacroIDsMap =
760 llvm::MapVector<IdentifierInfo *, SmallVector<PendingMacroInfo, 2>>;
761
762 /// Mapping from identifiers that have a macro history to the global
763 /// IDs have not yet been deserialized to the global IDs of those macros.
764 PendingMacroIDsMap PendingMacroIDs;
765
766 using GlobalPreprocessedEntityMapType =
767 ContinuousRangeMap<unsigned, ModuleFile *, 4>;
768
769 /// Mapping from global preprocessing entity IDs to the module in
770 /// which the preprocessed entity resides along with the offset that should be
771 /// added to the global preprocessing entity ID to produce a local ID.
772 GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap;
773
774 using GlobalSkippedRangeMapType =
775 ContinuousRangeMap<unsigned, ModuleFile *, 4>;
776
777 /// Mapping from global skipped range base IDs to the module in which
778 /// the skipped ranges reside.
779 GlobalSkippedRangeMapType GlobalSkippedRangeMap;
780
781 /// \name CodeGen-relevant special data
782 /// Fields containing data that is relevant to CodeGen.
783 //@{
784
785 /// The IDs of all declarations that fulfill the criteria of
786 /// "interesting" decls.
787 ///
788 /// This contains the data loaded from all EAGERLY_DESERIALIZED_DECLS blocks
789 /// in the chain. The referenced declarations are deserialized and passed to
790 /// the consumer eagerly.
791 SmallVector<GlobalDeclID, 16> EagerlyDeserializedDecls;
792
793 /// The IDs of all tentative definitions stored in the chain.
794 ///
795 /// Sema keeps track of all tentative definitions in a TU because it has to
796 /// complete them and pass them on to CodeGen. Thus, tentative definitions in
797 /// the PCH chain must be eagerly deserialized.
798 SmallVector<GlobalDeclID, 16> TentativeDefinitions;
799
800 /// The IDs of all CXXRecordDecls stored in the chain whose VTables are
801 /// used.
802 ///
803 /// CodeGen has to emit VTables for these records, so they have to be eagerly
804 /// deserialized.
805 struct VTableUse {
806 GlobalDeclID ID;
808 bool Used;
809 };
810 SmallVector<VTableUse> VTableUses;
811
812 /// A snapshot of the pending instantiations in the chain.
813 ///
814 /// This record tracks the instantiations that Sema has to perform at the
815 /// end of the TU. It consists of a pair of values for every pending
816 /// instantiation where the first value is the ID of the decl and the second
817 /// is the instantiation location.
818 struct PendingInstantiation {
819 GlobalDeclID ID;
821 };
822 SmallVector<PendingInstantiation, 64> PendingInstantiations;
823
824 //@}
825
826 /// \name DiagnosticsEngine-relevant special data
827 /// Fields containing data that is used for generating diagnostics
828 //@{
829
830 /// A snapshot of Sema's unused file-scoped variable tracking, for
831 /// generating warnings.
832 SmallVector<GlobalDeclID, 16> UnusedFileScopedDecls;
833
834 /// A list of all the delegating constructors we've seen, to diagnose
835 /// cycles.
836 SmallVector<GlobalDeclID, 4> DelegatingCtorDecls;
837
838 /// Method selectors used in a @selector expression. Used for
839 /// implementation of -Wselector.
840 SmallVector<serialization::SelectorID, 64> ReferencedSelectorsData;
841
842 /// A snapshot of Sema's weak undeclared identifier tracking, for
843 /// generating warnings.
844 SmallVector<serialization::IdentifierID, 64> WeakUndeclaredIdentifiers;
845
846 /// The IDs of type aliases for ext_vectors that exist in the chain.
847 ///
848 /// Used by Sema for finding sugared names for ext_vectors in diagnostics.
849 SmallVector<GlobalDeclID, 4> ExtVectorDecls;
850
851 //@}
852
853 /// \name Sema-relevant special data
854 /// Fields containing data that is used for semantic analysis
855 //@{
856
857 /// The IDs of all potentially unused typedef names in the chain.
858 ///
859 /// Sema tracks these to emit warnings.
860 SmallVector<GlobalDeclID, 16> UnusedLocalTypedefNameCandidates;
861
862 /// Our current depth in #pragma cuda force_host_device begin/end
863 /// macros.
864 unsigned ForceHostDeviceDepth = 0;
865
866 /// The IDs of the declarations Sema stores directly.
867 ///
868 /// Sema tracks a few important decls, such as namespace std, directly.
869 SmallVector<GlobalDeclID, 4> SemaDeclRefs;
870
871 /// The IDs of the types ASTContext stores directly.
872 ///
873 /// The AST context tracks a few important types, such as va_list, directly.
874 SmallVector<serialization::TypeID, 16> SpecialTypes;
875
876 /// The IDs of CUDA-specific declarations ASTContext stores directly.
877 ///
878 /// The AST context tracks a few important decls, currently cudaConfigureCall,
879 /// directly.
880 SmallVector<GlobalDeclID, 2> CUDASpecialDeclRefs;
881
882 /// The floating point pragma option settings.
883 SmallVector<uint64_t, 1> FPPragmaOptions;
884
885 /// The pragma clang optimize location (if the pragma state is "off").
886 SourceLocation OptimizeOffPragmaLocation;
887
888 /// The PragmaMSStructKind pragma ms_struct state if set, or -1.
889 int PragmaMSStructState = -1;
890
891 /// The PragmaMSPointersToMembersKind pragma pointers_to_members state.
892 int PragmaMSPointersToMembersState = -1;
893 SourceLocation PointersToMembersPragmaLocation;
894
895 /// The pragma float_control state.
896 std::optional<FPOptionsOverride> FpPragmaCurrentValue;
897 SourceLocation FpPragmaCurrentLocation;
898 struct FpPragmaStackEntry {
899 FPOptionsOverride Value;
900 SourceLocation Location;
901 SourceLocation PushLocation;
902 StringRef SlotLabel;
903 };
905 llvm::SmallVector<std::string, 2> FpPragmaStrings;
906
907 /// The pragma align/pack state.
908 std::optional<Sema::AlignPackInfo> PragmaAlignPackCurrentValue;
909 SourceLocation PragmaAlignPackCurrentLocation;
910 struct PragmaAlignPackStackEntry {
911 Sema::AlignPackInfo Value;
912 SourceLocation Location;
913 SourceLocation PushLocation;
914 StringRef SlotLabel;
915 };
917 llvm::SmallVector<std::string, 2> PragmaAlignPackStrings;
918
919 /// The OpenCL extension settings.
920 OpenCLOptions OpenCLExtensions;
921
922 /// Extensions required by an OpenCL type.
923 llvm::DenseMap<const Type *, std::set<std::string>> OpenCLTypeExtMap;
924
925 /// Extensions required by an OpenCL declaration.
926 llvm::DenseMap<const Decl *, std::set<std::string>> OpenCLDeclExtMap;
927
928 /// A list of the namespaces we've seen.
929 SmallVector<GlobalDeclID, 4> KnownNamespaces;
930
931 /// A list of undefined decls with internal linkage followed by the
932 /// SourceLocation of a matching ODR-use.
933 struct UndefinedButUsedDecl {
934 GlobalDeclID ID;
936 };
937 SmallVector<UndefinedButUsedDecl, 8> UndefinedButUsed;
938
939 /// Delete expressions to analyze at the end of translation unit.
940 SmallVector<uint64_t, 8> DelayedDeleteExprs;
941
942 // A list of late parsed template function data with their module files.
943 SmallVector<std::pair<ModuleFile *, SmallVector<uint64_t, 1>>, 4>
944 LateParsedTemplates;
945
946 /// The IDs of all decls to be checked for deferred diags.
947 ///
948 /// Sema tracks these to emit deferred diags.
949 llvm::SmallSetVector<GlobalDeclID, 4> DeclsToCheckForDeferredDiags;
950
951private:
952 struct ImportedSubmodule {
954 SourceLocation ImportLoc;
955
956 ImportedSubmodule(serialization::SubmoduleID ID, SourceLocation ImportLoc)
957 : ID(ID), ImportLoc(ImportLoc) {}
958 };
959
960 /// A list of modules that were imported by precompiled headers or
961 /// any other non-module AST file and have not yet been made visible. If a
962 /// module is made visible in the ASTReader, it will be transfered to
963 /// \c PendingImportedModulesSema.
964 SmallVector<ImportedSubmodule, 2> PendingImportedModules;
965
966 /// A list of modules that were imported by precompiled headers or
967 /// any other non-module AST file and have not yet been made visible for Sema.
968 SmallVector<ImportedSubmodule, 2> PendingImportedModulesSema;
969 //@}
970
971 /// The system include root to be used when loading the
972 /// precompiled header.
973 std::string isysroot;
974
975 /// Whether to disable the normal validation performed on precompiled
976 /// headers and module files when they are loaded.
977 DisableValidationForModuleKind DisableValidationKind;
978
979 /// Whether to accept an AST file with compiler errors.
980 bool AllowASTWithCompilerErrors;
981
982 /// Whether to accept an AST file that has a different configuration
983 /// from the current compiler instance.
984 bool AllowConfigurationMismatch;
985
986 /// Whether validate system input files.
987 bool ValidateSystemInputs;
988
989 /// Whether validate headers and module maps using hash based on contents.
990 bool ValidateASTInputFilesContent;
991
992 /// Whether we are allowed to use the global module index.
993 bool UseGlobalIndex;
994
995 /// Whether we have tried loading the global module index yet.
996 bool TriedLoadingGlobalIndex = false;
997
998 ///Whether we are currently processing update records.
999 bool ProcessingUpdateRecords = false;
1000
1001 using SwitchCaseMapTy = llvm::DenseMap<unsigned, SwitchCase *>;
1002
1003 /// Mapping from switch-case IDs in the chain to switch-case statements
1004 ///
1005 /// Statements usually don't have IDs, but switch cases need them, so that the
1006 /// switch statement can refer to them.
1007 SwitchCaseMapTy SwitchCaseStmts;
1008
1009 SwitchCaseMapTy *CurrSwitchCaseStmts;
1010
1011 /// The number of source location entries de-serialized from
1012 /// the PCH file.
1013 unsigned NumSLocEntriesRead = 0;
1014
1015 /// The number of source location entries in the chain.
1016 unsigned TotalNumSLocEntries = 0;
1017
1018 /// The number of statements (and expressions) de-serialized
1019 /// from the chain.
1020 unsigned NumStatementsRead = 0;
1021
1022 /// The total number of statements (and expressions) stored
1023 /// in the chain.
1024 unsigned TotalNumStatements = 0;
1025
1026 /// The number of macros de-serialized from the chain.
1027 unsigned NumMacrosRead = 0;
1028
1029 /// The total number of macros stored in the chain.
1030 unsigned TotalNumMacros = 0;
1031
1032 /// The number of lookups into identifier tables.
1033 unsigned NumIdentifierLookups = 0;
1034
1035 /// The number of lookups into identifier tables that succeed.
1036 unsigned NumIdentifierLookupHits = 0;
1037
1038 /// The number of selectors that have been read.
1039 unsigned NumSelectorsRead = 0;
1040
1041 /// The number of method pool entries that have been read.
1042 unsigned NumMethodPoolEntriesRead = 0;
1043
1044 /// The number of times we have looked up a selector in the method
1045 /// pool.
1046 unsigned NumMethodPoolLookups = 0;
1047
1048 /// The number of times we have looked up a selector in the method
1049 /// pool and found something.
1050 unsigned NumMethodPoolHits = 0;
1051
1052 /// The number of times we have looked up a selector in the method
1053 /// pool within a specific module.
1054 unsigned NumMethodPoolTableLookups = 0;
1055
1056 /// The number of times we have looked up a selector in the method
1057 /// pool within a specific module and found something.
1058 unsigned NumMethodPoolTableHits = 0;
1059
1060 /// The total number of method pool entries in the selector table.
1061 unsigned TotalNumMethodPoolEntries = 0;
1062
1063 /// Number of lexical decl contexts read/total.
1064 unsigned NumLexicalDeclContextsRead = 0, TotalLexicalDeclContexts = 0;
1065
1066 /// Number of visible decl contexts read/total.
1067 unsigned NumVisibleDeclContextsRead = 0, TotalVisibleDeclContexts = 0;
1068
1069 /// Total size of modules, in bits, currently loaded
1070 uint64_t TotalModulesSizeInBits = 0;
1071
1072 /// Number of Decl/types that are currently deserializing.
1073 unsigned NumCurrentElementsDeserializing = 0;
1074
1075 /// Set true while we are in the process of passing deserialized
1076 /// "interesting" decls to consumer inside FinishedDeserializing().
1077 /// This is used as a guard to avoid recursively repeating the process of
1078 /// passing decls to consumer.
1079 bool PassingDeclsToConsumer = false;
1080
1081 /// The set of identifiers that were read while the AST reader was
1082 /// (recursively) loading declarations.
1083 ///
1084 /// The declarations on the identifier chain for these identifiers will be
1085 /// loaded once the recursive loading has completed.
1086 llvm::MapVector<IdentifierInfo *, SmallVector<GlobalDeclID, 4>>
1087 PendingIdentifierInfos;
1088
1089 /// The set of lookup results that we have faked in order to support
1090 /// merging of partially deserialized decls but that we have not yet removed.
1091 llvm::SmallMapVector<const IdentifierInfo *, SmallVector<NamedDecl *, 2>, 16>
1092 PendingFakeLookupResults;
1093
1094 /// The generation number of each identifier, which keeps track of
1095 /// the last time we loaded information about this identifier.
1096 llvm::DenseMap<const IdentifierInfo *, unsigned> IdentifierGeneration;
1097
1098 /// Contains declarations and definitions that could be
1099 /// "interesting" to the ASTConsumer, when we get that AST consumer.
1100 ///
1101 /// "Interesting" declarations are those that have data that may
1102 /// need to be emitted, such as inline function definitions or
1103 /// Objective-C protocols.
1104 std::deque<Decl *> PotentiallyInterestingDecls;
1105
1106 /// The list of deduced function types that we have not yet read, because
1107 /// they might contain a deduced return type that refers to a local type
1108 /// declared within the function.
1109 SmallVector<std::pair<FunctionDecl *, serialization::TypeID>, 16>
1110 PendingDeducedFunctionTypes;
1111
1112 /// The list of deduced variable types that we have not yet read, because
1113 /// they might contain a deduced type that refers to a local type declared
1114 /// within the variable.
1115 SmallVector<std::pair<VarDecl *, serialization::TypeID>, 16>
1116 PendingDeducedVarTypes;
1117
1118 /// The list of redeclaration chains that still need to be
1119 /// reconstructed, and the local offset to the corresponding list
1120 /// of redeclarations.
1121 SmallVector<std::pair<Decl *, uint64_t>, 16> PendingDeclChains;
1122
1123 /// The list of canonical declarations whose redeclaration chains
1124 /// need to be marked as incomplete once we're done deserializing things.
1125 SmallVector<Decl *, 16> PendingIncompleteDeclChains;
1126
1127 /// The Decl IDs for the Sema/Lexical DeclContext of a Decl that has
1128 /// been loaded but its DeclContext was not set yet.
1129 struct PendingDeclContextInfo {
1130 Decl *D;
1131 GlobalDeclID SemaDC;
1132 GlobalDeclID LexicalDC;
1133 };
1134
1135 /// The set of Decls that have been loaded but their DeclContexts are
1136 /// not set yet.
1137 ///
1138 /// The DeclContexts for these Decls will be set once recursive loading has
1139 /// been completed.
1140 std::deque<PendingDeclContextInfo> PendingDeclContextInfos;
1141
1142 template <typename DeclTy>
1143 using DuplicateObjCDecls = std::pair<DeclTy *, DeclTy *>;
1144
1145 /// When resolving duplicate ivars from Objective-C extensions we don't error
1146 /// out immediately but check if can merge identical extensions. Not checking
1147 /// extensions for equality immediately because ivar deserialization isn't
1148 /// over yet at that point.
1149 llvm::SmallMapVector<DuplicateObjCDecls<ObjCCategoryDecl>,
1151 2>
1152 PendingObjCExtensionIvarRedeclarations;
1153
1154 /// Members that have been added to classes, for which the class has not yet
1155 /// been notified. CXXRecordDecl::addedMember will be called for each of
1156 /// these once recursive deserialization is complete.
1157 SmallVector<std::pair<CXXRecordDecl*, Decl*>, 4> PendingAddedClassMembers;
1158
1159 /// The set of NamedDecls that have been loaded, but are members of a
1160 /// context that has been merged into another context where the corresponding
1161 /// declaration is either missing or has not yet been loaded.
1162 ///
1163 /// We will check whether the corresponding declaration is in fact missing
1164 /// once recursing loading has been completed.
1165 llvm::SmallVector<NamedDecl *, 16> PendingOdrMergeChecks;
1166
1167 using DataPointers =
1168 std::pair<CXXRecordDecl *, struct CXXRecordDecl::DefinitionData *>;
1169 using ObjCInterfaceDataPointers =
1170 std::pair<ObjCInterfaceDecl *,
1171 struct ObjCInterfaceDecl::DefinitionData *>;
1172 using ObjCProtocolDataPointers =
1173 std::pair<ObjCProtocolDecl *, struct ObjCProtocolDecl::DefinitionData *>;
1174
1175 /// Record definitions in which we found an ODR violation.
1176 llvm::SmallDenseMap<CXXRecordDecl *, llvm::SmallVector<DataPointers, 2>, 2>
1177 PendingOdrMergeFailures;
1178
1179 /// C/ObjC record definitions in which we found an ODR violation.
1180 llvm::SmallDenseMap<RecordDecl *, llvm::SmallVector<RecordDecl *, 2>, 2>
1181 PendingRecordOdrMergeFailures;
1182
1183 /// Function definitions in which we found an ODR violation.
1184 llvm::SmallDenseMap<FunctionDecl *, llvm::SmallVector<FunctionDecl *, 2>, 2>
1185 PendingFunctionOdrMergeFailures;
1186
1187 /// Enum definitions in which we found an ODR violation.
1188 llvm::SmallDenseMap<EnumDecl *, llvm::SmallVector<EnumDecl *, 2>, 2>
1189 PendingEnumOdrMergeFailures;
1190
1191 /// ObjCInterfaceDecl in which we found an ODR violation.
1192 llvm::SmallDenseMap<ObjCInterfaceDecl *,
1194 PendingObjCInterfaceOdrMergeFailures;
1195
1196 /// ObjCProtocolDecl in which we found an ODR violation.
1197 llvm::SmallDenseMap<ObjCProtocolDecl *,
1199 PendingObjCProtocolOdrMergeFailures;
1200
1201 /// DeclContexts in which we have diagnosed an ODR violation.
1202 llvm::SmallPtrSet<DeclContext*, 2> DiagnosedOdrMergeFailures;
1203
1204 /// The set of Objective-C categories that have been deserialized
1205 /// since the last time the declaration chains were linked.
1206 llvm::SmallPtrSet<ObjCCategoryDecl *, 16> CategoriesDeserialized;
1207
1208 /// The set of Objective-C class definitions that have already been
1209 /// loaded, for which we will need to check for categories whenever a new
1210 /// module is loaded.
1211 SmallVector<ObjCInterfaceDecl *, 16> ObjCClassesLoaded;
1212
1213 using KeyDeclsMap = llvm::DenseMap<Decl *, SmallVector<GlobalDeclID, 2>>;
1214
1215 /// A mapping from canonical declarations to the set of global
1216 /// declaration IDs for key declaration that have been merged with that
1217 /// canonical declaration. A key declaration is a formerly-canonical
1218 /// declaration whose module did not import any other key declaration for that
1219 /// entity. These are the IDs that we use as keys when finding redecl chains.
1220 KeyDeclsMap KeyDecls;
1221
1222 /// A mapping from DeclContexts to the semantic DeclContext that we
1223 /// are treating as the definition of the entity. This is used, for instance,
1224 /// when merging implicit instantiations of class templates across modules.
1225 llvm::DenseMap<DeclContext *, DeclContext *> MergedDeclContexts;
1226
1227 /// A mapping from canonical declarations of enums to their canonical
1228 /// definitions. Only populated when using modules in C++.
1229 llvm::DenseMap<EnumDecl *, EnumDecl *> EnumDefinitions;
1230
1231 /// A mapping from canonical declarations of records to their canonical
1232 /// definitions. Doesn't cover CXXRecordDecl.
1233 llvm::DenseMap<RecordDecl *, RecordDecl *> RecordDefinitions;
1234
1235 /// When reading a Stmt tree, Stmt operands are placed in this stack.
1236 SmallVector<Stmt *, 16> StmtStack;
1237
1238 /// What kind of records we are reading.
1239 enum ReadingKind {
1240 Read_None, Read_Decl, Read_Type, Read_Stmt
1241 };
1242
1243 /// What kind of records we are reading.
1244 ReadingKind ReadingKind = Read_None;
1245
1246 /// RAII object to change the reading kind.
1247 class ReadingKindTracker {
1248 ASTReader &Reader;
1249 enum ReadingKind PrevKind;
1250
1251 public:
1252 ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
1253 : Reader(reader), PrevKind(Reader.ReadingKind) {
1254 Reader.ReadingKind = newKind;
1255 }
1256
1257 ReadingKindTracker(const ReadingKindTracker &) = delete;
1258 ReadingKindTracker &operator=(const ReadingKindTracker &) = delete;
1259 ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; }
1260 };
1261
1262 /// RAII object to mark the start of processing updates.
1263 class ProcessingUpdatesRAIIObj {
1264 ASTReader &Reader;
1265 bool PrevState;
1266
1267 public:
1268 ProcessingUpdatesRAIIObj(ASTReader &reader)
1269 : Reader(reader), PrevState(Reader.ProcessingUpdateRecords) {
1270 Reader.ProcessingUpdateRecords = true;
1271 }
1272
1273 ProcessingUpdatesRAIIObj(const ProcessingUpdatesRAIIObj &) = delete;
1274 ProcessingUpdatesRAIIObj &
1275 operator=(const ProcessingUpdatesRAIIObj &) = delete;
1276 ~ProcessingUpdatesRAIIObj() { Reader.ProcessingUpdateRecords = PrevState; }
1277 };
1278
1279 /// Suggested contents of the predefines buffer, after this
1280 /// PCH file has been processed.
1281 ///
1282 /// In most cases, this string will be empty, because the predefines
1283 /// buffer computed to build the PCH file will be identical to the
1284 /// predefines buffer computed from the command line. However, when
1285 /// there are differences that the PCH reader can work around, this
1286 /// predefines buffer may contain additional definitions.
1287 std::string SuggestedPredefines;
1288
1289 llvm::DenseMap<const Decl *, bool> DefinitionSource;
1290
1291 bool shouldDisableValidationForFile(const serialization::ModuleFile &M) const;
1292
1293 /// Reads a statement from the specified cursor.
1294 Stmt *ReadStmtFromStream(ModuleFile &F);
1295
1296 /// Retrieve the stored information about an input file.
1297 serialization::InputFileInfo getInputFileInfo(ModuleFile &F, unsigned ID);
1298
1299 /// Retrieve the file entry and 'overridden' bit for an input
1300 /// file in the given module file.
1301 serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
1302 bool Complain = true);
1303
1304public:
1305 void ResolveImportedPath(ModuleFile &M, std::string &Filename);
1306 static void ResolveImportedPath(std::string &Filename, StringRef Prefix);
1307
1308 /// Returns the first key declaration for the given declaration. This
1309 /// is one that is formerly-canonical (or still canonical) and whose module
1310 /// did not import any other key declaration of the entity.
1312 D = D->getCanonicalDecl();
1313 if (D->isFromASTFile())
1314 return D;
1315
1316 auto I = KeyDecls.find(D);
1317 if (I == KeyDecls.end() || I->second.empty())
1318 return D;
1319 return GetExistingDecl(I->second[0]);
1320 }
1321 const Decl *getKeyDeclaration(const Decl *D) {
1322 return getKeyDeclaration(const_cast<Decl*>(D));
1323 }
1324
1325 /// Run a callback on each imported key declaration of \p D.
1326 template <typename Fn>
1327 void forEachImportedKeyDecl(const Decl *D, Fn Visit) {
1328 D = D->getCanonicalDecl();
1329 if (D->isFromASTFile())
1330 Visit(D);
1331
1332 auto It = KeyDecls.find(const_cast<Decl*>(D));
1333 if (It != KeyDecls.end())
1334 for (auto ID : It->second)
1335 Visit(GetExistingDecl(ID));
1336 }
1337
1338 /// Get the loaded lookup tables for \p Primary, if any.
1340 getLoadedLookupTables(DeclContext *Primary) const;
1341
1342private:
1343 struct ImportedModule {
1344 ModuleFile *Mod;
1345 ModuleFile *ImportedBy;
1346 SourceLocation ImportLoc;
1347
1348 ImportedModule(ModuleFile *Mod,
1349 ModuleFile *ImportedBy,
1350 SourceLocation ImportLoc)
1351 : Mod(Mod), ImportedBy(ImportedBy), ImportLoc(ImportLoc) {}
1352 };
1353
1354 ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
1355 SourceLocation ImportLoc, ModuleFile *ImportedBy,
1356 SmallVectorImpl<ImportedModule> &Loaded,
1357 off_t ExpectedSize, time_t ExpectedModTime,
1358 ASTFileSignature ExpectedSignature,
1359 unsigned ClientLoadCapabilities);
1360 ASTReadResult ReadControlBlock(ModuleFile &F,
1361 SmallVectorImpl<ImportedModule> &Loaded,
1362 const ModuleFile *ImportedBy,
1363 unsigned ClientLoadCapabilities);
1364 static ASTReadResult ReadOptionsBlock(
1365 llvm::BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
1366 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
1367 std::string &SuggestedPredefines);
1368
1369 /// Read the unhashed control block.
1370 ///
1371 /// This has no effect on \c F.Stream, instead creating a fresh cursor from
1372 /// \c F.Data and reading ahead.
1373 ASTReadResult readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
1374 unsigned ClientLoadCapabilities);
1375
1376 static ASTReadResult
1377 readUnhashedControlBlockImpl(ModuleFile *F, llvm::StringRef StreamData,
1378 unsigned ClientLoadCapabilities,
1379 bool AllowCompatibleConfigurationMismatch,
1380 ASTReaderListener *Listener,
1381 bool ValidateDiagnosticOptions);
1382
1383 llvm::Error ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities);
1384 llvm::Error ReadExtensionBlock(ModuleFile &F);
1385 void ReadModuleOffsetMap(ModuleFile &F) const;
1386 void ParseLineTable(ModuleFile &F, const RecordData &Record);
1387 llvm::Error ReadSourceManagerBlock(ModuleFile &F);
1388 SourceLocation getImportLocation(ModuleFile *F);
1389 ASTReadResult ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
1390 const ModuleFile *ImportedBy,
1391 unsigned ClientLoadCapabilities);
1392 llvm::Error ReadSubmoduleBlock(ModuleFile &F,
1393 unsigned ClientLoadCapabilities);
1394 static bool ParseLanguageOptions(const RecordData &Record, bool Complain,
1395 ASTReaderListener &Listener,
1396 bool AllowCompatibleDifferences);
1397 static bool ParseTargetOptions(const RecordData &Record, bool Complain,
1398 ASTReaderListener &Listener,
1399 bool AllowCompatibleDifferences);
1400 static bool ParseDiagnosticOptions(const RecordData &Record, bool Complain,
1401 ASTReaderListener &Listener);
1402 static bool ParseFileSystemOptions(const RecordData &Record, bool Complain,
1403 ASTReaderListener &Listener);
1404 static bool ParseHeaderSearchOptions(const RecordData &Record, bool Complain,
1405 ASTReaderListener &Listener);
1406 static bool ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
1407 ASTReaderListener &Listener);
1408 static bool ParsePreprocessorOptions(const RecordData &Record, bool Complain,
1409 ASTReaderListener &Listener,
1410 std::string &SuggestedPredefines);
1411
1412 struct RecordLocation {
1413 ModuleFile *F;
1414 uint64_t Offset;
1415
1416 RecordLocation(ModuleFile *M, uint64_t O) : F(M), Offset(O) {}
1417 };
1418
1419 QualType readTypeRecord(serialization::TypeID ID);
1420 RecordLocation TypeCursorForIndex(serialization::TypeID ID);
1421 void LoadedDecl(unsigned Index, Decl *D);
1422 Decl *ReadDeclRecord(GlobalDeclID ID);
1423 void markIncompleteDeclChain(Decl *D);
1424
1425 /// Returns the most recent declaration of a declaration (which must be
1426 /// of a redeclarable kind) that is either local or has already been loaded
1427 /// merged into its redecl chain.
1428 Decl *getMostRecentExistingDecl(Decl *D);
1429
1430 RecordLocation DeclCursorForID(GlobalDeclID ID, SourceLocation &Location);
1431 void loadDeclUpdateRecords(PendingUpdateRecord &Record);
1432 void loadPendingDeclChain(Decl *D, uint64_t LocalOffset);
1433 void loadObjCCategories(GlobalDeclID ID, ObjCInterfaceDecl *D,
1434 unsigned PreviousGeneration = 0);
1435
1436 RecordLocation getLocalBitOffset(uint64_t GlobalOffset);
1437 uint64_t getGlobalBitOffset(ModuleFile &M, uint64_t LocalOffset);
1438
1439 /// Returns the first preprocessed entity ID that begins or ends after
1440 /// \arg Loc.
1442 findPreprocessedEntity(SourceLocation Loc, bool EndsAfter) const;
1443
1444 /// Find the next module that contains entities and return the ID
1445 /// of the first entry.
1446 ///
1447 /// \param SLocMapI points at a chunk of a module that contains no
1448 /// preprocessed entities or the entities it contains are not the
1449 /// ones we are looking for.
1451 findNextPreprocessedEntity(
1453
1454 /// Returns (ModuleFile, Local index) pair for \p GlobalIndex of a
1455 /// preprocessed entity.
1456 std::pair<ModuleFile *, unsigned>
1457 getModulePreprocessedEntity(unsigned GlobalIndex);
1458
1459 /// Returns (begin, end) pair for the preprocessed entities of a
1460 /// particular module.
1461 llvm::iterator_range<PreprocessingRecord::iterator>
1462 getModulePreprocessedEntities(ModuleFile &Mod) const;
1463
1464 bool canRecoverFromOutOfDate(StringRef ModuleFileName,
1465 unsigned ClientLoadCapabilities);
1466
1467public:
1469 : public llvm::iterator_adaptor_base<
1470 ModuleDeclIterator, const serialization::unaligned_decl_id_t *,
1471 std::random_access_iterator_tag, const Decl *, ptrdiff_t,
1472 const Decl *, const Decl *> {
1473 ASTReader *Reader = nullptr;
1474 ModuleFile *Mod = nullptr;
1475
1476 public:
1477 ModuleDeclIterator() : iterator_adaptor_base(nullptr) {}
1478
1481 : iterator_adaptor_base(Pos), Reader(Reader), Mod(Mod) {}
1482
1483 value_type operator*() const {
1484 LocalDeclID ID = LocalDeclID::get(*Reader, *Mod, *I);
1485 return Reader->GetDecl(Reader->getGlobalDeclID(*Mod, ID));
1486 }
1487
1488 value_type operator->() const { return **this; }
1489
1490 bool operator==(const ModuleDeclIterator &RHS) const {
1491 assert(Reader == RHS.Reader && Mod == RHS.Mod);
1492 return I == RHS.I;
1493 }
1494 };
1495
1496 llvm::iterator_range<ModuleDeclIterator>
1498
1499private:
1500 bool isConsumerInterestedIn(Decl *D);
1501 void PassInterestingDeclsToConsumer();
1502 void PassInterestingDeclToConsumer(Decl *D);
1503
1504 void finishPendingActions();
1505 void diagnoseOdrViolations();
1506
1507 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
1508
1509 void addPendingDeclContextInfo(Decl *D, GlobalDeclID SemaDC,
1510 GlobalDeclID LexicalDC) {
1511 assert(D);
1512 PendingDeclContextInfo Info = { D, SemaDC, LexicalDC };
1513 PendingDeclContextInfos.push_back(Info);
1514 }
1515
1516 /// Produce an error diagnostic and return true.
1517 ///
1518 /// This routine should only be used for fatal errors that have to
1519 /// do with non-routine failures (e.g., corrupted AST file).
1520 void Error(StringRef Msg) const;
1521 void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
1522 StringRef Arg2 = StringRef(), StringRef Arg3 = StringRef()) const;
1523 void Error(llvm::Error &&Err) const;
1524
1525 /// Translate a \param GlobalDeclID to the index of DeclsLoaded array.
1526 unsigned translateGlobalDeclIDToIndex(GlobalDeclID ID) const;
1527
1528 /// Translate an \param IdentifierID ID to the index of IdentifiersLoaded
1529 /// array and the corresponding module file.
1530 std::pair<ModuleFile *, unsigned>
1531 translateIdentifierIDToIndex(serialization::IdentifierID ID) const;
1532
1533 /// Translate an \param TypeID ID to the index of TypesLoaded
1534 /// array and the corresponding module file.
1535 std::pair<ModuleFile *, unsigned>
1536 translateTypeIDToIndex(serialization::TypeID ID) const;
1537
1538public:
1539 /// Load the AST file and validate its contents against the given
1540 /// Preprocessor.
1541 ///
1542 /// \param PP the preprocessor associated with the context in which this
1543 /// precompiled header will be loaded.
1544 ///
1545 /// \param Context the AST context that this precompiled header will be
1546 /// loaded into, if any.
1547 ///
1548 /// \param PCHContainerRdr the PCHContainerOperations to use for loading and
1549 /// creating modules.
1550 ///
1551 /// \param Extensions the list of module file extensions that can be loaded
1552 /// from the AST files.
1553 ///
1554 /// \param isysroot If non-NULL, the system include path specified by the
1555 /// user. This is only used with relocatable PCH files. If non-NULL,
1556 /// a relocatable PCH file will use the default path "/".
1557 ///
1558 /// \param DisableValidationKind If set, the AST reader will suppress most
1559 /// of its regular consistency checking, allowing the use of precompiled
1560 /// headers and module files that cannot be determined to be compatible.
1561 ///
1562 /// \param AllowASTWithCompilerErrors If true, the AST reader will accept an
1563 /// AST file the was created out of an AST with compiler errors,
1564 /// otherwise it will reject it.
1565 ///
1566 /// \param AllowConfigurationMismatch If true, the AST reader will not check
1567 /// for configuration differences between the AST file and the invocation.
1568 ///
1569 /// \param ValidateSystemInputs If true, the AST reader will validate
1570 /// system input files in addition to user input files. This is only
1571 /// meaningful if \p DisableValidation is false.
1572 ///
1573 /// \param UseGlobalIndex If true, the AST reader will try to load and use
1574 /// the global module index.
1575 ///
1576 /// \param ReadTimer If non-null, a timer used to track the time spent
1577 /// deserializing.
1578 ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
1579 ASTContext *Context, const PCHContainerReader &PCHContainerRdr,
1580 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
1581 StringRef isysroot = "",
1582 DisableValidationForModuleKind DisableValidationKind =
1584 bool AllowASTWithCompilerErrors = false,
1585 bool AllowConfigurationMismatch = false,
1586 bool ValidateSystemInputs = false,
1587 bool ValidateASTInputFilesContent = false,
1588 bool UseGlobalIndex = true,
1589 std::unique_ptr<llvm::Timer> ReadTimer = {});
1590 ASTReader(const ASTReader &) = delete;
1591 ASTReader &operator=(const ASTReader &) = delete;
1592 ~ASTReader() override;
1593
1594 SourceManager &getSourceManager() const { return SourceMgr; }
1595 FileManager &getFileManager() const { return FileMgr; }
1596 DiagnosticsEngine &getDiags() const { return Diags; }
1597
1598 /// Flags that indicate what kind of AST loading failures the client
1599 /// of the AST reader can directly handle.
1600 ///
1601 /// When a client states that it can handle a particular kind of failure,
1602 /// the AST reader will not emit errors when producing that kind of failure.
1604 /// The client can't handle any AST loading failures.
1606
1607 /// The client can handle an AST file that cannot load because it
1608 /// is missing.
1610
1611 /// The client can handle an AST file that cannot load because it
1612 /// is out-of-date relative to its input files.
1614
1615 /// The client can handle an AST file that cannot load because it
1616 /// was built with a different version of Clang.
1618
1619 /// The client can handle an AST file that cannot load because it's
1620 /// compiled configuration doesn't match that of the context it was
1621 /// loaded into.
1623
1624 /// If a module file is marked with errors treat it as out-of-date so the
1625 /// caller can rebuild it.
1628
1629 /// Load the AST file designated by the given file name.
1630 ///
1631 /// \param FileName The name of the AST file to load.
1632 ///
1633 /// \param Type The kind of AST being loaded, e.g., PCH, module, main file,
1634 /// or preamble.
1635 ///
1636 /// \param ImportLoc the location where the module file will be considered as
1637 /// imported from. For non-module AST types it should be invalid.
1638 ///
1639 /// \param ClientLoadCapabilities The set of client load-failure
1640 /// capabilities, represented as a bitset of the enumerators of
1641 /// LoadFailureCapabilities.
1642 ///
1643 /// \param LoadedModuleFile The optional out-parameter refers to the new
1644 /// loaded modules. In case the module specified by FileName is already
1645 /// loaded, the module file pointer referred by NewLoadedModuleFile wouldn't
1646 /// change. Otherwise if the AST file get loaded successfully,
1647 /// NewLoadedModuleFile would refer to the address of the new loaded top level
1648 /// module. The state of NewLoadedModuleFile is unspecified if the AST file
1649 /// isn't loaded successfully.
1651 SourceLocation ImportLoc,
1652 unsigned ClientLoadCapabilities,
1653 ModuleFile **NewLoadedModuleFile = nullptr);
1654
1655 /// Make the entities in the given module and any of its (non-explicit)
1656 /// submodules visible to name lookup.
1657 ///
1658 /// \param Mod The module whose names should be made visible.
1659 ///
1660 /// \param NameVisibility The level of visibility to give the names in the
1661 /// module. Visibility can only be increased over time.
1662 ///
1663 /// \param ImportLoc The location at which the import occurs.
1664 void makeModuleVisible(Module *Mod,
1665 Module::NameVisibilityKind NameVisibility,
1666 SourceLocation ImportLoc);
1667
1668 /// Make the names within this set of hidden names visible.
1669 void makeNamesVisible(const HiddenNames &Names, Module *Owner);
1670
1671 /// Note that MergedDef is a redefinition of the canonical definition
1672 /// Def, so Def should be visible whenever MergedDef is.
1673 void mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef);
1674
1675 /// Take the AST callbacks listener.
1676 std::unique_ptr<ASTReaderListener> takeListener() {
1677 return std::move(Listener);
1678 }
1679
1680 /// Set the AST callbacks listener.
1681 void setListener(std::unique_ptr<ASTReaderListener> Listener) {
1682 this->Listener = std::move(Listener);
1683 }
1684
1685 /// Add an AST callback listener.
1686 ///
1687 /// Takes ownership of \p L.
1688 void addListener(std::unique_ptr<ASTReaderListener> L) {
1689 if (Listener)
1690 L = std::make_unique<ChainedASTReaderListener>(std::move(L),
1691 std::move(Listener));
1692 Listener = std::move(L);
1693 }
1694
1695 /// RAII object to temporarily add an AST callback listener.
1697 ASTReader &Reader;
1698 bool Chained = false;
1699
1700 public:
1701 ListenerScope(ASTReader &Reader, std::unique_ptr<ASTReaderListener> L)
1702 : Reader(Reader) {
1703 auto Old = Reader.takeListener();
1704 if (Old) {
1705 Chained = true;
1706 L = std::make_unique<ChainedASTReaderListener>(std::move(L),
1707 std::move(Old));
1708 }
1709 Reader.setListener(std::move(L));
1710 }
1711
1713 auto New = Reader.takeListener();
1714 if (Chained)
1715 Reader.setListener(static_cast<ChainedASTReaderListener *>(New.get())
1716 ->takeSecond());
1717 }
1718 };
1719
1720 /// Set the AST deserialization listener.
1722 bool TakeOwnership = false);
1723
1724 /// Get the AST deserialization listener.
1726 return DeserializationListener;
1727 }
1728
1729 /// Determine whether this AST reader has a global index.
1730 bool hasGlobalIndex() const { return (bool)GlobalIndex; }
1731
1732 /// Return global module index.
1733 GlobalModuleIndex *getGlobalIndex() { return GlobalIndex.get(); }
1734
1735 /// Reset reader for a reload try.
1736 void resetForReload() { TriedLoadingGlobalIndex = false; }
1737
1738 /// Attempts to load the global index.
1739 ///
1740 /// \returns true if loading the global index has failed for any reason.
1741 bool loadGlobalIndex();
1742
1743 /// Determine whether we tried to load the global index, but failed,
1744 /// e.g., because it is out-of-date or does not exist.
1745 bool isGlobalIndexUnavailable() const;
1746
1747 /// Initializes the ASTContext
1748 void InitializeContext();
1749
1750 /// Update the state of Sema after loading some additional modules.
1751 void UpdateSema();
1752
1753 /// Add in-memory (virtual file) buffer.
1755 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
1756 ModuleMgr.addInMemoryBuffer(FileName, std::move(Buffer));
1757 }
1758
1759 /// Finalizes the AST reader's state before writing an AST file to
1760 /// disk.
1761 ///
1762 /// This operation may undo temporary state in the AST that should not be
1763 /// emitted.
1764 void finalizeForWriting();
1765
1766 /// Retrieve the module manager.
1767 ModuleManager &getModuleManager() { return ModuleMgr; }
1768 const ModuleManager &getModuleManager() const { return ModuleMgr; }
1769
1770 /// Retrieve the preprocessor.
1771 Preprocessor &getPreprocessor() const { return PP; }
1772
1773 /// Retrieve the name of the original source file name for the primary
1774 /// module file.
1776 return ModuleMgr.getPrimaryModule().OriginalSourceFileName;
1777 }
1778
1779 /// Retrieve the name of the original source file name directly from
1780 /// the AST file, without actually loading the AST file.
1781 static std::string
1782 getOriginalSourceFile(const std::string &ASTFileName, FileManager &FileMgr,
1783 const PCHContainerReader &PCHContainerRdr,
1784 DiagnosticsEngine &Diags);
1785
1786 /// Read the control block for the named AST file.
1787 ///
1788 /// \returns true if an error occurred, false otherwise.
1789 static bool readASTFileControlBlock(
1790 StringRef Filename, FileManager &FileMgr,
1791 const InMemoryModuleCache &ModuleCache,
1792 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
1793 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
1794 unsigned ClientLoadCapabilities = ARR_ConfigurationMismatch |
1796
1797 /// Determine whether the given AST file is acceptable to load into a
1798 /// translation unit with the given language and target options.
1799 static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
1800 const InMemoryModuleCache &ModuleCache,
1801 const PCHContainerReader &PCHContainerRdr,
1802 const LangOptions &LangOpts,
1803 const TargetOptions &TargetOpts,
1804 const PreprocessorOptions &PPOpts,
1805 StringRef ExistingModuleCachePath,
1806 bool RequireStrictOptionMatches = false);
1807
1808 /// Returns the suggested contents of the predefines buffer,
1809 /// which contains a (typically-empty) subset of the predefines
1810 /// build prior to including the precompiled header.
1811 const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
1812
1813 /// Read a preallocated preprocessed entity from the external source.
1814 ///
1815 /// \returns null if an error occurred that prevented the preprocessed
1816 /// entity from being loaded.
1817 PreprocessedEntity *ReadPreprocessedEntity(unsigned Index) override;
1818
1819 /// Returns a pair of [Begin, End) indices of preallocated
1820 /// preprocessed entities that \p Range encompasses.
1821 std::pair<unsigned, unsigned>
1823
1824 /// Optionally returns true or false if the preallocated preprocessed
1825 /// entity with index \p Index came from file \p FID.
1826 std::optional<bool> isPreprocessedEntityInFileID(unsigned Index,
1827 FileID FID) override;
1828
1829 /// Read a preallocated skipped range from the external source.
1830 SourceRange ReadSkippedRange(unsigned Index) override;
1831
1832 /// Read the header file information for the given file entry.
1834
1836
1837 /// Returns the number of source locations found in the chain.
1838 unsigned getTotalNumSLocs() const {
1839 return TotalNumSLocEntries;
1840 }
1841
1842 /// Returns the number of identifiers found in the chain.
1843 unsigned getTotalNumIdentifiers() const {
1844 return static_cast<unsigned>(IdentifiersLoaded.size());
1845 }
1846
1847 /// Returns the number of macros found in the chain.
1848 unsigned getTotalNumMacros() const {
1849 return static_cast<unsigned>(MacrosLoaded.size());
1850 }
1851
1852 /// Returns the number of types found in the chain.
1853 unsigned getTotalNumTypes() const {
1854 return static_cast<unsigned>(TypesLoaded.size());
1855 }
1856
1857 /// Returns the number of declarations found in the chain.
1858 unsigned getTotalNumDecls() const {
1859 return static_cast<unsigned>(DeclsLoaded.size());
1860 }
1861
1862 /// Returns the number of submodules known.
1863 unsigned getTotalNumSubmodules() const {
1864 return static_cast<unsigned>(SubmodulesLoaded.size());
1865 }
1866
1867 /// Returns the number of selectors found in the chain.
1868 unsigned getTotalNumSelectors() const {
1869 return static_cast<unsigned>(SelectorsLoaded.size());
1870 }
1871
1872 /// Returns the number of preprocessed entities known to the AST
1873 /// reader.
1875 unsigned Result = 0;
1876 for (const auto &M : ModuleMgr)
1877 Result += M.NumPreprocessedEntities;
1878 return Result;
1879 }
1880
1881 /// Resolve a type ID into a type, potentially building a new
1882 /// type.
1884
1885 /// Resolve a local type ID within a given AST file into a type.
1887
1888 /// Map a local type ID within a given AST file into a global type ID.
1891
1892 /// Read a type from the current position in the given record, which
1893 /// was read from the given AST file.
1894 QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) {
1895 if (Idx >= Record.size())
1896 return {};
1897
1898 return getLocalType(F, Record[Idx++]);
1899 }
1900
1901 /// Map from a local declaration ID within a given module to a
1902 /// global declaration ID.
1904
1905 /// Returns true if global DeclID \p ID originated from module \p M.
1906 bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const;
1907
1908 /// Retrieve the module file that owns the given declaration, or NULL
1909 /// if the declaration is not from a module file.
1910 ModuleFile *getOwningModuleFile(const Decl *D) const;
1912
1913 /// Returns the source location for the decl \p ID.
1915
1916 /// Resolve a declaration ID into a declaration, potentially
1917 /// building a new declaration.
1919 Decl *GetExternalDecl(GlobalDeclID ID) override;
1920
1921 /// Resolve a declaration ID into a declaration. Return 0 if it's not
1922 /// been loaded yet.
1924
1925 /// Reads a declaration with the given local ID in the given module.
1927 return GetDecl(getGlobalDeclID(F, LocalID));
1928 }
1929
1930 /// Reads a declaration with the given local ID in the given module.
1931 ///
1932 /// \returns The requested declaration, casted to the given return type.
1933 template <typename T> T *GetLocalDeclAs(ModuleFile &F, LocalDeclID LocalID) {
1934 return cast_or_null<T>(GetLocalDecl(F, LocalID));
1935 }
1936
1937 /// Map a global declaration ID into the declaration ID used to
1938 /// refer to this declaration within the given module fule.
1939 ///
1940 /// \returns the global ID of the given declaration as known in the given
1941 /// module file.
1943 GlobalDeclID GlobalID);
1944
1945 /// Reads a declaration ID from the given position in a record in the
1946 /// given module.
1947 ///
1948 /// \returns The declaration ID read from the record, adjusted to a global ID.
1950 unsigned &Idx);
1951
1952 /// Reads a declaration from the given position in a record in the
1953 /// given module.
1954 Decl *ReadDecl(ModuleFile &F, const RecordDataImpl &R, unsigned &I) {
1955 return GetDecl(ReadDeclID(F, R, I));
1956 }
1957
1958 /// Reads a declaration from the given position in a record in the
1959 /// given module.
1960 ///
1961 /// \returns The declaration read from this location, casted to the given
1962 /// result type.
1963 template <typename T>
1964 T *ReadDeclAs(ModuleFile &F, const RecordDataImpl &R, unsigned &I) {
1965 return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
1966 }
1967
1968 /// If any redeclarations of \p D have been imported since it was
1969 /// last checked, this digs out those redeclarations and adds them to the
1970 /// redeclaration chain for \p D.
1971 void CompleteRedeclChain(const Decl *D) override;
1972
1973 CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override;
1974
1975 /// Resolve the offset of a statement into a statement.
1976 ///
1977 /// This operation will read a new statement from the external
1978 /// source each time it is called, and is meant to be used via a
1979 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1980 Stmt *GetExternalDeclStmt(uint64_t Offset) override;
1981
1982 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1983 /// specified cursor. Read the abbreviations that are at the top of the block
1984 /// and then leave the cursor pointing into the block.
1985 static llvm::Error ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1986 unsigned BlockID,
1987 uint64_t *StartOfBlockOffset = nullptr);
1988
1989 /// Finds all the visible declarations with a given name.
1990 /// The current implementation of this method just loads the entire
1991 /// lookup table as unmaterialized references.
1993 DeclarationName Name) override;
1994
1995 /// Read all of the declarations lexically stored in a
1996 /// declaration context.
1997 ///
1998 /// \param DC The declaration context whose declarations will be
1999 /// read.
2000 ///
2001 /// \param IsKindWeWant A predicate indicating which declaration kinds
2002 /// we are interested in.
2003 ///
2004 /// \param Decls Vector that will contain the declarations loaded
2005 /// from the external source. The caller is responsible for merging
2006 /// these declarations with any declarations already stored in the
2007 /// declaration context.
2008 void
2010 llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
2011 SmallVectorImpl<Decl *> &Decls) override;
2012
2013 /// Get the decls that are contained in a file in the Offset/Length
2014 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
2015 /// a range.
2016 void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2017 SmallVectorImpl<Decl *> &Decls) override;
2018
2019 /// Notify ASTReader that we started deserialization of
2020 /// a decl or type so until FinishedDeserializing is called there may be
2021 /// decls that are initializing. Must be paired with FinishedDeserializing.
2022 void StartedDeserializing() override;
2023
2024 /// Notify ASTReader that we finished the deserialization of
2025 /// a decl or type. Must be paired with StartedDeserializing.
2026 void FinishedDeserializing() override;
2027
2028 /// Function that will be invoked when we begin parsing a new
2029 /// translation unit involving this external AST source.
2030 ///
2031 /// This function will provide all of the external definitions to
2032 /// the ASTConsumer.
2033 void StartTranslationUnit(ASTConsumer *Consumer) override;
2034
2035 /// Print some statistics about AST usage.
2036 void PrintStats() override;
2037
2038 /// Dump information about the AST reader to standard error.
2039 void dump();
2040
2041 /// Return the amount of memory used by memory buffers, breaking down
2042 /// by heap-backed versus mmap'ed memory.
2043 void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override;
2044
2045 /// Initialize the semantic source with the Sema instance
2046 /// being used to perform semantic analysis on the abstract syntax
2047 /// tree.
2048 void InitializeSema(Sema &S) override;
2049
2050 /// Inform the semantic consumer that Sema is no longer available.
2051 void ForgetSema() override { SemaObj = nullptr; }
2052
2053 /// Retrieve the IdentifierInfo for the named identifier.
2054 ///
2055 /// This routine builds a new IdentifierInfo for the given identifier. If any
2056 /// declarations with this name are visible from translation unit scope, their
2057 /// declarations will be deserialized and introduced into the declaration
2058 /// chain of the identifier.
2059 IdentifierInfo *get(StringRef Name) override;
2060
2061 /// Retrieve an iterator into the set of all identifiers
2062 /// in all loaded AST files.
2064
2065 /// Load the contents of the global method pool for a given
2066 /// selector.
2067 void ReadMethodPool(Selector Sel) override;
2068
2069 /// Load the contents of the global method pool for a given
2070 /// selector if necessary.
2071 void updateOutOfDateSelector(Selector Sel) override;
2072
2073 /// Load the set of namespaces that are known to the external source,
2074 /// which will be used during typo correction.
2076 SmallVectorImpl<NamespaceDecl *> &Namespaces) override;
2077
2079 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) override;
2080
2081 void ReadMismatchingDeleteExpressions(llvm::MapVector<
2082 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
2083 Exprs) override;
2084
2086 SmallVectorImpl<VarDecl *> &TentativeDefs) override;
2087
2090
2093
2095
2098
2100 llvm::SmallSetVector<Decl *, 4> &Decls) override;
2101
2103 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) override;
2104
2106 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) override;
2107
2109
2111 SmallVectorImpl<std::pair<ValueDecl *,
2112 SourceLocation>> &Pending) override;
2113
2115 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
2116 &LPTMap) override;
2117
2118 void AssignedLambdaNumbering(const CXXRecordDecl *Lambda) override;
2119
2120 /// Load a selector from disk, registering its ID if it exists.
2121 void LoadSelector(Selector Sel);
2122
2125 const SmallVectorImpl<GlobalDeclID> &DeclIDs,
2126 SmallVectorImpl<Decl *> *Decls = nullptr);
2127
2128 /// Report a diagnostic.
2129 DiagnosticBuilder Diag(unsigned DiagID) const;
2130
2131 /// Report a diagnostic.
2132 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const;
2133
2135
2137
2139 unsigned &Idx) {
2141 }
2142
2144 // Note that we are loading an identifier.
2145 Deserializing AnIdentifier(this);
2146
2147 return DecodeIdentifierInfo(ID);
2148 }
2149
2150 IdentifierInfo *getLocalIdentifier(ModuleFile &M, uint64_t LocalID);
2151
2153 uint64_t LocalID);
2154
2155 void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo);
2156
2157 /// Retrieve the macro with the given ID.
2159
2160 /// Retrieve the global macro ID corresponding to the given local
2161 /// ID within the given module file.
2163
2164 /// Read the source location entry with index ID.
2165 bool ReadSLocEntry(int ID) override;
2166 /// Get the index ID for the loaded SourceLocation offset.
2167 int getSLocEntryID(SourceLocation::UIntTy SLocOffset) override;
2168 /// Try to read the offset of the SLocEntry at the given index in the given
2169 /// module file.
2171 unsigned Index);
2172
2173 /// Retrieve the module import location and module name for the
2174 /// given source manager entry ID.
2175 std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) override;
2176
2177 /// Retrieve the global submodule ID given a module and its local ID
2178 /// number.
2180 unsigned LocalID) const;
2181
2182 /// Retrieve the submodule that corresponds to a global submodule ID.
2183 ///
2185
2186 /// Retrieve the module that corresponds to the given module ID.
2187 ///
2188 /// Note: overrides method in ExternalASTSource
2189 Module *getModule(unsigned ID) override;
2190
2191 /// Retrieve the module file with a given local ID within the specified
2192 /// ModuleFile.
2193 ModuleFile *getLocalModuleFile(ModuleFile &M, unsigned ID) const;
2194
2195 /// Get an ID for the given module file.
2196 unsigned getModuleFileID(ModuleFile *M);
2197
2198 /// Return a descriptor for the corresponding module.
2199 std::optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID) override;
2200
2201 ExtKind hasExternalDefinitions(const Decl *D) override;
2202
2203 /// Retrieve a selector from the given module with its local ID
2204 /// number.
2205 Selector getLocalSelector(ModuleFile &M, unsigned LocalID);
2206
2208
2210 uint32_t GetNumExternalSelectors() override;
2211
2212 Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) {
2213 return getLocalSelector(M, Record[Idx++]);
2214 }
2215
2216 /// Retrieve the global selector ID that corresponds to this
2217 /// the local selector ID in a given module.
2219 unsigned LocalID) const;
2220
2221 /// Read the contents of a CXXCtorInitializer array.
2222 CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset) override;
2223
2224 /// Read a AlignPackInfo from raw form.
2227 }
2228
2230
2231 /// Read a source location from raw form and return it in its
2232 /// originating module file's source location space.
2233 std::pair<SourceLocation, unsigned>
2235 LocSeq *Seq = nullptr) const {
2237 }
2238
2239 /// Read a source location from raw form.
2241 LocSeq *Seq = nullptr) const {
2242 if (!MF.ModuleOffsetMap.empty())
2243 ReadModuleOffsetMap(MF);
2244
2245 auto [Loc, ModuleFileIndex] = ReadUntranslatedSourceLocation(Raw, Seq);
2246 ModuleFile *OwningModuleFile =
2247 ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1];
2248
2249 assert(!SourceMgr.isLoadedSourceLocation(Loc) &&
2250 "Run out source location space");
2251
2252 return TranslateSourceLocation(*OwningModuleFile, Loc);
2253 }
2254
2255 /// Translate a source location from another module file's source
2256 /// location space into ours.
2258 SourceLocation Loc) const {
2259 if (Loc.isInvalid())
2260 return Loc;
2261
2262 // FIXME: TranslateSourceLocation is not re-enterable. It is problematic
2263 // to call TranslateSourceLocation on a translated source location.
2264 // We either need a method to know whether or not a source location is
2265 // translated or refactor the code to make it clear that
2266 // TranslateSourceLocation won't be called with translated source location.
2267
2268 return Loc.getLocWithOffset(ModuleFile.SLocEntryBaseOffset - 2);
2269 }
2270
2271 /// Read a source location.
2273 const RecordDataImpl &Record, unsigned &Idx,
2274 LocSeq *Seq = nullptr) {
2275 return ReadSourceLocation(ModuleFile, Record[Idx++], Seq);
2276 }
2277
2278 /// Read a FileID.
2280 unsigned &Idx) const {
2281 return TranslateFileID(F, FileID::get(Record[Idx++]));
2282 }
2283
2284 /// Translate a FileID from another module file's FileID space into ours.
2286 assert(FID.ID >= 0 && "Reading non-local FileID.");
2287 return FileID::get(F.SLocEntryBaseID + FID.ID - 1);
2288 }
2289
2290 /// Read a source range.
2292 unsigned &Idx, LocSeq *Seq = nullptr);
2293
2294 static llvm::BitVector ReadBitVector(const RecordData &Record,
2295 const StringRef Blob);
2296
2297 // Read a string
2298 static std::string ReadString(const RecordDataImpl &Record, unsigned &Idx);
2299
2300 // Skip a string
2301 static void SkipString(const RecordData &Record, unsigned &Idx) {
2302 Idx += Record[Idx] + 1;
2303 }
2304
2305 // Read a path
2306 std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx);
2307
2308 // Read a path
2309 std::string ReadPath(StringRef BaseDirectory, const RecordData &Record,
2310 unsigned &Idx);
2311
2312 // Skip a path
2313 static void SkipPath(const RecordData &Record, unsigned &Idx) {
2314 SkipString(Record, Idx);
2315 }
2316
2317 /// Read a version tuple.
2318 static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
2319
2321 unsigned &Idx);
2322
2323 /// Reads a statement.
2325
2326 /// Reads an expression.
2328
2329 /// Reads a sub-statement operand during statement reading.
2331 assert(ReadingKind == Read_Stmt &&
2332 "Should be called only during statement reading!");
2333 // Subexpressions are stored from last to first, so the next Stmt we need
2334 // is at the back of the stack.
2335 assert(!StmtStack.empty() && "Read too many sub-statements!");
2336 return StmtStack.pop_back_val();
2337 }
2338
2339 /// Reads a sub-expression operand during statement reading.
2340 Expr *ReadSubExpr();
2341
2342 /// Reads a token out of a record.
2343 Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx);
2344
2345 /// Reads the macro record located at the given offset.
2346 MacroInfo *ReadMacroRecord(ModuleFile &F, uint64_t Offset);
2347
2348 /// Determine the global preprocessed entity ID that corresponds to
2349 /// the given local ID within the given module.
2351 getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const;
2352
2353 /// Add a macro to deserialize its macro directive history.
2354 ///
2355 /// \param II The name of the macro.
2356 /// \param M The module file.
2357 /// \param MacroDirectivesOffset Offset of the serialized macro directive
2358 /// history.
2360 uint32_t MacroDirectivesOffset);
2361
2362 /// Read the set of macros defined by this external macro source.
2363 void ReadDefinedMacros() override;
2364
2365 /// Update an out-of-date identifier.
2366 void updateOutOfDateIdentifier(const IdentifierInfo &II) override;
2367
2368 /// Note that this identifier is up-to-date.
2369 void markIdentifierUpToDate(const IdentifierInfo *II);
2370
2371 /// Load all external visible decls in the given DeclContext.
2372 void completeVisibleDeclsMap(const DeclContext *DC) override;
2373
2374 /// Retrieve the AST context that this AST reader supplements.
2376 assert(ContextObj && "requested AST context when not loading AST");
2377 return *ContextObj;
2378 }
2379
2380 // Contains the IDs for declarations that were requested before we have
2381 // access to a Sema object.
2383
2384 /// Retrieve the semantic analysis object used to analyze the
2385 /// translation unit in which the precompiled header is being
2386 /// imported.
2387 Sema *getSema() { return SemaObj; }
2388
2389 /// Get the identifier resolver used for name lookup / updates
2390 /// in the translation unit scope. We have one of these even if we don't
2391 /// have a Sema object.
2393
2394 /// Retrieve the identifier table associated with the
2395 /// preprocessor.
2397
2398 /// Record that the given ID maps to the given switch-case
2399 /// statement.
2400 void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
2401
2402 /// Retrieve the switch-case statement with the given ID.
2403 SwitchCase *getSwitchCaseWithID(unsigned ID);
2404
2405 void ClearSwitchCaseIDs();
2406
2407 /// Cursors for comments blocks.
2408 SmallVector<std::pair<llvm::BitstreamCursor,
2410
2411 /// Loads comments ranges.
2412 void ReadComments() override;
2413
2414 /// Visit all the input file infos of the given module file.
2416 serialization::ModuleFile &MF, bool IncludeSystem,
2417 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
2418 bool IsSystem)>
2419 Visitor);
2420
2421 /// Visit all the input files of the given module file.
2423 bool IncludeSystem, bool Complain,
2424 llvm::function_ref<void(const serialization::InputFile &IF,
2425 bool isSystem)> Visitor);
2426
2427 /// Visit all the top-level module maps loaded when building the given module
2428 /// file.
2430 llvm::function_ref<void(FileEntryRef)> Visitor);
2431
2432 bool isProcessingUpdateRecords() { return ProcessingUpdateRecords; }
2433};
2434
2435/// A simple helper class to unpack an integer to bits and consuming
2436/// the bits in order.
2438 constexpr static uint32_t BitsIndexUpbound = 32;
2439
2440public:
2441 BitsUnpacker(uint32_t V) { updateValue(V); }
2442 BitsUnpacker(const BitsUnpacker &) = delete;
2446 ~BitsUnpacker() = default;
2447
2448 void updateValue(uint32_t V) {
2449 Value = V;
2450 CurrentBitsIndex = 0;
2451 }
2452
2453 void advance(uint32_t BitsWidth) { CurrentBitsIndex += BitsWidth; }
2454
2455 bool getNextBit() {
2456 assert(isValid());
2457 return Value & (1 << CurrentBitsIndex++);
2458 }
2459
2460 uint32_t getNextBits(uint32_t Width) {
2461 assert(isValid());
2462 assert(Width < BitsIndexUpbound);
2463 uint32_t Ret = (Value >> CurrentBitsIndex) & ((1 << Width) - 1);
2464 CurrentBitsIndex += Width;
2465 return Ret;
2466 }
2467
2468 bool canGetNextNBits(uint32_t Width) const {
2469 return CurrentBitsIndex + Width < BitsIndexUpbound;
2470 }
2471
2472private:
2473 bool isValid() const { return CurrentBitsIndex < BitsIndexUpbound; }
2474
2475 uint32_t Value;
2476 uint32_t CurrentBitsIndex = ~0;
2477};
2478
2479inline bool shouldSkipCheckingODR(const Decl *D) {
2480 return D->getASTContext().getLangOpts().SkipODRCheckInGMF &&
2482}
2483
2484} // namespace clang
2485
2486#endif // LLVM_CLANG_SERIALIZATION_ASTREADER_H
#define V(N, I)
Definition: ASTContext.h:3338
Defines the Diagnostic-related interfaces.
const Decl * D
enum clang::sema::@1651::IndirectLocalPathEntry::EntryKind Kind
StringRef Filename
Definition: Format.cpp:2989
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
llvm::MachO::Record Record
Definition: MachO.h:31
Defines the clang::OpenCLOptions class.
SourceRange Range
Definition: SemaObjC.cpp:757
SourceLocation Loc
Definition: SemaObjC.cpp:758
Defines the clang::SourceLocation class and associated facilities.
const char * Data
C Language Family Type Representation.
Defines version macros and version-related utility functions for Clang.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:34
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:186
const LangOptions & getLangOpts() const
Definition: ASTContext.h:796
An identifier-lookup iterator that enumerates all of the identifiers stored within a set of AST files...
Definition: ASTReader.cpp:8431
Abstract interface for callback invocations by the ASTReader.
Definition: ASTReader.h:114
virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain)
Receives the header search options.
Definition: ASTReader.h:174
virtual void ReadModuleMapFile(StringRef ModuleMapPath)
Definition: ASTReader.h:127
virtual bool needsInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.h:218
virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences)
Receives the target options.
Definition: ASTReader.h:142
virtual bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule)
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
Definition: ASTReader.h:230
virtual bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts, bool Complain)
Receives the header search paths.
Definition: ASTReader.h:189
virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain)
Receives the file system options.
Definition: ASTReader.h:161
virtual bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain)
Receives the diagnostic options.
Definition: ASTReader.h:152
virtual void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata)
Indicates that a particular module file extension has been read.
Definition: ASTReader.h:244
virtual bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences)
Receives the language options.
Definition: ASTReader.h:132
virtual void visitImport(StringRef ModuleName, StringRef Filename)
If needsImportVisitation returns true, this is called for each AST file imported by this AST file.
Definition: ASTReader.h:241
virtual void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind)
This is called for each AST file loaded.
Definition: ASTReader.h:213
virtual bool needsImportVisitation() const
Returns true if this ASTReaderListener wants to receive the imports of the AST file via visitImport,...
Definition: ASTReader.h:237
virtual bool ReadFullVersionInformation(StringRef FullVersion)
Receives the full Clang version information.
Definition: ASTReader.h:122
virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value)
Receives COUNTER value.
Definition: ASTReader.h:209
virtual void ReadModuleName(StringRef ModuleName)
Definition: ASTReader.h:126
virtual bool needsSystemInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.h:222
virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines)
Receives the preprocessor options.
Definition: ASTReader.h:202
RAII object to temporarily add an AST callback listener.
Definition: ASTReader.h:1696
ListenerScope(ASTReader &Reader, std::unique_ptr< ASTReaderListener > L)
Definition: ASTReader.h:1701
bool operator==(const ModuleDeclIterator &RHS) const
Definition: ASTReader.h:1490
ModuleDeclIterator(ASTReader *Reader, ModuleFile *Mod, const serialization::unaligned_decl_id_t *Pos)
Definition: ASTReader.h:1479
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:366
std::optional< bool > isPreprocessedEntityInFileID(unsigned Index, FileID FID) override
Optionally returns true or false if the preallocated preprocessed entity with index Index came from f...
Definition: ASTReader.cpp:6469
PreprocessedEntity * ReadPreprocessedEntity(unsigned Index) override
Read a preallocated preprocessed entity from the external source.
Definition: ASTReader.cpp:6250
void markIdentifierUpToDate(const IdentifierInfo *II)
Note that this identifier is up-to-date.
Definition: ASTReader.cpp:2293
void visitTopLevelModuleMaps(serialization::ModuleFile &MF, llvm::function_ref< void(FileEntryRef)> Visitor)
Visit all the top-level module maps loaded when building the given module file.
Definition: ASTReader.cpp:9626
void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership=false)
Set the AST deserialization listener.
Definition: ASTReader.cpp:901
SmallVectorImpl< uint64_t > RecordDataImpl
Definition: ASTReader.h:381
serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const
Retrieve the global submodule ID given a module and its local ID number.
Definition: ASTReader.cpp:9037
ExtKind hasExternalDefinitions(const Decl *D) override
Definition: ASTReader.cpp:9118
IdentifierTable & getIdentifierTable()
Retrieve the identifier table associated with the preprocessor.
Definition: ASTReader.cpp:9501
SourceLocationEncoding::RawLocEncoding RawLocEncoding
Definition: ASTReader.h:2229
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1767
ASTReader & operator=(const ASTReader &)=delete
bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
Definition: ASTReader.cpp:7698
bool ReadSLocEntry(int ID) override
Read the source location entry with index ID.
Definition: ASTReader.cpp:1576
void RecordSwitchCaseID(SwitchCase *SC, unsigned ID)
Record that the given ID maps to the given switch-case statement.
Definition: ASTReader.cpp:9507
DiagnosticBuilder Diag(unsigned DiagID) const
Report a diagnostic.
Definition: ASTReader.cpp:9477
unsigned getTotalNumPreprocessedEntities() const
Returns the number of preprocessed entities known to the AST reader.
Definition: ASTReader.h:1874
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Definition: ASTReader.h:2375
Decl * ReadDecl(ModuleFile &F, const RecordDataImpl &R, unsigned &I)
Reads a declaration from the given position in a record in the given module.
Definition: ASTReader.h:1954
ModuleManager::ModuleIterator ModuleIterator
Definition: ASTReader.h:414
static std::string ReadString(const RecordDataImpl &Record, unsigned &Idx)
Definition: ASTReader.cpp:9436
void ReadDeclsToCheckForDeferredDiags(llvm::SmallSetVector< Decl *, 4 > &Decls) override
Read the set of decls to be checked for deferred diags.
Definition: ASTReader.cpp:8753
void InitializeSema(Sema &S) override
Initialize the semantic source with the Sema instance being used to perform semantic analysis on the ...
Definition: ASTReader.cpp:8261
LoadFailureCapabilities
Flags that indicate what kind of AST loading failures the client of the AST reader can directly handl...
Definition: ASTReader.h:1603
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
Definition: ASTReader.h:1609
@ ARR_None
The client can't handle any AST loading failures.
Definition: ASTReader.h:1605
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition: ASTReader.h:1622
@ ARR_OutOfDate
The client can handle an AST file that cannot load because it is out-of-date relative to its input fi...
Definition: ASTReader.h:1613
@ ARR_TreatModuleWithErrorsAsOutOfDate
If a module file is marked with errors treat it as out-of-date so the caller can rebuild it.
Definition: ASTReader.h:1626
@ ARR_VersionMismatch
The client can handle an AST file that cannot load because it was built with a different version of C...
Definition: ASTReader.h:1617
void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &Exprs) override
Definition: ASTReader.cpp:8683
void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl< Decl * > &Decls) override
Get the decls that are contained in a file in the Offset/Length range.
Definition: ASTReader.cpp:7991
SourceRange ReadSkippedRange(unsigned Index) override
Read a preallocated skipped range from the external source.
Definition: ASTReader.cpp:6236
serialization::TypeID getGlobalTypeID(ModuleFile &F, serialization::LocalTypeID LocalID) const
Map a local type ID within a given AST file into a global type ID.
Definition: ASTReader.cpp:7463
const std::string & getSuggestedPredefines()
Returns the suggested contents of the predefines buffer, which contains a (typically-empty) subset of...
Definition: ASTReader.h:1811
void dump()
Dump information about the AST reader to standard error.
Definition: ASTReader.cpp:8228
void AssignedLambdaNumbering(const CXXRecordDecl *Lambda) override
Notify the external source that a lambda was assigned a mangling number.
Definition: ASTReader.cpp:8853
MacroInfo * ReadMacroRecord(ModuleFile &F, uint64_t Offset)
Reads the macro record located at the given offset.
Definition: ASTReader.cpp:1875
SmallVector< std::pair< llvm::BitstreamCursor, serialization::ModuleFile * >, 8 > CommentsCursors
Cursors for comments blocks.
Definition: ASTReader.h:2409
Selector getLocalSelector(ModuleFile &M, unsigned LocalID)
Retrieve a selector from the given module with its local ID number.
Definition: ASTReader.cpp:9125
void FindExternalLexicalDecls(const DeclContext *DC, llvm::function_ref< bool(Decl::Kind)> IsKindWeWant, SmallVectorImpl< Decl * > &Decls) override
Read all of the declarations lexically stored in a declaration context.
Definition: ASTReader.cpp:7913
ModuleFile * getOwningModuleFile(const Decl *D) const
Retrieve the module file that owns the given declaration, or NULL if the declaration is not from a mo...
Definition: ASTReader.cpp:7718
std::optional< ASTSourceDescriptor > getSourceDescriptor(unsigned ID) override
Return a descriptor for the corresponding module.
Definition: ASTReader.cpp:9100
const serialization::reader::DeclContextLookupTable * getLoadedLookupTables(DeclContext *Primary) const
Get the loaded lookup tables for Primary, if any.
Definition: ASTReader.cpp:8087
T * ReadDeclAs(ModuleFile &F, const RecordDataImpl &R, unsigned &I)
Reads a declaration from the given position in a record in the given module.
Definition: ASTReader.h:1964
QualType getLocalType(ModuleFile &F, serialization::LocalTypeID LocalID)
Resolve a local type ID within a given AST file into a type.
Definition: ASTReader.cpp:7459
void ClearSwitchCaseIDs()
Definition: ASTReader.cpp:9519
Sema::AlignPackInfo ReadAlignPackInfo(uint32_t Raw) const
Read a AlignPackInfo from raw form.
Definition: ASTReader.h:2225
QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Read a type from the current position in the given record, which was read from the given AST file.
Definition: ASTReader.h:1894
SourceLocation ReadSourceLocation(ModuleFile &MF, RawLocEncoding Raw, LocSeq *Seq=nullptr) const
Read a source location from raw form.
Definition: ASTReader.h:2240
void SetGloballyVisibleDecls(IdentifierInfo *II, const SmallVectorImpl< GlobalDeclID > &DeclIDs, SmallVectorImpl< Decl * > *Decls=nullptr)
Set the globally-visible declarations associated with the given identifier.
Definition: ASTReader.cpp:8894
serialization::ModuleKind ModuleKind
Definition: ASTReader.h:412
bool loadGlobalIndex()
Attempts to load the global index.
Definition: ASTReader.cpp:4338
void ReadComments() override
Loads comments ranges.
Definition: ASTReader.cpp:9523
SourceManager & getSourceManager() const
Definition: ASTReader.h:1594
SourceLocation getSourceLocationForDeclID(GlobalDeclID ID)
Returns the source location for the decl ID.
Definition: ASTReader.cpp:7725
void makeModuleVisible(Module *Mod, Module::NameVisibilityKind NameVisibility, SourceLocation ImportLoc)
Make the entities in the given module and any of its (non-explicit) submodules visible to name lookup...
Definition: ASTReader.cpp:4274
unsigned getTotalNumSubmodules() const
Returns the number of submodules known.
Definition: ASTReader.h:1863
ASTReader(const ASTReader &)=delete
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Definition: ASTReader.cpp:5227
Sema * getSema()
Retrieve the semantic analysis object used to analyze the translation unit in which the precompiled h...
Definition: ASTReader.h:2387
unsigned getTotalNumIdentifiers() const
Returns the number of identifiers found in the chain.
Definition: ASTReader.h:1843
CXXCtorInitializer ** GetExternalCXXCtorInitializers(uint64_t Offset) override
Read the contents of a CXXCtorInitializer array.
Definition: ASTReader.cpp:7601
void visitInputFileInfos(serialization::ModuleFile &MF, bool IncludeSystem, llvm::function_ref< void(const serialization::InputFileInfo &IFI, bool IsSystem)> Visitor)
Visit all the input file infos of the given module file.
Definition: ASTReader.cpp:9595
const ModuleManager & getModuleManager() const
Definition: ASTReader.h:1768
unsigned getTotalNumSLocs() const
Returns the number of source locations found in the chain.
Definition: ASTReader.h:1838
void StartTranslationUnit(ASTConsumer *Consumer) override
Function that will be invoked when we begin parsing a new translation unit involving this external AS...
Definition: ASTReader.cpp:8113
LocalDeclID mapGlobalIDToModuleFileGlobalID(ModuleFile &M, GlobalDeclID GlobalID)
Map a global declaration ID into the declaration ID used to refer to this declaration within the give...
Definition: ASTReader.cpp:7853
void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo)
Definition: ASTReader.cpp:2304
bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) override
Finds all the visible declarations with a given name.
Definition: ASTReader.cpp:8035
void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs) override
Read the set of tentative definitions known to the external Sema source.
Definition: ASTReader.cpp:8699
Decl * GetExternalDecl(GlobalDeclID ID) override
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7542
std::pair< SourceLocation, unsigned > ReadUntranslatedSourceLocation(RawLocEncoding Raw, LocSeq *Seq=nullptr) const
Read a source location from raw form and return it in its originating module file's source location s...
Definition: ASTReader.h:2234
GlobalDeclID ReadDeclID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx)
Reads a declaration ID from the given position in a record in the given module.
Definition: ASTReader.cpp:7882
llvm::Expected< SourceLocation::UIntTy > readSLocOffset(ModuleFile *F, unsigned Index)
Try to read the offset of the SLocEntry at the given index in the given module file.
Definition: ASTReader.cpp:1504
void forEachImportedKeyDecl(const Decl *D, Fn Visit)
Run a callback on each imported key declaration of D.
Definition: ASTReader.h:1327
~ASTReader() override
static void SkipPath(const RecordData &Record, unsigned &Idx)
Definition: ASTReader.h:2313
Stmt * ReadSubStmt()
Reads a sub-statement operand during statement reading.
Definition: ASTReader.h:2330
void CompleteRedeclChain(const Decl *D) override
If any redeclarations of D have been imported since it was last checked, this digs out those redeclar...
Definition: ASTReader.cpp:7544
Expr * ReadSubExpr()
Reads a sub-expression operand during statement reading.
SourceLocation TranslateSourceLocation(ModuleFile &ModuleFile, SourceLocation Loc) const
Translate a source location from another module file's source location space into ours.
Definition: ASTReader.h:2257
static llvm::Error ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID, uint64_t *StartOfBlockOffset=nullptr)
ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the specified cursor.
Definition: ASTReader.cpp:1796
void SetIdentifierInfo(serialization::IdentifierID ID, IdentifierInfo *II)
Definition: ASTReader.cpp:8869
serialization::PreprocessedEntityID getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const
Determine the global preprocessed entity ID that corresponds to the given local ID within the given m...
Definition: ASTReader.cpp:2006
std::pair< unsigned, unsigned > findPreprocessedEntitiesInRange(SourceRange Range) override
Returns a pair of [Begin, End) indices of preallocated preprocessed entities that Range encompasses.
Definition: ASTReader.cpp:6456
IdentifierInfo * get(StringRef Name) override
Retrieve the IdentifierInfo for the named identifier.
Definition: ASTReader.cpp:8392
IdentifierInfo * getLocalIdentifier(ModuleFile &M, uint64_t LocalID)
Definition: ASTReader.cpp:8972
void visitInputFiles(serialization::ModuleFile &MF, bool IncludeSystem, bool Complain, llvm::function_ref< void(const serialization::InputFile &IF, bool isSystem)> Visitor)
Visit all the input files of the given module file.
Definition: ASTReader.cpp:9611
Module * getModule(unsigned ID) override
Retrieve the module that corresponds to the given module ID.
Definition: ASTReader.cpp:9066
llvm::iterator_range< ModuleDeclIterator > getModuleFileLevelDecls(ModuleFile &Mod)
Definition: ASTReader.cpp:6229
Stmt * GetExternalDeclStmt(uint64_t Offset) override
Resolve the offset of a statement into a statement.
Definition: ASTReader.cpp:7897
Selector GetExternalSelector(serialization::SelectorID ID) override
Resolve a selector ID into a selector.
Definition: ASTReader.cpp:9154
unsigned getTotalNumSelectors() const
Returns the number of selectors found in the chain.
Definition: ASTReader.h:1868
MacroInfo * getMacro(serialization::MacroID ID)
Retrieve the macro with the given ID.
Definition: ASTReader.cpp:8995
void ReadUndefinedButUsed(llvm::MapVector< NamedDecl *, SourceLocation > &Undefined) override
Load the set of used but not defined functions or variables with internal linkage,...
Definition: ASTReader.cpp:8672
void ReadDelegatingConstructors(SmallVectorImpl< CXXConstructorDecl * > &Decls) override
Read the set of delegating constructors known to the external Sema source.
Definition: ASTReader.cpp:8720
unsigned getTotalNumTypes() const
Returns the number of types found in the chain.
Definition: ASTReader.h:1853
QualType GetType(serialization::TypeID ID)
Resolve a type ID into a type, potentially building a new type.
Definition: ASTReader.cpp:7161
void addPendingMacro(IdentifierInfo *II, ModuleFile *M, uint32_t MacroDirectivesOffset)
Add a macro to deserialize its macro directive history.
Definition: ASTReader.cpp:2144
SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx, LocSeq *Seq=nullptr)
Read a source range.
Definition: ASTReader.cpp:9411
GlobalDeclID getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const
Map from a local declaration ID within a given module to a global declaration ID.
Definition: ASTReader.cpp:7675
Expr * ReadExpr(ModuleFile &F)
Reads an expression.
void ReadWeakUndeclaredIdentifiers(SmallVectorImpl< std::pair< IdentifierInfo *, WeakInfo > > &WeakIDs) override
Read the set of weak, undeclared identifiers known to the external Sema source.
Definition: ASTReader.cpp:8781
void completeVisibleDeclsMap(const DeclContext *DC) override
Load all external visible decls in the given DeclContext.
Definition: ASTReader.cpp:8063
void warnStackExhausted(SourceLocation Loc)
Definition: ASTReader.cpp:9485
void ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector< const TypedefNameDecl *, 4 > &Decls) override
Read the set of potentially unused typedefs known to the source.
Definition: ASTReader.cpp:8741
IdentifierResolver & getIdResolver()
Get the identifier resolver used for name lookup / updates in the translation unit scope.
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const InMemoryModuleCache &ModuleCache, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions, unsigned ClientLoadCapabilities=ARR_ConfigurationMismatch|ARR_OutOfDate)
Read the control block for the named AST file.
Definition: ASTReader.cpp:5395
void ReadExtVectorDecls(SmallVectorImpl< TypedefNameDecl * > &Decls) override
Read the set of ext_vector type declarations known to the external Sema source.
Definition: ASTReader.cpp:8731
void ResolveImportedPath(ModuleFile &M, std::string &Filename)
If we are loading a relocatable PCH or module file, and the filename is not an absolute path,...
Definition: ASTReader.cpp:2730
static void SkipString(const RecordData &Record, unsigned &Idx)
Definition: ASTReader.h:2301
SmallVector< GlobalDeclID, 16 > PreloadedDeclIDs
Definition: ASTReader.h:2382
std::pair< SourceLocation, StringRef > getModuleImportLoc(int ID) override
Retrieve the module import location and module name for the given source manager entry ID.
Definition: ASTReader.cpp:1759
void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls) override
Read the set of unused file-scope declarations known to the external Sema source.
Definition: ASTReader.cpp:8709
void ReadReferencedSelectors(SmallVectorImpl< std::pair< Selector, SourceLocation > > &Sels) override
Read the set of referenced selectors known to the external Sema source.
Definition: ASTReader.cpp:8763
Selector DecodeSelector(serialization::SelectorID Idx)
Definition: ASTReader.cpp:9129
ASTReadResult ReadAST(StringRef FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities, ModuleFile **NewLoadedModuleFile=nullptr)
Load the AST file designated by the given file name.
Definition: ASTReader.cpp:4429
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition: ASTReader.h:1775
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9443
ASTDeserializationListener * getDeserializationListener()
Get the AST deserialization listener.
Definition: ASTReader.h:1725
void addListener(std::unique_ptr< ASTReaderListener > L)
Add an AST callback listener.
Definition: ASTReader.h:1688
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
Definition: ASTReader.cpp:9083
Decl * getKeyDeclaration(Decl *D)
Returns the first key declaration for the given declaration.
Definition: ASTReader.h:1311
void setListener(std::unique_ptr< ASTReaderListener > Listener)
Set the AST callbacks listener.
Definition: ASTReader.h:1681
Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.h:2212
ModuleManager::ModuleReverseIterator ModuleReverseIterator
Definition: ASTReader.h:416
IdentifierInfo * DecodeIdentifierInfo(serialization::IdentifierID ID)
Definition: ASTReader.cpp:8942
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons.
Definition: ASTReader.h:385
@ Success
The control block was read successfully.
Definition: ASTReader.h:388
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition: ASTReader.h:405
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition: ASTReader.h:398
@ Failure
The AST file itself appears corrupted.
Definition: ASTReader.h:391
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition: ASTReader.h:401
@ HadErrors
The AST file has errors.
Definition: ASTReader.h:408
@ Missing
The AST file was missing.
Definition: ASTReader.h:394
void addInMemoryBuffer(StringRef &FileName, std::unique_ptr< llvm::MemoryBuffer > Buffer)
Add in-memory (virtual file) buffer.
Definition: ASTReader.h:1754
static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx)
Read a version tuple.
Definition: ASTReader.cpp:9458
Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx)
Reads a token out of a record.
Definition: ASTReader.cpp:1823
SwitchCase * getSwitchCaseWithID(unsigned ID)
Retrieve the switch-case statement with the given ID.
Definition: ASTReader.cpp:9514
serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, uint64_t LocalID)
Definition: ASTReader.cpp:8976
FileID TranslateFileID(ModuleFile &F, FileID FID) const
Translate a FileID from another module file's FileID space into ours.
Definition: ASTReader.h:2285
void ReadLateParsedTemplates(llvm::MapVector< const FunctionDecl *, std::unique_ptr< LateParsedTemplate > > &LPTMap) override
Read the set of late parsed template functions for this source.
Definition: ASTReader.cpp:8824
IdentifierIterator * getIdentifiers() override
Retrieve an iterator into the set of all identifiers in all loaded AST files.
Definition: ASTReader.cpp:8517
void ReadUsedVTables(SmallVectorImpl< ExternalVTableUse > &VTables) override
Read the set of used vtables known to the external Sema source.
Definition: ASTReader.cpp:8799
bool isGlobalIndexUnavailable() const
Determine whether we tried to load the global index, but failed, e.g., because it is out-of-date or d...
Definition: ASTReader.cpp:4363
uint32_t GetNumExternalSelectors() override
Returns the number of selectors known to the external AST source.
Definition: ASTReader.cpp:9158
void updateOutOfDateSelector(Selector Sel) override
Load the contents of the global method pool for a given selector if necessary.
Definition: ASTReader.cpp:8656
Decl * GetExistingDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration.
Definition: ASTReader.cpp:7806
Stmt * ReadStmt(ModuleFile &F)
Reads a statement.
static llvm::BitVector ReadBitVector(const RecordData &Record, const StringRef Blob)
Definition: ASTReader.cpp:9418
ModuleFile * getLocalModuleFile(ModuleFile &M, unsigned ID) const
Retrieve the module file with a given local ID within the specified ModuleFile.
Definition: ASTReader.cpp:9070
void ForgetSema() override
Inform the semantic consumer that Sema is no longer available.
Definition: ASTReader.h:2051
DiagnosticsEngine & getDiags() const
Definition: ASTReader.h:1596
void LoadSelector(Selector Sel)
Load a selector from disk, registering its ID if it exists.
Definition: ASTReader.cpp:8864
void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag)
Definition: ASTReader.cpp:6528
void makeNamesVisible(const HiddenNames &Names, Module *Owner)
Make the names within this set of hidden names visible.
Definition: ASTReader.cpp:4260
void UpdateSema()
Update the state of Sema after loading some additional modules.
Definition: ASTReader.cpp:8287
Decl * GetDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7832
Decl * GetLocalDecl(ModuleFile &F, LocalDeclID LocalID)
Reads a declaration with the given local ID in the given module.
Definition: ASTReader.h:1926
bool isProcessingUpdateRecords()
Definition: ASTReader.h:2432
T * GetLocalDeclAs(ModuleFile &F, LocalDeclID LocalID)
Reads a declaration with the given local ID in the given module.
Definition: ASTReader.h:1933
ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache, ASTContext *Context, const PCHContainerReader &PCHContainerRdr, ArrayRef< std::shared_ptr< ModuleFileExtension > > Extensions, StringRef isysroot="", DisableValidationForModuleKind DisableValidationKind=DisableValidationForModuleKind::None, bool AllowASTWithCompilerErrors=false, bool AllowConfigurationMismatch=false, bool ValidateSystemInputs=false, bool ValidateASTInputFilesContent=false, bool UseGlobalIndex=true, std::unique_ptr< llvm::Timer > ReadTimer={})
Load the AST file and validate its contents against the given Preprocessor.
int getSLocEntryID(SourceLocation::UIntTy SLocOffset) override
Get the index ID for the loaded SourceLocation offset.
Definition: ASTReader.cpp:1539
void ReadPendingInstantiations(SmallVectorImpl< std::pair< ValueDecl *, SourceLocation > > &Pending) override
Read the set of pending instantiations known to the external Sema source.
Definition: ASTReader.cpp:8812
Preprocessor & getPreprocessor() const
Retrieve the preprocessor.
Definition: ASTReader.h:1771
CXXTemporary * ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9470
void ReadKnownNamespaces(SmallVectorImpl< NamespaceDecl * > &Namespaces) override
Load the set of namespaces that are known to the external source, which will be used during typo corr...
Definition: ASTReader.cpp:8661
const Decl * getKeyDeclaration(const Decl *D)
Definition: ASTReader.h:1321
ModuleManager::ModuleConstIterator ModuleConstIterator
Definition: ASTReader.h:415
Module * getSubmodule(serialization::SubmoduleID GlobalID)
Retrieve the submodule that corresponds to a global submodule ID.
Definition: ASTReader.cpp:9052
void PrintStats() override
Print some statistics about AST usage.
Definition: ASTReader.cpp:8123
void mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef)
Note that MergedDef is a redefinition of the canonical definition Def, so Def should be visible whene...
Definition: ASTReader.cpp:4323
serialization::SelectorID getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const
Retrieve the global selector ID that corresponds to this the local selector ID in a given module.
Definition: ASTReader.cpp:9164
SmallVector< uint64_t, 64 > RecordData
Definition: ASTReader.h:380
unsigned getTotalNumMacros() const
Returns the number of macros found in the chain.
Definition: ASTReader.h:1848
FileID ReadFileID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx) const
Read a FileID.
Definition: ASTReader.h:2279
void StartedDeserializing() override
Notify ASTReader that we started deserialization of a decl or type so until FinishedDeserializing is ...
void ReadMethodPool(Selector Sel) override
Load the contents of the global method pool for a given selector.
Definition: ASTReader.cpp:8616
void InitializeContext()
Initializes the ASTContext.
Definition: ASTReader.cpp:5084
CXXBaseSpecifier * GetExternalCXXBaseSpecifiers(uint64_t Offset) override
Resolve the offset of a set of C++ base specifiers in the decl stream into an array of specifiers.
Definition: ASTReader.cpp:7633
std::unique_ptr< ASTReaderListener > takeListener()
Take the AST callbacks listener.
Definition: ASTReader.h:1676
void resetForReload()
Reset reader for a reload try.
Definition: ASTReader.h:1736
FileManager & getFileManager() const
Definition: ASTReader.h:1595
unsigned getTotalNumDecls() const
Returns the number of declarations found in the chain.
Definition: ASTReader.h:1858
static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, const InMemoryModuleCache &ModuleCache, const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts, const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts, StringRef ExistingModuleCachePath, bool RequireStrictOptionMatches=false)
Determine whether the given AST file is acceptable to load into a translation unit with the given lan...
Definition: ASTReader.cpp:5689
void FinishedDeserializing() override
Notify ASTReader that we finished the deserialization of a decl or type.
IdentifierInfo * readIdentifier(ModuleFile &M, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.h:2138
void updateOutOfDateIdentifier(const IdentifierInfo &II) override
Update an out-of-date identifier.
Definition: ASTReader.cpp:2268
void ReadDefinedMacros() override
Read the set of macros defined by this external macro source.
Definition: ASTReader.cpp:2150
GlobalModuleIndex * getGlobalIndex()
Return global module index.
Definition: ASTReader.h:1733
IdentifierInfo * GetIdentifier(serialization::IdentifierID ID) override
Return the identifier associated with the given ID number.
Definition: ASTReader.h:2143
HeaderFileInfo GetHeaderFileInfo(FileEntryRef FE) override
Read the header file information for the given file entry.
Definition: ASTReader.cpp:6519
SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, const RecordDataImpl &Record, unsigned &Idx, LocSeq *Seq=nullptr)
Read a source location.
Definition: ASTReader.h:2272
serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID)
Retrieve the global macro ID corresponding to the given local ID within the given module file.
Definition: ASTReader.cpp:9022
serialization::ModuleFile ModuleFile
Definition: ASTReader.h:411
bool hasGlobalIndex() const
Determine whether this AST reader has a global index.
Definition: ASTReader.h:1730
An object for streaming information from a record.
Utility class for loading a ASTContext from an AST file.
Definition: ASTUnit.h:89
Writes an AST file containing the contents of a translation unit.
Definition: ASTWriter.h:89
A simple helper class to unpack an integer to bits and consuming the bits in order.
Definition: ASTReader.h:2437
BitsUnpacker operator=(const BitsUnpacker &)=delete
uint32_t getNextBits(uint32_t Width)
Definition: ASTReader.h:2460
void advance(uint32_t BitsWidth)
Definition: ASTReader.h:2453
bool canGetNextNBits(uint32_t Width) const
Definition: ASTReader.h:2468
BitsUnpacker(BitsUnpacker &&)=delete
BitsUnpacker(const BitsUnpacker &)=delete
void updateValue(uint32_t V)
Definition: ASTReader.h:2448
BitsUnpacker operator=(BitsUnpacker &&)=delete
BitsUnpacker(uint32_t V)
Definition: ASTReader.h:2441
~BitsUnpacker()=default
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2300
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
Represents a C++ temporary.
Definition: ExprCXX.h:1457
Simple wrapper class for chaining listeners.
Definition: ASTReader.h:249
bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule) override
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
Definition: ASTReader.cpp:246
std::unique_ptr< ASTReaderListener > takeSecond()
Definition: ASTReader.h:260
bool ReadFullVersionInformation(StringRef FullVersion) override
Receives the full Clang version information.
Definition: ASTReader.cpp:159
bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) override
Receives the file system options.
Definition: ASTReader.cpp:200
std::unique_ptr< ASTReaderListener > takeFirst()
Definition: ASTReader.h:259
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:215
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:224
void ReadModuleMapFile(StringRef ModuleMapPath) override
Definition: ASTReader.cpp:169
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:206
bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:184
void ReadModuleName(StringRef ModuleName) override
Definition: ASTReader.cpp:164
bool needsInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.cpp:230
ChainedASTReaderListener(std::unique_ptr< ASTReaderListener > First, std::unique_ptr< ASTReaderListener > Second)
Takes ownership of First and Second.
Definition: ASTReader.h:255
bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:175
void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata) override
Indicates that a particular module file extension has been read.
Definition: ASTReader.cpp:262
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:193
void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind) override
This is called for each AST file loaded.
Definition: ASTReader.cpp:240
bool needsSystemInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.cpp:235
A map from continuous integer ranges to some value, with a very specialized interface.
typename Representation::const_iterator const_iterator
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1425
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
bool isFromExplicitGlobalModule() const
Whether this declaration comes from explicit global module.
Definition: DeclBase.cpp:1144
The name of a declaration.
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1271
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
This represents one expression.
Definition: Expr.h:110
RAII class for safely pairing a StartedDeserializing call with FinishedDeserializing.
MemoryBufferSizes getMemoryBufferSizes() const
Return the amount of memory used by memory buffers, breaking down by heap-backed versus mmap'ed memor...
An external source of header file information, which may supply information about header files alread...
Definition: HeaderSearch.h:159
An abstract class that should be subclassed by any external source of preprocessing record entries.
Abstract interface for external sources of preprocessor information.
External source of source location entries.
An abstract interface that should be implemented by external AST sources that also provide informatio...
Represents a member of a struct/union/class.
Definition: Decl.h:3030
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition: FileEntry.h:57
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
Keeps track of options that affect how file operations are performed.
Represents a function declaration or definition.
Definition: Decl.h:1932
A global index for a set of module files, providing information about the identifiers within those mo...
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
Provides lookups to, and iteration over, IdentiferInfo objects.
One of these records is kept for each identifier that is lexed.
An iterator that walks over all of the known identifiers in the lookup table.
IdentifierResolver - Keeps track of shadowed decls on enclosing scopes.
Implements an efficient mapping from strings to IdentifierInfo nodes.
In-memory cache for modules.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
static LocalDeclID get(ASTReader &Reader, serialization::ModuleFile &MF, DeclID ID)
Definition: ASTReader.cpp:911
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:39
Describes a module or submodule.
Definition: Module.h:105
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition: Module.h:387
This represents a decl that may have a name.
Definition: Decl.h:249
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
ASTReaderListener implementation to validate the information of the PCH file against an initialized P...
Definition: ASTReader.h:294
PCHValidator(Preprocessor &PP, ASTReader &Reader)
Definition: ASTReader.h:299
bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:461
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:868
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:816
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:858
bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:452
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:581
Base class that describes a preprocessed entity, which may be a preprocessor directive or macro expan...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:137
A (possibly-)qualified type.
Definition: Type.h:941
Smart pointer class that efficiently represents Objective-C method names.
static AlignPackInfo getFromRawEncoding(unsigned Encoding)
Definition: Sema.h:1559
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:535
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition: ASTReader.h:321
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:826
SimpleASTReaderListener(Preprocessor &PP)
Definition: ASTReader.h:325
static std::pair< SourceLocation, unsigned > decode(RawLocEncoding, SourceLocationSequence *=nullptr)
Serialized encoding of a sequence of SourceLocations.
Encodes a location in the source.
This class handles loading and caching of source files into memory.
bool isLoadedSourceLocation(SourceLocation Loc) const
Returns true if Loc came from a PCH/Module.
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
Definition: Stmt.h:84
Options for controlling the target.
Definition: TargetOptions.h:26
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
The base class of the type hierarchy.
Definition: Type.h:1829
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
The input file that has been loaded from this AST file, along with bools indicating whether this was ...
Definition: ModuleFile.h:78
Information about a module that has been loaded by the ASTReader.
Definition: ModuleFile.h:124
int SLocEntryBaseID
The base ID in the source manager's view of this module.
Definition: ModuleFile.h:285
std::string OriginalSourceFileName
The original source file name that was used to build the primary AST file, which may have been modifi...
Definition: ModuleFile.h:154
StringRef ModuleOffsetMap
The module offset map data for this file.
Definition: ModuleFile.h:244
SourceLocation::UIntTy SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Definition: ModuleFile.h:288
llvm::SmallVector< ModuleFile *, 16 > TransitiveImports
List of modules which this modules dependent on.
Definition: ModuleFile.h:502
Manages the set of modules loaded by an AST reader.
Definition: ModuleManager.h:46
ModuleFile & getPrimaryModule()
Returns the primary module associated with the manager, that is, the first module loaded.
llvm::pointee_iterator< SmallVectorImpl< std::unique_ptr< ModuleFile > >::const_iterator > ModuleConstIterator
void addInMemoryBuffer(StringRef FileName, std::unique_ptr< llvm::MemoryBuffer > Buffer)
Add an in-memory buffer the list of known buffers.
llvm::pointee_iterator< SmallVectorImpl< std::unique_ptr< ModuleFile > >::reverse_iterator > ModuleReverseIterator
llvm::pointee_iterator< SmallVectorImpl< std::unique_ptr< ModuleFile > >::iterator > ModuleIterator
Class that performs lookup for an identifier stored in an AST file.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
uint64_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:88
llvm::support::detail::packed_endian_specific_integral< serialization::DeclID, llvm::endianness::native, llvm::support::unaligned > unaligned_decl_id_t
Definition: ASTBitCodes.h:286
TypeID LocalTypeID
Same with TypeID except that the LocalTypeID is only meaningful with the corresponding ModuleFile.
Definition: ASTBitCodes.h:94
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
Definition: ASTBitCodes.h:185
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
Definition: ASTBitCodes.h:167
uint32_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
Definition: ASTBitCodes.h:182
ModuleKind
Specifies the kind of module that has been loaded.
Definition: ModuleFile.h:42
uint64_t IdentifierID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:63
uint32_t MacroID
An ID number that refers to a macro in an AST file.
Definition: ASTBitCodes.h:154
The JSON file list parser is used to communicate input to InstallAPI.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
@ Result
The result type of a method or function.
const FunctionProtoType * T
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
@ None
Perform validation, don't disable it.
bool shouldSkipCheckingODR(const Decl *D)
Definition: ASTReader.h:2479
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:68
unsigned long uint64_t
The preprocessor keeps track of this information for each file that is #included.
Definition: HeaderSearch.h:59
Metadata for a module file extension.
The input file info that has been loaded from an AST file.
Definition: ModuleFile.h:63