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