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:
1892 llvm_unreachable(
"missing deserialization code for annotation token");
1909 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1911 consumeError(std::move(Err));
1923 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1925 Stream.advanceSkippingSubblocks(Flags);
1927 Error(MaybeEntry.takeError());
1930 llvm::BitstreamEntry Entry = MaybeEntry.get();
1932 switch (Entry.Kind) {
1933 case llvm::BitstreamEntry::SubBlock:
1934 case llvm::BitstreamEntry::Error:
1935 Error(
"malformed block record in AST file");
1937 case llvm::BitstreamEntry::EndBlock:
1939 case llvm::BitstreamEntry::Record:
1950 Error(MaybeRecType.takeError());
1966 unsigned NextIndex = 1;
1973 PP.getPreprocessorAllocator());
1976 bool isC99VarArgs =
Record[NextIndex++];
1977 bool isGNUVarArgs =
Record[NextIndex++];
1978 bool hasCommaPasting =
Record[NextIndex++];
1979 MacroParams.clear();
1980 unsigned NumArgs =
Record[NextIndex++];
1981 for (
unsigned i = 0; i != NumArgs; ++i)
1982 MacroParams.push_back(getLocalIdentifier(F,
Record[NextIndex++]));
1996 if (NextIndex + 1 ==
Record.size() && PP.getPreprocessingRecord() &&
2000 GlobalID = getGlobalPreprocessedEntityID(F,
Record[NextIndex]);
2002 PreprocessingRecord::PPEntityID PPID =
2003 PPRec.getPPEntityID(GlobalID - 1,
true);
2005 PPRec.getPreprocessedEntity(PPID));
2007 PPRec.RegisterMacroDefinition(Macro, PPDef);
2018 if (MacroTokens.empty()) {
2019 Error(
"unexpected number of macro tokens for a macro in AST file");
2024 MacroTokens[0] = ReadToken(F,
Record, Idx);
2025 MacroTokens = MacroTokens.drop_front();
2034 unsigned LocalID)
const {
2036 ReadModuleOffsetMap(M);
2041 &&
"Invalid index into preprocessed entity index remap");
2043 return LocalID + I->second;
2046const FileEntry *HeaderFileInfoTrait::getFile(
const internal_key_type &Key) {
2048 if (!Key.Imported) {
2054 std::string Resolved = std::string(Key.Filename);
2055 Reader.ResolveImportedPath(M, Resolved);
2062 uint8_t buf[
sizeof(ikey.
Size) +
sizeof(ikey.
ModTime)];
2065 return llvm::xxh3_64bits(buf);
2086 return FEA && FEA == FEB;
2089std::pair<unsigned, unsigned>
2090HeaderFileInfoTrait::ReadKeyDataLength(
const unsigned char*& d) {
2095HeaderFileInfoTrait::ReadKey(
const unsigned char *d,
unsigned) {
2096 using namespace llvm::support;
2099 ikey.
Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2101 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2110 using namespace llvm::support;
2112 const unsigned char *End = d + DataLen;
2114 unsigned Flags = *d++;
2116 bool Included = (Flags >> 6) & 0x01;
2121 Reader.getPreprocessor().getIncludedFiles().insert(FE);
2124 HFI.
isImport |= (Flags >> 5) & 0x01;
2126 HFI.
DirInfo = (Flags >> 1) & 0x07;
2129 M, endian::readNext<IdentifierID, llvm::endianness::little>(d));
2130 if (
unsigned FrameworkOffset =
2131 endian::readNext<uint32_t, llvm::endianness::little>(d)) {
2134 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
2135 HFI.
Framework = HS->getUniqueFrameworkName(FrameworkName);
2138 assert((End - d) % 4 == 0 &&
2139 "Wrong data length in HeaderFileInfo deserialization");
2141 uint32_t LocalSMID =
2142 endian::readNext<uint32_t, llvm::endianness::little>(d);
2148 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2149 Module *Mod = Reader.getSubmodule(GlobalSMID);
2152 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2156 Reader.ResolveImportedPath(M,
Filename);
2160 ModMap.
addHeader(Mod, H, HeaderRole,
true);
2172 uint32_t MacroDirectivesOffset) {
2173 assert(NumCurrentElementsDeserializing > 0 &&
"Missing deserialization guard");
2174 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2181 for (
ModuleFile &I : llvm::reverse(ModuleMgr)) {
2182 BitstreamCursor &MacroCursor = I.MacroCursor;
2185 if (MacroCursor.getBitcodeBytes().empty())
2188 BitstreamCursor Cursor = MacroCursor;
2189 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2190 Error(std::move(Err));
2198 Error(MaybeE.takeError());
2201 llvm::BitstreamEntry
E = MaybeE.get();
2204 case llvm::BitstreamEntry::SubBlock:
2205 case llvm::BitstreamEntry::Error:
2206 Error(
"malformed block record in AST file");
2208 case llvm::BitstreamEntry::EndBlock:
2211 case llvm::BitstreamEntry::Record: {
2215 Error(MaybeRecord.takeError());
2218 switch (MaybeRecord.get()) {
2226 updateOutOfDateIdentifier(*II);
2245 class IdentifierLookupVisitor {
2248 unsigned PriorGeneration;
2249 unsigned &NumIdentifierLookups;
2250 unsigned &NumIdentifierLookupHits;
2254 IdentifierLookupVisitor(StringRef Name,
unsigned PriorGeneration,
2255 unsigned &NumIdentifierLookups,
2256 unsigned &NumIdentifierLookupHits)
2258 PriorGeneration(PriorGeneration),
2259 NumIdentifierLookups(NumIdentifierLookups),
2260 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2274 ++NumIdentifierLookups;
2275 ASTIdentifierLookupTable::iterator Pos =
2276 IdTable->find_hashed(Name, NameHash, &Trait);
2277 if (Pos == IdTable->end())
2283 ++NumIdentifierLookupHits;
2299 unsigned PriorGeneration = 0;
2300 if (getContext().getLangOpts().Modules)
2301 PriorGeneration = IdentifierGeneration[&II];
2307 if (!loadGlobalIndex()) {
2308 if (GlobalIndex->lookupIdentifier(II.
getName(), Hits)) {
2313 IdentifierLookupVisitor Visitor(II.
getName(), PriorGeneration,
2314 NumIdentifierLookups,
2315 NumIdentifierLookupHits);
2316 ModuleMgr.visit(Visitor, HitsPtr);
2317 markIdentifierUpToDate(&II);
2327 if (getContext().getLangOpts().Modules)
2328 IdentifierGeneration[II] = getGeneration();
2332 const PendingMacroInfo &PMInfo) {
2337 if (llvm::Error Err =
2339 Error(std::move(Err));
2343 struct ModuleMacroRecord {
2356 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2358 Error(MaybeEntry.takeError());
2361 llvm::BitstreamEntry Entry = MaybeEntry.get();
2363 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2364 Error(
"malformed block record in AST file");
2371 Error(MaybePP.takeError());
2379 ModuleMacros.push_back(ModuleMacroRecord());
2380 auto &Info = ModuleMacros.back();
2381 Info.SubModID = getGlobalSubmoduleID(M,
Record[0]);
2382 Info.MI = getMacro(getGlobalMacroID(M,
Record[1]));
2383 for (
int I = 2, N =
Record.size(); I != N; ++I)
2384 Info.Overrides.push_back(getGlobalSubmoduleID(M,
Record[I]));
2389 Error(
"malformed block record in AST file");
2400 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2402 for (
auto &MMR : ModuleMacros) {
2404 for (
unsigned ModID : MMR.Overrides) {
2405 Module *Mod = getSubmodule(ModID);
2406 auto *Macro = PP.getModuleMacro(Mod, II);
2407 assert(Macro &&
"missing definition for overridden macro");
2408 Overrides.push_back(Macro);
2411 bool Inserted =
false;
2412 Module *Owner = getSubmodule(MMR.SubModID);
2413 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2424 unsigned Idx = 0, N =
Record.size();
2432 MD = PP.AllocateDefMacroDirective(MI,
Loc);
2436 MD = PP.AllocateUndefMacroDirective(
Loc);
2439 bool isPublic =
Record[Idx++];
2440 MD = PP.AllocateVisibilityMacroDirective(
Loc, isPublic);
2452 PP.setLoadedMacroDirective(II, Earliest, Latest);
2455bool ASTReader::shouldDisableValidationForFile(
2493 consumeError(std::move(Err));
2499 consumeError(MaybeCode.takeError());
2501 unsigned Code = MaybeCode.get();
2507 "invalid record type for input file");
2510 consumeError(Maybe.takeError());
2513 assert(
Record[0] == ID &&
"Bogus stored ID or offset");
2522 uint16_t AsRequestedLength =
Record[7];
2524 std::string NameAsRequested = Blob.substr(0, AsRequestedLength).str();
2525 std::string Name = Blob.substr(AsRequestedLength).str();
2527 ResolveImportedPath(F, NameAsRequested);
2528 ResolveImportedPath(F, Name);
2531 Name = NameAsRequested;
2533 return std::make_pair(std::move(NameAsRequested), std::move(Name));
2538 consumeError(MaybeEntry.takeError());
2539 llvm::BitstreamEntry Entry = MaybeEntry.get();
2540 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2541 "expected record type for input file hash");
2546 "invalid record type for input file hash");
2549 consumeError(Maybe.takeError());
2578 consumeError(std::move(Err));
2593 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2606 if ((Overridden || Transient || SkipChecks) && !
File)
2611 std::string ErrorStr =
"could not find file '";
2613 ErrorStr +=
"' referenced by AST file '";
2629 if ((!Overridden && !Transient) && !SkipChecks &&
2630 SM.isFileOverridden(*
File)) {
2644 enum ModificationKind {
2650 std::optional<int64_t> Old = std::nullopt;
2651 std::optional<int64_t> New = std::nullopt;
2653 auto HasInputContentChanged = [&](Change OriginalChange) {
2654 assert(ValidateASTInputFilesContent &&
2655 "We should only check the content of the inputs with "
2656 "ValidateASTInputFilesContent enabled.");
2658 if (StoredContentHash == 0)
2659 return OriginalChange;
2662 if (!MemBuffOrError) {
2664 return OriginalChange;
2665 std::string ErrorStr =
"could not get buffer for file '";
2666 ErrorStr +=
File->getName();
2669 return OriginalChange;
2672 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer());
2673 if (StoredContentHash ==
static_cast<uint64_t>(ContentHash))
2674 return Change{Change::None};
2676 return Change{Change::Content};
2678 auto HasInputFileChanged = [&]() {
2679 if (StoredSize !=
File->getSize())
2680 return Change{Change::Size, StoredSize,
File->getSize()};
2681 if (!shouldDisableValidationForFile(F) && StoredTime &&
2682 StoredTime !=
File->getModificationTime()) {
2683 Change MTimeChange = {Change::ModTime, StoredTime,
2684 File->getModificationTime()};
2688 if (ValidateASTInputFilesContent)
2689 return HasInputContentChanged(MTimeChange);
2693 return Change{Change::None};
2696 bool IsOutOfDate =
false;
2697 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2703 FileChange = HasInputContentChanged(FileChange);
2709 if (!StoredTime && ValidateASTInputFilesContent &&
2710 FileChange.Kind == Change::None)
2711 FileChange = HasInputContentChanged(FileChange);
2714 if (!Overridden && FileChange.Kind != Change::None) {
2715 if (Complain && !Diags.isDiagnosticInFlight()) {
2718 while (!ImportStack.back()->ImportedBy.empty())
2719 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2722 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2723 Diag(diag::err_fe_ast_file_modified)
2725 << TopLevelPCHName << FileChange.Kind
2726 << (FileChange.Old && FileChange.New)
2727 << llvm::itostr(FileChange.Old.value_or(0))
2728 << llvm::itostr(FileChange.New.value_or(0));
2731 if (ImportStack.size() > 1) {
2732 Diag(diag::note_pch_required_by)
2733 <<
Filename << ImportStack[0]->FileName;
2734 for (
unsigned I = 1; I < ImportStack.size(); ++I)
2735 Diag(diag::note_pch_required_by)
2736 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2739 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2769 llvm::sys::path::append(Buffer, Prefix,
Filename);
2770 Filename.assign(Buffer.begin(), Buffer.end());
2785 llvm_unreachable(
"unknown ASTReadResult");
2789 BitstreamCursor &Stream, StringRef
Filename,
2790 unsigned ClientLoadCapabilities,
bool AllowCompatibleConfigurationMismatch,
2794 consumeError(std::move(Err));
2805 consumeError(MaybeEntry.takeError());
2808 llvm::BitstreamEntry Entry = MaybeEntry.get();
2810 switch (Entry.Kind) {
2811 case llvm::BitstreamEntry::Error:
2812 case llvm::BitstreamEntry::SubBlock:
2815 case llvm::BitstreamEntry::EndBlock:
2818 case llvm::BitstreamEntry::Record:
2826 if (!MaybeRecordType) {
2828 consumeError(MaybeRecordType.takeError());
2833 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2835 AllowCompatibleConfigurationMismatch))
2836 Result = ConfigurationMismatch;
2841 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2843 AllowCompatibleConfigurationMismatch))
2844 Result = ConfigurationMismatch;
2849 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2850 if (!AllowCompatibleConfigurationMismatch &&
2851 ParseFileSystemOptions(
Record, Complain, Listener))
2852 Result = ConfigurationMismatch;
2857 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2858 if (!AllowCompatibleConfigurationMismatch &&
2860 Result = ConfigurationMismatch;
2865 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2866 if (!AllowCompatibleConfigurationMismatch &&
2868 SuggestedPredefines))
2869 Result = ConfigurationMismatch;
2879 unsigned ClientLoadCapabilities) {
2880 BitstreamCursor &Stream = F.
Stream;
2883 Error(std::move(Err));
2893 bool HasReadUnhashedControlBlock =
false;
2894 auto readUnhashedControlBlockOnce = [&]() {
2895 if (!HasReadUnhashedControlBlock) {
2896 HasReadUnhashedControlBlock =
true;
2897 if (ASTReadResult
Result =
2898 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2904 bool DisableValidation = shouldDisableValidationForFile(F);
2908 unsigned NumInputs = 0;
2909 unsigned NumUserInputs = 0;
2910 StringRef BaseDirectoryAsWritten;
2914 Error(MaybeEntry.takeError());
2917 llvm::BitstreamEntry Entry = MaybeEntry.get();
2919 switch (Entry.Kind) {
2920 case llvm::BitstreamEntry::Error:
2921 Error(
"malformed block record in AST file");
2923 case llvm::BitstreamEntry::EndBlock: {
2926 if (ASTReadResult
Result = readUnhashedControlBlockOnce())
2931 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2938 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2944 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
2950 for (
unsigned I = 0; I < N; ++I) {
2951 InputFile IF = getInputFile(F, I+1, Complain);
2963 for (
unsigned I = 0; I < N; ++I) {
2964 bool IsSystem = I >= NumUserInputs;
2975 case llvm::BitstreamEntry::SubBlock:
2979 if (llvm::Error Err = Stream.SkipBlock()) {
2980 Error(std::move(Err));
2984 Error(
"malformed block record in AST file");
2994 if (Listener && !ImportedBy) {
3000 bool AllowCompatibleConfigurationMismatch =
3004 ReadOptionsBlock(Stream, F.
FileName, ClientLoadCapabilities,
3005 AllowCompatibleConfigurationMismatch, *Listener,
3006 SuggestedPredefines);
3008 Error(
"malformed block record in AST file");
3012 if (DisableValidation ||
3013 (AllowConfigurationMismatch &&
Result == ConfigurationMismatch))
3021 }
else if (llvm::Error Err = Stream.SkipBlock()) {
3022 Error(std::move(Err));
3028 if (llvm::Error Err = Stream.SkipBlock()) {
3029 Error(std::move(Err));
3035 case llvm::BitstreamEntry::Record:
3044 Stream.readRecord(Entry.ID,
Record, &Blob);
3045 if (!MaybeRecordType) {
3046 Error(MaybeRecordType.takeError());
3052 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3054 : diag::err_ast_file_version_too_new)
3059 bool hasErrors =
Record[7];
3060 if (hasErrors && !DisableValidation) {
3063 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
3064 canRecoverFromOutOfDate(F.
FileName, ClientLoadCapabilities))
3067 if (!AllowASTWithCompilerErrors) {
3068 Diag(diag::err_ast_file_with_compiler_errors)
3074 Diags.ErrorOccurred =
true;
3075 Diags.UncompilableErrorOccurred =
true;
3076 Diags.UnrecoverableErrorOccurred =
true;
3089 StringRef ASTBranch = Blob;
3090 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3091 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3092 Diag(diag::err_ast_file_different_branch)
3104 if (ASTReadResult
Result = readUnhashedControlBlockOnce())
3108 unsigned Idx = 0, N =
Record.size();
3113 bool IsImportingStdCXXModule =
Record[Idx++];
3117 auto [ImportLoc, ImportModuleFileIndex] =
3118 ReadUntranslatedSourceLocation(
Record[Idx++]);
3120 assert(ImportModuleFileIndex == 0);
3121 off_t StoredSize = !IsImportingStdCXXModule ? (off_t)
Record[Idx++] : 0;
3122 time_t StoredModTime =
3123 !IsImportingStdCXXModule ? (time_t)
Record[Idx++] : 0;
3126 if (!IsImportingStdCXXModule) {
3127 auto FirstSignatureByte =
Record.begin() + Idx;
3133 std::string ImportedName = ReadString(
Record, Idx);
3134 std::string ImportedFile;
3143 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3144 ImportedName, !IsImportingStdCXXModule);
3148 if (!IsImportingStdCXXModule) {
3149 if (ImportedFile.empty()) {
3152 ImportedFile = ReadPath(BaseDirectoryAsWritten,
Record, Idx);
3155 }
else if (ImportedFile.empty()) {
3156 Diag(clang::diag::err_failed_to_find_module_file) << ImportedName;
3162 unsigned Capabilities = ClientLoadCapabilities;
3163 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3164 Capabilities &= ~ARR_Missing;
3167 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3168 Loaded, StoredSize, StoredModTime,
3169 StoredSignature, Capabilities);
3172 bool recompilingFinalized =
3173 Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&
3174 getModuleManager().getModuleCache().isPCMFinal(F.
FileName);
3176 Diag(diag::note_module_file_imported_by)
3178 if (recompilingFinalized)
3179 Diag(diag::note_module_file_conflict);
3182 case Failure:
return Failure;
3185 case OutOfDate:
return OutOfDate;
3187 case ConfigurationMismatch:
return ConfigurationMismatch;
3188 case HadErrors:
return HadErrors;
3208 Diag(diag::remark_module_import)
3210 << (ImportedBy ? StringRef(ImportedBy->
ModuleName) : StringRef());
3216 if (ASTReadResult
Result = readUnhashedControlBlockOnce())
3224 BaseDirectoryAsWritten = Blob;
3226 "MODULE_DIRECTORY found before MODULE_NAME");
3228 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3232 Module *M = PP.getHeaderSearchInfo().lookupModule(
3239 if (!
bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3242 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3243 if (!BuildDir || *BuildDir != M->
Directory) {
3244 if (!canRecoverFromOutOfDate(F.
FileName, ClientLoadCapabilities))
3245 Diag(diag::err_imported_module_relocated)
3256 if (ASTReadResult
Result =
3257 ReadModuleMapFileBlock(
Record, F, ImportedBy, ClientLoadCapabilities))
3263 NumUserInputs =
Record[1];
3265 (
const llvm::support::unaligned_uint64_t *)Blob.data();
3274llvm::Error ASTReader::ReadASTBlock(
ModuleFile &F,
3275 unsigned ClientLoadCapabilities) {
3276 BitstreamCursor &Stream = F.
Stream;
3278 if (llvm::Error Err = Stream.EnterSubBlock(
AST_BLOCK_ID))
3287 return MaybeEntry.takeError();
3288 llvm::BitstreamEntry Entry = MaybeEntry.get();
3290 switch (Entry.Kind) {
3291 case llvm::BitstreamEntry::Error:
3292 return llvm::createStringError(
3293 std::errc::illegal_byte_sequence,
3294 "error at end of module block in AST file");
3295 case llvm::BitstreamEntry::EndBlock:
3307 return llvm::Error::success();
3308 case llvm::BitstreamEntry::SubBlock:
3316 if (llvm::Error Err = Stream.SkipBlock())
3318 if (llvm::Error Err = ReadBlockAbbrevs(
3325 if (!PP.getExternalSource())
3326 PP.setExternalSource(
this);
3328 if (llvm::Error Err = Stream.SkipBlock())
3330 if (llvm::Error Err =
3339 if (llvm::Error Err = Stream.SkipBlock()) {
3348 if (!PP.getPreprocessingRecord())
3349 PP.createPreprocessingRecord();
3350 if (!PP.getPreprocessingRecord()->getExternalSource())
3351 PP.getPreprocessingRecord()->SetExternalSource(*
this);
3355 if (llvm::Error Err = ReadSourceManagerBlock(F))
3360 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3365 BitstreamCursor
C = Stream;
3367 if (llvm::Error Err = Stream.SkipBlock())
3371 CommentsCursors.push_back(std::make_pair(
C, &F));
3376 if (llvm::Error Err = Stream.SkipBlock())
3382 case llvm::BitstreamEntry::Record:
3391 Stream.readRecord(Entry.ID,
Record, &Blob);
3392 if (!MaybeRecordType)
3393 return MaybeRecordType.takeError();
3425 return llvm::createStringError(
3426 std::errc::illegal_byte_sequence,
3427 "duplicate TYPE_OFFSET record in AST file");
3440 return llvm::createStringError(
3441 std::errc::illegal_byte_sequence,
3442 "duplicate DECL_OFFSET record in AST file");
3454 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3455 LexicalContents Contents(
3457 static_cast<unsigned int>(Blob.size() /
sizeof(
DeclID)));
3458 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3466 auto *
Data = (
const unsigned char*)Blob.data();
3467 PendingVisibleUpdates[
ID].push_back(PendingVisibleUpdate{&F,
Data});
3470 if (
Decl *
D = GetExistingDecl(ID))
3471 PendingUpdateRecords.push_back(
3472 PendingUpdateRecord(ID,
D,
false));
3478 reinterpret_cast<const unsigned char *
>(Blob.data());
3486 PP.getIdentifierTable().setExternalIdentifierLookup(
this);
3492 return llvm::createStringError(
3493 std::errc::illegal_byte_sequence,
3494 "duplicate IDENTIFIER_OFFSET record in AST file");
3500 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3512 for (
unsigned I = 0, N =
Record.size(); I != N; )
3513 EagerlyDeserializedDecls.push_back(ReadDeclID(F,
Record, I));
3520 getContext().getLangOpts().BuildingPCHWithObjectFile)
3521 for (
unsigned I = 0, N =
Record.size(); I != N; )
3522 EagerlyDeserializedDecls.push_back(ReadDeclID(F,
Record, I));
3526 if (SpecialTypes.empty()) {
3527 for (
unsigned I = 0, N =
Record.size(); I != N; ++I)
3528 SpecialTypes.push_back(getGlobalTypeID(F,
Record[I]));
3532 if (SpecialTypes.size() !=
Record.size())
3533 return llvm::createStringError(std::errc::illegal_byte_sequence,
3534 "invalid special-types record");
3536 for (
unsigned I = 0, N =
Record.size(); I != N; ++I) {
3538 if (!SpecialTypes[I])
3539 SpecialTypes[I] =
ID;
3546 TotalNumStatements +=
Record[0];
3547 TotalNumMacros +=
Record[1];
3548 TotalLexicalDeclContexts +=
Record[2];
3549 TotalVisibleDeclContexts +=
Record[3];
3553 for (
unsigned I = 0, N =
Record.size(); I != N; )
3554 UnusedFileScopedDecls.push_back(ReadDeclID(F,
Record, I));
3558 for (
unsigned I = 0, N =
Record.size(); I != N; )
3559 DelegatingCtorDecls.push_back(ReadDeclID(F,
Record, I));
3563 if (
Record.size() % 3 != 0)
3564 return llvm::createStringError(std::errc::illegal_byte_sequence,
3565 "invalid weak identifiers record");
3569 WeakUndeclaredIdentifiers.clear();
3572 for (
unsigned I = 0, N =
Record.size(); I < N; ) {
3573 WeakUndeclaredIdentifiers.push_back(
3574 getGlobalIdentifierID(F,
Record[I++]));
3575 WeakUndeclaredIdentifiers.push_back(
3576 getGlobalIdentifierID(F,
Record[I++]));
3577 WeakUndeclaredIdentifiers.push_back(
3578 ReadSourceLocation(F,
Record, I).getRawEncoding());
3585 unsigned LocalBaseSelectorID =
Record[1];
3591 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3596 std::make_pair(LocalBaseSelectorID,
3608 = ASTSelectorLookupTable::Create(
3612 TotalNumMethodPoolEntries +=
Record[1];
3617 for (
unsigned Idx = 0, N =
Record.size() - 1; Idx < N; ) {
3618 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3620 ReferencedSelectorsData.push_back(ReadSourceLocation(F,
Record, Idx).
3629 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
3630 ReadSourceLocation(F,
Record, Idx));
3638 while (Idx <
Record.size())
3639 SrcLocs.push_back(ReadSourceLocation(F,
Record, Idx));
3640 PP.setDeserializedSafeBufferOptOutMap(SrcLocs);
3647 unsigned Idx = 0, End =
Record.size() - 1;
3648 bool ReachedEOFWhileSkipping =
Record[Idx++];
3649 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3650 if (ReachedEOFWhileSkipping) {
3653 bool FoundNonSkipPortion =
Record[Idx++];
3654 bool FoundElse =
Record[Idx++];
3656 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3657 FoundElse, ElseLoc);
3661 auto Loc = ReadSourceLocation(F,
Record, Idx);
3662 bool WasSkipping =
Record[Idx++];
3663 bool FoundNonSkip =
Record[Idx++];
3664 bool FoundElse =
Record[Idx++];
3665 ConditionalStack.push_back(
3666 {
Loc, WasSkipping, FoundNonSkip, FoundElse});
3668 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
3673 if (!
Record.empty() && Listener)
3691 if (!Diags.isDiagnosticInFlight()) {
3693 SourceMgr.noteSLocAddressSpaceUsage(Diags);
3695 return llvm::createStringError(std::errc::invalid_argument,
3696 "ran out of source locations");
3701 unsigned RangeStart =
3703 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3708 GlobalSLocOffsetMap.insert(
3710 - SLocSpaceSize,&F));
3721 ParseLineTable(F,
Record);
3725 for (
unsigned I = 0, N =
Record.size(); I != N; )
3726 ExtVectorDecls.push_back(ReadDeclID(F,
Record, I));
3730 if (
Record.size() % 3 != 0)
3731 return llvm::createStringError(std::errc::illegal_byte_sequence,
3732 "Invalid VTABLE_USES record");
3739 for (
unsigned Idx = 0, N =
Record.size(); Idx != N; ) {
3740 VTableUses.push_back(
3741 {ReadDeclID(F,
Record, Idx),
3742 ReadSourceLocation(F,
Record, Idx).getRawEncoding(),
3749 if (
Record.size() % 2 != 0)
3750 return llvm::createStringError(
3751 std::errc::illegal_byte_sequence,
3752 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3754 for (
unsigned I = 0, N =
Record.size(); I != N; ) {
3755 PendingInstantiations.push_back(
3756 {ReadDeclID(F,
Record, I),
3757 ReadSourceLocation(F,
Record, I).getRawEncoding()});
3763 return llvm::createStringError(std::errc::illegal_byte_sequence,
3764 "Invalid SEMA_DECL_REFS block");
3765 for (
unsigned I = 0, N =
Record.size(); I != N; )
3766 SemaDeclRefs.push_back(ReadDeclID(F,
Record, I));
3774 unsigned LocalBasePreprocessedEntityID =
Record[0];
3776 unsigned StartingID;
3777 if (!PP.getPreprocessingRecord())
3778 PP.createPreprocessingRecord();
3779 if (!PP.getPreprocessingRecord()->getExternalSource())
3780 PP.getPreprocessingRecord()->SetExternalSource(*
this);
3782 = PP.getPreprocessingRecord()
3789 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3794 std::make_pair(LocalBasePreprocessedEntityID,
3806 if (!PP.getPreprocessingRecord())
3807 PP.createPreprocessingRecord();
3808 if (!PP.getPreprocessingRecord()->getExternalSource())
3809 PP.getPreprocessingRecord()->SetExternalSource(*
this);
3814 GlobalSkippedRangeMap.insert(
3820 if (
Record.size() % 2 != 0)
3821 return llvm::createStringError(
3822 std::errc::illegal_byte_sequence,
3823 "invalid DECL_UPDATE_OFFSETS block in AST file");
3824 for (
unsigned I = 0, N =
Record.size(); I != N; ) {
3826 DeclUpdateOffsets[
ID].push_back(std::make_pair(&F,
Record[I++]));
3830 if (
Decl *
D = GetExistingDecl(ID))
3831 PendingUpdateRecords.push_back(
3832 PendingUpdateRecord(ID,
D,
false));
3837 if (
Record.size() % 3 != 0)
3838 return llvm::createStringError(
3839 std::errc::illegal_byte_sequence,
3840 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
3842 for (
unsigned I = 0, N =
Record.size(); I != N; ) {
3846 assert(BaseOffset &&
"Invalid DeclsBlockStartOffset for module file!");
3849 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0;
3852 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0;
3854 DelayedNamespaceOffsetMap[
ID] = {LexicalOffset, VisibleOffset};
3856 assert(!GetExistingDecl(ID) &&
3857 "We shouldn't load the namespace in the front of delayed "
3858 "namespace lexical and visible block");
3865 return llvm::createStringError(
3866 std::errc::illegal_byte_sequence,
3867 "duplicate OBJC_CATEGORIES_MAP record in AST file");
3880 CUDASpecialDeclRefs.clear();
3881 for (
unsigned I = 0, N =
Record.size(); I != N; )
3882 CUDASpecialDeclRefs.push_back(ReadDeclID(F,
Record, I));
3890 = HeaderFileInfoLookupTable::Create(
3894 &PP.getHeaderSearchInfo(),
3895 Blob.data() +
Record[2]));
3897 PP.getHeaderSearchInfo().SetExternalSource(
this);
3898 if (!PP.getHeaderSearchInfo().getExternalLookup())
3899 PP.getHeaderSearchInfo().SetExternalLookup(
this);
3905 FPPragmaOptions.swap(
Record);
3909 for (
unsigned I = 0,
E =
Record.size(); I !=
E; ) {
3910 auto Name = ReadString(
Record, I);
3911 auto &OptInfo = OpenCLExtensions.OptMap[Name];
3912 OptInfo.Supported =
Record[I++] != 0;
3913 OptInfo.Enabled =
Record[I++] != 0;
3914 OptInfo.WithPragma =
Record[I++] != 0;
3915 OptInfo.Avail =
Record[I++];
3916 OptInfo.Core =
Record[I++];
3917 OptInfo.Opt =
Record[I++];
3922 for (
unsigned I = 0, N =
Record.size(); I != N; )
3923 TentativeDefinitions.push_back(ReadDeclID(F,
Record, I));
3927 for (
unsigned I = 0, N =
Record.size(); I != N; )
3928 KnownNamespaces.push_back(ReadDeclID(F,
Record, I));
3932 if (
Record.size() % 2 != 0)
3933 return llvm::createStringError(std::errc::illegal_byte_sequence,
3934 "invalid undefined-but-used record");
3935 for (
unsigned I = 0, N =
Record.size(); I != N; ) {
3936 UndefinedButUsed.push_back(
3937 {ReadDeclID(F,
Record, I),
3938 ReadSourceLocation(F,
Record, I).getRawEncoding()});
3943 for (
unsigned I = 0, N =
Record.size(); I != N;) {
3944 DelayedDeleteExprs.push_back(ReadDeclID(F,
Record, I).getRawValue());
3946 DelayedDeleteExprs.push_back(Count);
3947 for (uint64_t
C = 0;
C < Count; ++
C) {
3948 DelayedDeleteExprs.push_back(ReadSourceLocation(F,
Record, I).getRawEncoding());
3949 bool IsArrayForm =
Record[I++] == 1;
3950 DelayedDeleteExprs.push_back(IsArrayForm);
3957 getContext().getLangOpts().BuildingPCHWithObjectFile)
3958 for (
unsigned I = 0, N =
Record.size(); I != N;)
3959 VTablesToEmit.push_back(ReadDeclID(F,
Record, I));
3967 for (
unsigned I = 0, N =
Record.size(); I != N; ) {
3968 unsigned GlobalID = getGlobalSubmoduleID(F,
Record[I++]);
3971 PendingImportedModules.push_back(ImportedSubmodule(GlobalID,
Loc));
3972 if (DeserializationListener)
3973 DeserializationListener->ModuleImportRead(GlobalID,
Loc);
3981 return llvm::createStringError(
3982 std::errc::illegal_byte_sequence,
3983 "duplicate MACRO_OFFSET record in AST file");
3986 unsigned LocalBaseMacroID =
Record[1];
3992 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3996 std::make_pair(LocalBaseMacroID,
4005 LateParsedTemplates.emplace_back(
4006 std::piecewise_construct, std::forward_as_tuple(&F),
4012 return llvm::createStringError(std::errc::illegal_byte_sequence,
4013 "invalid pragma optimize record");
4014 OptimizeOffPragmaLocation = ReadSourceLocation(F,
Record[0]);
4019 return llvm::createStringError(std::errc::illegal_byte_sequence,
4020 "invalid pragma ms_struct record");
4021 PragmaMSStructState =
Record[0];
4026 return llvm::createStringError(
4027 std::errc::illegal_byte_sequence,
4028 "invalid pragma pointers to members record");
4029 PragmaMSPointersToMembersState =
Record[0];
4030 PointersToMembersPragmaLocation = ReadSourceLocation(F,
Record[1]);
4034 for (
unsigned I = 0, N =
Record.size(); I != N; )
4035 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F,
Record, I));
4040 return llvm::createStringError(std::errc::illegal_byte_sequence,
4041 "invalid cuda pragma options record");
4042 ForceHostDeviceDepth =
Record[0];
4047 return llvm::createStringError(std::errc::illegal_byte_sequence,
4048 "invalid pragma pack record");
4049 PragmaAlignPackCurrentValue = ReadAlignPackInfo(
Record[0]);
4050 PragmaAlignPackCurrentLocation = ReadSourceLocation(F,
Record[1]);
4051 unsigned NumStackEntries =
Record[2];
4054 PragmaAlignPackStack.clear();
4055 for (
unsigned I = 0; I < NumStackEntries; ++I) {
4056 PragmaAlignPackStackEntry Entry;
4057 Entry.Value = ReadAlignPackInfo(
Record[Idx++]);
4058 Entry.Location = ReadSourceLocation(F,
Record[Idx++]);
4059 Entry.PushLocation = ReadSourceLocation(F,
Record[Idx++]);
4060 PragmaAlignPackStrings.push_back(ReadString(
Record, Idx));
4061 Entry.SlotLabel = PragmaAlignPackStrings.back();
4062 PragmaAlignPackStack.push_back(Entry);
4069 return llvm::createStringError(std::errc::illegal_byte_sequence,
4070 "invalid pragma float control record");
4072 FpPragmaCurrentLocation = ReadSourceLocation(F,
Record[1]);
4073 unsigned NumStackEntries =
Record[2];
4076 FpPragmaStack.clear();
4077 for (
unsigned I = 0; I < NumStackEntries; ++I) {
4078 FpPragmaStackEntry Entry;
4080 Entry.Location = ReadSourceLocation(F,
Record[Idx++]);
4081 Entry.PushLocation = ReadSourceLocation(F,
Record[Idx++]);
4082 FpPragmaStrings.push_back(ReadString(
Record, Idx));
4083 Entry.SlotLabel = FpPragmaStrings.back();
4084 FpPragmaStack.push_back(Entry);
4090 for (
unsigned I = 0, N =
Record.size(); I != N; )
4091 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F,
Record, I));
4097void ASTReader::ReadModuleOffsetMap(
ModuleFile &F)
const {
4112 assert(ImportedModuleVector.empty());
4114 while (
Data < DataEnd) {
4118 using namespace llvm::support;
4120 endian::readNext<uint8_t, llvm::endianness::little>(
Data));
4121 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(
Data);
4122 StringRef Name = StringRef((
const char*)
Data, Len);
4126 ? ModuleMgr.lookupByModuleName(Name)
4127 : ModuleMgr.lookupByFileName(Name));
4129 std::string Msg =
"refers to unknown module, cannot find ";
4130 Msg.append(std::string(Name));
4135 ImportedModuleVector.push_back(OM);
4137 uint32_t MacroIDOffset =
4138 endian::readNext<uint32_t, llvm::endianness::little>(
Data);
4139 uint32_t PreprocessedEntityIDOffset =
4140 endian::readNext<uint32_t, llvm::endianness::little>(
Data);
4141 uint32_t SubmoduleIDOffset =
4142 endian::readNext<uint32_t, llvm::endianness::little>(
Data);
4143 uint32_t SelectorIDOffset =
4144 endian::readNext<uint32_t, llvm::endianness::little>(
Data);
4146 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4147 RemapBuilder &Remap) {
4148 constexpr uint32_t
None = std::numeric_limits<uint32_t>::max();
4150 Remap.insert(std::make_pair(Offset,
4151 static_cast<int>(BaseOffset - Offset)));
4154 mapOffset(MacroIDOffset, OM->
BaseMacroID, MacroRemap);
4156 PreprocessedEntityRemap);
4165 unsigned ClientLoadCapabilities) {
4174 "MODULE_NAME should come before MODULE_MAP_FILE");
4175 if (PP.getPreprocessorOpts().ModulesCheckRelocated &&
4181 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4183 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4185 if (!
bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
4188 if (!canRecoverFromOutOfDate(F.
FileName, ClientLoadCapabilities)) {
4189 if (
auto ASTFE = M ? M->
getASTFile() : std::nullopt) {
4192 << ASTFE->getName();
4195 Diag(diag::err_imported_module_not_found)
4203 Diag(diag::note_imported_by_pch_module_not_found)
4210 assert(M && M->
Name == F.
ModuleName &&
"found module with different name");
4214 if (!StoredModMap || *StoredModMap != ModMap) {
4215 assert(ModMap &&
"found module is missing module map file");
4217 "top-level import should be verified");
4219 if (!canRecoverFromOutOfDate(F.
FileName, ClientLoadCapabilities))
4220 Diag(diag::err_imported_module_modmap_changed)
4227 for (
unsigned I = 0, N =
Record[Idx++]; I < N; ++I) {
4232 if (!canRecoverFromOutOfDate(F.
FileName, ClientLoadCapabilities))
4233 Error(
"could not find file '" +
Filename +
"' referenced by AST file");
4236 AdditionalStoredMaps.insert(*SF);
4241 if (
auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4245 if (!AdditionalStoredMaps.erase(ModMap)) {
4246 if (!canRecoverFromOutOfDate(F.
FileName, ClientLoadCapabilities))
4247 Diag(diag::err_module_different_modmap)
4257 if (!canRecoverFromOutOfDate(F.
FileName, ClientLoadCapabilities))
4258 Diag(diag::err_module_different_modmap)
4279 : Known->second.second;
4281 for (
ObjCMethodList *List = &Start; List; List = List->getNext()) {
4283 if (List->getMethod() == Method) {
4291 if (List->getNext())
4292 List->setMethod(List->getNext()->getMethod());
4294 List->setMethod(Method);
4300 for (
Decl *
D : Names) {
4304 if (wasHidden && SemaObj) {
4317 Stack.push_back(Mod);
4318 while (!Stack.empty()) {
4319 Mod = Stack.pop_back_val();
4321 if (NameVisibility <= Mod->NameVisibility) {
4337 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4338 if (Hidden != HiddenNamesMap.end()) {
4340 HiddenNamesMap.erase(Hidden);
4342 assert(!HiddenNamesMap.contains(Mod) &&
4343 "making names visible added hidden names");
4350 I = Exports.begin(),
E = Exports.end(); I !=
E; ++I) {
4352 if (
Visited.insert(Exported).second)
4353 Stack.push_back(Exported);
4368 getContext().mergeDefinitionIntoModule(
4371 PendingMergedDefinitionsToDeduplicate.insert(Def);
4380 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4381 !PP.getLangOpts().Modules)
4385 TriedLoadingGlobalIndex =
true;
4386 StringRef ModuleCachePath
4387 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4388 std::pair<GlobalModuleIndex *, llvm::Error>
Result =
4390 if (llvm::Error Err = std::move(
Result.second)) {
4392 consumeError(std::move(Err));
4396 GlobalIndex.reset(
Result.first);
4397 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4402 return PP.getLangOpts().Modules && UseGlobalIndex &&
4403 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4410 llvm::raw_fd_ostream OS(TimestampFilename, EC,
4411 llvm::sys::fs::OF_TextWithCRLF);
4414 OS <<
"Timestamp file\n";
4427 consumeError(MaybeEntry.takeError());
4430 llvm::BitstreamEntry Entry = MaybeEntry.get();
4432 switch (Entry.Kind) {
4433 case llvm::BitstreamEntry::Error:
4434 case llvm::BitstreamEntry::EndBlock:
4437 case llvm::BitstreamEntry::Record:
4443 consumeError(Skipped.takeError());
4447 case llvm::BitstreamEntry::SubBlock:
4448 if (Entry.ID == BlockID) {
4449 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4451 consumeError(std::move(Err));
4458 if (llvm::Error Err = Cursor.SkipBlock()) {
4460 consumeError(std::move(Err));
4469 unsigned ClientLoadCapabilities,
4471 llvm::TimeTraceScope scope(
"ReadAST",
FileName);
4475 CurrentDeserializingModuleKind,
Type);
4481 unsigned PreviousGeneration = 0;
4483 PreviousGeneration = incrementGeneration(*ContextObj);
4485 unsigned NumModules = ModuleMgr.size();
4490 ClientLoadCapabilities)) {
4491 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4495 GlobalIndex.reset();
4496 ModuleMgr.setGlobalIndex(
nullptr);
4500 if (NewLoadedModuleFile && !Loaded.empty())
4501 *NewLoadedModuleFile = Loaded.back().Mod;
4512 for (ImportedModule &M : Loaded) {
4514 llvm::TimeTraceScope Scope2(
"Read Loaded AST", F.
ModuleName);
4517 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4518 Error(std::move(Err));
4524 Error(diag::err_module_file_missing_top_level_submodule, F.
FileName);
4530 if (llvm::Error Err = ReadExtensionBlock(F)) {
4531 Error(std::move(Err));
4544 for (ImportedModule &M : Loaded) {
4560 if (!PP.getLangOpts().CPlusPlus) {
4567 auto It = PP.getIdentifierTable().find(Key);
4568 if (It == PP.getIdentifierTable().end())
4577 II = &PP.getIdentifierTable().getOwn(Key);
4588 SetIdentifierInfo(ID, II);
4595 for (
auto &
Id : PP.getIdentifierTable())
4596 Id.second->setOutOfDate(
true);
4599 for (
const auto &Sel : SelectorGeneration)
4600 SelectorOutOfDate[Sel.first] =
true;
4604 for (ImportedModule &M : Loaded) {
4607 ModuleMgr.moduleFileAccepted(&F);
4616 F.
ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4620 for (
unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4621 UnresolvedModuleRef &
Unresolved = UnresolvedModuleRefs[I];
4623 Module *ResolvedMod = getSubmodule(GlobalID);
4626 case UnresolvedModuleRef::Conflict:
4629 Conflict.
Other = ResolvedMod;
4631 Unresolved.Mod->Conflicts.push_back(Conflict);
4635 case UnresolvedModuleRef::Import:
4640 case UnresolvedModuleRef::Affecting:
4642 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
4645 case UnresolvedModuleRef::Export:
4652 UnresolvedModuleRefs.clear();
4659 InitializeContext();
4664 if (DeserializationListener)
4665 DeserializationListener->ReaderInitialized(
this);
4667 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
4682 for (
unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4683 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4684 ObjCClassesLoaded[I], PreviousGeneration);
4693 for (
unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4694 ImportedModule &M = Loaded[I];
4711 if (!Stream.canSkipToPos(4))
4712 return llvm::createStringError(std::errc::illegal_byte_sequence,
4713 "file too small to contain AST file magic");
4714 for (
unsigned C : {
'C',
'P',
'C',
'H'})
4717 return llvm::createStringError(
4718 std::errc::illegal_byte_sequence,
4719 "file doesn't start with AST file magic");
4721 return Res.takeError();
4722 return llvm::Error::success();
4737 llvm_unreachable(
"unknown module kind");
4741ASTReader::ReadASTCore(StringRef
FileName,
4746 off_t ExpectedSize, time_t ExpectedModTime,
4748 unsigned ClientLoadCapabilities) {
4750 std::string ErrorStr;
4752 = ModuleMgr.addModule(
FileName,
Type, ImportLoc, ImportedBy,
4753 getGeneration(), ExpectedSize, ExpectedModTime,
4757 switch (AddResult) {
4759 Diag(diag::remark_module_import)
4761 << (ImportedBy ? StringRef(ImportedBy->
ModuleName) : StringRef());
4771 if (ClientLoadCapabilities & ARR_Missing)
4775 Diag(diag::err_ast_file_not_found)
4783 if (ClientLoadCapabilities & ARR_OutOfDate)
4787 Diag(diag::err_ast_file_out_of_date)
4793 assert(M &&
"Missing module file");
4795 bool ShouldFinalizePCM =
false;
4796 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4797 auto &MC = getModuleManager().getModuleCache();
4798 if (ShouldFinalizePCM)
4804 BitstreamCursor &Stream = F.
Stream;
4805 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4806 F.SizeInBits = F.Buffer->getBufferSize() * 8;
4810 Diag(diag::err_ast_file_invalid)
4816 bool HaveReadControlBlock =
false;
4820 Error(MaybeEntry.takeError());
4823 llvm::BitstreamEntry Entry = MaybeEntry.get();
4825 switch (Entry.Kind) {
4826 case llvm::BitstreamEntry::Error:
4827 case llvm::BitstreamEntry::Record:
4828 case llvm::BitstreamEntry::EndBlock:
4829 Error(
"invalid record at top-level of AST file");
4832 case llvm::BitstreamEntry::SubBlock:
4838 HaveReadControlBlock =
true;
4839 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4847 F.ModuleName.empty()) {
4849 if (
Result != OutOfDate ||
4850 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4856 case Failure:
return Failure;
4857 case Missing:
return Missing;
4858 case OutOfDate:
return OutOfDate;
4860 case ConfigurationMismatch:
return ConfigurationMismatch;
4861 case HadErrors:
return HadErrors;
4866 if (!HaveReadControlBlock) {
4867 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4868 Diag(diag::err_ast_file_version_too_old)
4874 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4875 ShouldFinalizePCM =
true;
4879 if (llvm::Error Err = Stream.SkipBlock()) {
4880 Error(std::move(Err));
4887 llvm_unreachable(
"unexpected break; expected return");
4891ASTReader::readUnhashedControlBlock(
ModuleFile &F,
bool WasImportedBy,
4892 unsigned ClientLoadCapabilities) {
4894 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4895 bool AllowCompatibleConfigurationMismatch =
4897 bool DisableValidation = shouldDisableValidationForFile(F);
4899 ASTReadResult
Result = readUnhashedControlBlockImpl(
4901 AllowCompatibleConfigurationMismatch, Listener.get(),
4906 if (DisableValidation || WasImportedBy ||
4907 (AllowConfigurationMismatch &&
Result == ConfigurationMismatch))
4911 Error(
"malformed block record in AST file");
4934 if (getModuleManager().getModuleCache().isPCMFinal(F.
FileName)) {
4935 Diag(diag::warn_module_system_bit_conflict) << F.
FileName;
4945 unsigned ClientLoadCapabilities,
bool AllowCompatibleConfigurationMismatch,
4948 BitstreamCursor Stream(StreamData);
4953 consumeError(std::move(Err));
4968 consumeError(MaybeEntry.takeError());
4971 llvm::BitstreamEntry Entry = MaybeEntry.get();
4973 switch (Entry.Kind) {
4974 case llvm::BitstreamEntry::Error:
4975 case llvm::BitstreamEntry::SubBlock:
4978 case llvm::BitstreamEntry::EndBlock:
4981 case llvm::BitstreamEntry::Record:
4990 Stream.readRecord(Entry.ID,
Record, &Blob);
4991 if (!MaybeRecordType) {
5000 "Dummy AST file signature not backpatched in ASTWriter.");
5007 "Dummy AST block hash not backpatched in ASTWriter.");
5011 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
5012 if (Listener && ValidateDiagnosticOptions &&
5013 !AllowCompatibleConfigurationMismatch &&
5019 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
5020 if (Listener && !AllowCompatibleConfigurationMismatch &&
5021 ParseHeaderSearchPaths(
Record, Complain, *Listener))
5022 Result = ConfigurationMismatch;
5051 if (
Record.size() < 4)
return true;
5056 unsigned BlockNameLen =
Record[2];
5057 unsigned UserInfoLen =
Record[3];
5059 if (BlockNameLen + UserInfoLen > Blob.size())
return true;
5061 Metadata.
BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5062 Metadata.
UserInfo = std::string(Blob.data() + BlockNameLen,
5063 Blob.data() + BlockNameLen + UserInfoLen);
5067llvm::Error ASTReader::ReadExtensionBlock(
ModuleFile &F) {
5068 BitstreamCursor &Stream = F.
Stream;
5074 return MaybeEntry.takeError();
5075 llvm::BitstreamEntry Entry = MaybeEntry.get();
5077 switch (Entry.Kind) {
5078 case llvm::BitstreamEntry::SubBlock:
5079 if (llvm::Error Err = Stream.SkipBlock())
5082 case llvm::BitstreamEntry::EndBlock:
5083 return llvm::Error::success();
5084 case llvm::BitstreamEntry::Error:
5085 return llvm::createStringError(std::errc::illegal_byte_sequence,
5086 "malformed block record in AST file");
5087 case llvm::BitstreamEntry::Record:
5094 Stream.readRecord(Entry.ID,
Record, &Blob);
5096 return MaybeRecCode.takeError();
5097 switch (MaybeRecCode.get()) {
5101 return llvm::createStringError(
5102 std::errc::illegal_byte_sequence,
5103 "malformed EXTENSION_METADATA in AST file");
5106 auto Known = ModuleFileExtensions.find(Metadata.
BlockName);
5107 if (Known == ModuleFileExtensions.end())
break;
5110 if (
auto Reader = Known->second->createExtensionReader(Metadata, *
this,
5120 return llvm::Error::success();
5124 assert(ContextObj &&
"no context to initialize");
5128 if (DeserializationListener)
5129 DeserializationListener->DeclRead(
5139 if (!Context.CFConstantStringTypeDecl)
5146 Error(
"FILE type is NULL");
5150 if (!Context.FILEDecl) {
5156 Error(
"Invalid FILE type in AST file");
5165 QualType Jmp_bufType = GetType(Jmp_buf);
5166 if (Jmp_bufType.
isNull()) {
5167 Error(
"jmp_buf type is NULL");
5171 if (!Context.jmp_bufDecl) {
5177 Error(
"Invalid jmp_buf type in AST file");
5186 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5187 if (Sigjmp_bufType.
isNull()) {
5188 Error(
"sigjmp_buf type is NULL");
5192 if (!Context.sigjmp_bufDecl) {
5197 assert(Tag &&
"Invalid sigjmp_buf type in AST file");
5204 if (Context.ObjCIdRedefinitionType.
isNull())
5205 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5208 if (
TypeID ObjCClassRedef =
5210 if (Context.ObjCClassRedefinitionType.
isNull())
5211 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5214 if (
TypeID ObjCSelRedef =
5216 if (Context.ObjCSelRedefinitionType.
isNull())
5217 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5221 QualType Ucontext_tType = GetType(Ucontext_t);
5222 if (Ucontext_tType.
isNull()) {
5223 Error(
"ucontext_t type is NULL");
5227 if (!Context.ucontext_tDecl) {
5232 assert(Tag &&
"Invalid ucontext_t type in AST file");
5242 if (!CUDASpecialDeclRefs.empty()) {
5243 assert(CUDASpecialDeclRefs.size() == 1 &&
"More decl refs than expected!");
5245 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5250 for (
auto &Import : PendingImportedModules) {
5251 if (
Module *Imported = getSubmodule(Import.ID)) {
5254 if (Import.ImportLoc.isValid())
5255 PP.makeModuleVisible(Imported, Import.ImportLoc);
5262 PendingImportedModulesSema.append(PendingImportedModules);
5263 PendingImportedModules.clear();
5273 BitstreamCursor Stream(
PCH);
5276 consumeError(std::move(Err));
5288 Stream.advanceSkippingSubblocks();
5291 consumeError(MaybeEntry.takeError());
5294 llvm::BitstreamEntry Entry = MaybeEntry.get();
5296 if (Entry.Kind != llvm::BitstreamEntry::Record)
5304 consumeError(MaybeRecord.takeError());
5310 "Dummy AST file signature not backpatched in ASTWriter.");
5320 const std::string &ASTFileName,
FileManager &FileMgr,
5326 Diags.
Report(diag::err_fe_unable_to_read_pch_file)
5327 << ASTFileName << Buffer.getError().message();
5328 return std::string();
5332 BitstreamCursor Stream(PCHContainerRdr.
ExtractPCH(**Buffer));