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.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/LTO/LTO.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/ScopeExit.h"
16#include "llvm/ADT/SmallSet.h"
17#include "llvm/ADT/StableHashing.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/Analysis/OptimizationRemarkEmitter.h"
21#include "llvm/Analysis/StackSafetyAnalysis.h"
22#include "llvm/Analysis/TargetTransformInfo.h"
23#include "llvm/Bitcode/BitcodeReader.h"
24#include "llvm/Bitcode/BitcodeWriter.h"
25#include "llvm/CGData/CodeGenData.h"
26#include "llvm/CodeGen/Analysis.h"
27#include "llvm/Config/llvm-config.h"
28#include "llvm/IR/AutoUpgrade.h"
29#include "llvm/IR/DiagnosticPrinter.h"
30#include "llvm/IR/GlobalValue.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/LLVMRemarkStreamer.h"
33#include "llvm/IR/LegacyPassManager.h"
34#include "llvm/IR/Mangler.h"
35#include "llvm/IR/Metadata.h"
36#include "llvm/IR/RuntimeLibcalls.h"
37#include "llvm/LTO/LTOBackend.h"
38#include "llvm/Linker/IRMover.h"
39#include "llvm/MC/TargetRegistry.h"
40#include "llvm/Object/IRObjectFile.h"
41#include "llvm/Support/Caching.h"
42#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/Compiler.h"
44#include "llvm/Support/Error.h"
45#include "llvm/Support/FileSystem.h"
46#include "llvm/Support/MemoryBuffer.h"
47#include "llvm/Support/Path.h"
48#include "llvm/Support/Process.h"
49#include "llvm/Support/SHA1.h"
50#include "llvm/Support/Signals.h"
51#include "llvm/Support/SourceMgr.h"
52#include "llvm/Support/ThreadPool.h"
53#include "llvm/Support/Threading.h"
54#include "llvm/Support/TimeProfiler.h"
55#include "llvm/Support/ToolOutputFile.h"
56#include "llvm/Support/VCSRevision.h"
57#include "llvm/Support/raw_ostream.h"
58#include "llvm/Target/TargetOptions.h"
59#include "llvm/Transforms/IPO.h"
60#include "llvm/Transforms/IPO/MemProfContextDisambiguation.h"
61#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
62#include "llvm/Transforms/Utils/FunctionImportUtils.h"
63#include "llvm/Transforms/Utils/SplitModule.h"
64
65#include <optional>
66#include <set>
67
68using namespace llvm;
69using namespace lto;
70using namespace object;
71
72#define DEBUG_TYPE "lto"
73
74Error LTO::setupOptimizationRemarks() {
75 // Setup the remark streamer according to the provided configuration.
76 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
77 Context&: RegularLTO.Ctx, RemarksFilename: Conf.RemarksFilename, RemarksPasses: Conf.RemarksPasses,
78 RemarksFormat: Conf.RemarksFormat, RemarksWithHotness: Conf.RemarksWithHotness,
79 RemarksHotnessThreshold: Conf.RemarksHotnessThreshold);
80 if (!DiagFileOrErr)
81 return DiagFileOrErr.takeError();
82
83 DiagnosticOutputFile = std::move(*DiagFileOrErr);
84
85 // Create a dummy function to serve as a context for LTO-link remarks.
86 // This is required because OptimizationRemark requires a valid Function,
87 // and in ThinLTO we may not have any IR functions available during the
88 // thin link. Host it in a private module to avoid interfering with the LTO
89 // process.
90 if (!LinkerRemarkFunction) {
91 DummyModule = std::make_unique<Module>(args: "remark_dummy", args&: RegularLTO.Ctx);
92 LinkerRemarkFunction = Function::Create(
93 Ty: FunctionType::get(Result: Type::getVoidTy(C&: RegularLTO.Ctx), isVarArg: false),
94 Linkage: GlobalValue::ExternalLinkage, N: "thinlto_remark_dummy",
95 M: DummyModule.get());
96 }
97
98 return Error::success();
99}
100
101void LTO::emitRemark(OptimizationRemark &Remark) {
102 const Function &F = Remark.getFunction();
103 OptimizationRemarkEmitter ORE(const_cast<Function *>(&F));
104 ORE.emit(OptDiag&: Remark);
105}
106
107static cl::opt<bool>
108 DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(Val: false), cl::Hidden,
109 cl::desc("Dump the SCCs in the ThinLTO index's callgraph"));
110namespace llvm {
111extern cl::opt<bool> ForceImportAll;
112extern cl::opt<bool> AlwaysRenamePromotedLocals;
113} // end namespace llvm
114
115namespace llvm {
116/// Enable global value internalization in LTO.
117cl::opt<bool> EnableLTOInternalization(
118 "enable-lto-internalization", cl::init(Val: true), cl::Hidden,
119 cl::desc("Enable global value internalization in LTO"));
120
121static cl::opt<bool>
122 LTOKeepSymbolCopies("lto-keep-symbol-copies", cl::init(Val: false), cl::Hidden,
123 cl::desc("Keep copies of symbols in LTO indexing"));
124
125/// Indicate we are linking with an allocator that supports hot/cold operator
126/// new interfaces.
127extern cl::opt<bool> SupportsHotColdNew;
128
129/// Enable MemProf context disambiguation for thin link.
130extern cl::opt<bool> EnableMemProfContextDisambiguation;
131} // namespace llvm
132
133// Computes a unique hash for the Module considering the current list of
134// export/import and other global analysis results.
135// Returns the hash in its hexadecimal representation.
136std::string llvm::computeLTOCacheKey(
137 const Config &Conf, const ModuleSummaryIndex &Index, StringRef ModuleID,
138 const FunctionImporter::ImportMapTy &ImportList,
139 const FunctionImporter::ExportSetTy &ExportList,
140 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
141 const GVSummaryMapTy &DefinedGlobals,
142 const DenseSet<GlobalValue::GUID> &CfiFunctionDefs,
143 const DenseSet<GlobalValue::GUID> &CfiFunctionDecls) {
144 // Compute the unique hash for this entry.
145 // This is based on the current compiler version, the module itself, the
146 // export list, the hash for every single module in the import list, the
147 // list of ResolvedODR for the module, and the list of preserved symbols.
148 SHA1 Hasher;
149
150 // Start with the compiler revision
151 Hasher.update(LLVM_VERSION_STRING);
152#ifdef LLVM_REVISION
153 Hasher.update(LLVM_REVISION);
154#endif
155
156 // Include the parts of the LTO configuration that affect code generation.
157 auto AddString = [&](StringRef Str) {
158 Hasher.update(Str);
159 Hasher.update(Data: ArrayRef<uint8_t>{0});
160 };
161 auto AddUnsigned = [&](unsigned I) {
162 uint8_t Data[4];
163 support::endian::write32le(P: Data, V: I);
164 Hasher.update(Data);
165 };
166 auto AddUint64 = [&](uint64_t I) {
167 uint8_t Data[8];
168 support::endian::write64le(P: Data, V: I);
169 Hasher.update(Data);
170 };
171 auto AddUint8 = [&](const uint8_t I) {
172 Hasher.update(Data: ArrayRef<uint8_t>(&I, 1));
173 };
174 AddString(Conf.CPU);
175 // FIXME: Hash more of Options. For now all clients initialize Options from
176 // command-line flags (which is unsupported in production), but may set
177 // X86RelaxRelocations. The clang driver can also pass FunctionSections,
178 // DataSections and DebuggerTuning via command line flags.
179 AddUnsigned(Conf.Options.MCOptions.X86RelaxRelocations);
180 AddUnsigned(Conf.Options.FunctionSections);
181 AddUnsigned(Conf.Options.DataSections);
182 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
183 for (auto &A : Conf.MAttrs)
184 AddString(A);
185 if (Conf.RelocModel)
186 AddUnsigned(*Conf.RelocModel);
187 else
188 AddUnsigned(-1);
189 if (Conf.CodeModel)
190 AddUnsigned(*Conf.CodeModel);
191 else
192 AddUnsigned(-1);
193 for (const auto &S : Conf.MllvmArgs)
194 AddString(S);
195 AddUnsigned(static_cast<int>(Conf.CGOptLevel));
196 AddUnsigned(static_cast<int>(Conf.CGFileType));
197 AddUnsigned(Conf.OptLevel);
198 AddUnsigned(Conf.Freestanding);
199 AddString(Conf.OptPipeline);
200 AddString(Conf.AAPipeline);
201 AddString(Conf.OverrideTriple);
202 AddString(Conf.DefaultTriple);
203 AddString(Conf.DwoDir);
204 AddUint8(Conf.Dtlto);
205
206 // Include the hash for the current module
207 auto ModHash = Index.getModuleHash(ModPath: ModuleID);
208 Hasher.update(Data: ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
209
210 // TODO: `ExportList` is determined by `ImportList`. Since `ImportList` is
211 // used to compute cache key, we could omit hashing `ExportList` here.
212 std::vector<uint64_t> ExportsGUID;
213 ExportsGUID.reserve(n: ExportList.size());
214 for (const auto &VI : ExportList)
215 ExportsGUID.push_back(x: VI.getGUID());
216
217 // Sort the export list elements GUIDs.
218 llvm::sort(C&: ExportsGUID);
219 for (auto GUID : ExportsGUID)
220 Hasher.update(Data: ArrayRef<uint8_t>((uint8_t *)&GUID, sizeof(GUID)));
221
222 // Order using module hash, to be both independent of module name and
223 // module order.
224 auto Comp = [&](const std::pair<StringRef, GlobalValue::GUID> &L,
225 const std::pair<StringRef, GlobalValue::GUID> &R) {
226 return std::make_pair(x: Index.getModule(ModPath: L.first)->second, y: L.second) <
227 std::make_pair(x: Index.getModule(ModPath: R.first)->second, y: R.second);
228 };
229 FunctionImporter::SortedImportList SortedImportList(ImportList, Comp);
230
231 // Count the number of imports for each source module.
232 DenseMap<StringRef, unsigned> ModuleToNumImports;
233 for (const auto &[FromModule, GUID, Type] : SortedImportList)
234 ++ModuleToNumImports[FromModule];
235
236 std::optional<StringRef> LastModule;
237 for (const auto &[FromModule, GUID, Type] : SortedImportList) {
238 if (LastModule != FromModule) {
239 // Include the hash for every module we import functions from. The set of
240 // imported symbols for each module may affect code generation and is
241 // sensitive to link order, so include that as well.
242 LastModule = FromModule;
243 auto ModHash = Index.getModule(ModPath: FromModule)->second;
244 Hasher.update(Data: ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
245 AddUint64(ModuleToNumImports[FromModule]);
246 }
247 AddUint64(GUID);
248 AddUint8(Type);
249 }
250
251 // Include the hash for the resolved ODR.
252 for (auto &Entry : ResolvedODR) {
253 Hasher.update(Data: ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
254 sizeof(GlobalValue::GUID)));
255 Hasher.update(Data: ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
256 sizeof(GlobalValue::LinkageTypes)));
257 }
258
259 // Members of CfiFunctionDefs and CfiFunctionDecls that are referenced or
260 // defined in this module.
261 std::set<GlobalValue::GUID> UsedCfiDefs;
262 std::set<GlobalValue::GUID> UsedCfiDecls;
263
264 // Typeids used in this module.
265 std::set<GlobalValue::GUID> UsedTypeIds;
266
267 auto AddUsedCfiGlobal = [&](GlobalValue::GUID ValueGUID) {
268 if (CfiFunctionDefs.contains(V: ValueGUID))
269 UsedCfiDefs.insert(x: ValueGUID);
270 if (CfiFunctionDecls.contains(V: ValueGUID))
271 UsedCfiDecls.insert(x: ValueGUID);
272 };
273
274 auto AddUsedThings = [&](GlobalValueSummary *GS) {
275 if (!GS) return;
276 AddUnsigned(GS->getVisibility());
277 AddUnsigned(GS->isLive());
278 AddUnsigned(GS->canAutoHide());
279 for (const ValueInfo &VI : GS->refs()) {
280 AddUnsigned(VI.isDSOLocal(WithDSOLocalPropagation: Index.withDSOLocalPropagation()));
281 AddUsedCfiGlobal(VI.getGUID());
282 }
283 if (auto *GVS = dyn_cast<GlobalVarSummary>(Val: GS)) {
284 AddUnsigned(GVS->maybeReadOnly());
285 AddUnsigned(GVS->maybeWriteOnly());
286 }
287 if (auto *FS = dyn_cast<FunctionSummary>(Val: GS)) {
288 for (auto &TT : FS->type_tests())
289 UsedTypeIds.insert(x: TT);
290 for (auto &TT : FS->type_test_assume_vcalls())
291 UsedTypeIds.insert(x: TT.GUID);
292 for (auto &TT : FS->type_checked_load_vcalls())
293 UsedTypeIds.insert(x: TT.GUID);
294 for (auto &TT : FS->type_test_assume_const_vcalls())
295 UsedTypeIds.insert(x: TT.VFunc.GUID);
296 for (auto &TT : FS->type_checked_load_const_vcalls())
297 UsedTypeIds.insert(x: TT.VFunc.GUID);
298 for (auto &ET : FS->calls()) {
299 AddUnsigned(ET.first.isDSOLocal(WithDSOLocalPropagation: Index.withDSOLocalPropagation()));
300 AddUsedCfiGlobal(ET.first.getGUID());
301 }
302 }
303 };
304
305 // Sort the defined globals by GUID to be independent of the insertion order,
306 // which may depend on the order that modules are added.
307 SmallVector<std::pair<GlobalValue::GUID, GlobalValueSummary *>>
308 SortedDefinedGlobals(DefinedGlobals.begin(), DefinedGlobals.end());
309 llvm::sort(C&: SortedDefinedGlobals, Comp: llvm::less_first());
310 for (auto &GS : SortedDefinedGlobals) {
311 // Include the hash for the linkage type to reflect internalization and weak
312 // resolution, and collect any used type identifier resolutions.
313 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
314 Hasher.update(
315 Data: ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
316 AddUsedCfiGlobal(GS.first);
317 AddUsedThings(GS.second);
318 }
319
320 // Imported functions may introduce new uses of type identifier resolutions,
321 // so we need to collect their used resolutions as well.
322 for (const auto &[FromModule, GUID, Type] : SortedImportList) {
323 GlobalValueSummary *S = Index.findSummaryInModule(ValueGUID: GUID, ModuleId: FromModule);
324 AddUsedThings(S);
325 // If this is an alias, we also care about any types/etc. that the aliasee
326 // may reference.
327 if (auto *AS = dyn_cast_or_null<AliasSummary>(Val: S))
328 AddUsedThings(AS->getBaseObject());
329 }
330
331 auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
332 AddString(TId);
333
334 AddUnsigned(S.TTRes.TheKind);
335 AddUnsigned(S.TTRes.SizeM1BitWidth);
336
337 AddUint64(S.TTRes.AlignLog2);
338 AddUint64(S.TTRes.SizeM1);
339 AddUint64(S.TTRes.BitMask);
340 AddUint64(S.TTRes.InlineBits);
341
342 AddUint64(S.WPDRes.size());
343 for (auto &WPD : S.WPDRes) {
344 AddUnsigned(WPD.first);
345 AddUnsigned(WPD.second.TheKind);
346 AddString(WPD.second.SingleImplName);
347
348 AddUint64(WPD.second.ResByArg.size());
349 for (auto &ByArg : WPD.second.ResByArg) {
350 AddUint64(ByArg.first.size());
351 for (uint64_t Arg : ByArg.first)
352 AddUint64(Arg);
353 AddUnsigned(ByArg.second.TheKind);
354 AddUint64(ByArg.second.Info);
355 AddUnsigned(ByArg.second.Byte);
356 AddUnsigned(ByArg.second.Bit);
357 }
358 }
359 };
360
361 // Include the hash for all type identifiers used by this module.
362 for (GlobalValue::GUID TId : UsedTypeIds) {
363 auto TidIter = Index.typeIds().equal_range(x: TId);
364 for (const auto &I : make_range(p: TidIter))
365 AddTypeIdSummary(I.second.first, I.second.second);
366 }
367
368 AddUnsigned(UsedCfiDefs.size());
369 for (auto &V : UsedCfiDefs)
370 AddUint64(V);
371
372 AddUnsigned(UsedCfiDecls.size());
373 for (auto &V : UsedCfiDecls)
374 AddUint64(V);
375
376 if (!Conf.SampleProfile.empty()) {
377 auto FileOrErr = MemoryBuffer::getFile(Filename: Conf.SampleProfile);
378 if (FileOrErr) {
379 Hasher.update(Str: FileOrErr.get()->getBuffer());
380
381 if (!Conf.ProfileRemapping.empty()) {
382 FileOrErr = MemoryBuffer::getFile(Filename: Conf.ProfileRemapping);
383 if (FileOrErr)
384 Hasher.update(Str: FileOrErr.get()->getBuffer());
385 }
386 }
387 }
388
389 return toHex(Input: Hasher.result());
390}
391
392std::string llvm::recomputeLTOCacheKey(const std::string &Key,
393 StringRef ExtraID) {
394 SHA1 Hasher;
395
396 auto AddString = [&](StringRef Str) {
397 Hasher.update(Str);
398 Hasher.update(Data: ArrayRef<uint8_t>{0});
399 };
400 AddString(Key);
401 AddString(ExtraID);
402
403 return toHex(Input: Hasher.result());
404}
405
406static void thinLTOResolvePrevailingGUID(
407 const Config &C, ValueInfo VI,
408 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
409 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
410 isPrevailing,
411 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
412 recordNewLinkage,
413 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
414 GlobalValue::VisibilityTypes Visibility =
415 C.VisibilityScheme == Config::ELF ? VI.getELFVisibility()
416 : GlobalValue::DefaultVisibility;
417 for (auto &S : VI.getSummaryList()) {
418 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
419 // Ignore local and appending linkage values since the linker
420 // doesn't resolve them.
421 if (GlobalValue::isLocalLinkage(Linkage: OriginalLinkage) ||
422 GlobalValue::isAppendingLinkage(Linkage: S->linkage()))
423 continue;
424 // We need to emit only one of these. The prevailing module will keep it,
425 // but turned into a weak, while the others will drop it when possible.
426 // This is both a compile-time optimization and a correctness
427 // transformation. This is necessary for correctness when we have exported
428 // a reference - we need to convert the linkonce to weak to
429 // ensure a copy is kept to satisfy the exported reference.
430 // FIXME: We may want to split the compile time and correctness
431 // aspects into separate routines.
432 if (isPrevailing(VI.getGUID(), S.get())) {
433 assert(!S->wasPromoted() &&
434 "promoted symbols used to be internal linkage and shouldn't have "
435 "a prevailing variant");
436 if (GlobalValue::isLinkOnceLinkage(Linkage: OriginalLinkage)) {
437 S->setLinkage(GlobalValue::getWeakLinkage(
438 ODR: GlobalValue::isLinkOnceODRLinkage(Linkage: OriginalLinkage)));
439 // The kept copy is eligible for auto-hiding (hidden visibility) if all
440 // copies were (i.e. they were all linkonce_odr global unnamed addr).
441 // If any copy is not (e.g. it was originally weak_odr), then the symbol
442 // must remain externally available (e.g. a weak_odr from an explicitly
443 // instantiated template). Additionally, if it is in the
444 // GUIDPreservedSymbols set, that means that it is visibile outside
445 // the summary (e.g. in a native object or a bitcode file without
446 // summary), and in that case we cannot hide it as it isn't possible to
447 // check all copies.
448 S->setCanAutoHide(VI.canAutoHide() &&
449 !GUIDPreservedSymbols.count(V: VI.getGUID()));
450 }
451 if (C.VisibilityScheme == Config::FromPrevailing)
452 Visibility = S->getVisibility();
453 }
454 // Alias and aliasee can't be turned into available_externally.
455 // When force-import-all is used, it indicates that object linking is not
456 // supported by the target. In this case, we can't change the linkage as
457 // well in case the global is converted to declaration.
458 // Also, if the symbol was promoted, it wouldn't have a prevailing variant,
459 // but also its linkage is set correctly (to External) already.
460 else if (!isa<AliasSummary>(Val: S.get()) &&
461 !GlobalInvolvedWithAlias.count(V: S.get()) && !ForceImportAll &&
462 !S->wasPromoted())
463 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
464
465 // For ELF, set visibility to the computed visibility from summaries. We
466 // don't track visibility from declarations so this may be more relaxed than
467 // the most constraining one.
468 if (C.VisibilityScheme == Config::ELF)
469 S->setVisibility(Visibility);
470
471 if (S->linkage() != OriginalLinkage)
472 recordNewLinkage(S->modulePath(), VI.getGUID(), S->linkage());
473 }
474
475 if (C.VisibilityScheme == Config::FromPrevailing) {
476 for (auto &S : VI.getSummaryList()) {
477 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
478 if (GlobalValue::isLocalLinkage(Linkage: OriginalLinkage) ||
479 GlobalValue::isAppendingLinkage(Linkage: S->linkage()))
480 continue;
481 S->setVisibility(Visibility);
482 }
483 }
484}
485
486/// Resolve linkage for prevailing symbols in the \p Index.
487//
488// We'd like to drop these functions if they are no longer referenced in the
489// current module. However there is a chance that another module is still
490// referencing them because of the import. We make sure we always emit at least
491// one copy.
492void llvm::thinLTOResolvePrevailingInIndex(
493 const Config &C, ModuleSummaryIndex &Index,
494 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
495 isPrevailing,
496 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
497 recordNewLinkage,
498 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
499 // We won't optimize the globals that are referenced by an alias for now
500 // Ideally we should turn the alias into a global and duplicate the definition
501 // when needed.
502 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
503 for (auto &I : Index)
504 for (auto &S : I.second.getSummaryList())
505 if (auto AS = dyn_cast<AliasSummary>(Val: S.get()))
506 GlobalInvolvedWithAlias.insert(V: &AS->getAliasee());
507
508 for (auto &I : Index)
509 thinLTOResolvePrevailingGUID(C, VI: Index.getValueInfo(R: I),
510 GlobalInvolvedWithAlias, isPrevailing,
511 recordNewLinkage, GUIDPreservedSymbols);
512}
513
514static void thinLTOInternalizeAndPromoteGUID(
515 ValueInfo VI, function_ref<bool(StringRef, ValueInfo)> isExported,
516 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
517 isPrevailing,
518 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr) {
519 // Before performing index-based internalization and promotion for this GUID,
520 // the local flag should be consistent with the summary list linkage types.
521 VI.verifyLocal();
522
523 const bool SingleExternallyVisibleCopy =
524 VI.getSummaryList().size() == 1 &&
525 !GlobalValue::isLocalLinkage(Linkage: VI.getSummaryList().front()->linkage());
526
527 bool NameRecorded = false;
528 for (auto &S : VI.getSummaryList()) {
529 // First see if we need to promote an internal value because it is not
530 // exported.
531 if (isExported(S->modulePath(), VI)) {
532 if (GlobalValue::isLocalLinkage(Linkage: S->linkage())) {
533 // Only the first local GlobalValue in a list of summaries does not
534 // need renaming. In rare cases if there exist more than one summaries
535 // in the list, the rest of them must have renaming (through promotion)
536 // to avoid conflict.
537 if (ExternallyVisibleSymbolNamesPtr && !NameRecorded) {
538 NameRecorded = true;
539 if (ExternallyVisibleSymbolNamesPtr->insert(V: VI.name()).second)
540 S->setNoRenameOnPromotion(true);
541 }
542
543 S->promote();
544 }
545 continue;
546 }
547
548 // Otherwise, see if we can internalize.
549 if (!EnableLTOInternalization)
550 continue;
551
552 // Non-exported values with external linkage can be internalized.
553 if (GlobalValue::isExternalLinkage(Linkage: S->linkage())) {
554 S->setLinkage(GlobalValue::InternalLinkage);
555 continue;
556 }
557
558 // Non-exported function and variable definitions with a weak-for-linker
559 // linkage can be internalized in certain cases. The minimum legality
560 // requirements would be that they are not address taken to ensure that we
561 // don't break pointer equality checks, and that variables are either read-
562 // or write-only. For functions, this is the case if either all copies are
563 // [local_]unnamed_addr, or we can propagate reference edge attributes
564 // (which is how this is guaranteed for variables, when analyzing whether
565 // they are read or write-only).
566 //
567 // However, we only get to this code for weak-for-linkage values in one of
568 // two cases:
569 // 1) The prevailing copy is not in IR (it is in native code).
570 // 2) The prevailing copy in IR is not exported from its module.
571 // Additionally, at least for the new LTO API, case 2 will only happen if
572 // there is exactly one definition of the value (i.e. in exactly one
573 // module), as duplicate defs are result in the value being marked exported.
574 // Likely, users of the legacy LTO API are similar, however, currently there
575 // are llvm-lto based tests of the legacy LTO API that do not mark
576 // duplicate linkonce_odr copies as exported via the tool, so we need
577 // to handle that case below by checking the number of copies.
578 //
579 // Generally, we only want to internalize a weak-for-linker value in case
580 // 2, because in case 1 we cannot see how the value is used to know if it
581 // is read or write-only. We also don't want to bloat the binary with
582 // multiple internalized copies of non-prevailing linkonce/weak functions.
583 // Note if we don't internalize, we will convert non-prevailing copies to
584 // available_externally anyway, so that we drop them after inlining. The
585 // only reason to internalize such a function is if we indeed have a single
586 // copy, because internalizing it won't increase binary size, and enables
587 // use of inliner heuristics that are more aggressive in the face of a
588 // single call to a static (local). For variables, internalizing a read or
589 // write only variable can enable more aggressive optimization. However, we
590 // already perform this elsewhere in the ThinLTO backend handling for
591 // read or write-only variables (processGlobalForThinLTO).
592 //
593 // Therefore, only internalize linkonce/weak if there is a single copy, that
594 // is prevailing in this IR module. We can do so aggressively, without
595 // requiring the address to be insignificant, or that a variable be read or
596 // write-only.
597 if (!GlobalValue::isWeakForLinker(Linkage: S->linkage()) ||
598 GlobalValue::isExternalWeakLinkage(Linkage: S->linkage()))
599 continue;
600
601 // We may have a single summary copy that is externally visible but not
602 // prevailing if the prevailing copy is in a native object.
603 if (SingleExternallyVisibleCopy && isPrevailing(VI.getGUID(), S.get()))
604 S->setLinkage(GlobalValue::InternalLinkage);
605 }
606}
607
608// Update the linkages in the given \p Index to mark exported values
609// as external and non-exported values as internal.
610void llvm::thinLTOInternalizeAndPromoteInIndex(
611 ModuleSummaryIndex &Index,
612 function_ref<bool(StringRef, ValueInfo)> isExported,
613 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
614 isPrevailing,
615 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr) {
616 assert(!Index.withInternalizeAndPromote());
617
618 for (auto &I : Index)
619 thinLTOInternalizeAndPromoteGUID(VI: Index.getValueInfo(R: I), isExported,
620 isPrevailing,
621 ExternallyVisibleSymbolNamesPtr);
622 Index.setWithInternalizeAndPromote();
623}
624
625// Requires a destructor for std::vector<InputModule>.
626InputFile::~InputFile() = default;
627
628Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
629 std::unique_ptr<InputFile> File(new InputFile);
630
631 Expected<IRSymtabFile> FOrErr = readIRSymtab(MBRef: Object);
632 if (!FOrErr)
633 return FOrErr.takeError();
634
635 File->TargetTriple = FOrErr->TheReader.getTargetTriple();
636 File->SourceFileName = FOrErr->TheReader.getSourceFileName();
637 File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
638 File->DependentLibraries = FOrErr->TheReader.getDependentLibraries();
639 File->ComdatTable = FOrErr->TheReader.getComdatTable();
640 File->MbRef =
641 Object; // Save a memory buffer reference to an input file object.
642
643 for (unsigned I = 0; I != FOrErr->Mods.size(); ++I) {
644 size_t Begin = File->Symbols.size();
645 for (const irsymtab::Reader::SymbolRef &Sym :
646 FOrErr->TheReader.module_symbols(I))
647 // Skip symbols that are irrelevant to LTO. Note that this condition needs
648 // to match the one in Skip() in LTO::addRegularLTO().
649 if (Sym.isGlobal() && !Sym.isFormatSpecific())
650 File->Symbols.push_back(x: Sym);
651 File->ModuleSymIndices.push_back(x: {Begin, File->Symbols.size()});
652 }
653
654 File->Mods = FOrErr->Mods;
655 File->Strtab = std::move(FOrErr->Strtab);
656 return std::move(File);
657}
658
659bool InputFile::Symbol::isLibcall(
660 const TargetLibraryInfo &TLI,
661 const RTLIB::RuntimeLibcallsInfo &Libcalls) const {
662 if (TLI.has(F: TLI.getLibFunc(funcName: IRName)))
663 return true;
664 return Libcalls.getSupportedLibcallImpl(FuncName: IRName) != RTLIB::Unsupported;
665}
666
667StringRef InputFile::getName() const {
668 return Mods[0].getModuleIdentifier();
669}
670
671BitcodeModule &InputFile::getSingleBitcodeModule() {
672 assert(Mods.size() == 1 && "Expect only one bitcode module");
673 return Mods[0];
674}
675
676BitcodeModule &InputFile::getPrimaryBitcodeModule() { return Mods[0]; }
677
678LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
679 const Config &Conf)
680 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
681 Ctx(Conf), CombinedModule(std::make_unique<Module>(args: "ld-temp.o", args&: Ctx)),
682 Mover(std::make_unique<IRMover>(args&: *CombinedModule)) {}
683
684LTO::ThinLTOState::ThinLTOState(ThinBackend BackendParam)
685 : Backend(std::move(BackendParam)), CombinedIndex(/*HaveGVs*/ false) {
686 if (!Backend.isValid())
687 Backend =
688 createInProcessThinBackend(Parallelism: llvm::heavyweight_hardware_concurrency());
689}
690
691LTO::LTO(Config Conf, ThinBackend Backend,
692 unsigned ParallelCodeGenParallelismLevel, LTOKind LTOMode)
693 : Conf(std::move(Conf)),
694 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
695 ThinLTO(std::move(Backend)),
696 GlobalResolutions(
697 std::make_unique<DenseMap<StringRef, GlobalResolution>>()),
698 LTOMode(LTOMode) {
699 if (Conf.KeepSymbolNameCopies || LTOKeepSymbolCopies) {
700 Alloc = std::make_unique<BumpPtrAllocator>();
701 GlobalResolutionSymbolSaver = std::make_unique<llvm::StringSaver>(args&: *Alloc);
702 }
703}
704
705// Requires a destructor for MapVector<BitcodeModule>.
706LTO::~LTO() = default;
707
708void LTO::cleanup() {
709 DummyModule.reset();
710 LinkerRemarkFunction = nullptr;
711 consumeError(Err: finalizeOptimizationRemarks(DiagOutputFile: std::move(DiagnosticOutputFile)));
712}
713
714// Add the symbols in the given module to the GlobalResolutions map, and resolve
715// their partitions.
716void LTO::addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
717 ArrayRef<SymbolResolution> Res,
718 unsigned Partition, bool InSummary,
719 const Triple &TT) {
720 llvm::TimeTraceScope timeScope("LTO add module to global resolution");
721 auto *ResI = Res.begin();
722 auto *ResE = Res.end();
723 (void)ResE;
724 RTLIB::RuntimeLibcallsInfo Libcalls(TT);
725 TargetLibraryInfoImpl TLII(TT);
726 TargetLibraryInfo TLI(TLII);
727 for (const InputFile::Symbol &Sym : Syms) {
728 assert(ResI != ResE);
729 SymbolResolution Res = *ResI++;
730
731 StringRef SymbolName = Sym.getName();
732 // Keep copies of symbols if the client of LTO says so.
733 if (GlobalResolutionSymbolSaver && !GlobalResolutions->contains(Val: SymbolName))
734 SymbolName = GlobalResolutionSymbolSaver->save(S: SymbolName);
735
736 auto &GlobalRes = (*GlobalResolutions)[SymbolName];
737 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
738 if (Res.Prevailing) {
739 assert(!GlobalRes.Prevailing &&
740 "Multiple prevailing defs are not allowed");
741 GlobalRes.Prevailing = true;
742 GlobalRes.IRName = std::string(Sym.getIRName());
743 } else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
744 // Sometimes it can be two copies of symbol in a module and prevailing
745 // symbol can have no IR name. That might happen if symbol is defined in
746 // module level inline asm block. In case we have multiple modules with
747 // the same symbol we want to use IR name of the prevailing symbol.
748 // Otherwise, if we haven't seen a prevailing symbol, set the name so that
749 // we can later use it to check if there is any prevailing copy in IR.
750 GlobalRes.IRName = std::string(Sym.getIRName());
751 }
752
753 // In rare occasion, the symbol used to initialize GlobalRes has a different
754 // IRName from the inspected Symbol. This can happen on macOS + iOS, when a
755 // symbol is referenced through its mangled name, say @"\01_symbol" while
756 // the IRName is @symbol (the prefix underscore comes from MachO mangling).
757 // In that case, we have the same actual Symbol that can get two different
758 // GUID, leading to some invalid internalization. Workaround this by marking
759 // the GlobalRes external.
760
761 // FIXME: instead of this check, it would be desirable to compute GUIDs
762 // based on mangled name, but this requires an access to the Target Triple
763 // and would be relatively invasive on the codebase.
764 // FIXME: use the GUID member of GlobalRes.
765 if (GlobalRes.IRName != Sym.getIRName()) {
766 GlobalRes.Partition = GlobalResolution::External;
767 GlobalRes.VisibleOutsideSummary = true;
768 }
769
770 bool IsLibcall = Sym.isLibcall(TLI, Libcalls);
771
772 // Set the partition to external if we know it is re-defined by the linker
773 // with -defsym or -wrap options, used elsewhere, e.g. it is visible to a
774 // regular object, is referenced from llvm.compiler.used/llvm.used, or was
775 // already recorded as being referenced from a different partition.
776 if (Res.LinkerRedefined || Res.VisibleToRegularObj || Sym.isUsed() ||
777 IsLibcall ||
778 (GlobalRes.Partition != GlobalResolution::Unknown &&
779 GlobalRes.Partition != Partition)) {
780 GlobalRes.Partition = GlobalResolution::External;
781 } else
782 // First recorded reference, save the current partition.
783 GlobalRes.Partition = Partition;
784
785 // Flag as visible outside of summary if visible from a regular object or
786 // from a module that does not have a summary.
787 GlobalRes.VisibleOutsideSummary |=
788 (Res.VisibleToRegularObj || Sym.isUsed() || IsLibcall || !InSummary);
789
790 GlobalRes.ExportDynamic |= Res.ExportDynamic;
791 }
792}
793
794void LTO::releaseGlobalResolutionsMemory() {
795 // Release GlobalResolutions dense-map itself.
796 GlobalResolutions.reset();
797 // Release the string saver memory.
798 GlobalResolutionSymbolSaver.reset();
799 Alloc.reset();
800}
801
802static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
803 ArrayRef<SymbolResolution> Res) {
804 StringRef Path = Input->getName();
805 OS << Path << '\n';
806 auto ResI = Res.begin();
807 for (const InputFile::Symbol &Sym : Input->symbols()) {
808 assert(ResI != Res.end());
809 SymbolResolution Res = *ResI++;
810
811 OS << "-r=" << Path << ',' << Sym.getName() << ',';
812 if (Res.Prevailing)
813 OS << 'p';
814 if (Res.FinalDefinitionInLinkageUnit)
815 OS << 'l';
816 if (Res.VisibleToRegularObj)
817 OS << 'x';
818 if (Res.LinkerRedefined)
819 OS << 'r';
820 OS << '\n';
821 }
822 OS.flush();
823 assert(ResI == Res.end());
824}
825
826Error LTO::add(std::unique_ptr<InputFile> InputPtr,
827 ArrayRef<SymbolResolution> Res) {
828 llvm::TimeTraceScope timeScope("LTO add input", InputPtr->getName());
829 assert(!CalledGetMaxTasks);
830
831 Expected<std::shared_ptr<InputFile>> InputOrErr =
832 addInput(InputPtr: std::move(InputPtr));
833 if (!InputOrErr)
834 return InputOrErr.takeError();
835 InputFile *Input = (*InputOrErr).get();
836
837 if (Conf.ResolutionFile)
838 writeToResolutionFile(OS&: *Conf.ResolutionFile, Input, Res);
839
840 if (RegularLTO.CombinedModule->getTargetTriple().empty()) {
841 Triple InputTriple(Input->getTargetTriple());
842 RegularLTO.CombinedModule->setTargetTriple(InputTriple);
843 if (InputTriple.isOSBinFormatELF())
844 Conf.VisibilityScheme = Config::ELF;
845 }
846
847 ArrayRef<SymbolResolution> InputRes = Res;
848 for (unsigned I = 0; I != Input->Mods.size(); ++I) {
849 if (auto Err = addModule(Input&: *Input, InputRes, ModI: I, Res).moveInto(Value&: Res))
850 return Err;
851 }
852
853 assert(Res.empty());
854 return Error::success();
855}
856
857void LTO::setBitcodeLibFuncs(ArrayRef<StringRef> BitcodeLibFuncs) {
858 assert(this->BitcodeLibFuncs.empty() &&
859 "bitcode libfuncs were set twice; maybe accidentally clobbered?");
860 this->BitcodeLibFuncs.append(in_start: BitcodeLibFuncs.begin(), in_end: BitcodeLibFuncs.end());
861}
862
863Expected<ArrayRef<SymbolResolution>>
864LTO::addModule(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
865 unsigned ModI, ArrayRef<SymbolResolution> Res) {
866 llvm::TimeTraceScope timeScope("LTO add module", Input.getName());
867 Expected<BitcodeLTOInfo> LTOInfo = Input.Mods[ModI].getLTOInfo();
868 if (!LTOInfo)
869 return LTOInfo.takeError();
870
871 if (EnableSplitLTOUnit) {
872 // If only some modules were split, flag this in the index so that
873 // we can skip or error on optimizations that need consistently split
874 // modules (whole program devirt and lower type tests).
875 if (*EnableSplitLTOUnit != LTOInfo->EnableSplitLTOUnit)
876 ThinLTO.CombinedIndex.setPartiallySplitLTOUnits();
877 } else
878 EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
879
880 BitcodeModule BM = Input.Mods[ModI];
881
882 if ((LTOMode == LTOK_UnifiedRegular || LTOMode == LTOK_UnifiedThin) &&
883 !LTOInfo->UnifiedLTO)
884 return make_error<StringError>(
885 Args: "unified LTO compilation must use "
886 "compatible bitcode modules (use -funified-lto)",
887 Args: inconvertibleErrorCode());
888
889 if (LTOInfo->UnifiedLTO && LTOMode == LTOK_Default)
890 LTOMode = LTOK_UnifiedThin;
891
892 bool IsThinLTO = LTOInfo->IsThinLTO && (LTOMode != LTOK_UnifiedRegular);
893 // If any of the modules inside of a input bitcode file was compiled with
894 // ThinLTO, we assume that the whole input file also was compiled with
895 // ThinLTO.
896 Input.IsThinLTO |= IsThinLTO;
897
898 auto ModSyms = Input.module_symbols(I: ModI);
899 addModuleToGlobalRes(Syms: ModSyms, Res,
900 Partition: IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0,
901 InSummary: LTOInfo->HasSummary, TT: Triple(Input.getTargetTriple()));
902
903 if (IsThinLTO)
904 return addThinLTO(BM, Syms: ModSyms, Res);
905
906 RegularLTO.EmptyCombinedModule = false;
907 auto ModOrErr = addRegularLTO(Input, InputRes, BM, Syms: ModSyms, Res);
908 if (!ModOrErr)
909 return ModOrErr.takeError();
910 Res = ModOrErr->second;
911
912 if (!LTOInfo->HasSummary) {
913 if (Error Err = linkRegularLTO(Mod: std::move(ModOrErr->first),
914 /*LivenessFromIndex=*/false))
915 return Err;
916 return Res;
917 }
918
919 // Regular LTO module summaries are added to a dummy module that represents
920 // the combined regular LTO module.
921 if (Error Err = BM.readSummary(CombinedIndex&: ThinLTO.CombinedIndex, ModulePath: ""))
922 return Err;
923 RegularLTO.ModsWithSummaries.push_back(x: std::move(ModOrErr->first));
924 return Res;
925}
926
927// Checks whether the given global value is in a non-prevailing comdat
928// (comdat containing values the linker indicated were not prevailing,
929// which we then dropped to available_externally), and if so, removes
930// it from the comdat. This is called for all global values to ensure the
931// comdat is empty rather than leaving an incomplete comdat. It is needed for
932// regular LTO modules, in case we are in a mixed-LTO mode (both regular
933// and thin LTO modules) compilation. Since the regular LTO module will be
934// linked first in the final native link, we want to make sure the linker
935// doesn't select any of these incomplete comdats that would be left
936// in the regular LTO module without this cleanup.
937static void
938handleNonPrevailingComdat(GlobalValue &GV,
939 std::set<const Comdat *> &NonPrevailingComdats) {
940 Comdat *C = GV.getComdat();
941 if (!C)
942 return;
943
944 if (!NonPrevailingComdats.count(x: C))
945 return;
946
947 // Additionally need to drop all global values from the comdat to
948 // available_externally, to satisfy the COMDAT requirement that all members
949 // are discarded as a unit. The non-local linkage global values avoid
950 // duplicate definition linker errors.
951 GV.setLinkage(GlobalValue::AvailableExternallyLinkage);
952
953 if (auto GO = dyn_cast<GlobalObject>(Val: &GV))
954 GO->setComdat(nullptr);
955}
956
957// Add a regular LTO object to the link.
958// The resulting module needs to be linked into the combined LTO module with
959// linkRegularLTO.
960Expected<
961 std::pair<LTO::RegularLTOState::AddedModule, ArrayRef<SymbolResolution>>>
962LTO::addRegularLTO(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
963 BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
964 ArrayRef<SymbolResolution> Res) {
965 llvm::TimeTraceScope timeScope("LTO add regular LTO");
966 RegularLTOState::AddedModule Mod;
967 Expected<std::unique_ptr<Module>> MOrErr =
968 BM.getLazyModule(Context&: RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
969 /*IsImporting*/ false);
970 if (!MOrErr)
971 return MOrErr.takeError();
972 Module &M = **MOrErr;
973 Mod.M = std::move(*MOrErr);
974
975 if (Error Err = M.materializeMetadata())
976 return std::move(Err);
977
978 if (LTOMode == LTOK_UnifiedRegular) {
979 // cfi.functions metadata is intended to be used with ThinLTO and may
980 // trigger invalid IR transformations if they are present when doing regular
981 // LTO, so delete it.
982 if (NamedMDNode *CfiFunctionsMD = M.getNamedMetadata(Name: "cfi.functions"))
983 M.eraseNamedMetadata(NMD: CfiFunctionsMD);
984 } else if (NamedMDNode *AliasesMD = M.getNamedMetadata(Name: "aliases")) {
985 // Delete aliases entries for non-prevailing symbols on the ThinLTO side of
986 // this input file.
987 DenseSet<StringRef> Prevailing;
988 for (auto [I, R] : zip(t: Input.symbols(), u&: InputRes))
989 if (R.Prevailing && !I.getIRName().empty())
990 Prevailing.insert(V: I.getIRName());
991 std::vector<MDNode *> AliasGroups;
992 for (MDNode *AliasGroup : AliasesMD->operands()) {
993 std::vector<Metadata *> Aliases;
994 for (Metadata *Alias : AliasGroup->operands()) {
995 if (isa<MDString>(Val: Alias) &&
996 Prevailing.count(V: cast<MDString>(Val: Alias)->getString()))
997 Aliases.push_back(x: Alias);
998 }
999 if (Aliases.size() > 1)
1000 AliasGroups.push_back(x: MDTuple::get(Context&: RegularLTO.Ctx, MDs: Aliases));
1001 }
1002 AliasesMD->clearOperands();
1003 for (MDNode *G : AliasGroups)
1004 AliasesMD->addOperand(M: G);
1005 }
1006
1007 UpgradeDebugInfo(M);
1008
1009 ModuleSymbolTable SymTab;
1010 SymTab.addModule(M: &M);
1011
1012 for (GlobalVariable &GV : M.globals())
1013 if (GV.hasAppendingLinkage())
1014 Mod.Keep.push_back(x: &GV);
1015
1016 DenseSet<GlobalObject *> AliasedGlobals;
1017 for (auto &GA : M.aliases())
1018 if (GlobalObject *GO = GA.getAliaseeObject())
1019 AliasedGlobals.insert(V: GO);
1020
1021 // In this function we need IR GlobalValues matching the symbols in Syms
1022 // (which is not backed by a module), so we need to enumerate them in the same
1023 // order. The symbol enumeration order of a ModuleSymbolTable intentionally
1024 // matches the order of an irsymtab, but when we read the irsymtab in
1025 // InputFile::create we omit some symbols that are irrelevant to LTO. The
1026 // Skip() function skips the same symbols from the module as InputFile does
1027 // from the symbol table.
1028 auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
1029 auto Skip = [&]() {
1030 while (MsymI != MsymE) {
1031 auto Flags = SymTab.getSymbolFlags(S: *MsymI);
1032 if ((Flags & object::BasicSymbolRef::SF_Global) &&
1033 !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
1034 return;
1035 ++MsymI;
1036 }
1037 };
1038 Skip();
1039
1040 std::set<const Comdat *> NonPrevailingComdats;
1041 SmallSet<StringRef, 2> NonPrevailingAsmSymbols;
1042 for (const InputFile::Symbol &Sym : Syms) {
1043 assert(!Res.empty());
1044 const SymbolResolution &R = Res.consume_front();
1045
1046 assert(MsymI != MsymE);
1047 ModuleSymbolTable::Symbol Msym = *MsymI++;
1048 Skip();
1049
1050 if (GlobalValue *GV = dyn_cast_if_present<GlobalValue *>(Val&: Msym)) {
1051 if (R.Prevailing) {
1052 if (Sym.isUndefined())
1053 continue;
1054 Mod.Keep.push_back(x: GV);
1055 // For symbols re-defined with linker -wrap and -defsym options,
1056 // set the linkage to weak to inhibit IPO. The linkage will be
1057 // restored by the linker.
1058 if (R.LinkerRedefined)
1059 GV->setLinkage(GlobalValue::WeakAnyLinkage);
1060
1061 GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage();
1062 if (GlobalValue::isLinkOnceLinkage(Linkage: OriginalLinkage))
1063 GV->setLinkage(GlobalValue::getWeakLinkage(
1064 ODR: GlobalValue::isLinkOnceODRLinkage(Linkage: OriginalLinkage)));
1065 } else if (isa<GlobalObject>(Val: GV) &&
1066 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
1067 GV->hasAvailableExternallyLinkage()) &&
1068 !AliasedGlobals.count(V: cast<GlobalObject>(Val: GV))) {
1069 // Any of the above three types of linkage indicates that the
1070 // chosen prevailing symbol will have the same semantics as this copy of
1071 // the symbol, so we may be able to link it with available_externally
1072 // linkage. We will decide later whether to do that when we link this
1073 // module (in linkRegularLTO), based on whether it is undefined.
1074 Mod.Keep.push_back(x: GV);
1075 GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
1076 if (GV->hasComdat())
1077 NonPrevailingComdats.insert(x: GV->getComdat());
1078 cast<GlobalObject>(Val: GV)->setComdat(nullptr);
1079 }
1080
1081 // Set the 'local' flag based on the linker resolution for this symbol.
1082 if (R.FinalDefinitionInLinkageUnit) {
1083 GV->setDSOLocal(true);
1084 if (GV->hasDLLImportStorageClass())
1085 GV->setDLLStorageClass(GlobalValue::DLLStorageClassTypes::
1086 DefaultStorageClass);
1087 }
1088 } else if (auto *AS =
1089 dyn_cast_if_present<ModuleSymbolTable::AsmSymbol *>(Val&: Msym)) {
1090 // Collect non-prevailing symbols.
1091 if (!R.Prevailing)
1092 NonPrevailingAsmSymbols.insert(V: AS->first);
1093 } else {
1094 llvm_unreachable("unknown symbol type");
1095 }
1096
1097 // Common resolution: collect the maximum size/alignment over all commons.
1098 // We also record if we see an instance of a common as prevailing, so that
1099 // if none is prevailing we can ignore it later.
1100 if (Sym.isCommon()) {
1101 // FIXME: We should figure out what to do about commons defined by asm.
1102 // For now they aren't reported correctly by ModuleSymbolTable.
1103 auto &CommonRes = RegularLTO.Commons[std::string(Sym.getIRName())];
1104 CommonRes.Size = std::max(a: CommonRes.Size, b: Sym.getCommonSize());
1105 if (uint32_t SymAlignValue = Sym.getCommonAlignment()) {
1106 CommonRes.Alignment =
1107 std::max(a: Align(SymAlignValue), b: CommonRes.Alignment);
1108 }
1109 CommonRes.Prevailing |= R.Prevailing;
1110 }
1111 }
1112
1113 if (!M.getComdatSymbolTable().empty())
1114 for (GlobalValue &GV : M.global_values())
1115 handleNonPrevailingComdat(GV, NonPrevailingComdats);
1116
1117 // Prepend ".lto_discard <sym>, <sym>*" directive to each module inline asm
1118 // block.
1119 if (M.hasModuleInlineAsm()) {
1120 std::string NewIA = ".lto_discard";
1121 if (!NonPrevailingAsmSymbols.empty()) {
1122 // Don't dicard a symbol if there is a live .symver for it.
1123 ModuleSymbolTable::CollectAsmSymvers(
1124 M, AsmSymver: [&](StringRef Name, StringRef Alias) {
1125 if (!NonPrevailingAsmSymbols.count(V: Alias))
1126 NonPrevailingAsmSymbols.erase(V: Name);
1127 });
1128 NewIA += " " + llvm::join(R&: NonPrevailingAsmSymbols, Separator: ", ");
1129 }
1130 NewIA += "\n";
1131 M.prependModuleInlineAsm(Fragment: {NewIA, M.getModuleInlineAsm().front().Props});
1132 }
1133
1134 assert(MsymI == MsymE);
1135 return std::make_pair(x: std::move(Mod), y&: Res);
1136}
1137
1138Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod,
1139 bool LivenessFromIndex) {
1140 llvm::TimeTraceScope timeScope("LTO link regular LTO");
1141 std::vector<GlobalValue *> Keep;
1142 for (GlobalValue *GV : Mod.Keep) {
1143 if (LivenessFromIndex) {
1144 const auto GUID = GV->getGUIDOrFallback();
1145 if (!ThinLTO.CombinedIndex.isGUIDLive(GUID)) {
1146 if (Function *F = dyn_cast<Function>(Val: GV)) {
1147 if (DiagnosticOutputFile) {
1148 if (Error Err = F->materialize())
1149 return Err;
1150 auto R = OptimizationRemark(DEBUG_TYPE, "deadfunction", F);
1151 R << ore::NV("Function", F) << " not added to the combined module ";
1152 emitRemark(Remark&: R);
1153 }
1154 }
1155 continue;
1156 }
1157 }
1158
1159 if (!GV->hasAvailableExternallyLinkage()) {
1160 Keep.push_back(x: GV);
1161 continue;
1162 }
1163
1164 // Only link available_externally definitions if we don't already have a
1165 // definition.
1166 GlobalValue *CombinedGV =
1167 RegularLTO.CombinedModule->getNamedValue(Name: GV->getName());
1168 if (CombinedGV && !CombinedGV->isDeclaration())
1169 continue;
1170
1171 Keep.push_back(x: GV);
1172 }
1173
1174 return RegularLTO.Mover->move(Src: std::move(Mod.M), ValuesToLink: Keep, AddLazyFor: nullptr,
1175 /* IsPerformingImport */ false);
1176}
1177
1178// Add a ThinLTO module to the link.
1179Expected<ArrayRef<SymbolResolution>>
1180LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
1181 ArrayRef<SymbolResolution> Res) {
1182 llvm::TimeTraceScope timeScope("LTO add thin LTO");
1183 const auto BMID = BM.getModuleIdentifier();
1184 ArrayRef<SymbolResolution> ResTmp = Res;
1185 DenseSet<StringRef> Prevailing;
1186 for (const InputFile::Symbol &Sym : Syms) {
1187 assert(!ResTmp.empty());
1188 const SymbolResolution &R = ResTmp.consume_front();
1189 if (!Sym.getIRName().empty() && R.Prevailing)
1190 Prevailing.insert(V: Sym.getIRName());
1191 }
1192
1193 // Track the GUIDs stored in the bitcode GUID table.
1194 StringMap<GlobalValue::GUID> IRSpecifiedGUIDs;
1195 if (Error Err = BM.readSummary(
1196 CombinedIndex&: ThinLTO.CombinedIndex, ModulePath: BMID,
1197 IsPrevailing: [&](StringRef Name) { return (Prevailing.count(V: Name) > 0); },
1198 OnValueInfo: [&](ValueInfo VI) {
1199 auto IT = IRSpecifiedGUIDs.insert(KV: {VI.name(), VI.getGUID()});
1200 (void)IT;
1201 assert(IT.second);
1202 if (auto GRIt = GlobalResolutions->find(Val: VI.name());
1203 GRIt != GlobalResolutions->end() &&
1204 Prevailing.count(V: VI.name())) {
1205 GRIt->second.setGUID(VI.getGUID());
1206 }
1207 }))
1208 return Err;
1209 LLVM_DEBUG(dbgs() << "Module " << BMID << "\n");
1210
1211 for (const InputFile::Symbol &Sym : Syms) {
1212 assert(!Res.empty());
1213 const SymbolResolution &R = Res.consume_front();
1214 auto GUIDIter = IRSpecifiedGUIDs.find(Key: Sym.getIRName());
1215 // The bitcode GUID table might not be present if this is an old bitcode
1216 // file. For backwards-compatibility, just compute the GUID now in that
1217 // case.
1218 auto GUID =
1219 GUIDIter == IRSpecifiedGUIDs.end()
1220 ? GlobalValue::getGUIDAssumingExternalLinkage(
1221 GlobalName: GlobalValue::getGlobalIdentifier(
1222 Name: Sym.getIRName(), Linkage: GlobalValue::ExternalLinkage, FileName: ""))
1223 : GUIDIter->second;
1224 if (!Sym.getIRName().empty() &&
1225 (R.Prevailing || R.FinalDefinitionInLinkageUnit)) {
1226 if (R.Prevailing) {
1227 ThinLTO.setPrevailingModuleForGUID(GUID, Module: BMID);
1228 // For linker redefined symbols (via --wrap or --defsym) we want to
1229 // switch the linkage to `weak` to prevent IPOs from happening.
1230 // Find the summary in the module for this very GV and record the new
1231 // linkage so that we can switch it when we import the GV.
1232 if (R.LinkerRedefined)
1233 if (auto *S = ThinLTO.CombinedIndex.findSummaryInModule(ValueGUID: GUID, ModuleId: BMID))
1234 S->setLinkage(GlobalValue::WeakAnyLinkage);
1235 }
1236
1237 // If the linker resolved the symbol to a local definition then mark it
1238 // as local in the summary for the module we are adding.
1239 if (R.FinalDefinitionInLinkageUnit) {
1240 if (auto *S = ThinLTO.CombinedIndex.findSummaryInModule(ValueGUID: GUID, ModuleId: BMID)) {
1241 S->setDSOLocal(true);
1242 }
1243 }
1244 }
1245 }
1246
1247 if (!ThinLTO.ModuleMap.insert(KV: {BMID, BM}).second)
1248 return make_error<StringError>(
1249 Args: "Expected at most one ThinLTO module per bitcode file",
1250 Args: inconvertibleErrorCode());
1251
1252 if (!Conf.ThinLTOModulesToCompile.empty()) {
1253 if (!ThinLTO.ModulesToCompile)
1254 ThinLTO.ModulesToCompile = ModuleMapType();
1255 // This is a fuzzy name matching where only modules with name containing the
1256 // specified switch values are going to be compiled.
1257 for (const std::string &Name : Conf.ThinLTOModulesToCompile) {
1258 if (BMID.contains(Other: Name)) {
1259 ThinLTO.ModulesToCompile->insert(KV: {BMID, BM});
1260 LLVM_DEBUG(dbgs() << "[ThinLTO] Selecting " << BMID << " to compile\n");
1261 break;
1262 }
1263 }
1264 }
1265
1266 return Res;
1267}
1268
1269unsigned LTO::getMaxTasks() const {
1270 CalledGetMaxTasks = true;
1271 auto ModuleCount = ThinLTO.ModulesToCompile ? ThinLTO.ModulesToCompile->size()
1272 : ThinLTO.ModuleMap.size();
1273 return RegularLTO.ParallelCodeGenParallelismLevel + ModuleCount;
1274}
1275
1276// If only some of the modules were split, we cannot correctly handle
1277// code that contains type tests or type checked loads.
1278Error LTO::checkPartiallySplit() {
1279 if (!ThinLTO.CombinedIndex.partiallySplitLTOUnits())
1280 return Error::success();
1281
1282 const Module *Combined = RegularLTO.CombinedModule.get();
1283 Function *TypeTestFunc =
1284 Intrinsic::getDeclarationIfExists(M: Combined, id: Intrinsic::type_test);
1285 Function *TypeCheckedLoadFunc =
1286 Intrinsic::getDeclarationIfExists(M: Combined, id: Intrinsic::type_checked_load);
1287 Function *TypeCheckedLoadRelativeFunc = Intrinsic::getDeclarationIfExists(
1288 M: Combined, id: Intrinsic::type_checked_load_relative);
1289
1290 // First check if there are type tests / type checked loads in the
1291 // merged regular LTO module IR.
1292 if ((TypeTestFunc && !TypeTestFunc->use_empty()) ||
1293 (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty()) ||
1294 (TypeCheckedLoadRelativeFunc &&
1295 !TypeCheckedLoadRelativeFunc->use_empty()))
1296 return make_error<StringError>(
1297 Args: "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1298 Args: inconvertibleErrorCode());
1299
1300 // Otherwise check if there are any recorded in the combined summary from the
1301 // ThinLTO modules.
1302 for (auto &P : ThinLTO.CombinedIndex) {
1303 for (auto &S : P.second.getSummaryList()) {
1304 auto *FS = dyn_cast<FunctionSummary>(Val: S.get());
1305 if (!FS)
1306 continue;
1307 if (!FS->type_test_assume_vcalls().empty() ||
1308 !FS->type_checked_load_vcalls().empty() ||
1309 !FS->type_test_assume_const_vcalls().empty() ||
1310 !FS->type_checked_load_const_vcalls().empty() ||
1311 !FS->type_tests().empty())
1312 return make_error<StringError>(
1313 Args: "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1314 Args: inconvertibleErrorCode());
1315 }
1316 }
1317 return Error::success();
1318}
1319
1320Error LTO::run(AddStreamFn AddStream, FileCache Cache) {
1321 // Call the base class cleanup() explicitly since run() may be invoked on a
1322 // derived LTO object.
1323 llvm::scope_exit CleanUp([this]() { LTO::cleanup(); });
1324
1325 // Compute "dead" symbols, we don't want to import/export these!
1326 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
1327 DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions;
1328 for (auto &Res : *GlobalResolutions) {
1329 // Normally resolution have IR name of symbol. We can do nothing here
1330 // otherwise. See comments in GlobalResolution struct for more details.
1331 if (Res.second.IRName.empty())
1332 continue;
1333
1334 GlobalValue::GUID GUID = Res.second.getGUID();
1335
1336 if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
1337 GUIDPreservedSymbols.insert(V: GUID);
1338
1339 if (Res.second.ExportDynamic)
1340 DynamicExportSymbols.insert(V: GUID);
1341
1342 GUIDPrevailingResolutions[GUID] =
1343 Res.second.Prevailing ? PrevailingType::Yes : PrevailingType::No;
1344 }
1345
1346 auto isPrevailing = [&](GlobalValue::GUID G) {
1347 auto It = GUIDPrevailingResolutions.find(Val: G);
1348 if (It == GUIDPrevailingResolutions.end())
1349 return PrevailingType::Unknown;
1350 return It->second;
1351 };
1352 computeDeadSymbolsWithConstProp(Index&: ThinLTO.CombinedIndex, GUIDPreservedSymbols,
1353 isPrevailing, ImportEnabled: Conf.OptLevel > 0);
1354
1355 // Setup output file to emit statistics.
1356 auto StatsFileOrErr = setupStatsFile(Conf.StatsFile);
1357 if (!StatsFileOrErr)
1358 return StatsFileOrErr.takeError();
1359 std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
1360
1361 if (Error Err = setupOptimizationRemarks())
1362 return Err;
1363
1364 // TODO: Ideally this would be controlled automatically by detecting that we
1365 // are linking with an allocator that supports these interfaces, rather than
1366 // an internal option (which would still be needed for tests, however). For
1367 // example, if the library exported a symbol like __malloc_hot_cold the linker
1368 // could recognize that and set a flag in the lto::Config.
1369 if (SupportsHotColdNew)
1370 ThinLTO.CombinedIndex.setWithSupportsHotColdNew();
1371
1372 Error Result = runRegularLTO(AddStream);
1373 if (!Result)
1374 // This will reset the GlobalResolutions optional once done with it to
1375 // reduce peak memory before importing.
1376 Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
1377
1378 if (StatsFile)
1379 PrintStatisticsJSON(OS&: StatsFile->os());
1380
1381 return Result;
1382}
1383
1384Error LTO::runRegularLTO(AddStreamFn AddStream) {
1385 llvm::TimeTraceScope timeScope("Run regular LTO");
1386 LLVM_DEBUG(dbgs() << "Running regular LTO\n");
1387
1388 // Finalize linking of regular LTO modules containing summaries now that
1389 // we have computed liveness information.
1390 {
1391 llvm::TimeTraceScope timeScope("Link regular LTO");
1392 for (auto &M : RegularLTO.ModsWithSummaries)
1393 if (Error Err = linkRegularLTO(Mod: std::move(M), /*LivenessFromIndex=*/true))
1394 return Err;
1395 }
1396
1397 // Ensure we don't have inconsistently split LTO units with type tests.
1398 // FIXME: this checks both LTO and ThinLTO. It happens to work as we take
1399 // this path both cases but eventually this should be split into two and
1400 // do the ThinLTO checks in `runThinLTO`.
1401 if (Error Err = checkPartiallySplit())
1402 return Err;
1403
1404 // Make sure commons have the right size/alignment: we kept the largest from
1405 // all the prevailing when adding the inputs, and we apply it here.
1406 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
1407 for (auto &I : RegularLTO.Commons) {
1408 if (!I.second.Prevailing)
1409 // Don't do anything if no instance of this common was prevailing.
1410 continue;
1411 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(Name: I.first);
1412 if (OldGV && OldGV->getGlobalSize(DL) == I.second.Size) {
1413 // Don't create a new global if the type is already correct, just make
1414 // sure the alignment is correct.
1415 OldGV->setAlignment(I.second.Alignment);
1416 continue;
1417 }
1418 ArrayType *Ty =
1419 ArrayType::get(ElementType: Type::getInt8Ty(C&: RegularLTO.Ctx), NumElements: I.second.Size);
1420 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
1421 GlobalValue::CommonLinkage,
1422 ConstantAggregateZero::get(Ty), "");
1423 GV->setAlignment(I.second.Alignment);
1424 if (OldGV) {
1425 OldGV->replaceAllUsesWith(V: GV);
1426 GV->takeName(V: OldGV);
1427 OldGV->eraseFromParent();
1428 } else {
1429 GV->setName(I.first);
1430 }
1431 }
1432
1433 bool WholeProgramVisibilityEnabledInLTO =
1434 Conf.HasWholeProgramVisibility &&
1435 // If validation is enabled, upgrade visibility only when all vtables
1436 // have typeinfos.
1437 (!Conf.ValidateAllVtablesHaveTypeInfos || Conf.AllVtablesHaveTypeInfos);
1438
1439 // This returns true when the name is local or not defined. Locals are
1440 // expected to be handled separately.
1441 auto IsVisibleToRegularObj = [&](StringRef name) {
1442 auto It = GlobalResolutions->find(Val: name);
1443 return (It == GlobalResolutions->end() ||
1444 It->second.VisibleOutsideSummary || !It->second.Prevailing);
1445 };
1446
1447 // If allowed, upgrade public vcall visibility metadata to linkage unit
1448 // visibility before whole program devirtualization in the optimizer.
1449 updateVCallVisibilityInModule(
1450 M&: *RegularLTO.CombinedModule, WholeProgramVisibilityEnabledInLTO,
1451 DynamicExportSymbols, ValidateAllVtablesHaveTypeInfos: Conf.ValidateAllVtablesHaveTypeInfos,
1452 IsVisibleToRegularObj);
1453 updatePublicTypeTestCalls(M&: *RegularLTO.CombinedModule,
1454 WholeProgramVisibilityEnabledInLTO);
1455
1456 if (Conf.PreOptModuleHook &&
1457 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
1458 return Error::success();
1459
1460 if (!Conf.CodeGenOnly) {
1461 for (const auto &R : *GlobalResolutions) {
1462 GlobalValue *GV =
1463 RegularLTO.CombinedModule->getNamedValue(Name: R.second.IRName);
1464 if (!R.second.isPrevailingIRSymbol())
1465 continue;
1466 if (R.second.Partition != 0 &&
1467 R.second.Partition != GlobalResolution::External)
1468 continue;
1469
1470 // Ignore symbols defined in other partitions.
1471 // Also skip declarations, which are not allowed to have internal linkage.
1472 if (!GV || GV->hasLocalLinkage() || GV->isDeclaration())
1473 continue;
1474
1475 // Symbols that are marked DLLImport or DLLExport should not be
1476 // internalized, as they are either externally visible or referencing
1477 // external symbols. Symbols that have AvailableExternally or Appending
1478 // linkage might be used by future passes and should be kept as is.
1479 // These linkages are seen in Unified regular LTO, because the process
1480 // of creating split LTO units introduces symbols with that linkage into
1481 // one of the created modules. Normally, only the ThinLTO backend would
1482 // compile this module, but Unified Regular LTO processes both
1483 // modules created by the splitting process as regular LTO modules.
1484 if ((LTOMode == LTOKind::LTOK_UnifiedRegular) &&
1485 ((GV->getDLLStorageClass() != GlobalValue::DefaultStorageClass) ||
1486 GV->hasAvailableExternallyLinkage() || GV->hasAppendingLinkage()))
1487 continue;
1488
1489 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
1490 : GlobalValue::UnnamedAddr::None);
1491 if (EnableLTOInternalization && R.second.Partition == 0)
1492 GV->setLinkage(GlobalValue::InternalLinkage);
1493 }
1494
1495 if (Conf.PostInternalizeModuleHook &&
1496 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
1497 return Error::success();
1498 }
1499
1500 if (!RegularLTO.EmptyCombinedModule || Conf.AlwaysEmitRegularLTOObj) {
1501 if (Error Err = backend(
1502 C: Conf, AddStream, ParallelCodeGenParallelismLevel: RegularLTO.ParallelCodeGenParallelismLevel,
1503 M&: *RegularLTO.CombinedModule, CombinedIndex&: ThinLTO.CombinedIndex, BitcodeLibFuncs))
1504 return Err;
1505 }
1506
1507 return Error::success();
1508}
1509
1510SmallVector<const char *> LTO::getRuntimeLibcallSymbols(const Triple &TT) {
1511 RTLIB::RuntimeLibcallsInfo Libcalls(TT);
1512 SmallVector<const char *> LibcallSymbols;
1513 LibcallSymbols.reserve(N: Libcalls.getNumAvailableLibcallImpls());
1514
1515 for (RTLIB::LibcallImpl Impl : RTLIB::libcall_impls()) {
1516 if (Libcalls.isAvailable(Impl))
1517 LibcallSymbols.push_back(Elt: Libcalls.getLibcallImplName(CallImpl: Impl).data());
1518 }
1519
1520 return LibcallSymbols;
1521}
1522
1523SmallVector<StringRef> LTO::getLibFuncSymbols(const Triple &TT,
1524 StringSaver &Saver) {
1525 auto TLII = std::make_unique<TargetLibraryInfoImpl>(args: TT);
1526 TargetLibraryInfo TLI(*TLII);
1527 SmallVector<StringRef> LibFuncSymbols;
1528 LibFuncSymbols.reserve(N: LibFunc::NumLibFuncs);
1529 for (unsigned I = LibFunc::Begin_LibFunc; I != LibFunc::End_LibFunc; ++I) {
1530 LibFunc F = static_cast<LibFunc>(I);
1531 if (TLI.has(F))
1532 LibFuncSymbols.push_back(Elt: Saver.save(S: TLI.getName(F)).data());
1533 }
1534 return LibFuncSymbols;
1535}
1536
1537Error ThinBackendProc::emitFiles(
1538 const FunctionImporter::ImportMapTy &ImportList, unsigned Task,
1539 llvm::StringRef ModulePath, const std::string &NewModulePath) const {
1540 return emitFiles(ImportList, Task, ModulePath, NewModulePath,
1541 SummaryPath: NewModulePath + ".thinlto.bc");
1542}
1543
1544Error ThinBackendProc::emitFiles(
1545 const FunctionImporter::ImportMapTy &ImportList, unsigned Task,
1546 llvm::StringRef ModulePath, const std::string &NewModulePath,
1547 StringRef SummaryPath) const {
1548 ModuleToSummariesForIndexTy ModuleToSummariesForIndex;
1549 GVSummaryPtrSet DeclarationSummaries;
1550
1551 std::error_code EC;
1552 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
1553 ImportList, ModuleToSummariesForIndex,
1554 DecSummaries&: DeclarationSummaries);
1555 // Resolve the output stream (either file-backed or callback-provided) for the
1556 // index file.
1557 std::unique_ptr<raw_pwrite_stream> OS;
1558 if (Conf.GetSummaryIndexOutputStream) {
1559 OS = Conf.GetSummaryIndexOutputStream(Task);
1560 assert(OS && "GetSummaryIndexOutputStream returned null");
1561 } else {
1562 auto FileOS = std::make_unique<raw_fd_ostream>(args&: SummaryPath, args&: EC,
1563 args: sys::fs::OpenFlags::OF_None);
1564 if (EC)
1565 return createFileError(F: "cannot open " + Twine(SummaryPath), EC);
1566 OS = std::move(FileOS);
1567 }
1568
1569 writeIndexToFile(Index: CombinedIndex, Out&: *OS, ModuleToSummariesForIndex: &ModuleToSummariesForIndex,
1570 DecSummaries: &DeclarationSummaries);
1571
1572 // Emit imports files if requested, using callback if provided.
1573 if (Conf.GetImportsListOutputArray) {
1574 std::vector<std::string> &ImportsListRef =
1575 Conf.GetImportsListOutputArray(Task);
1576 processImportsFiles(
1577 ModulePath, ModuleToSummariesForIndex,
1578 F: [&](StringRef M) { ImportsListRef.push_back(x: M.str()); });
1579 } else if (ShouldEmitImportsFiles) {
1580 if (Error E = EmitImportsFiles(ModulePath, OutputFilename: NewModulePath + ".imports",
1581 ModuleToSummariesForIndex))
1582 return E;
1583 }
1584 return Error::success();
1585}
1586
1587namespace {
1588/// Base class for ThinLTO backends that perform code generation and insert the
1589/// generated files back into the link.
1590class CGThinBackend : public ThinBackendProc {
1591protected:
1592 DenseSet<GlobalValue::GUID> CfiFunctionDefs;
1593 DenseSet<GlobalValue::GUID> CfiFunctionDecls;
1594 bool ShouldEmitIndexFiles;
1595
1596public:
1597 CGThinBackend(
1598 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1599 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1600 lto::IndexWriteCallback OnWrite, bool ShouldEmitIndexFiles,
1601 bool ShouldEmitImportsFiles, ThreadPoolStrategy ThinLTOParallelism)
1602 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
1603 OnWrite, ShouldEmitImportsFiles, ThinLTOParallelism),
1604 ShouldEmitIndexFiles(ShouldEmitIndexFiles) {
1605 auto &Defs = CombinedIndex.cfiFunctionDefs();
1606 CfiFunctionDefs.insert_range(R: Defs.getExportedThinLTOGUIDs());
1607 auto &Decls = CombinedIndex.cfiFunctionDecls();
1608 CfiFunctionDecls.insert_range(R: Decls.getExportedThinLTOGUIDs());
1609 }
1610};
1611
1612/// This backend performs code generation by scheduling a job to run on
1613/// an in-process thread when invoked for each task.
1614class InProcessThinBackend : public CGThinBackend {
1615protected:
1616 // Callback used to add generated native object files to the link by code
1617 // generating directly into the returned output stream.
1618 AddStreamFn AddStream;
1619 FileCache Cache;
1620 ArrayRef<StringRef> BitcodeLibFuncs;
1621
1622public:
1623 InProcessThinBackend(
1624 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1625 ThreadPoolStrategy ThinLTOParallelism,
1626 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1627 AddStreamFn AddStream, FileCache Cache, lto::IndexWriteCallback OnWrite,
1628 bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles,
1629 ArrayRef<StringRef> BitcodeLibFuncs)
1630 : CGThinBackend(Conf, CombinedIndex, ModuleToDefinedGVSummaries, OnWrite,
1631 ShouldEmitIndexFiles, ShouldEmitImportsFiles,
1632 ThinLTOParallelism),
1633 AddStream(std::move(AddStream)), Cache(std::move(Cache)),
1634 BitcodeLibFuncs(BitcodeLibFuncs) {}
1635
1636 virtual Error runThinLTOBackendThread(
1637 AddStreamFn AddStream, FileCache Cache, unsigned Task, BitcodeModule BM,
1638 ModuleSummaryIndex &CombinedIndex,
1639 const FunctionImporter::ImportMapTy &ImportList,
1640 const FunctionImporter::ExportSetTy &ExportList,
1641 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1642 const GVSummaryMapTy &DefinedGlobals,
1643 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1644 auto ModuleID = BM.getModuleIdentifier();
1645 llvm::TimeTraceScope timeScope("Run ThinLTO backend thread (in-process)",
1646 ModuleID);
1647 auto RunThinBackend = [&](AddStreamFn AddStream) {
1648 LTOLLVMContext BackendContext(Conf);
1649 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(Context&: BackendContext);
1650 if (!MOrErr)
1651 return MOrErr.takeError();
1652
1653 return thinBackend(C: Conf, Task, AddStream, M&: **MOrErr, CombinedIndex,
1654 ImportList, DefinedGlobals, ModuleMap: &ModuleMap,
1655 CodeGenOnly: Conf.CodeGenOnly, BitcodeLibFuncs);
1656 };
1657 if (ShouldEmitIndexFiles) {
1658 if (auto E = emitFiles(ImportList, Task, ModulePath: ModuleID, NewModulePath: ModuleID.str()))
1659 return E;
1660 }
1661
1662 if (!Cache.isValid() || !CombinedIndex.modulePaths().count(Key: ModuleID) ||
1663 all_of(Range: CombinedIndex.getModuleHash(ModPath: ModuleID),
1664 P: [](uint32_t V) { return V == 0; }))
1665 // Cache disabled or no entry for this module in the combined index or
1666 // no module hash.
1667 return RunThinBackend(AddStream);
1668
1669 // The module may be cached, this helps handling it.
1670 std::string Key = computeLTOCacheKey(
1671 Conf, Index: CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1672 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1673 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task, Key, ModuleID);
1674 if (Error Err = CacheAddStreamOrErr.takeError())
1675 return Err;
1676 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1677 if (CacheAddStream)
1678 return RunThinBackend(CacheAddStream);
1679
1680 return Error::success();
1681 }
1682
1683 Error start(
1684 unsigned Task, BitcodeModule BM,
1685 const FunctionImporter::ImportMapTy &ImportList,
1686 const FunctionImporter::ExportSetTy &ExportList,
1687 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1688 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1689 StringRef ModulePath = BM.getModuleIdentifier();
1690 assert(ModuleToDefinedGVSummaries.count(ModulePath));
1691 const GVSummaryMapTy &DefinedGlobals =
1692 ModuleToDefinedGVSummaries.find(Val: ModulePath)->second;
1693 BackendThreadPool.async(
1694 F: [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1695 const FunctionImporter::ImportMapTy &ImportList,
1696 const FunctionImporter::ExportSetTy &ExportList,
1697 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1698 &ResolvedODR,
1699 const GVSummaryMapTy &DefinedGlobals,
1700 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1701 if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1702 timeTraceProfilerInitialize(TimeTraceGranularity: Conf.TimeTraceGranularity,
1703 ProcName: "thin backend");
1704 Error E = runThinLTOBackendThread(
1705 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1706 ResolvedODR, DefinedGlobals, ModuleMap);
1707 if (E) {
1708 std::unique_lock<std::mutex> L(ErrMu);
1709 if (Err)
1710 Err = joinErrors(E1: std::move(*Err), E2: std::move(E));
1711 else
1712 Err = std::move(E);
1713 }
1714 if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1715 timeTraceProfilerFinishThread();
1716 },
1717 ArgList&: BM, ArgList: std::ref(t&: CombinedIndex), ArgList: std::ref(t: ImportList), ArgList: std::ref(t: ExportList),
1718 ArgList: std::ref(t: ResolvedODR), ArgList: std::ref(t: DefinedGlobals), ArgList: std::ref(t&: ModuleMap));
1719
1720 if (OnWrite)
1721 OnWrite(std::string(ModulePath));
1722 return Error::success();
1723 }
1724};
1725
1726/// This backend is utilized in the first round of a two-codegen round process.
1727/// It first saves optimized bitcode files to disk before the codegen process
1728/// begins. After codegen, it stores the resulting object files in a scratch
1729/// buffer. Note the codegen data stored in the scratch buffer will be extracted
1730/// and merged in the subsequent step.
1731class FirstRoundThinBackend : public InProcessThinBackend {
1732 AddStreamFn IRAddStream;
1733 FileCache IRCache;
1734
1735public:
1736 FirstRoundThinBackend(
1737 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1738 ThreadPoolStrategy ThinLTOParallelism,
1739 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1740 AddStreamFn CGAddStream, FileCache CGCache,
1741 ArrayRef<StringRef> BitcodeLibFuncs, AddStreamFn IRAddStream,
1742 FileCache IRCache)
1743 : InProcessThinBackend(Conf, CombinedIndex, ThinLTOParallelism,
1744 ModuleToDefinedGVSummaries, std::move(CGAddStream),
1745 std::move(CGCache), /*OnWrite=*/nullptr,
1746 /*ShouldEmitIndexFiles=*/false,
1747 /*ShouldEmitImportsFiles=*/false, BitcodeLibFuncs),
1748 IRAddStream(std::move(IRAddStream)), IRCache(std::move(IRCache)) {}
1749
1750 Error runThinLTOBackendThread(
1751 AddStreamFn CGAddStream, FileCache CGCache, unsigned Task,
1752 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1753 const FunctionImporter::ImportMapTy &ImportList,
1754 const FunctionImporter::ExportSetTy &ExportList,
1755 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1756 const GVSummaryMapTy &DefinedGlobals,
1757 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1758 auto ModuleID = BM.getModuleIdentifier();
1759 llvm::TimeTraceScope timeScope("Run ThinLTO backend thread (first round)",
1760 ModuleID);
1761 auto RunThinBackend = [&](AddStreamFn CGAddStream,
1762 AddStreamFn IRAddStream) {
1763 LTOLLVMContext BackendContext(Conf);
1764 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(Context&: BackendContext);
1765 if (!MOrErr)
1766 return MOrErr.takeError();
1767
1768 return thinBackend(C: Conf, Task, AddStream: CGAddStream, M&: **MOrErr, CombinedIndex,
1769 ImportList, DefinedGlobals, ModuleMap: &ModuleMap,
1770 CodeGenOnly: Conf.CodeGenOnly, BitcodeLibFuncs, IRAddStream);
1771 };
1772 // Like InProcessThinBackend, we produce index files as needed for
1773 // FirstRoundThinBackend. However, these files are not generated for
1774 // SecondRoundThinBackend.
1775 if (ShouldEmitIndexFiles) {
1776 if (auto E = emitFiles(ImportList, Task, ModulePath: ModuleID, NewModulePath: ModuleID.str()))
1777 return E;
1778 }
1779
1780 assert((CGCache.isValid() == IRCache.isValid()) &&
1781 "Both caches for CG and IR should have matching availability");
1782 if (!CGCache.isValid() || !CombinedIndex.modulePaths().count(Key: ModuleID) ||
1783 all_of(Range: CombinedIndex.getModuleHash(ModPath: ModuleID),
1784 P: [](uint32_t V) { return V == 0; }))
1785 // Cache disabled or no entry for this module in the combined index or
1786 // no module hash.
1787 return RunThinBackend(CGAddStream, IRAddStream);
1788
1789 // Get CGKey for caching object in CGCache.
1790 std::string CGKey = computeLTOCacheKey(
1791 Conf, Index: CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1792 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1793 Expected<AddStreamFn> CacheCGAddStreamOrErr =
1794 CGCache(Task, CGKey, ModuleID);
1795 if (Error Err = CacheCGAddStreamOrErr.takeError())
1796 return Err;
1797 AddStreamFn &CacheCGAddStream = *CacheCGAddStreamOrErr;
1798
1799 // Get IRKey for caching (optimized) IR in IRCache with an extra ID.
1800 std::string IRKey = recomputeLTOCacheKey(Key: CGKey, /*ExtraID=*/"IR");
1801 Expected<AddStreamFn> CacheIRAddStreamOrErr =
1802 IRCache(Task, IRKey, ModuleID);
1803 if (Error Err = CacheIRAddStreamOrErr.takeError())
1804 return Err;
1805 AddStreamFn &CacheIRAddStream = *CacheIRAddStreamOrErr;
1806
1807 // Ideally, both CG and IR caching should be synchronized. However, in
1808 // practice, their availability may differ due to different expiration
1809 // times. Therefore, if either cache is missing, the backend process is
1810 // triggered.
1811 if (CacheCGAddStream || CacheIRAddStream) {
1812 LLVM_DEBUG(dbgs() << "[FirstRound] Cache Miss for "
1813 << BM.getModuleIdentifier() << "\n");
1814 return RunThinBackend(CacheCGAddStream ? CacheCGAddStream : CGAddStream,
1815 CacheIRAddStream ? CacheIRAddStream : IRAddStream);
1816 }
1817
1818 return Error::success();
1819 }
1820};
1821
1822/// This backend operates in the second round of a two-codegen round process.
1823/// It starts by reading the optimized bitcode files that were saved during the
1824/// first round. The backend then executes the codegen only to further optimize
1825/// the code, utilizing the codegen data merged from the first round. Finally,
1826/// it writes the resulting object files as usual.
1827class SecondRoundThinBackend : public InProcessThinBackend {
1828 std::unique_ptr<SmallVector<StringRef>> IRFiles;
1829 stable_hash CombinedCGDataHash;
1830
1831public:
1832 SecondRoundThinBackend(
1833 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1834 ThreadPoolStrategy ThinLTOParallelism,
1835 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1836 AddStreamFn AddStream, FileCache Cache,
1837 ArrayRef<StringRef> BitcodeLibFuncs,
1838 std::unique_ptr<SmallVector<StringRef>> IRFiles,
1839 stable_hash CombinedCGDataHash)
1840 : InProcessThinBackend(Conf, CombinedIndex, ThinLTOParallelism,
1841 ModuleToDefinedGVSummaries, std::move(AddStream),
1842 std::move(Cache),
1843 /*OnWrite=*/nullptr,
1844 /*ShouldEmitIndexFiles=*/false,
1845 /*ShouldEmitImportsFiles=*/false, BitcodeLibFuncs),
1846 IRFiles(std::move(IRFiles)), CombinedCGDataHash(CombinedCGDataHash) {}
1847
1848 Error runThinLTOBackendThread(
1849 AddStreamFn AddStream, FileCache Cache, unsigned Task, BitcodeModule BM,
1850 ModuleSummaryIndex &CombinedIndex,
1851 const FunctionImporter::ImportMapTy &ImportList,
1852 const FunctionImporter::ExportSetTy &ExportList,
1853 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1854 const GVSummaryMapTy &DefinedGlobals,
1855 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1856 auto ModuleID = BM.getModuleIdentifier();
1857 llvm::TimeTraceScope timeScope("Run ThinLTO backend thread (second round)",
1858 ModuleID);
1859 auto RunThinBackend = [&](AddStreamFn AddStream) {
1860 LTOLLVMContext BackendContext(Conf);
1861 std::unique_ptr<Module> LoadedModule =
1862 cgdata::loadModuleForTwoRounds(OrigModule&: BM, Task, Context&: BackendContext, IRFiles: *IRFiles);
1863
1864 return thinBackend(C: Conf, Task, AddStream, M&: *LoadedModule, CombinedIndex,
1865 ImportList, DefinedGlobals, ModuleMap: &ModuleMap,
1866 /*CodeGenOnly=*/true, BitcodeLibFuncs);
1867 };
1868 if (!Cache.isValid() || !CombinedIndex.modulePaths().count(Key: ModuleID) ||
1869 all_of(Range: CombinedIndex.getModuleHash(ModPath: ModuleID),
1870 P: [](uint32_t V) { return V == 0; }))
1871 // Cache disabled or no entry for this module in the combined index or
1872 // no module hash.
1873 return RunThinBackend(AddStream);
1874
1875 // Get Key for caching the final object file in Cache with the combined
1876 // CGData hash.
1877 std::string Key = computeLTOCacheKey(
1878 Conf, Index: CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1879 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1880 Key = recomputeLTOCacheKey(Key,
1881 /*ExtraID=*/std::to_string(val: CombinedCGDataHash));
1882 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task, Key, ModuleID);
1883 if (Error Err = CacheAddStreamOrErr.takeError())
1884 return Err;
1885 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1886
1887 if (CacheAddStream) {
1888 LLVM_DEBUG(dbgs() << "[SecondRound] Cache Miss for "
1889 << BM.getModuleIdentifier() << "\n");
1890 return RunThinBackend(CacheAddStream);
1891 }
1892
1893 return Error::success();
1894 }
1895};
1896} // end anonymous namespace
1897
1898ThinBackend lto::createInProcessThinBackend(ThreadPoolStrategy Parallelism,
1899 lto::IndexWriteCallback OnWrite,
1900 bool ShouldEmitIndexFiles,
1901 bool ShouldEmitImportsFiles) {
1902 auto Func =
1903 [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1904 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1905 AddStreamFn AddStream, FileCache Cache,
1906 ArrayRef<StringRef> BitcodeLibFuncs) {
1907 return std::make_unique<InProcessThinBackend>(
1908 args: Conf, args&: CombinedIndex, args: Parallelism, args: ModuleToDefinedGVSummaries,
1909 args&: AddStream, args&: Cache, args: OnWrite, args: ShouldEmitIndexFiles,
1910 args: ShouldEmitImportsFiles, args&: BitcodeLibFuncs);
1911 };
1912 return ThinBackend(Func, Parallelism);
1913}
1914
1915StringLiteral lto::getThinLTODefaultCPU(const Triple &TheTriple) {
1916 if (!TheTriple.isOSDarwin())
1917 return "";
1918 if (TheTriple.getArch() == Triple::x86_64)
1919 return "core2";
1920 if (TheTriple.getArch() == Triple::x86)
1921 return "yonah";
1922 if (TheTriple.isArm64e())
1923 return "apple-a12";
1924 if (TheTriple.getArch() == Triple::aarch64 ||
1925 TheTriple.getArch() == Triple::aarch64_32)
1926 return "cyclone";
1927 return "";
1928}
1929
1930// Given the original \p Path to an output file, replace any path
1931// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
1932// resulting directory if it does not yet exist.
1933std::string lto::getThinLTOOutputFile(StringRef Path, StringRef OldPrefix,
1934 StringRef NewPrefix) {
1935 if (OldPrefix.empty() && NewPrefix.empty())
1936 return std::string(Path);
1937 SmallString<128> NewPath(Path);
1938 llvm::sys::path::replace_path_prefix(Path&: NewPath, OldPrefix, NewPrefix);
1939 StringRef ParentPath = llvm::sys::path::parent_path(path: NewPath.str());
1940 if (!ParentPath.empty()) {
1941 // Make sure the new directory exists, creating it if necessary.
1942 if (std::error_code EC = llvm::sys::fs::create_directories(path: ParentPath))
1943 llvm::errs() << "warning: could not create directory '" << ParentPath
1944 << "': " << EC.message() << '\n';
1945 }
1946 return std::string(NewPath);
1947}
1948
1949namespace {
1950class WriteIndexesThinBackend : public ThinBackendProc {
1951 std::string OldPrefix, NewPrefix, NativeObjectPrefix;
1952 raw_fd_ostream *LinkedObjectsFile;
1953 DenseSet<GlobalValue::GUID> CfiFunctionDefs;
1954 DenseSet<GlobalValue::GUID> CfiFunctionDecls;
1955
1956public:
1957 WriteIndexesThinBackend(
1958 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1959 ThreadPoolStrategy ThinLTOParallelism,
1960 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1961 std::string OldPrefix, std::string NewPrefix,
1962 std::string NativeObjectPrefix, bool ShouldEmitImportsFiles,
1963 raw_fd_ostream *LinkedObjectsFile, lto::IndexWriteCallback OnWrite)
1964 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
1965 OnWrite, ShouldEmitImportsFiles, ThinLTOParallelism),
1966 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
1967 NativeObjectPrefix(NativeObjectPrefix),
1968 LinkedObjectsFile(LinkedObjectsFile) {
1969 auto Defs = CombinedIndex.cfiFunctionDefs().getExportedThinLTOGUIDs();
1970 CfiFunctionDefs.insert(I: Defs.begin(), E: Defs.end());
1971 auto Decls = CombinedIndex.cfiFunctionDecls().getExportedThinLTOGUIDs();
1972 CfiFunctionDecls.insert(I: Decls.begin(), E: Decls.end());
1973 }
1974
1975 Error start(
1976 unsigned Task, BitcodeModule BM,
1977 const FunctionImporter::ImportMapTy &ImportList,
1978 const FunctionImporter::ExportSetTy &ExportList,
1979 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1980 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1981 StringRef ModulePath = BM.getModuleIdentifier();
1982
1983 // The contents of this file may be used as input to a native link, and must
1984 // therefore contain the processed modules in a determinstic order that
1985 // match the order they are provided on the command line. For that reason,
1986 // we cannot include this in the asynchronously executed lambda below.
1987 if (LinkedObjectsFile) {
1988 std::string ObjectPrefix =
1989 NativeObjectPrefix.empty() ? NewPrefix : NativeObjectPrefix;
1990 std::string LinkedObjectsFilePath =
1991 getThinLTOOutputFile(Path: ModulePath, OldPrefix, NewPrefix: ObjectPrefix);
1992 *LinkedObjectsFile << LinkedObjectsFilePath << '\n';
1993 }
1994
1995 BackendThreadPool.async(
1996 F: [this](unsigned Task, const StringRef ModulePath,
1997 const FunctionImporter::ImportMapTy &ImportList,
1998 const FunctionImporter::ExportSetTy &ExportList,
1999 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
2000 &ResolvedODR,
2001 const std::string &OldPrefix, const std::string &NewPrefix) {
2002 std::string NewModulePath =
2003 getThinLTOOutputFile(Path: ModulePath, OldPrefix, NewPrefix);
2004 auto E = emitFiles(ImportList, Task, ModulePath, NewModulePath);
2005 if (E) {
2006 std::unique_lock<std::mutex> L(ErrMu);
2007 if (Err)
2008 Err = joinErrors(E1: std::move(*Err), E2: std::move(E));
2009 else
2010 Err = std::move(E);
2011 }
2012 assert(ModuleToDefinedGVSummaries.count(ModulePath));
2013 const GVSummaryMapTy &DefinedGlobals =
2014 ModuleToDefinedGVSummaries.find(Val: ModulePath)->second;
2015
2016 // DTLTO needs the per-module LTO cache key to probe the cache.
2017 if (Conf.GetCacheKeyOutputString) {
2018 std::string &CacheKey = Conf.GetCacheKeyOutputString(Task);
2019 CacheKey = computeLTOCacheKey(
2020 Conf, Index: CombinedIndex, ModuleID: ModulePath, ImportList, ExportList,
2021 ResolvedODR, DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
2022 }
2023 },
2024 ArgList&: Task, ArgList&: ModulePath, ArgList: ImportList, ArgList: ExportList, ArgList: ResolvedODR, ArgList&: OldPrefix,
2025 ArgList&: NewPrefix);
2026
2027 if (OnWrite)
2028 OnWrite(std::string(ModulePath));
2029 return Error::success();
2030 }
2031
2032 bool isSensitiveToInputOrder() override {
2033 // The order which modules are written to LinkedObjectsFile should be
2034 // deterministic and match the order they are passed on the command line.
2035 return true;
2036 }
2037};
2038} // end anonymous namespace
2039
2040ThinBackend lto::createWriteIndexesThinBackend(
2041 ThreadPoolStrategy Parallelism, std::string OldPrefix,
2042 std::string NewPrefix, std::string NativeObjectPrefix,
2043 bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile,
2044 IndexWriteCallback OnWrite) {
2045 auto Func =
2046 [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
2047 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
2048 AddStreamFn AddStream, FileCache Cache,
2049 ArrayRef<StringRef> BitcodeLibFuncs) {
2050 return std::make_unique<WriteIndexesThinBackend>(
2051 args: Conf, args&: CombinedIndex, args: Parallelism, args: ModuleToDefinedGVSummaries,
2052 args: OldPrefix, args: NewPrefix, args: NativeObjectPrefix, args: ShouldEmitImportsFiles,
2053 args: LinkedObjectsFile, args: OnWrite);
2054 };
2055 return ThinBackend(Func, Parallelism);
2056}
2057
2058Error LTO::runThinLTO(AddStreamFn AddStream, FileCache Cache,
2059 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
2060 llvm::TimeTraceScope timeScope("Run ThinLTO");
2061 LLVM_DEBUG(dbgs() << "Running ThinLTO\n");
2062 ThinLTO.CombinedIndex.releaseTemporaryMemory();
2063 timeTraceProfilerBegin(Name: "ThinLink", Detail: StringRef(""));
2064 llvm::scope_exit TimeTraceScopeExit([]() {
2065 if (llvm::timeTraceProfilerEnabled())
2066 llvm::timeTraceProfilerEnd();
2067 });
2068 if (ThinLTO.ModuleMap.empty())
2069 return Error::success();
2070
2071 if (ThinLTO.ModulesToCompile && ThinLTO.ModulesToCompile->empty()) {
2072 llvm::errs() << "warning: [ThinLTO] No module compiled\n";
2073 return Error::success();
2074 }
2075
2076 if (Conf.CombinedIndexHook &&
2077 !Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols))
2078 return Error::success();
2079
2080 // Collect for each module the list of function it defines (GUID ->
2081 // Summary).
2082 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(
2083 ThinLTO.ModuleMap.size());
2084 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
2085 ModuleToDefinedGVSummaries);
2086 // Create entries for any modules that didn't have any GV summaries
2087 // (either they didn't have any GVs to start with, or we suppressed
2088 // generation of the summaries because they e.g. had inline assembly
2089 // uses that couldn't be promoted/renamed on export). This is so
2090 // InProcessThinBackend::start can still launch a backend thread, which
2091 // is passed the map of summaries for the module, without any special
2092 // handling for this case.
2093 for (auto &Mod : ThinLTO.ModuleMap)
2094 if (!ModuleToDefinedGVSummaries.count(Val: Mod.first))
2095 ModuleToDefinedGVSummaries.try_emplace(Key: Mod.first);
2096
2097 FunctionImporter::ImportListsTy ImportLists(ThinLTO.ModuleMap.size());
2098 DenseMap<StringRef, FunctionImporter::ExportSetTy> ExportLists(
2099 ThinLTO.ModuleMap.size());
2100 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
2101
2102 if (DumpThinCGSCCs)
2103 ThinLTO.CombinedIndex.dumpSCCs(OS&: outs());
2104
2105 std::set<GlobalValue::GUID> ExportedGUIDs;
2106
2107 bool WholeProgramVisibilityEnabledInLTO =
2108 Conf.HasWholeProgramVisibility &&
2109 // If validation is enabled, upgrade visibility only when all vtables
2110 // have typeinfos.
2111 (!Conf.ValidateAllVtablesHaveTypeInfos || Conf.AllVtablesHaveTypeInfos);
2112 if (hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
2113 ThinLTO.CombinedIndex.setWithWholeProgramVisibility();
2114
2115 // If we're validating, get the vtable symbols that should not be
2116 // upgraded because they correspond to typeIDs outside of index-based
2117 // WPD info.
2118 DenseSet<GlobalValue::GUID> VisibleToRegularObjSymbols;
2119 if (WholeProgramVisibilityEnabledInLTO &&
2120 Conf.ValidateAllVtablesHaveTypeInfos) {
2121 // This returns true when the name is local or not defined. Locals are
2122 // expected to be handled separately.
2123 auto IsVisibleToRegularObj = [&](StringRef name) {
2124 auto It = GlobalResolutions->find(Val: name);
2125 return (It == GlobalResolutions->end() ||
2126 It->second.VisibleOutsideSummary || !It->second.Prevailing);
2127 };
2128
2129 getVisibleToRegularObjVtableGUIDs(Index&: ThinLTO.CombinedIndex,
2130 VisibleToRegularObjSymbols,
2131 IsVisibleToRegularObj);
2132 }
2133
2134 // If allowed, upgrade public vcall visibility to linkage unit visibility in
2135 // the summaries before whole program devirtualization below.
2136 updateVCallVisibilityInIndex(
2137 Index&: ThinLTO.CombinedIndex, WholeProgramVisibilityEnabledInLTO,
2138 DynamicExportSymbols, VisibleToRegularObjSymbols);
2139
2140 // Perform index-based WPD. This will return immediately if there are
2141 // no index entries in the typeIdMetadata map (e.g. if we are instead
2142 // performing IR-based WPD in hybrid regular/thin LTO mode).
2143 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
2144 DenseSet<StringRef> ExternallyVisibleSymbolNames;
2145
2146 // Used by the promotion-time renaming logic. When non-null, this set
2147 // identifies symbols that should not be renamed during promotion.
2148 // It is non-null only when whole-program visibility is enabled and
2149 // renaming is not forced. Otherwise, the default renaming behavior applies.
2150 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr =
2151 (WholeProgramVisibilityEnabledInLTO && !AlwaysRenamePromotedLocals)
2152 ? &ExternallyVisibleSymbolNames
2153 : nullptr;
2154 runWholeProgramDevirtOnIndex(Summary&: ThinLTO.CombinedIndex, ExportedGUIDs,
2155 LocalWPDTargetsMap,
2156 ExternallyVisibleSymbolNamesPtr);
2157
2158 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
2159 return ThinLTO.isPrevailingModuleForGUID(GUID, Module: S->modulePath());
2160 };
2161 if (EnableMemProfContextDisambiguation) {
2162 MemProfContextDisambiguation ContextDisambiguation;
2163 ContextDisambiguation.run(
2164 Index&: ThinLTO.CombinedIndex, isPrevailing, Ctx&: RegularLTO.Ctx,
2165 EmitRemark: [&](StringRef PassName, StringRef RemarkName, const Twine &Msg) {
2166 auto R = OptimizationRemark(PassName.data(), RemarkName,
2167 LinkerRemarkFunction);
2168 R << Msg.str();
2169 emitRemark(Remark&: R);
2170 });
2171 }
2172
2173 // Figure out which symbols need to be internalized. This also needs to happen
2174 // at -O0 because summary-based DCE is implemented using internalization, and
2175 // we must apply DCE consistently with the full LTO module in order to avoid
2176 // undefined references during the final link.
2177 for (auto &Res : *GlobalResolutions) {
2178 // If the symbol does not have external references or it is not prevailing,
2179 // then not need to mark it as exported from a ThinLTO partition.
2180 if (Res.second.Partition != GlobalResolution::External ||
2181 !Res.second.isPrevailingIRSymbol())
2182 continue;
2183 auto GUID = Res.second.getGUID();
2184 // Mark exported unless index-based analysis determined it to be dead.
2185 if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
2186 ExportedGUIDs.insert(x: GUID);
2187 }
2188
2189 // Reset the GlobalResolutions to deallocate the associated memory, as there
2190 // are no further accesses. We specifically want to do this before computing
2191 // cross module importing, which adds to peak memory via the computed import
2192 // and export lists.
2193 releaseGlobalResolutionsMemory();
2194
2195 if (Conf.OptLevel > 0)
2196 ComputeCrossModuleImport(Index: ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
2197 isPrevailing, ImportLists, ExportLists);
2198
2199 // Any functions referenced by the jump table in the regular LTO object must
2200 // be exported.
2201 auto Defs = ThinLTO.CombinedIndex.cfiFunctionDefs().getExportedThinLTOGUIDs();
2202 ExportedGUIDs.insert(first: Defs.begin(), last: Defs.end());
2203 auto Decls =
2204 ThinLTO.CombinedIndex.cfiFunctionDecls().getExportedThinLTOGUIDs();
2205 ExportedGUIDs.insert(first: Decls.begin(), last: Decls.end());
2206
2207 auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
2208 const auto &ExportList = ExportLists.find(Val: ModuleIdentifier);
2209 return (ExportList != ExportLists.end() && ExportList->second.count(V: VI)) ||
2210 ExportedGUIDs.count(x: VI.getGUID());
2211 };
2212
2213 // Update local devirtualized targets that were exported by cross-module
2214 // importing or by other devirtualizations marked in the ExportedGUIDs set.
2215 updateIndexWPDForExports(Summary&: ThinLTO.CombinedIndex, isExported,
2216 LocalWPDTargetsMap, ExternallyVisibleSymbolNamesPtr);
2217
2218 if (ExternallyVisibleSymbolNamesPtr) {
2219 // Add to ExternallyVisibleSymbolNames the set of unique names used by all
2220 // externally visible symbols in the index.
2221 for (auto &I : ThinLTO.CombinedIndex) {
2222 ValueInfo VI = ThinLTO.CombinedIndex.getValueInfo(R: I);
2223 for (const auto &Summary : VI.getSummaryList()) {
2224 const GlobalValueSummary *Base = Summary->getBaseObject();
2225 if (GlobalValue::isLocalLinkage(Linkage: Base->linkage()))
2226 continue;
2227
2228 ExternallyVisibleSymbolNamesPtr->insert(V: VI.name());
2229 break;
2230 }
2231 }
2232 }
2233
2234 thinLTOInternalizeAndPromoteInIndex(Index&: ThinLTO.CombinedIndex, isExported,
2235 isPrevailing,
2236 ExternallyVisibleSymbolNamesPtr);
2237
2238 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
2239 GlobalValue::GUID GUID,
2240 GlobalValue::LinkageTypes NewLinkage) {
2241 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
2242 };
2243 thinLTOResolvePrevailingInIndex(C: Conf, Index&: ThinLTO.CombinedIndex, isPrevailing,
2244 recordNewLinkage, GUIDPreservedSymbols);
2245
2246 thinLTOPropagateFunctionAttrs(Index&: ThinLTO.CombinedIndex, isPrevailing);
2247
2248 generateParamAccessSummary(Index&: ThinLTO.CombinedIndex);
2249
2250 if (llvm::timeTraceProfilerEnabled())
2251 llvm::timeTraceProfilerEnd();
2252
2253 TimeTraceScopeExit.release();
2254
2255 auto &ModuleMap =
2256 ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap;
2257
2258 auto RunBackends = [&](ThinBackendProc *BackendProcess) -> Error {
2259 auto ProcessOneModule = [&](int I) -> Error {
2260 auto &Mod = *(ModuleMap.begin() + I);
2261 // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for
2262 // combined module and parallel code generation partitions.
2263 return BackendProcess->start(
2264 Task: RegularLTO.ParallelCodeGenParallelismLevel + I, BM: Mod.second,
2265 ImportList: ImportLists[Mod.first], ExportList: ExportLists[Mod.first],
2266 ResolvedODR: ResolvedODR[Mod.first], ModuleMap&: ThinLTO.ModuleMap);
2267 };
2268
2269 BackendProcess->setup(ThinLTONumTasks: ModuleMap.size(),
2270 ThinLTOTaskOffset: RegularLTO.ParallelCodeGenParallelismLevel,
2271 Triple: RegularLTO.CombinedModule->getTargetTriple());
2272
2273 if (BackendProcess->getThreadCount() == 1 ||
2274 BackendProcess->isSensitiveToInputOrder()) {
2275 // Process the modules in the order they were provided on the
2276 // command-line. It is important for this codepath to be used for
2277 // WriteIndexesThinBackend, to ensure the emitted LinkedObjectsFile lists
2278 // ThinLTO objects in the same order as the inputs, which otherwise would
2279 // affect the final link order.
2280 for (int I = 0, E = ModuleMap.size(); I != E; ++I)
2281 if (Error E = ProcessOneModule(I))
2282 return E;
2283 } else {
2284 // When executing in parallel, process largest bitsize modules first to
2285 // improve parallelism, and avoid starving the thread pool near the end.
2286 // This saves about 15 sec on a 36-core machine while link `clang.exe`
2287 // (out of 100 sec).
2288 std::vector<BitcodeModule *> ModulesVec;
2289 ModulesVec.reserve(n: ModuleMap.size());
2290 for (auto &Mod : ModuleMap)
2291 ModulesVec.push_back(x: &Mod.second);
2292 for (int I : generateModulesOrdering(R: ModulesVec))
2293 if (Error E = ProcessOneModule(I))
2294 return E;
2295 }
2296 return BackendProcess->wait();
2297 };
2298
2299 if (!cgdata::thinLTOTwoRounds()) {
2300 std::unique_ptr<ThinBackendProc> BackendProc =
2301 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
2302 AddStream, Cache, BitcodeLibFuncs);
2303 return RunBackends(BackendProc.get());
2304 }
2305
2306 // Perform two rounds of code generation for ThinLTO:
2307 // 1. First round: Perform optimization and code generation, outputting to
2308 // temporary scratch objects.
2309 // 2. Merge code generation data extracted from the temporary scratch objects.
2310 // 3. Second round: Execute code generation again using the merged data.
2311 LLVM_DEBUG(dbgs() << "[TwoRounds] Initializing ThinLTO two-codegen rounds\n");
2312
2313 unsigned MaxTasks = getMaxTasks();
2314 auto Parallelism = ThinLTO.Backend.getParallelism();
2315 // Set up two additional streams and caches for storing temporary scratch
2316 // objects and optimized IRs, using the same cache directory as the original.
2317 cgdata::StreamCacheData CG(MaxTasks, Cache, "CG"), IR(MaxTasks, Cache, "IR");
2318
2319 // First round: Execute optimization and code generation, outputting to
2320 // temporary scratch objects. Serialize the optimized IRs before initiating
2321 // code generation.
2322 LLVM_DEBUG(dbgs() << "[TwoRounds] Running the first round of codegen\n");
2323 auto FirstRoundLTO = std::make_unique<FirstRoundThinBackend>(
2324 args&: Conf, args&: ThinLTO.CombinedIndex, args&: Parallelism, args&: ModuleToDefinedGVSummaries,
2325 args&: CG.AddStream, args&: CG.Cache, args&: BitcodeLibFuncs, args&: IR.AddStream, args&: IR.Cache);
2326 if (Error E = RunBackends(FirstRoundLTO.get()))
2327 return E;
2328
2329 LLVM_DEBUG(dbgs() << "[TwoRounds] Merging codegen data\n");
2330 auto CombinedHashOrErr = cgdata::mergeCodeGenData(ObjectFiles: *CG.getResult());
2331 if (Error E = CombinedHashOrErr.takeError())
2332 return E;
2333 auto CombinedHash = *CombinedHashOrErr;
2334 LLVM_DEBUG(dbgs() << "[TwoRounds] CGData hash: " << CombinedHash << "\n");
2335
2336 // Second round: Read the optimized IRs and execute code generation using the
2337 // merged data.
2338 LLVM_DEBUG(dbgs() << "[TwoRounds] Running the second round of codegen\n");
2339 auto SecondRoundLTO = std::make_unique<SecondRoundThinBackend>(
2340 args&: Conf, args&: ThinLTO.CombinedIndex, args&: Parallelism, args&: ModuleToDefinedGVSummaries,
2341 args&: AddStream, args&: Cache, args&: BitcodeLibFuncs, args: IR.getResult(), args&: CombinedHash);
2342 return RunBackends(SecondRoundLTO.get());
2343}
2344
2345Expected<LLVMRemarkFileHandle> lto::setupLLVMOptimizationRemarks(
2346 LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
2347 StringRef RemarksFormat, bool RemarksWithHotness,
2348 std::optional<uint64_t> RemarksHotnessThreshold, int Count) {
2349 std::string Filename = std::string(RemarksFilename);
2350 // For ThinLTO, file.opt.<format> becomes
2351 // file.opt.<format>.thin.<num>.<format>.
2352 if (!Filename.empty() && Count != -1)
2353 Filename =
2354 (Twine(Filename) + ".thin." + llvm::utostr(X: Count) + "." + RemarksFormat)
2355 .str();
2356
2357 auto ResultOrErr = llvm::setupLLVMOptimizationRemarks(
2358 Context, RemarksFilename: Filename, RemarksPasses, RemarksFormat, RemarksWithHotness,
2359 RemarksHotnessThreshold);
2360 if (Error E = ResultOrErr.takeError())
2361 return std::move(E);
2362
2363 if (*ResultOrErr)
2364 (*ResultOrErr)->keep();
2365
2366 return ResultOrErr;
2367}
2368
2369Expected<std::unique_ptr<ToolOutputFile>>
2370lto::setupStatsFile(StringRef StatsFilename) {
2371 // Setup output file to emit statistics.
2372 if (StatsFilename.empty())
2373 return nullptr;
2374
2375 llvm::EnableStatistics(DoPrintOnExit: false);
2376 std::error_code EC;
2377 auto StatsFile =
2378 std::make_unique<ToolOutputFile>(args&: StatsFilename, args&: EC, args: sys::fs::OF_None);
2379 if (EC)
2380 return errorCodeToError(EC);
2381
2382 StatsFile->keep();
2383 return std::move(StatsFile);
2384}
2385
2386// Compute the ordering we will process the inputs: the rough heuristic here
2387// is to sort them per size so that the largest module get schedule as soon as
2388// possible. This is purely a compile-time optimization.
2389std::vector<int> lto::generateModulesOrdering(ArrayRef<BitcodeModule *> R) {
2390 auto Seq = llvm::seq<int>(Begin: 0, End: R.size());
2391 std::vector<int> ModulesOrdering(Seq.begin(), Seq.end());
2392 llvm::sort(C&: ModulesOrdering, Comp: [&](int LeftIndex, int RightIndex) {
2393 auto LSize = R[LeftIndex]->getBuffer().size();
2394 auto RSize = R[RightIndex]->getBuffer().size();
2395 return LSize > RSize;
2396 });
2397 return ModulesOrdering;
2398}
2399