21 #include "llvm/Config/llvm-config.h" 40 #include "llvm/Support/VCSRevision.h" 55 #define DEBUG_TYPE "lto" 59 cl::desc(
"Dump the SCCs in the ThinLTO index's callgraph"));
64 cl::desc(
"Enable global value internalization in LTO"));
73 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
75 const std::set<GlobalValue::GUID> &CfiFunctionDefs,
76 const std::set<GlobalValue::GUID> &CfiFunctionDecls) {
84 Hasher.
update(LLVM_VERSION_STRING);
86 Hasher.
update(LLVM_REVISION);
94 auto AddUnsigned = [&](
unsigned I) {
102 auto AddUint64 = [&](uint64_t
I) {
123 for (
auto &A : Conf.
MAttrs)
147 for (
auto F : ExportList)
154 for (
auto &Entry : ImportList) {
158 AddUint64(Entry.second.size());
159 for (
auto &Fn : Entry.second)
164 for (
auto &Entry : ResolvedODR) {
173 std::set<GlobalValue::GUID> UsedCfiDefs;
174 std::set<GlobalValue::GUID> UsedCfiDecls;
177 std::set<GlobalValue::GUID> UsedTypeIds;
180 if (CfiFunctionDefs.count(ValueGUID))
181 UsedCfiDefs.insert(ValueGUID);
182 if (CfiFunctionDecls.count(ValueGUID))
183 UsedCfiDecls.insert(ValueGUID);
188 AddUnsigned(GS->isLive());
190 AddUnsigned(
VI.isDSOLocal());
191 AddUsedCfiGlobal(
VI.getGUID());
193 if (
auto *GVS = dyn_cast<GlobalVarSummary>(GS))
194 AddUnsigned(GVS->isReadOnly());
195 if (
auto *FS = dyn_cast<FunctionSummary>(GS)) {
196 for (
auto &TT : FS->type_tests())
197 UsedTypeIds.insert(TT);
198 for (
auto &TT : FS->type_test_assume_vcalls())
199 UsedTypeIds.insert(TT.GUID);
200 for (
auto &TT : FS->type_checked_load_vcalls())
201 UsedTypeIds.insert(TT.GUID);
202 for (
auto &TT : FS->type_test_assume_const_vcalls())
203 UsedTypeIds.insert(TT.VFunc.GUID);
204 for (
auto &TT : FS->type_checked_load_const_vcalls())
205 UsedTypeIds.insert(TT.VFunc.GUID);
206 for (
auto &ET : FS->calls()) {
207 AddUnsigned(ET.first.isDSOLocal());
208 AddUsedCfiGlobal(ET.first.getGUID());
215 for (
auto &GS : DefinedGlobals) {
219 AddUsedCfiGlobal(GS.first);
220 AddUsedThings(GS.second);
225 for (
auto &ImpM : ImportList)
226 for (
auto &ImpF : ImpM.second) {
231 if (
auto *AS = dyn_cast_or_null<AliasSummary>(S))
232 AddUsedThings(AS->getBaseObject());
238 AddUnsigned(S.TTRes.TheKind);
239 AddUnsigned(S.TTRes.SizeM1BitWidth);
241 AddUint64(S.TTRes.AlignLog2);
242 AddUint64(S.TTRes.SizeM1);
243 AddUint64(S.TTRes.BitMask);
244 AddUint64(S.TTRes.InlineBits);
246 AddUint64(S.WPDRes.size());
247 for (
auto &WPD : S.WPDRes) {
248 AddUnsigned(WPD.first);
249 AddUnsigned(WPD.second.TheKind);
250 AddString(WPD.second.SingleImplName);
252 AddUint64(WPD.second.ResByArg.size());
253 for (
auto &ByArg : WPD.second.ResByArg) {
254 AddUint64(ByArg.first.size());
255 for (uint64_t
Arg : ByArg.first)
257 AddUnsigned(ByArg.second.TheKind);
258 AddUint64(ByArg.second.Info);
259 AddUnsigned(ByArg.second.Byte);
260 AddUnsigned(ByArg.second.Bit);
267 auto TidIter = Index.
typeIds().equal_range(TId);
268 for (
auto It = TidIter.first; It != TidIter.second; ++It)
269 AddTypeIdSummary(It->second.first, It->second.second);
272 AddUnsigned(UsedCfiDefs.size());
273 for (
auto &V : UsedCfiDefs)
276 AddUnsigned(UsedCfiDecls.size());
277 for (
auto &V : UsedCfiDecls)
283 Hasher.
update(FileOrErr.get()->getBuffer());
288 Hasher.
update(FileOrErr.get()->getBuffer());
303 for (
auto &S : GVSummaryList) {
318 if (isPrevailing(GUID, S.get())) {
324 else if (!isa<AliasSummary>(S.get()) &&
325 !GlobalInvolvedWithAlias.
count(S.get()))
327 if (S->linkage() != OriginalLinkage)
328 recordNewLinkage(S->modulePath(), GUID, S->linkage());
348 for (
auto &
I : Index)
349 for (
auto &S :
I.second.SummaryList)
350 if (
auto AS = dyn_cast<AliasSummary>(S.get()))
351 GlobalInvolvedWithAlias.
insert(&AS->getAliasee());
353 for (
auto &
I : Index)
355 GlobalInvolvedWithAlias, isPrevailing,
362 for (
auto &S : GVSummaryList) {
363 if (isExported(S->modulePath(), GUID)) {
383 for (
auto &
I : Index)
397 File->TargetTriple = FOrErr->TheReader.getTargetTriple();
398 File->SourceFileName = FOrErr->TheReader.getSourceFileName();
399 File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
400 File->ComdatTable = FOrErr->TheReader.getComdatTable();
402 for (
unsigned I = 0;
I != FOrErr->Mods.size(); ++
I) {
403 size_t Begin = File->Symbols.size();
405 FOrErr->TheReader.module_symbols(
I))
408 if (Sym.isGlobal() && !Sym.isFormatSpecific())
409 File->Symbols.push_back(Sym);
410 File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
413 File->Mods = FOrErr->Mods;
414 File->Strtab = std::move(FOrErr->Strtab);
415 return std::move(File);
419 return Mods[0].getModuleIdentifier();
422 LTO::RegularLTOState::RegularLTOState(
unsigned ParallelCodeGenParallelismLevel,
424 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
425 Ctx(Conf), CombinedModule(llvm::make_unique<Module>(
"ld-temp.o", Ctx)),
426 Mover(llvm::make_unique<IRMover>(*CombinedModule)) {}
428 LTO::ThinLTOState::ThinLTOState(
ThinBackend Backend)
429 : Backend(Backend), CombinedIndex(
false) {
436 unsigned ParallelCodeGenParallelismLevel)
437 : Conf(
std::move(Conf)),
438 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
439 ThinLTO(
std::move(Backend)) {}
448 unsigned Partition,
bool InSummary) {
449 auto *ResI = Res.
begin();
450 auto *ResE = Res.
end();
457 Triple TT(RegularLTO.CombinedModule->getTargetTriple());
461 if (TT.isOSBinFormatCOFF() && Name.
startswith(
"__imp_"))
462 Name = Name.
substr(strlen(
"__imp_"));
463 auto &GlobalRes = GlobalResolutions[
Name];
464 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
466 assert(!GlobalRes.Prevailing &&
467 "Multiple prevailing defs are not allowed");
468 GlobalRes.Prevailing =
true;
469 GlobalRes.IRName = Sym.getIRName();
470 }
else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
477 GlobalRes.IRName = Sym.getIRName();
486 GlobalRes.Partition != Partition)) {
487 GlobalRes.Partition = GlobalResolution::External;
490 GlobalRes.Partition = Partition;
494 GlobalRes.VisibleOutsideSummary |=
503 auto ResI = Res.
begin();
508 OS <<
"-r=" << Path <<
',' << Sym.getName() <<
',';
511 if (Res.FinalDefinitionInLinkageUnit)
513 if (Res.VisibleToRegularObj)
515 if (Res.LinkerRedefined)
525 assert(!CalledGetMaxTasks);
530 if (RegularLTO.CombinedModule->getTargetTriple().empty())
531 RegularLTO.CombinedModule->setTargetTriple(Input->getTargetTriple());
534 for (
unsigned I = 0;
I != Input->Mods.size(); ++
I)
535 if (
Error Err = addModule(*Input,
I, ResI, Res.
end()))
549 if (EnableSplitLTOUnit.
hasValue()) {
553 if (EnableSplitLTOUnit.
getValue() != LTOInfo->EnableSplitLTOUnit)
554 ThinLTO.CombinedIndex.setPartiallySplitLTOUnits();
556 EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
559 auto ModSyms = Input.module_symbols(ModI);
560 addModuleToGlobalRes(ModSyms, {ResI, ResE},
561 LTOInfo->IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0,
562 LTOInfo->HasSummary);
564 if (LTOInfo->IsThinLTO)
565 return addThinLTO(BM, ModSyms, ResI, ResE);
568 addRegularLTO(BM, ModSyms, ResI, ResE);
572 if (!LTOInfo->HasSummary)
573 return linkRegularLTO(std::move(*ModOrErr),
false);
579 RegularLTO.ModsWithSummaries.push_back(std::move(*ModOrErr));
595 std::set<const Comdat *> &NonPrevailingComdats) {
600 if (!NonPrevailingComdats.count(C))
609 if (
auto GO = dyn_cast<GlobalObject>(&GV))
610 GO->setComdat(
nullptr);
620 RegularLTOState::AddedModule
Mod;
627 Mod.M = std::move(*MOrErr);
630 return std::move(Err);
637 if (GV.hasAppendingLinkage())
638 Mod.Keep.push_back(&GV);
643 AliasedGlobals.
insert(GO);
652 auto MsymI = SymTab.
symbols().begin(), MsymE = SymTab.
symbols().end();
654 while (MsymI != MsymE) {
664 std::set<const Comdat *> NonPrevailingComdats;
675 if (Sym.isUndefined())
677 Mod.Keep.push_back(GV);
688 }
else if (isa<GlobalObject>(GV) &&
689 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
690 GV->hasAvailableExternallyLinkage()) &&
691 !AliasedGlobals.
count(cast<GlobalObject>(GV))) {
697 Mod.Keep.push_back(GV);
700 NonPrevailingComdats.insert(GV->getComdat());
701 cast<GlobalObject>(GV)->setComdat(
nullptr);
706 GV->setDSOLocal(
true);
707 if (GV->hasDLLImportStorageClass())
709 DefaultStorageClass);
715 if (Sym.isCommon()) {
718 auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
719 CommonRes.Size =
std::max(CommonRes.Size, Sym.getCommonSize());
720 CommonRes.Align =
std::max(CommonRes.Align, Sym.getCommonAlignment());
729 return std::move(Mod);
732 Error LTO::linkRegularLTO(RegularLTOState::AddedModule
Mod,
733 bool LivenessFromIndex) {
734 std::vector<GlobalValue *> Keep;
736 if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->
getGUID()))
747 RegularLTO.CombinedModule->getNamedValue(GV->
getName());
754 return RegularLTO.Mover->move(std::move(Mod.M), Keep,
765 ThinLTO.ModuleMap.size()))
772 if (!Sym.getIRName().empty()) {
783 if (
auto S = ThinLTO.CombinedIndex.findSummaryInModule(
791 if (
auto S = ThinLTO.CombinedIndex.findSummaryInModule(
793 S->setDSOLocal(
true);
799 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
800 return make_error<StringError>(
801 "Expected at most one ThinLTO module per bitcode file",
808 CalledGetMaxTasks =
true;
809 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
816 for (
auto &Res : GlobalResolutions) {
819 if (Res.second.IRName.
empty())
825 if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
829 GUIDPrevailingResolutions[GUID] =
834 auto It = GUIDPrevailingResolutions.
find(
G);
835 if (It == GUIDPrevailingResolutions.
end())
843 std::unique_ptr<ToolOutputFile> StatsFile =
nullptr;
854 Error Result = runRegularLTO(AddStream);
856 Result = runThinLTO(AddStream, Cache);
865 for (
auto &M : RegularLTO.ModsWithSummaries)
866 if (
Error Err = linkRegularLTO(std::move(M),
872 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
873 for (
auto &
I : RegularLTO.Commons) {
874 if (!
I.second.Prevailing)
877 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(
I.first);
886 auto *GV =
new GlobalVariable(*RegularLTO.CombinedModule, Ty,
false,
889 GV->setAlignment(
I.second.Align);
895 GV->setName(
I.first);
904 for (
const auto &R : GlobalResolutions) {
905 if (!R.second.isPrevailingIRSymbol())
907 if (R.second.Partition != 0 &&
908 R.second.Partition != GlobalResolution::External)
912 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
927 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
928 std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
941 : Conf(Conf), CombinedIndex(CombinedIndex),
942 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
949 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
951 virtual Error wait() = 0;
959 std::set<GlobalValue::GUID> CfiFunctionDefs;
960 std::set<GlobalValue::GUID> CfiFunctionDecls;
966 InProcessThinBackend(
968 unsigned ThinLTOParallelismLevel,
972 BackendThreadPool(ThinLTOParallelismLevel),
973 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {
975 CfiFunctionDefs.insert(
978 CfiFunctionDecls.insert(
982 Error runThinLTOBackendThread(
987 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
996 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
997 ImportList, DefinedGlobals, ModuleMap);
1004 [](
uint32_t V) {
return V == 0; }))
1007 return RunThinBackend(AddStream);
1012 ExportList, ResolvedODR, DefinedGlobals, CfiFunctionDefs,
1014 if (
AddStreamFn CacheAddStream = Cache(Task, Key))
1015 return RunThinBackend(CacheAddStream);
1024 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1027 assert(ModuleToDefinedGVSummaries.
count(ModulePath));
1029 ModuleToDefinedGVSummaries.
find(ModulePath)->second;
1030 BackendThreadPool.
async(
1034 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1038 Error E = runThinLTOBackendThread(
1039 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1040 ResolvedODR, DefinedGlobals, ModuleMap);
1042 std::unique_lock<std::mutex> L(ErrMu);
1044 Err =
joinErrors(std::move(*Err), std::move(E));
1049 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
1050 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
1054 Error wait()
override {
1055 BackendThreadPool.
wait();
1057 return std::move(*Err);
1068 return llvm::make_unique<InProcessThinBackend>(
1069 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
1078 const std::string &OldPrefix,
1079 const std::string &NewPrefix) {
1080 if (OldPrefix.empty() && NewPrefix.empty())
1085 if (!ParentPath.
empty()) {
1088 llvm::errs() <<
"warning: could not create directory '" << ParentPath
1089 <<
"': " << EC.message() <<
'\n';
1091 return NewPath.
str();
1096 std::string OldPrefix, NewPrefix;
1097 bool ShouldEmitImportsFiles;
1102 WriteIndexesThinBackend(
1105 std::string OldPrefix, std::string NewPrefix,
bool ShouldEmitImportsFiles,
1108 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
1109 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
1110 LinkedObjectsFile(LinkedObjectsFile), OnWrite(OnWrite) {}
1116 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1119 std::string NewModulePath =
1122 if (LinkedObjectsFile)
1123 *LinkedObjectsFile << NewModulePath <<
'\n';
1125 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
1127 ImportList, ModuleToSummariesForIndex);
1136 if (ShouldEmitImportsFiles) {
1138 ModuleToSummariesForIndex);
1144 OnWrite(ModulePath);
1153 std::string OldPrefix, std::string NewPrefix,
bool ShouldEmitImportsFiles,
1158 return llvm::make_unique<WriteIndexesThinBackend>(
1159 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
1160 ShouldEmitImportsFiles, LinkedObjectsFile, OnWrite);
1165 if (ThinLTO.ModuleMap.empty())
1174 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
1175 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
1176 ModuleToDefinedGVSummaries);
1184 for (
auto &Mod : ThinLTO.ModuleMap)
1185 if (!ModuleToDefinedGVSummaries.count(Mod.first))
1186 ModuleToDefinedGVSummaries.
try_emplace(Mod.first);
1192 ThinLTO.ModuleMap.size());
1194 ThinLTO.ModuleMap.size());
1198 ThinLTO.CombinedIndex.dumpSCCs(
outs());
1202 ImportLists, ExportLists);
1208 std::set<GlobalValue::GUID> ExportedGUIDs;
1209 for (
auto &Res : GlobalResolutions) {
1212 if (Res.second.Partition != GlobalResolution::External ||
1213 !Res.second.isPrevailingIRSymbol())
1218 if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
1219 ExportedGUIDs.insert(GUID);
1224 for (
auto &
Def : ThinLTO.CombinedIndex.cfiFunctionDefs())
1225 ExportedGUIDs.insert(
1229 const auto &ExportList = ExportLists.find(ModuleIdentifier);
1230 return (ExportList != ExportLists.end() &&
1231 ExportList->second.count(GUID)) ||
1232 ExportedGUIDs.count(GUID);
1238 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1240 auto recordNewLinkage = [&](
StringRef ModuleIdentifier,
1243 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1248 std::unique_ptr<ThinBackendProc> BackendProc =
1249 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1254 unsigned Task = RegularLTO.ParallelCodeGenParallelismLevel;
1255 for (
auto &Mod : ThinLTO.ModuleMap) {
1256 if (
Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
1257 ExportLists[Mod.first],
1258 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
1263 return BackendProc->wait();
1270 if (LTOPassRemarksWithHotness)
1272 if (LTORemarksFilename.
empty())
1280 auto DiagnosticFile =
1285 llvm::make_unique<yaml::Output>(DiagnosticFile->os()));
1286 DiagnosticFile->keep();
1287 return std::move(DiagnosticFile);
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.
A parsed version of the target data layout string in and methods for querying it. ...
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef LTORemarksFilename, bool LTOPassRemarksWithHotness, int Count=-1)
Setup optimization remarks.
This class defines the interface to the ThinLTO backend.
bool hasLocalLinkage() const
Special purpose, only applies to global arrays.
uint32_t getSymbolFlags(Symbol S) const
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
void EnableStatistics(bool PrintOnExit=true)
Enable the collection and printing of statistics.
unsigned Prevailing
The linker has chosen this definition of the symbol.
CodeGenOpt::Level CGOptLevel
void replace_path_prefix(SmallVectorImpl< char > &Path, const StringRef &OldPrefix, const StringRef &NewPrefix, Style style=Style::native)
Replace matching path prefix with another path.
std::vector< std::unique_ptr< GlobalValueSummary > > GlobalValueSummaryList
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
This class represents lattice values for constants.
void setDiagnosticsOutputFile(std::unique_ptr< yaml::Output > F)
Set the diagnostics output file used for optimization diagnostics.
cl::opt< std::string > LTORemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
unsigned heavyweight_hardware_concurrency()
Get the amount of currency to use for tasks requiring significant memory or other resources...
A Module instance is used to store all the information related to an LLVM module. ...
GlobalValueSummary * findSummaryInModule(GlobalValue::GUID ValueGUID, StringRef ModuleId) const
Find the summary for global GUID in module ModuleId, or nullptr if not found.
Implements a dense probed hash-table based set.
std::string OverrideTriple
Setting this field will replace target triples in input files with this triple.
Available for inspection, not emission.
unsigned DataSections
Emit data into separate sections.
static ConstantAggregateZero * get(Type *Ty)
std::error_code EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Emit into OutputFilename the files module ModulePath will import from.
bool CodeGenOnly
Disable entirely the optimizer, including importing for ThinLTO.
Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, uint64_t ModuleId)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
bool hasAvailableExternallyLinkage() const
unsigned LinkerRedefined
Linker redefined version of the symbol which appeared in -wrap or -defsym linker option.
std::unique_ptr< raw_ostream > ResolutionFile
If this field is set, LTO will write input file paths and symbol resolutions here in llvm-lto2 comman...
An efficient, type-erasing, non-owning reference to a callable.
iterator find(StringRef Key)
const StringMap< std::pair< uint64_t, ModuleHash > > & modulePaths() const
Table of modules, containing module hash and id.
Externally visible function.
The resolution for a symbol.
This class implements a map that also provides access to all stored values in a deterministic order...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
const StringMap< GVSummaryMapTy > & ModuleToDefinedGVSummaries
A class that wrap the SHA1 algorithm.
Error takeError()
Take ownership of the stored error.
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e...
void setAlignment(unsigned Align)
std::function< void(const std::string &)> IndexWriteCallback
This ThinBackend writes individual module indexes to files, instead of running the individual backend...
std::shared_future< void > async(Function &&F, Args &&... ArgList)
Asynchronous submission of a task to the pool.
StringRef getModuleIdentifier() const
ThinBackend createWriteIndexesThinBackend(std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite)
static bool isLocalLinkage(LinkageTypes Linkage)
static bool isLinkOnceLinkage(LinkageTypes Linkage)
CombinedIndexHookFn CombinedIndexHook
std::function< std::unique_ptr< NativeObjectStream >unsigned Task)> AddStreamFn
This type defines the callback to add a native object that is generated on the fly.
amdgpu Simplify well known AMD library false Value Value const Twine & Name
Represents a module in a bitcode file.
std::string DwoDir
The directory to store .dwo files.
const ComdatSymTabType & getComdatSymbolTable() const
Get the Module's symbol table for COMDATs (constant).
std::vector< std::string > MAttrs
std::string ProfileRemapping
Name remapping file for profile data.
ModuleSummaryIndex & CombinedIndex
const TypeIdSummaryMapTy & typeIds() const
std::unordered_set< GlobalValue::GUID > ExportSetTy
The set contains an entry for every global value the module exports.
ArrayRef< Symbol > symbols() const
Tagged union holding either a T or a Error.
StringRef result()
Return a reference to the current raw 160-bits SHA1 for the digested data since the last call to init...
void addModule(Module *M)
static bool isLinkOnceODRLinkage(LinkageTypes Linkage)
StringRef str() const
Explicit conversion to StringRef.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
cl::opt< bool > LTOPassRemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
const T & getValue() const LLVM_LVALUE_FUNCTION
void setDiagnosticsHotnessRequested(bool Requested)
Set if a code hotness metric should be included in optimization diagnostics.
Class to represent array types.
std::string SampleProfile
Sample PGO profile path.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
unsigned FunctionSections
Emit functions into separate sections.
Optional< CodeModel::Model > CodeModel
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
A ThreadPool for asynchronous parallel execution on a defined number of threads.
static bool isAppendingLinkage(LinkageTypes Linkage)
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&... Args)
Emplace a new element for the specified key into the map if the key isn't already in the map...
Class to hold module path string table and global value map, and encapsulate methods for operating on...
void update(ArrayRef< uint8_t > Data)
Digest more data.
iterator find(const_arg_type_t< KeyT > Val)
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Ephemeral symbols produced by Reader::symbols() and Reader::module_symbols().
Error add(std::unique_ptr< InputFile > Obj, ArrayRef< SymbolResolution > Res)
Add an input file to the LTO link, using the provided symbol resolutions.
DebuggerKind DebuggerTuning
Which debugger to tune for.
raw_ostream & outs()
This returns a reference to a raw_ostream for standard output.
initializer< Ty > init(const Ty &Val)
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module, before modifying it.
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"))
std::function< AddStreamFn(unsigned Task, StringRef Key)> NativeObjectCache
This is the type of a native object cache.
void gatherImportedSummariesForModule(StringRef ModulePath, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, const FunctionImporter::ImportMapTy &ImportList, std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Compute the set of summaries needed for a ThinLTO backend compilation of ModulePath.
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
This is an important class for using LLVM in a threaded context.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
std::pair< iterator, bool > insert(const ValueT &V)
bool UseNewPM
Use the new pass manager.
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
void thinLTOResolvePrevailingInIndex(ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage)
Resolve linkage for prevailing symbols in the Index.
std::string DefaultTriple
Setting this field will replace unspecified target triples in input files with this triple...
DLLStorageClassTypes
Storage classes of global values for PE targets.
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
StringRef parent_path(StringRef path, Style style=Style::native)
Get parent path.
Function and variable summary information to aid decisions and implementation of importing.
static GUID getGUID(StringRef GlobalName)
Return a 64-bit global unique ID constructed from global value name (i.e.
std::string StatsFile
Statistics output file path.
T dyn_cast() const
Returns the current pointer if it is of the specified pointer type, otherwises returns null...
ModuleHookFn PostInternalizeModuleHook
This hook is called after internalizing the module.
TargetMachine::CodeGenFileType CGFileType
Triple - Helper class for working with autoconf configuration names.
static LinkageTypes getWeakLinkage(bool ODR)
Struct that holds a reference to a particular GUID in a global value summary.
static void writeToResolutionFile(raw_ostream &OS, InputFile *Input, ArrayRef< SymbolResolution > Res)
void computeSyntheticCounts(ModuleSummaryIndex &Index)
Compute synthetic function entry counts.
void PrintStatisticsJSON(raw_ostream &OS)
Print statistics in JSON format.
static ErrorSuccess success()
Create a success value.
std::function< std::unique_ptr< ThinBackendProc > Config &C, ModuleSummaryIndex &CombinedIndex, StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, AddStreamFn AddStream, NativeObjectCache Cache)> ThinBackend
A ThinBackend defines what happens after the thin-link phase during ThinLTO.
unsigned getMaxTasks() const
Returns an upper bound on the number of tasks that the client may expect.
void computeLTOCacheKey(SmallString< 40 > &Key, 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 std::set< GlobalValue::GUID > &CfiFunctionDefs={}, const std::set< GlobalValue::GUID > &CfiFunctionDecls={})
Computes a unique hash for the Module considering the current list of export/import and other global ...
static void thinLTOInternalizeAndPromoteGUID(GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID, function_ref< bool(StringRef, GlobalValue::GUID)> isExported)
virtual ~ThinBackendProc()
Optional< Reloc::Model > RelocModel
std::string utostr(uint64_t X, bool isNeg=false)
void setLinkage(LinkageTypes LT)
The access may modify the value stored in memory.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
const Comdat * getComdat() const
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1', drop it.
LinkageTypes
An enumeration for the kinds of linkage for global values.
std::string OptPipeline
If this field is set, the set of passes run in the middle-end optimizer will be the one specified by ...
void WriteIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const std::map< std::string, GVSummaryMapTy > *ModuleToSummariesForIndex=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
unsigned RelaxELFRelocations
ThinBackend createInProcessThinBackend(unsigned ParallelismLevel)
This ThinBackend runs the individual backend jobs in-process.
amdgpu Simplify well known AMD library false Value Value * Arg
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
std::set< std::string > & cfiFunctionDefs()
Error thinBackend(Config &C, unsigned Task, AddStreamFn AddStream, Module &M, const ModuleSummaryIndex &CombinedIndex, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector< StringRef, BitcodeModule > &ModuleMap)
Runs a ThinLTO backend.
void ComputeCrossModuleImport(const ModuleSummaryIndex &Index, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, StringMap< FunctionImporter::ImportMapTy > &ImportLists, StringMap< FunctionImporter::ExportSetTy > &ExportLists)
Compute all the imports and exports for every module in the Index.
A raw_ostream that writes to a file descriptor.
LTO(Config Conf, ThinBackend Backend=nullptr, unsigned ParallelCodeGenParallelismLevel=1)
Create an LTO object.
void setUnnamedAddr(UnnamedAddr Val)
static void handleNonPrevailingComdat(GlobalValue &GV, std::set< const Comdat *> &NonPrevailingComdats)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
StringRef getName() const
Return a constant reference to the value's name.
Error run(AddStreamFn AddStream, NativeObjectCache Cache=nullptr)
Runs the LTO pipeline.
static void thinLTOResolvePrevailingGUID(GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID, DenseSet< GlobalValueSummary *> &GlobalInvolvedWithAlias, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage)
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Type * getValueType() const
Keep one copy of named function when linking (weak)
Rename collisions when linking (static functions).
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
unsigned VisibleToRegularObj
The definition of this symbol is visible outside of the LTO unit.
cl::opt< bool > EnableLTOInternalization("enable-lto-internalization", cl::init(true), cl::Hidden, cl::desc("Enable global value internalization in LTO"))
Enable global value internalization in LTO.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
const GlobalObject * getBaseObject() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
void computeDeadSymbolsWithConstProp(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.
Error backend(Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, std::unique_ptr< Module > M, ModuleSummaryIndex &CombinedIndex)
Runs a regular LTO backend.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::set< std::string > & cfiFunctionDecls()
std::function< void(GlobalValue &)> ValueAdder
Lightweight error class with error context and mandatory checking.
This class implements an extremely fast bulk output stream that can only output to a stream...
Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting)
Read the bitcode module and prepare for lazy deserialization of function bodies.
Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context)
Read the entire bitcode module and return it.
iterator_range< global_iterator > globals()
A derived class of LLVMContext that initializes itself according to a given Config object...
StringRef - Represent a constant reference to a string, i.e.
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target...
unsigned FinalDefinitionInLinkageUnit
The definition of this symbol is unpreemptable at runtime and is known to be in this linkage unit...
Expected< IRSymtabFile > readIRSymtab(MemoryBufferRef MBRef)
Reads a bitcode file, creating its irsymtab if necessary.
std::string toHex(StringRef Input, bool LowerCase=false)
Convert buffer Input to its hexadecimal representation.
iterator_range< global_value_iterator > global_values()
void wait()
Blocking wait for all the threads to complete and the queue to be empty.
llvm::Error materializeMetadata()
static IntegerType * getInt8Ty(LLVMContext &C)
PointerType * getType() const
Global values are always pointers.
std::string getThinLTOOutputFile(const std::string &Path, const std::string &OldPrefix, const std::string &NewPrefix)
Given the original Path to an output file, replace any path prefix matching OldPrefix with NewPrefix...
void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, GlobalValue::GUID)> isExported)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
bool empty() const
empty - Check if the array is empty.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
A discriminated union of two pointer types, with the discriminator in the low bit of the pointer...
iterator_range< alias_iterator > aliases()