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/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/Frontend/PCHContainerOperations.h"
23 #include "clang/AST/ASTMutationListener.h"
24 #include "clang/AST/NestedNameSpecifier.h"
25 #include "clang/AST/Type.h"
26 #include "clang/AST/TypeLocVisitor.h"
27 #include "clang/Basic/DiagnosticOptions.h"
28 #include "clang/Basic/FileManager.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/SourceManagerInternals.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Basic/TargetOptions.h"
33 #include "clang/Basic/Version.h"
34 #include "clang/Basic/VersionTuple.h"
35 #include "clang/Frontend/Utils.h"
36 #include "clang/Lex/HeaderSearch.h"
37 #include "clang/Lex/HeaderSearchOptions.h"
38 #include "clang/Lex/MacroInfo.h"
39 #include "clang/Lex/PreprocessingRecord.h"
40 #include "clang/Lex/Preprocessor.h"
41 #include "clang/Lex/PreprocessorOptions.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/Sema.h"
44 #include "clang/Serialization/ASTDeserializationListener.h"
45 #include "clang/Serialization/GlobalModuleIndex.h"
46 #include "clang/Serialization/ModuleManager.h"
47 #include "clang/Serialization/SerializationDiagnostic.h"
48 #include "llvm/ADT/Hashing.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/Bitcode/BitstreamReader.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/FileSystem.h"
53 #include "llvm/Support/MemoryBuffer.h"
54 #include "llvm/Support/Path.h"
55 #include "llvm/Support/SaveAndRestore.h"
56 #include "llvm/Support/raw_ostream.h"
60 #include <system_error>
62 using namespace clang;
63 using namespace clang::serialization;
64 using namespace clang::serialization::reader;
65 using llvm::BitstreamCursor;
68 //===----------------------------------------------------------------------===//
69 // ChainedASTReaderListener implementation
70 //===----------------------------------------------------------------------===//
73 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
74 return First->ReadFullVersionInformation(FullVersion) ||
75 Second->ReadFullVersionInformation(FullVersion);
77 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
78 First->ReadModuleName(ModuleName);
79 Second->ReadModuleName(ModuleName);
81 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
82 First->ReadModuleMapFile(ModuleMapPath);
83 Second->ReadModuleMapFile(ModuleMapPath);
86 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
88 bool AllowCompatibleDifferences) {
89 return First->ReadLanguageOptions(LangOpts, Complain,
90 AllowCompatibleDifferences) ||
91 Second->ReadLanguageOptions(LangOpts, Complain,
92 AllowCompatibleDifferences);
94 bool ChainedASTReaderListener::ReadTargetOptions(
95 const TargetOptions &TargetOpts, bool Complain,
96 bool AllowCompatibleDifferences) {
97 return First->ReadTargetOptions(TargetOpts, Complain,
98 AllowCompatibleDifferences) ||
99 Second->ReadTargetOptions(TargetOpts, Complain,
100 AllowCompatibleDifferences);
102 bool ChainedASTReaderListener::ReadDiagnosticOptions(
103 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
104 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
105 Second->ReadDiagnosticOptions(DiagOpts, Complain);
108 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
110 return First->ReadFileSystemOptions(FSOpts, Complain) ||
111 Second->ReadFileSystemOptions(FSOpts, Complain);
114 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
115 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
117 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
119 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
122 bool ChainedASTReaderListener::ReadPreprocessorOptions(
123 const PreprocessorOptions &PPOpts, bool Complain,
124 std::string &SuggestedPredefines) {
125 return First->ReadPreprocessorOptions(PPOpts, Complain,
126 SuggestedPredefines) ||
127 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
129 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
131 First->ReadCounter(M, Value);
132 Second->ReadCounter(M, Value);
134 bool ChainedASTReaderListener::needsInputFileVisitation() {
135 return First->needsInputFileVisitation() ||
136 Second->needsInputFileVisitation();
138 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
139 return First->needsSystemInputFileVisitation() ||
140 Second->needsSystemInputFileVisitation();
142 void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
144 First->visitModuleFile(Filename, Kind);
145 Second->visitModuleFile(Filename, Kind);
147 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
150 bool isExplicitModule) {
151 bool Continue = false;
152 if (First->needsInputFileVisitation() &&
153 (!isSystem || First->needsSystemInputFileVisitation()))
154 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
156 if (Second->needsInputFileVisitation() &&
157 (!isSystem || Second->needsSystemInputFileVisitation()))
158 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
163 void ChainedASTReaderListener::readModuleFileExtension(
164 const ModuleFileExtensionMetadata &Metadata) {
165 First->readModuleFileExtension(Metadata);
166 Second->readModuleFileExtension(Metadata);
169 //===----------------------------------------------------------------------===//
170 // PCH validator implementation
171 //===----------------------------------------------------------------------===//
173 ASTReaderListener::~ASTReaderListener() {}
175 /// \brief Compare the given set of language options against an existing set of
176 /// language options.
178 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
179 /// \param AllowCompatibleDifferences If true, differences between compatible
180 /// language options will be permitted.
182 /// \returns true if the languagae options mis-match, false otherwise.
183 static bool checkLanguageOptions(const LangOptions &LangOpts,
184 const LangOptions &ExistingLangOpts,
185 DiagnosticsEngine *Diags,
186 bool AllowCompatibleDifferences = true) {
187 #define LANGOPT(Name, Bits, Default, Description) \
188 if (ExistingLangOpts.Name != LangOpts.Name) { \
190 Diags->Report(diag::err_pch_langopt_mismatch) \
191 << Description << LangOpts.Name << ExistingLangOpts.Name; \
195 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
196 if (ExistingLangOpts.Name != LangOpts.Name) { \
198 Diags->Report(diag::err_pch_langopt_value_mismatch) \
203 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
204 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
206 Diags->Report(diag::err_pch_langopt_value_mismatch) \
211 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
212 if (!AllowCompatibleDifferences) \
213 LANGOPT(Name, Bits, Default, Description)
215 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
216 if (!AllowCompatibleDifferences) \
217 ENUM_LANGOPT(Name, Bits, Default, Description)
219 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
220 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
221 #include "clang/Basic/LangOptions.def"
223 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
225 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
229 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
231 Diags->Report(diag::err_pch_langopt_value_mismatch)
232 << "target Objective-C runtime";
236 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
237 LangOpts.CommentOpts.BlockCommandNames) {
239 Diags->Report(diag::err_pch_langopt_value_mismatch)
240 << "block command names";
247 /// \brief Compare the given set of target options against an existing set of
250 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
252 /// \returns true if the target options mis-match, false otherwise.
253 static bool checkTargetOptions(const TargetOptions &TargetOpts,
254 const TargetOptions &ExistingTargetOpts,
255 DiagnosticsEngine *Diags,
256 bool AllowCompatibleDifferences = true) {
257 #define CHECK_TARGET_OPT(Field, Name) \
258 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
260 Diags->Report(diag::err_pch_targetopt_mismatch) \
261 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
265 // The triple and ABI must match exactly.
266 CHECK_TARGET_OPT(Triple, "target");
267 CHECK_TARGET_OPT(ABI, "target ABI");
269 // We can tolerate different CPUs in many cases, notably when one CPU
270 // supports a strict superset of another. When allowing compatible
271 // differences skip this check.
272 if (!AllowCompatibleDifferences)
273 CHECK_TARGET_OPT(CPU, "target CPU");
275 #undef CHECK_TARGET_OPT
277 // Compare feature sets.
278 SmallVector<StringRef, 4> ExistingFeatures(
279 ExistingTargetOpts.FeaturesAsWritten.begin(),
280 ExistingTargetOpts.FeaturesAsWritten.end());
281 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
282 TargetOpts.FeaturesAsWritten.end());
283 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
284 std::sort(ReadFeatures.begin(), ReadFeatures.end());
286 // We compute the set difference in both directions explicitly so that we can
287 // diagnose the differences differently.
288 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
290 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
291 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
292 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
293 ExistingFeatures.begin(), ExistingFeatures.end(),
294 std::back_inserter(UnmatchedReadFeatures));
296 // If we are allowing compatible differences and the read feature set is
297 // a strict subset of the existing feature set, there is nothing to diagnose.
298 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
302 for (StringRef Feature : UnmatchedReadFeatures)
303 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
304 << /* is-existing-feature */ false << Feature;
305 for (StringRef Feature : UnmatchedExistingFeatures)
306 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
307 << /* is-existing-feature */ true << Feature;
310 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
314 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
316 bool AllowCompatibleDifferences) {
317 const LangOptions &ExistingLangOpts = PP.getLangOpts();
318 return checkLanguageOptions(LangOpts, ExistingLangOpts,
319 Complain ? &Reader.Diags : nullptr,
320 AllowCompatibleDifferences);
323 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
325 bool AllowCompatibleDifferences) {
326 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
327 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
328 Complain ? &Reader.Diags : nullptr,
329 AllowCompatibleDifferences);
333 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
335 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
339 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
340 DiagnosticsEngine &Diags,
342 typedef DiagnosticsEngine::Level Level;
344 // Check current mappings for new -Werror mappings, and the stored mappings
345 // for cases that were explicitly mapped to *not* be errors that are now
346 // errors because of options like -Werror.
347 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
349 for (DiagnosticsEngine *MappingSource : MappingSources) {
350 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
351 diag::kind DiagID = DiagIDMappingPair.first;
352 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
353 if (CurLevel < DiagnosticsEngine::Error)
354 continue; // not significant
356 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
357 if (StoredLevel < DiagnosticsEngine::Error) {
359 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
360 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
369 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
370 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
371 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
373 return Ext >= diag::Severity::Error;
376 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
377 DiagnosticsEngine &Diags,
378 bool IsSystem, bool Complain) {
381 if (Diags.getSuppressSystemWarnings())
383 // If -Wsystem-headers was not enabled before, be conservative
384 if (StoredDiags.getSuppressSystemWarnings()) {
386 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
391 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
393 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
397 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
398 !StoredDiags.getEnableAllWarnings()) {
400 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
404 if (isExtHandlingFromDiagsError(Diags) &&
405 !isExtHandlingFromDiagsError(StoredDiags)) {
407 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
411 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
414 bool PCHValidator::ReadDiagnosticOptions(
415 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
416 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
417 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
418 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
419 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
420 // This should never fail, because we would have processed these options
421 // before writing them to an ASTFile.
422 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
424 ModuleManager &ModuleMgr = Reader.getModuleManager();
425 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
427 // If the original import came from a file explicitly generated by the user,
428 // don't check the diagnostic mappings.
429 // FIXME: currently this is approximated by checking whether this is not a
430 // module import of an implicitly-loaded module file.
431 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
432 // the transitive closure of its imports, since unrelated modules cannot be
433 // imported until after this module finishes validation.
434 ModuleFile *TopImport = *ModuleMgr.rbegin();
435 while (!TopImport->ImportedBy.empty())
436 TopImport = TopImport->ImportedBy[0];
437 if (TopImport->Kind != MK_ImplicitModule)
440 StringRef ModuleName = TopImport->ModuleName;
441 assert(!ModuleName.empty() && "diagnostic options read before module name");
443 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
444 assert(M && "missing module");
446 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
447 // contains the union of their flags.
448 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
451 /// \brief Collect the macro definitions provided by the given preprocessor
454 collectMacroDefinitions(const PreprocessorOptions &PPOpts,
455 MacroDefinitionsMap &Macros,
456 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
457 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
458 StringRef Macro = PPOpts.Macros[I].first;
459 bool IsUndef = PPOpts.Macros[I].second;
461 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
462 StringRef MacroName = MacroPair.first;
463 StringRef MacroBody = MacroPair.second;
465 // For an #undef'd macro, we only care about the name.
467 if (MacroNames && !Macros.count(MacroName))
468 MacroNames->push_back(MacroName);
470 Macros[MacroName] = std::make_pair("", true);
474 // For a #define'd macro, figure out the actual definition.
475 if (MacroName.size() == Macro.size())
478 // Note: GCC drops anything following an end-of-line character.
479 StringRef::size_type End = MacroBody.find_first_of("\n\r");
480 MacroBody = MacroBody.substr(0, End);
483 if (MacroNames && !Macros.count(MacroName))
484 MacroNames->push_back(MacroName);
485 Macros[MacroName] = std::make_pair(MacroBody, false);
489 /// \brief Check the preprocessor options deserialized from the control block
490 /// against the preprocessor options in an existing preprocessor.
492 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
493 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
494 const PreprocessorOptions &ExistingPPOpts,
495 DiagnosticsEngine *Diags,
496 FileManager &FileMgr,
497 std::string &SuggestedPredefines,
498 const LangOptions &LangOpts) {
499 // Check macro definitions.
500 MacroDefinitionsMap ASTFileMacros;
501 collectMacroDefinitions(PPOpts, ASTFileMacros);
502 MacroDefinitionsMap ExistingMacros;
503 SmallVector<StringRef, 4> ExistingMacroNames;
504 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
506 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
507 // Dig out the macro definition in the existing preprocessor options.
508 StringRef MacroName = ExistingMacroNames[I];
509 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
511 // Check whether we know anything about this macro name or not.
512 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
513 = ASTFileMacros.find(MacroName);
514 if (Known == ASTFileMacros.end()) {
515 // FIXME: Check whether this identifier was referenced anywhere in the
516 // AST file. If so, we should reject the AST file. Unfortunately, this
517 // information isn't in the control block. What shall we do about it?
519 if (Existing.second) {
520 SuggestedPredefines += "#undef ";
521 SuggestedPredefines += MacroName.str();
522 SuggestedPredefines += '\n';
524 SuggestedPredefines += "#define ";
525 SuggestedPredefines += MacroName.str();
526 SuggestedPredefines += ' ';
527 SuggestedPredefines += Existing.first.str();
528 SuggestedPredefines += '\n';
533 // If the macro was defined in one but undef'd in the other, we have a
535 if (Existing.second != Known->second.second) {
537 Diags->Report(diag::err_pch_macro_def_undef)
538 << MacroName << Known->second.second;
543 // If the macro was #undef'd in both, or if the macro bodies are identical,
545 if (Existing.second || Existing.first == Known->second.first)
548 // The macro bodies differ; complain.
550 Diags->Report(diag::err_pch_macro_def_conflict)
551 << MacroName << Known->second.first << Existing.first;
556 // Check whether we're using predefines.
557 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
559 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
564 // Detailed record is important since it is used for the module cache hash.
565 if (LangOpts.Modules &&
566 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
568 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
573 // Compute the #include and #include_macros lines we need.
574 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
575 StringRef File = ExistingPPOpts.Includes[I];
576 if (File == ExistingPPOpts.ImplicitPCHInclude)
579 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
580 != PPOpts.Includes.end())
583 SuggestedPredefines += "#include \"";
584 SuggestedPredefines += File;
585 SuggestedPredefines += "\"\n";
588 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
589 StringRef File = ExistingPPOpts.MacroIncludes[I];
590 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
592 != PPOpts.MacroIncludes.end())
595 SuggestedPredefines += "#__include_macros \"";
596 SuggestedPredefines += File;
597 SuggestedPredefines += "\"\n##\n";
603 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
605 std::string &SuggestedPredefines) {
606 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
608 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
609 Complain? &Reader.Diags : nullptr,
615 /// Check the header search options deserialized from the control block
616 /// against the header search options in an existing preprocessor.
618 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
619 static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
620 StringRef SpecificModuleCachePath,
621 StringRef ExistingModuleCachePath,
622 DiagnosticsEngine *Diags,
623 const LangOptions &LangOpts) {
624 if (LangOpts.Modules) {
625 if (SpecificModuleCachePath != ExistingModuleCachePath) {
627 Diags->Report(diag::err_pch_modulecache_mismatch)
628 << SpecificModuleCachePath << ExistingModuleCachePath;
636 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
637 StringRef SpecificModuleCachePath,
639 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
640 PP.getHeaderSearchInfo().getModuleCachePath(),
641 Complain ? &Reader.Diags : nullptr,
645 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
646 PP.setCounterValue(Value);
649 //===----------------------------------------------------------------------===//
650 // AST reader implementation
651 //===----------------------------------------------------------------------===//
653 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
654 bool TakeOwnership) {
655 DeserializationListener = Listener;
656 OwnsDeserializationListener = TakeOwnership;
661 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
662 return serialization::ComputeHash(Sel);
666 std::pair<unsigned, unsigned>
667 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
668 using namespace llvm::support;
669 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
670 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
671 return std::make_pair(KeyLen, DataLen);
674 ASTSelectorLookupTrait::internal_key_type
675 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
676 using namespace llvm::support;
677 SelectorTable &SelTable = Reader.getContext().Selectors;
678 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
679 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
680 F, endian::readNext<uint32_t, little, unaligned>(d));
682 return SelTable.getNullarySelector(FirstII);
684 return SelTable.getUnarySelector(FirstII);
686 SmallVector<IdentifierInfo *, 16> Args;
687 Args.push_back(FirstII);
688 for (unsigned I = 1; I != N; ++I)
689 Args.push_back(Reader.getLocalIdentifier(
690 F, endian::readNext<uint32_t, little, unaligned>(d)));
692 return SelTable.getSelector(N, Args.data());
695 ASTSelectorLookupTrait::data_type
696 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
698 using namespace llvm::support;
702 Result.ID = Reader.getGlobalSelectorID(
703 F, endian::readNext<uint32_t, little, unaligned>(d));
704 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
705 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
706 Result.InstanceBits = FullInstanceBits & 0x3;
707 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
708 Result.FactoryBits = FullFactoryBits & 0x3;
709 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
710 unsigned NumInstanceMethods = FullInstanceBits >> 3;
711 unsigned NumFactoryMethods = FullFactoryBits >> 3;
713 // Load instance methods
714 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
715 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
716 F, endian::readNext<uint32_t, little, unaligned>(d)))
717 Result.Instance.push_back(Method);
720 // Load factory methods
721 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
722 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
723 F, endian::readNext<uint32_t, little, unaligned>(d)))
724 Result.Factory.push_back(Method);
730 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
731 return llvm::HashString(a);
734 std::pair<unsigned, unsigned>
735 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
736 using namespace llvm::support;
737 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
738 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
739 return std::make_pair(KeyLen, DataLen);
742 ASTIdentifierLookupTraitBase::internal_key_type
743 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
744 assert(n >= 2 && d[n-1] == '\0');
745 return StringRef((const char*) d, n-1);
748 /// \brief Whether the given identifier is "interesting".
749 static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
751 return II.hadMacroDefinition() ||
753 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
754 II.hasRevertedTokenIDToIdentifier() ||
755 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
756 II.getFETokenInfo<void>());
759 static bool readBit(unsigned &Bits) {
760 bool Value = Bits & 0x1;
765 IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
766 using namespace llvm::support;
767 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
768 return Reader.getGlobalIdentifierID(F, RawID >> 1);
771 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
772 const unsigned char* d,
774 using namespace llvm::support;
775 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
776 bool IsInteresting = RawID & 0x01;
778 // Wipe out the "is interesting" bit.
781 // Build the IdentifierInfo and link the identifier ID with it.
782 IdentifierInfo *II = KnownII;
784 II = &Reader.getIdentifierTable().getOwn(k);
787 if (!II->isFromAST()) {
789 bool IsModule = Reader.PP.getCurrentModule() != nullptr;
790 if (isInterestingIdentifier(Reader, *II, IsModule))
791 II->setChangedSinceDeserialization();
793 Reader.markIdentifierUpToDate(II);
795 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
796 if (!IsInteresting) {
797 // For uninteresting identifiers, there's nothing else to do. Just notify
798 // the reader that we've finished loading this identifier.
799 Reader.SetIdentifierInfo(ID, II);
803 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
804 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
805 bool CPlusPlusOperatorKeyword = readBit(Bits);
806 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
807 bool HasRevertedBuiltin = readBit(Bits);
808 bool Poisoned = readBit(Bits);
809 bool ExtensionToken = readBit(Bits);
810 bool HadMacroDefinition = readBit(Bits);
812 assert(Bits == 0 && "Extra bits in the identifier?");
815 // Set or check the various bits in the IdentifierInfo structure.
816 // Token IDs are read-only.
817 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
818 II->revertTokenIDToIdentifier();
820 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
821 else if (HasRevertedBuiltin && II->getBuiltinID()) {
823 assert((II->hasRevertedBuiltin() ||
824 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
825 "Incorrect ObjC keyword or builtin ID");
827 assert(II->isExtensionToken() == ExtensionToken &&
828 "Incorrect extension token flag");
829 (void)ExtensionToken;
831 II->setIsPoisoned(true);
832 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
833 "Incorrect C++ operator keyword flag");
834 (void)CPlusPlusOperatorKeyword;
836 // If this identifier is a macro, deserialize the macro
838 if (HadMacroDefinition) {
839 uint32_t MacroDirectivesOffset =
840 endian::readNext<uint32_t, little, unaligned>(d);
843 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
846 Reader.SetIdentifierInfo(ID, II);
848 // Read all of the declarations visible at global scope with this
851 SmallVector<uint32_t, 4> DeclIDs;
852 for (; DataLen > 0; DataLen -= 4)
853 DeclIDs.push_back(Reader.getGlobalDeclID(
854 F, endian::readNext<uint32_t, little, unaligned>(d)));
855 Reader.SetGloballyVisibleDecls(II, DeclIDs);
861 DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
862 : Kind(Name.getNameKind()) {
864 case DeclarationName::Identifier:
865 Data = (uint64_t)Name.getAsIdentifierInfo();
867 case DeclarationName::ObjCZeroArgSelector:
868 case DeclarationName::ObjCOneArgSelector:
869 case DeclarationName::ObjCMultiArgSelector:
870 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
872 case DeclarationName::CXXOperatorName:
873 Data = Name.getCXXOverloadedOperator();
875 case DeclarationName::CXXLiteralOperatorName:
876 Data = (uint64_t)Name.getCXXLiteralIdentifier();
878 case DeclarationName::CXXConstructorName:
879 case DeclarationName::CXXDestructorName:
880 case DeclarationName::CXXConversionFunctionName:
881 case DeclarationName::CXXUsingDirective:
887 unsigned DeclarationNameKey::getHash() const {
888 llvm::FoldingSetNodeID ID;
892 case DeclarationName::Identifier:
893 case DeclarationName::CXXLiteralOperatorName:
894 ID.AddString(((IdentifierInfo*)Data)->getName());
896 case DeclarationName::ObjCZeroArgSelector:
897 case DeclarationName::ObjCOneArgSelector:
898 case DeclarationName::ObjCMultiArgSelector:
899 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
901 case DeclarationName::CXXOperatorName:
902 ID.AddInteger((OverloadedOperatorKind)Data);
904 case DeclarationName::CXXConstructorName:
905 case DeclarationName::CXXDestructorName:
906 case DeclarationName::CXXConversionFunctionName:
907 case DeclarationName::CXXUsingDirective:
911 return ID.ComputeHash();
915 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
916 using namespace llvm::support;
917 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
918 return Reader.getLocalModuleFile(F, ModuleFileID);
921 std::pair<unsigned, unsigned>
922 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
923 using namespace llvm::support;
924 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
925 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
926 return std::make_pair(KeyLen, DataLen);
929 ASTDeclContextNameLookupTrait::internal_key_type
930 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
931 using namespace llvm::support;
933 auto Kind = (DeclarationName::NameKind)*d++;
936 case DeclarationName::Identifier:
937 Data = (uint64_t)Reader.getLocalIdentifier(
938 F, endian::readNext<uint32_t, little, unaligned>(d));
940 case DeclarationName::ObjCZeroArgSelector:
941 case DeclarationName::ObjCOneArgSelector:
942 case DeclarationName::ObjCMultiArgSelector:
944 (uint64_t)Reader.getLocalSelector(
945 F, endian::readNext<uint32_t, little, unaligned>(
946 d)).getAsOpaquePtr();
948 case DeclarationName::CXXOperatorName:
949 Data = *d++; // OverloadedOperatorKind
951 case DeclarationName::CXXLiteralOperatorName:
952 Data = (uint64_t)Reader.getLocalIdentifier(
953 F, endian::readNext<uint32_t, little, unaligned>(d));
955 case DeclarationName::CXXConstructorName:
956 case DeclarationName::CXXDestructorName:
957 case DeclarationName::CXXConversionFunctionName:
958 case DeclarationName::CXXUsingDirective:
963 return DeclarationNameKey(Kind, Data);
966 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
967 const unsigned char *d,
969 data_type_builder &Val) {
970 using namespace llvm::support;
971 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
972 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
973 Val.insert(Reader.getGlobalDeclID(F, LocalID));
977 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
978 BitstreamCursor &Cursor,
983 SavedStreamPosition SavedPosition(Cursor);
984 Cursor.JumpToBit(Offset);
988 unsigned Code = Cursor.ReadCode();
989 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
990 if (RecCode != DECL_CONTEXT_LEXICAL) {
991 Error("Expected lexical block");
995 assert(!isa<TranslationUnitDecl>(DC) &&
996 "expected a TU_UPDATE_LEXICAL record for TU");
997 // If we are handling a C++ class template instantiation, we can see multiple
998 // lexical updates for the same record. It's important that we select only one
999 // of them, so that field numbering works properly. Just pick the first one we
1001 auto &Lex = LexicalDecls[DC];
1003 Lex = std::make_pair(
1004 &M, llvm::makeArrayRef(
1005 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1009 DC->setHasExternalLexicalStorage(true);
1013 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1014 BitstreamCursor &Cursor,
1017 assert(Offset != 0);
1019 SavedStreamPosition SavedPosition(Cursor);
1020 Cursor.JumpToBit(Offset);
1024 unsigned Code = Cursor.ReadCode();
1025 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1026 if (RecCode != DECL_CONTEXT_VISIBLE) {
1027 Error("Expected visible lookup table block");
1031 // We can't safely determine the primary context yet, so delay attaching the
1032 // lookup table until we're done with recursive deserialization.
1033 auto *Data = (const unsigned char*)Blob.data();
1034 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1038 void ASTReader::Error(StringRef Msg) {
1039 Error(diag::err_fe_pch_malformed, Msg);
1040 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1041 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1042 Diag(diag::note_module_cache_path)
1043 << PP.getHeaderSearchInfo().getModuleCachePath();
1047 void ASTReader::Error(unsigned DiagID,
1048 StringRef Arg1, StringRef Arg2) {
1049 if (Diags.isDiagnosticInFlight())
1050 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1052 Diag(DiagID) << Arg1 << Arg2;
1055 //===----------------------------------------------------------------------===//
1056 // Source Manager Deserialization
1057 //===----------------------------------------------------------------------===//
1059 /// \brief Read the line table in the source manager block.
1060 /// \returns true if there was an error.
1061 bool ASTReader::ParseLineTable(ModuleFile &F,
1062 const RecordData &Record) {
1064 LineTableInfo &LineTable = SourceMgr.getLineTable();
1066 // Parse the file names
1067 std::map<int, int> FileIDs;
1068 for (unsigned I = 0; Record[Idx]; ++I) {
1069 // Extract the file name
1070 auto Filename = ReadPath(F, Record, Idx);
1071 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1075 // Parse the line entries
1076 std::vector<LineEntry> Entries;
1077 while (Idx < Record.size()) {
1078 int FID = Record[Idx++];
1079 assert(FID >= 0 && "Serialized line entries for non-local file.");
1080 // Remap FileID from 1-based old view.
1081 FID += F.SLocEntryBaseID - 1;
1083 // Extract the line entries
1084 unsigned NumEntries = Record[Idx++];
1085 assert(NumEntries && "no line entries for file ID");
1087 Entries.reserve(NumEntries);
1088 for (unsigned I = 0; I != NumEntries; ++I) {
1089 unsigned FileOffset = Record[Idx++];
1090 unsigned LineNo = Record[Idx++];
1091 int FilenameID = FileIDs[Record[Idx++]];
1092 SrcMgr::CharacteristicKind FileKind
1093 = (SrcMgr::CharacteristicKind)Record[Idx++];
1094 unsigned IncludeOffset = Record[Idx++];
1095 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1096 FileKind, IncludeOffset));
1098 LineTable.AddEntry(FileID::get(FID), Entries);
1104 /// \brief Read a source manager block
1105 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1106 using namespace SrcMgr;
1108 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1110 // Set the source-location entry cursor to the current position in
1111 // the stream. This cursor will be used to read the contents of the
1112 // source manager block initially, and then lazily read
1113 // source-location entries as needed.
1114 SLocEntryCursor = F.Stream;
1116 // The stream itself is going to skip over the source manager block.
1117 if (F.Stream.SkipBlock()) {
1118 Error("malformed block record in AST file");
1122 // Enter the source manager block.
1123 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1124 Error("malformed source manager block record in AST file");
1130 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1133 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1134 case llvm::BitstreamEntry::Error:
1135 Error("malformed block record in AST file");
1137 case llvm::BitstreamEntry::EndBlock:
1139 case llvm::BitstreamEntry::Record:
1140 // The interesting case.
1147 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
1148 default: // Default behavior: ignore.
1151 case SM_SLOC_FILE_ENTRY:
1152 case SM_SLOC_BUFFER_ENTRY:
1153 case SM_SLOC_EXPANSION_ENTRY:
1154 // Once we hit one of the source location entries, we're done.
1160 /// \brief If a header file is not found at the path that we expect it to be
1161 /// and the PCH file was moved from its original location, try to resolve the
1162 /// file by assuming that header+PCH were moved together and the header is in
1163 /// the same place relative to the PCH.
1165 resolveFileRelativeToOriginalDir(const std::string &Filename,
1166 const std::string &OriginalDir,
1167 const std::string &CurrDir) {
1168 assert(OriginalDir != CurrDir &&
1169 "No point trying to resolve the file if the PCH dir didn't change");
1170 using namespace llvm::sys;
1171 SmallString<128> filePath(Filename);
1172 fs::make_absolute(filePath);
1173 assert(path::is_absolute(OriginalDir));
1174 SmallString<128> currPCHPath(CurrDir);
1176 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1177 fileDirE = path::end(path::parent_path(filePath));
1178 path::const_iterator origDirI = path::begin(OriginalDir),
1179 origDirE = path::end(OriginalDir);
1180 // Skip the common path components from filePath and OriginalDir.
1181 while (fileDirI != fileDirE && origDirI != origDirE &&
1182 *fileDirI == *origDirI) {
1186 for (; origDirI != origDirE; ++origDirI)
1187 path::append(currPCHPath, "..");
1188 path::append(currPCHPath, fileDirI, fileDirE);
1189 path::append(currPCHPath, path::filename(Filename));
1190 return currPCHPath.str();
1193 bool ASTReader::ReadSLocEntry(int ID) {
1197 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1198 Error("source location entry ID out-of-range for AST file");
1202 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1203 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
1204 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1205 unsigned BaseOffset = F->SLocEntryBaseOffset;
1207 ++NumSLocEntriesRead;
1208 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1209 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1210 Error("incorrectly-formatted source location entry in AST file");
1216 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
1218 Error("incorrectly-formatted source location entry in AST file");
1221 case SM_SLOC_FILE_ENTRY: {
1222 // We will detect whether a file changed and return 'Failure' for it, but
1223 // we will also try to fail gracefully by setting up the SLocEntry.
1224 unsigned InputID = Record[4];
1225 InputFile IF = getInputFile(*F, InputID);
1226 const FileEntry *File = IF.getFile();
1227 bool OverriddenBuffer = IF.isOverridden();
1229 // Note that we only check if a File was returned. If it was out-of-date
1230 // we have complained but we will continue creating a FileID to recover
1235 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1236 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1237 // This is the module's main file.
1238 IncludeLoc = getImportLocation(F);
1240 SrcMgr::CharacteristicKind
1241 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1242 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1243 ID, BaseOffset + Record[0]);
1244 SrcMgr::FileInfo &FileInfo =
1245 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1246 FileInfo.NumCreatedFIDs = Record[5];
1248 FileInfo.setHasLineDirectives();
1250 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1251 unsigned NumFileDecls = Record[7];
1253 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1254 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1258 const SrcMgr::ContentCache *ContentCache
1259 = SourceMgr.getOrCreateContentCache(File,
1260 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1261 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1262 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1263 !ContentCache->getRawBuffer()) {
1264 unsigned Code = SLocEntryCursor.ReadCode();
1266 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1268 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1269 Error("AST record has invalid code");
1273 std::unique_ptr<llvm::MemoryBuffer> Buffer
1274 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
1275 SourceMgr.overrideFileContents(File, std::move(Buffer));
1281 case SM_SLOC_BUFFER_ENTRY: {
1282 const char *Name = Blob.data();
1283 unsigned Offset = Record[0];
1284 SrcMgr::CharacteristicKind
1285 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1286 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1287 if (IncludeLoc.isInvalid() &&
1288 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
1289 IncludeLoc = getImportLocation(F);
1291 unsigned Code = SLocEntryCursor.ReadCode();
1294 = SLocEntryCursor.readRecord(Code, Record, &Blob);
1296 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1297 Error("AST record has invalid code");
1301 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1302 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
1303 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1304 BaseOffset + Offset, IncludeLoc);
1308 case SM_SLOC_EXPANSION_ENTRY: {
1309 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1310 SourceMgr.createExpansionLoc(SpellingLoc,
1311 ReadSourceLocation(*F, Record[2]),
1312 ReadSourceLocation(*F, Record[3]),
1315 BaseOffset + Record[0]);
1323 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1325 return std::make_pair(SourceLocation(), "");
1327 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1328 Error("source location entry ID out-of-range for AST file");
1329 return std::make_pair(SourceLocation(), "");
1332 // Find which module file this entry lands in.
1333 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1334 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
1335 return std::make_pair(SourceLocation(), "");
1337 // FIXME: Can we map this down to a particular submodule? That would be
1339 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1342 /// \brief Find the location where the module F is imported.
1343 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1344 if (F->ImportLoc.isValid())
1345 return F->ImportLoc;
1347 // Otherwise we have a PCH. It's considered to be "imported" at the first
1348 // location of its includer.
1349 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1350 // Main file is the importer.
1351 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1352 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1354 return F->ImportedBy[0]->FirstLoc;
1357 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1358 /// specified cursor. Read the abbreviations that are at the top of the block
1359 /// and then leave the cursor pointing into the block.
1360 bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
1361 if (Cursor.EnterSubBlock(BlockID))
1365 uint64_t Offset = Cursor.GetCurrentBitNo();
1366 unsigned Code = Cursor.ReadCode();
1368 // We expect all abbrevs to be at the start of the block.
1369 if (Code != llvm::bitc::DEFINE_ABBREV) {
1370 Cursor.JumpToBit(Offset);
1373 Cursor.ReadAbbrevRecord();
1377 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1381 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1382 Tok.setLength(Record[Idx++]);
1383 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1384 Tok.setIdentifierInfo(II);
1385 Tok.setKind((tok::TokenKind)Record[Idx++]);
1386 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1390 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1391 BitstreamCursor &Stream = F.MacroCursor;
1393 // Keep track of where we are in the stream, then jump back there
1394 // after reading this macro.
1395 SavedStreamPosition SavedPosition(Stream);
1397 Stream.JumpToBit(Offset);
1399 SmallVector<IdentifierInfo*, 16> MacroArgs;
1400 MacroInfo *Macro = nullptr;
1403 // Advance to the next record, but if we get to the end of the block, don't
1404 // pop it (removing all the abbreviations from the cursor) since we want to
1405 // be able to reseek within the block and read entries.
1406 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1407 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1409 switch (Entry.Kind) {
1410 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1411 case llvm::BitstreamEntry::Error:
1412 Error("malformed block record in AST file");
1414 case llvm::BitstreamEntry::EndBlock:
1416 case llvm::BitstreamEntry::Record:
1417 // The interesting case.
1423 PreprocessorRecordTypes RecType =
1424 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
1426 case PP_MODULE_MACRO:
1427 case PP_MACRO_DIRECTIVE_HISTORY:
1430 case PP_MACRO_OBJECT_LIKE:
1431 case PP_MACRO_FUNCTION_LIKE: {
1432 // If we already have a macro, that means that we've hit the end
1433 // of the definition of the macro we were looking for. We're
1438 unsigned NextIndex = 1; // Skip identifier ID.
1439 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
1440 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1441 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
1442 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1443 MI->setIsUsed(Record[NextIndex++]);
1444 MI->setUsedForHeaderGuard(Record[NextIndex++]);
1446 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1447 // Decode function-like macro info.
1448 bool isC99VarArgs = Record[NextIndex++];
1449 bool isGNUVarArgs = Record[NextIndex++];
1450 bool hasCommaPasting = Record[NextIndex++];
1452 unsigned NumArgs = Record[NextIndex++];
1453 for (unsigned i = 0; i != NumArgs; ++i)
1454 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1456 // Install function-like macro info.
1457 MI->setIsFunctionLike();
1458 if (isC99VarArgs) MI->setIsC99Varargs();
1459 if (isGNUVarArgs) MI->setIsGNUVarargs();
1460 if (hasCommaPasting) MI->setHasCommaPasting();
1461 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
1464 // Remember that we saw this macro last so that we add the tokens that
1465 // form its body to it.
1468 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1469 Record[NextIndex]) {
1470 // We have a macro definition. Register the association
1471 PreprocessedEntityID
1472 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1473 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1474 PreprocessingRecord::PPEntityID PPID =
1475 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1476 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1477 PPRec.getPreprocessedEntity(PPID));
1479 PPRec.RegisterMacroDefinition(Macro, PPDef);
1487 // If we see a TOKEN before a PP_MACRO_*, then the file is
1488 // erroneous, just pretend we didn't see this.
1492 Token Tok = ReadToken(F, Record, Idx);
1493 Macro->AddTokenToBody(Tok);
1500 PreprocessedEntityID
1501 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1502 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1503 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1504 assert(I != M.PreprocessedEntityRemap.end()
1505 && "Invalid index into preprocessed entity index remap");
1507 return LocalID + I->second;
1510 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1511 return llvm::hash_combine(ikey.Size, ikey.ModTime);
1514 HeaderFileInfoTrait::internal_key_type
1515 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1516 internal_key_type ikey = {FE->getSize(),
1517 M.HasTimestamps ? FE->getModificationTime() : 0,
1518 FE->getName(), /*Imported*/ false};
1522 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1523 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
1526 if (llvm::sys::path::is_absolute(a.Filename) &&
1527 strcmp(a.Filename, b.Filename) == 0)
1530 // Determine whether the actual files are equivalent.
1531 FileManager &FileMgr = Reader.getFileManager();
1532 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1534 return FileMgr.getFile(Key.Filename);
1536 std::string Resolved = Key.Filename;
1537 Reader.ResolveImportedPath(M, Resolved);
1538 return FileMgr.getFile(Resolved);
1541 const FileEntry *FEA = GetFile(a);
1542 const FileEntry *FEB = GetFile(b);
1543 return FEA && FEA == FEB;
1546 std::pair<unsigned, unsigned>
1547 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1548 using namespace llvm::support;
1549 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1550 unsigned DataLen = (unsigned) *d++;
1551 return std::make_pair(KeyLen, DataLen);
1554 HeaderFileInfoTrait::internal_key_type
1555 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1556 using namespace llvm::support;
1557 internal_key_type ikey;
1558 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1559 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1560 ikey.Filename = (const char *)d;
1561 ikey.Imported = true;
1565 HeaderFileInfoTrait::data_type
1566 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1568 const unsigned char *End = d + DataLen;
1569 using namespace llvm::support;
1571 unsigned Flags = *d++;
1572 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1573 HFI.isImport |= (Flags >> 4) & 0x01;
1574 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1575 HFI.DirInfo = (Flags >> 1) & 0x03;
1576 HFI.IndexHeaderMapHeader = Flags & 0x01;
1577 // FIXME: Find a better way to handle this. Maybe just store a
1578 // "has been included" flag?
1579 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1581 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1582 M, endian::readNext<uint32_t, little, unaligned>(d));
1583 if (unsigned FrameworkOffset =
1584 endian::readNext<uint32_t, little, unaligned>(d)) {
1585 // The framework offset is 1 greater than the actual offset,
1586 // since 0 is used as an indicator for "no framework name".
1587 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1588 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1591 assert((End - d) % 4 == 0 &&
1592 "Wrong data length in HeaderFileInfo deserialization");
1594 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1595 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1598 // This header is part of a module. Associate it with the module to enable
1599 // implicit module import.
1600 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1601 Module *Mod = Reader.getSubmodule(GlobalSMID);
1602 FileManager &FileMgr = Reader.getFileManager();
1604 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1606 std::string Filename = key.Filename;
1608 Reader.ResolveImportedPath(M, Filename);
1609 // FIXME: This is not always the right filename-as-written, but we're not
1610 // going to use this information to rebuild the module, so it doesn't make
1611 // a lot of difference.
1612 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
1613 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1614 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
1617 // This HeaderFileInfo was externally loaded.
1618 HFI.External = true;
1623 void ASTReader::addPendingMacro(IdentifierInfo *II,
1625 uint64_t MacroDirectivesOffset) {
1626 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1627 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1630 void ASTReader::ReadDefinedMacros() {
1631 // Note that we are loading defined macros.
1632 Deserializing Macros(this);
1634 for (auto &I : llvm::reverse(ModuleMgr)) {
1635 BitstreamCursor &MacroCursor = I->MacroCursor;
1637 // If there was no preprocessor block, skip this file.
1638 if (!MacroCursor.getBitStreamReader())
1641 BitstreamCursor Cursor = MacroCursor;
1642 Cursor.JumpToBit(I->MacroStartOffset);
1646 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1649 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1650 case llvm::BitstreamEntry::Error:
1651 Error("malformed block record in AST file");
1653 case llvm::BitstreamEntry::EndBlock:
1656 case llvm::BitstreamEntry::Record:
1658 switch (Cursor.readRecord(E.ID, Record)) {
1659 default: // Default behavior: ignore.
1662 case PP_MACRO_OBJECT_LIKE:
1663 case PP_MACRO_FUNCTION_LIKE:
1664 getLocalIdentifier(*I, Record[0]);
1679 /// \brief Visitor class used to look up identifirs in an AST file.
1680 class IdentifierLookupVisitor {
1683 unsigned PriorGeneration;
1684 unsigned &NumIdentifierLookups;
1685 unsigned &NumIdentifierLookupHits;
1686 IdentifierInfo *Found;
1689 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1690 unsigned &NumIdentifierLookups,
1691 unsigned &NumIdentifierLookupHits)
1692 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1693 PriorGeneration(PriorGeneration),
1694 NumIdentifierLookups(NumIdentifierLookups),
1695 NumIdentifierLookupHits(NumIdentifierLookupHits),
1700 bool operator()(ModuleFile &M) {
1701 // If we've already searched this module file, skip it now.
1702 if (M.Generation <= PriorGeneration)
1705 ASTIdentifierLookupTable *IdTable
1706 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1710 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
1712 ++NumIdentifierLookups;
1713 ASTIdentifierLookupTable::iterator Pos =
1714 IdTable->find_hashed(Name, NameHash, &Trait);
1715 if (Pos == IdTable->end())
1718 // Dereferencing the iterator has the effect of building the
1719 // IdentifierInfo node and populating it with the various
1720 // declarations it needs.
1721 ++NumIdentifierLookupHits;
1726 // \brief Retrieve the identifier info found within the module
1728 IdentifierInfo *getIdentifierInfo() const { return Found; }
1732 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1733 // Note that we are loading an identifier.
1734 Deserializing AnIdentifier(this);
1736 unsigned PriorGeneration = 0;
1737 if (getContext().getLangOpts().Modules)
1738 PriorGeneration = IdentifierGeneration[&II];
1740 // If there is a global index, look there first to determine which modules
1741 // provably do not have any results for this identifier.
1742 GlobalModuleIndex::HitSet Hits;
1743 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
1744 if (!loadGlobalIndex()) {
1745 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1750 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
1751 NumIdentifierLookups,
1752 NumIdentifierLookupHits);
1753 ModuleMgr.visit(Visitor, HitsPtr);
1754 markIdentifierUpToDate(&II);
1757 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1761 II->setOutOfDate(false);
1763 // Update the generation for this identifier.
1764 if (getContext().getLangOpts().Modules)
1765 IdentifierGeneration[II] = getGeneration();
1768 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1769 const PendingMacroInfo &PMInfo) {
1770 ModuleFile &M = *PMInfo.M;
1772 BitstreamCursor &Cursor = M.MacroCursor;
1773 SavedStreamPosition SavedPosition(Cursor);
1774 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
1776 struct ModuleMacroRecord {
1777 SubmoduleID SubModID;
1779 SmallVector<SubmoduleID, 8> Overrides;
1781 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
1783 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1784 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1788 llvm::BitstreamEntry Entry =
1789 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1790 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1791 Error("malformed block record in AST file");
1796 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
1797 case PP_MACRO_DIRECTIVE_HISTORY:
1800 case PP_MODULE_MACRO: {
1801 ModuleMacros.push_back(ModuleMacroRecord());
1802 auto &Info = ModuleMacros.back();
1803 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1804 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
1805 for (int I = 2, N = Record.size(); I != N; ++I)
1806 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
1811 Error("malformed block record in AST file");
1815 // We found the macro directive history; that's the last record
1820 // Module macros are listed in reverse dependency order.
1822 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
1823 llvm::SmallVector<ModuleMacro*, 8> Overrides;
1824 for (auto &MMR : ModuleMacros) {
1826 for (unsigned ModID : MMR.Overrides) {
1827 Module *Mod = getSubmodule(ModID);
1828 auto *Macro = PP.getModuleMacro(Mod, II);
1829 assert(Macro && "missing definition for overridden macro");
1830 Overrides.push_back(Macro);
1833 bool Inserted = false;
1834 Module *Owner = getSubmodule(MMR.SubModID);
1835 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
1839 // Don't read the directive history for a module; we don't have anywhere
1841 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1844 // Deserialize the macro directives history in reverse source-order.
1845 MacroDirective *Latest = nullptr, *Earliest = nullptr;
1846 unsigned Idx = 0, N = Record.size();
1848 MacroDirective *MD = nullptr;
1849 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
1850 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1852 case MacroDirective::MD_Define: {
1853 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
1854 MD = PP.AllocateDefMacroDirective(MI, Loc);
1857 case MacroDirective::MD_Undefine: {
1858 MD = PP.AllocateUndefMacroDirective(Loc);
1861 case MacroDirective::MD_Visibility:
1862 bool isPublic = Record[Idx++];
1863 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1870 Earliest->setPrevious(MD);
1875 PP.setLoadedMacroDirective(II, Latest);
1878 ASTReader::InputFileInfo
1879 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
1880 // Go find this input file.
1881 BitstreamCursor &Cursor = F.InputFilesCursor;
1882 SavedStreamPosition SavedPosition(Cursor);
1883 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1885 unsigned Code = Cursor.ReadCode();
1889 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1890 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1891 "invalid record type for input file");
1894 assert(Record[0] == ID && "Bogus stored ID or offset");
1896 R.StoredSize = static_cast<off_t>(Record[1]);
1897 R.StoredTime = static_cast<time_t>(Record[2]);
1898 R.Overridden = static_cast<bool>(Record[3]);
1899 R.Transient = static_cast<bool>(Record[4]);
1901 ResolveImportedPath(F, R.Filename);
1905 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
1906 // If this ID is bogus, just return an empty input file.
1907 if (ID == 0 || ID > F.InputFilesLoaded.size())
1910 // If we've already loaded this input file, return it.
1911 if (F.InputFilesLoaded[ID-1].getFile())
1912 return F.InputFilesLoaded[ID-1];
1914 if (F.InputFilesLoaded[ID-1].isNotFound())
1917 // Go find this input file.
1918 BitstreamCursor &Cursor = F.InputFilesCursor;
1919 SavedStreamPosition SavedPosition(Cursor);
1920 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1922 InputFileInfo FI = readInputFileInfo(F, ID);
1923 off_t StoredSize = FI.StoredSize;
1924 time_t StoredTime = FI.StoredTime;
1925 bool Overridden = FI.Overridden;
1926 bool Transient = FI.Transient;
1927 StringRef Filename = FI.Filename;
1929 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
1931 // If we didn't find the file, resolve it relative to the
1932 // original directory from which this AST file was created.
1933 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1934 F.OriginalDir != CurrentDir) {
1935 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1938 if (!Resolved.empty())
1939 File = FileMgr.getFile(Resolved);
1942 // For an overridden file, create a virtual file with the stored
1944 if ((Overridden || Transient) && File == nullptr)
1945 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1947 if (File == nullptr) {
1949 std::string ErrorStr = "could not find file '";
1950 ErrorStr += Filename;
1951 ErrorStr += "' referenced by AST file '";
1952 ErrorStr += F.FileName;
1954 Error(ErrorStr.c_str());
1956 // Record that we didn't find the file.
1957 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1961 // Check if there was a request to override the contents of the file
1962 // that was part of the precompiled header. Overridding such a file
1963 // can lead to problems when lexing using the source locations from the
1965 SourceManager &SM = getSourceManager();
1966 // FIXME: Reject if the overrides are different.
1967 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
1969 Error(diag::err_fe_pch_file_overridden, Filename);
1970 // After emitting the diagnostic, recover by disabling the override so
1971 // that the original file will be used.
1973 // FIXME: This recovery is just as broken as the original state; there may
1974 // be another precompiled module that's using the overridden contents, or
1975 // we might be half way through parsing it. Instead, we should treat the
1976 // overridden contents as belonging to a separate FileEntry.
1977 SM.disableFileContentsOverride(File);
1978 // The FileEntry is a virtual file entry with the size of the contents
1979 // that would override the original contents. Set it to the original's
1981 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1982 StoredSize, StoredTime);
1985 bool IsOutOfDate = false;
1987 // For an overridden file, there is nothing to validate.
1988 if (!Overridden && //
1989 (StoredSize != File->getSize() ||
1990 #if defined(LLVM_ON_WIN32)
1993 // In our regression testing, the Windows file system seems to
1994 // have inconsistent modification times that sometimes
1995 // erroneously trigger this error-handling path.
1997 // FIXME: This probably also breaks HeaderFileInfo lookups on Windows.
1998 (StoredTime && StoredTime != File->getModificationTime() &&
2003 // Build a list of the PCH imports that got us here (in reverse).
2004 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2005 while (ImportStack.back()->ImportedBy.size() > 0)
2006 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2008 // The top-level PCH is stale.
2009 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2010 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2012 // Print the import stack.
2013 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2014 Diag(diag::note_pch_required_by)
2015 << Filename << ImportStack[0]->FileName;
2016 for (unsigned I = 1; I < ImportStack.size(); ++I)
2017 Diag(diag::note_pch_required_by)
2018 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2021 if (!Diags.isDiagnosticInFlight())
2022 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2027 // FIXME: If the file is overridden and we've already opened it,
2028 // issue an error (or split it into a separate FileEntry).
2030 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
2032 // Note that we've loaded this input file.
2033 F.InputFilesLoaded[ID-1] = IF;
2037 /// \brief If we are loading a relocatable PCH or module file, and the filename
2038 /// is not an absolute path, add the system or module root to the beginning of
2040 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2041 // Resolve relative to the base directory, if we have one.
2042 if (!M.BaseDirectory.empty())
2043 return ResolveImportedPath(Filename, M.BaseDirectory);
2046 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2047 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2050 SmallString<128> Buffer;
2051 llvm::sys::path::append(Buffer, Prefix, Filename);
2052 Filename.assign(Buffer.begin(), Buffer.end());
2055 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2057 case ASTReader::Failure: return true;
2058 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2059 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2060 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2061 case ASTReader::ConfigurationMismatch:
2062 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2063 case ASTReader::HadErrors: return true;
2064 case ASTReader::Success: return false;
2067 llvm_unreachable("unknown ASTReadResult");
2070 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2071 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2072 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2073 std::string &SuggestedPredefines) {
2074 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2077 // Read all of the records in the options block.
2079 ASTReadResult Result = Success;
2081 llvm::BitstreamEntry Entry = Stream.advance();
2083 switch (Entry.Kind) {
2084 case llvm::BitstreamEntry::Error:
2085 case llvm::BitstreamEntry::SubBlock:
2088 case llvm::BitstreamEntry::EndBlock:
2091 case llvm::BitstreamEntry::Record:
2092 // The interesting case.
2096 // Read and process a record.
2098 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2099 case LANGUAGE_OPTIONS: {
2100 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2101 if (ParseLanguageOptions(Record, Complain, Listener,
2102 AllowCompatibleConfigurationMismatch))
2103 Result = ConfigurationMismatch;
2107 case TARGET_OPTIONS: {
2108 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2109 if (ParseTargetOptions(Record, Complain, Listener,
2110 AllowCompatibleConfigurationMismatch))
2111 Result = ConfigurationMismatch;
2115 case DIAGNOSTIC_OPTIONS: {
2116 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2117 if (!AllowCompatibleConfigurationMismatch &&
2118 ParseDiagnosticOptions(Record, Complain, Listener))
2123 case FILE_SYSTEM_OPTIONS: {
2124 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2125 if (!AllowCompatibleConfigurationMismatch &&
2126 ParseFileSystemOptions(Record, Complain, Listener))
2127 Result = ConfigurationMismatch;
2131 case HEADER_SEARCH_OPTIONS: {
2132 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2133 if (!AllowCompatibleConfigurationMismatch &&
2134 ParseHeaderSearchOptions(Record, Complain, Listener))
2135 Result = ConfigurationMismatch;
2139 case PREPROCESSOR_OPTIONS:
2140 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2141 if (!AllowCompatibleConfigurationMismatch &&
2142 ParsePreprocessorOptions(Record, Complain, Listener,
2143 SuggestedPredefines))
2144 Result = ConfigurationMismatch;
2150 ASTReader::ASTReadResult
2151 ASTReader::ReadControlBlock(ModuleFile &F,
2152 SmallVectorImpl<ImportedModule> &Loaded,
2153 const ModuleFile *ImportedBy,
2154 unsigned ClientLoadCapabilities) {
2155 BitstreamCursor &Stream = F.Stream;
2156 ASTReadResult Result = Success;
2158 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2159 Error("malformed block record in AST file");
2163 // Read all of the records and blocks in the control block.
2165 unsigned NumInputs = 0;
2166 unsigned NumUserInputs = 0;
2168 llvm::BitstreamEntry Entry = Stream.advance();
2170 switch (Entry.Kind) {
2171 case llvm::BitstreamEntry::Error:
2172 Error("malformed block record in AST file");
2174 case llvm::BitstreamEntry::EndBlock: {
2175 // Validate input files.
2176 const HeaderSearchOptions &HSOpts =
2177 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2179 // All user input files reside at the index range [0, NumUserInputs), and
2180 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2181 // loaded module files, ignore missing inputs.
2182 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
2183 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2185 // If we are reading a module, we will create a verification timestamp,
2186 // so we verify all input files. Otherwise, verify only user input
2189 unsigned N = NumUserInputs;
2190 if (ValidateSystemInputs ||
2191 (HSOpts.ModulesValidateOncePerBuildSession &&
2192 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
2193 F.Kind == MK_ImplicitModule))
2196 for (unsigned I = 0; I < N; ++I) {
2197 InputFile IF = getInputFile(F, I+1, Complain);
2198 if (!IF.getFile() || IF.isOutOfDate())
2204 Listener->visitModuleFile(F.FileName, F.Kind);
2206 if (Listener && Listener->needsInputFileVisitation()) {
2207 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2209 for (unsigned I = 0; I < N; ++I) {
2210 bool IsSystem = I >= NumUserInputs;
2211 InputFileInfo FI = readInputFileInfo(F, I+1);
2212 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2213 F.Kind == MK_ExplicitModule);
2220 case llvm::BitstreamEntry::SubBlock:
2222 case INPUT_FILES_BLOCK_ID:
2223 F.InputFilesCursor = Stream;
2224 if (Stream.SkipBlock() || // Skip with the main cursor
2225 // Read the abbreviations
2226 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2227 Error("malformed block record in AST file");
2232 case OPTIONS_BLOCK_ID:
2233 // If we're reading the first module for this group, check its options
2234 // are compatible with ours. For modules it imports, no further checking
2235 // is required, because we checked them when we built it.
2236 if (Listener && !ImportedBy) {
2237 // Should we allow the configuration of the module file to differ from
2238 // the configuration of the current translation unit in a compatible
2241 // FIXME: Allow this for files explicitly specified with -include-pch.
2242 bool AllowCompatibleConfigurationMismatch =
2243 F.Kind == MK_ExplicitModule;
2245 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2246 AllowCompatibleConfigurationMismatch,
2247 *Listener, SuggestedPredefines);
2248 if (Result == Failure) {
2249 Error("malformed block record in AST file");
2253 if (DisableValidation ||
2254 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2257 // If we've diagnosed a problem, we're done.
2258 if (Result != Success &&
2259 isDiagnosedResult(Result, ClientLoadCapabilities))
2261 } else if (Stream.SkipBlock()) {
2262 Error("malformed block record in AST file");
2268 if (Stream.SkipBlock()) {
2269 Error("malformed block record in AST file");
2275 case llvm::BitstreamEntry::Record:
2276 // The interesting case.
2280 // Read and process a record.
2283 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2285 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2286 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2287 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2288 : diag::err_pch_version_too_new);
2289 return VersionMismatch;
2292 bool hasErrors = Record[6];
2293 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2294 Diag(diag::err_pch_with_compiler_errors);
2298 F.RelocatablePCH = Record[4];
2299 // Relative paths in a relocatable PCH are relative to our sysroot.
2300 if (F.RelocatablePCH)
2301 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
2303 F.HasTimestamps = Record[5];
2305 const std::string &CurBranch = getClangFullRepositoryVersion();
2306 StringRef ASTBranch = Blob;
2307 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2308 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2309 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2310 return VersionMismatch;
2316 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2317 F.Signature = Record[0];
2321 // Load each of the imported PCH files.
2322 unsigned Idx = 0, N = Record.size();
2324 // Read information about the AST file.
2325 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2326 // The import location will be the local one for now; we will adjust
2327 // all import locations of module imports after the global source
2328 // location info are setup.
2329 SourceLocation ImportLoc =
2330 SourceLocation::getFromRawEncoding(Record[Idx++]);
2331 off_t StoredSize = (off_t)Record[Idx++];
2332 time_t StoredModTime = (time_t)Record[Idx++];
2333 ASTFileSignature StoredSignature = Record[Idx++];
2334 auto ImportedFile = ReadPath(F, Record, Idx);
2336 // If our client can't cope with us being out of date, we can't cope with
2337 // our dependency being missing.
2338 unsigned Capabilities = ClientLoadCapabilities;
2339 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2340 Capabilities &= ~ARR_Missing;
2342 // Load the AST file.
2343 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2344 Loaded, StoredSize, StoredModTime,
2345 StoredSignature, Capabilities);
2347 // If we diagnosed a problem, produce a backtrace.
2348 if (isDiagnosedResult(Result, Capabilities))
2349 Diag(diag::note_module_file_imported_by)
2350 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2353 case Failure: return Failure;
2354 // If we have to ignore the dependency, we'll have to ignore this too.
2356 case OutOfDate: return OutOfDate;
2357 case VersionMismatch: return VersionMismatch;
2358 case ConfigurationMismatch: return ConfigurationMismatch;
2359 case HadErrors: return HadErrors;
2360 case Success: break;
2367 F.OriginalSourceFileID = FileID::get(Record[0]);
2368 F.ActualOriginalSourceFileName = Blob;
2369 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2370 ResolveImportedPath(F, F.OriginalSourceFileName);
2373 case ORIGINAL_FILE_ID:
2374 F.OriginalSourceFileID = FileID::get(Record[0]);
2377 case ORIGINAL_PCH_DIR:
2378 F.OriginalDir = Blob;
2382 F.ModuleName = Blob;
2384 Listener->ReadModuleName(F.ModuleName);
2387 case MODULE_DIRECTORY: {
2388 assert(!F.ModuleName.empty() &&
2389 "MODULE_DIRECTORY found before MODULE_NAME");
2390 // If we've already loaded a module map file covering this module, we may
2391 // have a better path for it (relative to the current build).
2392 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2393 if (M && M->Directory) {
2394 // If we're implicitly loading a module, the base directory can't
2395 // change between the build and use.
2396 if (F.Kind != MK_ExplicitModule) {
2397 const DirectoryEntry *BuildDir =
2398 PP.getFileManager().getDirectory(Blob);
2399 if (!BuildDir || BuildDir != M->Directory) {
2400 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2401 Diag(diag::err_imported_module_relocated)
2402 << F.ModuleName << Blob << M->Directory->getName();
2406 F.BaseDirectory = M->Directory->getName();
2408 F.BaseDirectory = Blob;
2413 case MODULE_MAP_FILE:
2414 if (ASTReadResult Result =
2415 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2419 case INPUT_FILE_OFFSETS:
2420 NumInputs = Record[0];
2421 NumUserInputs = Record[1];
2422 F.InputFileOffsets =
2423 (const llvm::support::unaligned_uint64_t *)Blob.data();
2424 F.InputFilesLoaded.resize(NumInputs);
2430 ASTReader::ASTReadResult
2431 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
2432 BitstreamCursor &Stream = F.Stream;
2434 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2435 Error("malformed block record in AST file");
2439 // Read all of the records and blocks for the AST file.
2442 llvm::BitstreamEntry Entry = Stream.advance();
2444 switch (Entry.Kind) {
2445 case llvm::BitstreamEntry::Error:
2446 Error("error at end of module block in AST file");
2448 case llvm::BitstreamEntry::EndBlock: {
2449 // Outside of C++, we do not store a lookup map for the translation unit.
2450 // Instead, mark it as needing a lookup map to be built if this module
2451 // contains any declarations lexically within it (which it always does!).
2452 // This usually has no cost, since we very rarely need the lookup map for
2453 // the translation unit outside C++.
2454 DeclContext *DC = Context.getTranslationUnitDecl();
2455 if (DC->hasExternalLexicalStorage() &&
2456 !getContext().getLangOpts().CPlusPlus)
2457 DC->setMustBuildLookupTable();
2461 case llvm::BitstreamEntry::SubBlock:
2463 case DECLTYPES_BLOCK_ID:
2464 // We lazily load the decls block, but we want to set up the
2465 // DeclsCursor cursor to point into it. Clone our current bitcode
2466 // cursor to it, enter the block and read the abbrevs in that block.
2467 // With the main cursor, we just skip over it.
2468 F.DeclsCursor = Stream;
2469 if (Stream.SkipBlock() || // Skip with the main cursor.
2470 // Read the abbrevs.
2471 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2472 Error("malformed block record in AST file");
2477 case PREPROCESSOR_BLOCK_ID:
2478 F.MacroCursor = Stream;
2479 if (!PP.getExternalSource())
2480 PP.setExternalSource(this);
2482 if (Stream.SkipBlock() ||
2483 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2484 Error("malformed block record in AST file");
2487 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2490 case PREPROCESSOR_DETAIL_BLOCK_ID:
2491 F.PreprocessorDetailCursor = Stream;
2492 if (Stream.SkipBlock() ||
2493 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
2494 PREPROCESSOR_DETAIL_BLOCK_ID)) {
2495 Error("malformed preprocessor detail record in AST file");
2498 F.PreprocessorDetailStartOffset
2499 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2501 if (!PP.getPreprocessingRecord())
2502 PP.createPreprocessingRecord();
2503 if (!PP.getPreprocessingRecord()->getExternalSource())
2504 PP.getPreprocessingRecord()->SetExternalSource(*this);
2507 case SOURCE_MANAGER_BLOCK_ID:
2508 if (ReadSourceManagerBlock(F))
2512 case SUBMODULE_BLOCK_ID:
2513 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2517 case COMMENTS_BLOCK_ID: {
2518 BitstreamCursor C = Stream;
2519 if (Stream.SkipBlock() ||
2520 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2521 Error("malformed comments block in AST file");
2524 CommentsCursors.push_back(std::make_pair(C, &F));
2529 if (Stream.SkipBlock()) {
2530 Error("malformed block record in AST file");
2537 case llvm::BitstreamEntry::Record:
2538 // The interesting case.
2542 // Read and process a record.
2545 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2546 default: // Default behavior: ignore.
2550 if (F.LocalNumTypes != 0) {
2551 Error("duplicate TYPE_OFFSET record in AST file");
2554 F.TypeOffsets = (const uint32_t *)Blob.data();
2555 F.LocalNumTypes = Record[0];
2556 unsigned LocalBaseTypeIndex = Record[1];
2557 F.BaseTypeIndex = getTotalNumTypes();
2559 if (F.LocalNumTypes > 0) {
2560 // Introduce the global -> local mapping for types within this module.
2561 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2563 // Introduce the local -> global mapping for types within this module.
2564 F.TypeRemap.insertOrReplace(
2565 std::make_pair(LocalBaseTypeIndex,
2566 F.BaseTypeIndex - LocalBaseTypeIndex));
2568 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2574 if (F.LocalNumDecls != 0) {
2575 Error("duplicate DECL_OFFSET record in AST file");
2578 F.DeclOffsets = (const DeclOffset *)Blob.data();
2579 F.LocalNumDecls = Record[0];
2580 unsigned LocalBaseDeclID = Record[1];
2581 F.BaseDeclID = getTotalNumDecls();
2583 if (F.LocalNumDecls > 0) {
2584 // Introduce the global -> local mapping for declarations within this
2586 GlobalDeclMap.insert(
2587 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2589 // Introduce the local -> global mapping for declarations within this
2591 F.DeclRemap.insertOrReplace(
2592 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2594 // Introduce the global -> local mapping for declarations within this
2596 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2598 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2603 case TU_UPDATE_LEXICAL: {
2604 DeclContext *TU = Context.getTranslationUnitDecl();
2605 LexicalContents Contents(
2606 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2608 static_cast<unsigned int>(Blob.size() / 4));
2609 TULexicalDecls.push_back(std::make_pair(&F, Contents));
2610 TU->setHasExternalLexicalStorage(true);
2614 case UPDATE_VISIBLE: {
2616 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2617 auto *Data = (const unsigned char*)Blob.data();
2618 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
2619 // If we've already loaded the decl, perform the updates when we finish
2620 // loading this block.
2621 if (Decl *D = GetExistingDecl(ID))
2622 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2626 case IDENTIFIER_TABLE:
2627 F.IdentifierTableData = Blob.data();
2629 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2630 (const unsigned char *)F.IdentifierTableData + Record[0],
2631 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2632 (const unsigned char *)F.IdentifierTableData,
2633 ASTIdentifierLookupTrait(*this, F));
2635 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2639 case IDENTIFIER_OFFSET: {
2640 if (F.LocalNumIdentifiers != 0) {
2641 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2644 F.IdentifierOffsets = (const uint32_t *)Blob.data();
2645 F.LocalNumIdentifiers = Record[0];
2646 unsigned LocalBaseIdentifierID = Record[1];
2647 F.BaseIdentifierID = getTotalNumIdentifiers();
2649 if (F.LocalNumIdentifiers > 0) {
2650 // Introduce the global -> local mapping for identifiers within this
2652 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2655 // Introduce the local -> global mapping for identifiers within this
2657 F.IdentifierRemap.insertOrReplace(
2658 std::make_pair(LocalBaseIdentifierID,
2659 F.BaseIdentifierID - LocalBaseIdentifierID));
2661 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2662 + F.LocalNumIdentifiers);
2667 case INTERESTING_IDENTIFIERS:
2668 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2671 case EAGERLY_DESERIALIZED_DECLS:
2672 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2673 // about "interesting" decls (for instance, if we're building a module).
2674 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2675 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2679 if (SpecialTypes.empty()) {
2680 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2681 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2685 if (SpecialTypes.size() != Record.size()) {
2686 Error("invalid special-types record");
2690 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2691 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2692 if (!SpecialTypes[I])
2693 SpecialTypes[I] = ID;
2694 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2700 TotalNumStatements += Record[0];
2701 TotalNumMacros += Record[1];
2702 TotalLexicalDeclContexts += Record[2];
2703 TotalVisibleDeclContexts += Record[3];
2706 case UNUSED_FILESCOPED_DECLS:
2707 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2708 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2711 case DELEGATING_CTORS:
2712 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2713 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2716 case WEAK_UNDECLARED_IDENTIFIERS:
2717 if (Record.size() % 4 != 0) {
2718 Error("invalid weak identifiers record");
2722 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2723 // files. This isn't the way to do it :)
2724 WeakUndeclaredIdentifiers.clear();
2726 // Translate the weak, undeclared identifiers into global IDs.
2727 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2728 WeakUndeclaredIdentifiers.push_back(
2729 getGlobalIdentifierID(F, Record[I++]));
2730 WeakUndeclaredIdentifiers.push_back(
2731 getGlobalIdentifierID(F, Record[I++]));
2732 WeakUndeclaredIdentifiers.push_back(
2733 ReadSourceLocation(F, Record, I).getRawEncoding());
2734 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2738 case SELECTOR_OFFSETS: {
2739 F.SelectorOffsets = (const uint32_t *)Blob.data();
2740 F.LocalNumSelectors = Record[0];
2741 unsigned LocalBaseSelectorID = Record[1];
2742 F.BaseSelectorID = getTotalNumSelectors();
2744 if (F.LocalNumSelectors > 0) {
2745 // Introduce the global -> local mapping for selectors within this
2747 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2749 // Introduce the local -> global mapping for selectors within this
2751 F.SelectorRemap.insertOrReplace(
2752 std::make_pair(LocalBaseSelectorID,
2753 F.BaseSelectorID - LocalBaseSelectorID));
2755 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2761 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
2763 F.SelectorLookupTable
2764 = ASTSelectorLookupTable::Create(
2765 F.SelectorLookupTableData + Record[0],
2766 F.SelectorLookupTableData,
2767 ASTSelectorLookupTrait(*this, F));
2768 TotalNumMethodPoolEntries += Record[1];
2771 case REFERENCED_SELECTOR_POOL:
2772 if (!Record.empty()) {
2773 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2774 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2776 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2782 case PP_COUNTER_VALUE:
2783 if (!Record.empty() && Listener)
2784 Listener->ReadCounter(F, Record[0]);
2787 case FILE_SORTED_DECLS:
2788 F.FileSortedDecls = (const DeclID *)Blob.data();
2789 F.NumFileSortedDecls = Record[0];
2792 case SOURCE_LOCATION_OFFSETS: {
2793 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
2794 F.LocalNumSLocEntries = Record[0];
2795 unsigned SLocSpaceSize = Record[1];
2796 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2797 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2799 if (!F.SLocEntryBaseID) {
2800 Error("ran out of source locations");
2803 // Make our entry in the range map. BaseID is negative and growing, so
2804 // we invert it. Because we invert it, though, we need the other end of
2806 unsigned RangeStart =
2807 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2808 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2809 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2811 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2812 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2813 GlobalSLocOffsetMap.insert(
2814 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2815 - SLocSpaceSize,&F));
2817 // Initialize the remapping table.
2818 // Invalid stays invalid.
2819 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
2820 // This module. Base was 2 when being compiled.
2821 F.SLocRemap.insertOrReplace(std::make_pair(2U,
2822 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2824 TotalNumSLocEntries += F.LocalNumSLocEntries;
2828 case MODULE_OFFSET_MAP: {
2829 // Additional remapping information.
2830 const unsigned char *Data = (const unsigned char*)Blob.data();
2831 const unsigned char *DataEnd = Data + Blob.size();
2833 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2834 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2835 F.SLocRemap.insert(std::make_pair(0U, 0));
2836 F.SLocRemap.insert(std::make_pair(2U, 1));
2839 // Continuous range maps we may be updating in our module.
2840 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2842 RemapBuilder SLocRemap(F.SLocRemap);
2843 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2844 RemapBuilder MacroRemap(F.MacroRemap);
2845 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2846 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2847 RemapBuilder SelectorRemap(F.SelectorRemap);
2848 RemapBuilder DeclRemap(F.DeclRemap);
2849 RemapBuilder TypeRemap(F.TypeRemap);
2851 while (Data < DataEnd) {
2852 using namespace llvm::support;
2853 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
2854 StringRef Name = StringRef((const char*)Data, Len);
2856 ModuleFile *OM = ModuleMgr.lookup(Name);
2858 Error("SourceLocation remap refers to unknown module");
2862 uint32_t SLocOffset =
2863 endian::readNext<uint32_t, little, unaligned>(Data);
2864 uint32_t IdentifierIDOffset =
2865 endian::readNext<uint32_t, little, unaligned>(Data);
2866 uint32_t MacroIDOffset =
2867 endian::readNext<uint32_t, little, unaligned>(Data);
2868 uint32_t PreprocessedEntityIDOffset =
2869 endian::readNext<uint32_t, little, unaligned>(Data);
2870 uint32_t SubmoduleIDOffset =
2871 endian::readNext<uint32_t, little, unaligned>(Data);
2872 uint32_t SelectorIDOffset =
2873 endian::readNext<uint32_t, little, unaligned>(Data);
2874 uint32_t DeclIDOffset =
2875 endian::readNext<uint32_t, little, unaligned>(Data);
2876 uint32_t TypeIndexOffset =
2877 endian::readNext<uint32_t, little, unaligned>(Data);
2879 uint32_t None = std::numeric_limits<uint32_t>::max();
2881 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2882 RemapBuilder &Remap) {
2884 Remap.insert(std::make_pair(Offset,
2885 static_cast<int>(BaseOffset - Offset)));
2887 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2888 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2889 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2890 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2891 PreprocessedEntityRemap);
2892 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2893 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2894 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2895 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
2897 // Global -> local mappings.
2898 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2903 case SOURCE_MANAGER_LINE_TABLE:
2904 if (ParseLineTable(F, Record))
2908 case SOURCE_LOCATION_PRELOADS: {
2909 // Need to transform from the local view (1-based IDs) to the global view,
2910 // which is based off F.SLocEntryBaseID.
2911 if (!F.PreloadSLocEntries.empty()) {
2912 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2916 F.PreloadSLocEntries.swap(Record);
2920 case EXT_VECTOR_DECLS:
2921 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2922 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2926 if (Record.size() % 3 != 0) {
2927 Error("Invalid VTABLE_USES record");
2931 // Later tables overwrite earlier ones.
2932 // FIXME: Modules will have some trouble with this. This is clearly not
2933 // the right way to do this.
2936 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2937 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2938 VTableUses.push_back(
2939 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2940 VTableUses.push_back(Record[Idx++]);
2944 case PENDING_IMPLICIT_INSTANTIATIONS:
2945 if (PendingInstantiations.size() % 2 != 0) {
2946 Error("Invalid existing PendingInstantiations");
2950 if (Record.size() % 2 != 0) {
2951 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2955 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2956 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2957 PendingInstantiations.push_back(
2958 ReadSourceLocation(F, Record, I).getRawEncoding());
2962 case SEMA_DECL_REFS:
2963 if (Record.size() != 2) {
2964 Error("Invalid SEMA_DECL_REFS block");
2967 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2968 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2971 case PPD_ENTITIES_OFFSETS: {
2972 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2973 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2974 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
2976 unsigned LocalBasePreprocessedEntityID = Record[0];
2978 unsigned StartingID;
2979 if (!PP.getPreprocessingRecord())
2980 PP.createPreprocessingRecord();
2981 if (!PP.getPreprocessingRecord()->getExternalSource())
2982 PP.getPreprocessingRecord()->SetExternalSource(*this);
2984 = PP.getPreprocessingRecord()
2985 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2986 F.BasePreprocessedEntityID = StartingID;
2988 if (F.NumPreprocessedEntities > 0) {
2989 // Introduce the global -> local mapping for preprocessed entities in
2991 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2993 // Introduce the local -> global mapping for preprocessed entities in
2995 F.PreprocessedEntityRemap.insertOrReplace(
2996 std::make_pair(LocalBasePreprocessedEntityID,
2997 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3003 case DECL_UPDATE_OFFSETS: {
3004 if (Record.size() % 2 != 0) {
3005 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
3008 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3009 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3010 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3012 // If we've already loaded the decl, perform the updates when we finish
3013 // loading this block.
3014 if (Decl *D = GetExistingDecl(ID))
3015 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3020 case DECL_REPLACEMENTS: {
3021 if (Record.size() % 3 != 0) {
3022 Error("invalid DECL_REPLACEMENTS block in AST file");
3025 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3026 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3027 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3031 case OBJC_CATEGORIES_MAP: {
3032 if (F.LocalNumObjCCategoriesInMap != 0) {
3033 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
3037 F.LocalNumObjCCategoriesInMap = Record[0];
3038 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3042 case OBJC_CATEGORIES:
3043 F.ObjCCategories.swap(Record);
3046 case CXX_BASE_SPECIFIER_OFFSETS: {
3047 if (F.LocalNumCXXBaseSpecifiers != 0) {
3048 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
3052 F.LocalNumCXXBaseSpecifiers = Record[0];
3053 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
3057 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3058 if (F.LocalNumCXXCtorInitializers != 0) {
3059 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3063 F.LocalNumCXXCtorInitializers = Record[0];
3064 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
3068 case DIAG_PRAGMA_MAPPINGS:
3069 if (F.PragmaDiagMappings.empty())
3070 F.PragmaDiagMappings.swap(Record);
3072 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3073 Record.begin(), Record.end());
3076 case CUDA_SPECIAL_DECL_REFS:
3077 // Later tables overwrite earlier ones.
3078 // FIXME: Modules will have trouble with this.
3079 CUDASpecialDeclRefs.clear();
3080 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3081 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3084 case HEADER_SEARCH_TABLE: {
3085 F.HeaderFileInfoTableData = Blob.data();
3086 F.LocalNumHeaderFileInfos = Record[1];
3088 F.HeaderFileInfoTable
3089 = HeaderFileInfoLookupTable::Create(
3090 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3091 (const unsigned char *)F.HeaderFileInfoTableData,
3092 HeaderFileInfoTrait(*this, F,
3093 &PP.getHeaderSearchInfo(),
3094 Blob.data() + Record[2]));
3096 PP.getHeaderSearchInfo().SetExternalSource(this);
3097 if (!PP.getHeaderSearchInfo().getExternalLookup())
3098 PP.getHeaderSearchInfo().SetExternalLookup(this);
3103 case FP_PRAGMA_OPTIONS:
3104 // Later tables overwrite earlier ones.
3105 FPPragmaOptions.swap(Record);
3108 case OPENCL_EXTENSIONS:
3109 // Later tables overwrite earlier ones.
3110 OpenCLExtensions.swap(Record);
3113 case TENTATIVE_DEFINITIONS:
3114 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3115 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3118 case KNOWN_NAMESPACES:
3119 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3120 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3123 case UNDEFINED_BUT_USED:
3124 if (UndefinedButUsed.size() % 2 != 0) {
3125 Error("Invalid existing UndefinedButUsed");
3129 if (Record.size() % 2 != 0) {
3130 Error("invalid undefined-but-used record");
3133 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3134 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3135 UndefinedButUsed.push_back(
3136 ReadSourceLocation(F, Record, I).getRawEncoding());
3139 case DELETE_EXPRS_TO_ANALYZE:
3140 for (unsigned I = 0, N = Record.size(); I != N;) {
3141 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3142 const uint64_t Count = Record[I++];
3143 DelayedDeleteExprs.push_back(Count);
3144 for (uint64_t C = 0; C < Count; ++C) {
3145 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3146 bool IsArrayForm = Record[I++] == 1;
3147 DelayedDeleteExprs.push_back(IsArrayForm);
3152 case IMPORTED_MODULES: {
3153 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
3154 // If we aren't loading a module (which has its own exports), make
3155 // all of the imported modules visible.
3156 // FIXME: Deal with macros-only imports.
3157 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3158 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3159 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3161 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3167 case MACRO_OFFSET: {
3168 if (F.LocalNumMacros != 0) {
3169 Error("duplicate MACRO_OFFSET record in AST file");
3172 F.MacroOffsets = (const uint32_t *)Blob.data();
3173 F.LocalNumMacros = Record[0];
3174 unsigned LocalBaseMacroID = Record[1];
3175 F.BaseMacroID = getTotalNumMacros();
3177 if (F.LocalNumMacros > 0) {
3178 // Introduce the global -> local mapping for macros within this module.
3179 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3181 // Introduce the local -> global mapping for macros within this module.
3182 F.MacroRemap.insertOrReplace(
3183 std::make_pair(LocalBaseMacroID,
3184 F.BaseMacroID - LocalBaseMacroID));
3186 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3191 case LATE_PARSED_TEMPLATE: {
3192 LateParsedTemplates.append(Record.begin(), Record.end());
3196 case OPTIMIZE_PRAGMA_OPTIONS:
3197 if (Record.size() != 1) {
3198 Error("invalid pragma optimize record");
3201 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3204 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3205 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3206 UnusedLocalTypedefNameCandidates.push_back(
3207 getGlobalDeclID(F, Record[I]));
3213 ASTReader::ASTReadResult
3214 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3215 const ModuleFile *ImportedBy,
3216 unsigned ClientLoadCapabilities) {
3218 F.ModuleMapPath = ReadPath(F, Record, Idx);
3220 if (F.Kind == MK_ExplicitModule) {
3221 // For an explicitly-loaded module, we don't care whether the original
3222 // module map file exists or matches.
3226 // Try to resolve ModuleName in the current header search context and
3227 // verify that it is found in the same module map file as we saved. If the
3228 // top-level AST file is a main file, skip this check because there is no
3229 // usable header search context.
3230 assert(!F.ModuleName.empty() &&
3231 "MODULE_NAME should come before MODULE_MAP_FILE");
3232 if (F.Kind == MK_ImplicitModule &&
3233 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3234 // An implicitly-loaded module file should have its module listed in some
3235 // module map file that we've already loaded.
3236 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
3237 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3238 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3240 assert(ImportedBy && "top-level import should be verified");
3241 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3242 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3243 // This module was defined by an imported (explicit) module.
3244 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3245 << ASTFE->getName();
3247 // This module was built with a different module map.
3248 Diag(diag::err_imported_module_not_found)
3249 << F.ModuleName << F.FileName << ImportedBy->FileName
3255 assert(M->Name == F.ModuleName && "found module with different name");
3257 // Check the primary module map file.
3258 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3259 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3260 assert(ModMap && "found module is missing module map file");
3261 assert(ImportedBy && "top-level import should be verified");
3262 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3263 Diag(diag::err_imported_module_modmap_changed)
3264 << F.ModuleName << ImportedBy->FileName
3265 << ModMap->getName() << F.ModuleMapPath;
3269 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3270 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3271 // FIXME: we should use input files rather than storing names.
3272 std::string Filename = ReadPath(F, Record, Idx);
3273 const FileEntry *F =
3274 FileMgr.getFile(Filename, false, false);
3276 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3277 Error("could not find file '" + Filename +"' referenced by AST file");
3280 AdditionalStoredMaps.insert(F);
3283 // Check any additional module map files (e.g. module.private.modulemap)
3284 // that are not in the pcm.
3285 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3286 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3287 // Remove files that match
3288 // Note: SmallPtrSet::erase is really remove
3289 if (!AdditionalStoredMaps.erase(ModMap)) {
3290 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3291 Diag(diag::err_module_different_modmap)
3292 << F.ModuleName << /*new*/0 << ModMap->getName();
3298 // Check any additional module map files that are in the pcm, but not
3299 // found in header search. Cases that match are already removed.
3300 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3301 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3302 Diag(diag::err_module_different_modmap)
3303 << F.ModuleName << /*not new*/1 << ModMap->getName();
3309 Listener->ReadModuleMapFile(F.ModuleMapPath);
3314 /// \brief Move the given method to the back of the global list of methods.
3315 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3316 // Find the entry for this selector in the method pool.
3317 Sema::GlobalMethodPool::iterator Known
3318 = S.MethodPool.find(Method->getSelector());
3319 if (Known == S.MethodPool.end())
3322 // Retrieve the appropriate method list.
3323 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3324 : Known->second.second;
3326 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
3328 if (List->getMethod() == Method) {
3336 if (List->getNext())
3337 List->setMethod(List->getNext()->getMethod());
3339 List->setMethod(Method);
3343 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
3344 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
3345 for (Decl *D : Names) {
3346 bool wasHidden = D->Hidden;
3349 if (wasHidden && SemaObj) {
3350 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3351 moveMethodToBackOfGlobalList(*SemaObj, Method);
3357 void ASTReader::makeModuleVisible(Module *Mod,
3358 Module::NameVisibilityKind NameVisibility,
3359 SourceLocation ImportLoc) {
3360 llvm::SmallPtrSet<Module *, 4> Visited;
3361 SmallVector<Module *, 4> Stack;
3362 Stack.push_back(Mod);
3363 while (!Stack.empty()) {
3364 Mod = Stack.pop_back_val();
3366 if (NameVisibility <= Mod->NameVisibility) {
3367 // This module already has this level of visibility (or greater), so
3368 // there is nothing more to do.
3372 if (!Mod->isAvailable()) {
3373 // Modules that aren't available cannot be made visible.
3377 // Update the module's name visibility.
3378 Mod->NameVisibility = NameVisibility;
3380 // If we've already deserialized any names from this module,
3381 // mark them as visible.
3382 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3383 if (Hidden != HiddenNamesMap.end()) {
3384 auto HiddenNames = std::move(*Hidden);
3385 HiddenNamesMap.erase(Hidden);
3386 makeNamesVisible(HiddenNames.second, HiddenNames.first);
3387 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3388 "making names visible added hidden names");
3391 // Push any exported modules onto the stack to be marked as visible.
3392 SmallVector<Module *, 16> Exports;
3393 Mod->getExportedModules(Exports);
3394 for (SmallVectorImpl<Module *>::iterator
3395 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3396 Module *Exported = *I;
3397 if (Visited.insert(Exported).second)
3398 Stack.push_back(Exported);
3403 bool ASTReader::loadGlobalIndex() {
3407 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3408 !Context.getLangOpts().Modules)
3411 // Try to load the global index.
3412 TriedLoadingGlobalIndex = true;
3413 StringRef ModuleCachePath
3414 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3415 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
3416 = GlobalModuleIndex::readIndex(ModuleCachePath);
3420 GlobalIndex.reset(Result.first);
3421 ModuleMgr.setGlobalIndex(GlobalIndex.get());
3425 bool ASTReader::isGlobalIndexUnavailable() const {
3426 return Context.getLangOpts().Modules && UseGlobalIndex &&
3427 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3430 static void updateModuleTimestamp(ModuleFile &MF) {
3431 // Overwrite the timestamp file contents so that file's mtime changes.
3432 std::string TimestampFilename = MF.getTimestampFilename();
3434 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3437 OS << "Timestamp file\n";
3440 /// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3441 /// cursor into the start of the given block ID, returning false on success and
3442 /// true on failure.
3443 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3445 llvm::BitstreamEntry Entry = Cursor.advance();
3446 switch (Entry.Kind) {
3447 case llvm::BitstreamEntry::Error:
3448 case llvm::BitstreamEntry::EndBlock:
3451 case llvm::BitstreamEntry::Record:
3452 // Ignore top-level records.
3453 Cursor.skipRecord(Entry.ID);
3456 case llvm::BitstreamEntry::SubBlock:
3457 if (Entry.ID == BlockID) {
3458 if (Cursor.EnterSubBlock(BlockID))
3464 if (Cursor.SkipBlock())
3470 ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3472 SourceLocation ImportLoc,
3473 unsigned ClientLoadCapabilities) {
3474 llvm::SaveAndRestore<SourceLocation>
3475 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3477 // Defer any pending actions until we get to the end of reading the AST file.
3478 Deserializing AnASTFile(this);
3480 // Bump the generation number.
3481 unsigned PreviousGeneration = incrementGeneration(Context);
3483 unsigned NumModules = ModuleMgr.size();
3484 SmallVector<ImportedModule, 4> Loaded;
3485 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3486 /*ImportedBy=*/nullptr, Loaded,
3488 ClientLoadCapabilities)) {
3492 case VersionMismatch:
3493 case ConfigurationMismatch:
3495 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3496 for (const ImportedModule &IM : Loaded)
3497 LoadedSet.insert(IM.Mod);
3499 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3501 Context.getLangOpts().Modules
3502 ? &PP.getHeaderSearchInfo().getModuleMap()
3505 // If we find that any modules are unusable, the global index is going
3506 // to be out-of-date. Just remove it.
3507 GlobalIndex.reset();
3508 ModuleMgr.setGlobalIndex(nullptr);
3515 // Here comes stuff that we only do once the entire chain is loaded.
3517 // Load the AST blocks of all of the modules that we loaded.
3518 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3519 MEnd = Loaded.end();
3521 ModuleFile &F = *M->Mod;
3523 // Read the AST block.
3524 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3527 // Read the extension blocks.
3528 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3529 if (ASTReadResult Result = ReadExtensionBlock(F))
3533 // Once read, set the ModuleFile bit base offset and update the size in
3534 // bits of all files we've seen.
3535 F.GlobalBitOffset = TotalModulesSizeInBits;
3536 TotalModulesSizeInBits += F.SizeInBits;
3537 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3539 // Preload SLocEntries.
3540 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3541 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3542 // Load it through the SourceManager and don't call ReadSLocEntry()
3543 // directly because the entry may have already been loaded in which case
3544 // calling ReadSLocEntry() directly would trigger an assertion in
3546 SourceMgr.getLoadedSLocEntryByID(Index);
3549 // Preload all the pending interesting identifiers by marking them out of
3551 for (auto Offset : F.PreloadIdentifierOffsets) {
3552 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3553 F.IdentifierTableData + Offset);
3555 ASTIdentifierLookupTrait Trait(*this, F);
3556 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3557 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3558 auto &II = PP.getIdentifierTable().getOwn(Key);
3559 II.setOutOfDate(true);
3561 // Mark this identifier as being from an AST file so that we can track
3562 // whether we need to serialize it.
3563 if (!II.isFromAST()) {
3565 bool IsModule = PP.getCurrentModule() != nullptr;
3566 if (isInterestingIdentifier(*this, II, IsModule))
3567 II.setChangedSinceDeserialization();
3570 // Associate the ID with the identifier so that the writer can reuse it.
3571 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3572 SetIdentifierInfo(ID, &II);
3576 // Setup the import locations and notify the module manager that we've
3577 // committed to these module files.
3578 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3579 MEnd = Loaded.end();
3581 ModuleFile &F = *M->Mod;
3583 ModuleMgr.moduleFileAccepted(&F);
3585 // Set the import location.
3586 F.DirectImportLoc = ImportLoc;
3588 F.ImportLoc = M->ImportLoc;
3590 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3591 M->ImportLoc.getRawEncoding());
3594 if (!Context.getLangOpts().CPlusPlus ||
3595 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3596 // Mark all of the identifiers in the identifier table as being out of date,
3597 // so that various accessors know to check the loaded modules when the
3598 // identifier is used.
3600 // For C++ modules, we don't need information on many identifiers (just
3601 // those that provide macros or are poisoned), so we mark all of
3602 // the interesting ones via PreloadIdentifierOffsets.
3603 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3604 IdEnd = PP.getIdentifierTable().end();
3606 Id->second->setOutOfDate(true);
3609 // Resolve any unresolved module exports.
3610 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3611 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
3612 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3613 Module *ResolvedMod = getSubmodule(GlobalID);
3615 switch (Unresolved.Kind) {
3616 case UnresolvedModuleRef::Conflict:
3618 Module::Conflict Conflict;
3619 Conflict.Other = ResolvedMod;
3620 Conflict.Message = Unresolved.String.str();
3621 Unresolved.Mod->Conflicts.push_back(Conflict);
3625 case UnresolvedModuleRef::Import:
3627 Unresolved.Mod->Imports.insert(ResolvedMod);
3630 case UnresolvedModuleRef::Export:
3631 if (ResolvedMod || Unresolved.IsWildcard)
3632 Unresolved.Mod->Exports.push_back(
3633 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3637 UnresolvedModuleRefs.clear();
3639 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3640 // Might be unnecessary as use declarations are only used to build the
3643 InitializeContext();
3648 if (DeserializationListener)
3649 DeserializationListener->ReaderInitialized(this);
3651 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3652 if (PrimaryModule.OriginalSourceFileID.isValid()) {
3653 PrimaryModule.OriginalSourceFileID
3654 = FileID::get(PrimaryModule.SLocEntryBaseID
3655 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3657 // If this AST file is a precompiled preamble, then set the
3658 // preamble file ID of the source manager to the file source file
3659 // from which the preamble was built.
3660 if (Type == MK_Preamble) {
3661 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3662 } else if (Type == MK_MainFile) {
3663 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3667 // For any Objective-C class definitions we have already loaded, make sure
3668 // that we load any additional categories.
3669 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3670 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3671 ObjCClassesLoaded[I],
3672 PreviousGeneration);
3675 if (PP.getHeaderSearchInfo()
3676 .getHeaderSearchOpts()
3677 .ModulesValidateOncePerBuildSession) {
3678 // Now we are certain that the module and all modules it depends on are
3679 // up to date. Create or update timestamp files for modules that are
3680 // located in the module cache (not for PCH files that could be anywhere
3681 // in the filesystem).
3682 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3683 ImportedModule &M = Loaded[I];
3684 if (M.Mod->Kind == MK_ImplicitModule) {
3685 updateModuleTimestamp(*M.Mod);
3693 static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3695 /// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3696 static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3697 return Stream.Read(8) == 'C' &&
3698 Stream.Read(8) == 'P' &&
3699 Stream.Read(8) == 'C' &&
3700 Stream.Read(8) == 'H';
3703 static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3707 case MK_ImplicitModule:
3708 case MK_ExplicitModule:
3712 return 2; // main source file
3714 llvm_unreachable("unknown module kind");
3717 ASTReader::ASTReadResult
3718 ASTReader::ReadASTCore(StringRef FileName,
3720 SourceLocation ImportLoc,
3721 ModuleFile *ImportedBy,
3722 SmallVectorImpl<ImportedModule> &Loaded,
3723 off_t ExpectedSize, time_t ExpectedModTime,
3724 ASTFileSignature ExpectedSignature,
3725 unsigned ClientLoadCapabilities) {
3727 std::string ErrorStr;
3728 ModuleManager::AddModuleResult AddResult
3729 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3730 getGeneration(), ExpectedSize, ExpectedModTime,
3731 ExpectedSignature, readASTFileSignature,
3734 switch (AddResult) {
3735 case ModuleManager::AlreadyLoaded:
3738 case ModuleManager::NewlyLoaded:
3739 // Load module file below.
3742 case ModuleManager::Missing:
3743 // The module file was missing; if the client can handle that, return
3745 if (ClientLoadCapabilities & ARR_Missing)
3748 // Otherwise, return an error.
3749 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3750 << FileName << ErrorStr.empty()
3754 case ModuleManager::OutOfDate:
3755 // We couldn't load the module file because it is out-of-date. If the
3756 // client can handle out-of-date, return it.
3757 if (ClientLoadCapabilities & ARR_OutOfDate)
3760 // Otherwise, return an error.
3761 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3762 << FileName << ErrorStr.empty()
3767 assert(M && "Missing module file");
3769 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3771 if (FileName != "-") {
3772 CurrentDir = llvm::sys::path::parent_path(FileName);
3773 if (CurrentDir.empty()) CurrentDir = ".";
3777 BitstreamCursor &Stream = F.Stream;
3778 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
3779 Stream.init(&F.StreamFile);
3780 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3782 // Sniff for the signature.
3783 if (!startsWithASTFileMagic(Stream)) {
3784 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3789 // This is used for compatibility with older PCH formats.
3790 bool HaveReadControlBlock = false;
3792 llvm::BitstreamEntry Entry = Stream.advance();
3794 switch (Entry.Kind) {
3795 case llvm::BitstreamEntry::Error:
3796 case llvm::BitstreamEntry::Record:
3797 case llvm::BitstreamEntry::EndBlock:
3798 Error("invalid record at top-level of AST file");
3801 case llvm::BitstreamEntry::SubBlock:
3806 case CONTROL_BLOCK_ID:
3807 HaveReadControlBlock = true;
3808 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
3810 // Check that we didn't try to load a non-module AST file as a module.
3812 // FIXME: Should we also perform the converse check? Loading a module as
3813 // a PCH file sort of works, but it's a bit wonky.
3814 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3815 F.ModuleName.empty()) {
3816 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3817 if (Result != OutOfDate ||
3818 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3819 Diag(diag::err_module_file_not_module) << FileName;
3824 case Failure: return Failure;
3825 case Missing: return Missing;
3826 case OutOfDate: return OutOfDate;
3827 case VersionMismatch: return VersionMismatch;
3828 case ConfigurationMismatch: return ConfigurationMismatch;
3829 case HadErrors: return HadErrors;
3834 if (!HaveReadControlBlock) {
3835 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3836 Diag(diag::err_pch_version_too_old);
3837 return VersionMismatch;
3840 // Record that we've loaded this module.
3841 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3845 if (Stream.SkipBlock()) {
3846 Error("malformed block record in AST file");
3856 /// Parse a record and blob containing module file extension metadata.
3857 static bool parseModuleFileExtensionMetadata(
3858 const SmallVectorImpl<uint64_t> &Record,
3860 ModuleFileExtensionMetadata &Metadata) {
3861 if (Record.size() < 4) return true;
3863 Metadata.MajorVersion = Record[0];
3864 Metadata.MinorVersion = Record[1];
3866 unsigned BlockNameLen = Record[2];
3867 unsigned UserInfoLen = Record[3];
3869 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
3871 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
3872 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
3873 Blob.data() + BlockNameLen + UserInfoLen);
3877 ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
3878 BitstreamCursor &Stream = F.Stream;
3882 llvm::BitstreamEntry Entry = Stream.advance();
3883 switch (Entry.Kind) {
3884 case llvm::BitstreamEntry::SubBlock:
3885 if (Stream.SkipBlock())
3890 case llvm::BitstreamEntry::EndBlock:
3893 case llvm::BitstreamEntry::Error:
3896 case llvm::BitstreamEntry::Record:
3902 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
3904 case EXTENSION_METADATA: {
3905 ModuleFileExtensionMetadata Metadata;
3906 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
3909 // Find a module file extension with this block name.
3910 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
3911 if (Known == ModuleFileExtensions.end()) break;
3914 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
3916 F.ExtensionReaders.push_back(std::move(Reader));
3927 void ASTReader::InitializeContext() {
3928 // If there's a listener, notify them that we "read" the translation unit.
3929 if (DeserializationListener)
3930 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3931 Context.getTranslationUnitDecl());
3933 // FIXME: Find a better way to deal with collisions between these
3934 // built-in types. Right now, we just ignore the problem.
3936 // Load the special types.
3937 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3938 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3939 if (!Context.CFConstantStringTypeDecl)
3940 Context.setCFConstantStringType(GetType(String));
3943 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3944 QualType FileType = GetType(File);
3945 if (FileType.isNull()) {
3946 Error("FILE type is NULL");
3950 if (!Context.FILEDecl) {
3951 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3952 Context.setFILEDecl(Typedef->getDecl());
3954 const TagType *Tag = FileType->getAs<TagType>();
3956 Error("Invalid FILE type in AST file");
3959 Context.setFILEDecl(Tag->getDecl());
3964 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3965 QualType Jmp_bufType = GetType(Jmp_buf);
3966 if (Jmp_bufType.isNull()) {
3967 Error("jmp_buf type is NULL");
3971 if (!Context.jmp_bufDecl) {
3972 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3973 Context.setjmp_bufDecl(Typedef->getDecl());
3975 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3977 Error("Invalid jmp_buf type in AST file");
3980 Context.setjmp_bufDecl(Tag->getDecl());
3985 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3986 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3987 if (Sigjmp_bufType.isNull()) {
3988 Error("sigjmp_buf type is NULL");
3992 if (!Context.sigjmp_bufDecl) {
3993 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3994 Context.setsigjmp_bufDecl(Typedef->getDecl());
3996 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3997 assert(Tag && "Invalid sigjmp_buf type in AST file");
3998 Context.setsigjmp_bufDecl(Tag->getDecl());
4003 if (unsigned ObjCIdRedef
4004 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4005 if (Context.ObjCIdRedefinitionType.isNull())
4006 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4009 if (unsigned ObjCClassRedef
4010 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4011 if (Context.ObjCClassRedefinitionType.isNull())
4012 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4015 if (unsigned ObjCSelRedef
4016 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4017 if (Context.ObjCSelRedefinitionType.isNull())
4018 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4021 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4022 QualType Ucontext_tType = GetType(Ucontext_t);
4023 if (Ucontext_tType.isNull()) {
4024 Error("ucontext_t type is NULL");
4028 if (!Context.ucontext_tDecl) {
4029 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4030 Context.setucontext_tDecl(Typedef->getDecl());
4032 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4033 assert(Tag && "Invalid ucontext_t type in AST file");
4034 Context.setucontext_tDecl(Tag->getDecl());
4040 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4042 // If there were any CUDA special declarations, deserialize them.
4043 if (!CUDASpecialDeclRefs.empty()) {
4044 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4045 Context.setcudaConfigureCallDecl(
4046 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4049 // Re-export any modules that were imported by a non-module AST file.
4050 // FIXME: This does not make macro-only imports visible again.
4051 for (auto &Import : ImportedModules) {
4052 if (Module *Imported = getSubmodule(Import.ID)) {
4053 makeModuleVisible(Imported, Module::AllVisible,
4054 /*ImportLoc=*/Import.ImportLoc);
4055 PP.makeModuleVisible(Imported, Import.ImportLoc);
4058 ImportedModules.clear();
4061 void ASTReader::finalizeForWriting() {
4062 // Nothing to do for now.
4065 /// \brief Reads and return the signature record from \p StreamFile's control
4066 /// block, or else returns 0.
4067 static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4068 BitstreamCursor Stream(StreamFile);
4069 if (!startsWithASTFileMagic(Stream))
4072 // Scan for the CONTROL_BLOCK_ID block.
4073 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4076 // Scan for SIGNATURE inside the control block.
4077 ASTReader::RecordData Record;
4079 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4080 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4081 Entry.Kind != llvm::BitstreamEntry::Record)
4086 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4091 /// \brief Retrieve the name of the original source file name
4092 /// directly from the AST file, without actually loading the AST
4094 std::string ASTReader::getOriginalSourceFile(
4095 const std::string &ASTFileName, FileManager &FileMgr,
4096 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
4097 // Open the AST file.
4098 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
4100 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4101 << ASTFileName << Buffer.getError().message();
4102 return std::string();
4105 // Initialize the stream
4106 llvm::BitstreamReader StreamFile;
4107 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
4108 BitstreamCursor Stream(StreamFile);
4110 // Sniff for the signature.
4111 if (!startsWithASTFileMagic(Stream)) {
4112 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4113 return std::string();
4116 // Scan for the CONTROL_BLOCK_ID block.
4117 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
4118 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4119 return std::string();
4122 // Scan for ORIGINAL_FILE inside the control block.
4125 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4126 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4127 return std::string();
4129 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4130 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4131 return std::string();
4136 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4142 class SimplePCHValidator : public ASTReaderListener {
4143 const LangOptions &ExistingLangOpts;
4144 const TargetOptions &ExistingTargetOpts;
4145 const PreprocessorOptions &ExistingPPOpts;
4146 std::string ExistingModuleCachePath;
4147 FileManager &FileMgr;
4150 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4151 const TargetOptions &ExistingTargetOpts,
4152 const PreprocessorOptions &ExistingPPOpts,
4153 StringRef ExistingModuleCachePath,
4154 FileManager &FileMgr)
4155 : ExistingLangOpts(ExistingLangOpts),
4156 ExistingTargetOpts(ExistingTargetOpts),
4157 ExistingPPOpts(ExistingPPOpts),
4158 ExistingModuleCachePath(ExistingModuleCachePath),
4163 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4164 bool AllowCompatibleDifferences) override {
4165 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4166 AllowCompatibleDifferences);
4168 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4169 bool AllowCompatibleDifferences) override {
4170 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4171 AllowCompatibleDifferences);
4173 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4174 StringRef SpecificModuleCachePath,
4175 bool Complain) override {
4176 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4177 ExistingModuleCachePath,
4178 nullptr, ExistingLangOpts);
4180 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4182 std::string &SuggestedPredefines) override {
4183 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
4184 SuggestedPredefines, ExistingLangOpts);
4189 bool ASTReader::readASTFileControlBlock(
4190 StringRef Filename, FileManager &FileMgr,
4191 const PCHContainerReader &PCHContainerRdr,
4192 bool FindModuleFileExtensions,
4193 ASTReaderListener &Listener) {
4194 // Open the AST file.
4195 // FIXME: This allows use of the VFS; we do not allow use of the
4196 // VFS when actually loading a module.
4197 auto Buffer = FileMgr.getBufferForFile(Filename);
4202 // Initialize the stream
4203 llvm::BitstreamReader StreamFile;
4204 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
4205 BitstreamCursor Stream(StreamFile);
4207 // Sniff for the signature.
4208 if (!startsWithASTFileMagic(Stream))
4211 // Scan for the CONTROL_BLOCK_ID block.
4212 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4215 bool NeedsInputFiles = Listener.needsInputFileVisitation();
4216 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
4217 bool NeedsImports = Listener.needsImportVisitation();
4218 BitstreamCursor InputFilesCursor;
4221 std::string ModuleDir;
4222 bool DoneWithControlBlock = false;
4223 while (!DoneWithControlBlock) {
4224 llvm::BitstreamEntry Entry = Stream.advance();
4226 switch (Entry.Kind) {
4227 case llvm::BitstreamEntry::SubBlock: {
4229 case OPTIONS_BLOCK_ID: {
4230 std::string IgnoredSuggestedPredefines;
4231 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4232 /*AllowCompatibleConfigurationMismatch*/ false,
4233 Listener, IgnoredSuggestedPredefines) != Success)
4238 case INPUT_FILES_BLOCK_ID:
4239 InputFilesCursor = Stream;
4240 if (Stream.SkipBlock() ||
4242 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4247 if (Stream.SkipBlock())
4255 case llvm::BitstreamEntry::EndBlock:
4256 DoneWithControlBlock = true;
4259 case llvm::BitstreamEntry::Error:
4262 case llvm::BitstreamEntry::Record:
4266 if (DoneWithControlBlock) break;
4270 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4271 switch ((ControlRecordTypes)RecCode) {
4273 if (Record[0] != VERSION_MAJOR)
4276 if (Listener.ReadFullVersionInformation(Blob))
4282 Listener.ReadModuleName(Blob);
4284 case MODULE_DIRECTORY:
4287 case MODULE_MAP_FILE: {
4289 auto Path = ReadString(Record, Idx);
4290 ResolveImportedPath(Path, ModuleDir);
4291 Listener.ReadModuleMapFile(Path);
4294 case INPUT_FILE_OFFSETS: {
4295 if (!NeedsInputFiles)
4298 unsigned NumInputFiles = Record[0];
4299 unsigned NumUserFiles = Record[1];
4300 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
4301 for (unsigned I = 0; I != NumInputFiles; ++I) {
4302 // Go find this input file.
4303 bool isSystemFile = I >= NumUserFiles;
4305 if (isSystemFile && !NeedsSystemInputFiles)
4306 break; // the rest are system input files
4308 BitstreamCursor &Cursor = InputFilesCursor;
4309 SavedStreamPosition SavedPosition(Cursor);
4310 Cursor.JumpToBit(InputFileOffs[I]);
4312 unsigned Code = Cursor.ReadCode();
4315 bool shouldContinue = false;
4316 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4318 bool Overridden = static_cast<bool>(Record[3]);
4319 std::string Filename = Blob;
4320 ResolveImportedPath(Filename, ModuleDir);
4321 shouldContinue = Listener.visitInputFile(
4322 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
4325 if (!shouldContinue)
4335 unsigned Idx = 0, N = Record.size();
4337 // Read information about the AST file.
4338 Idx += 5; // ImportLoc, Size, ModTime, Signature
4339 std::string Filename = ReadString(Record, Idx);
4340 ResolveImportedPath(Filename, ModuleDir);
4341 Listener.visitImport(Filename);
4347 // No other validation to perform.
4352 // Look for module file extension blocks, if requested.
4353 if (FindModuleFileExtensions) {
4354 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4355 bool DoneWithExtensionBlock = false;
4356 while (!DoneWithExtensionBlock) {
4357 llvm::BitstreamEntry Entry = Stream.advance();
4359 switch (Entry.Kind) {
4360 case llvm::BitstreamEntry::SubBlock:
4361 if (Stream.SkipBlock())
4366 case llvm::BitstreamEntry::EndBlock:
4367 DoneWithExtensionBlock = true;
4370 case llvm::BitstreamEntry::Error:
4373 case llvm::BitstreamEntry::Record:
4379 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4381 case EXTENSION_METADATA: {
4382 ModuleFileExtensionMetadata Metadata;
4383 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4386 Listener.readModuleFileExtension(Metadata);
4397 bool ASTReader::isAcceptableASTFile(
4398 StringRef Filename, FileManager &FileMgr,
4399 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
4400 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4401 std::string ExistingModuleCachePath) {
4402 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4403 ExistingModuleCachePath, FileMgr);
4404 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
4405 /*FindModuleFileExtensions=*/false,
4409 ASTReader::ASTReadResult
4410 ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
4411 // Enter the submodule block.
4412 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4413 Error("malformed submodule block record in AST file");
4417 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4419 Module *CurrentModule = nullptr;
4422 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4424 switch (Entry.Kind) {
4425 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4426 case llvm::BitstreamEntry::Error:
4427 Error("malformed block record in AST file");
4429 case llvm::BitstreamEntry::EndBlock:
4431 case llvm::BitstreamEntry::Record:
4432 // The interesting case.
4439 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4441 if ((Kind == SUBMODULE_METADATA) != First) {
4442 Error("submodule metadata record should be at beginning of block");
4447 // Submodule information is only valid if we have a current module.
4448 // FIXME: Should we error on these cases?
4449 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4450 Kind != SUBMODULE_DEFINITION)
4454 default: // Default behavior: ignore.
4457 case SUBMODULE_DEFINITION: {
4458 if (Record.size() < 8) {
4459 Error("malformed module definition");
4463 StringRef Name = Blob;
4465 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4466 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4467 bool IsFramework = Record[Idx++];
4468 bool IsExplicit = Record[Idx++];
4469 bool IsSystem = Record[Idx++];
4470 bool IsExternC = Record[Idx++];
4471 bool InferSubmodules = Record[Idx++];
4472 bool InferExplicitSubmodules = Record[Idx++];
4473 bool InferExportWildcard = Record[Idx++];
4474 bool ConfigMacrosExhaustive = Record[Idx++];
4476 Module *ParentModule = nullptr;
4478 ParentModule = getSubmodule(Parent);
4480 // Retrieve this (sub)module from the module map, creating it if
4482 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
4485 // FIXME: set the definition loc for CurrentModule, or call
4486 // ModMap.setInferredModuleAllowedBy()
4488 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4489 if (GlobalIndex >= SubmodulesLoaded.size() ||
4490 SubmodulesLoaded[GlobalIndex]) {
4491 Error("too many submodules");
4495 if (!ParentModule) {
4496 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4497 if (CurFile != F.File) {
4498 if (!Diags.isDiagnosticInFlight()) {
4499 Diag(diag::err_module_file_conflict)
4500 << CurrentModule->getTopLevelModuleName()
4501 << CurFile->getName()
4502 << F.File->getName();
4508 CurrentModule->setASTFile(F.File);
4511 CurrentModule->Signature = F.Signature;
4512 CurrentModule->IsFromModuleFile = true;
4513 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
4514 CurrentModule->IsExternC = IsExternC;
4515 CurrentModule->InferSubmodules = InferSubmodules;
4516 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4517 CurrentModule->InferExportWildcard = InferExportWildcard;
4518 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
4519 if (DeserializationListener)
4520 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4522 SubmodulesLoaded[GlobalIndex] = CurrentModule;
4524 // Clear out data that will be replaced by what is the module file.
4525 CurrentModule->LinkLibraries.clear();
4526 CurrentModule->ConfigMacros.clear();
4527 CurrentModule->UnresolvedConflicts.clear();
4528 CurrentModule->Conflicts.clear();
4532 case SUBMODULE_UMBRELLA_HEADER: {
4533 std::string Filename = Blob;
4534 ResolveImportedPath(F, Filename);
4535 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
4536 if (!CurrentModule->getUmbrellaHeader())
4537 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4538 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
4539 // This can be a spurious difference caused by changing the VFS to
4540 // point to a different copy of the file, and it is too late to
4541 // to rebuild safely.
4542 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4543 // after input file validation only real problems would remain and we
4544 // could just error. For now, assume it's okay.
4551 case SUBMODULE_HEADER:
4552 case SUBMODULE_EXCLUDED_HEADER:
4553 case SUBMODULE_PRIVATE_HEADER:
4554 // We lazily associate headers with their modules via the HeaderInfo table.
4555 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4556 // of complete filenames or remove it entirely.
4559 case SUBMODULE_TEXTUAL_HEADER:
4560 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4561 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4565 case SUBMODULE_TOPHEADER: {
4566 CurrentModule->addTopHeaderFilename(Blob);
4570 case SUBMODULE_UMBRELLA_DIR: {
4571 std::string Dirname = Blob;
4572 ResolveImportedPath(F, Dirname);
4573 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
4574 if (!CurrentModule->getUmbrellaDir())
4575 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4576 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
4577 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4578 Error("mismatched umbrella directories in submodule");
4585 case SUBMODULE_METADATA: {
4586 F.BaseSubmoduleID = getTotalNumSubmodules();
4587 F.LocalNumSubmodules = Record[0];
4588 unsigned LocalBaseSubmoduleID = Record[1];
4589 if (F.LocalNumSubmodules > 0) {
4590 // Introduce the global -> local mapping for submodules within this
4592 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4594 // Introduce the local -> global mapping for submodules within this
4596 F.SubmoduleRemap.insertOrReplace(
4597 std::make_pair(LocalBaseSubmoduleID,
4598 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4600 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4605 case SUBMODULE_IMPORTS: {
4606 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
4607 UnresolvedModuleRef Unresolved;
4608 Unresolved.File = &F;
4609 Unresolved.Mod = CurrentModule;
4610 Unresolved.ID = Record[Idx];
4611 Unresolved.Kind = UnresolvedModuleRef::Import;
4612 Unresolved.IsWildcard = false;
4613 UnresolvedModuleRefs.push_back(Unresolved);
4618 case SUBMODULE_EXPORTS: {
4619 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
4620 UnresolvedModuleRef Unresolved;
4621 Unresolved.File = &F;
4622 Unresolved.Mod = CurrentModule;
4623 Unresolved.ID = Record[Idx];
4624 Unresolved.Kind = UnresolvedModuleRef::Export;
4625 Unresolved.IsWildcard = Record[Idx + 1];
4626 UnresolvedModuleRefs.push_back(Unresolved);
4629 // Once we've loaded the set of exports, there's no reason to keep
4630 // the parsed, unresolved exports around.
4631 CurrentModule->UnresolvedExports.clear();
4634 case SUBMODULE_REQUIRES: {
4635 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
4636 Context.getTargetInfo());
4640 case SUBMODULE_LINK_LIBRARY:
4641 CurrentModule->LinkLibraries.push_back(
4642 Module::LinkLibrary(Blob, Record[0]));
4645 case SUBMODULE_CONFIG_MACRO:
4646 CurrentModule->ConfigMacros.push_back(Blob.str());
4649 case SUBMODULE_CONFLICT: {
4650 UnresolvedModuleRef Unresolved;
4651 Unresolved.File = &F;
4652 Unresolved.Mod = CurrentModule;
4653 Unresolved.ID = Record[0];
4654 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4655 Unresolved.IsWildcard = false;
4656 Unresolved.String = Blob;
4657 UnresolvedModuleRefs.push_back(Unresolved);
4664 /// \brief Parse the record that corresponds to a LangOptions data
4667 /// This routine parses the language options from the AST file and then gives
4668 /// them to the AST listener if one is set.
4670 /// \returns true if the listener deems the file unacceptable, false otherwise.
4671 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4673 ASTReaderListener &Listener,
4674 bool AllowCompatibleDifferences) {
4675 LangOptions LangOpts;
4677 #define LANGOPT(Name, Bits, Default, Description) \
4678 LangOpts.Name = Record[Idx++];
4679 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4680 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4681 #include "clang/Basic/LangOptions.def"
4682 #define SANITIZER(NAME, ID) \
4683 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
4684 #include "clang/Basic/Sanitizers.def"
4686 for (unsigned N = Record[Idx++]; N; --N)
4687 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4689 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4690 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4691 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4693 LangOpts.CurrentModule = ReadString(Record, Idx);
4696 for (unsigned N = Record[Idx++]; N; --N) {
4697 LangOpts.CommentOpts.BlockCommandNames.push_back(
4698 ReadString(Record, Idx));
4700 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
4702 return Listener.ReadLanguageOptions(LangOpts, Complain,
4703 AllowCompatibleDifferences);
4706 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4707 ASTReaderListener &Listener,
4708 bool AllowCompatibleDifferences) {
4710 TargetOptions TargetOpts;
4711 TargetOpts.Triple = ReadString(Record, Idx);
4712 TargetOpts.CPU = ReadString(Record, Idx);
4713 TargetOpts.ABI = ReadString(Record, Idx);
4714 for (unsigned N = Record[Idx++]; N; --N) {
4715 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4717 for (unsigned N = Record[Idx++]; N; --N) {
4718 TargetOpts.Features.push_back(ReadString(Record, Idx));
4721 return Listener.ReadTargetOptions(TargetOpts, Complain,
4722 AllowCompatibleDifferences);
4725 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4726 ASTReaderListener &Listener) {
4727 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
4729 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
4730 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4731 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
4732 #include "clang/Basic/DiagnosticOptions.def"
4734 for (unsigned N = Record[Idx++]; N; --N)
4735 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
4736 for (unsigned N = Record[Idx++]; N; --N)
4737 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
4739 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4742 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4743 ASTReaderListener &Listener) {
4744 FileSystemOptions FSOpts;
4746 FSOpts.WorkingDir = ReadString(Record, Idx);
4747 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4750 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4752 ASTReaderListener &Listener) {
4753 HeaderSearchOptions HSOpts;
4755 HSOpts.Sysroot = ReadString(Record, Idx);
4758 for (unsigned N = Record[Idx++]; N; --N) {
4759 std::string Path = ReadString(Record, Idx);
4760 frontend::IncludeDirGroup Group
4761 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
4762 bool IsFramework = Record[Idx++];
4763 bool IgnoreSysRoot = Record[Idx++];
4764 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4768 // System header prefixes.
4769 for (unsigned N = Record[Idx++]; N; --N) {
4770 std::string Prefix = ReadString(Record, Idx);
4771 bool IsSystemHeader = Record[Idx++];
4772 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
4775 HSOpts.ResourceDir = ReadString(Record, Idx);
4776 HSOpts.ModuleCachePath = ReadString(Record, Idx);
4777 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
4778 HSOpts.DisableModuleHash = Record[Idx++];
4779 HSOpts.UseBuiltinIncludes = Record[Idx++];
4780 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4781 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4782 HSOpts.UseLibcxx = Record[Idx++];
4783 std::string SpecificModuleCachePath = ReadString(Record, Idx);
4785 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4789 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4791 ASTReaderListener &Listener,
4792 std::string &SuggestedPredefines) {
4793 PreprocessorOptions PPOpts;
4796 // Macro definitions/undefs
4797 for (unsigned N = Record[Idx++]; N; --N) {
4798 std::string Macro = ReadString(Record, Idx);
4799 bool IsUndef = Record[Idx++];
4800 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4804 for (unsigned N = Record[Idx++]; N; --N) {
4805 PPOpts.Includes.push_back(ReadString(Record, Idx));
4809 for (unsigned N = Record[Idx++]; N; --N) {
4810 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4813 PPOpts.UsePredefines = Record[Idx++];
4814 PPOpts.DetailedRecord = Record[Idx++];
4815 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4816 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4817 PPOpts.ObjCXXARCStandardLibrary =
4818 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4819 SuggestedPredefines.clear();
4820 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4821 SuggestedPredefines);
4824 std::pair<ModuleFile *, unsigned>
4825 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4826 GlobalPreprocessedEntityMapType::iterator
4827 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4828 assert(I != GlobalPreprocessedEntityMap.end() &&
4829 "Corrupted global preprocessed entity map");
4830 ModuleFile *M = I->second;
4831 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4832 return std::make_pair(M, LocalIndex);
4835 llvm::iterator_range<PreprocessingRecord::iterator>
4836 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4837 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4838 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4839 Mod.NumPreprocessedEntities);
4841 return llvm::make_range(PreprocessingRecord::iterator(),
4842 PreprocessingRecord::iterator());
4845 llvm::iterator_range<ASTReader::ModuleDeclIterator>
4846 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4847 return llvm::make_range(
4848 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4849 ModuleDeclIterator(this, &Mod,
4850 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4853 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4854 PreprocessedEntityID PPID = Index+1;
4855 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4856 ModuleFile &M = *PPInfo.first;
4857 unsigned LocalIndex = PPInfo.second;
4858 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4860 if (!PP.getPreprocessingRecord()) {
4861 Error("no preprocessing record");
4865 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4866 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4868 llvm::BitstreamEntry Entry =
4869 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4870 if (Entry.Kind != llvm::BitstreamEntry::Record)
4874 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4875 ReadSourceLocation(M, PPOffs.End));
4876 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
4879 PreprocessorDetailRecordTypes RecType =
4880 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4881 Entry.ID, Record, &Blob);
4883 case PPD_MACRO_EXPANSION: {
4884 bool isBuiltin = Record[0];
4885 IdentifierInfo *Name = nullptr;
4886 MacroDefinitionRecord *Def = nullptr;
4888 Name = getLocalIdentifier(M, Record[1]);
4890 PreprocessedEntityID GlobalID =
4891 getGlobalPreprocessedEntityID(M, Record[1]);
4892 Def = cast<MacroDefinitionRecord>(
4893 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
4898 ME = new (PPRec) MacroExpansion(Name, Range);
4900 ME = new (PPRec) MacroExpansion(Def, Range);
4905 case PPD_MACRO_DEFINITION: {
4906 // Decode the identifier info and then check again; if the macro is
4907 // still defined and associated with the identifier,
4908 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4909 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
4911 if (DeserializationListener)
4912 DeserializationListener->MacroDefinitionRead(PPID, MD);
4917 case PPD_INCLUSION_DIRECTIVE: {
4918 const char *FullFileNameStart = Blob.data() + Record[0];
4919 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
4920 const FileEntry *File = nullptr;
4921 if (!FullFileName.empty())
4922 File = PP.getFileManager().getFile(FullFileName);
4924 // FIXME: Stable encoding
4925 InclusionDirective::InclusionKind Kind
4926 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4927 InclusionDirective *ID
4928 = new (PPRec) InclusionDirective(PPRec, Kind,
4929 StringRef(Blob.data(), Record[0]),
4930 Record[1], Record[3],
4937 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4940 /// \brief \arg SLocMapI points at a chunk of a module that contains no
4941 /// preprocessed entities or the entities it contains are not the ones we are
4942 /// looking for. Find the next module that contains entities and return the ID
4943 /// of the first entry.
4944 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4945 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4947 for (GlobalSLocOffsetMapType::const_iterator
4948 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4949 ModuleFile &M = *SLocMapI->second;
4950 if (M.NumPreprocessedEntities)
4951 return M.BasePreprocessedEntityID;
4954 return getTotalNumPreprocessedEntities();
4959 template <unsigned PPEntityOffset::*PPLoc>
4960 struct PPEntityComp {
4961 const ASTReader &Reader;
4964 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4966 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4967 SourceLocation LHS = getLoc(L);
4968 SourceLocation RHS = getLoc(R);
4969 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4972 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4973 SourceLocation LHS = getLoc(L);
4974 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4977 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4978 SourceLocation RHS = getLoc(R);
4979 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4982 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4983 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4989 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4990 bool EndsAfter) const {
4991 if (SourceMgr.isLocalSourceLocation(Loc))
4992 return getTotalNumPreprocessedEntities();
4994 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4995 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
4996 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4997 "Corrupted global sloc offset map");
4999 if (SLocMapI->second->NumPreprocessedEntities == 0)
5000 return findNextPreprocessedEntity(SLocMapI);
5002 ModuleFile &M = *SLocMapI->second;
5003 typedef const PPEntityOffset *pp_iterator;
5004 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5005 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5007 size_t Count = M.NumPreprocessedEntities;
5009 pp_iterator First = pp_begin;
5013 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5014 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
5016 // Do a binary search manually instead of using std::lower_bound because
5017 // The end locations of entities may be unordered (when a macro expansion
5018 // is inside another macro argument), but for this case it is not important
5019 // whether we get the first macro expansion or its containing macro.
5023 std::advance(PPI, Half);
5024 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
5028 Count = Count - Half - 1;
5035 return findNextPreprocessedEntity(SLocMapI);
5037 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5040 /// \brief Returns a pair of [Begin, End) indices of preallocated
5041 /// preprocessed entities that \arg Range encompasses.
5042 std::pair<unsigned, unsigned>
5043 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5044 if (Range.isInvalid())
5045 return std::make_pair(0,0);
5046 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5048 PreprocessedEntityID BeginID =
5049 findPreprocessedEntity(Range.getBegin(), false);
5050 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
5051 return std::make_pair(BeginID, EndID);
5054 /// \brief Optionally returns true or false if the preallocated preprocessed
5055 /// entity with index \arg Index came from file \arg FID.
5056 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
5058 if (FID.isInvalid())
5061 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5062 ModuleFile &M = *PPInfo.first;
5063 unsigned LocalIndex = PPInfo.second;
5064 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5066 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5067 if (Loc.isInvalid())
5070 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5077 /// \brief Visitor used to search for information about a header file.
5078 class HeaderFileInfoVisitor {
5079 const FileEntry *FE;
5081 Optional<HeaderFileInfo> HFI;
5084 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5087 bool operator()(ModuleFile &M) {
5088 HeaderFileInfoLookupTable *Table
5089 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5093 // Look in the on-disk hash table for an entry for this file name.
5094 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
5095 if (Pos == Table->end())
5102 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
5106 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
5107 HeaderFileInfoVisitor Visitor(FE);
5108 ModuleMgr.visit(Visitor);
5109 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
5112 return HeaderFileInfo();
5115 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5116 // FIXME: Make it work properly with modules.
5117 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
5118 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5119 ModuleFile &F = *(*I);
5122 assert(!Diag.DiagStates.empty());
5123 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5124 while (Idx < F.PragmaDiagMappings.size()) {
5125 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5126 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5127 if (DiagStateID != 0) {
5128 Diag.DiagStatePoints.push_back(
5129 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5130 FullSourceLoc(Loc, SourceMgr)));
5134 assert(DiagStateID == 0);
5135 // A new DiagState was created here.
5136 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5137 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5138 DiagStates.push_back(NewState);
5139 Diag.DiagStatePoints.push_back(
5140 DiagnosticsEngine::DiagStatePoint(NewState,
5141 FullSourceLoc(Loc, SourceMgr)));
5143 assert(Idx < F.PragmaDiagMappings.size() &&
5144 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5145 if (Idx >= F.PragmaDiagMappings.size()) {
5146 break; // Something is messed up but at least avoid infinite loop in
5149 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5150 if (DiagID == (unsigned)-1) {
5151 break; // no more diag/map pairs for this location.
5153 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5154 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5155 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
5161 /// \brief Get the correct cursor and offset for loading a type.
5162 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5163 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5164 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5165 ModuleFile *M = I->second;
5166 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5169 /// \brief Read and return the type with the given index..
5171 /// The index is the type ID, shifted and minus the number of predefs. This
5172 /// routine actually reads the record corresponding to the type at the given
5173 /// location. It is a helper routine for GetType, which deals with reading type
5175 QualType ASTReader::readTypeRecord(unsigned Index) {
5176 RecordLocation Loc = TypeCursorForIndex(Index);
5177 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
5179 // Keep track of where we are in the stream, then jump back there
5180 // after reading this type.
5181 SavedStreamPosition SavedPosition(DeclsCursor);
5183 ReadingKindTracker ReadingKind(Read_Type, *this);
5185 // Note that we are loading a type record.
5186 Deserializing AType(this);
5189 DeclsCursor.JumpToBit(Loc.Offset);
5191 unsigned Code = DeclsCursor.ReadCode();
5192 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
5193 case TYPE_EXT_QUAL: {
5194 if (Record.size() != 2) {
5195 Error("Incorrect encoding of extended qualifier type");
5198 QualType Base = readType(*Loc.F, Record, Idx);
5199 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5200 return Context.getQualifiedType(Base, Quals);
5203 case TYPE_COMPLEX: {
5204 if (Record.size() != 1) {
5205 Error("Incorrect encoding of complex type");
5208 QualType ElemType = readType(*Loc.F, Record, Idx);
5209 return Context.getComplexType(ElemType);
5212 case TYPE_POINTER: {
5213 if (Record.size() != 1) {
5214 Error("Incorrect encoding of pointer type");
5217 QualType PointeeType = readType(*Loc.F, Record, Idx);
5218 return Context.getPointerType(PointeeType);
5221 case TYPE_DECAYED: {
5222 if (Record.size() != 1) {
5223 Error("Incorrect encoding of decayed type");
5226 QualType OriginalType = readType(*Loc.F, Record, Idx);
5227 QualType DT = Context.getAdjustedParameterType(OriginalType);
5228 if (!isa<DecayedType>(DT))
5229 Error("Decayed type does not decay");
5233 case TYPE_ADJUSTED: {
5234 if (Record.size() != 2) {
5235 Error("Incorrect encoding of adjusted type");
5238 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5239 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5240 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5243 case TYPE_BLOCK_POINTER: {
5244 if (Record.size() != 1) {
5245 Error("Incorrect encoding of block pointer type");
5248 QualType PointeeType = readType(*Loc.F, Record, Idx);
5249 return Context.getBlockPointerType(PointeeType);
5252 case TYPE_LVALUE_REFERENCE: {
5253 if (Record.size() != 2) {
5254 Error("Incorrect encoding of lvalue reference type");
5257 QualType PointeeType = readType(*Loc.F, Record, Idx);
5258 return Context.getLValueReferenceType(PointeeType, Record[1]);
5261 case TYPE_RVALUE_REFERENCE: {
5262 if (Record.size() != 1) {
5263 Error("Incorrect encoding of rvalue reference type");
5266 QualType PointeeType = readType(*Loc.F, Record, Idx);
5267 return Context.getRValueReferenceType(PointeeType);
5270 case TYPE_MEMBER_POINTER: {
5271 if (Record.size() != 2) {
5272 Error("Incorrect encoding of member pointer type");
5275 QualType PointeeType = readType(*Loc.F, Record, Idx);
5276 QualType ClassType = readType(*Loc.F, Record, Idx);
5277 if (PointeeType.isNull() || ClassType.isNull())
5280 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5283 case TYPE_CONSTANT_ARRAY: {
5284 QualType ElementType = readType(*Loc.F, Record, Idx);
5285 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5286 unsigned IndexTypeQuals = Record[2];
5288 llvm::APInt Size = ReadAPInt(Record, Idx);
5289 return Context.getConstantArrayType(ElementType, Size,
5290 ASM, IndexTypeQuals);
5293 case TYPE_INCOMPLETE_ARRAY: {
5294 QualType ElementType = readType(*Loc.F, Record, Idx);
5295 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5296 unsigned IndexTypeQuals = Record[2];
5297 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5300 case TYPE_VARIABLE_ARRAY: {
5301 QualType ElementType = readType(*Loc.F, Record, Idx);
5302 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5303 unsigned IndexTypeQuals = Record[2];
5304 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5305 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5306 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5307 ASM, IndexTypeQuals,
5308 SourceRange(LBLoc, RBLoc));
5312 if (Record.size() != 3) {
5313 Error("incorrect encoding of vector type in AST file");
5317 QualType ElementType = readType(*Loc.F, Record, Idx);
5318 unsigned NumElements = Record[1];
5319 unsigned VecKind = Record[2];
5320 return Context.getVectorType(ElementType, NumElements,
5321 (VectorType::VectorKind)VecKind);
5324 case TYPE_EXT_VECTOR: {
5325 if (Record.size() != 3) {
5326 Error("incorrect encoding of extended vector type in AST file");
5330 QualType ElementType = readType(*Loc.F, Record, Idx);
5331 unsigned NumElements = Record[1];
5332 return Context.getExtVectorType(ElementType, NumElements);
5335 case TYPE_FUNCTION_NO_PROTO: {
5336 if (Record.size() != 6) {
5337 Error("incorrect encoding of no-proto function type");
5340 QualType ResultType = readType(*Loc.F, Record, Idx);
5341 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5342 (CallingConv)Record[4], Record[5]);
5343 return Context.getFunctionNoProtoType(ResultType, Info);
5346 case TYPE_FUNCTION_PROTO: {
5347 QualType ResultType = readType(*Loc.F, Record, Idx);
5349 FunctionProtoType::ExtProtoInfo EPI;
5350 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5351 /*hasregparm*/ Record[2],
5352 /*regparm*/ Record[3],
5353 static_cast<CallingConv>(Record[4]),
5354 /*produces*/ Record[5]);
5358 EPI.Variadic = Record[Idx++];
5359 EPI.HasTrailingReturn = Record[Idx++];
5360 EPI.TypeQuals = Record[Idx++];
5361 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
5362 SmallVector<QualType, 8> ExceptionStorage;
5363 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
5365 unsigned NumParams = Record[Idx++];
5366 SmallVector<QualType, 16> ParamTypes;
5367 for (unsigned I = 0; I != NumParams; ++I)
5368 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5370 return Context.getFunctionType(ResultType, ParamTypes, EPI);
5373 case TYPE_UNRESOLVED_USING: {
5375 return Context.getTypeDeclType(
5376 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5379 case TYPE_TYPEDEF: {
5380 if (Record.size() != 2) {
5381 Error("incorrect encoding of typedef type");
5385 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5386 QualType Canonical = readType(*Loc.F, Record, Idx);
5387 if (!Canonical.isNull())
5388 Canonical = Context.getCanonicalType(Canonical);
5389 return Context.getTypedefType(Decl, Canonical);
5392 case TYPE_TYPEOF_EXPR:
5393 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5396 if (Record.size() != 1) {
5397 Error("incorrect encoding of typeof(type) in AST file");
5400 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5401 return Context.getTypeOfType(UnderlyingType);
5404 case TYPE_DECLTYPE: {
5405 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5406 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5409 case TYPE_UNARY_TRANSFORM: {
5410 QualType BaseType = readType(*Loc.F, Record, Idx);
5411 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5412 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5413 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5417 QualType Deduced = readType(*Loc.F, Record, Idx);
5418 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
5419 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5420 return Context.getAutoType(Deduced, Keyword, IsDependent);
5424 if (Record.size() != 2) {
5425 Error("incorrect encoding of record type");
5429 bool IsDependent = Record[Idx++];
5430 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5431 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5432 QualType T = Context.getRecordType(RD);
5433 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5438 if (Record.size() != 2) {
5439 Error("incorrect encoding of enum type");
5443 bool IsDependent = Record[Idx++];
5445 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5446 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5450 case TYPE_ATTRIBUTED: {
5451 if (Record.size() != 3) {
5452 Error("incorrect encoding of attributed type");
5455 QualType modifiedType = readType(*Loc.F, Record, Idx);
5456 QualType equivalentType = readType(*Loc.F, Record, Idx);
5457 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5458 return Context.getAttributedType(kind, modifiedType, equivalentType);
5462 if (Record.size() != 1) {
5463 Error("incorrect encoding of paren type");
5466 QualType InnerType = readType(*Loc.F, Record, Idx);
5467 return Context.getParenType(InnerType);
5470 case TYPE_PACK_EXPANSION: {
5471 if (Record.size() != 2) {
5472 Error("incorrect encoding of pack expansion type");
5475 QualType Pattern = readType(*Loc.F, Record, Idx);
5476 if (Pattern.isNull())
5478 Optional<unsigned> NumExpansions;
5480 NumExpansions = Record[1] - 1;
5481 return Context.getPackExpansionType(Pattern, NumExpansions);
5484 case TYPE_ELABORATED: {
5486 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5487 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5488 QualType NamedType = readType(*Loc.F, Record, Idx);
5489 return Context.getElaboratedType(Keyword, NNS, NamedType);
5492 case TYPE_OBJC_INTERFACE: {
5494 ObjCInterfaceDecl *ItfD
5495 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5496 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5499 case TYPE_OBJC_OBJECT: {
5501 QualType Base = readType(*Loc.F, Record, Idx);
5502 unsigned NumTypeArgs = Record[Idx++];
5503 SmallVector<QualType, 4> TypeArgs;
5504 for (unsigned I = 0; I != NumTypeArgs; ++I)
5505 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
5506 unsigned NumProtos = Record[Idx++];
5507 SmallVector<ObjCProtocolDecl*, 4> Protos;
5508 for (unsigned I = 0; I != NumProtos; ++I)
5509 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5510 bool IsKindOf = Record[Idx++];
5511 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
5514 case TYPE_OBJC_OBJECT_POINTER: {
5516 QualType Pointee = readType(*Loc.F, Record, Idx);
5517 return Context.getObjCObjectPointerType(Pointee);
5520 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5522 QualType Parm = readType(*Loc.F, Record, Idx);
5523 QualType Replacement = readType(*Loc.F, Record, Idx);
5524 return Context.getSubstTemplateTypeParmType(
5525 cast<TemplateTypeParmType>(Parm),
5526 Context.getCanonicalType(Replacement));
5529 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5531 QualType Parm = readType(*Loc.F, Record, Idx);
5532 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5533 return Context.getSubstTemplateTypeParmPackType(
5534 cast<TemplateTypeParmType>(Parm),
5538 case TYPE_INJECTED_CLASS_NAME: {
5539 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5540 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5541 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5542 // for AST reading, too much interdependencies.
5543 const Type *T = nullptr;
5544 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5545 if (const Type *Existing = DI->getTypeForDecl()) {
5551 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5552 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5553 DI->setTypeForDecl(T);
5555 return QualType(T, 0);
5558 case TYPE_TEMPLATE_TYPE_PARM: {
5560 unsigned Depth = Record[Idx++];
5561 unsigned Index = Record[Idx++];
5562 bool Pack = Record[Idx++];
5563 TemplateTypeParmDecl *D
5564 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5565 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5568 case TYPE_DEPENDENT_NAME: {
5570 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5571 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5572 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
5573 QualType Canon = readType(*Loc.F, Record, Idx);
5574 if (!Canon.isNull())
5575 Canon = Context.getCanonicalType(Canon);
5576 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5579 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5581 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5582 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5583 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
5584 unsigned NumArgs = Record[Idx++];
5585 SmallVector<TemplateArgument, 8> Args;
5586 Args.reserve(NumArgs);
5588 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5589 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5590 Args.size(), Args.data());
5593 case TYPE_DEPENDENT_SIZED_ARRAY: {
5597 QualType ElementType = readType(*Loc.F, Record, Idx);
5598 ArrayType::ArraySizeModifier ASM
5599 = (ArrayType::ArraySizeModifier)Record[Idx++];
5600 unsigned IndexTypeQuals = Record[Idx++];
5602 // DependentSizedArrayType
5603 Expr *NumElts = ReadExpr(*Loc.F);
5604 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5606 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5607 IndexTypeQuals, Brackets);
5610 case TYPE_TEMPLATE_SPECIALIZATION: {
5612 bool IsDependent = Record[Idx++];
5613 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5614 SmallVector<TemplateArgument, 8> Args;
5615 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5616 QualType Underlying = readType(*Loc.F, Record, Idx);
5618 if (Underlying.isNull())
5619 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5622 T = Context.getTemplateSpecializationType(Name, Args.data(),
5623 Args.size(), Underlying);
5624 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5629 if (Record.size() != 1) {
5630 Error("Incorrect encoding of atomic type");
5633 QualType ValueType = readType(*Loc.F, Record, Idx);
5634 return Context.getAtomicType(ValueType);
5637 llvm_unreachable("Invalid TypeCode!");
5640 void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5641 SmallVectorImpl<QualType> &Exceptions,
5642 FunctionProtoType::ExceptionSpecInfo &ESI,
5643 const RecordData &Record, unsigned &Idx) {
5644 ExceptionSpecificationType EST =
5645 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5647 if (EST == EST_Dynamic) {
5648 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
5649 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5650 ESI.Exceptions = Exceptions;
5651 } else if (EST == EST_ComputedNoexcept) {
5652 ESI.NoexceptExpr = ReadExpr(ModuleFile);
5653 } else if (EST == EST_Uninstantiated) {
5654 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5655 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5656 } else if (EST == EST_Unevaluated) {
5657 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5661 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5664 const ASTReader::RecordData &Record;
5667 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5669 return Reader.ReadSourceLocation(F, R, I);
5672 template<typename T>
5673 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5674 return Reader.ReadDeclAs<T>(F, Record, Idx);
5678 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5679 const ASTReader::RecordData &Record, unsigned &Idx)
5680 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5683 // We want compile-time assurance that we've enumerated all of
5684 // these, so unfortunately we have to declare them first, then
5685 // define them out-of-line.
5686 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5687 #define TYPELOC(CLASS, PARENT) \
5688 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5689 #include "clang/AST/TypeLocNodes.def"
5691 void VisitFunctionTypeLoc(FunctionTypeLoc);
5692 void VisitArrayTypeLoc(ArrayTypeLoc);
5695 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5698 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5699 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5700 if (TL.needsExtraLocalData()) {
5701 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5702 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5703 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5704 TL.setModeAttr(Record[Idx++]);
5707 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5708 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5710 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5711 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5713 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5716 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5719 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5720 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5722 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5723 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5725 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5726 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5728 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5729 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5730 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5732 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5733 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5734 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5736 TL.setSizeExpr(Reader.ReadExpr(F));
5738 TL.setSizeExpr(nullptr);
5740 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5741 VisitArrayTypeLoc(TL);
5743 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5744 VisitArrayTypeLoc(TL);
5746 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5747 VisitArrayTypeLoc(TL);
5749 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5750 DependentSizedArrayTypeLoc TL) {
5751 VisitArrayTypeLoc(TL);
5753 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5754 DependentSizedExtVectorTypeLoc TL) {
5755 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5757 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5758 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5760 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5761 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5763 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5764 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5765 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5766 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5767 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
5768 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5769 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
5772 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5773 VisitFunctionTypeLoc(TL);
5775 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5776 VisitFunctionTypeLoc(TL);
5778 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5779 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5781 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5782 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5784 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5785 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5786 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5787 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5789 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5790 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5791 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5792 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5793 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5795 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5796 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5798 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5799 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5800 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5801 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5802 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5804 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5805 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5807 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5808 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5810 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5811 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5813 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5814 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5815 if (TL.hasAttrOperand()) {
5817 range.setBegin(ReadSourceLocation(Record, Idx));
5818 range.setEnd(ReadSourceLocation(Record, Idx));
5819 TL.setAttrOperandParensRange(range);
5821 if (TL.hasAttrExprOperand()) {
5823 TL.setAttrExprOperand(Reader.ReadExpr(F));
5825 TL.setAttrExprOperand(nullptr);
5826 } else if (TL.hasAttrEnumOperand())
5827 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5829 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5830 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5832 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5833 SubstTemplateTypeParmTypeLoc TL) {
5834 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5836 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5837 SubstTemplateTypeParmPackTypeLoc TL) {
5838 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5840 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5841 TemplateSpecializationTypeLoc TL) {
5842 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5843 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5844 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5845 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5846 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5848 Reader.GetTemplateArgumentLocInfo(F,
5849 TL.getTypePtr()->getArg(i).getKind(),
5852 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5853 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5854 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5856 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5857 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5858 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5860 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5861 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5863 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5864 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5865 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5866 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5868 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5869 DependentTemplateSpecializationTypeLoc TL) {
5870 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5871 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5872 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5873 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5874 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5875 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5876 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5878 Reader.GetTemplateArgumentLocInfo(F,
5879 TL.getTypePtr()->getArg(I).getKind(),
5882 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5883 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5885 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5886 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5888 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5889 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5890 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5891 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5892 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5893 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5894 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5895 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
5896 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5897 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5899 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5900 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5902 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5903 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5904 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5905 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5908 TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5909 const RecordData &Record,
5911 QualType InfoTy = readType(F, Record, Idx);
5912 if (InfoTy.isNull())
5915 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5916 TypeLocReader TLR(*this, F, Record, Idx);
5917 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5922 QualType ASTReader::GetType(TypeID ID) {
5923 unsigned FastQuals = ID & Qualifiers::FastMask;
5924 unsigned Index = ID >> Qualifiers::FastWidth;
5926 if (Index < NUM_PREDEF_TYPE_IDS) {
5928 switch ((PredefinedTypeIDs)Index) {
5929 case PREDEF_TYPE_NULL_ID:
5931 case PREDEF_TYPE_VOID_ID:
5934 case PREDEF_TYPE_BOOL_ID:
5938 case PREDEF_TYPE_CHAR_U_ID:
5939 case PREDEF_TYPE_CHAR_S_ID:
5940 // FIXME: Check that the signedness of CharTy is correct!
5944 case PREDEF_TYPE_UCHAR_ID:
5945 T = Context.UnsignedCharTy;
5947 case PREDEF_TYPE_USHORT_ID:
5948 T = Context.UnsignedShortTy;
5950 case PREDEF_TYPE_UINT_ID:
5951 T = Context.UnsignedIntTy;
5953 case PREDEF_TYPE_ULONG_ID:
5954 T = Context.UnsignedLongTy;
5956 case PREDEF_TYPE_ULONGLONG_ID:
5957 T = Context.UnsignedLongLongTy;
5959 case PREDEF_TYPE_UINT128_ID:
5960 T = Context.UnsignedInt128Ty;
5962 case PREDEF_TYPE_SCHAR_ID:
5963 T = Context.SignedCharTy;
5965 case PREDEF_TYPE_WCHAR_ID:
5966 T = Context.WCharTy;
5968 case PREDEF_TYPE_SHORT_ID:
5969 T = Context.ShortTy;
5971 case PREDEF_TYPE_INT_ID:
5974 case PREDEF_TYPE_LONG_ID:
5977 case PREDEF_TYPE_LONGLONG_ID:
5978 T = Context.LongLongTy;
5980 case PREDEF_TYPE_INT128_ID:
5981 T = Context.Int128Ty;
5983 case PREDEF_TYPE_HALF_ID:
5986 case PREDEF_TYPE_FLOAT_ID:
5987 T = Context.FloatTy;
5989 case PREDEF_TYPE_DOUBLE_ID:
5990 T = Context.DoubleTy;
5992 case PREDEF_TYPE_LONGDOUBLE_ID:
5993 T = Context.LongDoubleTy;
5995 case PREDEF_TYPE_OVERLOAD_ID:
5996 T = Context.OverloadTy;
5998 case PREDEF_TYPE_BOUND_MEMBER:
5999 T = Context.BoundMemberTy;
6001 case PREDEF_TYPE_PSEUDO_OBJECT:
6002 T = Context.PseudoObjectTy;
6004 case PREDEF_TYPE_DEPENDENT_ID:
6005 T = Context.DependentTy;
6007 case PREDEF_TYPE_UNKNOWN_ANY:
6008 T = Context.UnknownAnyTy;
6010 case PREDEF_TYPE_NULLPTR_ID:
6011 T = Context.NullPtrTy;
6013 case PREDEF_TYPE_CHAR16_ID:
6014 T = Context.Char16Ty;
6016 case PREDEF_TYPE_CHAR32_ID:
6017 T = Context.Char32Ty;
6019 case PREDEF_TYPE_OBJC_ID:
6020 T = Context.ObjCBuiltinIdTy;
6022 case PREDEF_TYPE_OBJC_CLASS:
6023 T = Context.ObjCBuiltinClassTy;
6025 case PREDEF_TYPE_OBJC_SEL:
6026 T = Context.ObjCBuiltinSelTy;
6028 case PREDEF_TYPE_IMAGE1D_ID:
6029 T = Context.OCLImage1dTy;
6031 case PREDEF_TYPE_IMAGE1D_ARR_ID:
6032 T = Context.OCLImage1dArrayTy;
6034 case PREDEF_TYPE_IMAGE1D_BUFF_ID:
6035 T = Context.OCLImage1dBufferTy;
6037 case PREDEF_TYPE_IMAGE2D_ID:
6038 T = Context.OCLImage2dTy;
6040 case PREDEF_TYPE_IMAGE2D_ARR_ID:
6041 T = Context.OCLImage2dArrayTy;
6043 case PREDEF_TYPE_IMAGE2D_DEP_ID:
6044 T = Context.OCLImage2dDepthTy;
6046 case PREDEF_TYPE_IMAGE2D_ARR_DEP_ID:
6047 T = Context.OCLImage2dArrayDepthTy;
6049 case PREDEF_TYPE_IMAGE2D_MSAA_ID:
6050 T = Context.OCLImage2dMSAATy;
6052 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_ID:
6053 T = Context.OCLImage2dArrayMSAATy;
6055 case PREDEF_TYPE_IMAGE2D_MSAA_DEP_ID:
6056 T = Context.OCLImage2dMSAADepthTy;
6058 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_DEPTH_ID:
6059 T = Context.OCLImage2dArrayMSAADepthTy;
6061 case PREDEF_TYPE_IMAGE3D_ID:
6062 T = Context.OCLImage3dTy;
6064 case PREDEF_TYPE_SAMPLER_ID:
6065 T = Context.OCLSamplerTy;
6067 case PREDEF_TYPE_EVENT_ID:
6068 T = Context.OCLEventTy;
6070 case PREDEF_TYPE_CLK_EVENT_ID:
6071 T = Context.OCLClkEventTy;
6073 case PREDEF_TYPE_QUEUE_ID:
6074 T = Context.OCLQueueTy;
6076 case PREDEF_TYPE_NDRANGE_ID:
6077 T = Context.OCLNDRangeTy;
6079 case PREDEF_TYPE_RESERVE_ID_ID:
6080 T = Context.OCLReserveIDTy;
6082 case PREDEF_TYPE_AUTO_DEDUCT:
6083 T = Context.getAutoDeductType();
6086 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6087 T = Context.getAutoRRefDeductType();
6090 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6091 T = Context.ARCUnbridgedCastTy;
6094 case PREDEF_TYPE_BUILTIN_FN:
6095 T = Context.BuiltinFnTy;
6098 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6099 T = Context.OMPArraySectionTy;
6103 assert(!T.isNull() && "Unknown predefined type");
6104 return T.withFastQualifiers(FastQuals);
6107 Index -= NUM_PREDEF_TYPE_IDS;
6108 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6109 if (TypesLoaded[Index].isNull()) {
6110 TypesLoaded[Index] = readTypeRecord(Index);
6111 if (TypesLoaded[Index].isNull())
6114 TypesLoaded[Index]->setFromAST();
6115 if (DeserializationListener)
6116 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6117 TypesLoaded[Index]);
6120 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6123 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6124 return GetType(getGlobalTypeID(F, LocalID));
6127 serialization::TypeID
6128 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6129 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6130 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6132 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6135 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6136 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6137 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6139 unsigned GlobalIndex = LocalIndex + I->second;
6140 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6143 TemplateArgumentLocInfo
6144 ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6145 TemplateArgument::ArgKind Kind,
6146 const RecordData &Record,
6149 case TemplateArgument::Expression:
6151 case TemplateArgument::Type:
6152 return GetTypeSourceInfo(F, Record, Index);
6153 case TemplateArgument::Template: {
6154 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6156 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6157 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6160 case TemplateArgument::TemplateExpansion: {
6161 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6163 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6164 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6165 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6168 case TemplateArgument::Null:
6169 case TemplateArgument::Integral:
6170 case TemplateArgument::Declaration:
6171 case TemplateArgument::NullPtr:
6172 case TemplateArgument::Pack:
6173 // FIXME: Is this right?
6174 return TemplateArgumentLocInfo();
6176 llvm_unreachable("unexpected template argument loc");
6180 ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6181 const RecordData &Record, unsigned &Index) {
6182 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6184 if (Arg.getKind() == TemplateArgument::Expression) {
6185 if (Record[Index++]) // bool InfoHasSameExpr.
6186 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6188 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6192 const ASTTemplateArgumentListInfo*
6193 ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6194 const RecordData &Record,
6196 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6197 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6198 unsigned NumArgsAsWritten = Record[Index++];
6199 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6200 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6201 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6202 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6205 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6209 template<typename TemplateSpecializationDecl>
6210 static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6211 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6212 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6215 void ASTReader::CompleteRedeclChain(const Decl *D) {
6216 if (NumCurrentElementsDeserializing) {
6217 // We arrange to not care about the complete redeclaration chain while we're
6218 // deserializing. Just remember that the AST has marked this one as complete
6219 // but that it's not actually complete yet, so we know we still need to
6220 // complete it later.
6221 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6225 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6227 // If this is a named declaration, complete it by looking it up
6228 // within its context.
6230 // FIXME: Merging a function definition should merge
6231 // all mergeable entities within it.
6232 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6233 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6234 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6235 if (!getContext().getLangOpts().CPlusPlus &&
6236 isa<TranslationUnitDecl>(DC)) {
6237 // Outside of C++, we don't have a lookup table for the TU, so update
6238 // the identifier instead. (For C++ modules, we don't store decls
6239 // in the serialized identifier table, so we do the lookup in the TU.)
6240 auto *II = Name.getAsIdentifierInfo();
6241 assert(II && "non-identifier name in C?");
6242 if (II->isOutOfDate())
6243 updateOutOfDateIdentifier(*II);
6246 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6247 // Find all declarations of this kind from the relevant context.
6248 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6249 auto *DC = cast<DeclContext>(DCDecl);
6250 SmallVector<Decl*, 8> Decls;
6251 FindExternalLexicalDecls(
6252 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6257 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6258 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6259 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6260 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6261 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6262 if (auto *Template = FD->getPrimaryTemplate())
6263 Template->LoadLazySpecializations();
6267 uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
6268 const RecordData &Record,
6270 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
6271 Error("malformed AST file: missing C++ ctor initializers");
6275 unsigned LocalID = Record[Idx++];
6276 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6279 CXXCtorInitializer **
6280 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6281 RecordLocation Loc = getLocalBitOffset(Offset);
6282 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6283 SavedStreamPosition SavedPosition(Cursor);
6284 Cursor.JumpToBit(Loc.Offset);
6285 ReadingKindTracker ReadingKind(Read_Decl, *this);
6288 unsigned Code = Cursor.ReadCode();
6289 unsigned RecCode = Cursor.readRecord(Code, Record);
6290 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6291 Error("malformed AST file: missing C++ ctor initializers");
6296 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6299 uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6300 const RecordData &Record,
6302 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6303 Error("malformed AST file: missing C++ base specifier");
6307 unsigned LocalID = Record[Idx++];
6308 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6311 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6312 RecordLocation Loc = getLocalBitOffset(Offset);
6313 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6314 SavedStreamPosition SavedPosition(Cursor);
6315 Cursor.JumpToBit(Loc.Offset);
6316 ReadingKindTracker ReadingKind(Read_Decl, *this);
6318 unsigned Code = Cursor.ReadCode();
6319 unsigned RecCode = Cursor.readRecord(Code, Record);
6320 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
6321 Error("malformed AST file: missing C++ base specifiers");
6326 unsigned NumBases = Record[Idx++];
6327 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6328 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6329 for (unsigned I = 0; I != NumBases; ++I)
6330 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6334 serialization::DeclID
6335 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6336 if (LocalID < NUM_PREDEF_DECL_IDS)
6339 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6340 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6341 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6343 return LocalID + I->second;
6346 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6347 ModuleFile &M) const {
6348 // Predefined decls aren't from any module.
6349 if (ID < NUM_PREDEF_DECL_IDS)
6352 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6353 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
6356 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
6357 if (!D->isFromASTFile())
6359 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6360 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6364 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6365 if (ID < NUM_PREDEF_DECL_IDS)
6366 return SourceLocation();
6368 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6370 if (Index > DeclsLoaded.size()) {
6371 Error("declaration ID out-of-range for AST file");
6372 return SourceLocation();
6375 if (Decl *D = DeclsLoaded[Index])
6376 return D->getLocation();
6378 unsigned RawLocation = 0;
6379 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6380 return ReadSourceLocation(*Rec.F, RawLocation);
6383 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6385 case PREDEF_DECL_NULL_ID:
6388 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6389 return Context.getTranslationUnitDecl();
6391 case PREDEF_DECL_OBJC_ID_ID:
6392 return Context.getObjCIdDecl();
6394 case PREDEF_DECL_OBJC_SEL_ID:
6395 return Context.getObjCSelDecl();
6397 case PREDEF_DECL_OBJC_CLASS_ID:
6398 return Context.getObjCClassDecl();
6400 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6401 return Context.getObjCProtocolDecl();
6403 case PREDEF_DECL_INT_128_ID:
6404 return Context.getInt128Decl();
6406 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6407 return Context.getUInt128Decl();
6409 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6410 return Context.getObjCInstanceTypeDecl();
6412 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6413 return Context.getBuiltinVaListDecl();
6415 case PREDEF_DECL_VA_LIST_TAG:
6416 return Context.getVaListTagDecl();
6418 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6419 return Context.getBuiltinMSVaListDecl();
6421 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6422 return Context.getExternCContextDecl();
6424 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6425 return Context.getMakeIntegerSeqDecl();
6427 llvm_unreachable("PredefinedDeclIDs unknown enum value");
6430 Decl *ASTReader::GetExistingDecl(DeclID ID) {
6431 if (ID < NUM_PREDEF_DECL_IDS) {
6432 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6434 // Track that we have merged the declaration with ID \p ID into the
6435 // pre-existing predefined declaration \p D.
6436 auto &Merged = KeyDecls[D->getCanonicalDecl()];
6438 Merged.push_back(ID);
6443 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6445 if (Index >= DeclsLoaded.size()) {
6446 assert(0 && "declaration ID out-of-range for AST file");
6447 Error("declaration ID out-of-range for AST file");
6451 return DeclsLoaded[Index];
6454 Decl *ASTReader::GetDecl(DeclID ID) {
6455 if (ID < NUM_PREDEF_DECL_IDS)
6456 return GetExistingDecl(ID);
6458 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6460 if (Index >= DeclsLoaded.size()) {
6461 assert(0 && "declaration ID out-of-range for AST file");
6462 Error("declaration ID out-of-range for AST file");
6466 if (!DeclsLoaded[Index]) {
6468 if (DeserializationListener)
6469 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6472 return DeclsLoaded[Index];
6475 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6477 if (GlobalID < NUM_PREDEF_DECL_IDS)
6480 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6481 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6482 ModuleFile *Owner = I->second;
6484 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6485 = M.GlobalToLocalDeclIDs.find(Owner);
6486 if (Pos == M.GlobalToLocalDeclIDs.end())
6489 return GlobalID - Owner->BaseDeclID + Pos->second;
6492 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6493 const RecordData &Record,
6495 if (Idx >= Record.size()) {
6496 Error("Corrupted AST file");
6500 return getGlobalDeclID(F, Record[Idx++]);
6503 /// \brief Resolve the offset of a statement into a statement.
6505 /// This operation will read a new statement from the external
6506 /// source each time it is called, and is meant to be used via a
6507 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6508 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6509 // Switch case IDs are per Decl.
6510 ClearSwitchCaseIDs();
6512 // Offset here is a global offset across the entire chain.
6513 RecordLocation Loc = getLocalBitOffset(Offset);
6514 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6515 return ReadStmtFromStream(*Loc.F);
6518 void ASTReader::FindExternalLexicalDecls(
6519 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6520 SmallVectorImpl<Decl *> &Decls) {
6521 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6523 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
6524 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6525 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6526 auto K = (Decl::Kind)+LexicalDecls[I];
6527 if (!IsKindWeWant(K))
6530 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6532 // Don't add predefined declarations to the lexical context more
6534 if (ID < NUM_PREDEF_DECL_IDS) {
6535 if (PredefsVisited[ID])
6538 PredefsVisited[ID] = true;
6541 if (Decl *D = GetLocalDecl(*M, ID)) {
6542 assert(D->getKind() == K && "wrong kind for lexical decl");
6543 if (!DC->isDeclInLexicalTraversal(D))
6549 if (isa<TranslationUnitDecl>(DC)) {
6550 for (auto Lexical : TULexicalDecls)
6551 Visit(Lexical.first, Lexical.second);
6553 auto I = LexicalDecls.find(DC);
6554 if (I != LexicalDecls.end())
6555 Visit(I->second.first, I->second.second);
6558 ++NumLexicalDeclContextsRead;
6568 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6570 bool operator()(LocalDeclID L, LocalDeclID R) const {
6571 SourceLocation LHS = getLocation(L);
6572 SourceLocation RHS = getLocation(R);
6573 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6576 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6577 SourceLocation RHS = getLocation(R);
6578 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6581 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6582 SourceLocation LHS = getLocation(L);
6583 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6586 SourceLocation getLocation(LocalDeclID ID) const {
6587 return Reader.getSourceManager().getFileLoc(
6588 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6594 void ASTReader::FindFileRegionDecls(FileID File,
6595 unsigned Offset, unsigned Length,
6596 SmallVectorImpl<Decl *> &Decls) {
6597 SourceManager &SM = getSourceManager();
6599 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6600 if (I == FileDeclIDs.end())
6603 FileDeclsInfo &DInfo = I->second;
6604 if (DInfo.Decls.empty())
6608 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6609 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6611 DeclIDComp DIDComp(*this, *DInfo.Mod);
6612 ArrayRef<serialization::LocalDeclID>::iterator
6613 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6615 if (BeginIt != DInfo.Decls.begin())
6618 // If we are pointing at a top-level decl inside an objc container, we need
6619 // to backtrack until we find it otherwise we will fail to report that the
6620 // region overlaps with an objc container.
6621 while (BeginIt != DInfo.Decls.begin() &&
6622 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6623 ->isTopLevelDeclInObjCContainer())
6626 ArrayRef<serialization::LocalDeclID>::iterator
6627 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6629 if (EndIt != DInfo.Decls.end())
6632 for (ArrayRef<serialization::LocalDeclID>::iterator
6633 DIt = BeginIt; DIt != EndIt; ++DIt)
6634 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6638 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6639 DeclarationName Name) {
6640 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
6641 "DeclContext has no visible decls in storage");
6645 auto It = Lookups.find(DC);
6646 if (It == Lookups.end())
6649 Deserializing LookupResults(this);
6651 // Load the list of declarations.
6652 SmallVector<NamedDecl *, 64> Decls;
6653 for (DeclID ID : It->second.Table.find(Name)) {
6654 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6655 if (ND->getDeclName() == Name)
6656 Decls.push_back(ND);
6659 ++NumVisibleDeclContextsRead;
6660 SetExternalVisibleDeclsForName(DC, Name, Decls);
6661 return !Decls.empty();
6664 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6665 if (!DC->hasExternalVisibleStorage())
6668 auto It = Lookups.find(DC);
6669 assert(It != Lookups.end() &&
6670 "have external visible storage but no lookup tables");
6674 for (DeclID ID : It->second.Table.findAll()) {
6675 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6676 Decls[ND->getDeclName()].push_back(ND);
6679 ++NumVisibleDeclContextsRead;
6681 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
6682 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6684 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6687 const serialization::reader::DeclContextLookupTable *
6688 ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6689 auto I = Lookups.find(Primary);
6690 return I == Lookups.end() ? nullptr : &I->second;
6693 /// \brief Under non-PCH compilation the consumer receives the objc methods
6694 /// before receiving the implementation, and codegen depends on this.
6695 /// We simulate this by deserializing and passing to consumer the methods of the
6696 /// implementation before passing the deserialized implementation decl.
6697 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6698 ASTConsumer *Consumer) {
6699 assert(ImplD && Consumer);
6701 for (auto *I : ImplD->methods())
6702 Consumer->HandleInterestingDecl(DeclGroupRef(I));
6704 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6707 void ASTReader::PassInterestingDeclsToConsumer() {
6710 if (PassingDeclsToConsumer)
6713 // Guard variable to avoid recursively redoing the process of passing
6714 // decls to consumer.
6715 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6718 // Ensure that we've loaded all potentially-interesting declarations
6719 // that need to be eagerly loaded.
6720 for (auto ID : EagerlyDeserializedDecls)
6722 EagerlyDeserializedDecls.clear();
6724 while (!InterestingDecls.empty()) {
6725 Decl *D = InterestingDecls.front();
6726 InterestingDecls.pop_front();
6728 PassInterestingDeclToConsumer(D);
6732 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6733 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6734 PassObjCImplDeclToConsumer(ImplD, Consumer);
6736 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6739 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6740 this->Consumer = Consumer;
6743 PassInterestingDeclsToConsumer();
6745 if (DeserializationListener)
6746 DeserializationListener->ReaderInitialized(this);
6749 void ASTReader::PrintStats() {
6750 std::fprintf(stderr, "*** AST File Statistics:\n");
6752 unsigned NumTypesLoaded
6753 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6755 unsigned NumDeclsLoaded
6756 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6758 unsigned NumIdentifiersLoaded
6759 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6760 IdentifiersLoaded.end(),
6761 (IdentifierInfo *)nullptr);
6762 unsigned NumMacrosLoaded
6763 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6765 (MacroInfo *)nullptr);
6766 unsigned NumSelectorsLoaded
6767 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6768 SelectorsLoaded.end(),
6771 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6772 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6773 NumSLocEntriesRead, TotalNumSLocEntries,
6774 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6775 if (!TypesLoaded.empty())
6776 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6777 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6778 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6779 if (!DeclsLoaded.empty())
6780 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6781 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6782 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6783 if (!IdentifiersLoaded.empty())
6784 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6785 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6786 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6787 if (!MacrosLoaded.empty())
6788 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6789 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6790 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6791 if (!SelectorsLoaded.empty())
6792 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6793 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6794 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6795 if (TotalNumStatements)
6796 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6797 NumStatementsRead, TotalNumStatements,
6798 ((float)NumStatementsRead/TotalNumStatements * 100));
6800 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6801 NumMacrosRead, TotalNumMacros,
6802 ((float)NumMacrosRead/TotalNumMacros * 100));
6803 if (TotalLexicalDeclContexts)
6804 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6805 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6806 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6808 if (TotalVisibleDeclContexts)
6809 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6810 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6811 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6813 if (TotalNumMethodPoolEntries) {
6814 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6815 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6816 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6819 if (NumMethodPoolLookups) {
6820 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6821 NumMethodPoolHits, NumMethodPoolLookups,
6822 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6824 if (NumMethodPoolTableLookups) {
6825 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6826 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6827 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6831 if (NumIdentifierLookupHits) {
6832 std::fprintf(stderr,
6833 " %u / %u identifier table lookups succeeded (%f%%)\n",
6834 NumIdentifierLookupHits, NumIdentifierLookups,
6835 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6839 std::fprintf(stderr, "\n");
6840 GlobalIndex->printStats();
6843 std::fprintf(stderr, "\n");
6845 std::fprintf(stderr, "\n");
6848 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6850 dumpModuleIDMap(StringRef Name,
6851 const ContinuousRangeMap<Key, ModuleFile *,
6852 InitialCapacity> &Map) {
6853 if (Map.begin() == Map.end())
6856 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6857 llvm::errs() << Name << ":\n";
6858 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6860 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6865 void ASTReader::dump() {
6866 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6867 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6868 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6869 dumpModuleIDMap("Global type map", GlobalTypeMap);
6870 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6871 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6872 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6873 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6874 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6875 dumpModuleIDMap("Global preprocessed entity map",
6876 GlobalPreprocessedEntityMap);
6878 llvm::errs() << "\n*** PCH/Modules Loaded:";
6879 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6880 MEnd = ModuleMgr.end();
6885 /// Return the amount of memory used by memory buffers, breaking down
6886 /// by heap-backed versus mmap'ed memory.
6887 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6888 for (ModuleConstIterator I = ModuleMgr.begin(),
6889 E = ModuleMgr.end(); I != E; ++I) {
6890 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6891 size_t bytes = buf->getBufferSize();
6892 switch (buf->getBufferKind()) {
6893 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6894 sizes.malloc_bytes += bytes;
6896 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6897 sizes.mmap_bytes += bytes;
6904 void ASTReader::InitializeSema(Sema &S) {
6906 S.addExternalSource(this);
6908 // Makes sure any declarations that were deserialized "too early"
6909 // still get added to the identifier's declaration chains.
6910 for (uint64_t ID : PreloadedDeclIDs) {
6911 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6912 pushExternalDeclIntoScope(D, D->getDeclName());
6914 PreloadedDeclIDs.clear();
6916 // FIXME: What happens if these are changed by a module import?
6917 if (!FPPragmaOptions.empty()) {
6918 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6919 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6922 // FIXME: What happens if these are changed by a module import?
6923 if (!OpenCLExtensions.empty()) {
6925 #define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6926 #include "clang/Basic/OpenCLExtensions.def"
6928 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6934 void ASTReader::UpdateSema() {
6935 assert(SemaObj && "no Sema to update");
6937 // Load the offsets of the declarations that Sema references.
6938 // They will be lazily deserialized when needed.
6939 if (!SemaDeclRefs.empty()) {
6940 assert(SemaDeclRefs.size() % 2 == 0);
6941 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6942 if (!SemaObj->StdNamespace)
6943 SemaObj->StdNamespace = SemaDeclRefs[I];
6944 if (!SemaObj->StdBadAlloc)
6945 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6947 SemaDeclRefs.clear();
6950 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6951 // encountered the pragma in the source.
6952 if(OptimizeOffPragmaLocation.isValid())
6953 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
6956 IdentifierInfo *ASTReader::get(StringRef Name) {
6957 // Note that we are loading an identifier.
6958 Deserializing AnIdentifier(this);
6960 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
6961 NumIdentifierLookups,
6962 NumIdentifierLookupHits);
6964 // We don't need to do identifier table lookups in C++ modules (we preload
6965 // all interesting declarations, and don't need to use the scope for name
6966 // lookups). Perform the lookup in PCH files, though, since we don't build
6967 // a complete initial identifier table if we're carrying on from a PCH.
6968 if (Context.getLangOpts().CPlusPlus) {
6969 for (auto F : ModuleMgr.pch_modules())
6973 // If there is a global index, look there first to determine which modules
6974 // provably do not have any results for this identifier.
6975 GlobalModuleIndex::HitSet Hits;
6976 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6977 if (!loadGlobalIndex()) {
6978 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6983 ModuleMgr.visit(Visitor, HitsPtr);
6986 IdentifierInfo *II = Visitor.getIdentifierInfo();
6987 markIdentifierUpToDate(II);
6992 /// \brief An identifier-lookup iterator that enumerates all of the
6993 /// identifiers stored within a set of AST files.
6994 class ASTIdentifierIterator : public IdentifierIterator {
6995 /// \brief The AST reader whose identifiers are being enumerated.
6996 const ASTReader &Reader;
6998 /// \brief The current index into the chain of AST files stored in
7002 /// \brief The current position within the identifier lookup table
7003 /// of the current AST file.
7004 ASTIdentifierLookupTable::key_iterator Current;
7006 /// \brief The end position within the identifier lookup table of
7007 /// the current AST file.
7008 ASTIdentifierLookupTable::key_iterator End;
7011 explicit ASTIdentifierIterator(const ASTReader &Reader);
7013 StringRef Next() override;
7017 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7018 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7019 ASTIdentifierLookupTable *IdTable
7020 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7021 Current = IdTable->key_begin();
7022 End = IdTable->key_end();
7025 StringRef ASTIdentifierIterator::Next() {
7026 while (Current == End) {
7027 // If we have exhausted all of our AST files, we're done.
7032 ASTIdentifierLookupTable *IdTable
7033 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7034 IdentifierLookupTable;
7035 Current = IdTable->key_begin();
7036 End = IdTable->key_end();
7039 // We have any identifiers remaining in the current AST file; return
7041 StringRef Result = *Current;
7046 IdentifierIterator *ASTReader::getIdentifiers() {
7047 if (!loadGlobalIndex())
7048 return GlobalIndex->createIdentifierIterator();
7050 return new ASTIdentifierIterator(*this);
7053 namespace clang { namespace serialization {
7054 class ReadMethodPoolVisitor {
7057 unsigned PriorGeneration;
7058 unsigned InstanceBits;
7059 unsigned FactoryBits;
7060 bool InstanceHasMoreThanOneDecl;
7061 bool FactoryHasMoreThanOneDecl;
7062 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7063 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
7066 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
7067 unsigned PriorGeneration)
7068 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
7069 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7070 FactoryHasMoreThanOneDecl(false) {}
7072 bool operator()(ModuleFile &M) {
7073 if (!M.SelectorLookupTable)
7076 // If we've already searched this module file, skip it now.
7077 if (M.Generation <= PriorGeneration)
7080 ++Reader.NumMethodPoolTableLookups;
7081 ASTSelectorLookupTable *PoolTable
7082 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7083 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
7084 if (Pos == PoolTable->end())
7087 ++Reader.NumMethodPoolTableHits;
7088 ++Reader.NumSelectorsRead;
7089 // FIXME: Not quite happy with the statistics here. We probably should
7090 // disable this tracking when called via LoadSelector.
7091 // Also, should entries without methods count as misses?
7092 ++Reader.NumMethodPoolEntriesRead;
7093 ASTSelectorLookupTrait::data_type Data = *Pos;
7094 if (Reader.DeserializationListener)
7095 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
7097 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7098 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7099 InstanceBits = Data.InstanceBits;
7100 FactoryBits = Data.FactoryBits;
7101 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7102 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
7106 /// \brief Retrieve the instance methods found by this visitor.
7107 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7108 return InstanceMethods;
7111 /// \brief Retrieve the instance methods found by this visitor.
7112 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7113 return FactoryMethods;
7116 unsigned getInstanceBits() const { return InstanceBits; }
7117 unsigned getFactoryBits() const { return FactoryBits; }
7118 bool instanceHasMoreThanOneDecl() const {
7119 return InstanceHasMoreThanOneDecl;
7121 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
7123 } } // end namespace clang::serialization
7125 /// \brief Add the given set of methods to the method list.
7126 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7127 ObjCMethodList &List) {
7128 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7129 S.addMethodToGlobalList(&List, Methods[I]);
7133 void ASTReader::ReadMethodPool(Selector Sel) {
7134 // Get the selector generation and update it to the current generation.
7135 unsigned &Generation = SelectorGeneration[Sel];
7136 unsigned PriorGeneration = Generation;
7137 Generation = getGeneration();
7139 // Search for methods defined with this selector.
7140 ++NumMethodPoolLookups;
7141 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7142 ModuleMgr.visit(Visitor);
7144 if (Visitor.getInstanceMethods().empty() &&
7145 Visitor.getFactoryMethods().empty())
7148 ++NumMethodPoolHits;
7153 Sema &S = *getSema();
7154 Sema::GlobalMethodPool::iterator Pos
7155 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7157 Pos->second.first.setBits(Visitor.getInstanceBits());
7158 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
7159 Pos->second.second.setBits(Visitor.getFactoryBits());
7160 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
7162 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7163 // when building a module we keep every method individually and may need to
7164 // update hasMoreThanOneDecl as we add the methods.
7165 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7166 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
7169 void ASTReader::ReadKnownNamespaces(
7170 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7173 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7174 if (NamespaceDecl *Namespace
7175 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7176 Namespaces.push_back(Namespace);
7180 void ASTReader::ReadUndefinedButUsed(
7181 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
7182 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7183 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
7184 SourceLocation Loc =
7185 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
7186 Undefined.insert(std::make_pair(D, Loc));
7190 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7191 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7193 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7194 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7195 uint64_t Count = DelayedDeleteExprs[Idx++];
7196 for (uint64_t C = 0; C < Count; ++C) {
7197 SourceLocation DeleteLoc =
7198 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7199 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7200 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7205 void ASTReader::ReadTentativeDefinitions(
7206 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7207 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7208 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7210 TentativeDefs.push_back(Var);
7212 TentativeDefinitions.clear();
7215 void ASTReader::ReadUnusedFileScopedDecls(
7216 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7217 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7219 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7223 UnusedFileScopedDecls.clear();
7226 void ASTReader::ReadDelegatingConstructors(
7227 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7228 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7229 CXXConstructorDecl *D
7230 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7234 DelegatingCtorDecls.clear();
7237 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7238 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7240 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7244 ExtVectorDecls.clear();
7247 void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7248 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7249 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7251 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7252 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7256 UnusedLocalTypedefNameCandidates.clear();
7259 void ASTReader::ReadReferencedSelectors(
7260 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7261 if (ReferencedSelectorsData.empty())
7264 // If there are @selector references added them to its pool. This is for
7265 // implementation of -Wselector.
7266 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7268 while (I < DataSize) {
7269 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7270 SourceLocation SelLoc
7271 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7272 Sels.push_back(std::make_pair(Sel, SelLoc));
7274 ReferencedSelectorsData.clear();
7277 void ASTReader::ReadWeakUndeclaredIdentifiers(
7278 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7279 if (WeakUndeclaredIdentifiers.empty())
7282 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7283 IdentifierInfo *WeakId
7284 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7285 IdentifierInfo *AliasId
7286 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7288 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7289 bool Used = WeakUndeclaredIdentifiers[I++];
7290 WeakInfo WI(AliasId, Loc);
7292 WeakIDs.push_back(std::make_pair(WeakId, WI));
7294 WeakUndeclaredIdentifiers.clear();
7297 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7298 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7299 ExternalVTableUse VT;
7300 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7301 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7302 VT.DefinitionRequired = VTableUses[Idx++];
7303 VTables.push_back(VT);
7309 void ASTReader::ReadPendingInstantiations(
7310 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7311 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7312 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7314 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7316 Pending.push_back(std::make_pair(D, Loc));
7318 PendingInstantiations.clear();
7321 void ASTReader::ReadLateParsedTemplates(
7322 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7323 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7325 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7327 LateParsedTemplate *LT = new LateParsedTemplate;
7328 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7330 ModuleFile *F = getOwningModuleFile(LT->D);
7331 assert(F && "No module");
7333 unsigned TokN = LateParsedTemplates[Idx++];
7334 LT->Toks.reserve(TokN);
7335 for (unsigned T = 0; T < TokN; ++T)
7336 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7338 LPTMap.insert(std::make_pair(FD, LT));
7341 LateParsedTemplates.clear();
7344 void ASTReader::LoadSelector(Selector Sel) {
7345 // It would be complicated to avoid reading the methods anyway. So don't.
7346 ReadMethodPool(Sel);
7349 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7350 assert(ID && "Non-zero identifier ID required");
7351 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7352 IdentifiersLoaded[ID - 1] = II;
7353 if (DeserializationListener)
7354 DeserializationListener->IdentifierRead(ID, II);
7357 /// \brief Set the globally-visible declarations associated with the given
7360 /// If the AST reader is currently in a state where the given declaration IDs
7361 /// cannot safely be resolved, they are queued until it is safe to resolve
7364 /// \param II an IdentifierInfo that refers to one or more globally-visible
7367 /// \param DeclIDs the set of declaration IDs with the name @p II that are
7368 /// visible at global scope.
7370 /// \param Decls if non-null, this vector will be populated with the set of
7371 /// deserialized declarations. These declarations will not be pushed into
7374 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7375 const SmallVectorImpl<uint32_t> &DeclIDs,
7376 SmallVectorImpl<Decl *> *Decls) {
7377 if (NumCurrentElementsDeserializing && !Decls) {
7378 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
7382 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7384 // Queue this declaration so that it will be added to the
7385 // translation unit scope and identifier's declaration chain
7386 // once a Sema object is known.
7387 PreloadedDeclIDs.push_back(DeclIDs[I]);
7391 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7393 // If we're simply supposed to record the declarations, do so now.
7395 Decls->push_back(D);
7399 // Introduce this declaration into the translation-unit scope
7400 // and add it to the declaration chain for this identifier, so
7401 // that (unqualified) name lookup will find it.
7402 pushExternalDeclIntoScope(D, II);
7406 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
7410 if (IdentifiersLoaded.empty()) {
7411 Error("no identifier table in AST file");
7416 if (!IdentifiersLoaded[ID]) {
7417 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7418 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7419 ModuleFile *M = I->second;
7420 unsigned Index = ID - M->BaseIdentifierID;
7421 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7423 // All of the strings in the AST file are preceded by a 16-bit length.
7424 // Extract that 16-bit length to avoid having to execute strlen().
7425 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7426 // unsigned integers. This is important to avoid integer overflow when
7427 // we cast them to 'unsigned'.
7428 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7429 unsigned StrLen = (((unsigned) StrLenPtr[0])
7430 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
7431 IdentifiersLoaded[ID]
7432 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
7433 if (DeserializationListener)
7434 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7437 return IdentifiersLoaded[ID];
7440 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7441 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
7444 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7445 if (LocalID < NUM_PREDEF_IDENT_IDS)
7448 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7449 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7450 assert(I != M.IdentifierRemap.end()
7451 && "Invalid index into identifier index remap");
7453 return LocalID + I->second;
7456 MacroInfo *ASTReader::getMacro(MacroID ID) {
7460 if (MacrosLoaded.empty()) {
7461 Error("no macro table in AST file");
7465 ID -= NUM_PREDEF_MACRO_IDS;
7466 if (!MacrosLoaded[ID]) {
7467 GlobalMacroMapType::iterator I
7468 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7469 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7470 ModuleFile *M = I->second;
7471 unsigned Index = ID - M->BaseMacroID;
7472 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7474 if (DeserializationListener)
7475 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7479 return MacrosLoaded[ID];
7482 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7483 if (LocalID < NUM_PREDEF_MACRO_IDS)
7486 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7487 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7488 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7490 return LocalID + I->second;
7493 serialization::SubmoduleID
7494 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7495 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7498 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7499 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7500 assert(I != M.SubmoduleRemap.end()
7501 && "Invalid index into submodule index remap");
7503 return LocalID + I->second;
7506 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7507 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7508 assert(GlobalID == 0 && "Unhandled global submodule ID");
7512 if (GlobalID > SubmodulesLoaded.size()) {
7513 Error("submodule ID out of range in AST file");
7517 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7520 Module *ASTReader::getModule(unsigned ID) {
7521 return getSubmodule(ID);
7524 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7526 // It's a module, look it up by submodule ID.
7527 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7528 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7530 // It's a prefix (preamble, PCH, ...). Look it up by index.
7531 unsigned IndexFromEnd = ID >> 1;
7532 assert(IndexFromEnd && "got reference to unknown module file");
7533 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7537 unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7541 // For a file representing a module, use the submodule ID of the top-level
7542 // module as the file ID. For any other kind of file, the number of such
7543 // files loaded beforehand will be the same on reload.
7544 // FIXME: Is this true even if we have an explicit module file and a PCH?
7546 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7548 auto PCHModules = getModuleManager().pch_modules();
7549 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7550 assert(I != PCHModules.end() && "emitting reference to unknown file");
7551 return (I - PCHModules.end()) << 1;
7554 llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7555 ASTReader::getSourceDescriptor(unsigned ID) {
7556 if (const Module *M = getSubmodule(ID))
7557 return ExternalASTSource::ASTSourceDescriptor(*M);
7559 // If there is only a single PCH, return it instead.
7560 // Chained PCH are not suported.
7561 if (ModuleMgr.size() == 1) {
7562 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7563 return ASTReader::ASTSourceDescriptor(
7564 MF.OriginalSourceFileName, MF.OriginalDir, MF.FileName, MF.Signature);
7569 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7570 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7573 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7577 if (ID > SelectorsLoaded.size()) {
7578 Error("selector ID out of range in AST file");
7582 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
7583 // Load this selector from the selector table.
7584 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7585 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7586 ModuleFile &M = *I->second;
7587 ASTSelectorLookupTrait Trait(*this, M);
7588 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7589 SelectorsLoaded[ID - 1] =
7590 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7591 if (DeserializationListener)
7592 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7595 return SelectorsLoaded[ID - 1];
7598 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7599 return DecodeSelector(ID);
7602 uint32_t ASTReader::GetNumExternalSelectors() {
7603 // ID 0 (the null selector) is considered an external selector.
7604 return getTotalNumSelectors() + 1;
7607 serialization::SelectorID
7608 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7609 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7612 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7613 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7614 assert(I != M.SelectorRemap.end()
7615 && "Invalid index into selector index remap");
7617 return LocalID + I->second;
7621 ASTReader::ReadDeclarationName(ModuleFile &F,
7622 const RecordData &Record, unsigned &Idx) {
7623 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7625 case DeclarationName::Identifier:
7626 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
7628 case DeclarationName::ObjCZeroArgSelector:
7629 case DeclarationName::ObjCOneArgSelector:
7630 case DeclarationName::ObjCMultiArgSelector:
7631 return DeclarationName(ReadSelector(F, Record, Idx));
7633 case DeclarationName::CXXConstructorName:
7634 return Context.DeclarationNames.getCXXConstructorName(
7635 Context.getCanonicalType(readType(F, Record, Idx)));
7637 case DeclarationName::CXXDestructorName:
7638 return Context.DeclarationNames.getCXXDestructorName(
7639 Context.getCanonicalType(readType(F, Record, Idx)));
7641 case DeclarationName::CXXConversionFunctionName:
7642 return Context.DeclarationNames.getCXXConversionFunctionName(
7643 Context.getCanonicalType(readType(F, Record, Idx)));
7645 case DeclarationName::CXXOperatorName:
7646 return Context.DeclarationNames.getCXXOperatorName(
7647 (OverloadedOperatorKind)Record[Idx++]);
7649 case DeclarationName::CXXLiteralOperatorName:
7650 return Context.DeclarationNames.getCXXLiteralOperatorName(
7651 GetIdentifierInfo(F, Record, Idx));
7653 case DeclarationName::CXXUsingDirective:
7654 return DeclarationName::getUsingDirectiveName();
7657 llvm_unreachable("Invalid NameKind!");
7660 void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7661 DeclarationNameLoc &DNLoc,
7662 DeclarationName Name,
7663 const RecordData &Record, unsigned &Idx) {
7664 switch (Name.getNameKind()) {
7665 case DeclarationName::CXXConstructorName:
7666 case DeclarationName::CXXDestructorName:
7667 case DeclarationName::CXXConversionFunctionName:
7668 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7671 case DeclarationName::CXXOperatorName:
7672 DNLoc.CXXOperatorName.BeginOpNameLoc
7673 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7674 DNLoc.CXXOperatorName.EndOpNameLoc
7675 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7678 case DeclarationName::CXXLiteralOperatorName:
7679 DNLoc.CXXLiteralOperatorName.OpNameLoc
7680 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7683 case DeclarationName::Identifier:
7684 case DeclarationName::ObjCZeroArgSelector:
7685 case DeclarationName::ObjCOneArgSelector:
7686 case DeclarationName::ObjCMultiArgSelector:
7687 case DeclarationName::CXXUsingDirective:
7692 void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7693 DeclarationNameInfo &NameInfo,
7694 const RecordData &Record, unsigned &Idx) {
7695 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7696 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7697 DeclarationNameLoc DNLoc;
7698 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7699 NameInfo.setInfo(DNLoc);
7702 void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7703 const RecordData &Record, unsigned &Idx) {
7704 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7705 unsigned NumTPLists = Record[Idx++];
7706 Info.NumTemplParamLists = NumTPLists;
7708 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7709 for (unsigned i=0; i != NumTPLists; ++i)
7710 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7715 ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7717 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7719 case TemplateName::Template:
7720 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7722 case TemplateName::OverloadedTemplate: {
7723 unsigned size = Record[Idx++];
7724 UnresolvedSet<8> Decls;
7726 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7728 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7731 case TemplateName::QualifiedTemplate: {
7732 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7733 bool hasTemplKeyword = Record[Idx++];
7734 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7735 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7738 case TemplateName::DependentTemplate: {
7739 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7740 if (Record[Idx++]) // isIdentifier
7741 return Context.getDependentTemplateName(NNS,
7742 GetIdentifierInfo(F, Record,
7744 return Context.getDependentTemplateName(NNS,
7745 (OverloadedOperatorKind)Record[Idx++]);
7748 case TemplateName::SubstTemplateTemplateParm: {
7749 TemplateTemplateParmDecl *param
7750 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7751 if (!param) return TemplateName();
7752 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7753 return Context.getSubstTemplateTemplateParm(param, replacement);
7756 case TemplateName::SubstTemplateTemplateParmPack: {
7757 TemplateTemplateParmDecl *Param
7758 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7760 return TemplateName();
7762 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7763 if (ArgPack.getKind() != TemplateArgument::Pack)
7764 return TemplateName();
7766 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7770 llvm_unreachable("Unhandled template name kind!");
7773 TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7774 const RecordData &Record,
7776 bool Canonicalize) {
7778 // The caller wants a canonical template argument. Sometimes the AST only
7779 // wants template arguments in canonical form (particularly as the template
7780 // argument lists of template specializations) so ensure we preserve that
7781 // canonical form across serialization.
7782 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7783 return Context.getCanonicalTemplateArgument(Arg);
7786 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7788 case TemplateArgument::Null:
7789 return TemplateArgument();
7790 case TemplateArgument::Type:
7791 return TemplateArgument(readType(F, Record, Idx));
7792 case TemplateArgument::Declaration: {
7793 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7794 return TemplateArgument(D, readType(F, Record, Idx));
7796 case TemplateArgument::NullPtr:
7797 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7798 case TemplateArgument::Integral: {
7799 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7800 QualType T = readType(F, Record, Idx);
7801 return TemplateArgument(Context, Value, T);
7803 case TemplateArgument::Template:
7804 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7805 case TemplateArgument::TemplateExpansion: {
7806 TemplateName Name = ReadTemplateName(F, Record, Idx);
7807 Optional<unsigned> NumTemplateExpansions;
7808 if (unsigned NumExpansions = Record[Idx++])
7809 NumTemplateExpansions = NumExpansions - 1;
7810 return TemplateArgument(Name, NumTemplateExpansions);
7812 case TemplateArgument::Expression:
7813 return TemplateArgument(ReadExpr(F));
7814 case TemplateArgument::Pack: {
7815 unsigned NumArgs = Record[Idx++];
7816 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7817 for (unsigned I = 0; I != NumArgs; ++I)
7818 Args[I] = ReadTemplateArgument(F, Record, Idx);
7819 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
7823 llvm_unreachable("Unhandled template argument kind!");
7826 TemplateParameterList *
7827 ASTReader::ReadTemplateParameterList(ModuleFile &F,
7828 const RecordData &Record, unsigned &Idx) {
7829 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7830 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7831 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7833 unsigned NumParams = Record[Idx++];
7834 SmallVector<NamedDecl *, 16> Params;
7835 Params.reserve(NumParams);
7837 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7839 TemplateParameterList* TemplateParams =
7840 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7842 return TemplateParams;
7847 ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
7848 ModuleFile &F, const RecordData &Record,
7849 unsigned &Idx, bool Canonicalize) {
7850 unsigned NumTemplateArgs = Record[Idx++];
7851 TemplArgs.reserve(NumTemplateArgs);
7852 while (NumTemplateArgs--)
7853 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
7856 /// \brief Read a UnresolvedSet structure.
7857 void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
7858 const RecordData &Record, unsigned &Idx) {
7859 unsigned NumDecls = Record[Idx++];
7860 Set.reserve(Context, NumDecls);
7861 while (NumDecls--) {
7862 DeclID ID = ReadDeclID(F, Record, Idx);
7863 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
7864 Set.addLazyDecl(Context, ID, AS);
7869 ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7870 const RecordData &Record, unsigned &Idx) {
7871 bool isVirtual = static_cast<bool>(Record[Idx++]);
7872 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7873 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7874 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7875 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7876 SourceRange Range = ReadSourceRange(F, Record, Idx);
7877 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7878 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7880 Result.setInheritConstructors(inheritConstructors);
7884 CXXCtorInitializer **
7885 ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7887 unsigned NumInitializers = Record[Idx++];
7888 assert(NumInitializers && "wrote ctor initializers but have no inits");
7889 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7890 for (unsigned i = 0; i != NumInitializers; ++i) {
7891 TypeSourceInfo *TInfo = nullptr;
7892 bool IsBaseVirtual = false;
7893 FieldDecl *Member = nullptr;
7894 IndirectFieldDecl *IndirectMember = nullptr;
7896 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7898 case CTOR_INITIALIZER_BASE:
7899 TInfo = GetTypeSourceInfo(F, Record, Idx);
7900 IsBaseVirtual = Record[Idx++];
7903 case CTOR_INITIALIZER_DELEGATING:
7904 TInfo = GetTypeSourceInfo(F, Record, Idx);
7907 case CTOR_INITIALIZER_MEMBER:
7908 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7911 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7912 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7916 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7917 Expr *Init = ReadExpr(F);
7918 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7919 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7920 bool IsWritten = Record[Idx++];
7921 unsigned SourceOrderOrNumArrayIndices;
7922 SmallVector<VarDecl *, 8> Indices;
7924 SourceOrderOrNumArrayIndices = Record[Idx++];
7926 SourceOrderOrNumArrayIndices = Record[Idx++];
7927 Indices.reserve(SourceOrderOrNumArrayIndices);
7928 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7929 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7932 CXXCtorInitializer *BOMInit;
7933 if (Type == CTOR_INITIALIZER_BASE) {
7934 BOMInit = new (Context)
7935 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7936 RParenLoc, MemberOrEllipsisLoc);
7937 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7938 BOMInit = new (Context)
7939 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7940 } else if (IsWritten) {
7942 BOMInit = new (Context) CXXCtorInitializer(
7943 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7945 BOMInit = new (Context)
7946 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7947 LParenLoc, Init, RParenLoc);
7949 if (IndirectMember) {
7950 assert(Indices.empty() && "Indirect field improperly initialized");
7951 BOMInit = new (Context)
7952 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7953 LParenLoc, Init, RParenLoc);
7955 BOMInit = CXXCtorInitializer::Create(
7956 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7957 Indices.data(), Indices.size());
7962 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7963 CtorInitializers[i] = BOMInit;
7966 return CtorInitializers;
7969 NestedNameSpecifier *
7970 ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7971 const RecordData &Record, unsigned &Idx) {
7972 unsigned N = Record[Idx++];
7973 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
7974 for (unsigned I = 0; I != N; ++I) {
7975 NestedNameSpecifier::SpecifierKind Kind
7976 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7978 case NestedNameSpecifier::Identifier: {
7979 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7980 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7984 case NestedNameSpecifier::Namespace: {
7985 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7986 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7990 case NestedNameSpecifier::NamespaceAlias: {
7991 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7992 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7996 case NestedNameSpecifier::TypeSpec:
7997 case NestedNameSpecifier::TypeSpecWithTemplate: {
7998 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8002 bool Template = Record[Idx++];
8003 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8007 case NestedNameSpecifier::Global: {
8008 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8009 // No associated value, and there can't be a prefix.
8013 case NestedNameSpecifier::Super: {
8014 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8015 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8024 NestedNameSpecifierLoc
8025 ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8027 unsigned N = Record[Idx++];
8028 NestedNameSpecifierLocBuilder Builder;
8029 for (unsigned I = 0; I != N; ++I) {
8030 NestedNameSpecifier::SpecifierKind Kind
8031 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8033 case NestedNameSpecifier::Identifier: {
8034 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8035 SourceRange Range = ReadSourceRange(F, Record, Idx);
8036 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8040 case NestedNameSpecifier::Namespace: {
8041 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8042 SourceRange Range = ReadSourceRange(F, Record, Idx);
8043 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8047 case NestedNameSpecifier::NamespaceAlias: {
8048 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8049 SourceRange Range = ReadSourceRange(F, Record, Idx);
8050 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8054 case NestedNameSpecifier::TypeSpec:
8055 case NestedNameSpecifier::TypeSpecWithTemplate: {
8056 bool Template = Record[Idx++];
8057 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8059 return NestedNameSpecifierLoc();
8060 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8062 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8063 Builder.Extend(Context,
8064 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8065 T->getTypeLoc(), ColonColonLoc);
8069 case NestedNameSpecifier::Global: {
8070 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8071 Builder.MakeGlobal(Context, ColonColonLoc);
8075 case NestedNameSpecifier::Super: {
8076 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8077 SourceRange Range = ReadSourceRange(F, Record, Idx);
8078 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8084 return Builder.getWithLocInContext(Context);
8088 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8090 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8091 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8092 return SourceRange(beg, end);
8095 /// \brief Read an integral value
8096 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8097 unsigned BitWidth = Record[Idx++];
8098 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8099 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8104 /// \brief Read a signed integral value
8105 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8106 bool isUnsigned = Record[Idx++];
8107 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8110 /// \brief Read a floating-point value
8111 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8112 const llvm::fltSemantics &Sem,
8114 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
8117 // \brief Read a string
8118 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8119 unsigned Len = Record[Idx++];
8120 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8125 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8127 std::string Filename = ReadString(Record, Idx);
8128 ResolveImportedPath(F, Filename);
8132 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8134 unsigned Major = Record[Idx++];
8135 unsigned Minor = Record[Idx++];
8136 unsigned Subminor = Record[Idx++];
8138 return VersionTuple(Major);
8140 return VersionTuple(Major, Minor - 1);
8141 return VersionTuple(Major, Minor - 1, Subminor - 1);
8144 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8145 const RecordData &Record,
8147 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8148 return CXXTemporary::Create(Context, Decl);
8151 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
8152 return Diag(CurrentImportLoc, DiagID);
8155 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8156 return Diags.Report(Loc, DiagID);
8159 /// \brief Retrieve the identifier table associated with the
8161 IdentifierTable &ASTReader::getIdentifierTable() {
8162 return PP.getIdentifierTable();
8165 /// \brief Record that the given ID maps to the given switch-case
8167 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
8168 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
8169 "Already have a SwitchCase with this ID");
8170 (*CurrSwitchCaseStmts)[ID] = SC;
8173 /// \brief Retrieve the switch-case statement with the given ID.
8174 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
8175 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
8176 return (*CurrSwitchCaseStmts)[ID];
8179 void ASTReader::ClearSwitchCaseIDs() {
8180 CurrSwitchCaseStmts->clear();
8183 void ASTReader::ReadComments() {
8184 std::vector<RawComment *> Comments;
8185 for (SmallVectorImpl<std::pair<BitstreamCursor,
8186 serialization::ModuleFile *> >::iterator
8187 I = CommentsCursors.begin(),
8188 E = CommentsCursors.end();
8191 BitstreamCursor &Cursor = I->first;
8192 serialization::ModuleFile &F = *I->second;
8193 SavedStreamPosition SavedPosition(Cursor);
8197 llvm::BitstreamEntry Entry =
8198 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
8200 switch (Entry.Kind) {
8201 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8202 case llvm::BitstreamEntry::Error:
8203 Error("malformed block record in AST file");
8205 case llvm::BitstreamEntry::EndBlock:
8207 case llvm::BitstreamEntry::Record:
8208 // The interesting case.
8214 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
8215 case COMMENTS_RAW_COMMENT: {
8217 SourceRange SR = ReadSourceRange(F, Record, Idx);
8218 RawComment::CommentKind Kind =
8219 (RawComment::CommentKind) Record[Idx++];
8220 bool IsTrailingComment = Record[Idx++];
8221 bool IsAlmostTrailingComment = Record[Idx++];
8222 Comments.push_back(new (Context) RawComment(
8223 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8224 Context.getLangOpts().CommentOpts.ParseAllComments));
8230 Context.Comments.addDeserializedComments(Comments);
8234 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8235 // If we know the owning module, use it.
8236 if (Module *M = D->getImportedOwningModule())
8237 return M->getFullModuleName();
8239 // Otherwise, use the name of the top-level module the decl is within.
8240 if (ModuleFile *M = getOwningModuleFile(D))
8241 return M->ModuleName;
8243 // Not from a module.
8247 void ASTReader::finishPendingActions() {
8248 while (!PendingIdentifierInfos.empty() ||
8249 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
8250 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
8251 !PendingUpdateRecords.empty()) {
8252 // If any identifiers with corresponding top-level declarations have
8253 // been loaded, load those declarations now.
8254 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8256 TopLevelDeclsMap TopLevelDecls;
8258 while (!PendingIdentifierInfos.empty()) {
8259 IdentifierInfo *II = PendingIdentifierInfos.back().first;
8260 SmallVector<uint32_t, 4> DeclIDs =
8261 std::move(PendingIdentifierInfos.back().second);
8262 PendingIdentifierInfos.pop_back();
8264 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
8267 // For each decl chain that we wanted to complete while deserializing, mark
8268 // it as "still needs to be completed".
8269 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8270 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8272 PendingIncompleteDeclChains.clear();
8274 // Load pending declaration chains.
8275 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
8276 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
8277 PendingDeclChains.clear();
8279 // Make the most recent of the top-level declarations visible.
8280 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8281 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
8282 IdentifierInfo *II = TLD->first;
8283 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
8284 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
8288 // Load any pending macro definitions.
8289 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
8290 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8291 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8292 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8293 // Initialize the macro history from chained-PCHs ahead of module imports.
8294 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8296 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8297 if (Info.M->Kind != MK_ImplicitModule &&
8298 Info.M->Kind != MK_ExplicitModule)
8299 resolvePendingMacro(II, Info);
8301 // Handle module imports.
8302 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8304 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8305 if (Info.M->Kind == MK_ImplicitModule ||
8306 Info.M->Kind == MK_ExplicitModule)
8307 resolvePendingMacro(II, Info);
8310 PendingMacroIDs.clear();
8312 // Wire up the DeclContexts for Decls that we delayed setting until
8313 // recursive loading is completed.
8314 while (!PendingDeclContextInfos.empty()) {
8315 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8316 PendingDeclContextInfos.pop_front();
8317 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8318 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8319 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8322 // Perform any pending declaration updates.
8323 while (!PendingUpdateRecords.empty()) {
8324 auto Update = PendingUpdateRecords.pop_back_val();
8325 ReadingKindTracker ReadingKind(Read_Decl, *this);
8326 loadDeclUpdateRecords(Update.first, Update.second);
8330 // At this point, all update records for loaded decls are in place, so any
8331 // fake class definitions should have become real.
8332 assert(PendingFakeDefinitionData.empty() &&
8333 "faked up a class definition but never saw the real one");
8335 // If we deserialized any C++ or Objective-C class definitions, any
8336 // Objective-C protocol definitions, or any redeclarable templates, make sure
8337 // that all redeclarations point to the definitions. Note that this can only
8338 // happen now, after the redeclaration chains have been fully wired.
8339 for (Decl *D : PendingDefinitions) {
8340 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8341 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
8342 // Make sure that the TagType points at the definition.
8343 const_cast<TagType*>(TagT)->decl = TD;
8346 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
8347 for (auto *R = getMostRecentExistingDecl(RD); R;
8348 R = R->getPreviousDecl()) {
8350 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
8351 "declaration thinks it's the definition but it isn't");
8352 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
8359 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
8360 // Make sure that the ObjCInterfaceType points at the definition.
8361 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8364 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8365 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8370 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
8371 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8372 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8377 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
8378 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8379 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
8381 PendingDefinitions.clear();
8383 // Load the bodies of any functions or methods we've encountered. We do
8384 // this now (delayed) so that we can be sure that the declaration chains
8385 // have been fully wired up (hasBody relies on this).
8386 // FIXME: We shouldn't require complete redeclaration chains here.
8387 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8388 PBEnd = PendingBodies.end();
8389 PB != PBEnd; ++PB) {
8390 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8391 // FIXME: Check for =delete/=default?
8392 // FIXME: Complain about ODR violations here?
8393 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8394 FD->setLazyBody(PB->second);
8398 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8399 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8400 MD->setLazyBody(PB->second);
8402 PendingBodies.clear();
8405 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8406 getContext().deduplicateMergedDefinitonsFor(ND);
8407 PendingMergedDefinitionsToDeduplicate.clear();
8410 void ASTReader::diagnoseOdrViolations() {
8411 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8414 // Trigger the import of the full definition of each class that had any
8415 // odr-merging problems, so we can produce better diagnostics for them.
8416 // These updates may in turn find and diagnose some ODR failures, so take
8417 // ownership of the set first.
8418 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8419 PendingOdrMergeFailures.clear();
8420 for (auto &Merge : OdrMergeFailures) {
8421 Merge.first->buildLookup();
8422 Merge.first->decls_begin();
8423 Merge.first->bases_begin();
8424 Merge.first->vbases_begin();
8425 for (auto *RD : Merge.second) {
8432 // For each declaration from a merged context, check that the canonical
8433 // definition of that context also contains a declaration of the same
8436 // Caution: this loop does things that might invalidate iterators into
8437 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8438 while (!PendingOdrMergeChecks.empty()) {
8439 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8441 // FIXME: Skip over implicit declarations for now. This matters for things
8442 // like implicitly-declared special member functions. This isn't entirely
8443 // correct; we can end up with multiple unmerged declarations of the same
8445 if (D->isImplicit())
8448 DeclContext *CanonDef = D->getDeclContext();
8451 const Decl *DCanon = D->getCanonicalDecl();
8453 for (auto RI : D->redecls()) {
8454 if (RI->getLexicalDeclContext() == CanonDef) {
8462 // Quick check failed, time to do the slow thing. Note, we can't just
8463 // look up the name of D in CanonDef here, because the member that is
8464 // in CanonDef might not be found by name lookup (it might have been
8465 // replaced by a more recent declaration in the lookup table), and we
8466 // can't necessarily find it in the redeclaration chain because it might
8467 // be merely mergeable, not redeclarable.
8468 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8469 for (auto *CanonMember : CanonDef->decls()) {
8470 if (CanonMember->getCanonicalDecl() == DCanon) {
8471 // This can happen if the declaration is merely mergeable and not
8472 // actually redeclarable (we looked for redeclarations earlier).
8474 // FIXME: We should be able to detect this more efficiently, without
8475 // pulling in all of the members of CanonDef.
8479 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8480 if (ND->getDeclName() == D->getDeclName())
8481 Candidates.push_back(ND);
8485 // The AST doesn't like TagDecls becoming invalid after they've been
8486 // completed. We only really need to mark FieldDecls as invalid here.
8487 if (!isa<TagDecl>(D))
8488 D->setInvalidDecl();
8490 // Ensure we don't accidentally recursively enter deserialization while
8491 // we're producing our diagnostic.
8492 Deserializing RecursionGuard(this);
8494 std::string CanonDefModule =
8495 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8496 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8497 << D << getOwningModuleNameForDiagnostic(D)
8498 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8500 if (Candidates.empty())
8501 Diag(cast<Decl>(CanonDef)->getLocation(),
8502 diag::note_module_odr_violation_no_possible_decls) << D;
8504 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8505 Diag(Candidates[I]->getLocation(),
8506 diag::note_module_odr_violation_possible_decl)
8510 DiagnosedOdrMergeFailures.insert(CanonDef);
8514 if (OdrMergeFailures.empty())
8517 // Ensure we don't accidentally recursively enter deserialization while
8518 // we're producing our diagnostics.
8519 Deserializing RecursionGuard(this);
8521 // Issue any pending ODR-failure diagnostics.
8522 for (auto &Merge : OdrMergeFailures) {
8523 // If we've already pointed out a specific problem with this class, don't
8524 // bother issuing a general "something's different" diagnostic.
8525 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
8528 bool Diagnosed = false;
8529 for (auto *RD : Merge.second) {
8530 // Multiple different declarations got merged together; tell the user
8531 // where they came from.
8532 if (Merge.first != RD) {
8533 // FIXME: Walk the definition, figure out what's different,
8534 // and diagnose that.
8536 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8537 Diag(Merge.first->getLocation(),
8538 diag::err_module_odr_violation_different_definitions)
8539 << Merge.first << Module.empty() << Module;
8543 Diag(RD->getLocation(),
8544 diag::note_module_odr_violation_different_definitions)
8545 << getOwningModuleNameForDiagnostic(RD);
8550 // All definitions are updates to the same declaration. This happens if a
8551 // module instantiates the declaration of a class template specialization
8552 // and two or more other modules instantiate its definition.
8554 // FIXME: Indicate which modules had instantiations of this definition.
8555 // FIXME: How can this even happen?
8556 Diag(Merge.first->getLocation(),
8557 diag::err_module_odr_violation_different_instantiations)
8563 void ASTReader::StartedDeserializing() {
8564 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8565 ReadTimer->startTimer();
8568 void ASTReader::FinishedDeserializing() {
8569 assert(NumCurrentElementsDeserializing &&
8570 "FinishedDeserializing not paired with StartedDeserializing");
8571 if (NumCurrentElementsDeserializing == 1) {
8572 // We decrease NumCurrentElementsDeserializing only after pending actions
8573 // are finished, to avoid recursively re-calling finishPendingActions().
8574 finishPendingActions();
8576 --NumCurrentElementsDeserializing;
8578 if (NumCurrentElementsDeserializing == 0) {
8579 // Propagate exception specification updates along redeclaration chains.
8580 while (!PendingExceptionSpecUpdates.empty()) {
8581 auto Updates = std::move(PendingExceptionSpecUpdates);
8582 PendingExceptionSpecUpdates.clear();
8583 for (auto Update : Updates) {
8584 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8585 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
8586 if (auto *Listener = Context.getASTMutationListener())
8587 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
8588 for (auto *Redecl : Update.second->redecls())
8589 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
8594 ReadTimer->stopTimer();
8596 diagnoseOdrViolations();
8598 // We are not in recursive loading, so it's safe to pass the "interesting"
8599 // decls to the consumer.
8601 PassInterestingDeclsToConsumer();
8605 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
8606 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8607 // Remove any fake results before adding any real ones.
8608 auto It = PendingFakeLookupResults.find(II);
8609 if (It != PendingFakeLookupResults.end()) {
8610 for (auto *ND : It->second)
8611 SemaObj->IdResolver.RemoveDecl(ND);
8612 // FIXME: this works around module+PCH performance issue.
8613 // Rather than erase the result from the map, which is O(n), just clear
8614 // the vector of NamedDecls.
8619 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8620 SemaObj->TUScope->AddDecl(D);
8621 } else if (SemaObj->TUScope) {
8622 // Adding the decl to IdResolver may have failed because it was already in
8623 // (even though it was not added in scope). If it is already in, make sure
8624 // it gets in the scope as well.
8625 if (std::find(SemaObj->IdResolver.begin(Name),
8626 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8627 SemaObj->TUScope->AddDecl(D);
8631 ASTReader::ASTReader(
8632 Preprocessor &PP, ASTContext &Context,
8633 const PCHContainerReader &PCHContainerRdr,
8634 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
8635 StringRef isysroot, bool DisableValidation,
8636 bool AllowASTWithCompilerErrors,
8637 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8638 bool UseGlobalIndex,
8639 std::unique_ptr<llvm::Timer> ReadTimer)
8640 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
8641 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
8642 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
8643 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
8644 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
8645 ReadTimer(std::move(ReadTimer)),
8646 isysroot(isysroot), DisableValidation(DisableValidation),
8647 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8648 AllowConfigurationMismatch(AllowConfigurationMismatch),
8649 ValidateSystemInputs(ValidateSystemInputs),
8650 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
8651 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8652 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8653 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8654 NumIdentifierLookupHits(0), NumSelectorsRead(0),
8655 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8656 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8657 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8658 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8659 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8660 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8661 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
8662 SourceMgr.setExternalSLocEntrySource(this);
8664 for (const auto &Ext : Extensions) {
8665 auto BlockName = Ext->getExtensionMetadata().BlockName;
8666 auto Known = ModuleFileExtensions.find(BlockName);
8667 if (Known != ModuleFileExtensions.end()) {
8668 Diags.Report(diag::warn_duplicate_module_file_extension)
8673 ModuleFileExtensions.insert({BlockName, Ext});
8677 ASTReader::~ASTReader() {
8678 if (OwnsDeserializationListener)
8679 delete DeserializationListener;