1 //===-- ASTReader.cpp - AST File Reader -----------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ASTReader class, which reads AST files.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Serialization/ASTReader.h"
15 #include "ASTCommon.h"
16 #include "ASTReaderInternals.h"
17 #include "clang/AST/ASTConsumer.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/ASTUnresolvedSet.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclGroup.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/NestedNameSpecifier.h"
29 #include "clang/AST/RawCommentList.h"
30 #include "clang/AST/Type.h"
31 #include "clang/AST/TypeLocVisitor.h"
32 #include "clang/AST/UnresolvedSet.h"
33 #include "clang/Basic/CommentOptions.h"
34 #include "clang/Basic/DiagnosticOptions.h"
35 #include "clang/Basic/ExceptionSpecificationType.h"
36 #include "clang/Basic/FileManager.h"
37 #include "clang/Basic/FileSystemOptions.h"
38 #include "clang/Basic/LangOptions.h"
39 #include "clang/Basic/ObjCRuntime.h"
40 #include "clang/Basic/OperatorKinds.h"
41 #include "clang/Basic/Sanitizers.h"
42 #include "clang/Basic/SourceManager.h"
43 #include "clang/Basic/SourceManagerInternals.h"
44 #include "clang/Basic/Specifiers.h"
45 #include "clang/Basic/TargetInfo.h"
46 #include "clang/Basic/TargetOptions.h"
47 #include "clang/Basic/TokenKinds.h"
48 #include "clang/Basic/Version.h"
49 #include "clang/Basic/VersionTuple.h"
50 #include "clang/Frontend/PCHContainerOperations.h"
51 #include "clang/Lex/HeaderSearch.h"
52 #include "clang/Lex/HeaderSearchOptions.h"
53 #include "clang/Lex/MacroInfo.h"
54 #include "clang/Lex/ModuleMap.h"
55 #include "clang/Lex/PreprocessingRecord.h"
56 #include "clang/Lex/Preprocessor.h"
57 #include "clang/Lex/PreprocessorOptions.h"
58 #include "clang/Sema/Scope.h"
59 #include "clang/Sema/Sema.h"
60 #include "clang/Sema/Weak.h"
61 #include "clang/Serialization/ASTDeserializationListener.h"
62 #include "clang/Serialization/GlobalModuleIndex.h"
63 #include "clang/Serialization/ModuleManager.h"
64 #include "clang/Serialization/SerializationDiagnostic.h"
65 #include "llvm/ADT/APFloat.h"
66 #include "llvm/ADT/APInt.h"
67 #include "llvm/ADT/APSInt.h"
68 #include "llvm/ADT/Hashing.h"
69 #include "llvm/ADT/SmallString.h"
70 #include "llvm/ADT/StringExtras.h"
71 #include "llvm/ADT/Triple.h"
72 #include "llvm/Bitcode/BitstreamReader.h"
73 #include "llvm/Support/Compression.h"
74 #include "llvm/Support/Compiler.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/FileSystem.h"
77 #include "llvm/Support/MemoryBuffer.h"
78 #include "llvm/Support/Path.h"
79 #include "llvm/Support/SaveAndRestore.h"
80 #include "llvm/Support/raw_ostream.h"
93 #include <system_error>
98 using namespace clang;
99 using namespace clang::serialization;
100 using namespace clang::serialization::reader;
101 using llvm::BitstreamCursor;
103 //===----------------------------------------------------------------------===//
104 // ChainedASTReaderListener implementation
105 //===----------------------------------------------------------------------===//
108 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
109 return First->ReadFullVersionInformation(FullVersion) ||
110 Second->ReadFullVersionInformation(FullVersion);
113 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
114 First->ReadModuleName(ModuleName);
115 Second->ReadModuleName(ModuleName);
118 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
119 First->ReadModuleMapFile(ModuleMapPath);
120 Second->ReadModuleMapFile(ModuleMapPath);
124 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
126 bool AllowCompatibleDifferences) {
127 return First->ReadLanguageOptions(LangOpts, Complain,
128 AllowCompatibleDifferences) ||
129 Second->ReadLanguageOptions(LangOpts, Complain,
130 AllowCompatibleDifferences);
133 bool ChainedASTReaderListener::ReadTargetOptions(
134 const TargetOptions &TargetOpts, bool Complain,
135 bool AllowCompatibleDifferences) {
136 return First->ReadTargetOptions(TargetOpts, Complain,
137 AllowCompatibleDifferences) ||
138 Second->ReadTargetOptions(TargetOpts, Complain,
139 AllowCompatibleDifferences);
142 bool ChainedASTReaderListener::ReadDiagnosticOptions(
143 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
144 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
145 Second->ReadDiagnosticOptions(DiagOpts, Complain);
149 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
151 return First->ReadFileSystemOptions(FSOpts, Complain) ||
152 Second->ReadFileSystemOptions(FSOpts, Complain);
155 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
156 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
158 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
160 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
164 bool ChainedASTReaderListener::ReadPreprocessorOptions(
165 const PreprocessorOptions &PPOpts, bool Complain,
166 std::string &SuggestedPredefines) {
167 return First->ReadPreprocessorOptions(PPOpts, Complain,
168 SuggestedPredefines) ||
169 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
171 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
173 First->ReadCounter(M, Value);
174 Second->ReadCounter(M, Value);
176 bool ChainedASTReaderListener::needsInputFileVisitation() {
177 return First->needsInputFileVisitation() ||
178 Second->needsInputFileVisitation();
180 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
181 return First->needsSystemInputFileVisitation() ||
182 Second->needsSystemInputFileVisitation();
184 void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
186 First->visitModuleFile(Filename, Kind);
187 Second->visitModuleFile(Filename, Kind);
190 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
193 bool isExplicitModule) {
194 bool Continue = false;
195 if (First->needsInputFileVisitation() &&
196 (!isSystem || First->needsSystemInputFileVisitation()))
197 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
199 if (Second->needsInputFileVisitation() &&
200 (!isSystem || Second->needsSystemInputFileVisitation()))
201 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
206 void ChainedASTReaderListener::readModuleFileExtension(
207 const ModuleFileExtensionMetadata &Metadata) {
208 First->readModuleFileExtension(Metadata);
209 Second->readModuleFileExtension(Metadata);
212 //===----------------------------------------------------------------------===//
213 // PCH validator implementation
214 //===----------------------------------------------------------------------===//
216 ASTReaderListener::~ASTReaderListener() {}
218 /// \brief Compare the given set of language options against an existing set of
219 /// language options.
221 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
222 /// \param AllowCompatibleDifferences If true, differences between compatible
223 /// language options will be permitted.
225 /// \returns true if the languagae options mis-match, false otherwise.
226 static bool checkLanguageOptions(const LangOptions &LangOpts,
227 const LangOptions &ExistingLangOpts,
228 DiagnosticsEngine *Diags,
229 bool AllowCompatibleDifferences = true) {
230 #define LANGOPT(Name, Bits, Default, Description) \
231 if (ExistingLangOpts.Name != LangOpts.Name) { \
233 Diags->Report(diag::err_pch_langopt_mismatch) \
234 << Description << LangOpts.Name << ExistingLangOpts.Name; \
238 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
239 if (ExistingLangOpts.Name != LangOpts.Name) { \
241 Diags->Report(diag::err_pch_langopt_value_mismatch) \
246 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
247 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
249 Diags->Report(diag::err_pch_langopt_value_mismatch) \
254 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
255 if (!AllowCompatibleDifferences) \
256 LANGOPT(Name, Bits, Default, Description)
258 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
259 if (!AllowCompatibleDifferences) \
260 ENUM_LANGOPT(Name, Bits, Default, Description)
262 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
263 if (!AllowCompatibleDifferences) \
264 VALUE_LANGOPT(Name, Bits, Default, Description)
266 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
267 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
268 #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
269 #include "clang/Basic/LangOptions.def"
271 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
273 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
277 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
279 Diags->Report(diag::err_pch_langopt_value_mismatch)
280 << "target Objective-C runtime";
284 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
285 LangOpts.CommentOpts.BlockCommandNames) {
287 Diags->Report(diag::err_pch_langopt_value_mismatch)
288 << "block command names";
295 /// \brief Compare the given set of target options against an existing set of
298 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
300 /// \returns true if the target options mis-match, false otherwise.
301 static bool checkTargetOptions(const TargetOptions &TargetOpts,
302 const TargetOptions &ExistingTargetOpts,
303 DiagnosticsEngine *Diags,
304 bool AllowCompatibleDifferences = true) {
305 #define CHECK_TARGET_OPT(Field, Name) \
306 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
308 Diags->Report(diag::err_pch_targetopt_mismatch) \
309 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
313 // The triple and ABI must match exactly.
314 CHECK_TARGET_OPT(Triple, "target");
315 CHECK_TARGET_OPT(ABI, "target ABI");
317 // We can tolerate different CPUs in many cases, notably when one CPU
318 // supports a strict superset of another. When allowing compatible
319 // differences skip this check.
320 if (!AllowCompatibleDifferences)
321 CHECK_TARGET_OPT(CPU, "target CPU");
323 #undef CHECK_TARGET_OPT
325 // Compare feature sets.
326 SmallVector<StringRef, 4> ExistingFeatures(
327 ExistingTargetOpts.FeaturesAsWritten.begin(),
328 ExistingTargetOpts.FeaturesAsWritten.end());
329 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
330 TargetOpts.FeaturesAsWritten.end());
331 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
332 std::sort(ReadFeatures.begin(), ReadFeatures.end());
334 // We compute the set difference in both directions explicitly so that we can
335 // diagnose the differences differently.
336 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
338 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
339 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
340 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
341 ExistingFeatures.begin(), ExistingFeatures.end(),
342 std::back_inserter(UnmatchedReadFeatures));
344 // If we are allowing compatible differences and the read feature set is
345 // a strict subset of the existing feature set, there is nothing to diagnose.
346 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
350 for (StringRef Feature : UnmatchedReadFeatures)
351 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
352 << /* is-existing-feature */ false << Feature;
353 for (StringRef Feature : UnmatchedExistingFeatures)
354 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
355 << /* is-existing-feature */ true << Feature;
358 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
362 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
364 bool AllowCompatibleDifferences) {
365 const LangOptions &ExistingLangOpts = PP.getLangOpts();
366 return checkLanguageOptions(LangOpts, ExistingLangOpts,
367 Complain ? &Reader.Diags : nullptr,
368 AllowCompatibleDifferences);
371 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
373 bool AllowCompatibleDifferences) {
374 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
375 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
376 Complain ? &Reader.Diags : nullptr,
377 AllowCompatibleDifferences);
382 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
384 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
387 } // end anonymous namespace
389 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
390 DiagnosticsEngine &Diags,
392 typedef DiagnosticsEngine::Level Level;
394 // Check current mappings for new -Werror mappings, and the stored mappings
395 // for cases that were explicitly mapped to *not* be errors that are now
396 // errors because of options like -Werror.
397 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
399 for (DiagnosticsEngine *MappingSource : MappingSources) {
400 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
401 diag::kind DiagID = DiagIDMappingPair.first;
402 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
403 if (CurLevel < DiagnosticsEngine::Error)
404 continue; // not significant
406 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
407 if (StoredLevel < DiagnosticsEngine::Error) {
409 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
410 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
419 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
420 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
421 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
423 return Ext >= diag::Severity::Error;
426 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
427 DiagnosticsEngine &Diags,
428 bool IsSystem, bool Complain) {
431 if (Diags.getSuppressSystemWarnings())
433 // If -Wsystem-headers was not enabled before, be conservative
434 if (StoredDiags.getSuppressSystemWarnings()) {
436 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
441 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
443 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
447 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
448 !StoredDiags.getEnableAllWarnings()) {
450 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
454 if (isExtHandlingFromDiagsError(Diags) &&
455 !isExtHandlingFromDiagsError(StoredDiags)) {
457 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
461 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
464 bool PCHValidator::ReadDiagnosticOptions(
465 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
466 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
467 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
468 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
469 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
470 // This should never fail, because we would have processed these options
471 // before writing them to an ASTFile.
472 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
474 ModuleManager &ModuleMgr = Reader.getModuleManager();
475 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
477 // If the original import came from a file explicitly generated by the user,
478 // don't check the diagnostic mappings.
479 // FIXME: currently this is approximated by checking whether this is not a
480 // module import of an implicitly-loaded module file.
481 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
482 // the transitive closure of its imports, since unrelated modules cannot be
483 // imported until after this module finishes validation.
484 ModuleFile *TopImport = *ModuleMgr.rbegin();
485 while (!TopImport->ImportedBy.empty())
486 TopImport = TopImport->ImportedBy[0];
487 if (TopImport->Kind != MK_ImplicitModule)
490 StringRef ModuleName = TopImport->ModuleName;
491 assert(!ModuleName.empty() && "diagnostic options read before module name");
493 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
494 assert(M && "missing module");
496 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
497 // contains the union of their flags.
498 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
501 /// \brief Collect the macro definitions provided by the given preprocessor
504 collectMacroDefinitions(const PreprocessorOptions &PPOpts,
505 MacroDefinitionsMap &Macros,
506 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
507 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
508 StringRef Macro = PPOpts.Macros[I].first;
509 bool IsUndef = PPOpts.Macros[I].second;
511 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
512 StringRef MacroName = MacroPair.first;
513 StringRef MacroBody = MacroPair.second;
515 // For an #undef'd macro, we only care about the name.
517 if (MacroNames && !Macros.count(MacroName))
518 MacroNames->push_back(MacroName);
520 Macros[MacroName] = std::make_pair("", true);
524 // For a #define'd macro, figure out the actual definition.
525 if (MacroName.size() == Macro.size())
528 // Note: GCC drops anything following an end-of-line character.
529 StringRef::size_type End = MacroBody.find_first_of("\n\r");
530 MacroBody = MacroBody.substr(0, End);
533 if (MacroNames && !Macros.count(MacroName))
534 MacroNames->push_back(MacroName);
535 Macros[MacroName] = std::make_pair(MacroBody, false);
539 /// \brief Check the preprocessor options deserialized from the control block
540 /// against the preprocessor options in an existing preprocessor.
542 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
543 /// \param Validate If true, validate preprocessor options. If false, allow
544 /// macros defined by \p ExistingPPOpts to override those defined by
545 /// \p PPOpts in SuggestedPredefines.
546 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
547 const PreprocessorOptions &ExistingPPOpts,
548 DiagnosticsEngine *Diags,
549 FileManager &FileMgr,
550 std::string &SuggestedPredefines,
551 const LangOptions &LangOpts,
552 bool Validate = true) {
553 // Check macro definitions.
554 MacroDefinitionsMap ASTFileMacros;
555 collectMacroDefinitions(PPOpts, ASTFileMacros);
556 MacroDefinitionsMap ExistingMacros;
557 SmallVector<StringRef, 4> ExistingMacroNames;
558 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
560 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
561 // Dig out the macro definition in the existing preprocessor options.
562 StringRef MacroName = ExistingMacroNames[I];
563 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
565 // Check whether we know anything about this macro name or not.
566 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
567 = ASTFileMacros.find(MacroName);
568 if (!Validate || Known == ASTFileMacros.end()) {
569 // FIXME: Check whether this identifier was referenced anywhere in the
570 // AST file. If so, we should reject the AST file. Unfortunately, this
571 // information isn't in the control block. What shall we do about it?
573 if (Existing.second) {
574 SuggestedPredefines += "#undef ";
575 SuggestedPredefines += MacroName.str();
576 SuggestedPredefines += '\n';
578 SuggestedPredefines += "#define ";
579 SuggestedPredefines += MacroName.str();
580 SuggestedPredefines += ' ';
581 SuggestedPredefines += Existing.first.str();
582 SuggestedPredefines += '\n';
587 // If the macro was defined in one but undef'd in the other, we have a
589 if (Existing.second != Known->second.second) {
591 Diags->Report(diag::err_pch_macro_def_undef)
592 << MacroName << Known->second.second;
597 // If the macro was #undef'd in both, or if the macro bodies are identical,
599 if (Existing.second || Existing.first == Known->second.first)
602 // The macro bodies differ; complain.
604 Diags->Report(diag::err_pch_macro_def_conflict)
605 << MacroName << Known->second.first << Existing.first;
610 // Check whether we're using predefines.
611 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
613 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
618 // Detailed record is important since it is used for the module cache hash.
619 if (LangOpts.Modules &&
620 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
622 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
627 // Compute the #include and #include_macros lines we need.
628 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
629 StringRef File = ExistingPPOpts.Includes[I];
630 if (File == ExistingPPOpts.ImplicitPCHInclude)
633 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
634 != PPOpts.Includes.end())
637 SuggestedPredefines += "#include \"";
638 SuggestedPredefines += File;
639 SuggestedPredefines += "\"\n";
642 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
643 StringRef File = ExistingPPOpts.MacroIncludes[I];
644 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
646 != PPOpts.MacroIncludes.end())
649 SuggestedPredefines += "#__include_macros \"";
650 SuggestedPredefines += File;
651 SuggestedPredefines += "\"\n##\n";
657 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
659 std::string &SuggestedPredefines) {
660 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
662 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
663 Complain? &Reader.Diags : nullptr,
669 bool SimpleASTReaderListener::ReadPreprocessorOptions(
670 const PreprocessorOptions &PPOpts,
672 std::string &SuggestedPredefines) {
673 return checkPreprocessorOptions(PPOpts,
674 PP.getPreprocessorOpts(),
682 /// Check the header search options deserialized from the control block
683 /// against the header search options in an existing preprocessor.
685 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
686 static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
687 StringRef SpecificModuleCachePath,
688 StringRef ExistingModuleCachePath,
689 DiagnosticsEngine *Diags,
690 const LangOptions &LangOpts) {
691 if (LangOpts.Modules) {
692 if (SpecificModuleCachePath != ExistingModuleCachePath) {
694 Diags->Report(diag::err_pch_modulecache_mismatch)
695 << SpecificModuleCachePath << ExistingModuleCachePath;
703 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
704 StringRef SpecificModuleCachePath,
706 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
707 PP.getHeaderSearchInfo().getModuleCachePath(),
708 Complain ? &Reader.Diags : nullptr,
712 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
713 PP.setCounterValue(Value);
716 //===----------------------------------------------------------------------===//
717 // AST reader implementation
718 //===----------------------------------------------------------------------===//
720 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
721 bool TakeOwnership) {
722 DeserializationListener = Listener;
723 OwnsDeserializationListener = TakeOwnership;
726 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
727 return serialization::ComputeHash(Sel);
730 std::pair<unsigned, unsigned>
731 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
732 using namespace llvm::support;
733 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
734 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
735 return std::make_pair(KeyLen, DataLen);
738 ASTSelectorLookupTrait::internal_key_type
739 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
740 using namespace llvm::support;
741 SelectorTable &SelTable = Reader.getContext().Selectors;
742 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
743 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
744 F, endian::readNext<uint32_t, little, unaligned>(d));
746 return SelTable.getNullarySelector(FirstII);
748 return SelTable.getUnarySelector(FirstII);
750 SmallVector<IdentifierInfo *, 16> Args;
751 Args.push_back(FirstII);
752 for (unsigned I = 1; I != N; ++I)
753 Args.push_back(Reader.getLocalIdentifier(
754 F, endian::readNext<uint32_t, little, unaligned>(d)));
756 return SelTable.getSelector(N, Args.data());
759 ASTSelectorLookupTrait::data_type
760 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
762 using namespace llvm::support;
766 Result.ID = Reader.getGlobalSelectorID(
767 F, endian::readNext<uint32_t, little, unaligned>(d));
768 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
769 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
770 Result.InstanceBits = FullInstanceBits & 0x3;
771 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
772 Result.FactoryBits = FullFactoryBits & 0x3;
773 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
774 unsigned NumInstanceMethods = FullInstanceBits >> 3;
775 unsigned NumFactoryMethods = FullFactoryBits >> 3;
777 // Load instance methods
778 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
779 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
780 F, endian::readNext<uint32_t, little, unaligned>(d)))
781 Result.Instance.push_back(Method);
784 // Load factory methods
785 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
786 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
787 F, endian::readNext<uint32_t, little, unaligned>(d)))
788 Result.Factory.push_back(Method);
794 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
795 return llvm::HashString(a);
798 std::pair<unsigned, unsigned>
799 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
800 using namespace llvm::support;
801 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
802 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
803 return std::make_pair(KeyLen, DataLen);
806 ASTIdentifierLookupTraitBase::internal_key_type
807 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
808 assert(n >= 2 && d[n-1] == '\0');
809 return StringRef((const char*) d, n-1);
812 /// \brief Whether the given identifier is "interesting".
813 static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
815 return II.hadMacroDefinition() ||
817 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
818 II.hasRevertedTokenIDToIdentifier() ||
819 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
820 II.getFETokenInfo<void>());
823 static bool readBit(unsigned &Bits) {
824 bool Value = Bits & 0x1;
829 IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
830 using namespace llvm::support;
831 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
832 return Reader.getGlobalIdentifierID(F, RawID >> 1);
835 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
836 if (!II.isFromAST()) {
838 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
839 if (isInterestingIdentifier(Reader, II, IsModule))
840 II.setChangedSinceDeserialization();
844 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
845 const unsigned char* d,
847 using namespace llvm::support;
848 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
849 bool IsInteresting = RawID & 0x01;
851 // Wipe out the "is interesting" bit.
854 // Build the IdentifierInfo and link the identifier ID with it.
855 IdentifierInfo *II = KnownII;
857 II = &Reader.getIdentifierTable().getOwn(k);
860 markIdentifierFromAST(Reader, *II);
861 Reader.markIdentifierUpToDate(II);
863 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
864 if (!IsInteresting) {
865 // For uninteresting identifiers, there's nothing else to do. Just notify
866 // the reader that we've finished loading this identifier.
867 Reader.SetIdentifierInfo(ID, II);
871 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
872 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
873 bool CPlusPlusOperatorKeyword = readBit(Bits);
874 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
875 bool HasRevertedBuiltin = readBit(Bits);
876 bool Poisoned = readBit(Bits);
877 bool ExtensionToken = readBit(Bits);
878 bool HadMacroDefinition = readBit(Bits);
880 assert(Bits == 0 && "Extra bits in the identifier?");
883 // Set or check the various bits in the IdentifierInfo structure.
884 // Token IDs are read-only.
885 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
886 II->revertTokenIDToIdentifier();
888 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
889 else if (HasRevertedBuiltin && II->getBuiltinID()) {
891 assert((II->hasRevertedBuiltin() ||
892 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
893 "Incorrect ObjC keyword or builtin ID");
895 assert(II->isExtensionToken() == ExtensionToken &&
896 "Incorrect extension token flag");
897 (void)ExtensionToken;
899 II->setIsPoisoned(true);
900 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
901 "Incorrect C++ operator keyword flag");
902 (void)CPlusPlusOperatorKeyword;
904 // If this identifier is a macro, deserialize the macro
906 if (HadMacroDefinition) {
907 uint32_t MacroDirectivesOffset =
908 endian::readNext<uint32_t, little, unaligned>(d);
911 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
914 Reader.SetIdentifierInfo(ID, II);
916 // Read all of the declarations visible at global scope with this
919 SmallVector<uint32_t, 4> DeclIDs;
920 for (; DataLen > 0; DataLen -= 4)
921 DeclIDs.push_back(Reader.getGlobalDeclID(
922 F, endian::readNext<uint32_t, little, unaligned>(d)));
923 Reader.SetGloballyVisibleDecls(II, DeclIDs);
929 DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
930 : Kind(Name.getNameKind()) {
932 case DeclarationName::Identifier:
933 Data = (uint64_t)Name.getAsIdentifierInfo();
935 case DeclarationName::ObjCZeroArgSelector:
936 case DeclarationName::ObjCOneArgSelector:
937 case DeclarationName::ObjCMultiArgSelector:
938 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
940 case DeclarationName::CXXOperatorName:
941 Data = Name.getCXXOverloadedOperator();
943 case DeclarationName::CXXLiteralOperatorName:
944 Data = (uint64_t)Name.getCXXLiteralIdentifier();
946 case DeclarationName::CXXConstructorName:
947 case DeclarationName::CXXDestructorName:
948 case DeclarationName::CXXConversionFunctionName:
949 case DeclarationName::CXXUsingDirective:
955 unsigned DeclarationNameKey::getHash() const {
956 llvm::FoldingSetNodeID ID;
960 case DeclarationName::Identifier:
961 case DeclarationName::CXXLiteralOperatorName:
962 ID.AddString(((IdentifierInfo*)Data)->getName());
964 case DeclarationName::ObjCZeroArgSelector:
965 case DeclarationName::ObjCOneArgSelector:
966 case DeclarationName::ObjCMultiArgSelector:
967 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
969 case DeclarationName::CXXOperatorName:
970 ID.AddInteger((OverloadedOperatorKind)Data);
972 case DeclarationName::CXXConstructorName:
973 case DeclarationName::CXXDestructorName:
974 case DeclarationName::CXXConversionFunctionName:
975 case DeclarationName::CXXUsingDirective:
979 return ID.ComputeHash();
983 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
984 using namespace llvm::support;
985 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
986 return Reader.getLocalModuleFile(F, ModuleFileID);
989 std::pair<unsigned, unsigned>
990 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
991 using namespace llvm::support;
992 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
993 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
994 return std::make_pair(KeyLen, DataLen);
997 ASTDeclContextNameLookupTrait::internal_key_type
998 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
999 using namespace llvm::support;
1001 auto Kind = (DeclarationName::NameKind)*d++;
1004 case DeclarationName::Identifier:
1005 Data = (uint64_t)Reader.getLocalIdentifier(
1006 F, endian::readNext<uint32_t, little, unaligned>(d));
1008 case DeclarationName::ObjCZeroArgSelector:
1009 case DeclarationName::ObjCOneArgSelector:
1010 case DeclarationName::ObjCMultiArgSelector:
1012 (uint64_t)Reader.getLocalSelector(
1013 F, endian::readNext<uint32_t, little, unaligned>(
1014 d)).getAsOpaquePtr();
1016 case DeclarationName::CXXOperatorName:
1017 Data = *d++; // OverloadedOperatorKind
1019 case DeclarationName::CXXLiteralOperatorName:
1020 Data = (uint64_t)Reader.getLocalIdentifier(
1021 F, endian::readNext<uint32_t, little, unaligned>(d));
1023 case DeclarationName::CXXConstructorName:
1024 case DeclarationName::CXXDestructorName:
1025 case DeclarationName::CXXConversionFunctionName:
1026 case DeclarationName::CXXUsingDirective:
1031 return DeclarationNameKey(Kind, Data);
1034 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1035 const unsigned char *d,
1037 data_type_builder &Val) {
1038 using namespace llvm::support;
1039 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1040 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1041 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1045 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1046 BitstreamCursor &Cursor,
1049 assert(Offset != 0);
1051 SavedStreamPosition SavedPosition(Cursor);
1052 Cursor.JumpToBit(Offset);
1056 unsigned Code = Cursor.ReadCode();
1057 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1058 if (RecCode != DECL_CONTEXT_LEXICAL) {
1059 Error("Expected lexical block");
1063 assert(!isa<TranslationUnitDecl>(DC) &&
1064 "expected a TU_UPDATE_LEXICAL record for TU");
1065 // If we are handling a C++ class template instantiation, we can see multiple
1066 // lexical updates for the same record. It's important that we select only one
1067 // of them, so that field numbering works properly. Just pick the first one we
1069 auto &Lex = LexicalDecls[DC];
1071 Lex = std::make_pair(
1072 &M, llvm::makeArrayRef(
1073 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1077 DC->setHasExternalLexicalStorage(true);
1081 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1082 BitstreamCursor &Cursor,
1085 assert(Offset != 0);
1087 SavedStreamPosition SavedPosition(Cursor);
1088 Cursor.JumpToBit(Offset);
1092 unsigned Code = Cursor.ReadCode();
1093 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1094 if (RecCode != DECL_CONTEXT_VISIBLE) {
1095 Error("Expected visible lookup table block");
1099 // We can't safely determine the primary context yet, so delay attaching the
1100 // lookup table until we're done with recursive deserialization.
1101 auto *Data = (const unsigned char*)Blob.data();
1102 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1106 void ASTReader::Error(StringRef Msg) {
1107 Error(diag::err_fe_pch_malformed, Msg);
1108 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1109 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1110 Diag(diag::note_module_cache_path)
1111 << PP.getHeaderSearchInfo().getModuleCachePath();
1115 void ASTReader::Error(unsigned DiagID,
1116 StringRef Arg1, StringRef Arg2) {
1117 if (Diags.isDiagnosticInFlight())
1118 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1120 Diag(DiagID) << Arg1 << Arg2;
1123 //===----------------------------------------------------------------------===//
1124 // Source Manager Deserialization
1125 //===----------------------------------------------------------------------===//
1127 /// \brief Read the line table in the source manager block.
1128 /// \returns true if there was an error.
1129 bool ASTReader::ParseLineTable(ModuleFile &F,
1130 const RecordData &Record) {
1132 LineTableInfo &LineTable = SourceMgr.getLineTable();
1134 // Parse the file names
1135 std::map<int, int> FileIDs;
1136 for (unsigned I = 0; Record[Idx]; ++I) {
1137 // Extract the file name
1138 auto Filename = ReadPath(F, Record, Idx);
1139 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1143 // Parse the line entries
1144 std::vector<LineEntry> Entries;
1145 while (Idx < Record.size()) {
1146 int FID = Record[Idx++];
1147 assert(FID >= 0 && "Serialized line entries for non-local file.");
1148 // Remap FileID from 1-based old view.
1149 FID += F.SLocEntryBaseID - 1;
1151 // Extract the line entries
1152 unsigned NumEntries = Record[Idx++];
1153 assert(NumEntries && "no line entries for file ID");
1155 Entries.reserve(NumEntries);
1156 for (unsigned I = 0; I != NumEntries; ++I) {
1157 unsigned FileOffset = Record[Idx++];
1158 unsigned LineNo = Record[Idx++];
1159 int FilenameID = FileIDs[Record[Idx++]];
1160 SrcMgr::CharacteristicKind FileKind
1161 = (SrcMgr::CharacteristicKind)Record[Idx++];
1162 unsigned IncludeOffset = Record[Idx++];
1163 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1164 FileKind, IncludeOffset));
1166 LineTable.AddEntry(FileID::get(FID), Entries);
1172 /// \brief Read a source manager block
1173 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1174 using namespace SrcMgr;
1176 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1178 // Set the source-location entry cursor to the current position in
1179 // the stream. This cursor will be used to read the contents of the
1180 // source manager block initially, and then lazily read
1181 // source-location entries as needed.
1182 SLocEntryCursor = F.Stream;
1184 // The stream itself is going to skip over the source manager block.
1185 if (F.Stream.SkipBlock()) {
1186 Error("malformed block record in AST file");
1190 // Enter the source manager block.
1191 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1192 Error("malformed source manager block record in AST file");
1198 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1201 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1202 case llvm::BitstreamEntry::Error:
1203 Error("malformed block record in AST file");
1205 case llvm::BitstreamEntry::EndBlock:
1207 case llvm::BitstreamEntry::Record:
1208 // The interesting case.
1215 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
1216 default: // Default behavior: ignore.
1219 case SM_SLOC_FILE_ENTRY:
1220 case SM_SLOC_BUFFER_ENTRY:
1221 case SM_SLOC_EXPANSION_ENTRY:
1222 // Once we hit one of the source location entries, we're done.
1228 /// \brief If a header file is not found at the path that we expect it to be
1229 /// and the PCH file was moved from its original location, try to resolve the
1230 /// file by assuming that header+PCH were moved together and the header is in
1231 /// the same place relative to the PCH.
1233 resolveFileRelativeToOriginalDir(const std::string &Filename,
1234 const std::string &OriginalDir,
1235 const std::string &CurrDir) {
1236 assert(OriginalDir != CurrDir &&
1237 "No point trying to resolve the file if the PCH dir didn't change");
1238 using namespace llvm::sys;
1239 SmallString<128> filePath(Filename);
1240 fs::make_absolute(filePath);
1241 assert(path::is_absolute(OriginalDir));
1242 SmallString<128> currPCHPath(CurrDir);
1244 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1245 fileDirE = path::end(path::parent_path(filePath));
1246 path::const_iterator origDirI = path::begin(OriginalDir),
1247 origDirE = path::end(OriginalDir);
1248 // Skip the common path components from filePath and OriginalDir.
1249 while (fileDirI != fileDirE && origDirI != origDirE &&
1250 *fileDirI == *origDirI) {
1254 for (; origDirI != origDirE; ++origDirI)
1255 path::append(currPCHPath, "..");
1256 path::append(currPCHPath, fileDirI, fileDirE);
1257 path::append(currPCHPath, path::filename(Filename));
1258 return currPCHPath.str();
1261 bool ASTReader::ReadSLocEntry(int ID) {
1265 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1266 Error("source location entry ID out-of-range for AST file");
1270 // Local helper to read the (possibly-compressed) buffer data following the
1272 auto ReadBuffer = [this](
1273 BitstreamCursor &SLocEntryCursor,
1274 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1277 unsigned Code = SLocEntryCursor.ReadCode();
1278 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1280 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1281 SmallString<0> Uncompressed;
1282 if (llvm::zlib::uncompress(Blob, Uncompressed, Record[0]) !=
1283 llvm::zlib::StatusOK) {
1284 Error("could not decompress embedded file contents");
1287 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1288 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1289 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1291 Error("AST record has invalid code");
1296 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1297 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
1298 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1299 unsigned BaseOffset = F->SLocEntryBaseOffset;
1301 ++NumSLocEntriesRead;
1302 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1303 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1304 Error("incorrectly-formatted source location entry in AST file");
1310 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
1312 Error("incorrectly-formatted source location entry in AST file");
1315 case SM_SLOC_FILE_ENTRY: {
1316 // We will detect whether a file changed and return 'Failure' for it, but
1317 // we will also try to fail gracefully by setting up the SLocEntry.
1318 unsigned InputID = Record[4];
1319 InputFile IF = getInputFile(*F, InputID);
1320 const FileEntry *File = IF.getFile();
1321 bool OverriddenBuffer = IF.isOverridden();
1323 // Note that we only check if a File was returned. If it was out-of-date
1324 // we have complained but we will continue creating a FileID to recover
1329 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1330 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1331 // This is the module's main file.
1332 IncludeLoc = getImportLocation(F);
1334 SrcMgr::CharacteristicKind
1335 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1336 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1337 ID, BaseOffset + Record[0]);
1338 SrcMgr::FileInfo &FileInfo =
1339 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1340 FileInfo.NumCreatedFIDs = Record[5];
1342 FileInfo.setHasLineDirectives();
1344 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1345 unsigned NumFileDecls = Record[7];
1347 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1348 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1352 const SrcMgr::ContentCache *ContentCache
1353 = SourceMgr.getOrCreateContentCache(File,
1354 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1355 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1356 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1357 !ContentCache->getRawBuffer()) {
1358 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1361 SourceMgr.overrideFileContents(File, std::move(Buffer));
1367 case SM_SLOC_BUFFER_ENTRY: {
1368 const char *Name = Blob.data();
1369 unsigned Offset = Record[0];
1370 SrcMgr::CharacteristicKind
1371 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1372 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1373 if (IncludeLoc.isInvalid() && F->isModule()) {
1374 IncludeLoc = getImportLocation(F);
1377 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1380 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1381 BaseOffset + Offset, IncludeLoc);
1385 case SM_SLOC_EXPANSION_ENTRY: {
1386 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1387 SourceMgr.createExpansionLoc(SpellingLoc,
1388 ReadSourceLocation(*F, Record[2]),
1389 ReadSourceLocation(*F, Record[3]),
1392 BaseOffset + Record[0]);
1400 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1402 return std::make_pair(SourceLocation(), "");
1404 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1405 Error("source location entry ID out-of-range for AST file");
1406 return std::make_pair(SourceLocation(), "");
1409 // Find which module file this entry lands in.
1410 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1412 return std::make_pair(SourceLocation(), "");
1414 // FIXME: Can we map this down to a particular submodule? That would be
1416 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1419 /// \brief Find the location where the module F is imported.
1420 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1421 if (F->ImportLoc.isValid())
1422 return F->ImportLoc;
1424 // Otherwise we have a PCH. It's considered to be "imported" at the first
1425 // location of its includer.
1426 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1427 // Main file is the importer.
1428 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1429 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1431 return F->ImportedBy[0]->FirstLoc;
1434 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1435 /// specified cursor. Read the abbreviations that are at the top of the block
1436 /// and then leave the cursor pointing into the block.
1437 bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
1438 if (Cursor.EnterSubBlock(BlockID))
1442 uint64_t Offset = Cursor.GetCurrentBitNo();
1443 unsigned Code = Cursor.ReadCode();
1445 // We expect all abbrevs to be at the start of the block.
1446 if (Code != llvm::bitc::DEFINE_ABBREV) {
1447 Cursor.JumpToBit(Offset);
1450 Cursor.ReadAbbrevRecord();
1454 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1458 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1459 Tok.setLength(Record[Idx++]);
1460 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1461 Tok.setIdentifierInfo(II);
1462 Tok.setKind((tok::TokenKind)Record[Idx++]);
1463 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1467 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1468 BitstreamCursor &Stream = F.MacroCursor;
1470 // Keep track of where we are in the stream, then jump back there
1471 // after reading this macro.
1472 SavedStreamPosition SavedPosition(Stream);
1474 Stream.JumpToBit(Offset);
1476 SmallVector<IdentifierInfo*, 16> MacroArgs;
1477 MacroInfo *Macro = nullptr;
1480 // Advance to the next record, but if we get to the end of the block, don't
1481 // pop it (removing all the abbreviations from the cursor) since we want to
1482 // be able to reseek within the block and read entries.
1483 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1484 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1486 switch (Entry.Kind) {
1487 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1488 case llvm::BitstreamEntry::Error:
1489 Error("malformed block record in AST file");
1491 case llvm::BitstreamEntry::EndBlock:
1493 case llvm::BitstreamEntry::Record:
1494 // The interesting case.
1500 PreprocessorRecordTypes RecType =
1501 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
1503 case PP_MODULE_MACRO:
1504 case PP_MACRO_DIRECTIVE_HISTORY:
1507 case PP_MACRO_OBJECT_LIKE:
1508 case PP_MACRO_FUNCTION_LIKE: {
1509 // If we already have a macro, that means that we've hit the end
1510 // of the definition of the macro we were looking for. We're
1515 unsigned NextIndex = 1; // Skip identifier ID.
1516 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
1517 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1518 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
1519 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1520 MI->setIsUsed(Record[NextIndex++]);
1521 MI->setUsedForHeaderGuard(Record[NextIndex++]);
1523 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1524 // Decode function-like macro info.
1525 bool isC99VarArgs = Record[NextIndex++];
1526 bool isGNUVarArgs = Record[NextIndex++];
1527 bool hasCommaPasting = Record[NextIndex++];
1529 unsigned NumArgs = Record[NextIndex++];
1530 for (unsigned i = 0; i != NumArgs; ++i)
1531 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1533 // Install function-like macro info.
1534 MI->setIsFunctionLike();
1535 if (isC99VarArgs) MI->setIsC99Varargs();
1536 if (isGNUVarArgs) MI->setIsGNUVarargs();
1537 if (hasCommaPasting) MI->setHasCommaPasting();
1538 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
1541 // Remember that we saw this macro last so that we add the tokens that
1542 // form its body to it.
1545 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1546 Record[NextIndex]) {
1547 // We have a macro definition. Register the association
1548 PreprocessedEntityID
1549 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1550 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1551 PreprocessingRecord::PPEntityID PPID =
1552 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1553 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1554 PPRec.getPreprocessedEntity(PPID));
1556 PPRec.RegisterMacroDefinition(Macro, PPDef);
1564 // If we see a TOKEN before a PP_MACRO_*, then the file is
1565 // erroneous, just pretend we didn't see this.
1569 Token Tok = ReadToken(F, Record, Idx);
1570 Macro->AddTokenToBody(Tok);
1577 PreprocessedEntityID
1578 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1579 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1580 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1581 assert(I != M.PreprocessedEntityRemap.end()
1582 && "Invalid index into preprocessed entity index remap");
1584 return LocalID + I->second;
1587 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1588 return llvm::hash_combine(ikey.Size, ikey.ModTime);
1591 HeaderFileInfoTrait::internal_key_type
1592 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1593 internal_key_type ikey = {FE->getSize(),
1594 M.HasTimestamps ? FE->getModificationTime() : 0,
1595 FE->getName(), /*Imported*/ false};
1599 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1600 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
1603 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
1606 // Determine whether the actual files are equivalent.
1607 FileManager &FileMgr = Reader.getFileManager();
1608 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1610 return FileMgr.getFile(Key.Filename);
1612 std::string Resolved = Key.Filename;
1613 Reader.ResolveImportedPath(M, Resolved);
1614 return FileMgr.getFile(Resolved);
1617 const FileEntry *FEA = GetFile(a);
1618 const FileEntry *FEB = GetFile(b);
1619 return FEA && FEA == FEB;
1622 std::pair<unsigned, unsigned>
1623 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1624 using namespace llvm::support;
1625 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1626 unsigned DataLen = (unsigned) *d++;
1627 return std::make_pair(KeyLen, DataLen);
1630 HeaderFileInfoTrait::internal_key_type
1631 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1632 using namespace llvm::support;
1633 internal_key_type ikey;
1634 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1635 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1636 ikey.Filename = (const char *)d;
1637 ikey.Imported = true;
1641 HeaderFileInfoTrait::data_type
1642 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1644 const unsigned char *End = d + DataLen;
1645 using namespace llvm::support;
1647 unsigned Flags = *d++;
1648 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1649 HFI.isImport |= (Flags >> 4) & 0x01;
1650 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1651 HFI.DirInfo = (Flags >> 1) & 0x03;
1652 HFI.IndexHeaderMapHeader = Flags & 0x01;
1653 // FIXME: Find a better way to handle this. Maybe just store a
1654 // "has been included" flag?
1655 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1657 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1658 M, endian::readNext<uint32_t, little, unaligned>(d));
1659 if (unsigned FrameworkOffset =
1660 endian::readNext<uint32_t, little, unaligned>(d)) {
1661 // The framework offset is 1 greater than the actual offset,
1662 // since 0 is used as an indicator for "no framework name".
1663 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1664 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1667 assert((End - d) % 4 == 0 &&
1668 "Wrong data length in HeaderFileInfo deserialization");
1670 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1671 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1674 // This header is part of a module. Associate it with the module to enable
1675 // implicit module import.
1676 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1677 Module *Mod = Reader.getSubmodule(GlobalSMID);
1678 FileManager &FileMgr = Reader.getFileManager();
1680 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1682 std::string Filename = key.Filename;
1684 Reader.ResolveImportedPath(M, Filename);
1685 // FIXME: This is not always the right filename-as-written, but we're not
1686 // going to use this information to rebuild the module, so it doesn't make
1687 // a lot of difference.
1688 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
1689 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1690 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
1693 // This HeaderFileInfo was externally loaded.
1694 HFI.External = true;
1699 void ASTReader::addPendingMacro(IdentifierInfo *II,
1701 uint64_t MacroDirectivesOffset) {
1702 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1703 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1706 void ASTReader::ReadDefinedMacros() {
1707 // Note that we are loading defined macros.
1708 Deserializing Macros(this);
1710 for (auto &I : llvm::reverse(ModuleMgr)) {
1711 BitstreamCursor &MacroCursor = I->MacroCursor;
1713 // If there was no preprocessor block, skip this file.
1714 if (MacroCursor.getBitcodeBytes().empty())
1717 BitstreamCursor Cursor = MacroCursor;
1718 Cursor.JumpToBit(I->MacroStartOffset);
1722 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1725 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1726 case llvm::BitstreamEntry::Error:
1727 Error("malformed block record in AST file");
1729 case llvm::BitstreamEntry::EndBlock:
1732 case llvm::BitstreamEntry::Record:
1734 switch (Cursor.readRecord(E.ID, Record)) {
1735 default: // Default behavior: ignore.
1738 case PP_MACRO_OBJECT_LIKE:
1739 case PP_MACRO_FUNCTION_LIKE: {
1740 IdentifierInfo *II = getLocalIdentifier(*I, Record[0]);
1741 if (II->isOutOfDate())
1742 updateOutOfDateIdentifier(*II);
1759 /// \brief Visitor class used to look up identifirs in an AST file.
1760 class IdentifierLookupVisitor {
1763 unsigned PriorGeneration;
1764 unsigned &NumIdentifierLookups;
1765 unsigned &NumIdentifierLookupHits;
1766 IdentifierInfo *Found;
1769 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1770 unsigned &NumIdentifierLookups,
1771 unsigned &NumIdentifierLookupHits)
1772 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1773 PriorGeneration(PriorGeneration),
1774 NumIdentifierLookups(NumIdentifierLookups),
1775 NumIdentifierLookupHits(NumIdentifierLookupHits),
1780 bool operator()(ModuleFile &M) {
1781 // If we've already searched this module file, skip it now.
1782 if (M.Generation <= PriorGeneration)
1785 ASTIdentifierLookupTable *IdTable
1786 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1790 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
1792 ++NumIdentifierLookups;
1793 ASTIdentifierLookupTable::iterator Pos =
1794 IdTable->find_hashed(Name, NameHash, &Trait);
1795 if (Pos == IdTable->end())
1798 // Dereferencing the iterator has the effect of building the
1799 // IdentifierInfo node and populating it with the various
1800 // declarations it needs.
1801 ++NumIdentifierLookupHits;
1806 // \brief Retrieve the identifier info found within the module
1808 IdentifierInfo *getIdentifierInfo() const { return Found; }
1811 } // end anonymous namespace
1813 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1814 // Note that we are loading an identifier.
1815 Deserializing AnIdentifier(this);
1817 unsigned PriorGeneration = 0;
1818 if (getContext().getLangOpts().Modules)
1819 PriorGeneration = IdentifierGeneration[&II];
1821 // If there is a global index, look there first to determine which modules
1822 // provably do not have any results for this identifier.
1823 GlobalModuleIndex::HitSet Hits;
1824 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
1825 if (!loadGlobalIndex()) {
1826 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1831 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
1832 NumIdentifierLookups,
1833 NumIdentifierLookupHits);
1834 ModuleMgr.visit(Visitor, HitsPtr);
1835 markIdentifierUpToDate(&II);
1838 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1842 II->setOutOfDate(false);
1844 // Update the generation for this identifier.
1845 if (getContext().getLangOpts().Modules)
1846 IdentifierGeneration[II] = getGeneration();
1849 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1850 const PendingMacroInfo &PMInfo) {
1851 ModuleFile &M = *PMInfo.M;
1853 BitstreamCursor &Cursor = M.MacroCursor;
1854 SavedStreamPosition SavedPosition(Cursor);
1855 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
1857 struct ModuleMacroRecord {
1858 SubmoduleID SubModID;
1860 SmallVector<SubmoduleID, 8> Overrides;
1862 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
1864 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1865 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1869 llvm::BitstreamEntry Entry =
1870 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1871 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1872 Error("malformed block record in AST file");
1877 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
1878 case PP_MACRO_DIRECTIVE_HISTORY:
1881 case PP_MODULE_MACRO: {
1882 ModuleMacros.push_back(ModuleMacroRecord());
1883 auto &Info = ModuleMacros.back();
1884 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1885 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
1886 for (int I = 2, N = Record.size(); I != N; ++I)
1887 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
1892 Error("malformed block record in AST file");
1896 // We found the macro directive history; that's the last record
1901 // Module macros are listed in reverse dependency order.
1903 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
1904 llvm::SmallVector<ModuleMacro*, 8> Overrides;
1905 for (auto &MMR : ModuleMacros) {
1907 for (unsigned ModID : MMR.Overrides) {
1908 Module *Mod = getSubmodule(ModID);
1909 auto *Macro = PP.getModuleMacro(Mod, II);
1910 assert(Macro && "missing definition for overridden macro");
1911 Overrides.push_back(Macro);
1914 bool Inserted = false;
1915 Module *Owner = getSubmodule(MMR.SubModID);
1916 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
1920 // Don't read the directive history for a module; we don't have anywhere
1925 // Deserialize the macro directives history in reverse source-order.
1926 MacroDirective *Latest = nullptr, *Earliest = nullptr;
1927 unsigned Idx = 0, N = Record.size();
1929 MacroDirective *MD = nullptr;
1930 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
1931 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1933 case MacroDirective::MD_Define: {
1934 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
1935 MD = PP.AllocateDefMacroDirective(MI, Loc);
1938 case MacroDirective::MD_Undefine: {
1939 MD = PP.AllocateUndefMacroDirective(Loc);
1942 case MacroDirective::MD_Visibility:
1943 bool isPublic = Record[Idx++];
1944 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1951 Earliest->setPrevious(MD);
1956 PP.setLoadedMacroDirective(II, Earliest, Latest);
1959 ASTReader::InputFileInfo
1960 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
1961 // Go find this input file.
1962 BitstreamCursor &Cursor = F.InputFilesCursor;
1963 SavedStreamPosition SavedPosition(Cursor);
1964 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1966 unsigned Code = Cursor.ReadCode();
1970 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1971 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1972 "invalid record type for input file");
1975 assert(Record[0] == ID && "Bogus stored ID or offset");
1977 R.StoredSize = static_cast<off_t>(Record[1]);
1978 R.StoredTime = static_cast<time_t>(Record[2]);
1979 R.Overridden = static_cast<bool>(Record[3]);
1980 R.Transient = static_cast<bool>(Record[4]);
1982 ResolveImportedPath(F, R.Filename);
1986 static unsigned moduleKindForDiagnostic(ModuleKind Kind);
1987 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
1988 // If this ID is bogus, just return an empty input file.
1989 if (ID == 0 || ID > F.InputFilesLoaded.size())
1992 // If we've already loaded this input file, return it.
1993 if (F.InputFilesLoaded[ID-1].getFile())
1994 return F.InputFilesLoaded[ID-1];
1996 if (F.InputFilesLoaded[ID-1].isNotFound())
1999 // Go find this input file.
2000 BitstreamCursor &Cursor = F.InputFilesCursor;
2001 SavedStreamPosition SavedPosition(Cursor);
2002 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2004 InputFileInfo FI = readInputFileInfo(F, ID);
2005 off_t StoredSize = FI.StoredSize;
2006 time_t StoredTime = FI.StoredTime;
2007 bool Overridden = FI.Overridden;
2008 bool Transient = FI.Transient;
2009 StringRef Filename = FI.Filename;
2011 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
2013 // If we didn't find the file, resolve it relative to the
2014 // original directory from which this AST file was created.
2015 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
2016 F.OriginalDir != CurrentDir) {
2017 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2020 if (!Resolved.empty())
2021 File = FileMgr.getFile(Resolved);
2024 // For an overridden file, create a virtual file with the stored
2026 if ((Overridden || Transient) && File == nullptr)
2027 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2029 if (File == nullptr) {
2031 std::string ErrorStr = "could not find file '";
2032 ErrorStr += Filename;
2033 ErrorStr += "' referenced by AST file '";
2034 ErrorStr += F.FileName;
2038 // Record that we didn't find the file.
2039 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2043 // Check if there was a request to override the contents of the file
2044 // that was part of the precompiled header. Overridding such a file
2045 // can lead to problems when lexing using the source locations from the
2047 SourceManager &SM = getSourceManager();
2048 // FIXME: Reject if the overrides are different.
2049 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
2051 Error(diag::err_fe_pch_file_overridden, Filename);
2052 // After emitting the diagnostic, recover by disabling the override so
2053 // that the original file will be used.
2055 // FIXME: This recovery is just as broken as the original state; there may
2056 // be another precompiled module that's using the overridden contents, or
2057 // we might be half way through parsing it. Instead, we should treat the
2058 // overridden contents as belonging to a separate FileEntry.
2059 SM.disableFileContentsOverride(File);
2060 // The FileEntry is a virtual file entry with the size of the contents
2061 // that would override the original contents. Set it to the original's
2063 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2064 StoredSize, StoredTime);
2067 bool IsOutOfDate = false;
2069 // For an overridden file, there is nothing to validate.
2070 if (!Overridden && //
2071 (StoredSize != File->getSize() ||
2072 (StoredTime && StoredTime != File->getModificationTime() &&
2076 // Build a list of the PCH imports that got us here (in reverse).
2077 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2078 while (ImportStack.back()->ImportedBy.size() > 0)
2079 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2081 // The top-level PCH is stale.
2082 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2083 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2084 if (DiagnosticKind == 0)
2085 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2086 else if (DiagnosticKind == 1)
2087 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2089 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
2091 // Print the import stack.
2092 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2093 Diag(diag::note_pch_required_by)
2094 << Filename << ImportStack[0]->FileName;
2095 for (unsigned I = 1; I < ImportStack.size(); ++I)
2096 Diag(diag::note_pch_required_by)
2097 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2100 if (!Diags.isDiagnosticInFlight())
2101 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2106 // FIXME: If the file is overridden and we've already opened it,
2107 // issue an error (or split it into a separate FileEntry).
2109 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
2111 // Note that we've loaded this input file.
2112 F.InputFilesLoaded[ID-1] = IF;
2116 /// \brief If we are loading a relocatable PCH or module file, and the filename
2117 /// is not an absolute path, add the system or module root to the beginning of
2119 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2120 // Resolve relative to the base directory, if we have one.
2121 if (!M.BaseDirectory.empty())
2122 return ResolveImportedPath(Filename, M.BaseDirectory);
2125 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2126 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2129 SmallString<128> Buffer;
2130 llvm::sys::path::append(Buffer, Prefix, Filename);
2131 Filename.assign(Buffer.begin(), Buffer.end());
2134 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2136 case ASTReader::Failure: return true;
2137 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2138 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2139 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2140 case ASTReader::ConfigurationMismatch:
2141 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2142 case ASTReader::HadErrors: return true;
2143 case ASTReader::Success: return false;
2146 llvm_unreachable("unknown ASTReadResult");
2149 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2150 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2151 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2152 std::string &SuggestedPredefines, bool ValidateDiagnosticOptions) {
2153 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2156 // Read all of the records in the options block.
2158 ASTReadResult Result = Success;
2160 llvm::BitstreamEntry Entry = Stream.advance();
2162 switch (Entry.Kind) {
2163 case llvm::BitstreamEntry::Error:
2164 case llvm::BitstreamEntry::SubBlock:
2167 case llvm::BitstreamEntry::EndBlock:
2170 case llvm::BitstreamEntry::Record:
2171 // The interesting case.
2175 // Read and process a record.
2177 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2178 case LANGUAGE_OPTIONS: {
2179 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2180 if (ParseLanguageOptions(Record, Complain, Listener,
2181 AllowCompatibleConfigurationMismatch))
2182 Result = ConfigurationMismatch;
2186 case TARGET_OPTIONS: {
2187 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2188 if (ParseTargetOptions(Record, Complain, Listener,
2189 AllowCompatibleConfigurationMismatch))
2190 Result = ConfigurationMismatch;
2194 case DIAGNOSTIC_OPTIONS: {
2195 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2196 if (ValidateDiagnosticOptions &&
2197 !AllowCompatibleConfigurationMismatch &&
2198 ParseDiagnosticOptions(Record, Complain, Listener))
2203 case FILE_SYSTEM_OPTIONS: {
2204 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2205 if (!AllowCompatibleConfigurationMismatch &&
2206 ParseFileSystemOptions(Record, Complain, Listener))
2207 Result = ConfigurationMismatch;
2211 case HEADER_SEARCH_OPTIONS: {
2212 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2213 if (!AllowCompatibleConfigurationMismatch &&
2214 ParseHeaderSearchOptions(Record, Complain, Listener))
2215 Result = ConfigurationMismatch;
2219 case PREPROCESSOR_OPTIONS:
2220 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2221 if (!AllowCompatibleConfigurationMismatch &&
2222 ParsePreprocessorOptions(Record, Complain, Listener,
2223 SuggestedPredefines))
2224 Result = ConfigurationMismatch;
2230 ASTReader::ASTReadResult
2231 ASTReader::ReadControlBlock(ModuleFile &F,
2232 SmallVectorImpl<ImportedModule> &Loaded,
2233 const ModuleFile *ImportedBy,
2234 unsigned ClientLoadCapabilities) {
2235 BitstreamCursor &Stream = F.Stream;
2236 ASTReadResult Result = Success;
2238 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2239 Error("malformed block record in AST file");
2243 // Read all of the records and blocks in the control block.
2245 unsigned NumInputs = 0;
2246 unsigned NumUserInputs = 0;
2248 llvm::BitstreamEntry Entry = Stream.advance();
2250 switch (Entry.Kind) {
2251 case llvm::BitstreamEntry::Error:
2252 Error("malformed block record in AST file");
2254 case llvm::BitstreamEntry::EndBlock: {
2255 // Validate input files.
2256 const HeaderSearchOptions &HSOpts =
2257 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2259 // All user input files reside at the index range [0, NumUserInputs), and
2260 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2261 // loaded module files, ignore missing inputs.
2262 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2263 F.Kind != MK_PrebuiltModule) {
2264 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2266 // If we are reading a module, we will create a verification timestamp,
2267 // so we verify all input files. Otherwise, verify only user input
2270 unsigned N = NumUserInputs;
2271 if (ValidateSystemInputs ||
2272 (HSOpts.ModulesValidateOncePerBuildSession &&
2273 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
2274 F.Kind == MK_ImplicitModule))
2277 for (unsigned I = 0; I < N; ++I) {
2278 InputFile IF = getInputFile(F, I+1, Complain);
2279 if (!IF.getFile() || IF.isOutOfDate())
2285 Listener->visitModuleFile(F.FileName, F.Kind);
2287 if (Listener && Listener->needsInputFileVisitation()) {
2288 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2290 for (unsigned I = 0; I < N; ++I) {
2291 bool IsSystem = I >= NumUserInputs;
2292 InputFileInfo FI = readInputFileInfo(F, I+1);
2293 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2294 F.Kind == MK_ExplicitModule ||
2295 F.Kind == MK_PrebuiltModule);
2302 case llvm::BitstreamEntry::SubBlock:
2304 case INPUT_FILES_BLOCK_ID:
2305 F.InputFilesCursor = Stream;
2306 if (Stream.SkipBlock() || // Skip with the main cursor
2307 // Read the abbreviations
2308 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2309 Error("malformed block record in AST file");
2314 case OPTIONS_BLOCK_ID:
2315 // If we're reading the first module for this group, check its options
2316 // are compatible with ours. For modules it imports, no further checking
2317 // is required, because we checked them when we built it.
2318 if (Listener && !ImportedBy) {
2319 // Should we allow the configuration of the module file to differ from
2320 // the configuration of the current translation unit in a compatible
2323 // FIXME: Allow this for files explicitly specified with -include-pch.
2324 bool AllowCompatibleConfigurationMismatch =
2325 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
2326 const HeaderSearchOptions &HSOpts =
2327 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2329 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2330 AllowCompatibleConfigurationMismatch,
2331 *Listener, SuggestedPredefines,
2332 HSOpts.ModulesValidateDiagnosticOptions);
2333 if (Result == Failure) {
2334 Error("malformed block record in AST file");
2338 if (DisableValidation ||
2339 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2342 // If we can't load the module, exit early since we likely
2343 // will rebuild the module anyway. The stream may be in the
2344 // middle of a block.
2345 if (Result != Success)
2347 } else if (Stream.SkipBlock()) {
2348 Error("malformed block record in AST file");
2354 if (Stream.SkipBlock()) {
2355 Error("malformed block record in AST file");
2361 case llvm::BitstreamEntry::Record:
2362 // The interesting case.
2366 // Read and process a record.
2369 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2371 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2372 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2373 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2374 : diag::err_pch_version_too_new);
2375 return VersionMismatch;
2378 bool hasErrors = Record[6];
2379 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2380 Diag(diag::err_pch_with_compiler_errors);
2384 Diags.ErrorOccurred = true;
2385 Diags.UncompilableErrorOccurred = true;
2386 Diags.UnrecoverableErrorOccurred = true;
2389 F.RelocatablePCH = Record[4];
2390 // Relative paths in a relocatable PCH are relative to our sysroot.
2391 if (F.RelocatablePCH)
2392 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
2394 F.HasTimestamps = Record[5];
2396 const std::string &CurBranch = getClangFullRepositoryVersion();
2397 StringRef ASTBranch = Blob;
2398 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2399 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2400 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2401 return VersionMismatch;
2407 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2408 F.Signature = Record[0];
2412 // Load each of the imported PCH files.
2413 unsigned Idx = 0, N = Record.size();
2415 // Read information about the AST file.
2416 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2417 // The import location will be the local one for now; we will adjust
2418 // all import locations of module imports after the global source
2419 // location info are setup, in ReadAST.
2420 SourceLocation ImportLoc =
2421 ReadUntranslatedSourceLocation(Record[Idx++]);
2422 off_t StoredSize = (off_t)Record[Idx++];
2423 time_t StoredModTime = (time_t)Record[Idx++];
2424 ASTFileSignature StoredSignature = Record[Idx++];
2425 auto ImportedFile = ReadPath(F, Record, Idx);
2427 // If our client can't cope with us being out of date, we can't cope with
2428 // our dependency being missing.
2429 unsigned Capabilities = ClientLoadCapabilities;
2430 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2431 Capabilities &= ~ARR_Missing;
2433 // Load the AST file.
2434 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2435 Loaded, StoredSize, StoredModTime,
2436 StoredSignature, Capabilities);
2438 // If we diagnosed a problem, produce a backtrace.
2439 if (isDiagnosedResult(Result, Capabilities))
2440 Diag(diag::note_module_file_imported_by)
2441 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2444 case Failure: return Failure;
2445 // If we have to ignore the dependency, we'll have to ignore this too.
2447 case OutOfDate: return OutOfDate;
2448 case VersionMismatch: return VersionMismatch;
2449 case ConfigurationMismatch: return ConfigurationMismatch;
2450 case HadErrors: return HadErrors;
2451 case Success: break;
2458 F.OriginalSourceFileID = FileID::get(Record[0]);
2459 F.ActualOriginalSourceFileName = Blob;
2460 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2461 ResolveImportedPath(F, F.OriginalSourceFileName);
2464 case ORIGINAL_FILE_ID:
2465 F.OriginalSourceFileID = FileID::get(Record[0]);
2468 case ORIGINAL_PCH_DIR:
2469 F.OriginalDir = Blob;
2473 F.ModuleName = Blob;
2475 Listener->ReadModuleName(F.ModuleName);
2478 case MODULE_DIRECTORY: {
2479 assert(!F.ModuleName.empty() &&
2480 "MODULE_DIRECTORY found before MODULE_NAME");
2481 // If we've already loaded a module map file covering this module, we may
2482 // have a better path for it (relative to the current build).
2483 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2484 if (M && M->Directory) {
2485 // If we're implicitly loading a module, the base directory can't
2486 // change between the build and use.
2487 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
2488 const DirectoryEntry *BuildDir =
2489 PP.getFileManager().getDirectory(Blob);
2490 if (!BuildDir || BuildDir != M->Directory) {
2491 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2492 Diag(diag::err_imported_module_relocated)
2493 << F.ModuleName << Blob << M->Directory->getName();
2497 F.BaseDirectory = M->Directory->getName();
2499 F.BaseDirectory = Blob;
2504 case MODULE_MAP_FILE:
2505 if (ASTReadResult Result =
2506 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2510 case INPUT_FILE_OFFSETS:
2511 NumInputs = Record[0];
2512 NumUserInputs = Record[1];
2513 F.InputFileOffsets =
2514 (const llvm::support::unaligned_uint64_t *)Blob.data();
2515 F.InputFilesLoaded.resize(NumInputs);
2521 ASTReader::ASTReadResult
2522 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
2523 BitstreamCursor &Stream = F.Stream;
2525 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2526 Error("malformed block record in AST file");
2530 // Read all of the records and blocks for the AST file.
2533 llvm::BitstreamEntry Entry = Stream.advance();
2535 switch (Entry.Kind) {
2536 case llvm::BitstreamEntry::Error:
2537 Error("error at end of module block in AST file");
2539 case llvm::BitstreamEntry::EndBlock: {
2540 // Outside of C++, we do not store a lookup map for the translation unit.
2541 // Instead, mark it as needing a lookup map to be built if this module
2542 // contains any declarations lexically within it (which it always does!).
2543 // This usually has no cost, since we very rarely need the lookup map for
2544 // the translation unit outside C++.
2545 DeclContext *DC = Context.getTranslationUnitDecl();
2546 if (DC->hasExternalLexicalStorage() &&
2547 !getContext().getLangOpts().CPlusPlus)
2548 DC->setMustBuildLookupTable();
2552 case llvm::BitstreamEntry::SubBlock:
2554 case DECLTYPES_BLOCK_ID:
2555 // We lazily load the decls block, but we want to set up the
2556 // DeclsCursor cursor to point into it. Clone our current bitcode
2557 // cursor to it, enter the block and read the abbrevs in that block.
2558 // With the main cursor, we just skip over it.
2559 F.DeclsCursor = Stream;
2560 if (Stream.SkipBlock() || // Skip with the main cursor.
2561 // Read the abbrevs.
2562 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2563 Error("malformed block record in AST file");
2568 case PREPROCESSOR_BLOCK_ID:
2569 F.MacroCursor = Stream;
2570 if (!PP.getExternalSource())
2571 PP.setExternalSource(this);
2573 if (Stream.SkipBlock() ||
2574 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2575 Error("malformed block record in AST file");
2578 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2581 case PREPROCESSOR_DETAIL_BLOCK_ID:
2582 F.PreprocessorDetailCursor = Stream;
2583 if (Stream.SkipBlock() ||
2584 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
2585 PREPROCESSOR_DETAIL_BLOCK_ID)) {
2586 Error("malformed preprocessor detail record in AST file");
2589 F.PreprocessorDetailStartOffset
2590 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2592 if (!PP.getPreprocessingRecord())
2593 PP.createPreprocessingRecord();
2594 if (!PP.getPreprocessingRecord()->getExternalSource())
2595 PP.getPreprocessingRecord()->SetExternalSource(*this);
2598 case SOURCE_MANAGER_BLOCK_ID:
2599 if (ReadSourceManagerBlock(F))
2603 case SUBMODULE_BLOCK_ID:
2604 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2608 case COMMENTS_BLOCK_ID: {
2609 BitstreamCursor C = Stream;
2610 if (Stream.SkipBlock() ||
2611 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2612 Error("malformed comments block in AST file");
2615 CommentsCursors.push_back(std::make_pair(C, &F));
2620 if (Stream.SkipBlock()) {
2621 Error("malformed block record in AST file");
2628 case llvm::BitstreamEntry::Record:
2629 // The interesting case.
2633 // Read and process a record.
2636 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2637 default: // Default behavior: ignore.
2641 if (F.LocalNumTypes != 0) {
2642 Error("duplicate TYPE_OFFSET record in AST file");
2645 F.TypeOffsets = (const uint32_t *)Blob.data();
2646 F.LocalNumTypes = Record[0];
2647 unsigned LocalBaseTypeIndex = Record[1];
2648 F.BaseTypeIndex = getTotalNumTypes();
2650 if (F.LocalNumTypes > 0) {
2651 // Introduce the global -> local mapping for types within this module.
2652 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2654 // Introduce the local -> global mapping for types within this module.
2655 F.TypeRemap.insertOrReplace(
2656 std::make_pair(LocalBaseTypeIndex,
2657 F.BaseTypeIndex - LocalBaseTypeIndex));
2659 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2665 if (F.LocalNumDecls != 0) {
2666 Error("duplicate DECL_OFFSET record in AST file");
2669 F.DeclOffsets = (const DeclOffset *)Blob.data();
2670 F.LocalNumDecls = Record[0];
2671 unsigned LocalBaseDeclID = Record[1];
2672 F.BaseDeclID = getTotalNumDecls();
2674 if (F.LocalNumDecls > 0) {
2675 // Introduce the global -> local mapping for declarations within this
2677 GlobalDeclMap.insert(
2678 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2680 // Introduce the local -> global mapping for declarations within this
2682 F.DeclRemap.insertOrReplace(
2683 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2685 // Introduce the global -> local mapping for declarations within this
2687 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2689 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2694 case TU_UPDATE_LEXICAL: {
2695 DeclContext *TU = Context.getTranslationUnitDecl();
2696 LexicalContents Contents(
2697 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2699 static_cast<unsigned int>(Blob.size() / 4));
2700 TULexicalDecls.push_back(std::make_pair(&F, Contents));
2701 TU->setHasExternalLexicalStorage(true);
2705 case UPDATE_VISIBLE: {
2707 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2708 auto *Data = (const unsigned char*)Blob.data();
2709 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
2710 // If we've already loaded the decl, perform the updates when we finish
2711 // loading this block.
2712 if (Decl *D = GetExistingDecl(ID))
2713 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2717 case IDENTIFIER_TABLE:
2718 F.IdentifierTableData = Blob.data();
2720 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2721 (const unsigned char *)F.IdentifierTableData + Record[0],
2722 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2723 (const unsigned char *)F.IdentifierTableData,
2724 ASTIdentifierLookupTrait(*this, F));
2726 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2730 case IDENTIFIER_OFFSET: {
2731 if (F.LocalNumIdentifiers != 0) {
2732 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2735 F.IdentifierOffsets = (const uint32_t *)Blob.data();
2736 F.LocalNumIdentifiers = Record[0];
2737 unsigned LocalBaseIdentifierID = Record[1];
2738 F.BaseIdentifierID = getTotalNumIdentifiers();
2740 if (F.LocalNumIdentifiers > 0) {
2741 // Introduce the global -> local mapping for identifiers within this
2743 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2746 // Introduce the local -> global mapping for identifiers within this
2748 F.IdentifierRemap.insertOrReplace(
2749 std::make_pair(LocalBaseIdentifierID,
2750 F.BaseIdentifierID - LocalBaseIdentifierID));
2752 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2753 + F.LocalNumIdentifiers);
2758 case INTERESTING_IDENTIFIERS:
2759 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2762 case EAGERLY_DESERIALIZED_DECLS:
2763 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2764 // about "interesting" decls (for instance, if we're building a module).
2765 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2766 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2770 if (SpecialTypes.empty()) {
2771 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2772 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2776 if (SpecialTypes.size() != Record.size()) {
2777 Error("invalid special-types record");
2781 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2782 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2783 if (!SpecialTypes[I])
2784 SpecialTypes[I] = ID;
2785 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2791 TotalNumStatements += Record[0];
2792 TotalNumMacros += Record[1];
2793 TotalLexicalDeclContexts += Record[2];
2794 TotalVisibleDeclContexts += Record[3];
2797 case UNUSED_FILESCOPED_DECLS:
2798 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2799 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2802 case DELEGATING_CTORS:
2803 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2804 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2807 case WEAK_UNDECLARED_IDENTIFIERS:
2808 if (Record.size() % 4 != 0) {
2809 Error("invalid weak identifiers record");
2813 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2814 // files. This isn't the way to do it :)
2815 WeakUndeclaredIdentifiers.clear();
2817 // Translate the weak, undeclared identifiers into global IDs.
2818 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2819 WeakUndeclaredIdentifiers.push_back(
2820 getGlobalIdentifierID(F, Record[I++]));
2821 WeakUndeclaredIdentifiers.push_back(
2822 getGlobalIdentifierID(F, Record[I++]));
2823 WeakUndeclaredIdentifiers.push_back(
2824 ReadSourceLocation(F, Record, I).getRawEncoding());
2825 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2829 case SELECTOR_OFFSETS: {
2830 F.SelectorOffsets = (const uint32_t *)Blob.data();
2831 F.LocalNumSelectors = Record[0];
2832 unsigned LocalBaseSelectorID = Record[1];
2833 F.BaseSelectorID = getTotalNumSelectors();
2835 if (F.LocalNumSelectors > 0) {
2836 // Introduce the global -> local mapping for selectors within this
2838 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2840 // Introduce the local -> global mapping for selectors within this
2842 F.SelectorRemap.insertOrReplace(
2843 std::make_pair(LocalBaseSelectorID,
2844 F.BaseSelectorID - LocalBaseSelectorID));
2846 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2852 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
2854 F.SelectorLookupTable
2855 = ASTSelectorLookupTable::Create(
2856 F.SelectorLookupTableData + Record[0],
2857 F.SelectorLookupTableData,
2858 ASTSelectorLookupTrait(*this, F));
2859 TotalNumMethodPoolEntries += Record[1];
2862 case REFERENCED_SELECTOR_POOL:
2863 if (!Record.empty()) {
2864 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2865 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2867 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2873 case PP_COUNTER_VALUE:
2874 if (!Record.empty() && Listener)
2875 Listener->ReadCounter(F, Record[0]);
2878 case FILE_SORTED_DECLS:
2879 F.FileSortedDecls = (const DeclID *)Blob.data();
2880 F.NumFileSortedDecls = Record[0];
2883 case SOURCE_LOCATION_OFFSETS: {
2884 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
2885 F.LocalNumSLocEntries = Record[0];
2886 unsigned SLocSpaceSize = Record[1];
2887 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2888 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2890 if (!F.SLocEntryBaseID) {
2891 Error("ran out of source locations");
2894 // Make our entry in the range map. BaseID is negative and growing, so
2895 // we invert it. Because we invert it, though, we need the other end of
2897 unsigned RangeStart =
2898 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2899 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2900 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2902 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2903 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2904 GlobalSLocOffsetMap.insert(
2905 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2906 - SLocSpaceSize,&F));
2908 // Initialize the remapping table.
2909 // Invalid stays invalid.
2910 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
2911 // This module. Base was 2 when being compiled.
2912 F.SLocRemap.insertOrReplace(std::make_pair(2U,
2913 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2915 TotalNumSLocEntries += F.LocalNumSLocEntries;
2919 case MODULE_OFFSET_MAP: {
2920 // Additional remapping information.
2921 const unsigned char *Data = (const unsigned char*)Blob.data();
2922 const unsigned char *DataEnd = Data + Blob.size();
2924 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2925 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2926 F.SLocRemap.insert(std::make_pair(0U, 0));
2927 F.SLocRemap.insert(std::make_pair(2U, 1));
2930 // Continuous range maps we may be updating in our module.
2931 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2933 RemapBuilder SLocRemap(F.SLocRemap);
2934 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2935 RemapBuilder MacroRemap(F.MacroRemap);
2936 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2937 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2938 RemapBuilder SelectorRemap(F.SelectorRemap);
2939 RemapBuilder DeclRemap(F.DeclRemap);
2940 RemapBuilder TypeRemap(F.TypeRemap);
2942 while (Data < DataEnd) {
2943 using namespace llvm::support;
2944 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
2945 StringRef Name = StringRef((const char*)Data, Len);
2947 ModuleFile *OM = ModuleMgr.lookup(Name);
2949 Error("SourceLocation remap refers to unknown module");
2953 uint32_t SLocOffset =
2954 endian::readNext<uint32_t, little, unaligned>(Data);
2955 uint32_t IdentifierIDOffset =
2956 endian::readNext<uint32_t, little, unaligned>(Data);
2957 uint32_t MacroIDOffset =
2958 endian::readNext<uint32_t, little, unaligned>(Data);
2959 uint32_t PreprocessedEntityIDOffset =
2960 endian::readNext<uint32_t, little, unaligned>(Data);
2961 uint32_t SubmoduleIDOffset =
2962 endian::readNext<uint32_t, little, unaligned>(Data);
2963 uint32_t SelectorIDOffset =
2964 endian::readNext<uint32_t, little, unaligned>(Data);
2965 uint32_t DeclIDOffset =
2966 endian::readNext<uint32_t, little, unaligned>(Data);
2967 uint32_t TypeIndexOffset =
2968 endian::readNext<uint32_t, little, unaligned>(Data);
2970 uint32_t None = std::numeric_limits<uint32_t>::max();
2972 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2973 RemapBuilder &Remap) {
2975 Remap.insert(std::make_pair(Offset,
2976 static_cast<int>(BaseOffset - Offset)));
2978 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2979 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2980 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2981 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2982 PreprocessedEntityRemap);
2983 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2984 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2985 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2986 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
2988 // Global -> local mappings.
2989 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2994 case SOURCE_MANAGER_LINE_TABLE:
2995 if (ParseLineTable(F, Record))
2999 case SOURCE_LOCATION_PRELOADS: {
3000 // Need to transform from the local view (1-based IDs) to the global view,
3001 // which is based off F.SLocEntryBaseID.
3002 if (!F.PreloadSLocEntries.empty()) {
3003 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
3007 F.PreloadSLocEntries.swap(Record);
3011 case EXT_VECTOR_DECLS:
3012 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3013 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3017 if (Record.size() % 3 != 0) {
3018 Error("Invalid VTABLE_USES record");
3022 // Later tables overwrite earlier ones.
3023 // FIXME: Modules will have some trouble with this. This is clearly not
3024 // the right way to do this.
3027 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3028 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3029 VTableUses.push_back(
3030 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3031 VTableUses.push_back(Record[Idx++]);
3035 case PENDING_IMPLICIT_INSTANTIATIONS:
3036 if (PendingInstantiations.size() % 2 != 0) {
3037 Error("Invalid existing PendingInstantiations");
3041 if (Record.size() % 2 != 0) {
3042 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3046 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3047 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3048 PendingInstantiations.push_back(
3049 ReadSourceLocation(F, Record, I).getRawEncoding());
3053 case SEMA_DECL_REFS:
3054 if (Record.size() != 3) {
3055 Error("Invalid SEMA_DECL_REFS block");
3058 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3059 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3062 case PPD_ENTITIES_OFFSETS: {
3063 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3064 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3065 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3067 unsigned LocalBasePreprocessedEntityID = Record[0];
3069 unsigned StartingID;
3070 if (!PP.getPreprocessingRecord())
3071 PP.createPreprocessingRecord();
3072 if (!PP.getPreprocessingRecord()->getExternalSource())
3073 PP.getPreprocessingRecord()->SetExternalSource(*this);
3075 = PP.getPreprocessingRecord()
3076 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3077 F.BasePreprocessedEntityID = StartingID;
3079 if (F.NumPreprocessedEntities > 0) {
3080 // Introduce the global -> local mapping for preprocessed entities in
3082 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3084 // Introduce the local -> global mapping for preprocessed entities in
3086 F.PreprocessedEntityRemap.insertOrReplace(
3087 std::make_pair(LocalBasePreprocessedEntityID,
3088 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3094 case DECL_UPDATE_OFFSETS: {
3095 if (Record.size() % 2 != 0) {
3096 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
3099 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3100 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3101 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3103 // If we've already loaded the decl, perform the updates when we finish
3104 // loading this block.
3105 if (Decl *D = GetExistingDecl(ID))
3106 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3111 case OBJC_CATEGORIES_MAP: {
3112 if (F.LocalNumObjCCategoriesInMap != 0) {
3113 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
3117 F.LocalNumObjCCategoriesInMap = Record[0];
3118 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3122 case OBJC_CATEGORIES:
3123 F.ObjCCategories.swap(Record);
3126 case DIAG_PRAGMA_MAPPINGS:
3127 if (F.PragmaDiagMappings.empty())
3128 F.PragmaDiagMappings.swap(Record);
3130 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3131 Record.begin(), Record.end());
3134 case CUDA_SPECIAL_DECL_REFS:
3135 // Later tables overwrite earlier ones.
3136 // FIXME: Modules will have trouble with this.
3137 CUDASpecialDeclRefs.clear();
3138 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3139 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3142 case HEADER_SEARCH_TABLE: {
3143 F.HeaderFileInfoTableData = Blob.data();
3144 F.LocalNumHeaderFileInfos = Record[1];
3146 F.HeaderFileInfoTable
3147 = HeaderFileInfoLookupTable::Create(
3148 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3149 (const unsigned char *)F.HeaderFileInfoTableData,
3150 HeaderFileInfoTrait(*this, F,
3151 &PP.getHeaderSearchInfo(),
3152 Blob.data() + Record[2]));
3154 PP.getHeaderSearchInfo().SetExternalSource(this);
3155 if (!PP.getHeaderSearchInfo().getExternalLookup())
3156 PP.getHeaderSearchInfo().SetExternalLookup(this);
3161 case FP_PRAGMA_OPTIONS:
3162 // Later tables overwrite earlier ones.
3163 FPPragmaOptions.swap(Record);
3166 case OPENCL_EXTENSIONS:
3167 for (unsigned I = 0, E = Record.size(); I != E; ) {
3168 auto Name = ReadString(Record, I);
3169 auto &Opt = OpenCLExtensions.OptMap[Name];
3170 Opt.Supported = Record[I++] != 0;
3171 Opt.Enabled = Record[I++] != 0;
3172 Opt.Avail = Record[I++];
3173 Opt.Core = Record[I++];
3177 case OPENCL_EXTENSION_TYPES:
3178 for (unsigned I = 0, E = Record.size(); I != E;) {
3179 auto TypeID = static_cast<::TypeID>(Record[I++]);
3180 auto *Type = GetType(TypeID).getTypePtr();
3181 auto NumExt = static_cast<unsigned>(Record[I++]);
3182 for (unsigned II = 0; II != NumExt; ++II) {
3183 auto Ext = ReadString(Record, I);
3184 OpenCLTypeExtMap[Type].insert(Ext);
3189 case OPENCL_EXTENSION_DECLS:
3190 for (unsigned I = 0, E = Record.size(); I != E;) {
3191 auto DeclID = static_cast<::DeclID>(Record[I++]);
3192 auto *Decl = GetDecl(DeclID);
3193 auto NumExt = static_cast<unsigned>(Record[I++]);
3194 for (unsigned II = 0; II != NumExt; ++II) {
3195 auto Ext = ReadString(Record, I);
3196 OpenCLDeclExtMap[Decl].insert(Ext);
3201 case TENTATIVE_DEFINITIONS:
3202 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3203 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3206 case KNOWN_NAMESPACES:
3207 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3208 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3211 case UNDEFINED_BUT_USED:
3212 if (UndefinedButUsed.size() % 2 != 0) {
3213 Error("Invalid existing UndefinedButUsed");
3217 if (Record.size() % 2 != 0) {
3218 Error("invalid undefined-but-used record");
3221 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3222 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3223 UndefinedButUsed.push_back(
3224 ReadSourceLocation(F, Record, I).getRawEncoding());
3227 case DELETE_EXPRS_TO_ANALYZE:
3228 for (unsigned I = 0, N = Record.size(); I != N;) {
3229 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3230 const uint64_t Count = Record[I++];
3231 DelayedDeleteExprs.push_back(Count);
3232 for (uint64_t C = 0; C < Count; ++C) {
3233 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3234 bool IsArrayForm = Record[I++] == 1;
3235 DelayedDeleteExprs.push_back(IsArrayForm);
3240 case IMPORTED_MODULES: {
3241 if (!F.isModule()) {
3242 // If we aren't loading a module (which has its own exports), make
3243 // all of the imported modules visible.
3244 // FIXME: Deal with macros-only imports.
3245 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3246 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3247 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3249 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3255 case MACRO_OFFSET: {
3256 if (F.LocalNumMacros != 0) {
3257 Error("duplicate MACRO_OFFSET record in AST file");
3260 F.MacroOffsets = (const uint32_t *)Blob.data();
3261 F.LocalNumMacros = Record[0];
3262 unsigned LocalBaseMacroID = Record[1];
3263 F.BaseMacroID = getTotalNumMacros();
3265 if (F.LocalNumMacros > 0) {
3266 // Introduce the global -> local mapping for macros within this module.
3267 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3269 // Introduce the local -> global mapping for macros within this module.
3270 F.MacroRemap.insertOrReplace(
3271 std::make_pair(LocalBaseMacroID,
3272 F.BaseMacroID - LocalBaseMacroID));
3274 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3279 case LATE_PARSED_TEMPLATE: {
3280 LateParsedTemplates.append(Record.begin(), Record.end());
3284 case OPTIMIZE_PRAGMA_OPTIONS:
3285 if (Record.size() != 1) {
3286 Error("invalid pragma optimize record");
3289 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3292 case MSSTRUCT_PRAGMA_OPTIONS:
3293 if (Record.size() != 1) {
3294 Error("invalid pragma ms_struct record");
3297 PragmaMSStructState = Record[0];
3300 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3301 if (Record.size() != 2) {
3302 Error("invalid pragma ms_struct record");
3305 PragmaMSPointersToMembersState = Record[0];
3306 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3309 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3310 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3311 UnusedLocalTypedefNameCandidates.push_back(
3312 getGlobalDeclID(F, Record[I]));
3315 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3316 if (Record.size() != 1) {
3317 Error("invalid cuda pragma options record");
3320 ForceCUDAHostDeviceDepth = Record[0];
3326 ASTReader::ASTReadResult
3327 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3328 const ModuleFile *ImportedBy,
3329 unsigned ClientLoadCapabilities) {
3331 F.ModuleMapPath = ReadPath(F, Record, Idx);
3333 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
3334 // For an explicitly-loaded module, we don't care whether the original
3335 // module map file exists or matches.
3339 // Try to resolve ModuleName in the current header search context and
3340 // verify that it is found in the same module map file as we saved. If the
3341 // top-level AST file is a main file, skip this check because there is no
3342 // usable header search context.
3343 assert(!F.ModuleName.empty() &&
3344 "MODULE_NAME should come before MODULE_MAP_FILE");
3345 if (F.Kind == MK_ImplicitModule &&
3346 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3347 // An implicitly-loaded module file should have its module listed in some
3348 // module map file that we've already loaded.
3349 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
3350 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3351 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3353 assert(ImportedBy && "top-level import should be verified");
3354 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3355 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3356 // This module was defined by an imported (explicit) module.
3357 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3358 << ASTFE->getName();
3360 // This module was built with a different module map.
3361 Diag(diag::err_imported_module_not_found)
3362 << F.ModuleName << F.FileName << ImportedBy->FileName
3368 assert(M->Name == F.ModuleName && "found module with different name");
3370 // Check the primary module map file.
3371 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3372 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3373 assert(ModMap && "found module is missing module map file");
3374 assert(ImportedBy && "top-level import should be verified");
3375 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3376 Diag(diag::err_imported_module_modmap_changed)
3377 << F.ModuleName << ImportedBy->FileName
3378 << ModMap->getName() << F.ModuleMapPath;
3382 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3383 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3384 // FIXME: we should use input files rather than storing names.
3385 std::string Filename = ReadPath(F, Record, Idx);
3386 const FileEntry *F =
3387 FileMgr.getFile(Filename, false, false);
3389 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3390 Error("could not find file '" + Filename +"' referenced by AST file");
3393 AdditionalStoredMaps.insert(F);
3396 // Check any additional module map files (e.g. module.private.modulemap)
3397 // that are not in the pcm.
3398 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3399 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3400 // Remove files that match
3401 // Note: SmallPtrSet::erase is really remove
3402 if (!AdditionalStoredMaps.erase(ModMap)) {
3403 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3404 Diag(diag::err_module_different_modmap)
3405 << F.ModuleName << /*new*/0 << ModMap->getName();
3411 // Check any additional module map files that are in the pcm, but not
3412 // found in header search. Cases that match are already removed.
3413 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3414 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3415 Diag(diag::err_module_different_modmap)
3416 << F.ModuleName << /*not new*/1 << ModMap->getName();
3422 Listener->ReadModuleMapFile(F.ModuleMapPath);
3427 /// \brief Move the given method to the back of the global list of methods.
3428 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3429 // Find the entry for this selector in the method pool.
3430 Sema::GlobalMethodPool::iterator Known
3431 = S.MethodPool.find(Method->getSelector());
3432 if (Known == S.MethodPool.end())
3435 // Retrieve the appropriate method list.
3436 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3437 : Known->second.second;
3439 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
3441 if (List->getMethod() == Method) {
3449 if (List->getNext())
3450 List->setMethod(List->getNext()->getMethod());
3452 List->setMethod(Method);
3456 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
3457 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
3458 for (Decl *D : Names) {
3459 bool wasHidden = D->Hidden;
3462 if (wasHidden && SemaObj) {
3463 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3464 moveMethodToBackOfGlobalList(*SemaObj, Method);
3470 void ASTReader::makeModuleVisible(Module *Mod,
3471 Module::NameVisibilityKind NameVisibility,
3472 SourceLocation ImportLoc) {
3473 llvm::SmallPtrSet<Module *, 4> Visited;
3474 SmallVector<Module *, 4> Stack;
3475 Stack.push_back(Mod);
3476 while (!Stack.empty()) {
3477 Mod = Stack.pop_back_val();
3479 if (NameVisibility <= Mod->NameVisibility) {
3480 // This module already has this level of visibility (or greater), so
3481 // there is nothing more to do.
3485 if (!Mod->isAvailable()) {
3486 // Modules that aren't available cannot be made visible.
3490 // Update the module's name visibility.
3491 Mod->NameVisibility = NameVisibility;
3493 // If we've already deserialized any names from this module,
3494 // mark them as visible.
3495 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3496 if (Hidden != HiddenNamesMap.end()) {
3497 auto HiddenNames = std::move(*Hidden);
3498 HiddenNamesMap.erase(Hidden);
3499 makeNamesVisible(HiddenNames.second, HiddenNames.first);
3500 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3501 "making names visible added hidden names");
3504 // Push any exported modules onto the stack to be marked as visible.
3505 SmallVector<Module *, 16> Exports;
3506 Mod->getExportedModules(Exports);
3507 for (SmallVectorImpl<Module *>::iterator
3508 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3509 Module *Exported = *I;
3510 if (Visited.insert(Exported).second)
3511 Stack.push_back(Exported);
3516 /// We've merged the definition \p MergedDef into the existing definition
3517 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3519 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3520 NamedDecl *MergedDef) {
3521 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3522 // in modules other than its owning module. We should instead give the
3523 // ASTContext a list of merged definitions for Def.
3524 if (Def->isHidden()) {
3525 // If MergedDef is visible or becomes visible, make the definition visible.
3526 if (!MergedDef->isHidden())
3527 Def->Hidden = false;
3528 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3529 getContext().mergeDefinitionIntoModule(
3530 Def, MergedDef->getImportedOwningModule(),
3531 /*NotifyListeners*/ false);
3532 PendingMergedDefinitionsToDeduplicate.insert(Def);
3534 auto SubmoduleID = MergedDef->getOwningModuleID();
3535 assert(SubmoduleID && "hidden definition in no module");
3536 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3541 bool ASTReader::loadGlobalIndex() {
3545 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3546 !Context.getLangOpts().Modules)
3549 // Try to load the global index.
3550 TriedLoadingGlobalIndex = true;
3551 StringRef ModuleCachePath
3552 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3553 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
3554 = GlobalModuleIndex::readIndex(ModuleCachePath);
3558 GlobalIndex.reset(Result.first);
3559 ModuleMgr.setGlobalIndex(GlobalIndex.get());
3563 bool ASTReader::isGlobalIndexUnavailable() const {
3564 return Context.getLangOpts().Modules && UseGlobalIndex &&
3565 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3568 static void updateModuleTimestamp(ModuleFile &MF) {
3569 // Overwrite the timestamp file contents so that file's mtime changes.
3570 std::string TimestampFilename = MF.getTimestampFilename();
3572 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3575 OS << "Timestamp file\n";
3578 /// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3579 /// cursor into the start of the given block ID, returning false on success and
3580 /// true on failure.
3581 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3583 llvm::BitstreamEntry Entry = Cursor.advance();
3584 switch (Entry.Kind) {
3585 case llvm::BitstreamEntry::Error:
3586 case llvm::BitstreamEntry::EndBlock:
3589 case llvm::BitstreamEntry::Record:
3590 // Ignore top-level records.
3591 Cursor.skipRecord(Entry.ID);
3594 case llvm::BitstreamEntry::SubBlock:
3595 if (Entry.ID == BlockID) {
3596 if (Cursor.EnterSubBlock(BlockID))
3602 if (Cursor.SkipBlock())
3608 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
3610 SourceLocation ImportLoc,
3611 unsigned ClientLoadCapabilities,
3612 SmallVectorImpl<ImportedSubmodule> *Imported) {
3613 llvm::SaveAndRestore<SourceLocation>
3614 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3616 // Defer any pending actions until we get to the end of reading the AST file.
3617 Deserializing AnASTFile(this);
3619 // Bump the generation number.
3620 unsigned PreviousGeneration = incrementGeneration(Context);
3622 unsigned NumModules = ModuleMgr.size();
3623 SmallVector<ImportedModule, 4> Loaded;
3624 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3625 /*ImportedBy=*/nullptr, Loaded,
3627 ClientLoadCapabilities)) {
3631 case VersionMismatch:
3632 case ConfigurationMismatch:
3634 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3635 for (const ImportedModule &IM : Loaded)
3636 LoadedSet.insert(IM.Mod);
3638 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3640 Context.getLangOpts().Modules
3641 ? &PP.getHeaderSearchInfo().getModuleMap()
3644 // If we find that any modules are unusable, the global index is going
3645 // to be out-of-date. Just remove it.
3646 GlobalIndex.reset();
3647 ModuleMgr.setGlobalIndex(nullptr);
3654 // Here comes stuff that we only do once the entire chain is loaded.
3656 // Load the AST blocks of all of the modules that we loaded.
3657 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3658 MEnd = Loaded.end();
3660 ModuleFile &F = *M->Mod;
3662 // Read the AST block.
3663 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3666 // Read the extension blocks.
3667 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3668 if (ASTReadResult Result = ReadExtensionBlock(F))
3672 // Once read, set the ModuleFile bit base offset and update the size in
3673 // bits of all files we've seen.
3674 F.GlobalBitOffset = TotalModulesSizeInBits;
3675 TotalModulesSizeInBits += F.SizeInBits;
3676 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3678 // Preload SLocEntries.
3679 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3680 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3681 // Load it through the SourceManager and don't call ReadSLocEntry()
3682 // directly because the entry may have already been loaded in which case
3683 // calling ReadSLocEntry() directly would trigger an assertion in
3685 SourceMgr.getLoadedSLocEntryByID(Index);
3688 // Preload all the pending interesting identifiers by marking them out of
3690 for (auto Offset : F.PreloadIdentifierOffsets) {
3691 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3692 F.IdentifierTableData + Offset);
3694 ASTIdentifierLookupTrait Trait(*this, F);
3695 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3696 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3697 auto &II = PP.getIdentifierTable().getOwn(Key);
3698 II.setOutOfDate(true);
3700 // Mark this identifier as being from an AST file so that we can track
3701 // whether we need to serialize it.
3702 markIdentifierFromAST(*this, II);
3704 // Associate the ID with the identifier so that the writer can reuse it.
3705 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3706 SetIdentifierInfo(ID, &II);
3710 // Setup the import locations and notify the module manager that we've
3711 // committed to these module files.
3712 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3713 MEnd = Loaded.end();
3715 ModuleFile &F = *M->Mod;
3717 ModuleMgr.moduleFileAccepted(&F);
3719 // Set the import location.
3720 F.DirectImportLoc = ImportLoc;
3721 // FIXME: We assume that locations from PCH / preamble do not need
3724 F.ImportLoc = M->ImportLoc;
3726 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
3729 if (!Context.getLangOpts().CPlusPlus ||
3730 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3731 Type != MK_PrebuiltModule)) {
3732 // Mark all of the identifiers in the identifier table as being out of date,
3733 // so that various accessors know to check the loaded modules when the
3734 // identifier is used.
3736 // For C++ modules, we don't need information on many identifiers (just
3737 // those that provide macros or are poisoned), so we mark all of
3738 // the interesting ones via PreloadIdentifierOffsets.
3739 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3740 IdEnd = PP.getIdentifierTable().end();
3742 Id->second->setOutOfDate(true);
3744 // Mark selectors as out of date.
3745 for (auto Sel : SelectorGeneration)
3746 SelectorOutOfDate[Sel.first] = true;
3748 // Resolve any unresolved module exports.
3749 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3750 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
3751 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3752 Module *ResolvedMod = getSubmodule(GlobalID);
3754 switch (Unresolved.Kind) {
3755 case UnresolvedModuleRef::Conflict:
3757 Module::Conflict Conflict;
3758 Conflict.Other = ResolvedMod;
3759 Conflict.Message = Unresolved.String.str();
3760 Unresolved.Mod->Conflicts.push_back(Conflict);
3764 case UnresolvedModuleRef::Import:
3766 Unresolved.Mod->Imports.insert(ResolvedMod);
3769 case UnresolvedModuleRef::Export:
3770 if (ResolvedMod || Unresolved.IsWildcard)
3771 Unresolved.Mod->Exports.push_back(
3772 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3776 UnresolvedModuleRefs.clear();
3779 Imported->append(ImportedModules.begin(),
3780 ImportedModules.end());
3782 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3783 // Might be unnecessary as use declarations are only used to build the
3786 InitializeContext();
3791 if (DeserializationListener)
3792 DeserializationListener->ReaderInitialized(this);
3794 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3795 if (PrimaryModule.OriginalSourceFileID.isValid()) {
3796 PrimaryModule.OriginalSourceFileID
3797 = FileID::get(PrimaryModule.SLocEntryBaseID
3798 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3800 // If this AST file is a precompiled preamble, then set the
3801 // preamble file ID of the source manager to the file source file
3802 // from which the preamble was built.
3803 if (Type == MK_Preamble) {
3804 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3805 } else if (Type == MK_MainFile) {
3806 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3810 // For any Objective-C class definitions we have already loaded, make sure
3811 // that we load any additional categories.
3812 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3813 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3814 ObjCClassesLoaded[I],
3815 PreviousGeneration);
3818 if (PP.getHeaderSearchInfo()
3819 .getHeaderSearchOpts()
3820 .ModulesValidateOncePerBuildSession) {
3821 // Now we are certain that the module and all modules it depends on are
3822 // up to date. Create or update timestamp files for modules that are
3823 // located in the module cache (not for PCH files that could be anywhere
3824 // in the filesystem).
3825 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3826 ImportedModule &M = Loaded[I];
3827 if (M.Mod->Kind == MK_ImplicitModule) {
3828 updateModuleTimestamp(*M.Mod);
3836 static ASTFileSignature readASTFileSignature(StringRef PCH);
3838 /// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3839 static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3840 return Stream.canSkipToPos(4) &&
3841 Stream.Read(8) == 'C' &&
3842 Stream.Read(8) == 'P' &&
3843 Stream.Read(8) == 'C' &&
3844 Stream.Read(8) == 'H';
3847 static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3851 case MK_ImplicitModule:
3852 case MK_ExplicitModule:
3853 case MK_PrebuiltModule:
3857 return 2; // main source file
3859 llvm_unreachable("unknown module kind");
3862 ASTReader::ASTReadResult
3863 ASTReader::ReadASTCore(StringRef FileName,
3865 SourceLocation ImportLoc,
3866 ModuleFile *ImportedBy,
3867 SmallVectorImpl<ImportedModule> &Loaded,
3868 off_t ExpectedSize, time_t ExpectedModTime,
3869 ASTFileSignature ExpectedSignature,
3870 unsigned ClientLoadCapabilities) {
3872 std::string ErrorStr;
3873 ModuleManager::AddModuleResult AddResult
3874 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3875 getGeneration(), ExpectedSize, ExpectedModTime,
3876 ExpectedSignature, readASTFileSignature,
3879 switch (AddResult) {
3880 case ModuleManager::AlreadyLoaded:
3883 case ModuleManager::NewlyLoaded:
3884 // Load module file below.
3887 case ModuleManager::Missing:
3888 // The module file was missing; if the client can handle that, return
3890 if (ClientLoadCapabilities & ARR_Missing)
3893 // Otherwise, return an error.
3894 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3895 << FileName << !ErrorStr.empty()
3899 case ModuleManager::OutOfDate:
3900 // We couldn't load the module file because it is out-of-date. If the
3901 // client can handle out-of-date, return it.
3902 if (ClientLoadCapabilities & ARR_OutOfDate)
3905 // Otherwise, return an error.
3906 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3907 << FileName << !ErrorStr.empty()
3912 assert(M && "Missing module file");
3914 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3916 if (FileName != "-") {
3917 CurrentDir = llvm::sys::path::parent_path(FileName);
3918 if (CurrentDir.empty()) CurrentDir = ".";
3922 BitstreamCursor &Stream = F.Stream;
3923 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
3924 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3926 // Sniff for the signature.
3927 if (!startsWithASTFileMagic(Stream)) {
3928 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3933 // This is used for compatibility with older PCH formats.
3934 bool HaveReadControlBlock = false;
3936 llvm::BitstreamEntry Entry = Stream.advance();
3938 switch (Entry.Kind) {
3939 case llvm::BitstreamEntry::Error:
3940 case llvm::BitstreamEntry::Record:
3941 case llvm::BitstreamEntry::EndBlock:
3942 Error("invalid record at top-level of AST file");
3945 case llvm::BitstreamEntry::SubBlock:
3950 case CONTROL_BLOCK_ID:
3951 HaveReadControlBlock = true;
3952 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
3954 // Check that we didn't try to load a non-module AST file as a module.
3956 // FIXME: Should we also perform the converse check? Loading a module as
3957 // a PCH file sort of works, but it's a bit wonky.
3958 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
3959 Type == MK_PrebuiltModule) &&
3960 F.ModuleName.empty()) {
3961 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3962 if (Result != OutOfDate ||
3963 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3964 Diag(diag::err_module_file_not_module) << FileName;
3969 case Failure: return Failure;
3970 case Missing: return Missing;
3971 case OutOfDate: return OutOfDate;
3972 case VersionMismatch: return VersionMismatch;
3973 case ConfigurationMismatch: return ConfigurationMismatch;
3974 case HadErrors: return HadErrors;
3979 if (!HaveReadControlBlock) {
3980 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3981 Diag(diag::err_pch_version_too_old);
3982 return VersionMismatch;
3985 // Record that we've loaded this module.
3986 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3990 if (Stream.SkipBlock()) {
3991 Error("malformed block record in AST file");
4001 /// Parse a record and blob containing module file extension metadata.
4002 static bool parseModuleFileExtensionMetadata(
4003 const SmallVectorImpl<uint64_t> &Record,
4005 ModuleFileExtensionMetadata &Metadata) {
4006 if (Record.size() < 4) return true;
4008 Metadata.MajorVersion = Record[0];
4009 Metadata.MinorVersion = Record[1];
4011 unsigned BlockNameLen = Record[2];
4012 unsigned UserInfoLen = Record[3];
4014 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4016 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4017 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4018 Blob.data() + BlockNameLen + UserInfoLen);
4022 ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4023 BitstreamCursor &Stream = F.Stream;
4027 llvm::BitstreamEntry Entry = Stream.advance();
4028 switch (Entry.Kind) {
4029 case llvm::BitstreamEntry::SubBlock:
4030 if (Stream.SkipBlock())
4035 case llvm::BitstreamEntry::EndBlock:
4038 case llvm::BitstreamEntry::Error:
4041 case llvm::BitstreamEntry::Record:
4047 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4049 case EXTENSION_METADATA: {
4050 ModuleFileExtensionMetadata Metadata;
4051 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4054 // Find a module file extension with this block name.
4055 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4056 if (Known == ModuleFileExtensions.end()) break;
4059 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4061 F.ExtensionReaders.push_back(std::move(Reader));
4072 void ASTReader::InitializeContext() {
4073 // If there's a listener, notify them that we "read" the translation unit.
4074 if (DeserializationListener)
4075 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
4076 Context.getTranslationUnitDecl());
4078 // FIXME: Find a better way to deal with collisions between these
4079 // built-in types. Right now, we just ignore the problem.
4081 // Load the special types.
4082 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4083 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4084 if (!Context.CFConstantStringTypeDecl)
4085 Context.setCFConstantStringType(GetType(String));
4088 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4089 QualType FileType = GetType(File);
4090 if (FileType.isNull()) {
4091 Error("FILE type is NULL");
4095 if (!Context.FILEDecl) {
4096 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4097 Context.setFILEDecl(Typedef->getDecl());
4099 const TagType *Tag = FileType->getAs<TagType>();
4101 Error("Invalid FILE type in AST file");
4104 Context.setFILEDecl(Tag->getDecl());
4109 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4110 QualType Jmp_bufType = GetType(Jmp_buf);
4111 if (Jmp_bufType.isNull()) {
4112 Error("jmp_buf type is NULL");
4116 if (!Context.jmp_bufDecl) {
4117 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4118 Context.setjmp_bufDecl(Typedef->getDecl());
4120 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4122 Error("Invalid jmp_buf type in AST file");
4125 Context.setjmp_bufDecl(Tag->getDecl());
4130 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4131 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4132 if (Sigjmp_bufType.isNull()) {
4133 Error("sigjmp_buf type is NULL");
4137 if (!Context.sigjmp_bufDecl) {
4138 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4139 Context.setsigjmp_bufDecl(Typedef->getDecl());
4141 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4142 assert(Tag && "Invalid sigjmp_buf type in AST file");
4143 Context.setsigjmp_bufDecl(Tag->getDecl());
4148 if (unsigned ObjCIdRedef
4149 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4150 if (Context.ObjCIdRedefinitionType.isNull())
4151 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4154 if (unsigned ObjCClassRedef
4155 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4156 if (Context.ObjCClassRedefinitionType.isNull())
4157 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4160 if (unsigned ObjCSelRedef
4161 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4162 if (Context.ObjCSelRedefinitionType.isNull())
4163 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4166 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4167 QualType Ucontext_tType = GetType(Ucontext_t);
4168 if (Ucontext_tType.isNull()) {
4169 Error("ucontext_t type is NULL");
4173 if (!Context.ucontext_tDecl) {
4174 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4175 Context.setucontext_tDecl(Typedef->getDecl());
4177 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4178 assert(Tag && "Invalid ucontext_t type in AST file");
4179 Context.setucontext_tDecl(Tag->getDecl());
4185 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4187 // If there were any CUDA special declarations, deserialize them.
4188 if (!CUDASpecialDeclRefs.empty()) {
4189 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4190 Context.setcudaConfigureCallDecl(
4191 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4194 // Re-export any modules that were imported by a non-module AST file.
4195 // FIXME: This does not make macro-only imports visible again.
4196 for (auto &Import : ImportedModules) {
4197 if (Module *Imported = getSubmodule(Import.ID)) {
4198 makeModuleVisible(Imported, Module::AllVisible,
4199 /*ImportLoc=*/Import.ImportLoc);
4200 if (Import.ImportLoc.isValid())
4201 PP.makeModuleVisible(Imported, Import.ImportLoc);
4202 // FIXME: should we tell Sema to make the module visible too?
4205 ImportedModules.clear();
4208 void ASTReader::finalizeForWriting() {
4209 // Nothing to do for now.
4212 /// \brief Reads and return the signature record from \p PCH's control block, or
4214 static ASTFileSignature readASTFileSignature(StringRef PCH) {
4215 BitstreamCursor Stream(PCH);
4216 if (!startsWithASTFileMagic(Stream))
4219 // Scan for the CONTROL_BLOCK_ID block.
4220 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4223 // Scan for SIGNATURE inside the control block.
4224 ASTReader::RecordData Record;
4226 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4227 if (Entry.Kind != llvm::BitstreamEntry::Record)
4232 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4237 /// \brief Retrieve the name of the original source file name
4238 /// directly from the AST file, without actually loading the AST
4240 std::string ASTReader::getOriginalSourceFile(
4241 const std::string &ASTFileName, FileManager &FileMgr,
4242 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
4243 // Open the AST file.
4244 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
4246 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4247 << ASTFileName << Buffer.getError().message();
4248 return std::string();
4251 // Initialize the stream
4252 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
4254 // Sniff for the signature.
4255 if (!startsWithASTFileMagic(Stream)) {
4256 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4257 return std::string();
4260 // Scan for the CONTROL_BLOCK_ID block.
4261 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
4262 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4263 return std::string();
4266 // Scan for ORIGINAL_FILE inside the control block.
4269 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4270 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4271 return std::string();
4273 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4274 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4275 return std::string();
4280 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4287 class SimplePCHValidator : public ASTReaderListener {
4288 const LangOptions &ExistingLangOpts;
4289 const TargetOptions &ExistingTargetOpts;
4290 const PreprocessorOptions &ExistingPPOpts;
4291 std::string ExistingModuleCachePath;
4292 FileManager &FileMgr;
4295 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4296 const TargetOptions &ExistingTargetOpts,
4297 const PreprocessorOptions &ExistingPPOpts,
4298 StringRef ExistingModuleCachePath,
4299 FileManager &FileMgr)
4300 : ExistingLangOpts(ExistingLangOpts),
4301 ExistingTargetOpts(ExistingTargetOpts),
4302 ExistingPPOpts(ExistingPPOpts),
4303 ExistingModuleCachePath(ExistingModuleCachePath),
4308 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4309 bool AllowCompatibleDifferences) override {
4310 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4311 AllowCompatibleDifferences);
4314 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4315 bool AllowCompatibleDifferences) override {
4316 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4317 AllowCompatibleDifferences);
4320 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4321 StringRef SpecificModuleCachePath,
4322 bool Complain) override {
4323 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4324 ExistingModuleCachePath,
4325 nullptr, ExistingLangOpts);
4328 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4330 std::string &SuggestedPredefines) override {
4331 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
4332 SuggestedPredefines, ExistingLangOpts);
4336 } // end anonymous namespace
4338 bool ASTReader::readASTFileControlBlock(
4339 StringRef Filename, FileManager &FileMgr,
4340 const PCHContainerReader &PCHContainerRdr,
4341 bool FindModuleFileExtensions,
4342 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
4343 // Open the AST file.
4344 // FIXME: This allows use of the VFS; we do not allow use of the
4345 // VFS when actually loading a module.
4346 auto Buffer = FileMgr.getBufferForFile(Filename);
4351 // Initialize the stream
4352 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
4354 // Sniff for the signature.
4355 if (!startsWithASTFileMagic(Stream))
4358 // Scan for the CONTROL_BLOCK_ID block.
4359 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4362 bool NeedsInputFiles = Listener.needsInputFileVisitation();
4363 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
4364 bool NeedsImports = Listener.needsImportVisitation();
4365 BitstreamCursor InputFilesCursor;
4368 std::string ModuleDir;
4369 bool DoneWithControlBlock = false;
4370 while (!DoneWithControlBlock) {
4371 llvm::BitstreamEntry Entry = Stream.advance();
4373 switch (Entry.Kind) {
4374 case llvm::BitstreamEntry::SubBlock: {
4376 case OPTIONS_BLOCK_ID: {
4377 std::string IgnoredSuggestedPredefines;
4378 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4379 /*AllowCompatibleConfigurationMismatch*/ false,
4380 Listener, IgnoredSuggestedPredefines,
4381 ValidateDiagnosticOptions) != Success)
4386 case INPUT_FILES_BLOCK_ID:
4387 InputFilesCursor = Stream;
4388 if (Stream.SkipBlock() ||
4390 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4395 if (Stream.SkipBlock())
4403 case llvm::BitstreamEntry::EndBlock:
4404 DoneWithControlBlock = true;
4407 case llvm::BitstreamEntry::Error:
4410 case llvm::BitstreamEntry::Record:
4414 if (DoneWithControlBlock) break;
4418 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4419 switch ((ControlRecordTypes)RecCode) {
4421 if (Record[0] != VERSION_MAJOR)
4424 if (Listener.ReadFullVersionInformation(Blob))
4430 Listener.ReadModuleName(Blob);
4432 case MODULE_DIRECTORY:
4435 case MODULE_MAP_FILE: {
4437 auto Path = ReadString(Record, Idx);
4438 ResolveImportedPath(Path, ModuleDir);
4439 Listener.ReadModuleMapFile(Path);
4442 case INPUT_FILE_OFFSETS: {
4443 if (!NeedsInputFiles)
4446 unsigned NumInputFiles = Record[0];
4447 unsigned NumUserFiles = Record[1];
4448 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
4449 for (unsigned I = 0; I != NumInputFiles; ++I) {
4450 // Go find this input file.
4451 bool isSystemFile = I >= NumUserFiles;
4453 if (isSystemFile && !NeedsSystemInputFiles)
4454 break; // the rest are system input files
4456 BitstreamCursor &Cursor = InputFilesCursor;
4457 SavedStreamPosition SavedPosition(Cursor);
4458 Cursor.JumpToBit(InputFileOffs[I]);
4460 unsigned Code = Cursor.ReadCode();
4463 bool shouldContinue = false;
4464 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4466 bool Overridden = static_cast<bool>(Record[3]);
4467 std::string Filename = Blob;
4468 ResolveImportedPath(Filename, ModuleDir);
4469 shouldContinue = Listener.visitInputFile(
4470 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
4473 if (!shouldContinue)
4483 unsigned Idx = 0, N = Record.size();
4485 // Read information about the AST file.
4486 Idx += 5; // ImportLoc, Size, ModTime, Signature
4487 std::string Filename = ReadString(Record, Idx);
4488 ResolveImportedPath(Filename, ModuleDir);
4489 Listener.visitImport(Filename);
4495 // No other validation to perform.
4500 // Look for module file extension blocks, if requested.
4501 if (FindModuleFileExtensions) {
4502 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4503 bool DoneWithExtensionBlock = false;
4504 while (!DoneWithExtensionBlock) {
4505 llvm::BitstreamEntry Entry = Stream.advance();
4507 switch (Entry.Kind) {
4508 case llvm::BitstreamEntry::SubBlock:
4509 if (Stream.SkipBlock())
4514 case llvm::BitstreamEntry::EndBlock:
4515 DoneWithExtensionBlock = true;
4518 case llvm::BitstreamEntry::Error:
4521 case llvm::BitstreamEntry::Record:
4527 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4529 case EXTENSION_METADATA: {
4530 ModuleFileExtensionMetadata Metadata;
4531 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4534 Listener.readModuleFileExtension(Metadata);
4545 bool ASTReader::isAcceptableASTFile(
4546 StringRef Filename, FileManager &FileMgr,
4547 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
4548 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4549 std::string ExistingModuleCachePath) {
4550 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4551 ExistingModuleCachePath, FileMgr);
4552 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
4553 /*FindModuleFileExtensions=*/false,
4555 /*ValidateDiagnosticOptions=*/true);
4558 ASTReader::ASTReadResult
4559 ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
4560 // Enter the submodule block.
4561 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4562 Error("malformed submodule block record in AST file");
4566 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4568 Module *CurrentModule = nullptr;
4571 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4573 switch (Entry.Kind) {
4574 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4575 case llvm::BitstreamEntry::Error:
4576 Error("malformed block record in AST file");
4578 case llvm::BitstreamEntry::EndBlock:
4580 case llvm::BitstreamEntry::Record:
4581 // The interesting case.
4588 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4590 if ((Kind == SUBMODULE_METADATA) != First) {
4591 Error("submodule metadata record should be at beginning of block");
4596 // Submodule information is only valid if we have a current module.
4597 // FIXME: Should we error on these cases?
4598 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4599 Kind != SUBMODULE_DEFINITION)
4603 default: // Default behavior: ignore.
4606 case SUBMODULE_DEFINITION: {
4607 if (Record.size() < 8) {
4608 Error("malformed module definition");
4612 StringRef Name = Blob;
4614 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4615 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4616 bool IsFramework = Record[Idx++];
4617 bool IsExplicit = Record[Idx++];
4618 bool IsSystem = Record[Idx++];
4619 bool IsExternC = Record[Idx++];
4620 bool InferSubmodules = Record[Idx++];
4621 bool InferExplicitSubmodules = Record[Idx++];
4622 bool InferExportWildcard = Record[Idx++];
4623 bool ConfigMacrosExhaustive = Record[Idx++];
4625 Module *ParentModule = nullptr;
4627 ParentModule = getSubmodule(Parent);
4629 // Retrieve this (sub)module from the module map, creating it if
4631 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
4634 // FIXME: set the definition loc for CurrentModule, or call
4635 // ModMap.setInferredModuleAllowedBy()
4637 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4638 if (GlobalIndex >= SubmodulesLoaded.size() ||
4639 SubmodulesLoaded[GlobalIndex]) {
4640 Error("too many submodules");
4644 if (!ParentModule) {
4645 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4646 if (CurFile != F.File) {
4647 if (!Diags.isDiagnosticInFlight()) {
4648 Diag(diag::err_module_file_conflict)
4649 << CurrentModule->getTopLevelModuleName()
4650 << CurFile->getName()
4651 << F.File->getName();
4657 CurrentModule->setASTFile(F.File);
4660 CurrentModule->Signature = F.Signature;
4661 CurrentModule->IsFromModuleFile = true;
4662 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
4663 CurrentModule->IsExternC = IsExternC;
4664 CurrentModule->InferSubmodules = InferSubmodules;
4665 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4666 CurrentModule->InferExportWildcard = InferExportWildcard;
4667 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
4668 if (DeserializationListener)
4669 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4671 SubmodulesLoaded[GlobalIndex] = CurrentModule;
4673 // Clear out data that will be replaced by what is in the module file.
4674 CurrentModule->LinkLibraries.clear();
4675 CurrentModule->ConfigMacros.clear();
4676 CurrentModule->UnresolvedConflicts.clear();
4677 CurrentModule->Conflicts.clear();
4679 // The module is available unless it's missing a requirement; relevant
4680 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4681 // Missing headers that were present when the module was built do not
4682 // make it unavailable -- if we got this far, this must be an explicitly
4683 // imported module file.
4684 CurrentModule->Requirements.clear();
4685 CurrentModule->MissingHeaders.clear();
4686 CurrentModule->IsMissingRequirement =
4687 ParentModule && ParentModule->IsMissingRequirement;
4688 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
4692 case SUBMODULE_UMBRELLA_HEADER: {
4693 std::string Filename = Blob;
4694 ResolveImportedPath(F, Filename);
4695 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
4696 if (!CurrentModule->getUmbrellaHeader())
4697 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4698 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
4699 // This can be a spurious difference caused by changing the VFS to
4700 // point to a different copy of the file, and it is too late to
4701 // to rebuild safely.
4702 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4703 // after input file validation only real problems would remain and we
4704 // could just error. For now, assume it's okay.
4711 case SUBMODULE_HEADER:
4712 case SUBMODULE_EXCLUDED_HEADER:
4713 case SUBMODULE_PRIVATE_HEADER:
4714 // We lazily associate headers with their modules via the HeaderInfo table.
4715 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4716 // of complete filenames or remove it entirely.
4719 case SUBMODULE_TEXTUAL_HEADER:
4720 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4721 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4725 case SUBMODULE_TOPHEADER: {
4726 CurrentModule->addTopHeaderFilename(Blob);
4730 case SUBMODULE_UMBRELLA_DIR: {
4731 std::string Dirname = Blob;
4732 ResolveImportedPath(F, Dirname);
4733 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
4734 if (!CurrentModule->getUmbrellaDir())
4735 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4736 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
4737 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4738 Error("mismatched umbrella directories in submodule");
4745 case SUBMODULE_METADATA: {
4746 F.BaseSubmoduleID = getTotalNumSubmodules();
4747 F.LocalNumSubmodules = Record[0];
4748 unsigned LocalBaseSubmoduleID = Record[1];
4749 if (F.LocalNumSubmodules > 0) {
4750 // Introduce the global -> local mapping for submodules within this
4752 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4754 // Introduce the local -> global mapping for submodules within this
4756 F.SubmoduleRemap.insertOrReplace(
4757 std::make_pair(LocalBaseSubmoduleID,
4758 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4760 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4765 case SUBMODULE_IMPORTS: {
4766 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
4767 UnresolvedModuleRef Unresolved;
4768 Unresolved.File = &F;
4769 Unresolved.Mod = CurrentModule;
4770 Unresolved.ID = Record[Idx];
4771 Unresolved.Kind = UnresolvedModuleRef::Import;
4772 Unresolved.IsWildcard = false;
4773 UnresolvedModuleRefs.push_back(Unresolved);
4778 case SUBMODULE_EXPORTS: {
4779 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
4780 UnresolvedModuleRef Unresolved;
4781 Unresolved.File = &F;
4782 Unresolved.Mod = CurrentModule;
4783 Unresolved.ID = Record[Idx];
4784 Unresolved.Kind = UnresolvedModuleRef::Export;
4785 Unresolved.IsWildcard = Record[Idx + 1];
4786 UnresolvedModuleRefs.push_back(Unresolved);
4789 // Once we've loaded the set of exports, there's no reason to keep
4790 // the parsed, unresolved exports around.
4791 CurrentModule->UnresolvedExports.clear();
4794 case SUBMODULE_REQUIRES: {
4795 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
4796 Context.getTargetInfo());
4800 case SUBMODULE_LINK_LIBRARY:
4801 CurrentModule->LinkLibraries.push_back(
4802 Module::LinkLibrary(Blob, Record[0]));
4805 case SUBMODULE_CONFIG_MACRO:
4806 CurrentModule->ConfigMacros.push_back(Blob.str());
4809 case SUBMODULE_CONFLICT: {
4810 UnresolvedModuleRef Unresolved;
4811 Unresolved.File = &F;
4812 Unresolved.Mod = CurrentModule;
4813 Unresolved.ID = Record[0];
4814 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4815 Unresolved.IsWildcard = false;
4816 Unresolved.String = Blob;
4817 UnresolvedModuleRefs.push_back(Unresolved);
4821 case SUBMODULE_INITIALIZERS:
4822 SmallVector<uint32_t, 16> Inits;
4823 for (auto &ID : Record)
4824 Inits.push_back(getGlobalDeclID(F, ID));
4825 Context.addLazyModuleInitializers(CurrentModule, Inits);
4831 /// \brief Parse the record that corresponds to a LangOptions data
4834 /// This routine parses the language options from the AST file and then gives
4835 /// them to the AST listener if one is set.
4837 /// \returns true if the listener deems the file unacceptable, false otherwise.
4838 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4840 ASTReaderListener &Listener,
4841 bool AllowCompatibleDifferences) {
4842 LangOptions LangOpts;
4844 #define LANGOPT(Name, Bits, Default, Description) \
4845 LangOpts.Name = Record[Idx++];
4846 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4847 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4848 #include "clang/Basic/LangOptions.def"
4849 #define SANITIZER(NAME, ID) \
4850 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
4851 #include "clang/Basic/Sanitizers.def"
4853 for (unsigned N = Record[Idx++]; N; --N)
4854 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4856 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4857 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4858 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4860 LangOpts.CurrentModule = ReadString(Record, Idx);
4863 for (unsigned N = Record[Idx++]; N; --N) {
4864 LangOpts.CommentOpts.BlockCommandNames.push_back(
4865 ReadString(Record, Idx));
4867 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
4869 // OpenMP offloading options.
4870 for (unsigned N = Record[Idx++]; N; --N) {
4871 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4874 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4876 return Listener.ReadLanguageOptions(LangOpts, Complain,
4877 AllowCompatibleDifferences);
4880 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4881 ASTReaderListener &Listener,
4882 bool AllowCompatibleDifferences) {
4884 TargetOptions TargetOpts;
4885 TargetOpts.Triple = ReadString(Record, Idx);
4886 TargetOpts.CPU = ReadString(Record, Idx);
4887 TargetOpts.ABI = ReadString(Record, Idx);
4888 for (unsigned N = Record[Idx++]; N; --N) {
4889 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4891 for (unsigned N = Record[Idx++]; N; --N) {
4892 TargetOpts.Features.push_back(ReadString(Record, Idx));
4895 return Listener.ReadTargetOptions(TargetOpts, Complain,
4896 AllowCompatibleDifferences);
4899 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4900 ASTReaderListener &Listener) {
4901 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
4903 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
4904 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4905 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
4906 #include "clang/Basic/DiagnosticOptions.def"
4908 for (unsigned N = Record[Idx++]; N; --N)
4909 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
4910 for (unsigned N = Record[Idx++]; N; --N)
4911 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
4913 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4916 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4917 ASTReaderListener &Listener) {
4918 FileSystemOptions FSOpts;
4920 FSOpts.WorkingDir = ReadString(Record, Idx);
4921 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4924 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4926 ASTReaderListener &Listener) {
4927 HeaderSearchOptions HSOpts;
4929 HSOpts.Sysroot = ReadString(Record, Idx);
4932 for (unsigned N = Record[Idx++]; N; --N) {
4933 std::string Path = ReadString(Record, Idx);
4934 frontend::IncludeDirGroup Group
4935 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
4936 bool IsFramework = Record[Idx++];
4937 bool IgnoreSysRoot = Record[Idx++];
4938 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4942 // System header prefixes.
4943 for (unsigned N = Record[Idx++]; N; --N) {
4944 std::string Prefix = ReadString(Record, Idx);
4945 bool IsSystemHeader = Record[Idx++];
4946 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
4949 HSOpts.ResourceDir = ReadString(Record, Idx);
4950 HSOpts.ModuleCachePath = ReadString(Record, Idx);
4951 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
4952 HSOpts.DisableModuleHash = Record[Idx++];
4953 HSOpts.UseBuiltinIncludes = Record[Idx++];
4954 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4955 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4956 HSOpts.UseLibcxx = Record[Idx++];
4957 std::string SpecificModuleCachePath = ReadString(Record, Idx);
4959 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4963 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4965 ASTReaderListener &Listener,
4966 std::string &SuggestedPredefines) {
4967 PreprocessorOptions PPOpts;
4970 // Macro definitions/undefs
4971 for (unsigned N = Record[Idx++]; N; --N) {
4972 std::string Macro = ReadString(Record, Idx);
4973 bool IsUndef = Record[Idx++];
4974 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4978 for (unsigned N = Record[Idx++]; N; --N) {
4979 PPOpts.Includes.push_back(ReadString(Record, Idx));
4983 for (unsigned N = Record[Idx++]; N; --N) {
4984 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4987 PPOpts.UsePredefines = Record[Idx++];
4988 PPOpts.DetailedRecord = Record[Idx++];
4989 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4990 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4991 PPOpts.ObjCXXARCStandardLibrary =
4992 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4993 SuggestedPredefines.clear();
4994 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4995 SuggestedPredefines);
4998 std::pair<ModuleFile *, unsigned>
4999 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5000 GlobalPreprocessedEntityMapType::iterator
5001 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
5002 assert(I != GlobalPreprocessedEntityMap.end() &&
5003 "Corrupted global preprocessed entity map");
5004 ModuleFile *M = I->second;
5005 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5006 return std::make_pair(M, LocalIndex);
5009 llvm::iterator_range<PreprocessingRecord::iterator>
5010 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5011 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5012 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5013 Mod.NumPreprocessedEntities);
5015 return llvm::make_range(PreprocessingRecord::iterator(),
5016 PreprocessingRecord::iterator());
5019 llvm::iterator_range<ASTReader::ModuleDeclIterator>
5020 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
5021 return llvm::make_range(
5022 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5023 ModuleDeclIterator(this, &Mod,
5024 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
5027 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5028 PreprocessedEntityID PPID = Index+1;
5029 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5030 ModuleFile &M = *PPInfo.first;
5031 unsigned LocalIndex = PPInfo.second;
5032 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5034 if (!PP.getPreprocessingRecord()) {
5035 Error("no preprocessing record");
5039 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
5040 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5042 llvm::BitstreamEntry Entry =
5043 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5044 if (Entry.Kind != llvm::BitstreamEntry::Record)
5048 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5049 TranslateSourceLocation(M, PPOffs.getEnd()));
5050 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
5053 PreprocessorDetailRecordTypes RecType =
5054 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5055 Entry.ID, Record, &Blob);
5057 case PPD_MACRO_EXPANSION: {
5058 bool isBuiltin = Record[0];
5059 IdentifierInfo *Name = nullptr;
5060 MacroDefinitionRecord *Def = nullptr;
5062 Name = getLocalIdentifier(M, Record[1]);
5064 PreprocessedEntityID GlobalID =
5065 getGlobalPreprocessedEntityID(M, Record[1]);
5066 Def = cast<MacroDefinitionRecord>(
5067 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
5072 ME = new (PPRec) MacroExpansion(Name, Range);
5074 ME = new (PPRec) MacroExpansion(Def, Range);
5079 case PPD_MACRO_DEFINITION: {
5080 // Decode the identifier info and then check again; if the macro is
5081 // still defined and associated with the identifier,
5082 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
5083 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
5085 if (DeserializationListener)
5086 DeserializationListener->MacroDefinitionRead(PPID, MD);
5091 case PPD_INCLUSION_DIRECTIVE: {
5092 const char *FullFileNameStart = Blob.data() + Record[0];
5093 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
5094 const FileEntry *File = nullptr;
5095 if (!FullFileName.empty())
5096 File = PP.getFileManager().getFile(FullFileName);
5098 // FIXME: Stable encoding
5099 InclusionDirective::InclusionKind Kind
5100 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5101 InclusionDirective *ID
5102 = new (PPRec) InclusionDirective(PPRec, Kind,
5103 StringRef(Blob.data(), Record[0]),
5104 Record[1], Record[3],
5111 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5114 /// \brief \arg SLocMapI points at a chunk of a module that contains no
5115 /// preprocessed entities or the entities it contains are not the ones we are
5116 /// looking for. Find the next module that contains entities and return the ID
5117 /// of the first entry.
5118 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5119 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5121 for (GlobalSLocOffsetMapType::const_iterator
5122 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5123 ModuleFile &M = *SLocMapI->second;
5124 if (M.NumPreprocessedEntities)
5125 return M.BasePreprocessedEntityID;
5128 return getTotalNumPreprocessedEntities();
5133 struct PPEntityComp {
5134 const ASTReader &Reader;
5137 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5139 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5140 SourceLocation LHS = getLoc(L);
5141 SourceLocation RHS = getLoc(R);
5142 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5145 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5146 SourceLocation LHS = getLoc(L);
5147 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5150 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5151 SourceLocation RHS = getLoc(R);
5152 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5155 SourceLocation getLoc(const PPEntityOffset &PPE) const {
5156 return Reader.TranslateSourceLocation(M, PPE.getBegin());
5160 } // end anonymous namespace
5162 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5163 bool EndsAfter) const {
5164 if (SourceMgr.isLocalSourceLocation(Loc))
5165 return getTotalNumPreprocessedEntities();
5167 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5168 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
5169 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5170 "Corrupted global sloc offset map");
5172 if (SLocMapI->second->NumPreprocessedEntities == 0)
5173 return findNextPreprocessedEntity(SLocMapI);
5175 ModuleFile &M = *SLocMapI->second;
5176 typedef const PPEntityOffset *pp_iterator;
5177 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5178 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5180 size_t Count = M.NumPreprocessedEntities;
5182 pp_iterator First = pp_begin;
5186 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5187 PPEntityComp(*this, M));
5189 // Do a binary search manually instead of using std::lower_bound because
5190 // The end locations of entities may be unordered (when a macro expansion
5191 // is inside another macro argument), but for this case it is not important
5192 // whether we get the first macro expansion or its containing macro.
5196 std::advance(PPI, Half);
5197 if (SourceMgr.isBeforeInTranslationUnit(
5198 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
5201 Count = Count - Half - 1;
5208 return findNextPreprocessedEntity(SLocMapI);
5210 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5213 /// \brief Returns a pair of [Begin, End) indices of preallocated
5214 /// preprocessed entities that \arg Range encompasses.
5215 std::pair<unsigned, unsigned>
5216 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5217 if (Range.isInvalid())
5218 return std::make_pair(0,0);
5219 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5221 PreprocessedEntityID BeginID =
5222 findPreprocessedEntity(Range.getBegin(), false);
5223 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
5224 return std::make_pair(BeginID, EndID);
5227 /// \brief Optionally returns true or false if the preallocated preprocessed
5228 /// entity with index \arg Index came from file \arg FID.
5229 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
5231 if (FID.isInvalid())
5234 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5235 ModuleFile &M = *PPInfo.first;
5236 unsigned LocalIndex = PPInfo.second;
5237 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5239 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
5240 if (Loc.isInvalid())
5243 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5251 /// \brief Visitor used to search for information about a header file.
5252 class HeaderFileInfoVisitor {
5253 const FileEntry *FE;
5255 Optional<HeaderFileInfo> HFI;
5258 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5261 bool operator()(ModuleFile &M) {
5262 HeaderFileInfoLookupTable *Table
5263 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5267 // Look in the on-disk hash table for an entry for this file name.
5268 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
5269 if (Pos == Table->end())
5276 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
5279 } // end anonymous namespace
5281 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
5282 HeaderFileInfoVisitor Visitor(FE);
5283 ModuleMgr.visit(Visitor);
5284 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
5287 return HeaderFileInfo();
5290 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5291 // FIXME: Make it work properly with modules.
5292 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
5293 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5294 ModuleFile &F = *(*I);
5297 assert(!Diag.DiagStates.empty());
5298 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5299 while (Idx < F.PragmaDiagMappings.size()) {
5300 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5301 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5302 if (DiagStateID != 0) {
5303 Diag.DiagStatePoints.push_back(
5304 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5305 FullSourceLoc(Loc, SourceMgr)));
5309 assert(DiagStateID == 0);
5310 // A new DiagState was created here.
5311 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5312 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5313 DiagStates.push_back(NewState);
5314 Diag.DiagStatePoints.push_back(
5315 DiagnosticsEngine::DiagStatePoint(NewState,
5316 FullSourceLoc(Loc, SourceMgr)));
5318 assert(Idx < F.PragmaDiagMappings.size() &&
5319 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5320 if (Idx >= F.PragmaDiagMappings.size()) {
5321 break; // Something is messed up but at least avoid infinite loop in
5324 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5325 if (DiagID == (unsigned)-1) {
5326 break; // no more diag/map pairs for this location.
5328 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5329 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5330 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
5336 /// \brief Get the correct cursor and offset for loading a type.
5337 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5338 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5339 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5340 ModuleFile *M = I->second;
5341 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5344 /// \brief Read and return the type with the given index..
5346 /// The index is the type ID, shifted and minus the number of predefs. This
5347 /// routine actually reads the record corresponding to the type at the given
5348 /// location. It is a helper routine for GetType, which deals with reading type
5350 QualType ASTReader::readTypeRecord(unsigned Index) {
5351 RecordLocation Loc = TypeCursorForIndex(Index);
5352 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
5354 // Keep track of where we are in the stream, then jump back there
5355 // after reading this type.
5356 SavedStreamPosition SavedPosition(DeclsCursor);
5358 ReadingKindTracker ReadingKind(Read_Type, *this);
5360 // Note that we are loading a type record.
5361 Deserializing AType(this);
5364 DeclsCursor.JumpToBit(Loc.Offset);
5366 unsigned Code = DeclsCursor.ReadCode();
5367 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
5368 case TYPE_EXT_QUAL: {
5369 if (Record.size() != 2) {
5370 Error("Incorrect encoding of extended qualifier type");
5373 QualType Base = readType(*Loc.F, Record, Idx);
5374 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5375 return Context.getQualifiedType(Base, Quals);
5378 case TYPE_COMPLEX: {
5379 if (Record.size() != 1) {
5380 Error("Incorrect encoding of complex type");
5383 QualType ElemType = readType(*Loc.F, Record, Idx);
5384 return Context.getComplexType(ElemType);
5387 case TYPE_POINTER: {
5388 if (Record.size() != 1) {
5389 Error("Incorrect encoding of pointer type");
5392 QualType PointeeType = readType(*Loc.F, Record, Idx);
5393 return Context.getPointerType(PointeeType);
5396 case TYPE_DECAYED: {
5397 if (Record.size() != 1) {
5398 Error("Incorrect encoding of decayed type");
5401 QualType OriginalType = readType(*Loc.F, Record, Idx);
5402 QualType DT = Context.getAdjustedParameterType(OriginalType);
5403 if (!isa<DecayedType>(DT))
5404 Error("Decayed type does not decay");
5408 case TYPE_ADJUSTED: {
5409 if (Record.size() != 2) {
5410 Error("Incorrect encoding of adjusted type");
5413 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5414 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5415 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5418 case TYPE_BLOCK_POINTER: {
5419 if (Record.size() != 1) {
5420 Error("Incorrect encoding of block pointer type");
5423 QualType PointeeType = readType(*Loc.F, Record, Idx);
5424 return Context.getBlockPointerType(PointeeType);
5427 case TYPE_LVALUE_REFERENCE: {
5428 if (Record.size() != 2) {
5429 Error("Incorrect encoding of lvalue reference type");
5432 QualType PointeeType = readType(*Loc.F, Record, Idx);
5433 return Context.getLValueReferenceType(PointeeType, Record[1]);
5436 case TYPE_RVALUE_REFERENCE: {
5437 if (Record.size() != 1) {
5438 Error("Incorrect encoding of rvalue reference type");
5441 QualType PointeeType = readType(*Loc.F, Record, Idx);
5442 return Context.getRValueReferenceType(PointeeType);
5445 case TYPE_MEMBER_POINTER: {
5446 if (Record.size() != 2) {
5447 Error("Incorrect encoding of member pointer type");
5450 QualType PointeeType = readType(*Loc.F, Record, Idx);
5451 QualType ClassType = readType(*Loc.F, Record, Idx);
5452 if (PointeeType.isNull() || ClassType.isNull())
5455 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5458 case TYPE_CONSTANT_ARRAY: {
5459 QualType ElementType = readType(*Loc.F, Record, Idx);
5460 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5461 unsigned IndexTypeQuals = Record[2];
5463 llvm::APInt Size = ReadAPInt(Record, Idx);
5464 return Context.getConstantArrayType(ElementType, Size,
5465 ASM, IndexTypeQuals);
5468 case TYPE_INCOMPLETE_ARRAY: {
5469 QualType ElementType = readType(*Loc.F, Record, Idx);
5470 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5471 unsigned IndexTypeQuals = Record[2];
5472 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5475 case TYPE_VARIABLE_ARRAY: {
5476 QualType ElementType = readType(*Loc.F, Record, Idx);
5477 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5478 unsigned IndexTypeQuals = Record[2];
5479 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5480 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5481 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5482 ASM, IndexTypeQuals,
5483 SourceRange(LBLoc, RBLoc));
5487 if (Record.size() != 3) {
5488 Error("incorrect encoding of vector type in AST file");
5492 QualType ElementType = readType(*Loc.F, Record, Idx);
5493 unsigned NumElements = Record[1];
5494 unsigned VecKind = Record[2];
5495 return Context.getVectorType(ElementType, NumElements,
5496 (VectorType::VectorKind)VecKind);
5499 case TYPE_EXT_VECTOR: {
5500 if (Record.size() != 3) {
5501 Error("incorrect encoding of extended vector type in AST file");
5505 QualType ElementType = readType(*Loc.F, Record, Idx);
5506 unsigned NumElements = Record[1];
5507 return Context.getExtVectorType(ElementType, NumElements);
5510 case TYPE_FUNCTION_NO_PROTO: {
5511 if (Record.size() != 6) {
5512 Error("incorrect encoding of no-proto function type");
5515 QualType ResultType = readType(*Loc.F, Record, Idx);
5516 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5517 (CallingConv)Record[4], Record[5]);
5518 return Context.getFunctionNoProtoType(ResultType, Info);
5521 case TYPE_FUNCTION_PROTO: {
5522 QualType ResultType = readType(*Loc.F, Record, Idx);
5524 FunctionProtoType::ExtProtoInfo EPI;
5525 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5526 /*hasregparm*/ Record[2],
5527 /*regparm*/ Record[3],
5528 static_cast<CallingConv>(Record[4]),
5529 /*produces*/ Record[5]);
5533 EPI.Variadic = Record[Idx++];
5534 EPI.HasTrailingReturn = Record[Idx++];
5535 EPI.TypeQuals = Record[Idx++];
5536 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
5537 SmallVector<QualType, 8> ExceptionStorage;
5538 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
5540 unsigned NumParams = Record[Idx++];
5541 SmallVector<QualType, 16> ParamTypes;
5542 for (unsigned I = 0; I != NumParams; ++I)
5543 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5545 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5546 if (Idx != Record.size()) {
5547 for (unsigned I = 0; I != NumParams; ++I)
5548 ExtParameterInfos.push_back(
5549 FunctionProtoType::ExtParameterInfo
5550 ::getFromOpaqueValue(Record[Idx++]));
5551 EPI.ExtParameterInfos = ExtParameterInfos.data();
5554 assert(Idx == Record.size());
5556 return Context.getFunctionType(ResultType, ParamTypes, EPI);
5559 case TYPE_UNRESOLVED_USING: {
5561 return Context.getTypeDeclType(
5562 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5565 case TYPE_TYPEDEF: {
5566 if (Record.size() != 2) {
5567 Error("incorrect encoding of typedef type");
5571 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5572 QualType Canonical = readType(*Loc.F, Record, Idx);
5573 if (!Canonical.isNull())
5574 Canonical = Context.getCanonicalType(Canonical);
5575 return Context.getTypedefType(Decl, Canonical);
5578 case TYPE_TYPEOF_EXPR:
5579 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5582 if (Record.size() != 1) {
5583 Error("incorrect encoding of typeof(type) in AST file");
5586 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5587 return Context.getTypeOfType(UnderlyingType);
5590 case TYPE_DECLTYPE: {
5591 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5592 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5595 case TYPE_UNARY_TRANSFORM: {
5596 QualType BaseType = readType(*Loc.F, Record, Idx);
5597 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5598 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5599 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5603 QualType Deduced = readType(*Loc.F, Record, Idx);
5604 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
5605 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5606 return Context.getAutoType(Deduced, Keyword, IsDependent);
5610 if (Record.size() != 2) {
5611 Error("incorrect encoding of record type");
5615 bool IsDependent = Record[Idx++];
5616 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5617 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5618 QualType T = Context.getRecordType(RD);
5619 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5624 if (Record.size() != 2) {
5625 Error("incorrect encoding of enum type");
5629 bool IsDependent = Record[Idx++];
5631 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5632 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5636 case TYPE_ATTRIBUTED: {
5637 if (Record.size() != 3) {
5638 Error("incorrect encoding of attributed type");
5641 QualType modifiedType = readType(*Loc.F, Record, Idx);
5642 QualType equivalentType = readType(*Loc.F, Record, Idx);
5643 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5644 return Context.getAttributedType(kind, modifiedType, equivalentType);
5648 if (Record.size() != 1) {
5649 Error("incorrect encoding of paren type");
5652 QualType InnerType = readType(*Loc.F, Record, Idx);
5653 return Context.getParenType(InnerType);
5656 case TYPE_PACK_EXPANSION: {
5657 if (Record.size() != 2) {
5658 Error("incorrect encoding of pack expansion type");
5661 QualType Pattern = readType(*Loc.F, Record, Idx);
5662 if (Pattern.isNull())
5664 Optional<unsigned> NumExpansions;
5666 NumExpansions = Record[1] - 1;
5667 return Context.getPackExpansionType(Pattern, NumExpansions);
5670 case TYPE_ELABORATED: {
5672 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5673 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5674 QualType NamedType = readType(*Loc.F, Record, Idx);
5675 return Context.getElaboratedType(Keyword, NNS, NamedType);
5678 case TYPE_OBJC_INTERFACE: {
5680 ObjCInterfaceDecl *ItfD
5681 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5682 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5685 case TYPE_OBJC_TYPE_PARAM: {
5687 ObjCTypeParamDecl *Decl
5688 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
5689 unsigned NumProtos = Record[Idx++];
5690 SmallVector<ObjCProtocolDecl*, 4> Protos;
5691 for (unsigned I = 0; I != NumProtos; ++I)
5692 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5693 return Context.getObjCTypeParamType(Decl, Protos);
5695 case TYPE_OBJC_OBJECT: {
5697 QualType Base = readType(*Loc.F, Record, Idx);
5698 unsigned NumTypeArgs = Record[Idx++];
5699 SmallVector<QualType, 4> TypeArgs;
5700 for (unsigned I = 0; I != NumTypeArgs; ++I)
5701 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
5702 unsigned NumProtos = Record[Idx++];
5703 SmallVector<ObjCProtocolDecl*, 4> Protos;
5704 for (unsigned I = 0; I != NumProtos; ++I)
5705 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5706 bool IsKindOf = Record[Idx++];
5707 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
5710 case TYPE_OBJC_OBJECT_POINTER: {
5712 QualType Pointee = readType(*Loc.F, Record, Idx);
5713 return Context.getObjCObjectPointerType(Pointee);
5716 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5718 QualType Parm = readType(*Loc.F, Record, Idx);
5719 QualType Replacement = readType(*Loc.F, Record, Idx);
5720 return Context.getSubstTemplateTypeParmType(
5721 cast<TemplateTypeParmType>(Parm),
5722 Context.getCanonicalType(Replacement));
5725 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5727 QualType Parm = readType(*Loc.F, Record, Idx);
5728 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5729 return Context.getSubstTemplateTypeParmPackType(
5730 cast<TemplateTypeParmType>(Parm),
5734 case TYPE_INJECTED_CLASS_NAME: {
5735 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5736 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5737 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5738 // for AST reading, too much interdependencies.
5739 const Type *T = nullptr;
5740 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5741 if (const Type *Existing = DI->getTypeForDecl()) {
5747 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5748 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5749 DI->setTypeForDecl(T);
5751 return QualType(T, 0);
5754 case TYPE_TEMPLATE_TYPE_PARM: {
5756 unsigned Depth = Record[Idx++];
5757 unsigned Index = Record[Idx++];
5758 bool Pack = Record[Idx++];
5759 TemplateTypeParmDecl *D
5760 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5761 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5764 case TYPE_DEPENDENT_NAME: {
5766 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5767 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5768 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
5769 QualType Canon = readType(*Loc.F, Record, Idx);
5770 if (!Canon.isNull())
5771 Canon = Context.getCanonicalType(Canon);
5772 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5775 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5777 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5778 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5779 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
5780 unsigned NumArgs = Record[Idx++];
5781 SmallVector<TemplateArgument, 8> Args;
5782 Args.reserve(NumArgs);
5784 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5785 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5789 case TYPE_DEPENDENT_SIZED_ARRAY: {
5793 QualType ElementType = readType(*Loc.F, Record, Idx);
5794 ArrayType::ArraySizeModifier ASM
5795 = (ArrayType::ArraySizeModifier)Record[Idx++];
5796 unsigned IndexTypeQuals = Record[Idx++];
5798 // DependentSizedArrayType
5799 Expr *NumElts = ReadExpr(*Loc.F);
5800 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5802 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5803 IndexTypeQuals, Brackets);
5806 case TYPE_TEMPLATE_SPECIALIZATION: {
5808 bool IsDependent = Record[Idx++];
5809 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5810 SmallVector<TemplateArgument, 8> Args;
5811 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5812 QualType Underlying = readType(*Loc.F, Record, Idx);
5814 if (Underlying.isNull())
5815 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
5817 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
5818 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5823 if (Record.size() != 1) {
5824 Error("Incorrect encoding of atomic type");
5827 QualType ValueType = readType(*Loc.F, Record, Idx);
5828 return Context.getAtomicType(ValueType);
5832 if (Record.size() != 2) {
5833 Error("Incorrect encoding of pipe type");
5837 // Reading the pipe element type.
5838 QualType ElementType = readType(*Loc.F, Record, Idx);
5839 unsigned ReadOnly = Record[1];
5840 return Context.getPipeType(ElementType, ReadOnly);
5844 llvm_unreachable("Invalid TypeCode!");
5847 void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5848 SmallVectorImpl<QualType> &Exceptions,
5849 FunctionProtoType::ExceptionSpecInfo &ESI,
5850 const RecordData &Record, unsigned &Idx) {
5851 ExceptionSpecificationType EST =
5852 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5854 if (EST == EST_Dynamic) {
5855 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
5856 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5857 ESI.Exceptions = Exceptions;
5858 } else if (EST == EST_ComputedNoexcept) {
5859 ESI.NoexceptExpr = ReadExpr(ModuleFile);
5860 } else if (EST == EST_Uninstantiated) {
5861 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5862 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5863 } else if (EST == EST_Unevaluated) {
5864 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5868 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5871 const ASTReader::RecordData &Record;
5874 SourceLocation ReadSourceLocation() {
5875 return Reader->ReadSourceLocation(*F, Record, Idx);
5878 TypeSourceInfo *GetTypeSourceInfo() {
5879 return Reader->GetTypeSourceInfo(*F, Record, Idx);
5882 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
5883 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
5887 TypeLocReader(ModuleFile &F, ASTReader &Reader,
5888 const ASTReader::RecordData &Record, unsigned &Idx)
5889 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
5891 // We want compile-time assurance that we've enumerated all of
5892 // these, so unfortunately we have to declare them first, then
5893 // define them out-of-line.
5894 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5895 #define TYPELOC(CLASS, PARENT) \
5896 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5897 #include "clang/AST/TypeLocNodes.def"
5899 void VisitFunctionTypeLoc(FunctionTypeLoc);
5900 void VisitArrayTypeLoc(ArrayTypeLoc);
5903 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5907 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5908 TL.setBuiltinLoc(ReadSourceLocation());
5909 if (TL.needsExtraLocalData()) {
5910 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5911 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5912 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5913 TL.setModeAttr(Record[Idx++]);
5917 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5918 TL.setNameLoc(ReadSourceLocation());
5921 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5922 TL.setStarLoc(ReadSourceLocation());
5925 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5929 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5933 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5934 TL.setCaretLoc(ReadSourceLocation());
5937 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5938 TL.setAmpLoc(ReadSourceLocation());
5941 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5942 TL.setAmpAmpLoc(ReadSourceLocation());
5945 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5946 TL.setStarLoc(ReadSourceLocation());
5947 TL.setClassTInfo(GetTypeSourceInfo());
5950 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5951 TL.setLBracketLoc(ReadSourceLocation());
5952 TL.setRBracketLoc(ReadSourceLocation());
5954 TL.setSizeExpr(Reader->ReadExpr(*F));
5956 TL.setSizeExpr(nullptr);
5959 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5960 VisitArrayTypeLoc(TL);
5963 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5964 VisitArrayTypeLoc(TL);
5967 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5968 VisitArrayTypeLoc(TL);
5971 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5972 DependentSizedArrayTypeLoc TL) {
5973 VisitArrayTypeLoc(TL);
5976 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5977 DependentSizedExtVectorTypeLoc TL) {
5978 TL.setNameLoc(ReadSourceLocation());
5981 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5982 TL.setNameLoc(ReadSourceLocation());
5985 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5986 TL.setNameLoc(ReadSourceLocation());
5989 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5990 TL.setLocalRangeBegin(ReadSourceLocation());
5991 TL.setLParenLoc(ReadSourceLocation());
5992 TL.setRParenLoc(ReadSourceLocation());
5993 TL.setLocalRangeEnd(ReadSourceLocation());
5994 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5995 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
5999 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6000 VisitFunctionTypeLoc(TL);
6003 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6004 VisitFunctionTypeLoc(TL);
6006 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6007 TL.setNameLoc(ReadSourceLocation());
6009 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6010 TL.setNameLoc(ReadSourceLocation());
6012 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6013 TL.setTypeofLoc(ReadSourceLocation());
6014 TL.setLParenLoc(ReadSourceLocation());
6015 TL.setRParenLoc(ReadSourceLocation());
6017 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6018 TL.setTypeofLoc(ReadSourceLocation());
6019 TL.setLParenLoc(ReadSourceLocation());
6020 TL.setRParenLoc(ReadSourceLocation());
6021 TL.setUnderlyingTInfo(GetTypeSourceInfo());
6023 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6024 TL.setNameLoc(ReadSourceLocation());
6027 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6028 TL.setKWLoc(ReadSourceLocation());
6029 TL.setLParenLoc(ReadSourceLocation());
6030 TL.setRParenLoc(ReadSourceLocation());
6031 TL.setUnderlyingTInfo(GetTypeSourceInfo());
6034 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6035 TL.setNameLoc(ReadSourceLocation());
6038 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6039 TL.setNameLoc(ReadSourceLocation());
6042 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6043 TL.setNameLoc(ReadSourceLocation());
6046 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6047 TL.setAttrNameLoc(ReadSourceLocation());
6048 if (TL.hasAttrOperand()) {
6050 range.setBegin(ReadSourceLocation());
6051 range.setEnd(ReadSourceLocation());
6052 TL.setAttrOperandParensRange(range);
6054 if (TL.hasAttrExprOperand()) {
6056 TL.setAttrExprOperand(Reader->ReadExpr(*F));
6058 TL.setAttrExprOperand(nullptr);
6059 } else if (TL.hasAttrEnumOperand())
6060 TL.setAttrEnumOperandLoc(ReadSourceLocation());
6063 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6064 TL.setNameLoc(ReadSourceLocation());
6067 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6068 SubstTemplateTypeParmTypeLoc TL) {
6069 TL.setNameLoc(ReadSourceLocation());
6071 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6072 SubstTemplateTypeParmPackTypeLoc TL) {
6073 TL.setNameLoc(ReadSourceLocation());
6075 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6076 TemplateSpecializationTypeLoc TL) {
6077 TL.setTemplateKeywordLoc(ReadSourceLocation());
6078 TL.setTemplateNameLoc(ReadSourceLocation());
6079 TL.setLAngleLoc(ReadSourceLocation());
6080 TL.setRAngleLoc(ReadSourceLocation());
6081 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6084 Reader->GetTemplateArgumentLocInfo(
6085 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
6087 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
6088 TL.setLParenLoc(ReadSourceLocation());
6089 TL.setRParenLoc(ReadSourceLocation());
6092 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6093 TL.setElaboratedKeywordLoc(ReadSourceLocation());
6094 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6097 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
6098 TL.setNameLoc(ReadSourceLocation());
6101 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6102 TL.setElaboratedKeywordLoc(ReadSourceLocation());
6103 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6104 TL.setNameLoc(ReadSourceLocation());
6107 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6108 DependentTemplateSpecializationTypeLoc TL) {
6109 TL.setElaboratedKeywordLoc(ReadSourceLocation());
6110 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6111 TL.setTemplateKeywordLoc(ReadSourceLocation());
6112 TL.setTemplateNameLoc(ReadSourceLocation());
6113 TL.setLAngleLoc(ReadSourceLocation());
6114 TL.setRAngleLoc(ReadSourceLocation());
6115 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
6118 Reader->GetTemplateArgumentLocInfo(
6119 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
6122 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
6123 TL.setEllipsisLoc(ReadSourceLocation());
6126 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6127 TL.setNameLoc(ReadSourceLocation());
6130 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6131 if (TL.getNumProtocols()) {
6132 TL.setProtocolLAngleLoc(ReadSourceLocation());
6133 TL.setProtocolRAngleLoc(ReadSourceLocation());
6135 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6136 TL.setProtocolLoc(i, ReadSourceLocation());
6139 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6140 TL.setHasBaseTypeAsWritten(Record[Idx++]);
6141 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6142 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
6143 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
6144 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
6145 TL.setProtocolLAngleLoc(ReadSourceLocation());
6146 TL.setProtocolRAngleLoc(ReadSourceLocation());
6147 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6148 TL.setProtocolLoc(i, ReadSourceLocation());
6151 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6152 TL.setStarLoc(ReadSourceLocation());
6155 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6156 TL.setKWLoc(ReadSourceLocation());
6157 TL.setLParenLoc(ReadSourceLocation());
6158 TL.setRParenLoc(ReadSourceLocation());
6161 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
6162 TL.setKWLoc(ReadSourceLocation());
6166 ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6168 QualType InfoTy = readType(F, Record, Idx);
6169 if (InfoTy.isNull())
6172 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
6173 TypeLocReader TLR(F, *this, Record, Idx);
6174 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6179 QualType ASTReader::GetType(TypeID ID) {
6180 unsigned FastQuals = ID & Qualifiers::FastMask;
6181 unsigned Index = ID >> Qualifiers::FastWidth;
6183 if (Index < NUM_PREDEF_TYPE_IDS) {
6185 switch ((PredefinedTypeIDs)Index) {
6186 case PREDEF_TYPE_NULL_ID:
6188 case PREDEF_TYPE_VOID_ID:
6191 case PREDEF_TYPE_BOOL_ID:
6195 case PREDEF_TYPE_CHAR_U_ID:
6196 case PREDEF_TYPE_CHAR_S_ID:
6197 // FIXME: Check that the signedness of CharTy is correct!
6201 case PREDEF_TYPE_UCHAR_ID:
6202 T = Context.UnsignedCharTy;
6204 case PREDEF_TYPE_USHORT_ID:
6205 T = Context.UnsignedShortTy;
6207 case PREDEF_TYPE_UINT_ID:
6208 T = Context.UnsignedIntTy;
6210 case PREDEF_TYPE_ULONG_ID:
6211 T = Context.UnsignedLongTy;
6213 case PREDEF_TYPE_ULONGLONG_ID:
6214 T = Context.UnsignedLongLongTy;
6216 case PREDEF_TYPE_UINT128_ID:
6217 T = Context.UnsignedInt128Ty;
6219 case PREDEF_TYPE_SCHAR_ID:
6220 T = Context.SignedCharTy;
6222 case PREDEF_TYPE_WCHAR_ID:
6223 T = Context.WCharTy;
6225 case PREDEF_TYPE_SHORT_ID:
6226 T = Context.ShortTy;
6228 case PREDEF_TYPE_INT_ID:
6231 case PREDEF_TYPE_LONG_ID:
6234 case PREDEF_TYPE_LONGLONG_ID:
6235 T = Context.LongLongTy;
6237 case PREDEF_TYPE_INT128_ID:
6238 T = Context.Int128Ty;
6240 case PREDEF_TYPE_HALF_ID:
6243 case PREDEF_TYPE_FLOAT_ID:
6244 T = Context.FloatTy;
6246 case PREDEF_TYPE_DOUBLE_ID:
6247 T = Context.DoubleTy;
6249 case PREDEF_TYPE_LONGDOUBLE_ID:
6250 T = Context.LongDoubleTy;
6252 case PREDEF_TYPE_FLOAT128_ID:
6253 T = Context.Float128Ty;
6255 case PREDEF_TYPE_OVERLOAD_ID:
6256 T = Context.OverloadTy;
6258 case PREDEF_TYPE_BOUND_MEMBER:
6259 T = Context.BoundMemberTy;
6261 case PREDEF_TYPE_PSEUDO_OBJECT:
6262 T = Context.PseudoObjectTy;
6264 case PREDEF_TYPE_DEPENDENT_ID:
6265 T = Context.DependentTy;
6267 case PREDEF_TYPE_UNKNOWN_ANY:
6268 T = Context.UnknownAnyTy;
6270 case PREDEF_TYPE_NULLPTR_ID:
6271 T = Context.NullPtrTy;
6273 case PREDEF_TYPE_CHAR16_ID:
6274 T = Context.Char16Ty;
6276 case PREDEF_TYPE_CHAR32_ID:
6277 T = Context.Char32Ty;
6279 case PREDEF_TYPE_OBJC_ID:
6280 T = Context.ObjCBuiltinIdTy;
6282 case PREDEF_TYPE_OBJC_CLASS:
6283 T = Context.ObjCBuiltinClassTy;
6285 case PREDEF_TYPE_OBJC_SEL:
6286 T = Context.ObjCBuiltinSelTy;
6288 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6289 case PREDEF_TYPE_##Id##_ID: \
6290 T = Context.SingletonId; \
6292 #include "clang/Basic/OpenCLImageTypes.def"
6293 case PREDEF_TYPE_SAMPLER_ID:
6294 T = Context.OCLSamplerTy;
6296 case PREDEF_TYPE_EVENT_ID:
6297 T = Context.OCLEventTy;
6299 case PREDEF_TYPE_CLK_EVENT_ID:
6300 T = Context.OCLClkEventTy;
6302 case PREDEF_TYPE_QUEUE_ID:
6303 T = Context.OCLQueueTy;
6305 case PREDEF_TYPE_NDRANGE_ID:
6306 T = Context.OCLNDRangeTy;
6308 case PREDEF_TYPE_RESERVE_ID_ID:
6309 T = Context.OCLReserveIDTy;
6311 case PREDEF_TYPE_AUTO_DEDUCT:
6312 T = Context.getAutoDeductType();
6315 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6316 T = Context.getAutoRRefDeductType();
6319 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6320 T = Context.ARCUnbridgedCastTy;
6323 case PREDEF_TYPE_BUILTIN_FN:
6324 T = Context.BuiltinFnTy;
6327 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6328 T = Context.OMPArraySectionTy;
6332 assert(!T.isNull() && "Unknown predefined type");
6333 return T.withFastQualifiers(FastQuals);
6336 Index -= NUM_PREDEF_TYPE_IDS;
6337 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6338 if (TypesLoaded[Index].isNull()) {
6339 TypesLoaded[Index] = readTypeRecord(Index);
6340 if (TypesLoaded[Index].isNull())
6343 TypesLoaded[Index]->setFromAST();
6344 if (DeserializationListener)
6345 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6346 TypesLoaded[Index]);
6349 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6352 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6353 return GetType(getGlobalTypeID(F, LocalID));
6356 serialization::TypeID
6357 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6358 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6359 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6361 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6364 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6365 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6366 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6368 unsigned GlobalIndex = LocalIndex + I->second;
6369 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6372 TemplateArgumentLocInfo
6373 ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6374 TemplateArgument::ArgKind Kind,
6375 const RecordData &Record,
6378 case TemplateArgument::Expression:
6380 case TemplateArgument::Type:
6381 return GetTypeSourceInfo(F, Record, Index);
6382 case TemplateArgument::Template: {
6383 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6385 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6386 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6389 case TemplateArgument::TemplateExpansion: {
6390 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6392 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6393 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6394 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6397 case TemplateArgument::Null:
6398 case TemplateArgument::Integral:
6399 case TemplateArgument::Declaration:
6400 case TemplateArgument::NullPtr:
6401 case TemplateArgument::Pack:
6402 // FIXME: Is this right?
6403 return TemplateArgumentLocInfo();
6405 llvm_unreachable("unexpected template argument loc");
6409 ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6410 const RecordData &Record, unsigned &Index) {
6411 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6413 if (Arg.getKind() == TemplateArgument::Expression) {
6414 if (Record[Index++]) // bool InfoHasSameExpr.
6415 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6417 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6421 const ASTTemplateArgumentListInfo*
6422 ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6423 const RecordData &Record,
6425 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6426 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6427 unsigned NumArgsAsWritten = Record[Index++];
6428 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6429 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6430 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6431 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6434 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6438 template<typename TemplateSpecializationDecl>
6439 static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6440 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6441 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6444 void ASTReader::CompleteRedeclChain(const Decl *D) {
6445 if (NumCurrentElementsDeserializing) {
6446 // We arrange to not care about the complete redeclaration chain while we're
6447 // deserializing. Just remember that the AST has marked this one as complete
6448 // but that it's not actually complete yet, so we know we still need to
6449 // complete it later.
6450 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6454 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6456 // If this is a named declaration, complete it by looking it up
6457 // within its context.
6459 // FIXME: Merging a function definition should merge
6460 // all mergeable entities within it.
6461 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6462 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6463 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6464 if (!getContext().getLangOpts().CPlusPlus &&
6465 isa<TranslationUnitDecl>(DC)) {
6466 // Outside of C++, we don't have a lookup table for the TU, so update
6467 // the identifier instead. (For C++ modules, we don't store decls
6468 // in the serialized identifier table, so we do the lookup in the TU.)
6469 auto *II = Name.getAsIdentifierInfo();
6470 assert(II && "non-identifier name in C?");
6471 if (II->isOutOfDate())
6472 updateOutOfDateIdentifier(*II);
6475 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6476 // Find all declarations of this kind from the relevant context.
6477 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6478 auto *DC = cast<DeclContext>(DCDecl);
6479 SmallVector<Decl*, 8> Decls;
6480 FindExternalLexicalDecls(
6481 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6486 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6487 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6488 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6489 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6490 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6491 if (auto *Template = FD->getPrimaryTemplate())
6492 Template->LoadLazySpecializations();
6496 CXXCtorInitializer **
6497 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6498 RecordLocation Loc = getLocalBitOffset(Offset);
6499 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6500 SavedStreamPosition SavedPosition(Cursor);
6501 Cursor.JumpToBit(Loc.Offset);
6502 ReadingKindTracker ReadingKind(Read_Decl, *this);
6505 unsigned Code = Cursor.ReadCode();
6506 unsigned RecCode = Cursor.readRecord(Code, Record);
6507 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6508 Error("malformed AST file: missing C++ ctor initializers");
6513 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6516 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6517 RecordLocation Loc = getLocalBitOffset(Offset);
6518 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6519 SavedStreamPosition SavedPosition(Cursor);
6520 Cursor.JumpToBit(Loc.Offset);
6521 ReadingKindTracker ReadingKind(Read_Decl, *this);
6523 unsigned Code = Cursor.ReadCode();
6524 unsigned RecCode = Cursor.readRecord(Code, Record);
6525 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
6526 Error("malformed AST file: missing C++ base specifiers");
6531 unsigned NumBases = Record[Idx++];
6532 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6533 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6534 for (unsigned I = 0; I != NumBases; ++I)
6535 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6539 serialization::DeclID
6540 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6541 if (LocalID < NUM_PREDEF_DECL_IDS)
6544 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6545 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6546 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6548 return LocalID + I->second;
6551 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6552 ModuleFile &M) const {
6553 // Predefined decls aren't from any module.
6554 if (ID < NUM_PREDEF_DECL_IDS)
6557 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6558 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
6561 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
6562 if (!D->isFromASTFile())
6564 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6565 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6569 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6570 if (ID < NUM_PREDEF_DECL_IDS)
6571 return SourceLocation();
6573 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6575 if (Index > DeclsLoaded.size()) {
6576 Error("declaration ID out-of-range for AST file");
6577 return SourceLocation();
6580 if (Decl *D = DeclsLoaded[Index])
6581 return D->getLocation();
6584 DeclCursorForID(ID, Loc);
6588 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6590 case PREDEF_DECL_NULL_ID:
6593 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6594 return Context.getTranslationUnitDecl();
6596 case PREDEF_DECL_OBJC_ID_ID:
6597 return Context.getObjCIdDecl();
6599 case PREDEF_DECL_OBJC_SEL_ID:
6600 return Context.getObjCSelDecl();
6602 case PREDEF_DECL_OBJC_CLASS_ID:
6603 return Context.getObjCClassDecl();
6605 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6606 return Context.getObjCProtocolDecl();
6608 case PREDEF_DECL_INT_128_ID:
6609 return Context.getInt128Decl();
6611 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6612 return Context.getUInt128Decl();
6614 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6615 return Context.getObjCInstanceTypeDecl();
6617 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6618 return Context.getBuiltinVaListDecl();
6620 case PREDEF_DECL_VA_LIST_TAG:
6621 return Context.getVaListTagDecl();
6623 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6624 return Context.getBuiltinMSVaListDecl();
6626 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6627 return Context.getExternCContextDecl();
6629 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6630 return Context.getMakeIntegerSeqDecl();
6632 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6633 return Context.getCFConstantStringDecl();
6635 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6636 return Context.getCFConstantStringTagDecl();
6638 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6639 return Context.getTypePackElementDecl();
6641 llvm_unreachable("PredefinedDeclIDs unknown enum value");
6644 Decl *ASTReader::GetExistingDecl(DeclID ID) {
6645 if (ID < NUM_PREDEF_DECL_IDS) {
6646 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6648 // Track that we have merged the declaration with ID \p ID into the
6649 // pre-existing predefined declaration \p D.
6650 auto &Merged = KeyDecls[D->getCanonicalDecl()];
6652 Merged.push_back(ID);
6657 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6659 if (Index >= DeclsLoaded.size()) {
6660 assert(0 && "declaration ID out-of-range for AST file");
6661 Error("declaration ID out-of-range for AST file");
6665 return DeclsLoaded[Index];
6668 Decl *ASTReader::GetDecl(DeclID ID) {
6669 if (ID < NUM_PREDEF_DECL_IDS)
6670 return GetExistingDecl(ID);
6672 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6674 if (Index >= DeclsLoaded.size()) {
6675 assert(0 && "declaration ID out-of-range for AST file");
6676 Error("declaration ID out-of-range for AST file");
6680 if (!DeclsLoaded[Index]) {
6682 if (DeserializationListener)
6683 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6686 return DeclsLoaded[Index];
6689 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6691 if (GlobalID < NUM_PREDEF_DECL_IDS)
6694 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6695 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6696 ModuleFile *Owner = I->second;
6698 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6699 = M.GlobalToLocalDeclIDs.find(Owner);
6700 if (Pos == M.GlobalToLocalDeclIDs.end())
6703 return GlobalID - Owner->BaseDeclID + Pos->second;
6706 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6707 const RecordData &Record,
6709 if (Idx >= Record.size()) {
6710 Error("Corrupted AST file");
6714 return getGlobalDeclID(F, Record[Idx++]);
6717 /// \brief Resolve the offset of a statement into a statement.
6719 /// This operation will read a new statement from the external
6720 /// source each time it is called, and is meant to be used via a
6721 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6722 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6723 // Switch case IDs are per Decl.
6724 ClearSwitchCaseIDs();
6726 // Offset here is a global offset across the entire chain.
6727 RecordLocation Loc = getLocalBitOffset(Offset);
6728 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6729 return ReadStmtFromStream(*Loc.F);
6732 void ASTReader::FindExternalLexicalDecls(
6733 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6734 SmallVectorImpl<Decl *> &Decls) {
6735 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6737 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
6738 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6739 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6740 auto K = (Decl::Kind)+LexicalDecls[I];
6741 if (!IsKindWeWant(K))
6744 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6746 // Don't add predefined declarations to the lexical context more
6748 if (ID < NUM_PREDEF_DECL_IDS) {
6749 if (PredefsVisited[ID])
6752 PredefsVisited[ID] = true;
6755 if (Decl *D = GetLocalDecl(*M, ID)) {
6756 assert(D->getKind() == K && "wrong kind for lexical decl");
6757 if (!DC->isDeclInLexicalTraversal(D))
6763 if (isa<TranslationUnitDecl>(DC)) {
6764 for (auto Lexical : TULexicalDecls)
6765 Visit(Lexical.first, Lexical.second);
6767 auto I = LexicalDecls.find(DC);
6768 if (I != LexicalDecls.end())
6769 Visit(I->second.first, I->second.second);
6772 ++NumLexicalDeclContextsRead;
6782 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6784 bool operator()(LocalDeclID L, LocalDeclID R) const {
6785 SourceLocation LHS = getLocation(L);
6786 SourceLocation RHS = getLocation(R);
6787 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6790 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6791 SourceLocation RHS = getLocation(R);
6792 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6795 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6796 SourceLocation LHS = getLocation(L);
6797 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6800 SourceLocation getLocation(LocalDeclID ID) const {
6801 return Reader.getSourceManager().getFileLoc(
6802 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6806 } // end anonymous namespace
6808 void ASTReader::FindFileRegionDecls(FileID File,
6809 unsigned Offset, unsigned Length,
6810 SmallVectorImpl<Decl *> &Decls) {
6811 SourceManager &SM = getSourceManager();
6813 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6814 if (I == FileDeclIDs.end())
6817 FileDeclsInfo &DInfo = I->second;
6818 if (DInfo.Decls.empty())
6822 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6823 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6825 DeclIDComp DIDComp(*this, *DInfo.Mod);
6826 ArrayRef<serialization::LocalDeclID>::iterator
6827 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6829 if (BeginIt != DInfo.Decls.begin())
6832 // If we are pointing at a top-level decl inside an objc container, we need
6833 // to backtrack until we find it otherwise we will fail to report that the
6834 // region overlaps with an objc container.
6835 while (BeginIt != DInfo.Decls.begin() &&
6836 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6837 ->isTopLevelDeclInObjCContainer())
6840 ArrayRef<serialization::LocalDeclID>::iterator
6841 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6843 if (EndIt != DInfo.Decls.end())
6846 for (ArrayRef<serialization::LocalDeclID>::iterator
6847 DIt = BeginIt; DIt != EndIt; ++DIt)
6848 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6852 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6853 DeclarationName Name) {
6854 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
6855 "DeclContext has no visible decls in storage");
6859 auto It = Lookups.find(DC);
6860 if (It == Lookups.end())
6863 Deserializing LookupResults(this);
6865 // Load the list of declarations.
6866 SmallVector<NamedDecl *, 64> Decls;
6867 for (DeclID ID : It->second.Table.find(Name)) {
6868 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6869 if (ND->getDeclName() == Name)
6870 Decls.push_back(ND);
6873 ++NumVisibleDeclContextsRead;
6874 SetExternalVisibleDeclsForName(DC, Name, Decls);
6875 return !Decls.empty();
6878 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6879 if (!DC->hasExternalVisibleStorage())
6882 auto It = Lookups.find(DC);
6883 assert(It != Lookups.end() &&
6884 "have external visible storage but no lookup tables");
6888 for (DeclID ID : It->second.Table.findAll()) {
6889 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6890 Decls[ND->getDeclName()].push_back(ND);
6893 ++NumVisibleDeclContextsRead;
6895 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
6896 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6898 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6901 const serialization::reader::DeclContextLookupTable *
6902 ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6903 auto I = Lookups.find(Primary);
6904 return I == Lookups.end() ? nullptr : &I->second;
6907 /// \brief Under non-PCH compilation the consumer receives the objc methods
6908 /// before receiving the implementation, and codegen depends on this.
6909 /// We simulate this by deserializing and passing to consumer the methods of the
6910 /// implementation before passing the deserialized implementation decl.
6911 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6912 ASTConsumer *Consumer) {
6913 assert(ImplD && Consumer);
6915 for (auto *I : ImplD->methods())
6916 Consumer->HandleInterestingDecl(DeclGroupRef(I));
6918 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6921 void ASTReader::PassInterestingDeclsToConsumer() {
6924 if (PassingDeclsToConsumer)
6927 // Guard variable to avoid recursively redoing the process of passing
6928 // decls to consumer.
6929 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6932 // Ensure that we've loaded all potentially-interesting declarations
6933 // that need to be eagerly loaded.
6934 for (auto ID : EagerlyDeserializedDecls)
6936 EagerlyDeserializedDecls.clear();
6938 while (!InterestingDecls.empty()) {
6939 Decl *D = InterestingDecls.front();
6940 InterestingDecls.pop_front();
6942 PassInterestingDeclToConsumer(D);
6946 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6947 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6948 PassObjCImplDeclToConsumer(ImplD, Consumer);
6950 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6953 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6954 this->Consumer = Consumer;
6957 PassInterestingDeclsToConsumer();
6959 if (DeserializationListener)
6960 DeserializationListener->ReaderInitialized(this);
6963 void ASTReader::PrintStats() {
6964 std::fprintf(stderr, "*** AST File Statistics:\n");
6966 unsigned NumTypesLoaded
6967 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6969 unsigned NumDeclsLoaded
6970 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6972 unsigned NumIdentifiersLoaded
6973 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6974 IdentifiersLoaded.end(),
6975 (IdentifierInfo *)nullptr);
6976 unsigned NumMacrosLoaded
6977 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6979 (MacroInfo *)nullptr);
6980 unsigned NumSelectorsLoaded
6981 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6982 SelectorsLoaded.end(),
6985 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6986 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6987 NumSLocEntriesRead, TotalNumSLocEntries,
6988 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6989 if (!TypesLoaded.empty())
6990 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6991 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6992 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6993 if (!DeclsLoaded.empty())
6994 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6995 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6996 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6997 if (!IdentifiersLoaded.empty())
6998 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6999 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7000 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7001 if (!MacrosLoaded.empty())
7002 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7003 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7004 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7005 if (!SelectorsLoaded.empty())
7006 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7007 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7008 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7009 if (TotalNumStatements)
7010 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7011 NumStatementsRead, TotalNumStatements,
7012 ((float)NumStatementsRead/TotalNumStatements * 100));
7014 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7015 NumMacrosRead, TotalNumMacros,
7016 ((float)NumMacrosRead/TotalNumMacros * 100));
7017 if (TotalLexicalDeclContexts)
7018 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7019 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7020 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7022 if (TotalVisibleDeclContexts)
7023 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7024 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7025 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7027 if (TotalNumMethodPoolEntries) {
7028 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7029 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7030 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7033 if (NumMethodPoolLookups) {
7034 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7035 NumMethodPoolHits, NumMethodPoolLookups,
7036 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7038 if (NumMethodPoolTableLookups) {
7039 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7040 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7041 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7045 if (NumIdentifierLookupHits) {
7046 std::fprintf(stderr,
7047 " %u / %u identifier table lookups succeeded (%f%%)\n",
7048 NumIdentifierLookupHits, NumIdentifierLookups,
7049 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7053 std::fprintf(stderr, "\n");
7054 GlobalIndex->printStats();
7057 std::fprintf(stderr, "\n");
7059 std::fprintf(stderr, "\n");
7062 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
7064 dumpModuleIDMap(StringRef Name,
7065 const ContinuousRangeMap<Key, ModuleFile *,
7066 InitialCapacity> &Map) {
7067 if (Map.begin() == Map.end())
7070 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7071 llvm::errs() << Name << ":\n";
7072 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7074 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7079 LLVM_DUMP_METHOD void ASTReader::dump() {
7080 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7081 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7082 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7083 dumpModuleIDMap("Global type map", GlobalTypeMap);
7084 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7085 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7086 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7087 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7088 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
7089 dumpModuleIDMap("Global preprocessed entity map",
7090 GlobalPreprocessedEntityMap);
7092 llvm::errs() << "\n*** PCH/Modules Loaded:";
7093 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
7094 MEnd = ModuleMgr.end();
7099 /// Return the amount of memory used by memory buffers, breaking down
7100 /// by heap-backed versus mmap'ed memory.
7101 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7102 for (ModuleConstIterator I = ModuleMgr.begin(),
7103 E = ModuleMgr.end(); I != E; ++I) {
7104 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
7105 size_t bytes = buf->getBufferSize();
7106 switch (buf->getBufferKind()) {
7107 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7108 sizes.malloc_bytes += bytes;
7110 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7111 sizes.mmap_bytes += bytes;
7118 void ASTReader::InitializeSema(Sema &S) {
7120 S.addExternalSource(this);
7122 // Makes sure any declarations that were deserialized "too early"
7123 // still get added to the identifier's declaration chains.
7124 for (uint64_t ID : PreloadedDeclIDs) {
7125 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7126 pushExternalDeclIntoScope(D, D->getDeclName());
7128 PreloadedDeclIDs.clear();
7130 // FIXME: What happens if these are changed by a module import?
7131 if (!FPPragmaOptions.empty()) {
7132 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7133 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7136 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7137 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7138 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
7143 void ASTReader::UpdateSema() {
7144 assert(SemaObj && "no Sema to update");
7146 // Load the offsets of the declarations that Sema references.
7147 // They will be lazily deserialized when needed.
7148 if (!SemaDeclRefs.empty()) {
7149 assert(SemaDeclRefs.size() % 3 == 0);
7150 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
7151 if (!SemaObj->StdNamespace)
7152 SemaObj->StdNamespace = SemaDeclRefs[I];
7153 if (!SemaObj->StdBadAlloc)
7154 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7155 if (!SemaObj->StdAlignValT)
7156 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
7158 SemaDeclRefs.clear();
7161 // Update the state of pragmas. Use the same API as if we had encountered the
7162 // pragma in the source.
7163 if(OptimizeOffPragmaLocation.isValid())
7164 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
7165 if (PragmaMSStructState != -1)
7166 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
7167 if (PointersToMembersPragmaLocation.isValid()) {
7168 SemaObj->ActOnPragmaMSPointersToMembers(
7169 (LangOptions::PragmaMSPointersToMembersKind)
7170 PragmaMSPointersToMembersState,
7171 PointersToMembersPragmaLocation);
7173 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
7176 IdentifierInfo *ASTReader::get(StringRef Name) {
7177 // Note that we are loading an identifier.
7178 Deserializing AnIdentifier(this);
7180 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
7181 NumIdentifierLookups,
7182 NumIdentifierLookupHits);
7184 // We don't need to do identifier table lookups in C++ modules (we preload
7185 // all interesting declarations, and don't need to use the scope for name
7186 // lookups). Perform the lookup in PCH files, though, since we don't build
7187 // a complete initial identifier table if we're carrying on from a PCH.
7188 if (Context.getLangOpts().CPlusPlus) {
7189 for (auto F : ModuleMgr.pch_modules())
7193 // If there is a global index, look there first to determine which modules
7194 // provably do not have any results for this identifier.
7195 GlobalModuleIndex::HitSet Hits;
7196 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7197 if (!loadGlobalIndex()) {
7198 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7203 ModuleMgr.visit(Visitor, HitsPtr);
7206 IdentifierInfo *II = Visitor.getIdentifierInfo();
7207 markIdentifierUpToDate(II);
7213 /// \brief An identifier-lookup iterator that enumerates all of the
7214 /// identifiers stored within a set of AST files.
7215 class ASTIdentifierIterator : public IdentifierIterator {
7216 /// \brief The AST reader whose identifiers are being enumerated.
7217 const ASTReader &Reader;
7219 /// \brief The current index into the chain of AST files stored in
7223 /// \brief The current position within the identifier lookup table
7224 /// of the current AST file.
7225 ASTIdentifierLookupTable::key_iterator Current;
7227 /// \brief The end position within the identifier lookup table of
7228 /// the current AST file.
7229 ASTIdentifierLookupTable::key_iterator End;
7231 /// \brief Whether to skip any modules in the ASTReader.
7235 explicit ASTIdentifierIterator(const ASTReader &Reader,
7236 bool SkipModules = false);
7238 StringRef Next() override;
7241 } // end namespace clang
7243 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7245 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
7248 StringRef ASTIdentifierIterator::Next() {
7249 while (Current == End) {
7250 // If we have exhausted all of our AST files, we're done.
7255 ModuleFile &F = Reader.ModuleMgr[Index];
7256 if (SkipModules && F.isModule())
7259 ASTIdentifierLookupTable *IdTable =
7260 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
7261 Current = IdTable->key_begin();
7262 End = IdTable->key_end();
7265 // We have any identifiers remaining in the current AST file; return
7267 StringRef Result = *Current;
7274 /// A utility for appending two IdentifierIterators.
7275 class ChainedIdentifierIterator : public IdentifierIterator {
7276 std::unique_ptr<IdentifierIterator> Current;
7277 std::unique_ptr<IdentifierIterator> Queued;
7280 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7281 std::unique_ptr<IdentifierIterator> Second)
7282 : Current(std::move(First)), Queued(std::move(Second)) {}
7284 StringRef Next() override {
7288 StringRef result = Current->Next();
7289 if (!result.empty())
7292 // Try the queued iterator, which may itself be empty.
7294 std::swap(Current, Queued);
7299 } // end anonymous namespace.
7301 IdentifierIterator *ASTReader::getIdentifiers() {
7302 if (!loadGlobalIndex()) {
7303 std::unique_ptr<IdentifierIterator> ReaderIter(
7304 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7305 std::unique_ptr<IdentifierIterator> ModulesIter(
7306 GlobalIndex->createIdentifierIterator());
7307 return new ChainedIdentifierIterator(std::move(ReaderIter),
7308 std::move(ModulesIter));
7311 return new ASTIdentifierIterator(*this);
7315 namespace serialization {
7317 class ReadMethodPoolVisitor {
7320 unsigned PriorGeneration;
7321 unsigned InstanceBits;
7322 unsigned FactoryBits;
7323 bool InstanceHasMoreThanOneDecl;
7324 bool FactoryHasMoreThanOneDecl;
7325 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7326 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
7329 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
7330 unsigned PriorGeneration)
7331 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
7332 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7333 FactoryHasMoreThanOneDecl(false) {}
7335 bool operator()(ModuleFile &M) {
7336 if (!M.SelectorLookupTable)
7339 // If we've already searched this module file, skip it now.
7340 if (M.Generation <= PriorGeneration)
7343 ++Reader.NumMethodPoolTableLookups;
7344 ASTSelectorLookupTable *PoolTable
7345 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7346 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
7347 if (Pos == PoolTable->end())
7350 ++Reader.NumMethodPoolTableHits;
7351 ++Reader.NumSelectorsRead;
7352 // FIXME: Not quite happy with the statistics here. We probably should
7353 // disable this tracking when called via LoadSelector.
7354 // Also, should entries without methods count as misses?
7355 ++Reader.NumMethodPoolEntriesRead;
7356 ASTSelectorLookupTrait::data_type Data = *Pos;
7357 if (Reader.DeserializationListener)
7358 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
7360 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7361 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7362 InstanceBits = Data.InstanceBits;
7363 FactoryBits = Data.FactoryBits;
7364 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7365 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
7369 /// \brief Retrieve the instance methods found by this visitor.
7370 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7371 return InstanceMethods;
7374 /// \brief Retrieve the instance methods found by this visitor.
7375 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7376 return FactoryMethods;
7379 unsigned getInstanceBits() const { return InstanceBits; }
7380 unsigned getFactoryBits() const { return FactoryBits; }
7381 bool instanceHasMoreThanOneDecl() const {
7382 return InstanceHasMoreThanOneDecl;
7384 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
7387 } // end namespace serialization
7388 } // end namespace clang
7390 /// \brief Add the given set of methods to the method list.
7391 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7392 ObjCMethodList &List) {
7393 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7394 S.addMethodToGlobalList(&List, Methods[I]);
7398 void ASTReader::ReadMethodPool(Selector Sel) {
7399 // Get the selector generation and update it to the current generation.
7400 unsigned &Generation = SelectorGeneration[Sel];
7401 unsigned PriorGeneration = Generation;
7402 Generation = getGeneration();
7403 SelectorOutOfDate[Sel] = false;
7405 // Search for methods defined with this selector.
7406 ++NumMethodPoolLookups;
7407 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7408 ModuleMgr.visit(Visitor);
7410 if (Visitor.getInstanceMethods().empty() &&
7411 Visitor.getFactoryMethods().empty())
7414 ++NumMethodPoolHits;
7419 Sema &S = *getSema();
7420 Sema::GlobalMethodPool::iterator Pos
7421 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7423 Pos->second.first.setBits(Visitor.getInstanceBits());
7424 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
7425 Pos->second.second.setBits(Visitor.getFactoryBits());
7426 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
7428 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7429 // when building a module we keep every method individually and may need to
7430 // update hasMoreThanOneDecl as we add the methods.
7431 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7432 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
7435 void ASTReader::updateOutOfDateSelector(Selector Sel) {
7436 if (SelectorOutOfDate[Sel])
7437 ReadMethodPool(Sel);
7440 void ASTReader::ReadKnownNamespaces(
7441 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7444 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7445 if (NamespaceDecl *Namespace
7446 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7447 Namespaces.push_back(Namespace);
7451 void ASTReader::ReadUndefinedButUsed(
7452 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
7453 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7454 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
7455 SourceLocation Loc =
7456 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
7457 Undefined.insert(std::make_pair(D, Loc));
7461 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7462 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7464 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7465 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7466 uint64_t Count = DelayedDeleteExprs[Idx++];
7467 for (uint64_t C = 0; C < Count; ++C) {
7468 SourceLocation DeleteLoc =
7469 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7470 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7471 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7476 void ASTReader::ReadTentativeDefinitions(
7477 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7478 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7479 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7481 TentativeDefs.push_back(Var);
7483 TentativeDefinitions.clear();
7486 void ASTReader::ReadUnusedFileScopedDecls(
7487 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7488 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7490 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7494 UnusedFileScopedDecls.clear();
7497 void ASTReader::ReadDelegatingConstructors(
7498 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7499 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7500 CXXConstructorDecl *D
7501 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7505 DelegatingCtorDecls.clear();
7508 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7509 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7511 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7515 ExtVectorDecls.clear();
7518 void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7519 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7520 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7522 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7523 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7527 UnusedLocalTypedefNameCandidates.clear();
7530 void ASTReader::ReadReferencedSelectors(
7531 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7532 if (ReferencedSelectorsData.empty())
7535 // If there are @selector references added them to its pool. This is for
7536 // implementation of -Wselector.
7537 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7539 while (I < DataSize) {
7540 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7541 SourceLocation SelLoc
7542 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7543 Sels.push_back(std::make_pair(Sel, SelLoc));
7545 ReferencedSelectorsData.clear();
7548 void ASTReader::ReadWeakUndeclaredIdentifiers(
7549 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7550 if (WeakUndeclaredIdentifiers.empty())
7553 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7554 IdentifierInfo *WeakId
7555 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7556 IdentifierInfo *AliasId
7557 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7559 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7560 bool Used = WeakUndeclaredIdentifiers[I++];
7561 WeakInfo WI(AliasId, Loc);
7563 WeakIDs.push_back(std::make_pair(WeakId, WI));
7565 WeakUndeclaredIdentifiers.clear();
7568 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7569 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7570 ExternalVTableUse VT;
7571 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7572 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7573 VT.DefinitionRequired = VTableUses[Idx++];
7574 VTables.push_back(VT);
7580 void ASTReader::ReadPendingInstantiations(
7581 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7582 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7583 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7585 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7587 Pending.push_back(std::make_pair(D, Loc));
7589 PendingInstantiations.clear();
7592 void ASTReader::ReadLateParsedTemplates(
7593 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7595 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7597 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7599 auto LT = llvm::make_unique<LateParsedTemplate>();
7600 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7602 ModuleFile *F = getOwningModuleFile(LT->D);
7603 assert(F && "No module");
7605 unsigned TokN = LateParsedTemplates[Idx++];
7606 LT->Toks.reserve(TokN);
7607 for (unsigned T = 0; T < TokN; ++T)
7608 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7610 LPTMap.insert(std::make_pair(FD, std::move(LT)));
7613 LateParsedTemplates.clear();
7616 void ASTReader::LoadSelector(Selector Sel) {
7617 // It would be complicated to avoid reading the methods anyway. So don't.
7618 ReadMethodPool(Sel);
7621 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7622 assert(ID && "Non-zero identifier ID required");
7623 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7624 IdentifiersLoaded[ID - 1] = II;
7625 if (DeserializationListener)
7626 DeserializationListener->IdentifierRead(ID, II);
7629 /// \brief Set the globally-visible declarations associated with the given
7632 /// If the AST reader is currently in a state where the given declaration IDs
7633 /// cannot safely be resolved, they are queued until it is safe to resolve
7636 /// \param II an IdentifierInfo that refers to one or more globally-visible
7639 /// \param DeclIDs the set of declaration IDs with the name @p II that are
7640 /// visible at global scope.
7642 /// \param Decls if non-null, this vector will be populated with the set of
7643 /// deserialized declarations. These declarations will not be pushed into
7646 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7647 const SmallVectorImpl<uint32_t> &DeclIDs,
7648 SmallVectorImpl<Decl *> *Decls) {
7649 if (NumCurrentElementsDeserializing && !Decls) {
7650 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
7654 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7656 // Queue this declaration so that it will be added to the
7657 // translation unit scope and identifier's declaration chain
7658 // once a Sema object is known.
7659 PreloadedDeclIDs.push_back(DeclIDs[I]);
7663 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7665 // If we're simply supposed to record the declarations, do so now.
7667 Decls->push_back(D);
7671 // Introduce this declaration into the translation-unit scope
7672 // and add it to the declaration chain for this identifier, so
7673 // that (unqualified) name lookup will find it.
7674 pushExternalDeclIntoScope(D, II);
7678 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
7682 if (IdentifiersLoaded.empty()) {
7683 Error("no identifier table in AST file");
7688 if (!IdentifiersLoaded[ID]) {
7689 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7690 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7691 ModuleFile *M = I->second;
7692 unsigned Index = ID - M->BaseIdentifierID;
7693 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7695 // All of the strings in the AST file are preceded by a 16-bit length.
7696 // Extract that 16-bit length to avoid having to execute strlen().
7697 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7698 // unsigned integers. This is important to avoid integer overflow when
7699 // we cast them to 'unsigned'.
7700 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7701 unsigned StrLen = (((unsigned) StrLenPtr[0])
7702 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
7703 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7704 IdentifiersLoaded[ID] = &II;
7705 markIdentifierFromAST(*this, II);
7706 if (DeserializationListener)
7707 DeserializationListener->IdentifierRead(ID + 1, &II);
7710 return IdentifiersLoaded[ID];
7713 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7714 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
7717 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7718 if (LocalID < NUM_PREDEF_IDENT_IDS)
7721 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7722 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7723 assert(I != M.IdentifierRemap.end()
7724 && "Invalid index into identifier index remap");
7726 return LocalID + I->second;
7729 MacroInfo *ASTReader::getMacro(MacroID ID) {
7733 if (MacrosLoaded.empty()) {
7734 Error("no macro table in AST file");
7738 ID -= NUM_PREDEF_MACRO_IDS;
7739 if (!MacrosLoaded[ID]) {
7740 GlobalMacroMapType::iterator I
7741 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7742 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7743 ModuleFile *M = I->second;
7744 unsigned Index = ID - M->BaseMacroID;
7745 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7747 if (DeserializationListener)
7748 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7752 return MacrosLoaded[ID];
7755 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7756 if (LocalID < NUM_PREDEF_MACRO_IDS)
7759 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7760 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7761 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7763 return LocalID + I->second;
7766 serialization::SubmoduleID
7767 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7768 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7771 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7772 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7773 assert(I != M.SubmoduleRemap.end()
7774 && "Invalid index into submodule index remap");
7776 return LocalID + I->second;
7779 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7780 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7781 assert(GlobalID == 0 && "Unhandled global submodule ID");
7785 if (GlobalID > SubmodulesLoaded.size()) {
7786 Error("submodule ID out of range in AST file");
7790 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7793 Module *ASTReader::getModule(unsigned ID) {
7794 return getSubmodule(ID);
7797 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7799 // It's a module, look it up by submodule ID.
7800 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7801 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7803 // It's a prefix (preamble, PCH, ...). Look it up by index.
7804 unsigned IndexFromEnd = ID >> 1;
7805 assert(IndexFromEnd && "got reference to unknown module file");
7806 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7810 unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7814 // For a file representing a module, use the submodule ID of the top-level
7815 // module as the file ID. For any other kind of file, the number of such
7816 // files loaded beforehand will be the same on reload.
7817 // FIXME: Is this true even if we have an explicit module file and a PCH?
7819 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7821 auto PCHModules = getModuleManager().pch_modules();
7822 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7823 assert(I != PCHModules.end() && "emitting reference to unknown file");
7824 return (I - PCHModules.end()) << 1;
7827 llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7828 ASTReader::getSourceDescriptor(unsigned ID) {
7829 if (const Module *M = getSubmodule(ID))
7830 return ExternalASTSource::ASTSourceDescriptor(*M);
7832 // If there is only a single PCH, return it instead.
7833 // Chained PCH are not suported.
7834 if (ModuleMgr.size() == 1) {
7835 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7836 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
7837 StringRef FileName = llvm::sys::path::filename(MF.FileName);
7838 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
7844 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7845 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7848 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7852 if (ID > SelectorsLoaded.size()) {
7853 Error("selector ID out of range in AST file");
7857 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
7858 // Load this selector from the selector table.
7859 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7860 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7861 ModuleFile &M = *I->second;
7862 ASTSelectorLookupTrait Trait(*this, M);
7863 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7864 SelectorsLoaded[ID - 1] =
7865 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7866 if (DeserializationListener)
7867 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7870 return SelectorsLoaded[ID - 1];
7873 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7874 return DecodeSelector(ID);
7877 uint32_t ASTReader::GetNumExternalSelectors() {
7878 // ID 0 (the null selector) is considered an external selector.
7879 return getTotalNumSelectors() + 1;
7882 serialization::SelectorID
7883 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7884 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7887 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7888 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7889 assert(I != M.SelectorRemap.end()
7890 && "Invalid index into selector index remap");
7892 return LocalID + I->second;
7896 ASTReader::ReadDeclarationName(ModuleFile &F,
7897 const RecordData &Record, unsigned &Idx) {
7898 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7900 case DeclarationName::Identifier:
7901 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
7903 case DeclarationName::ObjCZeroArgSelector:
7904 case DeclarationName::ObjCOneArgSelector:
7905 case DeclarationName::ObjCMultiArgSelector:
7906 return DeclarationName(ReadSelector(F, Record, Idx));
7908 case DeclarationName::CXXConstructorName:
7909 return Context.DeclarationNames.getCXXConstructorName(
7910 Context.getCanonicalType(readType(F, Record, Idx)));
7912 case DeclarationName::CXXDestructorName:
7913 return Context.DeclarationNames.getCXXDestructorName(
7914 Context.getCanonicalType(readType(F, Record, Idx)));
7916 case DeclarationName::CXXConversionFunctionName:
7917 return Context.DeclarationNames.getCXXConversionFunctionName(
7918 Context.getCanonicalType(readType(F, Record, Idx)));
7920 case DeclarationName::CXXOperatorName:
7921 return Context.DeclarationNames.getCXXOperatorName(
7922 (OverloadedOperatorKind)Record[Idx++]);
7924 case DeclarationName::CXXLiteralOperatorName:
7925 return Context.DeclarationNames.getCXXLiteralOperatorName(
7926 GetIdentifierInfo(F, Record, Idx));
7928 case DeclarationName::CXXUsingDirective:
7929 return DeclarationName::getUsingDirectiveName();
7932 llvm_unreachable("Invalid NameKind!");
7935 void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7936 DeclarationNameLoc &DNLoc,
7937 DeclarationName Name,
7938 const RecordData &Record, unsigned &Idx) {
7939 switch (Name.getNameKind()) {
7940 case DeclarationName::CXXConstructorName:
7941 case DeclarationName::CXXDestructorName:
7942 case DeclarationName::CXXConversionFunctionName:
7943 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7946 case DeclarationName::CXXOperatorName:
7947 DNLoc.CXXOperatorName.BeginOpNameLoc
7948 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7949 DNLoc.CXXOperatorName.EndOpNameLoc
7950 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7953 case DeclarationName::CXXLiteralOperatorName:
7954 DNLoc.CXXLiteralOperatorName.OpNameLoc
7955 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7958 case DeclarationName::Identifier:
7959 case DeclarationName::ObjCZeroArgSelector:
7960 case DeclarationName::ObjCOneArgSelector:
7961 case DeclarationName::ObjCMultiArgSelector:
7962 case DeclarationName::CXXUsingDirective:
7967 void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7968 DeclarationNameInfo &NameInfo,
7969 const RecordData &Record, unsigned &Idx) {
7970 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7971 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7972 DeclarationNameLoc DNLoc;
7973 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7974 NameInfo.setInfo(DNLoc);
7977 void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7978 const RecordData &Record, unsigned &Idx) {
7979 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7980 unsigned NumTPLists = Record[Idx++];
7981 Info.NumTemplParamLists = NumTPLists;
7983 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7984 for (unsigned i = 0; i != NumTPLists; ++i)
7985 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7990 ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7992 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7994 case TemplateName::Template:
7995 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7997 case TemplateName::OverloadedTemplate: {
7998 unsigned size = Record[Idx++];
7999 UnresolvedSet<8> Decls;
8001 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8003 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8006 case TemplateName::QualifiedTemplate: {
8007 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8008 bool hasTemplKeyword = Record[Idx++];
8009 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8010 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8013 case TemplateName::DependentTemplate: {
8014 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8015 if (Record[Idx++]) // isIdentifier
8016 return Context.getDependentTemplateName(NNS,
8017 GetIdentifierInfo(F, Record,
8019 return Context.getDependentTemplateName(NNS,
8020 (OverloadedOperatorKind)Record[Idx++]);
8023 case TemplateName::SubstTemplateTemplateParm: {
8024 TemplateTemplateParmDecl *param
8025 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8026 if (!param) return TemplateName();
8027 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8028 return Context.getSubstTemplateTemplateParm(param, replacement);
8031 case TemplateName::SubstTemplateTemplateParmPack: {
8032 TemplateTemplateParmDecl *Param
8033 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8035 return TemplateName();
8037 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8038 if (ArgPack.getKind() != TemplateArgument::Pack)
8039 return TemplateName();
8041 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8045 llvm_unreachable("Unhandled template name kind!");
8048 TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8049 const RecordData &Record,
8051 bool Canonicalize) {
8053 // The caller wants a canonical template argument. Sometimes the AST only
8054 // wants template arguments in canonical form (particularly as the template
8055 // argument lists of template specializations) so ensure we preserve that
8056 // canonical form across serialization.
8057 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8058 return Context.getCanonicalTemplateArgument(Arg);
8061 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8063 case TemplateArgument::Null:
8064 return TemplateArgument();
8065 case TemplateArgument::Type:
8066 return TemplateArgument(readType(F, Record, Idx));
8067 case TemplateArgument::Declaration: {
8068 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
8069 return TemplateArgument(D, readType(F, Record, Idx));
8071 case TemplateArgument::NullPtr:
8072 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8073 case TemplateArgument::Integral: {
8074 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8075 QualType T = readType(F, Record, Idx);
8076 return TemplateArgument(Context, Value, T);
8078 case TemplateArgument::Template:
8079 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8080 case TemplateArgument::TemplateExpansion: {
8081 TemplateName Name = ReadTemplateName(F, Record, Idx);
8082 Optional<unsigned> NumTemplateExpansions;
8083 if (unsigned NumExpansions = Record[Idx++])
8084 NumTemplateExpansions = NumExpansions - 1;
8085 return TemplateArgument(Name, NumTemplateExpansions);
8087 case TemplateArgument::Expression:
8088 return TemplateArgument(ReadExpr(F));
8089 case TemplateArgument::Pack: {
8090 unsigned NumArgs = Record[Idx++];
8091 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8092 for (unsigned I = 0; I != NumArgs; ++I)
8093 Args[I] = ReadTemplateArgument(F, Record, Idx);
8094 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
8098 llvm_unreachable("Unhandled template argument kind!");
8101 TemplateParameterList *
8102 ASTReader::ReadTemplateParameterList(ModuleFile &F,
8103 const RecordData &Record, unsigned &Idx) {
8104 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8105 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8106 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8108 unsigned NumParams = Record[Idx++];
8109 SmallVector<NamedDecl *, 16> Params;
8110 Params.reserve(NumParams);
8112 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8115 TemplateParameterList* TemplateParams =
8116 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
8117 Params, RAngleLoc, nullptr);
8118 return TemplateParams;
8123 ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
8124 ModuleFile &F, const RecordData &Record,
8125 unsigned &Idx, bool Canonicalize) {
8126 unsigned NumTemplateArgs = Record[Idx++];
8127 TemplArgs.reserve(NumTemplateArgs);
8128 while (NumTemplateArgs--)
8129 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
8132 /// \brief Read a UnresolvedSet structure.
8133 void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
8134 const RecordData &Record, unsigned &Idx) {
8135 unsigned NumDecls = Record[Idx++];
8136 Set.reserve(Context, NumDecls);
8137 while (NumDecls--) {
8138 DeclID ID = ReadDeclID(F, Record, Idx);
8139 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
8140 Set.addLazyDecl(Context, ID, AS);
8145 ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8146 const RecordData &Record, unsigned &Idx) {
8147 bool isVirtual = static_cast<bool>(Record[Idx++]);
8148 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8149 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8150 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8151 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8152 SourceRange Range = ReadSourceRange(F, Record, Idx);
8153 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
8154 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
8156 Result.setInheritConstructors(inheritConstructors);
8160 CXXCtorInitializer **
8161 ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8163 unsigned NumInitializers = Record[Idx++];
8164 assert(NumInitializers && "wrote ctor initializers but have no inits");
8165 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8166 for (unsigned i = 0; i != NumInitializers; ++i) {
8167 TypeSourceInfo *TInfo = nullptr;
8168 bool IsBaseVirtual = false;
8169 FieldDecl *Member = nullptr;
8170 IndirectFieldDecl *IndirectMember = nullptr;
8172 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8174 case CTOR_INITIALIZER_BASE:
8175 TInfo = GetTypeSourceInfo(F, Record, Idx);
8176 IsBaseVirtual = Record[Idx++];
8179 case CTOR_INITIALIZER_DELEGATING:
8180 TInfo = GetTypeSourceInfo(F, Record, Idx);
8183 case CTOR_INITIALIZER_MEMBER:
8184 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8187 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8188 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8192 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8193 Expr *Init = ReadExpr(F);
8194 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8195 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
8197 CXXCtorInitializer *BOMInit;
8198 if (Type == CTOR_INITIALIZER_BASE)
8199 BOMInit = new (Context)
8200 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8201 RParenLoc, MemberOrEllipsisLoc);
8202 else if (Type == CTOR_INITIALIZER_DELEGATING)
8203 BOMInit = new (Context)
8204 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
8206 BOMInit = new (Context)
8207 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8210 BOMInit = new (Context)
8211 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8212 LParenLoc, Init, RParenLoc);
8214 if (/*IsWritten*/Record[Idx++]) {
8215 unsigned SourceOrder = Record[Idx++];
8216 BOMInit->setSourceOrder(SourceOrder);
8219 CtorInitializers[i] = BOMInit;
8222 return CtorInitializers;
8225 NestedNameSpecifier *
8226 ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8227 const RecordData &Record, unsigned &Idx) {
8228 unsigned N = Record[Idx++];
8229 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
8230 for (unsigned I = 0; I != N; ++I) {
8231 NestedNameSpecifier::SpecifierKind Kind
8232 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8234 case NestedNameSpecifier::Identifier: {
8235 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8236 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8240 case NestedNameSpecifier::Namespace: {
8241 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8242 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8246 case NestedNameSpecifier::NamespaceAlias: {
8247 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8248 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8252 case NestedNameSpecifier::TypeSpec:
8253 case NestedNameSpecifier::TypeSpecWithTemplate: {
8254 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8258 bool Template = Record[Idx++];
8259 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8263 case NestedNameSpecifier::Global: {
8264 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8265 // No associated value, and there can't be a prefix.
8269 case NestedNameSpecifier::Super: {
8270 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8271 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8280 NestedNameSpecifierLoc
8281 ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8283 unsigned N = Record[Idx++];
8284 NestedNameSpecifierLocBuilder Builder;
8285 for (unsigned I = 0; I != N; ++I) {
8286 NestedNameSpecifier::SpecifierKind Kind
8287 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8289 case NestedNameSpecifier::Identifier: {
8290 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8291 SourceRange Range = ReadSourceRange(F, Record, Idx);
8292 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8296 case NestedNameSpecifier::Namespace: {
8297 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8298 SourceRange Range = ReadSourceRange(F, Record, Idx);
8299 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8303 case NestedNameSpecifier::NamespaceAlias: {
8304 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8305 SourceRange Range = ReadSourceRange(F, Record, Idx);
8306 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8310 case NestedNameSpecifier::TypeSpec:
8311 case NestedNameSpecifier::TypeSpecWithTemplate: {
8312 bool Template = Record[Idx++];
8313 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8315 return NestedNameSpecifierLoc();
8316 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8318 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8319 Builder.Extend(Context,
8320 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8321 T->getTypeLoc(), ColonColonLoc);
8325 case NestedNameSpecifier::Global: {
8326 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8327 Builder.MakeGlobal(Context, ColonColonLoc);
8331 case NestedNameSpecifier::Super: {
8332 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8333 SourceRange Range = ReadSourceRange(F, Record, Idx);
8334 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8340 return Builder.getWithLocInContext(Context);
8344 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8346 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8347 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8348 return SourceRange(beg, end);
8351 /// \brief Read an integral value
8352 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8353 unsigned BitWidth = Record[Idx++];
8354 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8355 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8360 /// \brief Read a signed integral value
8361 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8362 bool isUnsigned = Record[Idx++];
8363 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8366 /// \brief Read a floating-point value
8367 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8368 const llvm::fltSemantics &Sem,
8370 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
8373 // \brief Read a string
8374 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8375 unsigned Len = Record[Idx++];
8376 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8381 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8383 std::string Filename = ReadString(Record, Idx);
8384 ResolveImportedPath(F, Filename);
8388 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8390 unsigned Major = Record[Idx++];
8391 unsigned Minor = Record[Idx++];
8392 unsigned Subminor = Record[Idx++];
8394 return VersionTuple(Major);
8396 return VersionTuple(Major, Minor - 1);
8397 return VersionTuple(Major, Minor - 1, Subminor - 1);
8400 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8401 const RecordData &Record,
8403 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8404 return CXXTemporary::Create(Context, Decl);
8407 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
8408 return Diag(CurrentImportLoc, DiagID);
8411 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8412 return Diags.Report(Loc, DiagID);
8415 /// \brief Retrieve the identifier table associated with the
8417 IdentifierTable &ASTReader::getIdentifierTable() {
8418 return PP.getIdentifierTable();
8421 /// \brief Record that the given ID maps to the given switch-case
8423 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
8424 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
8425 "Already have a SwitchCase with this ID");
8426 (*CurrSwitchCaseStmts)[ID] = SC;
8429 /// \brief Retrieve the switch-case statement with the given ID.
8430 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
8431 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
8432 return (*CurrSwitchCaseStmts)[ID];
8435 void ASTReader::ClearSwitchCaseIDs() {
8436 CurrSwitchCaseStmts->clear();
8439 void ASTReader::ReadComments() {
8440 std::vector<RawComment *> Comments;
8441 for (SmallVectorImpl<std::pair<BitstreamCursor,
8442 serialization::ModuleFile *> >::iterator
8443 I = CommentsCursors.begin(),
8444 E = CommentsCursors.end();
8447 BitstreamCursor &Cursor = I->first;
8448 serialization::ModuleFile &F = *I->second;
8449 SavedStreamPosition SavedPosition(Cursor);
8453 llvm::BitstreamEntry Entry =
8454 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
8456 switch (Entry.Kind) {
8457 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8458 case llvm::BitstreamEntry::Error:
8459 Error("malformed block record in AST file");
8461 case llvm::BitstreamEntry::EndBlock:
8463 case llvm::BitstreamEntry::Record:
8464 // The interesting case.
8470 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
8471 case COMMENTS_RAW_COMMENT: {
8473 SourceRange SR = ReadSourceRange(F, Record, Idx);
8474 RawComment::CommentKind Kind =
8475 (RawComment::CommentKind) Record[Idx++];
8476 bool IsTrailingComment = Record[Idx++];
8477 bool IsAlmostTrailingComment = Record[Idx++];
8478 Comments.push_back(new (Context) RawComment(
8479 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8480 Context.getLangOpts().CommentOpts.ParseAllComments));
8486 // De-serialized SourceLocations get negative FileIDs for other modules,
8487 // potentially invalidating the original order. Sort it again.
8488 std::sort(Comments.begin(), Comments.end(),
8489 BeforeThanCompare<RawComment>(SourceMgr));
8490 Context.Comments.addDeserializedComments(Comments);
8494 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8495 // If we know the owning module, use it.
8496 if (Module *M = D->getImportedOwningModule())
8497 return M->getFullModuleName();
8499 // Otherwise, use the name of the top-level module the decl is within.
8500 if (ModuleFile *M = getOwningModuleFile(D))
8501 return M->ModuleName;
8503 // Not from a module.
8507 void ASTReader::finishPendingActions() {
8508 while (!PendingIdentifierInfos.empty() ||
8509 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
8510 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
8511 !PendingUpdateRecords.empty()) {
8512 // If any identifiers with corresponding top-level declarations have
8513 // been loaded, load those declarations now.
8514 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8516 TopLevelDeclsMap TopLevelDecls;
8518 while (!PendingIdentifierInfos.empty()) {
8519 IdentifierInfo *II = PendingIdentifierInfos.back().first;
8520 SmallVector<uint32_t, 4> DeclIDs =
8521 std::move(PendingIdentifierInfos.back().second);
8522 PendingIdentifierInfos.pop_back();
8524 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
8527 // For each decl chain that we wanted to complete while deserializing, mark
8528 // it as "still needs to be completed".
8529 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8530 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8532 PendingIncompleteDeclChains.clear();
8534 // Load pending declaration chains.
8535 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
8536 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
8537 PendingDeclChains.clear();
8539 // Make the most recent of the top-level declarations visible.
8540 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8541 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
8542 IdentifierInfo *II = TLD->first;
8543 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
8544 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
8548 // Load any pending macro definitions.
8549 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
8550 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8551 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8552 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8553 // Initialize the macro history from chained-PCHs ahead of module imports.
8554 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8556 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8557 if (!Info.M->isModule())
8558 resolvePendingMacro(II, Info);
8560 // Handle module imports.
8561 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8563 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8564 if (Info.M->isModule())
8565 resolvePendingMacro(II, Info);
8568 PendingMacroIDs.clear();
8570 // Wire up the DeclContexts for Decls that we delayed setting until
8571 // recursive loading is completed.
8572 while (!PendingDeclContextInfos.empty()) {
8573 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8574 PendingDeclContextInfos.pop_front();
8575 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8576 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8577 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8580 // Perform any pending declaration updates.
8581 while (!PendingUpdateRecords.empty()) {
8582 auto Update = PendingUpdateRecords.pop_back_val();
8583 ReadingKindTracker ReadingKind(Read_Decl, *this);
8584 loadDeclUpdateRecords(Update.first, Update.second);
8588 // At this point, all update records for loaded decls are in place, so any
8589 // fake class definitions should have become real.
8590 assert(PendingFakeDefinitionData.empty() &&
8591 "faked up a class definition but never saw the real one");
8593 // If we deserialized any C++ or Objective-C class definitions, any
8594 // Objective-C protocol definitions, or any redeclarable templates, make sure
8595 // that all redeclarations point to the definitions. Note that this can only
8596 // happen now, after the redeclaration chains have been fully wired.
8597 for (Decl *D : PendingDefinitions) {
8598 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8599 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
8600 // Make sure that the TagType points at the definition.
8601 const_cast<TagType*>(TagT)->decl = TD;
8604 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
8605 for (auto *R = getMostRecentExistingDecl(RD); R;
8606 R = R->getPreviousDecl()) {
8608 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
8609 "declaration thinks it's the definition but it isn't");
8610 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
8617 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
8618 // Make sure that the ObjCInterfaceType points at the definition.
8619 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8622 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8623 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8628 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
8629 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8630 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8635 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
8636 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8637 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
8639 PendingDefinitions.clear();
8641 // Load the bodies of any functions or methods we've encountered. We do
8642 // this now (delayed) so that we can be sure that the declaration chains
8643 // have been fully wired up (hasBody relies on this).
8644 // FIXME: We shouldn't require complete redeclaration chains here.
8645 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8646 PBEnd = PendingBodies.end();
8647 PB != PBEnd; ++PB) {
8648 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8649 // FIXME: Check for =delete/=default?
8650 // FIXME: Complain about ODR violations here?
8651 const FunctionDecl *Defn = nullptr;
8652 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn))
8653 FD->setLazyBody(PB->second);
8655 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
8659 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8660 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8661 MD->setLazyBody(PB->second);
8663 PendingBodies.clear();
8666 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8667 getContext().deduplicateMergedDefinitonsFor(ND);
8668 PendingMergedDefinitionsToDeduplicate.clear();
8671 void ASTReader::diagnoseOdrViolations() {
8672 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8675 // Trigger the import of the full definition of each class that had any
8676 // odr-merging problems, so we can produce better diagnostics for them.
8677 // These updates may in turn find and diagnose some ODR failures, so take
8678 // ownership of the set first.
8679 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8680 PendingOdrMergeFailures.clear();
8681 for (auto &Merge : OdrMergeFailures) {
8682 Merge.first->buildLookup();
8683 Merge.first->decls_begin();
8684 Merge.first->bases_begin();
8685 Merge.first->vbases_begin();
8686 for (auto *RD : Merge.second) {
8693 // For each declaration from a merged context, check that the canonical
8694 // definition of that context also contains a declaration of the same
8697 // Caution: this loop does things that might invalidate iterators into
8698 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8699 while (!PendingOdrMergeChecks.empty()) {
8700 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8702 // FIXME: Skip over implicit declarations for now. This matters for things
8703 // like implicitly-declared special member functions. This isn't entirely
8704 // correct; we can end up with multiple unmerged declarations of the same
8706 if (D->isImplicit())
8709 DeclContext *CanonDef = D->getDeclContext();
8712 const Decl *DCanon = D->getCanonicalDecl();
8714 for (auto RI : D->redecls()) {
8715 if (RI->getLexicalDeclContext() == CanonDef) {
8723 // Quick check failed, time to do the slow thing. Note, we can't just
8724 // look up the name of D in CanonDef here, because the member that is
8725 // in CanonDef might not be found by name lookup (it might have been
8726 // replaced by a more recent declaration in the lookup table), and we
8727 // can't necessarily find it in the redeclaration chain because it might
8728 // be merely mergeable, not redeclarable.
8729 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8730 for (auto *CanonMember : CanonDef->decls()) {
8731 if (CanonMember->getCanonicalDecl() == DCanon) {
8732 // This can happen if the declaration is merely mergeable and not
8733 // actually redeclarable (we looked for redeclarations earlier).
8735 // FIXME: We should be able to detect this more efficiently, without
8736 // pulling in all of the members of CanonDef.
8740 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8741 if (ND->getDeclName() == D->getDeclName())
8742 Candidates.push_back(ND);
8746 // The AST doesn't like TagDecls becoming invalid after they've been
8747 // completed. We only really need to mark FieldDecls as invalid here.
8748 if (!isa<TagDecl>(D))
8749 D->setInvalidDecl();
8751 // Ensure we don't accidentally recursively enter deserialization while
8752 // we're producing our diagnostic.
8753 Deserializing RecursionGuard(this);
8755 std::string CanonDefModule =
8756 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8757 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8758 << D << getOwningModuleNameForDiagnostic(D)
8759 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8761 if (Candidates.empty())
8762 Diag(cast<Decl>(CanonDef)->getLocation(),
8763 diag::note_module_odr_violation_no_possible_decls) << D;
8765 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8766 Diag(Candidates[I]->getLocation(),
8767 diag::note_module_odr_violation_possible_decl)
8771 DiagnosedOdrMergeFailures.insert(CanonDef);
8775 if (OdrMergeFailures.empty())
8778 // Ensure we don't accidentally recursively enter deserialization while
8779 // we're producing our diagnostics.
8780 Deserializing RecursionGuard(this);
8782 // Issue any pending ODR-failure diagnostics.
8783 for (auto &Merge : OdrMergeFailures) {
8784 // If we've already pointed out a specific problem with this class, don't
8785 // bother issuing a general "something's different" diagnostic.
8786 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
8789 bool Diagnosed = false;
8790 for (auto *RD : Merge.second) {
8791 // Multiple different declarations got merged together; tell the user
8792 // where they came from.
8793 if (Merge.first != RD) {
8794 // FIXME: Walk the definition, figure out what's different,
8795 // and diagnose that.
8797 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8798 Diag(Merge.first->getLocation(),
8799 diag::err_module_odr_violation_different_definitions)
8800 << Merge.first << Module.empty() << Module;
8804 Diag(RD->getLocation(),
8805 diag::note_module_odr_violation_different_definitions)
8806 << getOwningModuleNameForDiagnostic(RD);
8811 // All definitions are updates to the same declaration. This happens if a
8812 // module instantiates the declaration of a class template specialization
8813 // and two or more other modules instantiate its definition.
8815 // FIXME: Indicate which modules had instantiations of this definition.
8816 // FIXME: How can this even happen?
8817 Diag(Merge.first->getLocation(),
8818 diag::err_module_odr_violation_different_instantiations)
8824 void ASTReader::StartedDeserializing() {
8825 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8826 ReadTimer->startTimer();
8829 void ASTReader::FinishedDeserializing() {
8830 assert(NumCurrentElementsDeserializing &&
8831 "FinishedDeserializing not paired with StartedDeserializing");
8832 if (NumCurrentElementsDeserializing == 1) {
8833 // We decrease NumCurrentElementsDeserializing only after pending actions
8834 // are finished, to avoid recursively re-calling finishPendingActions().
8835 finishPendingActions();
8837 --NumCurrentElementsDeserializing;
8839 if (NumCurrentElementsDeserializing == 0) {
8840 // Propagate exception specification updates along redeclaration chains.
8841 while (!PendingExceptionSpecUpdates.empty()) {
8842 auto Updates = std::move(PendingExceptionSpecUpdates);
8843 PendingExceptionSpecUpdates.clear();
8844 for (auto Update : Updates) {
8845 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
8846 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8847 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
8848 if (auto *Listener = Context.getASTMutationListener())
8849 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
8850 for (auto *Redecl : Update.second->redecls())
8851 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
8856 ReadTimer->stopTimer();
8858 diagnoseOdrViolations();
8860 // We are not in recursive loading, so it's safe to pass the "interesting"
8861 // decls to the consumer.
8863 PassInterestingDeclsToConsumer();
8867 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
8868 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8869 // Remove any fake results before adding any real ones.
8870 auto It = PendingFakeLookupResults.find(II);
8871 if (It != PendingFakeLookupResults.end()) {
8872 for (auto *ND : It->second)
8873 SemaObj->IdResolver.RemoveDecl(ND);
8874 // FIXME: this works around module+PCH performance issue.
8875 // Rather than erase the result from the map, which is O(n), just clear
8876 // the vector of NamedDecls.
8881 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8882 SemaObj->TUScope->AddDecl(D);
8883 } else if (SemaObj->TUScope) {
8884 // Adding the decl to IdResolver may have failed because it was already in
8885 // (even though it was not added in scope). If it is already in, make sure
8886 // it gets in the scope as well.
8887 if (std::find(SemaObj->IdResolver.begin(Name),
8888 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8889 SemaObj->TUScope->AddDecl(D);
8893 ASTReader::ASTReader(
8894 Preprocessor &PP, ASTContext &Context,
8895 const PCHContainerReader &PCHContainerRdr,
8896 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
8897 StringRef isysroot, bool DisableValidation,
8898 bool AllowASTWithCompilerErrors,
8899 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8900 bool UseGlobalIndex,
8901 std::unique_ptr<llvm::Timer> ReadTimer)
8902 : Listener(DisableValidation ?
8903 cast<ASTReaderListener>(new SimpleASTReaderListener(PP)) :
8904 cast<ASTReaderListener>(new PCHValidator(PP, *this))),
8905 DeserializationListener(nullptr),
8906 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
8907 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
8908 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
8909 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
8910 DummyIdResolver(PP),
8911 ReadTimer(std::move(ReadTimer)),
8912 PragmaMSStructState(-1),
8913 PragmaMSPointersToMembersState(-1),
8914 isysroot(isysroot), DisableValidation(DisableValidation),
8915 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8916 AllowConfigurationMismatch(AllowConfigurationMismatch),
8917 ValidateSystemInputs(ValidateSystemInputs),
8918 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
8919 ProcessingUpdateRecords(false),
8920 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8921 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8922 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8923 NumIdentifierLookupHits(0), NumSelectorsRead(0),
8924 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8925 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8926 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8927 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8928 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8929 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8930 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
8931 SourceMgr.setExternalSLocEntrySource(this);
8933 for (const auto &Ext : Extensions) {
8934 auto BlockName = Ext->getExtensionMetadata().BlockName;
8935 auto Known = ModuleFileExtensions.find(BlockName);
8936 if (Known != ModuleFileExtensions.end()) {
8937 Diags.Report(diag::warn_duplicate_module_file_extension)
8942 ModuleFileExtensions.insert({BlockName, Ext});
8946 ASTReader::~ASTReader() {
8947 if (OwnsDeserializationListener)
8948 delete DeserializationListener;
8951 IdentifierResolver &ASTReader::getIdResolver() {
8952 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
8955 unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
8956 unsigned AbbrevID) {
8959 return Cursor.readRecord(AbbrevID, Record);