96#include "llvm/ADT/APFloat.h"
97#include "llvm/ADT/APInt.h"
98#include "llvm/ADT/APSInt.h"
99#include "llvm/ADT/ArrayRef.h"
100#include "llvm/ADT/DenseMap.h"
101#include "llvm/ADT/FloatingPointMode.h"
102#include "llvm/ADT/FoldingSet.h"
103#include "llvm/ADT/Hashing.h"
104#include "llvm/ADT/IntrusiveRefCntPtr.h"
105#include "llvm/ADT/STLExtras.h"
106#include "llvm/ADT/ScopeExit.h"
107#include "llvm/ADT/Sequence.h"
108#include "llvm/ADT/SmallPtrSet.h"
109#include "llvm/ADT/SmallString.h"
110#include "llvm/ADT/SmallVector.h"
111#include "llvm/ADT/StringExtras.h"
112#include "llvm/ADT/StringMap.h"
113#include "llvm/ADT/StringRef.h"
114#include "llvm/ADT/iterator_range.h"
115#include "llvm/Bitstream/BitstreamReader.h"
116#include "llvm/Support/Casting.h"
117#include "llvm/Support/Compiler.h"
118#include "llvm/Support/Compression.h"
119#include "llvm/Support/DJB.h"
120#include "llvm/Support/Endian.h"
121#include "llvm/Support/Error.h"
122#include "llvm/Support/ErrorHandling.h"
123#include "llvm/Support/FileSystem.h"
124#include "llvm/Support/LEB128.h"
125#include "llvm/Support/MemoryBuffer.h"
126#include "llvm/Support/Path.h"
127#include "llvm/Support/SaveAndRestore.h"
128#include "llvm/Support/TimeProfiler.h"
129#include "llvm/Support/Timer.h"
130#include "llvm/Support/VersionTuple.h"
131#include "llvm/Support/raw_ostream.h"
132#include "llvm/TargetParser/Triple.h"
145#include <system_error>
150using namespace clang;
153using llvm::BitstreamCursor;
161 return First->ReadFullVersionInformation(FullVersion) ||
162 Second->ReadFullVersionInformation(FullVersion);
166 First->ReadModuleName(ModuleName);
167 Second->ReadModuleName(ModuleName);
171 First->ReadModuleMapFile(ModuleMapPath);
172 Second->ReadModuleMapFile(ModuleMapPath);
176 const LangOptions &LangOpts, StringRef ModuleFilename,
bool Complain,
177 bool AllowCompatibleDifferences) {
178 return First->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
179 AllowCompatibleDifferences) ||
180 Second->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
181 AllowCompatibleDifferences);
185 const TargetOptions &TargetOpts, StringRef ModuleFilename,
bool Complain,
186 bool AllowCompatibleDifferences) {
187 return First->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
188 AllowCompatibleDifferences) ||
189 Second->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
190 AllowCompatibleDifferences);
196 return First->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain) ||
197 Second->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
203 return First->ReadFileSystemOptions(FSOpts, Complain) ||
204 Second->ReadFileSystemOptions(FSOpts, Complain);
209 StringRef SpecificModuleCachePath,
bool Complain) {
210 return First->ReadHeaderSearchOptions(HSOpts, ModuleFilename,
211 SpecificModuleCachePath, Complain) ||
212 Second->ReadHeaderSearchOptions(HSOpts, ModuleFilename,
213 SpecificModuleCachePath, Complain);
218 bool ReadMacros,
bool Complain, std::string &SuggestedPredefines) {
219 return First->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
220 Complain, SuggestedPredefines) ||
221 Second->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
222 Complain, SuggestedPredefines);
227 First->ReadCounter(M,
Value);
228 Second->ReadCounter(M,
Value);
232 return First->needsInputFileVisitation() ||
233 Second->needsInputFileVisitation();
237 return First->needsSystemInputFileVisitation() ||
238 Second->needsSystemInputFileVisitation();
243 First->visitModuleFile(
Filename, Kind);
244 Second->visitModuleFile(
Filename, Kind);
250 bool isExplicitModule) {
251 bool Continue =
false;
252 if (First->needsInputFileVisitation() &&
253 (!isSystem || First->needsSystemInputFileVisitation()))
254 Continue |= First->visitInputFile(
Filename, isSystem, isOverridden,
256 if (Second->needsInputFileVisitation() &&
257 (!isSystem || Second->needsSystemInputFileVisitation()))
258 Continue |= Second->visitInputFile(
Filename, isSystem, isOverridden,
265 First->readModuleFileExtension(Metadata);
266 Second->readModuleFileExtension(Metadata);
285 StringRef ModuleFilename,
287 bool AllowCompatibleDifferences =
true) {
288#define LANGOPT(Name, Bits, Default, Description) \
289 if (ExistingLangOpts.Name != LangOpts.Name) { \
292 Diags->Report(diag::err_ast_file_langopt_mismatch) \
293 << Description << LangOpts.Name << ExistingLangOpts.Name \
296 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
297 << Description << ModuleFilename; \
302#define VALUE_LANGOPT(Name, Bits, Default, Description) \
303 if (ExistingLangOpts.Name != LangOpts.Name) { \
305 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
306 << Description << ModuleFilename; \
310#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
311 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
313 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
314 << Description << ModuleFilename; \
318#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
319 if (!AllowCompatibleDifferences) \
320 LANGOPT(Name, Bits, Default, Description)
322#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
323 if (!AllowCompatibleDifferences) \
324 ENUM_LANGOPT(Name, Bits, Default, Description)
326#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
327 if (!AllowCompatibleDifferences) \
328 VALUE_LANGOPT(Name, Bits, Default, Description)
330#define BENIGN_LANGOPT(Name, Bits, Default, Description)
331#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
332#define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description)
333#include "clang/Basic/LangOptions.def"
337 Diags->
Report(diag::err_ast_file_langopt_value_mismatch)
338 <<
"module features" << ModuleFilename;
344 Diags->
Report(diag::err_ast_file_langopt_value_mismatch)
345 <<
"target Objective-C runtime" << ModuleFilename;
352 Diags->
Report(diag::err_ast_file_langopt_value_mismatch)
353 <<
"block command names" << ModuleFilename;
361 if (!AllowCompatibleDifferences) {
365 ExistingSanitizers.
clear(ModularSanitizers);
366 ImportedSanitizers.
clear(ModularSanitizers);
367 if (ExistingSanitizers.
Mask != ImportedSanitizers.
Mask) {
368 const std::string Flag =
"-fsanitize=";
370#define SANITIZER(NAME, ID) \
372 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
373 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
374 if (InExistingModule != InImportedModule) \
375 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch) \
376 << InExistingModule << ModuleFilename << (Flag + NAME); \
378#include "clang/Basic/Sanitizers.def"
395 StringRef ModuleFilename,
397 bool AllowCompatibleDifferences =
true) {
398#define CHECK_TARGET_OPT(Field, Name) \
399 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
401 Diags->Report(diag::err_ast_file_targetopt_mismatch) \
402 << ModuleFilename << Name << TargetOpts.Field \
403 << ExistingTargetOpts.Field; \
414 if (!AllowCompatibleDifferences) {
419#undef CHECK_TARGET_OPT
427 llvm::sort(ExistingFeatures);
428 llvm::sort(ReadFeatures);
434 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
435 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
436 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
437 ExistingFeatures.begin(), ExistingFeatures.end(),
438 std::back_inserter(UnmatchedReadFeatures));
442 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
446 for (StringRef Feature : UnmatchedReadFeatures)
447 Diags->
Report(diag::err_ast_file_targetopt_feature_mismatch)
448 <<
false << ModuleFilename << Feature;
449 for (StringRef Feature : UnmatchedExistingFeatures)
450 Diags->
Report(diag::err_ast_file_targetopt_feature_mismatch)
451 <<
true << ModuleFilename << Feature;
454 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
458 StringRef ModuleFilename,
bool Complain,
459 bool AllowCompatibleDifferences) {
462 Complain ? &Reader.Diags :
nullptr,
463 AllowCompatibleDifferences);
467 StringRef ModuleFilename,
bool Complain,
468 bool AllowCompatibleDifferences) {
471 Complain ? &Reader.Diags :
nullptr,
472 AllowCompatibleDifferences);
477using MacroDefinitionsMap =
478 llvm::StringMap<std::pair<StringRef,
bool >>;
479using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
485 StringRef ModuleFilename,
495 for (
auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
504 Diags.
Report(diag::err_ast_file_diagopt_mismatch)
506 ->getWarningOptionForDiag(DiagID)
526 StringRef ModuleFilename,
bool IsSystem,
527 bool SystemHeaderWarningsInModule,
536 !SystemHeaderWarningsInModule) {
538 Diags.
Report(diag::err_ast_file_diagopt_mismatch)
539 <<
"-Wsystem-headers" << ModuleFilename;
546 Diags.
Report(diag::err_ast_file_diagopt_mismatch)
547 <<
"-Werror" << ModuleFilename;
554 Diags.
Report(diag::err_ast_file_diagopt_mismatch)
555 <<
"-Weverything -Werror" << ModuleFilename;
562 Diags.
Report(diag::err_ast_file_diagopt_mismatch)
563 <<
"-pedantic-errors" << ModuleFilename;
588 assert(!ModuleName.empty() &&
"diagnostic options read before module name");
592 assert(M &&
"missing module");
608 assert(ModuleMgr.
size() >= 1 &&
"what ASTFile is this then");
617 bool SystemHeaderWarningsInModule =
624 TopM->
IsSystem, SystemHeaderWarningsInModule,
632 MacroDefinitionsMap &Macros,
634 for (
unsigned I = 0, N = PPOpts.
Macros.size(); I != N; ++I) {
635 StringRef Macro = PPOpts.
Macros[I].first;
636 bool IsUndef = PPOpts.
Macros[I].second;
638 std::pair<StringRef, StringRef> MacroPair = Macro.split(
'=');
639 StringRef MacroName = MacroPair.first;
640 StringRef MacroBody = MacroPair.second;
644 if (MacroNames && !Macros.count(MacroName))
645 MacroNames->push_back(MacroName);
647 Macros[MacroName] = std::make_pair(
"",
true);
652 if (MacroName.size() == Macro.size())
656 StringRef::size_type End = MacroBody.find_first_of(
"\n\r");
657 MacroBody = MacroBody.substr(0, End);
660 if (MacroNames && !Macros.count(MacroName))
661 MacroNames->push_back(MacroName);
662 Macros[MacroName] = std::make_pair(MacroBody,
false);
686 std::string &SuggestedPredefines,
const LangOptions &LangOpts,
690 MacroDefinitionsMap ASTFileMacros;
692 MacroDefinitionsMap ExistingMacros;
695 &ExistingMacroNames);
699 SuggestedPredefines +=
"# 1 \"<command line>\" 1\n";
701 for (
unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
703 StringRef MacroName = ExistingMacroNames[I];
704 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
707 llvm::StringMap<std::pair<StringRef,
bool >>::iterator Known =
708 ASTFileMacros.find(MacroName);
714 Diags->
Report(diag::err_ast_file_macro_def_undef)
715 << MacroName <<
true << ModuleFilename;
723 if (Existing.second) {
724 SuggestedPredefines +=
"#undef ";
725 SuggestedPredefines += MacroName.str();
726 SuggestedPredefines +=
'\n';
728 SuggestedPredefines +=
"#define ";
729 SuggestedPredefines += MacroName.str();
730 SuggestedPredefines +=
' ';
731 SuggestedPredefines += Existing.first.str();
732 SuggestedPredefines +=
'\n';
739 if (Existing.second != Known->second.second) {
741 Diags->
Report(diag::err_ast_file_macro_def_undef)
742 << MacroName << Known->second.second << ModuleFilename;
749 if (Existing.second || Existing.first == Known->second.first) {
750 ASTFileMacros.erase(Known);
756 Diags->
Report(diag::err_ast_file_macro_def_conflict)
757 << MacroName << Known->second.first << Existing.first
764 SuggestedPredefines +=
"# 1 \"<built-in>\" 2\n";
769 for (
const auto &MacroName : ASTFileMacros.keys()) {
771 Diags->
Report(diag::err_ast_file_macro_def_undef)
772 << MacroName <<
false << ModuleFilename;
783 Diags->
Report(diag::err_ast_file_undef)
790 if (LangOpts.Modules &&
794 Diags->
Report(diag::err_ast_file_pp_detailed_record)
801 for (
unsigned I = 0, N = ExistingPPOpts.
Includes.size(); I != N; ++I) {
808 SuggestedPredefines +=
"#include \"";
809 SuggestedPredefines +=
File;
810 SuggestedPredefines +=
"\"\n";
820 SuggestedPredefines +=
"#include \"";
821 SuggestedPredefines +=
File;
822 SuggestedPredefines +=
"\"\n";
825 for (
unsigned I = 0, N = ExistingPPOpts.
MacroIncludes.size(); I != N; ++I) {
830 SuggestedPredefines +=
"#__include_macros \"";
831 SuggestedPredefines +=
File;
832 SuggestedPredefines +=
"\"\n##\n";
839 StringRef ModuleFilename,
840 bool ReadMacros,
bool Complain,
841 std::string &SuggestedPredefines) {
845 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros,
852 bool ReadMacros,
bool Complain, std::string &SuggestedPredefines) {
854 ModuleFilename, ReadMacros,
nullptr,
864 StringRef SpecificModuleCachePath,
865 StringRef ExistingModuleCachePath,
866 StringRef ModuleFilename,
871 SpecificModuleCachePath == ExistingModuleCachePath)
874 VFS.equivalent(SpecificModuleCachePath, ExistingModuleCachePath);
875 if (EqualOrErr && *EqualOrErr)
878 Diags->
Report(diag::err_ast_file_modulecache_mismatch)
879 << SpecificModuleCachePath << ExistingModuleCachePath << ModuleFilename;
884 StringRef ModuleFilename,
885 StringRef SpecificModuleCachePath,
890 Complain ? &Reader.Diags :
nullptr, PP.
getLangOpts(),
904 const char *Error =
nullptr;
906 uint64_t Val = llvm::decodeULEB128(
P, &Length,
nullptr, &Error);
908 llvm::report_fatal_error(Error);
914static std::pair<unsigned, unsigned>
917 if ((
unsigned)KeyLen != KeyLen)
918 llvm::report_fatal_error(
"key too large");
921 if ((
unsigned)DataLen != DataLen)
922 llvm::report_fatal_error(
"data too large");
924 return std::make_pair(KeyLen, DataLen);
928 bool TakeOwnership) {
929 DeserializationListener = Listener;
930 OwnsDeserializationListener = TakeOwnership;
941 Reader.ReadModuleOffsetMap(MF);
943 unsigned ModuleFileIndex =
ID.getModuleFileIndex();
950 assert(OwningModuleFile);
954 if (!ModuleFileIndex)
970std::pair<unsigned, unsigned>
977 using namespace llvm::support;
980 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);
982 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
989 Args.push_back(FirstII);
990 for (
unsigned I = 1; I != N; ++I)
991 Args.push_back(Reader.getLocalIdentifier(
992 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)));
1000 using namespace llvm::support;
1004 Result.ID = Reader.getGlobalSelectorID(
1005 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
1006 unsigned FullInstanceBits =
1007 endian::readNext<uint16_t, llvm::endianness::little>(d);
1008 unsigned FullFactoryBits =
1009 endian::readNext<uint16_t, llvm::endianness::little>(d);
1010 Result.InstanceBits = FullInstanceBits & 0x3;
1011 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
1012 Result.FactoryBits = FullFactoryBits & 0x3;
1013 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
1014 unsigned NumInstanceMethods = FullInstanceBits >> 3;
1015 unsigned NumFactoryMethods = FullFactoryBits >> 3;
1018 for (
unsigned I = 0; I != NumInstanceMethods; ++I) {
1022 endian::readNext<DeclID, llvm::endianness::little>(d))))
1023 Result.Instance.push_back(Method);
1027 for (
unsigned I = 0; I != NumFactoryMethods; ++I) {
1031 endian::readNext<DeclID, llvm::endianness::little>(d))))
1032 Result.Factory.push_back(Method);
1039 return llvm::djbHash(a);
1042std::pair<unsigned, unsigned>
1049 assert(n >= 2 && d[n-1] ==
'\0');
1050 return StringRef((
const char*) d, n-1);
1056 bool IsInteresting =
1067 bool Value = Bits & 0x1;
1073 using namespace llvm::support;
1076 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1077 return Reader.getGlobalIdentifierID(F, RawID >> 1);
1090 const unsigned char* d,
1092 using namespace llvm::support;
1095 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1096 bool IsInteresting = RawID & 0x01;
1106 II = &Reader.getIdentifierTable().getOwn(k);
1109 bool IsModule = Reader.getPreprocessor().getCurrentModule() !=
nullptr;
1111 Reader.markIdentifierUpToDate(II);
1113 IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID);
1114 if (!IsInteresting) {
1117 Reader.SetIdentifierInfo(ID, II);
1121 unsigned ObjCOrBuiltinID =
1122 endian::readNext<uint16_t, llvm::endianness::little>(d);
1123 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);
1124 bool CPlusPlusOperatorKeyword =
readBit(Bits);
1125 bool HasRevertedTokenIDToIdentifier =
readBit(Bits);
1126 bool Poisoned =
readBit(Bits);
1127 bool ExtensionToken =
readBit(Bits);
1128 bool HadMacroDefinition =
readBit(Bits);
1130 assert(Bits == 0 &&
"Extra bits in the identifier?");
1131 DataLen -=
sizeof(uint16_t) * 2;
1135 if (HasRevertedTokenIDToIdentifier && II->
getTokenID() != tok::identifier)
1140 "Incorrect extension token flag");
1141 (void)ExtensionToken;
1145 "Incorrect C++ operator keyword flag");
1146 (void)CPlusPlusOperatorKeyword;
1150 if (HadMacroDefinition) {
1151 uint32_t MacroDirectivesOffset =
1152 endian::readNext<uint32_t, llvm::endianness::little>(d);
1155 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1158 Reader.SetIdentifierInfo(ID, II);
1164 for (; DataLen > 0; DataLen -=
sizeof(
DeclID))
1165 DeclIDs.push_back(Reader.getGlobalDeclID(
1168 endian::readNext<DeclID, llvm::endianness::little>(d))));
1169 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1176 : Kind(Name.getNameKind()) {
1179 Data = (uint64_t)Name.getAsIdentifierInfo();
1184 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1187 Data = Name.getCXXOverloadedOperator();
1190 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1193 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1194 ->getDeclName().getAsIdentifierInfo();
1206 llvm::FoldingSetNodeID ID;
1207 ID.AddInteger(Kind);
1230 return ID.computeStableHash();
1234ASTDeclContextNameLookupTrait::ReadFileRef(
const unsigned char *&d) {
1235 using namespace llvm::support;
1237 uint32_t ModuleFileID =
1238 endian::readNext<uint32_t, llvm::endianness::little>(d);
1239 return Reader.getLocalModuleFile(F, ModuleFileID);
1242std::pair<unsigned, unsigned>
1243ASTDeclContextNameLookupTrait::ReadKeyDataLength(
const unsigned char *&d) {
1248ASTDeclContextNameLookupTrait::ReadKey(
const unsigned char *d,
unsigned) {
1249 using namespace llvm::support;
1257 Data = (uint64_t)Reader.getLocalIdentifier(
1258 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1263 Data = (uint64_t)Reader
1265 F, endian::readNext<uint32_t, llvm::endianness::little>(d))
1283 const unsigned char *d,
1286 using namespace llvm::support;
1288 for (
unsigned NumDecls = DataLen /
sizeof(
DeclID); NumDecls; --NumDecls) {
1290 Reader, F, endian::readNext<DeclID, llvm::endianness::little>(d));
1291 Val.
insert(Reader.getGlobalDeclID(F, ID));
1295bool ASTReader::ReadLexicalDeclContextStorage(
ModuleFile &M,
1296 BitstreamCursor &Cursor,
1299 assert(Offset != 0);
1302 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1303 Error(std::move(Err));
1311 Error(MaybeCode.takeError());
1314 unsigned Code = MaybeCode.get();
1317 if (!MaybeRecCode) {
1318 Error(MaybeRecCode.takeError());
1321 unsigned RecCode = MaybeRecCode.get();
1323 Error(
"Expected lexical block");
1327 assert(!isa<TranslationUnitDecl>(DC) &&
1328 "expected a TU_UPDATE_LEXICAL record for TU");
1333 auto &Lex = LexicalDecls[DC];
1335 Lex = std::make_pair(
1338 Blob.size() /
sizeof(
DeclID)));
1344bool ASTReader::ReadVisibleDeclContextStorage(
ModuleFile &M,
1345 BitstreamCursor &Cursor,
1348 assert(Offset != 0);
1351 if (llvm::Error Err =
Cursor.JumpToBit(Offset)) {
1352 Error(std::move(Err));
1360 Error(MaybeCode.takeError());
1363 unsigned Code = MaybeCode.get();
1366 if (!MaybeRecCode) {
1367 Error(MaybeRecCode.takeError());
1370 unsigned RecCode = MaybeRecCode.get();
1372 Error(
"Expected visible lookup table block");
1378 auto *
Data = (
const unsigned char*)Blob.data();
1379 PendingVisibleUpdates[
ID].push_back(PendingVisibleUpdate{&M,
Data});
1383void ASTReader::Error(StringRef Msg)
const {
1384 Error(diag::err_fe_pch_malformed, Msg);
1385 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1386 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1387 Diag(diag::note_module_cache_path)
1388 << PP.getHeaderSearchInfo().getModuleCachePath();
1392void ASTReader::Error(
unsigned DiagID, StringRef Arg1, StringRef Arg2,
1393 StringRef Arg3)
const {
1394 if (Diags.isDiagnosticInFlight())
1395 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
1397 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1400void ASTReader::Error(llvm::Error &&Err)
const {
1401 llvm::Error RemainingErr =
1403 auto Diag =
E.getDiagnostic().second;
1408 assert(NumArgs <= 3 &&
"Can only have up to 3 arguments");
1409 StringRef Arg1, Arg2, Arg3;
1412 Arg3 =
Diag.getStringArg(2);
1415 Arg2 =
Diag.getStringArg(1);
1418 Arg1 =
Diag.getStringArg(0);
1420 Error(
Diag.getDiagID(), Arg1, Arg2, Arg3);
1436 std::map<int, int> FileIDs;
1438 for (
unsigned I = 0;
Record[Idx]; ++I) {
1446 std::vector<LineEntry> Entries;
1447 while (Idx <
Record.size()) {
1451 unsigned NumEntries =
Record[Idx++];
1452 assert(NumEntries &&
"no line entries for file ID");
1454 Entries.reserve(NumEntries);
1455 for (
unsigned I = 0; I != NumEntries; ++I) {
1456 unsigned FileOffset =
Record[Idx++];
1457 unsigned LineNo =
Record[Idx++];
1458 int FilenameID = FileIDs[
Record[Idx++]];
1461 unsigned IncludeOffset =
Record[Idx++];
1463 FileKind, IncludeOffset));
1470llvm::Error ASTReader::ReadSourceManagerBlock(
ModuleFile &F) {
1471 using namespace SrcMgr;
1479 SLocEntryCursor = F.
Stream;
1482 if (llvm::Error Err = F.
Stream.SkipBlock())
1493 SLocEntryCursor.advanceSkippingSubblocks();
1495 return MaybeE.takeError();
1496 llvm::BitstreamEntry
E = MaybeE.get();
1499 case llvm::BitstreamEntry::SubBlock:
1500 case llvm::BitstreamEntry::Error:
1501 return llvm::createStringError(std::errc::illegal_byte_sequence,
1502 "malformed block record in AST file");
1503 case llvm::BitstreamEntry::EndBlock:
1504 return llvm::Error::success();
1505 case llvm::BitstreamEntry::Record:
1514 SLocEntryCursor.readRecord(
E.ID,
Record, &Blob);
1516 return MaybeRecord.takeError();
1517 switch (MaybeRecord.get()) {
1525 return llvm::Error::success();
1536 return std::move(Err);
1540 return MaybeEntry.takeError();
1542 llvm::BitstreamEntry Entry = MaybeEntry.get();
1543 if (Entry.Kind != llvm::BitstreamEntry::Record)
1544 return llvm::createStringError(
1545 std::errc::illegal_byte_sequence,
1546 "incorrectly-formatted source location entry in AST file");
1552 return MaybeSLOC.takeError();
1554 switch (MaybeSLOC.get()) {
1556 return llvm::createStringError(
1557 std::errc::illegal_byte_sequence,
1558 "incorrectly-formatted source location entry in AST file");
1568 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1569 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1570 "Corrupted global sloc offset map");
1575 auto It = llvm::upper_bound(
1578 int ID = F->SLocEntryBaseID + LocalIndex;
1579 std::size_t Index = -ID - 2;
1580 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1581 assert(!SourceMgr.SLocEntryLoaded[Index]);
1582 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1583 if (!MaybeEntryOffset) {
1584 Error(MaybeEntryOffset.takeError());
1588 SourceMgr.LoadedSLocEntryTable[Index] =
1589 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1590 SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1592 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1607 if (
unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1608 Error(
"source location entry ID out-of-range for AST file");
1614 auto ReadBuffer = [
this](
1615 BitstreamCursor &SLocEntryCursor,
1616 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1621 Error(MaybeCode.takeError());
1624 unsigned Code = MaybeCode.get();
1627 SLocEntryCursor.readRecord(Code,
Record, &Blob);
1628 if (!MaybeRecCode) {
1629 Error(MaybeRecCode.takeError());
1632 unsigned RecCode = MaybeRecCode.get();
1637 const llvm::compression::Format F =
1638 Blob.size() > 0 && Blob.data()[0] == 0x78
1639 ? llvm::compression::Format::Zlib
1640 : llvm::compression::Format::Zstd;
1641 if (
const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1646 if (llvm::Error
E = llvm::compression::decompress(
1647 F, llvm::arrayRefFromStringRef(Blob), Decompressed,
Record[0])) {
1648 Error(
"could not decompress embedded file contents: " +
1649 llvm::toString(std::move(
E)));
1652 return llvm::MemoryBuffer::getMemBufferCopy(
1653 llvm::toStringRef(Decompressed), Name);
1655 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name,
true);
1657 Error(
"AST record has invalid code");
1662 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1666 Error(std::move(Err));
1673 ++NumSLocEntriesRead;
1676 Error(MaybeEntry.takeError());
1679 llvm::BitstreamEntry Entry = MaybeEntry.get();
1681 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1682 Error(
"incorrectly-formatted source location entry in AST file");
1689 SLocEntryCursor.readRecord(Entry.ID,
Record, &Blob);
1691 Error(MaybeSLOC.takeError());
1694 switch (MaybeSLOC.get()) {
1696 Error(
"incorrectly-formatted source location entry in AST file");
1702 unsigned InputID =
Record[4];
1703 InputFile IF = getInputFile(*F, InputID);
1716 IncludeLoc = getImportLocation(F);
1720 FileID FID = SourceMgr.createFileID(*
File, IncludeLoc, FileCharacter, ID,
1723 FileInfo.NumCreatedFIDs =
Record[5];
1727 unsigned NumFileDecls =
Record[7];
1728 if (NumFileDecls && ContextObj) {
1730 assert(F->
FileSortedDecls &&
"FILE_SORTED_DECLS not encountered yet ?");
1736 SourceMgr.getOrCreateContentCache(*
File, isSystem(FileCharacter));
1740 auto Buffer = ReadBuffer(SLocEntryCursor,
File->getName());
1743 SourceMgr.overrideFileContents(*
File, std::move(Buffer));
1750 const char *Name = Blob.data();
1751 unsigned Offset =
Record[0];
1756 IncludeLoc = getImportLocation(F);
1759 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1762 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1763 BaseOffset + Offset, IncludeLoc);
1765 auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
1766 FileInfo.setHasLineDirectives();
1776 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
1790 if (
unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1791 Error(
"source location entry ID out-of-range for AST file");
1796 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1814 assert(SourceMgr.getMainFileID().isValid() &&
"missing main file");
1815 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1825 uint64_t *StartOfBlockOffset) {
1826 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
1829 if (StartOfBlockOffset)
1830 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
1833 uint64_t Offset = Cursor.GetCurrentBitNo();
1836 return MaybeCode.takeError();
1837 unsigned Code = MaybeCode.get();
1840 if (Code != llvm::bitc::DEFINE_ABBREV) {
1841 if (llvm::Error Err = Cursor.JumpToBit(Offset))
1843 return llvm::Error::success();
1845 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
1861 case tok::annot_pragma_loop_hint: {
1864 Info->Option = ReadToken(M,
Record, Idx);
1865 unsigned NumTokens =
Record[Idx++];
1867 Toks.reserve(NumTokens);
1868 for (
unsigned I = 0; I < NumTokens; ++I)
1869 Toks.push_back(ReadToken(M,
Record, Idx));
1870 Info->Toks =
llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
1874 case tok::annot_pragma_pack: {
1877 auto SlotLabel = ReadString(
Record, Idx);
1879 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
1880 Info->Alignment = ReadToken(M,
Record, Idx);
1885 case tok::annot_pragma_openmp:
1886 case tok::annot_pragma_openmp_end:
1887 case tok::annot_pragma_unused:
1888 case tok::annot_pragma_openacc:
1889 case tok::annot_pragma_openacc_end:
1890 case tok::annot_repl_input_end:
1893 llvm_unreachable(
"missing deserialization code for annotation token");
1910 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1912 consumeError(std::move(Err));
1924 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1926 Stream.advanceSkippingSubblocks(Flags);
1928 Error(MaybeEntry.takeError());
1931 llvm::BitstreamEntry Entry = MaybeEntry.get();
1933 switch (Entry.Kind) {
1934 case llvm::BitstreamEntry::SubBlock:
1935 case llvm::BitstreamEntry::Error:
1936 Error(
"malformed block record in AST file");
1938 case llvm::BitstreamEntry::EndBlock:
1940 case llvm::BitstreamEntry::Record:
1951 Error(MaybeRecType.takeError());
1967 unsigned NextIndex = 1;
1974 PP.getPreprocessorAllocator());
1977 bool isC99VarArgs =
Record[NextIndex++];
1978 bool isGNUVarArgs =
Record[NextIndex++];
1979 bool hasCommaPasting =
Record[NextIndex++];
1980 MacroParams.clear();
1981 unsigned NumArgs =
Record[NextIndex++];
1982 for (
unsigned i = 0; i != NumArgs; ++i)
1983 MacroParams.push_back(getLocalIdentifier(F,
Record[NextIndex++]));
1997 if (NextIndex + 1 ==
Record.size() && PP.getPreprocessingRecord() &&
2001 GlobalID = getGlobalPreprocessedEntityID(F,
Record[NextIndex]);
2003 PreprocessingRecord::PPEntityID PPID =
2004 PPRec.getPPEntityID(GlobalID - 1,
true);
2006 PPRec.getPreprocessedEntity(PPID));
2008 PPRec.RegisterMacroDefinition(Macro, PPDef);
2019 if (MacroTokens.empty()) {
2020 Error(
"unexpected number of macro tokens for a macro in AST file");
2025 MacroTokens[0] = ReadToken(F,
Record, Idx);
2026 MacroTokens = MacroTokens.drop_front();
2035 unsigned LocalID)
const {
2037 ReadModuleOffsetMap(M);
2042 &&
"Invalid index into preprocessed entity index remap");
2044 return LocalID + I->second;
2047const FileEntry *HeaderFileInfoTrait::getFile(
const internal_key_type &Key) {
2049 if (!Key.Imported) {
2055 std::string Resolved = std::string(Key.Filename);
2056 Reader.ResolveImportedPath(M, Resolved);
2063 uint8_t buf[
sizeof(ikey.
Size) +
sizeof(ikey.
ModTime)];
2066 return llvm::xxh3_64bits(buf);
2087 return FEA && FEA == FEB;
2090std::pair<unsigned, unsigned>
2091HeaderFileInfoTrait::ReadKeyDataLength(
const unsigned char*& d) {
2096HeaderFileInfoTrait::ReadKey(
const unsigned char *d,
unsigned) {
2097 using namespace llvm::support;
2100 ikey.
Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2102 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2111 using namespace llvm::support;
2113 const unsigned char *End = d + DataLen;
2115 unsigned Flags = *d++;
2117 bool Included = (Flags >> 6) & 0x01;
2122 Reader.getPreprocessor().getIncludedFiles().insert(FE);
2125 HFI.
isImport |= (Flags >> 5) & 0x01;
2127 HFI.
DirInfo = (Flags >> 1) & 0x07;
2130 M, endian::readNext<IdentifierID, llvm::endianness::little>(d));
2131 if (
unsigned FrameworkOffset =
2132 endian::readNext<uint32_t, llvm::endianness::little>(d)) {
2135 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
2136 HFI.
Framework = HS->getUniqueFrameworkName(FrameworkName);
2139 assert((End - d) % 4 == 0 &&
2140 "Wrong data length in HeaderFileInfo deserialization");
2142 uint32_t LocalSMID =
2143 endian::readNext<uint32_t, llvm::endianness::little>(d);
2149 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2150 Module *Mod = Reader.getSubmodule(GlobalSMID);
2153 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2157 Reader.ResolveImportedPath(M,
Filename);
2161 ModMap.
addHeader(Mod, H, HeaderRole,
true);
2173 uint32_t MacroDirectivesOffset) {
2174 assert(NumCurrentElementsDeserializing > 0 &&
"Missing deserialization guard");
2175 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2182 for (
ModuleFile &I : llvm::reverse(ModuleMgr)) {
2183 BitstreamCursor &MacroCursor = I.MacroCursor;
2186 if (MacroCursor.getBitcodeBytes().empty())
2189 BitstreamCursor Cursor = MacroCursor;
2190 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2191 Error(std::move(Err));
2199 Error(MaybeE.takeError());
2202 llvm::BitstreamEntry
E = MaybeE.get();
2205 case llvm::BitstreamEntry::SubBlock:
2206 case llvm::BitstreamEntry::Error:
2207 Error(
"malformed block record in AST file");
2209 case llvm::BitstreamEntry::EndBlock:
2212 case llvm::BitstreamEntry::Record: {
2216 Error(MaybeRecord.takeError());
2219 switch (MaybeRecord.get()) {
2227 updateOutOfDateIdentifier(*II);
2246 class IdentifierLookupVisitor {
2249 unsigned PriorGeneration;
2250 unsigned &NumIdentifierLookups;
2251 unsigned &NumIdentifierLookupHits;
2255 IdentifierLookupVisitor(StringRef Name,
unsigned PriorGeneration,
2256 unsigned &NumIdentifierLookups,
2257 unsigned &NumIdentifierLookupHits)
2259 PriorGeneration(PriorGeneration),
2260 NumIdentifierLookups(NumIdentifierLookups),
2261 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2275 ++NumIdentifierLookups;
2276 ASTIdentifierLookupTable::iterator Pos =
2277 IdTable->find_hashed(Name, NameHash, &Trait);
2278 if (Pos == IdTable->end())
2284 ++NumIdentifierLookupHits;
2300 unsigned PriorGeneration = 0;
2301 if (getContext().getLangOpts().Modules)
2302 PriorGeneration = IdentifierGeneration[&II];
2308 if (!loadGlobalIndex()) {
2309 if (GlobalIndex->lookupIdentifier(II.
getName(), Hits)) {
2314 IdentifierLookupVisitor Visitor(II.
getName(), PriorGeneration,
2315 NumIdentifierLookups,
2316 NumIdentifierLookupHits);
2317 ModuleMgr.visit(Visitor, HitsPtr);
2318 markIdentifierUpToDate(&II);
2328 if (getContext().getLangOpts().Modules)
2329 IdentifierGeneration[II] = getGeneration();
2333 const PendingMacroInfo &PMInfo) {
2338 if (llvm::Error Err =
2340 Error(std::move(Err));
2344 struct ModuleMacroRecord {
2357 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2359 Error(MaybeEntry.takeError());
2362 llvm::BitstreamEntry Entry = MaybeEntry.get();
2364 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2365 Error(
"malformed block record in AST file");
2372 Error(MaybePP.takeError());
2380 ModuleMacros.push_back(ModuleMacroRecord());
2381 auto &Info = ModuleMacros.back();
2382 Info.SubModID = getGlobalSubmoduleID(M,
Record[0]);
2383 Info.MI = getMacro(getGlobalMacroID(M,
Record[1]));
2384 for (
int I = 2, N =
Record.size(); I != N; ++I)
2385 Info.Overrides.push_back(getGlobalSubmoduleID(M,
Record[I]));
2390 Error(
"malformed block record in AST file");
2401 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2403 for (
auto &MMR : ModuleMacros) {
2405 for (
unsigned ModID : MMR.Overrides) {
2406 Module *Mod = getSubmodule(ModID);
2407 auto *Macro = PP.getModuleMacro(Mod, II);
2408 assert(Macro &&
"missing definition for overridden macro");
2409 Overrides.push_back(Macro);
2412 bool Inserted =
false;
2413 Module *Owner = getSubmodule(MMR.SubModID);
2414 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2425 unsigned Idx = 0, N =
Record.size();
2433 MD = PP.AllocateDefMacroDirective(MI,
Loc);
2437 MD = PP.AllocateUndefMacroDirective(
Loc);
2440 bool isPublic =
Record[Idx++];
2441 MD = PP.AllocateVisibilityMacroDirective(
Loc, isPublic);
2453 PP.setLoadedMacroDirective(II, Earliest, Latest);
2456bool ASTReader::shouldDisableValidationForFile(
2494 consumeError(std::move(Err));
2500 consumeError(MaybeCode.takeError());
2502 unsigned Code = MaybeCode.get();
2508 "invalid record type for input file");
2511 consumeError(Maybe.takeError());
2514 assert(
Record[0] == ID &&
"Bogus stored ID or offset");
2523 uint16_t AsRequestedLength =
Record[7];
2525 std::string NameAsRequested = Blob.substr(0, AsRequestedLength).str();
2526 std::string Name = Blob.substr(AsRequestedLength).str();
2528 ResolveImportedPath(F, NameAsRequested);
2529 ResolveImportedPath(F, Name);
2532 Name = NameAsRequested;
2534 return std::make_pair(std::move(NameAsRequested), std::move(Name));
2539 consumeError(MaybeEntry.takeError());
2540 llvm::BitstreamEntry Entry = MaybeEntry.get();
2541 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2542 "expected record type for input file hash");
2547 "invalid record type for input file hash");
2550 consumeError(Maybe.takeError());
2579 consumeError(std::move(Err));
2594 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2607 if ((Overridden || Transient || SkipChecks) && !
File)
2612 std::string ErrorStr =
"could not find file '";
2614 ErrorStr +=
"' referenced by AST file '";
2630 if ((!Overridden && !Transient) && !SkipChecks &&
2631 SM.isFileOverridden(*
File)) {
2645 enum ModificationKind {
2651 std::optional<int64_t> Old = std::nullopt;
2652 std::optional<int64_t> New = std::nullopt;
2654 auto HasInputContentChanged = [&](Change OriginalChange) {
2655 assert(ValidateASTInputFilesContent &&
2656 "We should only check the content of the inputs with "
2657 "ValidateASTInputFilesContent enabled.");
2659 if (StoredContentHash == 0)
2660 return OriginalChange;
2663 if (!MemBuffOrError) {
2665 return OriginalChange;
2666 std::string ErrorStr =
"could not get buffer for file '";
2667 ErrorStr +=
File->getName();
2670 return OriginalChange;
2673 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer());
2674 if (StoredContentHash ==
static_cast<uint64_t>(ContentHash))
2675 return Change{Change::None};
2677 return Change{Change::Content};
2679 auto HasInputFileChanged = [&]() {
2680 if (StoredSize !=
File->getSize())
2681 return Change{Change::Size, StoredSize,
File->getSize()};
2682 if (!shouldDisableValidationForFile(F) && StoredTime &&
2683 StoredTime !=
File->getModificationTime()) {
2684 Change MTimeChange = {Change::ModTime, StoredTime,
2685 File->getModificationTime()};
2689 if (ValidateASTInputFilesContent)
2690 return HasInputContentChanged(MTimeChange);
2694 return Change{Change::None};
2697 bool IsOutOfDate =
false;
2698 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2704 FileChange = HasInputContentChanged(FileChange);
2710 if (!StoredTime && ValidateASTInputFilesContent &&
2711 FileChange.Kind == Change::None)
2712 FileChange = HasInputContentChanged(FileChange);
2715 if (!Overridden && FileChange.Kind != Change::None) {
2716 if (Complain && !Diags.isDiagnosticInFlight()) {
2719 while (!ImportStack.back()->ImportedBy.empty())
2720 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2723 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2724 Diag(diag::err_fe_ast_file_modified)
2726 << TopLevelPCHName << FileChange.Kind
2727 << (FileChange.Old && FileChange.New)
2728 << llvm::itostr(FileChange.Old.value_or(0))
2729 << llvm::itostr(FileChange.New.value_or(0));
2732 if (ImportStack.size() > 1) {
2733 Diag(diag::note_pch_required_by)
2734 <<
Filename << ImportStack[0]->FileName;
2735 for (
unsigned I = 1; I < ImportStack.size(); ++I)
2736 Diag(diag::note_pch_required_by)
2737 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2740 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2770 llvm::sys::path::append(Buffer, Prefix,
Filename);
2771 Filename.assign(Buffer.begin(), Buffer.end());
2786 llvm_unreachable(
"unknown ASTReadResult");
2790 BitstreamCursor &Stream, StringRef
Filename,
2791 unsigned ClientLoadCapabilities,
bool AllowCompatibleConfigurationMismatch,
2795 consumeError(std::move(Err));
2806 consumeError(MaybeEntry.takeError());
2809 llvm::BitstreamEntry Entry = MaybeEntry.get();
2811 switch (Entry.Kind) {
2812 case llvm::BitstreamEntry::Error:
2813 case llvm::BitstreamEntry::SubBlock:
2816 case llvm::BitstreamEntry::EndBlock:
2819 case llvm::BitstreamEntry::Record:
2827 if (!MaybeRecordType) {
2829 consumeError(MaybeRecordType.takeError());
2834 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2836 AllowCompatibleConfigurationMismatch))
2837 Result = ConfigurationMismatch;
2842 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2844 AllowCompatibleConfigurationMismatch))
2845 Result = ConfigurationMismatch;
2850 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2851 if (!AllowCompatibleConfigurationMismatch &&
2852 ParseFileSystemOptions(
Record, Complain, Listener))
2853 Result = ConfigurationMismatch;
2858 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2859 if (!AllowCompatibleConfigurationMismatch &&
2861 Result = ConfigurationMismatch;
2866 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2867 if (!AllowCompatibleConfigurationMismatch &&
2869 SuggestedPredefines))
2870 Result = ConfigurationMismatch;
2880 unsigned ClientLoadCapabilities) {
2881 BitstreamCursor &Stream = F.
Stream;
2884 Error(std::move(Err));
2894 bool HasReadUnhashedControlBlock =
false;
2895 auto readUnhashedControlBlockOnce = [&]() {
2896 if (!HasReadUnhashedControlBlock) {
2897 HasReadUnhashedControlBlock =
true;
2898 if (ASTReadResult
Result =
2899 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2905 bool DisableValidation = shouldDisableValidationForFile(F);
2909 unsigned NumInputs = 0;
2910 unsigned NumUserInputs = 0;
2911 StringRef BaseDirectoryAsWritten;
2915 Error(MaybeEntry.takeError());
2918 llvm::BitstreamEntry Entry = MaybeEntry.get();
2920 switch (Entry.Kind) {
2921 case llvm::BitstreamEntry::Error:
2922 Error(
"malformed block record in AST file");
2924 case llvm::BitstreamEntry::EndBlock: {
2927 if (ASTReadResult
Result = readUnhashedControlBlockOnce())
2932 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2939 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2945 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
2951 for (
unsigned I = 0; I < N; ++I) {
2952 InputFile IF = getInputFile(F, I+1, Complain);
2964 for (
unsigned I = 0; I < N; ++I) {
2965 bool IsSystem = I >= NumUserInputs;
2976 case llvm::BitstreamEntry::SubBlock:
2980 if (llvm::Error Err = Stream.SkipBlock()) {
2981 Error(std::move(Err));
2985 Error(
"malformed block record in AST file");
2995 if (Listener && !ImportedBy) {
3001 bool AllowCompatibleConfigurationMismatch =
3005 ReadOptionsBlock(Stream, F.
FileName, ClientLoadCapabilities,
3006 AllowCompatibleConfigurationMismatch, *Listener,
3007 SuggestedPredefines);
3009 Error(
"malformed block record in AST file");
3013 if (DisableValidation ||
3014 (AllowConfigurationMismatch &&
Result == ConfigurationMismatch))
3022 }
else if (llvm::Error Err = Stream.SkipBlock()) {
3023 Error(std::move(Err));
3029 if (llvm::Error Err = Stream.SkipBlock()) {
3030 Error(std::move(Err));
3036 case llvm::BitstreamEntry::Record:
3045 Stream.readRecord(Entry.ID,
Record, &Blob);
3046 if (!MaybeRecordType) {
3047 Error(MaybeRecordType.takeError());
3053 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3055 : diag::err_ast_file_version_too_new)
3060 bool hasErrors =
Record[7];
3061 if (hasErrors && !DisableValidation) {
3064 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
3065 canRecoverFromOutOfDate(F.
FileName, ClientLoadCapabilities))
3068 if (!AllowASTWithCompilerErrors) {
3069 Diag(diag::err_ast_file_with_compiler_errors)
3075 Diags.ErrorOccurred =
true;
3076 Diags.UncompilableErrorOccurred =
true;
3077 Diags.UnrecoverableErrorOccurred =
true;
3090 StringRef ASTBranch = Blob;
3091 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3092 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3093 Diag(diag::err_ast_file_different_branch)
3105 if (ASTReadResult
Result = readUnhashedControlBlockOnce())
3109 unsigned Idx = 0, N =
Record.size();
3114 bool IsImportingStdCXXModule =
Record[Idx++];
3118 auto [ImportLoc, ImportModuleFileIndex] =
3119 ReadUntranslatedSourceLocation(
Record[Idx++]);
3121 assert(ImportModuleFileIndex == 0);
3122 off_t StoredSize = !IsImportingStdCXXModule ? (off_t)
Record[Idx++] : 0;
3123 time_t StoredModTime =
3124 !IsImportingStdCXXModule ? (time_t)
Record[Idx++] : 0;
3127 if (!IsImportingStdCXXModule) {
3128 auto FirstSignatureByte =
Record.begin() + Idx;
3134 std::string ImportedName = ReadString(
Record, Idx);
3135 std::string ImportedFile;
3144 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3145 ImportedName, !IsImportingStdCXXModule);
3149 if (!IsImportingStdCXXModule) {
3150 if (ImportedFile.empty()) {
3153 ImportedFile = ReadPath(BaseDirectoryAsWritten,
Record, Idx);
3156 }
else if (ImportedFile.empty()) {
3157 Diag(clang::diag::err_failed_to_find_module_file) << ImportedName;
3163 unsigned Capabilities = ClientLoadCapabilities;
3164 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3165 Capabilities &= ~ARR_Missing;
3168 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3169 Loaded, StoredSize, StoredModTime,
3170 StoredSignature, Capabilities);
3173 bool recompilingFinalized =
3174 Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&
3175 getModuleManager().getModuleCache().isPCMFinal(F.
FileName);
3177 Diag(diag::note_module_file_imported_by)
3179 if (recompilingFinalized)
3180 Diag(diag::note_module_file_conflict);
3183 case Failure:
return Failure;
3186 case OutOfDate:
return OutOfDate;
3188 case ConfigurationMismatch:
return ConfigurationMismatch;
3189 case HadErrors:
return HadErrors;
3209 Diag(diag::remark_module_import)
3211 << (ImportedBy ? StringRef(ImportedBy->
ModuleName) : StringRef());
3217 if (ASTReadResult
Result = readUnhashedControlBlockOnce())
3225 BaseDirectoryAsWritten = Blob;
3227 "MODULE_DIRECTORY found before MODULE_NAME");
3229 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3233 Module *M = PP.getHeaderSearchInfo().lookupModule(
3240 if (!
bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3243 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3244 if (!BuildDir || *BuildDir != M->
Directory) {
3245 if (!canRecoverFromOutOfDate(F.
FileName, ClientLoadCapabilities))
3246 Diag(diag::err_imported_module_relocated)
3257 if (ASTReadResult
Result =
3258 ReadModuleMapFileBlock(
Record, F, ImportedBy, ClientLoadCapabilities))
3264 NumUserInputs =
Record[1];
3266 (
const llvm::support::unaligned_uint64_t *)Blob.data();
3275llvm::Error ASTReader::ReadASTBlock(
ModuleFile &F,
3276 unsigned ClientLoadCapabilities) {
3277 BitstreamCursor &Stream = F.
Stream;
3279 if (llvm::Error Err = Stream.EnterSubBlock(
AST_BLOCK_ID))
3288 return MaybeEntry.takeError();
3289 llvm::BitstreamEntry Entry = MaybeEntry.get();
3291 switch (Entry.Kind) {
3292 case llvm::BitstreamEntry::Error:
3293 return llvm::createStringError(
3294 std::errc::illegal_byte_sequence,
3295 "error at end of module block in AST file");
3296 case llvm::BitstreamEntry::EndBlock:
3308 return llvm::Error::success();
3309 case llvm::BitstreamEntry::SubBlock:
3317 if (llvm::Error Err = Stream.SkipBlock())
3319 if (llvm::Error Err = ReadBlockAbbrevs(
3326 if (!PP.getExternalSource())
3327 PP.setExternalSource(
this);
3329 if (llvm::Error Err = Stream.SkipBlock())
3331 if (llvm::Error Err =
3340 if (llvm::Error Err = Stream.SkipBlock()) {
3349 if (!PP.getPreprocessingRecord())
3350 PP.createPreprocessingRecord();
3351 if (!PP.getPreprocessingRecord()->getExternalSource())
3352 PP.getPreprocessingRecord()->SetExternalSource(*
this);
3356 if (llvm::Error Err = ReadSourceManagerBlock(F))
3361 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3366 BitstreamCursor
C = Stream;
3368 if (llvm::Error Err = Stream.SkipBlock())
3372 CommentsCursors.push_back(std::make_pair(
C, &F));
3377 if (llvm::Error Err = Stream.SkipBlock())
3383 case llvm::BitstreamEntry::Record:
3392 Stream.readRecord(Entry.ID,
Record, &Blob);
3393 if (!MaybeRecordType)
3394 return MaybeRecordType.takeError();
3426 return llvm::createStringError(
3427 std::errc::illegal_byte_sequence,
3428 "duplicate TYPE_OFFSET record in AST file");
3441 return llvm::createStringError(
3442 std::errc::illegal_byte_sequence,
3443 "duplicate DECL_OFFSET record in AST file");
3455 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3456 LexicalContents Contents(
3458 static_cast<unsigned int>(Blob.size() /
sizeof(
DeclID)));
3459 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3467 auto *
Data = (
const unsigned char*)Blob.data();
3468 PendingVisibleUpdates[
ID].push_back(PendingVisibleUpdate{&F,
Data});
3471 if (
Decl *
D = GetExistingDecl(ID))
3472 PendingUpdateRecords.push_back(
3473 PendingUpdateRecord(ID,
D,
false));
3479 reinterpret_cast<const unsigned char *
>(Blob.data());
3487 PP.getIdentifierTable().setExternalIdentifierLookup(
this);
3493 return llvm::createStringError(
3494 std::errc::illegal_byte_sequence,
3495 "duplicate IDENTIFIER_OFFSET record in AST file");
3501 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3513 for (
unsigned I = 0, N =
Record.size(); I != N; )
3514 EagerlyDeserializedDecls.push_back(ReadDeclID(F,
Record, I));
3521 getContext().getLangOpts().BuildingPCHWithObjectFile)
3522 for (
unsigned I = 0, N =
Record.size(); I != N; )
3523 EagerlyDeserializedDecls.push_back(ReadDeclID(F,
Record, I));
3527 if (SpecialTypes.empty()) {
3528 for (
unsigned I = 0, N =
Record.size(); I != N; ++I)
3529 SpecialTypes.push_back(getGlobalTypeID(F,
Record[I]));
3533 if (SpecialTypes.size() !=
Record.size())
3534 return llvm::createStringError(std::errc::illegal_byte_sequence,
3535 "invalid special-types record");
3537 for (
unsigned I = 0, N =
Record.size(); I != N; ++I) {
3539 if (!SpecialTypes[I])
3540 SpecialTypes[I] =
ID;
3547 TotalNumStatements +=
Record[0];
3548 TotalNumMacros +=
Record[1];
3549 TotalLexicalDeclContexts +=
Record[2];
3550 TotalVisibleDeclContexts +=
Record[3];
3554 for (
unsigned I = 0, N =
Record.size(); I != N; )
3555 UnusedFileScopedDecls.push_back(ReadDeclID(F,
Record, I));
3559 for (
unsigned I = 0, N =
Record.size(); I != N; )
3560 DelegatingCtorDecls.push_back(ReadDeclID(F,
Record, I));
3564 if (
Record.size() % 3 != 0)
3565 return llvm::createStringError(std::errc::illegal_byte_sequence,
3566 "invalid weak identifiers record");
3570 WeakUndeclaredIdentifiers.clear();
3573 for (
unsigned I = 0, N =
Record.size(); I < N; ) {
3574 WeakUndeclaredIdentifiers.push_back(
3575 getGlobalIdentifierID(F,
Record[I++]));
3576 WeakUndeclaredIdentifiers.push_back(
3577 getGlobalIdentifierID(F,
Record[I++]));
3578 WeakUndeclaredIdentifiers.push_back(
3579 ReadSourceLocation(F,
Record, I).getRawEncoding());
3586 unsigned LocalBaseSelectorID =
Record[1];
3592 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3597 std::make_pair(LocalBaseSelectorID,
3609 = ASTSelectorLookupTable::Create(
3613 TotalNumMethodPoolEntries +=
Record[1];
3618 for (
unsigned Idx = 0, N =
Record.size() - 1; Idx < N; ) {
3619 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3621 ReferencedSelectorsData.push_back(ReadSourceLocation(F,
Record, Idx).
3630 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
3631 ReadSourceLocation(F,
Record, Idx));
3639 while (Idx <
Record.size())
3640 SrcLocs.push_back(ReadSourceLocation(F,
Record, Idx));
3641 PP.setDeserializedSafeBufferOptOutMap(SrcLocs);
3648 unsigned Idx = 0, End =
Record.size() - 1;
3649 bool ReachedEOFWhileSkipping =
Record[Idx++];
3650 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3651 if (ReachedEOFWhileSkipping) {
3654 bool FoundNonSkipPortion =
Record[Idx++];
3655 bool FoundElse =
Record[Idx++];
3657 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3658 FoundElse, ElseLoc);
3662 auto Loc = ReadSourceLocation(F,
Record, Idx);
3663 bool WasSkipping =
Record[Idx++];
3664 bool FoundNonSkip =
Record[Idx++];
3665 bool FoundElse =
Record[Idx++];
3666 ConditionalStack.push_back(
3667 {
Loc, WasSkipping, FoundNonSkip, FoundElse});
3669 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
3674 if (!
Record.empty() && Listener)
3692 if (!Diags.isDiagnosticInFlight()) {
3694 SourceMgr.noteSLocAddressSpaceUsage(Diags);
3696 return llvm::createStringError(std::errc::invalid_argument,
3697 "ran out of source locations");
3702 unsigned RangeStart =
3704 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3709 GlobalSLocOffsetMap.insert(
3711 - SLocSpaceSize,&F));
3722 ParseLineTable(F,
Record);
3726 for (
unsigned I = 0, N =
Record.size(); I != N; )
3727 ExtVectorDecls.push_back(ReadDeclID(F,
Record, I));
3731 if (
Record.size() % 3 != 0)
3732 return llvm::createStringError(std::errc::illegal_byte_sequence,
3733 "Invalid VTABLE_USES record");
3740 for (
unsigned Idx = 0, N =
Record.size(); Idx != N; ) {
3741 VTableUses.push_back(
3742 {ReadDeclID(F,
Record, Idx),
3743 ReadSourceLocation(F,
Record, Idx).getRawEncoding(),
3750 if (
Record.size() % 2 != 0)
3751 return llvm::createStringError(
3752 std::errc::illegal_byte_sequence,
3753 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3755 for (
unsigned I = 0, N =
Record.size(); I != N; ) {
3756 PendingInstantiations.push_back(
3757 {ReadDeclID(F,
Record, I),
3758 ReadSourceLocation(F,
Record, I).getRawEncoding()});
3764 return llvm::createStringError(std::errc::illegal_byte_sequence,
3765 "Invalid SEMA_DECL_REFS block");
3766 for (
unsigned I = 0, N =
Record.size(); I != N; )
3767 SemaDeclRefs.push_back(ReadDeclID(F,
Record, I));
3775 unsigned LocalBasePreprocessedEntityID =
Record[0];
3777 unsigned StartingID;
3778 if (!PP.getPreprocessingRecord())
3779 PP.createPreprocessingRecord();
3780 if (!PP.getPreprocessingRecord()->getExternalSource())
3781 PP.getPreprocessingRecord()->SetExternalSource(*
this);
3783 = PP.getPreprocessingRecord()
3790 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3795 std::make_pair(LocalBasePreprocessedEntityID,
3807 if (!PP.getPreprocessingRecord())
3808 PP.createPreprocessingRecord();
3809 if (!PP.getPreprocessingRecord()->getExternalSource())
3810 PP.getPreprocessingRecord()->SetExternalSource(*
this);
3815 GlobalSkippedRangeMap.insert(
3821 if (
Record.size() % 2 != 0)
3822 return llvm::createStringError(
3823 std::errc::illegal_byte_sequence,
3824 "invalid DECL_UPDATE_OFFSETS block in AST file");
3825 for (
unsigned I = 0, N =
Record.size(); I != N; ) {
3827 DeclUpdateOffsets[
ID].push_back(std::make_pair(&F,
Record[I++]));
3831 if (
Decl *
D = GetExistingDecl(ID))
3832 PendingUpdateRecords.push_back(
3833 PendingUpdateRecord(ID,
D,
false));
3838 if (
Record.size() % 3 != 0)
3839 return llvm::createStringError(
3840 std::errc::illegal_byte_sequence,
3841 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
3843 for (
unsigned I = 0, N =
Record.size(); I != N; ) {
3847 assert(BaseOffset &&
"Invalid DeclsBlockStartOffset for module file!");
3850 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0;
3853 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0;
3855 DelayedNamespaceOffsetMap[
ID] = {LexicalOffset, VisibleOffset};
3857 assert(!GetExistingDecl(ID) &&
3858 "We shouldn't load the namespace in the front of delayed "
3859 "namespace lexical and visible block");
3866 return llvm::createStringError(
3867 std::errc::illegal_byte_sequence,
3868 "duplicate OBJC_CATEGORIES_MAP record in AST file");
3881 CUDASpecialDeclRefs.clear();
3882 for (
unsigned I = 0, N =
Record.size(); I != N; )
3883 CUDASpecialDeclRefs.push_back(ReadDeclID(F,
Record, I));
3891 = HeaderFileInfoLookupTable::Create(
3895 &PP.getHeaderSearchInfo(),
3896 Blob.data() +
Record[2]));
3898 PP.getHeaderSearchInfo().SetExternalSource(
this);
3899 if (!PP.getHeaderSearchInfo().getExternalLookup())
3900 PP.getHeaderSearchInfo().SetExternalLookup(
this);
3906 FPPragmaOptions.swap(
Record);
3910 for (
unsigned I = 0,
E =
Record.size(); I !=
E; ) {
3911 auto Name = ReadString(
Record, I);
3912 auto &OptInfo = OpenCLExtensions.OptMap[Name];
3913 OptInfo.Supported =
Record[I++] != 0;
3914 OptInfo.Enabled =
Record[I++] != 0;
3915 OptInfo.WithPragma =
Record[I++] != 0;
3916 OptInfo.Avail =
Record[I++];
3917 OptInfo.Core =
Record[I++];
3918 OptInfo.Opt =
Record[I++];
3923 for (
unsigned I = 0, N =
Record.size(); I != N; )
3924 TentativeDefinitions.push_back(ReadDeclID(F,
Record, I));
3928 for (
unsigned I = 0, N =
Record.size(); I != N; )
3929 KnownNamespaces.push_back(ReadDeclID(F,
Record, I));
3933 if (
Record.size() % 2 != 0)
3934 return llvm::createStringError(std::errc::illegal_byte_sequence,
3935 "invalid undefined-but-used record");
3936 for (
unsigned I = 0, N =
Record.size(); I != N; ) {
3937 UndefinedButUsed.push_back(
3938 {ReadDeclID(F,
Record, I),
3939 ReadSourceLocation(F,
Record, I).getRawEncoding()});
3944 for (
unsigned I = 0, N =
Record.size(); I != N;) {
3945 DelayedDeleteExprs.push_back(ReadDeclID(F,
Record, I).getRawValue());
3947 DelayedDeleteExprs.push_back(Count);
3948 for (uint64_t
C = 0;
C < Count; ++
C) {
3949 DelayedDeleteExprs.push_back(ReadSourceLocation(F,
Record, I).getRawEncoding());
3950 bool IsArrayForm =
Record[I++] == 1;
3951 DelayedDeleteExprs.push_back(IsArrayForm);
3958 getContext().getLangOpts().BuildingPCHWithObjectFile)
3959 for (
unsigned I = 0, N =
Record.size(); I != N;)
3960 VTablesToEmit.push_back(ReadDeclID(F,
Record, I));
3968 for (
unsigned I = 0, N =
Record.size(); I != N; ) {
3969 unsigned GlobalID = getGlobalSubmoduleID(F,
Record[I++]);
3972 PendingImportedModules.push_back(ImportedSubmodule(GlobalID,
Loc));
3973 if (DeserializationListener)
3974 DeserializationListener->ModuleImportRead(GlobalID,
Loc);
3982 return llvm::createStringError(
3983 std::errc::illegal_byte_sequence,
3984 "duplicate MACRO_OFFSET record in AST file");
3987 unsigned LocalBaseMacroID =
Record[1];
3993 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3997 std::make_pair(LocalBaseMacroID,
4006 LateParsedTemplates.emplace_back(
4007 std::piecewise_construct, std::forward_as_tuple(&F),
4013 return llvm::createStringError(std::errc::illegal_byte_sequence,
4014 "invalid pragma optimize record");
4015 OptimizeOffPragmaLocation = ReadSourceLocation(F,
Record[0]);
4020 return llvm::createStringError(std::errc::illegal_byte_sequence,
4021 "invalid pragma ms_struct record");
4022 PragmaMSStructState =
Record[0];
4027 return llvm::createStringError(
4028 std::errc::illegal_byte_sequence,
4029 "invalid pragma pointers to members record");
4030 PragmaMSPointersToMembersState =
Record[0];
4031 PointersToMembersPragmaLocation = ReadSourceLocation(F,
Record[1]);
4035 for (
unsigned I = 0, N =
Record.size(); I != N; )
4036 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F,
Record, I));
4041 return llvm::createStringError(std::errc::illegal_byte_sequence,
4042 "invalid cuda pragma options record");
4043 ForceHostDeviceDepth =
Record[0];
4048 return llvm::createStringError(std::errc::illegal_byte_sequence,
4049 "invalid pragma pack record");
4050 PragmaAlignPackCurrentValue = ReadAlignPackInfo(
Record[0]);
4051 PragmaAlignPackCurrentLocation = ReadSourceLocation(F,
Record[1]);
4052 unsigned NumStackEntries =
Record[2];
4055 PragmaAlignPackStack.clear();
4056 for (
unsigned I = 0; I < NumStackEntries; ++I) {
4057 PragmaAlignPackStackEntry Entry;
4058 Entry.Value = ReadAlignPackInfo(
Record[Idx++]);
4059 Entry.Location = ReadSourceLocation(F,
Record[Idx++]);
4060 Entry.PushLocation = ReadSourceLocation(F,
Record[Idx++]);
4061 PragmaAlignPackStrings.push_back(ReadString(
Record, Idx));
4062 Entry.SlotLabel = PragmaAlignPackStrings.back();
4063 PragmaAlignPackStack.push_back(Entry);
4070 return llvm::createStringError(std::errc::illegal_byte_sequence,
4071 "invalid pragma float control record");
4073 FpPragmaCurrentLocation = ReadSourceLocation(F,
Record[1]);
4074 unsigned NumStackEntries =
Record[2];
4077 FpPragmaStack.clear();
4078 for (
unsigned I = 0; I < NumStackEntries; ++I) {
4079 FpPragmaStackEntry Entry;
4081 Entry.Location = ReadSourceLocation(F,
Record[Idx++]);
4082 Entry.PushLocation = ReadSourceLocation(F,
Record[Idx++]);
4083 FpPragmaStrings.push_back(ReadString(
Record, Idx));
4084 Entry.SlotLabel = FpPragmaStrings.back();
4085 FpPragmaStack.push_back(Entry);
4091 for (
unsigned I = 0, N =
Record.size(); I != N; )
4092 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F,
Record, I));
4098void ASTReader::ReadModuleOffsetMap(
ModuleFile &F)
const {
4113 assert(ImportedModuleVector.empty());
4115 while (
Data < DataEnd) {
4119 using namespace llvm::support;
4121 endian::readNext<uint8_t, llvm::endianness::little>(
Data));
4122 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(
Data);
4123 StringRef Name = StringRef((
const char*)
Data, Len);
4127 ? ModuleMgr.lookupByModuleName(Name)
4128 : ModuleMgr.lookupByFileName(Name));
4130 std::string Msg =
"refers to unknown module, cannot find ";
4131 Msg.append(std::string(Name));
4136 ImportedModuleVector.push_back(OM);
4139 endian::readNext<uint32_t, llvm::endianness::little>(
Data);
4140 uint32_t PreprocessedEntityIDOffset =
4141 endian::readNext<uint32_t, llvm::endianness::little>(
Data);
4143 endian::readNext<uint32_t, llvm::endianness::little>(
Data);
4145 endian::readNext<uint32_t, llvm::endianness::little>(
Data);
4148 RemapBuilder &Remap) {
4149 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4151 Remap.insert(std::make_pair(Offset,
4152 static_cast<int>(BaseOffset - Offset)));
4155 mapOffset(MacroIDOffset, OM->
BaseMacroID, MacroRemap);
4157 PreprocessedEntityRemap);
4166 unsigned ClientLoadCapabilities) {
4175 "MODULE_NAME should come before MODULE_MAP_FILE");
4176 if (PP.getPreprocessorOpts().ModulesCheckRelocated &&
4182 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4184 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4186 if (!
bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
4189 if (!canRecoverFromOutOfDate(F.
FileName, ClientLoadCapabilities)) {
4190 if (
auto ASTFE = M ? M->
getASTFile() : std::nullopt) {
4193 << ASTFE->getName();
4196 Diag(diag::err_imported_module_not_found)
4204 Diag(diag::note_imported_by_pch_module_not_found)
4211 assert(M && M->
Name == F.
ModuleName &&
"found module with different name");
4215 if (!StoredModMap || *StoredModMap != ModMap) {
4216 assert(ModMap &&
"found module is missing module map file");
4218 "top-level import should be verified");
4220 if (!canRecoverFromOutOfDate(F.
FileName, ClientLoadCapabilities))
4221 Diag(diag::err_imported_module_modmap_changed)
4228 for (
unsigned I = 0, N =
Record[Idx++]; I < N; ++I) {
4233 if (!canRecoverFromOutOfDate(F.
FileName, ClientLoadCapabilities))
4234 Error(
"could not find file '" +
Filename +
"' referenced by AST file");
4237 AdditionalStoredMaps.insert(*SF);
4242 if (
auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4246 if (!AdditionalStoredMaps.erase(ModMap)) {
4247 if (!canRecoverFromOutOfDate(F.
FileName, ClientLoadCapabilities))
4248 Diag(diag::err_module_different_modmap)
4258 if (!canRecoverFromOutOfDate(F.
FileName, ClientLoadCapabilities))
4259 Diag(diag::err_module_different_modmap)
4280 : Known->second.second;
4282 for (
ObjCMethodList *List = &Start; List; List = List->getNext()) {
4284 if (List->getMethod() == Method) {
4292 if (List->getNext())
4293 List->setMethod(List->getNext()->getMethod());
4295 List->setMethod(Method);
4301 for (
Decl *
D : Names) {
4305 if (wasHidden && SemaObj) {
4318 Stack.push_back(Mod);
4319 while (!Stack.empty()) {
4320 Mod = Stack.pop_back_val();
4322 if (NameVisibility <= Mod->NameVisibility) {
4338 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4339 if (Hidden != HiddenNamesMap.end()) {
4341 HiddenNamesMap.erase(Hidden);
4343 assert(!HiddenNamesMap.contains(Mod) &&
4344 "making names visible added hidden names");
4351 I = Exports.begin(),
E = Exports.end(); I !=
E; ++I) {
4353 if (
Visited.insert(Exported).second)
4354 Stack.push_back(Exported);
4369 getContext().mergeDefinitionIntoModule(
4372 PendingMergedDefinitionsToDeduplicate.insert(Def);
4381 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4382 !PP.getLangOpts().Modules)
4386 TriedLoadingGlobalIndex =
true;
4387 StringRef ModuleCachePath
4388 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4389 std::pair<GlobalModuleIndex *, llvm::Error>
Result =
4391 if (llvm::Error Err = std::move(
Result.second)) {
4393 consumeError(std::move(Err));
4397 GlobalIndex.reset(
Result.first);
4398 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4403 return PP.getLangOpts().Modules && UseGlobalIndex &&
4404 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4411 llvm::raw_fd_ostream OS(TimestampFilename, EC,
4412 llvm::sys::fs::OF_TextWithCRLF);
4415 OS <<
"Timestamp file\n";
4428 consumeError(MaybeEntry.takeError());
4431 llvm::BitstreamEntry Entry = MaybeEntry.get();
4433 switch (Entry.Kind) {
4434 case llvm::BitstreamEntry::Error:
4435 case llvm::BitstreamEntry::EndBlock:
4438 case llvm::BitstreamEntry::Record:
4444 consumeError(Skipped.takeError());
4448 case llvm::BitstreamEntry::SubBlock:
4449 if (Entry.ID == BlockID) {
4450 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4452 consumeError(std::move(Err));
4459 if (llvm::Error Err = Cursor.SkipBlock()) {
4461 consumeError(std::move(Err));
4470 unsigned ClientLoadCapabilities,
4472 llvm::TimeTraceScope scope(
"ReadAST",
FileName);
4476 CurrentDeserializingModuleKind,
Type);
4482 unsigned PreviousGeneration = 0;
4484 PreviousGeneration = incrementGeneration(*ContextObj);
4486 unsigned NumModules = ModuleMgr.size();
4491 ClientLoadCapabilities)) {
4492 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4496 GlobalIndex.reset();
4497 ModuleMgr.setGlobalIndex(
nullptr);
4501 if (NewLoadedModuleFile && !Loaded.empty())
4502 *NewLoadedModuleFile = Loaded.back().Mod;
4513 for (ImportedModule &M : Loaded) {
4515 llvm::TimeTraceScope Scope2(
"Read Loaded AST", F.
ModuleName);
4518 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4519 Error(std::move(Err));
4525 Error(diag::err_module_file_missing_top_level_submodule, F.
FileName);
4531 if (llvm::Error Err = ReadExtensionBlock(F)) {
4532 Error(std::move(Err));
4545 for (ImportedModule &M : Loaded) {
4561 if (!PP.getLangOpts().CPlusPlus) {
4568 auto It = PP.getIdentifierTable().find(Key);
4569 if (It == PP.getIdentifierTable().end())
4578 II = &PP.getIdentifierTable().getOwn(Key);
4589 SetIdentifierInfo(ID, II);
4596 for (
auto &
Id : PP.getIdentifierTable())
4597 Id.second->setOutOfDate(
true);
4600 for (
const auto &Sel : SelectorGeneration)
4601 SelectorOutOfDate[Sel.first] =
true;
4605 for (ImportedModule &M : Loaded) {
4608 ModuleMgr.moduleFileAccepted(&F);
4617 F.
ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4621 for (
unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4622 UnresolvedModuleRef &
Unresolved = UnresolvedModuleRefs[I];
4624 Module *ResolvedMod = getSubmodule(GlobalID);
4627 case UnresolvedModuleRef::Conflict:
4630 Conflict.
Other = ResolvedMod;
4632 Unresolved.Mod->Conflicts.push_back(Conflict);
4636 case UnresolvedModuleRef::Import:
4641 case UnresolvedModuleRef::Affecting:
4643 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
4646 case UnresolvedModuleRef::Export:
4653 UnresolvedModuleRefs.clear();
4660 InitializeContext();
4665 if (DeserializationListener)
4666 DeserializationListener->ReaderInitialized(
this);
4668 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
4683 for (
unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4684 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4685 ObjCClassesLoaded[I], PreviousGeneration);
4694 for (
unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4695 ImportedModule &M = Loaded[I];
4712 if (!Stream.canSkipToPos(4))
4713 return llvm::createStringError(std::errc::illegal_byte_sequence,
4714 "file too small to contain AST file magic");
4715 for (
unsigned C : {
'C',
'P',
'C',
'H'})
4718 return llvm::createStringError(
4719 std::errc::illegal_byte_sequence,
4720 "file doesn't start with AST file magic");
4722 return Res.takeError();
4723 return llvm::Error::success();
4738 llvm_unreachable(
"unknown module kind");
4742ASTReader::ReadASTCore(StringRef
FileName,
4747 off_t ExpectedSize, time_t ExpectedModTime,
4749 unsigned ClientLoadCapabilities) {
4751 std::string ErrorStr;
4753 = ModuleMgr.addModule(
FileName,
Type, ImportLoc, ImportedBy,
4754 getGeneration(), ExpectedSize, ExpectedModTime,
4758 switch (AddResult) {
4760 Diag(diag::remark_module_import)
4762 << (ImportedBy ? StringRef(ImportedBy->
ModuleName) : StringRef());
4772 if (ClientLoadCapabilities & ARR_Missing)
4776 Diag(diag::err_ast_file_not_found)
4784 if (ClientLoadCapabilities & ARR_OutOfDate)
4788 Diag(diag::err_ast_file_out_of_date)
4794 assert(M &&
"Missing module file");
4796 bool ShouldFinalizePCM =
false;
4797 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4798 auto &MC = getModuleManager().getModuleCache();
4799 if (ShouldFinalizePCM)
4805 BitstreamCursor &Stream = F.
Stream;
4806 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4807 F.SizeInBits = F.Buffer->getBufferSize() * 8;
4811 Diag(diag::err_ast_file_invalid)
4817 bool HaveReadControlBlock =
false;
4821 Error(MaybeEntry.takeError());
4824 llvm::BitstreamEntry Entry = MaybeEntry.get();
4826 switch (Entry.Kind) {
4827 case llvm::BitstreamEntry::Error:
4828 case llvm::BitstreamEntry::Record:
4829 case llvm::BitstreamEntry::EndBlock:
4830 Error(
"invalid record at top-level of AST file");
4833 case llvm::BitstreamEntry::SubBlock:
4839 HaveReadControlBlock =
true;
4840 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4848 F.ModuleName.empty()) {
4850 if (
Result != OutOfDate ||
4851 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4857 case Failure:
return Failure;
4858 case Missing:
return Missing;
4859 case OutOfDate:
return OutOfDate;
4861 case ConfigurationMismatch:
return ConfigurationMismatch;
4862 case HadErrors:
return HadErrors;
4867 if (!HaveReadControlBlock) {
4868 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4869 Diag(diag::err_ast_file_version_too_old)
4875 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4876 ShouldFinalizePCM =
true;
4880 if (llvm::Error Err = Stream.SkipBlock()) {
4881 Error(std::move(Err));
4888 llvm_unreachable(
"unexpected break; expected return");
4892ASTReader::readUnhashedControlBlock(
ModuleFile &F,
bool WasImportedBy,
4893 unsigned ClientLoadCapabilities) {
4895 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4896 bool AllowCompatibleConfigurationMismatch =
4898 bool DisableValidation = shouldDisableValidationForFile(F);
4900 ASTReadResult
Result = readUnhashedControlBlockImpl(
4902 AllowCompatibleConfigurationMismatch, Listener.get(),
4907 if (DisableValidation || WasImportedBy ||
4908 (AllowConfigurationMismatch &&
Result == ConfigurationMismatch))
4912 Error(
"malformed block record in AST file");
4935 if (getModuleManager().getModuleCache().isPCMFinal(F.
FileName)) {
4936 Diag(diag::warn_module_system_bit_conflict) << F.
FileName;
4946 unsigned ClientLoadCapabilities,
bool AllowCompatibleConfigurationMismatch,
4949 BitstreamCursor Stream(StreamData);
4954 consumeError(std::move(Err));
4969 consumeError(MaybeEntry.takeError());
4972 llvm::BitstreamEntry Entry = MaybeEntry.get();
4974 switch (Entry.Kind) {
4975 case llvm::BitstreamEntry::Error:
4976 case llvm::BitstreamEntry::SubBlock:
4979 case llvm::BitstreamEntry::EndBlock:
4982 case llvm::BitstreamEntry::Record:
4991 Stream.readRecord(Entry.ID,
Record, &Blob);
4992 if (!MaybeRecordType) {
5001 "Dummy AST file signature not backpatched in ASTWriter.");
5008 "Dummy AST block hash not backpatched in ASTWriter.");
5012 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
5013 if (Listener && ValidateDiagnosticOptions &&
5014 !AllowCompatibleConfigurationMismatch &&
5020 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
5021 if (Listener && !AllowCompatibleConfigurationMismatch &&
5022 ParseHeaderSearchPaths(
Record, Complain, *Listener))
5023 Result = ConfigurationMismatch;
5052 if (
Record.size() < 4)
return true;
5057 unsigned BlockNameLen =
Record[2];
5058 unsigned UserInfoLen =
Record[3];
5060 if (BlockNameLen + UserInfoLen > Blob.size())
return true;
5062 Metadata.
BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5063 Metadata.
UserInfo = std::string(Blob.data() + BlockNameLen,
5064 Blob.data() + BlockNameLen + UserInfoLen);
5068llvm::Error ASTReader::ReadExtensionBlock(
ModuleFile &F) {
5069 BitstreamCursor &Stream = F.
Stream;
5075 return MaybeEntry.takeError();
5076 llvm::BitstreamEntry Entry = MaybeEntry.get();
5078 switch (Entry.Kind) {
5079 case llvm::BitstreamEntry::SubBlock:
5080 if (llvm::Error Err = Stream.SkipBlock())
5083 case llvm::BitstreamEntry::EndBlock:
5084 return llvm::Error::success();
5085 case llvm::BitstreamEntry::Error:
5086 return llvm::createStringError(std::errc::illegal_byte_sequence,
5087 "malformed block record in AST file");
5088 case llvm::BitstreamEntry::Record:
5095 Stream.readRecord(Entry.ID,
Record, &Blob);
5097 return MaybeRecCode.takeError();
5098 switch (MaybeRecCode.get()) {
5102 return llvm::createStringError(
5103 std::errc::illegal_byte_sequence,
5104 "malformed EXTENSION_METADATA in AST file");
5107 auto Known = ModuleFileExtensions.find(Metadata.
BlockName);
5108 if (Known == ModuleFileExtensions.end())
break;
5111 if (
auto Reader = Known->second->createExtensionReader(Metadata, *
this,
5121 return llvm::Error::success();
5125 assert(ContextObj &&
"no context to initialize");
5129 if (DeserializationListener)
5130 DeserializationListener->DeclRead(
5140 if (!Context.CFConstantStringTypeDecl)
5147 Error(
"FILE type is NULL");
5151 if (!Context.FILEDecl) {
5157 Error(
"Invalid FILE type in AST file");
5166 QualType Jmp_bufType = GetType(Jmp_buf);
5167 if (Jmp_bufType.
isNull()) {
5168 Error(
"jmp_buf type is NULL");
5172 if (!Context.jmp_bufDecl) {
5178 Error(
"Invalid jmp_buf type in AST file");
5187 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5188 if (Sigjmp_bufType.
isNull()) {
5189 Error(
"sigjmp_buf type is NULL");
5193 if (!Context.sigjmp_bufDecl) {
5198 assert(Tag &&
"Invalid sigjmp_buf type in AST file");
5205 if (Context.ObjCIdRedefinitionType.
isNull())
5206 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5209 if (
TypeID ObjCClassRedef =
5211 if (Context.ObjCClassRedefinitionType.
isNull())
5212 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5215 if (
TypeID ObjCSelRedef =
5217 if (Context.ObjCSelRedefinitionType.
isNull())
5218 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5222 QualType Ucontext_tType = GetType(Ucontext_t);
5223 if (Ucontext_tType.
isNull()) {
5224 Error(
"ucontext_t type is NULL");
5228 if (!Context.ucontext_tDecl) {
5233 assert(Tag &&
"Invalid ucontext_t type in AST file");
5243 if (!CUDASpecialDeclRefs.empty()) {
5244 assert(CUDASpecialDeclRefs.size() == 1 &&
"More decl refs than expected!");
5246 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5251 for (
auto &Import : PendingImportedModules) {
5252 if (
Module *Imported = getSubmodule(Import.ID)) {
5255 if (Import.ImportLoc.isValid())
5256 PP.makeModuleVisible(Imported, Import.ImportLoc);
5263 PendingImportedModulesSema.append(PendingImportedModules);
5264 PendingImportedModules.clear();
5274 BitstreamCursor Stream(
PCH);
5277 consumeError(std::move(Err));
5289 Stream.advanceSkippingSubblocks();
5292 consumeError(MaybeEntry.takeError());
5295 llvm::BitstreamEntry Entry = MaybeEntry.get();
5297 if (Entry.Kind != llvm::BitstreamEntry::Record)
5305 consumeError(MaybeRecord.takeError());
5311 "Dummy AST file signature not backpatched in ASTWriter.");
5321 const std::string &ASTFileName,
FileManager &FileMgr,
5327 Diags.
Report(diag::err_fe_unable_to_read_pch_file)