1 //===--- ASTReader.cpp - AST File Reader ----------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ASTReader class, which reads AST files.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Serialization/ASTReader.h"
15 #include "ASTCommon.h"
16 #include "ASTReaderInternals.h"
17 #include "clang/AST/ASTConsumer.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/NestedNameSpecifier.h"
23 #include "clang/AST/Type.h"
24 #include "clang/AST/TypeLocVisitor.h"
25 #include "clang/Basic/DiagnosticOptions.h"
26 #include "clang/Basic/FileManager.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/SourceManagerInternals.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Basic/TargetOptions.h"
31 #include "clang/Basic/Version.h"
32 #include "clang/Basic/VersionTuple.h"
33 #include "clang/Frontend/Utils.h"
34 #include "clang/Lex/HeaderSearch.h"
35 #include "clang/Lex/HeaderSearchOptions.h"
36 #include "clang/Lex/MacroInfo.h"
37 #include "clang/Lex/PreprocessingRecord.h"
38 #include "clang/Lex/Preprocessor.h"
39 #include "clang/Lex/PreprocessorOptions.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/Sema.h"
42 #include "clang/Serialization/ASTDeserializationListener.h"
43 #include "clang/Serialization/GlobalModuleIndex.h"
44 #include "clang/Serialization/ModuleManager.h"
45 #include "clang/Serialization/SerializationDiagnostic.h"
46 #include "llvm/ADT/Hashing.h"
47 #include "llvm/ADT/StringExtras.h"
48 #include "llvm/Bitcode/BitstreamReader.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/FileSystem.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/Path.h"
53 #include "llvm/Support/SaveAndRestore.h"
54 #include "llvm/Support/raw_ostream.h"
58 #include <system_error>
60 using namespace clang;
61 using namespace clang::serialization;
62 using namespace clang::serialization::reader;
63 using llvm::BitstreamCursor;
66 //===----------------------------------------------------------------------===//
67 // ChainedASTReaderListener implementation
68 //===----------------------------------------------------------------------===//
71 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
72 return First->ReadFullVersionInformation(FullVersion) ||
73 Second->ReadFullVersionInformation(FullVersion);
75 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
76 First->ReadModuleName(ModuleName);
77 Second->ReadModuleName(ModuleName);
79 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
80 First->ReadModuleMapFile(ModuleMapPath);
81 Second->ReadModuleMapFile(ModuleMapPath);
83 bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
85 return First->ReadLanguageOptions(LangOpts, Complain) ||
86 Second->ReadLanguageOptions(LangOpts, Complain);
89 ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
91 return First->ReadTargetOptions(TargetOpts, Complain) ||
92 Second->ReadTargetOptions(TargetOpts, Complain);
94 bool ChainedASTReaderListener::ReadDiagnosticOptions(
95 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
96 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
97 Second->ReadDiagnosticOptions(DiagOpts, Complain);
100 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
102 return First->ReadFileSystemOptions(FSOpts, Complain) ||
103 Second->ReadFileSystemOptions(FSOpts, Complain);
106 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
107 const HeaderSearchOptions &HSOpts, bool Complain) {
108 return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
109 Second->ReadHeaderSearchOptions(HSOpts, Complain);
111 bool ChainedASTReaderListener::ReadPreprocessorOptions(
112 const PreprocessorOptions &PPOpts, bool Complain,
113 std::string &SuggestedPredefines) {
114 return First->ReadPreprocessorOptions(PPOpts, Complain,
115 SuggestedPredefines) ||
116 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
118 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
120 First->ReadCounter(M, Value);
121 Second->ReadCounter(M, Value);
123 bool ChainedASTReaderListener::needsInputFileVisitation() {
124 return First->needsInputFileVisitation() ||
125 Second->needsInputFileVisitation();
127 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
128 return First->needsSystemInputFileVisitation() ||
129 Second->needsSystemInputFileVisitation();
131 void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
132 First->visitModuleFile(Filename);
133 Second->visitModuleFile(Filename);
135 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
138 bool Continue = false;
139 if (First->needsInputFileVisitation() &&
140 (!isSystem || First->needsSystemInputFileVisitation()))
141 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
142 if (Second->needsInputFileVisitation() &&
143 (!isSystem || Second->needsSystemInputFileVisitation()))
144 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
148 //===----------------------------------------------------------------------===//
149 // PCH validator implementation
150 //===----------------------------------------------------------------------===//
152 ASTReaderListener::~ASTReaderListener() {}
154 /// \brief Compare the given set of language options against an existing set of
155 /// language options.
157 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
159 /// \returns true if the languagae options mis-match, false otherwise.
160 static bool checkLanguageOptions(const LangOptions &LangOpts,
161 const LangOptions &ExistingLangOpts,
162 DiagnosticsEngine *Diags) {
163 #define LANGOPT(Name, Bits, Default, Description) \
164 if (ExistingLangOpts.Name != LangOpts.Name) { \
166 Diags->Report(diag::err_pch_langopt_mismatch) \
167 << Description << LangOpts.Name << ExistingLangOpts.Name; \
171 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
172 if (ExistingLangOpts.Name != LangOpts.Name) { \
174 Diags->Report(diag::err_pch_langopt_value_mismatch) \
179 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
180 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
182 Diags->Report(diag::err_pch_langopt_value_mismatch) \
187 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
188 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
189 #include "clang/Basic/LangOptions.def"
191 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
193 Diags->Report(diag::err_pch_langopt_value_mismatch)
194 << "target Objective-C runtime";
198 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
199 LangOpts.CommentOpts.BlockCommandNames) {
201 Diags->Report(diag::err_pch_langopt_value_mismatch)
202 << "block command names";
209 /// \brief Compare the given set of target options against an existing set of
212 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
214 /// \returns true if the target options mis-match, false otherwise.
215 static bool checkTargetOptions(const TargetOptions &TargetOpts,
216 const TargetOptions &ExistingTargetOpts,
217 DiagnosticsEngine *Diags) {
218 #define CHECK_TARGET_OPT(Field, Name) \
219 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
221 Diags->Report(diag::err_pch_targetopt_mismatch) \
222 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
226 CHECK_TARGET_OPT(Triple, "target");
227 CHECK_TARGET_OPT(CPU, "target CPU");
228 CHECK_TARGET_OPT(ABI, "target ABI");
229 #undef CHECK_TARGET_OPT
231 // Compare feature sets.
232 SmallVector<StringRef, 4> ExistingFeatures(
233 ExistingTargetOpts.FeaturesAsWritten.begin(),
234 ExistingTargetOpts.FeaturesAsWritten.end());
235 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
236 TargetOpts.FeaturesAsWritten.end());
237 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
238 std::sort(ReadFeatures.begin(), ReadFeatures.end());
240 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
241 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
242 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
243 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
249 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
251 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
252 << false << ReadFeatures[ReadIdx];
257 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
258 << true << ExistingFeatures[ExistingIdx];
262 if (ExistingIdx < ExistingN) {
264 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
265 << true << ExistingFeatures[ExistingIdx];
269 if (ReadIdx < ReadN) {
271 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
272 << false << ReadFeatures[ReadIdx];
280 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
282 const LangOptions &ExistingLangOpts = PP.getLangOpts();
283 return checkLanguageOptions(LangOpts, ExistingLangOpts,
284 Complain? &Reader.Diags : nullptr);
287 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
289 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
290 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
291 Complain? &Reader.Diags : nullptr);
295 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
297 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
301 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
302 DiagnosticsEngine &Diags,
304 typedef DiagnosticsEngine::Level Level;
306 // Check current mappings for new -Werror mappings, and the stored mappings
307 // for cases that were explicitly mapped to *not* be errors that are now
308 // errors because of options like -Werror.
309 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
311 for (DiagnosticsEngine *MappingSource : MappingSources) {
312 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
313 diag::kind DiagID = DiagIDMappingPair.first;
314 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
315 if (CurLevel < DiagnosticsEngine::Error)
316 continue; // not significant
318 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
319 if (StoredLevel < DiagnosticsEngine::Error) {
321 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
322 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
331 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
332 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
333 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
335 return Ext >= diag::Severity::Error;
338 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
339 DiagnosticsEngine &Diags,
340 bool IsSystem, bool Complain) {
343 if (Diags.getSuppressSystemWarnings())
345 // If -Wsystem-headers was not enabled before, be conservative
346 if (StoredDiags.getSuppressSystemWarnings()) {
348 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
353 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
355 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
359 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
360 !StoredDiags.getEnableAllWarnings()) {
362 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
366 if (isExtHandlingFromDiagsError(Diags) &&
367 !isExtHandlingFromDiagsError(StoredDiags)) {
369 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
373 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
376 bool PCHValidator::ReadDiagnosticOptions(
377 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
378 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
379 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
380 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
381 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
382 // This should never fail, because we would have processed these options
383 // before writing them to an ASTFile.
384 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
386 ModuleManager &ModuleMgr = Reader.getModuleManager();
387 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
389 // If the original import came from a file explicitly generated by the user,
390 // don't check the diagnostic mappings.
391 // FIXME: currently this is approximated by checking whether this is not a
393 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
394 // the transitive closure of its imports, since unrelated modules cannot be
395 // imported until after this module finishes validation.
396 ModuleFile *TopImport = *ModuleMgr.rbegin();
397 while (!TopImport->ImportedBy.empty())
398 TopImport = TopImport->ImportedBy[0];
399 if (TopImport->Kind != MK_Module)
402 StringRef ModuleName = TopImport->ModuleName;
403 assert(!ModuleName.empty() && "diagnostic options read before module name");
405 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
406 assert(M && "missing module");
408 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
409 // contains the union of their flags.
410 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
413 /// \brief Collect the macro definitions provided by the given preprocessor
416 collectMacroDefinitions(const PreprocessorOptions &PPOpts,
417 MacroDefinitionsMap &Macros,
418 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
419 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
420 StringRef Macro = PPOpts.Macros[I].first;
421 bool IsUndef = PPOpts.Macros[I].second;
423 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
424 StringRef MacroName = MacroPair.first;
425 StringRef MacroBody = MacroPair.second;
427 // For an #undef'd macro, we only care about the name.
429 if (MacroNames && !Macros.count(MacroName))
430 MacroNames->push_back(MacroName);
432 Macros[MacroName] = std::make_pair("", true);
436 // For a #define'd macro, figure out the actual definition.
437 if (MacroName.size() == Macro.size())
440 // Note: GCC drops anything following an end-of-line character.
441 StringRef::size_type End = MacroBody.find_first_of("\n\r");
442 MacroBody = MacroBody.substr(0, End);
445 if (MacroNames && !Macros.count(MacroName))
446 MacroNames->push_back(MacroName);
447 Macros[MacroName] = std::make_pair(MacroBody, false);
451 /// \brief Check the preprocessor options deserialized from the control block
452 /// against the preprocessor options in an existing preprocessor.
454 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
455 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
456 const PreprocessorOptions &ExistingPPOpts,
457 DiagnosticsEngine *Diags,
458 FileManager &FileMgr,
459 std::string &SuggestedPredefines,
460 const LangOptions &LangOpts) {
461 // Check macro definitions.
462 MacroDefinitionsMap ASTFileMacros;
463 collectMacroDefinitions(PPOpts, ASTFileMacros);
464 MacroDefinitionsMap ExistingMacros;
465 SmallVector<StringRef, 4> ExistingMacroNames;
466 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
468 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
469 // Dig out the macro definition in the existing preprocessor options.
470 StringRef MacroName = ExistingMacroNames[I];
471 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
473 // Check whether we know anything about this macro name or not.
474 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
475 = ASTFileMacros.find(MacroName);
476 if (Known == ASTFileMacros.end()) {
477 // FIXME: Check whether this identifier was referenced anywhere in the
478 // AST file. If so, we should reject the AST file. Unfortunately, this
479 // information isn't in the control block. What shall we do about it?
481 if (Existing.second) {
482 SuggestedPredefines += "#undef ";
483 SuggestedPredefines += MacroName.str();
484 SuggestedPredefines += '\n';
486 SuggestedPredefines += "#define ";
487 SuggestedPredefines += MacroName.str();
488 SuggestedPredefines += ' ';
489 SuggestedPredefines += Existing.first.str();
490 SuggestedPredefines += '\n';
495 // If the macro was defined in one but undef'd in the other, we have a
497 if (Existing.second != Known->second.second) {
499 Diags->Report(diag::err_pch_macro_def_undef)
500 << MacroName << Known->second.second;
505 // If the macro was #undef'd in both, or if the macro bodies are identical,
507 if (Existing.second || Existing.first == Known->second.first)
510 // The macro bodies differ; complain.
512 Diags->Report(diag::err_pch_macro_def_conflict)
513 << MacroName << Known->second.first << Existing.first;
518 // Check whether we're using predefines.
519 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
521 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
526 // Detailed record is important since it is used for the module cache hash.
527 if (LangOpts.Modules &&
528 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
530 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
535 // Compute the #include and #include_macros lines we need.
536 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
537 StringRef File = ExistingPPOpts.Includes[I];
538 if (File == ExistingPPOpts.ImplicitPCHInclude)
541 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
542 != PPOpts.Includes.end())
545 SuggestedPredefines += "#include \"";
546 SuggestedPredefines +=
547 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
548 SuggestedPredefines += "\"\n";
551 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
552 StringRef File = ExistingPPOpts.MacroIncludes[I];
553 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
555 != PPOpts.MacroIncludes.end())
558 SuggestedPredefines += "#__include_macros \"";
559 SuggestedPredefines +=
560 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
561 SuggestedPredefines += "\"\n##\n";
567 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
569 std::string &SuggestedPredefines) {
570 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
572 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
573 Complain? &Reader.Diags : nullptr,
579 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
580 PP.setCounterValue(Value);
583 //===----------------------------------------------------------------------===//
584 // AST reader implementation
585 //===----------------------------------------------------------------------===//
587 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
588 bool TakeOwnership) {
589 DeserializationListener = Listener;
590 OwnsDeserializationListener = TakeOwnership;
595 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
596 return serialization::ComputeHash(Sel);
600 std::pair<unsigned, unsigned>
601 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
602 using namespace llvm::support;
603 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
604 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
605 return std::make_pair(KeyLen, DataLen);
608 ASTSelectorLookupTrait::internal_key_type
609 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
610 using namespace llvm::support;
611 SelectorTable &SelTable = Reader.getContext().Selectors;
612 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
613 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
614 F, endian::readNext<uint32_t, little, unaligned>(d));
616 return SelTable.getNullarySelector(FirstII);
618 return SelTable.getUnarySelector(FirstII);
620 SmallVector<IdentifierInfo *, 16> Args;
621 Args.push_back(FirstII);
622 for (unsigned I = 1; I != N; ++I)
623 Args.push_back(Reader.getLocalIdentifier(
624 F, endian::readNext<uint32_t, little, unaligned>(d)));
626 return SelTable.getSelector(N, Args.data());
629 ASTSelectorLookupTrait::data_type
630 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
632 using namespace llvm::support;
636 Result.ID = Reader.getGlobalSelectorID(
637 F, endian::readNext<uint32_t, little, unaligned>(d));
638 unsigned NumInstanceMethodsAndBits =
639 endian::readNext<uint16_t, little, unaligned>(d);
640 unsigned NumFactoryMethodsAndBits =
641 endian::readNext<uint16_t, little, unaligned>(d);
642 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
643 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
644 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
645 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
647 // Load instance methods
648 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
649 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
650 F, endian::readNext<uint32_t, little, unaligned>(d)))
651 Result.Instance.push_back(Method);
654 // Load factory methods
655 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
656 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
657 F, endian::readNext<uint32_t, little, unaligned>(d)))
658 Result.Factory.push_back(Method);
664 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
665 return llvm::HashString(a);
668 std::pair<unsigned, unsigned>
669 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
670 using namespace llvm::support;
671 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
672 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
673 return std::make_pair(KeyLen, DataLen);
676 ASTIdentifierLookupTraitBase::internal_key_type
677 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
678 assert(n >= 2 && d[n-1] == '\0');
679 return StringRef((const char*) d, n-1);
682 /// \brief Whether the given identifier is "interesting".
683 static bool isInterestingIdentifier(IdentifierInfo &II) {
684 return II.isPoisoned() ||
685 II.isExtensionToken() ||
686 II.getObjCOrBuiltinID() ||
687 II.hasRevertedTokenIDToIdentifier() ||
688 II.hadMacroDefinition() ||
689 II.getFETokenInfo<void>();
692 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
693 const unsigned char* d,
695 using namespace llvm::support;
696 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
697 bool IsInteresting = RawID & 0x01;
699 // Wipe out the "is interesting" bit.
702 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
703 if (!IsInteresting) {
704 // For uninteresting identifiers, just build the IdentifierInfo
705 // and associate it with the persistent ID.
706 IdentifierInfo *II = KnownII;
708 II = &Reader.getIdentifierTable().getOwn(k);
711 Reader.SetIdentifierInfo(ID, II);
712 if (!II->isFromAST()) {
713 bool WasInteresting = isInterestingIdentifier(*II);
716 II->setChangedSinceDeserialization();
718 Reader.markIdentifierUpToDate(II);
722 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
723 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
724 bool CPlusPlusOperatorKeyword = Bits & 0x01;
726 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
728 bool Poisoned = Bits & 0x01;
730 bool ExtensionToken = Bits & 0x01;
732 bool hasSubmoduleMacros = Bits & 0x01;
734 bool hadMacroDefinition = Bits & 0x01;
737 assert(Bits == 0 && "Extra bits in the identifier?");
740 // Build the IdentifierInfo itself and link the identifier ID with
741 // the new IdentifierInfo.
742 IdentifierInfo *II = KnownII;
744 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
747 Reader.markIdentifierUpToDate(II);
748 if (!II->isFromAST()) {
749 bool WasInteresting = isInterestingIdentifier(*II);
752 II->setChangedSinceDeserialization();
755 // Set or check the various bits in the IdentifierInfo structure.
756 // Token IDs are read-only.
757 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
758 II->RevertTokenIDToIdentifier();
759 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
760 assert(II->isExtensionToken() == ExtensionToken &&
761 "Incorrect extension token flag");
762 (void)ExtensionToken;
764 II->setIsPoisoned(true);
765 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
766 "Incorrect C++ operator keyword flag");
767 (void)CPlusPlusOperatorKeyword;
769 // If this identifier is a macro, deserialize the macro
771 if (hadMacroDefinition) {
772 uint32_t MacroDirectivesOffset =
773 endian::readNext<uint32_t, little, unaligned>(d);
775 SmallVector<uint32_t, 8> LocalMacroIDs;
776 if (hasSubmoduleMacros) {
777 while (uint32_t LocalMacroID =
778 endian::readNext<uint32_t, little, unaligned>(d)) {
780 LocalMacroIDs.push_back(LocalMacroID);
785 if (F.Kind == MK_Module) {
786 // Macro definitions are stored from newest to oldest, so reverse them
787 // before registering them.
788 llvm::SmallVector<unsigned, 8> MacroSizes;
789 for (SmallVectorImpl<uint32_t>::iterator
790 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
793 static const uint32_t HasOverridesFlag = 0x80000000U;
794 if (I + 1 != E && (I[1] & HasOverridesFlag))
795 Size += 1 + (I[1] & ~HasOverridesFlag);
797 MacroSizes.push_back(Size);
801 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
802 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
803 SE = MacroSizes.rend();
807 uint32_t LocalMacroID = *I;
808 ArrayRef<uint32_t> Overrides;
810 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
811 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
813 assert(I == LocalMacroIDs.begin());
815 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
819 Reader.SetIdentifierInfo(ID, II);
821 // Read all of the declarations visible at global scope with this
824 SmallVector<uint32_t, 4> DeclIDs;
825 for (; DataLen > 0; DataLen -= 4)
826 DeclIDs.push_back(Reader.getGlobalDeclID(
827 F, endian::readNext<uint32_t, little, unaligned>(d)));
828 Reader.SetGloballyVisibleDecls(II, DeclIDs);
835 ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
836 llvm::FoldingSetNodeID ID;
837 ID.AddInteger(Key.Kind);
840 case DeclarationName::Identifier:
841 case DeclarationName::CXXLiteralOperatorName:
842 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
844 case DeclarationName::ObjCZeroArgSelector:
845 case DeclarationName::ObjCOneArgSelector:
846 case DeclarationName::ObjCMultiArgSelector:
847 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
849 case DeclarationName::CXXOperatorName:
850 ID.AddInteger((OverloadedOperatorKind)Key.Data);
852 case DeclarationName::CXXConstructorName:
853 case DeclarationName::CXXDestructorName:
854 case DeclarationName::CXXConversionFunctionName:
855 case DeclarationName::CXXUsingDirective:
859 return ID.ComputeHash();
862 ASTDeclContextNameLookupTrait::internal_key_type
863 ASTDeclContextNameLookupTrait::GetInternalKey(
864 const external_key_type& Name) const {
866 Key.Kind = Name.getNameKind();
867 switch (Name.getNameKind()) {
868 case DeclarationName::Identifier:
869 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
871 case DeclarationName::ObjCZeroArgSelector:
872 case DeclarationName::ObjCOneArgSelector:
873 case DeclarationName::ObjCMultiArgSelector:
874 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
876 case DeclarationName::CXXOperatorName:
877 Key.Data = Name.getCXXOverloadedOperator();
879 case DeclarationName::CXXLiteralOperatorName:
880 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
882 case DeclarationName::CXXConstructorName:
883 case DeclarationName::CXXDestructorName:
884 case DeclarationName::CXXConversionFunctionName:
885 case DeclarationName::CXXUsingDirective:
893 std::pair<unsigned, unsigned>
894 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
895 using namespace llvm::support;
896 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
897 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
898 return std::make_pair(KeyLen, DataLen);
901 ASTDeclContextNameLookupTrait::internal_key_type
902 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
903 using namespace llvm::support;
906 Key.Kind = (DeclarationName::NameKind)*d++;
908 case DeclarationName::Identifier:
909 Key.Data = (uint64_t)Reader.getLocalIdentifier(
910 F, endian::readNext<uint32_t, little, unaligned>(d));
912 case DeclarationName::ObjCZeroArgSelector:
913 case DeclarationName::ObjCOneArgSelector:
914 case DeclarationName::ObjCMultiArgSelector:
916 (uint64_t)Reader.getLocalSelector(
917 F, endian::readNext<uint32_t, little, unaligned>(
918 d)).getAsOpaquePtr();
920 case DeclarationName::CXXOperatorName:
921 Key.Data = *d++; // OverloadedOperatorKind
923 case DeclarationName::CXXLiteralOperatorName:
924 Key.Data = (uint64_t)Reader.getLocalIdentifier(
925 F, endian::readNext<uint32_t, little, unaligned>(d));
927 case DeclarationName::CXXConstructorName:
928 case DeclarationName::CXXDestructorName:
929 case DeclarationName::CXXConversionFunctionName:
930 case DeclarationName::CXXUsingDirective:
938 ASTDeclContextNameLookupTrait::data_type
939 ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
940 const unsigned char* d,
942 using namespace llvm::support;
943 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
944 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
945 const_cast<unsigned char *>(d));
946 return std::make_pair(Start, Start + NumDecls);
949 bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
950 BitstreamCursor &Cursor,
951 const std::pair<uint64_t, uint64_t> &Offsets,
952 DeclContextInfo &Info) {
953 SavedStreamPosition SavedPosition(Cursor);
954 // First the lexical decls.
955 if (Offsets.first != 0) {
956 Cursor.JumpToBit(Offsets.first);
960 unsigned Code = Cursor.ReadCode();
961 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
962 if (RecCode != DECL_CONTEXT_LEXICAL) {
963 Error("Expected lexical block");
967 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
968 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
971 // Now the lookup table.
972 if (Offsets.second != 0) {
973 Cursor.JumpToBit(Offsets.second);
977 unsigned Code = Cursor.ReadCode();
978 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
979 if (RecCode != DECL_CONTEXT_VISIBLE) {
980 Error("Expected visible lookup table block");
983 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
984 (const unsigned char *)Blob.data() + Record[0],
985 (const unsigned char *)Blob.data() + sizeof(uint32_t),
986 (const unsigned char *)Blob.data(),
987 ASTDeclContextNameLookupTrait(*this, M));
993 void ASTReader::Error(StringRef Msg) {
994 Error(diag::err_fe_pch_malformed, Msg);
995 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
996 Diag(diag::note_module_cache_path)
997 << PP.getHeaderSearchInfo().getModuleCachePath();
1001 void ASTReader::Error(unsigned DiagID,
1002 StringRef Arg1, StringRef Arg2) {
1003 if (Diags.isDiagnosticInFlight())
1004 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1006 Diag(DiagID) << Arg1 << Arg2;
1009 //===----------------------------------------------------------------------===//
1010 // Source Manager Deserialization
1011 //===----------------------------------------------------------------------===//
1013 /// \brief Read the line table in the source manager block.
1014 /// \returns true if there was an error.
1015 bool ASTReader::ParseLineTable(ModuleFile &F,
1016 SmallVectorImpl<uint64_t> &Record) {
1018 LineTableInfo &LineTable = SourceMgr.getLineTable();
1020 // Parse the file names
1021 std::map<int, int> FileIDs;
1022 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1023 // Extract the file name
1024 unsigned FilenameLen = Record[Idx++];
1025 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1027 MaybeAddSystemRootToFilename(F, Filename);
1028 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1031 // Parse the line entries
1032 std::vector<LineEntry> Entries;
1033 while (Idx < Record.size()) {
1034 int FID = Record[Idx++];
1035 assert(FID >= 0 && "Serialized line entries for non-local file.");
1036 // Remap FileID from 1-based old view.
1037 FID += F.SLocEntryBaseID - 1;
1039 // Extract the line entries
1040 unsigned NumEntries = Record[Idx++];
1041 assert(NumEntries && "Numentries is 00000");
1043 Entries.reserve(NumEntries);
1044 for (unsigned I = 0; I != NumEntries; ++I) {
1045 unsigned FileOffset = Record[Idx++];
1046 unsigned LineNo = Record[Idx++];
1047 int FilenameID = FileIDs[Record[Idx++]];
1048 SrcMgr::CharacteristicKind FileKind
1049 = (SrcMgr::CharacteristicKind)Record[Idx++];
1050 unsigned IncludeOffset = Record[Idx++];
1051 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1052 FileKind, IncludeOffset));
1054 LineTable.AddEntry(FileID::get(FID), Entries);
1060 /// \brief Read a source manager block
1061 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1062 using namespace SrcMgr;
1064 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1066 // Set the source-location entry cursor to the current position in
1067 // the stream. This cursor will be used to read the contents of the
1068 // source manager block initially, and then lazily read
1069 // source-location entries as needed.
1070 SLocEntryCursor = F.Stream;
1072 // The stream itself is going to skip over the source manager block.
1073 if (F.Stream.SkipBlock()) {
1074 Error("malformed block record in AST file");
1078 // Enter the source manager block.
1079 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1080 Error("malformed source manager block record in AST file");
1086 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1089 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1090 case llvm::BitstreamEntry::Error:
1091 Error("malformed block record in AST file");
1093 case llvm::BitstreamEntry::EndBlock:
1095 case llvm::BitstreamEntry::Record:
1096 // The interesting case.
1103 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
1104 default: // Default behavior: ignore.
1107 case SM_SLOC_FILE_ENTRY:
1108 case SM_SLOC_BUFFER_ENTRY:
1109 case SM_SLOC_EXPANSION_ENTRY:
1110 // Once we hit one of the source location entries, we're done.
1116 /// \brief If a header file is not found at the path that we expect it to be
1117 /// and the PCH file was moved from its original location, try to resolve the
1118 /// file by assuming that header+PCH were moved together and the header is in
1119 /// the same place relative to the PCH.
1121 resolveFileRelativeToOriginalDir(const std::string &Filename,
1122 const std::string &OriginalDir,
1123 const std::string &CurrDir) {
1124 assert(OriginalDir != CurrDir &&
1125 "No point trying to resolve the file if the PCH dir didn't change");
1126 using namespace llvm::sys;
1127 SmallString<128> filePath(Filename);
1128 fs::make_absolute(filePath);
1129 assert(path::is_absolute(OriginalDir));
1130 SmallString<128> currPCHPath(CurrDir);
1132 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1133 fileDirE = path::end(path::parent_path(filePath));
1134 path::const_iterator origDirI = path::begin(OriginalDir),
1135 origDirE = path::end(OriginalDir);
1136 // Skip the common path components from filePath and OriginalDir.
1137 while (fileDirI != fileDirE && origDirI != origDirE &&
1138 *fileDirI == *origDirI) {
1142 for (; origDirI != origDirE; ++origDirI)
1143 path::append(currPCHPath, "..");
1144 path::append(currPCHPath, fileDirI, fileDirE);
1145 path::append(currPCHPath, path::filename(Filename));
1146 return currPCHPath.str();
1149 bool ASTReader::ReadSLocEntry(int ID) {
1153 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1154 Error("source location entry ID out-of-range for AST file");
1158 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1159 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
1160 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1161 unsigned BaseOffset = F->SLocEntryBaseOffset;
1163 ++NumSLocEntriesRead;
1164 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1165 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1166 Error("incorrectly-formatted source location entry in AST file");
1172 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
1174 Error("incorrectly-formatted source location entry in AST file");
1177 case SM_SLOC_FILE_ENTRY: {
1178 // We will detect whether a file changed and return 'Failure' for it, but
1179 // we will also try to fail gracefully by setting up the SLocEntry.
1180 unsigned InputID = Record[4];
1181 InputFile IF = getInputFile(*F, InputID);
1182 const FileEntry *File = IF.getFile();
1183 bool OverriddenBuffer = IF.isOverridden();
1185 // Note that we only check if a File was returned. If it was out-of-date
1186 // we have complained but we will continue creating a FileID to recover
1191 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1192 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1193 // This is the module's main file.
1194 IncludeLoc = getImportLocation(F);
1196 SrcMgr::CharacteristicKind
1197 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1198 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1199 ID, BaseOffset + Record[0]);
1200 SrcMgr::FileInfo &FileInfo =
1201 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1202 FileInfo.NumCreatedFIDs = Record[5];
1204 FileInfo.setHasLineDirectives();
1206 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1207 unsigned NumFileDecls = Record[7];
1209 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1210 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1214 const SrcMgr::ContentCache *ContentCache
1215 = SourceMgr.getOrCreateContentCache(File,
1216 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1217 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1218 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1219 unsigned Code = SLocEntryCursor.ReadCode();
1221 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1223 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1224 Error("AST record has invalid code");
1228 llvm::MemoryBuffer *Buffer
1229 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
1230 SourceMgr.overrideFileContents(File, Buffer);
1236 case SM_SLOC_BUFFER_ENTRY: {
1237 const char *Name = Blob.data();
1238 unsigned Offset = Record[0];
1239 SrcMgr::CharacteristicKind
1240 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1241 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1242 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1243 IncludeLoc = getImportLocation(F);
1245 unsigned Code = SLocEntryCursor.ReadCode();
1248 = SLocEntryCursor.readRecord(Code, Record, &Blob);
1250 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1251 Error("AST record has invalid code");
1255 llvm::MemoryBuffer *Buffer
1256 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
1257 SourceMgr.createFileID(Buffer, FileCharacter, ID, BaseOffset + Offset,
1262 case SM_SLOC_EXPANSION_ENTRY: {
1263 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1264 SourceMgr.createExpansionLoc(SpellingLoc,
1265 ReadSourceLocation(*F, Record[2]),
1266 ReadSourceLocation(*F, Record[3]),
1269 BaseOffset + Record[0]);
1277 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1279 return std::make_pair(SourceLocation(), "");
1281 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1282 Error("source location entry ID out-of-range for AST file");
1283 return std::make_pair(SourceLocation(), "");
1286 // Find which module file this entry lands in.
1287 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1288 if (M->Kind != MK_Module)
1289 return std::make_pair(SourceLocation(), "");
1291 // FIXME: Can we map this down to a particular submodule? That would be
1293 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1296 /// \brief Find the location where the module F is imported.
1297 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1298 if (F->ImportLoc.isValid())
1299 return F->ImportLoc;
1301 // Otherwise we have a PCH. It's considered to be "imported" at the first
1302 // location of its includer.
1303 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1304 // Main file is the importer.
1305 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1306 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1308 return F->ImportedBy[0]->FirstLoc;
1311 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1312 /// specified cursor. Read the abbreviations that are at the top of the block
1313 /// and then leave the cursor pointing into the block.
1314 bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
1315 if (Cursor.EnterSubBlock(BlockID)) {
1316 Error("malformed block record in AST file");
1321 uint64_t Offset = Cursor.GetCurrentBitNo();
1322 unsigned Code = Cursor.ReadCode();
1324 // We expect all abbrevs to be at the start of the block.
1325 if (Code != llvm::bitc::DEFINE_ABBREV) {
1326 Cursor.JumpToBit(Offset);
1329 Cursor.ReadAbbrevRecord();
1333 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1337 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1338 Tok.setLength(Record[Idx++]);
1339 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1340 Tok.setIdentifierInfo(II);
1341 Tok.setKind((tok::TokenKind)Record[Idx++]);
1342 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1346 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1347 BitstreamCursor &Stream = F.MacroCursor;
1349 // Keep track of where we are in the stream, then jump back there
1350 // after reading this macro.
1351 SavedStreamPosition SavedPosition(Stream);
1353 Stream.JumpToBit(Offset);
1355 SmallVector<IdentifierInfo*, 16> MacroArgs;
1356 MacroInfo *Macro = nullptr;
1359 // Advance to the next record, but if we get to the end of the block, don't
1360 // pop it (removing all the abbreviations from the cursor) since we want to
1361 // be able to reseek within the block and read entries.
1362 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1363 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1365 switch (Entry.Kind) {
1366 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1367 case llvm::BitstreamEntry::Error:
1368 Error("malformed block record in AST file");
1370 case llvm::BitstreamEntry::EndBlock:
1372 case llvm::BitstreamEntry::Record:
1373 // The interesting case.
1379 PreprocessorRecordTypes RecType =
1380 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
1382 case PP_MACRO_DIRECTIVE_HISTORY:
1385 case PP_MACRO_OBJECT_LIKE:
1386 case PP_MACRO_FUNCTION_LIKE: {
1387 // If we already have a macro, that means that we've hit the end
1388 // of the definition of the macro we were looking for. We're
1393 unsigned NextIndex = 1; // Skip identifier ID.
1394 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
1395 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1396 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
1397 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1398 MI->setIsUsed(Record[NextIndex++]);
1399 MI->setUsedForHeaderGuard(Record[NextIndex++]);
1401 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1402 // Decode function-like macro info.
1403 bool isC99VarArgs = Record[NextIndex++];
1404 bool isGNUVarArgs = Record[NextIndex++];
1405 bool hasCommaPasting = Record[NextIndex++];
1407 unsigned NumArgs = Record[NextIndex++];
1408 for (unsigned i = 0; i != NumArgs; ++i)
1409 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1411 // Install function-like macro info.
1412 MI->setIsFunctionLike();
1413 if (isC99VarArgs) MI->setIsC99Varargs();
1414 if (isGNUVarArgs) MI->setIsGNUVarargs();
1415 if (hasCommaPasting) MI->setHasCommaPasting();
1416 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1417 PP.getPreprocessorAllocator());
1420 // Remember that we saw this macro last so that we add the tokens that
1421 // form its body to it.
1424 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1425 Record[NextIndex]) {
1426 // We have a macro definition. Register the association
1427 PreprocessedEntityID
1428 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1429 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1430 PreprocessingRecord::PPEntityID
1431 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1432 MacroDefinition *PPDef =
1433 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1435 PPRec.RegisterMacroDefinition(Macro, PPDef);
1443 // If we see a TOKEN before a PP_MACRO_*, then the file is
1444 // erroneous, just pretend we didn't see this.
1448 Token Tok = ReadToken(F, Record, Idx);
1449 Macro->AddTokenToBody(Tok);
1456 PreprocessedEntityID
1457 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1458 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1459 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1460 assert(I != M.PreprocessedEntityRemap.end()
1461 && "Invalid index into preprocessed entity index remap");
1463 return LocalID + I->second;
1466 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1467 return llvm::hash_combine(ikey.Size, ikey.ModTime);
1470 HeaderFileInfoTrait::internal_key_type
1471 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1472 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1477 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1478 if (a.Size != b.Size || a.ModTime != b.ModTime)
1481 if (strcmp(a.Filename, b.Filename) == 0)
1484 // Determine whether the actual files are equivalent.
1485 FileManager &FileMgr = Reader.getFileManager();
1486 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1487 const FileEntry *FEB = FileMgr.getFile(b.Filename);
1488 return (FEA && FEA == FEB);
1491 std::pair<unsigned, unsigned>
1492 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1493 using namespace llvm::support;
1494 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1495 unsigned DataLen = (unsigned) *d++;
1496 return std::make_pair(KeyLen, DataLen);
1499 HeaderFileInfoTrait::internal_key_type
1500 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1501 using namespace llvm::support;
1502 internal_key_type ikey;
1503 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1504 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1505 ikey.Filename = (const char *)d;
1509 HeaderFileInfoTrait::data_type
1510 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1512 const unsigned char *End = d + DataLen;
1513 using namespace llvm::support;
1515 unsigned Flags = *d++;
1516 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1517 ((Flags >> 6) & 0x03);
1518 HFI.isImport = (Flags >> 5) & 0x01;
1519 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1520 HFI.DirInfo = (Flags >> 2) & 0x03;
1521 HFI.Resolved = (Flags >> 1) & 0x01;
1522 HFI.IndexHeaderMapHeader = Flags & 0x01;
1523 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1524 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1525 M, endian::readNext<uint32_t, little, unaligned>(d));
1526 if (unsigned FrameworkOffset =
1527 endian::readNext<uint32_t, little, unaligned>(d)) {
1528 // The framework offset is 1 greater than the actual offset,
1529 // since 0 is used as an indicator for "no framework name".
1530 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1531 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1535 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1537 // This header is part of a module. Associate it with the module to enable
1538 // implicit module import.
1539 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1540 Module *Mod = Reader.getSubmodule(GlobalSMID);
1541 HFI.isModuleHeader = true;
1542 FileManager &FileMgr = Reader.getFileManager();
1544 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1545 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
1549 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1552 // This HeaderFileInfo was externally loaded.
1553 HFI.External = true;
1558 ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1559 GlobalMacroID GMacID,
1560 ArrayRef<SubmoduleID> Overrides) {
1561 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1562 SubmoduleID *OverrideData = nullptr;
1563 if (!Overrides.empty()) {
1564 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1565 OverrideData[0] = Overrides.size();
1566 for (unsigned I = 0; I != Overrides.size(); ++I)
1567 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1569 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
1572 void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1574 uint64_t MacroDirectivesOffset) {
1575 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1576 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1579 void ASTReader::ReadDefinedMacros() {
1580 // Note that we are loading defined macros.
1581 Deserializing Macros(this);
1583 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1584 E = ModuleMgr.rend(); I != E; ++I) {
1585 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
1587 // If there was no preprocessor block, skip this file.
1588 if (!MacroCursor.getBitStreamReader())
1591 BitstreamCursor Cursor = MacroCursor;
1592 Cursor.JumpToBit((*I)->MacroStartOffset);
1596 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1599 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1600 case llvm::BitstreamEntry::Error:
1601 Error("malformed block record in AST file");
1603 case llvm::BitstreamEntry::EndBlock:
1606 case llvm::BitstreamEntry::Record:
1608 switch (Cursor.readRecord(E.ID, Record)) {
1609 default: // Default behavior: ignore.
1612 case PP_MACRO_OBJECT_LIKE:
1613 case PP_MACRO_FUNCTION_LIKE:
1614 getLocalIdentifier(**I, Record[0]);
1629 /// \brief Visitor class used to look up identifirs in an AST file.
1630 class IdentifierLookupVisitor {
1632 unsigned PriorGeneration;
1633 unsigned &NumIdentifierLookups;
1634 unsigned &NumIdentifierLookupHits;
1635 IdentifierInfo *Found;
1638 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1639 unsigned &NumIdentifierLookups,
1640 unsigned &NumIdentifierLookupHits)
1641 : Name(Name), PriorGeneration(PriorGeneration),
1642 NumIdentifierLookups(NumIdentifierLookups),
1643 NumIdentifierLookupHits(NumIdentifierLookupHits),
1648 static bool visit(ModuleFile &M, void *UserData) {
1649 IdentifierLookupVisitor *This
1650 = static_cast<IdentifierLookupVisitor *>(UserData);
1652 // If we've already searched this module file, skip it now.
1653 if (M.Generation <= This->PriorGeneration)
1656 ASTIdentifierLookupTable *IdTable
1657 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1661 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1663 ++This->NumIdentifierLookups;
1664 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
1665 if (Pos == IdTable->end())
1668 // Dereferencing the iterator has the effect of building the
1669 // IdentifierInfo node and populating it with the various
1670 // declarations it needs.
1671 ++This->NumIdentifierLookupHits;
1676 // \brief Retrieve the identifier info found within the module
1678 IdentifierInfo *getIdentifierInfo() const { return Found; }
1682 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1683 // Note that we are loading an identifier.
1684 Deserializing AnIdentifier(this);
1686 unsigned PriorGeneration = 0;
1687 if (getContext().getLangOpts().Modules)
1688 PriorGeneration = IdentifierGeneration[&II];
1690 // If there is a global index, look there first to determine which modules
1691 // provably do not have any results for this identifier.
1692 GlobalModuleIndex::HitSet Hits;
1693 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
1694 if (!loadGlobalIndex()) {
1695 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1700 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
1701 NumIdentifierLookups,
1702 NumIdentifierLookupHits);
1703 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
1704 markIdentifierUpToDate(&II);
1707 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1711 II->setOutOfDate(false);
1713 // Update the generation for this identifier.
1714 if (getContext().getLangOpts().Modules)
1715 IdentifierGeneration[II] = getGeneration();
1718 struct ASTReader::ModuleMacroInfo {
1719 SubmoduleID SubModID;
1721 SubmoduleID *Overrides;
1722 // FIXME: Remove this.
1725 bool isDefine() const { return MI; }
1727 SubmoduleID getSubmoduleID() const { return SubModID; }
1729 ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
1732 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1735 DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1738 return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1742 ASTReader::ModuleMacroInfo *
1743 ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1744 ModuleMacroInfo Info;
1746 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1748 // Macro undefinition.
1749 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
1752 // Macro definition.
1753 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1756 // If this macro has already been loaded, don't do so again.
1757 // FIXME: This is highly dubious. Multiple macro definitions can have the
1758 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1759 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1762 Info.MI = getMacro(GMacID);
1763 Info.SubModID = Info.MI->getOwningModuleID();
1765 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1768 return new (Context) ModuleMacroInfo(Info);
1771 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1772 const PendingMacroInfo &PMInfo) {
1775 if (PMInfo.M->Kind != MK_Module) {
1776 installPCHMacroDirectives(II, *PMInfo.M,
1777 PMInfo.PCHMacroData.MacroDirectivesOffset);
1783 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1787 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1788 if (Owner && Owner->NameVisibility == Module::Hidden) {
1789 // Macros in the owning module are hidden. Just remember this macro to
1790 // install if we make this module visible.
1791 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1793 installImportedMacro(II, MMI, Owner, /*FromFinalization*/false);
1797 void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1798 ModuleFile &M, uint64_t Offset) {
1799 assert(M.Kind != MK_Module);
1801 BitstreamCursor &Cursor = M.MacroCursor;
1802 SavedStreamPosition SavedPosition(Cursor);
1803 Cursor.JumpToBit(Offset);
1805 llvm::BitstreamEntry Entry =
1806 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1807 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1808 Error("malformed block record in AST file");
1813 PreprocessorRecordTypes RecType =
1814 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1815 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1816 Error("malformed block record in AST file");
1820 // Deserialize the macro directives history in reverse source-order.
1821 MacroDirective *Latest = nullptr, *Earliest = nullptr;
1822 unsigned Idx = 0, N = Record.size();
1824 MacroDirective *MD = nullptr;
1825 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
1826 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1828 case MacroDirective::MD_Define: {
1829 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1830 MacroInfo *MI = getMacro(GMacID);
1831 bool isImported = Record[Idx++];
1832 bool isAmbiguous = Record[Idx++];
1833 DefMacroDirective *DefMD =
1834 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1835 DefMD->setAmbiguous(isAmbiguous);
1839 case MacroDirective::MD_Undefine:
1840 MD = PP.AllocateUndefMacroDirective(Loc);
1842 case MacroDirective::MD_Visibility: {
1843 bool isPublic = Record[Idx++];
1844 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1852 Earliest->setPrevious(MD);
1856 PP.setLoadedMacroDirective(II, Latest);
1859 /// \brief For the given macro definitions, check if they are both in system
1861 static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
1862 Module *NewOwner, ASTReader &Reader) {
1863 assert(PrevMI && NewMI);
1864 Module *PrevOwner = nullptr;
1865 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1866 PrevOwner = Reader.getSubmodule(PrevModID);
1867 SourceManager &SrcMgr = Reader.getSourceManager();
1869 = PrevOwner? PrevOwner->IsSystem
1870 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1872 = NewOwner? NewOwner->IsSystem
1873 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1874 if (PrevOwner && PrevOwner == NewOwner)
1876 return PrevInSystem && NewInSystem;
1879 void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1880 AmbiguousMacros &Ambig,
1881 ArrayRef<SubmoduleID> Overrides) {
1882 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1883 SubmoduleID OwnerID = Overrides[OI];
1885 // If this macro is not yet visible, remove it from the hidden names list.
1886 Module *Owner = getSubmodule(OwnerID);
1887 HiddenNames &Hidden = HiddenNamesMap[Owner];
1888 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1889 if (HI != Hidden.HiddenMacros.end()) {
1890 auto SubOverrides = HI->second->getOverriddenSubmodules();
1891 Hidden.HiddenMacros.erase(HI);
1892 removeOverriddenMacros(II, Ambig, SubOverrides);
1895 // If this macro is already in our list of conflicts, remove it from there.
1897 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1898 return MD->getInfo()->getOwningModuleID() == OwnerID;
1904 ASTReader::AmbiguousMacros *
1905 ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1906 ArrayRef<SubmoduleID> Overrides) {
1907 MacroDirective *Prev = PP.getMacroDirective(II);
1908 if (!Prev && Overrides.empty())
1911 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1913 if (PrevDef && PrevDef->isAmbiguous()) {
1914 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1915 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1916 Ambig.push_back(PrevDef);
1918 removeOverriddenMacros(II, Ambig, Overrides);
1923 AmbiguousMacroDefs.erase(II);
1925 // There's no ambiguity yet. Maybe we're introducing one.
1926 AmbiguousMacros Ambig;
1928 Ambig.push_back(PrevDef);
1930 removeOverriddenMacros(II, Ambig, Overrides);
1932 if (!Ambig.empty()) {
1933 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
1934 std::swap(Result, Ambig);
1939 // We ended up with no ambiguity.
1943 void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
1944 Module *Owner, bool FromFinalization) {
1945 assert(II && Owner);
1947 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
1948 if (ImportLoc.isInvalid() && !FromFinalization) {
1949 // FIXME: If we made macros from this module visible but didn't provide a
1950 // source location for the import, we don't have a location for the macro.
1951 // Use the location at which the containing module file was first imported
1953 ImportLoc = MMI->F->DirectImportLoc;
1954 assert(ImportLoc.isValid() && "no import location for a visible macro?");
1957 AmbiguousMacros *Prev =
1958 removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1960 // Create a synthetic macro definition corresponding to the import (or null
1961 // if this was an undefinition of the macro).
1962 DefMacroDirective *MD = MMI->import(PP, ImportLoc);
1964 // If there's no ambiguity, just install the macro.
1967 PP.appendMacroDirective(II, MD);
1969 PP.appendMacroDirective(II, PP.AllocateUndefMacroDirective(ImportLoc));
1972 assert(!Prev->empty());
1975 // We imported a #undef that didn't remove all prior definitions. The most
1976 // recent prior definition remains, and we install it in the place of the
1977 // imported directive.
1978 MacroInfo *NewMI = Prev->back()->getInfo();
1980 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc, /*Imported*/true);
1983 // We're introducing a macro definition that creates or adds to an ambiguity.
1984 // We can resolve that ambiguity if this macro is token-for-token identical to
1985 // all of the existing definitions.
1986 MacroInfo *NewMI = MD->getInfo();
1987 assert(NewMI && "macro definition with no MacroInfo?");
1988 while (!Prev->empty()) {
1989 MacroInfo *PrevMI = Prev->back()->getInfo();
1990 assert(PrevMI && "macro definition with no MacroInfo?");
1992 // Before marking the macros as ambiguous, check if this is a case where
1993 // both macros are in system headers. If so, we trust that the system
1994 // did not get it wrong. This also handles cases where Clang's own
1995 // headers have a different spelling of certain system macros:
1996 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1997 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1999 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2000 // overrides the system limits.h's macros, so there's no conflict here.
2001 if (NewMI != PrevMI &&
2002 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2003 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2006 // The previous definition is the same as this one (or both are defined in
2007 // system modules so we can assume they're equivalent); we don't need to
2008 // track it any more.
2013 MD->setAmbiguous(true);
2015 PP.appendMacroDirective(II, MD);
2018 ASTReader::InputFileInfo
2019 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
2020 // Go find this input file.
2021 BitstreamCursor &Cursor = F.InputFilesCursor;
2022 SavedStreamPosition SavedPosition(Cursor);
2023 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2025 unsigned Code = Cursor.ReadCode();
2029 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2030 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2031 "invalid record type for input file");
2034 std::string Filename;
2039 assert(Record[0] == ID && "Bogus stored ID or offset");
2040 StoredSize = static_cast<off_t>(Record[1]);
2041 StoredTime = static_cast<time_t>(Record[2]);
2042 Overridden = static_cast<bool>(Record[3]);
2044 MaybeAddSystemRootToFilename(F, Filename);
2046 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2050 std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
2051 return readInputFileInfo(F, ID).Filename;
2054 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2055 // If this ID is bogus, just return an empty input file.
2056 if (ID == 0 || ID > F.InputFilesLoaded.size())
2059 // If we've already loaded this input file, return it.
2060 if (F.InputFilesLoaded[ID-1].getFile())
2061 return F.InputFilesLoaded[ID-1];
2063 if (F.InputFilesLoaded[ID-1].isNotFound())
2066 // Go find this input file.
2067 BitstreamCursor &Cursor = F.InputFilesCursor;
2068 SavedStreamPosition SavedPosition(Cursor);
2069 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2071 InputFileInfo FI = readInputFileInfo(F, ID);
2072 off_t StoredSize = FI.StoredSize;
2073 time_t StoredTime = FI.StoredTime;
2074 bool Overridden = FI.Overridden;
2075 StringRef Filename = FI.Filename;
2077 const FileEntry *File
2078 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2079 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2081 // If we didn't find the file, resolve it relative to the
2082 // original directory from which this AST file was created.
2083 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
2084 F.OriginalDir != CurrentDir) {
2085 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2088 if (!Resolved.empty())
2089 File = FileMgr.getFile(Resolved);
2092 // For an overridden file, create a virtual file with the stored
2094 if (Overridden && File == nullptr) {
2095 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2098 if (File == nullptr) {
2100 std::string ErrorStr = "could not find file '";
2101 ErrorStr += Filename;
2102 ErrorStr += "' referenced by AST file";
2103 Error(ErrorStr.c_str());
2105 // Record that we didn't find the file.
2106 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2110 // Check if there was a request to override the contents of the file
2111 // that was part of the precompiled header. Overridding such a file
2112 // can lead to problems when lexing using the source locations from the
2114 SourceManager &SM = getSourceManager();
2115 if (!Overridden && SM.isFileOverridden(File)) {
2117 Error(diag::err_fe_pch_file_overridden, Filename);
2118 // After emitting the diagnostic, recover by disabling the override so
2119 // that the original file will be used.
2120 SM.disableFileContentsOverride(File);
2121 // The FileEntry is a virtual file entry with the size of the contents
2122 // that would override the original contents. Set it to the original's
2124 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2125 StoredSize, StoredTime);
2128 bool IsOutOfDate = false;
2130 // For an overridden file, there is nothing to validate.
2131 if (!Overridden && (StoredSize != File->getSize()
2132 #if !defined(LLVM_ON_WIN32)
2133 // In our regression testing, the Windows file system seems to
2134 // have inconsistent modification times that sometimes
2135 // erroneously trigger this error-handling path.
2136 || StoredTime != File->getModificationTime()
2140 // Build a list of the PCH imports that got us here (in reverse).
2141 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2142 while (ImportStack.back()->ImportedBy.size() > 0)
2143 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2145 // The top-level PCH is stale.
2146 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2147 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2149 // Print the import stack.
2150 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2151 Diag(diag::note_pch_required_by)
2152 << Filename << ImportStack[0]->FileName;
2153 for (unsigned I = 1; I < ImportStack.size(); ++I)
2154 Diag(diag::note_pch_required_by)
2155 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2158 if (!Diags.isDiagnosticInFlight())
2159 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2165 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2167 // Note that we've loaded this input file.
2168 F.InputFilesLoaded[ID-1] = IF;
2172 const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2173 ModuleFile &M = ModuleMgr.getPrimaryModule();
2174 std::string Filename = filenameStrRef;
2175 MaybeAddSystemRootToFilename(M, Filename);
2176 const FileEntry *File = FileMgr.getFile(Filename);
2177 if (File == nullptr && !M.OriginalDir.empty() && !CurrentDir.empty() &&
2178 M.OriginalDir != CurrentDir) {
2179 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2182 if (!resolved.empty())
2183 File = FileMgr.getFile(resolved);
2189 /// \brief If we are loading a relocatable PCH file, and the filename is
2190 /// not an absolute path, add the system root to the beginning of the file
2192 void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2193 std::string &Filename) {
2194 // If this is not a relocatable PCH file, there's nothing to do.
2195 if (!M.RelocatablePCH)
2198 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2201 if (isysroot.empty()) {
2202 // If no system root was given, default to '/'
2203 Filename.insert(Filename.begin(), '/');
2207 unsigned Length = isysroot.size();
2208 if (isysroot[Length - 1] != '/')
2209 Filename.insert(Filename.begin(), '/');
2211 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2214 ASTReader::ASTReadResult
2215 ASTReader::ReadControlBlock(ModuleFile &F,
2216 SmallVectorImpl<ImportedModule> &Loaded,
2217 const ModuleFile *ImportedBy,
2218 unsigned ClientLoadCapabilities) {
2219 BitstreamCursor &Stream = F.Stream;
2221 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2222 Error("malformed block record in AST file");
2226 // Read all of the records and blocks in the control block.
2229 llvm::BitstreamEntry Entry = Stream.advance();
2231 switch (Entry.Kind) {
2232 case llvm::BitstreamEntry::Error:
2233 Error("malformed block record in AST file");
2235 case llvm::BitstreamEntry::EndBlock: {
2236 // Validate input files.
2237 const HeaderSearchOptions &HSOpts =
2238 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2240 // All user input files reside at the index range [0, Record[1]), and
2241 // system input files reside at [Record[1], Record[0]).
2242 // Record is the one from INPUT_FILE_OFFSETS.
2243 unsigned NumInputs = Record[0];
2244 unsigned NumUserInputs = Record[1];
2246 if (!DisableValidation &&
2247 (ValidateSystemInputs || !HSOpts.ModulesValidateOncePerBuildSession ||
2248 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
2249 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2251 // If we are reading a module, we will create a verification timestamp,
2252 // so we verify all input files. Otherwise, verify only user input
2255 unsigned N = NumUserInputs;
2256 if (ValidateSystemInputs ||
2257 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2260 for (unsigned I = 0; I < N; ++I) {
2261 InputFile IF = getInputFile(F, I+1, Complain);
2262 if (!IF.getFile() || IF.isOutOfDate())
2268 Listener->visitModuleFile(F.FileName);
2270 if (Listener && Listener->needsInputFileVisitation()) {
2271 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2273 for (unsigned I = 0; I < N; ++I) {
2274 bool IsSystem = I >= NumUserInputs;
2275 InputFileInfo FI = readInputFileInfo(F, I+1);
2276 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2283 case llvm::BitstreamEntry::SubBlock:
2285 case INPUT_FILES_BLOCK_ID:
2286 F.InputFilesCursor = Stream;
2287 if (Stream.SkipBlock() || // Skip with the main cursor
2288 // Read the abbreviations
2289 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2290 Error("malformed block record in AST file");
2296 if (Stream.SkipBlock()) {
2297 Error("malformed block record in AST file");
2303 case llvm::BitstreamEntry::Record:
2304 // The interesting case.
2308 // Read and process a record.
2311 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2313 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2314 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2315 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2316 : diag::err_pch_version_too_new);
2317 return VersionMismatch;
2320 bool hasErrors = Record[5];
2321 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2322 Diag(diag::err_pch_with_compiler_errors);
2326 F.RelocatablePCH = Record[4];
2328 const std::string &CurBranch = getClangFullRepositoryVersion();
2329 StringRef ASTBranch = Blob;
2330 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2331 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2332 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2333 return VersionMismatch;
2339 // Load each of the imported PCH files.
2340 unsigned Idx = 0, N = Record.size();
2342 // Read information about the AST file.
2343 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2344 // The import location will be the local one for now; we will adjust
2345 // all import locations of module imports after the global source
2346 // location info are setup.
2347 SourceLocation ImportLoc =
2348 SourceLocation::getFromRawEncoding(Record[Idx++]);
2349 off_t StoredSize = (off_t)Record[Idx++];
2350 time_t StoredModTime = (time_t)Record[Idx++];
2351 unsigned Length = Record[Idx++];
2352 SmallString<128> ImportedFile(Record.begin() + Idx,
2353 Record.begin() + Idx + Length);
2356 // Load the AST file.
2357 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
2358 StoredSize, StoredModTime,
2359 ClientLoadCapabilities)) {
2360 case Failure: return Failure;
2361 // If we have to ignore the dependency, we'll have to ignore this too.
2363 case OutOfDate: return OutOfDate;
2364 case VersionMismatch: return VersionMismatch;
2365 case ConfigurationMismatch: return ConfigurationMismatch;
2366 case HadErrors: return HadErrors;
2367 case Success: break;
2373 case LANGUAGE_OPTIONS: {
2374 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2375 if (Listener && &F == *ModuleMgr.begin() &&
2376 ParseLanguageOptions(Record, Complain, *Listener) &&
2377 !DisableValidation && !AllowConfigurationMismatch)
2378 return ConfigurationMismatch;
2382 case TARGET_OPTIONS: {
2383 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2384 if (Listener && &F == *ModuleMgr.begin() &&
2385 ParseTargetOptions(Record, Complain, *Listener) &&
2386 !DisableValidation && !AllowConfigurationMismatch)
2387 return ConfigurationMismatch;
2391 case DIAGNOSTIC_OPTIONS: {
2392 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
2393 if (Listener && &F == *ModuleMgr.begin() &&
2394 ParseDiagnosticOptions(Record, Complain, *Listener) &&
2400 case FILE_SYSTEM_OPTIONS: {
2401 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2402 if (Listener && &F == *ModuleMgr.begin() &&
2403 ParseFileSystemOptions(Record, Complain, *Listener) &&
2404 !DisableValidation && !AllowConfigurationMismatch)
2405 return ConfigurationMismatch;
2409 case HEADER_SEARCH_OPTIONS: {
2410 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2411 if (Listener && &F == *ModuleMgr.begin() &&
2412 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
2413 !DisableValidation && !AllowConfigurationMismatch)
2414 return ConfigurationMismatch;
2418 case PREPROCESSOR_OPTIONS: {
2419 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2420 if (Listener && &F == *ModuleMgr.begin() &&
2421 ParsePreprocessorOptions(Record, Complain, *Listener,
2422 SuggestedPredefines) &&
2423 !DisableValidation && !AllowConfigurationMismatch)
2424 return ConfigurationMismatch;
2429 F.OriginalSourceFileID = FileID::get(Record[0]);
2430 F.ActualOriginalSourceFileName = Blob;
2431 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2432 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2435 case ORIGINAL_FILE_ID:
2436 F.OriginalSourceFileID = FileID::get(Record[0]);
2439 case ORIGINAL_PCH_DIR:
2440 F.OriginalDir = Blob;
2444 F.ModuleName = Blob;
2446 Listener->ReadModuleName(F.ModuleName);
2449 case MODULE_MAP_FILE:
2450 F.ModuleMapPath = Blob;
2452 // Try to resolve ModuleName in the current header search context and
2453 // verify that it is found in the same module map file as we saved. If the
2454 // top-level AST file is a main file, skip this check because there is no
2455 // usable header search context.
2456 assert(!F.ModuleName.empty() &&
2457 "MODULE_NAME should come before MOUDLE_MAP_FILE");
2458 if (F.Kind == MK_Module &&
2459 (*ModuleMgr.begin())->Kind != MK_MainFile) {
2460 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2462 assert(ImportedBy && "top-level import should be verified");
2463 if ((ClientLoadCapabilities & ARR_Missing) == 0)
2464 Diag(diag::err_imported_module_not_found)
2465 << F.ModuleName << ImportedBy->FileName;
2469 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
2470 if (StoredModMap == nullptr || StoredModMap != M->ModuleMap) {
2471 assert(M->ModuleMap && "found module is missing module map file");
2472 assert(M->Name == F.ModuleName && "found module with different name");
2473 assert(ImportedBy && "top-level import should be verified");
2474 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2475 Diag(diag::err_imported_module_modmap_changed)
2476 << F.ModuleName << ImportedBy->FileName
2477 << M->ModuleMap->getName() << F.ModuleMapPath;
2483 Listener->ReadModuleMapFile(F.ModuleMapPath);
2486 case INPUT_FILE_OFFSETS:
2487 F.InputFileOffsets = (const uint32_t *)Blob.data();
2488 F.InputFilesLoaded.resize(Record[0]);
2494 ASTReader::ASTReadResult
2495 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
2496 BitstreamCursor &Stream = F.Stream;
2498 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2499 Error("malformed block record in AST file");
2503 // Read all of the records and blocks for the AST file.
2506 llvm::BitstreamEntry Entry = Stream.advance();
2508 switch (Entry.Kind) {
2509 case llvm::BitstreamEntry::Error:
2510 Error("error at end of module block in AST file");
2512 case llvm::BitstreamEntry::EndBlock: {
2513 // Outside of C++, we do not store a lookup map for the translation unit.
2514 // Instead, mark it as needing a lookup map to be built if this module
2515 // contains any declarations lexically within it (which it always does!).
2516 // This usually has no cost, since we very rarely need the lookup map for
2517 // the translation unit outside C++.
2518 DeclContext *DC = Context.getTranslationUnitDecl();
2519 if (DC->hasExternalLexicalStorage() &&
2520 !getContext().getLangOpts().CPlusPlus)
2521 DC->setMustBuildLookupTable();
2525 case llvm::BitstreamEntry::SubBlock:
2527 case DECLTYPES_BLOCK_ID:
2528 // We lazily load the decls block, but we want to set up the
2529 // DeclsCursor cursor to point into it. Clone our current bitcode
2530 // cursor to it, enter the block and read the abbrevs in that block.
2531 // With the main cursor, we just skip over it.
2532 F.DeclsCursor = Stream;
2533 if (Stream.SkipBlock() || // Skip with the main cursor.
2534 // Read the abbrevs.
2535 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2536 Error("malformed block record in AST file");
2541 case PREPROCESSOR_BLOCK_ID:
2542 F.MacroCursor = Stream;
2543 if (!PP.getExternalSource())
2544 PP.setExternalSource(this);
2546 if (Stream.SkipBlock() ||
2547 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2548 Error("malformed block record in AST file");
2551 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2554 case PREPROCESSOR_DETAIL_BLOCK_ID:
2555 F.PreprocessorDetailCursor = Stream;
2556 if (Stream.SkipBlock() ||
2557 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
2558 PREPROCESSOR_DETAIL_BLOCK_ID)) {
2559 Error("malformed preprocessor detail record in AST file");
2562 F.PreprocessorDetailStartOffset
2563 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2565 if (!PP.getPreprocessingRecord())
2566 PP.createPreprocessingRecord();
2567 if (!PP.getPreprocessingRecord()->getExternalSource())
2568 PP.getPreprocessingRecord()->SetExternalSource(*this);
2571 case SOURCE_MANAGER_BLOCK_ID:
2572 if (ReadSourceManagerBlock(F))
2576 case SUBMODULE_BLOCK_ID:
2577 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2581 case COMMENTS_BLOCK_ID: {
2582 BitstreamCursor C = Stream;
2583 if (Stream.SkipBlock() ||
2584 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2585 Error("malformed comments block in AST file");
2588 CommentsCursors.push_back(std::make_pair(C, &F));
2593 if (Stream.SkipBlock()) {
2594 Error("malformed block record in AST file");
2601 case llvm::BitstreamEntry::Record:
2602 // The interesting case.
2606 // Read and process a record.
2609 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2610 default: // Default behavior: ignore.
2614 if (F.LocalNumTypes != 0) {
2615 Error("duplicate TYPE_OFFSET record in AST file");
2618 F.TypeOffsets = (const uint32_t *)Blob.data();
2619 F.LocalNumTypes = Record[0];
2620 unsigned LocalBaseTypeIndex = Record[1];
2621 F.BaseTypeIndex = getTotalNumTypes();
2623 if (F.LocalNumTypes > 0) {
2624 // Introduce the global -> local mapping for types within this module.
2625 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2627 // Introduce the local -> global mapping for types within this module.
2628 F.TypeRemap.insertOrReplace(
2629 std::make_pair(LocalBaseTypeIndex,
2630 F.BaseTypeIndex - LocalBaseTypeIndex));
2632 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2638 if (F.LocalNumDecls != 0) {
2639 Error("duplicate DECL_OFFSET record in AST file");
2642 F.DeclOffsets = (const DeclOffset *)Blob.data();
2643 F.LocalNumDecls = Record[0];
2644 unsigned LocalBaseDeclID = Record[1];
2645 F.BaseDeclID = getTotalNumDecls();
2647 if (F.LocalNumDecls > 0) {
2648 // Introduce the global -> local mapping for declarations within this
2650 GlobalDeclMap.insert(
2651 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2653 // Introduce the local -> global mapping for declarations within this
2655 F.DeclRemap.insertOrReplace(
2656 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2658 // Introduce the global -> local mapping for declarations within this
2660 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2662 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2667 case TU_UPDATE_LEXICAL: {
2668 DeclContext *TU = Context.getTranslationUnitDecl();
2669 DeclContextInfo &Info = F.DeclContextInfos[TU];
2670 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
2671 Info.NumLexicalDecls
2672 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
2673 TU->setHasExternalLexicalStorage(true);
2677 case UPDATE_VISIBLE: {
2679 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2680 ASTDeclContextNameLookupTable *Table =
2681 ASTDeclContextNameLookupTable::Create(
2682 (const unsigned char *)Blob.data() + Record[Idx++],
2683 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2684 (const unsigned char *)Blob.data(),
2685 ASTDeclContextNameLookupTrait(*this, F));
2686 if (Decl *D = GetExistingDecl(ID)) {
2687 auto *DC = cast<DeclContext>(D);
2688 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
2689 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2690 // FIXME: There should never be an existing lookup table.
2692 LookupTable = Table;
2694 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2698 case IDENTIFIER_TABLE:
2699 F.IdentifierTableData = Blob.data();
2701 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2702 (const unsigned char *)F.IdentifierTableData + Record[0],
2703 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2704 (const unsigned char *)F.IdentifierTableData,
2705 ASTIdentifierLookupTrait(*this, F));
2707 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2711 case IDENTIFIER_OFFSET: {
2712 if (F.LocalNumIdentifiers != 0) {
2713 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2716 F.IdentifierOffsets = (const uint32_t *)Blob.data();
2717 F.LocalNumIdentifiers = Record[0];
2718 unsigned LocalBaseIdentifierID = Record[1];
2719 F.BaseIdentifierID = getTotalNumIdentifiers();
2721 if (F.LocalNumIdentifiers > 0) {
2722 // Introduce the global -> local mapping for identifiers within this
2724 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2727 // Introduce the local -> global mapping for identifiers within this
2729 F.IdentifierRemap.insertOrReplace(
2730 std::make_pair(LocalBaseIdentifierID,
2731 F.BaseIdentifierID - LocalBaseIdentifierID));
2733 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2734 + F.LocalNumIdentifiers);
2739 case EAGERLY_DESERIALIZED_DECLS:
2740 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2741 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2745 if (SpecialTypes.empty()) {
2746 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2747 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2751 if (SpecialTypes.size() != Record.size()) {
2752 Error("invalid special-types record");
2756 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2757 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2758 if (!SpecialTypes[I])
2759 SpecialTypes[I] = ID;
2760 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2766 TotalNumStatements += Record[0];
2767 TotalNumMacros += Record[1];
2768 TotalLexicalDeclContexts += Record[2];
2769 TotalVisibleDeclContexts += Record[3];
2772 case UNUSED_FILESCOPED_DECLS:
2773 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2774 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2777 case DELEGATING_CTORS:
2778 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2779 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2782 case WEAK_UNDECLARED_IDENTIFIERS:
2783 if (Record.size() % 4 != 0) {
2784 Error("invalid weak identifiers record");
2788 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2789 // files. This isn't the way to do it :)
2790 WeakUndeclaredIdentifiers.clear();
2792 // Translate the weak, undeclared identifiers into global IDs.
2793 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2794 WeakUndeclaredIdentifiers.push_back(
2795 getGlobalIdentifierID(F, Record[I++]));
2796 WeakUndeclaredIdentifiers.push_back(
2797 getGlobalIdentifierID(F, Record[I++]));
2798 WeakUndeclaredIdentifiers.push_back(
2799 ReadSourceLocation(F, Record, I).getRawEncoding());
2800 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2804 case LOCALLY_SCOPED_EXTERN_C_DECLS:
2805 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2806 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
2809 case SELECTOR_OFFSETS: {
2810 F.SelectorOffsets = (const uint32_t *)Blob.data();
2811 F.LocalNumSelectors = Record[0];
2812 unsigned LocalBaseSelectorID = Record[1];
2813 F.BaseSelectorID = getTotalNumSelectors();
2815 if (F.LocalNumSelectors > 0) {
2816 // Introduce the global -> local mapping for selectors within this
2818 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2820 // Introduce the local -> global mapping for selectors within this
2822 F.SelectorRemap.insertOrReplace(
2823 std::make_pair(LocalBaseSelectorID,
2824 F.BaseSelectorID - LocalBaseSelectorID));
2826 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2832 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
2834 F.SelectorLookupTable
2835 = ASTSelectorLookupTable::Create(
2836 F.SelectorLookupTableData + Record[0],
2837 F.SelectorLookupTableData,
2838 ASTSelectorLookupTrait(*this, F));
2839 TotalNumMethodPoolEntries += Record[1];
2842 case REFERENCED_SELECTOR_POOL:
2843 if (!Record.empty()) {
2844 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2845 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2847 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2853 case PP_COUNTER_VALUE:
2854 if (!Record.empty() && Listener)
2855 Listener->ReadCounter(F, Record[0]);
2858 case FILE_SORTED_DECLS:
2859 F.FileSortedDecls = (const DeclID *)Blob.data();
2860 F.NumFileSortedDecls = Record[0];
2863 case SOURCE_LOCATION_OFFSETS: {
2864 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
2865 F.LocalNumSLocEntries = Record[0];
2866 unsigned SLocSpaceSize = Record[1];
2867 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2868 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2870 // Make our entry in the range map. BaseID is negative and growing, so
2871 // we invert it. Because we invert it, though, we need the other end of
2873 unsigned RangeStart =
2874 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2875 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2876 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2878 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2879 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2880 GlobalSLocOffsetMap.insert(
2881 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2882 - SLocSpaceSize,&F));
2884 // Initialize the remapping table.
2885 // Invalid stays invalid.
2886 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
2887 // This module. Base was 2 when being compiled.
2888 F.SLocRemap.insertOrReplace(std::make_pair(2U,
2889 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2891 TotalNumSLocEntries += F.LocalNumSLocEntries;
2895 case MODULE_OFFSET_MAP: {
2896 // Additional remapping information.
2897 const unsigned char *Data = (const unsigned char*)Blob.data();
2898 const unsigned char *DataEnd = Data + Blob.size();
2900 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2901 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2902 F.SLocRemap.insert(std::make_pair(0U, 0));
2903 F.SLocRemap.insert(std::make_pair(2U, 1));
2906 // Continuous range maps we may be updating in our module.
2907 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2908 ContinuousRangeMap<uint32_t, int, 2>::Builder
2909 IdentifierRemap(F.IdentifierRemap);
2910 ContinuousRangeMap<uint32_t, int, 2>::Builder
2911 MacroRemap(F.MacroRemap);
2912 ContinuousRangeMap<uint32_t, int, 2>::Builder
2913 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2914 ContinuousRangeMap<uint32_t, int, 2>::Builder
2915 SubmoduleRemap(F.SubmoduleRemap);
2916 ContinuousRangeMap<uint32_t, int, 2>::Builder
2917 SelectorRemap(F.SelectorRemap);
2918 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2919 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2921 while(Data < DataEnd) {
2922 using namespace llvm::support;
2923 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
2924 StringRef Name = StringRef((const char*)Data, Len);
2926 ModuleFile *OM = ModuleMgr.lookup(Name);
2928 Error("SourceLocation remap refers to unknown module");
2932 uint32_t SLocOffset =
2933 endian::readNext<uint32_t, little, unaligned>(Data);
2934 uint32_t IdentifierIDOffset =
2935 endian::readNext<uint32_t, little, unaligned>(Data);
2936 uint32_t MacroIDOffset =
2937 endian::readNext<uint32_t, little, unaligned>(Data);
2938 uint32_t PreprocessedEntityIDOffset =
2939 endian::readNext<uint32_t, little, unaligned>(Data);
2940 uint32_t SubmoduleIDOffset =
2941 endian::readNext<uint32_t, little, unaligned>(Data);
2942 uint32_t SelectorIDOffset =
2943 endian::readNext<uint32_t, little, unaligned>(Data);
2944 uint32_t DeclIDOffset =
2945 endian::readNext<uint32_t, little, unaligned>(Data);
2946 uint32_t TypeIndexOffset =
2947 endian::readNext<uint32_t, little, unaligned>(Data);
2949 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2950 SLocRemap.insert(std::make_pair(SLocOffset,
2951 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2952 IdentifierRemap.insert(
2953 std::make_pair(IdentifierIDOffset,
2954 OM->BaseIdentifierID - IdentifierIDOffset));
2955 MacroRemap.insert(std::make_pair(MacroIDOffset,
2956 OM->BaseMacroID - MacroIDOffset));
2957 PreprocessedEntityRemap.insert(
2958 std::make_pair(PreprocessedEntityIDOffset,
2959 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2960 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2961 OM->BaseSubmoduleID - SubmoduleIDOffset));
2962 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2963 OM->BaseSelectorID - SelectorIDOffset));
2964 DeclRemap.insert(std::make_pair(DeclIDOffset,
2965 OM->BaseDeclID - DeclIDOffset));
2967 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2968 OM->BaseTypeIndex - TypeIndexOffset));
2970 // Global -> local mappings.
2971 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2976 case SOURCE_MANAGER_LINE_TABLE:
2977 if (ParseLineTable(F, Record))
2981 case SOURCE_LOCATION_PRELOADS: {
2982 // Need to transform from the local view (1-based IDs) to the global view,
2983 // which is based off F.SLocEntryBaseID.
2984 if (!F.PreloadSLocEntries.empty()) {
2985 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2989 F.PreloadSLocEntries.swap(Record);
2993 case EXT_VECTOR_DECLS:
2994 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2995 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2999 if (Record.size() % 3 != 0) {
3000 Error("Invalid VTABLE_USES record");
3004 // Later tables overwrite earlier ones.
3005 // FIXME: Modules will have some trouble with this. This is clearly not
3006 // the right way to do this.
3009 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3010 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3011 VTableUses.push_back(
3012 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3013 VTableUses.push_back(Record[Idx++]);
3017 case DYNAMIC_CLASSES:
3018 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3019 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3022 case PENDING_IMPLICIT_INSTANTIATIONS:
3023 if (PendingInstantiations.size() % 2 != 0) {
3024 Error("Invalid existing PendingInstantiations");
3028 if (Record.size() % 2 != 0) {
3029 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3033 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3034 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3035 PendingInstantiations.push_back(
3036 ReadSourceLocation(F, Record, I).getRawEncoding());
3040 case SEMA_DECL_REFS:
3041 if (Record.size() != 2) {
3042 Error("Invalid SEMA_DECL_REFS block");
3045 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3046 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3049 case PPD_ENTITIES_OFFSETS: {
3050 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3051 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3052 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3054 unsigned LocalBasePreprocessedEntityID = Record[0];
3056 unsigned StartingID;
3057 if (!PP.getPreprocessingRecord())
3058 PP.createPreprocessingRecord();
3059 if (!PP.getPreprocessingRecord()->getExternalSource())
3060 PP.getPreprocessingRecord()->SetExternalSource(*this);
3062 = PP.getPreprocessingRecord()
3063 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3064 F.BasePreprocessedEntityID = StartingID;
3066 if (F.NumPreprocessedEntities > 0) {
3067 // Introduce the global -> local mapping for preprocessed entities in
3069 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3071 // Introduce the local -> global mapping for preprocessed entities in
3073 F.PreprocessedEntityRemap.insertOrReplace(
3074 std::make_pair(LocalBasePreprocessedEntityID,
3075 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3081 case DECL_UPDATE_OFFSETS: {
3082 if (Record.size() % 2 != 0) {
3083 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
3086 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3087 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3088 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3090 // If we've already loaded the decl, perform the updates when we finish
3091 // loading this block.
3092 if (Decl *D = GetExistingDecl(ID))
3093 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3098 case DECL_REPLACEMENTS: {
3099 if (Record.size() % 3 != 0) {
3100 Error("invalid DECL_REPLACEMENTS block in AST file");
3103 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3104 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3105 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3109 case OBJC_CATEGORIES_MAP: {
3110 if (F.LocalNumObjCCategoriesInMap != 0) {
3111 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
3115 F.LocalNumObjCCategoriesInMap = Record[0];
3116 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3120 case OBJC_CATEGORIES:
3121 F.ObjCCategories.swap(Record);
3124 case CXX_BASE_SPECIFIER_OFFSETS: {
3125 if (F.LocalNumCXXBaseSpecifiers != 0) {
3126 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
3130 F.LocalNumCXXBaseSpecifiers = Record[0];
3131 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
3132 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3136 case DIAG_PRAGMA_MAPPINGS:
3137 if (F.PragmaDiagMappings.empty())
3138 F.PragmaDiagMappings.swap(Record);
3140 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3141 Record.begin(), Record.end());
3144 case CUDA_SPECIAL_DECL_REFS:
3145 // Later tables overwrite earlier ones.
3146 // FIXME: Modules will have trouble with this.
3147 CUDASpecialDeclRefs.clear();
3148 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3149 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3152 case HEADER_SEARCH_TABLE: {
3153 F.HeaderFileInfoTableData = Blob.data();
3154 F.LocalNumHeaderFileInfos = Record[1];
3156 F.HeaderFileInfoTable
3157 = HeaderFileInfoLookupTable::Create(
3158 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3159 (const unsigned char *)F.HeaderFileInfoTableData,
3160 HeaderFileInfoTrait(*this, F,
3161 &PP.getHeaderSearchInfo(),
3162 Blob.data() + Record[2]));
3164 PP.getHeaderSearchInfo().SetExternalSource(this);
3165 if (!PP.getHeaderSearchInfo().getExternalLookup())
3166 PP.getHeaderSearchInfo().SetExternalLookup(this);
3171 case FP_PRAGMA_OPTIONS:
3172 // Later tables overwrite earlier ones.
3173 FPPragmaOptions.swap(Record);
3176 case OPENCL_EXTENSIONS:
3177 // Later tables overwrite earlier ones.
3178 OpenCLExtensions.swap(Record);
3181 case TENTATIVE_DEFINITIONS:
3182 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3183 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3186 case KNOWN_NAMESPACES:
3187 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3188 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3191 case UNDEFINED_BUT_USED:
3192 if (UndefinedButUsed.size() % 2 != 0) {
3193 Error("Invalid existing UndefinedButUsed");
3197 if (Record.size() % 2 != 0) {
3198 Error("invalid undefined-but-used record");
3201 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3202 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3203 UndefinedButUsed.push_back(
3204 ReadSourceLocation(F, Record, I).getRawEncoding());
3208 case IMPORTED_MODULES: {
3209 if (F.Kind != MK_Module) {
3210 // If we aren't loading a module (which has its own exports), make
3211 // all of the imported modules visible.
3212 // FIXME: Deal with macros-only imports.
3213 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3214 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3215 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3217 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3223 case LOCAL_REDECLARATIONS: {
3224 F.RedeclarationChains.swap(Record);
3228 case LOCAL_REDECLARATIONS_MAP: {
3229 if (F.LocalNumRedeclarationsInMap != 0) {
3230 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
3234 F.LocalNumRedeclarationsInMap = Record[0];
3235 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
3239 case MERGED_DECLARATIONS: {
3240 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3241 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3242 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3243 for (unsigned N = Record[Idx++]; N > 0; --N)
3244 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3249 case MACRO_OFFSET: {
3250 if (F.LocalNumMacros != 0) {
3251 Error("duplicate MACRO_OFFSET record in AST file");
3254 F.MacroOffsets = (const uint32_t *)Blob.data();
3255 F.LocalNumMacros = Record[0];
3256 unsigned LocalBaseMacroID = Record[1];
3257 F.BaseMacroID = getTotalNumMacros();
3259 if (F.LocalNumMacros > 0) {
3260 // Introduce the global -> local mapping for macros within this module.
3261 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3263 // Introduce the local -> global mapping for macros within this module.
3264 F.MacroRemap.insertOrReplace(
3265 std::make_pair(LocalBaseMacroID,
3266 F.BaseMacroID - LocalBaseMacroID));
3268 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3274 // FIXME: Not used yet.
3278 case LATE_PARSED_TEMPLATE: {
3279 LateParsedTemplates.append(Record.begin(), Record.end());
3283 case OPTIMIZE_PRAGMA_OPTIONS:
3284 if (Record.size() != 1) {
3285 Error("invalid pragma optimize record");
3288 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3294 /// \brief Move the given method to the back of the global list of methods.
3295 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3296 // Find the entry for this selector in the method pool.
3297 Sema::GlobalMethodPool::iterator Known
3298 = S.MethodPool.find(Method->getSelector());
3299 if (Known == S.MethodPool.end())
3302 // Retrieve the appropriate method list.
3303 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3304 : Known->second.second;
3306 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
3308 if (List->Method == Method) {
3316 if (List->getNext())
3317 List->Method = List->getNext()->Method;
3319 List->Method = Method;
3323 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3324 bool FromFinalization) {
3325 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
3326 for (Decl *D : Names.HiddenDecls) {
3327 bool wasHidden = D->Hidden;
3330 if (wasHidden && SemaObj) {
3331 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3332 moveMethodToBackOfGlobalList(*SemaObj, Method);
3337 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3338 "nothing to make visible?");
3339 for (const auto &Macro : Names.HiddenMacros)
3340 installImportedMacro(Macro.first, Macro.second, Owner, FromFinalization);
3343 void ASTReader::makeModuleVisible(Module *Mod,
3344 Module::NameVisibilityKind NameVisibility,
3345 SourceLocation ImportLoc,
3347 llvm::SmallPtrSet<Module *, 4> Visited;
3348 SmallVector<Module *, 4> Stack;
3349 Stack.push_back(Mod);
3350 while (!Stack.empty()) {
3351 Mod = Stack.pop_back_val();
3353 if (NameVisibility <= Mod->NameVisibility) {
3354 // This module already has this level of visibility (or greater), so
3355 // there is nothing more to do.
3359 if (!Mod->isAvailable()) {
3360 // Modules that aren't available cannot be made visible.
3364 // Update the module's name visibility.
3365 if (NameVisibility >= Module::MacrosVisible &&
3366 Mod->NameVisibility < Module::MacrosVisible)
3367 Mod->MacroVisibilityLoc = ImportLoc;
3368 Mod->NameVisibility = NameVisibility;
3370 // If we've already deserialized any names from this module,
3371 // mark them as visible.
3372 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3373 if (Hidden != HiddenNamesMap.end()) {
3374 auto HiddenNames = std::move(*Hidden);
3375 HiddenNamesMap.erase(Hidden);
3376 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3377 /*FromFinalization*/false);
3378 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3379 "making names visible added hidden names");
3382 // Push any exported modules onto the stack to be marked as visible.
3383 SmallVector<Module *, 16> Exports;
3384 Mod->getExportedModules(Exports);
3385 for (SmallVectorImpl<Module *>::iterator
3386 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3387 Module *Exported = *I;
3388 if (Visited.insert(Exported))
3389 Stack.push_back(Exported);
3392 // Detect any conflicts.
3394 assert(ImportLoc.isValid() && "Missing import location");
3395 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3396 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3397 Diag(ImportLoc, diag::warn_module_conflict)
3398 << Mod->getFullModuleName()
3399 << Mod->Conflicts[I].Other->getFullModuleName()
3400 << Mod->Conflicts[I].Message;
3401 // FIXME: Need note where the other module was imported.
3408 bool ASTReader::loadGlobalIndex() {
3412 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3413 !Context.getLangOpts().Modules)
3416 // Try to load the global index.
3417 TriedLoadingGlobalIndex = true;
3418 StringRef ModuleCachePath
3419 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3420 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
3421 = GlobalModuleIndex::readIndex(ModuleCachePath);
3425 GlobalIndex.reset(Result.first);
3426 ModuleMgr.setGlobalIndex(GlobalIndex.get());
3430 bool ASTReader::isGlobalIndexUnavailable() const {
3431 return Context.getLangOpts().Modules && UseGlobalIndex &&
3432 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3435 static void updateModuleTimestamp(ModuleFile &MF) {
3436 // Overwrite the timestamp file contents so that file's mtime changes.
3437 std::string TimestampFilename = MF.getTimestampFilename();
3438 std::string ErrorInfo;
3439 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
3440 llvm::sys::fs::F_Text);
3441 if (!ErrorInfo.empty())
3443 OS << "Timestamp file\n";
3446 ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3448 SourceLocation ImportLoc,
3449 unsigned ClientLoadCapabilities) {
3450 llvm::SaveAndRestore<SourceLocation>
3451 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3453 // Defer any pending actions until we get to the end of reading the AST file.
3454 Deserializing AnASTFile(this);
3456 // Bump the generation number.
3457 unsigned PreviousGeneration = incrementGeneration(Context);
3459 unsigned NumModules = ModuleMgr.size();
3460 SmallVector<ImportedModule, 4> Loaded;
3461 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3462 /*ImportedBy=*/nullptr, Loaded,
3464 ClientLoadCapabilities)) {
3468 case VersionMismatch:
3469 case ConfigurationMismatch:
3471 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3472 for (const ImportedModule &IM : Loaded)
3473 LoadedSet.insert(IM.Mod);
3475 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3477 Context.getLangOpts().Modules
3478 ? &PP.getHeaderSearchInfo().getModuleMap()
3481 // If we find that any modules are unusable, the global index is going
3482 // to be out-of-date. Just remove it.
3483 GlobalIndex.reset();
3484 ModuleMgr.setGlobalIndex(nullptr);
3491 // Here comes stuff that we only do once the entire chain is loaded.
3493 // Load the AST blocks of all of the modules that we loaded.
3494 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3495 MEnd = Loaded.end();
3497 ModuleFile &F = *M->Mod;
3499 // Read the AST block.
3500 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3503 // Once read, set the ModuleFile bit base offset and update the size in
3504 // bits of all files we've seen.
3505 F.GlobalBitOffset = TotalModulesSizeInBits;
3506 TotalModulesSizeInBits += F.SizeInBits;
3507 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3509 // Preload SLocEntries.
3510 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3511 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3512 // Load it through the SourceManager and don't call ReadSLocEntry()
3513 // directly because the entry may have already been loaded in which case
3514 // calling ReadSLocEntry() directly would trigger an assertion in
3516 SourceMgr.getLoadedSLocEntryByID(Index);
3520 // Setup the import locations and notify the module manager that we've
3521 // committed to these module files.
3522 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3523 MEnd = Loaded.end();
3525 ModuleFile &F = *M->Mod;
3527 ModuleMgr.moduleFileAccepted(&F);
3529 // Set the import location.
3530 F.DirectImportLoc = ImportLoc;
3532 F.ImportLoc = M->ImportLoc;
3534 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3535 M->ImportLoc.getRawEncoding());
3538 // Mark all of the identifiers in the identifier table as being out of date,
3539 // so that various accessors know to check the loaded modules when the
3540 // identifier is used.
3541 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3542 IdEnd = PP.getIdentifierTable().end();
3544 Id->second->setOutOfDate(true);
3546 // Resolve any unresolved module exports.
3547 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3548 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
3549 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3550 Module *ResolvedMod = getSubmodule(GlobalID);
3552 switch (Unresolved.Kind) {
3553 case UnresolvedModuleRef::Conflict:
3555 Module::Conflict Conflict;
3556 Conflict.Other = ResolvedMod;
3557 Conflict.Message = Unresolved.String.str();
3558 Unresolved.Mod->Conflicts.push_back(Conflict);
3562 case UnresolvedModuleRef::Import:
3564 Unresolved.Mod->Imports.push_back(ResolvedMod);
3567 case UnresolvedModuleRef::Export:
3568 if (ResolvedMod || Unresolved.IsWildcard)
3569 Unresolved.Mod->Exports.push_back(
3570 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3574 UnresolvedModuleRefs.clear();
3576 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3577 // Might be unnecessary as use declarations are only used to build the
3580 InitializeContext();
3585 if (DeserializationListener)
3586 DeserializationListener->ReaderInitialized(this);
3588 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3589 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3590 PrimaryModule.OriginalSourceFileID
3591 = FileID::get(PrimaryModule.SLocEntryBaseID
3592 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3594 // If this AST file is a precompiled preamble, then set the
3595 // preamble file ID of the source manager to the file source file
3596 // from which the preamble was built.
3597 if (Type == MK_Preamble) {
3598 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3599 } else if (Type == MK_MainFile) {
3600 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3604 // For any Objective-C class definitions we have already loaded, make sure
3605 // that we load any additional categories.
3606 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3607 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3608 ObjCClassesLoaded[I],
3609 PreviousGeneration);
3612 if (PP.getHeaderSearchInfo()
3613 .getHeaderSearchOpts()
3614 .ModulesValidateOncePerBuildSession) {
3615 // Now we are certain that the module and all modules it depends on are
3616 // up to date. Create or update timestamp files for modules that are
3617 // located in the module cache (not for PCH files that could be anywhere
3618 // in the filesystem).
3619 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3620 ImportedModule &M = Loaded[I];
3621 if (M.Mod->Kind == MK_Module) {
3622 updateModuleTimestamp(*M.Mod);
3630 ASTReader::ASTReadResult
3631 ASTReader::ReadASTCore(StringRef FileName,
3633 SourceLocation ImportLoc,
3634 ModuleFile *ImportedBy,
3635 SmallVectorImpl<ImportedModule> &Loaded,
3636 off_t ExpectedSize, time_t ExpectedModTime,
3637 unsigned ClientLoadCapabilities) {
3639 std::string ErrorStr;
3640 ModuleManager::AddModuleResult AddResult
3641 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3642 getGeneration(), ExpectedSize, ExpectedModTime,
3645 switch (AddResult) {
3646 case ModuleManager::AlreadyLoaded:
3649 case ModuleManager::NewlyLoaded:
3650 // Load module file below.
3653 case ModuleManager::Missing:
3654 // The module file was missing; if the client handle handle, that, return
3656 if (ClientLoadCapabilities & ARR_Missing)
3659 // Otherwise, return an error.
3661 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3667 case ModuleManager::OutOfDate:
3668 // We couldn't load the module file because it is out-of-date. If the
3669 // client can handle out-of-date, return it.
3670 if (ClientLoadCapabilities & ARR_OutOfDate)
3673 // Otherwise, return an error.
3675 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3682 assert(M && "Missing module file");
3684 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3686 if (FileName != "-") {
3687 CurrentDir = llvm::sys::path::parent_path(FileName);
3688 if (CurrentDir.empty()) CurrentDir = ".";
3692 BitstreamCursor &Stream = F.Stream;
3693 Stream.init(F.StreamFile);
3694 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3696 // Sniff for the signature.
3697 if (Stream.Read(8) != 'C' ||
3698 Stream.Read(8) != 'P' ||
3699 Stream.Read(8) != 'C' ||
3700 Stream.Read(8) != 'H') {
3701 Diag(diag::err_not_a_pch_file) << FileName;
3705 // This is used for compatibility with older PCH formats.
3706 bool HaveReadControlBlock = false;
3709 llvm::BitstreamEntry Entry = Stream.advance();
3711 switch (Entry.Kind) {
3712 case llvm::BitstreamEntry::Error:
3713 case llvm::BitstreamEntry::EndBlock:
3714 case llvm::BitstreamEntry::Record:
3715 Error("invalid record at top-level of AST file");
3718 case llvm::BitstreamEntry::SubBlock:
3722 // We only know the control subblock ID.
3724 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3725 if (Stream.ReadBlockInfoBlock()) {
3726 Error("malformed BlockInfoBlock in AST file");
3730 case CONTROL_BLOCK_ID:
3731 HaveReadControlBlock = true;
3732 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
3736 case Failure: return Failure;
3737 case Missing: return Missing;
3738 case OutOfDate: return OutOfDate;
3739 case VersionMismatch: return VersionMismatch;
3740 case ConfigurationMismatch: return ConfigurationMismatch;
3741 case HadErrors: return HadErrors;
3745 if (!HaveReadControlBlock) {
3746 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3747 Diag(diag::err_pch_version_too_old);
3748 return VersionMismatch;
3751 // Record that we've loaded this module.
3752 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3756 if (Stream.SkipBlock()) {
3757 Error("malformed block record in AST file");
3767 void ASTReader::InitializeContext() {
3768 // If there's a listener, notify them that we "read" the translation unit.
3769 if (DeserializationListener)
3770 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3771 Context.getTranslationUnitDecl());
3773 // FIXME: Find a better way to deal with collisions between these
3774 // built-in types. Right now, we just ignore the problem.
3776 // Load the special types.
3777 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3778 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3779 if (!Context.CFConstantStringTypeDecl)
3780 Context.setCFConstantStringType(GetType(String));
3783 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3784 QualType FileType = GetType(File);
3785 if (FileType.isNull()) {
3786 Error("FILE type is NULL");
3790 if (!Context.FILEDecl) {
3791 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3792 Context.setFILEDecl(Typedef->getDecl());
3794 const TagType *Tag = FileType->getAs<TagType>();
3796 Error("Invalid FILE type in AST file");
3799 Context.setFILEDecl(Tag->getDecl());
3804 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3805 QualType Jmp_bufType = GetType(Jmp_buf);
3806 if (Jmp_bufType.isNull()) {
3807 Error("jmp_buf type is NULL");
3811 if (!Context.jmp_bufDecl) {
3812 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3813 Context.setjmp_bufDecl(Typedef->getDecl());
3815 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3817 Error("Invalid jmp_buf type in AST file");
3820 Context.setjmp_bufDecl(Tag->getDecl());
3825 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3826 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3827 if (Sigjmp_bufType.isNull()) {
3828 Error("sigjmp_buf type is NULL");
3832 if (!Context.sigjmp_bufDecl) {
3833 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3834 Context.setsigjmp_bufDecl(Typedef->getDecl());
3836 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3837 assert(Tag && "Invalid sigjmp_buf type in AST file");
3838 Context.setsigjmp_bufDecl(Tag->getDecl());
3843 if (unsigned ObjCIdRedef
3844 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3845 if (Context.ObjCIdRedefinitionType.isNull())
3846 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3849 if (unsigned ObjCClassRedef
3850 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3851 if (Context.ObjCClassRedefinitionType.isNull())
3852 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3855 if (unsigned ObjCSelRedef
3856 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3857 if (Context.ObjCSelRedefinitionType.isNull())
3858 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3861 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3862 QualType Ucontext_tType = GetType(Ucontext_t);
3863 if (Ucontext_tType.isNull()) {
3864 Error("ucontext_t type is NULL");
3868 if (!Context.ucontext_tDecl) {
3869 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3870 Context.setucontext_tDecl(Typedef->getDecl());
3872 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3873 assert(Tag && "Invalid ucontext_t type in AST file");
3874 Context.setucontext_tDecl(Tag->getDecl());
3880 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3882 // If there were any CUDA special declarations, deserialize them.
3883 if (!CUDASpecialDeclRefs.empty()) {
3884 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3885 Context.setcudaConfigureCallDecl(
3886 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3889 // Re-export any modules that were imported by a non-module AST file.
3890 // FIXME: This does not make macro-only imports visible again. It also doesn't
3891 // make #includes mapped to module imports visible.
3892 for (auto &Import : ImportedModules) {
3893 if (Module *Imported = getSubmodule(Import.ID))
3894 makeModuleVisible(Imported, Module::AllVisible,
3895 /*ImportLoc=*/Import.ImportLoc,
3896 /*Complain=*/false);
3898 ImportedModules.clear();
3901 void ASTReader::finalizeForWriting() {
3902 while (!HiddenNamesMap.empty()) {
3903 auto HiddenNames = std::move(*HiddenNamesMap.begin());
3904 HiddenNamesMap.erase(HiddenNamesMap.begin());
3905 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3906 /*FromFinalization*/true);
3910 /// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3911 /// cursor into the start of the given block ID, returning false on success and
3912 /// true on failure.
3913 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3915 llvm::BitstreamEntry Entry = Cursor.advance();
3916 switch (Entry.Kind) {
3917 case llvm::BitstreamEntry::Error:
3918 case llvm::BitstreamEntry::EndBlock:
3921 case llvm::BitstreamEntry::Record:
3922 // Ignore top-level records.
3923 Cursor.skipRecord(Entry.ID);
3926 case llvm::BitstreamEntry::SubBlock:
3927 if (Entry.ID == BlockID) {
3928 if (Cursor.EnterSubBlock(BlockID))
3934 if (Cursor.SkipBlock())
3940 /// \brief Retrieve the name of the original source file name
3941 /// directly from the AST file, without actually loading the AST
3943 std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3944 FileManager &FileMgr,
3945 DiagnosticsEngine &Diags) {
3946 // Open the AST file.
3948 std::unique_ptr<llvm::MemoryBuffer> Buffer;
3949 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3951 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3952 return std::string();
3955 // Initialize the stream
3956 llvm::BitstreamReader StreamFile;
3957 BitstreamCursor Stream;
3958 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3959 (const unsigned char *)Buffer->getBufferEnd());
3960 Stream.init(StreamFile);
3962 // Sniff for the signature.
3963 if (Stream.Read(8) != 'C' ||
3964 Stream.Read(8) != 'P' ||
3965 Stream.Read(8) != 'C' ||
3966 Stream.Read(8) != 'H') {
3967 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3968 return std::string();
3971 // Scan for the CONTROL_BLOCK_ID block.
3972 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
3973 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3974 return std::string();
3977 // Scan for ORIGINAL_FILE inside the control block.
3980 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3981 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3982 return std::string();
3984 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3985 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3986 return std::string();
3991 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3997 class SimplePCHValidator : public ASTReaderListener {
3998 const LangOptions &ExistingLangOpts;
3999 const TargetOptions &ExistingTargetOpts;
4000 const PreprocessorOptions &ExistingPPOpts;
4001 FileManager &FileMgr;
4004 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4005 const TargetOptions &ExistingTargetOpts,
4006 const PreprocessorOptions &ExistingPPOpts,
4007 FileManager &FileMgr)
4008 : ExistingLangOpts(ExistingLangOpts),
4009 ExistingTargetOpts(ExistingTargetOpts),
4010 ExistingPPOpts(ExistingPPOpts),
4015 bool ReadLanguageOptions(const LangOptions &LangOpts,
4016 bool Complain) override {
4017 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr);
4019 bool ReadTargetOptions(const TargetOptions &TargetOpts,
4020 bool Complain) override {
4021 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
4023 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4025 std::string &SuggestedPredefines) override {
4026 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
4027 SuggestedPredefines, ExistingLangOpts);
4032 bool ASTReader::readASTFileControlBlock(StringRef Filename,
4033 FileManager &FileMgr,
4034 ASTReaderListener &Listener) {
4035 // Open the AST file.
4037 std::unique_ptr<llvm::MemoryBuffer> Buffer;
4038 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
4043 // Initialize the stream
4044 llvm::BitstreamReader StreamFile;
4045 BitstreamCursor Stream;
4046 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
4047 (const unsigned char *)Buffer->getBufferEnd());
4048 Stream.init(StreamFile);
4050 // Sniff for the signature.
4051 if (Stream.Read(8) != 'C' ||
4052 Stream.Read(8) != 'P' ||
4053 Stream.Read(8) != 'C' ||
4054 Stream.Read(8) != 'H') {
4058 // Scan for the CONTROL_BLOCK_ID block.
4059 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4062 bool NeedsInputFiles = Listener.needsInputFileVisitation();
4063 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
4064 BitstreamCursor InputFilesCursor;
4065 if (NeedsInputFiles) {
4066 InputFilesCursor = Stream;
4067 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4070 // Read the abbreviations
4072 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4073 unsigned Code = InputFilesCursor.ReadCode();
4075 // We expect all abbrevs to be at the start of the block.
4076 if (Code != llvm::bitc::DEFINE_ABBREV) {
4077 InputFilesCursor.JumpToBit(Offset);
4080 InputFilesCursor.ReadAbbrevRecord();
4084 // Scan for ORIGINAL_FILE inside the control block.
4087 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4088 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4091 if (Entry.Kind != llvm::BitstreamEntry::Record)
4096 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4097 switch ((ControlRecordTypes)RecCode) {
4099 if (Record[0] != VERSION_MAJOR)
4102 if (Listener.ReadFullVersionInformation(Blob))
4108 Listener.ReadModuleName(Blob);
4110 case MODULE_MAP_FILE:
4111 Listener.ReadModuleMapFile(Blob);
4113 case LANGUAGE_OPTIONS:
4114 if (ParseLanguageOptions(Record, false, Listener))
4118 case TARGET_OPTIONS:
4119 if (ParseTargetOptions(Record, false, Listener))
4123 case DIAGNOSTIC_OPTIONS:
4124 if (ParseDiagnosticOptions(Record, false, Listener))
4128 case FILE_SYSTEM_OPTIONS:
4129 if (ParseFileSystemOptions(Record, false, Listener))
4133 case HEADER_SEARCH_OPTIONS:
4134 if (ParseHeaderSearchOptions(Record, false, Listener))
4138 case PREPROCESSOR_OPTIONS: {
4139 std::string IgnoredSuggestedPredefines;
4140 if (ParsePreprocessorOptions(Record, false, Listener,
4141 IgnoredSuggestedPredefines))
4146 case INPUT_FILE_OFFSETS: {
4147 if (!NeedsInputFiles)
4150 unsigned NumInputFiles = Record[0];
4151 unsigned NumUserFiles = Record[1];
4152 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4153 for (unsigned I = 0; I != NumInputFiles; ++I) {
4154 // Go find this input file.
4155 bool isSystemFile = I >= NumUserFiles;
4157 if (isSystemFile && !NeedsSystemInputFiles)
4158 break; // the rest are system input files
4160 BitstreamCursor &Cursor = InputFilesCursor;
4161 SavedStreamPosition SavedPosition(Cursor);
4162 Cursor.JumpToBit(InputFileOffs[I]);
4164 unsigned Code = Cursor.ReadCode();
4167 bool shouldContinue = false;
4168 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4170 bool Overridden = static_cast<bool>(Record[3]);
4171 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
4174 if (!shouldContinue)
4181 // No other validation to perform.
4188 bool ASTReader::isAcceptableASTFile(StringRef Filename,
4189 FileManager &FileMgr,
4190 const LangOptions &LangOpts,
4191 const TargetOptions &TargetOpts,
4192 const PreprocessorOptions &PPOpts) {
4193 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4194 return !readASTFileControlBlock(Filename, FileMgr, validator);
4197 ASTReader::ASTReadResult
4198 ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
4199 // Enter the submodule block.
4200 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4201 Error("malformed submodule block record in AST file");
4205 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4207 Module *CurrentModule = nullptr;
4210 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4212 switch (Entry.Kind) {
4213 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4214 case llvm::BitstreamEntry::Error:
4215 Error("malformed block record in AST file");
4217 case llvm::BitstreamEntry::EndBlock:
4219 case llvm::BitstreamEntry::Record:
4220 // The interesting case.
4227 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
4228 default: // Default behavior: ignore.
4231 case SUBMODULE_DEFINITION: {
4233 Error("missing submodule metadata record at beginning of block");
4237 if (Record.size() < 8) {
4238 Error("malformed module definition");
4242 StringRef Name = Blob;
4244 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4245 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4246 bool IsFramework = Record[Idx++];
4247 bool IsExplicit = Record[Idx++];
4248 bool IsSystem = Record[Idx++];
4249 bool IsExternC = Record[Idx++];
4250 bool InferSubmodules = Record[Idx++];
4251 bool InferExplicitSubmodules = Record[Idx++];
4252 bool InferExportWildcard = Record[Idx++];
4253 bool ConfigMacrosExhaustive = Record[Idx++];
4255 Module *ParentModule = nullptr;
4256 const FileEntry *ModuleMap = nullptr;
4258 ParentModule = getSubmodule(Parent);
4259 ModuleMap = ParentModule->ModuleMap;
4262 if (!F.ModuleMapPath.empty())
4263 ModuleMap = FileMgr.getFile(F.ModuleMapPath);
4265 // Retrieve this (sub)module from the module map, creating it if
4267 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, ModuleMap,
4270 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4271 if (GlobalIndex >= SubmodulesLoaded.size() ||
4272 SubmodulesLoaded[GlobalIndex]) {
4273 Error("too many submodules");
4277 if (!ParentModule) {
4278 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4279 if (CurFile != F.File) {
4280 if (!Diags.isDiagnosticInFlight()) {
4281 Diag(diag::err_module_file_conflict)
4282 << CurrentModule->getTopLevelModuleName()
4283 << CurFile->getName()
4284 << F.File->getName();
4290 CurrentModule->setASTFile(F.File);
4293 CurrentModule->IsFromModuleFile = true;
4294 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
4295 CurrentModule->IsExternC = IsExternC;
4296 CurrentModule->InferSubmodules = InferSubmodules;
4297 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4298 CurrentModule->InferExportWildcard = InferExportWildcard;
4299 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
4300 if (DeserializationListener)
4301 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4303 SubmodulesLoaded[GlobalIndex] = CurrentModule;
4305 // Clear out data that will be replaced by what is the module file.
4306 CurrentModule->LinkLibraries.clear();
4307 CurrentModule->ConfigMacros.clear();
4308 CurrentModule->UnresolvedConflicts.clear();
4309 CurrentModule->Conflicts.clear();
4313 case SUBMODULE_UMBRELLA_HEADER: {
4315 Error("missing submodule metadata record at beginning of block");
4322 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
4323 if (!CurrentModule->getUmbrellaHeader())
4324 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4325 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
4326 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4327 Error("mismatched umbrella headers in submodule");
4334 case SUBMODULE_HEADER: {
4336 Error("missing submodule metadata record at beginning of block");
4343 // We lazily associate headers with their modules via the HeaderInfoTable.
4344 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4345 // of complete filenames or remove it entirely.
4349 case SUBMODULE_EXCLUDED_HEADER: {
4351 Error("missing submodule metadata record at beginning of block");
4358 // We lazily associate headers with their modules via the HeaderInfoTable.
4359 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4360 // of complete filenames or remove it entirely.
4364 case SUBMODULE_PRIVATE_HEADER: {
4366 Error("missing submodule metadata record at beginning of block");
4373 // We lazily associate headers with their modules via the HeaderInfoTable.
4374 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4375 // of complete filenames or remove it entirely.
4379 case SUBMODULE_TOPHEADER: {
4381 Error("missing submodule metadata record at beginning of block");
4388 CurrentModule->addTopHeaderFilename(Blob);
4392 case SUBMODULE_UMBRELLA_DIR: {
4394 Error("missing submodule metadata record at beginning of block");
4401 if (const DirectoryEntry *Umbrella
4402 = PP.getFileManager().getDirectory(Blob)) {
4403 if (!CurrentModule->getUmbrellaDir())
4404 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4405 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
4406 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4407 Error("mismatched umbrella directories in submodule");
4414 case SUBMODULE_METADATA: {
4416 Error("submodule metadata record not at beginning of block");
4421 F.BaseSubmoduleID = getTotalNumSubmodules();
4422 F.LocalNumSubmodules = Record[0];
4423 unsigned LocalBaseSubmoduleID = Record[1];
4424 if (F.LocalNumSubmodules > 0) {
4425 // Introduce the global -> local mapping for submodules within this
4427 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4429 // Introduce the local -> global mapping for submodules within this
4431 F.SubmoduleRemap.insertOrReplace(
4432 std::make_pair(LocalBaseSubmoduleID,
4433 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4435 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4440 case SUBMODULE_IMPORTS: {
4442 Error("missing submodule metadata record at beginning of block");
4449 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
4450 UnresolvedModuleRef Unresolved;
4451 Unresolved.File = &F;
4452 Unresolved.Mod = CurrentModule;
4453 Unresolved.ID = Record[Idx];
4454 Unresolved.Kind = UnresolvedModuleRef::Import;
4455 Unresolved.IsWildcard = false;
4456 UnresolvedModuleRefs.push_back(Unresolved);
4461 case SUBMODULE_EXPORTS: {
4463 Error("missing submodule metadata record at beginning of block");
4470 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
4471 UnresolvedModuleRef Unresolved;
4472 Unresolved.File = &F;
4473 Unresolved.Mod = CurrentModule;
4474 Unresolved.ID = Record[Idx];
4475 Unresolved.Kind = UnresolvedModuleRef::Export;
4476 Unresolved.IsWildcard = Record[Idx + 1];
4477 UnresolvedModuleRefs.push_back(Unresolved);
4480 // Once we've loaded the set of exports, there's no reason to keep
4481 // the parsed, unresolved exports around.
4482 CurrentModule->UnresolvedExports.clear();
4485 case SUBMODULE_REQUIRES: {
4487 Error("missing submodule metadata record at beginning of block");
4494 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
4495 Context.getTargetInfo());
4499 case SUBMODULE_LINK_LIBRARY:
4501 Error("missing submodule metadata record at beginning of block");
4508 CurrentModule->LinkLibraries.push_back(
4509 Module::LinkLibrary(Blob, Record[0]));
4512 case SUBMODULE_CONFIG_MACRO:
4514 Error("missing submodule metadata record at beginning of block");
4521 CurrentModule->ConfigMacros.push_back(Blob.str());
4524 case SUBMODULE_CONFLICT: {
4526 Error("missing submodule metadata record at beginning of block");
4533 UnresolvedModuleRef Unresolved;
4534 Unresolved.File = &F;
4535 Unresolved.Mod = CurrentModule;
4536 Unresolved.ID = Record[0];
4537 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4538 Unresolved.IsWildcard = false;
4539 Unresolved.String = Blob;
4540 UnresolvedModuleRefs.push_back(Unresolved);
4547 /// \brief Parse the record that corresponds to a LangOptions data
4550 /// This routine parses the language options from the AST file and then gives
4551 /// them to the AST listener if one is set.
4553 /// \returns true if the listener deems the file unacceptable, false otherwise.
4554 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4556 ASTReaderListener &Listener) {
4557 LangOptions LangOpts;
4559 #define LANGOPT(Name, Bits, Default, Description) \
4560 LangOpts.Name = Record[Idx++];
4561 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4562 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4563 #include "clang/Basic/LangOptions.def"
4564 #define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4565 #include "clang/Basic/Sanitizers.def"
4567 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4568 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4569 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4571 unsigned Length = Record[Idx++];
4572 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4573 Record.begin() + Idx + Length);
4578 for (unsigned N = Record[Idx++]; N; --N) {
4579 LangOpts.CommentOpts.BlockCommandNames.push_back(
4580 ReadString(Record, Idx));
4582 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
4584 return Listener.ReadLanguageOptions(LangOpts, Complain);
4587 bool ASTReader::ParseTargetOptions(const RecordData &Record,
4589 ASTReaderListener &Listener) {
4591 TargetOptions TargetOpts;
4592 TargetOpts.Triple = ReadString(Record, Idx);
4593 TargetOpts.CPU = ReadString(Record, Idx);
4594 TargetOpts.ABI = ReadString(Record, Idx);
4595 for (unsigned N = Record[Idx++]; N; --N) {
4596 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4598 for (unsigned N = Record[Idx++]; N; --N) {
4599 TargetOpts.Features.push_back(ReadString(Record, Idx));
4602 return Listener.ReadTargetOptions(TargetOpts, Complain);
4605 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4606 ASTReaderListener &Listener) {
4607 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
4609 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
4610 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4611 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
4612 #include "clang/Basic/DiagnosticOptions.def"
4614 for (unsigned N = Record[Idx++]; N; --N)
4615 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
4616 for (unsigned N = Record[Idx++]; N; --N)
4617 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
4619 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4622 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4623 ASTReaderListener &Listener) {
4624 FileSystemOptions FSOpts;
4626 FSOpts.WorkingDir = ReadString(Record, Idx);
4627 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4630 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4632 ASTReaderListener &Listener) {
4633 HeaderSearchOptions HSOpts;
4635 HSOpts.Sysroot = ReadString(Record, Idx);
4638 for (unsigned N = Record[Idx++]; N; --N) {
4639 std::string Path = ReadString(Record, Idx);
4640 frontend::IncludeDirGroup Group
4641 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
4642 bool IsFramework = Record[Idx++];
4643 bool IgnoreSysRoot = Record[Idx++];
4644 HSOpts.UserEntries.push_back(
4645 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
4648 // System header prefixes.
4649 for (unsigned N = Record[Idx++]; N; --N) {
4650 std::string Prefix = ReadString(Record, Idx);
4651 bool IsSystemHeader = Record[Idx++];
4652 HSOpts.SystemHeaderPrefixes.push_back(
4653 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4656 HSOpts.ResourceDir = ReadString(Record, Idx);
4657 HSOpts.ModuleCachePath = ReadString(Record, Idx);
4658 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
4659 HSOpts.DisableModuleHash = Record[Idx++];
4660 HSOpts.UseBuiltinIncludes = Record[Idx++];
4661 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4662 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4663 HSOpts.UseLibcxx = Record[Idx++];
4665 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4668 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4670 ASTReaderListener &Listener,
4671 std::string &SuggestedPredefines) {
4672 PreprocessorOptions PPOpts;
4675 // Macro definitions/undefs
4676 for (unsigned N = Record[Idx++]; N; --N) {
4677 std::string Macro = ReadString(Record, Idx);
4678 bool IsUndef = Record[Idx++];
4679 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4683 for (unsigned N = Record[Idx++]; N; --N) {
4684 PPOpts.Includes.push_back(ReadString(Record, Idx));
4688 for (unsigned N = Record[Idx++]; N; --N) {
4689 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4692 PPOpts.UsePredefines = Record[Idx++];
4693 PPOpts.DetailedRecord = Record[Idx++];
4694 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4695 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4696 PPOpts.ObjCXXARCStandardLibrary =
4697 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4698 SuggestedPredefines.clear();
4699 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4700 SuggestedPredefines);
4703 std::pair<ModuleFile *, unsigned>
4704 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4705 GlobalPreprocessedEntityMapType::iterator
4706 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4707 assert(I != GlobalPreprocessedEntityMap.end() &&
4708 "Corrupted global preprocessed entity map");
4709 ModuleFile *M = I->second;
4710 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4711 return std::make_pair(M, LocalIndex);
4714 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4715 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4716 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4717 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4718 Mod.NumPreprocessedEntities);
4720 return std::make_pair(PreprocessingRecord::iterator(),
4721 PreprocessingRecord::iterator());
4724 std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4725 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4726 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4727 ModuleDeclIterator(this, &Mod,
4728 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4731 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4732 PreprocessedEntityID PPID = Index+1;
4733 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4734 ModuleFile &M = *PPInfo.first;
4735 unsigned LocalIndex = PPInfo.second;
4736 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4738 if (!PP.getPreprocessingRecord()) {
4739 Error("no preprocessing record");
4743 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4744 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4746 llvm::BitstreamEntry Entry =
4747 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4748 if (Entry.Kind != llvm::BitstreamEntry::Record)
4752 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4753 ReadSourceLocation(M, PPOffs.End));
4754 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
4757 PreprocessorDetailRecordTypes RecType =
4758 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4759 Entry.ID, Record, &Blob);
4761 case PPD_MACRO_EXPANSION: {
4762 bool isBuiltin = Record[0];
4763 IdentifierInfo *Name = nullptr;
4764 MacroDefinition *Def = nullptr;
4766 Name = getLocalIdentifier(M, Record[1]);
4768 PreprocessedEntityID
4769 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4770 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4775 ME = new (PPRec) MacroExpansion(Name, Range);
4777 ME = new (PPRec) MacroExpansion(Def, Range);
4782 case PPD_MACRO_DEFINITION: {
4783 // Decode the identifier info and then check again; if the macro is
4784 // still defined and associated with the identifier,
4785 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4787 = new (PPRec) MacroDefinition(II, Range);
4789 if (DeserializationListener)
4790 DeserializationListener->MacroDefinitionRead(PPID, MD);
4795 case PPD_INCLUSION_DIRECTIVE: {
4796 const char *FullFileNameStart = Blob.data() + Record[0];
4797 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
4798 const FileEntry *File = nullptr;
4799 if (!FullFileName.empty())
4800 File = PP.getFileManager().getFile(FullFileName);
4802 // FIXME: Stable encoding
4803 InclusionDirective::InclusionKind Kind
4804 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4805 InclusionDirective *ID
4806 = new (PPRec) InclusionDirective(PPRec, Kind,
4807 StringRef(Blob.data(), Record[0]),
4808 Record[1], Record[3],
4815 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4818 /// \brief \arg SLocMapI points at a chunk of a module that contains no
4819 /// preprocessed entities or the entities it contains are not the ones we are
4820 /// looking for. Find the next module that contains entities and return the ID
4821 /// of the first entry.
4822 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4823 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4825 for (GlobalSLocOffsetMapType::const_iterator
4826 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4827 ModuleFile &M = *SLocMapI->second;
4828 if (M.NumPreprocessedEntities)
4829 return M.BasePreprocessedEntityID;
4832 return getTotalNumPreprocessedEntities();
4837 template <unsigned PPEntityOffset::*PPLoc>
4838 struct PPEntityComp {
4839 const ASTReader &Reader;
4842 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4844 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4845 SourceLocation LHS = getLoc(L);
4846 SourceLocation RHS = getLoc(R);
4847 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4850 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4851 SourceLocation LHS = getLoc(L);
4852 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4855 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4856 SourceLocation RHS = getLoc(R);
4857 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4860 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4861 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4867 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4868 bool EndsAfter) const {
4869 if (SourceMgr.isLocalSourceLocation(Loc))
4870 return getTotalNumPreprocessedEntities();
4872 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4873 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
4874 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4875 "Corrupted global sloc offset map");
4877 if (SLocMapI->second->NumPreprocessedEntities == 0)
4878 return findNextPreprocessedEntity(SLocMapI);
4880 ModuleFile &M = *SLocMapI->second;
4881 typedef const PPEntityOffset *pp_iterator;
4882 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4883 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4885 size_t Count = M.NumPreprocessedEntities;
4887 pp_iterator First = pp_begin;
4891 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4892 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4894 // Do a binary search manually instead of using std::lower_bound because
4895 // The end locations of entities may be unordered (when a macro expansion
4896 // is inside another macro argument), but for this case it is not important
4897 // whether we get the first macro expansion or its containing macro.
4901 std::advance(PPI, Half);
4902 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4906 Count = Count - Half - 1;
4913 return findNextPreprocessedEntity(SLocMapI);
4915 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4918 /// \brief Returns a pair of [Begin, End) indices of preallocated
4919 /// preprocessed entities that \arg Range encompasses.
4920 std::pair<unsigned, unsigned>
4921 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4922 if (Range.isInvalid())
4923 return std::make_pair(0,0);
4924 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4926 PreprocessedEntityID BeginID =
4927 findPreprocessedEntity(Range.getBegin(), false);
4928 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
4929 return std::make_pair(BeginID, EndID);
4932 /// \brief Optionally returns true or false if the preallocated preprocessed
4933 /// entity with index \arg Index came from file \arg FID.
4934 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
4936 if (FID.isInvalid())
4939 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4940 ModuleFile &M = *PPInfo.first;
4941 unsigned LocalIndex = PPInfo.second;
4942 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4944 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4945 if (Loc.isInvalid())
4948 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4955 /// \brief Visitor used to search for information about a header file.
4956 class HeaderFileInfoVisitor {
4957 const FileEntry *FE;
4959 Optional<HeaderFileInfo> HFI;
4962 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4965 static bool visit(ModuleFile &M, void *UserData) {
4966 HeaderFileInfoVisitor *This
4967 = static_cast<HeaderFileInfoVisitor *>(UserData);
4969 HeaderFileInfoLookupTable *Table
4970 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4974 // Look in the on-disk hash table for an entry for this file name.
4975 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
4976 if (Pos == Table->end())
4983 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
4987 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
4988 HeaderFileInfoVisitor Visitor(FE);
4989 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
4990 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
4993 return HeaderFileInfo();
4996 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4997 // FIXME: Make it work properly with modules.
4998 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
4999 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5000 ModuleFile &F = *(*I);
5003 assert(!Diag.DiagStates.empty());
5004 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5005 while (Idx < F.PragmaDiagMappings.size()) {
5006 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5007 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5008 if (DiagStateID != 0) {
5009 Diag.DiagStatePoints.push_back(
5010 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5011 FullSourceLoc(Loc, SourceMgr)));
5015 assert(DiagStateID == 0);
5016 // A new DiagState was created here.
5017 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5018 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5019 DiagStates.push_back(NewState);
5020 Diag.DiagStatePoints.push_back(
5021 DiagnosticsEngine::DiagStatePoint(NewState,
5022 FullSourceLoc(Loc, SourceMgr)));
5024 assert(Idx < F.PragmaDiagMappings.size() &&
5025 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5026 if (Idx >= F.PragmaDiagMappings.size()) {
5027 break; // Something is messed up but at least avoid infinite loop in
5030 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5031 if (DiagID == (unsigned)-1) {
5032 break; // no more diag/map pairs for this location.
5034 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5035 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5036 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
5042 /// \brief Get the correct cursor and offset for loading a type.
5043 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5044 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5045 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5046 ModuleFile *M = I->second;
5047 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5050 /// \brief Read and return the type with the given index..
5052 /// The index is the type ID, shifted and minus the number of predefs. This
5053 /// routine actually reads the record corresponding to the type at the given
5054 /// location. It is a helper routine for GetType, which deals with reading type
5056 QualType ASTReader::readTypeRecord(unsigned Index) {
5057 RecordLocation Loc = TypeCursorForIndex(Index);
5058 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
5060 // Keep track of where we are in the stream, then jump back there
5061 // after reading this type.
5062 SavedStreamPosition SavedPosition(DeclsCursor);
5064 ReadingKindTracker ReadingKind(Read_Type, *this);
5066 // Note that we are loading a type record.
5067 Deserializing AType(this);
5070 DeclsCursor.JumpToBit(Loc.Offset);
5072 unsigned Code = DeclsCursor.ReadCode();
5073 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
5074 case TYPE_EXT_QUAL: {
5075 if (Record.size() != 2) {
5076 Error("Incorrect encoding of extended qualifier type");
5079 QualType Base = readType(*Loc.F, Record, Idx);
5080 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5081 return Context.getQualifiedType(Base, Quals);
5084 case TYPE_COMPLEX: {
5085 if (Record.size() != 1) {
5086 Error("Incorrect encoding of complex type");
5089 QualType ElemType = readType(*Loc.F, Record, Idx);
5090 return Context.getComplexType(ElemType);
5093 case TYPE_POINTER: {
5094 if (Record.size() != 1) {
5095 Error("Incorrect encoding of pointer type");
5098 QualType PointeeType = readType(*Loc.F, Record, Idx);
5099 return Context.getPointerType(PointeeType);
5102 case TYPE_DECAYED: {
5103 if (Record.size() != 1) {
5104 Error("Incorrect encoding of decayed type");
5107 QualType OriginalType = readType(*Loc.F, Record, Idx);
5108 QualType DT = Context.getAdjustedParameterType(OriginalType);
5109 if (!isa<DecayedType>(DT))
5110 Error("Decayed type does not decay");
5114 case TYPE_ADJUSTED: {
5115 if (Record.size() != 2) {
5116 Error("Incorrect encoding of adjusted type");
5119 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5120 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5121 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5124 case TYPE_BLOCK_POINTER: {
5125 if (Record.size() != 1) {
5126 Error("Incorrect encoding of block pointer type");
5129 QualType PointeeType = readType(*Loc.F, Record, Idx);
5130 return Context.getBlockPointerType(PointeeType);
5133 case TYPE_LVALUE_REFERENCE: {
5134 if (Record.size() != 2) {
5135 Error("Incorrect encoding of lvalue reference type");
5138 QualType PointeeType = readType(*Loc.F, Record, Idx);
5139 return Context.getLValueReferenceType(PointeeType, Record[1]);
5142 case TYPE_RVALUE_REFERENCE: {
5143 if (Record.size() != 1) {
5144 Error("Incorrect encoding of rvalue reference type");
5147 QualType PointeeType = readType(*Loc.F, Record, Idx);
5148 return Context.getRValueReferenceType(PointeeType);
5151 case TYPE_MEMBER_POINTER: {
5152 if (Record.size() != 2) {
5153 Error("Incorrect encoding of member pointer type");
5156 QualType PointeeType = readType(*Loc.F, Record, Idx);
5157 QualType ClassType = readType(*Loc.F, Record, Idx);
5158 if (PointeeType.isNull() || ClassType.isNull())
5161 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5164 case TYPE_CONSTANT_ARRAY: {
5165 QualType ElementType = readType(*Loc.F, Record, Idx);
5166 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5167 unsigned IndexTypeQuals = Record[2];
5169 llvm::APInt Size = ReadAPInt(Record, Idx);
5170 return Context.getConstantArrayType(ElementType, Size,
5171 ASM, IndexTypeQuals);
5174 case TYPE_INCOMPLETE_ARRAY: {
5175 QualType ElementType = readType(*Loc.F, Record, Idx);
5176 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5177 unsigned IndexTypeQuals = Record[2];
5178 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5181 case TYPE_VARIABLE_ARRAY: {
5182 QualType ElementType = readType(*Loc.F, Record, Idx);
5183 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5184 unsigned IndexTypeQuals = Record[2];
5185 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5186 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5187 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5188 ASM, IndexTypeQuals,
5189 SourceRange(LBLoc, RBLoc));
5193 if (Record.size() != 3) {
5194 Error("incorrect encoding of vector type in AST file");
5198 QualType ElementType = readType(*Loc.F, Record, Idx);
5199 unsigned NumElements = Record[1];
5200 unsigned VecKind = Record[2];
5201 return Context.getVectorType(ElementType, NumElements,
5202 (VectorType::VectorKind)VecKind);
5205 case TYPE_EXT_VECTOR: {
5206 if (Record.size() != 3) {
5207 Error("incorrect encoding of extended vector type in AST file");
5211 QualType ElementType = readType(*Loc.F, Record, Idx);
5212 unsigned NumElements = Record[1];
5213 return Context.getExtVectorType(ElementType, NumElements);
5216 case TYPE_FUNCTION_NO_PROTO: {
5217 if (Record.size() != 6) {
5218 Error("incorrect encoding of no-proto function type");
5221 QualType ResultType = readType(*Loc.F, Record, Idx);
5222 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5223 (CallingConv)Record[4], Record[5]);
5224 return Context.getFunctionNoProtoType(ResultType, Info);
5227 case TYPE_FUNCTION_PROTO: {
5228 QualType ResultType = readType(*Loc.F, Record, Idx);
5230 FunctionProtoType::ExtProtoInfo EPI;
5231 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5232 /*hasregparm*/ Record[2],
5233 /*regparm*/ Record[3],
5234 static_cast<CallingConv>(Record[4]),
5235 /*produces*/ Record[5]);
5238 unsigned NumParams = Record[Idx++];
5239 SmallVector<QualType, 16> ParamTypes;
5240 for (unsigned I = 0; I != NumParams; ++I)
5241 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5243 EPI.Variadic = Record[Idx++];
5244 EPI.HasTrailingReturn = Record[Idx++];
5245 EPI.TypeQuals = Record[Idx++];
5246 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
5247 SmallVector<QualType, 8> ExceptionStorage;
5248 readExceptionSpec(*Loc.F, ExceptionStorage, EPI, Record, Idx);
5249 return Context.getFunctionType(ResultType, ParamTypes, EPI);
5252 case TYPE_UNRESOLVED_USING: {
5254 return Context.getTypeDeclType(
5255 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5258 case TYPE_TYPEDEF: {
5259 if (Record.size() != 2) {
5260 Error("incorrect encoding of typedef type");
5264 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5265 QualType Canonical = readType(*Loc.F, Record, Idx);
5266 if (!Canonical.isNull())
5267 Canonical = Context.getCanonicalType(Canonical);
5268 return Context.getTypedefType(Decl, Canonical);
5271 case TYPE_TYPEOF_EXPR:
5272 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5275 if (Record.size() != 1) {
5276 Error("incorrect encoding of typeof(type) in AST file");
5279 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5280 return Context.getTypeOfType(UnderlyingType);
5283 case TYPE_DECLTYPE: {
5284 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5285 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5288 case TYPE_UNARY_TRANSFORM: {
5289 QualType BaseType = readType(*Loc.F, Record, Idx);
5290 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5291 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5292 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5296 QualType Deduced = readType(*Loc.F, Record, Idx);
5297 bool IsDecltypeAuto = Record[Idx++];
5298 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5299 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
5303 if (Record.size() != 2) {
5304 Error("incorrect encoding of record type");
5308 bool IsDependent = Record[Idx++];
5309 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5310 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5311 QualType T = Context.getRecordType(RD);
5312 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5317 if (Record.size() != 2) {
5318 Error("incorrect encoding of enum type");
5322 bool IsDependent = Record[Idx++];
5324 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5325 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5329 case TYPE_ATTRIBUTED: {
5330 if (Record.size() != 3) {
5331 Error("incorrect encoding of attributed type");
5334 QualType modifiedType = readType(*Loc.F, Record, Idx);
5335 QualType equivalentType = readType(*Loc.F, Record, Idx);
5336 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5337 return Context.getAttributedType(kind, modifiedType, equivalentType);
5341 if (Record.size() != 1) {
5342 Error("incorrect encoding of paren type");
5345 QualType InnerType = readType(*Loc.F, Record, Idx);
5346 return Context.getParenType(InnerType);
5349 case TYPE_PACK_EXPANSION: {
5350 if (Record.size() != 2) {
5351 Error("incorrect encoding of pack expansion type");
5354 QualType Pattern = readType(*Loc.F, Record, Idx);
5355 if (Pattern.isNull())
5357 Optional<unsigned> NumExpansions;
5359 NumExpansions = Record[1] - 1;
5360 return Context.getPackExpansionType(Pattern, NumExpansions);
5363 case TYPE_ELABORATED: {
5365 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5366 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5367 QualType NamedType = readType(*Loc.F, Record, Idx);
5368 return Context.getElaboratedType(Keyword, NNS, NamedType);
5371 case TYPE_OBJC_INTERFACE: {
5373 ObjCInterfaceDecl *ItfD
5374 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5375 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5378 case TYPE_OBJC_OBJECT: {
5380 QualType Base = readType(*Loc.F, Record, Idx);
5381 unsigned NumProtos = Record[Idx++];
5382 SmallVector<ObjCProtocolDecl*, 4> Protos;
5383 for (unsigned I = 0; I != NumProtos; ++I)
5384 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5385 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5388 case TYPE_OBJC_OBJECT_POINTER: {
5390 QualType Pointee = readType(*Loc.F, Record, Idx);
5391 return Context.getObjCObjectPointerType(Pointee);
5394 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5396 QualType Parm = readType(*Loc.F, Record, Idx);
5397 QualType Replacement = readType(*Loc.F, Record, Idx);
5398 return Context.getSubstTemplateTypeParmType(
5399 cast<TemplateTypeParmType>(Parm),
5400 Context.getCanonicalType(Replacement));
5403 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5405 QualType Parm = readType(*Loc.F, Record, Idx);
5406 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5407 return Context.getSubstTemplateTypeParmPackType(
5408 cast<TemplateTypeParmType>(Parm),
5412 case TYPE_INJECTED_CLASS_NAME: {
5413 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5414 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5415 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5416 // for AST reading, too much interdependencies.
5418 if (const Type *Existing = D->getTypeForDecl())
5420 else if (auto *Prev = D->getPreviousDecl())
5421 T = Prev->getTypeForDecl();
5423 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5424 return QualType(T, 0);
5427 case TYPE_TEMPLATE_TYPE_PARM: {
5429 unsigned Depth = Record[Idx++];
5430 unsigned Index = Record[Idx++];
5431 bool Pack = Record[Idx++];
5432 TemplateTypeParmDecl *D
5433 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5434 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5437 case TYPE_DEPENDENT_NAME: {
5439 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5440 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5441 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5442 QualType Canon = readType(*Loc.F, Record, Idx);
5443 if (!Canon.isNull())
5444 Canon = Context.getCanonicalType(Canon);
5445 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5448 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5450 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5451 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5452 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5453 unsigned NumArgs = Record[Idx++];
5454 SmallVector<TemplateArgument, 8> Args;
5455 Args.reserve(NumArgs);
5457 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5458 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5459 Args.size(), Args.data());
5462 case TYPE_DEPENDENT_SIZED_ARRAY: {
5466 QualType ElementType = readType(*Loc.F, Record, Idx);
5467 ArrayType::ArraySizeModifier ASM
5468 = (ArrayType::ArraySizeModifier)Record[Idx++];
5469 unsigned IndexTypeQuals = Record[Idx++];
5471 // DependentSizedArrayType
5472 Expr *NumElts = ReadExpr(*Loc.F);
5473 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5475 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5476 IndexTypeQuals, Brackets);
5479 case TYPE_TEMPLATE_SPECIALIZATION: {
5481 bool IsDependent = Record[Idx++];
5482 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5483 SmallVector<TemplateArgument, 8> Args;
5484 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5485 QualType Underlying = readType(*Loc.F, Record, Idx);
5487 if (Underlying.isNull())
5488 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5491 T = Context.getTemplateSpecializationType(Name, Args.data(),
5492 Args.size(), Underlying);
5493 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5498 if (Record.size() != 1) {
5499 Error("Incorrect encoding of atomic type");
5502 QualType ValueType = readType(*Loc.F, Record, Idx);
5503 return Context.getAtomicType(ValueType);
5506 llvm_unreachable("Invalid TypeCode!");
5509 void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5510 SmallVectorImpl<QualType> &Exceptions,
5511 FunctionProtoType::ExtProtoInfo &EPI,
5512 const RecordData &Record, unsigned &Idx) {
5513 ExceptionSpecificationType EST =
5514 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5515 EPI.ExceptionSpecType = EST;
5516 if (EST == EST_Dynamic) {
5517 EPI.NumExceptions = Record[Idx++];
5518 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5519 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5520 EPI.Exceptions = Exceptions.data();
5521 } else if (EST == EST_ComputedNoexcept) {
5522 EPI.NoexceptExpr = ReadExpr(ModuleFile);
5523 } else if (EST == EST_Uninstantiated) {
5524 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5525 EPI.ExceptionSpecTemplate =
5526 ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5527 } else if (EST == EST_Unevaluated) {
5528 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5532 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5535 const ASTReader::RecordData &Record;
5538 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5540 return Reader.ReadSourceLocation(F, R, I);
5543 template<typename T>
5544 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5545 return Reader.ReadDeclAs<T>(F, Record, Idx);
5549 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5550 const ASTReader::RecordData &Record, unsigned &Idx)
5551 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5554 // We want compile-time assurance that we've enumerated all of
5555 // these, so unfortunately we have to declare them first, then
5556 // define them out-of-line.
5557 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5558 #define TYPELOC(CLASS, PARENT) \
5559 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5560 #include "clang/AST/TypeLocNodes.def"
5562 void VisitFunctionTypeLoc(FunctionTypeLoc);
5563 void VisitArrayTypeLoc(ArrayTypeLoc);
5566 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5569 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5570 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5571 if (TL.needsExtraLocalData()) {
5572 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5573 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5574 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5575 TL.setModeAttr(Record[Idx++]);
5578 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5579 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5581 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5582 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5584 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5587 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5590 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5591 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5593 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5594 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5596 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5597 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5599 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5600 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5601 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5603 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5604 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5605 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5607 TL.setSizeExpr(Reader.ReadExpr(F));
5609 TL.setSizeExpr(nullptr);
5611 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5612 VisitArrayTypeLoc(TL);
5614 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5615 VisitArrayTypeLoc(TL);
5617 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5618 VisitArrayTypeLoc(TL);
5620 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5621 DependentSizedArrayTypeLoc TL) {
5622 VisitArrayTypeLoc(TL);
5624 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5625 DependentSizedExtVectorTypeLoc TL) {
5626 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5628 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5629 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5631 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5632 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5634 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5635 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5636 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5637 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5638 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
5639 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5640 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
5643 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5644 VisitFunctionTypeLoc(TL);
5646 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5647 VisitFunctionTypeLoc(TL);
5649 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5650 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5652 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5653 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5655 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5656 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5657 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5658 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5660 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5661 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5662 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5663 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5664 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5666 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5667 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5669 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5670 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5671 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5672 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5673 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5675 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5676 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5678 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5679 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5681 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5682 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5684 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5685 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5686 if (TL.hasAttrOperand()) {
5688 range.setBegin(ReadSourceLocation(Record, Idx));
5689 range.setEnd(ReadSourceLocation(Record, Idx));
5690 TL.setAttrOperandParensRange(range);
5692 if (TL.hasAttrExprOperand()) {
5694 TL.setAttrExprOperand(Reader.ReadExpr(F));
5696 TL.setAttrExprOperand(nullptr);
5697 } else if (TL.hasAttrEnumOperand())
5698 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5700 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5701 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5703 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5704 SubstTemplateTypeParmTypeLoc TL) {
5705 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5707 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5708 SubstTemplateTypeParmPackTypeLoc TL) {
5709 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5711 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5712 TemplateSpecializationTypeLoc TL) {
5713 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5714 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5715 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5716 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5717 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5719 Reader.GetTemplateArgumentLocInfo(F,
5720 TL.getTypePtr()->getArg(i).getKind(),
5723 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5724 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5725 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5727 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5728 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5729 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5731 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5732 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5734 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5735 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5736 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5737 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5739 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5740 DependentTemplateSpecializationTypeLoc TL) {
5741 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5742 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5743 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5744 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5745 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5746 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5747 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5749 Reader.GetTemplateArgumentLocInfo(F,
5750 TL.getTypePtr()->getArg(I).getKind(),
5753 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5754 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5756 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5757 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5759 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5760 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5761 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5762 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5763 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5764 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5766 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5767 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5769 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5770 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5771 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5772 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5775 TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5776 const RecordData &Record,
5778 QualType InfoTy = readType(F, Record, Idx);
5779 if (InfoTy.isNull())
5782 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5783 TypeLocReader TLR(*this, F, Record, Idx);
5784 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5789 QualType ASTReader::GetType(TypeID ID) {
5790 unsigned FastQuals = ID & Qualifiers::FastMask;
5791 unsigned Index = ID >> Qualifiers::FastWidth;
5793 if (Index < NUM_PREDEF_TYPE_IDS) {
5795 switch ((PredefinedTypeIDs)Index) {
5796 case PREDEF_TYPE_NULL_ID: return QualType();
5797 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5798 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5800 case PREDEF_TYPE_CHAR_U_ID:
5801 case PREDEF_TYPE_CHAR_S_ID:
5802 // FIXME: Check that the signedness of CharTy is correct!
5806 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5807 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5808 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5809 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5810 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5811 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5812 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5813 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5814 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5815 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5816 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5817 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5818 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5819 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5820 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5821 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5822 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5823 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5824 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5825 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5826 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5827 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5828 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5829 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5830 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5831 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5832 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5833 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
5834 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5835 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5836 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5837 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5838 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5839 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
5840 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
5841 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
5842 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5844 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5845 T = Context.getAutoRRefDeductType();
5848 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5849 T = Context.ARCUnbridgedCastTy;
5852 case PREDEF_TYPE_VA_LIST_TAG:
5853 T = Context.getVaListTagType();
5856 case PREDEF_TYPE_BUILTIN_FN:
5857 T = Context.BuiltinFnTy;
5861 assert(!T.isNull() && "Unknown predefined type");
5862 return T.withFastQualifiers(FastQuals);
5865 Index -= NUM_PREDEF_TYPE_IDS;
5866 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5867 if (TypesLoaded[Index].isNull()) {
5868 TypesLoaded[Index] = readTypeRecord(Index);
5869 if (TypesLoaded[Index].isNull())
5872 TypesLoaded[Index]->setFromAST();
5873 if (DeserializationListener)
5874 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5875 TypesLoaded[Index]);
5878 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5881 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5882 return GetType(getGlobalTypeID(F, LocalID));
5885 serialization::TypeID
5886 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5887 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5888 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5890 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5893 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5894 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5895 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5897 unsigned GlobalIndex = LocalIndex + I->second;
5898 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5901 TemplateArgumentLocInfo
5902 ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5903 TemplateArgument::ArgKind Kind,
5904 const RecordData &Record,
5907 case TemplateArgument::Expression:
5909 case TemplateArgument::Type:
5910 return GetTypeSourceInfo(F, Record, Index);
5911 case TemplateArgument::Template: {
5912 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5914 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5915 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5918 case TemplateArgument::TemplateExpansion: {
5919 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5921 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5922 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5923 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5926 case TemplateArgument::Null:
5927 case TemplateArgument::Integral:
5928 case TemplateArgument::Declaration:
5929 case TemplateArgument::NullPtr:
5930 case TemplateArgument::Pack:
5931 // FIXME: Is this right?
5932 return TemplateArgumentLocInfo();
5934 llvm_unreachable("unexpected template argument loc");
5938 ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5939 const RecordData &Record, unsigned &Index) {
5940 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5942 if (Arg.getKind() == TemplateArgument::Expression) {
5943 if (Record[Index++]) // bool InfoHasSameExpr.
5944 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5946 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5950 const ASTTemplateArgumentListInfo*
5951 ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5952 const RecordData &Record,
5954 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5955 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5956 unsigned NumArgsAsWritten = Record[Index++];
5957 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5958 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5959 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5960 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5963 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5967 void ASTReader::CompleteRedeclChain(const Decl *D) {
5968 if (NumCurrentElementsDeserializing) {
5969 // We arrange to not care about the complete redeclaration chain while we're
5970 // deserializing. Just remember that the AST has marked this one as complete
5971 // but that it's not actually complete yet, so we know we still need to
5972 // complete it later.
5973 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5977 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5979 // Recursively ensure that the decl context itself is complete
5980 // (in particular, this matters if the decl context is a namespace).
5982 // FIXME: This should be performed by lookup instead of here.
5983 cast<Decl>(DC)->getMostRecentDecl();
5985 // If this is a named declaration, complete it by looking it up
5986 // within its context.
5988 // FIXME: We don't currently handle the cases where we can't do this;
5989 // merging a class definition that contains unnamed entities should merge
5990 // those entities. Likewise, merging a function definition should merge
5991 // all mergeable entities within it.
5992 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5993 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5994 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
5995 auto *II = Name.getAsIdentifierInfo();
5996 if (isa<TranslationUnitDecl>(DC) && II) {
5997 // Outside of C++, we don't have a lookup table for the TU, so update
5998 // the identifier instead. In C++, either way should work fine.
5999 if (II->isOutOfDate())
6000 updateOutOfDateIdentifier(*II);
6007 uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6008 const RecordData &Record,
6010 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6011 Error("malformed AST file: missing C++ base specifier");
6015 unsigned LocalID = Record[Idx++];
6016 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6019 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6020 RecordLocation Loc = getLocalBitOffset(Offset);
6021 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6022 SavedStreamPosition SavedPosition(Cursor);
6023 Cursor.JumpToBit(Loc.Offset);
6024 ReadingKindTracker ReadingKind(Read_Decl, *this);
6026 unsigned Code = Cursor.ReadCode();
6027 unsigned RecCode = Cursor.readRecord(Code, Record);
6028 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
6029 Error("malformed AST file: missing C++ base specifiers");
6034 unsigned NumBases = Record[Idx++];
6035 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6036 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6037 for (unsigned I = 0; I != NumBases; ++I)
6038 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6042 serialization::DeclID
6043 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6044 if (LocalID < NUM_PREDEF_DECL_IDS)
6047 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6048 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6049 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6051 return LocalID + I->second;
6054 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6055 ModuleFile &M) const {
6056 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6057 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6058 return &M == I->second;
6061 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
6062 if (!D->isFromASTFile())
6064 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6065 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6069 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6070 if (ID < NUM_PREDEF_DECL_IDS)
6071 return SourceLocation();
6073 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6075 if (Index > DeclsLoaded.size()) {
6076 Error("declaration ID out-of-range for AST file");
6077 return SourceLocation();
6080 if (Decl *D = DeclsLoaded[Index])
6081 return D->getLocation();
6083 unsigned RawLocation = 0;
6084 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6085 return ReadSourceLocation(*Rec.F, RawLocation);
6088 Decl *ASTReader::GetExistingDecl(DeclID ID) {
6089 if (ID < NUM_PREDEF_DECL_IDS) {
6090 switch ((PredefinedDeclIDs)ID) {
6091 case PREDEF_DECL_NULL_ID:
6094 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6095 return Context.getTranslationUnitDecl();
6097 case PREDEF_DECL_OBJC_ID_ID:
6098 return Context.getObjCIdDecl();
6100 case PREDEF_DECL_OBJC_SEL_ID:
6101 return Context.getObjCSelDecl();
6103 case PREDEF_DECL_OBJC_CLASS_ID:
6104 return Context.getObjCClassDecl();
6106 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6107 return Context.getObjCProtocolDecl();
6109 case PREDEF_DECL_INT_128_ID:
6110 return Context.getInt128Decl();
6112 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6113 return Context.getUInt128Decl();
6115 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6116 return Context.getObjCInstanceTypeDecl();
6118 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6119 return Context.getBuiltinVaListDecl();
6123 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6125 if (Index >= DeclsLoaded.size()) {
6126 assert(0 && "declaration ID out-of-range for AST file");
6127 Error("declaration ID out-of-range for AST file");
6131 return DeclsLoaded[Index];
6134 Decl *ASTReader::GetDecl(DeclID ID) {
6135 if (ID < NUM_PREDEF_DECL_IDS)
6136 return GetExistingDecl(ID);
6138 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6140 if (Index >= DeclsLoaded.size()) {
6141 assert(0 && "declaration ID out-of-range for AST file");
6142 Error("declaration ID out-of-range for AST file");
6146 if (!DeclsLoaded[Index]) {
6148 if (DeserializationListener)
6149 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6152 return DeclsLoaded[Index];
6155 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6157 if (GlobalID < NUM_PREDEF_DECL_IDS)
6160 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6161 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6162 ModuleFile *Owner = I->second;
6164 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6165 = M.GlobalToLocalDeclIDs.find(Owner);
6166 if (Pos == M.GlobalToLocalDeclIDs.end())
6169 return GlobalID - Owner->BaseDeclID + Pos->second;
6172 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6173 const RecordData &Record,
6175 if (Idx >= Record.size()) {
6176 Error("Corrupted AST file");
6180 return getGlobalDeclID(F, Record[Idx++]);
6183 /// \brief Resolve the offset of a statement into a statement.
6185 /// This operation will read a new statement from the external
6186 /// source each time it is called, and is meant to be used via a
6187 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6188 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6189 // Switch case IDs are per Decl.
6190 ClearSwitchCaseIDs();
6192 // Offset here is a global offset across the entire chain.
6193 RecordLocation Loc = getLocalBitOffset(Offset);
6194 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6195 return ReadStmtFromStream(*Loc.F);
6199 class FindExternalLexicalDeclsVisitor {
6201 const DeclContext *DC;
6202 bool (*isKindWeWant)(Decl::Kind);
6204 SmallVectorImpl<Decl*> &Decls;
6205 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6208 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6209 bool (*isKindWeWant)(Decl::Kind),
6210 SmallVectorImpl<Decl*> &Decls)
6211 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6213 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6214 PredefsVisited[I] = false;
6217 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6221 FindExternalLexicalDeclsVisitor *This
6222 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6224 ModuleFile::DeclContextInfosMap::iterator Info
6225 = M.DeclContextInfos.find(This->DC);
6226 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6229 // Load all of the declaration IDs
6230 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6231 *IDE = ID + Info->second.NumLexicalDecls;
6233 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6236 // Don't add predefined declarations to the lexical context more
6238 if (ID->second < NUM_PREDEF_DECL_IDS) {
6239 if (This->PredefsVisited[ID->second])
6242 This->PredefsVisited[ID->second] = true;
6245 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6246 if (!This->DC->isDeclInLexicalTraversal(D))
6247 This->Decls.push_back(D);
6256 ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6257 bool (*isKindWeWant)(Decl::Kind),
6258 SmallVectorImpl<Decl*> &Decls) {
6259 // There might be lexical decls in multiple modules, for the TU at
6260 // least. Walk all of the modules in the order they were loaded.
6261 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6262 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6263 ++NumLexicalDeclContextsRead;
6274 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6276 bool operator()(LocalDeclID L, LocalDeclID R) const {
6277 SourceLocation LHS = getLocation(L);
6278 SourceLocation RHS = getLocation(R);
6279 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6282 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6283 SourceLocation RHS = getLocation(R);
6284 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6287 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6288 SourceLocation LHS = getLocation(L);
6289 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6292 SourceLocation getLocation(LocalDeclID ID) const {
6293 return Reader.getSourceManager().getFileLoc(
6294 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6300 void ASTReader::FindFileRegionDecls(FileID File,
6301 unsigned Offset, unsigned Length,
6302 SmallVectorImpl<Decl *> &Decls) {
6303 SourceManager &SM = getSourceManager();
6305 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6306 if (I == FileDeclIDs.end())
6309 FileDeclsInfo &DInfo = I->second;
6310 if (DInfo.Decls.empty())
6314 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6315 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6317 DeclIDComp DIDComp(*this, *DInfo.Mod);
6318 ArrayRef<serialization::LocalDeclID>::iterator
6319 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6321 if (BeginIt != DInfo.Decls.begin())
6324 // If we are pointing at a top-level decl inside an objc container, we need
6325 // to backtrack until we find it otherwise we will fail to report that the
6326 // region overlaps with an objc container.
6327 while (BeginIt != DInfo.Decls.begin() &&
6328 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6329 ->isTopLevelDeclInObjCContainer())
6332 ArrayRef<serialization::LocalDeclID>::iterator
6333 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6335 if (EndIt != DInfo.Decls.end())
6338 for (ArrayRef<serialization::LocalDeclID>::iterator
6339 DIt = BeginIt; DIt != EndIt; ++DIt)
6340 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6344 /// \brief ModuleFile visitor used to perform name lookup into a
6345 /// declaration context.
6346 class DeclContextNameLookupVisitor {
6348 SmallVectorImpl<const DeclContext *> &Contexts;
6349 DeclarationName Name;
6350 SmallVectorImpl<NamedDecl *> &Decls;
6353 DeclContextNameLookupVisitor(ASTReader &Reader,
6354 SmallVectorImpl<const DeclContext *> &Contexts,
6355 DeclarationName Name,
6356 SmallVectorImpl<NamedDecl *> &Decls)
6357 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6359 static bool visit(ModuleFile &M, void *UserData) {
6360 DeclContextNameLookupVisitor *This
6361 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6363 // Check whether we have any visible declaration information for
6364 // this context in this module.
6365 ModuleFile::DeclContextInfosMap::iterator Info;
6366 bool FoundInfo = false;
6367 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6368 Info = M.DeclContextInfos.find(This->Contexts[I]);
6369 if (Info != M.DeclContextInfos.end() &&
6370 Info->second.NameLookupTableData) {
6379 // Look for this name within this module.
6380 ASTDeclContextNameLookupTable *LookupTable =
6381 Info->second.NameLookupTableData;
6382 ASTDeclContextNameLookupTable::iterator Pos
6383 = LookupTable->find(This->Name);
6384 if (Pos == LookupTable->end())
6387 bool FoundAnything = false;
6388 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6389 for (; Data.first != Data.second; ++Data.first) {
6390 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6394 if (ND->getDeclName() != This->Name) {
6395 // A name might be null because the decl's redeclarable part is
6396 // currently read before reading its name. The lookup is triggered by
6397 // building that decl (likely indirectly), and so it is later in the
6398 // sense of "already existing" and can be ignored here.
6402 // Record this declaration.
6403 FoundAnything = true;
6404 This->Decls.push_back(ND);
6407 return FoundAnything;
6412 /// \brief Retrieve the "definitive" module file for the definition of the
6413 /// given declaration context, if there is one.
6415 /// The "definitive" module file is the only place where we need to look to
6416 /// find information about the declarations within the given declaration
6417 /// context. For example, C++ and Objective-C classes, C structs/unions, and
6418 /// Objective-C protocols, categories, and extensions are all defined in a
6419 /// single place in the source code, so they have definitive module files
6420 /// associated with them. C++ namespaces, on the other hand, can have
6421 /// definitions in multiple different module files.
6423 /// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6424 /// NDEBUG checking.
6425 static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6426 ASTReader &Reader) {
6427 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6428 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6434 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6435 DeclarationName Name) {
6436 assert(DC->hasExternalVisibleStorage() &&
6437 "DeclContext has no visible decls in storage");
6441 SmallVector<NamedDecl *, 64> Decls;
6443 // Compute the declaration contexts we need to look into. Multiple such
6444 // declaration contexts occur when two declaration contexts from disjoint
6445 // modules get merged, e.g., when two namespaces with the same name are
6446 // independently defined in separate modules.
6447 SmallVector<const DeclContext *, 2> Contexts;
6448 Contexts.push_back(DC);
6450 if (DC->isNamespace()) {
6451 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6452 if (Merged != MergedDecls.end()) {
6453 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6454 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6457 if (isa<CXXRecordDecl>(DC)) {
6458 auto Merged = MergedLookups.find(DC);
6459 if (Merged != MergedLookups.end())
6460 Contexts.insert(Contexts.end(), Merged->second.begin(),
6461 Merged->second.end());
6464 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
6466 // If we can definitively determine which module file to look into,
6467 // only look there. Otherwise, look in all module files.
6468 ModuleFile *Definitive;
6469 if (Contexts.size() == 1 &&
6470 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6471 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6473 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6475 ++NumVisibleDeclContextsRead;
6476 SetExternalVisibleDeclsForName(DC, Name, Decls);
6477 return !Decls.empty();
6481 /// \brief ModuleFile visitor used to retrieve all visible names in a
6482 /// declaration context.
6483 class DeclContextAllNamesVisitor {
6485 SmallVectorImpl<const DeclContext *> &Contexts;
6490 DeclContextAllNamesVisitor(ASTReader &Reader,
6491 SmallVectorImpl<const DeclContext *> &Contexts,
6492 DeclsMap &Decls, bool VisitAll)
6493 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
6495 static bool visit(ModuleFile &M, void *UserData) {
6496 DeclContextAllNamesVisitor *This
6497 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6499 // Check whether we have any visible declaration information for
6500 // this context in this module.
6501 ModuleFile::DeclContextInfosMap::iterator Info;
6502 bool FoundInfo = false;
6503 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6504 Info = M.DeclContextInfos.find(This->Contexts[I]);
6505 if (Info != M.DeclContextInfos.end() &&
6506 Info->second.NameLookupTableData) {
6515 ASTDeclContextNameLookupTable *LookupTable =
6516 Info->second.NameLookupTableData;
6517 bool FoundAnything = false;
6518 for (ASTDeclContextNameLookupTable::data_iterator
6519 I = LookupTable->data_begin(), E = LookupTable->data_end();
6522 ASTDeclContextNameLookupTrait::data_type Data = *I;
6523 for (; Data.first != Data.second; ++Data.first) {
6524 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6529 // Record this declaration.
6530 FoundAnything = true;
6531 This->Decls[ND->getDeclName()].push_back(ND);
6535 return FoundAnything && !This->VisitAll;
6540 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6541 if (!DC->hasExternalVisibleStorage())
6545 // Compute the declaration contexts we need to look into. Multiple such
6546 // declaration contexts occur when two declaration contexts from disjoint
6547 // modules get merged, e.g., when two namespaces with the same name are
6548 // independently defined in separate modules.
6549 SmallVector<const DeclContext *, 2> Contexts;
6550 Contexts.push_back(DC);
6552 if (DC->isNamespace()) {
6553 MergedDeclsMap::iterator Merged
6554 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6555 if (Merged != MergedDecls.end()) {
6556 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6557 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6561 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6562 /*VisitAll=*/DC->isFileContext());
6563 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6564 ++NumVisibleDeclContextsRead;
6566 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
6567 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6569 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6572 /// \brief Under non-PCH compilation the consumer receives the objc methods
6573 /// before receiving the implementation, and codegen depends on this.
6574 /// We simulate this by deserializing and passing to consumer the methods of the
6575 /// implementation before passing the deserialized implementation decl.
6576 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6577 ASTConsumer *Consumer) {
6578 assert(ImplD && Consumer);
6580 for (auto *I : ImplD->methods())
6581 Consumer->HandleInterestingDecl(DeclGroupRef(I));
6583 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6586 void ASTReader::PassInterestingDeclsToConsumer() {
6589 if (PassingDeclsToConsumer)
6592 // Guard variable to avoid recursively redoing the process of passing
6593 // decls to consumer.
6594 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6597 while (!InterestingDecls.empty()) {
6598 Decl *D = InterestingDecls.front();
6599 InterestingDecls.pop_front();
6601 PassInterestingDeclToConsumer(D);
6605 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6606 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6607 PassObjCImplDeclToConsumer(ImplD, Consumer);
6609 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6612 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6613 this->Consumer = Consumer;
6618 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
6619 // Force deserialization of this decl, which will cause it to be queued for
6620 // passing to the consumer.
6621 GetDecl(EagerlyDeserializedDecls[I]);
6623 EagerlyDeserializedDecls.clear();
6625 PassInterestingDeclsToConsumer();
6628 void ASTReader::PrintStats() {
6629 std::fprintf(stderr, "*** AST File Statistics:\n");
6631 unsigned NumTypesLoaded
6632 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6634 unsigned NumDeclsLoaded
6635 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6637 unsigned NumIdentifiersLoaded
6638 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6639 IdentifiersLoaded.end(),
6640 (IdentifierInfo *)nullptr);
6641 unsigned NumMacrosLoaded
6642 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6644 (MacroInfo *)nullptr);
6645 unsigned NumSelectorsLoaded
6646 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6647 SelectorsLoaded.end(),
6650 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6651 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6652 NumSLocEntriesRead, TotalNumSLocEntries,
6653 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6654 if (!TypesLoaded.empty())
6655 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6656 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6657 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6658 if (!DeclsLoaded.empty())
6659 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6660 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6661 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6662 if (!IdentifiersLoaded.empty())
6663 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6664 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6665 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6666 if (!MacrosLoaded.empty())
6667 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6668 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6669 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6670 if (!SelectorsLoaded.empty())
6671 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6672 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6673 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6674 if (TotalNumStatements)
6675 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6676 NumStatementsRead, TotalNumStatements,
6677 ((float)NumStatementsRead/TotalNumStatements * 100));
6679 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6680 NumMacrosRead, TotalNumMacros,
6681 ((float)NumMacrosRead/TotalNumMacros * 100));
6682 if (TotalLexicalDeclContexts)
6683 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6684 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6685 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6687 if (TotalVisibleDeclContexts)
6688 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6689 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6690 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6692 if (TotalNumMethodPoolEntries) {
6693 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6694 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6695 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6698 if (NumMethodPoolLookups) {
6699 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6700 NumMethodPoolHits, NumMethodPoolLookups,
6701 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6703 if (NumMethodPoolTableLookups) {
6704 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6705 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6706 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6710 if (NumIdentifierLookupHits) {
6711 std::fprintf(stderr,
6712 " %u / %u identifier table lookups succeeded (%f%%)\n",
6713 NumIdentifierLookupHits, NumIdentifierLookups,
6714 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6718 std::fprintf(stderr, "\n");
6719 GlobalIndex->printStats();
6722 std::fprintf(stderr, "\n");
6724 std::fprintf(stderr, "\n");
6727 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6729 dumpModuleIDMap(StringRef Name,
6730 const ContinuousRangeMap<Key, ModuleFile *,
6731 InitialCapacity> &Map) {
6732 if (Map.begin() == Map.end())
6735 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6736 llvm::errs() << Name << ":\n";
6737 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6739 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6744 void ASTReader::dump() {
6745 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6746 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6747 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6748 dumpModuleIDMap("Global type map", GlobalTypeMap);
6749 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6750 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6751 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6752 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6753 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6754 dumpModuleIDMap("Global preprocessed entity map",
6755 GlobalPreprocessedEntityMap);
6757 llvm::errs() << "\n*** PCH/Modules Loaded:";
6758 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6759 MEnd = ModuleMgr.end();
6764 /// Return the amount of memory used by memory buffers, breaking down
6765 /// by heap-backed versus mmap'ed memory.
6766 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6767 for (ModuleConstIterator I = ModuleMgr.begin(),
6768 E = ModuleMgr.end(); I != E; ++I) {
6769 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6770 size_t bytes = buf->getBufferSize();
6771 switch (buf->getBufferKind()) {
6772 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6773 sizes.malloc_bytes += bytes;
6775 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6776 sizes.mmap_bytes += bytes;
6783 void ASTReader::InitializeSema(Sema &S) {
6785 S.addExternalSource(this);
6787 // Makes sure any declarations that were deserialized "too early"
6788 // still get added to the identifier's declaration chains.
6789 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
6790 pushExternalDeclIntoScope(PreloadedDecls[I],
6791 PreloadedDecls[I]->getDeclName());
6793 PreloadedDecls.clear();
6795 // FIXME: What happens if these are changed by a module import?
6796 if (!FPPragmaOptions.empty()) {
6797 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6798 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6801 // FIXME: What happens if these are changed by a module import?
6802 if (!OpenCLExtensions.empty()) {
6804 #define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6805 #include "clang/Basic/OpenCLExtensions.def"
6807 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6813 void ASTReader::UpdateSema() {
6814 assert(SemaObj && "no Sema to update");
6816 // Load the offsets of the declarations that Sema references.
6817 // They will be lazily deserialized when needed.
6818 if (!SemaDeclRefs.empty()) {
6819 assert(SemaDeclRefs.size() % 2 == 0);
6820 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6821 if (!SemaObj->StdNamespace)
6822 SemaObj->StdNamespace = SemaDeclRefs[I];
6823 if (!SemaObj->StdBadAlloc)
6824 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6826 SemaDeclRefs.clear();
6829 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6830 // encountered the pragma in the source.
6831 if(OptimizeOffPragmaLocation.isValid())
6832 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
6835 IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6836 // Note that we are loading an identifier.
6837 Deserializing AnIdentifier(this);
6838 StringRef Name(NameStart, NameEnd - NameStart);
6840 // If there is a global index, look there first to determine which modules
6841 // provably do not have any results for this identifier.
6842 GlobalModuleIndex::HitSet Hits;
6843 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6844 if (!loadGlobalIndex()) {
6845 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6849 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
6850 NumIdentifierLookups,
6851 NumIdentifierLookupHits);
6852 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
6853 IdentifierInfo *II = Visitor.getIdentifierInfo();
6854 markIdentifierUpToDate(II);
6859 /// \brief An identifier-lookup iterator that enumerates all of the
6860 /// identifiers stored within a set of AST files.
6861 class ASTIdentifierIterator : public IdentifierIterator {
6862 /// \brief The AST reader whose identifiers are being enumerated.
6863 const ASTReader &Reader;
6865 /// \brief The current index into the chain of AST files stored in
6869 /// \brief The current position within the identifier lookup table
6870 /// of the current AST file.
6871 ASTIdentifierLookupTable::key_iterator Current;
6873 /// \brief The end position within the identifier lookup table of
6874 /// the current AST file.
6875 ASTIdentifierLookupTable::key_iterator End;
6878 explicit ASTIdentifierIterator(const ASTReader &Reader);
6880 StringRef Next() override;
6884 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6885 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6886 ASTIdentifierLookupTable *IdTable
6887 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6888 Current = IdTable->key_begin();
6889 End = IdTable->key_end();
6892 StringRef ASTIdentifierIterator::Next() {
6893 while (Current == End) {
6894 // If we have exhausted all of our AST files, we're done.
6899 ASTIdentifierLookupTable *IdTable
6900 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6901 IdentifierLookupTable;
6902 Current = IdTable->key_begin();
6903 End = IdTable->key_end();
6906 // We have any identifiers remaining in the current AST file; return
6908 StringRef Result = *Current;
6913 IdentifierIterator *ASTReader::getIdentifiers() {
6914 if (!loadGlobalIndex())
6915 return GlobalIndex->createIdentifierIterator();
6917 return new ASTIdentifierIterator(*this);
6920 namespace clang { namespace serialization {
6921 class ReadMethodPoolVisitor {
6924 unsigned PriorGeneration;
6925 unsigned InstanceBits;
6926 unsigned FactoryBits;
6927 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6928 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
6931 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6932 unsigned PriorGeneration)
6933 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6934 InstanceBits(0), FactoryBits(0) { }
6936 static bool visit(ModuleFile &M, void *UserData) {
6937 ReadMethodPoolVisitor *This
6938 = static_cast<ReadMethodPoolVisitor *>(UserData);
6940 if (!M.SelectorLookupTable)
6943 // If we've already searched this module file, skip it now.
6944 if (M.Generation <= This->PriorGeneration)
6947 ++This->Reader.NumMethodPoolTableLookups;
6948 ASTSelectorLookupTable *PoolTable
6949 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6950 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6951 if (Pos == PoolTable->end())
6954 ++This->Reader.NumMethodPoolTableHits;
6955 ++This->Reader.NumSelectorsRead;
6956 // FIXME: Not quite happy with the statistics here. We probably should
6957 // disable this tracking when called via LoadSelector.
6958 // Also, should entries without methods count as misses?
6959 ++This->Reader.NumMethodPoolEntriesRead;
6960 ASTSelectorLookupTrait::data_type Data = *Pos;
6961 if (This->Reader.DeserializationListener)
6962 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6965 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6966 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6967 This->InstanceBits = Data.InstanceBits;
6968 This->FactoryBits = Data.FactoryBits;
6972 /// \brief Retrieve the instance methods found by this visitor.
6973 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6974 return InstanceMethods;
6977 /// \brief Retrieve the instance methods found by this visitor.
6978 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6979 return FactoryMethods;
6982 unsigned getInstanceBits() const { return InstanceBits; }
6983 unsigned getFactoryBits() const { return FactoryBits; }
6985 } } // end namespace clang::serialization
6987 /// \brief Add the given set of methods to the method list.
6988 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6989 ObjCMethodList &List) {
6990 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6991 S.addMethodToGlobalList(&List, Methods[I]);
6995 void ASTReader::ReadMethodPool(Selector Sel) {
6996 // Get the selector generation and update it to the current generation.
6997 unsigned &Generation = SelectorGeneration[Sel];
6998 unsigned PriorGeneration = Generation;
6999 Generation = getGeneration();
7001 // Search for methods defined with this selector.
7002 ++NumMethodPoolLookups;
7003 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7004 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7006 if (Visitor.getInstanceMethods().empty() &&
7007 Visitor.getFactoryMethods().empty())
7010 ++NumMethodPoolHits;
7015 Sema &S = *getSema();
7016 Sema::GlobalMethodPool::iterator Pos
7017 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7019 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7020 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
7021 Pos->second.first.setBits(Visitor.getInstanceBits());
7022 Pos->second.second.setBits(Visitor.getFactoryBits());
7025 void ASTReader::ReadKnownNamespaces(
7026 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7029 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7030 if (NamespaceDecl *Namespace
7031 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7032 Namespaces.push_back(Namespace);
7036 void ASTReader::ReadUndefinedButUsed(
7037 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
7038 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7039 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
7040 SourceLocation Loc =
7041 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
7042 Undefined.insert(std::make_pair(D, Loc));
7046 void ASTReader::ReadTentativeDefinitions(
7047 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7048 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7049 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7051 TentativeDefs.push_back(Var);
7053 TentativeDefinitions.clear();
7056 void ASTReader::ReadUnusedFileScopedDecls(
7057 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7058 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7060 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7064 UnusedFileScopedDecls.clear();
7067 void ASTReader::ReadDelegatingConstructors(
7068 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7069 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7070 CXXConstructorDecl *D
7071 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7075 DelegatingCtorDecls.clear();
7078 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7079 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7081 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7085 ExtVectorDecls.clear();
7088 void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7089 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7091 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7095 DynamicClasses.clear();
7099 ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7100 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7102 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
7106 LocallyScopedExternCDecls.clear();
7109 void ASTReader::ReadReferencedSelectors(
7110 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7111 if (ReferencedSelectorsData.empty())
7114 // If there are @selector references added them to its pool. This is for
7115 // implementation of -Wselector.
7116 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7118 while (I < DataSize) {
7119 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7120 SourceLocation SelLoc
7121 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7122 Sels.push_back(std::make_pair(Sel, SelLoc));
7124 ReferencedSelectorsData.clear();
7127 void ASTReader::ReadWeakUndeclaredIdentifiers(
7128 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7129 if (WeakUndeclaredIdentifiers.empty())
7132 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7133 IdentifierInfo *WeakId
7134 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7135 IdentifierInfo *AliasId
7136 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7138 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7139 bool Used = WeakUndeclaredIdentifiers[I++];
7140 WeakInfo WI(AliasId, Loc);
7142 WeakIDs.push_back(std::make_pair(WeakId, WI));
7144 WeakUndeclaredIdentifiers.clear();
7147 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7148 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7149 ExternalVTableUse VT;
7150 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7151 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7152 VT.DefinitionRequired = VTableUses[Idx++];
7153 VTables.push_back(VT);
7159 void ASTReader::ReadPendingInstantiations(
7160 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7161 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7162 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7164 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7166 Pending.push_back(std::make_pair(D, Loc));
7168 PendingInstantiations.clear();
7171 void ASTReader::ReadLateParsedTemplates(
7172 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7173 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7175 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7177 LateParsedTemplate *LT = new LateParsedTemplate;
7178 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7180 ModuleFile *F = getOwningModuleFile(LT->D);
7181 assert(F && "No module");
7183 unsigned TokN = LateParsedTemplates[Idx++];
7184 LT->Toks.reserve(TokN);
7185 for (unsigned T = 0; T < TokN; ++T)
7186 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7191 LateParsedTemplates.clear();
7194 void ASTReader::LoadSelector(Selector Sel) {
7195 // It would be complicated to avoid reading the methods anyway. So don't.
7196 ReadMethodPool(Sel);
7199 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7200 assert(ID && "Non-zero identifier ID required");
7201 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7202 IdentifiersLoaded[ID - 1] = II;
7203 if (DeserializationListener)
7204 DeserializationListener->IdentifierRead(ID, II);
7207 /// \brief Set the globally-visible declarations associated with the given
7210 /// If the AST reader is currently in a state where the given declaration IDs
7211 /// cannot safely be resolved, they are queued until it is safe to resolve
7214 /// \param II an IdentifierInfo that refers to one or more globally-visible
7217 /// \param DeclIDs the set of declaration IDs with the name @p II that are
7218 /// visible at global scope.
7220 /// \param Decls if non-null, this vector will be populated with the set of
7221 /// deserialized declarations. These declarations will not be pushed into
7224 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7225 const SmallVectorImpl<uint32_t> &DeclIDs,
7226 SmallVectorImpl<Decl *> *Decls) {
7227 if (NumCurrentElementsDeserializing && !Decls) {
7228 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
7232 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7233 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7235 // If we're simply supposed to record the declarations, do so now.
7237 Decls->push_back(D);
7241 // Introduce this declaration into the translation-unit scope
7242 // and add it to the declaration chain for this identifier, so
7243 // that (unqualified) name lookup will find it.
7244 pushExternalDeclIntoScope(D, II);
7246 // Queue this declaration so that it will be added to the
7247 // translation unit scope and identifier's declaration chain
7248 // once a Sema object is known.
7249 PreloadedDecls.push_back(D);
7254 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
7258 if (IdentifiersLoaded.empty()) {
7259 Error("no identifier table in AST file");
7264 if (!IdentifiersLoaded[ID]) {
7265 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7266 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7267 ModuleFile *M = I->second;
7268 unsigned Index = ID - M->BaseIdentifierID;
7269 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7271 // All of the strings in the AST file are preceded by a 16-bit length.
7272 // Extract that 16-bit length to avoid having to execute strlen().
7273 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7274 // unsigned integers. This is important to avoid integer overflow when
7275 // we cast them to 'unsigned'.
7276 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7277 unsigned StrLen = (((unsigned) StrLenPtr[0])
7278 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
7279 IdentifiersLoaded[ID]
7280 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
7281 if (DeserializationListener)
7282 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7285 return IdentifiersLoaded[ID];
7288 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7289 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
7292 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7293 if (LocalID < NUM_PREDEF_IDENT_IDS)
7296 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7297 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7298 assert(I != M.IdentifierRemap.end()
7299 && "Invalid index into identifier index remap");
7301 return LocalID + I->second;
7304 MacroInfo *ASTReader::getMacro(MacroID ID) {
7308 if (MacrosLoaded.empty()) {
7309 Error("no macro table in AST file");
7313 ID -= NUM_PREDEF_MACRO_IDS;
7314 if (!MacrosLoaded[ID]) {
7315 GlobalMacroMapType::iterator I
7316 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7317 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7318 ModuleFile *M = I->second;
7319 unsigned Index = ID - M->BaseMacroID;
7320 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7322 if (DeserializationListener)
7323 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7327 return MacrosLoaded[ID];
7330 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7331 if (LocalID < NUM_PREDEF_MACRO_IDS)
7334 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7335 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7336 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7338 return LocalID + I->second;
7341 serialization::SubmoduleID
7342 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7343 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7346 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7347 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7348 assert(I != M.SubmoduleRemap.end()
7349 && "Invalid index into submodule index remap");
7351 return LocalID + I->second;
7354 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7355 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7356 assert(GlobalID == 0 && "Unhandled global submodule ID");
7360 if (GlobalID > SubmodulesLoaded.size()) {
7361 Error("submodule ID out of range in AST file");
7365 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7368 Module *ASTReader::getModule(unsigned ID) {
7369 return getSubmodule(ID);
7372 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7373 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7376 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7380 if (ID > SelectorsLoaded.size()) {
7381 Error("selector ID out of range in AST file");
7385 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
7386 // Load this selector from the selector table.
7387 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7388 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7389 ModuleFile &M = *I->second;
7390 ASTSelectorLookupTrait Trait(*this, M);
7391 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7392 SelectorsLoaded[ID - 1] =
7393 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7394 if (DeserializationListener)
7395 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7398 return SelectorsLoaded[ID - 1];
7401 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7402 return DecodeSelector(ID);
7405 uint32_t ASTReader::GetNumExternalSelectors() {
7406 // ID 0 (the null selector) is considered an external selector.
7407 return getTotalNumSelectors() + 1;
7410 serialization::SelectorID
7411 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7412 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7415 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7416 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7417 assert(I != M.SelectorRemap.end()
7418 && "Invalid index into selector index remap");
7420 return LocalID + I->second;
7424 ASTReader::ReadDeclarationName(ModuleFile &F,
7425 const RecordData &Record, unsigned &Idx) {
7426 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7428 case DeclarationName::Identifier:
7429 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
7431 case DeclarationName::ObjCZeroArgSelector:
7432 case DeclarationName::ObjCOneArgSelector:
7433 case DeclarationName::ObjCMultiArgSelector:
7434 return DeclarationName(ReadSelector(F, Record, Idx));
7436 case DeclarationName::CXXConstructorName:
7437 return Context.DeclarationNames.getCXXConstructorName(
7438 Context.getCanonicalType(readType(F, Record, Idx)));
7440 case DeclarationName::CXXDestructorName:
7441 return Context.DeclarationNames.getCXXDestructorName(
7442 Context.getCanonicalType(readType(F, Record, Idx)));
7444 case DeclarationName::CXXConversionFunctionName:
7445 return Context.DeclarationNames.getCXXConversionFunctionName(
7446 Context.getCanonicalType(readType(F, Record, Idx)));
7448 case DeclarationName::CXXOperatorName:
7449 return Context.DeclarationNames.getCXXOperatorName(
7450 (OverloadedOperatorKind)Record[Idx++]);
7452 case DeclarationName::CXXLiteralOperatorName:
7453 return Context.DeclarationNames.getCXXLiteralOperatorName(
7454 GetIdentifierInfo(F, Record, Idx));
7456 case DeclarationName::CXXUsingDirective:
7457 return DeclarationName::getUsingDirectiveName();
7460 llvm_unreachable("Invalid NameKind!");
7463 void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7464 DeclarationNameLoc &DNLoc,
7465 DeclarationName Name,
7466 const RecordData &Record, unsigned &Idx) {
7467 switch (Name.getNameKind()) {
7468 case DeclarationName::CXXConstructorName:
7469 case DeclarationName::CXXDestructorName:
7470 case DeclarationName::CXXConversionFunctionName:
7471 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7474 case DeclarationName::CXXOperatorName:
7475 DNLoc.CXXOperatorName.BeginOpNameLoc
7476 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7477 DNLoc.CXXOperatorName.EndOpNameLoc
7478 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7481 case DeclarationName::CXXLiteralOperatorName:
7482 DNLoc.CXXLiteralOperatorName.OpNameLoc
7483 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7486 case DeclarationName::Identifier:
7487 case DeclarationName::ObjCZeroArgSelector:
7488 case DeclarationName::ObjCOneArgSelector:
7489 case DeclarationName::ObjCMultiArgSelector:
7490 case DeclarationName::CXXUsingDirective:
7495 void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7496 DeclarationNameInfo &NameInfo,
7497 const RecordData &Record, unsigned &Idx) {
7498 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7499 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7500 DeclarationNameLoc DNLoc;
7501 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7502 NameInfo.setInfo(DNLoc);
7505 void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7506 const RecordData &Record, unsigned &Idx) {
7507 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7508 unsigned NumTPLists = Record[Idx++];
7509 Info.NumTemplParamLists = NumTPLists;
7511 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7512 for (unsigned i=0; i != NumTPLists; ++i)
7513 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7518 ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7520 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7522 case TemplateName::Template:
7523 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7525 case TemplateName::OverloadedTemplate: {
7526 unsigned size = Record[Idx++];
7527 UnresolvedSet<8> Decls;
7529 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7531 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7534 case TemplateName::QualifiedTemplate: {
7535 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7536 bool hasTemplKeyword = Record[Idx++];
7537 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7538 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7541 case TemplateName::DependentTemplate: {
7542 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7543 if (Record[Idx++]) // isIdentifier
7544 return Context.getDependentTemplateName(NNS,
7545 GetIdentifierInfo(F, Record,
7547 return Context.getDependentTemplateName(NNS,
7548 (OverloadedOperatorKind)Record[Idx++]);
7551 case TemplateName::SubstTemplateTemplateParm: {
7552 TemplateTemplateParmDecl *param
7553 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7554 if (!param) return TemplateName();
7555 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7556 return Context.getSubstTemplateTemplateParm(param, replacement);
7559 case TemplateName::SubstTemplateTemplateParmPack: {
7560 TemplateTemplateParmDecl *Param
7561 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7563 return TemplateName();
7565 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7566 if (ArgPack.getKind() != TemplateArgument::Pack)
7567 return TemplateName();
7569 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7573 llvm_unreachable("Unhandled template name kind!");
7577 ASTReader::ReadTemplateArgument(ModuleFile &F,
7578 const RecordData &Record, unsigned &Idx) {
7579 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7581 case TemplateArgument::Null:
7582 return TemplateArgument();
7583 case TemplateArgument::Type:
7584 return TemplateArgument(readType(F, Record, Idx));
7585 case TemplateArgument::Declaration: {
7586 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7587 bool ForReferenceParam = Record[Idx++];
7588 return TemplateArgument(D, ForReferenceParam);
7590 case TemplateArgument::NullPtr:
7591 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7592 case TemplateArgument::Integral: {
7593 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7594 QualType T = readType(F, Record, Idx);
7595 return TemplateArgument(Context, Value, T);
7597 case TemplateArgument::Template:
7598 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7599 case TemplateArgument::TemplateExpansion: {
7600 TemplateName Name = ReadTemplateName(F, Record, Idx);
7601 Optional<unsigned> NumTemplateExpansions;
7602 if (unsigned NumExpansions = Record[Idx++])
7603 NumTemplateExpansions = NumExpansions - 1;
7604 return TemplateArgument(Name, NumTemplateExpansions);
7606 case TemplateArgument::Expression:
7607 return TemplateArgument(ReadExpr(F));
7608 case TemplateArgument::Pack: {
7609 unsigned NumArgs = Record[Idx++];
7610 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7611 for (unsigned I = 0; I != NumArgs; ++I)
7612 Args[I] = ReadTemplateArgument(F, Record, Idx);
7613 return TemplateArgument(Args, NumArgs);
7617 llvm_unreachable("Unhandled template argument kind!");
7620 TemplateParameterList *
7621 ASTReader::ReadTemplateParameterList(ModuleFile &F,
7622 const RecordData &Record, unsigned &Idx) {
7623 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7624 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7625 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7627 unsigned NumParams = Record[Idx++];
7628 SmallVector<NamedDecl *, 16> Params;
7629 Params.reserve(NumParams);
7631 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7633 TemplateParameterList* TemplateParams =
7634 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7635 Params.data(), Params.size(), RAngleLoc);
7636 return TemplateParams;
7641 ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
7642 ModuleFile &F, const RecordData &Record,
7644 unsigned NumTemplateArgs = Record[Idx++];
7645 TemplArgs.reserve(NumTemplateArgs);
7646 while (NumTemplateArgs--)
7647 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7650 /// \brief Read a UnresolvedSet structure.
7651 void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
7652 const RecordData &Record, unsigned &Idx) {
7653 unsigned NumDecls = Record[Idx++];
7654 Set.reserve(Context, NumDecls);
7655 while (NumDecls--) {
7656 DeclID ID = ReadDeclID(F, Record, Idx);
7657 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
7658 Set.addLazyDecl(Context, ID, AS);
7663 ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7664 const RecordData &Record, unsigned &Idx) {
7665 bool isVirtual = static_cast<bool>(Record[Idx++]);
7666 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7667 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7668 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7669 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7670 SourceRange Range = ReadSourceRange(F, Record, Idx);
7671 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7672 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7674 Result.setInheritConstructors(inheritConstructors);
7678 std::pair<CXXCtorInitializer **, unsigned>
7679 ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7681 CXXCtorInitializer **CtorInitializers = nullptr;
7682 unsigned NumInitializers = Record[Idx++];
7683 if (NumInitializers) {
7685 = new (Context) CXXCtorInitializer*[NumInitializers];
7686 for (unsigned i=0; i != NumInitializers; ++i) {
7687 TypeSourceInfo *TInfo = nullptr;
7688 bool IsBaseVirtual = false;
7689 FieldDecl *Member = nullptr;
7690 IndirectFieldDecl *IndirectMember = nullptr;
7692 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7694 case CTOR_INITIALIZER_BASE:
7695 TInfo = GetTypeSourceInfo(F, Record, Idx);
7696 IsBaseVirtual = Record[Idx++];
7699 case CTOR_INITIALIZER_DELEGATING:
7700 TInfo = GetTypeSourceInfo(F, Record, Idx);
7703 case CTOR_INITIALIZER_MEMBER:
7704 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7707 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7708 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7712 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7713 Expr *Init = ReadExpr(F);
7714 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7715 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7716 bool IsWritten = Record[Idx++];
7717 unsigned SourceOrderOrNumArrayIndices;
7718 SmallVector<VarDecl *, 8> Indices;
7720 SourceOrderOrNumArrayIndices = Record[Idx++];
7722 SourceOrderOrNumArrayIndices = Record[Idx++];
7723 Indices.reserve(SourceOrderOrNumArrayIndices);
7724 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7725 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7728 CXXCtorInitializer *BOMInit;
7729 if (Type == CTOR_INITIALIZER_BASE) {
7730 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7731 LParenLoc, Init, RParenLoc,
7732 MemberOrEllipsisLoc);
7733 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7734 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7736 } else if (IsWritten) {
7738 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7739 LParenLoc, Init, RParenLoc);
7741 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7742 MemberOrEllipsisLoc, LParenLoc,
7745 if (IndirectMember) {
7746 assert(Indices.empty() && "Indirect field improperly initialized");
7747 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7748 MemberOrEllipsisLoc, LParenLoc,
7751 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7752 LParenLoc, Init, RParenLoc,
7753 Indices.data(), Indices.size());
7758 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7759 CtorInitializers[i] = BOMInit;
7763 return std::make_pair(CtorInitializers, NumInitializers);
7766 NestedNameSpecifier *
7767 ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7768 const RecordData &Record, unsigned &Idx) {
7769 unsigned N = Record[Idx++];
7770 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
7771 for (unsigned I = 0; I != N; ++I) {
7772 NestedNameSpecifier::SpecifierKind Kind
7773 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7775 case NestedNameSpecifier::Identifier: {
7776 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7777 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7781 case NestedNameSpecifier::Namespace: {
7782 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7783 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7787 case NestedNameSpecifier::NamespaceAlias: {
7788 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7789 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7793 case NestedNameSpecifier::TypeSpec:
7794 case NestedNameSpecifier::TypeSpecWithTemplate: {
7795 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7799 bool Template = Record[Idx++];
7800 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7804 case NestedNameSpecifier::Global: {
7805 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7806 // No associated value, and there can't be a prefix.
7815 NestedNameSpecifierLoc
7816 ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7818 unsigned N = Record[Idx++];
7819 NestedNameSpecifierLocBuilder Builder;
7820 for (unsigned I = 0; I != N; ++I) {
7821 NestedNameSpecifier::SpecifierKind Kind
7822 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7824 case NestedNameSpecifier::Identifier: {
7825 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7826 SourceRange Range = ReadSourceRange(F, Record, Idx);
7827 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7831 case NestedNameSpecifier::Namespace: {
7832 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7833 SourceRange Range = ReadSourceRange(F, Record, Idx);
7834 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7838 case NestedNameSpecifier::NamespaceAlias: {
7839 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7840 SourceRange Range = ReadSourceRange(F, Record, Idx);
7841 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7845 case NestedNameSpecifier::TypeSpec:
7846 case NestedNameSpecifier::TypeSpecWithTemplate: {
7847 bool Template = Record[Idx++];
7848 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7850 return NestedNameSpecifierLoc();
7851 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7853 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7854 Builder.Extend(Context,
7855 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7856 T->getTypeLoc(), ColonColonLoc);
7860 case NestedNameSpecifier::Global: {
7861 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7862 Builder.MakeGlobal(Context, ColonColonLoc);
7868 return Builder.getWithLocInContext(Context);
7872 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7874 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7875 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7876 return SourceRange(beg, end);
7879 /// \brief Read an integral value
7880 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7881 unsigned BitWidth = Record[Idx++];
7882 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7883 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7888 /// \brief Read a signed integral value
7889 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7890 bool isUnsigned = Record[Idx++];
7891 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7894 /// \brief Read a floating-point value
7895 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7896 const llvm::fltSemantics &Sem,
7898 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
7901 // \brief Read a string
7902 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7903 unsigned Len = Record[Idx++];
7904 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7909 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7911 unsigned Major = Record[Idx++];
7912 unsigned Minor = Record[Idx++];
7913 unsigned Subminor = Record[Idx++];
7915 return VersionTuple(Major);
7917 return VersionTuple(Major, Minor - 1);
7918 return VersionTuple(Major, Minor - 1, Subminor - 1);
7921 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7922 const RecordData &Record,
7924 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7925 return CXXTemporary::Create(Context, Decl);
7928 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
7929 return Diag(CurrentImportLoc, DiagID);
7932 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7933 return Diags.Report(Loc, DiagID);
7936 /// \brief Retrieve the identifier table associated with the
7938 IdentifierTable &ASTReader::getIdentifierTable() {
7939 return PP.getIdentifierTable();
7942 /// \brief Record that the given ID maps to the given switch-case
7944 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7945 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
7946 "Already have a SwitchCase with this ID");
7947 (*CurrSwitchCaseStmts)[ID] = SC;
7950 /// \brief Retrieve the switch-case statement with the given ID.
7951 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7952 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
7953 return (*CurrSwitchCaseStmts)[ID];
7956 void ASTReader::ClearSwitchCaseIDs() {
7957 CurrSwitchCaseStmts->clear();
7960 void ASTReader::ReadComments() {
7961 std::vector<RawComment *> Comments;
7962 for (SmallVectorImpl<std::pair<BitstreamCursor,
7963 serialization::ModuleFile *> >::iterator
7964 I = CommentsCursors.begin(),
7965 E = CommentsCursors.end();
7968 BitstreamCursor &Cursor = I->first;
7969 serialization::ModuleFile &F = *I->second;
7970 SavedStreamPosition SavedPosition(Cursor);
7974 llvm::BitstreamEntry Entry =
7975 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
7977 switch (Entry.Kind) {
7978 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7979 case llvm::BitstreamEntry::Error:
7980 Error("malformed block record in AST file");
7982 case llvm::BitstreamEntry::EndBlock:
7984 case llvm::BitstreamEntry::Record:
7985 // The interesting case.
7991 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
7992 case COMMENTS_RAW_COMMENT: {
7994 SourceRange SR = ReadSourceRange(F, Record, Idx);
7995 RawComment::CommentKind Kind =
7996 (RawComment::CommentKind) Record[Idx++];
7997 bool IsTrailingComment = Record[Idx++];
7998 bool IsAlmostTrailingComment = Record[Idx++];
7999 Comments.push_back(new (Context) RawComment(
8000 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8001 Context.getLangOpts().CommentOpts.ParseAllComments));
8007 Context.Comments.addDeserializedComments(Comments);
8011 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8012 // If we know the owning module, use it.
8013 if (Module *M = D->getOwningModule())
8014 return M->getFullModuleName();
8016 // Otherwise, use the name of the top-level module the decl is within.
8017 if (ModuleFile *M = getOwningModuleFile(D))
8018 return M->ModuleName;
8020 // Not from a module.
8024 void ASTReader::finishPendingActions() {
8025 while (!PendingIdentifierInfos.empty() ||
8026 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
8027 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
8028 !PendingUpdateRecords.empty() || !PendingOdrMergeChecks.empty()) {
8029 // If any identifiers with corresponding top-level declarations have
8030 // been loaded, load those declarations now.
8031 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8033 TopLevelDeclsMap TopLevelDecls;
8035 while (!PendingIdentifierInfos.empty()) {
8036 IdentifierInfo *II = PendingIdentifierInfos.back().first;
8037 SmallVector<uint32_t, 4> DeclIDs =
8038 std::move(PendingIdentifierInfos.back().second);
8039 PendingIdentifierInfos.pop_back();
8041 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
8044 // For each decl chain that we wanted to complete while deserializing, mark
8045 // it as "still needs to be completed".
8046 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8047 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8049 PendingIncompleteDeclChains.clear();
8051 // Load pending declaration chains.
8052 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8053 loadPendingDeclChain(PendingDeclChains[I]);
8054 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8056 PendingDeclChains.clear();
8058 // Make the most recent of the top-level declarations visible.
8059 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8060 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
8061 IdentifierInfo *II = TLD->first;
8062 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
8063 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
8067 // Load any pending macro definitions.
8068 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
8069 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8070 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8071 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8072 // Initialize the macro history from chained-PCHs ahead of module imports.
8073 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8075 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8076 if (Info.M->Kind != MK_Module)
8077 resolvePendingMacro(II, Info);
8079 // Handle module imports.
8080 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8082 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8083 if (Info.M->Kind == MK_Module)
8084 resolvePendingMacro(II, Info);
8087 PendingMacroIDs.clear();
8089 // Wire up the DeclContexts for Decls that we delayed setting until
8090 // recursive loading is completed.
8091 while (!PendingDeclContextInfos.empty()) {
8092 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8093 PendingDeclContextInfos.pop_front();
8094 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8095 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8096 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8099 // Perform any pending declaration updates.
8101 // Don't do this if we have known-incomplete redecl chains: it relies on
8102 // being able to walk redeclaration chains.
8103 while (PendingDeclChains.empty() && !PendingUpdateRecords.empty()) {
8104 auto Update = PendingUpdateRecords.pop_back_val();
8105 ReadingKindTracker ReadingKind(Read_Decl, *this);
8106 loadDeclUpdateRecords(Update.first, Update.second);
8109 // Trigger the import of the full definition of each class that had any
8110 // odr-merging problems, so we can produce better diagnostics for them.
8111 for (auto &Merge : PendingOdrMergeFailures) {
8112 Merge.first->buildLookup();
8113 Merge.first->decls_begin();
8114 Merge.first->bases_begin();
8115 Merge.first->vbases_begin();
8116 for (auto *RD : Merge.second) {
8123 // For each declaration from a merged context, check that the canonical
8124 // definition of that context also contains a declaration of the same
8126 while (!PendingOdrMergeChecks.empty()) {
8127 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8129 // FIXME: Skip over implicit declarations for now. This matters for things
8130 // like implicitly-declared special member functions. This isn't entirely
8131 // correct; we can end up with multiple unmerged declarations of the same
8133 if (D->isImplicit())
8136 DeclContext *CanonDef = D->getDeclContext();
8137 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
8140 const Decl *DCanon = D->getCanonicalDecl();
8142 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8143 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8144 !Found && I != E; ++I) {
8145 for (auto RI : (*I)->redecls()) {
8146 if (RI->getLexicalDeclContext() == CanonDef) {
8147 // This declaration is present in the canonical definition. If it's
8148 // in the same redecl chain, it's the one we're looking for.
8149 if (RI->getCanonicalDecl() == DCanon)
8152 Candidates.push_back(cast<NamedDecl>(RI));
8159 D->setInvalidDecl();
8161 std::string CanonDefModule =
8162 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8163 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8164 << D << getOwningModuleNameForDiagnostic(D)
8165 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8167 if (Candidates.empty())
8168 Diag(cast<Decl>(CanonDef)->getLocation(),
8169 diag::note_module_odr_violation_no_possible_decls) << D;
8171 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8172 Diag(Candidates[I]->getLocation(),
8173 diag::note_module_odr_violation_possible_decl)
8177 DiagnosedOdrMergeFailures.insert(CanonDef);
8182 // If we deserialized any C++ or Objective-C class definitions, any
8183 // Objective-C protocol definitions, or any redeclarable templates, make sure
8184 // that all redeclarations point to the definitions. Note that this can only
8185 // happen now, after the redeclaration chains have been fully wired.
8186 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
8187 DEnd = PendingDefinitions.end();
8189 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
8190 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
8191 // Make sure that the TagType points at the definition.
8192 const_cast<TagType*>(TagT)->decl = TD;
8195 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
8196 for (auto R : RD->redecls())
8197 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
8203 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
8204 // Make sure that the ObjCInterfaceType points at the definition.
8205 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8208 for (auto R : ID->redecls())
8214 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
8215 for (auto R : PD->redecls())
8221 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
8222 for (auto R : RTD->redecls())
8223 R->Common = RTD->Common;
8225 PendingDefinitions.clear();
8227 // Load the bodies of any functions or methods we've encountered. We do
8228 // this now (delayed) so that we can be sure that the declaration chains
8229 // have been fully wired up.
8230 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8231 PBEnd = PendingBodies.end();
8232 PB != PBEnd; ++PB) {
8233 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8234 // FIXME: Check for =delete/=default?
8235 // FIXME: Complain about ODR violations here?
8236 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8237 FD->setLazyBody(PB->second);
8241 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8242 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8243 MD->setLazyBody(PB->second);
8245 PendingBodies.clear();
8247 // Issue any pending ODR-failure diagnostics.
8248 for (auto &Merge : PendingOdrMergeFailures) {
8249 if (!DiagnosedOdrMergeFailures.insert(Merge.first))
8252 bool Diagnosed = false;
8253 for (auto *RD : Merge.second) {
8254 // Multiple different declarations got merged together; tell the user
8255 // where they came from.
8256 if (Merge.first != RD) {
8257 // FIXME: Walk the definition, figure out what's different,
8258 // and diagnose that.
8260 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8261 Diag(Merge.first->getLocation(),
8262 diag::err_module_odr_violation_different_definitions)
8263 << Merge.first << Module.empty() << Module;
8267 Diag(RD->getLocation(),
8268 diag::note_module_odr_violation_different_definitions)
8269 << getOwningModuleNameForDiagnostic(RD);
8274 // All definitions are updates to the same declaration. This happens if a
8275 // module instantiates the declaration of a class template specialization
8276 // and two or more other modules instantiate its definition.
8278 // FIXME: Indicate which modules had instantiations of this definition.
8279 // FIXME: How can this even happen?
8280 Diag(Merge.first->getLocation(),
8281 diag::err_module_odr_violation_different_instantiations)
8285 PendingOdrMergeFailures.clear();
8288 void ASTReader::FinishedDeserializing() {
8289 assert(NumCurrentElementsDeserializing &&
8290 "FinishedDeserializing not paired with StartedDeserializing");
8291 if (NumCurrentElementsDeserializing == 1) {
8292 // We decrease NumCurrentElementsDeserializing only after pending actions
8293 // are finished, to avoid recursively re-calling finishPendingActions().
8294 finishPendingActions();
8296 --NumCurrentElementsDeserializing;
8298 if (NumCurrentElementsDeserializing == 0 && Consumer) {
8299 // We are not in recursive loading, so it's safe to pass the "interesting"
8300 // decls to the consumer.
8301 PassInterestingDeclsToConsumer();
8305 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
8306 D = D->getMostRecentDecl();
8308 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8309 SemaObj->TUScope->AddDecl(D);
8310 } else if (SemaObj->TUScope) {
8311 // Adding the decl to IdResolver may have failed because it was already in
8312 // (even though it was not added in scope). If it is already in, make sure
8313 // it gets in the scope as well.
8314 if (std::find(SemaObj->IdResolver.begin(Name),
8315 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8316 SemaObj->TUScope->AddDecl(D);
8320 ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8321 bool DisableValidation, bool AllowASTWithCompilerErrors,
8322 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8323 bool UseGlobalIndex)
8324 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
8325 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
8326 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8327 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8328 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8329 DisableValidation(DisableValidation),
8330 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8331 AllowConfigurationMismatch(AllowConfigurationMismatch),
8332 ValidateSystemInputs(ValidateSystemInputs),
8333 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
8334 CurrSwitchCaseStmts(&SwitchCaseStmts),
8335 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8336 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8337 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8338 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8339 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8340 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8341 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8342 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8343 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8344 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8345 ReadingKind(Read_None) {
8346 SourceMgr.setExternalSLocEntrySource(this);
8349 ASTReader::~ASTReader() {
8350 if (OwnsDeserializationListener)
8351 delete DeserializationListener;
8353 for (DeclContextVisibleUpdatesPending::iterator
8354 I = PendingVisibleUpdates.begin(),
8355 E = PendingVisibleUpdates.end();
8357 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8358 F = I->second.end();