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