Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / llvm / lib / LTO / LTO.cpp
blob214c2ef45de0664edc2154c006da0c6b84e8f10d
1 //===-LTO.cpp - LLVM Link Time Optimizer ----------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements functions and classes used to support LTO.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/LTO/LTO.h"
14 #include "llvm/ADT/ScopeExit.h"
15 #include "llvm/ADT/SmallSet.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
19 #include "llvm/Analysis/StackSafetyAnalysis.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Bitcode/BitcodeReader.h"
23 #include "llvm/Bitcode/BitcodeWriter.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/Config/llvm-config.h"
26 #include "llvm/IR/AutoUpgrade.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/LLVMRemarkStreamer.h"
30 #include "llvm/IR/LegacyPassManager.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/IR/Metadata.h"
33 #include "llvm/LTO/LTOBackend.h"
34 #include "llvm/LTO/SummaryBasedOptimizations.h"
35 #include "llvm/Linker/IRMover.h"
36 #include "llvm/MC/TargetRegistry.h"
37 #include "llvm/Object/IRObjectFile.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Error.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/SHA1.h"
45 #include "llvm/Support/SourceMgr.h"
46 #include "llvm/Support/ThreadPool.h"
47 #include "llvm/Support/Threading.h"
48 #include "llvm/Support/TimeProfiler.h"
49 #include "llvm/Support/ToolOutputFile.h"
50 #include "llvm/Support/VCSRevision.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "llvm/Transforms/IPO.h"
54 #include "llvm/Transforms/IPO/MemProfContextDisambiguation.h"
55 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
56 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
57 #include "llvm/Transforms/Utils/SplitModule.h"
59 #include <optional>
60 #include <set>
62 using namespace llvm;
63 using namespace lto;
64 using namespace object;
66 #define DEBUG_TYPE "lto"
68 static cl::opt<bool>
69 DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(false), cl::Hidden,
70 cl::desc("Dump the SCCs in the ThinLTO index's callgraph"));
72 namespace llvm {
73 /// Enable global value internalization in LTO.
74 cl::opt<bool> EnableLTOInternalization(
75 "enable-lto-internalization", cl::init(true), cl::Hidden,
76 cl::desc("Enable global value internalization in LTO"));
78 /// Indicate we are linking with an allocator that supports hot/cold operator
79 /// new interfaces.
80 extern cl::opt<bool> SupportsHotColdNew;
82 /// Enable MemProf context disambiguation for thin link.
83 extern cl::opt<bool> EnableMemProfContextDisambiguation;
84 } // namespace llvm
86 // Computes a unique hash for the Module considering the current list of
87 // export/import and other global analysis results.
88 // The hash is produced in \p Key.
89 void llvm::computeLTOCacheKey(
90 SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
91 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
92 const FunctionImporter::ExportSetTy &ExportList,
93 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
94 const GVSummaryMapTy &DefinedGlobals,
95 const std::set<GlobalValue::GUID> &CfiFunctionDefs,
96 const std::set<GlobalValue::GUID> &CfiFunctionDecls) {
97 // Compute the unique hash for this entry.
98 // This is based on the current compiler version, the module itself, the
99 // export list, the hash for every single module in the import list, the
100 // list of ResolvedODR for the module, and the list of preserved symbols.
101 SHA1 Hasher;
103 // Start with the compiler revision
104 Hasher.update(LLVM_VERSION_STRING);
105 #ifdef LLVM_REVISION
106 Hasher.update(LLVM_REVISION);
107 #endif
109 // Include the parts of the LTO configuration that affect code generation.
110 auto AddString = [&](StringRef Str) {
111 Hasher.update(Str);
112 Hasher.update(ArrayRef<uint8_t>{0});
114 auto AddUnsigned = [&](unsigned I) {
115 uint8_t Data[4];
116 support::endian::write32le(Data, I);
117 Hasher.update(ArrayRef<uint8_t>{Data, 4});
119 auto AddUint64 = [&](uint64_t I) {
120 uint8_t Data[8];
121 support::endian::write64le(Data, I);
122 Hasher.update(ArrayRef<uint8_t>{Data, 8});
124 AddString(Conf.CPU);
125 // FIXME: Hash more of Options. For now all clients initialize Options from
126 // command-line flags (which is unsupported in production), but may set
127 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
128 // DataSections and DebuggerTuning via command line flags.
129 AddUnsigned(Conf.Options.RelaxELFRelocations);
130 AddUnsigned(Conf.Options.FunctionSections);
131 AddUnsigned(Conf.Options.DataSections);
132 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
133 for (auto &A : Conf.MAttrs)
134 AddString(A);
135 if (Conf.RelocModel)
136 AddUnsigned(*Conf.RelocModel);
137 else
138 AddUnsigned(-1);
139 if (Conf.CodeModel)
140 AddUnsigned(*Conf.CodeModel);
141 else
142 AddUnsigned(-1);
143 for (const auto &S : Conf.MllvmArgs)
144 AddString(S);
145 AddUnsigned(static_cast<int>(Conf.CGOptLevel));
146 AddUnsigned(static_cast<int>(Conf.CGFileType));
147 AddUnsigned(Conf.OptLevel);
148 AddUnsigned(Conf.Freestanding);
149 AddString(Conf.OptPipeline);
150 AddString(Conf.AAPipeline);
151 AddString(Conf.OverrideTriple);
152 AddString(Conf.DefaultTriple);
153 AddString(Conf.DwoDir);
155 // Include the hash for the current module
156 auto ModHash = Index.getModuleHash(ModuleID);
157 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
159 std::vector<uint64_t> ExportsGUID;
160 ExportsGUID.reserve(ExportList.size());
161 for (const auto &VI : ExportList) {
162 auto GUID = VI.getGUID();
163 ExportsGUID.push_back(GUID);
166 // Sort the export list elements GUIDs.
167 llvm::sort(ExportsGUID);
168 for (uint64_t GUID : ExportsGUID) {
169 // The export list can impact the internalization, be conservative here
170 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&GUID, sizeof(GUID)));
173 // Include the hash for every module we import functions from. The set of
174 // imported symbols for each module may affect code generation and is
175 // sensitive to link order, so include that as well.
176 using ImportMapIteratorTy = FunctionImporter::ImportMapTy::const_iterator;
177 struct ImportModule {
178 ImportMapIteratorTy ModIt;
179 const ModuleSummaryIndex::ModuleInfo *ModInfo;
181 StringRef getIdentifier() const { return ModIt->getFirst(); }
182 const FunctionImporter::FunctionsToImportTy &getFunctions() const {
183 return ModIt->second;
186 const ModuleHash &getHash() const { return ModInfo->second; }
189 std::vector<ImportModule> ImportModulesVector;
190 ImportModulesVector.reserve(ImportList.size());
192 for (ImportMapIteratorTy It = ImportList.begin(); It != ImportList.end();
193 ++It) {
194 ImportModulesVector.push_back({It, Index.getModule(It->getFirst())});
196 // Order using module hash, to be both independent of module name and
197 // module order.
198 llvm::sort(ImportModulesVector,
199 [](const ImportModule &Lhs, const ImportModule &Rhs) -> bool {
200 return Lhs.getHash() < Rhs.getHash();
202 for (const ImportModule &Entry : ImportModulesVector) {
203 auto ModHash = Entry.getHash();
204 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
206 AddUint64(Entry.getFunctions().size());
207 for (auto &Fn : Entry.getFunctions())
208 AddUint64(Fn);
211 // Include the hash for the resolved ODR.
212 for (auto &Entry : ResolvedODR) {
213 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
214 sizeof(GlobalValue::GUID)));
215 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
216 sizeof(GlobalValue::LinkageTypes)));
219 // Members of CfiFunctionDefs and CfiFunctionDecls that are referenced or
220 // defined in this module.
221 std::set<GlobalValue::GUID> UsedCfiDefs;
222 std::set<GlobalValue::GUID> UsedCfiDecls;
224 // Typeids used in this module.
225 std::set<GlobalValue::GUID> UsedTypeIds;
227 auto AddUsedCfiGlobal = [&](GlobalValue::GUID ValueGUID) {
228 if (CfiFunctionDefs.count(ValueGUID))
229 UsedCfiDefs.insert(ValueGUID);
230 if (CfiFunctionDecls.count(ValueGUID))
231 UsedCfiDecls.insert(ValueGUID);
234 auto AddUsedThings = [&](GlobalValueSummary *GS) {
235 if (!GS) return;
236 AddUnsigned(GS->getVisibility());
237 AddUnsigned(GS->isLive());
238 AddUnsigned(GS->canAutoHide());
239 for (const ValueInfo &VI : GS->refs()) {
240 AddUnsigned(VI.isDSOLocal(Index.withDSOLocalPropagation()));
241 AddUsedCfiGlobal(VI.getGUID());
243 if (auto *GVS = dyn_cast<GlobalVarSummary>(GS)) {
244 AddUnsigned(GVS->maybeReadOnly());
245 AddUnsigned(GVS->maybeWriteOnly());
247 if (auto *FS = dyn_cast<FunctionSummary>(GS)) {
248 for (auto &TT : FS->type_tests())
249 UsedTypeIds.insert(TT);
250 for (auto &TT : FS->type_test_assume_vcalls())
251 UsedTypeIds.insert(TT.GUID);
252 for (auto &TT : FS->type_checked_load_vcalls())
253 UsedTypeIds.insert(TT.GUID);
254 for (auto &TT : FS->type_test_assume_const_vcalls())
255 UsedTypeIds.insert(TT.VFunc.GUID);
256 for (auto &TT : FS->type_checked_load_const_vcalls())
257 UsedTypeIds.insert(TT.VFunc.GUID);
258 for (auto &ET : FS->calls()) {
259 AddUnsigned(ET.first.isDSOLocal(Index.withDSOLocalPropagation()));
260 AddUsedCfiGlobal(ET.first.getGUID());
265 // Include the hash for the linkage type to reflect internalization and weak
266 // resolution, and collect any used type identifier resolutions.
267 for (auto &GS : DefinedGlobals) {
268 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
269 Hasher.update(
270 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
271 AddUsedCfiGlobal(GS.first);
272 AddUsedThings(GS.second);
275 // Imported functions may introduce new uses of type identifier resolutions,
276 // so we need to collect their used resolutions as well.
277 for (const ImportModule &ImpM : ImportModulesVector)
278 for (auto &ImpF : ImpM.getFunctions()) {
279 GlobalValueSummary *S =
280 Index.findSummaryInModule(ImpF, ImpM.getIdentifier());
281 AddUsedThings(S);
282 // If this is an alias, we also care about any types/etc. that the aliasee
283 // may reference.
284 if (auto *AS = dyn_cast_or_null<AliasSummary>(S))
285 AddUsedThings(AS->getBaseObject());
288 auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
289 AddString(TId);
291 AddUnsigned(S.TTRes.TheKind);
292 AddUnsigned(S.TTRes.SizeM1BitWidth);
294 AddUint64(S.TTRes.AlignLog2);
295 AddUint64(S.TTRes.SizeM1);
296 AddUint64(S.TTRes.BitMask);
297 AddUint64(S.TTRes.InlineBits);
299 AddUint64(S.WPDRes.size());
300 for (auto &WPD : S.WPDRes) {
301 AddUnsigned(WPD.first);
302 AddUnsigned(WPD.second.TheKind);
303 AddString(WPD.second.SingleImplName);
305 AddUint64(WPD.second.ResByArg.size());
306 for (auto &ByArg : WPD.second.ResByArg) {
307 AddUint64(ByArg.first.size());
308 for (uint64_t Arg : ByArg.first)
309 AddUint64(Arg);
310 AddUnsigned(ByArg.second.TheKind);
311 AddUint64(ByArg.second.Info);
312 AddUnsigned(ByArg.second.Byte);
313 AddUnsigned(ByArg.second.Bit);
318 // Include the hash for all type identifiers used by this module.
319 for (GlobalValue::GUID TId : UsedTypeIds) {
320 auto TidIter = Index.typeIds().equal_range(TId);
321 for (auto It = TidIter.first; It != TidIter.second; ++It)
322 AddTypeIdSummary(It->second.first, It->second.second);
325 AddUnsigned(UsedCfiDefs.size());
326 for (auto &V : UsedCfiDefs)
327 AddUint64(V);
329 AddUnsigned(UsedCfiDecls.size());
330 for (auto &V : UsedCfiDecls)
331 AddUint64(V);
333 if (!Conf.SampleProfile.empty()) {
334 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
335 if (FileOrErr) {
336 Hasher.update(FileOrErr.get()->getBuffer());
338 if (!Conf.ProfileRemapping.empty()) {
339 FileOrErr = MemoryBuffer::getFile(Conf.ProfileRemapping);
340 if (FileOrErr)
341 Hasher.update(FileOrErr.get()->getBuffer());
346 Key = toHex(Hasher.result());
349 static void thinLTOResolvePrevailingGUID(
350 const Config &C, ValueInfo VI,
351 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
352 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
353 isPrevailing,
354 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
355 recordNewLinkage,
356 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
357 GlobalValue::VisibilityTypes Visibility =
358 C.VisibilityScheme == Config::ELF ? VI.getELFVisibility()
359 : GlobalValue::DefaultVisibility;
360 for (auto &S : VI.getSummaryList()) {
361 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
362 // Ignore local and appending linkage values since the linker
363 // doesn't resolve them.
364 if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
365 GlobalValue::isAppendingLinkage(S->linkage()))
366 continue;
367 // We need to emit only one of these. The prevailing module will keep it,
368 // but turned into a weak, while the others will drop it when possible.
369 // This is both a compile-time optimization and a correctness
370 // transformation. This is necessary for correctness when we have exported
371 // a reference - we need to convert the linkonce to weak to
372 // ensure a copy is kept to satisfy the exported reference.
373 // FIXME: We may want to split the compile time and correctness
374 // aspects into separate routines.
375 if (isPrevailing(VI.getGUID(), S.get())) {
376 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage)) {
377 S->setLinkage(GlobalValue::getWeakLinkage(
378 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
379 // The kept copy is eligible for auto-hiding (hidden visibility) if all
380 // copies were (i.e. they were all linkonce_odr global unnamed addr).
381 // If any copy is not (e.g. it was originally weak_odr), then the symbol
382 // must remain externally available (e.g. a weak_odr from an explicitly
383 // instantiated template). Additionally, if it is in the
384 // GUIDPreservedSymbols set, that means that it is visibile outside
385 // the summary (e.g. in a native object or a bitcode file without
386 // summary), and in that case we cannot hide it as it isn't possible to
387 // check all copies.
388 S->setCanAutoHide(VI.canAutoHide() &&
389 !GUIDPreservedSymbols.count(VI.getGUID()));
391 if (C.VisibilityScheme == Config::FromPrevailing)
392 Visibility = S->getVisibility();
394 // Alias and aliasee can't be turned into available_externally.
395 else if (!isa<AliasSummary>(S.get()) &&
396 !GlobalInvolvedWithAlias.count(S.get()))
397 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
399 // For ELF, set visibility to the computed visibility from summaries. We
400 // don't track visibility from declarations so this may be more relaxed than
401 // the most constraining one.
402 if (C.VisibilityScheme == Config::ELF)
403 S->setVisibility(Visibility);
405 if (S->linkage() != OriginalLinkage)
406 recordNewLinkage(S->modulePath(), VI.getGUID(), S->linkage());
409 if (C.VisibilityScheme == Config::FromPrevailing) {
410 for (auto &S : VI.getSummaryList()) {
411 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
412 if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
413 GlobalValue::isAppendingLinkage(S->linkage()))
414 continue;
415 S->setVisibility(Visibility);
420 /// Resolve linkage for prevailing symbols in the \p Index.
422 // We'd like to drop these functions if they are no longer referenced in the
423 // current module. However there is a chance that another module is still
424 // referencing them because of the import. We make sure we always emit at least
425 // one copy.
426 void llvm::thinLTOResolvePrevailingInIndex(
427 const Config &C, ModuleSummaryIndex &Index,
428 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
429 isPrevailing,
430 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
431 recordNewLinkage,
432 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
433 // We won't optimize the globals that are referenced by an alias for now
434 // Ideally we should turn the alias into a global and duplicate the definition
435 // when needed.
436 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
437 for (auto &I : Index)
438 for (auto &S : I.second.SummaryList)
439 if (auto AS = dyn_cast<AliasSummary>(S.get()))
440 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
442 for (auto &I : Index)
443 thinLTOResolvePrevailingGUID(C, Index.getValueInfo(I),
444 GlobalInvolvedWithAlias, isPrevailing,
445 recordNewLinkage, GUIDPreservedSymbols);
448 static void thinLTOInternalizeAndPromoteGUID(
449 ValueInfo VI, function_ref<bool(StringRef, ValueInfo)> isExported,
450 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
451 isPrevailing) {
452 auto ExternallyVisibleCopies =
453 llvm::count_if(VI.getSummaryList(),
454 [](const std::unique_ptr<GlobalValueSummary> &Summary) {
455 return !GlobalValue::isLocalLinkage(Summary->linkage());
458 for (auto &S : VI.getSummaryList()) {
459 // First see if we need to promote an internal value because it is not
460 // exported.
461 if (isExported(S->modulePath(), VI)) {
462 if (GlobalValue::isLocalLinkage(S->linkage()))
463 S->setLinkage(GlobalValue::ExternalLinkage);
464 continue;
467 // Otherwise, see if we can internalize.
468 if (!EnableLTOInternalization)
469 continue;
471 // Non-exported values with external linkage can be internalized.
472 if (GlobalValue::isExternalLinkage(S->linkage())) {
473 S->setLinkage(GlobalValue::InternalLinkage);
474 continue;
477 // Non-exported function and variable definitions with a weak-for-linker
478 // linkage can be internalized in certain cases. The minimum legality
479 // requirements would be that they are not address taken to ensure that we
480 // don't break pointer equality checks, and that variables are either read-
481 // or write-only. For functions, this is the case if either all copies are
482 // [local_]unnamed_addr, or we can propagate reference edge attributes
483 // (which is how this is guaranteed for variables, when analyzing whether
484 // they are read or write-only).
486 // However, we only get to this code for weak-for-linkage values in one of
487 // two cases:
488 // 1) The prevailing copy is not in IR (it is in native code).
489 // 2) The prevailing copy in IR is not exported from its module.
490 // Additionally, at least for the new LTO API, case 2 will only happen if
491 // there is exactly one definition of the value (i.e. in exactly one
492 // module), as duplicate defs are result in the value being marked exported.
493 // Likely, users of the legacy LTO API are similar, however, currently there
494 // are llvm-lto based tests of the legacy LTO API that do not mark
495 // duplicate linkonce_odr copies as exported via the tool, so we need
496 // to handle that case below by checking the number of copies.
498 // Generally, we only want to internalize a weak-for-linker value in case
499 // 2, because in case 1 we cannot see how the value is used to know if it
500 // is read or write-only. We also don't want to bloat the binary with
501 // multiple internalized copies of non-prevailing linkonce/weak functions.
502 // Note if we don't internalize, we will convert non-prevailing copies to
503 // available_externally anyway, so that we drop them after inlining. The
504 // only reason to internalize such a function is if we indeed have a single
505 // copy, because internalizing it won't increase binary size, and enables
506 // use of inliner heuristics that are more aggressive in the face of a
507 // single call to a static (local). For variables, internalizing a read or
508 // write only variable can enable more aggressive optimization. However, we
509 // already perform this elsewhere in the ThinLTO backend handling for
510 // read or write-only variables (processGlobalForThinLTO).
512 // Therefore, only internalize linkonce/weak if there is a single copy, that
513 // is prevailing in this IR module. We can do so aggressively, without
514 // requiring the address to be insignificant, or that a variable be read or
515 // write-only.
516 if (!GlobalValue::isWeakForLinker(S->linkage()) ||
517 GlobalValue::isExternalWeakLinkage(S->linkage()))
518 continue;
520 if (isPrevailing(VI.getGUID(), S.get()) && ExternallyVisibleCopies == 1)
521 S->setLinkage(GlobalValue::InternalLinkage);
525 // Update the linkages in the given \p Index to mark exported values
526 // as external and non-exported values as internal.
527 void llvm::thinLTOInternalizeAndPromoteInIndex(
528 ModuleSummaryIndex &Index,
529 function_ref<bool(StringRef, ValueInfo)> isExported,
530 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
531 isPrevailing) {
532 for (auto &I : Index)
533 thinLTOInternalizeAndPromoteGUID(Index.getValueInfo(I), isExported,
534 isPrevailing);
537 // Requires a destructor for std::vector<InputModule>.
538 InputFile::~InputFile() = default;
540 Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
541 std::unique_ptr<InputFile> File(new InputFile);
543 Expected<IRSymtabFile> FOrErr = readIRSymtab(Object);
544 if (!FOrErr)
545 return FOrErr.takeError();
547 File->TargetTriple = FOrErr->TheReader.getTargetTriple();
548 File->SourceFileName = FOrErr->TheReader.getSourceFileName();
549 File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
550 File->DependentLibraries = FOrErr->TheReader.getDependentLibraries();
551 File->ComdatTable = FOrErr->TheReader.getComdatTable();
553 for (unsigned I = 0; I != FOrErr->Mods.size(); ++I) {
554 size_t Begin = File->Symbols.size();
555 for (const irsymtab::Reader::SymbolRef &Sym :
556 FOrErr->TheReader.module_symbols(I))
557 // Skip symbols that are irrelevant to LTO. Note that this condition needs
558 // to match the one in Skip() in LTO::addRegularLTO().
559 if (Sym.isGlobal() && !Sym.isFormatSpecific())
560 File->Symbols.push_back(Sym);
561 File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
564 File->Mods = FOrErr->Mods;
565 File->Strtab = std::move(FOrErr->Strtab);
566 return std::move(File);
569 StringRef InputFile::getName() const {
570 return Mods[0].getModuleIdentifier();
573 BitcodeModule &InputFile::getSingleBitcodeModule() {
574 assert(Mods.size() == 1 && "Expect only one bitcode module");
575 return Mods[0];
578 LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
579 const Config &Conf)
580 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
581 Ctx(Conf), CombinedModule(std::make_unique<Module>("ld-temp.o", Ctx)),
582 Mover(std::make_unique<IRMover>(*CombinedModule)) {}
584 LTO::ThinLTOState::ThinLTOState(ThinBackend Backend)
585 : Backend(Backend), CombinedIndex(/*HaveGVs*/ false) {
586 if (!Backend)
587 this->Backend =
588 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
591 LTO::LTO(Config Conf, ThinBackend Backend,
592 unsigned ParallelCodeGenParallelismLevel, LTOKind LTOMode)
593 : Conf(std::move(Conf)),
594 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
595 ThinLTO(std::move(Backend)), LTOMode(LTOMode) {}
597 // Requires a destructor for MapVector<BitcodeModule>.
598 LTO::~LTO() = default;
600 // Add the symbols in the given module to the GlobalResolutions map, and resolve
601 // their partitions.
602 void LTO::addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
603 ArrayRef<SymbolResolution> Res,
604 unsigned Partition, bool InSummary) {
605 auto *ResI = Res.begin();
606 auto *ResE = Res.end();
607 (void)ResE;
608 const Triple TT(RegularLTO.CombinedModule->getTargetTriple());
609 for (const InputFile::Symbol &Sym : Syms) {
610 assert(ResI != ResE);
611 SymbolResolution Res = *ResI++;
613 StringRef Name = Sym.getName();
614 // Strip the __imp_ prefix from COFF dllimport symbols (similar to the
615 // way they are handled by lld), otherwise we can end up with two
616 // global resolutions (one with and one for a copy of the symbol without).
617 if (TT.isOSBinFormatCOFF() && Name.startswith("__imp_"))
618 Name = Name.substr(strlen("__imp_"));
619 auto &GlobalRes = GlobalResolutions[Name];
620 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
621 if (Res.Prevailing) {
622 assert(!GlobalRes.Prevailing &&
623 "Multiple prevailing defs are not allowed");
624 GlobalRes.Prevailing = true;
625 GlobalRes.IRName = std::string(Sym.getIRName());
626 } else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
627 // Sometimes it can be two copies of symbol in a module and prevailing
628 // symbol can have no IR name. That might happen if symbol is defined in
629 // module level inline asm block. In case we have multiple modules with
630 // the same symbol we want to use IR name of the prevailing symbol.
631 // Otherwise, if we haven't seen a prevailing symbol, set the name so that
632 // we can later use it to check if there is any prevailing copy in IR.
633 GlobalRes.IRName = std::string(Sym.getIRName());
636 // In rare occasion, the symbol used to initialize GlobalRes has a different
637 // IRName from the inspected Symbol. This can happen on macOS + iOS, when a
638 // symbol is referenced through its mangled name, say @"\01_symbol" while
639 // the IRName is @symbol (the prefix underscore comes from MachO mangling).
640 // In that case, we have the same actual Symbol that can get two different
641 // GUID, leading to some invalid internalization. Workaround this by marking
642 // the GlobalRes external.
644 // FIXME: instead of this check, it would be desirable to compute GUIDs
645 // based on mangled name, but this requires an access to the Target Triple
646 // and would be relatively invasive on the codebase.
647 if (GlobalRes.IRName != Sym.getIRName()) {
648 GlobalRes.Partition = GlobalResolution::External;
649 GlobalRes.VisibleOutsideSummary = true;
652 // Set the partition to external if we know it is re-defined by the linker
653 // with -defsym or -wrap options, used elsewhere, e.g. it is visible to a
654 // regular object, is referenced from llvm.compiler.used/llvm.used, or was
655 // already recorded as being referenced from a different partition.
656 if (Res.LinkerRedefined || Res.VisibleToRegularObj || Sym.isUsed() ||
657 (GlobalRes.Partition != GlobalResolution::Unknown &&
658 GlobalRes.Partition != Partition)) {
659 GlobalRes.Partition = GlobalResolution::External;
660 } else
661 // First recorded reference, save the current partition.
662 GlobalRes.Partition = Partition;
664 // Flag as visible outside of summary if visible from a regular object or
665 // from a module that does not have a summary.
666 GlobalRes.VisibleOutsideSummary |=
667 (Res.VisibleToRegularObj || Sym.isUsed() || !InSummary);
669 GlobalRes.ExportDynamic |= Res.ExportDynamic;
673 static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
674 ArrayRef<SymbolResolution> Res) {
675 StringRef Path = Input->getName();
676 OS << Path << '\n';
677 auto ResI = Res.begin();
678 for (const InputFile::Symbol &Sym : Input->symbols()) {
679 assert(ResI != Res.end());
680 SymbolResolution Res = *ResI++;
682 OS << "-r=" << Path << ',' << Sym.getName() << ',';
683 if (Res.Prevailing)
684 OS << 'p';
685 if (Res.FinalDefinitionInLinkageUnit)
686 OS << 'l';
687 if (Res.VisibleToRegularObj)
688 OS << 'x';
689 if (Res.LinkerRedefined)
690 OS << 'r';
691 OS << '\n';
693 OS.flush();
694 assert(ResI == Res.end());
697 Error LTO::add(std::unique_ptr<InputFile> Input,
698 ArrayRef<SymbolResolution> Res) {
699 assert(!CalledGetMaxTasks);
701 if (Conf.ResolutionFile)
702 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
704 if (RegularLTO.CombinedModule->getTargetTriple().empty()) {
705 RegularLTO.CombinedModule->setTargetTriple(Input->getTargetTriple());
706 if (Triple(Input->getTargetTriple()).isOSBinFormatELF())
707 Conf.VisibilityScheme = Config::ELF;
710 const SymbolResolution *ResI = Res.begin();
711 for (unsigned I = 0; I != Input->Mods.size(); ++I)
712 if (Error Err = addModule(*Input, I, ResI, Res.end()))
713 return Err;
715 assert(ResI == Res.end());
716 return Error::success();
719 Error LTO::addModule(InputFile &Input, unsigned ModI,
720 const SymbolResolution *&ResI,
721 const SymbolResolution *ResE) {
722 Expected<BitcodeLTOInfo> LTOInfo = Input.Mods[ModI].getLTOInfo();
723 if (!LTOInfo)
724 return LTOInfo.takeError();
726 if (EnableSplitLTOUnit) {
727 // If only some modules were split, flag this in the index so that
728 // we can skip or error on optimizations that need consistently split
729 // modules (whole program devirt and lower type tests).
730 if (*EnableSplitLTOUnit != LTOInfo->EnableSplitLTOUnit)
731 ThinLTO.CombinedIndex.setPartiallySplitLTOUnits();
732 } else
733 EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
735 BitcodeModule BM = Input.Mods[ModI];
737 if ((LTOMode == LTOK_UnifiedRegular || LTOMode == LTOK_UnifiedThin) &&
738 !LTOInfo->UnifiedLTO)
739 return make_error<StringError>(
740 "unified LTO compilation must use "
741 "compatible bitcode modules (use -funified-lto)",
742 inconvertibleErrorCode());
744 if (LTOInfo->UnifiedLTO && LTOMode == LTOK_Default)
745 LTOMode = LTOK_UnifiedThin;
747 bool IsThinLTO = LTOInfo->IsThinLTO && (LTOMode != LTOK_UnifiedRegular);
749 auto ModSyms = Input.module_symbols(ModI);
750 addModuleToGlobalRes(ModSyms, {ResI, ResE},
751 IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0,
752 LTOInfo->HasSummary);
754 if (IsThinLTO)
755 return addThinLTO(BM, ModSyms, ResI, ResE);
757 RegularLTO.EmptyCombinedModule = false;
758 Expected<RegularLTOState::AddedModule> ModOrErr =
759 addRegularLTO(BM, ModSyms, ResI, ResE);
760 if (!ModOrErr)
761 return ModOrErr.takeError();
763 if (!LTOInfo->HasSummary)
764 return linkRegularLTO(std::move(*ModOrErr), /*LivenessFromIndex=*/false);
766 // Regular LTO module summaries are added to a dummy module that represents
767 // the combined regular LTO module.
768 if (Error Err = BM.readSummary(ThinLTO.CombinedIndex, ""))
769 return Err;
770 RegularLTO.ModsWithSummaries.push_back(std::move(*ModOrErr));
771 return Error::success();
774 // Checks whether the given global value is in a non-prevailing comdat
775 // (comdat containing values the linker indicated were not prevailing,
776 // which we then dropped to available_externally), and if so, removes
777 // it from the comdat. This is called for all global values to ensure the
778 // comdat is empty rather than leaving an incomplete comdat. It is needed for
779 // regular LTO modules, in case we are in a mixed-LTO mode (both regular
780 // and thin LTO modules) compilation. Since the regular LTO module will be
781 // linked first in the final native link, we want to make sure the linker
782 // doesn't select any of these incomplete comdats that would be left
783 // in the regular LTO module without this cleanup.
784 static void
785 handleNonPrevailingComdat(GlobalValue &GV,
786 std::set<const Comdat *> &NonPrevailingComdats) {
787 Comdat *C = GV.getComdat();
788 if (!C)
789 return;
791 if (!NonPrevailingComdats.count(C))
792 return;
794 // Additionally need to drop all global values from the comdat to
795 // available_externally, to satisfy the COMDAT requirement that all members
796 // are discarded as a unit. The non-local linkage global values avoid
797 // duplicate definition linker errors.
798 GV.setLinkage(GlobalValue::AvailableExternallyLinkage);
800 if (auto GO = dyn_cast<GlobalObject>(&GV))
801 GO->setComdat(nullptr);
804 // Add a regular LTO object to the link.
805 // The resulting module needs to be linked into the combined LTO module with
806 // linkRegularLTO.
807 Expected<LTO::RegularLTOState::AddedModule>
808 LTO::addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
809 const SymbolResolution *&ResI,
810 const SymbolResolution *ResE) {
811 RegularLTOState::AddedModule Mod;
812 Expected<std::unique_ptr<Module>> MOrErr =
813 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
814 /*IsImporting*/ false);
815 if (!MOrErr)
816 return MOrErr.takeError();
817 Module &M = **MOrErr;
818 Mod.M = std::move(*MOrErr);
820 if (Error Err = M.materializeMetadata())
821 return std::move(Err);
823 // If cfi.functions is present and we are in regular LTO mode, LowerTypeTests
824 // will rename local functions in the merged module as "<function name>.1".
825 // This causes linking errors, since other parts of the module expect the
826 // original function name.
827 if (LTOMode == LTOK_UnifiedRegular)
828 if (NamedMDNode *CfiFunctionsMD = M.getNamedMetadata("cfi.functions"))
829 M.eraseNamedMetadata(CfiFunctionsMD);
831 UpgradeDebugInfo(M);
833 ModuleSymbolTable SymTab;
834 SymTab.addModule(&M);
836 for (GlobalVariable &GV : M.globals())
837 if (GV.hasAppendingLinkage())
838 Mod.Keep.push_back(&GV);
840 DenseSet<GlobalObject *> AliasedGlobals;
841 for (auto &GA : M.aliases())
842 if (GlobalObject *GO = GA.getAliaseeObject())
843 AliasedGlobals.insert(GO);
845 // In this function we need IR GlobalValues matching the symbols in Syms
846 // (which is not backed by a module), so we need to enumerate them in the same
847 // order. The symbol enumeration order of a ModuleSymbolTable intentionally
848 // matches the order of an irsymtab, but when we read the irsymtab in
849 // InputFile::create we omit some symbols that are irrelevant to LTO. The
850 // Skip() function skips the same symbols from the module as InputFile does
851 // from the symbol table.
852 auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
853 auto Skip = [&]() {
854 while (MsymI != MsymE) {
855 auto Flags = SymTab.getSymbolFlags(*MsymI);
856 if ((Flags & object::BasicSymbolRef::SF_Global) &&
857 !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
858 return;
859 ++MsymI;
862 Skip();
864 std::set<const Comdat *> NonPrevailingComdats;
865 SmallSet<StringRef, 2> NonPrevailingAsmSymbols;
866 for (const InputFile::Symbol &Sym : Syms) {
867 assert(ResI != ResE);
868 SymbolResolution Res = *ResI++;
870 assert(MsymI != MsymE);
871 ModuleSymbolTable::Symbol Msym = *MsymI++;
872 Skip();
874 if (GlobalValue *GV = dyn_cast_if_present<GlobalValue *>(Msym)) {
875 if (Res.Prevailing) {
876 if (Sym.isUndefined())
877 continue;
878 Mod.Keep.push_back(GV);
879 // For symbols re-defined with linker -wrap and -defsym options,
880 // set the linkage to weak to inhibit IPO. The linkage will be
881 // restored by the linker.
882 if (Res.LinkerRedefined)
883 GV->setLinkage(GlobalValue::WeakAnyLinkage);
885 GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage();
886 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
887 GV->setLinkage(GlobalValue::getWeakLinkage(
888 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
889 } else if (isa<GlobalObject>(GV) &&
890 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
891 GV->hasAvailableExternallyLinkage()) &&
892 !AliasedGlobals.count(cast<GlobalObject>(GV))) {
893 // Any of the above three types of linkage indicates that the
894 // chosen prevailing symbol will have the same semantics as this copy of
895 // the symbol, so we may be able to link it with available_externally
896 // linkage. We will decide later whether to do that when we link this
897 // module (in linkRegularLTO), based on whether it is undefined.
898 Mod.Keep.push_back(GV);
899 GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
900 if (GV->hasComdat())
901 NonPrevailingComdats.insert(GV->getComdat());
902 cast<GlobalObject>(GV)->setComdat(nullptr);
905 // Set the 'local' flag based on the linker resolution for this symbol.
906 if (Res.FinalDefinitionInLinkageUnit) {
907 GV->setDSOLocal(true);
908 if (GV->hasDLLImportStorageClass())
909 GV->setDLLStorageClass(GlobalValue::DLLStorageClassTypes::
910 DefaultStorageClass);
912 } else if (auto *AS =
913 dyn_cast_if_present<ModuleSymbolTable::AsmSymbol *>(Msym)) {
914 // Collect non-prevailing symbols.
915 if (!Res.Prevailing)
916 NonPrevailingAsmSymbols.insert(AS->first);
917 } else {
918 llvm_unreachable("unknown symbol type");
921 // Common resolution: collect the maximum size/alignment over all commons.
922 // We also record if we see an instance of a common as prevailing, so that
923 // if none is prevailing we can ignore it later.
924 if (Sym.isCommon()) {
925 // FIXME: We should figure out what to do about commons defined by asm.
926 // For now they aren't reported correctly by ModuleSymbolTable.
927 auto &CommonRes = RegularLTO.Commons[std::string(Sym.getIRName())];
928 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
929 if (uint32_t SymAlignValue = Sym.getCommonAlignment()) {
930 CommonRes.Alignment =
931 std::max(Align(SymAlignValue), CommonRes.Alignment);
933 CommonRes.Prevailing |= Res.Prevailing;
937 if (!M.getComdatSymbolTable().empty())
938 for (GlobalValue &GV : M.global_values())
939 handleNonPrevailingComdat(GV, NonPrevailingComdats);
941 // Prepend ".lto_discard <sym>, <sym>*" directive to each module inline asm
942 // block.
943 if (!M.getModuleInlineAsm().empty()) {
944 std::string NewIA = ".lto_discard";
945 if (!NonPrevailingAsmSymbols.empty()) {
946 // Don't dicard a symbol if there is a live .symver for it.
947 ModuleSymbolTable::CollectAsmSymvers(
948 M, [&](StringRef Name, StringRef Alias) {
949 if (!NonPrevailingAsmSymbols.count(Alias))
950 NonPrevailingAsmSymbols.erase(Name);
952 NewIA += " " + llvm::join(NonPrevailingAsmSymbols, ", ");
954 NewIA += "\n";
955 M.setModuleInlineAsm(NewIA + M.getModuleInlineAsm());
958 assert(MsymI == MsymE);
959 return std::move(Mod);
962 Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod,
963 bool LivenessFromIndex) {
964 std::vector<GlobalValue *> Keep;
965 for (GlobalValue *GV : Mod.Keep) {
966 if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->getGUID())) {
967 if (Function *F = dyn_cast<Function>(GV)) {
968 if (DiagnosticOutputFile) {
969 if (Error Err = F->materialize())
970 return Err;
971 OptimizationRemarkEmitter ORE(F, nullptr);
972 ORE.emit(OptimizationRemark(DEBUG_TYPE, "deadfunction", F)
973 << ore::NV("Function", F)
974 << " not added to the combined module ");
977 continue;
980 if (!GV->hasAvailableExternallyLinkage()) {
981 Keep.push_back(GV);
982 continue;
985 // Only link available_externally definitions if we don't already have a
986 // definition.
987 GlobalValue *CombinedGV =
988 RegularLTO.CombinedModule->getNamedValue(GV->getName());
989 if (CombinedGV && !CombinedGV->isDeclaration())
990 continue;
992 Keep.push_back(GV);
995 return RegularLTO.Mover->move(std::move(Mod.M), Keep, nullptr,
996 /* IsPerformingImport */ false);
999 // Add a ThinLTO module to the link.
1000 Error LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
1001 const SymbolResolution *&ResI,
1002 const SymbolResolution *ResE) {
1003 const SymbolResolution *ResITmp = ResI;
1004 for (const InputFile::Symbol &Sym : Syms) {
1005 assert(ResITmp != ResE);
1006 SymbolResolution Res = *ResITmp++;
1008 if (!Sym.getIRName().empty()) {
1009 auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
1010 Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
1011 if (Res.Prevailing)
1012 ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
1016 if (Error Err =
1017 BM.readSummary(ThinLTO.CombinedIndex, BM.getModuleIdentifier(),
1018 [&](GlobalValue::GUID GUID) {
1019 return ThinLTO.PrevailingModuleForGUID[GUID] ==
1020 BM.getModuleIdentifier();
1022 return Err;
1023 LLVM_DEBUG(dbgs() << "Module " << BM.getModuleIdentifier() << "\n");
1025 for (const InputFile::Symbol &Sym : Syms) {
1026 assert(ResI != ResE);
1027 SymbolResolution Res = *ResI++;
1029 if (!Sym.getIRName().empty()) {
1030 auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
1031 Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
1032 if (Res.Prevailing) {
1033 assert(ThinLTO.PrevailingModuleForGUID[GUID] ==
1034 BM.getModuleIdentifier());
1036 // For linker redefined symbols (via --wrap or --defsym) we want to
1037 // switch the linkage to `weak` to prevent IPOs from happening.
1038 // Find the summary in the module for this very GV and record the new
1039 // linkage so that we can switch it when we import the GV.
1040 if (Res.LinkerRedefined)
1041 if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
1042 GUID, BM.getModuleIdentifier()))
1043 S->setLinkage(GlobalValue::WeakAnyLinkage);
1046 // If the linker resolved the symbol to a local definition then mark it
1047 // as local in the summary for the module we are adding.
1048 if (Res.FinalDefinitionInLinkageUnit) {
1049 if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
1050 GUID, BM.getModuleIdentifier())) {
1051 S->setDSOLocal(true);
1057 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
1058 return make_error<StringError>(
1059 "Expected at most one ThinLTO module per bitcode file",
1060 inconvertibleErrorCode());
1062 if (!Conf.ThinLTOModulesToCompile.empty()) {
1063 if (!ThinLTO.ModulesToCompile)
1064 ThinLTO.ModulesToCompile = ModuleMapType();
1065 // This is a fuzzy name matching where only modules with name containing the
1066 // specified switch values are going to be compiled.
1067 for (const std::string &Name : Conf.ThinLTOModulesToCompile) {
1068 if (BM.getModuleIdentifier().contains(Name)) {
1069 ThinLTO.ModulesToCompile->insert({BM.getModuleIdentifier(), BM});
1070 llvm::errs() << "[ThinLTO] Selecting " << BM.getModuleIdentifier()
1071 << " to compile\n";
1076 return Error::success();
1079 unsigned LTO::getMaxTasks() const {
1080 CalledGetMaxTasks = true;
1081 auto ModuleCount = ThinLTO.ModulesToCompile ? ThinLTO.ModulesToCompile->size()
1082 : ThinLTO.ModuleMap.size();
1083 return RegularLTO.ParallelCodeGenParallelismLevel + ModuleCount;
1086 // If only some of the modules were split, we cannot correctly handle
1087 // code that contains type tests or type checked loads.
1088 Error LTO::checkPartiallySplit() {
1089 if (!ThinLTO.CombinedIndex.partiallySplitLTOUnits())
1090 return Error::success();
1092 Function *TypeTestFunc = RegularLTO.CombinedModule->getFunction(
1093 Intrinsic::getName(Intrinsic::type_test));
1094 Function *TypeCheckedLoadFunc = RegularLTO.CombinedModule->getFunction(
1095 Intrinsic::getName(Intrinsic::type_checked_load));
1096 Function *TypeCheckedLoadRelativeFunc =
1097 RegularLTO.CombinedModule->getFunction(
1098 Intrinsic::getName(Intrinsic::type_checked_load_relative));
1100 // First check if there are type tests / type checked loads in the
1101 // merged regular LTO module IR.
1102 if ((TypeTestFunc && !TypeTestFunc->use_empty()) ||
1103 (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty()) ||
1104 (TypeCheckedLoadRelativeFunc &&
1105 !TypeCheckedLoadRelativeFunc->use_empty()))
1106 return make_error<StringError>(
1107 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1108 inconvertibleErrorCode());
1110 // Otherwise check if there are any recorded in the combined summary from the
1111 // ThinLTO modules.
1112 for (auto &P : ThinLTO.CombinedIndex) {
1113 for (auto &S : P.second.SummaryList) {
1114 auto *FS = dyn_cast<FunctionSummary>(S.get());
1115 if (!FS)
1116 continue;
1117 if (!FS->type_test_assume_vcalls().empty() ||
1118 !FS->type_checked_load_vcalls().empty() ||
1119 !FS->type_test_assume_const_vcalls().empty() ||
1120 !FS->type_checked_load_const_vcalls().empty() ||
1121 !FS->type_tests().empty())
1122 return make_error<StringError>(
1123 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1124 inconvertibleErrorCode());
1127 return Error::success();
1130 Error LTO::run(AddStreamFn AddStream, FileCache Cache) {
1131 // Compute "dead" symbols, we don't want to import/export these!
1132 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
1133 DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions;
1134 for (auto &Res : GlobalResolutions) {
1135 // Normally resolution have IR name of symbol. We can do nothing here
1136 // otherwise. See comments in GlobalResolution struct for more details.
1137 if (Res.second.IRName.empty())
1138 continue;
1140 GlobalValue::GUID GUID = GlobalValue::getGUID(
1141 GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
1143 if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
1144 GUIDPreservedSymbols.insert(GUID);
1146 if (Res.second.ExportDynamic)
1147 DynamicExportSymbols.insert(GUID);
1149 GUIDPrevailingResolutions[GUID] =
1150 Res.second.Prevailing ? PrevailingType::Yes : PrevailingType::No;
1153 auto isPrevailing = [&](GlobalValue::GUID G) {
1154 auto It = GUIDPrevailingResolutions.find(G);
1155 if (It == GUIDPrevailingResolutions.end())
1156 return PrevailingType::Unknown;
1157 return It->second;
1159 computeDeadSymbolsWithConstProp(ThinLTO.CombinedIndex, GUIDPreservedSymbols,
1160 isPrevailing, Conf.OptLevel > 0);
1162 // Setup output file to emit statistics.
1163 auto StatsFileOrErr = setupStatsFile(Conf.StatsFile);
1164 if (!StatsFileOrErr)
1165 return StatsFileOrErr.takeError();
1166 std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
1168 // TODO: Ideally this would be controlled automatically by detecting that we
1169 // are linking with an allocator that supports these interfaces, rather than
1170 // an internal option (which would still be needed for tests, however). For
1171 // example, if the library exported a symbol like __malloc_hot_cold the linker
1172 // could recognize that and set a flag in the lto::Config.
1173 if (SupportsHotColdNew)
1174 ThinLTO.CombinedIndex.setWithSupportsHotColdNew();
1176 Error Result = runRegularLTO(AddStream);
1177 if (!Result)
1178 Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
1180 if (StatsFile)
1181 PrintStatisticsJSON(StatsFile->os());
1183 return Result;
1186 void lto::updateMemProfAttributes(Module &Mod,
1187 const ModuleSummaryIndex &Index) {
1188 if (Index.withSupportsHotColdNew())
1189 return;
1191 // The profile matcher applies hotness attributes directly for allocations,
1192 // and those will cause us to generate calls to the hot/cold interfaces
1193 // unconditionally. If supports-hot-cold-new was not enabled in the LTO
1194 // link then assume we don't want these calls (e.g. not linking with
1195 // the appropriate library, or otherwise trying to disable this behavior).
1196 for (auto &F : Mod) {
1197 for (auto &BB : F) {
1198 for (auto &I : BB) {
1199 auto *CI = dyn_cast<CallBase>(&I);
1200 if (!CI)
1201 continue;
1202 if (CI->hasFnAttr("memprof"))
1203 CI->removeFnAttr("memprof");
1204 // Strip off all memprof metadata as it is no longer needed.
1205 // Importantly, this avoids the addition of new memprof attributes
1206 // after inlining propagation.
1207 // TODO: If we support additional types of MemProf metadata beyond hot
1208 // and cold, we will need to update the metadata based on the allocator
1209 // APIs supported instead of completely stripping all.
1210 CI->setMetadata(LLVMContext::MD_memprof, nullptr);
1211 CI->setMetadata(LLVMContext::MD_callsite, nullptr);
1217 Error LTO::runRegularLTO(AddStreamFn AddStream) {
1218 // Setup optimization remarks.
1219 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
1220 RegularLTO.CombinedModule->getContext(), Conf.RemarksFilename,
1221 Conf.RemarksPasses, Conf.RemarksFormat, Conf.RemarksWithHotness,
1222 Conf.RemarksHotnessThreshold);
1223 LLVM_DEBUG(dbgs() << "Running regular LTO\n");
1224 if (!DiagFileOrErr)
1225 return DiagFileOrErr.takeError();
1226 DiagnosticOutputFile = std::move(*DiagFileOrErr);
1228 // Finalize linking of regular LTO modules containing summaries now that
1229 // we have computed liveness information.
1230 for (auto &M : RegularLTO.ModsWithSummaries)
1231 if (Error Err = linkRegularLTO(std::move(M),
1232 /*LivenessFromIndex=*/true))
1233 return Err;
1235 // Ensure we don't have inconsistently split LTO units with type tests.
1236 // FIXME: this checks both LTO and ThinLTO. It happens to work as we take
1237 // this path both cases but eventually this should be split into two and
1238 // do the ThinLTO checks in `runThinLTO`.
1239 if (Error Err = checkPartiallySplit())
1240 return Err;
1242 // Make sure commons have the right size/alignment: we kept the largest from
1243 // all the prevailing when adding the inputs, and we apply it here.
1244 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
1245 for (auto &I : RegularLTO.Commons) {
1246 if (!I.second.Prevailing)
1247 // Don't do anything if no instance of this common was prevailing.
1248 continue;
1249 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
1250 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
1251 // Don't create a new global if the type is already correct, just make
1252 // sure the alignment is correct.
1253 OldGV->setAlignment(I.second.Alignment);
1254 continue;
1256 ArrayType *Ty =
1257 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
1258 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
1259 GlobalValue::CommonLinkage,
1260 ConstantAggregateZero::get(Ty), "");
1261 GV->setAlignment(I.second.Alignment);
1262 if (OldGV) {
1263 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
1264 GV->takeName(OldGV);
1265 OldGV->eraseFromParent();
1266 } else {
1267 GV->setName(I.first);
1271 updateMemProfAttributes(*RegularLTO.CombinedModule, ThinLTO.CombinedIndex);
1273 bool WholeProgramVisibilityEnabledInLTO =
1274 Conf.HasWholeProgramVisibility &&
1275 // If validation is enabled, upgrade visibility only when all vtables
1276 // have typeinfos.
1277 (!Conf.ValidateAllVtablesHaveTypeInfos || Conf.AllVtablesHaveTypeInfos);
1279 // This returns true when the name is local or not defined. Locals are
1280 // expected to be handled separately.
1281 auto IsVisibleToRegularObj = [&](StringRef name) {
1282 auto It = GlobalResolutions.find(name);
1283 return (It == GlobalResolutions.end() || It->second.VisibleOutsideSummary);
1286 // If allowed, upgrade public vcall visibility metadata to linkage unit
1287 // visibility before whole program devirtualization in the optimizer.
1288 updateVCallVisibilityInModule(
1289 *RegularLTO.CombinedModule, WholeProgramVisibilityEnabledInLTO,
1290 DynamicExportSymbols, Conf.ValidateAllVtablesHaveTypeInfos,
1291 IsVisibleToRegularObj);
1292 updatePublicTypeTestCalls(*RegularLTO.CombinedModule,
1293 WholeProgramVisibilityEnabledInLTO);
1295 if (Conf.PreOptModuleHook &&
1296 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
1297 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
1299 if (!Conf.CodeGenOnly) {
1300 for (const auto &R : GlobalResolutions) {
1301 GlobalValue *GV =
1302 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
1303 if (!R.second.isPrevailingIRSymbol())
1304 continue;
1305 if (R.second.Partition != 0 &&
1306 R.second.Partition != GlobalResolution::External)
1307 continue;
1309 // Ignore symbols defined in other partitions.
1310 // Also skip declarations, which are not allowed to have internal linkage.
1311 if (!GV || GV->hasLocalLinkage() || GV->isDeclaration())
1312 continue;
1314 // Symbols that are marked DLLImport or DLLExport should not be
1315 // internalized, as they are either externally visible or referencing
1316 // external symbols. Symbols that have AvailableExternally or Appending
1317 // linkage might be used by future passes and should be kept as is.
1318 // These linkages are seen in Unified regular LTO, because the process
1319 // of creating split LTO units introduces symbols with that linkage into
1320 // one of the created modules. Normally, only the ThinLTO backend would
1321 // compile this module, but Unified Regular LTO processes both
1322 // modules created by the splitting process as regular LTO modules.
1323 if ((LTOMode == LTOKind::LTOK_UnifiedRegular) &&
1324 ((GV->getDLLStorageClass() != GlobalValue::DefaultStorageClass) ||
1325 GV->hasAvailableExternallyLinkage() || GV->hasAppendingLinkage()))
1326 continue;
1328 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
1329 : GlobalValue::UnnamedAddr::None);
1330 if (EnableLTOInternalization && R.second.Partition == 0)
1331 GV->setLinkage(GlobalValue::InternalLinkage);
1334 if (Conf.PostInternalizeModuleHook &&
1335 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
1336 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
1339 if (!RegularLTO.EmptyCombinedModule || Conf.AlwaysEmitRegularLTOObj) {
1340 if (Error Err =
1341 backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
1342 *RegularLTO.CombinedModule, ThinLTO.CombinedIndex))
1343 return Err;
1346 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
1349 static const char *libcallRoutineNames[] = {
1350 #define HANDLE_LIBCALL(code, name) name,
1351 #include "llvm/IR/RuntimeLibcalls.def"
1352 #undef HANDLE_LIBCALL
1355 ArrayRef<const char*> LTO::getRuntimeLibcallSymbols() {
1356 return ArrayRef(libcallRoutineNames);
1359 /// This class defines the interface to the ThinLTO backend.
1360 class lto::ThinBackendProc {
1361 protected:
1362 const Config &Conf;
1363 ModuleSummaryIndex &CombinedIndex;
1364 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries;
1365 lto::IndexWriteCallback OnWrite;
1366 bool ShouldEmitImportsFiles;
1368 public:
1369 ThinBackendProc(
1370 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1371 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1372 lto::IndexWriteCallback OnWrite, bool ShouldEmitImportsFiles)
1373 : Conf(Conf), CombinedIndex(CombinedIndex),
1374 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries),
1375 OnWrite(OnWrite), ShouldEmitImportsFiles(ShouldEmitImportsFiles) {}
1377 virtual ~ThinBackendProc() = default;
1378 virtual Error start(
1379 unsigned Task, BitcodeModule BM,
1380 const FunctionImporter::ImportMapTy &ImportList,
1381 const FunctionImporter::ExportSetTy &ExportList,
1382 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1383 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
1384 virtual Error wait() = 0;
1385 virtual unsigned getThreadCount() = 0;
1387 // Write sharded indices and (optionally) imports to disk
1388 Error emitFiles(const FunctionImporter::ImportMapTy &ImportList,
1389 llvm::StringRef ModulePath,
1390 const std::string &NewModulePath) {
1391 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
1392 std::error_code EC;
1393 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
1394 ImportList, ModuleToSummariesForIndex);
1396 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
1397 sys::fs::OpenFlags::OF_None);
1398 if (EC)
1399 return errorCodeToError(EC);
1400 writeIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
1402 if (ShouldEmitImportsFiles) {
1403 EC = EmitImportsFiles(ModulePath, NewModulePath + ".imports",
1404 ModuleToSummariesForIndex);
1405 if (EC)
1406 return errorCodeToError(EC);
1408 return Error::success();
1412 namespace {
1413 class InProcessThinBackend : public ThinBackendProc {
1414 ThreadPool BackendThreadPool;
1415 AddStreamFn AddStream;
1416 FileCache Cache;
1417 std::set<GlobalValue::GUID> CfiFunctionDefs;
1418 std::set<GlobalValue::GUID> CfiFunctionDecls;
1420 std::optional<Error> Err;
1421 std::mutex ErrMu;
1423 bool ShouldEmitIndexFiles;
1425 public:
1426 InProcessThinBackend(
1427 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1428 ThreadPoolStrategy ThinLTOParallelism,
1429 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1430 AddStreamFn AddStream, FileCache Cache, lto::IndexWriteCallback OnWrite,
1431 bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles)
1432 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
1433 OnWrite, ShouldEmitImportsFiles),
1434 BackendThreadPool(ThinLTOParallelism), AddStream(std::move(AddStream)),
1435 Cache(std::move(Cache)), ShouldEmitIndexFiles(ShouldEmitIndexFiles) {
1436 for (auto &Name : CombinedIndex.cfiFunctionDefs())
1437 CfiFunctionDefs.insert(
1438 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
1439 for (auto &Name : CombinedIndex.cfiFunctionDecls())
1440 CfiFunctionDecls.insert(
1441 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
1444 Error runThinLTOBackendThread(
1445 AddStreamFn AddStream, FileCache Cache, unsigned Task, BitcodeModule BM,
1446 ModuleSummaryIndex &CombinedIndex,
1447 const FunctionImporter::ImportMapTy &ImportList,
1448 const FunctionImporter::ExportSetTy &ExportList,
1449 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1450 const GVSummaryMapTy &DefinedGlobals,
1451 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1452 auto RunThinBackend = [&](AddStreamFn AddStream) {
1453 LTOLLVMContext BackendContext(Conf);
1454 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
1455 if (!MOrErr)
1456 return MOrErr.takeError();
1458 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
1459 ImportList, DefinedGlobals, &ModuleMap);
1462 auto ModuleID = BM.getModuleIdentifier();
1464 if (ShouldEmitIndexFiles) {
1465 if (auto E = emitFiles(ImportList, ModuleID, ModuleID.str()))
1466 return E;
1469 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
1470 all_of(CombinedIndex.getModuleHash(ModuleID),
1471 [](uint32_t V) { return V == 0; }))
1472 // Cache disabled or no entry for this module in the combined index or
1473 // no module hash.
1474 return RunThinBackend(AddStream);
1476 SmallString<40> Key;
1477 // The module may be cached, this helps handling it.
1478 computeLTOCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList,
1479 ExportList, ResolvedODR, DefinedGlobals, CfiFunctionDefs,
1480 CfiFunctionDecls);
1481 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task, Key, ModuleID);
1482 if (Error Err = CacheAddStreamOrErr.takeError())
1483 return Err;
1484 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1485 if (CacheAddStream)
1486 return RunThinBackend(CacheAddStream);
1488 return Error::success();
1491 Error start(
1492 unsigned Task, BitcodeModule BM,
1493 const FunctionImporter::ImportMapTy &ImportList,
1494 const FunctionImporter::ExportSetTy &ExportList,
1495 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1496 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1497 StringRef ModulePath = BM.getModuleIdentifier();
1498 assert(ModuleToDefinedGVSummaries.count(ModulePath));
1499 const GVSummaryMapTy &DefinedGlobals =
1500 ModuleToDefinedGVSummaries.find(ModulePath)->second;
1501 BackendThreadPool.async(
1502 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1503 const FunctionImporter::ImportMapTy &ImportList,
1504 const FunctionImporter::ExportSetTy &ExportList,
1505 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1506 &ResolvedODR,
1507 const GVSummaryMapTy &DefinedGlobals,
1508 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1509 if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1510 timeTraceProfilerInitialize(Conf.TimeTraceGranularity,
1511 "thin backend");
1512 Error E = runThinLTOBackendThread(
1513 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1514 ResolvedODR, DefinedGlobals, ModuleMap);
1515 if (E) {
1516 std::unique_lock<std::mutex> L(ErrMu);
1517 if (Err)
1518 Err = joinErrors(std::move(*Err), std::move(E));
1519 else
1520 Err = std::move(E);
1522 if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1523 timeTraceProfilerFinishThread();
1525 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
1526 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
1528 if (OnWrite)
1529 OnWrite(std::string(ModulePath));
1530 return Error::success();
1533 Error wait() override {
1534 BackendThreadPool.wait();
1535 if (Err)
1536 return std::move(*Err);
1537 else
1538 return Error::success();
1541 unsigned getThreadCount() override {
1542 return BackendThreadPool.getThreadCount();
1545 } // end anonymous namespace
1547 ThinBackend lto::createInProcessThinBackend(ThreadPoolStrategy Parallelism,
1548 lto::IndexWriteCallback OnWrite,
1549 bool ShouldEmitIndexFiles,
1550 bool ShouldEmitImportsFiles) {
1551 return
1552 [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1553 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1554 AddStreamFn AddStream, FileCache Cache) {
1555 return std::make_unique<InProcessThinBackend>(
1556 Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
1557 AddStream, Cache, OnWrite, ShouldEmitIndexFiles,
1558 ShouldEmitImportsFiles);
1562 // Given the original \p Path to an output file, replace any path
1563 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
1564 // resulting directory if it does not yet exist.
1565 std::string lto::getThinLTOOutputFile(StringRef Path, StringRef OldPrefix,
1566 StringRef NewPrefix) {
1567 if (OldPrefix.empty() && NewPrefix.empty())
1568 return std::string(Path);
1569 SmallString<128> NewPath(Path);
1570 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
1571 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
1572 if (!ParentPath.empty()) {
1573 // Make sure the new directory exists, creating it if necessary.
1574 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
1575 llvm::errs() << "warning: could not create directory '" << ParentPath
1576 << "': " << EC.message() << '\n';
1578 return std::string(NewPath.str());
1581 namespace {
1582 class WriteIndexesThinBackend : public ThinBackendProc {
1583 std::string OldPrefix, NewPrefix, NativeObjectPrefix;
1584 raw_fd_ostream *LinkedObjectsFile;
1586 public:
1587 WriteIndexesThinBackend(
1588 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1589 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1590 std::string OldPrefix, std::string NewPrefix,
1591 std::string NativeObjectPrefix, bool ShouldEmitImportsFiles,
1592 raw_fd_ostream *LinkedObjectsFile, lto::IndexWriteCallback OnWrite)
1593 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
1594 OnWrite, ShouldEmitImportsFiles),
1595 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
1596 NativeObjectPrefix(NativeObjectPrefix),
1597 LinkedObjectsFile(LinkedObjectsFile) {}
1599 Error start(
1600 unsigned Task, BitcodeModule BM,
1601 const FunctionImporter::ImportMapTy &ImportList,
1602 const FunctionImporter::ExportSetTy &ExportList,
1603 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1604 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1605 StringRef ModulePath = BM.getModuleIdentifier();
1606 std::string NewModulePath =
1607 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
1609 if (LinkedObjectsFile) {
1610 std::string ObjectPrefix =
1611 NativeObjectPrefix.empty() ? NewPrefix : NativeObjectPrefix;
1612 std::string LinkedObjectsFilePath =
1613 getThinLTOOutputFile(ModulePath, OldPrefix, ObjectPrefix);
1614 *LinkedObjectsFile << LinkedObjectsFilePath << '\n';
1617 if (auto E = emitFiles(ImportList, ModulePath, NewModulePath))
1618 return E;
1620 if (OnWrite)
1621 OnWrite(std::string(ModulePath));
1622 return Error::success();
1625 Error wait() override { return Error::success(); }
1627 // WriteIndexesThinBackend should always return 1 to prevent module
1628 // re-ordering and avoid non-determinism in the final link.
1629 unsigned getThreadCount() override { return 1; }
1631 } // end anonymous namespace
1633 ThinBackend lto::createWriteIndexesThinBackend(
1634 std::string OldPrefix, std::string NewPrefix,
1635 std::string NativeObjectPrefix, bool ShouldEmitImportsFiles,
1636 raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite) {
1637 return
1638 [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1639 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1640 AddStreamFn AddStream, FileCache Cache) {
1641 return std::make_unique<WriteIndexesThinBackend>(
1642 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix,
1643 NewPrefix, NativeObjectPrefix, ShouldEmitImportsFiles,
1644 LinkedObjectsFile, OnWrite);
1648 Error LTO::runThinLTO(AddStreamFn AddStream, FileCache Cache,
1649 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
1650 LLVM_DEBUG(dbgs() << "Running ThinLTO\n");
1651 ThinLTO.CombinedIndex.releaseTemporaryMemory();
1652 timeTraceProfilerBegin("ThinLink", StringRef(""));
1653 auto TimeTraceScopeExit = llvm::make_scope_exit([]() {
1654 if (llvm::timeTraceProfilerEnabled())
1655 llvm::timeTraceProfilerEnd();
1657 if (ThinLTO.ModuleMap.empty())
1658 return Error::success();
1660 if (ThinLTO.ModulesToCompile && ThinLTO.ModulesToCompile->empty()) {
1661 llvm::errs() << "warning: [ThinLTO] No module compiled\n";
1662 return Error::success();
1665 if (Conf.CombinedIndexHook &&
1666 !Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols))
1667 return Error::success();
1669 // Collect for each module the list of function it defines (GUID ->
1670 // Summary).
1671 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(
1672 ThinLTO.ModuleMap.size());
1673 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
1674 ModuleToDefinedGVSummaries);
1675 // Create entries for any modules that didn't have any GV summaries
1676 // (either they didn't have any GVs to start with, or we suppressed
1677 // generation of the summaries because they e.g. had inline assembly
1678 // uses that couldn't be promoted/renamed on export). This is so
1679 // InProcessThinBackend::start can still launch a backend thread, which
1680 // is passed the map of summaries for the module, without any special
1681 // handling for this case.
1682 for (auto &Mod : ThinLTO.ModuleMap)
1683 if (!ModuleToDefinedGVSummaries.count(Mod.first))
1684 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
1686 // Synthesize entry counts for functions in the CombinedIndex.
1687 computeSyntheticCounts(ThinLTO.CombinedIndex);
1689 DenseMap<StringRef, FunctionImporter::ImportMapTy> ImportLists(
1690 ThinLTO.ModuleMap.size());
1691 DenseMap<StringRef, FunctionImporter::ExportSetTy> ExportLists(
1692 ThinLTO.ModuleMap.size());
1693 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
1695 if (DumpThinCGSCCs)
1696 ThinLTO.CombinedIndex.dumpSCCs(outs());
1698 std::set<GlobalValue::GUID> ExportedGUIDs;
1700 bool WholeProgramVisibilityEnabledInLTO =
1701 Conf.HasWholeProgramVisibility &&
1702 // If validation is enabled, upgrade visibility only when all vtables
1703 // have typeinfos.
1704 (!Conf.ValidateAllVtablesHaveTypeInfos || Conf.AllVtablesHaveTypeInfos);
1705 if (hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
1706 ThinLTO.CombinedIndex.setWithWholeProgramVisibility();
1708 // If we're validating, get the vtable symbols that should not be
1709 // upgraded because they correspond to typeIDs outside of index-based
1710 // WPD info.
1711 DenseSet<GlobalValue::GUID> VisibleToRegularObjSymbols;
1712 if (WholeProgramVisibilityEnabledInLTO &&
1713 Conf.ValidateAllVtablesHaveTypeInfos) {
1714 // This returns true when the name is local or not defined. Locals are
1715 // expected to be handled separately.
1716 auto IsVisibleToRegularObj = [&](StringRef name) {
1717 auto It = GlobalResolutions.find(name);
1718 return (It == GlobalResolutions.end() ||
1719 It->second.VisibleOutsideSummary);
1722 getVisibleToRegularObjVtableGUIDs(ThinLTO.CombinedIndex,
1723 VisibleToRegularObjSymbols,
1724 IsVisibleToRegularObj);
1727 // If allowed, upgrade public vcall visibility to linkage unit visibility in
1728 // the summaries before whole program devirtualization below.
1729 updateVCallVisibilityInIndex(
1730 ThinLTO.CombinedIndex, WholeProgramVisibilityEnabledInLTO,
1731 DynamicExportSymbols, VisibleToRegularObjSymbols);
1733 // Perform index-based WPD. This will return immediately if there are
1734 // no index entries in the typeIdMetadata map (e.g. if we are instead
1735 // performing IR-based WPD in hybrid regular/thin LTO mode).
1736 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1737 runWholeProgramDevirtOnIndex(ThinLTO.CombinedIndex, ExportedGUIDs,
1738 LocalWPDTargetsMap);
1740 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
1741 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1743 if (EnableMemProfContextDisambiguation) {
1744 MemProfContextDisambiguation ContextDisambiguation;
1745 ContextDisambiguation.run(ThinLTO.CombinedIndex, isPrevailing);
1748 if (Conf.OptLevel > 0)
1749 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1750 isPrevailing, ImportLists, ExportLists);
1752 // Figure out which symbols need to be internalized. This also needs to happen
1753 // at -O0 because summary-based DCE is implemented using internalization, and
1754 // we must apply DCE consistently with the full LTO module in order to avoid
1755 // undefined references during the final link.
1756 for (auto &Res : GlobalResolutions) {
1757 // If the symbol does not have external references or it is not prevailing,
1758 // then not need to mark it as exported from a ThinLTO partition.
1759 if (Res.second.Partition != GlobalResolution::External ||
1760 !Res.second.isPrevailingIRSymbol())
1761 continue;
1762 auto GUID = GlobalValue::getGUID(
1763 GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
1764 // Mark exported unless index-based analysis determined it to be dead.
1765 if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
1766 ExportedGUIDs.insert(GUID);
1769 // Any functions referenced by the jump table in the regular LTO object must
1770 // be exported.
1771 for (auto &Def : ThinLTO.CombinedIndex.cfiFunctionDefs())
1772 ExportedGUIDs.insert(
1773 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Def)));
1774 for (auto &Decl : ThinLTO.CombinedIndex.cfiFunctionDecls())
1775 ExportedGUIDs.insert(
1776 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Decl)));
1778 auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
1779 const auto &ExportList = ExportLists.find(ModuleIdentifier);
1780 return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
1781 ExportedGUIDs.count(VI.getGUID());
1784 // Update local devirtualized targets that were exported by cross-module
1785 // importing or by other devirtualizations marked in the ExportedGUIDs set.
1786 updateIndexWPDForExports(ThinLTO.CombinedIndex, isExported,
1787 LocalWPDTargetsMap);
1789 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported,
1790 isPrevailing);
1792 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1793 GlobalValue::GUID GUID,
1794 GlobalValue::LinkageTypes NewLinkage) {
1795 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1797 thinLTOResolvePrevailingInIndex(Conf, ThinLTO.CombinedIndex, isPrevailing,
1798 recordNewLinkage, GUIDPreservedSymbols);
1800 thinLTOPropagateFunctionAttrs(ThinLTO.CombinedIndex, isPrevailing);
1802 generateParamAccessSummary(ThinLTO.CombinedIndex);
1804 if (llvm::timeTraceProfilerEnabled())
1805 llvm::timeTraceProfilerEnd();
1807 TimeTraceScopeExit.release();
1809 std::unique_ptr<ThinBackendProc> BackendProc =
1810 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1811 AddStream, Cache);
1813 auto &ModuleMap =
1814 ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap;
1816 auto ProcessOneModule = [&](int I) -> Error {
1817 auto &Mod = *(ModuleMap.begin() + I);
1818 // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for
1819 // combined module and parallel code generation partitions.
1820 return BackendProc->start(RegularLTO.ParallelCodeGenParallelismLevel + I,
1821 Mod.second, ImportLists[Mod.first],
1822 ExportLists[Mod.first], ResolvedODR[Mod.first],
1823 ThinLTO.ModuleMap);
1826 if (BackendProc->getThreadCount() == 1) {
1827 // Process the modules in the order they were provided on the command-line.
1828 // It is important for this codepath to be used for WriteIndexesThinBackend,
1829 // to ensure the emitted LinkedObjectsFile lists ThinLTO objects in the same
1830 // order as the inputs, which otherwise would affect the final link order.
1831 for (int I = 0, E = ModuleMap.size(); I != E; ++I)
1832 if (Error E = ProcessOneModule(I))
1833 return E;
1834 } else {
1835 // When executing in parallel, process largest bitsize modules first to
1836 // improve parallelism, and avoid starving the thread pool near the end.
1837 // This saves about 15 sec on a 36-core machine while link `clang.exe` (out
1838 // of 100 sec).
1839 std::vector<BitcodeModule *> ModulesVec;
1840 ModulesVec.reserve(ModuleMap.size());
1841 for (auto &Mod : ModuleMap)
1842 ModulesVec.push_back(&Mod.second);
1843 for (int I : generateModulesOrdering(ModulesVec))
1844 if (Error E = ProcessOneModule(I))
1845 return E;
1847 return BackendProc->wait();
1850 Expected<std::unique_ptr<ToolOutputFile>> lto::setupLLVMOptimizationRemarks(
1851 LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
1852 StringRef RemarksFormat, bool RemarksWithHotness,
1853 std::optional<uint64_t> RemarksHotnessThreshold, int Count) {
1854 std::string Filename = std::string(RemarksFilename);
1855 // For ThinLTO, file.opt.<format> becomes
1856 // file.opt.<format>.thin.<num>.<format>.
1857 if (!Filename.empty() && Count != -1)
1858 Filename =
1859 (Twine(Filename) + ".thin." + llvm::utostr(Count) + "." + RemarksFormat)
1860 .str();
1862 auto ResultOrErr = llvm::setupLLVMOptimizationRemarks(
1863 Context, Filename, RemarksPasses, RemarksFormat, RemarksWithHotness,
1864 RemarksHotnessThreshold);
1865 if (Error E = ResultOrErr.takeError())
1866 return std::move(E);
1868 if (*ResultOrErr)
1869 (*ResultOrErr)->keep();
1871 return ResultOrErr;
1874 Expected<std::unique_ptr<ToolOutputFile>>
1875 lto::setupStatsFile(StringRef StatsFilename) {
1876 // Setup output file to emit statistics.
1877 if (StatsFilename.empty())
1878 return nullptr;
1880 llvm::EnableStatistics(false);
1881 std::error_code EC;
1882 auto StatsFile =
1883 std::make_unique<ToolOutputFile>(StatsFilename, EC, sys::fs::OF_None);
1884 if (EC)
1885 return errorCodeToError(EC);
1887 StatsFile->keep();
1888 return std::move(StatsFile);
1891 // Compute the ordering we will process the inputs: the rough heuristic here
1892 // is to sort them per size so that the largest module get schedule as soon as
1893 // possible. This is purely a compile-time optimization.
1894 std::vector<int> lto::generateModulesOrdering(ArrayRef<BitcodeModule *> R) {
1895 auto Seq = llvm::seq<int>(0, R.size());
1896 std::vector<int> ModulesOrdering(Seq.begin(), Seq.end());
1897 llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) {
1898 auto LSize = R[LeftIndex]->getBuffer().size();
1899 auto RSize = R[RightIndex]->getBuffer().size();
1900 return LSize > RSize;
1902 return ModulesOrdering;