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 containing values the linker indicated were 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 if (GV->hasComdat())
1087 NonPrevailingComdats.insert(GV->getComdat());
1088 cast<GlobalObject>(GV)->setComdat(nullptr);
1089 }
1090
1091 // Set the 'local' flag based on the linker resolution for this symbol.
1092 if (R.FinalDefinitionInLinkageUnit) {
1093 GV->setDSOLocal(true);
1094 if (GV->hasDLLImportStorageClass())
1095 GV->setDLLStorageClass(GlobalValue::DLLStorageClassTypes::
1096 DefaultStorageClass);
1097 }
1098 } else if (auto *AS =
1100 // Collect non-prevailing symbols.
1101 if (!R.Prevailing)
1102 NonPrevailingAsmSymbols.insert(AS->first);
1103 } else {
1104 llvm_unreachable("unknown symbol type");
1105 }
1106
1107 // Common resolution: collect the maximum size/alignment over all commons.
1108 // We also record if we see an instance of a common as prevailing, so that
1109 // if none is prevailing we can ignore it later.
1110 if (Sym.isCommon()) {
1111 // FIXME: We should figure out what to do about commons defined by asm.
1112 // For now they aren't reported correctly by ModuleSymbolTable.
1113 auto &CommonRes = RegularLTO.Commons[std::string(Sym.getIRName())];
1114 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
1115 if (uint32_t SymAlignValue = Sym.getCommonAlignment()) {
1116 CommonRes.Alignment =
1117 std::max(Align(SymAlignValue), CommonRes.Alignment);
1118 }
1119 CommonRes.Prevailing |= R.Prevailing;
1120 }
1121 }
1122
1123 if (!M.getComdatSymbolTable().empty())
1124 for (GlobalValue &GV : M.global_values())
1125 handleNonPrevailingComdat(GV, NonPrevailingComdats);
1126
1127 // Prepend ".lto_discard <sym>, <sym>*" directive to each module inline asm
1128 // block.
1129 if (M.hasModuleInlineAsm()) {
1130 std::string NewIA = ".lto_discard";
1131 if (!NonPrevailingAsmSymbols.empty()) {
1132 // Don't dicard a symbol if there is a live .symver for it.
1134 M, [&](StringRef Name, StringRef Alias) {
1135 if (!NonPrevailingAsmSymbols.count(Alias))
1136 NonPrevailingAsmSymbols.erase(Name);
1137 });
1138 NewIA += " " + llvm::join(NonPrevailingAsmSymbols, ", ");
1139 }
1140 NewIA += "\n";
1141 M.prependModuleInlineAsm({NewIA, M.getModuleInlineAsm().front().Props});
1142 }
1143
1144 assert(MsymI == MsymE);
1145 return std::make_pair(std::move(Mod), Res);
1146}
1147
1148Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod,
1149 bool LivenessFromIndex) {
1150 llvm::TimeTraceScope timeScope("LTO link regular LTO");
1151 std::vector<GlobalValue *> Keep;
1152 for (GlobalValue *GV : Mod.Keep) {
1153 if (LivenessFromIndex) {
1154 const auto GUID = GV->getGUIDOrFallback();
1155 if (!ThinLTO.CombinedIndex.isGUIDLive(GUID)) {
1156 if (Function *F = dyn_cast<Function>(GV)) {
1157 if (DiagnosticOutputFile) {
1158 if (Error Err = F->materialize())
1159 return Err;
1160 auto R = OptimizationRemark(DEBUG_TYPE, "deadfunction", F);
1161 R << ore::NV("Function", F) << " not added to the combined module ";
1162 emitRemark(R);
1163 }
1164 }
1165 continue;
1166 }
1167 }
1168
1169 if (!GV->hasAvailableExternallyLinkage()) {
1170 Keep.push_back(GV);
1171 continue;
1172 }
1173
1174 // Only link available_externally definitions if we don't already have a
1175 // definition.
1176 GlobalValue *CombinedGV =
1177 RegularLTO.CombinedModule->getNamedValue(GV->getName());
1178 if (CombinedGV && !CombinedGV->isDeclaration())
1179 continue;
1180
1181 Keep.push_back(GV);
1182 }
1183
1184 return RegularLTO.Mover->move(std::move(Mod.M), Keep, nullptr,
1185 /* IsPerformingImport */ false);
1186}
1187
1188// Add a ThinLTO module to the link.
1189Expected<ArrayRef<SymbolResolution>>
1190LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
1192 llvm::TimeTraceScope timeScope("LTO add thin LTO");
1193 const auto BMID = BM.getModuleIdentifier();
1194 ArrayRef<SymbolResolution> ResTmp = Res;
1195 DenseSet<StringRef> Prevailing;
1196 for (const InputFile::Symbol &Sym : Syms) {
1197 assert(!ResTmp.empty());
1198 const SymbolResolution &R = ResTmp.consume_front();
1199 if (!Sym.getIRName().empty() && R.Prevailing)
1200 Prevailing.insert(Sym.getIRName());
1201 }
1202
1203 // Track the GUIDs stored in the bitcode GUID table.
1204 StringMap<GlobalValue::GUID> IRSpecifiedGUIDs;
1205 if (Error Err = BM.readSummary(
1206 ThinLTO.CombinedIndex, BMID,
1207 [&](StringRef Name) { return (Prevailing.count(Name) > 0); },
1208 [&](ValueInfo VI) {
1209 auto IT = IRSpecifiedGUIDs.insert({VI.name(), VI.getGUID()});
1210 (void)IT;
1211 assert(IT.second);
1212 }))
1213 return Err;
1214 LLVM_DEBUG(dbgs() << "Module " << BMID << "\n");
1215
1216 for (const InputFile::Symbol &Sym : Syms) {
1217 assert(!Res.empty());
1218 const SymbolResolution &R = Res.consume_front();
1219 auto GUIDIter = IRSpecifiedGUIDs.find(Sym.getIRName());
1220 // The bitcode GUID table might not be present if this is an old bitcode
1221 // file. For backwards-compatibility, just compute the GUID now in that
1222 // case.
1223 auto GUID =
1224 GUIDIter == IRSpecifiedGUIDs.end()
1227 Sym.getIRName(), GlobalValue::ExternalLinkage, ""))
1228 : GUIDIter->second;
1229 if (!Sym.getIRName().empty() &&
1230 (R.Prevailing || R.FinalDefinitionInLinkageUnit)) {
1231 if (R.Prevailing) {
1232 (*GlobalResolutions)[Sym.getName()].setGUID(GUID);
1233 ThinLTO.setPrevailingModuleForGUID(GUID, BMID);
1234 // For linker redefined symbols (via --wrap or --defsym) we want to
1235 // switch the linkage to `weak` to prevent IPOs from happening.
1236 // Find the summary in the module for this very GV and record the new
1237 // linkage so that we can switch it when we import the GV.
1238 if (R.LinkerRedefined)
1239 if (auto *S = ThinLTO.CombinedIndex.findSummaryInModule(GUID, BMID))
1240 S->setLinkage(GlobalValue::WeakAnyLinkage);
1241 }
1242
1243 // If the linker resolved the symbol to a local definition then mark it
1244 // as local in the summary for the module we are adding.
1245 if (R.FinalDefinitionInLinkageUnit) {
1246 if (auto *S = ThinLTO.CombinedIndex.findSummaryInModule(GUID, BMID)) {
1247 S->setDSOLocal(true);
1248 }
1249 }
1250 }
1251 }
1252
1253 if (!ThinLTO.ModuleMap.insert({BMID, BM}).second)
1255 "Expected at most one ThinLTO module per bitcode file",
1257
1258 if (!Conf.ThinLTOModulesToCompile.empty()) {
1259 if (!ThinLTO.ModulesToCompile)
1260 ThinLTO.ModulesToCompile = ModuleMapType();
1261 // This is a fuzzy name matching where only modules with name containing the
1262 // specified switch values are going to be compiled.
1263 for (const std::string &Name : Conf.ThinLTOModulesToCompile) {
1264 if (BMID.contains(Name)) {
1265 ThinLTO.ModulesToCompile->insert({BMID, BM});
1266 LLVM_DEBUG(dbgs() << "[ThinLTO] Selecting " << BMID << " to compile\n");
1267 break;
1268 }
1269 }
1270 }
1271
1272 return Res;
1273}
1274
1275unsigned LTO::getMaxTasks() const {
1276 CalledGetMaxTasks = true;
1277 auto ModuleCount = ThinLTO.ModulesToCompile ? ThinLTO.ModulesToCompile->size()
1278 : ThinLTO.ModuleMap.size();
1279 return RegularLTO.ParallelCodeGenParallelismLevel + ModuleCount;
1280}
1281
1282// If only some of the modules were split, we cannot correctly handle
1283// code that contains type tests or type checked loads.
1284Error LTO::checkPartiallySplit() {
1286 return Error::success();
1287
1288 const Module *Combined = RegularLTO.CombinedModule.get();
1289 Function *TypeTestFunc =
1290 Intrinsic::getDeclarationIfExists(Combined, Intrinsic::type_test);
1291 Function *TypeCheckedLoadFunc =
1292 Intrinsic::getDeclarationIfExists(Combined, Intrinsic::type_checked_load);
1293 Function *TypeCheckedLoadRelativeFunc = Intrinsic::getDeclarationIfExists(
1294 Combined, Intrinsic::type_checked_load_relative);
1295
1296 // First check if there are type tests / type checked loads in the
1297 // merged regular LTO module IR.
1298 if ((TypeTestFunc && !TypeTestFunc->use_empty()) ||
1299 (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty()) ||
1300 (TypeCheckedLoadRelativeFunc &&
1301 !TypeCheckedLoadRelativeFunc->use_empty()))
1303 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1305
1306 // Otherwise check if there are any recorded in the combined summary from the
1307 // ThinLTO modules.
1308 for (auto &P : ThinLTO.CombinedIndex) {
1309 for (auto &S : P.second.getSummaryList()) {
1310 auto *FS = dyn_cast<FunctionSummary>(S.get());
1311 if (!FS)
1312 continue;
1313 if (!FS->type_test_assume_vcalls().empty() ||
1314 !FS->type_checked_load_vcalls().empty() ||
1315 !FS->type_test_assume_const_vcalls().empty() ||
1316 !FS->type_checked_load_const_vcalls().empty() ||
1317 !FS->type_tests().empty())
1319 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1321 }
1322 }
1323 return Error::success();
1324}
1325
1326Error LTO::setupPassPlugins() {
1327 // Load plugins from file. Failures leave them all unregistered.
1329 for (const std::string &PluginFN : Conf.PassPluginFilenames) {
1330 Expected<PassPlugin> Plugin = PassPlugin::load(PluginFN);
1331 if (!Plugin)
1332 return Plugin.takeError();
1333 Loaded.push_back(std::make_unique<PassPlugin>(std::move(*Plugin)));
1334 }
1335
1336 // Register them ahead of the client loaded ones.
1337 SmallVector<PassPlugin *> FromFiles;
1338 for (std::unique_ptr<PassPlugin> &Plugin : Loaded) {
1339 FromFiles.push_back(Plugin.get());
1340 PassPlugins.push_back(std::move(Plugin));
1341 }
1342 Conf.LoadedPassPlugins.insert(Conf.LoadedPassPlugins.begin(),
1343 FromFiles.begin(), FromFiles.end());
1344
1345 Conf.PassPluginFilenames.clear();
1346
1347 if (Conf.PassPluginArgs.empty())
1348 return Error::success();
1350 for (const PassPlugin *Plugin : Conf.LoadedPassPlugins)
1351 Infos.push_back(Plugin->getInfo());
1352#define HANDLE_EXTENSION(Ext) Infos.push_back(get##Ext##PluginInfo());
1353#include "llvm/Support/Extension.def"
1354 return llvm::passPluginArguments(Infos, Conf.PassPluginArgs);
1355}
1356
1358 // Call the base class cleanup() explicitly since run() may be invoked on a
1359 // derived LTO object.
1360 llvm::scope_exit CleanUp([this]() { LTO::cleanup(); });
1361
1362 if (Error Err = setupPassPlugins())
1363 return Err;
1364
1365 // Compute "dead" symbols, we don't want to import/export these!
1366 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
1367 DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions;
1368 for (auto &Res : *GlobalResolutions) {
1369 // Normally resolution have IR name of symbol. We can do nothing here
1370 // otherwise. See comments in GlobalResolution struct for more details.
1371 if (Res.second.IRName.empty())
1372 continue;
1373
1374 GlobalValue::GUID GUID = Res.second.getGUID();
1375
1376 if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
1377 GUIDPreservedSymbols.insert(GUID);
1378
1379 if (Res.second.ExportDynamic)
1380 DynamicExportSymbols.insert(GUID);
1381
1382 GUIDPrevailingResolutions[GUID] =
1383 Res.second.Prevailing ? PrevailingType::Yes : PrevailingType::No;
1384 }
1385
1386 auto isPrevailing = [&](GlobalValue::GUID G) {
1387 auto It = GUIDPrevailingResolutions.find(G);
1388 if (It == GUIDPrevailingResolutions.end())
1390 return It->second;
1391 };
1392 computeDeadSymbolsWithConstProp(ThinLTO.CombinedIndex, GUIDPreservedSymbols,
1393 isPrevailing, Conf.OptLevel > 0);
1394
1395 // Setup output file to emit statistics.
1396 auto StatsFileOrErr = setupStatsFile(Conf.StatsFile);
1397 if (!StatsFileOrErr)
1398 return StatsFileOrErr.takeError();
1399 std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
1400
1401 if (Error Err = setupOptimizationRemarks())
1402 return Err;
1403
1404 // TODO: Ideally this would be controlled automatically by detecting that we
1405 // are linking with an allocator that supports these interfaces, rather than
1406 // an internal option (which would still be needed for tests, however). For
1407 // example, if the library exported a symbol like __malloc_hot_cold the linker
1408 // could recognize that and set a flag in the lto::Config.
1410 ThinLTO.CombinedIndex.setWithSupportsHotColdNew();
1411
1412 Error Result = runRegularLTO(AddStream);
1413 if (!Result)
1414 // This will reset the GlobalResolutions optional once done with it to
1415 // reduce peak memory before importing.
1416 Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
1417
1418 if (StatsFile)
1419 PrintStatisticsJSON(StatsFile->os());
1420
1421 return Result;
1422}
1423
1424Error LTO::runRegularLTO(AddStreamFn AddStream) {
1425 llvm::TimeTraceScope timeScope("Run regular LTO");
1426 LLVM_DEBUG(dbgs() << "Running regular LTO\n");
1427
1428 // Finalize linking of regular LTO modules containing summaries now that
1429 // we have computed liveness information.
1430 if (!RegularLTO.ModsWithSummaries.empty()) {
1431 {
1432 llvm::TimeTraceScope timeScope("Link regular LTO");
1433 for (auto &M : RegularLTO.ModsWithSummaries)
1434 if (Error Err =
1435 linkRegularLTO(std::move(M), /*LivenessFromIndex=*/true))
1436 return Err;
1438 RegularLTO.ModsWithSummaries.shrink_to_fit();
1439 }
1442 }
1443
1444 // Ensure we don't have inconsistently split LTO units with type tests.
1445 // FIXME: this checks both LTO and ThinLTO. It happens to work as we take
1446 // this path both cases but eventually this should be split into two and
1447 // do the ThinLTO checks in `runThinLTO`.
1448 if (Error Err = checkPartiallySplit())
1449 return Err;
1450
1451 // Make sure commons have the right size/alignment: we kept the largest from
1452 // all the prevailing when adding the inputs, and we apply it here.
1453 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
1454 for (auto &I : RegularLTO.Commons) {
1455 if (!I.second.Prevailing)
1456 // Don't do anything if no instance of this common was prevailing.
1457 continue;
1458 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
1459 if (OldGV && OldGV->getGlobalSize(DL) == I.second.Size) {
1460 // Don't create a new global if the type is already correct, just make
1461 // sure the alignment is correct.
1462 OldGV->setAlignment(I.second.Alignment);
1463 continue;
1464 }
1465 ArrayType *Ty =
1466 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
1467 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
1470 GV->setAlignment(I.second.Alignment);
1471 if (OldGV) {
1472 OldGV->replaceAllUsesWith(GV);
1473 GV->takeName(OldGV);
1474 OldGV->eraseFromParent();
1475 } else {
1476 GV->setName(I.first);
1477 }
1478 }
1479
1480 bool WholeProgramVisibilityEnabledInLTO =
1481 Conf.HasWholeProgramVisibility &&
1482 // If validation is enabled, upgrade visibility only when all vtables
1483 // have typeinfos.
1484 (!Conf.ValidateAllVtablesHaveTypeInfos || Conf.AllVtablesHaveTypeInfos);
1485
1486 // This returns true when the name is local or not defined. Locals are
1487 // expected to be handled separately.
1488 auto IsVisibleToRegularObj = [&](StringRef name) {
1489 auto It = GlobalResolutions->find(name);
1490 return (It == GlobalResolutions->end() ||
1491 It->second.VisibleOutsideSummary || !It->second.Prevailing);
1492 };
1493
1494 // If allowed, upgrade public vcall visibility metadata to linkage unit
1495 // visibility before whole program devirtualization in the optimizer.
1497 *RegularLTO.CombinedModule, WholeProgramVisibilityEnabledInLTO,
1498 DynamicExportSymbols, Conf.ValidateAllVtablesHaveTypeInfos,
1499 IsVisibleToRegularObj);
1500 updatePublicTypeTestCalls(*RegularLTO.CombinedModule,
1501 WholeProgramVisibilityEnabledInLTO);
1502
1503 if (Conf.PreOptModuleHook &&
1504 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
1505 return Error::success();
1506
1507 if (!Conf.CodeGenOnly) {
1508 for (const auto &R : *GlobalResolutions) {
1509 GlobalValue *GV =
1510 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
1511 if (!R.second.isPrevailingIRSymbol())
1512 continue;
1513 if (R.second.Partition != 0 &&
1514 R.second.Partition != GlobalResolution::External)
1515 continue;
1516
1517 // Ignore symbols defined in other partitions.
1518 // Also skip declarations, which are not allowed to have internal linkage.
1519 if (!GV || GV->hasLocalLinkage() || GV->isDeclaration())
1520 continue;
1521
1522 // Symbols that are marked DLLImport or DLLExport should not be
1523 // internalized, as they are either externally visible or referencing
1524 // external symbols. Symbols that have AvailableExternally or Appending
1525 // linkage might be used by future passes and should be kept as is.
1526 // These linkages are seen in Unified regular LTO, because the process
1527 // of creating split LTO units introduces symbols with that linkage into
1528 // one of the created modules. Normally, only the ThinLTO backend would
1529 // compile this module, but Unified Regular LTO processes both
1530 // modules created by the splitting process as regular LTO modules.
1534 continue;
1535
1536 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
1538 if (EnableLTOInternalization && R.second.Partition == 0)
1540 }
1541
1542 if (Conf.PostInternalizeModuleHook &&
1543 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
1544 return Error::success();
1545 }
1546
1547 if (!RegularLTO.EmptyCombinedModule || Conf.AlwaysEmitRegularLTOObj) {
1548 if (Error Err = backend(
1549 Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
1550 *RegularLTO.CombinedModule, ThinLTO.CombinedIndex, BitcodeLibFuncs))
1551 return Err;
1552 }
1553
1554 return Error::success();
1555}
1556
1558 RTLIB::RuntimeLibcallsInfo Libcalls(TT);
1559 SmallVector<const char *> LibcallSymbols;
1560 LibcallSymbols.reserve(Libcalls.getNumAvailableLibcallImpls());
1561
1562 for (RTLIB::LibcallImpl Impl : RTLIB::libcall_impls()) {
1563 if (Libcalls.isAvailable(Impl))
1564 LibcallSymbols.push_back(Libcalls.getLibcallImplName(Impl).data());
1565 }
1566
1567 return LibcallSymbols;
1568}
1569
1571 StringSaver &Saver) {
1572 auto TLII = std::make_unique<TargetLibraryInfoImpl>(TT);
1573 TargetLibraryInfo TLI(*TLII);
1574 SmallVector<StringRef> LibFuncSymbols;
1575 LibFuncSymbols.reserve(LibFunc::NumLibFuncs);
1576 for (unsigned I = LibFunc::Begin_LibFunc; I != LibFunc::End_LibFunc; ++I) {
1577 LibFunc F = static_cast<LibFunc>(I);
1578 if (TLI.has(F))
1579 LibFuncSymbols.push_back(Saver.save(TLI.getName(F)).data());
1580 }
1581 return LibFuncSymbols;
1582}
1583
1585 const FunctionImporter::ImportMapTy &ImportList, unsigned Task,
1586 llvm::StringRef ModulePath, const std::string &NewModulePath) const {
1587 return emitFiles(ImportList, Task, ModulePath, NewModulePath,
1588 NewModulePath + ".thinlto.bc");
1589}
1590
1592 const FunctionImporter::ImportMapTy &ImportList, unsigned Task,
1593 llvm::StringRef ModulePath, const std::string &NewModulePath,
1594 StringRef SummaryPath) const {
1595 ModuleToSummariesForIndexTy ModuleToSummariesForIndex;
1596 GVSummaryPtrSet DeclarationSummaries;
1597
1598 std::error_code EC;
1600 ImportList, ModuleToSummariesForIndex,
1601 DeclarationSummaries);
1602 // Resolve the output stream (either file-backed or callback-provided) for the
1603 // index file.
1604 std::unique_ptr<raw_pwrite_stream> OS;
1605 if (Conf.GetSummaryIndexOutputStream) {
1606 OS = Conf.GetSummaryIndexOutputStream(Task);
1607 assert(OS && "GetSummaryIndexOutputStream returned null");
1608 } else {
1609 auto FileOS = std::make_unique<raw_fd_ostream>(SummaryPath, EC,
1611 if (EC)
1612 return createFileError("cannot open " + Twine(SummaryPath), EC);
1613 OS = std::move(FileOS);
1614 }
1615
1616 writeIndexToFile(CombinedIndex, *OS, &ModuleToSummariesForIndex,
1617 &DeclarationSummaries);
1618
1619 // Emit imports files if requested, using callback if provided.
1620 if (Conf.GetImportsListOutputArray) {
1621 std::vector<std::string> &ImportsListRef =
1622 Conf.GetImportsListOutputArray(Task);
1624 ModulePath, ModuleToSummariesForIndex,
1625 [&](StringRef M) { ImportsListRef.push_back(M.str()); });
1626 } else if (ShouldEmitImportsFiles) {
1627 if (Error E = EmitImportsFiles(ModulePath, NewModulePath + ".imports",
1628 ModuleToSummariesForIndex))
1629 return E;
1630 }
1631 return Error::success();
1632}
1633
1634namespace {
1635/// Base class for ThinLTO backends that perform code generation and insert the
1636/// generated files back into the link.
1637class CGThinBackend : public ThinBackendProc {
1638protected:
1639 DenseSet<GlobalValue::GUID> CfiFunctionDefs;
1640 DenseSet<GlobalValue::GUID> CfiFunctionDecls;
1641 bool ShouldEmitIndexFiles;
1642
1643public:
1644 CGThinBackend(
1645 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1646 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1647 lto::IndexWriteCallback OnWrite, bool ShouldEmitIndexFiles,
1648 bool ShouldEmitImportsFiles, ThreadPoolStrategy ThinLTOParallelism)
1649 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
1650 OnWrite, ShouldEmitImportsFiles, ThinLTOParallelism),
1651 ShouldEmitIndexFiles(ShouldEmitIndexFiles) {
1652 auto &Defs = CombinedIndex.cfiFunctionDefs();
1653 CfiFunctionDefs.insert_range(Defs.getExportedThinLTOGUIDs());
1654 auto &Decls = CombinedIndex.cfiFunctionDecls();
1655 CfiFunctionDecls.insert_range(Decls.getExportedThinLTOGUIDs());
1656 }
1657};
1658
1659/// This backend performs code generation by scheduling a job to run on
1660/// an in-process thread when invoked for each task.
1661class InProcessThinBackend : public CGThinBackend {
1662protected:
1663 // Callback used to add generated native object files to the link by code
1664 // generating directly into the returned output stream.
1665 AddStreamFn AddStream;
1666 FileCache Cache;
1667 ArrayRef<StringRef> BitcodeLibFuncs;
1668
1669public:
1670 InProcessThinBackend(
1671 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1672 ThreadPoolStrategy ThinLTOParallelism,
1673 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1674 AddStreamFn AddStream, FileCache Cache, lto::IndexWriteCallback OnWrite,
1675 bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles,
1676 ArrayRef<StringRef> BitcodeLibFuncs)
1677 : CGThinBackend(Conf, CombinedIndex, ModuleToDefinedGVSummaries, OnWrite,
1678 ShouldEmitIndexFiles, ShouldEmitImportsFiles,
1679 ThinLTOParallelism),
1680 AddStream(std::move(AddStream)), Cache(std::move(Cache)),
1681 BitcodeLibFuncs(BitcodeLibFuncs) {}
1682
1683 virtual Error runThinLTOBackendThread(
1684 AddStreamFn AddStream, FileCache Cache, unsigned Task, BitcodeModule BM,
1685 ModuleSummaryIndex &CombinedIndex,
1686 const FunctionImporter::ImportMapTy &ImportList,
1687 const FunctionImporter::ExportSetTy &ExportList,
1688 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1689 const GVSummaryMapTy &DefinedGlobals,
1690 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1691 auto ModuleID = BM.getModuleIdentifier();
1692 llvm::TimeTraceScope timeScope("Run ThinLTO backend thread (in-process)",
1693 ModuleID);
1694 auto RunThinBackend = [&](AddStreamFn AddStream) {
1695 LTOLLVMContext BackendContext(Conf);
1696 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
1697 if (!MOrErr)
1698 return MOrErr.takeError();
1699
1700 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
1701 ImportList, DefinedGlobals, &ModuleMap,
1702 Conf.CodeGenOnly, BitcodeLibFuncs);
1703 };
1704 if (ShouldEmitIndexFiles) {
1705 if (auto E = emitFiles(ImportList, Task, ModuleID, ModuleID.str()))
1706 return E;
1707 }
1708
1709 if (!Cache.isValid() || !CombinedIndex.modulePaths().count(ModuleID) ||
1710 all_of(CombinedIndex.getModuleHash(ModuleID),
1711 [](uint32_t V) { return V == 0; }))
1712 // Cache disabled or no entry for this module in the combined index or
1713 // no module hash.
1714 return RunThinBackend(AddStream);
1715
1716 // The module may be cached, this helps handling it.
1717 std::string Key = computeLTOCacheKey(
1718 Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1719 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1720 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task, Key, ModuleID);
1721 if (Error Err = CacheAddStreamOrErr.takeError())
1722 return Err;
1723 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1724 if (CacheAddStream)
1725 return RunThinBackend(CacheAddStream);
1726
1727 return Error::success();
1728 }
1729
1730 Error start(
1731 unsigned Task, BitcodeModule BM,
1732 const FunctionImporter::ImportMapTy &ImportList,
1733 const FunctionImporter::ExportSetTy &ExportList,
1734 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1735 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1736 StringRef ModulePath = BM.getModuleIdentifier();
1737 assert(ModuleToDefinedGVSummaries.count(ModulePath));
1738 const GVSummaryMapTy &DefinedGlobals =
1739 ModuleToDefinedGVSummaries.find(ModulePath)->second;
1740 BackendThreadPool.async(
1741 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1742 const FunctionImporter::ImportMapTy &ImportList,
1743 const FunctionImporter::ExportSetTy &ExportList,
1744 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1745 &ResolvedODR,
1746 const GVSummaryMapTy &DefinedGlobals,
1747 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1748 if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1750 "thin backend");
1751 Error E = runThinLTOBackendThread(
1752 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1753 ResolvedODR, DefinedGlobals, ModuleMap);
1754 if (E) {
1755 std::unique_lock<std::mutex> L(ErrMu);
1756 if (Err)
1757 Err = joinErrors(std::move(*Err), std::move(E));
1758 else
1759 Err = std::move(E);
1760 }
1761 if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1763 },
1764 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
1765 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
1766
1767 if (OnWrite)
1768 OnWrite(std::string(ModulePath));
1769 return Error::success();
1770 }
1771};
1772
1773/// This backend is utilized in the first round of a two-codegen round process.
1774/// It first saves optimized bitcode files to disk before the codegen process
1775/// begins. After codegen, it stores the resulting object files in a scratch
1776/// buffer. Note the codegen data stored in the scratch buffer will be extracted
1777/// and merged in the subsequent step.
1778class FirstRoundThinBackend : public InProcessThinBackend {
1779 AddStreamFn IRAddStream;
1780 FileCache IRCache;
1781
1782public:
1783 FirstRoundThinBackend(
1784 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1785 ThreadPoolStrategy ThinLTOParallelism,
1786 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1787 AddStreamFn CGAddStream, FileCache CGCache,
1788 ArrayRef<StringRef> BitcodeLibFuncs, AddStreamFn IRAddStream,
1789 FileCache IRCache)
1790 : InProcessThinBackend(Conf, CombinedIndex, ThinLTOParallelism,
1791 ModuleToDefinedGVSummaries, std::move(CGAddStream),
1792 std::move(CGCache), /*OnWrite=*/nullptr,
1793 /*ShouldEmitIndexFiles=*/false,
1794 /*ShouldEmitImportsFiles=*/false, BitcodeLibFuncs),
1795 IRAddStream(std::move(IRAddStream)), IRCache(std::move(IRCache)) {}
1796
1797 Error runThinLTOBackendThread(
1798 AddStreamFn CGAddStream, FileCache CGCache, unsigned Task,
1799 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1800 const FunctionImporter::ImportMapTy &ImportList,
1801 const FunctionImporter::ExportSetTy &ExportList,
1802 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1803 const GVSummaryMapTy &DefinedGlobals,
1804 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1805 auto ModuleID = BM.getModuleIdentifier();
1806 llvm::TimeTraceScope timeScope("Run ThinLTO backend thread (first round)",
1807 ModuleID);
1808 auto RunThinBackend = [&](AddStreamFn CGAddStream,
1809 AddStreamFn IRAddStream) {
1810 LTOLLVMContext BackendContext(Conf);
1811 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
1812 if (!MOrErr)
1813 return MOrErr.takeError();
1814
1815 return thinBackend(Conf, Task, CGAddStream, **MOrErr, CombinedIndex,
1816 ImportList, DefinedGlobals, &ModuleMap,
1817 Conf.CodeGenOnly, BitcodeLibFuncs, IRAddStream);
1818 };
1819 // Like InProcessThinBackend, we produce index files as needed for
1820 // FirstRoundThinBackend. However, these files are not generated for
1821 // SecondRoundThinBackend.
1822 if (ShouldEmitIndexFiles) {
1823 if (auto E = emitFiles(ImportList, Task, ModuleID, ModuleID.str()))
1824 return E;
1825 }
1826
1827 assert((CGCache.isValid() == IRCache.isValid()) &&
1828 "Both caches for CG and IR should have matching availability");
1829 if (!CGCache.isValid() || !CombinedIndex.modulePaths().count(ModuleID) ||
1830 all_of(CombinedIndex.getModuleHash(ModuleID),
1831 [](uint32_t V) { return V == 0; }))
1832 // Cache disabled or no entry for this module in the combined index or
1833 // no module hash.
1834 return RunThinBackend(CGAddStream, IRAddStream);
1835
1836 // Get CGKey for caching object in CGCache.
1837 std::string CGKey = computeLTOCacheKey(
1838 Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1839 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1840 Expected<AddStreamFn> CacheCGAddStreamOrErr =
1841 CGCache(Task, CGKey, ModuleID);
1842 if (Error Err = CacheCGAddStreamOrErr.takeError())
1843 return Err;
1844 AddStreamFn &CacheCGAddStream = *CacheCGAddStreamOrErr;
1845
1846 // Get IRKey for caching (optimized) IR in IRCache with an extra ID.
1847 std::string IRKey = recomputeLTOCacheKey(CGKey, /*ExtraID=*/"IR");
1848 Expected<AddStreamFn> CacheIRAddStreamOrErr =
1849 IRCache(Task, IRKey, ModuleID);
1850 if (Error Err = CacheIRAddStreamOrErr.takeError())
1851 return Err;
1852 AddStreamFn &CacheIRAddStream = *CacheIRAddStreamOrErr;
1853
1854 // Ideally, both CG and IR caching should be synchronized. However, in
1855 // practice, their availability may differ due to different expiration
1856 // times. Therefore, if either cache is missing, the backend process is
1857 // triggered.
1858 if (CacheCGAddStream || CacheIRAddStream) {
1859 LLVM_DEBUG(dbgs() << "[FirstRound] Cache Miss for "
1860 << BM.getModuleIdentifier() << "\n");
1861 return RunThinBackend(CacheCGAddStream ? CacheCGAddStream : CGAddStream,
1862 CacheIRAddStream ? CacheIRAddStream : IRAddStream);
1863 }
1864
1865 return Error::success();
1866 }
1867};
1868
1869/// This backend operates in the second round of a two-codegen round process.
1870/// It starts by reading the optimized bitcode files that were saved during the
1871/// first round. The backend then executes the codegen only to further optimize
1872/// the code, utilizing the codegen data merged from the first round. Finally,
1873/// it writes the resulting object files as usual.
1874class SecondRoundThinBackend : public InProcessThinBackend {
1875 std::unique_ptr<SmallVector<StringRef>> IRFiles;
1876 stable_hash CombinedCGDataHash;
1877
1878public:
1879 SecondRoundThinBackend(
1880 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1881 ThreadPoolStrategy ThinLTOParallelism,
1882 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1883 AddStreamFn AddStream, FileCache Cache,
1884 ArrayRef<StringRef> BitcodeLibFuncs,
1885 std::unique_ptr<SmallVector<StringRef>> IRFiles,
1886 stable_hash CombinedCGDataHash)
1887 : InProcessThinBackend(Conf, CombinedIndex, ThinLTOParallelism,
1888 ModuleToDefinedGVSummaries, std::move(AddStream),
1889 std::move(Cache),
1890 /*OnWrite=*/nullptr,
1891 /*ShouldEmitIndexFiles=*/false,
1892 /*ShouldEmitImportsFiles=*/false, BitcodeLibFuncs),
1893 IRFiles(std::move(IRFiles)), CombinedCGDataHash(CombinedCGDataHash) {}
1894
1895 Error runThinLTOBackendThread(
1896 AddStreamFn AddStream, FileCache Cache, unsigned Task, BitcodeModule BM,
1897 ModuleSummaryIndex &CombinedIndex,
1898 const FunctionImporter::ImportMapTy &ImportList,
1899 const FunctionImporter::ExportSetTy &ExportList,
1900 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1901 const GVSummaryMapTy &DefinedGlobals,
1902 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1903 auto ModuleID = BM.getModuleIdentifier();
1904 llvm::TimeTraceScope timeScope("Run ThinLTO backend thread (second round)",
1905 ModuleID);
1906 auto RunThinBackend = [&](AddStreamFn AddStream) {
1907 LTOLLVMContext BackendContext(Conf);
1908 std::unique_ptr<Module> LoadedModule =
1909 cgdata::loadModuleForTwoRounds(BM, Task, BackendContext, *IRFiles);
1910
1911 return thinBackend(Conf, Task, AddStream, *LoadedModule, CombinedIndex,
1912 ImportList, DefinedGlobals, &ModuleMap,
1913 /*CodeGenOnly=*/true, BitcodeLibFuncs);
1914 };
1915 if (!Cache.isValid() || !CombinedIndex.modulePaths().count(ModuleID) ||
1916 all_of(CombinedIndex.getModuleHash(ModuleID),
1917 [](uint32_t V) { return V == 0; }))
1918 // Cache disabled or no entry for this module in the combined index or
1919 // no module hash.
1920 return RunThinBackend(AddStream);
1921
1922 // Get Key for caching the final object file in Cache with the combined
1923 // CGData hash.
1924 std::string Key = computeLTOCacheKey(
1925 Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1926 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1928 /*ExtraID=*/std::to_string(CombinedCGDataHash));
1929 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task, Key, ModuleID);
1930 if (Error Err = CacheAddStreamOrErr.takeError())
1931 return Err;
1932 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1933
1934 if (CacheAddStream) {
1935 LLVM_DEBUG(dbgs() << "[SecondRound] Cache Miss for "
1936 << BM.getModuleIdentifier() << "\n");
1937 return RunThinBackend(CacheAddStream);
1938 }
1939
1940 return Error::success();
1941 }
1942};
1943} // end anonymous namespace
1944
1947 bool ShouldEmitIndexFiles,
1948 bool ShouldEmitImportsFiles) {
1949 auto Func =
1950 [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1951 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1952 AddStreamFn AddStream, FileCache Cache,
1953 ArrayRef<StringRef> BitcodeLibFuncs) {
1954 return std::make_unique<InProcessThinBackend>(
1955 Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
1956 AddStream, Cache, OnWrite, ShouldEmitIndexFiles,
1957 ShouldEmitImportsFiles, BitcodeLibFuncs);
1958 };
1959 return ThinBackend(Func, Parallelism);
1960}
1961
1963 if (!TheTriple.isOSDarwin())
1964 return "";
1965 if (TheTriple.getArch() == Triple::x86_64)
1966 return "core2";
1967 if (TheTriple.getArch() == Triple::x86)
1968 return "yonah";
1969 if (TheTriple.isArm64e())
1970 return "apple-a12";
1971 if (TheTriple.getArch() == Triple::aarch64 ||
1972 TheTriple.getArch() == Triple::aarch64_32)
1973 return "cyclone";
1974 return "";
1975}
1976
1977// Given the original \p Path to an output file, replace any path
1978// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
1979// resulting directory if it does not yet exist.
1981 StringRef NewPrefix) {
1982 if (OldPrefix.empty() && NewPrefix.empty())
1983 return std::string(Path);
1984 SmallString<128> NewPath(Path);
1985 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
1986 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
1987 if (!ParentPath.empty()) {
1988 // Make sure the new directory exists, creating it if necessary.
1989 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
1990 llvm::errs() << "warning: could not create directory '" << ParentPath
1991 << "': " << EC.message() << '\n';
1992 }
1993 return std::string(NewPath);
1994}
1995
1996namespace {
1997class WriteIndexesThinBackend : public ThinBackendProc {
1998 std::string OldPrefix, NewPrefix, NativeObjectPrefix;
1999 raw_fd_ostream *LinkedObjectsFile;
2000 DenseSet<GlobalValue::GUID> CfiFunctionDefs;
2001 DenseSet<GlobalValue::GUID> CfiFunctionDecls;
2002
2003public:
2004 WriteIndexesThinBackend(
2005 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
2006 ThreadPoolStrategy ThinLTOParallelism,
2007 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
2008 std::string OldPrefix, std::string NewPrefix,
2009 std::string NativeObjectPrefix, bool ShouldEmitImportsFiles,
2010 raw_fd_ostream *LinkedObjectsFile, lto::IndexWriteCallback OnWrite)
2011 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
2012 OnWrite, ShouldEmitImportsFiles, ThinLTOParallelism),
2013 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
2014 NativeObjectPrefix(NativeObjectPrefix),
2015 LinkedObjectsFile(LinkedObjectsFile) {
2016 auto Defs = CombinedIndex.cfiFunctionDefs().getExportedThinLTOGUIDs();
2017 CfiFunctionDefs.insert(Defs.begin(), Defs.end());
2018 auto Decls = CombinedIndex.cfiFunctionDecls().getExportedThinLTOGUIDs();
2019 CfiFunctionDecls.insert(Decls.begin(), Decls.end());
2020 }
2021
2022 Error start(
2023 unsigned Task, BitcodeModule BM,
2024 const FunctionImporter::ImportMapTy &ImportList,
2025 const FunctionImporter::ExportSetTy &ExportList,
2026 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
2027 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
2028 StringRef ModulePath = BM.getModuleIdentifier();
2029
2030 // The contents of this file may be used as input to a native link, and must
2031 // therefore contain the processed modules in a determinstic order that
2032 // match the order they are provided on the command line. For that reason,
2033 // we cannot include this in the asynchronously executed lambda below.
2034 if (LinkedObjectsFile) {
2035 std::string ObjectPrefix =
2036 NativeObjectPrefix.empty() ? NewPrefix : NativeObjectPrefix;
2037 std::string LinkedObjectsFilePath =
2038 getThinLTOOutputFile(ModulePath, OldPrefix, ObjectPrefix);
2039 *LinkedObjectsFile << LinkedObjectsFilePath << '\n';
2040 }
2041
2042 BackendThreadPool.async(
2043 [this](unsigned Task, const StringRef ModulePath,
2044 const FunctionImporter::ImportMapTy &ImportList,
2045 const FunctionImporter::ExportSetTy &ExportList,
2046 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
2047 &ResolvedODR,
2048 const std::string &OldPrefix, const std::string &NewPrefix) {
2049 std::string NewModulePath =
2050 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
2051 auto E = emitFiles(ImportList, Task, ModulePath, NewModulePath);
2052 if (E) {
2053 std::unique_lock<std::mutex> L(ErrMu);
2054 if (Err)
2055 Err = joinErrors(std::move(*Err), std::move(E));
2056 else
2057 Err = std::move(E);
2058 }
2059 assert(ModuleToDefinedGVSummaries.count(ModulePath));
2060 const GVSummaryMapTy &DefinedGlobals =
2061 ModuleToDefinedGVSummaries.find(ModulePath)->second;
2062
2063 // DTLTO needs the per-module LTO cache key to probe the cache.
2064 if (Conf.GetCacheKeyOutputString) {
2065 std::string &CacheKey = Conf.GetCacheKeyOutputString(Task);
2066 CacheKey = computeLTOCacheKey(
2067 Conf, CombinedIndex, ModulePath, ImportList, ExportList,
2068 ResolvedODR, DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
2069 }
2070 },
2071 Task, ModulePath, ImportList, ExportList, ResolvedODR, OldPrefix,
2072 NewPrefix);
2073
2074 if (OnWrite)
2075 OnWrite(std::string(ModulePath));
2076 return Error::success();
2077 }
2078
2079 bool isSensitiveToInputOrder() override {
2080 // The order which modules are written to LinkedObjectsFile should be
2081 // deterministic and match the order they are passed on the command line.
2082 return true;
2083 }
2084};
2085} // end anonymous namespace
2086
2088 ThreadPoolStrategy Parallelism, std::string OldPrefix,
2089 std::string NewPrefix, std::string NativeObjectPrefix,
2090 bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile,
2091 IndexWriteCallback OnWrite) {
2092 auto Func =
2093 [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
2094 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
2095 AddStreamFn AddStream, FileCache Cache,
2096 ArrayRef<StringRef> BitcodeLibFuncs) {
2097 return std::make_unique<WriteIndexesThinBackend>(
2098 Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2099 OldPrefix, NewPrefix, NativeObjectPrefix, ShouldEmitImportsFiles,
2100 LinkedObjectsFile, OnWrite);
2101 };
2102 return ThinBackend(Func, Parallelism);
2103}
2104
2105Error LTO::runThinLTO(AddStreamFn AddStream, FileCache Cache,
2106 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
2107 llvm::TimeTraceScope timeScope("Run ThinLTO");
2108 LLVM_DEBUG(dbgs() << "Running ThinLTO\n");
2110 timeTraceProfilerBegin("ThinLink", StringRef(""));
2111 llvm::scope_exit TimeTraceScopeExit([]() {
2114 });
2115 if (ThinLTO.ModuleMap.empty())
2116 return Error::success();
2117
2119 llvm::errs() << "warning: [ThinLTO] No module compiled\n";
2120 return Error::success();
2121 }
2122
2123 if (Conf.CombinedIndexHook &&
2124 !Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols))
2125 return Error::success();
2126
2127 // Collect for each module the list of function it defines (GUID ->
2128 // Summary).
2129 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(
2130 ThinLTO.ModuleMap.size());
2131 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
2132 ModuleToDefinedGVSummaries);
2133 // Create entries for any modules that didn't have any GV summaries
2134 // (either they didn't have any GVs to start with, or we suppressed
2135 // generation of the summaries because they e.g. had inline assembly
2136 // uses that couldn't be promoted/renamed on export). This is so
2137 // InProcessThinBackend::start can still launch a backend thread, which
2138 // is passed the map of summaries for the module, without any special
2139 // handling for this case.
2140 for (auto &Mod : ThinLTO.ModuleMap)
2141 if (!ModuleToDefinedGVSummaries.count(Mod.first))
2142 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
2143
2144 FunctionImporter::ImportListsTy ImportLists(ThinLTO.ModuleMap.size());
2145 DenseMap<StringRef, FunctionImporter::ExportSetTy> ExportLists(
2146 ThinLTO.ModuleMap.size());
2147 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
2148
2149 if (DumpThinCGSCCs)
2150 ThinLTO.CombinedIndex.dumpSCCs(outs());
2151
2152 std::set<GlobalValue::GUID> ExportedGUIDs;
2153
2154 bool WholeProgramVisibilityEnabledInLTO =
2155 Conf.HasWholeProgramVisibility &&
2156 // If validation is enabled, upgrade visibility only when all vtables
2157 // have typeinfos.
2158 (!Conf.ValidateAllVtablesHaveTypeInfos || Conf.AllVtablesHaveTypeInfos);
2159 if (hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
2160 ThinLTO.CombinedIndex.setWithWholeProgramVisibility();
2161
2162 // If we're validating, get the vtable symbols that should not be
2163 // upgraded because they correspond to typeIDs outside of index-based
2164 // WPD info.
2165 DenseSet<GlobalValue::GUID> VisibleToRegularObjSymbols;
2166 if (WholeProgramVisibilityEnabledInLTO &&
2167 Conf.ValidateAllVtablesHaveTypeInfos) {
2168 // This returns true when the name is local or not defined. Locals are
2169 // expected to be handled separately.
2170 auto IsVisibleToRegularObj = [&](StringRef name) {
2171 auto It = GlobalResolutions->find(name);
2172 return (It == GlobalResolutions->end() ||
2173 It->second.VisibleOutsideSummary || !It->second.Prevailing);
2174 };
2175
2177 VisibleToRegularObjSymbols,
2178 IsVisibleToRegularObj);
2179 }
2180
2181 // If allowed, upgrade public vcall visibility to linkage unit visibility in
2182 // the summaries before whole program devirtualization below.
2184 ThinLTO.CombinedIndex, WholeProgramVisibilityEnabledInLTO,
2185 DynamicExportSymbols, VisibleToRegularObjSymbols);
2186
2187 // Perform index-based WPD. This will return immediately if there are
2188 // no index entries in the typeIdMetadata map (e.g. if we are instead
2189 // performing IR-based WPD in hybrid regular/thin LTO mode).
2190 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
2191 DenseSet<StringRef> ExternallyVisibleSymbolNames;
2192
2193 // Used by the promotion-time renaming logic. When non-null, this set
2194 // identifies symbols that should not be renamed during promotion.
2195 // It is non-null only when whole-program visibility is enabled and
2196 // renaming is not forced. Otherwise, the default renaming behavior applies.
2197 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr =
2198 (WholeProgramVisibilityEnabledInLTO && !AlwaysRenamePromotedLocals)
2199 ? &ExternallyVisibleSymbolNames
2200 : nullptr;
2202 ThinLTO.CombinedIndex, ExportedGUIDs, LocalWPDTargetsMap,
2203 ExternallyVisibleSymbolNamesPtr, &RegularLTO.Ctx);
2204
2205 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
2206 return ThinLTO.isPrevailingModuleForGUID(GUID, S->modulePath());
2207 };
2209 MemProfContextDisambiguation ContextDisambiguation;
2210 ContextDisambiguation.run(
2211 ThinLTO.CombinedIndex, isPrevailing, RegularLTO.Ctx,
2212 [&](StringRef PassName, StringRef RemarkName, const Twine &Msg) {
2213 auto R = OptimizationRemark(PassName.data(), RemarkName,
2214 LinkerRemarkFunction);
2215 R << Msg.str();
2216 emitRemark(R);
2217 });
2218 }
2219
2220 // Figure out which symbols need to be internalized. This also needs to happen
2221 // at -O0 because summary-based DCE is implemented using internalization, and
2222 // we must apply DCE consistently with the full LTO module in order to avoid
2223 // undefined references during the final link.
2224 for (auto &Res : *GlobalResolutions) {
2225 // If the symbol does not have external references or it is not prevailing,
2226 // then not need to mark it as exported from a ThinLTO partition.
2227 if (Res.second.Partition != GlobalResolution::External ||
2228 !Res.second.isPrevailingIRSymbol())
2229 continue;
2230 auto GUID = Res.second.getGUID();
2231 // Mark exported unless index-based analysis determined it to be dead.
2232 if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
2233 ExportedGUIDs.insert(GUID);
2234 }
2235
2236 // Reset the GlobalResolutions to deallocate the associated memory, as there
2237 // are no further accesses. We specifically want to do this before computing
2238 // cross module importing, which adds to peak memory via the computed import
2239 // and export lists.
2240 releaseGlobalResolutionsMemory();
2241
2242 if (Conf.OptLevel > 0)
2243 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
2244 isPrevailing, ImportLists, ExportLists);
2245
2246 // Any functions referenced by the jump table in the regular LTO object must
2247 // be exported.
2248 auto Defs = ThinLTO.CombinedIndex.cfiFunctionDefs().getExportedThinLTOGUIDs();
2249 ExportedGUIDs.insert(Defs.begin(), Defs.end());
2250 auto Decls =
2251 ThinLTO.CombinedIndex.cfiFunctionDecls().getExportedThinLTOGUIDs();
2252 ExportedGUIDs.insert(Decls.begin(), Decls.end());
2253
2254 auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
2255 const auto &ExportList = ExportLists.find(ModuleIdentifier);
2256 return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
2257 ExportedGUIDs.count(VI.getGUID());
2258 };
2259
2260 // Update local devirtualized targets that were exported by cross-module
2261 // importing or by other devirtualizations marked in the ExportedGUIDs set.
2262 updateIndexWPDForExports(ThinLTO.CombinedIndex, isExported,
2263 LocalWPDTargetsMap, ExternallyVisibleSymbolNamesPtr);
2264
2265 if (ExternallyVisibleSymbolNamesPtr) {
2266 // Add to ExternallyVisibleSymbolNames the set of unique names used by all
2267 // externally visible symbols in the index.
2268 for (auto &I : ThinLTO.CombinedIndex) {
2269 ValueInfo VI = ThinLTO.CombinedIndex.getValueInfo(I);
2270 for (const auto &Summary : VI.getSummaryList()) {
2271 const GlobalValueSummary *Base = Summary->getBaseObject();
2272 if (GlobalValue::isLocalLinkage(Base->linkage()))
2273 continue;
2274
2275 ExternallyVisibleSymbolNamesPtr->insert(VI.name());
2276 break;
2277 }
2278 }
2279 }
2280
2281 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported,
2282 isPrevailing,
2283 ExternallyVisibleSymbolNamesPtr);
2284
2285 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
2287 GlobalValue::LinkageTypes NewLinkage) {
2288 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
2289 };
2290 thinLTOResolvePrevailingInIndex(Conf, ThinLTO.CombinedIndex, isPrevailing,
2291 recordNewLinkage, GUIDPreservedSymbols);
2292
2293 thinLTOPropagateFunctionAttrs(ThinLTO.CombinedIndex, isPrevailing);
2294
2295 generateParamAccessSummary(Conf.LibraryOptions, ThinLTO.CombinedIndex);
2296
2299
2300 TimeTraceScopeExit.release();
2301
2302 auto &ModuleMap =
2303 ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap;
2304
2305 auto RunBackends = [&](ThinBackendProc *BackendProcess) -> Error {
2306 auto ProcessOneModule = [&](int I) -> Error {
2307 auto &Mod = *(ModuleMap.begin() + I);
2308 // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for
2309 // combined module and parallel code generation partitions.
2310 return BackendProcess->start(
2311 RegularLTO.ParallelCodeGenParallelismLevel + I, Mod.second,
2312 ImportLists[Mod.first], ExportLists[Mod.first],
2313 ResolvedODR[Mod.first], ThinLTO.ModuleMap);
2314 };
2315
2316 BackendProcess->setup(ModuleMap.size(),
2317 RegularLTO.ParallelCodeGenParallelismLevel,
2318 RegularLTO.CombinedModule->getTargetTriple());
2319
2320 if (BackendProcess->getThreadCount() == 1 ||
2321 BackendProcess->isSensitiveToInputOrder()) {
2322 // Process the modules in the order they were provided on the
2323 // command-line. It is important for this codepath to be used for
2324 // WriteIndexesThinBackend, to ensure the emitted LinkedObjectsFile lists
2325 // ThinLTO objects in the same order as the inputs, which otherwise would
2326 // affect the final link order.
2327 for (int I = 0, E = ModuleMap.size(); I != E; ++I)
2328 if (Error E = ProcessOneModule(I))
2329 return E;
2330 } else {
2331 // When executing in parallel, process largest bitsize modules first to
2332 // improve parallelism, and avoid starving the thread pool near the end.
2333 // This saves about 15 sec on a 36-core machine while link `clang.exe`
2334 // (out of 100 sec).
2335 std::vector<BitcodeModule *> ModulesVec;
2336 ModulesVec.reserve(ModuleMap.size());
2337 for (auto &Mod : ModuleMap)
2338 ModulesVec.push_back(&Mod.second);
2339 for (int I : generateModulesOrdering(ModulesVec))
2340 if (Error E = ProcessOneModule(I))
2341 return E;
2342 }
2343 return BackendProcess->wait();
2344 };
2345
2346 if (!cgdata::thinLTOTwoRounds(RegularLTO.Ctx.getLibraryOptions())) {
2347 std::unique_ptr<ThinBackendProc> BackendProc =
2348 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
2349 AddStream, Cache, BitcodeLibFuncs);
2350 return RunBackends(BackendProc.get());
2351 }
2352
2353 // Perform two rounds of code generation for ThinLTO:
2354 // 1. First round: Perform optimization and code generation, outputting to
2355 // temporary scratch objects.
2356 // 2. Merge code generation data extracted from the temporary scratch objects.
2357 // 3. Second round: Execute code generation again using the merged data.
2358 LLVM_DEBUG(dbgs() << "[TwoRounds] Initializing ThinLTO two-codegen rounds\n");
2359
2360 unsigned MaxTasks = getMaxTasks();
2361 auto Parallelism = ThinLTO.Backend.getParallelism();
2362 // Set up two additional streams and caches for storing temporary scratch
2363 // objects and optimized IRs, using the same cache directory as the original.
2364 cgdata::StreamCacheData CG(MaxTasks, Cache, "CG"), IR(MaxTasks, Cache, "IR");
2365
2366 // First round: Execute optimization and code generation, outputting to
2367 // temporary scratch objects. Serialize the optimized IRs before initiating
2368 // code generation.
2369 LLVM_DEBUG(dbgs() << "[TwoRounds] Running the first round of codegen\n");
2370 auto FirstRoundLTO = std::make_unique<FirstRoundThinBackend>(
2371 Conf, ThinLTO.CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2372 CG.AddStream, CG.Cache, BitcodeLibFuncs, IR.AddStream, IR.Cache);
2373 if (Error E = RunBackends(FirstRoundLTO.get()))
2374 return E;
2375
2376 LLVM_DEBUG(dbgs() << "[TwoRounds] Merging codegen data\n");
2377 auto CombinedHashOrErr = cgdata::mergeCodeGenData(
2378 RegularLTO.Ctx.getLibraryOptions(), *CG.getResult());
2379 if (Error E = CombinedHashOrErr.takeError())
2380 return E;
2381 auto CombinedHash = *CombinedHashOrErr;
2382 LLVM_DEBUG(dbgs() << "[TwoRounds] CGData hash: " << CombinedHash << "\n");
2383
2384 // Second round: Read the optimized IRs and execute code generation using the
2385 // merged data.
2386 LLVM_DEBUG(dbgs() << "[TwoRounds] Running the second round of codegen\n");
2387 auto SecondRoundLTO = std::make_unique<SecondRoundThinBackend>(
2388 Conf, ThinLTO.CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2389 AddStream, Cache, BitcodeLibFuncs, IR.getResult(), CombinedHash);
2390 return RunBackends(SecondRoundLTO.get());
2391}
2392
2396 std::optional<uint64_t> RemarksHotnessThreshold, int Count) {
2397 std::string Filename = std::string(RemarksFilename);
2398 // For ThinLTO, file.opt.<format> becomes
2399 // file.opt.<format>.thin.<num>.<format>.
2400 if (!Filename.empty() && Count != -1)
2401 Filename =
2402 (Twine(Filename) + ".thin." + llvm::utostr(Count) + "." + RemarksFormat)
2403 .str();
2404
2405 auto ResultOrErr = llvm::setupLLVMOptimizationRemarks(
2408 if (Error E = ResultOrErr.takeError())
2409 return std::move(E);
2410
2411 if (*ResultOrErr)
2412 (*ResultOrErr)->keep();
2413
2414 return ResultOrErr;
2415}
2416
2419 // Setup output file to emit statistics.
2420 if (StatsFilename.empty())
2421 return nullptr;
2422
2424 std::error_code EC;
2425 auto StatsFile =
2426 std::make_unique<ToolOutputFile>(StatsFilename, EC, sys::fs::OF_None);
2427 if (EC)
2428 return errorCodeToError(EC);
2429
2430 StatsFile->keep();
2431 return std::move(StatsFile);
2432}
2433
2434// Compute the ordering we will process the inputs: the rough heuristic here
2435// is to sort them per size so that the largest module get schedule as soon as
2436// possible. This is purely a compile-time optimization.
2438 auto Seq = llvm::seq<int>(0, R.size());
2439 std::vector<int> ModulesOrdering(Seq.begin(), Seq.end());
2440 llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) {
2441 auto LSize = R[LeftIndex]->getBuffer().size();
2442 auto RSize = R[RightIndex]->getBuffer().size();
2443 return LSize > RSize;
2444 });
2445 return ModulesOrdering;
2446}
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:1557
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:1275
virtual Error run(AddStreamFn AddStream, FileCache Cache={})
Runs the LTO pipeline.
Definition LTO.cpp:1357
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:1570
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:1584
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:1945
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:1980
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:1962
LLVM_ABI Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
Definition LTO.cpp:2418
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:2087
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:2393
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
Definition LTO.cpp:2437
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