LLVM 23.0.0git
LTO.h
Go to the documentation of this file.
1//===-LTO.h - 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 declares functions and classes used to support LTO. It is intended
10// to be used both by LTO classes as well as by clients (gold-plugin) that
11// don't utilize the LTO code generator interfaces.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_LTO_LTO_H
16#define LLVM_LTO_LTO_H
17
21#include <memory>
22
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/MapVector.h"
27#include "llvm/LTO/Config.h"
30#include "llvm/Support/Error.h"
33#include "llvm/Support/thread.h"
36
37namespace llvm {
38
39class Error;
40class IRMover;
41class LLVMContext;
42class MemoryBufferRef;
43class Module;
45class ToolOutputFile;
46
47/// Resolve linkage for prevailing symbols in the \p Index. Linkage changes
48/// recorded in the index and the ThinLTO backends must apply the changes to
49/// the module via thinLTOFinalizeInModule.
50///
51/// This is done for correctness (if value exported, ensure we always
52/// emit a copy), and compile-time optimization (allow drop of duplicates).
54 const lto::Config &C, ModuleSummaryIndex &Index,
56 isPrevailing,
58 recordNewLinkage,
59 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
60
61/// Update the linkages in the given \p Index to mark exported values
62/// as external and non-exported values as internal. The ThinLTO backends
63/// must apply the changes to the Module via thinLTOInternalizeModule.
65 ModuleSummaryIndex &Index,
66 function_ref<bool(StringRef, ValueInfo)> isExported,
68 isPrevailing,
69 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr = nullptr);
70
71/// Computes a unique hash for the Module considering the current list of
72/// export/import and other global analysis results.
74 const lto::Config &Conf, const ModuleSummaryIndex &Index,
75 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
76 const FunctionImporter::ExportSetTy &ExportList,
77 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
78 const GVSummaryMapTy &DefinedGlobals,
79 const DenseSet<GlobalValue::GUID> &CfiFunctionDefs = {},
80 const DenseSet<GlobalValue::GUID> &CfiFunctionDecls = {});
81
82/// Recomputes the LTO cache key for a given key with an extra identifier.
83LLVM_ABI std::string recomputeLTOCacheKey(const std::string &Key,
84 StringRef ExtraID);
85
86namespace lto {
87
88LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple);
89
90/// Given the original \p Path to an output file, replace any path
91/// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
92/// resulting directory if it does not yet exist.
93LLVM_ABI std::string getThinLTOOutputFile(StringRef Path, StringRef OldPrefix,
94 StringRef NewPrefix);
95
96/// Setup optimization remarks.
97LLVM_ABI Expected<LLVMRemarkFileHandle> setupLLVMOptimizationRemarks(
98 LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
99 StringRef RemarksFormat, bool RemarksWithHotness,
100 std::optional<uint64_t> RemarksHotnessThreshold = 0, int Count = -1);
101
102/// Setups the output file for saving statistics.
103LLVM_ABI Expected<std::unique_ptr<ToolOutputFile>>
104setupStatsFile(StringRef StatsFilename);
105
106/// Produces a container ordering for optimal multi-threaded processing. Returns
107/// ordered indices to elements in the input array.
109
110class LTO;
111struct SymbolResolution;
112
113/// An input file. This is a symbol table wrapper that only exposes the
114/// information that an LTO client should need in order to do symbol resolution.
115class InputFile {
116public:
117 struct Symbol;
118
119private:
120 // FIXME: Remove LTO class friendship once we have bitcode symbol tables.
121 friend LTO;
122 InputFile() = default;
123
124 std::vector<BitcodeModule> Mods;
126 std::vector<Symbol> Symbols;
127
128 // [begin, end) for each module
129 std::vector<std::pair<size_t, size_t>> ModuleSymIndices;
130
131 StringRef TargetTriple, SourceFileName, COFFLinkerOpts;
132 std::vector<StringRef> DependentLibraries;
133 std::vector<std::pair<StringRef, Comdat::SelectionKind>> ComdatTable;
134
135 MemoryBufferRef MbRef;
136 bool IsFatLTOObject = false;
137 // For distributed compilation, each input must exist as an individual bitcode
138 // file on disk and be identified by its ModuleID. Archive members and FatLTO
139 // objects violate this. So, in these cases we flag that the bitcode must be
140 // written out to a new standalone file.
141 bool SerializeForDistribution = false;
142 bool IsThinLTO = false;
143 StringRef ArchivePath;
144 StringRef MemberName;
145
146public:
148
149 /// Create an InputFile.
151 create(MemoryBufferRef Object);
152
153 /// The purpose of this struct is to only expose the symbol information that
154 /// an LTO client should need in order to do symbol resolution.
156 friend LTO;
157
158 public:
160
177
178 // Returns whether this symbol is a library call that LTO code generation
179 // may emit references to. Such symbols must be considered external, as
180 // removing them or modifying their interfaces would invalidate the code
181 // generator's knowledge about them.
182 bool isLibcall(const TargetLibraryInfo &TLI,
183 const RTLIB::RuntimeLibcallsInfo &Libcalls) const;
184 };
185
186 /// A range over the symbols in this InputFile.
187 ArrayRef<Symbol> symbols() const { return Symbols; }
188
189 /// Returns linker options specified in the input file.
190 StringRef getCOFFLinkerOpts() const { return COFFLinkerOpts; }
191
192 /// Returns dependent library specifiers from the input file.
193 ArrayRef<StringRef> getDependentLibraries() const { return DependentLibraries; }
194
195 /// Returns the path to the InputFile.
196 LLVM_ABI StringRef getName() const;
197
198 /// Returns the input file's target triple.
199 StringRef getTargetTriple() const { return TargetTriple; }
200
201 /// Returns the source file path specified at compile time.
202 StringRef getSourceFileName() const { return SourceFileName; }
203
204 // Returns a table with all the comdats used by this file.
208
209 // Returns the only BitcodeModule from InputFile.
211 // Returns the primary BitcodeModule from InputFile.
213 // Returns the memory buffer reference for this input file.
214 MemoryBufferRef getFileBuffer() const { return MbRef; }
215 // Returns true if this input should be serialized to disk for distribution.
216 // See the comment on SerializeForDistribution for details.
217 bool getSerializeForDistribution() const { return SerializeForDistribution; }
218 // Mark whether this input should be serialized to disk for distribution.
219 // See the comment on SerializeForDistribution for details.
220 void setSerializeForDistribution(bool SFD) { SerializeForDistribution = SFD; }
221 // Returns true if this bitcode came from a FatLTO object.
222 bool isFatLTOObject() const { return IsFatLTOObject; }
223 // Mark this bitcode as coming from a FatLTO object.
224 void fatLTOObject(bool FO) { IsFatLTOObject = FO; }
225
226 // Returns true if bitcode is ThinLTO.
227 bool isThinLTO() const { return IsThinLTO; }
228
229 // Store an archive path and a member name.
231 ArchivePath = Path;
232 MemberName = Name;
233 }
234 StringRef getArchivePath() const { return ArchivePath; }
235 StringRef getMemberName() const { return MemberName; }
236
237private:
238 ArrayRef<Symbol> module_symbols(unsigned I) const {
239 const auto &Indices = ModuleSymIndices[I];
240 return {Symbols.data() + Indices.first, Symbols.data() + Indices.second};
241 }
242};
243
244using IndexWriteCallback = std::function<void(const std::string &)>;
245
247
248/// This class defines the interface to the ThinLTO backend.
250protected:
251 const Config &Conf;
257 std::optional<Error> Err;
258 std::mutex ErrMu;
259
260public:
270
271 virtual ~ThinBackendProc() = default;
272 virtual void setup(unsigned ThinLTONumTasks, unsigned ThinLTOTaskOffset,
273 Triple Triple) {}
274 virtual Error start(
275 unsigned Task, BitcodeModule BM,
276 const FunctionImporter::ImportMapTy &ImportList,
277 const FunctionImporter::ExportSetTy &ExportList,
278 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
280 virtual Error wait() {
281 BackendThreadPool.wait();
282 if (Err)
283 return std::move(*Err);
284 return Error::success();
285 }
286 unsigned getThreadCount() { return BackendThreadPool.getMaxConcurrency(); }
287 virtual bool isSensitiveToInputOrder() { return false; }
288
289 // Write sharded indices and (optionally) imports to disk
291 StringRef ModulePath,
292 const std::string &NewModulePath) const;
293
294 // Write sharded indices to SummaryPath, (optionally) imports to disk, and
295 // (optionally) record imports in ImportsFiles.
297 const FunctionImporter::ImportMapTy &ImportList, StringRef ModulePath,
298 const std::string &NewModulePath, StringRef SummaryPath,
299 std::optional<std::reference_wrapper<ImportsFilesContainer>> ImportsFiles)
300 const;
301};
302
303/// This callable defines the behavior of a ThinLTO backend after the thin-link
304/// phase. It accepts a configuration \p C, a combined module summary index
305/// \p CombinedIndex, a map of module identifiers to global variable summaries
306/// \p ModuleToDefinedGVSummaries, a function to add output streams \p
307/// AddStream, and a file cache \p Cache. It returns a unique pointer to a
308/// ThinBackendProc, which can be used to launch backends in parallel.
309using ThinBackendFunction = std::function<std::unique_ptr<ThinBackendProc>(
310 const Config &C, ModuleSummaryIndex &CombinedIndex,
311 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
312 AddStreamFn AddStream, FileCache Cache,
313 ArrayRef<StringRef> BitcodeLibFuncs)>;
314
315/// This type defines the behavior following the thin-link phase during ThinLTO.
316/// It encapsulates a backend function and a strategy for thread pool
317/// parallelism. Clients should use one of the provided create*ThinBackend()
318/// functions to instantiate a ThinBackend. Parallelism defines the thread pool
319/// strategy to be used for processing.
322 : Func(std::move(Func)), Parallelism(std::move(Parallelism)) {}
323 ThinBackend() = default;
324
325 std::unique_ptr<ThinBackendProc> operator()(
326 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
327 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
328 AddStreamFn AddStream, FileCache Cache,
329 ArrayRef<StringRef> BitcodeLibFuncs) {
330 assert(isValid() && "Invalid backend function");
331 return Func(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
332 std::move(AddStream), std::move(Cache), BitcodeLibFuncs);
333 }
334 ThreadPoolStrategy getParallelism() const { return Parallelism; }
335 bool isValid() const { return static_cast<bool>(Func); }
336
337private:
338 ThinBackendFunction Func = nullptr;
339 ThreadPoolStrategy Parallelism;
340};
341
342/// This ThinBackend runs the individual backend jobs in-process.
343/// The default value means to use one job per hardware core (not hyper-thread).
344/// OnWrite is callback which receives module identifier and notifies LTO user
345/// that index file for the module (and optionally imports file) was created.
346/// ShouldEmitIndexFiles being true will write sharded ThinLTO index files
347/// to the same path as the input module, with suffix ".thinlto.bc"
348/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
349/// similar path with ".imports" appended instead.
351 ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite = nullptr,
352 bool ShouldEmitIndexFiles = false, bool ShouldEmitImportsFiles = false);
353
354/// This ThinBackend generates the index shards and then runs the individual
355/// backend jobs via an external process. It takes the same parameters as the
356/// InProcessThinBackend; however, these parameters only control the behavior
357/// when generating the index files for the modules. Additionally:
358/// LinkerOutputFile is a string that should identify this LTO invocation in
359/// the context of a wider build. It's used for naming to aid the user in
360/// identifying activity related to a specific LTO invocation.
361/// Distributor specifies the path to a process to invoke to manage the backend
362/// job execution.
363/// DistributorArgs specifies a list of arguments to be applied to the
364/// distributor.
365/// RemoteCompiler specifies the path to a Clang executable to be invoked for
366/// the backend jobs.
367/// RemoteCompilerPrependArgs specifies a list of prepend arguments to be
368/// applied to the backend compilations.
369/// RemoteCompilerArgs specifies a list of arguments to be applied to the
370/// backend compilations.
371/// SaveTemps is a debugging tool that prevents temporary files created by this
372/// backend from being cleaned up.
373/// AddBuffer is used to add a pre-existing native object buffer to the link.
375 ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite,
376 bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles,
377 StringRef LinkerOutputFile, StringRef Distributor,
378 ArrayRef<StringRef> DistributorArgs, StringRef RemoteCompiler,
379 ArrayRef<StringRef> RemoteCompilerPrependArgs,
380 ArrayRef<StringRef> RemoteCompilerArgs, bool SaveTemps,
381 AddBufferFn AddBuffer);
382
383/// This ThinBackend writes individual module indexes to files, instead of
384/// running the individual backend jobs. This backend is for distributed builds
385/// where separate processes will invoke the real backends.
386///
387/// To find the path to write the index to, the backend checks if the path has a
388/// prefix of OldPrefix; if so, it replaces that prefix with NewPrefix. It then
389/// appends ".thinlto.bc" and writes the index to that path. If
390/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
391/// similar path with ".imports" appended instead.
392/// LinkedObjectsFile is an output stream to write the list of object files for
393/// the final ThinLTO linking. Can be nullptr. If LinkedObjectsFile is not
394/// nullptr and NativeObjectPrefix is not empty then it replaces the prefix of
395/// the objects with NativeObjectPrefix instead of NewPrefix. OnWrite is
396/// callback which receives module identifier and notifies LTO user that index
397/// file for the module (and optionally imports file) was created.
399 ThreadPoolStrategy Parallelism, std::string OldPrefix,
400 std::string NewPrefix, std::string NativeObjectPrefix,
401 bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile,
402 IndexWriteCallback OnWrite);
403
404/// This class implements a resolution-based interface to LLVM's LTO
405/// functionality. It supports regular LTO, parallel LTO code generation and
406/// ThinLTO. You can use it from a linker in the following way:
407/// - Set hooks and code generation options (see lto::Config struct defined in
408/// Config.h), and use the lto::Config object to create an lto::LTO object.
409/// - Create lto::InputFile objects using lto::InputFile::create(), then use
410/// the symbols() function to enumerate its symbols and compute a resolution
411/// for each symbol (see SymbolResolution below).
412/// - After the linker has visited each input file (and each regular object
413/// file) and computed a resolution for each symbol, take each lto::InputFile
414/// and pass it and an array of symbol resolutions to the add() function.
415/// - Call the getMaxTasks() function to get an upper bound on the number of
416/// native object files that LTO may add to the link.
417/// - Call the run() function. This function will use the supplied AddStream
418/// and Cache functions to add up to getMaxTasks() native object files to
419/// the link.
420class LTO {
421 friend InputFile;
422
423public:
424 /// Unified LTO modes
425 enum LTOKind {
426 /// Any LTO mode without Unified LTO. The default mode.
428
429 /// Regular LTO, with Unified LTO enabled.
431
432 /// ThinLTO, with Unified LTO enabled.
434 };
435
436 /// Create an LTO object. A default constructed LTO object has a reasonable
437 /// production configuration, but you can customize it by passing arguments to
438 /// this constructor.
439 /// FIXME: We do currently require the DiagHandler field to be set in Conf.
440 /// Until that is fixed, a Config argument is required.
441 LLVM_ABI LTO(Config Conf, ThinBackend Backend = {},
442 unsigned ParallelCodeGenParallelismLevel = 1,
443 LTOKind LTOMode = LTOK_Default);
444 LLVM_ABI virtual ~LTO();
445
446 /// Add an input file to the LTO link, using the provided symbol resolutions.
447 /// The symbol resolutions must appear in the enumeration order given by
448 /// InputFile::symbols().
449 LLVM_ABI Error add(std::unique_ptr<InputFile> Obj,
451
452 /// Set the list of functions implemented in bitcode that were not extracted
453 /// from an archive. Such functions may not be referenced, as they have
454 /// lost their opportunity to be defined.
455 LLVM_ABI void setBitcodeLibFuncs(ArrayRef<StringRef> BitcodeLibFuncs);
456
457 /// Returns an upper bound on the number of tasks that the client may expect.
458 /// This may only be called after all IR object files have been added. For a
459 /// full description of tasks see LTOBackend.h.
460 LLVM_ABI unsigned getMaxTasks() const;
461
462 /// Runs the LTO pipeline. This function calls the supplied AddStream
463 /// function to add native object files to the link.
464 ///
465 /// The Cache parameter is optional. If supplied, it will be used to cache
466 /// native object files and add them to the link.
467 ///
468 /// The client will receive at most one callback (via either AddStream or
469 /// Cache) for each task identifier.
470 LLVM_ABI Error run(AddStreamFn AddStream, FileCache Cache = {});
471
472 /// Static method that returns a list of libcall symbols that can be generated
473 /// by LTO but might not be visible from bitcode symbol table.
476
477 /// Static method that returns a list of library function symbols that can be
478 /// generated by LTO but might not be visible from bitcode symbol table.
479 /// Unlike the runtime libcalls, the linker can report to the code generator
480 /// which of these are actually available in the link, and the code generator
481 /// can then only reference that set of symbols.
483 getLibFuncSymbols(const Triple &TT, llvm::StringSaver &Saver);
484
485protected:
486 // Called at the start of run().
488
489 // Called before returning from run().
490 virtual void cleanup();
491
492private:
493 Config Conf;
494
495 struct RegularLTOState {
496 LLVM_ABI RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
497 const Config &Conf);
501 /// Record if at least one instance of the common was marked as prevailing
502 bool Prevailing = false;
503 };
504 std::map<std::string, CommonResolution> Commons;
505
506 unsigned ParallelCodeGenParallelismLevel;
507 LTOLLVMContext Ctx;
508 std::unique_ptr<Module> CombinedModule;
509 std::unique_ptr<IRMover> Mover;
510
511 // This stores the information about a regular LTO module that we have added
512 // to the link. It will either be linked immediately (for modules without
513 // summaries) or after summary-based dead stripping (for modules with
514 // summaries).
515 struct AddedModule {
516 std::unique_ptr<Module> M;
517 std::vector<GlobalValue *> Keep;
518 };
519 std::vector<AddedModule> ModsWithSummaries;
520 bool EmptyCombinedModule = true;
521 } RegularLTO;
522
523 using ModuleMapType = MapVector<StringRef, BitcodeModule>;
524
525 struct ThinLTOState {
526 LLVM_ABI ThinLTOState(ThinBackend Backend);
527
528 ThinBackend Backend;
529 ModuleSummaryIndex CombinedIndex;
530 // The full set of bitcode modules in input order.
531 ModuleMapType ModuleMap;
532 // The bitcode modules to compile, if specified by the LTO Config.
533 std::optional<ModuleMapType> ModulesToCompile;
534
535 void setPrevailingModuleForGUID(GlobalValue::GUID GUID, StringRef Module) {
536 PrevailingModuleForGUID[GUID] = Module;
537 }
538 bool isPrevailingModuleForGUID(GlobalValue::GUID GUID,
539 StringRef Module) const {
540 auto It = PrevailingModuleForGUID.find(GUID);
541 return It != PrevailingModuleForGUID.end() && It->second == Module;
542 }
543
544 private:
545 // Make this private so all accesses must go through above accessor methods
546 // to avoid inadvertently creating new entries on lookups.
547 DenseMap<GlobalValue::GUID, StringRef> PrevailingModuleForGUID;
548 } ThinLTO;
549
550 // The global resolution for a particular (mangled) symbol name. This is in
551 // particular necessary to track whether each symbol can be internalized.
552 // Because any input file may introduce a new cross-partition reference, we
553 // cannot make any final internalization decisions until all input files have
554 // been added and the client has called run(). During run() we apply
555 // internalization decisions either directly to the module (for regular LTO)
556 // or to the combined index (for ThinLTO).
557 struct GlobalResolution {
558 /// The unmangled name of the global.
559 std::string IRName;
560
561 /// Keep track if the symbol is visible outside of a module with a summary
562 /// (i.e. in either a regular object or a regular LTO module without a
563 /// summary).
564 bool VisibleOutsideSummary = false;
565
566 /// The symbol was exported dynamically, and therefore could be referenced
567 /// by a shared library not visible to the linker.
568 bool ExportDynamic = false;
569
570 bool UnnamedAddr = true;
571
572 /// True if module contains the prevailing definition.
573 bool Prevailing = false;
574
575 /// Returns true if module contains the prevailing definition and symbol is
576 /// an IR symbol. For example when module-level inline asm block is used,
577 /// symbol can be prevailing in module but have no IR name.
578 bool isPrevailingIRSymbol() const { return Prevailing && !IRName.empty(); }
579
580 /// This field keeps track of the partition number of this global. The
581 /// regular LTO object is partition 0, while each ThinLTO object has its own
582 /// partition number from 1 onwards.
583 ///
584 /// Any global that is defined or used by more than one partition, or that
585 /// is referenced externally, may not be internalized.
586 ///
587 /// Partitions generally have a one-to-one correspondence with tasks, except
588 /// that we use partition 0 for all parallel LTO code generation partitions.
589 /// Any partitioning of the combined LTO object is done internally by the
590 /// LTO backend.
591 unsigned Partition = Unknown;
592
593 /// Special partition numbers.
594 enum : unsigned {
595 /// A partition number has not yet been assigned to this global.
596 Unknown = -1u,
597
598 /// This global is either used by more than one partition or has an
599 /// external reference, and therefore cannot be internalized.
600 External = -2u,
601
602 /// The RegularLTO partition
603 RegularLTO = 0,
604 };
605 };
606
607 // GlobalResolutionSymbolSaver allocator.
608 std::unique_ptr<llvm::BumpPtrAllocator> Alloc;
609
610 // Symbol saver for global resolution map.
611 std::unique_ptr<llvm::StringSaver> GlobalResolutionSymbolSaver;
612
613 // Global mapping from mangled symbol names to resolutions.
614 // Make this an unique_ptr to guard against accessing after it has been reset
615 // (to reduce memory after we're done with it).
616 std::unique_ptr<llvm::DenseMap<StringRef, GlobalResolution>>
617 GlobalResolutions;
618
619 void releaseGlobalResolutionsMemory();
620
621 void addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
622 ArrayRef<SymbolResolution> Res, unsigned Partition,
623 bool InSummary, const Triple &TT);
624
625 // These functions take a range of symbol resolutions and consume the
626 // resolutions used by a single input module. Functions return ranges refering
627 // to the resolutions for the remaining modules in the InputFile.
628 Expected<ArrayRef<SymbolResolution>>
629 addModule(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
630 unsigned ModI, ArrayRef<SymbolResolution> Res);
631
632 Expected<std::pair<RegularLTOState::AddedModule, ArrayRef<SymbolResolution>>>
633 addRegularLTO(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
634 BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
637 bool LivenessFromIndex);
638
639 Expected<ArrayRef<SymbolResolution>>
640 addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
642
643 Error runRegularLTO(AddStreamFn AddStream);
644 Error runThinLTO(AddStreamFn AddStream, FileCache Cache,
645 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
646
647 Error checkPartiallySplit();
648
649 mutable bool CalledGetMaxTasks = false;
650
651 // LTO mode when using Unified LTO.
652 LTOKind LTOMode;
653
654 // Use Optional to distinguish false from not yet initialized.
655 std::optional<bool> EnableSplitLTOUnit;
656
657 // Identify symbols exported dynamically, and that therefore could be
658 // referenced by a shared library not visible to the linker.
659 DenseSet<GlobalValue::GUID> DynamicExportSymbols;
660
661 // Diagnostic optimization remarks file
662 LLVMRemarkFileHandle DiagnosticOutputFile;
663
664 // A dummy module to host the dummy function.
665 std::unique_ptr<Module> DummyModule;
666
667 // A dummy function created in a private module to provide a context for
668 // LTO-link optimization remarks. This is needed for ThinLTO where we
669 // may not have any IR functions available, because the optimization remark
670 // handling requires a function.
671 Function *LinkerRemarkFunction = nullptr;
672
673 // Setup optimization remarks according to the provided configuration.
674 Error setupOptimizationRemarks();
675
676 // LibFuncs that were implemented in bitcode but were not extracted
677 // from their libraries. Such functions cannot safely be called, since
678 // they have lost their opportunity to be defined.
679 SmallVector<StringRef> BitcodeLibFuncs;
680
681public:
682 /// Helper to emit an optimization remark during the LTO link when outside of
683 /// the standard optimization pass pipeline.
684 void emitRemark(OptimizationRemark &Remark);
685
686 virtual Expected<std::shared_ptr<lto::InputFile>>
687 addInput(std::unique_ptr<lto::InputFile> InputPtr) {
688 return std::shared_ptr<lto::InputFile>(InputPtr.release());
689 }
690};
691
692/// The resolution for a symbol. The linker must provide a SymbolResolution for
693/// each global symbol based on its internal resolution of that symbol.
698
699 /// The linker has chosen this definition of the symbol.
700 unsigned Prevailing : 1;
701
702 /// The definition of this symbol is unpreemptable at runtime and is known to
703 /// be in this linkage unit.
705
706 /// The definition of this symbol is visible outside of the LTO unit.
708
709 /// The symbol was exported dynamically, and therefore could be referenced
710 /// by a shared library not visible to the linker.
711 unsigned ExportDynamic : 1;
712
713 /// Linker redefined version of the symbol which appeared in -wrap or -defsym
714 /// linker option.
715 unsigned LinkerRedefined : 1;
716};
717
718} // namespace lto
719} // namespace llvm
720
721#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:213
This file defines the DenseMap class.
Provides passes for computing function attributes based on interprocedural analyses.
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Represents a module in a bitcode file.
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
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
The map maintains the list of imports.
DenseSet< ValueInfo > ExportSetTy
The set contains an entry for every global value that the module exports.
Function and variable summary information to aid decisions and implementation of importing.
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
Class to hold module path string table and global value map, and encapsulate methods for operating on...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition StringSaver.h:22
Provides information about what library functions are available for the current target.
This tells how a thread pool will be used.
Definition Threading.h:115
This class contains a raw_fd_ostream and adds a few extra features commonly needed for compiler-like ...
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
An efficient, type-erasing, non-owning reference to a callable.
LLVM_ABI BitcodeModule & getPrimaryBitcodeModule()
Definition LTO.cpp:673
MemoryBufferRef getFileBuffer() const
Definition LTO.h:214
static LLVM_ABI Expected< std::unique_ptr< InputFile > > create(MemoryBufferRef Object)
Create an InputFile.
Definition LTO.cpp:624
ArrayRef< Symbol > symbols() const
A range over the symbols in this InputFile.
Definition LTO.h:187
StringRef getCOFFLinkerOpts() const
Returns linker options specified in the input file.
Definition LTO.h:190
bool isFatLTOObject() const
Definition LTO.h:222
ArrayRef< StringRef > getDependentLibraries() const
Returns dependent library specifiers from the input file.
Definition LTO.h:193
StringRef getArchivePath() const
Definition LTO.h:234
StringRef getMemberName() const
Definition LTO.h:235
ArrayRef< std::pair< StringRef, Comdat::SelectionKind > > getComdatTable() const
Definition LTO.h:205
StringRef getTargetTriple() const
Returns the input file's target triple.
Definition LTO.h:199
LLVM_ABI StringRef getName() const
Returns the path to the InputFile.
Definition LTO.cpp:664
LLVM_ABI BitcodeModule & getSingleBitcodeModule()
Definition LTO.cpp:668
void setSerializeForDistribution(bool SFD)
Definition LTO.h:220
bool getSerializeForDistribution() const
Definition LTO.h:217
StringRef getSourceFileName() const
Returns the source file path specified at compile time.
Definition LTO.h:202
bool isThinLTO() const
Definition LTO.h:227
void fatLTOObject(bool FO)
Definition LTO.h:224
void setArchivePathAndName(StringRef Path, StringRef Name)
Definition LTO.h:230
This class implements a resolution-based interface to LLVM's LTO functionality.
Definition LTO.h:420
LLVM_ABI LTO(Config Conf, ThinBackend Backend={}, unsigned ParallelCodeGenParallelismLevel=1, LTOKind LTOMode=LTOK_Default)
Create an LTO object.
Definition LTO.cpp:688
LLVM_ABI 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:822
virtual void cleanup()
Definition LTO.cpp:705
static LLVM_ABI 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:1493
virtual Expected< std::shared_ptr< lto::InputFile > > addInput(std::unique_ptr< lto::InputFile > InputPtr)
Definition LTO.h:687
LLVM_ABI void setBitcodeLibFuncs(ArrayRef< StringRef > BitcodeLibFuncs)
Set the list of functions implemented in bitcode that were not extracted from an archive.
Definition LTO.cpp:853
virtual Error serializeInputsForDistribution()
Definition LTO.h:487
LTOKind
Unified LTO modes.
Definition LTO.h:425
@ LTOK_UnifiedRegular
Regular LTO, with Unified LTO enabled.
Definition LTO.h:430
@ LTOK_Default
Any LTO mode without Unified LTO. The default mode.
Definition LTO.h:427
@ LTOK_UnifiedThin
ThinLTO, with Unified LTO enabled.
Definition LTO.h:433
virtual LLVM_ABI ~LTO()
void emitRemark(OptimizationRemark &Remark)
Helper to emit an optimization remark during the LTO link when outside of the standard optimization p...
Definition LTO.cpp:101
LLVM_ABI unsigned getMaxTasks() const
Returns an upper bound on the number of tasks that the client may expect.
Definition LTO.cpp:1250
LLVM_ABI Error run(AddStreamFn AddStream, FileCache Cache={})
Runs the LTO pipeline.
Definition LTO.cpp:1301
static LLVM_ABI 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:1506
DefaultThreadPool BackendThreadPool
Definition LTO.h:256
const Config & Conf
Definition LTO.h:251
std::optional< Error > Err
Definition LTO.h:257
virtual bool isSensitiveToInputOrder()
Definition LTO.h:287
unsigned getThreadCount()
Definition LTO.h:286
const DenseMap< StringRef, GVSummaryMapTy > & ModuleToDefinedGVSummaries
Definition LTO.h:253
LLVM_ABI Error emitFiles(const FunctionImporter::ImportMapTy &ImportList, StringRef ModulePath, const std::string &NewModulePath) const
Definition LTO.cpp:1520
ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, lto::IndexWriteCallback OnWrite, bool ShouldEmitImportsFiles, ThreadPoolStrategy ThinLTOParallelism)
Definition LTO.h:261
virtual Error wait()
Definition LTO.h:280
ModuleSummaryIndex & CombinedIndex
Definition LTO.h:252
virtual void setup(unsigned ThinLTONumTasks, unsigned ThinLTOTaskOffset, Triple Triple)
Definition LTO.h:272
virtual ~ThinBackendProc()=default
virtual Error start(unsigned Task, BitcodeModule BM, const FunctionImporter::ImportMapTy &ImportList, const FunctionImporter::ExportSetTy &ExportList, const std::map< GlobalValue::GUID, GlobalValue::LinkageTypes > &ResolvedODR, MapVector< StringRef, BitcodeModule > &ModuleMap)=0
IndexWriteCallback OnWrite
Definition LTO.h:254
A raw_ostream that writes to a file descriptor.
An abstract base class for streams implementations that also support a pwrite operation.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
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:1875
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:1910
LLVM_ABI ThinBackend createOutOfProcessThinBackend(ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite, bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles, StringRef LinkerOutputFile, StringRef Distributor, ArrayRef< StringRef > DistributorArgs, StringRef RemoteCompiler, ArrayRef< StringRef > RemoteCompilerPrependArgs, ArrayRef< StringRef > RemoteCompilerArgs, bool SaveTemps, AddBufferFn AddBuffer)
This ThinBackend generates the index shards and then runs the individual backend jobs via an external...
Definition LTO.cpp:2793
std::function< std::unique_ptr< ThinBackendProc >( const Config &C, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, AddStreamFn AddStream, FileCache Cache, ArrayRef< StringRef > BitcodeLibFuncs)> ThinBackendFunction
This callable defines the behavior of a ThinLTO backend after the thin-link phase.
Definition LTO.h:309
LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple)
Definition LTO.cpp:1892
LLVM_ABI Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
Definition LTO.cpp:2326
std::function< void(const std::string &)> IndexWriteCallback
Definition LTO.h:244
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:1996
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:2301
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
Definition LTO.cpp:2345
llvm::SmallVector< std::string > ImportsFilesContainer
Definition LTO.h:246
This is an optimization pass for GlobalISel generic memory operations.
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"))
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"))
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
std::function< void(unsigned Task, const Twine &ModuleName, std::unique_ptr< MemoryBuffer > MB)> AddBufferFn
This type defines the callback to add a pre-existing file (e.g.
Definition Caching.h:107
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:388
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
cl::opt< bool > RemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
cl::opt< std::string > RemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
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:488
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
SingleThreadExecutor DefaultThreadPool
Definition ThreadPool.h:262
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
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)
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:137
std::function< Expected< std::unique_ptr< CachedFileStream > >( unsigned Task, const Twine &ModuleName)> AddStreamFn
This type defines the callback to add a file that is generated on the fly.
Definition Caching.h:58
LLVM_ABI void 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:606
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
This type represents a file cache system that manages caching of files.
Definition Caching.h:84
A simple container for information about the supported runtime calls.
Struct that holds a reference to a particular GUID in a global value summary.
This represents a symbol that has been read from a storage::Symbol and possibly a storage::Uncommon.
Definition IRSymtab.h:172
StringRef getName() const
Returns the mangled symbol name.
Definition IRSymtab.h:185
bool canBeOmittedFromSymbolTable() const
Definition IRSymtab.h:208
bool isUsed() const
Definition IRSymtab.h:205
StringRef getSectionName() const
Definition IRSymtab.h:234
bool isTLS() const
Definition IRSymtab.h:206
bool isWeak() const
Definition IRSymtab.h:202
bool isIndirect() const
Definition IRSymtab.h:204
bool isCommon() const
Definition IRSymtab.h:203
uint32_t getCommonAlignment() const
Definition IRSymtab.h:222
bool isExecutable() const
Definition IRSymtab.h:215
uint64_t getCommonSize() const
Definition IRSymtab.h:217
storage::Symbol S
Definition IRSymtab.h:195
int getComdatIndex() const
Returns the index into the comdat table (see Reader::getComdatTable()), or -1 if not a comdat member.
Definition IRSymtab.h:193
GlobalValue::VisibilityTypes getVisibility() const
Definition IRSymtab.h:197
bool isUndefined() const
Definition IRSymtab.h:201
StringRef getIRName() const
Returns the unmangled symbol name, or the empty string if this is not an IR symbol.
Definition IRSymtab.h:189
StringRef getCOFFWeakExternalFallback() const
COFF-specific: for weak externals, returns the name of the symbol that is used as a fallback if the w...
Definition IRSymtab.h:229
LTO configuration.
Definition Config.h:43
The purpose of this struct is to only expose the symbol information that an LTO client should need in...
Definition LTO.h:155
bool isLibcall(const TargetLibraryInfo &TLI, const RTLIB::RuntimeLibcallsInfo &Libcalls) const
Definition LTO.cpp:655
Symbol(const irsymtab::Symbol &S)
Definition LTO.h:159
A derived class of LLVMContext that initializes itself according to a given Config object.
Definition Config.h:311
std::vector< GlobalValue * > Keep
Definition LTO.h:517
std::unique_ptr< Module > M
Definition LTO.h:516
bool Prevailing
Record if at least one instance of the common was marked as prevailing.
Definition LTO.h:502
The resolution for a symbol.
Definition LTO.h:694
unsigned FinalDefinitionInLinkageUnit
The definition of this symbol is unpreemptable at runtime and is known to be in this linkage unit.
Definition LTO.h:704
unsigned ExportDynamic
The symbol was exported dynamically, and therefore could be referenced by a shared library not visibl...
Definition LTO.h:711
unsigned Prevailing
The linker has chosen this definition of the symbol.
Definition LTO.h:700
unsigned LinkerRedefined
Linker redefined version of the symbol which appeared in -wrap or -defsym linker option.
Definition LTO.h:715
unsigned VisibleToRegularObj
The definition of this symbol is visible outside of the LTO unit.
Definition LTO.h:707
This type defines the behavior following the thin-link phase during ThinLTO.
Definition LTO.h:320
bool isValid() const
Definition LTO.h:335
std::unique_ptr< ThinBackendProc > operator()(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, AddStreamFn AddStream, FileCache Cache, ArrayRef< StringRef > BitcodeLibFuncs)
Definition LTO.h:325
ThreadPoolStrategy getParallelism() const
Definition LTO.h:334
ThinBackend(ThinBackendFunction Func, ThreadPoolStrategy Parallelism)
Definition LTO.h:321