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