1 //===-- ASTReader.cpp - AST File Reader -----------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ASTReader class, which reads AST files.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Serialization/ASTReader.h"
15 #include "ASTCommon.h"
16 #include "ASTReaderInternals.h"
17 #include "clang/AST/ASTConsumer.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/ASTUnresolvedSet.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclGroup.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/NestedNameSpecifier.h"
29 #include "clang/AST/ODRHash.h"
30 #include "clang/AST/RawCommentList.h"
31 #include "clang/AST/Type.h"
32 #include "clang/AST/TypeLocVisitor.h"
33 #include "clang/AST/UnresolvedSet.h"
34 #include "clang/Basic/CommentOptions.h"
35 #include "clang/Basic/DiagnosticOptions.h"
36 #include "clang/Basic/ExceptionSpecificationType.h"
37 #include "clang/Basic/FileManager.h"
38 #include "clang/Basic/FileSystemOptions.h"
39 #include "clang/Basic/LangOptions.h"
40 #include "clang/Basic/MemoryBufferCache.h"
41 #include "clang/Basic/ObjCRuntime.h"
42 #include "clang/Basic/OperatorKinds.h"
43 #include "clang/Basic/Sanitizers.h"
44 #include "clang/Basic/SourceManager.h"
45 #include "clang/Basic/SourceManagerInternals.h"
46 #include "clang/Basic/Specifiers.h"
47 #include "clang/Basic/TargetInfo.h"
48 #include "clang/Basic/TargetOptions.h"
49 #include "clang/Basic/TokenKinds.h"
50 #include "clang/Basic/Version.h"
51 #include "clang/Basic/VersionTuple.h"
52 #include "clang/Frontend/PCHContainerOperations.h"
53 #include "clang/Lex/HeaderSearch.h"
54 #include "clang/Lex/HeaderSearchOptions.h"
55 #include "clang/Lex/MacroInfo.h"
56 #include "clang/Lex/ModuleMap.h"
57 #include "clang/Lex/PreprocessingRecord.h"
58 #include "clang/Lex/Preprocessor.h"
59 #include "clang/Lex/PreprocessorOptions.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/Sema.h"
62 #include "clang/Sema/Weak.h"
63 #include "clang/Serialization/ASTDeserializationListener.h"
64 #include "clang/Serialization/GlobalModuleIndex.h"
65 #include "clang/Serialization/ModuleManager.h"
66 #include "clang/Serialization/SerializationDiagnostic.h"
67 #include "llvm/ADT/APFloat.h"
68 #include "llvm/ADT/APInt.h"
69 #include "llvm/ADT/APSInt.h"
70 #include "llvm/ADT/Hashing.h"
71 #include "llvm/ADT/SmallString.h"
72 #include "llvm/ADT/StringExtras.h"
73 #include "llvm/ADT/Triple.h"
74 #include "llvm/Bitcode/BitstreamReader.h"
75 #include "llvm/Support/Compression.h"
76 #include "llvm/Support/Compiler.h"
77 #include "llvm/Support/Error.h"
78 #include "llvm/Support/ErrorHandling.h"
79 #include "llvm/Support/FileSystem.h"
80 #include "llvm/Support/MemoryBuffer.h"
81 #include "llvm/Support/Path.h"
82 #include "llvm/Support/SaveAndRestore.h"
83 #include "llvm/Support/raw_ostream.h"
96 #include <system_error>
101 using namespace clang;
102 using namespace clang::serialization;
103 using namespace clang::serialization::reader;
104 using llvm::BitstreamCursor;
106 //===----------------------------------------------------------------------===//
107 // ChainedASTReaderListener implementation
108 //===----------------------------------------------------------------------===//
111 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
112 return First->ReadFullVersionInformation(FullVersion) ||
113 Second->ReadFullVersionInformation(FullVersion);
116 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
117 First->ReadModuleName(ModuleName);
118 Second->ReadModuleName(ModuleName);
121 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
122 First->ReadModuleMapFile(ModuleMapPath);
123 Second->ReadModuleMapFile(ModuleMapPath);
127 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
129 bool AllowCompatibleDifferences) {
130 return First->ReadLanguageOptions(LangOpts, Complain,
131 AllowCompatibleDifferences) ||
132 Second->ReadLanguageOptions(LangOpts, Complain,
133 AllowCompatibleDifferences);
136 bool ChainedASTReaderListener::ReadTargetOptions(
137 const TargetOptions &TargetOpts, bool Complain,
138 bool AllowCompatibleDifferences) {
139 return First->ReadTargetOptions(TargetOpts, Complain,
140 AllowCompatibleDifferences) ||
141 Second->ReadTargetOptions(TargetOpts, Complain,
142 AllowCompatibleDifferences);
145 bool ChainedASTReaderListener::ReadDiagnosticOptions(
146 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
147 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
148 Second->ReadDiagnosticOptions(DiagOpts, Complain);
152 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
154 return First->ReadFileSystemOptions(FSOpts, Complain) ||
155 Second->ReadFileSystemOptions(FSOpts, Complain);
158 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
159 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
161 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
163 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
167 bool ChainedASTReaderListener::ReadPreprocessorOptions(
168 const PreprocessorOptions &PPOpts, bool Complain,
169 std::string &SuggestedPredefines) {
170 return First->ReadPreprocessorOptions(PPOpts, Complain,
171 SuggestedPredefines) ||
172 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
174 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
176 First->ReadCounter(M, Value);
177 Second->ReadCounter(M, Value);
179 bool ChainedASTReaderListener::needsInputFileVisitation() {
180 return First->needsInputFileVisitation() ||
181 Second->needsInputFileVisitation();
183 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
184 return First->needsSystemInputFileVisitation() ||
185 Second->needsSystemInputFileVisitation();
187 void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
189 First->visitModuleFile(Filename, Kind);
190 Second->visitModuleFile(Filename, Kind);
193 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
196 bool isExplicitModule) {
197 bool Continue = false;
198 if (First->needsInputFileVisitation() &&
199 (!isSystem || First->needsSystemInputFileVisitation()))
200 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
202 if (Second->needsInputFileVisitation() &&
203 (!isSystem || Second->needsSystemInputFileVisitation()))
204 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
209 void ChainedASTReaderListener::readModuleFileExtension(
210 const ModuleFileExtensionMetadata &Metadata) {
211 First->readModuleFileExtension(Metadata);
212 Second->readModuleFileExtension(Metadata);
215 //===----------------------------------------------------------------------===//
216 // PCH validator implementation
217 //===----------------------------------------------------------------------===//
219 ASTReaderListener::~ASTReaderListener() {}
221 /// \brief Compare the given set of language options against an existing set of
222 /// language options.
224 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
225 /// \param AllowCompatibleDifferences If true, differences between compatible
226 /// language options will be permitted.
228 /// \returns true if the languagae options mis-match, false otherwise.
229 static bool checkLanguageOptions(const LangOptions &LangOpts,
230 const LangOptions &ExistingLangOpts,
231 DiagnosticsEngine *Diags,
232 bool AllowCompatibleDifferences = true) {
233 #define LANGOPT(Name, Bits, Default, Description) \
234 if (ExistingLangOpts.Name != LangOpts.Name) { \
236 Diags->Report(diag::err_pch_langopt_mismatch) \
237 << Description << LangOpts.Name << ExistingLangOpts.Name; \
241 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
242 if (ExistingLangOpts.Name != LangOpts.Name) { \
244 Diags->Report(diag::err_pch_langopt_value_mismatch) \
249 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
250 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
252 Diags->Report(diag::err_pch_langopt_value_mismatch) \
257 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
258 if (!AllowCompatibleDifferences) \
259 LANGOPT(Name, Bits, Default, Description)
261 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
262 if (!AllowCompatibleDifferences) \
263 ENUM_LANGOPT(Name, Bits, Default, Description)
265 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
266 if (!AllowCompatibleDifferences) \
267 VALUE_LANGOPT(Name, Bits, Default, Description)
269 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
270 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
271 #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
272 #include "clang/Basic/LangOptions.def"
274 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
276 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
280 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
282 Diags->Report(diag::err_pch_langopt_value_mismatch)
283 << "target Objective-C runtime";
287 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
288 LangOpts.CommentOpts.BlockCommandNames) {
290 Diags->Report(diag::err_pch_langopt_value_mismatch)
291 << "block command names";
295 // Sanitizer feature mismatches are treated as compatible differences. If
296 // compatible differences aren't allowed, we still only want to check for
297 // mismatches of non-modular sanitizers (the only ones which can affect AST
299 if (!AllowCompatibleDifferences) {
300 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
301 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
302 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
303 ExistingSanitizers.clear(ModularSanitizers);
304 ImportedSanitizers.clear(ModularSanitizers);
305 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
306 const std::string Flag = "-fsanitize=";
308 #define SANITIZER(NAME, ID) \
310 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
311 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
312 if (InExistingModule != InImportedModule) \
313 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
314 << InExistingModule << (Flag + NAME); \
316 #include "clang/Basic/Sanitizers.def"
325 /// \brief Compare the given set of target options against an existing set of
328 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
330 /// \returns true if the target options mis-match, false otherwise.
331 static bool checkTargetOptions(const TargetOptions &TargetOpts,
332 const TargetOptions &ExistingTargetOpts,
333 DiagnosticsEngine *Diags,
334 bool AllowCompatibleDifferences = true) {
335 #define CHECK_TARGET_OPT(Field, Name) \
336 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
338 Diags->Report(diag::err_pch_targetopt_mismatch) \
339 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
343 // The triple and ABI must match exactly.
344 CHECK_TARGET_OPT(Triple, "target");
345 CHECK_TARGET_OPT(ABI, "target ABI");
347 // We can tolerate different CPUs in many cases, notably when one CPU
348 // supports a strict superset of another. When allowing compatible
349 // differences skip this check.
350 if (!AllowCompatibleDifferences)
351 CHECK_TARGET_OPT(CPU, "target CPU");
353 #undef CHECK_TARGET_OPT
355 // Compare feature sets.
356 SmallVector<StringRef, 4> ExistingFeatures(
357 ExistingTargetOpts.FeaturesAsWritten.begin(),
358 ExistingTargetOpts.FeaturesAsWritten.end());
359 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
360 TargetOpts.FeaturesAsWritten.end());
361 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
362 std::sort(ReadFeatures.begin(), ReadFeatures.end());
364 // We compute the set difference in both directions explicitly so that we can
365 // diagnose the differences differently.
366 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
368 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
369 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
370 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
371 ExistingFeatures.begin(), ExistingFeatures.end(),
372 std::back_inserter(UnmatchedReadFeatures));
374 // If we are allowing compatible differences and the read feature set is
375 // a strict subset of the existing feature set, there is nothing to diagnose.
376 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
380 for (StringRef Feature : UnmatchedReadFeatures)
381 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
382 << /* is-existing-feature */ false << Feature;
383 for (StringRef Feature : UnmatchedExistingFeatures)
384 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
385 << /* is-existing-feature */ true << Feature;
388 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
392 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
394 bool AllowCompatibleDifferences) {
395 const LangOptions &ExistingLangOpts = PP.getLangOpts();
396 return checkLanguageOptions(LangOpts, ExistingLangOpts,
397 Complain ? &Reader.Diags : nullptr,
398 AllowCompatibleDifferences);
401 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
403 bool AllowCompatibleDifferences) {
404 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
405 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
406 Complain ? &Reader.Diags : nullptr,
407 AllowCompatibleDifferences);
412 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
414 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
417 } // end anonymous namespace
419 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
420 DiagnosticsEngine &Diags,
422 typedef DiagnosticsEngine::Level Level;
424 // Check current mappings for new -Werror mappings, and the stored mappings
425 // for cases that were explicitly mapped to *not* be errors that are now
426 // errors because of options like -Werror.
427 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
429 for (DiagnosticsEngine *MappingSource : MappingSources) {
430 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
431 diag::kind DiagID = DiagIDMappingPair.first;
432 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
433 if (CurLevel < DiagnosticsEngine::Error)
434 continue; // not significant
436 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
437 if (StoredLevel < DiagnosticsEngine::Error) {
439 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
440 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
449 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
450 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
451 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
453 return Ext >= diag::Severity::Error;
456 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
457 DiagnosticsEngine &Diags,
458 bool IsSystem, bool Complain) {
461 if (Diags.getSuppressSystemWarnings())
463 // If -Wsystem-headers was not enabled before, be conservative
464 if (StoredDiags.getSuppressSystemWarnings()) {
466 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
471 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
473 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
477 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
478 !StoredDiags.getEnableAllWarnings()) {
480 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
484 if (isExtHandlingFromDiagsError(Diags) &&
485 !isExtHandlingFromDiagsError(StoredDiags)) {
487 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
491 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
494 /// Return the top import module if it is implicit, nullptr otherwise.
495 static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
497 // If the original import came from a file explicitly generated by the user,
498 // don't check the diagnostic mappings.
499 // FIXME: currently this is approximated by checking whether this is not a
500 // module import of an implicitly-loaded module file.
501 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
502 // the transitive closure of its imports, since unrelated modules cannot be
503 // imported until after this module finishes validation.
504 ModuleFile *TopImport = &*ModuleMgr.rbegin();
505 while (!TopImport->ImportedBy.empty())
506 TopImport = TopImport->ImportedBy[0];
507 if (TopImport->Kind != MK_ImplicitModule)
510 StringRef ModuleName = TopImport->ModuleName;
511 assert(!ModuleName.empty() && "diagnostic options read before module name");
513 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
514 assert(M && "missing module");
518 bool PCHValidator::ReadDiagnosticOptions(
519 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
520 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
521 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
522 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
523 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
524 // This should never fail, because we would have processed these options
525 // before writing them to an ASTFile.
526 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
528 ModuleManager &ModuleMgr = Reader.getModuleManager();
529 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
531 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
535 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
536 // contains the union of their flags.
537 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
541 /// \brief Collect the macro definitions provided by the given preprocessor
544 collectMacroDefinitions(const PreprocessorOptions &PPOpts,
545 MacroDefinitionsMap &Macros,
546 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
547 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
548 StringRef Macro = PPOpts.Macros[I].first;
549 bool IsUndef = PPOpts.Macros[I].second;
551 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
552 StringRef MacroName = MacroPair.first;
553 StringRef MacroBody = MacroPair.second;
555 // For an #undef'd macro, we only care about the name.
557 if (MacroNames && !Macros.count(MacroName))
558 MacroNames->push_back(MacroName);
560 Macros[MacroName] = std::make_pair("", true);
564 // For a #define'd macro, figure out the actual definition.
565 if (MacroName.size() == Macro.size())
568 // Note: GCC drops anything following an end-of-line character.
569 StringRef::size_type End = MacroBody.find_first_of("\n\r");
570 MacroBody = MacroBody.substr(0, End);
573 if (MacroNames && !Macros.count(MacroName))
574 MacroNames->push_back(MacroName);
575 Macros[MacroName] = std::make_pair(MacroBody, false);
579 /// \brief Check the preprocessor options deserialized from the control block
580 /// against the preprocessor options in an existing preprocessor.
582 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
583 /// \param Validate If true, validate preprocessor options. If false, allow
584 /// macros defined by \p ExistingPPOpts to override those defined by
585 /// \p PPOpts in SuggestedPredefines.
586 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
587 const PreprocessorOptions &ExistingPPOpts,
588 DiagnosticsEngine *Diags,
589 FileManager &FileMgr,
590 std::string &SuggestedPredefines,
591 const LangOptions &LangOpts,
592 bool Validate = true) {
593 // Check macro definitions.
594 MacroDefinitionsMap ASTFileMacros;
595 collectMacroDefinitions(PPOpts, ASTFileMacros);
596 MacroDefinitionsMap ExistingMacros;
597 SmallVector<StringRef, 4> ExistingMacroNames;
598 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
600 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
601 // Dig out the macro definition in the existing preprocessor options.
602 StringRef MacroName = ExistingMacroNames[I];
603 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
605 // Check whether we know anything about this macro name or not.
606 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
607 = ASTFileMacros.find(MacroName);
608 if (!Validate || Known == ASTFileMacros.end()) {
609 // FIXME: Check whether this identifier was referenced anywhere in the
610 // AST file. If so, we should reject the AST file. Unfortunately, this
611 // information isn't in the control block. What shall we do about it?
613 if (Existing.second) {
614 SuggestedPredefines += "#undef ";
615 SuggestedPredefines += MacroName.str();
616 SuggestedPredefines += '\n';
618 SuggestedPredefines += "#define ";
619 SuggestedPredefines += MacroName.str();
620 SuggestedPredefines += ' ';
621 SuggestedPredefines += Existing.first.str();
622 SuggestedPredefines += '\n';
627 // If the macro was defined in one but undef'd in the other, we have a
629 if (Existing.second != Known->second.second) {
631 Diags->Report(diag::err_pch_macro_def_undef)
632 << MacroName << Known->second.second;
637 // If the macro was #undef'd in both, or if the macro bodies are identical,
639 if (Existing.second || Existing.first == Known->second.first)
642 // The macro bodies differ; complain.
644 Diags->Report(diag::err_pch_macro_def_conflict)
645 << MacroName << Known->second.first << Existing.first;
650 // Check whether we're using predefines.
651 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
653 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
658 // Detailed record is important since it is used for the module cache hash.
659 if (LangOpts.Modules &&
660 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
662 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
667 // Compute the #include and #include_macros lines we need.
668 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
669 StringRef File = ExistingPPOpts.Includes[I];
670 if (File == ExistingPPOpts.ImplicitPCHInclude)
673 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
674 != PPOpts.Includes.end())
677 SuggestedPredefines += "#include \"";
678 SuggestedPredefines += File;
679 SuggestedPredefines += "\"\n";
682 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
683 StringRef File = ExistingPPOpts.MacroIncludes[I];
684 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
686 != PPOpts.MacroIncludes.end())
689 SuggestedPredefines += "#__include_macros \"";
690 SuggestedPredefines += File;
691 SuggestedPredefines += "\"\n##\n";
697 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
699 std::string &SuggestedPredefines) {
700 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
702 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
703 Complain? &Reader.Diags : nullptr,
709 bool SimpleASTReaderListener::ReadPreprocessorOptions(
710 const PreprocessorOptions &PPOpts,
712 std::string &SuggestedPredefines) {
713 return checkPreprocessorOptions(PPOpts,
714 PP.getPreprocessorOpts(),
722 /// Check the header search options deserialized from the control block
723 /// against the header search options in an existing preprocessor.
725 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
726 static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
727 StringRef SpecificModuleCachePath,
728 StringRef ExistingModuleCachePath,
729 DiagnosticsEngine *Diags,
730 const LangOptions &LangOpts) {
731 if (LangOpts.Modules) {
732 if (SpecificModuleCachePath != ExistingModuleCachePath) {
734 Diags->Report(diag::err_pch_modulecache_mismatch)
735 << SpecificModuleCachePath << ExistingModuleCachePath;
743 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
744 StringRef SpecificModuleCachePath,
746 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
747 PP.getHeaderSearchInfo().getModuleCachePath(),
748 Complain ? &Reader.Diags : nullptr,
752 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
753 PP.setCounterValue(Value);
756 //===----------------------------------------------------------------------===//
757 // AST reader implementation
758 //===----------------------------------------------------------------------===//
760 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
761 bool TakeOwnership) {
762 DeserializationListener = Listener;
763 OwnsDeserializationListener = TakeOwnership;
766 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
767 return serialization::ComputeHash(Sel);
770 std::pair<unsigned, unsigned>
771 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
772 using namespace llvm::support;
773 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
774 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
775 return std::make_pair(KeyLen, DataLen);
778 ASTSelectorLookupTrait::internal_key_type
779 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
780 using namespace llvm::support;
781 SelectorTable &SelTable = Reader.getContext().Selectors;
782 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
783 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
784 F, endian::readNext<uint32_t, little, unaligned>(d));
786 return SelTable.getNullarySelector(FirstII);
788 return SelTable.getUnarySelector(FirstII);
790 SmallVector<IdentifierInfo *, 16> Args;
791 Args.push_back(FirstII);
792 for (unsigned I = 1; I != N; ++I)
793 Args.push_back(Reader.getLocalIdentifier(
794 F, endian::readNext<uint32_t, little, unaligned>(d)));
796 return SelTable.getSelector(N, Args.data());
799 ASTSelectorLookupTrait::data_type
800 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
802 using namespace llvm::support;
806 Result.ID = Reader.getGlobalSelectorID(
807 F, endian::readNext<uint32_t, little, unaligned>(d));
808 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
809 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
810 Result.InstanceBits = FullInstanceBits & 0x3;
811 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
812 Result.FactoryBits = FullFactoryBits & 0x3;
813 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
814 unsigned NumInstanceMethods = FullInstanceBits >> 3;
815 unsigned NumFactoryMethods = FullFactoryBits >> 3;
817 // Load instance methods
818 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
819 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
820 F, endian::readNext<uint32_t, little, unaligned>(d)))
821 Result.Instance.push_back(Method);
824 // Load factory methods
825 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
826 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
827 F, endian::readNext<uint32_t, little, unaligned>(d)))
828 Result.Factory.push_back(Method);
834 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
835 return llvm::HashString(a);
838 std::pair<unsigned, unsigned>
839 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
840 using namespace llvm::support;
841 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
842 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
843 return std::make_pair(KeyLen, DataLen);
846 ASTIdentifierLookupTraitBase::internal_key_type
847 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
848 assert(n >= 2 && d[n-1] == '\0');
849 return StringRef((const char*) d, n-1);
852 /// \brief Whether the given identifier is "interesting".
853 static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
855 return II.hadMacroDefinition() ||
857 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
858 II.hasRevertedTokenIDToIdentifier() ||
859 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
860 II.getFETokenInfo<void>());
863 static bool readBit(unsigned &Bits) {
864 bool Value = Bits & 0x1;
869 IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
870 using namespace llvm::support;
871 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
872 return Reader.getGlobalIdentifierID(F, RawID >> 1);
875 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
876 if (!II.isFromAST()) {
878 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
879 if (isInterestingIdentifier(Reader, II, IsModule))
880 II.setChangedSinceDeserialization();
884 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
885 const unsigned char* d,
887 using namespace llvm::support;
888 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
889 bool IsInteresting = RawID & 0x01;
891 // Wipe out the "is interesting" bit.
894 // Build the IdentifierInfo and link the identifier ID with it.
895 IdentifierInfo *II = KnownII;
897 II = &Reader.getIdentifierTable().getOwn(k);
900 markIdentifierFromAST(Reader, *II);
901 Reader.markIdentifierUpToDate(II);
903 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
904 if (!IsInteresting) {
905 // For uninteresting identifiers, there's nothing else to do. Just notify
906 // the reader that we've finished loading this identifier.
907 Reader.SetIdentifierInfo(ID, II);
911 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
912 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
913 bool CPlusPlusOperatorKeyword = readBit(Bits);
914 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
915 bool HasRevertedBuiltin = readBit(Bits);
916 bool Poisoned = readBit(Bits);
917 bool ExtensionToken = readBit(Bits);
918 bool HadMacroDefinition = readBit(Bits);
920 assert(Bits == 0 && "Extra bits in the identifier?");
923 // Set or check the various bits in the IdentifierInfo structure.
924 // Token IDs are read-only.
925 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
926 II->revertTokenIDToIdentifier();
928 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
929 else if (HasRevertedBuiltin && II->getBuiltinID()) {
931 assert((II->hasRevertedBuiltin() ||
932 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
933 "Incorrect ObjC keyword or builtin ID");
935 assert(II->isExtensionToken() == ExtensionToken &&
936 "Incorrect extension token flag");
937 (void)ExtensionToken;
939 II->setIsPoisoned(true);
940 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
941 "Incorrect C++ operator keyword flag");
942 (void)CPlusPlusOperatorKeyword;
944 // If this identifier is a macro, deserialize the macro
946 if (HadMacroDefinition) {
947 uint32_t MacroDirectivesOffset =
948 endian::readNext<uint32_t, little, unaligned>(d);
951 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
954 Reader.SetIdentifierInfo(ID, II);
956 // Read all of the declarations visible at global scope with this
959 SmallVector<uint32_t, 4> DeclIDs;
960 for (; DataLen > 0; DataLen -= 4)
961 DeclIDs.push_back(Reader.getGlobalDeclID(
962 F, endian::readNext<uint32_t, little, unaligned>(d)));
963 Reader.SetGloballyVisibleDecls(II, DeclIDs);
969 DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
970 : Kind(Name.getNameKind()) {
972 case DeclarationName::Identifier:
973 Data = (uint64_t)Name.getAsIdentifierInfo();
975 case DeclarationName::ObjCZeroArgSelector:
976 case DeclarationName::ObjCOneArgSelector:
977 case DeclarationName::ObjCMultiArgSelector:
978 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
980 case DeclarationName::CXXOperatorName:
981 Data = Name.getCXXOverloadedOperator();
983 case DeclarationName::CXXLiteralOperatorName:
984 Data = (uint64_t)Name.getCXXLiteralIdentifier();
986 case DeclarationName::CXXDeductionGuideName:
987 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
988 ->getDeclName().getAsIdentifierInfo();
990 case DeclarationName::CXXConstructorName:
991 case DeclarationName::CXXDestructorName:
992 case DeclarationName::CXXConversionFunctionName:
993 case DeclarationName::CXXUsingDirective:
999 unsigned DeclarationNameKey::getHash() const {
1000 llvm::FoldingSetNodeID ID;
1001 ID.AddInteger(Kind);
1004 case DeclarationName::Identifier:
1005 case DeclarationName::CXXLiteralOperatorName:
1006 case DeclarationName::CXXDeductionGuideName:
1007 ID.AddString(((IdentifierInfo*)Data)->getName());
1009 case DeclarationName::ObjCZeroArgSelector:
1010 case DeclarationName::ObjCOneArgSelector:
1011 case DeclarationName::ObjCMultiArgSelector:
1012 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1014 case DeclarationName::CXXOperatorName:
1015 ID.AddInteger((OverloadedOperatorKind)Data);
1017 case DeclarationName::CXXConstructorName:
1018 case DeclarationName::CXXDestructorName:
1019 case DeclarationName::CXXConversionFunctionName:
1020 case DeclarationName::CXXUsingDirective:
1024 return ID.ComputeHash();
1028 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1029 using namespace llvm::support;
1030 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1031 return Reader.getLocalModuleFile(F, ModuleFileID);
1034 std::pair<unsigned, unsigned>
1035 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1036 using namespace llvm::support;
1037 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1038 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
1039 return std::make_pair(KeyLen, DataLen);
1042 ASTDeclContextNameLookupTrait::internal_key_type
1043 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1044 using namespace llvm::support;
1046 auto Kind = (DeclarationName::NameKind)*d++;
1049 case DeclarationName::Identifier:
1050 case DeclarationName::CXXLiteralOperatorName:
1051 case DeclarationName::CXXDeductionGuideName:
1052 Data = (uint64_t)Reader.getLocalIdentifier(
1053 F, endian::readNext<uint32_t, little, unaligned>(d));
1055 case DeclarationName::ObjCZeroArgSelector:
1056 case DeclarationName::ObjCOneArgSelector:
1057 case DeclarationName::ObjCMultiArgSelector:
1059 (uint64_t)Reader.getLocalSelector(
1060 F, endian::readNext<uint32_t, little, unaligned>(
1061 d)).getAsOpaquePtr();
1063 case DeclarationName::CXXOperatorName:
1064 Data = *d++; // OverloadedOperatorKind
1066 case DeclarationName::CXXConstructorName:
1067 case DeclarationName::CXXDestructorName:
1068 case DeclarationName::CXXConversionFunctionName:
1069 case DeclarationName::CXXUsingDirective:
1074 return DeclarationNameKey(Kind, Data);
1077 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1078 const unsigned char *d,
1080 data_type_builder &Val) {
1081 using namespace llvm::support;
1082 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1083 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1084 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1088 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1089 BitstreamCursor &Cursor,
1092 assert(Offset != 0);
1094 SavedStreamPosition SavedPosition(Cursor);
1095 Cursor.JumpToBit(Offset);
1099 unsigned Code = Cursor.ReadCode();
1100 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1101 if (RecCode != DECL_CONTEXT_LEXICAL) {
1102 Error("Expected lexical block");
1106 assert(!isa<TranslationUnitDecl>(DC) &&
1107 "expected a TU_UPDATE_LEXICAL record for TU");
1108 // If we are handling a C++ class template instantiation, we can see multiple
1109 // lexical updates for the same record. It's important that we select only one
1110 // of them, so that field numbering works properly. Just pick the first one we
1112 auto &Lex = LexicalDecls[DC];
1114 Lex = std::make_pair(
1115 &M, llvm::makeArrayRef(
1116 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1120 DC->setHasExternalLexicalStorage(true);
1124 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1125 BitstreamCursor &Cursor,
1128 assert(Offset != 0);
1130 SavedStreamPosition SavedPosition(Cursor);
1131 Cursor.JumpToBit(Offset);
1135 unsigned Code = Cursor.ReadCode();
1136 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1137 if (RecCode != DECL_CONTEXT_VISIBLE) {
1138 Error("Expected visible lookup table block");
1142 // We can't safely determine the primary context yet, so delay attaching the
1143 // lookup table until we're done with recursive deserialization.
1144 auto *Data = (const unsigned char*)Blob.data();
1145 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1149 void ASTReader::Error(StringRef Msg) const {
1150 Error(diag::err_fe_pch_malformed, Msg);
1151 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1152 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1153 Diag(diag::note_module_cache_path)
1154 << PP.getHeaderSearchInfo().getModuleCachePath();
1158 void ASTReader::Error(unsigned DiagID,
1159 StringRef Arg1, StringRef Arg2) const {
1160 if (Diags.isDiagnosticInFlight())
1161 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1163 Diag(DiagID) << Arg1 << Arg2;
1166 //===----------------------------------------------------------------------===//
1167 // Source Manager Deserialization
1168 //===----------------------------------------------------------------------===//
1170 /// \brief Read the line table in the source manager block.
1171 /// \returns true if there was an error.
1172 bool ASTReader::ParseLineTable(ModuleFile &F,
1173 const RecordData &Record) {
1175 LineTableInfo &LineTable = SourceMgr.getLineTable();
1177 // Parse the file names
1178 std::map<int, int> FileIDs;
1179 for (unsigned I = 0; Record[Idx]; ++I) {
1180 // Extract the file name
1181 auto Filename = ReadPath(F, Record, Idx);
1182 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1186 // Parse the line entries
1187 std::vector<LineEntry> Entries;
1188 while (Idx < Record.size()) {
1189 int FID = Record[Idx++];
1190 assert(FID >= 0 && "Serialized line entries for non-local file.");
1191 // Remap FileID from 1-based old view.
1192 FID += F.SLocEntryBaseID - 1;
1194 // Extract the line entries
1195 unsigned NumEntries = Record[Idx++];
1196 assert(NumEntries && "no line entries for file ID");
1198 Entries.reserve(NumEntries);
1199 for (unsigned I = 0; I != NumEntries; ++I) {
1200 unsigned FileOffset = Record[Idx++];
1201 unsigned LineNo = Record[Idx++];
1202 int FilenameID = FileIDs[Record[Idx++]];
1203 SrcMgr::CharacteristicKind FileKind
1204 = (SrcMgr::CharacteristicKind)Record[Idx++];
1205 unsigned IncludeOffset = Record[Idx++];
1206 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1207 FileKind, IncludeOffset));
1209 LineTable.AddEntry(FileID::get(FID), Entries);
1215 /// \brief Read a source manager block
1216 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1217 using namespace SrcMgr;
1219 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1221 // Set the source-location entry cursor to the current position in
1222 // the stream. This cursor will be used to read the contents of the
1223 // source manager block initially, and then lazily read
1224 // source-location entries as needed.
1225 SLocEntryCursor = F.Stream;
1227 // The stream itself is going to skip over the source manager block.
1228 if (F.Stream.SkipBlock()) {
1229 Error("malformed block record in AST file");
1233 // Enter the source manager block.
1234 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1235 Error("malformed source manager block record in AST file");
1241 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1244 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1245 case llvm::BitstreamEntry::Error:
1246 Error("malformed block record in AST file");
1248 case llvm::BitstreamEntry::EndBlock:
1250 case llvm::BitstreamEntry::Record:
1251 // The interesting case.
1258 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
1259 default: // Default behavior: ignore.
1262 case SM_SLOC_FILE_ENTRY:
1263 case SM_SLOC_BUFFER_ENTRY:
1264 case SM_SLOC_EXPANSION_ENTRY:
1265 // Once we hit one of the source location entries, we're done.
1271 /// \brief If a header file is not found at the path that we expect it to be
1272 /// and the PCH file was moved from its original location, try to resolve the
1273 /// file by assuming that header+PCH were moved together and the header is in
1274 /// the same place relative to the PCH.
1276 resolveFileRelativeToOriginalDir(const std::string &Filename,
1277 const std::string &OriginalDir,
1278 const std::string &CurrDir) {
1279 assert(OriginalDir != CurrDir &&
1280 "No point trying to resolve the file if the PCH dir didn't change");
1281 using namespace llvm::sys;
1282 SmallString<128> filePath(Filename);
1283 fs::make_absolute(filePath);
1284 assert(path::is_absolute(OriginalDir));
1285 SmallString<128> currPCHPath(CurrDir);
1287 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1288 fileDirE = path::end(path::parent_path(filePath));
1289 path::const_iterator origDirI = path::begin(OriginalDir),
1290 origDirE = path::end(OriginalDir);
1291 // Skip the common path components from filePath and OriginalDir.
1292 while (fileDirI != fileDirE && origDirI != origDirE &&
1293 *fileDirI == *origDirI) {
1297 for (; origDirI != origDirE; ++origDirI)
1298 path::append(currPCHPath, "..");
1299 path::append(currPCHPath, fileDirI, fileDirE);
1300 path::append(currPCHPath, path::filename(Filename));
1301 return currPCHPath.str();
1304 bool ASTReader::ReadSLocEntry(int ID) {
1308 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1309 Error("source location entry ID out-of-range for AST file");
1313 // Local helper to read the (possibly-compressed) buffer data following the
1315 auto ReadBuffer = [this](
1316 BitstreamCursor &SLocEntryCursor,
1317 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1320 unsigned Code = SLocEntryCursor.ReadCode();
1321 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1323 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1324 if (!llvm::zlib::isAvailable()) {
1325 Error("zlib is not available");
1328 SmallString<0> Uncompressed;
1330 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1331 Error("could not decompress embedded file contents: " +
1332 llvm::toString(std::move(E)));
1335 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1336 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1337 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1339 Error("AST record has invalid code");
1344 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1345 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
1346 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1347 unsigned BaseOffset = F->SLocEntryBaseOffset;
1349 ++NumSLocEntriesRead;
1350 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1351 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1352 Error("incorrectly-formatted source location entry in AST file");
1358 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
1360 Error("incorrectly-formatted source location entry in AST file");
1363 case SM_SLOC_FILE_ENTRY: {
1364 // We will detect whether a file changed and return 'Failure' for it, but
1365 // we will also try to fail gracefully by setting up the SLocEntry.
1366 unsigned InputID = Record[4];
1367 InputFile IF = getInputFile(*F, InputID);
1368 const FileEntry *File = IF.getFile();
1369 bool OverriddenBuffer = IF.isOverridden();
1371 // Note that we only check if a File was returned. If it was out-of-date
1372 // we have complained but we will continue creating a FileID to recover
1377 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1378 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1379 // This is the module's main file.
1380 IncludeLoc = getImportLocation(F);
1382 SrcMgr::CharacteristicKind
1383 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1384 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1385 ID, BaseOffset + Record[0]);
1386 SrcMgr::FileInfo &FileInfo =
1387 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1388 FileInfo.NumCreatedFIDs = Record[5];
1390 FileInfo.setHasLineDirectives();
1392 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1393 unsigned NumFileDecls = Record[7];
1395 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1396 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1400 const SrcMgr::ContentCache *ContentCache
1401 = SourceMgr.getOrCreateContentCache(File,
1402 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1403 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1404 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1405 !ContentCache->getRawBuffer()) {
1406 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1409 SourceMgr.overrideFileContents(File, std::move(Buffer));
1415 case SM_SLOC_BUFFER_ENTRY: {
1416 const char *Name = Blob.data();
1417 unsigned Offset = Record[0];
1418 SrcMgr::CharacteristicKind
1419 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1420 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1421 if (IncludeLoc.isInvalid() && F->isModule()) {
1422 IncludeLoc = getImportLocation(F);
1425 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1428 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1429 BaseOffset + Offset, IncludeLoc);
1433 case SM_SLOC_EXPANSION_ENTRY: {
1434 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1435 SourceMgr.createExpansionLoc(SpellingLoc,
1436 ReadSourceLocation(*F, Record[2]),
1437 ReadSourceLocation(*F, Record[3]),
1440 BaseOffset + Record[0]);
1448 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1450 return std::make_pair(SourceLocation(), "");
1452 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1453 Error("source location entry ID out-of-range for AST file");
1454 return std::make_pair(SourceLocation(), "");
1457 // Find which module file this entry lands in.
1458 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1460 return std::make_pair(SourceLocation(), "");
1462 // FIXME: Can we map this down to a particular submodule? That would be
1464 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1467 /// \brief Find the location where the module F is imported.
1468 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1469 if (F->ImportLoc.isValid())
1470 return F->ImportLoc;
1472 // Otherwise we have a PCH. It's considered to be "imported" at the first
1473 // location of its includer.
1474 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1475 // Main file is the importer.
1476 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1477 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1479 return F->ImportedBy[0]->FirstLoc;
1482 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1483 /// specified cursor. Read the abbreviations that are at the top of the block
1484 /// and then leave the cursor pointing into the block.
1485 bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
1486 if (Cursor.EnterSubBlock(BlockID))
1490 uint64_t Offset = Cursor.GetCurrentBitNo();
1491 unsigned Code = Cursor.ReadCode();
1493 // We expect all abbrevs to be at the start of the block.
1494 if (Code != llvm::bitc::DEFINE_ABBREV) {
1495 Cursor.JumpToBit(Offset);
1498 Cursor.ReadAbbrevRecord();
1502 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1506 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1507 Tok.setLength(Record[Idx++]);
1508 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1509 Tok.setIdentifierInfo(II);
1510 Tok.setKind((tok::TokenKind)Record[Idx++]);
1511 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1515 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1516 BitstreamCursor &Stream = F.MacroCursor;
1518 // Keep track of where we are in the stream, then jump back there
1519 // after reading this macro.
1520 SavedStreamPosition SavedPosition(Stream);
1522 Stream.JumpToBit(Offset);
1524 SmallVector<IdentifierInfo*, 16> MacroArgs;
1525 MacroInfo *Macro = nullptr;
1528 // Advance to the next record, but if we get to the end of the block, don't
1529 // pop it (removing all the abbreviations from the cursor) since we want to
1530 // be able to reseek within the block and read entries.
1531 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1532 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1534 switch (Entry.Kind) {
1535 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1536 case llvm::BitstreamEntry::Error:
1537 Error("malformed block record in AST file");
1539 case llvm::BitstreamEntry::EndBlock:
1541 case llvm::BitstreamEntry::Record:
1542 // The interesting case.
1548 PreprocessorRecordTypes RecType =
1549 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
1551 case PP_MODULE_MACRO:
1552 case PP_MACRO_DIRECTIVE_HISTORY:
1555 case PP_MACRO_OBJECT_LIKE:
1556 case PP_MACRO_FUNCTION_LIKE: {
1557 // If we already have a macro, that means that we've hit the end
1558 // of the definition of the macro we were looking for. We're
1563 unsigned NextIndex = 1; // Skip identifier ID.
1564 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1565 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1566 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1567 MI->setIsUsed(Record[NextIndex++]);
1568 MI->setUsedForHeaderGuard(Record[NextIndex++]);
1570 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1571 // Decode function-like macro info.
1572 bool isC99VarArgs = Record[NextIndex++];
1573 bool isGNUVarArgs = Record[NextIndex++];
1574 bool hasCommaPasting = Record[NextIndex++];
1576 unsigned NumArgs = Record[NextIndex++];
1577 for (unsigned i = 0; i != NumArgs; ++i)
1578 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1580 // Install function-like macro info.
1581 MI->setIsFunctionLike();
1582 if (isC99VarArgs) MI->setIsC99Varargs();
1583 if (isGNUVarArgs) MI->setIsGNUVarargs();
1584 if (hasCommaPasting) MI->setHasCommaPasting();
1585 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
1588 // Remember that we saw this macro last so that we add the tokens that
1589 // form its body to it.
1592 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1593 Record[NextIndex]) {
1594 // We have a macro definition. Register the association
1595 PreprocessedEntityID
1596 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1597 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1598 PreprocessingRecord::PPEntityID PPID =
1599 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1600 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1601 PPRec.getPreprocessedEntity(PPID));
1603 PPRec.RegisterMacroDefinition(Macro, PPDef);
1611 // If we see a TOKEN before a PP_MACRO_*, then the file is
1612 // erroneous, just pretend we didn't see this.
1616 Token Tok = ReadToken(F, Record, Idx);
1617 Macro->AddTokenToBody(Tok);
1624 PreprocessedEntityID
1625 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1626 unsigned LocalID) const {
1627 if (!M.ModuleOffsetMap.empty())
1628 ReadModuleOffsetMap(M);
1630 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1631 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1632 assert(I != M.PreprocessedEntityRemap.end()
1633 && "Invalid index into preprocessed entity index remap");
1635 return LocalID + I->second;
1638 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1639 return llvm::hash_combine(ikey.Size, ikey.ModTime);
1642 HeaderFileInfoTrait::internal_key_type
1643 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1644 internal_key_type ikey = {FE->getSize(),
1645 M.HasTimestamps ? FE->getModificationTime() : 0,
1646 FE->getName(), /*Imported*/ false};
1650 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1651 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
1654 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
1657 // Determine whether the actual files are equivalent.
1658 FileManager &FileMgr = Reader.getFileManager();
1659 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1661 return FileMgr.getFile(Key.Filename);
1663 std::string Resolved = Key.Filename;
1664 Reader.ResolveImportedPath(M, Resolved);
1665 return FileMgr.getFile(Resolved);
1668 const FileEntry *FEA = GetFile(a);
1669 const FileEntry *FEB = GetFile(b);
1670 return FEA && FEA == FEB;
1673 std::pair<unsigned, unsigned>
1674 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1675 using namespace llvm::support;
1676 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1677 unsigned DataLen = (unsigned) *d++;
1678 return std::make_pair(KeyLen, DataLen);
1681 HeaderFileInfoTrait::internal_key_type
1682 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1683 using namespace llvm::support;
1684 internal_key_type ikey;
1685 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1686 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1687 ikey.Filename = (const char *)d;
1688 ikey.Imported = true;
1692 HeaderFileInfoTrait::data_type
1693 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1695 const unsigned char *End = d + DataLen;
1696 using namespace llvm::support;
1698 unsigned Flags = *d++;
1699 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1700 HFI.isImport |= (Flags >> 4) & 0x01;
1701 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1702 HFI.DirInfo = (Flags >> 1) & 0x03;
1703 HFI.IndexHeaderMapHeader = Flags & 0x01;
1704 // FIXME: Find a better way to handle this. Maybe just store a
1705 // "has been included" flag?
1706 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1708 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1709 M, endian::readNext<uint32_t, little, unaligned>(d));
1710 if (unsigned FrameworkOffset =
1711 endian::readNext<uint32_t, little, unaligned>(d)) {
1712 // The framework offset is 1 greater than the actual offset,
1713 // since 0 is used as an indicator for "no framework name".
1714 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1715 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1718 assert((End - d) % 4 == 0 &&
1719 "Wrong data length in HeaderFileInfo deserialization");
1721 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1722 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1725 // This header is part of a module. Associate it with the module to enable
1726 // implicit module import.
1727 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1728 Module *Mod = Reader.getSubmodule(GlobalSMID);
1729 FileManager &FileMgr = Reader.getFileManager();
1731 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1733 std::string Filename = key.Filename;
1735 Reader.ResolveImportedPath(M, Filename);
1736 // FIXME: This is not always the right filename-as-written, but we're not
1737 // going to use this information to rebuild the module, so it doesn't make
1738 // a lot of difference.
1739 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
1740 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1741 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
1744 // This HeaderFileInfo was externally loaded.
1745 HFI.External = true;
1750 void ASTReader::addPendingMacro(IdentifierInfo *II,
1752 uint64_t MacroDirectivesOffset) {
1753 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1754 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1757 void ASTReader::ReadDefinedMacros() {
1758 // Note that we are loading defined macros.
1759 Deserializing Macros(this);
1761 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1762 BitstreamCursor &MacroCursor = I.MacroCursor;
1764 // If there was no preprocessor block, skip this file.
1765 if (MacroCursor.getBitcodeBytes().empty())
1768 BitstreamCursor Cursor = MacroCursor;
1769 Cursor.JumpToBit(I.MacroStartOffset);
1773 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1776 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1777 case llvm::BitstreamEntry::Error:
1778 Error("malformed block record in AST file");
1780 case llvm::BitstreamEntry::EndBlock:
1783 case llvm::BitstreamEntry::Record:
1785 switch (Cursor.readRecord(E.ID, Record)) {
1786 default: // Default behavior: ignore.
1789 case PP_MACRO_OBJECT_LIKE:
1790 case PP_MACRO_FUNCTION_LIKE: {
1791 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
1792 if (II->isOutOfDate())
1793 updateOutOfDateIdentifier(*II);
1810 /// \brief Visitor class used to look up identifirs in an AST file.
1811 class IdentifierLookupVisitor {
1814 unsigned PriorGeneration;
1815 unsigned &NumIdentifierLookups;
1816 unsigned &NumIdentifierLookupHits;
1817 IdentifierInfo *Found;
1820 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1821 unsigned &NumIdentifierLookups,
1822 unsigned &NumIdentifierLookupHits)
1823 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1824 PriorGeneration(PriorGeneration),
1825 NumIdentifierLookups(NumIdentifierLookups),
1826 NumIdentifierLookupHits(NumIdentifierLookupHits),
1831 bool operator()(ModuleFile &M) {
1832 // If we've already searched this module file, skip it now.
1833 if (M.Generation <= PriorGeneration)
1836 ASTIdentifierLookupTable *IdTable
1837 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1841 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
1843 ++NumIdentifierLookups;
1844 ASTIdentifierLookupTable::iterator Pos =
1845 IdTable->find_hashed(Name, NameHash, &Trait);
1846 if (Pos == IdTable->end())
1849 // Dereferencing the iterator has the effect of building the
1850 // IdentifierInfo node and populating it with the various
1851 // declarations it needs.
1852 ++NumIdentifierLookupHits;
1857 // \brief Retrieve the identifier info found within the module
1859 IdentifierInfo *getIdentifierInfo() const { return Found; }
1862 } // end anonymous namespace
1864 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1865 // Note that we are loading an identifier.
1866 Deserializing AnIdentifier(this);
1868 unsigned PriorGeneration = 0;
1869 if (getContext().getLangOpts().Modules)
1870 PriorGeneration = IdentifierGeneration[&II];
1872 // If there is a global index, look there first to determine which modules
1873 // provably do not have any results for this identifier.
1874 GlobalModuleIndex::HitSet Hits;
1875 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
1876 if (!loadGlobalIndex()) {
1877 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1882 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
1883 NumIdentifierLookups,
1884 NumIdentifierLookupHits);
1885 ModuleMgr.visit(Visitor, HitsPtr);
1886 markIdentifierUpToDate(&II);
1889 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1893 II->setOutOfDate(false);
1895 // Update the generation for this identifier.
1896 if (getContext().getLangOpts().Modules)
1897 IdentifierGeneration[II] = getGeneration();
1900 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1901 const PendingMacroInfo &PMInfo) {
1902 ModuleFile &M = *PMInfo.M;
1904 BitstreamCursor &Cursor = M.MacroCursor;
1905 SavedStreamPosition SavedPosition(Cursor);
1906 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
1908 struct ModuleMacroRecord {
1909 SubmoduleID SubModID;
1911 SmallVector<SubmoduleID, 8> Overrides;
1913 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
1915 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1916 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1920 llvm::BitstreamEntry Entry =
1921 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1922 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1923 Error("malformed block record in AST file");
1928 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
1929 case PP_MACRO_DIRECTIVE_HISTORY:
1932 case PP_MODULE_MACRO: {
1933 ModuleMacros.push_back(ModuleMacroRecord());
1934 auto &Info = ModuleMacros.back();
1935 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1936 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
1937 for (int I = 2, N = Record.size(); I != N; ++I)
1938 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
1943 Error("malformed block record in AST file");
1947 // We found the macro directive history; that's the last record
1952 // Module macros are listed in reverse dependency order.
1954 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
1955 llvm::SmallVector<ModuleMacro*, 8> Overrides;
1956 for (auto &MMR : ModuleMacros) {
1958 for (unsigned ModID : MMR.Overrides) {
1959 Module *Mod = getSubmodule(ModID);
1960 auto *Macro = PP.getModuleMacro(Mod, II);
1961 assert(Macro && "missing definition for overridden macro");
1962 Overrides.push_back(Macro);
1965 bool Inserted = false;
1966 Module *Owner = getSubmodule(MMR.SubModID);
1967 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
1971 // Don't read the directive history for a module; we don't have anywhere
1976 // Deserialize the macro directives history in reverse source-order.
1977 MacroDirective *Latest = nullptr, *Earliest = nullptr;
1978 unsigned Idx = 0, N = Record.size();
1980 MacroDirective *MD = nullptr;
1981 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
1982 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1984 case MacroDirective::MD_Define: {
1985 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
1986 MD = PP.AllocateDefMacroDirective(MI, Loc);
1989 case MacroDirective::MD_Undefine: {
1990 MD = PP.AllocateUndefMacroDirective(Loc);
1993 case MacroDirective::MD_Visibility:
1994 bool isPublic = Record[Idx++];
1995 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2002 Earliest->setPrevious(MD);
2007 PP.setLoadedMacroDirective(II, Earliest, Latest);
2010 ASTReader::InputFileInfo
2011 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
2012 // Go find this input file.
2013 BitstreamCursor &Cursor = F.InputFilesCursor;
2014 SavedStreamPosition SavedPosition(Cursor);
2015 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2017 unsigned Code = Cursor.ReadCode();
2021 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2022 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2023 "invalid record type for input file");
2026 assert(Record[0] == ID && "Bogus stored ID or offset");
2028 R.StoredSize = static_cast<off_t>(Record[1]);
2029 R.StoredTime = static_cast<time_t>(Record[2]);
2030 R.Overridden = static_cast<bool>(Record[3]);
2031 R.Transient = static_cast<bool>(Record[4]);
2033 ResolveImportedPath(F, R.Filename);
2037 static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2038 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2039 // If this ID is bogus, just return an empty input file.
2040 if (ID == 0 || ID > F.InputFilesLoaded.size())
2043 // If we've already loaded this input file, return it.
2044 if (F.InputFilesLoaded[ID-1].getFile())
2045 return F.InputFilesLoaded[ID-1];
2047 if (F.InputFilesLoaded[ID-1].isNotFound())
2050 // Go find this input file.
2051 BitstreamCursor &Cursor = F.InputFilesCursor;
2052 SavedStreamPosition SavedPosition(Cursor);
2053 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2055 InputFileInfo FI = readInputFileInfo(F, ID);
2056 off_t StoredSize = FI.StoredSize;
2057 time_t StoredTime = FI.StoredTime;
2058 bool Overridden = FI.Overridden;
2059 bool Transient = FI.Transient;
2060 StringRef Filename = FI.Filename;
2062 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
2064 // If we didn't find the file, resolve it relative to the
2065 // original directory from which this AST file was created.
2066 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
2067 F.OriginalDir != CurrentDir) {
2068 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2071 if (!Resolved.empty())
2072 File = FileMgr.getFile(Resolved);
2075 // For an overridden file, create a virtual file with the stored
2077 if ((Overridden || Transient) && File == nullptr)
2078 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2080 if (File == nullptr) {
2082 std::string ErrorStr = "could not find file '";
2083 ErrorStr += Filename;
2084 ErrorStr += "' referenced by AST file '";
2085 ErrorStr += F.FileName;
2089 // Record that we didn't find the file.
2090 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2094 // Check if there was a request to override the contents of the file
2095 // that was part of the precompiled header. Overridding such a file
2096 // can lead to problems when lexing using the source locations from the
2098 SourceManager &SM = getSourceManager();
2099 // FIXME: Reject if the overrides are different.
2100 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
2102 Error(diag::err_fe_pch_file_overridden, Filename);
2103 // After emitting the diagnostic, recover by disabling the override so
2104 // that the original file will be used.
2106 // FIXME: This recovery is just as broken as the original state; there may
2107 // be another precompiled module that's using the overridden contents, or
2108 // we might be half way through parsing it. Instead, we should treat the
2109 // overridden contents as belonging to a separate FileEntry.
2110 SM.disableFileContentsOverride(File);
2111 // The FileEntry is a virtual file entry with the size of the contents
2112 // that would override the original contents. Set it to the original's
2114 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2115 StoredSize, StoredTime);
2118 bool IsOutOfDate = false;
2120 // For an overridden file, there is nothing to validate.
2121 if (!Overridden && //
2122 (StoredSize != File->getSize() ||
2123 (StoredTime && StoredTime != File->getModificationTime() &&
2127 // Build a list of the PCH imports that got us here (in reverse).
2128 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2129 while (ImportStack.back()->ImportedBy.size() > 0)
2130 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2132 // The top-level PCH is stale.
2133 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2134 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2135 if (DiagnosticKind == 0)
2136 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2137 else if (DiagnosticKind == 1)
2138 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2140 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
2142 // Print the import stack.
2143 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2144 Diag(diag::note_pch_required_by)
2145 << Filename << ImportStack[0]->FileName;
2146 for (unsigned I = 1; I < ImportStack.size(); ++I)
2147 Diag(diag::note_pch_required_by)
2148 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2151 if (!Diags.isDiagnosticInFlight())
2152 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2157 // FIXME: If the file is overridden and we've already opened it,
2158 // issue an error (or split it into a separate FileEntry).
2160 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
2162 // Note that we've loaded this input file.
2163 F.InputFilesLoaded[ID-1] = IF;
2167 /// \brief If we are loading a relocatable PCH or module file, and the filename
2168 /// is not an absolute path, add the system or module root to the beginning of
2170 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2171 // Resolve relative to the base directory, if we have one.
2172 if (!M.BaseDirectory.empty())
2173 return ResolveImportedPath(Filename, M.BaseDirectory);
2176 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2177 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2180 SmallString<128> Buffer;
2181 llvm::sys::path::append(Buffer, Prefix, Filename);
2182 Filename.assign(Buffer.begin(), Buffer.end());
2185 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2187 case ASTReader::Failure: return true;
2188 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2189 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2190 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2191 case ASTReader::ConfigurationMismatch:
2192 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2193 case ASTReader::HadErrors: return true;
2194 case ASTReader::Success: return false;
2197 llvm_unreachable("unknown ASTReadResult");
2200 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2201 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2202 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2203 std::string &SuggestedPredefines) {
2204 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2207 // Read all of the records in the options block.
2209 ASTReadResult Result = Success;
2211 llvm::BitstreamEntry Entry = Stream.advance();
2213 switch (Entry.Kind) {
2214 case llvm::BitstreamEntry::Error:
2215 case llvm::BitstreamEntry::SubBlock:
2218 case llvm::BitstreamEntry::EndBlock:
2221 case llvm::BitstreamEntry::Record:
2222 // The interesting case.
2226 // Read and process a record.
2228 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2229 case LANGUAGE_OPTIONS: {
2230 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2231 if (ParseLanguageOptions(Record, Complain, Listener,
2232 AllowCompatibleConfigurationMismatch))
2233 Result = ConfigurationMismatch;
2237 case TARGET_OPTIONS: {
2238 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2239 if (ParseTargetOptions(Record, Complain, Listener,
2240 AllowCompatibleConfigurationMismatch))
2241 Result = ConfigurationMismatch;
2245 case FILE_SYSTEM_OPTIONS: {
2246 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2247 if (!AllowCompatibleConfigurationMismatch &&
2248 ParseFileSystemOptions(Record, Complain, Listener))
2249 Result = ConfigurationMismatch;
2253 case HEADER_SEARCH_OPTIONS: {
2254 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2255 if (!AllowCompatibleConfigurationMismatch &&
2256 ParseHeaderSearchOptions(Record, Complain, Listener))
2257 Result = ConfigurationMismatch;
2261 case PREPROCESSOR_OPTIONS:
2262 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2263 if (!AllowCompatibleConfigurationMismatch &&
2264 ParsePreprocessorOptions(Record, Complain, Listener,
2265 SuggestedPredefines))
2266 Result = ConfigurationMismatch;
2272 ASTReader::ASTReadResult
2273 ASTReader::ReadControlBlock(ModuleFile &F,
2274 SmallVectorImpl<ImportedModule> &Loaded,
2275 const ModuleFile *ImportedBy,
2276 unsigned ClientLoadCapabilities) {
2277 BitstreamCursor &Stream = F.Stream;
2278 ASTReadResult Result = Success;
2280 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2281 Error("malformed block record in AST file");
2285 // Lambda to read the unhashed control block the first time it's called.
2287 // For PCM files, the unhashed control block cannot be read until after the
2288 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2289 // need to look ahead before reading the IMPORTS record. For consistency,
2290 // this block is always read somehow (see BitstreamEntry::EndBlock).
2291 bool HasReadUnhashedControlBlock = false;
2292 auto readUnhashedControlBlockOnce = [&]() {
2293 if (!HasReadUnhashedControlBlock) {
2294 HasReadUnhashedControlBlock = true;
2295 if (ASTReadResult Result =
2296 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2302 // Read all of the records and blocks in the control block.
2304 unsigned NumInputs = 0;
2305 unsigned NumUserInputs = 0;
2307 llvm::BitstreamEntry Entry = Stream.advance();
2309 switch (Entry.Kind) {
2310 case llvm::BitstreamEntry::Error:
2311 Error("malformed block record in AST file");
2313 case llvm::BitstreamEntry::EndBlock: {
2314 // Validate the module before returning. This call catches an AST with
2315 // no module name and no imports.
2316 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2319 // Validate input files.
2320 const HeaderSearchOptions &HSOpts =
2321 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2323 // All user input files reside at the index range [0, NumUserInputs), and
2324 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2325 // loaded module files, ignore missing inputs.
2326 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2327 F.Kind != MK_PrebuiltModule) {
2328 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2330 // If we are reading a module, we will create a verification timestamp,
2331 // so we verify all input files. Otherwise, verify only user input
2334 unsigned N = NumUserInputs;
2335 if (ValidateSystemInputs ||
2336 (HSOpts.ModulesValidateOncePerBuildSession &&
2337 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
2338 F.Kind == MK_ImplicitModule))
2341 for (unsigned I = 0; I < N; ++I) {
2342 InputFile IF = getInputFile(F, I+1, Complain);
2343 if (!IF.getFile() || IF.isOutOfDate())
2349 Listener->visitModuleFile(F.FileName, F.Kind);
2351 if (Listener && Listener->needsInputFileVisitation()) {
2352 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2354 for (unsigned I = 0; I < N; ++I) {
2355 bool IsSystem = I >= NumUserInputs;
2356 InputFileInfo FI = readInputFileInfo(F, I+1);
2357 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2358 F.Kind == MK_ExplicitModule ||
2359 F.Kind == MK_PrebuiltModule);
2366 case llvm::BitstreamEntry::SubBlock:
2368 case INPUT_FILES_BLOCK_ID:
2369 F.InputFilesCursor = Stream;
2370 if (Stream.SkipBlock() || // Skip with the main cursor
2371 // Read the abbreviations
2372 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2373 Error("malformed block record in AST file");
2378 case OPTIONS_BLOCK_ID:
2379 // If we're reading the first module for this group, check its options
2380 // are compatible with ours. For modules it imports, no further checking
2381 // is required, because we checked them when we built it.
2382 if (Listener && !ImportedBy) {
2383 // Should we allow the configuration of the module file to differ from
2384 // the configuration of the current translation unit in a compatible
2387 // FIXME: Allow this for files explicitly specified with -include-pch.
2388 bool AllowCompatibleConfigurationMismatch =
2389 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
2391 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2392 AllowCompatibleConfigurationMismatch,
2393 *Listener, SuggestedPredefines);
2394 if (Result == Failure) {
2395 Error("malformed block record in AST file");
2399 if (DisableValidation ||
2400 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2403 // If we can't load the module, exit early since we likely
2404 // will rebuild the module anyway. The stream may be in the
2405 // middle of a block.
2406 if (Result != Success)
2408 } else if (Stream.SkipBlock()) {
2409 Error("malformed block record in AST file");
2415 if (Stream.SkipBlock()) {
2416 Error("malformed block record in AST file");
2422 case llvm::BitstreamEntry::Record:
2423 // The interesting case.
2427 // Read and process a record.
2430 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2432 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2433 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2434 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2435 : diag::err_pch_version_too_new);
2436 return VersionMismatch;
2439 bool hasErrors = Record[6];
2440 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2441 Diag(diag::err_pch_with_compiler_errors);
2445 Diags.ErrorOccurred = true;
2446 Diags.UncompilableErrorOccurred = true;
2447 Diags.UnrecoverableErrorOccurred = true;
2450 F.RelocatablePCH = Record[4];
2451 // Relative paths in a relocatable PCH are relative to our sysroot.
2452 if (F.RelocatablePCH)
2453 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
2455 F.HasTimestamps = Record[5];
2457 const std::string &CurBranch = getClangFullRepositoryVersion();
2458 StringRef ASTBranch = Blob;
2459 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2460 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2461 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2462 return VersionMismatch;
2468 // Validate the AST before processing any imports (otherwise, untangling
2469 // them can be error-prone and expensive). A module will have a name and
2470 // will already have been validated, but this catches the PCH case.
2471 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2474 // Load each of the imported PCH files.
2475 unsigned Idx = 0, N = Record.size();
2477 // Read information about the AST file.
2478 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2479 // The import location will be the local one for now; we will adjust
2480 // all import locations of module imports after the global source
2481 // location info are setup, in ReadAST.
2482 SourceLocation ImportLoc =
2483 ReadUntranslatedSourceLocation(Record[Idx++]);
2484 off_t StoredSize = (off_t)Record[Idx++];
2485 time_t StoredModTime = (time_t)Record[Idx++];
2486 ASTFileSignature StoredSignature = {
2487 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2488 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2489 (uint32_t)Record[Idx++]}}};
2490 auto ImportedFile = ReadPath(F, Record, Idx);
2492 // If our client can't cope with us being out of date, we can't cope with
2493 // our dependency being missing.
2494 unsigned Capabilities = ClientLoadCapabilities;
2495 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2496 Capabilities &= ~ARR_Missing;
2498 // Load the AST file.
2499 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2500 Loaded, StoredSize, StoredModTime,
2501 StoredSignature, Capabilities);
2503 // If we diagnosed a problem, produce a backtrace.
2504 if (isDiagnosedResult(Result, Capabilities))
2505 Diag(diag::note_module_file_imported_by)
2506 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2509 case Failure: return Failure;
2510 // If we have to ignore the dependency, we'll have to ignore this too.
2512 case OutOfDate: return OutOfDate;
2513 case VersionMismatch: return VersionMismatch;
2514 case ConfigurationMismatch: return ConfigurationMismatch;
2515 case HadErrors: return HadErrors;
2516 case Success: break;
2523 F.OriginalSourceFileID = FileID::get(Record[0]);
2524 F.ActualOriginalSourceFileName = Blob;
2525 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2526 ResolveImportedPath(F, F.OriginalSourceFileName);
2529 case ORIGINAL_FILE_ID:
2530 F.OriginalSourceFileID = FileID::get(Record[0]);
2533 case ORIGINAL_PCH_DIR:
2534 F.OriginalDir = Blob;
2538 F.ModuleName = Blob;
2540 Listener->ReadModuleName(F.ModuleName);
2542 // Validate the AST as soon as we have a name so we can exit early on
2544 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2549 case MODULE_DIRECTORY: {
2550 assert(!F.ModuleName.empty() &&
2551 "MODULE_DIRECTORY found before MODULE_NAME");
2552 // If we've already loaded a module map file covering this module, we may
2553 // have a better path for it (relative to the current build).
2554 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2555 if (M && M->Directory) {
2556 // If we're implicitly loading a module, the base directory can't
2557 // change between the build and use.
2558 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
2559 const DirectoryEntry *BuildDir =
2560 PP.getFileManager().getDirectory(Blob);
2561 if (!BuildDir || BuildDir != M->Directory) {
2562 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2563 Diag(diag::err_imported_module_relocated)
2564 << F.ModuleName << Blob << M->Directory->getName();
2568 F.BaseDirectory = M->Directory->getName();
2570 F.BaseDirectory = Blob;
2575 case MODULE_MAP_FILE:
2576 if (ASTReadResult Result =
2577 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2581 case INPUT_FILE_OFFSETS:
2582 NumInputs = Record[0];
2583 NumUserInputs = Record[1];
2584 F.InputFileOffsets =
2585 (const llvm::support::unaligned_uint64_t *)Blob.data();
2586 F.InputFilesLoaded.resize(NumInputs);
2587 F.NumUserInputFiles = NumUserInputs;
2593 ASTReader::ASTReadResult
2594 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
2595 BitstreamCursor &Stream = F.Stream;
2597 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2598 Error("malformed block record in AST file");
2602 // Read all of the records and blocks for the AST file.
2605 llvm::BitstreamEntry Entry = Stream.advance();
2607 switch (Entry.Kind) {
2608 case llvm::BitstreamEntry::Error:
2609 Error("error at end of module block in AST file");
2611 case llvm::BitstreamEntry::EndBlock: {
2612 // Outside of C++, we do not store a lookup map for the translation unit.
2613 // Instead, mark it as needing a lookup map to be built if this module
2614 // contains any declarations lexically within it (which it always does!).
2615 // This usually has no cost, since we very rarely need the lookup map for
2616 // the translation unit outside C++.
2617 DeclContext *DC = Context.getTranslationUnitDecl();
2618 if (DC->hasExternalLexicalStorage() &&
2619 !getContext().getLangOpts().CPlusPlus)
2620 DC->setMustBuildLookupTable();
2624 case llvm::BitstreamEntry::SubBlock:
2626 case DECLTYPES_BLOCK_ID:
2627 // We lazily load the decls block, but we want to set up the
2628 // DeclsCursor cursor to point into it. Clone our current bitcode
2629 // cursor to it, enter the block and read the abbrevs in that block.
2630 // With the main cursor, we just skip over it.
2631 F.DeclsCursor = Stream;
2632 if (Stream.SkipBlock() || // Skip with the main cursor.
2633 // Read the abbrevs.
2634 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2635 Error("malformed block record in AST file");
2640 case PREPROCESSOR_BLOCK_ID:
2641 F.MacroCursor = Stream;
2642 if (!PP.getExternalSource())
2643 PP.setExternalSource(this);
2645 if (Stream.SkipBlock() ||
2646 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2647 Error("malformed block record in AST file");
2650 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2653 case PREPROCESSOR_DETAIL_BLOCK_ID:
2654 F.PreprocessorDetailCursor = Stream;
2655 if (Stream.SkipBlock() ||
2656 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
2657 PREPROCESSOR_DETAIL_BLOCK_ID)) {
2658 Error("malformed preprocessor detail record in AST file");
2661 F.PreprocessorDetailStartOffset
2662 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2664 if (!PP.getPreprocessingRecord())
2665 PP.createPreprocessingRecord();
2666 if (!PP.getPreprocessingRecord()->getExternalSource())
2667 PP.getPreprocessingRecord()->SetExternalSource(*this);
2670 case SOURCE_MANAGER_BLOCK_ID:
2671 if (ReadSourceManagerBlock(F))
2675 case SUBMODULE_BLOCK_ID:
2676 if (ASTReadResult Result =
2677 ReadSubmoduleBlock(F, ClientLoadCapabilities))
2681 case COMMENTS_BLOCK_ID: {
2682 BitstreamCursor C = Stream;
2683 if (Stream.SkipBlock() ||
2684 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2685 Error("malformed comments block in AST file");
2688 CommentsCursors.push_back(std::make_pair(C, &F));
2693 if (Stream.SkipBlock()) {
2694 Error("malformed block record in AST file");
2701 case llvm::BitstreamEntry::Record:
2702 // The interesting case.
2706 // Read and process a record.
2709 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2710 default: // Default behavior: ignore.
2714 if (F.LocalNumTypes != 0) {
2715 Error("duplicate TYPE_OFFSET record in AST file");
2718 F.TypeOffsets = (const uint32_t *)Blob.data();
2719 F.LocalNumTypes = Record[0];
2720 unsigned LocalBaseTypeIndex = Record[1];
2721 F.BaseTypeIndex = getTotalNumTypes();
2723 if (F.LocalNumTypes > 0) {
2724 // Introduce the global -> local mapping for types within this module.
2725 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2727 // Introduce the local -> global mapping for types within this module.
2728 F.TypeRemap.insertOrReplace(
2729 std::make_pair(LocalBaseTypeIndex,
2730 F.BaseTypeIndex - LocalBaseTypeIndex));
2732 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2738 if (F.LocalNumDecls != 0) {
2739 Error("duplicate DECL_OFFSET record in AST file");
2742 F.DeclOffsets = (const DeclOffset *)Blob.data();
2743 F.LocalNumDecls = Record[0];
2744 unsigned LocalBaseDeclID = Record[1];
2745 F.BaseDeclID = getTotalNumDecls();
2747 if (F.LocalNumDecls > 0) {
2748 // Introduce the global -> local mapping for declarations within this
2750 GlobalDeclMap.insert(
2751 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2753 // Introduce the local -> global mapping for declarations within this
2755 F.DeclRemap.insertOrReplace(
2756 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2758 // Introduce the global -> local mapping for declarations within this
2760 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2762 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2767 case TU_UPDATE_LEXICAL: {
2768 DeclContext *TU = Context.getTranslationUnitDecl();
2769 LexicalContents Contents(
2770 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2772 static_cast<unsigned int>(Blob.size() / 4));
2773 TULexicalDecls.push_back(std::make_pair(&F, Contents));
2774 TU->setHasExternalLexicalStorage(true);
2778 case UPDATE_VISIBLE: {
2780 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2781 auto *Data = (const unsigned char*)Blob.data();
2782 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
2783 // If we've already loaded the decl, perform the updates when we finish
2784 // loading this block.
2785 if (Decl *D = GetExistingDecl(ID))
2786 PendingUpdateRecords.push_back(
2787 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
2791 case IDENTIFIER_TABLE:
2792 F.IdentifierTableData = Blob.data();
2794 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2795 (const unsigned char *)F.IdentifierTableData + Record[0],
2796 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2797 (const unsigned char *)F.IdentifierTableData,
2798 ASTIdentifierLookupTrait(*this, F));
2800 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2804 case IDENTIFIER_OFFSET: {
2805 if (F.LocalNumIdentifiers != 0) {
2806 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2809 F.IdentifierOffsets = (const uint32_t *)Blob.data();
2810 F.LocalNumIdentifiers = Record[0];
2811 unsigned LocalBaseIdentifierID = Record[1];
2812 F.BaseIdentifierID = getTotalNumIdentifiers();
2814 if (F.LocalNumIdentifiers > 0) {
2815 // Introduce the global -> local mapping for identifiers within this
2817 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2820 // Introduce the local -> global mapping for identifiers within this
2822 F.IdentifierRemap.insertOrReplace(
2823 std::make_pair(LocalBaseIdentifierID,
2824 F.BaseIdentifierID - LocalBaseIdentifierID));
2826 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2827 + F.LocalNumIdentifiers);
2832 case INTERESTING_IDENTIFIERS:
2833 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2836 case EAGERLY_DESERIALIZED_DECLS:
2837 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2838 // about "interesting" decls (for instance, if we're building a module).
2839 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2840 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2843 case MODULAR_CODEGEN_DECLS:
2844 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2845 // them (ie: if we're not codegenerating this module).
2846 if (F.Kind == MK_MainFile)
2847 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2848 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2852 if (SpecialTypes.empty()) {
2853 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2854 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2858 if (SpecialTypes.size() != Record.size()) {
2859 Error("invalid special-types record");
2863 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2864 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2865 if (!SpecialTypes[I])
2866 SpecialTypes[I] = ID;
2867 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2873 TotalNumStatements += Record[0];
2874 TotalNumMacros += Record[1];
2875 TotalLexicalDeclContexts += Record[2];
2876 TotalVisibleDeclContexts += Record[3];
2879 case UNUSED_FILESCOPED_DECLS:
2880 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2881 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2884 case DELEGATING_CTORS:
2885 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2886 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2889 case WEAK_UNDECLARED_IDENTIFIERS:
2890 if (Record.size() % 4 != 0) {
2891 Error("invalid weak identifiers record");
2895 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2896 // files. This isn't the way to do it :)
2897 WeakUndeclaredIdentifiers.clear();
2899 // Translate the weak, undeclared identifiers into global IDs.
2900 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2901 WeakUndeclaredIdentifiers.push_back(
2902 getGlobalIdentifierID(F, Record[I++]));
2903 WeakUndeclaredIdentifiers.push_back(
2904 getGlobalIdentifierID(F, Record[I++]));
2905 WeakUndeclaredIdentifiers.push_back(
2906 ReadSourceLocation(F, Record, I).getRawEncoding());
2907 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2911 case SELECTOR_OFFSETS: {
2912 F.SelectorOffsets = (const uint32_t *)Blob.data();
2913 F.LocalNumSelectors = Record[0];
2914 unsigned LocalBaseSelectorID = Record[1];
2915 F.BaseSelectorID = getTotalNumSelectors();
2917 if (F.LocalNumSelectors > 0) {
2918 // Introduce the global -> local mapping for selectors within this
2920 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2922 // Introduce the local -> global mapping for selectors within this
2924 F.SelectorRemap.insertOrReplace(
2925 std::make_pair(LocalBaseSelectorID,
2926 F.BaseSelectorID - LocalBaseSelectorID));
2928 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2934 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
2936 F.SelectorLookupTable
2937 = ASTSelectorLookupTable::Create(
2938 F.SelectorLookupTableData + Record[0],
2939 F.SelectorLookupTableData,
2940 ASTSelectorLookupTrait(*this, F));
2941 TotalNumMethodPoolEntries += Record[1];
2944 case REFERENCED_SELECTOR_POOL:
2945 if (!Record.empty()) {
2946 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2947 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2949 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2955 case PP_CONDITIONAL_STACK:
2956 if (!Record.empty()) {
2957 SmallVector<PPConditionalInfo, 4> ConditionalStack;
2958 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2959 auto Loc = ReadSourceLocation(F, Record, Idx);
2960 bool WasSkipping = Record[Idx++];
2961 bool FoundNonSkip = Record[Idx++];
2962 bool FoundElse = Record[Idx++];
2963 ConditionalStack.push_back(
2964 {Loc, WasSkipping, FoundNonSkip, FoundElse});
2966 PP.setReplayablePreambleConditionalStack(ConditionalStack);
2970 case PP_COUNTER_VALUE:
2971 if (!Record.empty() && Listener)
2972 Listener->ReadCounter(F, Record[0]);
2975 case FILE_SORTED_DECLS:
2976 F.FileSortedDecls = (const DeclID *)Blob.data();
2977 F.NumFileSortedDecls = Record[0];
2980 case SOURCE_LOCATION_OFFSETS: {
2981 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
2982 F.LocalNumSLocEntries = Record[0];
2983 unsigned SLocSpaceSize = Record[1];
2984 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2985 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2987 if (!F.SLocEntryBaseID) {
2988 Error("ran out of source locations");
2991 // Make our entry in the range map. BaseID is negative and growing, so
2992 // we invert it. Because we invert it, though, we need the other end of
2994 unsigned RangeStart =
2995 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2996 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2997 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2999 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3000 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3001 GlobalSLocOffsetMap.insert(
3002 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3003 - SLocSpaceSize,&F));
3005 // Initialize the remapping table.
3006 // Invalid stays invalid.
3007 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
3008 // This module. Base was 2 when being compiled.
3009 F.SLocRemap.insertOrReplace(std::make_pair(2U,
3010 static_cast<int>(F.SLocEntryBaseOffset - 2)));
3012 TotalNumSLocEntries += F.LocalNumSLocEntries;
3016 case MODULE_OFFSET_MAP:
3017 F.ModuleOffsetMap = Blob;
3020 case SOURCE_MANAGER_LINE_TABLE:
3021 if (ParseLineTable(F, Record))
3025 case SOURCE_LOCATION_PRELOADS: {
3026 // Need to transform from the local view (1-based IDs) to the global view,
3027 // which is based off F.SLocEntryBaseID.
3028 if (!F.PreloadSLocEntries.empty()) {
3029 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
3033 F.PreloadSLocEntries.swap(Record);
3037 case EXT_VECTOR_DECLS:
3038 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3039 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3043 if (Record.size() % 3 != 0) {
3044 Error("Invalid VTABLE_USES record");
3048 // Later tables overwrite earlier ones.
3049 // FIXME: Modules will have some trouble with this. This is clearly not
3050 // the right way to do this.
3053 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3054 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3055 VTableUses.push_back(
3056 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3057 VTableUses.push_back(Record[Idx++]);
3061 case PENDING_IMPLICIT_INSTANTIATIONS:
3062 if (PendingInstantiations.size() % 2 != 0) {
3063 Error("Invalid existing PendingInstantiations");
3067 if (Record.size() % 2 != 0) {
3068 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3072 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3073 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3074 PendingInstantiations.push_back(
3075 ReadSourceLocation(F, Record, I).getRawEncoding());
3079 case SEMA_DECL_REFS:
3080 if (Record.size() != 3) {
3081 Error("Invalid SEMA_DECL_REFS block");
3084 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3085 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3088 case PPD_ENTITIES_OFFSETS: {
3089 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3090 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3091 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3093 unsigned LocalBasePreprocessedEntityID = Record[0];
3095 unsigned StartingID;
3096 if (!PP.getPreprocessingRecord())
3097 PP.createPreprocessingRecord();
3098 if (!PP.getPreprocessingRecord()->getExternalSource())
3099 PP.getPreprocessingRecord()->SetExternalSource(*this);
3101 = PP.getPreprocessingRecord()
3102 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3103 F.BasePreprocessedEntityID = StartingID;
3105 if (F.NumPreprocessedEntities > 0) {
3106 // Introduce the global -> local mapping for preprocessed entities in
3108 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3110 // Introduce the local -> global mapping for preprocessed entities in
3112 F.PreprocessedEntityRemap.insertOrReplace(
3113 std::make_pair(LocalBasePreprocessedEntityID,
3114 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3120 case DECL_UPDATE_OFFSETS: {
3121 if (Record.size() % 2 != 0) {
3122 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
3125 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3126 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3127 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3129 // If we've already loaded the decl, perform the updates when we finish
3130 // loading this block.
3131 if (Decl *D = GetExistingDecl(ID))
3132 PendingUpdateRecords.push_back(
3133 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3138 case OBJC_CATEGORIES_MAP: {
3139 if (F.LocalNumObjCCategoriesInMap != 0) {
3140 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
3144 F.LocalNumObjCCategoriesInMap = Record[0];
3145 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3149 case OBJC_CATEGORIES:
3150 F.ObjCCategories.swap(Record);
3153 case CUDA_SPECIAL_DECL_REFS:
3154 // Later tables overwrite earlier ones.
3155 // FIXME: Modules will have trouble with this.
3156 CUDASpecialDeclRefs.clear();
3157 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3158 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3161 case HEADER_SEARCH_TABLE: {
3162 F.HeaderFileInfoTableData = Blob.data();
3163 F.LocalNumHeaderFileInfos = Record[1];
3165 F.HeaderFileInfoTable
3166 = HeaderFileInfoLookupTable::Create(
3167 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3168 (const unsigned char *)F.HeaderFileInfoTableData,
3169 HeaderFileInfoTrait(*this, F,
3170 &PP.getHeaderSearchInfo(),
3171 Blob.data() + Record[2]));
3173 PP.getHeaderSearchInfo().SetExternalSource(this);
3174 if (!PP.getHeaderSearchInfo().getExternalLookup())
3175 PP.getHeaderSearchInfo().SetExternalLookup(this);
3180 case FP_PRAGMA_OPTIONS:
3181 // Later tables overwrite earlier ones.
3182 FPPragmaOptions.swap(Record);
3185 case OPENCL_EXTENSIONS:
3186 for (unsigned I = 0, E = Record.size(); I != E; ) {
3187 auto Name = ReadString(Record, I);
3188 auto &Opt = OpenCLExtensions.OptMap[Name];
3189 Opt.Supported = Record[I++] != 0;
3190 Opt.Enabled = Record[I++] != 0;
3191 Opt.Avail = Record[I++];
3192 Opt.Core = Record[I++];
3196 case OPENCL_EXTENSION_TYPES:
3197 for (unsigned I = 0, E = Record.size(); I != E;) {
3198 auto TypeID = static_cast<::TypeID>(Record[I++]);
3199 auto *Type = GetType(TypeID).getTypePtr();
3200 auto NumExt = static_cast<unsigned>(Record[I++]);
3201 for (unsigned II = 0; II != NumExt; ++II) {
3202 auto Ext = ReadString(Record, I);
3203 OpenCLTypeExtMap[Type].insert(Ext);
3208 case OPENCL_EXTENSION_DECLS:
3209 for (unsigned I = 0, E = Record.size(); I != E;) {
3210 auto DeclID = static_cast<::DeclID>(Record[I++]);
3211 auto *Decl = GetDecl(DeclID);
3212 auto NumExt = static_cast<unsigned>(Record[I++]);
3213 for (unsigned II = 0; II != NumExt; ++II) {
3214 auto Ext = ReadString(Record, I);
3215 OpenCLDeclExtMap[Decl].insert(Ext);
3220 case TENTATIVE_DEFINITIONS:
3221 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3222 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3225 case KNOWN_NAMESPACES:
3226 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3227 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3230 case UNDEFINED_BUT_USED:
3231 if (UndefinedButUsed.size() % 2 != 0) {
3232 Error("Invalid existing UndefinedButUsed");
3236 if (Record.size() % 2 != 0) {
3237 Error("invalid undefined-but-used record");
3240 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3241 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3242 UndefinedButUsed.push_back(
3243 ReadSourceLocation(F, Record, I).getRawEncoding());
3246 case DELETE_EXPRS_TO_ANALYZE:
3247 for (unsigned I = 0, N = Record.size(); I != N;) {
3248 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3249 const uint64_t Count = Record[I++];
3250 DelayedDeleteExprs.push_back(Count);
3251 for (uint64_t C = 0; C < Count; ++C) {
3252 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3253 bool IsArrayForm = Record[I++] == 1;
3254 DelayedDeleteExprs.push_back(IsArrayForm);
3259 case IMPORTED_MODULES: {
3260 if (!F.isModule()) {
3261 // If we aren't loading a module (which has its own exports), make
3262 // all of the imported modules visible.
3263 // FIXME: Deal with macros-only imports.
3264 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3265 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3266 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3268 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3269 if (DeserializationListener)
3270 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3277 case MACRO_OFFSET: {
3278 if (F.LocalNumMacros != 0) {
3279 Error("duplicate MACRO_OFFSET record in AST file");
3282 F.MacroOffsets = (const uint32_t *)Blob.data();
3283 F.LocalNumMacros = Record[0];
3284 unsigned LocalBaseMacroID = Record[1];
3285 F.BaseMacroID = getTotalNumMacros();
3287 if (F.LocalNumMacros > 0) {
3288 // Introduce the global -> local mapping for macros within this module.
3289 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3291 // Introduce the local -> global mapping for macros within this module.
3292 F.MacroRemap.insertOrReplace(
3293 std::make_pair(LocalBaseMacroID,
3294 F.BaseMacroID - LocalBaseMacroID));
3296 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3301 case LATE_PARSED_TEMPLATE: {
3302 LateParsedTemplates.append(Record.begin(), Record.end());
3306 case OPTIMIZE_PRAGMA_OPTIONS:
3307 if (Record.size() != 1) {
3308 Error("invalid pragma optimize record");
3311 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3314 case MSSTRUCT_PRAGMA_OPTIONS:
3315 if (Record.size() != 1) {
3316 Error("invalid pragma ms_struct record");
3319 PragmaMSStructState = Record[0];
3322 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3323 if (Record.size() != 2) {
3324 Error("invalid pragma ms_struct record");
3327 PragmaMSPointersToMembersState = Record[0];
3328 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3331 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3332 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3333 UnusedLocalTypedefNameCandidates.push_back(
3334 getGlobalDeclID(F, Record[I]));
3337 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3338 if (Record.size() != 1) {
3339 Error("invalid cuda pragma options record");
3342 ForceCUDAHostDeviceDepth = Record[0];
3345 case PACK_PRAGMA_OPTIONS: {
3346 if (Record.size() < 3) {
3347 Error("invalid pragma pack record");
3350 PragmaPackCurrentValue = Record[0];
3351 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3352 unsigned NumStackEntries = Record[2];
3354 // Reset the stack when importing a new module.
3355 PragmaPackStack.clear();
3356 for (unsigned I = 0; I < NumStackEntries; ++I) {
3357 PragmaPackStackEntry Entry;
3358 Entry.Value = Record[Idx++];
3359 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3360 PragmaPackStrings.push_back(ReadString(Record, Idx));
3361 Entry.SlotLabel = PragmaPackStrings.back();
3362 PragmaPackStack.push_back(Entry);
3370 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3371 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3373 // Additional remapping information.
3374 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3375 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3376 F.ModuleOffsetMap = StringRef();
3378 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3379 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3380 F.SLocRemap.insert(std::make_pair(0U, 0));
3381 F.SLocRemap.insert(std::make_pair(2U, 1));
3384 // Continuous range maps we may be updating in our module.
3385 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
3387 RemapBuilder SLocRemap(F.SLocRemap);
3388 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3389 RemapBuilder MacroRemap(F.MacroRemap);
3390 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3391 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3392 RemapBuilder SelectorRemap(F.SelectorRemap);
3393 RemapBuilder DeclRemap(F.DeclRemap);
3394 RemapBuilder TypeRemap(F.TypeRemap);
3396 while (Data < DataEnd) {
3397 // FIXME: Looking up dependency modules by filename is horrible.
3398 using namespace llvm::support;
3399 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3400 StringRef Name = StringRef((const char*)Data, Len);
3402 ModuleFile *OM = ModuleMgr.lookup(Name);
3405 "SourceLocation remap refers to unknown module, cannot find ";
3411 uint32_t SLocOffset =
3412 endian::readNext<uint32_t, little, unaligned>(Data);
3413 uint32_t IdentifierIDOffset =
3414 endian::readNext<uint32_t, little, unaligned>(Data);
3415 uint32_t MacroIDOffset =
3416 endian::readNext<uint32_t, little, unaligned>(Data);
3417 uint32_t PreprocessedEntityIDOffset =
3418 endian::readNext<uint32_t, little, unaligned>(Data);
3419 uint32_t SubmoduleIDOffset =
3420 endian::readNext<uint32_t, little, unaligned>(Data);
3421 uint32_t SelectorIDOffset =
3422 endian::readNext<uint32_t, little, unaligned>(Data);
3423 uint32_t DeclIDOffset =
3424 endian::readNext<uint32_t, little, unaligned>(Data);
3425 uint32_t TypeIndexOffset =
3426 endian::readNext<uint32_t, little, unaligned>(Data);
3428 uint32_t None = std::numeric_limits<uint32_t>::max();
3430 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3431 RemapBuilder &Remap) {
3433 Remap.insert(std::make_pair(Offset,
3434 static_cast<int>(BaseOffset - Offset)));
3436 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3437 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3438 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3439 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3440 PreprocessedEntityRemap);
3441 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3442 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3443 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3444 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3446 // Global -> local mappings.
3447 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3451 ASTReader::ASTReadResult
3452 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3453 const ModuleFile *ImportedBy,
3454 unsigned ClientLoadCapabilities) {
3456 F.ModuleMapPath = ReadPath(F, Record, Idx);
3458 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
3459 // For an explicitly-loaded module, we don't care whether the original
3460 // module map file exists or matches.
3464 // Try to resolve ModuleName in the current header search context and
3465 // verify that it is found in the same module map file as we saved. If the
3466 // top-level AST file is a main file, skip this check because there is no
3467 // usable header search context.
3468 assert(!F.ModuleName.empty() &&
3469 "MODULE_NAME should come before MODULE_MAP_FILE");
3470 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
3471 // An implicitly-loaded module file should have its module listed in some
3472 // module map file that we've already loaded.
3473 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
3474 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3475 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3477 assert(ImportedBy && "top-level import should be verified");
3478 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3479 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3480 // This module was defined by an imported (explicit) module.
3481 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3482 << ASTFE->getName();
3484 // This module was built with a different module map.
3485 Diag(diag::err_imported_module_not_found)
3486 << F.ModuleName << F.FileName << ImportedBy->FileName
3492 assert(M->Name == F.ModuleName && "found module with different name");
3494 // Check the primary module map file.
3495 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3496 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3497 assert(ModMap && "found module is missing module map file");
3498 assert(ImportedBy && "top-level import should be verified");
3499 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3500 Diag(diag::err_imported_module_modmap_changed)
3501 << F.ModuleName << ImportedBy->FileName
3502 << ModMap->getName() << F.ModuleMapPath;
3506 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3507 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3508 // FIXME: we should use input files rather than storing names.
3509 std::string Filename = ReadPath(F, Record, Idx);
3510 const FileEntry *F =
3511 FileMgr.getFile(Filename, false, false);
3513 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3514 Error("could not find file '" + Filename +"' referenced by AST file");
3517 AdditionalStoredMaps.insert(F);
3520 // Check any additional module map files (e.g. module.private.modulemap)
3521 // that are not in the pcm.
3522 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3523 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3524 // Remove files that match
3525 // Note: SmallPtrSet::erase is really remove
3526 if (!AdditionalStoredMaps.erase(ModMap)) {
3527 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3528 Diag(diag::err_module_different_modmap)
3529 << F.ModuleName << /*new*/0 << ModMap->getName();
3535 // Check any additional module map files that are in the pcm, but not
3536 // found in header search. Cases that match are already removed.
3537 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3538 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3539 Diag(diag::err_module_different_modmap)
3540 << F.ModuleName << /*not new*/1 << ModMap->getName();
3546 Listener->ReadModuleMapFile(F.ModuleMapPath);
3551 /// \brief Move the given method to the back of the global list of methods.
3552 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3553 // Find the entry for this selector in the method pool.
3554 Sema::GlobalMethodPool::iterator Known
3555 = S.MethodPool.find(Method->getSelector());
3556 if (Known == S.MethodPool.end())
3559 // Retrieve the appropriate method list.
3560 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3561 : Known->second.second;
3563 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
3565 if (List->getMethod() == Method) {
3573 if (List->getNext())
3574 List->setMethod(List->getNext()->getMethod());
3576 List->setMethod(Method);
3580 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
3581 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
3582 for (Decl *D : Names) {
3583 bool wasHidden = D->Hidden;
3586 if (wasHidden && SemaObj) {
3587 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3588 moveMethodToBackOfGlobalList(*SemaObj, Method);
3594 void ASTReader::makeModuleVisible(Module *Mod,
3595 Module::NameVisibilityKind NameVisibility,
3596 SourceLocation ImportLoc) {
3597 llvm::SmallPtrSet<Module *, 4> Visited;
3598 SmallVector<Module *, 4> Stack;
3599 Stack.push_back(Mod);
3600 while (!Stack.empty()) {
3601 Mod = Stack.pop_back_val();
3603 if (NameVisibility <= Mod->NameVisibility) {
3604 // This module already has this level of visibility (or greater), so
3605 // there is nothing more to do.
3609 if (!Mod->isAvailable()) {
3610 // Modules that aren't available cannot be made visible.
3614 // Update the module's name visibility.
3615 Mod->NameVisibility = NameVisibility;
3617 // If we've already deserialized any names from this module,
3618 // mark them as visible.
3619 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3620 if (Hidden != HiddenNamesMap.end()) {
3621 auto HiddenNames = std::move(*Hidden);
3622 HiddenNamesMap.erase(Hidden);
3623 makeNamesVisible(HiddenNames.second, HiddenNames.first);
3624 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3625 "making names visible added hidden names");
3628 // Push any exported modules onto the stack to be marked as visible.
3629 SmallVector<Module *, 16> Exports;
3630 Mod->getExportedModules(Exports);
3631 for (SmallVectorImpl<Module *>::iterator
3632 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3633 Module *Exported = *I;
3634 if (Visited.insert(Exported).second)
3635 Stack.push_back(Exported);
3640 /// We've merged the definition \p MergedDef into the existing definition
3641 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3643 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3644 NamedDecl *MergedDef) {
3645 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3646 // in modules other than its owning module. We should instead give the
3647 // ASTContext a list of merged definitions for Def.
3648 if (Def->isHidden()) {
3649 // If MergedDef is visible or becomes visible, make the definition visible.
3650 if (!MergedDef->isHidden())
3651 Def->Hidden = false;
3652 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3653 getContext().mergeDefinitionIntoModule(
3654 Def, MergedDef->getImportedOwningModule(),
3655 /*NotifyListeners*/ false);
3656 PendingMergedDefinitionsToDeduplicate.insert(Def);
3658 auto SubmoduleID = MergedDef->getOwningModuleID();
3659 assert(SubmoduleID && "hidden definition in no module");
3660 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3665 bool ASTReader::loadGlobalIndex() {
3669 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3670 !Context.getLangOpts().Modules)
3673 // Try to load the global index.
3674 TriedLoadingGlobalIndex = true;
3675 StringRef ModuleCachePath
3676 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3677 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
3678 = GlobalModuleIndex::readIndex(ModuleCachePath);
3682 GlobalIndex.reset(Result.first);
3683 ModuleMgr.setGlobalIndex(GlobalIndex.get());
3687 bool ASTReader::isGlobalIndexUnavailable() const {
3688 return Context.getLangOpts().Modules && UseGlobalIndex &&
3689 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3692 static void updateModuleTimestamp(ModuleFile &MF) {
3693 // Overwrite the timestamp file contents so that file's mtime changes.
3694 std::string TimestampFilename = MF.getTimestampFilename();
3696 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3699 OS << "Timestamp file\n";
3701 OS.clear_error(); // Avoid triggering a fatal error.
3704 /// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3705 /// cursor into the start of the given block ID, returning false on success and
3706 /// true on failure.
3707 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3709 llvm::BitstreamEntry Entry = Cursor.advance();
3710 switch (Entry.Kind) {
3711 case llvm::BitstreamEntry::Error:
3712 case llvm::BitstreamEntry::EndBlock:
3715 case llvm::BitstreamEntry::Record:
3716 // Ignore top-level records.
3717 Cursor.skipRecord(Entry.ID);
3720 case llvm::BitstreamEntry::SubBlock:
3721 if (Entry.ID == BlockID) {
3722 if (Cursor.EnterSubBlock(BlockID))
3728 if (Cursor.SkipBlock())
3734 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
3736 SourceLocation ImportLoc,
3737 unsigned ClientLoadCapabilities,
3738 SmallVectorImpl<ImportedSubmodule> *Imported) {
3739 llvm::SaveAndRestore<SourceLocation>
3740 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3742 // Defer any pending actions until we get to the end of reading the AST file.
3743 Deserializing AnASTFile(this);
3745 // Bump the generation number.
3746 unsigned PreviousGeneration = incrementGeneration(Context);
3748 unsigned NumModules = ModuleMgr.size();
3749 SmallVector<ImportedModule, 4> Loaded;
3750 switch (ASTReadResult ReadResult =
3751 ReadASTCore(FileName, Type, ImportLoc,
3752 /*ImportedBy=*/nullptr, Loaded, 0, 0,
3753 ASTFileSignature(), ClientLoadCapabilities)) {
3757 case VersionMismatch:
3758 case ConfigurationMismatch:
3760 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3761 for (const ImportedModule &IM : Loaded)
3762 LoadedSet.insert(IM.Mod);
3764 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
3765 Context.getLangOpts().Modules
3766 ? &PP.getHeaderSearchInfo().getModuleMap()
3769 // If we find that any modules are unusable, the global index is going
3770 // to be out-of-date. Just remove it.
3771 GlobalIndex.reset();
3772 ModuleMgr.setGlobalIndex(nullptr);
3779 // Here comes stuff that we only do once the entire chain is loaded.
3781 // Load the AST blocks of all of the modules that we loaded.
3782 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3783 MEnd = Loaded.end();
3785 ModuleFile &F = *M->Mod;
3787 // Read the AST block.
3788 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3791 // Read the extension blocks.
3792 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3793 if (ASTReadResult Result = ReadExtensionBlock(F))
3797 // Once read, set the ModuleFile bit base offset and update the size in
3798 // bits of all files we've seen.
3799 F.GlobalBitOffset = TotalModulesSizeInBits;
3800 TotalModulesSizeInBits += F.SizeInBits;
3801 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3803 // Preload SLocEntries.
3804 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3805 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3806 // Load it through the SourceManager and don't call ReadSLocEntry()
3807 // directly because the entry may have already been loaded in which case
3808 // calling ReadSLocEntry() directly would trigger an assertion in
3810 SourceMgr.getLoadedSLocEntryByID(Index);
3813 // Map the original source file ID into the ID space of the current
3815 if (F.OriginalSourceFileID.isValid()) {
3816 F.OriginalSourceFileID = FileID::get(
3817 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
3820 // Preload all the pending interesting identifiers by marking them out of
3822 for (auto Offset : F.PreloadIdentifierOffsets) {
3823 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3824 F.IdentifierTableData + Offset);
3826 ASTIdentifierLookupTrait Trait(*this, F);
3827 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3828 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3829 auto &II = PP.getIdentifierTable().getOwn(Key);
3830 II.setOutOfDate(true);
3832 // Mark this identifier as being from an AST file so that we can track
3833 // whether we need to serialize it.
3834 markIdentifierFromAST(*this, II);
3836 // Associate the ID with the identifier so that the writer can reuse it.
3837 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3838 SetIdentifierInfo(ID, &II);
3842 // Setup the import locations and notify the module manager that we've
3843 // committed to these module files.
3844 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3845 MEnd = Loaded.end();
3847 ModuleFile &F = *M->Mod;
3849 ModuleMgr.moduleFileAccepted(&F);
3851 // Set the import location.
3852 F.DirectImportLoc = ImportLoc;
3853 // FIXME: We assume that locations from PCH / preamble do not need
3856 F.ImportLoc = M->ImportLoc;
3858 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
3861 if (!Context.getLangOpts().CPlusPlus ||
3862 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3863 Type != MK_PrebuiltModule)) {
3864 // Mark all of the identifiers in the identifier table as being out of date,
3865 // so that various accessors know to check the loaded modules when the
3866 // identifier is used.
3868 // For C++ modules, we don't need information on many identifiers (just
3869 // those that provide macros or are poisoned), so we mark all of
3870 // the interesting ones via PreloadIdentifierOffsets.
3871 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3872 IdEnd = PP.getIdentifierTable().end();
3874 Id->second->setOutOfDate(true);
3876 // Mark selectors as out of date.
3877 for (auto Sel : SelectorGeneration)
3878 SelectorOutOfDate[Sel.first] = true;
3880 // Resolve any unresolved module exports.
3881 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3882 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
3883 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3884 Module *ResolvedMod = getSubmodule(GlobalID);
3886 switch (Unresolved.Kind) {
3887 case UnresolvedModuleRef::Conflict:
3889 Module::Conflict Conflict;
3890 Conflict.Other = ResolvedMod;
3891 Conflict.Message = Unresolved.String.str();
3892 Unresolved.Mod->Conflicts.push_back(Conflict);
3896 case UnresolvedModuleRef::Import:
3898 Unresolved.Mod->Imports.insert(ResolvedMod);
3901 case UnresolvedModuleRef::Export:
3902 if (ResolvedMod || Unresolved.IsWildcard)
3903 Unresolved.Mod->Exports.push_back(
3904 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3908 UnresolvedModuleRefs.clear();
3911 Imported->append(ImportedModules.begin(),
3912 ImportedModules.end());
3914 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3915 // Might be unnecessary as use declarations are only used to build the
3918 InitializeContext();
3923 if (DeserializationListener)
3924 DeserializationListener->ReaderInitialized(this);
3926 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3927 if (PrimaryModule.OriginalSourceFileID.isValid()) {
3928 // If this AST file is a precompiled preamble, then set the
3929 // preamble file ID of the source manager to the file source file
3930 // from which the preamble was built.
3931 if (Type == MK_Preamble) {
3932 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3933 } else if (Type == MK_MainFile) {
3934 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3938 // For any Objective-C class definitions we have already loaded, make sure
3939 // that we load any additional categories.
3940 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3941 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3942 ObjCClassesLoaded[I],
3943 PreviousGeneration);
3946 if (PP.getHeaderSearchInfo()
3947 .getHeaderSearchOpts()
3948 .ModulesValidateOncePerBuildSession) {
3949 // Now we are certain that the module and all modules it depends on are
3950 // up to date. Create or update timestamp files for modules that are
3951 // located in the module cache (not for PCH files that could be anywhere
3952 // in the filesystem).
3953 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3954 ImportedModule &M = Loaded[I];
3955 if (M.Mod->Kind == MK_ImplicitModule) {
3956 updateModuleTimestamp(*M.Mod);
3964 static ASTFileSignature readASTFileSignature(StringRef PCH);
3966 /// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3967 static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3968 return Stream.canSkipToPos(4) &&
3969 Stream.Read(8) == 'C' &&
3970 Stream.Read(8) == 'P' &&
3971 Stream.Read(8) == 'C' &&
3972 Stream.Read(8) == 'H';
3975 static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3979 case MK_ImplicitModule:
3980 case MK_ExplicitModule:
3981 case MK_PrebuiltModule:
3985 return 2; // main source file
3987 llvm_unreachable("unknown module kind");
3990 ASTReader::ASTReadResult
3991 ASTReader::ReadASTCore(StringRef FileName,
3993 SourceLocation ImportLoc,
3994 ModuleFile *ImportedBy,
3995 SmallVectorImpl<ImportedModule> &Loaded,
3996 off_t ExpectedSize, time_t ExpectedModTime,
3997 ASTFileSignature ExpectedSignature,
3998 unsigned ClientLoadCapabilities) {
4000 std::string ErrorStr;
4001 ModuleManager::AddModuleResult AddResult
4002 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
4003 getGeneration(), ExpectedSize, ExpectedModTime,
4004 ExpectedSignature, readASTFileSignature,
4007 switch (AddResult) {
4008 case ModuleManager::AlreadyLoaded:
4011 case ModuleManager::NewlyLoaded:
4012 // Load module file below.
4015 case ModuleManager::Missing:
4016 // The module file was missing; if the client can handle that, return
4018 if (ClientLoadCapabilities & ARR_Missing)
4021 // Otherwise, return an error.
4022 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
4023 << FileName << !ErrorStr.empty()
4027 case ModuleManager::OutOfDate:
4028 // We couldn't load the module file because it is out-of-date. If the
4029 // client can handle out-of-date, return it.
4030 if (ClientLoadCapabilities & ARR_OutOfDate)
4033 // Otherwise, return an error.
4034 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
4035 << FileName << !ErrorStr.empty()
4040 assert(M && "Missing module file");
4042 // FIXME: This seems rather a hack. Should CurrentDir be part of the
4044 if (FileName != "-") {
4045 CurrentDir = llvm::sys::path::parent_path(FileName);
4046 if (CurrentDir.empty()) CurrentDir = ".";
4050 BitstreamCursor &Stream = F.Stream;
4051 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4052 F.SizeInBits = F.Buffer->getBufferSize() * 8;
4054 // Sniff for the signature.
4055 if (!startsWithASTFileMagic(Stream)) {
4056 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
4061 // This is used for compatibility with older PCH formats.
4062 bool HaveReadControlBlock = false;
4064 llvm::BitstreamEntry Entry = Stream.advance();
4066 switch (Entry.Kind) {
4067 case llvm::BitstreamEntry::Error:
4068 case llvm::BitstreamEntry::Record:
4069 case llvm::BitstreamEntry::EndBlock:
4070 Error("invalid record at top-level of AST file");
4073 case llvm::BitstreamEntry::SubBlock:
4078 case CONTROL_BLOCK_ID:
4079 HaveReadControlBlock = true;
4080 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4082 // Check that we didn't try to load a non-module AST file as a module.
4084 // FIXME: Should we also perform the converse check? Loading a module as
4085 // a PCH file sort of works, but it's a bit wonky.
4086 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4087 Type == MK_PrebuiltModule) &&
4088 F.ModuleName.empty()) {
4089 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4090 if (Result != OutOfDate ||
4091 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4092 Diag(diag::err_module_file_not_module) << FileName;
4097 case Failure: return Failure;
4098 case Missing: return Missing;
4099 case OutOfDate: return OutOfDate;
4100 case VersionMismatch: return VersionMismatch;
4101 case ConfigurationMismatch: return ConfigurationMismatch;
4102 case HadErrors: return HadErrors;
4107 if (!HaveReadControlBlock) {
4108 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4109 Diag(diag::err_pch_version_too_old);
4110 return VersionMismatch;
4113 // Record that we've loaded this module.
4114 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4117 case UNHASHED_CONTROL_BLOCK_ID:
4118 // This block is handled using look-ahead during ReadControlBlock. We
4119 // shouldn't get here!
4120 Error("malformed block record in AST file");
4124 if (Stream.SkipBlock()) {
4125 Error("malformed block record in AST file");
4135 ASTReader::ASTReadResult
4136 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4137 unsigned ClientLoadCapabilities) {
4138 const HeaderSearchOptions &HSOpts =
4139 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4140 bool AllowCompatibleConfigurationMismatch =
4141 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4143 ASTReadResult Result = readUnhashedControlBlockImpl(
4144 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4146 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4148 // If F was directly imported by another module, it's implicitly validated by
4149 // the importing module.
4150 if (DisableValidation || WasImportedBy ||
4151 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4154 if (Result == Failure) {
4155 Error("malformed block record in AST file");
4159 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4160 // If this module has already been finalized in the PCMCache, we're stuck
4161 // with it; we can only load a single version of each module.
4163 // This can happen when a module is imported in two contexts: in one, as a
4164 // user module; in another, as a system module (due to an import from
4165 // another module marked with the [system] flag). It usually indicates a
4166 // bug in the module map: this module should also be marked with [system].
4168 // If -Wno-system-headers (the default), and the first import is as a
4169 // system module, then validation will fail during the as-user import,
4170 // since -Werror flags won't have been validated. However, it's reasonable
4171 // to treat this consistently as a system module.
4173 // If -Wsystem-headers, the PCM on disk was built with
4174 // -Wno-system-headers, and the first import is as a user module, then
4175 // validation will fail during the as-system import since the PCM on disk
4176 // doesn't guarantee that -Werror was respected. However, the -Werror
4177 // flags were checked during the initial as-user import.
4178 if (PCMCache.isBufferFinal(F.FileName)) {
4179 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4187 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4188 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4189 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4190 bool ValidateDiagnosticOptions) {
4191 // Initialize a stream.
4192 BitstreamCursor Stream(StreamData);
4194 // Sniff for the signature.
4195 if (!startsWithASTFileMagic(Stream))
4198 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4199 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4202 // Read all of the records in the options block.
4204 ASTReadResult Result = Success;
4206 llvm::BitstreamEntry Entry = Stream.advance();
4208 switch (Entry.Kind) {
4209 case llvm::BitstreamEntry::Error:
4210 case llvm::BitstreamEntry::SubBlock:
4213 case llvm::BitstreamEntry::EndBlock:
4216 case llvm::BitstreamEntry::Record:
4217 // The interesting case.
4221 // Read and process a record.
4224 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
4227 std::copy(Record.begin(), Record.end(), F->Signature.data());
4230 case DIAGNOSTIC_OPTIONS: {
4231 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4232 if (Listener && ValidateDiagnosticOptions &&
4233 !AllowCompatibleConfigurationMismatch &&
4234 ParseDiagnosticOptions(Record, Complain, *Listener))
4235 Result = OutOfDate; // Don't return early. Read the signature.
4238 case DIAG_PRAGMA_MAPPINGS:
4241 if (F->PragmaDiagMappings.empty())
4242 F->PragmaDiagMappings.swap(Record);
4244 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4245 Record.begin(), Record.end());
4251 /// Parse a record and blob containing module file extension metadata.
4252 static bool parseModuleFileExtensionMetadata(
4253 const SmallVectorImpl<uint64_t> &Record,
4255 ModuleFileExtensionMetadata &Metadata) {
4256 if (Record.size() < 4) return true;
4258 Metadata.MajorVersion = Record[0];
4259 Metadata.MinorVersion = Record[1];
4261 unsigned BlockNameLen = Record[2];
4262 unsigned UserInfoLen = Record[3];
4264 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4266 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4267 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4268 Blob.data() + BlockNameLen + UserInfoLen);
4272 ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4273 BitstreamCursor &Stream = F.Stream;
4277 llvm::BitstreamEntry Entry = Stream.advance();
4278 switch (Entry.Kind) {
4279 case llvm::BitstreamEntry::SubBlock:
4280 if (Stream.SkipBlock())
4285 case llvm::BitstreamEntry::EndBlock:
4288 case llvm::BitstreamEntry::Error:
4291 case llvm::BitstreamEntry::Record:
4297 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4299 case EXTENSION_METADATA: {
4300 ModuleFileExtensionMetadata Metadata;
4301 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4304 // Find a module file extension with this block name.
4305 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4306 if (Known == ModuleFileExtensions.end()) break;
4309 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4311 F.ExtensionReaders.push_back(std::move(Reader));
4322 void ASTReader::InitializeContext() {
4323 // If there's a listener, notify them that we "read" the translation unit.
4324 if (DeserializationListener)
4325 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
4326 Context.getTranslationUnitDecl());
4328 // FIXME: Find a better way to deal with collisions between these
4329 // built-in types. Right now, we just ignore the problem.
4331 // Load the special types.
4332 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4333 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4334 if (!Context.CFConstantStringTypeDecl)
4335 Context.setCFConstantStringType(GetType(String));
4338 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4339 QualType FileType = GetType(File);
4340 if (FileType.isNull()) {
4341 Error("FILE type is NULL");
4345 if (!Context.FILEDecl) {
4346 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4347 Context.setFILEDecl(Typedef->getDecl());
4349 const TagType *Tag = FileType->getAs<TagType>();
4351 Error("Invalid FILE type in AST file");
4354 Context.setFILEDecl(Tag->getDecl());
4359 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4360 QualType Jmp_bufType = GetType(Jmp_buf);
4361 if (Jmp_bufType.isNull()) {
4362 Error("jmp_buf type is NULL");
4366 if (!Context.jmp_bufDecl) {
4367 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4368 Context.setjmp_bufDecl(Typedef->getDecl());
4370 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4372 Error("Invalid jmp_buf type in AST file");
4375 Context.setjmp_bufDecl(Tag->getDecl());
4380 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4381 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4382 if (Sigjmp_bufType.isNull()) {
4383 Error("sigjmp_buf type is NULL");
4387 if (!Context.sigjmp_bufDecl) {
4388 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4389 Context.setsigjmp_bufDecl(Typedef->getDecl());
4391 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4392 assert(Tag && "Invalid sigjmp_buf type in AST file");
4393 Context.setsigjmp_bufDecl(Tag->getDecl());
4398 if (unsigned ObjCIdRedef
4399 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4400 if (Context.ObjCIdRedefinitionType.isNull())
4401 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4404 if (unsigned ObjCClassRedef
4405 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4406 if (Context.ObjCClassRedefinitionType.isNull())
4407 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4410 if (unsigned ObjCSelRedef
4411 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4412 if (Context.ObjCSelRedefinitionType.isNull())
4413 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4416 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4417 QualType Ucontext_tType = GetType(Ucontext_t);
4418 if (Ucontext_tType.isNull()) {
4419 Error("ucontext_t type is NULL");
4423 if (!Context.ucontext_tDecl) {
4424 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4425 Context.setucontext_tDecl(Typedef->getDecl());
4427 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4428 assert(Tag && "Invalid ucontext_t type in AST file");
4429 Context.setucontext_tDecl(Tag->getDecl());
4435 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4437 // If there were any CUDA special declarations, deserialize them.
4438 if (!CUDASpecialDeclRefs.empty()) {
4439 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4440 Context.setcudaConfigureCallDecl(
4441 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4444 // Re-export any modules that were imported by a non-module AST file.
4445 // FIXME: This does not make macro-only imports visible again.
4446 for (auto &Import : ImportedModules) {
4447 if (Module *Imported = getSubmodule(Import.ID)) {
4448 makeModuleVisible(Imported, Module::AllVisible,
4449 /*ImportLoc=*/Import.ImportLoc);
4450 if (Import.ImportLoc.isValid())
4451 PP.makeModuleVisible(Imported, Import.ImportLoc);
4452 // FIXME: should we tell Sema to make the module visible too?
4455 ImportedModules.clear();
4458 void ASTReader::finalizeForWriting() {
4459 // Nothing to do for now.
4462 /// \brief Reads and return the signature record from \p PCH's control block, or
4464 static ASTFileSignature readASTFileSignature(StringRef PCH) {
4465 BitstreamCursor Stream(PCH);
4466 if (!startsWithASTFileMagic(Stream))
4467 return ASTFileSignature();
4469 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4470 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4471 return ASTFileSignature();
4473 // Scan for SIGNATURE inside the diagnostic options block.
4474 ASTReader::RecordData Record;
4476 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4477 if (Entry.Kind != llvm::BitstreamEntry::Record)
4478 return ASTFileSignature();
4482 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4483 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4484 (uint32_t)Record[3], (uint32_t)Record[4]}}};
4488 /// \brief Retrieve the name of the original source file name
4489 /// directly from the AST file, without actually loading the AST
4491 std::string ASTReader::getOriginalSourceFile(
4492 const std::string &ASTFileName, FileManager &FileMgr,
4493 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
4494 // Open the AST file.
4495 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
4497 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4498 << ASTFileName << Buffer.getError().message();
4499 return std::string();
4502 // Initialize the stream
4503 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
4505 // Sniff for the signature.
4506 if (!startsWithASTFileMagic(Stream)) {
4507 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4508 return std::string();
4511 // Scan for the CONTROL_BLOCK_ID block.
4512 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
4513 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4514 return std::string();
4517 // Scan for ORIGINAL_FILE inside the control block.
4520 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4521 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4522 return std::string();
4524 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4525 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4526 return std::string();
4531 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4538 class SimplePCHValidator : public ASTReaderListener {
4539 const LangOptions &ExistingLangOpts;
4540 const TargetOptions &ExistingTargetOpts;
4541 const PreprocessorOptions &ExistingPPOpts;
4542 std::string ExistingModuleCachePath;
4543 FileManager &FileMgr;
4546 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4547 const TargetOptions &ExistingTargetOpts,
4548 const PreprocessorOptions &ExistingPPOpts,
4549 StringRef ExistingModuleCachePath,
4550 FileManager &FileMgr)
4551 : ExistingLangOpts(ExistingLangOpts),
4552 ExistingTargetOpts(ExistingTargetOpts),
4553 ExistingPPOpts(ExistingPPOpts),
4554 ExistingModuleCachePath(ExistingModuleCachePath),
4559 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4560 bool AllowCompatibleDifferences) override {
4561 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4562 AllowCompatibleDifferences);
4565 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4566 bool AllowCompatibleDifferences) override {
4567 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4568 AllowCompatibleDifferences);
4571 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4572 StringRef SpecificModuleCachePath,
4573 bool Complain) override {
4574 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4575 ExistingModuleCachePath,
4576 nullptr, ExistingLangOpts);
4579 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4581 std::string &SuggestedPredefines) override {
4582 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
4583 SuggestedPredefines, ExistingLangOpts);
4587 } // end anonymous namespace
4589 bool ASTReader::readASTFileControlBlock(
4590 StringRef Filename, FileManager &FileMgr,
4591 const PCHContainerReader &PCHContainerRdr,
4592 bool FindModuleFileExtensions,
4593 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
4594 // Open the AST file.
4595 // FIXME: This allows use of the VFS; we do not allow use of the
4596 // VFS when actually loading a module.
4597 auto Buffer = FileMgr.getBufferForFile(Filename);
4602 // Initialize the stream
4603 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4604 BitstreamCursor Stream(Bytes);
4606 // Sniff for the signature.
4607 if (!startsWithASTFileMagic(Stream))
4610 // Scan for the CONTROL_BLOCK_ID block.
4611 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4614 bool NeedsInputFiles = Listener.needsInputFileVisitation();
4615 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
4616 bool NeedsImports = Listener.needsImportVisitation();
4617 BitstreamCursor InputFilesCursor;
4620 std::string ModuleDir;
4621 bool DoneWithControlBlock = false;
4622 while (!DoneWithControlBlock) {
4623 llvm::BitstreamEntry Entry = Stream.advance();
4625 switch (Entry.Kind) {
4626 case llvm::BitstreamEntry::SubBlock: {
4628 case OPTIONS_BLOCK_ID: {
4629 std::string IgnoredSuggestedPredefines;
4630 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4631 /*AllowCompatibleConfigurationMismatch*/ false,
4632 Listener, IgnoredSuggestedPredefines) != Success)
4637 case INPUT_FILES_BLOCK_ID:
4638 InputFilesCursor = Stream;
4639 if (Stream.SkipBlock() ||
4641 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4646 if (Stream.SkipBlock())
4654 case llvm::BitstreamEntry::EndBlock:
4655 DoneWithControlBlock = true;
4658 case llvm::BitstreamEntry::Error:
4661 case llvm::BitstreamEntry::Record:
4665 if (DoneWithControlBlock) break;
4669 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4670 switch ((ControlRecordTypes)RecCode) {
4672 if (Record[0] != VERSION_MAJOR)
4675 if (Listener.ReadFullVersionInformation(Blob))
4681 Listener.ReadModuleName(Blob);
4683 case MODULE_DIRECTORY:
4686 case MODULE_MAP_FILE: {
4688 auto Path = ReadString(Record, Idx);
4689 ResolveImportedPath(Path, ModuleDir);
4690 Listener.ReadModuleMapFile(Path);
4693 case INPUT_FILE_OFFSETS: {
4694 if (!NeedsInputFiles)
4697 unsigned NumInputFiles = Record[0];
4698 unsigned NumUserFiles = Record[1];
4699 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
4700 for (unsigned I = 0; I != NumInputFiles; ++I) {
4701 // Go find this input file.
4702 bool isSystemFile = I >= NumUserFiles;
4704 if (isSystemFile && !NeedsSystemInputFiles)
4705 break; // the rest are system input files
4707 BitstreamCursor &Cursor = InputFilesCursor;
4708 SavedStreamPosition SavedPosition(Cursor);
4709 Cursor.JumpToBit(InputFileOffs[I]);
4711 unsigned Code = Cursor.ReadCode();
4714 bool shouldContinue = false;
4715 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4717 bool Overridden = static_cast<bool>(Record[3]);
4718 std::string Filename = Blob;
4719 ResolveImportedPath(Filename, ModuleDir);
4720 shouldContinue = Listener.visitInputFile(
4721 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
4724 if (!shouldContinue)
4734 unsigned Idx = 0, N = Record.size();
4736 // Read information about the AST file.
4737 Idx += 5; // ImportLoc, Size, ModTime, Signature
4738 std::string Filename = ReadString(Record, Idx);
4739 ResolveImportedPath(Filename, ModuleDir);
4740 Listener.visitImport(Filename);
4746 // No other validation to perform.
4751 // Look for module file extension blocks, if requested.
4752 if (FindModuleFileExtensions) {
4753 BitstreamCursor SavedStream = Stream;
4754 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4755 bool DoneWithExtensionBlock = false;
4756 while (!DoneWithExtensionBlock) {
4757 llvm::BitstreamEntry Entry = Stream.advance();
4759 switch (Entry.Kind) {
4760 case llvm::BitstreamEntry::SubBlock:
4761 if (Stream.SkipBlock())
4766 case llvm::BitstreamEntry::EndBlock:
4767 DoneWithExtensionBlock = true;
4770 case llvm::BitstreamEntry::Error:
4773 case llvm::BitstreamEntry::Record:
4779 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4781 case EXTENSION_METADATA: {
4782 ModuleFileExtensionMetadata Metadata;
4783 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4786 Listener.readModuleFileExtension(Metadata);
4792 Stream = SavedStream;
4795 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4796 if (readUnhashedControlBlockImpl(
4797 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4798 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4799 ValidateDiagnosticOptions) != Success)
4805 bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
4806 const PCHContainerReader &PCHContainerRdr,
4807 const LangOptions &LangOpts,
4808 const TargetOptions &TargetOpts,
4809 const PreprocessorOptions &PPOpts,
4810 StringRef ExistingModuleCachePath) {
4811 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4812 ExistingModuleCachePath, FileMgr);
4813 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
4814 /*FindModuleFileExtensions=*/false,
4816 /*ValidateDiagnosticOptions=*/true);
4819 ASTReader::ASTReadResult
4820 ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
4821 // Enter the submodule block.
4822 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4823 Error("malformed submodule block record in AST file");
4827 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4829 Module *CurrentModule = nullptr;
4830 Module::ModuleKind ModuleKind = Module::ModuleMapModule;
4833 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4835 switch (Entry.Kind) {
4836 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4837 case llvm::BitstreamEntry::Error:
4838 Error("malformed block record in AST file");
4840 case llvm::BitstreamEntry::EndBlock:
4842 case llvm::BitstreamEntry::Record:
4843 // The interesting case.
4850 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4852 if ((Kind == SUBMODULE_METADATA) != First) {
4853 Error("submodule metadata record should be at beginning of block");
4858 // Submodule information is only valid if we have a current module.
4859 // FIXME: Should we error on these cases?
4860 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4861 Kind != SUBMODULE_DEFINITION)
4865 default: // Default behavior: ignore.
4868 case SUBMODULE_DEFINITION: {
4869 if (Record.size() < 8) {
4870 Error("malformed module definition");
4874 StringRef Name = Blob;
4876 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4877 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4878 bool IsFramework = Record[Idx++];
4879 bool IsExplicit = Record[Idx++];
4880 bool IsSystem = Record[Idx++];
4881 bool IsExternC = Record[Idx++];
4882 bool InferSubmodules = Record[Idx++];
4883 bool InferExplicitSubmodules = Record[Idx++];
4884 bool InferExportWildcard = Record[Idx++];
4885 bool ConfigMacrosExhaustive = Record[Idx++];
4887 Module *ParentModule = nullptr;
4889 ParentModule = getSubmodule(Parent);
4891 // Retrieve this (sub)module from the module map, creating it if
4894 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4897 // FIXME: set the definition loc for CurrentModule, or call
4898 // ModMap.setInferredModuleAllowedBy()
4900 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4901 if (GlobalIndex >= SubmodulesLoaded.size() ||
4902 SubmodulesLoaded[GlobalIndex]) {
4903 Error("too many submodules");
4907 if (!ParentModule) {
4908 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4909 if (CurFile != F.File) {
4910 if (!Diags.isDiagnosticInFlight()) {
4911 Diag(diag::err_module_file_conflict)
4912 << CurrentModule->getTopLevelModuleName()
4913 << CurFile->getName()
4914 << F.File->getName();
4920 CurrentModule->setASTFile(F.File);
4923 CurrentModule->Kind = ModuleKind;
4924 CurrentModule->Signature = F.Signature;
4925 CurrentModule->IsFromModuleFile = true;
4926 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
4927 CurrentModule->IsExternC = IsExternC;
4928 CurrentModule->InferSubmodules = InferSubmodules;
4929 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4930 CurrentModule->InferExportWildcard = InferExportWildcard;
4931 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
4932 if (DeserializationListener)
4933 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4935 SubmodulesLoaded[GlobalIndex] = CurrentModule;
4937 // Clear out data that will be replaced by what is in the module file.
4938 CurrentModule->LinkLibraries.clear();
4939 CurrentModule->ConfigMacros.clear();
4940 CurrentModule->UnresolvedConflicts.clear();
4941 CurrentModule->Conflicts.clear();
4943 // The module is available unless it's missing a requirement; relevant
4944 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4945 // Missing headers that were present when the module was built do not
4946 // make it unavailable -- if we got this far, this must be an explicitly
4947 // imported module file.
4948 CurrentModule->Requirements.clear();
4949 CurrentModule->MissingHeaders.clear();
4950 CurrentModule->IsMissingRequirement =
4951 ParentModule && ParentModule->IsMissingRequirement;
4952 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
4956 case SUBMODULE_UMBRELLA_HEADER: {
4957 std::string Filename = Blob;
4958 ResolveImportedPath(F, Filename);
4959 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
4960 if (!CurrentModule->getUmbrellaHeader())
4961 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4962 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
4963 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4964 Error("mismatched umbrella headers in submodule");
4971 case SUBMODULE_HEADER:
4972 case SUBMODULE_EXCLUDED_HEADER:
4973 case SUBMODULE_PRIVATE_HEADER:
4974 // We lazily associate headers with their modules via the HeaderInfo table.
4975 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4976 // of complete filenames or remove it entirely.
4979 case SUBMODULE_TEXTUAL_HEADER:
4980 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4981 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4985 case SUBMODULE_TOPHEADER: {
4986 CurrentModule->addTopHeaderFilename(Blob);
4990 case SUBMODULE_UMBRELLA_DIR: {
4991 std::string Dirname = Blob;
4992 ResolveImportedPath(F, Dirname);
4993 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
4994 if (!CurrentModule->getUmbrellaDir())
4995 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4996 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
4997 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4998 Error("mismatched umbrella directories in submodule");
5005 case SUBMODULE_METADATA: {
5006 F.BaseSubmoduleID = getTotalNumSubmodules();
5007 F.LocalNumSubmodules = Record[0];
5008 unsigned LocalBaseSubmoduleID = Record[1];
5009 if (F.LocalNumSubmodules > 0) {
5010 // Introduce the global -> local mapping for submodules within this
5012 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
5014 // Introduce the local -> global mapping for submodules within this
5016 F.SubmoduleRemap.insertOrReplace(
5017 std::make_pair(LocalBaseSubmoduleID,
5018 F.BaseSubmoduleID - LocalBaseSubmoduleID));
5020 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5022 ModuleKind = (Module::ModuleKind)Record[2];
5026 case SUBMODULE_IMPORTS: {
5027 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5028 UnresolvedModuleRef Unresolved;
5029 Unresolved.File = &F;
5030 Unresolved.Mod = CurrentModule;
5031 Unresolved.ID = Record[Idx];
5032 Unresolved.Kind = UnresolvedModuleRef::Import;
5033 Unresolved.IsWildcard = false;
5034 UnresolvedModuleRefs.push_back(Unresolved);
5039 case SUBMODULE_EXPORTS: {
5040 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
5041 UnresolvedModuleRef Unresolved;
5042 Unresolved.File = &F;
5043 Unresolved.Mod = CurrentModule;
5044 Unresolved.ID = Record[Idx];
5045 Unresolved.Kind = UnresolvedModuleRef::Export;
5046 Unresolved.IsWildcard = Record[Idx + 1];
5047 UnresolvedModuleRefs.push_back(Unresolved);
5050 // Once we've loaded the set of exports, there's no reason to keep
5051 // the parsed, unresolved exports around.
5052 CurrentModule->UnresolvedExports.clear();
5055 case SUBMODULE_REQUIRES: {
5056 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
5057 Context.getTargetInfo());
5061 case SUBMODULE_LINK_LIBRARY:
5062 CurrentModule->LinkLibraries.push_back(
5063 Module::LinkLibrary(Blob, Record[0]));
5066 case SUBMODULE_CONFIG_MACRO:
5067 CurrentModule->ConfigMacros.push_back(Blob.str());
5070 case SUBMODULE_CONFLICT: {
5071 UnresolvedModuleRef Unresolved;
5072 Unresolved.File = &F;
5073 Unresolved.Mod = CurrentModule;
5074 Unresolved.ID = Record[0];
5075 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5076 Unresolved.IsWildcard = false;
5077 Unresolved.String = Blob;
5078 UnresolvedModuleRefs.push_back(Unresolved);
5082 case SUBMODULE_INITIALIZERS:
5083 SmallVector<uint32_t, 16> Inits;
5084 for (auto &ID : Record)
5085 Inits.push_back(getGlobalDeclID(F, ID));
5086 Context.addLazyModuleInitializers(CurrentModule, Inits);
5092 /// \brief Parse the record that corresponds to a LangOptions data
5095 /// This routine parses the language options from the AST file and then gives
5096 /// them to the AST listener if one is set.
5098 /// \returns true if the listener deems the file unacceptable, false otherwise.
5099 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5101 ASTReaderListener &Listener,
5102 bool AllowCompatibleDifferences) {
5103 LangOptions LangOpts;
5105 #define LANGOPT(Name, Bits, Default, Description) \
5106 LangOpts.Name = Record[Idx++];
5107 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5108 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5109 #include "clang/Basic/LangOptions.def"
5110 #define SANITIZER(NAME, ID) \
5111 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
5112 #include "clang/Basic/Sanitizers.def"
5114 for (unsigned N = Record[Idx++]; N; --N)
5115 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5117 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5118 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5119 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
5121 LangOpts.CurrentModule = ReadString(Record, Idx);
5124 for (unsigned N = Record[Idx++]; N; --N) {
5125 LangOpts.CommentOpts.BlockCommandNames.push_back(
5126 ReadString(Record, Idx));
5128 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
5130 // OpenMP offloading options.
5131 for (unsigned N = Record[Idx++]; N; --N) {
5132 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5135 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5137 return Listener.ReadLanguageOptions(LangOpts, Complain,
5138 AllowCompatibleDifferences);
5141 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5142 ASTReaderListener &Listener,
5143 bool AllowCompatibleDifferences) {
5145 TargetOptions TargetOpts;
5146 TargetOpts.Triple = ReadString(Record, Idx);
5147 TargetOpts.CPU = ReadString(Record, Idx);
5148 TargetOpts.ABI = ReadString(Record, Idx);
5149 for (unsigned N = Record[Idx++]; N; --N) {
5150 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5152 for (unsigned N = Record[Idx++]; N; --N) {
5153 TargetOpts.Features.push_back(ReadString(Record, Idx));
5156 return Listener.ReadTargetOptions(TargetOpts, Complain,
5157 AllowCompatibleDifferences);
5160 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5161 ASTReaderListener &Listener) {
5162 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
5164 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
5165 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
5166 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
5167 #include "clang/Basic/DiagnosticOptions.def"
5169 for (unsigned N = Record[Idx++]; N; --N)
5170 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
5171 for (unsigned N = Record[Idx++]; N; --N)
5172 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
5174 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5177 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5178 ASTReaderListener &Listener) {
5179 FileSystemOptions FSOpts;
5181 FSOpts.WorkingDir = ReadString(Record, Idx);
5182 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5185 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5187 ASTReaderListener &Listener) {
5188 HeaderSearchOptions HSOpts;
5190 HSOpts.Sysroot = ReadString(Record, Idx);
5193 for (unsigned N = Record[Idx++]; N; --N) {
5194 std::string Path = ReadString(Record, Idx);
5195 frontend::IncludeDirGroup Group
5196 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
5197 bool IsFramework = Record[Idx++];
5198 bool IgnoreSysRoot = Record[Idx++];
5199 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5203 // System header prefixes.
5204 for (unsigned N = Record[Idx++]; N; --N) {
5205 std::string Prefix = ReadString(Record, Idx);
5206 bool IsSystemHeader = Record[Idx++];
5207 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
5210 HSOpts.ResourceDir = ReadString(Record, Idx);
5211 HSOpts.ModuleCachePath = ReadString(Record, Idx);
5212 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
5213 HSOpts.DisableModuleHash = Record[Idx++];
5214 HSOpts.UseBuiltinIncludes = Record[Idx++];
5215 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5216 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5217 HSOpts.UseLibcxx = Record[Idx++];
5218 std::string SpecificModuleCachePath = ReadString(Record, Idx);
5220 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5224 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5226 ASTReaderListener &Listener,
5227 std::string &SuggestedPredefines) {
5228 PreprocessorOptions PPOpts;
5231 // Macro definitions/undefs
5232 for (unsigned N = Record[Idx++]; N; --N) {
5233 std::string Macro = ReadString(Record, Idx);
5234 bool IsUndef = Record[Idx++];
5235 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5239 for (unsigned N = Record[Idx++]; N; --N) {
5240 PPOpts.Includes.push_back(ReadString(Record, Idx));
5244 for (unsigned N = Record[Idx++]; N; --N) {
5245 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5248 PPOpts.UsePredefines = Record[Idx++];
5249 PPOpts.DetailedRecord = Record[Idx++];
5250 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5251 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5252 PPOpts.ObjCXXARCStandardLibrary =
5253 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5254 SuggestedPredefines.clear();
5255 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5256 SuggestedPredefines);
5259 std::pair<ModuleFile *, unsigned>
5260 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5261 GlobalPreprocessedEntityMapType::iterator
5262 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
5263 assert(I != GlobalPreprocessedEntityMap.end() &&
5264 "Corrupted global preprocessed entity map");
5265 ModuleFile *M = I->second;
5266 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5267 return std::make_pair(M, LocalIndex);
5270 llvm::iterator_range<PreprocessingRecord::iterator>
5271 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5272 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5273 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5274 Mod.NumPreprocessedEntities);
5276 return llvm::make_range(PreprocessingRecord::iterator(),
5277 PreprocessingRecord::iterator());
5280 llvm::iterator_range<ASTReader::ModuleDeclIterator>
5281 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
5282 return llvm::make_range(
5283 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5284 ModuleDeclIterator(this, &Mod,
5285 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
5288 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5289 PreprocessedEntityID PPID = Index+1;
5290 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5291 ModuleFile &M = *PPInfo.first;
5292 unsigned LocalIndex = PPInfo.second;
5293 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5295 if (!PP.getPreprocessingRecord()) {
5296 Error("no preprocessing record");
5300 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
5301 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5303 llvm::BitstreamEntry Entry =
5304 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5305 if (Entry.Kind != llvm::BitstreamEntry::Record)
5309 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5310 TranslateSourceLocation(M, PPOffs.getEnd()));
5311 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
5314 PreprocessorDetailRecordTypes RecType =
5315 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5316 Entry.ID, Record, &Blob);
5318 case PPD_MACRO_EXPANSION: {
5319 bool isBuiltin = Record[0];
5320 IdentifierInfo *Name = nullptr;
5321 MacroDefinitionRecord *Def = nullptr;
5323 Name = getLocalIdentifier(M, Record[1]);
5325 PreprocessedEntityID GlobalID =
5326 getGlobalPreprocessedEntityID(M, Record[1]);
5327 Def = cast<MacroDefinitionRecord>(
5328 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
5333 ME = new (PPRec) MacroExpansion(Name, Range);
5335 ME = new (PPRec) MacroExpansion(Def, Range);
5340 case PPD_MACRO_DEFINITION: {
5341 // Decode the identifier info and then check again; if the macro is
5342 // still defined and associated with the identifier,
5343 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
5344 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
5346 if (DeserializationListener)
5347 DeserializationListener->MacroDefinitionRead(PPID, MD);
5352 case PPD_INCLUSION_DIRECTIVE: {
5353 const char *FullFileNameStart = Blob.data() + Record[0];
5354 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
5355 const FileEntry *File = nullptr;
5356 if (!FullFileName.empty())
5357 File = PP.getFileManager().getFile(FullFileName);
5359 // FIXME: Stable encoding
5360 InclusionDirective::InclusionKind Kind
5361 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5362 InclusionDirective *ID
5363 = new (PPRec) InclusionDirective(PPRec, Kind,
5364 StringRef(Blob.data(), Record[0]),
5365 Record[1], Record[3],
5372 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5375 /// \brief \arg SLocMapI points at a chunk of a module that contains no
5376 /// preprocessed entities or the entities it contains are not the ones we are
5377 /// looking for. Find the next module that contains entities and return the ID
5378 /// of the first entry.
5379 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5380 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5382 for (GlobalSLocOffsetMapType::const_iterator
5383 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5384 ModuleFile &M = *SLocMapI->second;
5385 if (M.NumPreprocessedEntities)
5386 return M.BasePreprocessedEntityID;
5389 return getTotalNumPreprocessedEntities();
5394 struct PPEntityComp {
5395 const ASTReader &Reader;
5398 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5400 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5401 SourceLocation LHS = getLoc(L);
5402 SourceLocation RHS = getLoc(R);
5403 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5406 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5407 SourceLocation LHS = getLoc(L);
5408 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5411 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5412 SourceLocation RHS = getLoc(R);
5413 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5416 SourceLocation getLoc(const PPEntityOffset &PPE) const {
5417 return Reader.TranslateSourceLocation(M, PPE.getBegin());
5421 } // end anonymous namespace
5423 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5424 bool EndsAfter) const {
5425 if (SourceMgr.isLocalSourceLocation(Loc))
5426 return getTotalNumPreprocessedEntities();
5428 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5429 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
5430 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5431 "Corrupted global sloc offset map");
5433 if (SLocMapI->second->NumPreprocessedEntities == 0)
5434 return findNextPreprocessedEntity(SLocMapI);
5436 ModuleFile &M = *SLocMapI->second;
5437 typedef const PPEntityOffset *pp_iterator;
5438 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5439 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5441 size_t Count = M.NumPreprocessedEntities;
5443 pp_iterator First = pp_begin;
5447 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5448 PPEntityComp(*this, M));
5450 // Do a binary search manually instead of using std::lower_bound because
5451 // The end locations of entities may be unordered (when a macro expansion
5452 // is inside another macro argument), but for this case it is not important
5453 // whether we get the first macro expansion or its containing macro.
5457 std::advance(PPI, Half);
5458 if (SourceMgr.isBeforeInTranslationUnit(
5459 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
5462 Count = Count - Half - 1;
5469 return findNextPreprocessedEntity(SLocMapI);
5471 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5474 /// \brief Returns a pair of [Begin, End) indices of preallocated
5475 /// preprocessed entities that \arg Range encompasses.
5476 std::pair<unsigned, unsigned>
5477 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5478 if (Range.isInvalid())
5479 return std::make_pair(0,0);
5480 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5482 PreprocessedEntityID BeginID =
5483 findPreprocessedEntity(Range.getBegin(), false);
5484 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
5485 return std::make_pair(BeginID, EndID);
5488 /// \brief Optionally returns true or false if the preallocated preprocessed
5489 /// entity with index \arg Index came from file \arg FID.
5490 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
5492 if (FID.isInvalid())
5495 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5496 ModuleFile &M = *PPInfo.first;
5497 unsigned LocalIndex = PPInfo.second;
5498 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5500 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
5501 if (Loc.isInvalid())
5504 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5512 /// \brief Visitor used to search for information about a header file.
5513 class HeaderFileInfoVisitor {
5514 const FileEntry *FE;
5516 Optional<HeaderFileInfo> HFI;
5519 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5522 bool operator()(ModuleFile &M) {
5523 HeaderFileInfoLookupTable *Table
5524 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5528 // Look in the on-disk hash table for an entry for this file name.
5529 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
5530 if (Pos == Table->end())
5537 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
5540 } // end anonymous namespace
5542 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
5543 HeaderFileInfoVisitor Visitor(FE);
5544 ModuleMgr.visit(Visitor);
5545 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
5548 return HeaderFileInfo();
5551 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5552 using DiagState = DiagnosticsEngine::DiagState;
5553 SmallVector<DiagState *, 32> DiagStates;
5555 for (ModuleFile &F : ModuleMgr) {
5557 auto &Record = F.PragmaDiagMappings;
5563 auto ReadDiagState =
5564 [&](const DiagState &BasedOn, SourceLocation Loc,
5565 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5566 unsigned BackrefID = Record[Idx++];
5568 return DiagStates[BackrefID - 1];
5570 // A new DiagState was created here.
5571 Diag.DiagStates.push_back(BasedOn);
5572 DiagState *NewState = &Diag.DiagStates.back();
5573 DiagStates.push_back(NewState);
5574 unsigned Size = Record[Idx++];
5575 assert(Idx + Size * 2 <= Record.size() &&
5576 "Invalid data, not enough diag/map pairs");
5578 unsigned DiagID = Record[Idx++];
5579 DiagnosticMapping NewMapping =
5580 DiagnosticMapping::deserialize(Record[Idx++]);
5581 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
5584 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
5586 // If this mapping was specified as a warning but the severity was
5587 // upgraded due to diagnostic settings, simulate the current diagnostic
5588 // settings (and use a warning).
5589 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
5590 NewMapping.setSeverity(diag::Severity::Warning);
5591 NewMapping.setUpgradedFromWarning(false);
5594 Mapping = NewMapping;
5599 // Read the first state.
5600 DiagState *FirstState;
5601 if (F.Kind == MK_ImplicitModule) {
5602 // Implicitly-built modules are reused with different diagnostic
5603 // settings. Use the initial diagnostic state from Diag to simulate this
5604 // compilation's diagnostic settings.
5605 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
5606 DiagStates.push_back(FirstState);
5608 // Skip the initial diagnostic state from the serialized module.
5609 assert(Record[1] == 0 &&
5610 "Invalid data, unexpected backref in initial state");
5611 Idx = 3 + Record[2] * 2;
5612 assert(Idx < Record.size() &&
5613 "Invalid data, not enough state change pairs in initial state");
5614 } else if (F.isModule()) {
5615 // For an explicit module, preserve the flags from the module build
5616 // command line (-w, -Weverything, -Werror, ...) along with any explicit
5618 unsigned Flags = Record[Idx++];
5620 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
5621 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
5622 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
5623 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
5624 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
5625 Initial.ExtBehavior = (diag::Severity)Flags;
5626 FirstState = ReadDiagState(Initial, SourceLocation(), true);
5628 // Set up the root buffer of the module to start with the initial
5629 // diagnostic state of the module itself, to cover files that contain no
5630 // explicit transitions (for which we did not serialize anything).
5631 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
5632 .StateTransitions.push_back({FirstState, 0});
5634 // For prefix ASTs, start with whatever the user configured on the
5636 Idx++; // Skip flags.
5637 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
5638 SourceLocation(), false);
5641 // Read the state transitions.
5642 unsigned NumLocations = Record[Idx++];
5643 while (NumLocations--) {
5644 assert(Idx < Record.size() &&
5645 "Invalid data, missing pragma diagnostic states");
5646 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5647 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5648 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5649 unsigned Transitions = Record[Idx++];
5651 // Note that we don't need to set up Parent/ParentOffset here, because
5652 // we won't be changing the diagnostic state within imported FileIDs
5653 // (other than perhaps appending to the main source file, which has no
5655 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5656 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5657 for (unsigned I = 0; I != Transitions; ++I) {
5658 unsigned Offset = Record[Idx++];
5660 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5661 F.StateTransitions.push_back({State, Offset});
5665 // Read the final state.
5666 assert(Idx < Record.size() &&
5667 "Invalid data, missing final pragma diagnostic state");
5668 SourceLocation CurStateLoc =
5669 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5670 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5672 if (!F.isModule()) {
5673 Diag.DiagStatesByLoc.CurDiagState = CurState;
5674 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5676 // Preserve the property that the imaginary root file describes the
5678 auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions;
5680 T.push_back({CurState, 0});
5682 T[0].State = CurState;
5685 // Don't try to read these mappings again.
5690 /// \brief Get the correct cursor and offset for loading a type.
5691 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5692 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5693 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5694 ModuleFile *M = I->second;
5695 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5698 /// \brief Read and return the type with the given index..
5700 /// The index is the type ID, shifted and minus the number of predefs. This
5701 /// routine actually reads the record corresponding to the type at the given
5702 /// location. It is a helper routine for GetType, which deals with reading type
5704 QualType ASTReader::readTypeRecord(unsigned Index) {
5705 RecordLocation Loc = TypeCursorForIndex(Index);
5706 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
5708 // Keep track of where we are in the stream, then jump back there
5709 // after reading this type.
5710 SavedStreamPosition SavedPosition(DeclsCursor);
5712 ReadingKindTracker ReadingKind(Read_Type, *this);
5714 // Note that we are loading a type record.
5715 Deserializing AType(this);
5718 DeclsCursor.JumpToBit(Loc.Offset);
5720 unsigned Code = DeclsCursor.ReadCode();
5721 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
5722 case TYPE_EXT_QUAL: {
5723 if (Record.size() != 2) {
5724 Error("Incorrect encoding of extended qualifier type");
5727 QualType Base = readType(*Loc.F, Record, Idx);
5728 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5729 return Context.getQualifiedType(Base, Quals);
5732 case TYPE_COMPLEX: {
5733 if (Record.size() != 1) {
5734 Error("Incorrect encoding of complex type");
5737 QualType ElemType = readType(*Loc.F, Record, Idx);
5738 return Context.getComplexType(ElemType);
5741 case TYPE_POINTER: {
5742 if (Record.size() != 1) {
5743 Error("Incorrect encoding of pointer type");
5746 QualType PointeeType = readType(*Loc.F, Record, Idx);
5747 return Context.getPointerType(PointeeType);
5750 case TYPE_DECAYED: {
5751 if (Record.size() != 1) {
5752 Error("Incorrect encoding of decayed type");
5755 QualType OriginalType = readType(*Loc.F, Record, Idx);
5756 QualType DT = Context.getAdjustedParameterType(OriginalType);
5757 if (!isa<DecayedType>(DT))
5758 Error("Decayed type does not decay");
5762 case TYPE_ADJUSTED: {
5763 if (Record.size() != 2) {
5764 Error("Incorrect encoding of adjusted type");
5767 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5768 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5769 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5772 case TYPE_BLOCK_POINTER: {
5773 if (Record.size() != 1) {
5774 Error("Incorrect encoding of block pointer type");
5777 QualType PointeeType = readType(*Loc.F, Record, Idx);
5778 return Context.getBlockPointerType(PointeeType);
5781 case TYPE_LVALUE_REFERENCE: {
5782 if (Record.size() != 2) {
5783 Error("Incorrect encoding of lvalue reference type");
5786 QualType PointeeType = readType(*Loc.F, Record, Idx);
5787 return Context.getLValueReferenceType(PointeeType, Record[1]);
5790 case TYPE_RVALUE_REFERENCE: {
5791 if (Record.size() != 1) {
5792 Error("Incorrect encoding of rvalue reference type");
5795 QualType PointeeType = readType(*Loc.F, Record, Idx);
5796 return Context.getRValueReferenceType(PointeeType);
5799 case TYPE_MEMBER_POINTER: {
5800 if (Record.size() != 2) {
5801 Error("Incorrect encoding of member pointer type");
5804 QualType PointeeType = readType(*Loc.F, Record, Idx);
5805 QualType ClassType = readType(*Loc.F, Record, Idx);
5806 if (PointeeType.isNull() || ClassType.isNull())
5809 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5812 case TYPE_CONSTANT_ARRAY: {
5813 QualType ElementType = readType(*Loc.F, Record, Idx);
5814 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5815 unsigned IndexTypeQuals = Record[2];
5817 llvm::APInt Size = ReadAPInt(Record, Idx);
5818 return Context.getConstantArrayType(ElementType, Size,
5819 ASM, IndexTypeQuals);
5822 case TYPE_INCOMPLETE_ARRAY: {
5823 QualType ElementType = readType(*Loc.F, Record, Idx);
5824 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5825 unsigned IndexTypeQuals = Record[2];
5826 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5829 case TYPE_VARIABLE_ARRAY: {
5830 QualType ElementType = readType(*Loc.F, Record, Idx);
5831 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5832 unsigned IndexTypeQuals = Record[2];
5833 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5834 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5835 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5836 ASM, IndexTypeQuals,
5837 SourceRange(LBLoc, RBLoc));
5841 if (Record.size() != 3) {
5842 Error("incorrect encoding of vector type in AST file");
5846 QualType ElementType = readType(*Loc.F, Record, Idx);
5847 unsigned NumElements = Record[1];
5848 unsigned VecKind = Record[2];
5849 return Context.getVectorType(ElementType, NumElements,
5850 (VectorType::VectorKind)VecKind);
5853 case TYPE_EXT_VECTOR: {
5854 if (Record.size() != 3) {
5855 Error("incorrect encoding of extended vector type in AST file");
5859 QualType ElementType = readType(*Loc.F, Record, Idx);
5860 unsigned NumElements = Record[1];
5861 return Context.getExtVectorType(ElementType, NumElements);
5864 case TYPE_FUNCTION_NO_PROTO: {
5865 if (Record.size() != 7) {
5866 Error("incorrect encoding of no-proto function type");
5869 QualType ResultType = readType(*Loc.F, Record, Idx);
5870 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5871 (CallingConv)Record[4], Record[5], Record[6]);
5872 return Context.getFunctionNoProtoType(ResultType, Info);
5875 case TYPE_FUNCTION_PROTO: {
5876 QualType ResultType = readType(*Loc.F, Record, Idx);
5878 FunctionProtoType::ExtProtoInfo EPI;
5879 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5880 /*hasregparm*/ Record[2],
5881 /*regparm*/ Record[3],
5882 static_cast<CallingConv>(Record[4]),
5883 /*produces*/ Record[5],
5884 /*nocallersavedregs*/ Record[6]);
5888 EPI.Variadic = Record[Idx++];
5889 EPI.HasTrailingReturn = Record[Idx++];
5890 EPI.TypeQuals = Record[Idx++];
5891 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
5892 SmallVector<QualType, 8> ExceptionStorage;
5893 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
5895 unsigned NumParams = Record[Idx++];
5896 SmallVector<QualType, 16> ParamTypes;
5897 for (unsigned I = 0; I != NumParams; ++I)
5898 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5900 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5901 if (Idx != Record.size()) {
5902 for (unsigned I = 0; I != NumParams; ++I)
5903 ExtParameterInfos.push_back(
5904 FunctionProtoType::ExtParameterInfo
5905 ::getFromOpaqueValue(Record[Idx++]));
5906 EPI.ExtParameterInfos = ExtParameterInfos.data();
5909 assert(Idx == Record.size());
5911 return Context.getFunctionType(ResultType, ParamTypes, EPI);
5914 case TYPE_UNRESOLVED_USING: {
5916 return Context.getTypeDeclType(
5917 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5920 case TYPE_TYPEDEF: {
5921 if (Record.size() != 2) {
5922 Error("incorrect encoding of typedef type");
5926 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5927 QualType Canonical = readType(*Loc.F, Record, Idx);
5928 if (!Canonical.isNull())
5929 Canonical = Context.getCanonicalType(Canonical);
5930 return Context.getTypedefType(Decl, Canonical);
5933 case TYPE_TYPEOF_EXPR:
5934 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5937 if (Record.size() != 1) {
5938 Error("incorrect encoding of typeof(type) in AST file");
5941 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5942 return Context.getTypeOfType(UnderlyingType);
5945 case TYPE_DECLTYPE: {
5946 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5947 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5950 case TYPE_UNARY_TRANSFORM: {
5951 QualType BaseType = readType(*Loc.F, Record, Idx);
5952 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5953 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5954 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5958 QualType Deduced = readType(*Loc.F, Record, Idx);
5959 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
5960 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5961 return Context.getAutoType(Deduced, Keyword, IsDependent);
5964 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
5965 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5966 QualType Deduced = readType(*Loc.F, Record, Idx);
5967 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5968 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
5973 if (Record.size() != 2) {
5974 Error("incorrect encoding of record type");
5978 bool IsDependent = Record[Idx++];
5979 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5980 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5981 QualType T = Context.getRecordType(RD);
5982 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5987 if (Record.size() != 2) {
5988 Error("incorrect encoding of enum type");
5992 bool IsDependent = Record[Idx++];
5994 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5995 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5999 case TYPE_ATTRIBUTED: {
6000 if (Record.size() != 3) {
6001 Error("incorrect encoding of attributed type");
6004 QualType modifiedType = readType(*Loc.F, Record, Idx);
6005 QualType equivalentType = readType(*Loc.F, Record, Idx);
6006 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
6007 return Context.getAttributedType(kind, modifiedType, equivalentType);
6011 if (Record.size() != 1) {
6012 Error("incorrect encoding of paren type");
6015 QualType InnerType = readType(*Loc.F, Record, Idx);
6016 return Context.getParenType(InnerType);
6019 case TYPE_PACK_EXPANSION: {
6020 if (Record.size() != 2) {
6021 Error("incorrect encoding of pack expansion type");
6024 QualType Pattern = readType(*Loc.F, Record, Idx);
6025 if (Pattern.isNull())
6027 Optional<unsigned> NumExpansions;
6029 NumExpansions = Record[1] - 1;
6030 return Context.getPackExpansionType(Pattern, NumExpansions);
6033 case TYPE_ELABORATED: {
6035 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6036 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6037 QualType NamedType = readType(*Loc.F, Record, Idx);
6038 return Context.getElaboratedType(Keyword, NNS, NamedType);
6041 case TYPE_OBJC_INTERFACE: {
6043 ObjCInterfaceDecl *ItfD
6044 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
6045 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6048 case TYPE_OBJC_TYPE_PARAM: {
6050 ObjCTypeParamDecl *Decl
6051 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
6052 unsigned NumProtos = Record[Idx++];
6053 SmallVector<ObjCProtocolDecl*, 4> Protos;
6054 for (unsigned I = 0; I != NumProtos; ++I)
6055 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6056 return Context.getObjCTypeParamType(Decl, Protos);
6058 case TYPE_OBJC_OBJECT: {
6060 QualType Base = readType(*Loc.F, Record, Idx);
6061 unsigned NumTypeArgs = Record[Idx++];
6062 SmallVector<QualType, 4> TypeArgs;
6063 for (unsigned I = 0; I != NumTypeArgs; ++I)
6064 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
6065 unsigned NumProtos = Record[Idx++];
6066 SmallVector<ObjCProtocolDecl*, 4> Protos;
6067 for (unsigned I = 0; I != NumProtos; ++I)
6068 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6069 bool IsKindOf = Record[Idx++];
6070 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
6073 case TYPE_OBJC_OBJECT_POINTER: {
6075 QualType Pointee = readType(*Loc.F, Record, Idx);
6076 return Context.getObjCObjectPointerType(Pointee);
6079 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6081 QualType Parm = readType(*Loc.F, Record, Idx);
6082 QualType Replacement = readType(*Loc.F, Record, Idx);
6083 return Context.getSubstTemplateTypeParmType(
6084 cast<TemplateTypeParmType>(Parm),
6085 Context.getCanonicalType(Replacement));
6088 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6090 QualType Parm = readType(*Loc.F, Record, Idx);
6091 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6092 return Context.getSubstTemplateTypeParmPackType(
6093 cast<TemplateTypeParmType>(Parm),
6097 case TYPE_INJECTED_CLASS_NAME: {
6098 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
6099 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6100 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6101 // for AST reading, too much interdependencies.
6102 const Type *T = nullptr;
6103 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6104 if (const Type *Existing = DI->getTypeForDecl()) {
6110 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
6111 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6112 DI->setTypeForDecl(T);
6114 return QualType(T, 0);
6117 case TYPE_TEMPLATE_TYPE_PARM: {
6119 unsigned Depth = Record[Idx++];
6120 unsigned Index = Record[Idx++];
6121 bool Pack = Record[Idx++];
6122 TemplateTypeParmDecl *D
6123 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
6124 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6127 case TYPE_DEPENDENT_NAME: {
6129 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6130 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6131 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
6132 QualType Canon = readType(*Loc.F, Record, Idx);
6133 if (!Canon.isNull())
6134 Canon = Context.getCanonicalType(Canon);
6135 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6138 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6140 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6141 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6142 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
6143 unsigned NumArgs = Record[Idx++];
6144 SmallVector<TemplateArgument, 8> Args;
6145 Args.reserve(NumArgs);
6147 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6148 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
6152 case TYPE_DEPENDENT_SIZED_ARRAY: {
6156 QualType ElementType = readType(*Loc.F, Record, Idx);
6157 ArrayType::ArraySizeModifier ASM
6158 = (ArrayType::ArraySizeModifier)Record[Idx++];
6159 unsigned IndexTypeQuals = Record[Idx++];
6161 // DependentSizedArrayType
6162 Expr *NumElts = ReadExpr(*Loc.F);
6163 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6165 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6166 IndexTypeQuals, Brackets);
6169 case TYPE_TEMPLATE_SPECIALIZATION: {
6171 bool IsDependent = Record[Idx++];
6172 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6173 SmallVector<TemplateArgument, 8> Args;
6174 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6175 QualType Underlying = readType(*Loc.F, Record, Idx);
6177 if (Underlying.isNull())
6178 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
6180 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
6181 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6186 if (Record.size() != 1) {
6187 Error("Incorrect encoding of atomic type");
6190 QualType ValueType = readType(*Loc.F, Record, Idx);
6191 return Context.getAtomicType(ValueType);
6195 if (Record.size() != 2) {
6196 Error("Incorrect encoding of pipe type");
6200 // Reading the pipe element type.
6201 QualType ElementType = readType(*Loc.F, Record, Idx);
6202 unsigned ReadOnly = Record[1];
6203 return Context.getPipeType(ElementType, ReadOnly);
6206 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6209 // DependentSizedExtVectorType
6210 QualType ElementType = readType(*Loc.F, Record, Idx);
6211 Expr *SizeExpr = ReadExpr(*Loc.F);
6212 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6214 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6218 llvm_unreachable("Invalid TypeCode!");
6221 void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6222 SmallVectorImpl<QualType> &Exceptions,
6223 FunctionProtoType::ExceptionSpecInfo &ESI,
6224 const RecordData &Record, unsigned &Idx) {
6225 ExceptionSpecificationType EST =
6226 static_cast<ExceptionSpecificationType>(Record[Idx++]);
6228 if (EST == EST_Dynamic) {
6229 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
6230 Exceptions.push_back(readType(ModuleFile, Record, Idx));
6231 ESI.Exceptions = Exceptions;
6232 } else if (EST == EST_ComputedNoexcept) {
6233 ESI.NoexceptExpr = ReadExpr(ModuleFile);
6234 } else if (EST == EST_Uninstantiated) {
6235 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6236 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6237 } else if (EST == EST_Unevaluated) {
6238 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6242 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6245 const ASTReader::RecordData &Record;
6248 SourceLocation ReadSourceLocation() {
6249 return Reader->ReadSourceLocation(*F, Record, Idx);
6252 TypeSourceInfo *GetTypeSourceInfo() {
6253 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6256 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6257 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
6261 TypeLocReader(ModuleFile &F, ASTReader &Reader,
6262 const ASTReader::RecordData &Record, unsigned &Idx)
6263 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
6265 // We want compile-time assurance that we've enumerated all of
6266 // these, so unfortunately we have to declare them first, then
6267 // define them out-of-line.
6268 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6269 #define TYPELOC(CLASS, PARENT) \
6270 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6271 #include "clang/AST/TypeLocNodes.def"
6273 void VisitFunctionTypeLoc(FunctionTypeLoc);
6274 void VisitArrayTypeLoc(ArrayTypeLoc);
6277 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6281 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6282 TL.setBuiltinLoc(ReadSourceLocation());
6283 if (TL.needsExtraLocalData()) {
6284 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6285 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6286 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6287 TL.setModeAttr(Record[Idx++]);
6291 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6292 TL.setNameLoc(ReadSourceLocation());
6295 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6296 TL.setStarLoc(ReadSourceLocation());
6299 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6303 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6307 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6308 TL.setCaretLoc(ReadSourceLocation());
6311 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6312 TL.setAmpLoc(ReadSourceLocation());
6315 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6316 TL.setAmpAmpLoc(ReadSourceLocation());
6319 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6320 TL.setStarLoc(ReadSourceLocation());
6321 TL.setClassTInfo(GetTypeSourceInfo());
6324 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
6325 TL.setLBracketLoc(ReadSourceLocation());
6326 TL.setRBracketLoc(ReadSourceLocation());
6328 TL.setSizeExpr(Reader->ReadExpr(*F));
6330 TL.setSizeExpr(nullptr);
6333 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6334 VisitArrayTypeLoc(TL);
6337 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6338 VisitArrayTypeLoc(TL);
6341 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6342 VisitArrayTypeLoc(TL);
6345 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6346 DependentSizedArrayTypeLoc TL) {
6347 VisitArrayTypeLoc(TL);
6350 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6351 DependentSizedExtVectorTypeLoc TL) {
6352 TL.setNameLoc(ReadSourceLocation());
6355 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6356 TL.setNameLoc(ReadSourceLocation());
6359 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6360 TL.setNameLoc(ReadSourceLocation());
6363 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6364 TL.setLocalRangeBegin(ReadSourceLocation());
6365 TL.setLParenLoc(ReadSourceLocation());
6366 TL.setRParenLoc(ReadSourceLocation());
6367 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6368 Reader->ReadSourceLocation(*F, Record, Idx)));
6369 TL.setLocalRangeEnd(ReadSourceLocation());
6370 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6371 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
6375 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6376 VisitFunctionTypeLoc(TL);
6379 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6380 VisitFunctionTypeLoc(TL);
6382 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6383 TL.setNameLoc(ReadSourceLocation());
6385 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6386 TL.setNameLoc(ReadSourceLocation());
6388 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6389 TL.setTypeofLoc(ReadSourceLocation());
6390 TL.setLParenLoc(ReadSourceLocation());
6391 TL.setRParenLoc(ReadSourceLocation());
6393 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6394 TL.setTypeofLoc(ReadSourceLocation());
6395 TL.setLParenLoc(ReadSourceLocation());
6396 TL.setRParenLoc(ReadSourceLocation());
6397 TL.setUnderlyingTInfo(GetTypeSourceInfo());
6399 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6400 TL.setNameLoc(ReadSourceLocation());
6403 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6404 TL.setKWLoc(ReadSourceLocation());
6405 TL.setLParenLoc(ReadSourceLocation());
6406 TL.setRParenLoc(ReadSourceLocation());
6407 TL.setUnderlyingTInfo(GetTypeSourceInfo());
6410 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6411 TL.setNameLoc(ReadSourceLocation());
6414 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6415 DeducedTemplateSpecializationTypeLoc TL) {
6416 TL.setTemplateNameLoc(ReadSourceLocation());
6419 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6420 TL.setNameLoc(ReadSourceLocation());
6423 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6424 TL.setNameLoc(ReadSourceLocation());
6427 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6428 TL.setAttrNameLoc(ReadSourceLocation());
6429 if (TL.hasAttrOperand()) {
6431 range.setBegin(ReadSourceLocation());
6432 range.setEnd(ReadSourceLocation());
6433 TL.setAttrOperandParensRange(range);
6435 if (TL.hasAttrExprOperand()) {
6437 TL.setAttrExprOperand(Reader->ReadExpr(*F));
6439 TL.setAttrExprOperand(nullptr);
6440 } else if (TL.hasAttrEnumOperand())
6441 TL.setAttrEnumOperandLoc(ReadSourceLocation());
6444 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6445 TL.setNameLoc(ReadSourceLocation());
6448 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6449 SubstTemplateTypeParmTypeLoc TL) {
6450 TL.setNameLoc(ReadSourceLocation());
6452 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6453 SubstTemplateTypeParmPackTypeLoc TL) {
6454 TL.setNameLoc(ReadSourceLocation());
6456 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6457 TemplateSpecializationTypeLoc TL) {
6458 TL.setTemplateKeywordLoc(ReadSourceLocation());
6459 TL.setTemplateNameLoc(ReadSourceLocation());
6460 TL.setLAngleLoc(ReadSourceLocation());
6461 TL.setRAngleLoc(ReadSourceLocation());
6462 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6465 Reader->GetTemplateArgumentLocInfo(
6466 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
6468 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
6469 TL.setLParenLoc(ReadSourceLocation());
6470 TL.setRParenLoc(ReadSourceLocation());
6473 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6474 TL.setElaboratedKeywordLoc(ReadSourceLocation());
6475 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6478 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
6479 TL.setNameLoc(ReadSourceLocation());
6482 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6483 TL.setElaboratedKeywordLoc(ReadSourceLocation());
6484 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6485 TL.setNameLoc(ReadSourceLocation());
6488 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6489 DependentTemplateSpecializationTypeLoc TL) {
6490 TL.setElaboratedKeywordLoc(ReadSourceLocation());
6491 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6492 TL.setTemplateKeywordLoc(ReadSourceLocation());
6493 TL.setTemplateNameLoc(ReadSourceLocation());
6494 TL.setLAngleLoc(ReadSourceLocation());
6495 TL.setRAngleLoc(ReadSourceLocation());
6496 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
6499 Reader->GetTemplateArgumentLocInfo(
6500 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
6503 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
6504 TL.setEllipsisLoc(ReadSourceLocation());
6507 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6508 TL.setNameLoc(ReadSourceLocation());
6511 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6512 if (TL.getNumProtocols()) {
6513 TL.setProtocolLAngleLoc(ReadSourceLocation());
6514 TL.setProtocolRAngleLoc(ReadSourceLocation());
6516 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6517 TL.setProtocolLoc(i, ReadSourceLocation());
6520 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6521 TL.setHasBaseTypeAsWritten(Record[Idx++]);
6522 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6523 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
6524 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
6525 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
6526 TL.setProtocolLAngleLoc(ReadSourceLocation());
6527 TL.setProtocolRAngleLoc(ReadSourceLocation());
6528 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6529 TL.setProtocolLoc(i, ReadSourceLocation());
6532 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6533 TL.setStarLoc(ReadSourceLocation());
6536 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6537 TL.setKWLoc(ReadSourceLocation());
6538 TL.setLParenLoc(ReadSourceLocation());
6539 TL.setRParenLoc(ReadSourceLocation());
6542 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
6543 TL.setKWLoc(ReadSourceLocation());
6547 ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6549 QualType InfoTy = readType(F, Record, Idx);
6550 if (InfoTy.isNull())
6553 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
6554 TypeLocReader TLR(F, *this, Record, Idx);
6555 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6560 QualType ASTReader::GetType(TypeID ID) {
6561 unsigned FastQuals = ID & Qualifiers::FastMask;
6562 unsigned Index = ID >> Qualifiers::FastWidth;
6564 if (Index < NUM_PREDEF_TYPE_IDS) {
6566 switch ((PredefinedTypeIDs)Index) {
6567 case PREDEF_TYPE_NULL_ID:
6569 case PREDEF_TYPE_VOID_ID:
6572 case PREDEF_TYPE_BOOL_ID:
6576 case PREDEF_TYPE_CHAR_U_ID:
6577 case PREDEF_TYPE_CHAR_S_ID:
6578 // FIXME: Check that the signedness of CharTy is correct!
6582 case PREDEF_TYPE_UCHAR_ID:
6583 T = Context.UnsignedCharTy;
6585 case PREDEF_TYPE_USHORT_ID:
6586 T = Context.UnsignedShortTy;
6588 case PREDEF_TYPE_UINT_ID:
6589 T = Context.UnsignedIntTy;
6591 case PREDEF_TYPE_ULONG_ID:
6592 T = Context.UnsignedLongTy;
6594 case PREDEF_TYPE_ULONGLONG_ID:
6595 T = Context.UnsignedLongLongTy;
6597 case PREDEF_TYPE_UINT128_ID:
6598 T = Context.UnsignedInt128Ty;
6600 case PREDEF_TYPE_SCHAR_ID:
6601 T = Context.SignedCharTy;
6603 case PREDEF_TYPE_WCHAR_ID:
6604 T = Context.WCharTy;
6606 case PREDEF_TYPE_SHORT_ID:
6607 T = Context.ShortTy;
6609 case PREDEF_TYPE_INT_ID:
6612 case PREDEF_TYPE_LONG_ID:
6615 case PREDEF_TYPE_LONGLONG_ID:
6616 T = Context.LongLongTy;
6618 case PREDEF_TYPE_INT128_ID:
6619 T = Context.Int128Ty;
6621 case PREDEF_TYPE_HALF_ID:
6624 case PREDEF_TYPE_FLOAT_ID:
6625 T = Context.FloatTy;
6627 case PREDEF_TYPE_DOUBLE_ID:
6628 T = Context.DoubleTy;
6630 case PREDEF_TYPE_LONGDOUBLE_ID:
6631 T = Context.LongDoubleTy;
6633 case PREDEF_TYPE_FLOAT128_ID:
6634 T = Context.Float128Ty;
6636 case PREDEF_TYPE_OVERLOAD_ID:
6637 T = Context.OverloadTy;
6639 case PREDEF_TYPE_BOUND_MEMBER:
6640 T = Context.BoundMemberTy;
6642 case PREDEF_TYPE_PSEUDO_OBJECT:
6643 T = Context.PseudoObjectTy;
6645 case PREDEF_TYPE_DEPENDENT_ID:
6646 T = Context.DependentTy;
6648 case PREDEF_TYPE_UNKNOWN_ANY:
6649 T = Context.UnknownAnyTy;
6651 case PREDEF_TYPE_NULLPTR_ID:
6652 T = Context.NullPtrTy;
6654 case PREDEF_TYPE_CHAR16_ID:
6655 T = Context.Char16Ty;
6657 case PREDEF_TYPE_CHAR32_ID:
6658 T = Context.Char32Ty;
6660 case PREDEF_TYPE_OBJC_ID:
6661 T = Context.ObjCBuiltinIdTy;
6663 case PREDEF_TYPE_OBJC_CLASS:
6664 T = Context.ObjCBuiltinClassTy;
6666 case PREDEF_TYPE_OBJC_SEL:
6667 T = Context.ObjCBuiltinSelTy;
6669 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6670 case PREDEF_TYPE_##Id##_ID: \
6671 T = Context.SingletonId; \
6673 #include "clang/Basic/OpenCLImageTypes.def"
6674 case PREDEF_TYPE_SAMPLER_ID:
6675 T = Context.OCLSamplerTy;
6677 case PREDEF_TYPE_EVENT_ID:
6678 T = Context.OCLEventTy;
6680 case PREDEF_TYPE_CLK_EVENT_ID:
6681 T = Context.OCLClkEventTy;
6683 case PREDEF_TYPE_QUEUE_ID:
6684 T = Context.OCLQueueTy;
6686 case PREDEF_TYPE_RESERVE_ID_ID:
6687 T = Context.OCLReserveIDTy;
6689 case PREDEF_TYPE_AUTO_DEDUCT:
6690 T = Context.getAutoDeductType();
6693 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6694 T = Context.getAutoRRefDeductType();
6697 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6698 T = Context.ARCUnbridgedCastTy;
6701 case PREDEF_TYPE_BUILTIN_FN:
6702 T = Context.BuiltinFnTy;
6705 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6706 T = Context.OMPArraySectionTy;
6710 assert(!T.isNull() && "Unknown predefined type");
6711 return T.withFastQualifiers(FastQuals);
6714 Index -= NUM_PREDEF_TYPE_IDS;
6715 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6716 if (TypesLoaded[Index].isNull()) {
6717 TypesLoaded[Index] = readTypeRecord(Index);
6718 if (TypesLoaded[Index].isNull())
6721 TypesLoaded[Index]->setFromAST();
6722 if (DeserializationListener)
6723 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6724 TypesLoaded[Index]);
6727 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6730 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6731 return GetType(getGlobalTypeID(F, LocalID));
6734 serialization::TypeID
6735 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6736 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6737 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6739 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6742 if (!F.ModuleOffsetMap.empty())
6743 ReadModuleOffsetMap(F);
6745 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6746 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6747 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6749 unsigned GlobalIndex = LocalIndex + I->second;
6750 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6753 TemplateArgumentLocInfo
6754 ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6755 TemplateArgument::ArgKind Kind,
6756 const RecordData &Record,
6759 case TemplateArgument::Expression:
6761 case TemplateArgument::Type:
6762 return GetTypeSourceInfo(F, Record, Index);
6763 case TemplateArgument::Template: {
6764 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6766 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6767 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6770 case TemplateArgument::TemplateExpansion: {
6771 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6773 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6774 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6775 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6778 case TemplateArgument::Null:
6779 case TemplateArgument::Integral:
6780 case TemplateArgument::Declaration:
6781 case TemplateArgument::NullPtr:
6782 case TemplateArgument::Pack:
6783 // FIXME: Is this right?
6784 return TemplateArgumentLocInfo();
6786 llvm_unreachable("unexpected template argument loc");
6790 ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6791 const RecordData &Record, unsigned &Index) {
6792 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6794 if (Arg.getKind() == TemplateArgument::Expression) {
6795 if (Record[Index++]) // bool InfoHasSameExpr.
6796 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6798 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6802 const ASTTemplateArgumentListInfo*
6803 ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6804 const RecordData &Record,
6806 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6807 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6808 unsigned NumArgsAsWritten = Record[Index++];
6809 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6810 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6811 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6812 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6815 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6819 void ASTReader::CompleteRedeclChain(const Decl *D) {
6820 if (NumCurrentElementsDeserializing) {
6821 // We arrange to not care about the complete redeclaration chain while we're
6822 // deserializing. Just remember that the AST has marked this one as complete
6823 // but that it's not actually complete yet, so we know we still need to
6824 // complete it later.
6825 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6829 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6831 // If this is a named declaration, complete it by looking it up
6832 // within its context.
6834 // FIXME: Merging a function definition should merge
6835 // all mergeable entities within it.
6836 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6837 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6838 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6839 if (!getContext().getLangOpts().CPlusPlus &&
6840 isa<TranslationUnitDecl>(DC)) {
6841 // Outside of C++, we don't have a lookup table for the TU, so update
6842 // the identifier instead. (For C++ modules, we don't store decls
6843 // in the serialized identifier table, so we do the lookup in the TU.)
6844 auto *II = Name.getAsIdentifierInfo();
6845 assert(II && "non-identifier name in C?");
6846 if (II->isOutOfDate())
6847 updateOutOfDateIdentifier(*II);
6850 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6851 // Find all declarations of this kind from the relevant context.
6852 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6853 auto *DC = cast<DeclContext>(DCDecl);
6854 SmallVector<Decl*, 8> Decls;
6855 FindExternalLexicalDecls(
6856 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6861 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6862 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6863 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6864 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6865 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6866 if (auto *Template = FD->getPrimaryTemplate())
6867 Template->LoadLazySpecializations();
6871 CXXCtorInitializer **
6872 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6873 RecordLocation Loc = getLocalBitOffset(Offset);
6874 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6875 SavedStreamPosition SavedPosition(Cursor);
6876 Cursor.JumpToBit(Loc.Offset);
6877 ReadingKindTracker ReadingKind(Read_Decl, *this);
6880 unsigned Code = Cursor.ReadCode();
6881 unsigned RecCode = Cursor.readRecord(Code, Record);
6882 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6883 Error("malformed AST file: missing C++ ctor initializers");
6888 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6891 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6892 RecordLocation Loc = getLocalBitOffset(Offset);
6893 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6894 SavedStreamPosition SavedPosition(Cursor);
6895 Cursor.JumpToBit(Loc.Offset);
6896 ReadingKindTracker ReadingKind(Read_Decl, *this);
6898 unsigned Code = Cursor.ReadCode();
6899 unsigned RecCode = Cursor.readRecord(Code, Record);
6900 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
6901 Error("malformed AST file: missing C++ base specifiers");
6906 unsigned NumBases = Record[Idx++];
6907 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6908 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6909 for (unsigned I = 0; I != NumBases; ++I)
6910 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6914 serialization::DeclID
6915 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6916 if (LocalID < NUM_PREDEF_DECL_IDS)
6919 if (!F.ModuleOffsetMap.empty())
6920 ReadModuleOffsetMap(F);
6922 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6923 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6924 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6926 return LocalID + I->second;
6929 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6930 ModuleFile &M) const {
6931 // Predefined decls aren't from any module.
6932 if (ID < NUM_PREDEF_DECL_IDS)
6935 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6936 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
6939 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
6940 if (!D->isFromASTFile())
6942 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6943 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6947 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6948 if (ID < NUM_PREDEF_DECL_IDS)
6949 return SourceLocation();
6951 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6953 if (Index > DeclsLoaded.size()) {
6954 Error("declaration ID out-of-range for AST file");
6955 return SourceLocation();
6958 if (Decl *D = DeclsLoaded[Index])
6959 return D->getLocation();
6962 DeclCursorForID(ID, Loc);
6966 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6968 case PREDEF_DECL_NULL_ID:
6971 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6972 return Context.getTranslationUnitDecl();
6974 case PREDEF_DECL_OBJC_ID_ID:
6975 return Context.getObjCIdDecl();
6977 case PREDEF_DECL_OBJC_SEL_ID:
6978 return Context.getObjCSelDecl();
6980 case PREDEF_DECL_OBJC_CLASS_ID:
6981 return Context.getObjCClassDecl();
6983 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6984 return Context.getObjCProtocolDecl();
6986 case PREDEF_DECL_INT_128_ID:
6987 return Context.getInt128Decl();
6989 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6990 return Context.getUInt128Decl();
6992 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6993 return Context.getObjCInstanceTypeDecl();
6995 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6996 return Context.getBuiltinVaListDecl();
6998 case PREDEF_DECL_VA_LIST_TAG:
6999 return Context.getVaListTagDecl();
7001 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7002 return Context.getBuiltinMSVaListDecl();
7004 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7005 return Context.getExternCContextDecl();
7007 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7008 return Context.getMakeIntegerSeqDecl();
7010 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7011 return Context.getCFConstantStringDecl();
7013 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7014 return Context.getCFConstantStringTagDecl();
7016 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7017 return Context.getTypePackElementDecl();
7019 llvm_unreachable("PredefinedDeclIDs unknown enum value");
7022 Decl *ASTReader::GetExistingDecl(DeclID ID) {
7023 if (ID < NUM_PREDEF_DECL_IDS) {
7024 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
7026 // Track that we have merged the declaration with ID \p ID into the
7027 // pre-existing predefined declaration \p D.
7028 auto &Merged = KeyDecls[D->getCanonicalDecl()];
7030 Merged.push_back(ID);
7035 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7037 if (Index >= DeclsLoaded.size()) {
7038 assert(0 && "declaration ID out-of-range for AST file");
7039 Error("declaration ID out-of-range for AST file");
7043 return DeclsLoaded[Index];
7046 Decl *ASTReader::GetDecl(DeclID ID) {
7047 if (ID < NUM_PREDEF_DECL_IDS)
7048 return GetExistingDecl(ID);
7050 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7052 if (Index >= DeclsLoaded.size()) {
7053 assert(0 && "declaration ID out-of-range for AST file");
7054 Error("declaration ID out-of-range for AST file");
7058 if (!DeclsLoaded[Index]) {
7060 if (DeserializationListener)
7061 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7064 return DeclsLoaded[Index];
7067 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
7069 if (GlobalID < NUM_PREDEF_DECL_IDS)
7072 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7073 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7074 ModuleFile *Owner = I->second;
7076 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7077 = M.GlobalToLocalDeclIDs.find(Owner);
7078 if (Pos == M.GlobalToLocalDeclIDs.end())
7081 return GlobalID - Owner->BaseDeclID + Pos->second;
7084 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
7085 const RecordData &Record,
7087 if (Idx >= Record.size()) {
7088 Error("Corrupted AST file");
7092 return getGlobalDeclID(F, Record[Idx++]);
7095 /// \brief Resolve the offset of a statement into a statement.
7097 /// This operation will read a new statement from the external
7098 /// source each time it is called, and is meant to be used via a
7099 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7100 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7101 // Switch case IDs are per Decl.
7102 ClearSwitchCaseIDs();
7104 // Offset here is a global offset across the entire chain.
7105 RecordLocation Loc = getLocalBitOffset(Offset);
7106 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
7107 assert(NumCurrentElementsDeserializing == 0 &&
7108 "should not be called while already deserializing");
7109 Deserializing D(this);
7110 return ReadStmtFromStream(*Loc.F);
7113 void ASTReader::FindExternalLexicalDecls(
7114 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7115 SmallVectorImpl<Decl *> &Decls) {
7116 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7118 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
7119 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7120 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7121 auto K = (Decl::Kind)+LexicalDecls[I];
7122 if (!IsKindWeWant(K))
7125 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7127 // Don't add predefined declarations to the lexical context more
7129 if (ID < NUM_PREDEF_DECL_IDS) {
7130 if (PredefsVisited[ID])
7133 PredefsVisited[ID] = true;
7136 if (Decl *D = GetLocalDecl(*M, ID)) {
7137 assert(D->getKind() == K && "wrong kind for lexical decl");
7138 if (!DC->isDeclInLexicalTraversal(D))
7144 if (isa<TranslationUnitDecl>(DC)) {
7145 for (auto Lexical : TULexicalDecls)
7146 Visit(Lexical.first, Lexical.second);
7148 auto I = LexicalDecls.find(DC);
7149 if (I != LexicalDecls.end())
7150 Visit(I->second.first, I->second.second);
7153 ++NumLexicalDeclContextsRead;
7163 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7165 bool operator()(LocalDeclID L, LocalDeclID R) const {
7166 SourceLocation LHS = getLocation(L);
7167 SourceLocation RHS = getLocation(R);
7168 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7171 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7172 SourceLocation RHS = getLocation(R);
7173 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7176 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7177 SourceLocation LHS = getLocation(L);
7178 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7181 SourceLocation getLocation(LocalDeclID ID) const {
7182 return Reader.getSourceManager().getFileLoc(
7183 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7187 } // end anonymous namespace
7189 void ASTReader::FindFileRegionDecls(FileID File,
7190 unsigned Offset, unsigned Length,
7191 SmallVectorImpl<Decl *> &Decls) {
7192 SourceManager &SM = getSourceManager();
7194 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7195 if (I == FileDeclIDs.end())
7198 FileDeclsInfo &DInfo = I->second;
7199 if (DInfo.Decls.empty())
7203 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7204 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7206 DeclIDComp DIDComp(*this, *DInfo.Mod);
7207 ArrayRef<serialization::LocalDeclID>::iterator
7208 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7210 if (BeginIt != DInfo.Decls.begin())
7213 // If we are pointing at a top-level decl inside an objc container, we need
7214 // to backtrack until we find it otherwise we will fail to report that the
7215 // region overlaps with an objc container.
7216 while (BeginIt != DInfo.Decls.begin() &&
7217 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7218 ->isTopLevelDeclInObjCContainer())
7221 ArrayRef<serialization::LocalDeclID>::iterator
7222 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7224 if (EndIt != DInfo.Decls.end())
7227 for (ArrayRef<serialization::LocalDeclID>::iterator
7228 DIt = BeginIt; DIt != EndIt; ++DIt)
7229 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7233 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7234 DeclarationName Name) {
7235 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
7236 "DeclContext has no visible decls in storage");
7240 auto It = Lookups.find(DC);
7241 if (It == Lookups.end())
7244 Deserializing LookupResults(this);
7246 // Load the list of declarations.
7247 SmallVector<NamedDecl *, 64> Decls;
7248 for (DeclID ID : It->second.Table.find(Name)) {
7249 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7250 if (ND->getDeclName() == Name)
7251 Decls.push_back(ND);
7254 ++NumVisibleDeclContextsRead;
7255 SetExternalVisibleDeclsForName(DC, Name, Decls);
7256 return !Decls.empty();
7259 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7260 if (!DC->hasExternalVisibleStorage())
7263 auto It = Lookups.find(DC);
7264 assert(It != Lookups.end() &&
7265 "have external visible storage but no lookup tables");
7269 for (DeclID ID : It->second.Table.findAll()) {
7270 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7271 Decls[ND->getDeclName()].push_back(ND);
7274 ++NumVisibleDeclContextsRead;
7276 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7277 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7279 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7282 const serialization::reader::DeclContextLookupTable *
7283 ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7284 auto I = Lookups.find(Primary);
7285 return I == Lookups.end() ? nullptr : &I->second;
7288 /// \brief Under non-PCH compilation the consumer receives the objc methods
7289 /// before receiving the implementation, and codegen depends on this.
7290 /// We simulate this by deserializing and passing to consumer the methods of the
7291 /// implementation before passing the deserialized implementation decl.
7292 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7293 ASTConsumer *Consumer) {
7294 assert(ImplD && Consumer);
7296 for (auto *I : ImplD->methods())
7297 Consumer->HandleInterestingDecl(DeclGroupRef(I));
7299 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7302 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7303 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7304 PassObjCImplDeclToConsumer(ImplD, Consumer);
7306 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7309 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7310 this->Consumer = Consumer;
7313 PassInterestingDeclsToConsumer();
7315 if (DeserializationListener)
7316 DeserializationListener->ReaderInitialized(this);
7319 void ASTReader::PrintStats() {
7320 std::fprintf(stderr, "*** AST File Statistics:\n");
7322 unsigned NumTypesLoaded
7323 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7325 unsigned NumDeclsLoaded
7326 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
7328 unsigned NumIdentifiersLoaded
7329 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7330 IdentifiersLoaded.end(),
7331 (IdentifierInfo *)nullptr);
7332 unsigned NumMacrosLoaded
7333 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7335 (MacroInfo *)nullptr);
7336 unsigned NumSelectorsLoaded
7337 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7338 SelectorsLoaded.end(),
7341 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7342 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7343 NumSLocEntriesRead, TotalNumSLocEntries,
7344 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7345 if (!TypesLoaded.empty())
7346 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7347 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7348 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7349 if (!DeclsLoaded.empty())
7350 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7351 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7352 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7353 if (!IdentifiersLoaded.empty())
7354 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7355 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7356 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7357 if (!MacrosLoaded.empty())
7358 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7359 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7360 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7361 if (!SelectorsLoaded.empty())
7362 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7363 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7364 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7365 if (TotalNumStatements)
7366 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7367 NumStatementsRead, TotalNumStatements,
7368 ((float)NumStatementsRead/TotalNumStatements * 100));
7370 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7371 NumMacrosRead, TotalNumMacros,
7372 ((float)NumMacrosRead/TotalNumMacros * 100));
7373 if (TotalLexicalDeclContexts)
7374 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7375 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7376 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7378 if (TotalVisibleDeclContexts)
7379 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7380 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7381 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7383 if (TotalNumMethodPoolEntries) {
7384 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7385 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7386 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7389 if (NumMethodPoolLookups) {
7390 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7391 NumMethodPoolHits, NumMethodPoolLookups,
7392 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7394 if (NumMethodPoolTableLookups) {
7395 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7396 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7397 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7401 if (NumIdentifierLookupHits) {
7402 std::fprintf(stderr,
7403 " %u / %u identifier table lookups succeeded (%f%%)\n",
7404 NumIdentifierLookupHits, NumIdentifierLookups,
7405 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7409 std::fprintf(stderr, "\n");
7410 GlobalIndex->printStats();
7413 std::fprintf(stderr, "\n");
7415 std::fprintf(stderr, "\n");
7418 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
7419 LLVM_DUMP_METHOD static void
7420 dumpModuleIDMap(StringRef Name,
7421 const ContinuousRangeMap<Key, ModuleFile *,
7422 InitialCapacity> &Map) {
7423 if (Map.begin() == Map.end())
7426 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7427 llvm::errs() << Name << ":\n";
7428 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7430 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7435 LLVM_DUMP_METHOD void ASTReader::dump() {
7436 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7437 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7438 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7439 dumpModuleIDMap("Global type map", GlobalTypeMap);
7440 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7441 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7442 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7443 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7444 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
7445 dumpModuleIDMap("Global preprocessed entity map",
7446 GlobalPreprocessedEntityMap);
7448 llvm::errs() << "\n*** PCH/Modules Loaded:";
7449 for (ModuleFile &M : ModuleMgr)
7453 /// Return the amount of memory used by memory buffers, breaking down
7454 /// by heap-backed versus mmap'ed memory.
7455 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7456 for (ModuleFile &I : ModuleMgr) {
7457 if (llvm::MemoryBuffer *buf = I.Buffer) {
7458 size_t bytes = buf->getBufferSize();
7459 switch (buf->getBufferKind()) {
7460 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7461 sizes.malloc_bytes += bytes;
7463 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7464 sizes.mmap_bytes += bytes;
7471 void ASTReader::InitializeSema(Sema &S) {
7473 S.addExternalSource(this);
7475 // Makes sure any declarations that were deserialized "too early"
7476 // still get added to the identifier's declaration chains.
7477 for (uint64_t ID : PreloadedDeclIDs) {
7478 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7479 pushExternalDeclIntoScope(D, D->getDeclName());
7481 PreloadedDeclIDs.clear();
7483 // FIXME: What happens if these are changed by a module import?
7484 if (!FPPragmaOptions.empty()) {
7485 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7486 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
7489 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7490 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7491 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
7496 void ASTReader::UpdateSema() {
7497 assert(SemaObj && "no Sema to update");
7499 // Load the offsets of the declarations that Sema references.
7500 // They will be lazily deserialized when needed.
7501 if (!SemaDeclRefs.empty()) {
7502 assert(SemaDeclRefs.size() % 3 == 0);
7503 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
7504 if (!SemaObj->StdNamespace)
7505 SemaObj->StdNamespace = SemaDeclRefs[I];
7506 if (!SemaObj->StdBadAlloc)
7507 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7508 if (!SemaObj->StdAlignValT)
7509 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
7511 SemaDeclRefs.clear();
7514 // Update the state of pragmas. Use the same API as if we had encountered the
7515 // pragma in the source.
7516 if(OptimizeOffPragmaLocation.isValid())
7517 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
7518 if (PragmaMSStructState != -1)
7519 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
7520 if (PointersToMembersPragmaLocation.isValid()) {
7521 SemaObj->ActOnPragmaMSPointersToMembers(
7522 (LangOptions::PragmaMSPointersToMembersKind)
7523 PragmaMSPointersToMembersState,
7524 PointersToMembersPragmaLocation);
7526 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
7528 if (PragmaPackCurrentValue) {
7529 // The bottom of the stack might have a default value. It must be adjusted
7530 // to the current value to ensure that the packing state is preserved after
7531 // popping entries that were included/imported from a PCH/module.
7532 bool DropFirst = false;
7533 if (!PragmaPackStack.empty() &&
7534 PragmaPackStack.front().Location.isInvalid()) {
7535 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7536 "Expected a default alignment value");
7537 SemaObj->PackStack.Stack.emplace_back(
7538 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
7539 SemaObj->PackStack.CurrentPragmaLocation);
7542 for (const auto &Entry :
7543 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7544 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
7546 if (PragmaPackCurrentLocation.isInvalid()) {
7547 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7548 "Expected a default alignment value");
7549 // Keep the current values.
7551 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7552 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7557 IdentifierInfo *ASTReader::get(StringRef Name) {
7558 // Note that we are loading an identifier.
7559 Deserializing AnIdentifier(this);
7561 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
7562 NumIdentifierLookups,
7563 NumIdentifierLookupHits);
7565 // We don't need to do identifier table lookups in C++ modules (we preload
7566 // all interesting declarations, and don't need to use the scope for name
7567 // lookups). Perform the lookup in PCH files, though, since we don't build
7568 // a complete initial identifier table if we're carrying on from a PCH.
7569 if (Context.getLangOpts().CPlusPlus) {
7570 for (auto F : ModuleMgr.pch_modules())
7574 // If there is a global index, look there first to determine which modules
7575 // provably do not have any results for this identifier.
7576 GlobalModuleIndex::HitSet Hits;
7577 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7578 if (!loadGlobalIndex()) {
7579 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7584 ModuleMgr.visit(Visitor, HitsPtr);
7587 IdentifierInfo *II = Visitor.getIdentifierInfo();
7588 markIdentifierUpToDate(II);
7594 /// \brief An identifier-lookup iterator that enumerates all of the
7595 /// identifiers stored within a set of AST files.
7596 class ASTIdentifierIterator : public IdentifierIterator {
7597 /// \brief The AST reader whose identifiers are being enumerated.
7598 const ASTReader &Reader;
7600 /// \brief The current index into the chain of AST files stored in
7604 /// \brief The current position within the identifier lookup table
7605 /// of the current AST file.
7606 ASTIdentifierLookupTable::key_iterator Current;
7608 /// \brief The end position within the identifier lookup table of
7609 /// the current AST file.
7610 ASTIdentifierLookupTable::key_iterator End;
7612 /// \brief Whether to skip any modules in the ASTReader.
7616 explicit ASTIdentifierIterator(const ASTReader &Reader,
7617 bool SkipModules = false);
7619 StringRef Next() override;
7622 } // end namespace clang
7624 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7626 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
7629 StringRef ASTIdentifierIterator::Next() {
7630 while (Current == End) {
7631 // If we have exhausted all of our AST files, we're done.
7636 ModuleFile &F = Reader.ModuleMgr[Index];
7637 if (SkipModules && F.isModule())
7640 ASTIdentifierLookupTable *IdTable =
7641 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
7642 Current = IdTable->key_begin();
7643 End = IdTable->key_end();
7646 // We have any identifiers remaining in the current AST file; return
7648 StringRef Result = *Current;
7655 /// A utility for appending two IdentifierIterators.
7656 class ChainedIdentifierIterator : public IdentifierIterator {
7657 std::unique_ptr<IdentifierIterator> Current;
7658 std::unique_ptr<IdentifierIterator> Queued;
7661 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7662 std::unique_ptr<IdentifierIterator> Second)
7663 : Current(std::move(First)), Queued(std::move(Second)) {}
7665 StringRef Next() override {
7669 StringRef result = Current->Next();
7670 if (!result.empty())
7673 // Try the queued iterator, which may itself be empty.
7675 std::swap(Current, Queued);
7680 } // end anonymous namespace.
7682 IdentifierIterator *ASTReader::getIdentifiers() {
7683 if (!loadGlobalIndex()) {
7684 std::unique_ptr<IdentifierIterator> ReaderIter(
7685 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7686 std::unique_ptr<IdentifierIterator> ModulesIter(
7687 GlobalIndex->createIdentifierIterator());
7688 return new ChainedIdentifierIterator(std::move(ReaderIter),
7689 std::move(ModulesIter));
7692 return new ASTIdentifierIterator(*this);
7696 namespace serialization {
7698 class ReadMethodPoolVisitor {
7701 unsigned PriorGeneration;
7702 unsigned InstanceBits;
7703 unsigned FactoryBits;
7704 bool InstanceHasMoreThanOneDecl;
7705 bool FactoryHasMoreThanOneDecl;
7706 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7707 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
7710 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
7711 unsigned PriorGeneration)
7712 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
7713 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7714 FactoryHasMoreThanOneDecl(false) {}
7716 bool operator()(ModuleFile &M) {
7717 if (!M.SelectorLookupTable)
7720 // If we've already searched this module file, skip it now.
7721 if (M.Generation <= PriorGeneration)
7724 ++Reader.NumMethodPoolTableLookups;
7725 ASTSelectorLookupTable *PoolTable
7726 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7727 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
7728 if (Pos == PoolTable->end())
7731 ++Reader.NumMethodPoolTableHits;
7732 ++Reader.NumSelectorsRead;
7733 // FIXME: Not quite happy with the statistics here. We probably should
7734 // disable this tracking when called via LoadSelector.
7735 // Also, should entries without methods count as misses?
7736 ++Reader.NumMethodPoolEntriesRead;
7737 ASTSelectorLookupTrait::data_type Data = *Pos;
7738 if (Reader.DeserializationListener)
7739 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
7741 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7742 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7743 InstanceBits = Data.InstanceBits;
7744 FactoryBits = Data.FactoryBits;
7745 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7746 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
7750 /// \brief Retrieve the instance methods found by this visitor.
7751 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7752 return InstanceMethods;
7755 /// \brief Retrieve the instance methods found by this visitor.
7756 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7757 return FactoryMethods;
7760 unsigned getInstanceBits() const { return InstanceBits; }
7761 unsigned getFactoryBits() const { return FactoryBits; }
7762 bool instanceHasMoreThanOneDecl() const {
7763 return InstanceHasMoreThanOneDecl;
7765 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
7768 } // end namespace serialization
7769 } // end namespace clang
7771 /// \brief Add the given set of methods to the method list.
7772 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7773 ObjCMethodList &List) {
7774 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7775 S.addMethodToGlobalList(&List, Methods[I]);
7779 void ASTReader::ReadMethodPool(Selector Sel) {
7780 // Get the selector generation and update it to the current generation.
7781 unsigned &Generation = SelectorGeneration[Sel];
7782 unsigned PriorGeneration = Generation;
7783 Generation = getGeneration();
7784 SelectorOutOfDate[Sel] = false;
7786 // Search for methods defined with this selector.
7787 ++NumMethodPoolLookups;
7788 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7789 ModuleMgr.visit(Visitor);
7791 if (Visitor.getInstanceMethods().empty() &&
7792 Visitor.getFactoryMethods().empty())
7795 ++NumMethodPoolHits;
7800 Sema &S = *getSema();
7801 Sema::GlobalMethodPool::iterator Pos
7802 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7804 Pos->second.first.setBits(Visitor.getInstanceBits());
7805 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
7806 Pos->second.second.setBits(Visitor.getFactoryBits());
7807 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
7809 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7810 // when building a module we keep every method individually and may need to
7811 // update hasMoreThanOneDecl as we add the methods.
7812 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7813 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
7816 void ASTReader::updateOutOfDateSelector(Selector Sel) {
7817 if (SelectorOutOfDate[Sel])
7818 ReadMethodPool(Sel);
7821 void ASTReader::ReadKnownNamespaces(
7822 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7825 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7826 if (NamespaceDecl *Namespace
7827 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7828 Namespaces.push_back(Namespace);
7832 void ASTReader::ReadUndefinedButUsed(
7833 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
7834 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7835 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
7836 SourceLocation Loc =
7837 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
7838 Undefined.insert(std::make_pair(D, Loc));
7842 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7843 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7845 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7846 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7847 uint64_t Count = DelayedDeleteExprs[Idx++];
7848 for (uint64_t C = 0; C < Count; ++C) {
7849 SourceLocation DeleteLoc =
7850 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7851 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7852 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7857 void ASTReader::ReadTentativeDefinitions(
7858 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7859 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7860 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7862 TentativeDefs.push_back(Var);
7864 TentativeDefinitions.clear();
7867 void ASTReader::ReadUnusedFileScopedDecls(
7868 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7869 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7871 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7875 UnusedFileScopedDecls.clear();
7878 void ASTReader::ReadDelegatingConstructors(
7879 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7880 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7881 CXXConstructorDecl *D
7882 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7886 DelegatingCtorDecls.clear();
7889 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7890 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7892 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7896 ExtVectorDecls.clear();
7899 void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7900 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7901 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7903 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7904 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7908 UnusedLocalTypedefNameCandidates.clear();
7911 void ASTReader::ReadReferencedSelectors(
7912 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7913 if (ReferencedSelectorsData.empty())
7916 // If there are @selector references added them to its pool. This is for
7917 // implementation of -Wselector.
7918 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7920 while (I < DataSize) {
7921 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7922 SourceLocation SelLoc
7923 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7924 Sels.push_back(std::make_pair(Sel, SelLoc));
7926 ReferencedSelectorsData.clear();
7929 void ASTReader::ReadWeakUndeclaredIdentifiers(
7930 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7931 if (WeakUndeclaredIdentifiers.empty())
7934 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7935 IdentifierInfo *WeakId
7936 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7937 IdentifierInfo *AliasId
7938 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7940 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7941 bool Used = WeakUndeclaredIdentifiers[I++];
7942 WeakInfo WI(AliasId, Loc);
7944 WeakIDs.push_back(std::make_pair(WeakId, WI));
7946 WeakUndeclaredIdentifiers.clear();
7949 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7950 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7951 ExternalVTableUse VT;
7952 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7953 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7954 VT.DefinitionRequired = VTableUses[Idx++];
7955 VTables.push_back(VT);
7961 void ASTReader::ReadPendingInstantiations(
7962 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7963 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7964 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7966 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7968 Pending.push_back(std::make_pair(D, Loc));
7970 PendingInstantiations.clear();
7973 void ASTReader::ReadLateParsedTemplates(
7974 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7976 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7978 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7980 auto LT = llvm::make_unique<LateParsedTemplate>();
7981 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7983 ModuleFile *F = getOwningModuleFile(LT->D);
7984 assert(F && "No module");
7986 unsigned TokN = LateParsedTemplates[Idx++];
7987 LT->Toks.reserve(TokN);
7988 for (unsigned T = 0; T < TokN; ++T)
7989 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7991 LPTMap.insert(std::make_pair(FD, std::move(LT)));
7994 LateParsedTemplates.clear();
7997 void ASTReader::LoadSelector(Selector Sel) {
7998 // It would be complicated to avoid reading the methods anyway. So don't.
7999 ReadMethodPool(Sel);
8002 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8003 assert(ID && "Non-zero identifier ID required");
8004 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8005 IdentifiersLoaded[ID - 1] = II;
8006 if (DeserializationListener)
8007 DeserializationListener->IdentifierRead(ID, II);
8010 /// \brief Set the globally-visible declarations associated with the given
8013 /// If the AST reader is currently in a state where the given declaration IDs
8014 /// cannot safely be resolved, they are queued until it is safe to resolve
8017 /// \param II an IdentifierInfo that refers to one or more globally-visible
8020 /// \param DeclIDs the set of declaration IDs with the name @p II that are
8021 /// visible at global scope.
8023 /// \param Decls if non-null, this vector will be populated with the set of
8024 /// deserialized declarations. These declarations will not be pushed into
8027 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8028 const SmallVectorImpl<uint32_t> &DeclIDs,
8029 SmallVectorImpl<Decl *> *Decls) {
8030 if (NumCurrentElementsDeserializing && !Decls) {
8031 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
8035 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
8037 // Queue this declaration so that it will be added to the
8038 // translation unit scope and identifier's declaration chain
8039 // once a Sema object is known.
8040 PreloadedDeclIDs.push_back(DeclIDs[I]);
8044 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8046 // If we're simply supposed to record the declarations, do so now.
8048 Decls->push_back(D);
8052 // Introduce this declaration into the translation-unit scope
8053 // and add it to the declaration chain for this identifier, so
8054 // that (unqualified) name lookup will find it.
8055 pushExternalDeclIntoScope(D, II);
8059 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
8063 if (IdentifiersLoaded.empty()) {
8064 Error("no identifier table in AST file");
8069 if (!IdentifiersLoaded[ID]) {
8070 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8071 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8072 ModuleFile *M = I->second;
8073 unsigned Index = ID - M->BaseIdentifierID;
8074 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8076 // All of the strings in the AST file are preceded by a 16-bit length.
8077 // Extract that 16-bit length to avoid having to execute strlen().
8078 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8079 // unsigned integers. This is important to avoid integer overflow when
8080 // we cast them to 'unsigned'.
8081 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8082 unsigned StrLen = (((unsigned) StrLenPtr[0])
8083 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
8084 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8085 IdentifiersLoaded[ID] = &II;
8086 markIdentifierFromAST(*this, II);
8087 if (DeserializationListener)
8088 DeserializationListener->IdentifierRead(ID + 1, &II);
8091 return IdentifiersLoaded[ID];
8094 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8095 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
8098 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8099 if (LocalID < NUM_PREDEF_IDENT_IDS)
8102 if (!M.ModuleOffsetMap.empty())
8103 ReadModuleOffsetMap(M);
8105 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8106 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
8107 assert(I != M.IdentifierRemap.end()
8108 && "Invalid index into identifier index remap");
8110 return LocalID + I->second;
8113 MacroInfo *ASTReader::getMacro(MacroID ID) {
8117 if (MacrosLoaded.empty()) {
8118 Error("no macro table in AST file");
8122 ID -= NUM_PREDEF_MACRO_IDS;
8123 if (!MacrosLoaded[ID]) {
8124 GlobalMacroMapType::iterator I
8125 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8126 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8127 ModuleFile *M = I->second;
8128 unsigned Index = ID - M->BaseMacroID;
8129 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
8131 if (DeserializationListener)
8132 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8136 return MacrosLoaded[ID];
8139 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8140 if (LocalID < NUM_PREDEF_MACRO_IDS)
8143 if (!M.ModuleOffsetMap.empty())
8144 ReadModuleOffsetMap(M);
8146 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8147 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8148 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8150 return LocalID + I->second;
8153 serialization::SubmoduleID
8154 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8155 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8158 if (!M.ModuleOffsetMap.empty())
8159 ReadModuleOffsetMap(M);
8161 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8162 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
8163 assert(I != M.SubmoduleRemap.end()
8164 && "Invalid index into submodule index remap");
8166 return LocalID + I->second;
8169 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8170 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8171 assert(GlobalID == 0 && "Unhandled global submodule ID");
8175 if (GlobalID > SubmodulesLoaded.size()) {
8176 Error("submodule ID out of range in AST file");
8180 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8183 Module *ASTReader::getModule(unsigned ID) {
8184 return getSubmodule(ID);
8187 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8189 // It's a module, look it up by submodule ID.
8190 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8191 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8193 // It's a prefix (preamble, PCH, ...). Look it up by index.
8194 unsigned IndexFromEnd = ID >> 1;
8195 assert(IndexFromEnd && "got reference to unknown module file");
8196 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8200 unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8204 // For a file representing a module, use the submodule ID of the top-level
8205 // module as the file ID. For any other kind of file, the number of such
8206 // files loaded beforehand will be the same on reload.
8207 // FIXME: Is this true even if we have an explicit module file and a PCH?
8209 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8211 auto PCHModules = getModuleManager().pch_modules();
8212 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8213 assert(I != PCHModules.end() && "emitting reference to unknown file");
8214 return (I - PCHModules.end()) << 1;
8217 llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8218 ASTReader::getSourceDescriptor(unsigned ID) {
8219 if (const Module *M = getSubmodule(ID))
8220 return ExternalASTSource::ASTSourceDescriptor(*M);
8222 // If there is only a single PCH, return it instead.
8223 // Chained PCH are not suported.
8224 const auto &PCHChain = ModuleMgr.pch_modules();
8225 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
8226 ModuleFile &MF = ModuleMgr.getPrimaryModule();
8227 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
8228 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8229 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8235 ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
8236 auto I = BodySource.find(FD);
8237 if (I == BodySource.end())
8238 return EK_ReplyHazy;
8239 return I->second ? EK_Never : EK_Always;
8242 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8243 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8246 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8250 if (ID > SelectorsLoaded.size()) {
8251 Error("selector ID out of range in AST file");
8255 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
8256 // Load this selector from the selector table.
8257 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8258 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8259 ModuleFile &M = *I->second;
8260 ASTSelectorLookupTrait Trait(*this, M);
8261 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8262 SelectorsLoaded[ID - 1] =
8263 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8264 if (DeserializationListener)
8265 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8268 return SelectorsLoaded[ID - 1];
8271 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8272 return DecodeSelector(ID);
8275 uint32_t ASTReader::GetNumExternalSelectors() {
8276 // ID 0 (the null selector) is considered an external selector.
8277 return getTotalNumSelectors() + 1;
8280 serialization::SelectorID
8281 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8282 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8285 if (!M.ModuleOffsetMap.empty())
8286 ReadModuleOffsetMap(M);
8288 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8289 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
8290 assert(I != M.SelectorRemap.end()
8291 && "Invalid index into selector index remap");
8293 return LocalID + I->second;
8297 ASTReader::ReadDeclarationName(ModuleFile &F,
8298 const RecordData &Record, unsigned &Idx) {
8299 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
8301 case DeclarationName::Identifier:
8302 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
8304 case DeclarationName::ObjCZeroArgSelector:
8305 case DeclarationName::ObjCOneArgSelector:
8306 case DeclarationName::ObjCMultiArgSelector:
8307 return DeclarationName(ReadSelector(F, Record, Idx));
8309 case DeclarationName::CXXConstructorName:
8310 return Context.DeclarationNames.getCXXConstructorName(
8311 Context.getCanonicalType(readType(F, Record, Idx)));
8313 case DeclarationName::CXXDestructorName:
8314 return Context.DeclarationNames.getCXXDestructorName(
8315 Context.getCanonicalType(readType(F, Record, Idx)));
8317 case DeclarationName::CXXDeductionGuideName:
8318 return Context.DeclarationNames.getCXXDeductionGuideName(
8319 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8321 case DeclarationName::CXXConversionFunctionName:
8322 return Context.DeclarationNames.getCXXConversionFunctionName(
8323 Context.getCanonicalType(readType(F, Record, Idx)));
8325 case DeclarationName::CXXOperatorName:
8326 return Context.DeclarationNames.getCXXOperatorName(
8327 (OverloadedOperatorKind)Record[Idx++]);
8329 case DeclarationName::CXXLiteralOperatorName:
8330 return Context.DeclarationNames.getCXXLiteralOperatorName(
8331 GetIdentifierInfo(F, Record, Idx));
8333 case DeclarationName::CXXUsingDirective:
8334 return DeclarationName::getUsingDirectiveName();
8337 llvm_unreachable("Invalid NameKind!");
8340 void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8341 DeclarationNameLoc &DNLoc,
8342 DeclarationName Name,
8343 const RecordData &Record, unsigned &Idx) {
8344 switch (Name.getNameKind()) {
8345 case DeclarationName::CXXConstructorName:
8346 case DeclarationName::CXXDestructorName:
8347 case DeclarationName::CXXConversionFunctionName:
8348 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8351 case DeclarationName::CXXOperatorName:
8352 DNLoc.CXXOperatorName.BeginOpNameLoc
8353 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8354 DNLoc.CXXOperatorName.EndOpNameLoc
8355 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8358 case DeclarationName::CXXLiteralOperatorName:
8359 DNLoc.CXXLiteralOperatorName.OpNameLoc
8360 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8363 case DeclarationName::Identifier:
8364 case DeclarationName::ObjCZeroArgSelector:
8365 case DeclarationName::ObjCOneArgSelector:
8366 case DeclarationName::ObjCMultiArgSelector:
8367 case DeclarationName::CXXUsingDirective:
8368 case DeclarationName::CXXDeductionGuideName:
8373 void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8374 DeclarationNameInfo &NameInfo,
8375 const RecordData &Record, unsigned &Idx) {
8376 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8377 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8378 DeclarationNameLoc DNLoc;
8379 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8380 NameInfo.setInfo(DNLoc);
8383 void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8384 const RecordData &Record, unsigned &Idx) {
8385 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8386 unsigned NumTPLists = Record[Idx++];
8387 Info.NumTemplParamLists = NumTPLists;
8389 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
8390 for (unsigned i = 0; i != NumTPLists; ++i)
8391 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8396 ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
8398 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8400 case TemplateName::Template:
8401 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8403 case TemplateName::OverloadedTemplate: {
8404 unsigned size = Record[Idx++];
8405 UnresolvedSet<8> Decls;
8407 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8409 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8412 case TemplateName::QualifiedTemplate: {
8413 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8414 bool hasTemplKeyword = Record[Idx++];
8415 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8416 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8419 case TemplateName::DependentTemplate: {
8420 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8421 if (Record[Idx++]) // isIdentifier
8422 return Context.getDependentTemplateName(NNS,
8423 GetIdentifierInfo(F, Record,
8425 return Context.getDependentTemplateName(NNS,
8426 (OverloadedOperatorKind)Record[Idx++]);
8429 case TemplateName::SubstTemplateTemplateParm: {
8430 TemplateTemplateParmDecl *param
8431 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8432 if (!param) return TemplateName();
8433 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8434 return Context.getSubstTemplateTemplateParm(param, replacement);
8437 case TemplateName::SubstTemplateTemplateParmPack: {
8438 TemplateTemplateParmDecl *Param
8439 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8441 return TemplateName();
8443 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8444 if (ArgPack.getKind() != TemplateArgument::Pack)
8445 return TemplateName();
8447 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8451 llvm_unreachable("Unhandled template name kind!");
8454 TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8455 const RecordData &Record,
8457 bool Canonicalize) {
8459 // The caller wants a canonical template argument. Sometimes the AST only
8460 // wants template arguments in canonical form (particularly as the template
8461 // argument lists of template specializations) so ensure we preserve that
8462 // canonical form across serialization.
8463 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8464 return Context.getCanonicalTemplateArgument(Arg);
8467 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8469 case TemplateArgument::Null:
8470 return TemplateArgument();
8471 case TemplateArgument::Type:
8472 return TemplateArgument(readType(F, Record, Idx));
8473 case TemplateArgument::Declaration: {
8474 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
8475 return TemplateArgument(D, readType(F, Record, Idx));
8477 case TemplateArgument::NullPtr:
8478 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8479 case TemplateArgument::Integral: {
8480 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8481 QualType T = readType(F, Record, Idx);
8482 return TemplateArgument(Context, Value, T);
8484 case TemplateArgument::Template:
8485 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8486 case TemplateArgument::TemplateExpansion: {
8487 TemplateName Name = ReadTemplateName(F, Record, Idx);
8488 Optional<unsigned> NumTemplateExpansions;
8489 if (unsigned NumExpansions = Record[Idx++])
8490 NumTemplateExpansions = NumExpansions - 1;
8491 return TemplateArgument(Name, NumTemplateExpansions);
8493 case TemplateArgument::Expression:
8494 return TemplateArgument(ReadExpr(F));
8495 case TemplateArgument::Pack: {
8496 unsigned NumArgs = Record[Idx++];
8497 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8498 for (unsigned I = 0; I != NumArgs; ++I)
8499 Args[I] = ReadTemplateArgument(F, Record, Idx);
8500 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
8504 llvm_unreachable("Unhandled template argument kind!");
8507 TemplateParameterList *
8508 ASTReader::ReadTemplateParameterList(ModuleFile &F,
8509 const RecordData &Record, unsigned &Idx) {
8510 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8511 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8512 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8514 unsigned NumParams = Record[Idx++];
8515 SmallVector<NamedDecl *, 16> Params;
8516 Params.reserve(NumParams);
8518 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8521 TemplateParameterList* TemplateParams =
8522 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
8523 Params, RAngleLoc, nullptr);
8524 return TemplateParams;
8529 ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
8530 ModuleFile &F, const RecordData &Record,
8531 unsigned &Idx, bool Canonicalize) {
8532 unsigned NumTemplateArgs = Record[Idx++];
8533 TemplArgs.reserve(NumTemplateArgs);
8534 while (NumTemplateArgs--)
8535 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
8538 /// \brief Read a UnresolvedSet structure.
8539 void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
8540 const RecordData &Record, unsigned &Idx) {
8541 unsigned NumDecls = Record[Idx++];
8542 Set.reserve(Context, NumDecls);
8543 while (NumDecls--) {
8544 DeclID ID = ReadDeclID(F, Record, Idx);
8545 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
8546 Set.addLazyDecl(Context, ID, AS);
8551 ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8552 const RecordData &Record, unsigned &Idx) {
8553 bool isVirtual = static_cast<bool>(Record[Idx++]);
8554 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8555 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8556 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8557 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8558 SourceRange Range = ReadSourceRange(F, Record, Idx);
8559 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
8560 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
8562 Result.setInheritConstructors(inheritConstructors);
8566 CXXCtorInitializer **
8567 ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8569 unsigned NumInitializers = Record[Idx++];
8570 assert(NumInitializers && "wrote ctor initializers but have no inits");
8571 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8572 for (unsigned i = 0; i != NumInitializers; ++i) {
8573 TypeSourceInfo *TInfo = nullptr;
8574 bool IsBaseVirtual = false;
8575 FieldDecl *Member = nullptr;
8576 IndirectFieldDecl *IndirectMember = nullptr;
8578 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8580 case CTOR_INITIALIZER_BASE:
8581 TInfo = GetTypeSourceInfo(F, Record, Idx);
8582 IsBaseVirtual = Record[Idx++];
8585 case CTOR_INITIALIZER_DELEGATING:
8586 TInfo = GetTypeSourceInfo(F, Record, Idx);
8589 case CTOR_INITIALIZER_MEMBER:
8590 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8593 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8594 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8598 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8599 Expr *Init = ReadExpr(F);
8600 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8601 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
8603 CXXCtorInitializer *BOMInit;
8604 if (Type == CTOR_INITIALIZER_BASE)
8605 BOMInit = new (Context)
8606 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8607 RParenLoc, MemberOrEllipsisLoc);
8608 else if (Type == CTOR_INITIALIZER_DELEGATING)
8609 BOMInit = new (Context)
8610 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
8612 BOMInit = new (Context)
8613 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8616 BOMInit = new (Context)
8617 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8618 LParenLoc, Init, RParenLoc);
8620 if (/*IsWritten*/Record[Idx++]) {
8621 unsigned SourceOrder = Record[Idx++];
8622 BOMInit->setSourceOrder(SourceOrder);
8625 CtorInitializers[i] = BOMInit;
8628 return CtorInitializers;
8631 NestedNameSpecifier *
8632 ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8633 const RecordData &Record, unsigned &Idx) {
8634 unsigned N = Record[Idx++];
8635 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
8636 for (unsigned I = 0; I != N; ++I) {
8637 NestedNameSpecifier::SpecifierKind Kind
8638 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8640 case NestedNameSpecifier::Identifier: {
8641 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8642 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8646 case NestedNameSpecifier::Namespace: {
8647 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8648 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8652 case NestedNameSpecifier::NamespaceAlias: {
8653 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8654 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8658 case NestedNameSpecifier::TypeSpec:
8659 case NestedNameSpecifier::TypeSpecWithTemplate: {
8660 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8664 bool Template = Record[Idx++];
8665 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8669 case NestedNameSpecifier::Global: {
8670 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8671 // No associated value, and there can't be a prefix.
8675 case NestedNameSpecifier::Super: {
8676 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8677 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8686 NestedNameSpecifierLoc
8687 ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8689 unsigned N = Record[Idx++];
8690 NestedNameSpecifierLocBuilder Builder;
8691 for (unsigned I = 0; I != N; ++I) {
8692 NestedNameSpecifier::SpecifierKind Kind
8693 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8695 case NestedNameSpecifier::Identifier: {
8696 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8697 SourceRange Range = ReadSourceRange(F, Record, Idx);
8698 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8702 case NestedNameSpecifier::Namespace: {
8703 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8704 SourceRange Range = ReadSourceRange(F, Record, Idx);
8705 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8709 case NestedNameSpecifier::NamespaceAlias: {
8710 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8711 SourceRange Range = ReadSourceRange(F, Record, Idx);
8712 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8716 case NestedNameSpecifier::TypeSpec:
8717 case NestedNameSpecifier::TypeSpecWithTemplate: {
8718 bool Template = Record[Idx++];
8719 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8721 return NestedNameSpecifierLoc();
8722 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8724 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8725 Builder.Extend(Context,
8726 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8727 T->getTypeLoc(), ColonColonLoc);
8731 case NestedNameSpecifier::Global: {
8732 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8733 Builder.MakeGlobal(Context, ColonColonLoc);
8737 case NestedNameSpecifier::Super: {
8738 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8739 SourceRange Range = ReadSourceRange(F, Record, Idx);
8740 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8746 return Builder.getWithLocInContext(Context);
8750 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8752 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8753 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8754 return SourceRange(beg, end);
8757 /// \brief Read an integral value
8758 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8759 unsigned BitWidth = Record[Idx++];
8760 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8761 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8766 /// \brief Read a signed integral value
8767 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8768 bool isUnsigned = Record[Idx++];
8769 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8772 /// \brief Read a floating-point value
8773 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8774 const llvm::fltSemantics &Sem,
8776 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
8779 // \brief Read a string
8780 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8781 unsigned Len = Record[Idx++];
8782 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8787 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8789 std::string Filename = ReadString(Record, Idx);
8790 ResolveImportedPath(F, Filename);
8794 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8796 unsigned Major = Record[Idx++];
8797 unsigned Minor = Record[Idx++];
8798 unsigned Subminor = Record[Idx++];
8800 return VersionTuple(Major);
8802 return VersionTuple(Major, Minor - 1);
8803 return VersionTuple(Major, Minor - 1, Subminor - 1);
8806 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8807 const RecordData &Record,
8809 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8810 return CXXTemporary::Create(Context, Decl);
8813 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
8814 return Diag(CurrentImportLoc, DiagID);
8817 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
8818 return Diags.Report(Loc, DiagID);
8821 /// \brief Retrieve the identifier table associated with the
8823 IdentifierTable &ASTReader::getIdentifierTable() {
8824 return PP.getIdentifierTable();
8827 /// \brief Record that the given ID maps to the given switch-case
8829 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
8830 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
8831 "Already have a SwitchCase with this ID");
8832 (*CurrSwitchCaseStmts)[ID] = SC;
8835 /// \brief Retrieve the switch-case statement with the given ID.
8836 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
8837 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
8838 return (*CurrSwitchCaseStmts)[ID];
8841 void ASTReader::ClearSwitchCaseIDs() {
8842 CurrSwitchCaseStmts->clear();
8845 void ASTReader::ReadComments() {
8846 std::vector<RawComment *> Comments;
8847 for (SmallVectorImpl<std::pair<BitstreamCursor,
8848 serialization::ModuleFile *> >::iterator
8849 I = CommentsCursors.begin(),
8850 E = CommentsCursors.end();
8853 BitstreamCursor &Cursor = I->first;
8854 serialization::ModuleFile &F = *I->second;
8855 SavedStreamPosition SavedPosition(Cursor);
8859 llvm::BitstreamEntry Entry =
8860 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
8862 switch (Entry.Kind) {
8863 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8864 case llvm::BitstreamEntry::Error:
8865 Error("malformed block record in AST file");
8867 case llvm::BitstreamEntry::EndBlock:
8869 case llvm::BitstreamEntry::Record:
8870 // The interesting case.
8876 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
8877 case COMMENTS_RAW_COMMENT: {
8879 SourceRange SR = ReadSourceRange(F, Record, Idx);
8880 RawComment::CommentKind Kind =
8881 (RawComment::CommentKind) Record[Idx++];
8882 bool IsTrailingComment = Record[Idx++];
8883 bool IsAlmostTrailingComment = Record[Idx++];
8884 Comments.push_back(new (Context) RawComment(
8885 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8886 Context.getLangOpts().CommentOpts.ParseAllComments));
8892 // De-serialized SourceLocations get negative FileIDs for other modules,
8893 // potentially invalidating the original order. Sort it again.
8894 std::sort(Comments.begin(), Comments.end(),
8895 BeforeThanCompare<RawComment>(SourceMgr));
8896 Context.Comments.addDeserializedComments(Comments);
8900 void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
8901 bool IncludeSystem, bool Complain,
8902 llvm::function_ref<void(const serialization::InputFile &IF,
8903 bool isSystem)> Visitor) {
8904 unsigned NumUserInputs = MF.NumUserInputFiles;
8905 unsigned NumInputs = MF.InputFilesLoaded.size();
8906 assert(NumUserInputs <= NumInputs);
8907 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
8908 for (unsigned I = 0; I < N; ++I) {
8909 bool IsSystem = I >= NumUserInputs;
8910 InputFile IF = getInputFile(MF, I+1, Complain);
8911 Visitor(IF, IsSystem);
8915 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8916 // If we know the owning module, use it.
8917 if (Module *M = D->getImportedOwningModule())
8918 return M->getFullModuleName();
8920 // Otherwise, use the name of the top-level module the decl is within.
8921 if (ModuleFile *M = getOwningModuleFile(D))
8922 return M->ModuleName;
8924 // Not from a module.
8928 void ASTReader::finishPendingActions() {
8929 while (!PendingIdentifierInfos.empty() ||
8930 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
8931 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
8932 !PendingUpdateRecords.empty()) {
8933 // If any identifiers with corresponding top-level declarations have
8934 // been loaded, load those declarations now.
8935 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8937 TopLevelDeclsMap TopLevelDecls;
8939 while (!PendingIdentifierInfos.empty()) {
8940 IdentifierInfo *II = PendingIdentifierInfos.back().first;
8941 SmallVector<uint32_t, 4> DeclIDs =
8942 std::move(PendingIdentifierInfos.back().second);
8943 PendingIdentifierInfos.pop_back();
8945 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
8948 // For each decl chain that we wanted to complete while deserializing, mark
8949 // it as "still needs to be completed".
8950 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8951 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8953 PendingIncompleteDeclChains.clear();
8955 // Load pending declaration chains.
8956 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
8957 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
8958 PendingDeclChains.clear();
8960 // Make the most recent of the top-level declarations visible.
8961 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8962 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
8963 IdentifierInfo *II = TLD->first;
8964 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
8965 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
8969 // Load any pending macro definitions.
8970 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
8971 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8972 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8973 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8974 // Initialize the macro history from chained-PCHs ahead of module imports.
8975 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8977 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8978 if (!Info.M->isModule())
8979 resolvePendingMacro(II, Info);
8981 // Handle module imports.
8982 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8984 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8985 if (Info.M->isModule())
8986 resolvePendingMacro(II, Info);
8989 PendingMacroIDs.clear();
8991 // Wire up the DeclContexts for Decls that we delayed setting until
8992 // recursive loading is completed.
8993 while (!PendingDeclContextInfos.empty()) {
8994 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8995 PendingDeclContextInfos.pop_front();
8996 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8997 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8998 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9001 // Perform any pending declaration updates.
9002 while (!PendingUpdateRecords.empty()) {
9003 auto Update = PendingUpdateRecords.pop_back_val();
9004 ReadingKindTracker ReadingKind(Read_Decl, *this);
9005 loadDeclUpdateRecords(Update);
9009 // At this point, all update records for loaded decls are in place, so any
9010 // fake class definitions should have become real.
9011 assert(PendingFakeDefinitionData.empty() &&
9012 "faked up a class definition but never saw the real one");
9014 // If we deserialized any C++ or Objective-C class definitions, any
9015 // Objective-C protocol definitions, or any redeclarable templates, make sure
9016 // that all redeclarations point to the definitions. Note that this can only
9017 // happen now, after the redeclaration chains have been fully wired.
9018 for (Decl *D : PendingDefinitions) {
9019 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9020 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
9021 // Make sure that the TagType points at the definition.
9022 const_cast<TagType*>(TagT)->decl = TD;
9025 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
9026 for (auto *R = getMostRecentExistingDecl(RD); R;
9027 R = R->getPreviousDecl()) {
9029 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
9030 "declaration thinks it's the definition but it isn't");
9031 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
9038 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
9039 // Make sure that the ObjCInterfaceType points at the definition.
9040 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9043 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9044 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9049 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
9050 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9051 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9056 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9057 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9058 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9060 PendingDefinitions.clear();
9062 // Load the bodies of any functions or methods we've encountered. We do
9063 // this now (delayed) so that we can be sure that the declaration chains
9064 // have been fully wired up (hasBody relies on this).
9065 // FIXME: We shouldn't require complete redeclaration chains here.
9066 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9067 PBEnd = PendingBodies.end();
9068 PB != PBEnd; ++PB) {
9069 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9070 // FIXME: Check for =delete/=default?
9071 // FIXME: Complain about ODR violations here?
9072 const FunctionDecl *Defn = nullptr;
9073 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9074 FD->setLazyBody(PB->second);
9076 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
9080 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9081 if (!getContext().getLangOpts().Modules || !MD->hasBody())
9082 MD->setLazyBody(PB->second);
9084 PendingBodies.clear();
9087 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9088 getContext().deduplicateMergedDefinitonsFor(ND);
9089 PendingMergedDefinitionsToDeduplicate.clear();
9092 void ASTReader::diagnoseOdrViolations() {
9093 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
9096 // Trigger the import of the full definition of each class that had any
9097 // odr-merging problems, so we can produce better diagnostics for them.
9098 // These updates may in turn find and diagnose some ODR failures, so take
9099 // ownership of the set first.
9100 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9101 PendingOdrMergeFailures.clear();
9102 for (auto &Merge : OdrMergeFailures) {
9103 Merge.first->buildLookup();
9104 Merge.first->decls_begin();
9105 Merge.first->bases_begin();
9106 Merge.first->vbases_begin();
9107 for (auto *RD : Merge.second) {
9114 // For each declaration from a merged context, check that the canonical
9115 // definition of that context also contains a declaration of the same
9118 // Caution: this loop does things that might invalidate iterators into
9119 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9120 while (!PendingOdrMergeChecks.empty()) {
9121 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9123 // FIXME: Skip over implicit declarations for now. This matters for things
9124 // like implicitly-declared special member functions. This isn't entirely
9125 // correct; we can end up with multiple unmerged declarations of the same
9127 if (D->isImplicit())
9130 DeclContext *CanonDef = D->getDeclContext();
9133 const Decl *DCanon = D->getCanonicalDecl();
9135 for (auto RI : D->redecls()) {
9136 if (RI->getLexicalDeclContext() == CanonDef) {
9144 // Quick check failed, time to do the slow thing. Note, we can't just
9145 // look up the name of D in CanonDef here, because the member that is
9146 // in CanonDef might not be found by name lookup (it might have been
9147 // replaced by a more recent declaration in the lookup table), and we
9148 // can't necessarily find it in the redeclaration chain because it might
9149 // be merely mergeable, not redeclarable.
9150 llvm::SmallVector<const NamedDecl*, 4> Candidates;
9151 for (auto *CanonMember : CanonDef->decls()) {
9152 if (CanonMember->getCanonicalDecl() == DCanon) {
9153 // This can happen if the declaration is merely mergeable and not
9154 // actually redeclarable (we looked for redeclarations earlier).
9156 // FIXME: We should be able to detect this more efficiently, without
9157 // pulling in all of the members of CanonDef.
9161 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9162 if (ND->getDeclName() == D->getDeclName())
9163 Candidates.push_back(ND);
9167 // The AST doesn't like TagDecls becoming invalid after they've been
9168 // completed. We only really need to mark FieldDecls as invalid here.
9169 if (!isa<TagDecl>(D))
9170 D->setInvalidDecl();
9172 // Ensure we don't accidentally recursively enter deserialization while
9173 // we're producing our diagnostic.
9174 Deserializing RecursionGuard(this);
9176 std::string CanonDefModule =
9177 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9178 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9179 << D << getOwningModuleNameForDiagnostic(D)
9180 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9182 if (Candidates.empty())
9183 Diag(cast<Decl>(CanonDef)->getLocation(),
9184 diag::note_module_odr_violation_no_possible_decls) << D;
9186 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9187 Diag(Candidates[I]->getLocation(),
9188 diag::note_module_odr_violation_possible_decl)
9192 DiagnosedOdrMergeFailures.insert(CanonDef);
9196 if (OdrMergeFailures.empty())
9199 // Ensure we don't accidentally recursively enter deserialization while
9200 // we're producing our diagnostics.
9201 Deserializing RecursionGuard(this);
9203 // Issue any pending ODR-failure diagnostics.
9204 for (auto &Merge : OdrMergeFailures) {
9205 // If we've already pointed out a specific problem with this class, don't
9206 // bother issuing a general "something's different" diagnostic.
9207 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9210 bool Diagnosed = false;
9211 CXXRecordDecl *FirstRecord = Merge.first;
9212 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
9213 for (CXXRecordDecl *SecondRecord : Merge.second) {
9214 // Multiple different declarations got merged together; tell the user
9215 // where they came from.
9216 if (FirstRecord == SecondRecord)
9219 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
9220 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
9221 DeclHashes FirstHashes;
9222 DeclHashes SecondHashes;
9225 auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes,
9226 CXXRecordDecl *Record) {
9227 for (auto *D : Record->decls()) {
9228 // Due to decl merging, the first CXXRecordDecl is the parent of
9229 // Decls in both records.
9230 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9234 Hashes.emplace_back(D, Hash.CalculateHash());
9237 PopulateHashes(FirstHashes, FirstRecord);
9238 PopulateHashes(SecondHashes, SecondRecord);
9240 // Used with err_module_odr_violation_mismatch_decl and
9241 // note_module_odr_violation_mismatch_decl
9251 } FirstDiffType = Other,
9252 SecondDiffType = Other;
9254 auto DifferenceSelector = [](Decl *D) {
9255 assert(D && "valid Decl required");
9256 switch (D->getKind()) {
9259 case Decl::AccessSpec:
9260 switch (D->getAccess()) {
9262 return PublicSpecifer;
9264 return PrivateSpecifer;
9266 return ProtectedSpecifer;
9270 llvm_unreachable("Invalid access specifier");
9271 case Decl::StaticAssert:
9272 return StaticAssert;
9275 case Decl::CXXMethod:
9280 Decl *FirstDecl = nullptr;
9281 Decl *SecondDecl = nullptr;
9282 auto FirstIt = FirstHashes.begin();
9283 auto SecondIt = SecondHashes.begin();
9285 // If there is a diagnoseable difference, FirstDiffType and
9286 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9287 // filled in if not EndOfClass.
9288 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
9289 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9290 FirstIt->second == SecondIt->second) {
9296 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9297 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9299 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9301 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9306 if (FirstDiffType == Other || SecondDiffType == Other) {
9307 // Reaching this point means an unexpected Decl was encountered
9308 // or no difference was detected. This causes a generic error
9309 // message to be emitted.
9310 Diag(FirstRecord->getLocation(),
9311 diag::err_module_odr_violation_different_definitions)
9312 << FirstRecord << FirstModule.empty() << FirstModule;
9314 Diag(SecondRecord->getLocation(),
9315 diag::note_module_odr_violation_different_definitions)
9321 if (FirstDiffType != SecondDiffType) {
9322 SourceLocation FirstLoc;
9323 SourceRange FirstRange;
9324 if (FirstDiffType == EndOfClass) {
9325 FirstLoc = FirstRecord->getBraceRange().getEnd();
9327 FirstLoc = FirstIt->first->getLocation();
9328 FirstRange = FirstIt->first->getSourceRange();
9330 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9331 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9334 SourceLocation SecondLoc;
9335 SourceRange SecondRange;
9336 if (SecondDiffType == EndOfClass) {
9337 SecondLoc = SecondRecord->getBraceRange().getEnd();
9339 SecondLoc = SecondDecl->getLocation();
9340 SecondRange = SecondDecl->getSourceRange();
9342 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9343 << SecondModule << SecondRange << SecondDiffType;
9348 assert(FirstDiffType == SecondDiffType);
9350 // Used with err_module_odr_violation_mismatch_decl_diff and
9351 // note_module_odr_violation_mismatch_decl_diff
9352 enum ODRDeclDifference{
9353 StaticAssertCondition,
9354 StaticAssertMessage,
9355 StaticAssertOnlyMessage,
9358 FieldSingleBitField,
9359 FieldDifferentWidthBitField,
9361 FieldSingleInitializer,
9362 FieldDifferentInitializers,
9370 MethodNumberParameters,
9371 MethodParameterType,
9372 MethodParameterName,
9375 // These lambdas have the common portions of the ODR diagnostics. This
9376 // has the same return as Diag(), so addition parameters can be passed
9377 // in with operator<<
9378 auto ODRDiagError = [FirstRecord, &FirstModule, this](
9379 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9380 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9381 << FirstRecord << FirstModule.empty() << FirstModule << Range
9384 auto ODRDiagNote = [&SecondModule, this](
9385 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9386 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9387 << SecondModule << Range << DiffType;
9390 auto ComputeODRHash = [&Hash](const Stmt* S) {
9394 return Hash.CalculateHash();
9397 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9399 Hash.AddQualType(Ty);
9400 return Hash.CalculateHash();
9403 switch (FirstDiffType) {
9406 case PublicSpecifer:
9407 case PrivateSpecifer:
9408 case ProtectedSpecifer:
9409 llvm_unreachable("Invalid diff type");
9411 case StaticAssert: {
9412 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9413 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
9415 Expr *FirstExpr = FirstSA->getAssertExpr();
9416 Expr *SecondExpr = SecondSA->getAssertExpr();
9417 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9418 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
9419 if (FirstODRHash != SecondODRHash) {
9420 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
9421 StaticAssertCondition);
9422 ODRDiagNote(SecondExpr->getLocStart(),
9423 SecondExpr->getSourceRange(), StaticAssertCondition);
9428 StringLiteral *FirstStr = FirstSA->getMessage();
9429 StringLiteral *SecondStr = SecondSA->getMessage();
9430 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
9431 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
9432 SourceLocation FirstLoc, SecondLoc;
9433 SourceRange FirstRange, SecondRange;
9435 FirstLoc = FirstStr->getLocStart();
9436 FirstRange = FirstStr->getSourceRange();
9438 FirstLoc = FirstSA->getLocStart();
9439 FirstRange = FirstSA->getSourceRange();
9442 SecondLoc = SecondStr->getLocStart();
9443 SecondRange = SecondStr->getSourceRange();
9445 SecondLoc = SecondSA->getLocStart();
9446 SecondRange = SecondSA->getSourceRange();
9448 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
9449 << (FirstStr == nullptr);
9450 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
9451 << (SecondStr == nullptr);
9456 if (FirstStr && SecondStr &&
9457 FirstStr->getString() != SecondStr->getString()) {
9458 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
9459 StaticAssertMessage);
9460 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
9461 StaticAssertMessage);
9468 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
9469 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
9470 IdentifierInfo *FirstII = FirstField->getIdentifier();
9471 IdentifierInfo *SecondII = SecondField->getIdentifier();
9472 if (FirstII->getName() != SecondII->getName()) {
9473 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9476 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9485 Context.hasSameType(FirstField->getType(), SecondField->getType()));
9487 QualType FirstType = FirstField->getType();
9488 QualType SecondType = SecondField->getType();
9489 if (ComputeQualTypeODRHash(FirstType) !=
9490 ComputeQualTypeODRHash(SecondType)) {
9491 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9493 << FirstII << FirstType;
9494 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9496 << SecondII << SecondType;
9502 const bool IsFirstBitField = FirstField->isBitField();
9503 const bool IsSecondBitField = SecondField->isBitField();
9504 if (IsFirstBitField != IsSecondBitField) {
9505 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9506 FieldSingleBitField)
9507 << FirstII << IsFirstBitField;
9508 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9509 FieldSingleBitField)
9510 << SecondII << IsSecondBitField;
9515 if (IsFirstBitField && IsSecondBitField) {
9516 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9517 FieldDifferentWidthBitField)
9518 << FirstII << FirstField->getBitWidth()->getSourceRange();
9519 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9520 FieldDifferentWidthBitField)
9521 << SecondII << SecondField->getBitWidth()->getSourceRange();
9526 const bool IsFirstMutable = FirstField->isMutable();
9527 const bool IsSecondMutable = SecondField->isMutable();
9528 if (IsFirstMutable != IsSecondMutable) {
9529 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9531 << FirstII << IsFirstMutable;
9532 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9534 << SecondII << IsSecondMutable;
9539 const Expr *FirstInitializer = FirstField->getInClassInitializer();
9540 const Expr *SecondInitializer = SecondField->getInClassInitializer();
9541 if ((!FirstInitializer && SecondInitializer) ||
9542 (FirstInitializer && !SecondInitializer)) {
9543 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9544 FieldSingleInitializer)
9545 << FirstII << (FirstInitializer != nullptr);
9546 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9547 FieldSingleInitializer)
9548 << SecondII << (SecondInitializer != nullptr);
9553 if (FirstInitializer && SecondInitializer) {
9554 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
9555 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
9556 if (FirstInitHash != SecondInitHash) {
9557 ODRDiagError(FirstField->getLocation(),
9558 FirstField->getSourceRange(),
9559 FieldDifferentInitializers)
9560 << FirstII << FirstInitializer->getSourceRange();
9561 ODRDiagNote(SecondField->getLocation(),
9562 SecondField->getSourceRange(),
9563 FieldDifferentInitializers)
9564 << SecondII << SecondInitializer->getSourceRange();
9573 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
9574 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
9575 auto FirstName = FirstMethod->getDeclName();
9576 auto SecondName = SecondMethod->getDeclName();
9577 if (FirstName != SecondName) {
9578 ODRDiagError(FirstMethod->getLocation(),
9579 FirstMethod->getSourceRange(), MethodName)
9581 ODRDiagNote(SecondMethod->getLocation(),
9582 SecondMethod->getSourceRange(), MethodName)
9589 const bool FirstDeleted = FirstMethod->isDeleted();
9590 const bool SecondDeleted = SecondMethod->isDeleted();
9591 if (FirstDeleted != SecondDeleted) {
9592 ODRDiagError(FirstMethod->getLocation(),
9593 FirstMethod->getSourceRange(), MethodDeleted)
9594 << FirstName << FirstDeleted;
9596 ODRDiagNote(SecondMethod->getLocation(),
9597 SecondMethod->getSourceRange(), MethodDeleted)
9598 << SecondName << SecondDeleted;
9603 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
9604 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
9605 const bool FirstPure = FirstMethod->isPure();
9606 const bool SecondPure = SecondMethod->isPure();
9607 if ((FirstVirtual || SecondVirtual) &&
9608 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
9609 ODRDiagError(FirstMethod->getLocation(),
9610 FirstMethod->getSourceRange(), MethodVirtual)
9611 << FirstName << FirstPure << FirstVirtual;
9612 ODRDiagNote(SecondMethod->getLocation(),
9613 SecondMethod->getSourceRange(), MethodVirtual)
9614 << SecondName << SecondPure << SecondVirtual;
9619 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
9620 // FirstDecl is the canonical Decl of SecondDecl, so the storage
9621 // class needs to be checked instead.
9622 const auto FirstStorage = FirstMethod->getStorageClass();
9623 const auto SecondStorage = SecondMethod->getStorageClass();
9624 const bool FirstStatic = FirstStorage == SC_Static;
9625 const bool SecondStatic = SecondStorage == SC_Static;
9626 if (FirstStatic != SecondStatic) {
9627 ODRDiagError(FirstMethod->getLocation(),
9628 FirstMethod->getSourceRange(), MethodStatic)
9629 << FirstName << FirstStatic;
9630 ODRDiagNote(SecondMethod->getLocation(),
9631 SecondMethod->getSourceRange(), MethodStatic)
9632 << SecondName << SecondStatic;
9637 const bool FirstVolatile = FirstMethod->isVolatile();
9638 const bool SecondVolatile = SecondMethod->isVolatile();
9639 if (FirstVolatile != SecondVolatile) {
9640 ODRDiagError(FirstMethod->getLocation(),
9641 FirstMethod->getSourceRange(), MethodVolatile)
9642 << FirstName << FirstVolatile;
9643 ODRDiagNote(SecondMethod->getLocation(),
9644 SecondMethod->getSourceRange(), MethodVolatile)
9645 << SecondName << SecondVolatile;
9650 const bool FirstConst = FirstMethod->isConst();
9651 const bool SecondConst = SecondMethod->isConst();
9652 if (FirstConst != SecondConst) {
9653 ODRDiagError(FirstMethod->getLocation(),
9654 FirstMethod->getSourceRange(), MethodConst)
9655 << FirstName << FirstConst;
9656 ODRDiagNote(SecondMethod->getLocation(),
9657 SecondMethod->getSourceRange(), MethodConst)
9658 << SecondName << SecondConst;
9663 const bool FirstInline = FirstMethod->isInlineSpecified();
9664 const bool SecondInline = SecondMethod->isInlineSpecified();
9665 if (FirstInline != SecondInline) {
9666 ODRDiagError(FirstMethod->getLocation(),
9667 FirstMethod->getSourceRange(), MethodInline)
9668 << FirstName << FirstInline;
9669 ODRDiagNote(SecondMethod->getLocation(),
9670 SecondMethod->getSourceRange(), MethodInline)
9671 << SecondName << SecondInline;
9676 const unsigned FirstNumParameters = FirstMethod->param_size();
9677 const unsigned SecondNumParameters = SecondMethod->param_size();
9678 if (FirstNumParameters != SecondNumParameters) {
9679 ODRDiagError(FirstMethod->getLocation(),
9680 FirstMethod->getSourceRange(), MethodNumberParameters)
9681 << FirstName << FirstNumParameters;
9682 ODRDiagNote(SecondMethod->getLocation(),
9683 SecondMethod->getSourceRange(), MethodNumberParameters)
9684 << SecondName << SecondNumParameters;
9689 // Need this status boolean to know when break out of the switch.
9690 bool ParameterMismatch = false;
9691 for (unsigned I = 0; I < FirstNumParameters; ++I) {
9692 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
9693 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
9695 QualType FirstParamType = FirstParam->getType();
9696 QualType SecondParamType = SecondParam->getType();
9697 if (FirstParamType != SecondParamType &&
9698 ComputeQualTypeODRHash(FirstParamType) !=
9699 ComputeQualTypeODRHash(SecondParamType)) {
9700 if (const DecayedType *ParamDecayedType =
9701 FirstParamType->getAs<DecayedType>()) {
9702 ODRDiagError(FirstMethod->getLocation(),
9703 FirstMethod->getSourceRange(), MethodParameterType)
9704 << FirstName << (I + 1) << FirstParamType << true
9705 << ParamDecayedType->getOriginalType();
9707 ODRDiagError(FirstMethod->getLocation(),
9708 FirstMethod->getSourceRange(), MethodParameterType)
9709 << FirstName << (I + 1) << FirstParamType << false;
9712 if (const DecayedType *ParamDecayedType =
9713 SecondParamType->getAs<DecayedType>()) {
9714 ODRDiagNote(SecondMethod->getLocation(),
9715 SecondMethod->getSourceRange(), MethodParameterType)
9716 << SecondName << (I + 1) << SecondParamType << true
9717 << ParamDecayedType->getOriginalType();
9719 ODRDiagNote(SecondMethod->getLocation(),
9720 SecondMethod->getSourceRange(), MethodParameterType)
9721 << SecondName << (I + 1) << SecondParamType << false;
9723 ParameterMismatch = true;
9727 DeclarationName FirstParamName = FirstParam->getDeclName();
9728 DeclarationName SecondParamName = SecondParam->getDeclName();
9729 if (FirstParamName != SecondParamName) {
9730 ODRDiagError(FirstMethod->getLocation(),
9731 FirstMethod->getSourceRange(), MethodParameterName)
9732 << FirstName << (I + 1) << FirstParamName;
9733 ODRDiagNote(SecondMethod->getLocation(),
9734 SecondMethod->getSourceRange(), MethodParameterName)
9735 << SecondName << (I + 1) << SecondParamName;
9736 ParameterMismatch = true;
9741 if (ParameterMismatch) {
9750 if (Diagnosed == true)
9753 Diag(FirstRecord->getLocation(),
9754 diag::err_module_odr_violation_different_definitions)
9755 << FirstRecord << FirstModule.empty() << FirstModule;
9757 Diag(SecondRecord->getLocation(),
9758 diag::note_module_odr_violation_different_definitions)
9764 // All definitions are updates to the same declaration. This happens if a
9765 // module instantiates the declaration of a class template specialization
9766 // and two or more other modules instantiate its definition.
9768 // FIXME: Indicate which modules had instantiations of this definition.
9769 // FIXME: How can this even happen?
9770 Diag(Merge.first->getLocation(),
9771 diag::err_module_odr_violation_different_instantiations)
9777 void ASTReader::StartedDeserializing() {
9778 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
9779 ReadTimer->startTimer();
9782 void ASTReader::FinishedDeserializing() {
9783 assert(NumCurrentElementsDeserializing &&
9784 "FinishedDeserializing not paired with StartedDeserializing");
9785 if (NumCurrentElementsDeserializing == 1) {
9786 // We decrease NumCurrentElementsDeserializing only after pending actions
9787 // are finished, to avoid recursively re-calling finishPendingActions().
9788 finishPendingActions();
9790 --NumCurrentElementsDeserializing;
9792 if (NumCurrentElementsDeserializing == 0) {
9793 // Propagate exception specification updates along redeclaration chains.
9794 while (!PendingExceptionSpecUpdates.empty()) {
9795 auto Updates = std::move(PendingExceptionSpecUpdates);
9796 PendingExceptionSpecUpdates.clear();
9797 for (auto Update : Updates) {
9798 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
9799 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
9800 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
9801 if (auto *Listener = Context.getASTMutationListener())
9802 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
9803 for (auto *Redecl : Update.second->redecls())
9804 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
9809 ReadTimer->stopTimer();
9811 diagnoseOdrViolations();
9813 // We are not in recursive loading, so it's safe to pass the "interesting"
9814 // decls to the consumer.
9816 PassInterestingDeclsToConsumer();
9820 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
9821 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
9822 // Remove any fake results before adding any real ones.
9823 auto It = PendingFakeLookupResults.find(II);
9824 if (It != PendingFakeLookupResults.end()) {
9825 for (auto *ND : It->second)
9826 SemaObj->IdResolver.RemoveDecl(ND);
9827 // FIXME: this works around module+PCH performance issue.
9828 // Rather than erase the result from the map, which is O(n), just clear
9829 // the vector of NamedDecls.
9834 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
9835 SemaObj->TUScope->AddDecl(D);
9836 } else if (SemaObj->TUScope) {
9837 // Adding the decl to IdResolver may have failed because it was already in
9838 // (even though it was not added in scope). If it is already in, make sure
9839 // it gets in the scope as well.
9840 if (std::find(SemaObj->IdResolver.begin(Name),
9841 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
9842 SemaObj->TUScope->AddDecl(D);
9846 ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
9847 const PCHContainerReader &PCHContainerRdr,
9848 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
9849 StringRef isysroot, bool DisableValidation,
9850 bool AllowASTWithCompilerErrors,
9851 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
9852 bool UseGlobalIndex,
9853 std::unique_ptr<llvm::Timer> ReadTimer)
9854 : Listener(DisableValidation
9855 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
9856 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
9857 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
9858 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
9860 ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr),
9861 PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
9862 ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
9863 DisableValidation(DisableValidation),
9864 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
9865 AllowConfigurationMismatch(AllowConfigurationMismatch),
9866 ValidateSystemInputs(ValidateSystemInputs),
9867 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
9868 SourceMgr.setExternalSLocEntrySource(this);
9870 for (const auto &Ext : Extensions) {
9871 auto BlockName = Ext->getExtensionMetadata().BlockName;
9872 auto Known = ModuleFileExtensions.find(BlockName);
9873 if (Known != ModuleFileExtensions.end()) {
9874 Diags.Report(diag::warn_duplicate_module_file_extension)
9879 ModuleFileExtensions.insert({BlockName, Ext});
9883 ASTReader::~ASTReader() {
9884 if (OwnsDeserializationListener)
9885 delete DeserializationListener;
9888 IdentifierResolver &ASTReader::getIdResolver() {
9889 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
9892 unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
9893 unsigned AbbrevID) {
9896 return Cursor.readRecord(AbbrevID, Record);