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