27#include "llvm/Config/llvm-config.h"
57#include "llvm/Support/VCSRevision.h"
73#define HANDLE_EXTENSION(Ext) \
74 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
75#include "llvm/Support/Extension.def"
77#define DEBUG_TYPE "lto"
79Error LTO::setupOptimizationRemarks() {
86 return DiagFileOrErr.takeError();
88 DiagnosticOutputFile = std::move(*DiagFileOrErr);
95 if (!LinkerRemarkFunction) {
96 DummyModule = std::make_unique<Module>(
"remark_dummy",
RegularLTO.
Ctx);
114 cl::desc(
"Dump the SCCs in the ThinLTO index's callgraph"));
123 cl::desc(
"Enable global value internalization in LTO"));
127 cl::desc(
"Keep copies of symbols in LTO indexing"));
137 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
148 Hasher.
update(LLVM_VERSION_STRING);
150 Hasher.
update(LLVM_REVISION);
158 auto AddUnsigned = [&](
unsigned I) {
163 auto AddUint64 = [&](uint64_t
I) {
168 auto AddUint8 = [&](
const uint8_t I) {
193 AddUnsigned(
static_cast<int>(Conf.
CGOptLevel));
194 AddUnsigned(
static_cast<int>(Conf.
CGFileType));
202 AddUint8(Conf.
Dtlto);
205 auto ModHash = Index.getModuleHash(ModuleID);
210 std::vector<uint64_t> ExportsGUID;
211 ExportsGUID.reserve(ExportList.
size());
212 for (
const auto &VI : ExportList)
213 ExportsGUID.push_back(VI.getGUID());
217 for (
auto GUID : ExportsGUID)
222 auto Comp = [&](
const std::pair<StringRef, GlobalValue::GUID> &L,
223 const std::pair<StringRef, GlobalValue::GUID> &R) {
224 return std::make_pair(Index.getModule(L.first)->second, L.second) <
225 std::make_pair(Index.getModule(R.first)->second, R.second);
231 for (
const auto &[FromModule, GUID,
Type] : SortedImportList)
232 ++ModuleToNumImports[FromModule];
234 std::optional<StringRef> LastModule;
235 for (
const auto &[FromModule, GUID,
Type] : SortedImportList) {
236 if (LastModule != FromModule) {
240 LastModule = FromModule;
241 auto ModHash = Index.getModule(FromModule)->second;
243 AddUint64(ModuleToNumImports[FromModule]);
250 for (
auto &Entry : ResolvedODR) {
259 std::set<GlobalValue::GUID> UsedCfiDefs;
260 std::set<GlobalValue::GUID> UsedCfiDecls;
263 std::set<GlobalValue::GUID> UsedTypeIds;
266 if (CfiFunctionDefs.
contains(ValueGUID))
267 UsedCfiDefs.insert(ValueGUID);
268 if (CfiFunctionDecls.
contains(ValueGUID))
269 UsedCfiDecls.insert(ValueGUID);
274 AddUnsigned(GS->getVisibility());
275 AddUnsigned(GS->isLive());
276 AddUnsigned(GS->canAutoHide());
278 AddUnsigned(VI.isDSOLocal(Index.withDSOLocalPropagation()));
279 AddUsedCfiGlobal(VI.getGUID());
282 AddUnsigned(GVS->maybeReadOnly());
283 AddUnsigned(GVS->maybeWriteOnly());
286 for (
auto &TT : FS->type_tests())
287 UsedTypeIds.insert(TT);
288 for (
auto &TT : FS->type_test_assume_vcalls())
289 UsedTypeIds.insert(TT.GUID);
290 for (
auto &TT : FS->type_checked_load_vcalls())
291 UsedTypeIds.insert(TT.GUID);
292 for (
auto &TT : FS->type_test_assume_const_vcalls())
293 UsedTypeIds.insert(TT.VFunc.GUID);
294 for (
auto &TT : FS->type_checked_load_const_vcalls())
295 UsedTypeIds.insert(TT.VFunc.GUID);
296 for (
auto &ET : FS->calls()) {
297 AddUnsigned(ET.first.isDSOLocal(Index.withDSOLocalPropagation()));
298 AddUsedCfiGlobal(ET.first.getGUID());
306 SortedDefinedGlobals(DefinedGlobals.
begin(), DefinedGlobals.
end());
308 for (
auto &GS : SortedDefinedGlobals) {
314 AddUsedCfiGlobal(GS.first);
315 AddUsedThings(GS.second);
320 for (
const auto &[FromModule, GUID,
Type] : SortedImportList) {
326 AddUsedThings(AS->getBaseObject());
332 AddUnsigned(S.TTRes.TheKind);
333 AddUnsigned(S.TTRes.SizeM1BitWidth);
335 AddUint64(S.TTRes.AlignLog2);
336 AddUint64(S.TTRes.SizeM1);
337 AddUint64(S.TTRes.BitMask);
338 AddUint64(S.TTRes.InlineBits);
340 AddUint64(S.WPDRes.size());
341 for (
auto &WPD : S.WPDRes) {
342 AddUnsigned(WPD.first);
343 AddUnsigned(WPD.second.TheKind);
344 AddString(WPD.second.SingleImplName);
346 AddUint64(WPD.second.ResByArg.size());
347 for (
auto &ByArg : WPD.second.ResByArg) {
348 AddUint64(ByArg.first.size());
349 for (uint64_t Arg : ByArg.first)
351 AddUnsigned(ByArg.second.TheKind);
352 AddUint64(ByArg.second.Info);
353 AddUnsigned(ByArg.second.Byte);
354 AddUnsigned(ByArg.second.Bit);
361 auto TidIter = Index.typeIds().equal_range(TId);
363 AddTypeIdSummary(
I.second.first,
I.second.second);
366 AddUnsigned(UsedCfiDefs.size());
367 for (
auto &V : UsedCfiDefs)
370 AddUnsigned(UsedCfiDecls.size());
371 for (
auto &V : UsedCfiDecls)
377 Hasher.
update(FileOrErr.get()->getBuffer());
382 Hasher.
update(FileOrErr.get()->getBuffer());
413 C.VisibilityScheme ==
Config::ELF ? VI.getELFVisibility()
415 for (
auto &S : VI.getSummaryList()) {
430 if (isPrevailing(VI.getGUID(), S.get())) {
431 assert(!S->wasPromoted() &&
432 "promoted symbols used to be internal linkage and shouldn't have "
433 "a prevailing variant");
446 S->setCanAutoHide(VI.canAutoHide() &&
447 !GUIDPreservedSymbols.
count(VI.getGUID()));
450 Visibility = S->getVisibility();
459 !GlobalInvolvedWithAlias.
count(S.get()) && !ForceImportAll &&
467 S->setVisibility(Visibility);
469 if (S->linkage() != OriginalLinkage)
470 recordNewLinkage(S->modulePath(), VI.getGUID(), S->linkage());
474 for (
auto &S : VI.getSummaryList()) {
479 S->setVisibility(Visibility);
502 for (
auto &
I : Index)
503 for (
auto &S :
I.second.getSummaryList())
505 GlobalInvolvedWithAlias.
insert(&AS->getAliasee());
508 for (
auto &
I : Index)
510 GlobalInvolvedWithAlias, isPrevailing,
511 recordNewLinkage, GUIDPreservedSymbols);
523 const bool SingleExternallyVisibleCopy =
524 VI.getSummaryList().size() == 1 &&
527 bool NameRecorded =
false;
528 for (
auto &S : VI.getSummaryList()) {
531 if (isExported(S->modulePath(), VI)) {
537 if (ExternallyVisibleSymbolNamesPtr && !NameRecorded) {
539 if (ExternallyVisibleSymbolNamesPtr->
insert(VI.name()).second)
540 S->setNoRenameOnPromotion(
true);
603 if (SingleExternallyVisibleCopy && isPrevailing(VI.getGUID(), S.get()))
616 assert(!Index.withInternalizeAndPromote());
618 for (
auto &
I : Index)
621 ExternallyVisibleSymbolNamesPtr);
622 Index.setWithInternalizeAndPromote();
629 std::unique_ptr<InputFile> File(
new InputFile);
635 File->TargetTriple = FOrErr->TheReader.getTargetTriple();
636 File->SourceFileName = FOrErr->TheReader.getSourceFileName();
637 File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
638 File->DependentLibraries = FOrErr->TheReader.getDependentLibraries();
639 File->ComdatTable = FOrErr->TheReader.getComdatTable();
643 for (
unsigned I = 0;
I != FOrErr->Mods.size(); ++
I) {
644 size_t Begin = File->Symbols.size();
646 FOrErr->TheReader.module_symbols(
I))
649 if (Sym.isGlobal() && !Sym.isFormatSpecific())
650 File->Symbols.push_back(Sym);
651 File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
654 File->Mods = FOrErr->Mods;
655 File->Strtab = std::move(FOrErr->Strtab);
656 return std::move(File);
668 return Mods[0].getModuleIdentifier();
672 assert(Mods.size() == 1 &&
"Expect only one bitcode module");
700 Alloc = std::make_unique<BumpPtrAllocator>();
701 GlobalResolutionSymbolSaver = std::make_unique<llvm::StringSaver>(*Alloc);
710 LinkerRemarkFunction =
nullptr;
718 unsigned Partition,
bool InSummary,
721 auto *ResI = Res.
begin();
722 auto *ResE = Res.
end();
733 if (GlobalResolutionSymbolSaver && !GlobalResolutions->contains(SymbolName))
734 SymbolName = GlobalResolutionSymbolSaver->save(SymbolName);
736 auto &GlobalRes = (*GlobalResolutions)[SymbolName];
737 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
753 if ((GlobalRes.Prevailing || !GlobalRes.IRName.empty()) &&
754 GlobalRes.IRName != Sym.getIRName()) {
755 GlobalRes.Partition = GlobalResolution::External;
756 GlobalRes.VisibleOutsideSummary =
true;
760 assert(!GlobalRes.Prevailing &&
761 "Multiple prevailing defs are not allowed");
762 GlobalRes.Prevailing =
true;
763 GlobalRes.IRName = std::string(Sym.getIRName());
764 }
else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
771 GlobalRes.IRName = std::string(Sym.getIRName());
774 bool IsLibcall = Sym.isLibcall(
TLI, Libcalls);
782 (GlobalRes.Partition != GlobalResolution::Unknown &&
783 GlobalRes.Partition != Partition)) {
784 GlobalRes.Partition = GlobalResolution::External;
787 GlobalRes.Partition = Partition;
791 GlobalRes.VisibleOutsideSummary |=
798void LTO::releaseGlobalResolutionsMemory() {
800 GlobalResolutions.reset();
802 GlobalResolutionSymbolSaver.reset();
810 auto ResI = Res.
begin();
815 OS <<
"-r=" << Path <<
',' << Sym.getName() <<
',';
833 assert(!CalledGetMaxTasks);
839 InputFile *
Input = (*InputOrErr).get();
841 if (
Conf.ResolutionFile)
844 if (
RegularLTO.CombinedModule->getTargetTriple().empty()) {
846 RegularLTO.CombinedModule->setTargetTriple(InputTriple);
852 for (
unsigned I = 0;
I !=
Input->Mods.size(); ++
I) {
853 if (
auto Err = addModule(*
Input, InputRes,
I, Res).moveInto(Res))
863 "bitcode libfuncs were set twice; maybe accidentally clobbered?");
864 this->BitcodeLibFuncs.append(BitcodeLibFuncs.begin(), BitcodeLibFuncs.end());
875 if (EnableSplitLTOUnit) {
879 if (*EnableSplitLTOUnit != LTOInfo->EnableSplitLTOUnit)
882 EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
887 !LTOInfo->UnifiedLTO)
889 "unified LTO compilation must use "
890 "compatible bitcode modules (use -funified-lto)",
900 Input.IsThinLTO |= IsThinLTO;
902 auto ModSyms =
Input.module_symbols(ModI);
903 addModuleToGlobalRes(ModSyms, Res,
905 LTOInfo->HasSummary,
Triple(
Input.getTargetTriple()));
908 return addThinLTO(BM, ModSyms, Res);
911 auto ModOrErr = addRegularLTO(
Input, InputRes, BM, ModSyms, Res);
913 return ModOrErr.takeError();
914 Res = ModOrErr->second;
916 if (!LTOInfo->HasSummary) {
917 if (
Error Err = linkRegularLTO(std::move(ModOrErr->first),
943 std::set<const Comdat *> &NonPrevailingComdats) {
948 if (!NonPrevailingComdats.count(
C))
958 GO->setComdat(
nullptr);
965 std::pair<LTO::RegularLTOState::AddedModule, ArrayRef<SymbolResolution>>>
969 llvm::TimeTraceScope timeScope(
"LTO add regular LTO");
971 Expected<std::unique_ptr<Module>> MOrErr =
977 Mod.M = std::move(*MOrErr);
979 if (
Error Err =
M.materializeMetadata())
980 return std::move(Err);
986 if (NamedMDNode *CfiFunctionsMD =
M.getNamedMetadata(
"cfi.functions"))
987 M.eraseNamedMetadata(CfiFunctionsMD);
988 }
else if (NamedMDNode *AliasesMD =
M.getNamedMetadata(
"aliases")) {
991 DenseSet<StringRef> Prevailing;
992 for (
auto [
I, R] :
zip(
Input.symbols(), InputRes))
993 if (
R.Prevailing && !
I.getIRName().empty())
994 Prevailing.
insert(
I.getIRName());
995 std::vector<MDNode *> AliasGroups;
996 for (MDNode *AliasGroup : AliasesMD->operands()) {
997 std::vector<Metadata *> Aliases;
998 for (
Metadata *Alias : AliasGroup->operands()) {
1001 Aliases.push_back(Alias);
1003 if (Aliases.size() > 1)
1006 AliasesMD->clearOperands();
1007 for (MDNode *
G : AliasGroups)
1008 AliasesMD->addOperand(
G);
1013 ModuleSymbolTable SymTab;
1016 for (GlobalVariable &GV :
M.globals())
1017 if (GV.hasAppendingLinkage())
1018 Mod.Keep.push_back(&GV);
1020 DenseSet<GlobalObject *> AliasedGlobals;
1021 for (
auto &GA :
M.aliases())
1022 if (GlobalObject *GO = GA.getAliaseeObject())
1023 AliasedGlobals.
insert(GO);
1032 auto MsymI = SymTab.
symbols().begin(), MsymE = SymTab.
symbols().end();
1034 while (MsymI != MsymE) {
1044 std::set<const Comdat *> NonPrevailingComdats;
1045 SmallSet<StringRef, 2> NonPrevailingAsmSymbols;
1046 for (
const InputFile::Symbol &Sym : Syms) {
1056 if (Sym.isUndefined())
1058 Mod.Keep.push_back(GV);
1062 if (
R.LinkerRedefined)
1070 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
1071 GV->hasAvailableExternallyLinkage()) &&
1078 Mod.Keep.push_back(GV);
1083 if (GV->hasComdat() && GV->getComdat()->getName() == GV->getName())
1084 NonPrevailingComdats.insert(GV->getComdat());
1089 if (
R.FinalDefinitionInLinkageUnit) {
1090 GV->setDSOLocal(
true);
1091 if (GV->hasDLLImportStorageClass())
1093 DefaultStorageClass);
1095 }
else if (
auto *AS =
1099 NonPrevailingAsmSymbols.
insert(AS->first);
1107 if (Sym.isCommon()) {
1110 auto &CommonRes =
RegularLTO.Commons[std::string(Sym.getIRName())];
1111 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
1112 if (uint32_t SymAlignValue = Sym.getCommonAlignment()) {
1113 CommonRes.Alignment =
1114 std::max(
Align(SymAlignValue), CommonRes.Alignment);
1116 CommonRes.Prevailing |=
R.Prevailing;
1120 if (!NonPrevailingComdats.empty())
1121 for (GlobalValue &GV :
M.global_values())
1126 if (
M.hasModuleInlineAsm()) {
1127 std::string NewIA =
".lto_discard";
1128 if (!NonPrevailingAsmSymbols.
empty()) {
1131 M, [&](StringRef Name, StringRef Alias) {
1132 if (!NonPrevailingAsmSymbols.
count(Alias))
1133 NonPrevailingAsmSymbols.
erase(Name);
1135 NewIA +=
" " +
llvm::join(NonPrevailingAsmSymbols,
", ");
1138 M.prependModuleInlineAsm({NewIA,
M.getModuleInlineAsm().front().Props});
1142 return std::make_pair(std::move(
Mod), Res);
1145Error LTO::linkRegularLTO(RegularLTOState::AddedModule
Mod,
1146 bool LivenessFromIndex) {
1147 llvm::TimeTraceScope timeScope(
"LTO link regular LTO");
1148 std::vector<GlobalValue *>
Keep;
1149 for (GlobalValue *GV :
Mod.Keep) {
1150 if (LivenessFromIndex) {
1152 if (!
ThinLTO.CombinedIndex.isGUIDLive(GUID)) {
1154 if (DiagnosticOutputFile) {
1155 if (
Error Err =
F->materialize())
1157 auto R = OptimizationRemark(
DEBUG_TYPE,
"deadfunction",
F);
1158 R <<
ore::NV(
"Function",
F) <<
" not added to the combined module ";
1173 GlobalValue *CombinedGV =
1186Expected<ArrayRef<SymbolResolution>>
1189 llvm::TimeTraceScope timeScope(
"LTO add thin LTO");
1192 DenseSet<StringRef> Prevailing;
1193 for (
const InputFile::Symbol &Sym : Syms) {
1196 if (!Sym.getIRName().empty() &&
R.Prevailing)
1197 Prevailing.
insert(Sym.getIRName());
1201 StringMap<GlobalValue::GUID> IRSpecifiedGUIDs;
1204 [&](StringRef Name) { return (Prevailing.count(Name) > 0); },
1206 auto IT = IRSpecifiedGUIDs.insert({VI.name(), VI.getGUID()});
1216 auto GUIDIter = IRSpecifiedGUIDs.
find(Sym.getIRName());
1221 GUIDIter == IRSpecifiedGUIDs.
end()
1226 if (!Sym.getIRName().empty() &&
1227 (
R.Prevailing ||
R.FinalDefinitionInLinkageUnit)) {
1229 (*GlobalResolutions)[Sym.getName()].setGUID(GUID);
1230 ThinLTO.setPrevailingModuleForGUID(GUID, BMID);
1235 if (
R.LinkerRedefined)
1236 if (
auto *S = ThinLTO.CombinedIndex.findSummaryInModule(GUID, BMID))
1242 if (
R.FinalDefinitionInLinkageUnit) {
1243 if (
auto *S = ThinLTO.CombinedIndex.findSummaryInModule(GUID, BMID)) {
1244 S->setDSOLocal(
true);
1250 if (!ThinLTO.ModuleMap.insert({BMID, BM}).second)
1252 "Expected at most one ThinLTO module per bitcode file",
1255 if (!Conf.ThinLTOModulesToCompile.empty()) {
1256 if (!ThinLTO.ModulesToCompile)
1257 ThinLTO.ModulesToCompile = ModuleMapType();
1260 for (
const std::string &Name : Conf.ThinLTOModulesToCompile) {
1261 if (BMID.contains(Name)) {
1262 ThinLTO.ModulesToCompile->insert({BMID, BM});
1263 LLVM_DEBUG(
dbgs() <<
"[ThinLTO] Selecting " << BMID <<
" to compile\n");
1273 CalledGetMaxTasks =
true;
1274 auto ModuleCount =
ThinLTO.ModulesToCompile ?
ThinLTO.ModulesToCompile->size()
1276 return RegularLTO.ParallelCodeGenParallelismLevel + ModuleCount;
1281Error LTO::checkPartiallySplit() {
1291 Combined, Intrinsic::type_checked_load_relative);
1295 if ((TypeTestFunc && !TypeTestFunc->
use_empty()) ||
1296 (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->
use_empty()) ||
1297 (TypeCheckedLoadRelativeFunc &&
1298 !TypeCheckedLoadRelativeFunc->
use_empty()))
1300 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1306 for (
auto &S :
P.second.getSummaryList()) {
1310 if (!FS->type_test_assume_vcalls().empty() ||
1311 !FS->type_checked_load_vcalls().empty() ||
1312 !FS->type_test_assume_const_vcalls().empty() ||
1313 !FS->type_checked_load_const_vcalls().empty() ||
1314 !FS->type_tests().empty())
1316 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1323Error LTO::setupPassPlugins() {
1326 for (
const std::string &PluginFN :
Conf.PassPluginFilenames) {
1330 Loaded.push_back(std::make_unique<PassPlugin>(std::move(*Plugin)));
1335 for (std::unique_ptr<PassPlugin> &Plugin : Loaded) {
1337 PassPlugins.push_back(std::move(Plugin));
1339 Conf.LoadedPassPlugins.insert(
Conf.LoadedPassPlugins.begin(),
1340 FromFiles.
begin(), FromFiles.
end());
1342 Conf.PassPluginFilenames.clear();
1344 if (
Conf.PassPluginArgs.empty())
1347 for (
const PassPlugin *Plugin :
Conf.LoadedPassPlugins)
1349#define HANDLE_EXTENSION(Ext) Infos.push_back(get##Ext##PluginInfo());
1350#include "llvm/Support/Extension.def"
1359 if (
Error Err = setupPassPlugins())
1365 for (
auto &Res : *GlobalResolutions) {
1368 if (Res.second.IRName.
empty())
1373 if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
1374 GUIDPreservedSymbols.
insert(GUID);
1376 if (Res.second.ExportDynamic)
1377 DynamicExportSymbols.insert(GUID);
1379 GUIDPrevailingResolutions[GUID] =
1384 auto It = GUIDPrevailingResolutions.
find(
G);
1385 if (It == GUIDPrevailingResolutions.
end())
1390 ThinLTO.CombinedIndex, GUIDPreservedSymbols,
1391 isPrevailing,
Conf.OptLevel > 0);
1395 if (!StatsFileOrErr)
1396 return StatsFileOrErr.takeError();
1397 std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
1399 if (
Error Err = setupOptimizationRemarks())
1409 ThinLTO.CombinedIndex.setWithSupportsHotColdNew();
1411 Error Result = runRegularLTO(AddStream);
1415 Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
1434 linkRegularLTO(std::move(M),
true))
1447 if (
Error Err = checkPartiallySplit())
1454 if (!
I.second.Prevailing)
1466 auto *GV =
new GlobalVariable(*
RegularLTO.CombinedModule, Ty,
false,
1469 GV->setAlignment(
I.second.Alignment);
1479 bool WholeProgramVisibilityEnabledInLTO =
1480 Conf.HasWholeProgramVisibility &&
1483 (!
Conf.ValidateAllVtablesHaveTypeInfos ||
Conf.AllVtablesHaveTypeInfos);
1487 auto IsVisibleToRegularObj = [&](StringRef
name) {
1488 auto It = GlobalResolutions->find(
name);
1489 return (It == GlobalResolutions->end() ||
1490 It->second.VisibleOutsideSummary || !It->second.Prevailing);
1496 *
RegularLTO.CombinedModule, WholeProgramVisibilityEnabledInLTO,
1497 DynamicExportSymbols,
Conf.ValidateAllVtablesHaveTypeInfos,
1498 IsVisibleToRegularObj);
1500 WholeProgramVisibilityEnabledInLTO);
1502 if (
Conf.PreOptModuleHook &&
1506 if (!
Conf.CodeGenOnly) {
1507 for (
const auto &R : *GlobalResolutions) {
1509 RegularLTO.CombinedModule->getNamedValue(
R.second.IRName);
1510 if (!
R.second.isPrevailingIRSymbol())
1512 if (
R.second.Partition != 0 &&
1513 R.second.Partition != GlobalResolution::External)
1541 if (
Conf.PostInternalizeModuleHook &&
1546 if (!
RegularLTO.EmptyCombinedModule ||
Conf.AlwaysEmitRegularLTOObj) {
1566 return LibcallSymbols;
1571 auto TLII = std::make_unique<TargetLibraryInfoImpl>(TT);
1574 LibFuncSymbols.
reserve(LibFunc::NumLibFuncs);
1575 for (
unsigned I = LibFunc::Begin_LibFunc;
I != LibFunc::End_LibFunc; ++
I) {
1576 LibFunc
F =
static_cast<LibFunc
>(
I);
1580 return LibFuncSymbols;
1586 return emitFiles(ImportList, Task, ModulePath, NewModulePath,
1587 NewModulePath +
".thinlto.bc");
1599 ImportList, ModuleToSummariesForIndex,
1600 DeclarationSummaries);
1603 std::unique_ptr<raw_pwrite_stream> OS;
1604 if (
Conf.GetSummaryIndexOutputStream) {
1605 OS =
Conf.GetSummaryIndexOutputStream(Task);
1606 assert(OS &&
"GetSummaryIndexOutputStream returned null");
1608 auto FileOS = std::make_unique<raw_fd_ostream>(SummaryPath, EC,
1612 OS = std::move(FileOS);
1616 &DeclarationSummaries);
1619 if (
Conf.GetImportsListOutputArray) {
1620 std::vector<std::string> &ImportsListRef =
1621 Conf.GetImportsListOutputArray(Task);
1623 ModulePath, ModuleToSummariesForIndex,
1624 [&](
StringRef M) { ImportsListRef.push_back(M.str()); });
1627 ModuleToSummariesForIndex))
1640 bool ShouldEmitIndexFiles;
1649 OnWrite, ShouldEmitImportsFiles, ThinLTOParallelism),
1650 ShouldEmitIndexFiles(ShouldEmitIndexFiles) {
1652 CfiFunctionDefs.
insert_range(Defs.getExportedThinLTOGUIDs());
1654 CfiFunctionDecls.
insert_range(Decls.getExportedThinLTOGUIDs());
1660class InProcessThinBackend :
public CGThinBackend {
1669 InProcessThinBackend(
1674 bool ShouldEmitIndexFiles,
bool ShouldEmitImportsFiles,
1676 : CGThinBackend(Conf, CombinedIndex, ModuleToDefinedGVSummaries, OnWrite,
1677 ShouldEmitIndexFiles, ShouldEmitImportsFiles,
1678 ThinLTOParallelism),
1680 BitcodeLibFuncs(BitcodeLibFuncs) {}
1682 virtual Error runThinLTOBackendThread(
1683 AddStreamFn AddStream, FileCache Cache,
unsigned Task, BitcodeModule BM,
1684 ModuleSummaryIndex &CombinedIndex,
1685 const FunctionImporter::ImportMapTy &ImportList,
1687 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1689 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1691 llvm::TimeTraceScope timeScope(
"Run ThinLTO backend thread (in-process)",
1693 auto RunThinBackend = [&](
AddStreamFn AddStream) {
1694 LTOLLVMContext BackendContext(Conf);
1695 Expected<std::unique_ptr<Module>> MOrErr = BM.
parseModule(BackendContext);
1699 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
1700 ImportList, DefinedGlobals, &ModuleMap,
1703 if (ShouldEmitIndexFiles) {
1704 if (
auto E = emitFiles(ImportList, Task, ModuleID, ModuleID.str()))
1710 [](uint32_t
V) { return V == 0; }))
1713 return RunThinBackend(AddStream);
1717 Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1718 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1719 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task,
Key, ModuleID);
1722 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1724 return RunThinBackend(CacheAddStream);
1730 unsigned Task, BitcodeModule BM,
1731 const FunctionImporter::ImportMapTy &ImportList,
1733 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1734 MapVector<StringRef, BitcodeModule> &ModuleMap)
override {
1736 assert(ModuleToDefinedGVSummaries.
count(ModulePath));
1738 ModuleToDefinedGVSummaries.
find(ModulePath)->second;
1739 BackendThreadPool.async(
1740 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1741 const FunctionImporter::ImportMapTy &ImportList,
1743 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1746 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1750 Error E = runThinLTOBackendThread(
1751 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1752 ResolvedODR, DefinedGlobals, ModuleMap);
1754 std::unique_lock<std::mutex>
L(ErrMu);
1763 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
1764 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
1767 OnWrite(std::string(ModulePath));
1777class FirstRoundThinBackend :
public InProcessThinBackend {
1782 FirstRoundThinBackend(
1783 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1784 ThreadPoolStrategy ThinLTOParallelism,
1785 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1789 : InProcessThinBackend(Conf, CombinedIndex, ThinLTOParallelism,
1790 ModuleToDefinedGVSummaries, std::
move(CGAddStream),
1791 std::
move(CGCache), nullptr,
1793 false, BitcodeLibFuncs),
1794 IRAddStream(std::
move(IRAddStream)), IRCache(std::
move(IRCache)) {}
1796 Error runThinLTOBackendThread(
1797 AddStreamFn CGAddStream, FileCache CGCache,
unsigned Task,
1798 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1799 const FunctionImporter::ImportMapTy &ImportList,
1801 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1803 MapVector<StringRef, BitcodeModule> &ModuleMap)
override {
1805 llvm::TimeTraceScope timeScope(
"Run ThinLTO backend thread (first round)",
1807 auto RunThinBackend = [&](
AddStreamFn CGAddStream,
1809 LTOLLVMContext BackendContext(Conf);
1810 Expected<std::unique_ptr<Module>> MOrErr = BM.
parseModule(BackendContext);
1814 return thinBackend(Conf, Task, CGAddStream, **MOrErr, CombinedIndex,
1815 ImportList, DefinedGlobals, &ModuleMap,
1821 if (ShouldEmitIndexFiles) {
1822 if (
auto E = emitFiles(ImportList, Task, ModuleID, ModuleID.str()))
1827 "Both caches for CG and IR should have matching availability");
1830 [](uint32_t
V) { return V == 0; }))
1833 return RunThinBackend(CGAddStream, IRAddStream);
1837 Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1838 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1839 Expected<AddStreamFn> CacheCGAddStreamOrErr =
1840 CGCache(Task, CGKey, ModuleID);
1843 AddStreamFn &CacheCGAddStream = *CacheCGAddStreamOrErr;
1847 Expected<AddStreamFn> CacheIRAddStreamOrErr =
1848 IRCache(Task, IRKey, ModuleID);
1851 AddStreamFn &CacheIRAddStream = *CacheIRAddStreamOrErr;
1857 if (CacheCGAddStream || CacheIRAddStream) {
1860 return RunThinBackend(CacheCGAddStream ? CacheCGAddStream : CGAddStream,
1861 CacheIRAddStream ? CacheIRAddStream : IRAddStream);
1873class SecondRoundThinBackend :
public InProcessThinBackend {
1874 std::unique_ptr<SmallVector<StringRef>> IRFiles;
1878 SecondRoundThinBackend(
1879 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1880 ThreadPoolStrategy ThinLTOParallelism,
1881 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1886 : InProcessThinBackend(Conf, CombinedIndex, ThinLTOParallelism,
1887 ModuleToDefinedGVSummaries, std::
move(AddStream),
1891 false, BitcodeLibFuncs),
1892 IRFiles(std::
move(IRFiles)), CombinedCGDataHash(CombinedCGDataHash) {}
1894 Error runThinLTOBackendThread(
1895 AddStreamFn AddStream, FileCache Cache,
unsigned Task, BitcodeModule BM,
1896 ModuleSummaryIndex &CombinedIndex,
1897 const FunctionImporter::ImportMapTy &ImportList,
1899 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1901 MapVector<StringRef, BitcodeModule> &ModuleMap)
override {
1903 llvm::TimeTraceScope timeScope(
"Run ThinLTO backend thread (second round)",
1905 auto RunThinBackend = [&](
AddStreamFn AddStream) {
1906 LTOLLVMContext BackendContext(Conf);
1907 std::unique_ptr<Module> LoadedModule =
1910 return thinBackend(Conf, Task, AddStream, *LoadedModule, CombinedIndex,
1911 ImportList, DefinedGlobals, &ModuleMap,
1912 true, BitcodeLibFuncs);
1916 [](uint32_t
V) { return V == 0; }))
1919 return RunThinBackend(AddStream);
1924 Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1925 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1927 std::to_string(CombinedCGDataHash));
1928 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task,
Key, ModuleID);
1931 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1933 if (CacheAddStream) {
1936 return RunThinBackend(CacheAddStream);
1946 bool ShouldEmitIndexFiles,
1947 bool ShouldEmitImportsFiles) {
1953 return std::make_unique<InProcessThinBackend>(
1954 Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
1955 AddStream, Cache, OnWrite, ShouldEmitIndexFiles,
1956 ShouldEmitImportsFiles, BitcodeLibFuncs);
1982 return std::string(Path);
1986 if (!ParentPath.
empty()) {
1989 llvm::errs() <<
"warning: could not create directory '" << ParentPath
1990 <<
"': " << EC.message() <<
'\n';
1992 return std::string(NewPath);
1997 std::string OldPrefix, NewPrefix, NativeObjectPrefix;
2003 WriteIndexesThinBackend(
2007 std::string OldPrefix, std::string NewPrefix,
2008 std::string NativeObjectPrefix,
bool ShouldEmitImportsFiles,
2011 OnWrite, ShouldEmitImportsFiles, ThinLTOParallelism),
2012 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
2013 NativeObjectPrefix(NativeObjectPrefix),
2014 LinkedObjectsFile(LinkedObjectsFile) {
2015 auto Defs = CombinedIndex.
cfiFunctionDefs().getExportedThinLTOGUIDs();
2016 CfiFunctionDefs.
insert(Defs.begin(), Defs.end());
2018 CfiFunctionDecls.
insert(Decls.begin(), Decls.end());
2025 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
2033 if (LinkedObjectsFile) {
2034 std::string ObjectPrefix =
2035 NativeObjectPrefix.empty() ? NewPrefix : NativeObjectPrefix;
2036 std::string LinkedObjectsFilePath =
2038 *LinkedObjectsFile << LinkedObjectsFilePath <<
'\n';
2041 BackendThreadPool.async(
2042 [
this](
unsigned Task,
const StringRef ModulePath,
2043 const FunctionImporter::ImportMapTy &ImportList,
2045 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
2047 const std::string &OldPrefix,
const std::string &NewPrefix) {
2048 std::string NewModulePath =
2050 auto E = emitFiles(ImportList, Task, ModulePath, NewModulePath);
2052 std::unique_lock<std::mutex>
L(ErrMu);
2058 assert(ModuleToDefinedGVSummaries.
count(ModulePath));
2060 ModuleToDefinedGVSummaries.
find(ModulePath)->second;
2066 Conf, CombinedIndex, ModulePath, ImportList, ExportList,
2067 ResolvedODR, DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
2070 Task, ModulePath, ImportList, ExportList, ResolvedODR, OldPrefix,
2074 OnWrite(std::string(ModulePath));
2078 bool isSensitiveToInputOrder()
override {
2088 std::string NewPrefix, std::string NativeObjectPrefix,
2096 return std::make_unique<WriteIndexesThinBackend>(
2097 Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2098 OldPrefix, NewPrefix, NativeObjectPrefix, ShouldEmitImportsFiles,
2099 LinkedObjectsFile, OnWrite);
2118 llvm::errs() <<
"warning: [ThinLTO] No module compiled\n";
2122 if (
Conf.CombinedIndexHook &&
2123 !
Conf.CombinedIndexHook(
ThinLTO.CombinedIndex, GUIDPreservedSymbols))
2128 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(
2130 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
2131 ModuleToDefinedGVSummaries);
2140 if (!ModuleToDefinedGVSummaries.
count(
Mod.first))
2143 FunctionImporter::ImportListsTy ImportLists(
ThinLTO.ModuleMap.size());
2144 DenseMap<StringRef, FunctionImporter::ExportSetTy> ExportLists(
2146 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
2151 const cl::LibraryOptionsContext &LibraryOptions =
2153 std::set<GlobalValue::GUID> ExportedGUIDs;
2155 bool WholeProgramVisibilityEnabledInLTO =
2156 Conf.HasWholeProgramVisibility &&
2159 (!
Conf.ValidateAllVtablesHaveTypeInfos ||
Conf.AllVtablesHaveTypeInfos);
2161 WholeProgramVisibilityEnabledInLTO))
2162 ThinLTO.CombinedIndex.setWithWholeProgramVisibility();
2167 DenseSet<GlobalValue::GUID> VisibleToRegularObjSymbols;
2168 if (WholeProgramVisibilityEnabledInLTO &&
2169 Conf.ValidateAllVtablesHaveTypeInfos) {
2172 auto IsVisibleToRegularObj = [&](StringRef
name) {
2173 auto It = GlobalResolutions->find(
name);
2174 return (It == GlobalResolutions->end() ||
2175 It->second.VisibleOutsideSummary || !It->second.Prevailing);
2179 VisibleToRegularObjSymbols,
2180 IsVisibleToRegularObj);
2186 LibraryOptions,
ThinLTO.CombinedIndex, WholeProgramVisibilityEnabledInLTO,
2187 DynamicExportSymbols, VisibleToRegularObjSymbols);
2192 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
2193 DenseSet<StringRef> ExternallyVisibleSymbolNames;
2199 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr =
2201 ? &ExternallyVisibleSymbolNames
2204 ExportedGUIDs, LocalWPDTargetsMap,
2205 ExternallyVisibleSymbolNamesPtr);
2208 return ThinLTO.isPrevailingModuleForGUID(GUID, S->modulePath());
2211 MemProfContextDisambiguation ContextDisambiguation;
2212 ContextDisambiguation.
run(
2214 [&](StringRef
PassName, StringRef RemarkName,
const Twine &
Msg) {
2215 auto R = OptimizationRemark(PassName.data(), RemarkName,
2216 LinkerRemarkFunction);
2226 for (
auto &Res : *GlobalResolutions) {
2229 if (Res.second.Partition != GlobalResolution::External ||
2230 !Res.second.isPrevailingIRSymbol())
2232 auto GUID = Res.second.getGUID();
2234 if (
ThinLTO.CombinedIndex.isGUIDLive(GUID))
2235 ExportedGUIDs.insert(GUID);
2242 releaseGlobalResolutionsMemory();
2244 if (
Conf.OptLevel > 0)
2246 ModuleToDefinedGVSummaries, isPrevailing,
2247 ImportLists, ExportLists);
2251 auto Defs =
ThinLTO.CombinedIndex.cfiFunctionDefs().getExportedThinLTOGUIDs();
2252 ExportedGUIDs.insert(Defs.begin(), Defs.end());
2254 ThinLTO.CombinedIndex.cfiFunctionDecls().getExportedThinLTOGUIDs();
2255 ExportedGUIDs.insert(Decls.begin(), Decls.end());
2257 auto isExported = [&](StringRef ModuleIdentifier, ValueInfo
VI) {
2258 const auto &ExportList = ExportLists.
find(ModuleIdentifier);
2259 return (ExportList != ExportLists.end() && ExportList->second.
count(VI)) ||
2260 ExportedGUIDs.count(
VI.getGUID());
2266 LocalWPDTargetsMap, ExternallyVisibleSymbolNamesPtr);
2268 if (ExternallyVisibleSymbolNamesPtr) {
2271 for (
auto &
I :
ThinLTO.CombinedIndex) {
2272 ValueInfo
VI =
ThinLTO.CombinedIndex.getValueInfo(
I);
2273 for (
const auto &Summary :
VI.getSummaryList()) {
2274 const GlobalValueSummary *
Base =
Summary->getBaseObject();
2278 ExternallyVisibleSymbolNamesPtr->
insert(
VI.name());
2286 ExternallyVisibleSymbolNamesPtr);
2288 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
2291 ResolvedODR[ModuleIdentifier][
GUID] = NewLinkage;
2294 isPrevailing, recordNewLinkage,
2295 GUIDPreservedSymbols);
2305 TimeTraceScopeExit.release();
2310 auto RunBackends = [&](ThinBackendProc *BackendProcess) ->
Error {
2311 auto ProcessOneModule = [&](
int I) ->
Error {
2315 return BackendProcess->start(
2317 ImportLists[
Mod.first], ExportLists[
Mod.first],
2321 BackendProcess->setup(ModuleMap.
size(),
2323 RegularLTO.CombinedModule->getTargetTriple());
2325 if (BackendProcess->getThreadCount() == 1 ||
2326 BackendProcess->isSensitiveToInputOrder()) {
2332 for (
int I = 0,
E = ModuleMap.
size();
I !=
E; ++
I)
2333 if (
Error E = ProcessOneModule(
I))
2340 std::vector<BitcodeModule *> ModulesVec;
2341 ModulesVec.reserve(ModuleMap.
size());
2342 for (
auto &
Mod : ModuleMap)
2343 ModulesVec.push_back(&
Mod.second);
2345 if (
Error E = ProcessOneModule(
I))
2348 return BackendProcess->wait();
2352 std::unique_ptr<ThinBackendProc> BackendProc =
2354 AddStream, Cache, BitcodeLibFuncs);
2355 return RunBackends(BackendProc.get());
2363 LLVM_DEBUG(
dbgs() <<
"[TwoRounds] Initializing ThinLTO two-codegen rounds\n");
2366 auto Parallelism =
ThinLTO.Backend.getParallelism();
2369 cgdata::StreamCacheData CG(MaxTasks, Cache,
"CG"),
IR(MaxTasks, Cache,
"IR");
2374 LLVM_DEBUG(
dbgs() <<
"[TwoRounds] Running the first round of codegen\n");
2375 auto FirstRoundLTO = std::make_unique<FirstRoundThinBackend>(
2376 Conf,
ThinLTO.CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2377 CG.AddStream, CG.Cache, BitcodeLibFuncs,
IR.AddStream,
IR.Cache);
2378 if (
Error E = RunBackends(FirstRoundLTO.get()))
2383 RegularLTO.Ctx.getLibraryOptions(), *CG.getResult());
2384 if (
Error E = CombinedHashOrErr.takeError())
2386 auto CombinedHash = *CombinedHashOrErr;
2387 LLVM_DEBUG(
dbgs() <<
"[TwoRounds] CGData hash: " << CombinedHash <<
"\n");
2391 LLVM_DEBUG(
dbgs() <<
"[TwoRounds] Running the second round of codegen\n");
2392 auto SecondRoundLTO = std::make_unique<SecondRoundThinBackend>(
2393 Conf,
ThinLTO.CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2394 AddStream, Cache, BitcodeLibFuncs,
IR.getResult(), CombinedHash);
2395 return RunBackends(SecondRoundLTO.get());
2413 if (
Error E = ResultOrErr.takeError())
2414 return std::move(E);
2417 (*ResultOrErr)->keep();
2425 if (StatsFilename.
empty())
2436 return std::move(StatsFile);
2444 std::vector<int> ModulesOrdering(Seq.begin(), Seq.end());
2445 llvm::sort(ModulesOrdering, [&](
int LeftIndex,
int RightIndex) {
2446 auto LSize = R[LeftIndex]->getBuffer().size();
2447 auto RSize = R[RightIndex]->getBuffer().size();
2448 return LSize > RSize;
2450 return ModulesOrdering;
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static void writeToResolutionFile(raw_ostream &OS, InputFile *Input, ArrayRef< SymbolResolution > Res)
static void handleNonPrevailingComdat(GlobalValue &GV, std::set< const Comdat * > &NonPrevailingComdats)
static void thinLTOInternalizeAndPromoteGUID(ValueInfo VI, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr)
static cl::opt< bool > DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(false), cl::Hidden, cl::desc("Dump the SCCs in the ThinLTO index's callgraph"))
static void thinLTOResolvePrevailingGUID(const Config &C, bool ForceImportAll, ValueInfo VI, DenseSet< GlobalValueSummary * > &GlobalInvolvedWithAlias, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
Legalize the Machine IR a function s Machine IR
static constexpr StringLiteral Filename
Provides a library for accessing information about this process and other processes on the operating ...
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
static const char PassName[]
Represent a constant reference to an array (0 or more elements consecutively in memory),...
bool empty() const
Check if the array is empty.
const T & consume_front()
consume_front() - Returns the first element and drops it from ArrayRef.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Represents a module in a bitcode file.
StringRef getModuleIdentifier() const
LLVM_ABI Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
LLVM_ABI Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(StringRef)> IsPrevailing=nullptr, std::function< void(ValueInfo)> OnValueInfo=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks={})
Read the bitcode module and prepare for lazy deserialization of function bodies.
auto getExportedThinLTOGUIDs() const
get the set of GUIDs that should also be exported because they are the GUIDs of the cfi functions enc...
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
A parsed version of the target data layout string in and methods for querying it.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Implements a dense probed hash-table based set.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
The map maintains the list of imports.
static LLVM_ABI bool forceImportAll(const cl::LibraryOptionsContext &C)
DenseSet< ValueInfo > ExportSetTy
The set contains an entry for every global value that the module exports.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Function and variable summary information to aid decisions and implementation of importing.
static bool isAppendingLinkage(LinkageTypes Linkage)
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
static bool isExternalWeakLinkage(LinkageTypes Linkage)
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
bool hasLocalLinkage() const
LLVM_ABI GUID getGUIDOrFallback() const
Return the GUID for this value if it has been assigned, otherwise fall back to computing it based on ...
LLVM_ABI const Comdat * getComdat() const
static bool isLinkOnceLinkage(LinkageTypes Linkage)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
static bool isExternalLinkage(LinkageTypes Linkage)
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
static LinkageTypes getWeakLinkage(bool ODR)
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
bool hasAppendingLinkage() const
bool hasAvailableExternallyLinkage() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AvailableExternallyLinkage
Available for inspection, not emission.
DLLStorageClassTypes getDLLStorageClass() const
static bool isLinkOnceODRLinkage(LinkageTypes Linkage)
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
This is an important class for using LLVM in a threaded context.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
This class implements a map that also provides access to all stored values in a deterministic order.
static LLVM_ABI bool isEnabled(const cl::LibraryOptionsContext &C)
Return -memprof-context-disambiguation.
static LLVM_ABI bool supportsHotColdNew(const cl::LibraryOptionsContext &C)
Return -supports-hot-cold-new.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Class to hold module path string table and global value map, and encapsulate methods for operating on...
CfiFunctionIndex & cfiFunctionDecls()
void setPartiallySplitLTOUnits()
void releaseTemporaryMemory()
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
bool partiallySplitLTOUnits() const
const StringMap< ModuleHash > & modulePaths() const
Table of modules, containing module hash and id.
CfiFunctionIndex & cfiFunctionDefs()
LLVM_ABI void addModule(Module *M)
static LLVM_ABI void CollectAsmSymvers(const Module &M, function_ref< void(StringRef, StringRef)> AsmSymver)
Parse inline ASM and collect the symvers directives that are defined in the current module.
PointerUnion< GlobalValue *, AsmSymbol * > Symbol
LLVM_ABI uint32_t getSymbolFlags(Symbol S) const
ArrayRef< Symbol > symbols() const
A Module instance is used to store all the information related to an LLVM module.
const PassPluginLibraryInfo & getInfo() const
static LLVM_ABI Expected< PassPlugin > load(StringRef Filename)
Attempts to load a pass plugin from a given file.
A class that wrap the SHA1 algorithm.
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
LLVM_ABI std::array< uint8_t, 20 > result()
Return the current raw 160-bits SHA1 for the digested data since the last call to init().
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
StringRef str() const
Explicit conversion to StringRef.
void reserve(size_type N)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
iterator find(StringRef Key)
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
StringRef save(const char *S)
Implementation of the target library information.
Provides information about what library functions are available for the current target.
MCTargetOptions MCOptions
Machine level options.
unsigned FunctionSections
Emit functions into separate sections.
unsigned DataSections
Emit data into separate sections.
This tells how a thread pool will be used.
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
Triple - Helper class for working with autoconf configuration names.
bool isArm64e() const
Tests whether the target is the Apple "arm64e" AArch64 subarch.
ArchType getArch() const
Get the parsed architecture type of this triple.
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, DriverKit, XROS, or bridgeOS).
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
void insert_range(Range &&R)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
iterator find(const_arg_type_t< ValueT > V)
An efficient, type-erasing, non-owning reference to a callable.
Ephemeral symbols produced by Reader::symbols() and Reader::module_symbols().
LTO(Config Conf, ThinBackend Backend={}, unsigned ParallelCodeGenParallelismLevel=1, LTOKind LTOMode=LTOK_Default)
Create an LTO object.
Error add(std::unique_ptr< InputFile > Obj, ArrayRef< SymbolResolution > Res)
Add an input file to the LTO link, using the provided symbol resolutions.
struct llvm::lto::LTO::RegularLTOState RegularLTO
static SmallVector< const char * > getRuntimeLibcallSymbols(const Triple &TT)
Static method that returns a list of libcall symbols that can be generated by LTO but might not be vi...
virtual Expected< std::shared_ptr< lto::InputFile > > addInput(std::unique_ptr< lto::InputFile > InputPtr)
void setBitcodeLibFuncs(ArrayRef< StringRef > BitcodeLibFuncs)
Set the list of functions implemented in bitcode that were not extracted from an archive.
LTOKind
Unified LTO modes.
@ LTOK_UnifiedRegular
Regular LTO, with Unified LTO enabled.
@ LTOK_Default
Any LTO mode without Unified LTO. The default mode.
@ LTOK_UnifiedThin
ThinLTO, with Unified LTO enabled.
void emitRemark(OptimizationRemark &Remark)
Helper to emit an optimization remark during the LTO link when outside of the standard optimization p...
struct llvm::lto::LTO::ThinLTOState ThinLTO
unsigned getMaxTasks() const
Returns an upper bound on the number of tasks that the client may expect.
virtual Error run(AddStreamFn AddStream, FileCache Cache={})
Runs the LTO pipeline.
static SmallVector< StringRef > getLibFuncSymbols(const Triple &TT, llvm::StringSaver &Saver)
Static method that returns a list of library function symbols that can be generated by LTO but might ...
This class defines the interface to the ThinLTO backend.
bool ShouldEmitImportsFiles
const DenseMap< StringRef, GVSummaryMapTy > & ModuleToDefinedGVSummaries
ModuleSummaryIndex & CombinedIndex
LLVM_ABI Error emitFiles(const FunctionImporter::ImportMapTy &ImportList, unsigned Task, StringRef ModulePath, const std::string &NewModulePath) const
A raw_ostream that writes to a file descriptor.
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
static auto libcall_impls()
LLVM_ABI bool thinLTOTwoRounds(const cl::LibraryOptionsContext &LibraryOptions)
Returns whether ThinLTO runs two rounds of code generation (-codegen-data-thinlto-two-rounds).
LLVM_ABI Expected< stable_hash > mergeCodeGenData(const cl::LibraryOptionsContext &LibraryOptions, ArrayRef< StringRef > ObjectFiles)
Merge the codegen data from the scratch objects ObjectFiles from the first codegen round.
LLVM_ABI std::unique_ptr< Module > loadModuleForTwoRounds(BitcodeModule &OrigModule, unsigned Task, LLVMContext &Context, ArrayRef< StringRef > IRFiles)
Load the optimized bitcode module for the second codegen round.
initializer< Ty > init(const Ty &Val)
LLVM_ABI ThinBackend createInProcessThinBackend(ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite=nullptr, bool ShouldEmitIndexFiles=false, bool ShouldEmitImportsFiles=false)
This ThinBackend runs the individual backend jobs in-process.
LLVM_ABI std::string getThinLTOOutputFile(StringRef Path, StringRef OldPrefix, StringRef NewPrefix)
Given the original Path to an output file, replace any path prefix matching OldPrefix with NewPrefix.
LLVM_ABI Error thinBackend(const Config &C, unsigned Task, AddStreamFn AddStream, Module &M, const ModuleSummaryIndex &CombinedIndex, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector< StringRef, BitcodeModule > *ModuleMap, bool CodeGenOnly, ArrayRef< StringRef > BitcodeLibFuncs, AddStreamFn IRAddStream=nullptr, const std::vector< uint8_t > &CmdArgs=std::vector< uint8_t >())
Runs a ThinLTO backend.
LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple)
LLVM_ABI Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
LLVM_ABI Error backend(const Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, Module &M, ModuleSummaryIndex &CombinedIndex, ArrayRef< StringRef > BitcodeLibFuncs)
Runs a regular LTO backend.
std::function< void(const std::string &)> IndexWriteCallback
LLVM_ABI Error finalizeOptimizationRemarks(LLVMRemarkFileHandle DiagOutputFile)
LLVM_ABI ThinBackend createWriteIndexesThinBackend(ThreadPoolStrategy Parallelism, std::string OldPrefix, std::string NewPrefix, std::string NativeObjectPrefix, bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite)
This ThinBackend writes individual module indexes to files, instead of running the individual backend...
LLVM_ABI Expected< LLVMRemarkFileHandle > setupLLVMOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, std::optional< uint64_t > RemarksHotnessThreshold=0, int Count=-1)
Setup optimization remarks.
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
LLVM_ABI Expected< IRSymtabFile > readIRSymtab(MemoryBufferRef MBRef)
Reads a bitcode file, creating its irsymtab if necessary.
DiagnosticInfoOptimizationBase::Argument NV
void write64le(void *P, uint64_t V)
void write32le(void *P, uint32_t V)
LLVM_ABI std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
LLVM_ABI StringRef parent_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get parent path.
LLVM_ABI bool replace_path_prefix(SmallVectorImpl< char > &Path, StringRef OldPrefix, StringRef NewPrefix, Style style=Style::native)
Replace matching path prefix with another path.
This is an optimization pass for GlobalISel generic memory operations.
ThreadPoolStrategy heavyweight_hardware_concurrency(unsigned ThreadCount=0)
Returns a thread strategy for tasks requiring significant memory or other resources.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
cl::opt< std::string > RemarksFormat("lto-pass-remarks-format", cl::desc("The format used for serializing remarks (default: YAML)"), cl::value_desc("format"), cl::init("yaml"))
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
LLVM_ABI void computeDeadSymbolsWithConstProp(const cl::LibraryOptionsContext &LibraryOptions, ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, function_ref< PrevailingType(GlobalValue::GUID)> isPrevailing, bool ImportEnabled)
Compute dead symbols and run constant propagation in combined index after that.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI Expected< LLVMRemarkFileHandle > setupLLVMOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, std::optional< uint64_t > RemarksHotnessThreshold=0)
Set up optimization remarks that output to a file.
LLVM_ABI void thinLTOResolvePrevailingInIndex(const cl::LibraryOptionsContext &LibraryOptions, const lto::Config &C, ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
Resolve linkage for prevailing symbols in the Index.
cl::opt< std::string > RemarksPasses("lto-pass-remarks-filter", cl::desc("Only record optimization remarks from passes whose " "names match the given regular expression"), cl::value_desc("regex"))
LLVM_ABI void updatePublicTypeTestCalls(Module &M, bool WholeProgramVisibilityEnabledInLTO, bool DevirtSpeculativelyInIndex=false)
Convert llvm.public.type.test calls to llvm.type.test when whole program visibility is available,...
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
uint64_t stable_hash
An opaque object representing a stable hash code.
std::string utostr(uint64_t X, bool isNeg=false)
LLVM_ABI Error passPluginArguments(ArrayRef< PassPluginLibraryInfo > Infos, ArrayRef< std::string > Args)
Passes each "<PluginName>,<arg>" in Args to the ParseArguments callback of the extension in Infos wit...
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
auto dyn_cast_or_null(const Y &Val)
LLVM_ABI void EnableStatistics(bool DoPrintOnExit=true)
Enable the collection and printing of statistics.
LLVM_ABI void updateIndexWPDForExports(ModuleSummaryIndex &Summary, function_ref< bool(StringRef, ValueInfo)> isExported, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr=nullptr)
Call after cross-module importing to update the recorded single impl devirt target names for any loca...
LLVM_ABI void timeTraceProfilerInitialize(unsigned TimeTraceGranularity, StringRef ProcName, bool TimeTraceVerbose=false, TimeTraceCompression TimeTraceCompress=TimeTraceCompression::Infer)
Initialize the time trace profiler.
LLVM_ABI void timeTraceProfilerFinishThread()
Finish a time trace profiler running on a worker thread.
LLVM_ABI std::string recomputeLTOCacheKey(const std::string &Key, StringRef ExtraID)
Recomputes the LTO cache key for a given key with an extra identifier.
Error joinErrors(Error E1, Error E2)
Concatenate errors.
LLVM_ABI void getVisibleToRegularObjVtableGUIDs(ModuleSummaryIndex &Index, DenseSet< GlobalValue::GUID > &VisibleToRegularObjSymbols, function_ref< bool(StringRef)> IsVisibleToRegularObj)
Based on typeID string, get all associated vtable GUIDS that are visible to regular objects.
void sort(IteratorTy Start, IteratorTy End)
cl::opt< bool > AlwaysRenamePromotedLocals("always-rename-promoted-locals", cl::init(true), cl::Hidden, cl::desc("Always rename promoted locals."))
bool timeTraceProfilerEnabled()
Is the time trace profiler enabled, i.e. initialized?
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
LLVM_ABI cl::opt< bool > EnableLTOInternalization
Enable global value internalization in LTO.
cl::opt< bool > RemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
LLVM_ABI void timeTraceProfilerEnd()
Manually end the last time section.
cl::opt< std::string > RemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI void ComputeCrossModuleImport(const cl::LibraryOptionsContext &LibraryOptions, const ModuleSummaryIndex &Index, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, FunctionImporter::ImportListsTy &ImportLists, DenseMap< StringRef, FunctionImporter::ExportSetTy > &ExportLists)
Compute all the imports and exports for every module in the Index.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Mod
The access may modify the value stored in memory.
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
LLVM_ABI bool thinLTOPropagateFunctionAttrs(const cl::LibraryOptionsContext &LibraryOptions, ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Propagate function attributes for function summaries along the index's callgraph during thinlink.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
LLVM_ABI void gatherImportedSummariesForModule(StringRef ModulePath, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, const FunctionImporter::ImportMapTy &ImportList, ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, GVSummaryPtrSet &DecSummaries)
Compute the set of summaries needed for a ThinLTO backend compilation of ModulePath.
ArrayRef(const T &OneElt) -> ArrayRef< T >
void toHex(ArrayRef< uint8_t > Input, bool LowerCase, SmallVectorImpl< char > &Output)
Convert buffer Input to its hexadecimal representation. The returned string is double the size of Inp...
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI void processImportsFiles(StringRef ModulePath, const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, function_ref< void(const std::string &)> F)
Call F passing each of the files module ModulePath will import from.
cl::opt< std::optional< uint64_t >, false, remarks::HotnessThresholdParser > RemarksHotnessThreshold("lto-pass-remarks-hotness-threshold", cl::desc("Minimum profile count required for an " "optimization remark to be output." " Use 'auto' to apply the threshold from profile summary."), cl::value_desc("uint or 'auto'"), cl::init(0), cl::Hidden)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool hasWholeProgramVisibility(const cl::LibraryOptionsContext &LibraryOptions, bool WholeProgramVisibilityEnabledInLTO)
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
LLVM_ABI std::string computeLTOCacheKey(const lto::Config &Conf, const ModuleSummaryIndex &Index, StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList, const FunctionImporter::ExportSetTy &ExportList, const std::map< GlobalValue::GUID, GlobalValue::LinkageTypes > &ResolvedODR, const GVSummaryMapTy &DefinedGlobals, const DenseSet< GlobalValue::GUID > &CfiFunctionDefs={}, const DenseSet< GlobalValue::GUID > &CfiFunctionDecls={})
Computes a unique hash for the Module considering the current list of export/import and other global ...
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
static cl::opt< bool > LTOKeepSymbolCopies("lto-keep-symbol-copies", cl::init(false), cl::Hidden, cl::desc("Keep copies of symbols in LTO indexing"))
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
LLVM_ABI void generateParamAccessSummary(const cl::LibraryOptionsContext *LibraryOptions, ModuleSummaryIndex &Index)
Reads -stack-safety-max-iterations from LibraryOptions, or its global value if null.
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
std::function< Expected< std::unique_ptr< CachedFileStream > >( unsigned Task, const Twine &ModuleName)> AddStreamFn
This type defines the callback to add a file that is generated on the fly.
LLVM_ABI void PrintStatisticsJSON(raw_ostream &OS)
Print statistics in JSON format.
LLVM_ABI void runWholeProgramDevirtOnIndex(const cl::LibraryOptionsContext &LibraryOptions, ModuleSummaryIndex &Summary, std::set< GlobalValue::GUID > &ExportedGUIDs, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr)
Perform index-based whole program devirtualization on the Summary index.
void consumeError(Error Err)
Consume a Error without doing anything.
LLVM_ABI Error EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex)
Emit into OutputFilename the files module ModulePath will import from.
@ Keep
No function return thunk.
LLVM_ABI void updateVCallVisibilityInModule(Module &M, bool WholeProgramVisibilityEnabledInLTO, const DenseSet< GlobalValue::GUID > &DynamicExportSymbols, bool ValidateAllVtablesHaveTypeInfos, function_ref< bool(StringRef)> IsVisibleToRegularObj)
If whole program visibility asserted, then upgrade all public vcall visibility metadata on vtable def...
LLVM_ABI void updateVCallVisibilityInIndex(const cl::LibraryOptionsContext &LibraryOptions, ModuleSummaryIndex &Index, bool WholeProgramVisibilityEnabledInLTO, const DenseSet< GlobalValue::GUID > &DynamicExportSymbols, const DenseSet< GlobalValue::GUID > &VisibleToRegularObjSymbols)
If whole program visibility asserted, then upgrade all public vcall visibility metadata on vtable def...
LLVM_ABI TimeTraceProfilerEntry * timeTraceProfilerBegin(StringRef Name, StringRef Detail)
Manually begin a time section, with the given Name and Detail.
LLVM_ABI void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr=nullptr)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
Implement std::hash so that hash_code can be used in STL containers.
This type represents a file cache system that manages caching of files.
A simple container for information about the supported runtime calls.
unsigned getNumAvailableLibcallImpls() const
bool isAvailable(RTLIB::LibcallImpl Impl) const
RTLIB::LibcallImpl getSupportedLibcallImpl(StringRef FuncName) const
Check if this is valid libcall for the current module, otherwise RTLIB::Unsupported.
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.
Struct that holds a reference to a particular GUID in a global value summary.
Function object to check whether the first component of a container supported by std::get (like std::...
std::function< std::string &(size_t Task)> GetCacheKeyOutputString
Called by WriteIndexesThinBackend when it needs to store a bitcode module's cache key.
std::vector< std::string > PassPluginArgs
PostRegularLTOLinkHookFn PostRegularLTOLinkHook
std::optional< uint64_t > RemarksHotnessThreshold
The minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
std::optional< CodeModel::Model > CodeModel
bool CodeGenOnly
Disable entirely the optimizer, including importing for ThinLTO.
std::vector< std::string > MAttrs
std::vector< std::string > MllvmArgs
CodeGenOptLevel CGOptLevel
bool Dtlto
This flag is used as one of parameters to calculate cache entries and to ensure that in-process cache...
std::string DefaultTriple
Setting this field will replace unspecified target triples in input files with this triple.
std::string DwoDir
The directory to store .dwo files.
std::string RemarksFilename
Optimization remarks file path.
std::string OverrideTriple
Setting this field will replace target triples in input files with this triple.
std::string ProfileRemapping
Name remapping file for profile data.
bool TimeTraceEnabled
Time trace enabled.
std::string RemarksPasses
Optimization remarks pass filter.
std::string OptPipeline
If this field is set, the set of passes run in the middle-end optimizer will be the one specified by ...
unsigned TimeTraceGranularity
Time trace granularity.
bool RemarksWithHotness
Whether to emit optimization remarks with hotness informations.
std::optional< Reloc::Model > RelocModel
CodeGenFileType CGFileType
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target.
std::string SampleProfile
Sample PGO profile path.
std::string RemarksFormat
The format used for serializing remarks (default: YAML).
std::vector< AddedModule > ModsWithSummaries
std::unique_ptr< IRMover > Mover
unsigned ParallelCodeGenParallelismLevel
std::map< std::string, CommonResolution > Commons
std::unique_ptr< Module > CombinedModule
LLVM_ABI RegularLTOState(unsigned ParallelCodeGenParallelismLevel, const Config &Conf)
LLVM_ABI ThinLTOState(ThinBackend Backend)
std::optional< ModuleMapType > ModulesToCompile
ModuleSummaryIndex CombinedIndex
The resolution for a symbol.
unsigned FinalDefinitionInLinkageUnit
The definition of this symbol is unpreemptable at runtime and is known to be in this linkage unit.
unsigned ExportDynamic
The symbol was exported dynamically, and therefore could be referenced by a shared library not visibl...
unsigned Prevailing
The linker has chosen this definition of the symbol.
unsigned LinkerRedefined
Linker redefined version of the symbol which appeared in -wrap or -defsym linker option.
unsigned VisibleToRegularObj
The definition of this symbol is visible outside of the LTO unit.
This type defines the behavior following the thin-link phase during ThinLTO.