[RISCV] Refactor predicates for rvv intrinsic patterns.
[llvm-project.git] / llvm / lib / LTO / LTO.cpp
blobde9b8f1da62bef950231651683dc69e3a1b3aa8a
1 //===-LTO.cpp - LLVM Link Time Optimizer ----------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements functions and classes used to support LTO.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/LTO/LTO.h"
14 #include "llvm/ADT/ScopeExit.h"
15 #include "llvm/ADT/SmallSet.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
19 #include "llvm/Analysis/StackSafetyAnalysis.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Bitcode/BitcodeReader.h"
23 #include "llvm/Bitcode/BitcodeWriter.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/Config/llvm-config.h"
26 #include "llvm/IR/AutoUpgrade.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/LLVMRemarkStreamer.h"
30 #include "llvm/IR/LegacyPassManager.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/IR/Metadata.h"
33 #include "llvm/LTO/LTOBackend.h"
34 #include "llvm/LTO/SummaryBasedOptimizations.h"
35 #include "llvm/Linker/IRMover.h"
36 #include "llvm/MC/TargetRegistry.h"
37 #include "llvm/Object/IRObjectFile.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Error.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/SHA1.h"
45 #include "llvm/Support/SourceMgr.h"
46 #include "llvm/Support/ThreadPool.h"
47 #include "llvm/Support/Threading.h"
48 #include "llvm/Support/TimeProfiler.h"
49 #include "llvm/Support/ToolOutputFile.h"
50 #include "llvm/Support/VCSRevision.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "llvm/Transforms/IPO.h"
54 #include "llvm/Transforms/IPO/MemProfContextDisambiguation.h"
55 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
56 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
57 #include "llvm/Transforms/Utils/SplitModule.h"
59 #include <optional>
60 #include <set>
62 using namespace llvm;
63 using namespace lto;
64 using namespace object;
66 #define DEBUG_TYPE "lto"
68 static cl::opt<bool>
69 DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(false), cl::Hidden,
70 cl::desc("Dump the SCCs in the ThinLTO index's callgraph"));
72 namespace llvm {
73 /// Enable global value internalization in LTO.
74 cl::opt<bool> EnableLTOInternalization(
75 "enable-lto-internalization", cl::init(true), cl::Hidden,
76 cl::desc("Enable global value internalization in LTO"));
79 /// Indicate we are linking with an allocator that supports hot/cold operator
80 /// new interfaces.
81 extern cl::opt<bool> SupportsHotColdNew;
83 /// Enable MemProf context disambiguation for thin link.
84 extern cl::opt<bool> EnableMemProfContextDisambiguation;
86 // Computes a unique hash for the Module considering the current list of
87 // export/import and other global analysis results.
88 // The hash is produced in \p Key.
89 void llvm::computeLTOCacheKey(
90 SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
91 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
92 const FunctionImporter::ExportSetTy &ExportList,
93 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
94 const GVSummaryMapTy &DefinedGlobals,
95 const std::set<GlobalValue::GUID> &CfiFunctionDefs,
96 const std::set<GlobalValue::GUID> &CfiFunctionDecls) {
97 // Compute the unique hash for this entry.
98 // This is based on the current compiler version, the module itself, the
99 // export list, the hash for every single module in the import list, the
100 // list of ResolvedODR for the module, and the list of preserved symbols.
101 SHA1 Hasher;
103 // Start with the compiler revision
104 Hasher.update(LLVM_VERSION_STRING);
105 #ifdef LLVM_REVISION
106 Hasher.update(LLVM_REVISION);
107 #endif
109 // Include the parts of the LTO configuration that affect code generation.
110 auto AddString = [&](StringRef Str) {
111 Hasher.update(Str);
112 Hasher.update(ArrayRef<uint8_t>{0});
114 auto AddUnsigned = [&](unsigned I) {
115 uint8_t Data[4];
116 support::endian::write32le(Data, I);
117 Hasher.update(ArrayRef<uint8_t>{Data, 4});
119 auto AddUint64 = [&](uint64_t I) {
120 uint8_t Data[8];
121 support::endian::write64le(Data, I);
122 Hasher.update(ArrayRef<uint8_t>{Data, 8});
124 AddString(Conf.CPU);
125 // FIXME: Hash more of Options. For now all clients initialize Options from
126 // command-line flags (which is unsupported in production), but may set
127 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
128 // DataSections and DebuggerTuning via command line flags.
129 AddUnsigned(Conf.Options.RelaxELFRelocations);
130 AddUnsigned(Conf.Options.FunctionSections);
131 AddUnsigned(Conf.Options.DataSections);
132 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
133 for (auto &A : Conf.MAttrs)
134 AddString(A);
135 if (Conf.RelocModel)
136 AddUnsigned(*Conf.RelocModel);
137 else
138 AddUnsigned(-1);
139 if (Conf.CodeModel)
140 AddUnsigned(*Conf.CodeModel);
141 else
142 AddUnsigned(-1);
143 for (const auto &S : Conf.MllvmArgs)
144 AddString(S);
145 AddUnsigned(Conf.CGOptLevel);
146 AddUnsigned(Conf.CGFileType);
147 AddUnsigned(Conf.OptLevel);
148 AddUnsigned(Conf.Freestanding);
149 AddString(Conf.OptPipeline);
150 AddString(Conf.AAPipeline);
151 AddString(Conf.OverrideTriple);
152 AddString(Conf.DefaultTriple);
153 AddString(Conf.DwoDir);
155 // Include the hash for the current module
156 auto ModHash = Index.getModuleHash(ModuleID);
157 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
159 std::vector<uint64_t> ExportsGUID;
160 ExportsGUID.reserve(ExportList.size());
161 for (const auto &VI : ExportList) {
162 auto GUID = VI.getGUID();
163 ExportsGUID.push_back(GUID);
166 // Sort the export list elements GUIDs.
167 llvm::sort(ExportsGUID);
168 for (uint64_t GUID : ExportsGUID) {
169 // The export list can impact the internalization, be conservative here
170 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&GUID, sizeof(GUID)));
173 // Include the hash for every module we import functions from. The set of
174 // imported symbols for each module may affect code generation and is
175 // sensitive to link order, so include that as well.
176 using ImportMapIteratorTy = FunctionImporter::ImportMapTy::const_iterator;
177 std::vector<ImportMapIteratorTy> ImportModulesVector;
178 ImportModulesVector.reserve(ImportList.size());
180 for (ImportMapIteratorTy It = ImportList.begin(); It != ImportList.end();
181 ++It) {
182 ImportModulesVector.push_back(It);
184 llvm::sort(ImportModulesVector,
185 [](const ImportMapIteratorTy &Lhs, const ImportMapIteratorTy &Rhs)
186 -> bool { return Lhs->getKey() < Rhs->getKey(); });
187 for (const ImportMapIteratorTy &EntryIt : ImportModulesVector) {
188 auto ModHash = Index.getModuleHash(EntryIt->first());
189 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
191 AddUint64(EntryIt->second.size());
192 for (auto &Fn : EntryIt->second)
193 AddUint64(Fn);
196 // Include the hash for the resolved ODR.
197 for (auto &Entry : ResolvedODR) {
198 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
199 sizeof(GlobalValue::GUID)));
200 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
201 sizeof(GlobalValue::LinkageTypes)));
204 // Members of CfiFunctionDefs and CfiFunctionDecls that are referenced or
205 // defined in this module.
206 std::set<GlobalValue::GUID> UsedCfiDefs;
207 std::set<GlobalValue::GUID> UsedCfiDecls;
209 // Typeids used in this module.
210 std::set<GlobalValue::GUID> UsedTypeIds;
212 auto AddUsedCfiGlobal = [&](GlobalValue::GUID ValueGUID) {
213 if (CfiFunctionDefs.count(ValueGUID))
214 UsedCfiDefs.insert(ValueGUID);
215 if (CfiFunctionDecls.count(ValueGUID))
216 UsedCfiDecls.insert(ValueGUID);
219 auto AddUsedThings = [&](GlobalValueSummary *GS) {
220 if (!GS) return;
221 AddUnsigned(GS->getVisibility());
222 AddUnsigned(GS->isLive());
223 AddUnsigned(GS->canAutoHide());
224 for (const ValueInfo &VI : GS->refs()) {
225 AddUnsigned(VI.isDSOLocal(Index.withDSOLocalPropagation()));
226 AddUsedCfiGlobal(VI.getGUID());
228 if (auto *GVS = dyn_cast<GlobalVarSummary>(GS)) {
229 AddUnsigned(GVS->maybeReadOnly());
230 AddUnsigned(GVS->maybeWriteOnly());
232 if (auto *FS = dyn_cast<FunctionSummary>(GS)) {
233 for (auto &TT : FS->type_tests())
234 UsedTypeIds.insert(TT);
235 for (auto &TT : FS->type_test_assume_vcalls())
236 UsedTypeIds.insert(TT.GUID);
237 for (auto &TT : FS->type_checked_load_vcalls())
238 UsedTypeIds.insert(TT.GUID);
239 for (auto &TT : FS->type_test_assume_const_vcalls())
240 UsedTypeIds.insert(TT.VFunc.GUID);
241 for (auto &TT : FS->type_checked_load_const_vcalls())
242 UsedTypeIds.insert(TT.VFunc.GUID);
243 for (auto &ET : FS->calls()) {
244 AddUnsigned(ET.first.isDSOLocal(Index.withDSOLocalPropagation()));
245 AddUsedCfiGlobal(ET.first.getGUID());
250 // Include the hash for the linkage type to reflect internalization and weak
251 // resolution, and collect any used type identifier resolutions.
252 for (auto &GS : DefinedGlobals) {
253 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
254 Hasher.update(
255 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
256 AddUsedCfiGlobal(GS.first);
257 AddUsedThings(GS.second);
260 // Imported functions may introduce new uses of type identifier resolutions,
261 // so we need to collect their used resolutions as well.
262 for (auto &ImpM : ImportList)
263 for (auto &ImpF : ImpM.second) {
264 GlobalValueSummary *S = Index.findSummaryInModule(ImpF, ImpM.first());
265 AddUsedThings(S);
266 // If this is an alias, we also care about any types/etc. that the aliasee
267 // may reference.
268 if (auto *AS = dyn_cast_or_null<AliasSummary>(S))
269 AddUsedThings(AS->getBaseObject());
272 auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
273 AddString(TId);
275 AddUnsigned(S.TTRes.TheKind);
276 AddUnsigned(S.TTRes.SizeM1BitWidth);
278 AddUint64(S.TTRes.AlignLog2);
279 AddUint64(S.TTRes.SizeM1);
280 AddUint64(S.TTRes.BitMask);
281 AddUint64(S.TTRes.InlineBits);
283 AddUint64(S.WPDRes.size());
284 for (auto &WPD : S.WPDRes) {
285 AddUnsigned(WPD.first);
286 AddUnsigned(WPD.second.TheKind);
287 AddString(WPD.second.SingleImplName);
289 AddUint64(WPD.second.ResByArg.size());
290 for (auto &ByArg : WPD.second.ResByArg) {
291 AddUint64(ByArg.first.size());
292 for (uint64_t Arg : ByArg.first)
293 AddUint64(Arg);
294 AddUnsigned(ByArg.second.TheKind);
295 AddUint64(ByArg.second.Info);
296 AddUnsigned(ByArg.second.Byte);
297 AddUnsigned(ByArg.second.Bit);
302 // Include the hash for all type identifiers used by this module.
303 for (GlobalValue::GUID TId : UsedTypeIds) {
304 auto TidIter = Index.typeIds().equal_range(TId);
305 for (auto It = TidIter.first; It != TidIter.second; ++It)
306 AddTypeIdSummary(It->second.first, It->second.second);
309 AddUnsigned(UsedCfiDefs.size());
310 for (auto &V : UsedCfiDefs)
311 AddUint64(V);
313 AddUnsigned(UsedCfiDecls.size());
314 for (auto &V : UsedCfiDecls)
315 AddUint64(V);
317 if (!Conf.SampleProfile.empty()) {
318 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
319 if (FileOrErr) {
320 Hasher.update(FileOrErr.get()->getBuffer());
322 if (!Conf.ProfileRemapping.empty()) {
323 FileOrErr = MemoryBuffer::getFile(Conf.ProfileRemapping);
324 if (FileOrErr)
325 Hasher.update(FileOrErr.get()->getBuffer());
330 Key = toHex(Hasher.result());
333 static void thinLTOResolvePrevailingGUID(
334 const Config &C, ValueInfo VI,
335 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
336 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
337 isPrevailing,
338 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
339 recordNewLinkage,
340 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
341 GlobalValue::VisibilityTypes Visibility =
342 C.VisibilityScheme == Config::ELF ? VI.getELFVisibility()
343 : GlobalValue::DefaultVisibility;
344 for (auto &S : VI.getSummaryList()) {
345 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
346 // Ignore local and appending linkage values since the linker
347 // doesn't resolve them.
348 if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
349 GlobalValue::isAppendingLinkage(S->linkage()))
350 continue;
351 // We need to emit only one of these. The prevailing module will keep it,
352 // but turned into a weak, while the others will drop it when possible.
353 // This is both a compile-time optimization and a correctness
354 // transformation. This is necessary for correctness when we have exported
355 // a reference - we need to convert the linkonce to weak to
356 // ensure a copy is kept to satisfy the exported reference.
357 // FIXME: We may want to split the compile time and correctness
358 // aspects into separate routines.
359 if (isPrevailing(VI.getGUID(), S.get())) {
360 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage)) {
361 S->setLinkage(GlobalValue::getWeakLinkage(
362 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
363 // The kept copy is eligible for auto-hiding (hidden visibility) if all
364 // copies were (i.e. they were all linkonce_odr global unnamed addr).
365 // If any copy is not (e.g. it was originally weak_odr), then the symbol
366 // must remain externally available (e.g. a weak_odr from an explicitly
367 // instantiated template). Additionally, if it is in the
368 // GUIDPreservedSymbols set, that means that it is visibile outside
369 // the summary (e.g. in a native object or a bitcode file without
370 // summary), and in that case we cannot hide it as it isn't possible to
371 // check all copies.
372 S->setCanAutoHide(VI.canAutoHide() &&
373 !GUIDPreservedSymbols.count(VI.getGUID()));
375 if (C.VisibilityScheme == Config::FromPrevailing)
376 Visibility = S->getVisibility();
378 // Alias and aliasee can't be turned into available_externally.
379 else if (!isa<AliasSummary>(S.get()) &&
380 !GlobalInvolvedWithAlias.count(S.get()))
381 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
383 // For ELF, set visibility to the computed visibility from summaries. We
384 // don't track visibility from declarations so this may be more relaxed than
385 // the most constraining one.
386 if (C.VisibilityScheme == Config::ELF)
387 S->setVisibility(Visibility);
389 if (S->linkage() != OriginalLinkage)
390 recordNewLinkage(S->modulePath(), VI.getGUID(), S->linkage());
393 if (C.VisibilityScheme == Config::FromPrevailing) {
394 for (auto &S : VI.getSummaryList()) {
395 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
396 if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
397 GlobalValue::isAppendingLinkage(S->linkage()))
398 continue;
399 S->setVisibility(Visibility);
404 /// Resolve linkage for prevailing symbols in the \p Index.
406 // We'd like to drop these functions if they are no longer referenced in the
407 // current module. However there is a chance that another module is still
408 // referencing them because of the import. We make sure we always emit at least
409 // one copy.
410 void llvm::thinLTOResolvePrevailingInIndex(
411 const Config &C, ModuleSummaryIndex &Index,
412 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
413 isPrevailing,
414 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
415 recordNewLinkage,
416 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
417 // We won't optimize the globals that are referenced by an alias for now
418 // Ideally we should turn the alias into a global and duplicate the definition
419 // when needed.
420 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
421 for (auto &I : Index)
422 for (auto &S : I.second.SummaryList)
423 if (auto AS = dyn_cast<AliasSummary>(S.get()))
424 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
426 for (auto &I : Index)
427 thinLTOResolvePrevailingGUID(C, Index.getValueInfo(I),
428 GlobalInvolvedWithAlias, isPrevailing,
429 recordNewLinkage, GUIDPreservedSymbols);
432 static bool isWeakObjectWithRWAccess(GlobalValueSummary *GVS) {
433 if (auto *VarSummary = dyn_cast<GlobalVarSummary>(GVS->getBaseObject()))
434 return !VarSummary->maybeReadOnly() && !VarSummary->maybeWriteOnly() &&
435 (VarSummary->linkage() == GlobalValue::WeakODRLinkage ||
436 VarSummary->linkage() == GlobalValue::LinkOnceODRLinkage);
437 return false;
440 static void thinLTOInternalizeAndPromoteGUID(
441 ValueInfo VI, function_ref<bool(StringRef, ValueInfo)> isExported,
442 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
443 isPrevailing) {
444 for (auto &S : VI.getSummaryList()) {
445 if (isExported(S->modulePath(), VI)) {
446 if (GlobalValue::isLocalLinkage(S->linkage()))
447 S->setLinkage(GlobalValue::ExternalLinkage);
448 } else if (EnableLTOInternalization &&
449 // Ignore local and appending linkage values since the linker
450 // doesn't resolve them.
451 !GlobalValue::isLocalLinkage(S->linkage()) &&
452 (!GlobalValue::isInterposableLinkage(S->linkage()) ||
453 isPrevailing(VI.getGUID(), S.get())) &&
454 S->linkage() != GlobalValue::AppendingLinkage &&
455 // We can't internalize available_externally globals because this
456 // can break function pointer equality.
457 S->linkage() != GlobalValue::AvailableExternallyLinkage &&
458 // Functions and read-only variables with linkonce_odr and
459 // weak_odr linkage can be internalized. We can't internalize
460 // linkonce_odr and weak_odr variables which are both modified
461 // and read somewhere in the program because reads and writes
462 // will become inconsistent.
463 !isWeakObjectWithRWAccess(S.get()))
464 S->setLinkage(GlobalValue::InternalLinkage);
468 // Update the linkages in the given \p Index to mark exported values
469 // as external and non-exported values as internal.
470 void llvm::thinLTOInternalizeAndPromoteInIndex(
471 ModuleSummaryIndex &Index,
472 function_ref<bool(StringRef, ValueInfo)> isExported,
473 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
474 isPrevailing) {
475 for (auto &I : Index)
476 thinLTOInternalizeAndPromoteGUID(Index.getValueInfo(I), isExported,
477 isPrevailing);
480 // Requires a destructor for std::vector<InputModule>.
481 InputFile::~InputFile() = default;
483 Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
484 std::unique_ptr<InputFile> File(new InputFile);
486 Expected<IRSymtabFile> FOrErr = readIRSymtab(Object);
487 if (!FOrErr)
488 return FOrErr.takeError();
490 File->TargetTriple = FOrErr->TheReader.getTargetTriple();
491 File->SourceFileName = FOrErr->TheReader.getSourceFileName();
492 File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
493 File->DependentLibraries = FOrErr->TheReader.getDependentLibraries();
494 File->ComdatTable = FOrErr->TheReader.getComdatTable();
496 for (unsigned I = 0; I != FOrErr->Mods.size(); ++I) {
497 size_t Begin = File->Symbols.size();
498 for (const irsymtab::Reader::SymbolRef &Sym :
499 FOrErr->TheReader.module_symbols(I))
500 // Skip symbols that are irrelevant to LTO. Note that this condition needs
501 // to match the one in Skip() in LTO::addRegularLTO().
502 if (Sym.isGlobal() && !Sym.isFormatSpecific())
503 File->Symbols.push_back(Sym);
504 File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
507 File->Mods = FOrErr->Mods;
508 File->Strtab = std::move(FOrErr->Strtab);
509 return std::move(File);
512 StringRef InputFile::getName() const {
513 return Mods[0].getModuleIdentifier();
516 BitcodeModule &InputFile::getSingleBitcodeModule() {
517 assert(Mods.size() == 1 && "Expect only one bitcode module");
518 return Mods[0];
521 LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
522 const Config &Conf)
523 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
524 Ctx(Conf), CombinedModule(std::make_unique<Module>("ld-temp.o", Ctx)),
525 Mover(std::make_unique<IRMover>(*CombinedModule)) {}
527 LTO::ThinLTOState::ThinLTOState(ThinBackend Backend)
528 : Backend(Backend), CombinedIndex(/*HaveGVs*/ false) {
529 if (!Backend)
530 this->Backend =
531 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
534 LTO::LTO(Config Conf, ThinBackend Backend,
535 unsigned ParallelCodeGenParallelismLevel)
536 : Conf(std::move(Conf)),
537 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
538 ThinLTO(std::move(Backend)) {}
540 // Requires a destructor for MapVector<BitcodeModule>.
541 LTO::~LTO() = default;
543 // Add the symbols in the given module to the GlobalResolutions map, and resolve
544 // their partitions.
545 void LTO::addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
546 ArrayRef<SymbolResolution> Res,
547 unsigned Partition, bool InSummary) {
548 auto *ResI = Res.begin();
549 auto *ResE = Res.end();
550 (void)ResE;
551 const Triple TT(RegularLTO.CombinedModule->getTargetTriple());
552 for (const InputFile::Symbol &Sym : Syms) {
553 assert(ResI != ResE);
554 SymbolResolution Res = *ResI++;
556 StringRef Name = Sym.getName();
557 // Strip the __imp_ prefix from COFF dllimport symbols (similar to the
558 // way they are handled by lld), otherwise we can end up with two
559 // global resolutions (one with and one for a copy of the symbol without).
560 if (TT.isOSBinFormatCOFF() && Name.startswith("__imp_"))
561 Name = Name.substr(strlen("__imp_"));
562 auto &GlobalRes = GlobalResolutions[Name];
563 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
564 if (Res.Prevailing) {
565 assert(!GlobalRes.Prevailing &&
566 "Multiple prevailing defs are not allowed");
567 GlobalRes.Prevailing = true;
568 GlobalRes.IRName = std::string(Sym.getIRName());
569 } else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
570 // Sometimes it can be two copies of symbol in a module and prevailing
571 // symbol can have no IR name. That might happen if symbol is defined in
572 // module level inline asm block. In case we have multiple modules with
573 // the same symbol we want to use IR name of the prevailing symbol.
574 // Otherwise, if we haven't seen a prevailing symbol, set the name so that
575 // we can later use it to check if there is any prevailing copy in IR.
576 GlobalRes.IRName = std::string(Sym.getIRName());
579 // In rare occasion, the symbol used to initialize GlobalRes has a different
580 // IRName from the inspected Symbol. This can happen on macOS + iOS, when a
581 // symbol is referenced through its mangled name, say @"\01_symbol" while
582 // the IRName is @symbol (the prefix underscore comes from MachO mangling).
583 // In that case, we have the same actual Symbol that can get two different
584 // GUID, leading to some invalid internalization. Workaround this by marking
585 // the GlobalRes external.
587 // FIXME: instead of this check, it would be desirable to compute GUIDs
588 // based on mangled name, but this requires an access to the Target Triple
589 // and would be relatively invasive on the codebase.
590 if (GlobalRes.IRName != Sym.getIRName()) {
591 GlobalRes.Partition = GlobalResolution::External;
592 GlobalRes.VisibleOutsideSummary = true;
595 // Set the partition to external if we know it is re-defined by the linker
596 // with -defsym or -wrap options, used elsewhere, e.g. it is visible to a
597 // regular object, is referenced from llvm.compiler.used/llvm.used, or was
598 // already recorded as being referenced from a different partition.
599 if (Res.LinkerRedefined || Res.VisibleToRegularObj || Sym.isUsed() ||
600 (GlobalRes.Partition != GlobalResolution::Unknown &&
601 GlobalRes.Partition != Partition)) {
602 GlobalRes.Partition = GlobalResolution::External;
603 } else
604 // First recorded reference, save the current partition.
605 GlobalRes.Partition = Partition;
607 // Flag as visible outside of summary if visible from a regular object or
608 // from a module that does not have a summary.
609 GlobalRes.VisibleOutsideSummary |=
610 (Res.VisibleToRegularObj || Sym.isUsed() || !InSummary);
612 GlobalRes.ExportDynamic |= Res.ExportDynamic;
616 static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
617 ArrayRef<SymbolResolution> Res) {
618 StringRef Path = Input->getName();
619 OS << Path << '\n';
620 auto ResI = Res.begin();
621 for (const InputFile::Symbol &Sym : Input->symbols()) {
622 assert(ResI != Res.end());
623 SymbolResolution Res = *ResI++;
625 OS << "-r=" << Path << ',' << Sym.getName() << ',';
626 if (Res.Prevailing)
627 OS << 'p';
628 if (Res.FinalDefinitionInLinkageUnit)
629 OS << 'l';
630 if (Res.VisibleToRegularObj)
631 OS << 'x';
632 if (Res.LinkerRedefined)
633 OS << 'r';
634 OS << '\n';
636 OS.flush();
637 assert(ResI == Res.end());
640 Error LTO::add(std::unique_ptr<InputFile> Input,
641 ArrayRef<SymbolResolution> Res) {
642 assert(!CalledGetMaxTasks);
644 if (Conf.ResolutionFile)
645 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
647 if (RegularLTO.CombinedModule->getTargetTriple().empty()) {
648 RegularLTO.CombinedModule->setTargetTriple(Input->getTargetTriple());
649 if (Triple(Input->getTargetTriple()).isOSBinFormatELF())
650 Conf.VisibilityScheme = Config::ELF;
653 const SymbolResolution *ResI = Res.begin();
654 for (unsigned I = 0; I != Input->Mods.size(); ++I)
655 if (Error Err = addModule(*Input, I, ResI, Res.end()))
656 return Err;
658 assert(ResI == Res.end());
659 return Error::success();
662 Error LTO::addModule(InputFile &Input, unsigned ModI,
663 const SymbolResolution *&ResI,
664 const SymbolResolution *ResE) {
665 Expected<BitcodeLTOInfo> LTOInfo = Input.Mods[ModI].getLTOInfo();
666 if (!LTOInfo)
667 return LTOInfo.takeError();
669 if (EnableSplitLTOUnit) {
670 // If only some modules were split, flag this in the index so that
671 // we can skip or error on optimizations that need consistently split
672 // modules (whole program devirt and lower type tests).
673 if (*EnableSplitLTOUnit != LTOInfo->EnableSplitLTOUnit)
674 ThinLTO.CombinedIndex.setPartiallySplitLTOUnits();
675 } else
676 EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
678 BitcodeModule BM = Input.Mods[ModI];
679 auto ModSyms = Input.module_symbols(ModI);
680 addModuleToGlobalRes(ModSyms, {ResI, ResE},
681 LTOInfo->IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0,
682 LTOInfo->HasSummary);
684 if (LTOInfo->IsThinLTO)
685 return addThinLTO(BM, ModSyms, ResI, ResE);
687 RegularLTO.EmptyCombinedModule = false;
688 Expected<RegularLTOState::AddedModule> ModOrErr =
689 addRegularLTO(BM, ModSyms, ResI, ResE);
690 if (!ModOrErr)
691 return ModOrErr.takeError();
693 if (!LTOInfo->HasSummary)
694 return linkRegularLTO(std::move(*ModOrErr), /*LivenessFromIndex=*/false);
696 // Regular LTO module summaries are added to a dummy module that represents
697 // the combined regular LTO module.
698 if (Error Err = BM.readSummary(ThinLTO.CombinedIndex, "", -1ull))
699 return Err;
700 RegularLTO.ModsWithSummaries.push_back(std::move(*ModOrErr));
701 return Error::success();
704 // Checks whether the given global value is in a non-prevailing comdat
705 // (comdat containing values the linker indicated were not prevailing,
706 // which we then dropped to available_externally), and if so, removes
707 // it from the comdat. This is called for all global values to ensure the
708 // comdat is empty rather than leaving an incomplete comdat. It is needed for
709 // regular LTO modules, in case we are in a mixed-LTO mode (both regular
710 // and thin LTO modules) compilation. Since the regular LTO module will be
711 // linked first in the final native link, we want to make sure the linker
712 // doesn't select any of these incomplete comdats that would be left
713 // in the regular LTO module without this cleanup.
714 static void
715 handleNonPrevailingComdat(GlobalValue &GV,
716 std::set<const Comdat *> &NonPrevailingComdats) {
717 Comdat *C = GV.getComdat();
718 if (!C)
719 return;
721 if (!NonPrevailingComdats.count(C))
722 return;
724 // Additionally need to drop all global values from the comdat to
725 // available_externally, to satisfy the COMDAT requirement that all members
726 // are discarded as a unit. The non-local linkage global values avoid
727 // duplicate definition linker errors.
728 GV.setLinkage(GlobalValue::AvailableExternallyLinkage);
730 if (auto GO = dyn_cast<GlobalObject>(&GV))
731 GO->setComdat(nullptr);
734 // Add a regular LTO object to the link.
735 // The resulting module needs to be linked into the combined LTO module with
736 // linkRegularLTO.
737 Expected<LTO::RegularLTOState::AddedModule>
738 LTO::addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
739 const SymbolResolution *&ResI,
740 const SymbolResolution *ResE) {
741 RegularLTOState::AddedModule Mod;
742 Expected<std::unique_ptr<Module>> MOrErr =
743 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
744 /*IsImporting*/ false);
745 if (!MOrErr)
746 return MOrErr.takeError();
747 Module &M = **MOrErr;
748 Mod.M = std::move(*MOrErr);
750 if (Error Err = M.materializeMetadata())
751 return std::move(Err);
752 UpgradeDebugInfo(M);
754 ModuleSymbolTable SymTab;
755 SymTab.addModule(&M);
757 for (GlobalVariable &GV : M.globals())
758 if (GV.hasAppendingLinkage())
759 Mod.Keep.push_back(&GV);
761 DenseSet<GlobalObject *> AliasedGlobals;
762 for (auto &GA : M.aliases())
763 if (GlobalObject *GO = GA.getAliaseeObject())
764 AliasedGlobals.insert(GO);
766 // In this function we need IR GlobalValues matching the symbols in Syms
767 // (which is not backed by a module), so we need to enumerate them in the same
768 // order. The symbol enumeration order of a ModuleSymbolTable intentionally
769 // matches the order of an irsymtab, but when we read the irsymtab in
770 // InputFile::create we omit some symbols that are irrelevant to LTO. The
771 // Skip() function skips the same symbols from the module as InputFile does
772 // from the symbol table.
773 auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
774 auto Skip = [&]() {
775 while (MsymI != MsymE) {
776 auto Flags = SymTab.getSymbolFlags(*MsymI);
777 if ((Flags & object::BasicSymbolRef::SF_Global) &&
778 !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
779 return;
780 ++MsymI;
783 Skip();
785 std::set<const Comdat *> NonPrevailingComdats;
786 SmallSet<StringRef, 2> NonPrevailingAsmSymbols;
787 for (const InputFile::Symbol &Sym : Syms) {
788 assert(ResI != ResE);
789 SymbolResolution Res = *ResI++;
791 assert(MsymI != MsymE);
792 ModuleSymbolTable::Symbol Msym = *MsymI++;
793 Skip();
795 if (GlobalValue *GV = dyn_cast_if_present<GlobalValue *>(Msym)) {
796 if (Res.Prevailing) {
797 if (Sym.isUndefined())
798 continue;
799 Mod.Keep.push_back(GV);
800 // For symbols re-defined with linker -wrap and -defsym options,
801 // set the linkage to weak to inhibit IPO. The linkage will be
802 // restored by the linker.
803 if (Res.LinkerRedefined)
804 GV->setLinkage(GlobalValue::WeakAnyLinkage);
806 GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage();
807 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
808 GV->setLinkage(GlobalValue::getWeakLinkage(
809 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
810 } else if (isa<GlobalObject>(GV) &&
811 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
812 GV->hasAvailableExternallyLinkage()) &&
813 !AliasedGlobals.count(cast<GlobalObject>(GV))) {
814 // Any of the above three types of linkage indicates that the
815 // chosen prevailing symbol will have the same semantics as this copy of
816 // the symbol, so we may be able to link it with available_externally
817 // linkage. We will decide later whether to do that when we link this
818 // module (in linkRegularLTO), based on whether it is undefined.
819 Mod.Keep.push_back(GV);
820 GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
821 if (GV->hasComdat())
822 NonPrevailingComdats.insert(GV->getComdat());
823 cast<GlobalObject>(GV)->setComdat(nullptr);
826 // Set the 'local' flag based on the linker resolution for this symbol.
827 if (Res.FinalDefinitionInLinkageUnit) {
828 GV->setDSOLocal(true);
829 if (GV->hasDLLImportStorageClass())
830 GV->setDLLStorageClass(GlobalValue::DLLStorageClassTypes::
831 DefaultStorageClass);
833 } else if (auto *AS =
834 dyn_cast_if_present<ModuleSymbolTable::AsmSymbol *>(Msym)) {
835 // Collect non-prevailing symbols.
836 if (!Res.Prevailing)
837 NonPrevailingAsmSymbols.insert(AS->first);
838 } else {
839 llvm_unreachable("unknown symbol type");
842 // Common resolution: collect the maximum size/alignment over all commons.
843 // We also record if we see an instance of a common as prevailing, so that
844 // if none is prevailing we can ignore it later.
845 if (Sym.isCommon()) {
846 // FIXME: We should figure out what to do about commons defined by asm.
847 // For now they aren't reported correctly by ModuleSymbolTable.
848 auto &CommonRes = RegularLTO.Commons[std::string(Sym.getIRName())];
849 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
850 if (uint32_t SymAlignValue = Sym.getCommonAlignment()) {
851 CommonRes.Alignment =
852 std::max(Align(SymAlignValue), CommonRes.Alignment);
854 CommonRes.Prevailing |= Res.Prevailing;
858 if (!M.getComdatSymbolTable().empty())
859 for (GlobalValue &GV : M.global_values())
860 handleNonPrevailingComdat(GV, NonPrevailingComdats);
862 // Prepend ".lto_discard <sym>, <sym>*" directive to each module inline asm
863 // block.
864 if (!M.getModuleInlineAsm().empty()) {
865 std::string NewIA = ".lto_discard";
866 if (!NonPrevailingAsmSymbols.empty()) {
867 // Don't dicard a symbol if there is a live .symver for it.
868 ModuleSymbolTable::CollectAsmSymvers(
869 M, [&](StringRef Name, StringRef Alias) {
870 if (!NonPrevailingAsmSymbols.count(Alias))
871 NonPrevailingAsmSymbols.erase(Name);
873 NewIA += " " + llvm::join(NonPrevailingAsmSymbols, ", ");
875 NewIA += "\n";
876 M.setModuleInlineAsm(NewIA + M.getModuleInlineAsm());
879 assert(MsymI == MsymE);
880 return std::move(Mod);
883 Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod,
884 bool LivenessFromIndex) {
885 std::vector<GlobalValue *> Keep;
886 for (GlobalValue *GV : Mod.Keep) {
887 if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->getGUID())) {
888 if (Function *F = dyn_cast<Function>(GV)) {
889 if (DiagnosticOutputFile) {
890 if (Error Err = F->materialize())
891 return Err;
892 OptimizationRemarkEmitter ORE(F, nullptr);
893 ORE.emit(OptimizationRemark(DEBUG_TYPE, "deadfunction", F)
894 << ore::NV("Function", F)
895 << " not added to the combined module ");
898 continue;
901 if (!GV->hasAvailableExternallyLinkage()) {
902 Keep.push_back(GV);
903 continue;
906 // Only link available_externally definitions if we don't already have a
907 // definition.
908 GlobalValue *CombinedGV =
909 RegularLTO.CombinedModule->getNamedValue(GV->getName());
910 if (CombinedGV && !CombinedGV->isDeclaration())
911 continue;
913 Keep.push_back(GV);
916 return RegularLTO.Mover->move(std::move(Mod.M), Keep, nullptr,
917 /* IsPerformingImport */ false);
920 // Add a ThinLTO module to the link.
921 Error LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
922 const SymbolResolution *&ResI,
923 const SymbolResolution *ResE) {
924 const SymbolResolution *ResITmp = ResI;
925 for (const InputFile::Symbol &Sym : Syms) {
926 assert(ResITmp != ResE);
927 SymbolResolution Res = *ResITmp++;
929 if (!Sym.getIRName().empty()) {
930 auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
931 Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
932 if (Res.Prevailing)
933 ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
937 uint64_t ModuleId = ThinLTO.ModuleMap.size();
938 if (Error Err =
939 BM.readSummary(ThinLTO.CombinedIndex, BM.getModuleIdentifier(),
940 ModuleId, [&](GlobalValue::GUID GUID) {
941 return ThinLTO.PrevailingModuleForGUID[GUID] ==
942 BM.getModuleIdentifier();
944 return Err;
945 LLVM_DEBUG(dbgs() << "Module " << ModuleId << ": " << BM.getModuleIdentifier()
946 << "\n");
948 for (const InputFile::Symbol &Sym : Syms) {
949 assert(ResI != ResE);
950 SymbolResolution Res = *ResI++;
952 if (!Sym.getIRName().empty()) {
953 auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
954 Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
955 if (Res.Prevailing) {
956 assert(ThinLTO.PrevailingModuleForGUID[GUID] ==
957 BM.getModuleIdentifier());
959 // For linker redefined symbols (via --wrap or --defsym) we want to
960 // switch the linkage to `weak` to prevent IPOs from happening.
961 // Find the summary in the module for this very GV and record the new
962 // linkage so that we can switch it when we import the GV.
963 if (Res.LinkerRedefined)
964 if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
965 GUID, BM.getModuleIdentifier()))
966 S->setLinkage(GlobalValue::WeakAnyLinkage);
969 // If the linker resolved the symbol to a local definition then mark it
970 // as local in the summary for the module we are adding.
971 if (Res.FinalDefinitionInLinkageUnit) {
972 if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
973 GUID, BM.getModuleIdentifier())) {
974 S->setDSOLocal(true);
980 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
981 return make_error<StringError>(
982 "Expected at most one ThinLTO module per bitcode file",
983 inconvertibleErrorCode());
985 if (!Conf.ThinLTOModulesToCompile.empty()) {
986 if (!ThinLTO.ModulesToCompile)
987 ThinLTO.ModulesToCompile = ModuleMapType();
988 // This is a fuzzy name matching where only modules with name containing the
989 // specified switch values are going to be compiled.
990 for (const std::string &Name : Conf.ThinLTOModulesToCompile) {
991 if (BM.getModuleIdentifier().contains(Name)) {
992 ThinLTO.ModulesToCompile->insert({BM.getModuleIdentifier(), BM});
993 llvm::errs() << "[ThinLTO] Selecting " << BM.getModuleIdentifier()
994 << " to compile\n";
999 return Error::success();
1002 unsigned LTO::getMaxTasks() const {
1003 CalledGetMaxTasks = true;
1004 auto ModuleCount = ThinLTO.ModulesToCompile ? ThinLTO.ModulesToCompile->size()
1005 : ThinLTO.ModuleMap.size();
1006 return RegularLTO.ParallelCodeGenParallelismLevel + ModuleCount;
1009 // If only some of the modules were split, we cannot correctly handle
1010 // code that contains type tests or type checked loads.
1011 Error LTO::checkPartiallySplit() {
1012 if (!ThinLTO.CombinedIndex.partiallySplitLTOUnits())
1013 return Error::success();
1015 Function *TypeTestFunc = RegularLTO.CombinedModule->getFunction(
1016 Intrinsic::getName(Intrinsic::type_test));
1017 Function *TypeCheckedLoadFunc = RegularLTO.CombinedModule->getFunction(
1018 Intrinsic::getName(Intrinsic::type_checked_load));
1020 // First check if there are type tests / type checked loads in the
1021 // merged regular LTO module IR.
1022 if ((TypeTestFunc && !TypeTestFunc->use_empty()) ||
1023 (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty()))
1024 return make_error<StringError>(
1025 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1026 inconvertibleErrorCode());
1028 // Otherwise check if there are any recorded in the combined summary from the
1029 // ThinLTO modules.
1030 for (auto &P : ThinLTO.CombinedIndex) {
1031 for (auto &S : P.second.SummaryList) {
1032 auto *FS = dyn_cast<FunctionSummary>(S.get());
1033 if (!FS)
1034 continue;
1035 if (!FS->type_test_assume_vcalls().empty() ||
1036 !FS->type_checked_load_vcalls().empty() ||
1037 !FS->type_test_assume_const_vcalls().empty() ||
1038 !FS->type_checked_load_const_vcalls().empty() ||
1039 !FS->type_tests().empty())
1040 return make_error<StringError>(
1041 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1042 inconvertibleErrorCode());
1045 return Error::success();
1048 Error LTO::run(AddStreamFn AddStream, FileCache Cache) {
1049 // Compute "dead" symbols, we don't want to import/export these!
1050 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
1051 DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions;
1052 for (auto &Res : GlobalResolutions) {
1053 // Normally resolution have IR name of symbol. We can do nothing here
1054 // otherwise. See comments in GlobalResolution struct for more details.
1055 if (Res.second.IRName.empty())
1056 continue;
1058 GlobalValue::GUID GUID = GlobalValue::getGUID(
1059 GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
1061 if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
1062 GUIDPreservedSymbols.insert(GUID);
1064 if (Res.second.ExportDynamic)
1065 DynamicExportSymbols.insert(GUID);
1067 GUIDPrevailingResolutions[GUID] =
1068 Res.second.Prevailing ? PrevailingType::Yes : PrevailingType::No;
1071 auto isPrevailing = [&](GlobalValue::GUID G) {
1072 auto It = GUIDPrevailingResolutions.find(G);
1073 if (It == GUIDPrevailingResolutions.end())
1074 return PrevailingType::Unknown;
1075 return It->second;
1077 computeDeadSymbolsWithConstProp(ThinLTO.CombinedIndex, GUIDPreservedSymbols,
1078 isPrevailing, Conf.OptLevel > 0);
1080 // Setup output file to emit statistics.
1081 auto StatsFileOrErr = setupStatsFile(Conf.StatsFile);
1082 if (!StatsFileOrErr)
1083 return StatsFileOrErr.takeError();
1084 std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
1086 // TODO: Ideally this would be controlled automatically by detecting that we
1087 // are linking with an allocator that supports these interfaces, rather than
1088 // an internal option (which would still be needed for tests, however). For
1089 // example, if the library exported a symbol like __malloc_hot_cold the linker
1090 // could recognize that and set a flag in the lto::Config.
1091 if (SupportsHotColdNew)
1092 ThinLTO.CombinedIndex.setWithSupportsHotColdNew();
1094 Error Result = runRegularLTO(AddStream);
1095 if (!Result)
1096 Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
1098 if (StatsFile)
1099 PrintStatisticsJSON(StatsFile->os());
1101 return Result;
1104 void lto::updateMemProfAttributes(Module &Mod,
1105 const ModuleSummaryIndex &Index) {
1106 if (Index.withSupportsHotColdNew())
1107 return;
1109 // The profile matcher applies hotness attributes directly for allocations,
1110 // and those will cause us to generate calls to the hot/cold interfaces
1111 // unconditionally. If supports-hot-cold-new was not enabled in the LTO
1112 // link then assume we don't want these calls (e.g. not linking with
1113 // the appropriate library, or otherwise trying to disable this behavior).
1114 for (auto &F : Mod) {
1115 for (auto &BB : F) {
1116 for (auto &I : BB) {
1117 auto *CI = dyn_cast<CallBase>(&I);
1118 if (!CI)
1119 continue;
1120 if (CI->hasFnAttr("memprof"))
1121 CI->removeFnAttr("memprof");
1122 // Strip off all memprof metadata as it is no longer needed.
1123 // Importantly, this avoids the addition of new memprof attributes
1124 // after inlining propagation.
1125 // TODO: If we support additional types of MemProf metadata beyond hot
1126 // and cold, we will need to update the metadata based on the allocator
1127 // APIs supported instead of completely stripping all.
1128 CI->setMetadata(LLVMContext::MD_memprof, nullptr);
1129 CI->setMetadata(LLVMContext::MD_callsite, nullptr);
1135 Error LTO::runRegularLTO(AddStreamFn AddStream) {
1136 // Setup optimization remarks.
1137 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
1138 RegularLTO.CombinedModule->getContext(), Conf.RemarksFilename,
1139 Conf.RemarksPasses, Conf.RemarksFormat, Conf.RemarksWithHotness,
1140 Conf.RemarksHotnessThreshold);
1141 if (!DiagFileOrErr)
1142 return DiagFileOrErr.takeError();
1143 DiagnosticOutputFile = std::move(*DiagFileOrErr);
1145 // Finalize linking of regular LTO modules containing summaries now that
1146 // we have computed liveness information.
1147 for (auto &M : RegularLTO.ModsWithSummaries)
1148 if (Error Err = linkRegularLTO(std::move(M),
1149 /*LivenessFromIndex=*/true))
1150 return Err;
1152 // Ensure we don't have inconsistently split LTO units with type tests.
1153 // FIXME: this checks both LTO and ThinLTO. It happens to work as we take
1154 // this path both cases but eventually this should be split into two and
1155 // do the ThinLTO checks in `runThinLTO`.
1156 if (Error Err = checkPartiallySplit())
1157 return Err;
1159 // Make sure commons have the right size/alignment: we kept the largest from
1160 // all the prevailing when adding the inputs, and we apply it here.
1161 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
1162 for (auto &I : RegularLTO.Commons) {
1163 if (!I.second.Prevailing)
1164 // Don't do anything if no instance of this common was prevailing.
1165 continue;
1166 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
1167 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
1168 // Don't create a new global if the type is already correct, just make
1169 // sure the alignment is correct.
1170 OldGV->setAlignment(I.second.Alignment);
1171 continue;
1173 ArrayType *Ty =
1174 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
1175 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
1176 GlobalValue::CommonLinkage,
1177 ConstantAggregateZero::get(Ty), "");
1178 GV->setAlignment(I.second.Alignment);
1179 if (OldGV) {
1180 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
1181 GV->takeName(OldGV);
1182 OldGV->eraseFromParent();
1183 } else {
1184 GV->setName(I.first);
1188 updateMemProfAttributes(*RegularLTO.CombinedModule, ThinLTO.CombinedIndex);
1190 // If allowed, upgrade public vcall visibility metadata to linkage unit
1191 // visibility before whole program devirtualization in the optimizer.
1192 updateVCallVisibilityInModule(*RegularLTO.CombinedModule,
1193 Conf.HasWholeProgramVisibility,
1194 DynamicExportSymbols);
1195 updatePublicTypeTestCalls(*RegularLTO.CombinedModule,
1196 Conf.HasWholeProgramVisibility);
1198 if (Conf.PreOptModuleHook &&
1199 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
1200 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
1202 if (!Conf.CodeGenOnly) {
1203 for (const auto &R : GlobalResolutions) {
1204 if (!R.second.isPrevailingIRSymbol())
1205 continue;
1206 if (R.second.Partition != 0 &&
1207 R.second.Partition != GlobalResolution::External)
1208 continue;
1210 GlobalValue *GV =
1211 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
1212 // Ignore symbols defined in other partitions.
1213 // Also skip declarations, which are not allowed to have internal linkage.
1214 if (!GV || GV->hasLocalLinkage() || GV->isDeclaration())
1215 continue;
1216 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
1217 : GlobalValue::UnnamedAddr::None);
1218 if (EnableLTOInternalization && R.second.Partition == 0)
1219 GV->setLinkage(GlobalValue::InternalLinkage);
1222 RegularLTO.CombinedModule->addModuleFlag(Module::Error, "LTOPostLink", 1);
1224 if (Conf.PostInternalizeModuleHook &&
1225 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
1226 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
1229 if (!RegularLTO.EmptyCombinedModule || Conf.AlwaysEmitRegularLTOObj) {
1230 if (Error Err =
1231 backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
1232 *RegularLTO.CombinedModule, ThinLTO.CombinedIndex))
1233 return Err;
1236 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
1239 static const char *libcallRoutineNames[] = {
1240 #define HANDLE_LIBCALL(code, name) name,
1241 #include "llvm/IR/RuntimeLibcalls.def"
1242 #undef HANDLE_LIBCALL
1245 ArrayRef<const char*> LTO::getRuntimeLibcallSymbols() {
1246 return ArrayRef(libcallRoutineNames);
1249 /// This class defines the interface to the ThinLTO backend.
1250 class lto::ThinBackendProc {
1251 protected:
1252 const Config &Conf;
1253 ModuleSummaryIndex &CombinedIndex;
1254 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
1255 lto::IndexWriteCallback OnWrite;
1256 bool ShouldEmitImportsFiles;
1258 public:
1259 ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1260 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1261 lto::IndexWriteCallback OnWrite, bool ShouldEmitImportsFiles)
1262 : Conf(Conf), CombinedIndex(CombinedIndex),
1263 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries),
1264 OnWrite(OnWrite), ShouldEmitImportsFiles(ShouldEmitImportsFiles) {}
1266 virtual ~ThinBackendProc() = default;
1267 virtual Error start(
1268 unsigned Task, BitcodeModule BM,
1269 const FunctionImporter::ImportMapTy &ImportList,
1270 const FunctionImporter::ExportSetTy &ExportList,
1271 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1272 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
1273 virtual Error wait() = 0;
1274 virtual unsigned getThreadCount() = 0;
1276 // Write sharded indices and (optionally) imports to disk
1277 Error emitFiles(const FunctionImporter::ImportMapTy &ImportList,
1278 llvm::StringRef ModulePath,
1279 const std::string &NewModulePath) {
1280 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
1281 std::error_code EC;
1282 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
1283 ImportList, ModuleToSummariesForIndex);
1285 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
1286 sys::fs::OpenFlags::OF_None);
1287 if (EC)
1288 return errorCodeToError(EC);
1289 writeIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
1291 if (ShouldEmitImportsFiles) {
1292 EC = EmitImportsFiles(ModulePath, NewModulePath + ".imports",
1293 ModuleToSummariesForIndex);
1294 if (EC)
1295 return errorCodeToError(EC);
1297 return Error::success();
1301 namespace {
1302 class InProcessThinBackend : public ThinBackendProc {
1303 ThreadPool BackendThreadPool;
1304 AddStreamFn AddStream;
1305 FileCache Cache;
1306 std::set<GlobalValue::GUID> CfiFunctionDefs;
1307 std::set<GlobalValue::GUID> CfiFunctionDecls;
1309 std::optional<Error> Err;
1310 std::mutex ErrMu;
1312 bool ShouldEmitIndexFiles;
1314 public:
1315 InProcessThinBackend(
1316 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1317 ThreadPoolStrategy ThinLTOParallelism,
1318 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1319 AddStreamFn AddStream, FileCache Cache, lto::IndexWriteCallback OnWrite,
1320 bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles)
1321 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
1322 OnWrite, ShouldEmitImportsFiles),
1323 BackendThreadPool(ThinLTOParallelism), AddStream(std::move(AddStream)),
1324 Cache(std::move(Cache)), ShouldEmitIndexFiles(ShouldEmitIndexFiles) {
1325 for (auto &Name : CombinedIndex.cfiFunctionDefs())
1326 CfiFunctionDefs.insert(
1327 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
1328 for (auto &Name : CombinedIndex.cfiFunctionDecls())
1329 CfiFunctionDecls.insert(
1330 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
1333 Error runThinLTOBackendThread(
1334 AddStreamFn AddStream, FileCache Cache, unsigned Task, BitcodeModule BM,
1335 ModuleSummaryIndex &CombinedIndex,
1336 const FunctionImporter::ImportMapTy &ImportList,
1337 const FunctionImporter::ExportSetTy &ExportList,
1338 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1339 const GVSummaryMapTy &DefinedGlobals,
1340 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1341 auto RunThinBackend = [&](AddStreamFn AddStream) {
1342 LTOLLVMContext BackendContext(Conf);
1343 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
1344 if (!MOrErr)
1345 return MOrErr.takeError();
1347 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
1348 ImportList, DefinedGlobals, &ModuleMap);
1351 auto ModuleID = BM.getModuleIdentifier();
1353 if (ShouldEmitIndexFiles) {
1354 if (auto E = emitFiles(ImportList, ModuleID, ModuleID.str()))
1355 return E;
1358 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
1359 all_of(CombinedIndex.getModuleHash(ModuleID),
1360 [](uint32_t V) { return V == 0; }))
1361 // Cache disabled or no entry for this module in the combined index or
1362 // no module hash.
1363 return RunThinBackend(AddStream);
1365 SmallString<40> Key;
1366 // The module may be cached, this helps handling it.
1367 computeLTOCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList,
1368 ExportList, ResolvedODR, DefinedGlobals, CfiFunctionDefs,
1369 CfiFunctionDecls);
1370 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task, Key, ModuleID);
1371 if (Error Err = CacheAddStreamOrErr.takeError())
1372 return Err;
1373 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1374 if (CacheAddStream)
1375 return RunThinBackend(CacheAddStream);
1377 return Error::success();
1380 Error start(
1381 unsigned Task, BitcodeModule BM,
1382 const FunctionImporter::ImportMapTy &ImportList,
1383 const FunctionImporter::ExportSetTy &ExportList,
1384 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1385 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1386 StringRef ModulePath = BM.getModuleIdentifier();
1387 assert(ModuleToDefinedGVSummaries.count(ModulePath));
1388 const GVSummaryMapTy &DefinedGlobals =
1389 ModuleToDefinedGVSummaries.find(ModulePath)->second;
1390 BackendThreadPool.async(
1391 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1392 const FunctionImporter::ImportMapTy &ImportList,
1393 const FunctionImporter::ExportSetTy &ExportList,
1394 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1395 &ResolvedODR,
1396 const GVSummaryMapTy &DefinedGlobals,
1397 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1398 if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1399 timeTraceProfilerInitialize(Conf.TimeTraceGranularity,
1400 "thin backend");
1401 Error E = runThinLTOBackendThread(
1402 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1403 ResolvedODR, DefinedGlobals, ModuleMap);
1404 if (E) {
1405 std::unique_lock<std::mutex> L(ErrMu);
1406 if (Err)
1407 Err = joinErrors(std::move(*Err), std::move(E));
1408 else
1409 Err = std::move(E);
1411 if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1412 timeTraceProfilerFinishThread();
1414 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
1415 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
1417 if (OnWrite)
1418 OnWrite(std::string(ModulePath));
1419 return Error::success();
1422 Error wait() override {
1423 BackendThreadPool.wait();
1424 if (Err)
1425 return std::move(*Err);
1426 else
1427 return Error::success();
1430 unsigned getThreadCount() override {
1431 return BackendThreadPool.getThreadCount();
1434 } // end anonymous namespace
1436 ThinBackend lto::createInProcessThinBackend(ThreadPoolStrategy Parallelism,
1437 lto::IndexWriteCallback OnWrite,
1438 bool ShouldEmitIndexFiles,
1439 bool ShouldEmitImportsFiles) {
1440 return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1441 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1442 AddStreamFn AddStream, FileCache Cache) {
1443 return std::make_unique<InProcessThinBackend>(
1444 Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries, AddStream,
1445 Cache, OnWrite, ShouldEmitIndexFiles, ShouldEmitImportsFiles);
1449 // Given the original \p Path to an output file, replace any path
1450 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
1451 // resulting directory if it does not yet exist.
1452 std::string lto::getThinLTOOutputFile(StringRef Path, StringRef OldPrefix,
1453 StringRef NewPrefix) {
1454 if (OldPrefix.empty() && NewPrefix.empty())
1455 return std::string(Path);
1456 SmallString<128> NewPath(Path);
1457 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
1458 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
1459 if (!ParentPath.empty()) {
1460 // Make sure the new directory exists, creating it if necessary.
1461 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
1462 llvm::errs() << "warning: could not create directory '" << ParentPath
1463 << "': " << EC.message() << '\n';
1465 return std::string(NewPath.str());
1468 namespace {
1469 class WriteIndexesThinBackend : public ThinBackendProc {
1470 std::string OldPrefix, NewPrefix, NativeObjectPrefix;
1471 raw_fd_ostream *LinkedObjectsFile;
1473 public:
1474 WriteIndexesThinBackend(
1475 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1476 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1477 std::string OldPrefix, std::string NewPrefix,
1478 std::string NativeObjectPrefix, bool ShouldEmitImportsFiles,
1479 raw_fd_ostream *LinkedObjectsFile, lto::IndexWriteCallback OnWrite)
1480 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
1481 OnWrite, ShouldEmitImportsFiles),
1482 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
1483 NativeObjectPrefix(NativeObjectPrefix),
1484 LinkedObjectsFile(LinkedObjectsFile) {}
1486 Error start(
1487 unsigned Task, BitcodeModule BM,
1488 const FunctionImporter::ImportMapTy &ImportList,
1489 const FunctionImporter::ExportSetTy &ExportList,
1490 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1491 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1492 StringRef ModulePath = BM.getModuleIdentifier();
1493 std::string NewModulePath =
1494 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
1496 if (LinkedObjectsFile) {
1497 std::string ObjectPrefix =
1498 NativeObjectPrefix.empty() ? NewPrefix : NativeObjectPrefix;
1499 std::string LinkedObjectsFilePath =
1500 getThinLTOOutputFile(ModulePath, OldPrefix, ObjectPrefix);
1501 *LinkedObjectsFile << LinkedObjectsFilePath << '\n';
1504 if (auto E = emitFiles(ImportList, ModulePath, NewModulePath))
1505 return E;
1507 if (OnWrite)
1508 OnWrite(std::string(ModulePath));
1509 return Error::success();
1512 Error wait() override { return Error::success(); }
1514 // WriteIndexesThinBackend should always return 1 to prevent module
1515 // re-ordering and avoid non-determinism in the final link.
1516 unsigned getThreadCount() override { return 1; }
1518 } // end anonymous namespace
1520 ThinBackend lto::createWriteIndexesThinBackend(
1521 std::string OldPrefix, std::string NewPrefix,
1522 std::string NativeObjectPrefix, bool ShouldEmitImportsFiles,
1523 raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite) {
1524 return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1525 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1526 AddStreamFn AddStream, FileCache Cache) {
1527 return std::make_unique<WriteIndexesThinBackend>(
1528 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
1529 NativeObjectPrefix, ShouldEmitImportsFiles, LinkedObjectsFile, OnWrite);
1533 Error LTO::runThinLTO(AddStreamFn AddStream, FileCache Cache,
1534 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
1535 ThinLTO.CombinedIndex.releaseTemporaryMemory();
1536 timeTraceProfilerBegin("ThinLink", StringRef(""));
1537 auto TimeTraceScopeExit = llvm::make_scope_exit([]() {
1538 if (llvm::timeTraceProfilerEnabled())
1539 llvm::timeTraceProfilerEnd();
1541 if (ThinLTO.ModuleMap.empty())
1542 return Error::success();
1544 if (ThinLTO.ModulesToCompile && ThinLTO.ModulesToCompile->empty()) {
1545 llvm::errs() << "warning: [ThinLTO] No module compiled\n";
1546 return Error::success();
1549 if (Conf.CombinedIndexHook &&
1550 !Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols))
1551 return Error::success();
1553 // Collect for each module the list of function it defines (GUID ->
1554 // Summary).
1555 StringMap<GVSummaryMapTy>
1556 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
1557 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
1558 ModuleToDefinedGVSummaries);
1559 // Create entries for any modules that didn't have any GV summaries
1560 // (either they didn't have any GVs to start with, or we suppressed
1561 // generation of the summaries because they e.g. had inline assembly
1562 // uses that couldn't be promoted/renamed on export). This is so
1563 // InProcessThinBackend::start can still launch a backend thread, which
1564 // is passed the map of summaries for the module, without any special
1565 // handling for this case.
1566 for (auto &Mod : ThinLTO.ModuleMap)
1567 if (!ModuleToDefinedGVSummaries.count(Mod.first))
1568 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
1570 // Synthesize entry counts for functions in the CombinedIndex.
1571 computeSyntheticCounts(ThinLTO.CombinedIndex);
1573 StringMap<FunctionImporter::ImportMapTy> ImportLists(
1574 ThinLTO.ModuleMap.size());
1575 StringMap<FunctionImporter::ExportSetTy> ExportLists(
1576 ThinLTO.ModuleMap.size());
1577 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
1579 if (DumpThinCGSCCs)
1580 ThinLTO.CombinedIndex.dumpSCCs(outs());
1582 std::set<GlobalValue::GUID> ExportedGUIDs;
1584 if (hasWholeProgramVisibility(Conf.HasWholeProgramVisibility))
1585 ThinLTO.CombinedIndex.setWithWholeProgramVisibility();
1586 // If allowed, upgrade public vcall visibility to linkage unit visibility in
1587 // the summaries before whole program devirtualization below.
1588 updateVCallVisibilityInIndex(ThinLTO.CombinedIndex,
1589 Conf.HasWholeProgramVisibility,
1590 DynamicExportSymbols);
1592 // Perform index-based WPD. This will return immediately if there are
1593 // no index entries in the typeIdMetadata map (e.g. if we are instead
1594 // performing IR-based WPD in hybrid regular/thin LTO mode).
1595 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1596 runWholeProgramDevirtOnIndex(ThinLTO.CombinedIndex, ExportedGUIDs,
1597 LocalWPDTargetsMap);
1599 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
1600 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1602 if (EnableMemProfContextDisambiguation) {
1603 MemProfContextDisambiguation ContextDisambiguation;
1604 ContextDisambiguation.run(ThinLTO.CombinedIndex, isPrevailing);
1607 if (Conf.OptLevel > 0)
1608 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1609 isPrevailing, ImportLists, ExportLists);
1611 // Figure out which symbols need to be internalized. This also needs to happen
1612 // at -O0 because summary-based DCE is implemented using internalization, and
1613 // we must apply DCE consistently with the full LTO module in order to avoid
1614 // undefined references during the final link.
1615 for (auto &Res : GlobalResolutions) {
1616 // If the symbol does not have external references or it is not prevailing,
1617 // then not need to mark it as exported from a ThinLTO partition.
1618 if (Res.second.Partition != GlobalResolution::External ||
1619 !Res.second.isPrevailingIRSymbol())
1620 continue;
1621 auto GUID = GlobalValue::getGUID(
1622 GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
1623 // Mark exported unless index-based analysis determined it to be dead.
1624 if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
1625 ExportedGUIDs.insert(GUID);
1628 // Any functions referenced by the jump table in the regular LTO object must
1629 // be exported.
1630 for (auto &Def : ThinLTO.CombinedIndex.cfiFunctionDefs())
1631 ExportedGUIDs.insert(
1632 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Def)));
1633 for (auto &Decl : ThinLTO.CombinedIndex.cfiFunctionDecls())
1634 ExportedGUIDs.insert(
1635 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Decl)));
1637 auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
1638 const auto &ExportList = ExportLists.find(ModuleIdentifier);
1639 return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
1640 ExportedGUIDs.count(VI.getGUID());
1643 // Update local devirtualized targets that were exported by cross-module
1644 // importing or by other devirtualizations marked in the ExportedGUIDs set.
1645 updateIndexWPDForExports(ThinLTO.CombinedIndex, isExported,
1646 LocalWPDTargetsMap);
1648 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported,
1649 isPrevailing);
1651 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1652 GlobalValue::GUID GUID,
1653 GlobalValue::LinkageTypes NewLinkage) {
1654 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1656 thinLTOResolvePrevailingInIndex(Conf, ThinLTO.CombinedIndex, isPrevailing,
1657 recordNewLinkage, GUIDPreservedSymbols);
1659 thinLTOPropagateFunctionAttrs(ThinLTO.CombinedIndex, isPrevailing);
1661 generateParamAccessSummary(ThinLTO.CombinedIndex);
1663 if (llvm::timeTraceProfilerEnabled())
1664 llvm::timeTraceProfilerEnd();
1666 TimeTraceScopeExit.release();
1668 std::unique_ptr<ThinBackendProc> BackendProc =
1669 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1670 AddStream, Cache);
1672 auto &ModuleMap =
1673 ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap;
1675 auto ProcessOneModule = [&](int I) -> Error {
1676 auto &Mod = *(ModuleMap.begin() + I);
1677 // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for
1678 // combined module and parallel code generation partitions.
1679 return BackendProc->start(RegularLTO.ParallelCodeGenParallelismLevel + I,
1680 Mod.second, ImportLists[Mod.first],
1681 ExportLists[Mod.first], ResolvedODR[Mod.first],
1682 ThinLTO.ModuleMap);
1685 if (BackendProc->getThreadCount() == 1) {
1686 // Process the modules in the order they were provided on the command-line.
1687 // It is important for this codepath to be used for WriteIndexesThinBackend,
1688 // to ensure the emitted LinkedObjectsFile lists ThinLTO objects in the same
1689 // order as the inputs, which otherwise would affect the final link order.
1690 for (int I = 0, E = ModuleMap.size(); I != E; ++I)
1691 if (Error E = ProcessOneModule(I))
1692 return E;
1693 } else {
1694 // When executing in parallel, process largest bitsize modules first to
1695 // improve parallelism, and avoid starving the thread pool near the end.
1696 // This saves about 15 sec on a 36-core machine while link `clang.exe` (out
1697 // of 100 sec).
1698 std::vector<BitcodeModule *> ModulesVec;
1699 ModulesVec.reserve(ModuleMap.size());
1700 for (auto &Mod : ModuleMap)
1701 ModulesVec.push_back(&Mod.second);
1702 for (int I : generateModulesOrdering(ModulesVec))
1703 if (Error E = ProcessOneModule(I))
1704 return E;
1706 return BackendProc->wait();
1709 Expected<std::unique_ptr<ToolOutputFile>> lto::setupLLVMOptimizationRemarks(
1710 LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
1711 StringRef RemarksFormat, bool RemarksWithHotness,
1712 std::optional<uint64_t> RemarksHotnessThreshold, int Count) {
1713 std::string Filename = std::string(RemarksFilename);
1714 // For ThinLTO, file.opt.<format> becomes
1715 // file.opt.<format>.thin.<num>.<format>.
1716 if (!Filename.empty() && Count != -1)
1717 Filename =
1718 (Twine(Filename) + ".thin." + llvm::utostr(Count) + "." + RemarksFormat)
1719 .str();
1721 auto ResultOrErr = llvm::setupLLVMOptimizationRemarks(
1722 Context, Filename, RemarksPasses, RemarksFormat, RemarksWithHotness,
1723 RemarksHotnessThreshold);
1724 if (Error E = ResultOrErr.takeError())
1725 return std::move(E);
1727 if (*ResultOrErr)
1728 (*ResultOrErr)->keep();
1730 return ResultOrErr;
1733 Expected<std::unique_ptr<ToolOutputFile>>
1734 lto::setupStatsFile(StringRef StatsFilename) {
1735 // Setup output file to emit statistics.
1736 if (StatsFilename.empty())
1737 return nullptr;
1739 llvm::EnableStatistics(false);
1740 std::error_code EC;
1741 auto StatsFile =
1742 std::make_unique<ToolOutputFile>(StatsFilename, EC, sys::fs::OF_None);
1743 if (EC)
1744 return errorCodeToError(EC);
1746 StatsFile->keep();
1747 return std::move(StatsFile);
1750 // Compute the ordering we will process the inputs: the rough heuristic here
1751 // is to sort them per size so that the largest module get schedule as soon as
1752 // possible. This is purely a compile-time optimization.
1753 std::vector<int> lto::generateModulesOrdering(ArrayRef<BitcodeModule *> R) {
1754 auto Seq = llvm::seq<int>(0, R.size());
1755 std::vector<int> ModulesOrdering(Seq.begin(), Seq.end());
1756 llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) {
1757 auto LSize = R[LeftIndex]->getBuffer().size();
1758 auto RSize = R[RightIndex]->getBuffer().size();
1759 return LSize > RSize;
1761 return ModulesOrdering;