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