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