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 /// Get a predefined Decl from ASTContext.
1545 Decl *getPredefinedDecl(PredefinedDeclIDs ID);
1546
1547 public:
1548 /// Load the AST file and validate its contents against the given
1549 /// Preprocessor.
1550 ///
1551 /// \param PP the preprocessor associated with the context in which this
1552 /// precompiled header will be loaded.
1553 ///
1554 /// \param Context the AST context that this precompiled header will be
1555 /// loaded into, if any.
1556 ///
1557 /// \param PCHContainerRdr the PCHContainerOperations to use for loading and
1558 /// creating modules.
1559 ///
1560 /// \param Extensions the list of module file extensions that can be loaded
1561 /// from the AST files.
1562 ///
1563 /// \param isysroot If non-NULL, the system include path specified by the
1564 /// user. This is only used with relocatable PCH files. If non-NULL,
1565 /// a relocatable PCH file will use the default path "/".
1566 ///
1567 /// \param DisableValidationKind If set, the AST reader will suppress most
1568 /// of its regular consistency checking, allowing the use of precompiled
1569 /// headers and module files that cannot be determined to be compatible.
1570 ///
1571 /// \param AllowASTWithCompilerErrors If true, the AST reader will accept an
1572 /// AST file the was created out of an AST with compiler errors,
1573 /// otherwise it will reject it.
1574 ///
1575 /// \param AllowConfigurationMismatch If true, the AST reader will not check
1576 /// for configuration differences between the AST file and the invocation.
1577 ///
1578 /// \param ValidateSystemInputs If true, the AST reader will validate
1579 /// system input files in addition to user input files. This is only
1580 /// meaningful if \p DisableValidation is false.
1581 ///
1582 /// \param UseGlobalIndex If true, the AST reader will try to load and use
1583 /// the global module index.
1584 ///
1585 /// \param ReadTimer If non-null, a timer used to track the time spent
1586 /// deserializing.
1587 ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
1588 ASTContext *Context, const PCHContainerReader &PCHContainerRdr,
1589 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
1590 StringRef isysroot = "",
1591 DisableValidationForModuleKind DisableValidationKind =
1592 DisableValidationForModuleKind::None,
1593 bool AllowASTWithCompilerErrors = false,
1594 bool AllowConfigurationMismatch = false,
1595 bool ValidateSystemInputs = false,
1596 bool ValidateASTInputFilesContent = false,
1597 bool UseGlobalIndex = true,
1598 std::unique_ptr<llvm::Timer> ReadTimer = {});
1599 ASTReader(const ASTReader &) = delete;
1600 ASTReader &operator=(const ASTReader &) = delete;
1601 ~ASTReader() override;
1602
getSourceManager()1603 SourceManager &getSourceManager() const { return SourceMgr; }
getFileManager()1604 FileManager &getFileManager() const { return FileMgr; }
getDiags()1605 DiagnosticsEngine &getDiags() const { return Diags; }
1606
1607 /// Flags that indicate what kind of AST loading failures the client
1608 /// of the AST reader can directly handle.
1609 ///
1610 /// When a client states that it can handle a particular kind of failure,
1611 /// the AST reader will not emit errors when producing that kind of failure.
1612 enum LoadFailureCapabilities {
1613 /// The client can't handle any AST loading failures.
1614 ARR_None = 0,
1615
1616 /// The client can handle an AST file that cannot load because it
1617 /// is missing.
1618 ARR_Missing = 0x1,
1619
1620 /// The client can handle an AST file that cannot load because it
1621 /// is out-of-date relative to its input files.
1622 ARR_OutOfDate = 0x2,
1623
1624 /// The client can handle an AST file that cannot load because it
1625 /// was built with a different version of Clang.
1626 ARR_VersionMismatch = 0x4,
1627
1628 /// The client can handle an AST file that cannot load because it's
1629 /// compiled configuration doesn't match that of the context it was
1630 /// loaded into.
1631 ARR_ConfigurationMismatch = 0x8,
1632
1633 /// If a module file is marked with errors treat it as out-of-date so the
1634 /// caller can rebuild it.
1635 ARR_TreatModuleWithErrorsAsOutOfDate = 0x10
1636 };
1637
1638 /// Load the AST file designated by the given file name.
1639 ///
1640 /// \param FileName The name of the AST file to load.
1641 ///
1642 /// \param Type The kind of AST being loaded, e.g., PCH, module, main file,
1643 /// or preamble.
1644 ///
1645 /// \param ImportLoc the location where the module file will be considered as
1646 /// imported from. For non-module AST types it should be invalid.
1647 ///
1648 /// \param ClientLoadCapabilities The set of client load-failure
1649 /// capabilities, represented as a bitset of the enumerators of
1650 /// LoadFailureCapabilities.
1651 ///
1652 /// \param LoadedModuleFile The optional out-parameter refers to the new
1653 /// loaded modules. In case the module specified by FileName is already
1654 /// loaded, the module file pointer referred by NewLoadedModuleFile wouldn't
1655 /// change. Otherwise if the AST file get loaded successfully,
1656 /// NewLoadedModuleFile would refer to the address of the new loaded top level
1657 /// module. The state of NewLoadedModuleFile is unspecified if the AST file
1658 /// isn't loaded successfully.
1659 ASTReadResult ReadAST(StringRef FileName, ModuleKind Type,
1660 SourceLocation ImportLoc,
1661 unsigned ClientLoadCapabilities,
1662 ModuleFile **NewLoadedModuleFile = nullptr);
1663
1664 /// Make the entities in the given module and any of its (non-explicit)
1665 /// submodules visible to name lookup.
1666 ///
1667 /// \param Mod The module whose names should be made visible.
1668 ///
1669 /// \param NameVisibility The level of visibility to give the names in the
1670 /// module. Visibility can only be increased over time.
1671 ///
1672 /// \param ImportLoc The location at which the import occurs.
1673 void makeModuleVisible(Module *Mod,
1674 Module::NameVisibilityKind NameVisibility,
1675 SourceLocation ImportLoc);
1676
1677 /// Make the names within this set of hidden names visible.
1678 void makeNamesVisible(const HiddenNames &Names, Module *Owner);
1679
1680 /// Note that MergedDef is a redefinition of the canonical definition
1681 /// Def, so Def should be visible whenever MergedDef is.
1682 void mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef);
1683
1684 /// Take the AST callbacks listener.
takeListener()1685 std::unique_ptr<ASTReaderListener> takeListener() {
1686 return std::move(Listener);
1687 }
1688
1689 /// Set the AST callbacks listener.
setListener(std::unique_ptr<ASTReaderListener> Listener)1690 void setListener(std::unique_ptr<ASTReaderListener> Listener) {
1691 this->Listener = std::move(Listener);
1692 }
1693
1694 /// Add an AST callback listener.
1695 ///
1696 /// Takes ownership of \p L.
addListener(std::unique_ptr<ASTReaderListener> L)1697 void addListener(std::unique_ptr<ASTReaderListener> L) {
1698 if (Listener)
1699 L = std::make_unique<ChainedASTReaderListener>(std::move(L),
1700 std::move(Listener));
1701 Listener = std::move(L);
1702 }
1703
1704 /// RAII object to temporarily add an AST callback listener.
1705 class ListenerScope {
1706 ASTReader &Reader;
1707 bool Chained = false;
1708
1709 public:
ListenerScope(ASTReader & Reader,std::unique_ptr<ASTReaderListener> L)1710 ListenerScope(ASTReader &Reader, std::unique_ptr<ASTReaderListener> L)
1711 : Reader(Reader) {
1712 auto Old = Reader.takeListener();
1713 if (Old) {
1714 Chained = true;
1715 L = std::make_unique<ChainedASTReaderListener>(std::move(L),
1716 std::move(Old));
1717 }
1718 Reader.setListener(std::move(L));
1719 }
1720
~ListenerScope()1721 ~ListenerScope() {
1722 auto New = Reader.takeListener();
1723 if (Chained)
1724 Reader.setListener(static_cast<ChainedASTReaderListener *>(New.get())
1725 ->takeSecond());
1726 }
1727 };
1728
1729 /// Set the AST deserialization listener.
1730 void setDeserializationListener(ASTDeserializationListener *Listener,
1731 bool TakeOwnership = false);
1732
1733 /// Get the AST deserialization listener.
getDeserializationListener()1734 ASTDeserializationListener *getDeserializationListener() {
1735 return DeserializationListener;
1736 }
1737
1738 /// Determine whether this AST reader has a global index.
hasGlobalIndex()1739 bool hasGlobalIndex() const { return (bool)GlobalIndex; }
1740
1741 /// Return global module index.
getGlobalIndex()1742 GlobalModuleIndex *getGlobalIndex() { return GlobalIndex.get(); }
1743
1744 /// Reset reader for a reload try.
resetForReload()1745 void resetForReload() { TriedLoadingGlobalIndex = false; }
1746
1747 /// Attempts to load the global index.
1748 ///
1749 /// \returns true if loading the global index has failed for any reason.
1750 bool loadGlobalIndex();
1751
1752 /// Determine whether we tried to load the global index, but failed,
1753 /// e.g., because it is out-of-date or does not exist.
1754 bool isGlobalIndexUnavailable() const;
1755
1756 /// Initializes the ASTContext
1757 void InitializeContext();
1758
1759 /// Update the state of Sema after loading some additional modules.
1760 void UpdateSema();
1761
1762 /// Add in-memory (virtual file) buffer.
addInMemoryBuffer(StringRef & FileName,std::unique_ptr<llvm::MemoryBuffer> Buffer)1763 void addInMemoryBuffer(StringRef &FileName,
1764 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
1765 ModuleMgr.addInMemoryBuffer(FileName, std::move(Buffer));
1766 }
1767
1768 /// Finalizes the AST reader's state before writing an AST file to
1769 /// disk.
1770 ///
1771 /// This operation may undo temporary state in the AST that should not be
1772 /// emitted.
1773 void finalizeForWriting();
1774
1775 /// Retrieve the module manager.
getModuleManager()1776 ModuleManager &getModuleManager() { return ModuleMgr; }
getModuleManager()1777 const ModuleManager &getModuleManager() const { return ModuleMgr; }
1778
1779 /// Retrieve the preprocessor.
getPreprocessor()1780 Preprocessor &getPreprocessor() const { return PP; }
1781
1782 /// Retrieve the name of the original source file name for the primary
1783 /// module file.
getOriginalSourceFile()1784 StringRef getOriginalSourceFile() {
1785 return ModuleMgr.getPrimaryModule().OriginalSourceFileName;
1786 }
1787
1788 /// Retrieve the name of the original source file name directly from
1789 /// the AST file, without actually loading the AST file.
1790 static std::string
1791 getOriginalSourceFile(const std::string &ASTFileName, FileManager &FileMgr,
1792 const PCHContainerReader &PCHContainerRdr,
1793 DiagnosticsEngine &Diags);
1794
1795 /// Read the control block for the named AST file.
1796 ///
1797 /// \returns true if an error occurred, false otherwise.
1798 static bool readASTFileControlBlock(
1799 StringRef Filename, FileManager &FileMgr,
1800 const InMemoryModuleCache &ModuleCache,
1801 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
1802 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
1803 unsigned ClientLoadCapabilities = ARR_ConfigurationMismatch |
1804 ARR_OutOfDate);
1805
1806 /// Determine whether the given AST file is acceptable to load into a
1807 /// translation unit with the given language and target options.
1808 static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
1809 const InMemoryModuleCache &ModuleCache,
1810 const PCHContainerReader &PCHContainerRdr,
1811 const LangOptions &LangOpts,
1812 const TargetOptions &TargetOpts,
1813 const PreprocessorOptions &PPOpts,
1814 StringRef ExistingModuleCachePath,
1815 bool RequireStrictOptionMatches = false);
1816
1817 /// Returns the suggested contents of the predefines buffer,
1818 /// which contains a (typically-empty) subset of the predefines
1819 /// build prior to including the precompiled header.
getSuggestedPredefines()1820 const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
1821
1822 /// Read a preallocated preprocessed entity from the external source.
1823 ///
1824 /// \returns null if an error occurred that prevented the preprocessed
1825 /// entity from being loaded.
1826 PreprocessedEntity *ReadPreprocessedEntity(unsigned Index) override;
1827
1828 /// Returns a pair of [Begin, End) indices of preallocated
1829 /// preprocessed entities that \p Range encompasses.
1830 std::pair<unsigned, unsigned>
1831 findPreprocessedEntitiesInRange(SourceRange Range) override;
1832
1833 /// Optionally returns true or false if the preallocated preprocessed
1834 /// entity with index \p Index came from file \p FID.
1835 std::optional<bool> isPreprocessedEntityInFileID(unsigned Index,
1836 FileID FID) override;
1837
1838 /// Read a preallocated skipped range from the external source.
1839 SourceRange ReadSkippedRange(unsigned Index) override;
1840
1841 /// Read the header file information for the given file entry.
1842 HeaderFileInfo GetHeaderFileInfo(FileEntryRef FE) override;
1843
1844 void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag);
1845
1846 /// Returns the number of source locations found in the chain.
getTotalNumSLocs()1847 unsigned getTotalNumSLocs() const {
1848 return TotalNumSLocEntries;
1849 }
1850
1851 /// Returns the number of identifiers found in the chain.
getTotalNumIdentifiers()1852 unsigned getTotalNumIdentifiers() const {
1853 return static_cast<unsigned>(IdentifiersLoaded.size());
1854 }
1855
1856 /// Returns the number of macros found in the chain.
getTotalNumMacros()1857 unsigned getTotalNumMacros() const {
1858 return static_cast<unsigned>(MacrosLoaded.size());
1859 }
1860
1861 /// Returns the number of types found in the chain.
getTotalNumTypes()1862 unsigned getTotalNumTypes() const {
1863 return static_cast<unsigned>(TypesLoaded.size());
1864 }
1865
1866 /// Returns the number of declarations found in the chain.
getTotalNumDecls()1867 unsigned getTotalNumDecls() const {
1868 return static_cast<unsigned>(DeclsLoaded.size());
1869 }
1870
1871 /// Returns the number of submodules known.
getTotalNumSubmodules()1872 unsigned getTotalNumSubmodules() const {
1873 return static_cast<unsigned>(SubmodulesLoaded.size());
1874 }
1875
1876 /// Returns the number of selectors found in the chain.
getTotalNumSelectors()1877 unsigned getTotalNumSelectors() const {
1878 return static_cast<unsigned>(SelectorsLoaded.size());
1879 }
1880
1881 /// Returns the number of preprocessed entities known to the AST
1882 /// reader.
getTotalNumPreprocessedEntities()1883 unsigned getTotalNumPreprocessedEntities() const {
1884 unsigned Result = 0;
1885 for (const auto &M : ModuleMgr)
1886 Result += M.NumPreprocessedEntities;
1887 return Result;
1888 }
1889
1890 /// Resolve a type ID into a type, potentially building a new
1891 /// type.
1892 QualType GetType(serialization::TypeID ID);
1893
1894 /// Resolve a local type ID within a given AST file into a type.
1895 QualType getLocalType(ModuleFile &F, serialization::LocalTypeID LocalID);
1896
1897 /// Map a local type ID within a given AST file into a global type ID.
1898 serialization::TypeID
1899 getGlobalTypeID(ModuleFile &F, serialization::LocalTypeID LocalID) const;
1900
1901 /// Read a type from the current position in the given record, which
1902 /// was read from the given AST file.
readType(ModuleFile & F,const RecordData & Record,unsigned & Idx)1903 QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) {
1904 if (Idx >= Record.size())
1905 return {};
1906
1907 return getLocalType(F, Record[Idx++]);
1908 }
1909
1910 /// Map from a local declaration ID within a given module to a
1911 /// global declaration ID.
1912 GlobalDeclID getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const;
1913
1914 /// Returns true if global DeclID \p ID originated from module \p M.
1915 bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const;
1916
1917 /// Retrieve the module file that owns the given declaration, or NULL
1918 /// if the declaration is not from a module file.
1919 ModuleFile *getOwningModuleFile(const Decl *D) const;
1920 ModuleFile *getOwningModuleFile(GlobalDeclID ID) const;
1921
1922 /// Returns the source location for the decl \p ID.
1923 SourceLocation getSourceLocationForDeclID(GlobalDeclID ID);
1924
1925 /// Resolve a declaration ID into a declaration, potentially
1926 /// building a new declaration.
1927 Decl *GetDecl(GlobalDeclID ID);
1928 Decl *GetExternalDecl(GlobalDeclID ID) override;
1929
1930 /// Resolve a declaration ID into a declaration. Return 0 if it's not
1931 /// been loaded yet.
1932 Decl *GetExistingDecl(GlobalDeclID ID);
1933
1934 /// Reads a declaration with the given local ID in the given module.
GetLocalDecl(ModuleFile & F,LocalDeclID LocalID)1935 Decl *GetLocalDecl(ModuleFile &F, LocalDeclID LocalID) {
1936 return GetDecl(getGlobalDeclID(F, LocalID));
1937 }
1938
1939 /// Reads a declaration with the given local ID in the given module.
1940 ///
1941 /// \returns The requested declaration, casted to the given return type.
GetLocalDeclAs(ModuleFile & F,LocalDeclID LocalID)1942 template <typename T> T *GetLocalDeclAs(ModuleFile &F, LocalDeclID LocalID) {
1943 return cast_or_null<T>(GetLocalDecl(F, LocalID));
1944 }
1945
1946 /// Map a global declaration ID into the declaration ID used to
1947 /// refer to this declaration within the given module fule.
1948 ///
1949 /// \returns the global ID of the given declaration as known in the given
1950 /// module file.
1951 LocalDeclID mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
1952 GlobalDeclID GlobalID);
1953
1954 /// Reads a declaration ID from the given position in a record in the
1955 /// given module.
1956 ///
1957 /// \returns The declaration ID read from the record, adjusted to a global ID.
1958 GlobalDeclID ReadDeclID(ModuleFile &F, const RecordDataImpl &Record,
1959 unsigned &Idx);
1960
1961 /// Reads a declaration from the given position in a record in the
1962 /// given module.
ReadDecl(ModuleFile & F,const RecordDataImpl & R,unsigned & I)1963 Decl *ReadDecl(ModuleFile &F, const RecordDataImpl &R, unsigned &I) {
1964 return GetDecl(ReadDeclID(F, R, I));
1965 }
1966
1967 /// Reads a declaration from the given position in a record in the
1968 /// given module.
1969 ///
1970 /// \returns The declaration read from this location, casted to the given
1971 /// result type.
1972 template <typename T>
ReadDeclAs(ModuleFile & F,const RecordDataImpl & R,unsigned & I)1973 T *ReadDeclAs(ModuleFile &F, const RecordDataImpl &R, unsigned &I) {
1974 return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
1975 }
1976
1977 /// If any redeclarations of \p D have been imported since it was
1978 /// last checked, this digs out those redeclarations and adds them to the
1979 /// redeclaration chain for \p D.
1980 void CompleteRedeclChain(const Decl *D) override;
1981
1982 CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override;
1983
1984 /// Resolve the offset of a statement into a statement.
1985 ///
1986 /// This operation will read a new statement from the external
1987 /// source each time it is called, and is meant to be used via a
1988 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1989 Stmt *GetExternalDeclStmt(uint64_t Offset) override;
1990
1991 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1992 /// specified cursor. Read the abbreviations that are at the top of the block
1993 /// and then leave the cursor pointing into the block.
1994 static llvm::Error ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1995 unsigned BlockID,
1996 uint64_t *StartOfBlockOffset = nullptr);
1997
1998 /// Finds all the visible declarations with a given name.
1999 /// The current implementation of this method just loads the entire
2000 /// lookup table as unmaterialized references.
2001 bool FindExternalVisibleDeclsByName(const DeclContext *DC,
2002 DeclarationName Name) override;
2003
2004 /// Read all of the declarations lexically stored in a
2005 /// declaration context.
2006 ///
2007 /// \param DC The declaration context whose declarations will be
2008 /// read.
2009 ///
2010 /// \param IsKindWeWant A predicate indicating which declaration kinds
2011 /// we are interested in.
2012 ///
2013 /// \param Decls Vector that will contain the declarations loaded
2014 /// from the external source. The caller is responsible for merging
2015 /// these declarations with any declarations already stored in the
2016 /// declaration context.
2017 void
2018 FindExternalLexicalDecls(const DeclContext *DC,
2019 llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
2020 SmallVectorImpl<Decl *> &Decls) override;
2021
2022 /// Get the decls that are contained in a file in the Offset/Length
2023 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
2024 /// a range.
2025 void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2026 SmallVectorImpl<Decl *> &Decls) override;
2027
2028 /// Notify ASTReader that we started deserialization of
2029 /// a decl or type so until FinishedDeserializing is called there may be
2030 /// decls that are initializing. Must be paired with FinishedDeserializing.
2031 void StartedDeserializing() override;
2032
2033 /// Notify ASTReader that we finished the deserialization of
2034 /// a decl or type. Must be paired with StartedDeserializing.
2035 void FinishedDeserializing() override;
2036
2037 /// Function that will be invoked when we begin parsing a new
2038 /// translation unit involving this external AST source.
2039 ///
2040 /// This function will provide all of the external definitions to
2041 /// the ASTConsumer.
2042 void StartTranslationUnit(ASTConsumer *Consumer) override;
2043
2044 /// Print some statistics about AST usage.
2045 void PrintStats() override;
2046
2047 /// Dump information about the AST reader to standard error.
2048 void dump();
2049
2050 /// Return the amount of memory used by memory buffers, breaking down
2051 /// by heap-backed versus mmap'ed memory.
2052 void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override;
2053
2054 /// Initialize the semantic source with the Sema instance
2055 /// being used to perform semantic analysis on the abstract syntax
2056 /// tree.
2057 void InitializeSema(Sema &S) override;
2058
2059 /// Inform the semantic consumer that Sema is no longer available.
ForgetSema()2060 void ForgetSema() override { SemaObj = nullptr; }
2061
2062 /// Retrieve the IdentifierInfo for the named identifier.
2063 ///
2064 /// This routine builds a new IdentifierInfo for the given identifier. If any
2065 /// declarations with this name are visible from translation unit scope, their
2066 /// declarations will be deserialized and introduced into the declaration
2067 /// chain of the identifier.
2068 IdentifierInfo *get(StringRef Name) override;
2069
2070 /// Retrieve an iterator into the set of all identifiers
2071 /// in all loaded AST files.
2072 IdentifierIterator *getIdentifiers() override;
2073
2074 /// Load the contents of the global method pool for a given
2075 /// selector.
2076 void ReadMethodPool(Selector Sel) override;
2077
2078 /// Load the contents of the global method pool for a given
2079 /// selector if necessary.
2080 void updateOutOfDateSelector(Selector Sel) override;
2081
2082 /// Load the set of namespaces that are known to the external source,
2083 /// which will be used during typo correction.
2084 void ReadKnownNamespaces(
2085 SmallVectorImpl<NamespaceDecl *> &Namespaces) override;
2086
2087 void ReadUndefinedButUsed(
2088 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) override;
2089
2090 void ReadMismatchingDeleteExpressions(llvm::MapVector<
2091 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
2092 Exprs) override;
2093
2094 void ReadTentativeDefinitions(
2095 SmallVectorImpl<VarDecl *> &TentativeDefs) override;
2096
2097 void ReadUnusedFileScopedDecls(
2098 SmallVectorImpl<const DeclaratorDecl *> &Decls) override;
2099
2100 void ReadDelegatingConstructors(
2101 SmallVectorImpl<CXXConstructorDecl *> &Decls) override;
2102
2103 void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) override;
2104
2105 void ReadUnusedLocalTypedefNameCandidates(
2106 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) override;
2107
2108 void ReadDeclsToCheckForDeferredDiags(
2109 llvm::SmallSetVector<Decl *, 4> &Decls) override;
2110
2111 void ReadReferencedSelectors(
2112 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) override;
2113
2114 void ReadWeakUndeclaredIdentifiers(
2115 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) override;
2116
2117 void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) override;
2118
2119 void ReadPendingInstantiations(
2120 SmallVectorImpl<std::pair<ValueDecl *,
2121 SourceLocation>> &Pending) override;
2122
2123 void ReadLateParsedTemplates(
2124 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
2125 &LPTMap) override;
2126
2127 void AssignedLambdaNumbering(const CXXRecordDecl *Lambda) override;
2128
2129 /// Load a selector from disk, registering its ID if it exists.
2130 void LoadSelector(Selector Sel);
2131
2132 void SetIdentifierInfo(serialization::IdentifierID ID, IdentifierInfo *II);
2133 void SetGloballyVisibleDecls(IdentifierInfo *II,
2134 const SmallVectorImpl<GlobalDeclID> &DeclIDs,
2135 SmallVectorImpl<Decl *> *Decls = nullptr);
2136
2137 /// Report a diagnostic.
2138 DiagnosticBuilder Diag(unsigned DiagID) const;
2139
2140 /// Report a diagnostic.
2141 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const;
2142
2143 void warnStackExhausted(SourceLocation Loc);
2144
2145 IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID);
2146
readIdentifier(ModuleFile & M,const RecordData & Record,unsigned & Idx)2147 IdentifierInfo *readIdentifier(ModuleFile &M, const RecordData &Record,
2148 unsigned &Idx) {
2149 return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++]));
2150 }
2151
GetIdentifier(serialization::IdentifierID ID)2152 IdentifierInfo *GetIdentifier(serialization::IdentifierID ID) override {
2153 // Note that we are loading an identifier.
2154 Deserializing AnIdentifier(this);
2155
2156 return DecodeIdentifierInfo(ID);
2157 }
2158
2159 IdentifierInfo *getLocalIdentifier(ModuleFile &M, uint64_t LocalID);
2160
2161 serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M,
2162 uint64_t LocalID);
2163
2164 void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo);
2165
2166 /// Retrieve the macro with the given ID.
2167 MacroInfo *getMacro(serialization::MacroID ID);
2168
2169 /// Retrieve the global macro ID corresponding to the given local
2170 /// ID within the given module file.
2171 serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID);
2172
2173 /// Read the source location entry with index ID.
2174 bool ReadSLocEntry(int ID) override;
2175 /// Get the index ID for the loaded SourceLocation offset.
2176 int getSLocEntryID(SourceLocation::UIntTy SLocOffset) override;
2177 /// Try to read the offset of the SLocEntry at the given index in the given
2178 /// module file.
2179 llvm::Expected<SourceLocation::UIntTy> readSLocOffset(ModuleFile *F,
2180 unsigned Index);
2181
2182 /// Retrieve the module import location and module name for the
2183 /// given source manager entry ID.
2184 std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) override;
2185
2186 /// Retrieve the global submodule ID given a module and its local ID
2187 /// number.
2188 serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M,
2189 unsigned LocalID) const;
2190
2191 /// Retrieve the submodule that corresponds to a global submodule ID.
2192 ///
2193 Module *getSubmodule(serialization::SubmoduleID GlobalID);
2194
2195 /// Retrieve the module that corresponds to the given module ID.
2196 ///
2197 /// Note: overrides method in ExternalASTSource
2198 Module *getModule(unsigned ID) override;
2199
2200 /// Retrieve the module file with a given local ID within the specified
2201 /// ModuleFile.
2202 ModuleFile *getLocalModuleFile(ModuleFile &M, unsigned ID) const;
2203
2204 /// Get an ID for the given module file.
2205 unsigned getModuleFileID(ModuleFile *M);
2206
2207 /// Return a descriptor for the corresponding module.
2208 std::optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID) override;
2209
2210 ExtKind hasExternalDefinitions(const Decl *D) override;
2211
2212 /// Retrieve a selector from the given module with its local ID
2213 /// number.
2214 Selector getLocalSelector(ModuleFile &M, unsigned LocalID);
2215
2216 Selector DecodeSelector(serialization::SelectorID Idx);
2217
2218 Selector GetExternalSelector(serialization::SelectorID ID) override;
2219 uint32_t GetNumExternalSelectors() override;
2220
ReadSelector(ModuleFile & M,const RecordData & Record,unsigned & Idx)2221 Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) {
2222 return getLocalSelector(M, Record[Idx++]);
2223 }
2224
2225 /// Retrieve the global selector ID that corresponds to this
2226 /// the local selector ID in a given module.
2227 serialization::SelectorID getGlobalSelectorID(ModuleFile &M,
2228 unsigned LocalID) const;
2229
2230 /// Read the contents of a CXXCtorInitializer array.
2231 CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset) override;
2232
2233 /// Read a AlignPackInfo from raw form.
ReadAlignPackInfo(uint32_t Raw)2234 Sema::AlignPackInfo ReadAlignPackInfo(uint32_t Raw) const {
2235 return Sema::AlignPackInfo::getFromRawEncoding(Raw);
2236 }
2237
2238 using RawLocEncoding = SourceLocationEncoding::RawLocEncoding;
2239
2240 /// Read a source location from raw form and return it in its
2241 /// originating module file's source location space.
2242 std::pair<SourceLocation, unsigned>
2243 ReadUntranslatedSourceLocation(RawLocEncoding Raw,
2244 LocSeq *Seq = nullptr) const {
2245 return SourceLocationEncoding::decode(Raw, Seq);
2246 }
2247
2248 /// Read a source location from raw form.
2249 SourceLocation ReadSourceLocation(ModuleFile &MF, RawLocEncoding Raw,
2250 LocSeq *Seq = nullptr) const {
2251 if (!MF.ModuleOffsetMap.empty())
2252 ReadModuleOffsetMap(MF);
2253
2254 auto [Loc, ModuleFileIndex] = ReadUntranslatedSourceLocation(Raw, Seq);
2255 ModuleFile *OwningModuleFile =
2256 ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1];
2257
2258 assert(!SourceMgr.isLoadedSourceLocation(Loc) &&
2259 "Run out source location space");
2260
2261 return TranslateSourceLocation(*OwningModuleFile, Loc);
2262 }
2263
2264 /// Translate a source location from another module file's source
2265 /// location space into ours.
TranslateSourceLocation(ModuleFile & ModuleFile,SourceLocation Loc)2266 SourceLocation TranslateSourceLocation(ModuleFile &ModuleFile,
2267 SourceLocation Loc) const {
2268 if (Loc.isInvalid())
2269 return Loc;
2270
2271 // FIXME: TranslateSourceLocation is not re-enterable. It is problematic
2272 // to call TranslateSourceLocation on a translated source location.
2273 // We either need a method to know whether or not a source location is
2274 // translated or refactor the code to make it clear that
2275 // TranslateSourceLocation won't be called with translated source location.
2276
2277 return Loc.getLocWithOffset(ModuleFile.SLocEntryBaseOffset - 2);
2278 }
2279
2280 /// Read a source location.
2281 SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
2282 const RecordDataImpl &Record, unsigned &Idx,
2283 LocSeq *Seq = nullptr) {
2284 return ReadSourceLocation(ModuleFile, Record[Idx++], Seq);
2285 }
2286
2287 /// Read a FileID.
ReadFileID(ModuleFile & F,const RecordDataImpl & Record,unsigned & Idx)2288 FileID ReadFileID(ModuleFile &F, const RecordDataImpl &Record,
2289 unsigned &Idx) const {
2290 return TranslateFileID(F, FileID::get(Record[Idx++]));
2291 }
2292
2293 /// Translate a FileID from another module file's FileID space into ours.
TranslateFileID(ModuleFile & F,FileID FID)2294 FileID TranslateFileID(ModuleFile &F, FileID FID) const {
2295 assert(FID.ID >= 0 && "Reading non-local FileID.");
2296 return FileID::get(F.SLocEntryBaseID + FID.ID - 1);
2297 }
2298
2299 /// Read a source range.
2300 SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record,
2301 unsigned &Idx, LocSeq *Seq = nullptr);
2302
2303 static llvm::BitVector ReadBitVector(const RecordData &Record,
2304 const StringRef Blob);
2305
2306 // Read a string
2307 static std::string ReadString(const RecordDataImpl &Record, unsigned &Idx);
2308
2309 // Skip a string
SkipString(const RecordData & Record,unsigned & Idx)2310 static void SkipString(const RecordData &Record, unsigned &Idx) {
2311 Idx += Record[Idx] + 1;
2312 }
2313
2314 // Read a path
2315 std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx);
2316
2317 // Read a path
2318 std::string ReadPath(StringRef BaseDirectory, const RecordData &Record,
2319 unsigned &Idx);
2320
2321 // Skip a path
SkipPath(const RecordData & Record,unsigned & Idx)2322 static void SkipPath(const RecordData &Record, unsigned &Idx) {
2323 SkipString(Record, Idx);
2324 }
2325
2326 /// Read a version tuple.
2327 static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
2328
2329 CXXTemporary *ReadCXXTemporary(ModuleFile &F, const RecordData &Record,
2330 unsigned &Idx);
2331
2332 /// Reads a statement.
2333 Stmt *ReadStmt(ModuleFile &F);
2334
2335 /// Reads an expression.
2336 Expr *ReadExpr(ModuleFile &F);
2337
2338 /// Reads a sub-statement operand during statement reading.
ReadSubStmt()2339 Stmt *ReadSubStmt() {
2340 assert(ReadingKind == Read_Stmt &&
2341 "Should be called only during statement reading!");
2342 // Subexpressions are stored from last to first, so the next Stmt we need
2343 // is at the back of the stack.
2344 assert(!StmtStack.empty() && "Read too many sub-statements!");
2345 return StmtStack.pop_back_val();
2346 }
2347
2348 /// Reads a sub-expression operand during statement reading.
2349 Expr *ReadSubExpr();
2350
2351 /// Reads a token out of a record.
2352 Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx);
2353
2354 /// Reads the macro record located at the given offset.
2355 MacroInfo *ReadMacroRecord(ModuleFile &F, uint64_t Offset);
2356
2357 /// Determine the global preprocessed entity ID that corresponds to
2358 /// the given local ID within the given module.
2359 serialization::PreprocessedEntityID
2360 getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const;
2361
2362 /// Add a macro to deserialize its macro directive history.
2363 ///
2364 /// \param II The name of the macro.
2365 /// \param M The module file.
2366 /// \param MacroDirectivesOffset Offset of the serialized macro directive
2367 /// history.
2368 void addPendingMacro(IdentifierInfo *II, ModuleFile *M,
2369 uint32_t MacroDirectivesOffset);
2370
2371 /// Read the set of macros defined by this external macro source.
2372 void ReadDefinedMacros() override;
2373
2374 /// Update an out-of-date identifier.
2375 void updateOutOfDateIdentifier(const IdentifierInfo &II) override;
2376
2377 /// Note that this identifier is up-to-date.
2378 void markIdentifierUpToDate(const IdentifierInfo *II);
2379
2380 /// Load all external visible decls in the given DeclContext.
2381 void completeVisibleDeclsMap(const DeclContext *DC) override;
2382
2383 /// Retrieve the AST context that this AST reader supplements.
getContext()2384 ASTContext &getContext() {
2385 assert(ContextObj && "requested AST context when not loading AST");
2386 return *ContextObj;
2387 }
2388
2389 // Contains the IDs for declarations that were requested before we have
2390 // access to a Sema object.
2391 SmallVector<GlobalDeclID, 16> PreloadedDeclIDs;
2392
2393 /// Retrieve the semantic analysis object used to analyze the
2394 /// translation unit in which the precompiled header is being
2395 /// imported.
getSema()2396 Sema *getSema() { return SemaObj; }
2397
2398 /// Get the identifier resolver used for name lookup / updates
2399 /// in the translation unit scope. We have one of these even if we don't
2400 /// have a Sema object.
2401 IdentifierResolver &getIdResolver();
2402
2403 /// Retrieve the identifier table associated with the
2404 /// preprocessor.
2405 IdentifierTable &getIdentifierTable();
2406
2407 /// Record that the given ID maps to the given switch-case
2408 /// statement.
2409 void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
2410
2411 /// Retrieve the switch-case statement with the given ID.
2412 SwitchCase *getSwitchCaseWithID(unsigned ID);
2413
2414 void ClearSwitchCaseIDs();
2415
2416 /// Cursors for comments blocks.
2417 SmallVector<std::pair<llvm::BitstreamCursor,
2418 serialization::ModuleFile *>, 8> CommentsCursors;
2419
2420 /// Loads comments ranges.
2421 void ReadComments() override;
2422
2423 /// Visit all the input file infos of the given module file.
2424 void visitInputFileInfos(
2425 serialization::ModuleFile &MF, bool IncludeSystem,
2426 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
2427 bool IsSystem)>
2428 Visitor);
2429
2430 /// Visit all the input files of the given module file.
2431 void visitInputFiles(serialization::ModuleFile &MF,
2432 bool IncludeSystem, bool Complain,
2433 llvm::function_ref<void(const serialization::InputFile &IF,
2434 bool isSystem)> Visitor);
2435
2436 /// Visit all the top-level module maps loaded when building the given module
2437 /// file.
2438 void visitTopLevelModuleMaps(serialization::ModuleFile &MF,
2439 llvm::function_ref<void(FileEntryRef)> Visitor);
2440
isProcessingUpdateRecords()2441 bool isProcessingUpdateRecords() { return ProcessingUpdateRecords; }
2442 };
2443
2444 /// A simple helper class to unpack an integer to bits and consuming
2445 /// the bits in order.
2446 class BitsUnpacker {
2447 constexpr static uint32_t BitsIndexUpbound = 32;
2448
2449 public:
BitsUnpacker(uint32_t V)2450 BitsUnpacker(uint32_t V) { updateValue(V); }
2451 BitsUnpacker(const BitsUnpacker &) = delete;
2452 BitsUnpacker(BitsUnpacker &&) = delete;
2453 BitsUnpacker operator=(const BitsUnpacker &) = delete;
2454 BitsUnpacker operator=(BitsUnpacker &&) = delete;
2455 ~BitsUnpacker() = default;
2456
updateValue(uint32_t V)2457 void updateValue(uint32_t V) {
2458 Value = V;
2459 CurrentBitsIndex = 0;
2460 }
2461
advance(uint32_t BitsWidth)2462 void advance(uint32_t BitsWidth) { CurrentBitsIndex += BitsWidth; }
2463
getNextBit()2464 bool getNextBit() {
2465 assert(isValid());
2466 return Value & (1 << CurrentBitsIndex++);
2467 }
2468
getNextBits(uint32_t Width)2469 uint32_t getNextBits(uint32_t Width) {
2470 assert(isValid());
2471 assert(Width < BitsIndexUpbound);
2472 uint32_t Ret = (Value >> CurrentBitsIndex) & ((1 << Width) - 1);
2473 CurrentBitsIndex += Width;
2474 return Ret;
2475 }
2476
canGetNextNBits(uint32_t Width)2477 bool canGetNextNBits(uint32_t Width) const {
2478 return CurrentBitsIndex + Width < BitsIndexUpbound;
2479 }
2480
2481 private:
isValid()2482 bool isValid() const { return CurrentBitsIndex < BitsIndexUpbound; }
2483
2484 uint32_t Value;
2485 uint32_t CurrentBitsIndex = ~0;
2486 };
2487
shouldSkipCheckingODR(const Decl * D)2488 inline bool shouldSkipCheckingODR(const Decl *D) {
2489 return D->getASTContext().getLangOpts().SkipODRCheckInGMF &&
2490 D->isFromExplicitGlobalModule();
2491 }
2492
2493 } // namespace clang
2494
2495 #endif // LLVM_CLANG_SERIALIZATION_ASTREADER_H
2496