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