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