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
70/// Computes a unique hash for the Module considering the current list of
71/// export/import and other global analysis results.
73 const lto::Config &Conf, const ModuleSummaryIndex &Index,
74 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
75 const FunctionImporter::ExportSetTy &ExportList,
76 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
77 const GVSummaryMapTy &DefinedGlobals,
78 const DenseSet<GlobalValue::GUID> &CfiFunctionDefs = {},
79 const DenseSet<GlobalValue::GUID> &CfiFunctionDecls = {});
80
81/// Recomputes the LTO cache key for a given key with an extra identifier.
82LLVM_ABI std::string recomputeLTOCacheKey(const std::string &Key,
83 StringRef ExtraID);
84
85namespace lto {
86
87LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple);
88
89/// Given the original \p Path to an output file, replace any path
90/// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
91/// resulting directory if it does not yet exist.
92LLVM_ABI std::string getThinLTOOutputFile(StringRef Path, StringRef OldPrefix,
93 StringRef NewPrefix);
94
95/// Setup optimization remarks.
96LLVM_ABI Expected<LLVMRemarkFileHandle> setupLLVMOptimizationRemarks(
97 LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
98 StringRef RemarksFormat, bool RemarksWithHotness,
99 std::optional<uint64_t> RemarksHotnessThreshold = 0, int Count = -1);
100
101/// Setups the output file for saving statistics.
102LLVM_ABI Expected<std::unique_ptr<ToolOutputFile>>
103setupStatsFile(StringRef StatsFilename);
104
105/// Produces a container ordering for optimal multi-threaded processing. Returns
106/// ordered indices to elements in the input array.
108
109class LTO;
110struct SymbolResolution;
111
112/// An input file. This is a symbol table wrapper that only exposes the
113/// information that an LTO client should need in order to do symbol resolution.
114class InputFile {
115public:
116 struct Symbol;
117
118private:
119 // FIXME: Remove LTO class friendship once we have bitcode symbol tables.
120 friend LTO;
121 InputFile() = default;
122
123 std::vector<BitcodeModule> Mods;
125 std::vector<Symbol> Symbols;
126
127 // [begin, end) for each module
128 std::vector<std::pair<size_t, size_t>> ModuleSymIndices;
129
130 StringRef TargetTriple, SourceFileName, COFFLinkerOpts;
131 std::vector<StringRef> DependentLibraries;
132 std::vector<std::pair<StringRef, Comdat::SelectionKind>> ComdatTable;
133
134 MemoryBufferRef MbRef;
135 bool IsFatLTOObject = false;
136 // For distributed compilation, each input must exist as an individual bitcode
137 // file on disk and be identified by its ModuleID. Archive members and FatLTO
138 // objects violate this. So, in these cases we flag that the bitcode must be
139 // written out to a new standalone file.
140 bool SerializeForDistribution = false;
141 bool IsThinLTO = false;
142 StringRef ArchivePath;
143 StringRef MemberName;
144
145public:
147
148 /// Create an InputFile.
150 create(MemoryBufferRef Object);
151
152 /// The purpose of this struct is to only expose the symbol information that
153 /// an LTO client should need in order to do symbol resolution.
155 friend LTO;
156
157 public:
159
176
177 // Returns whether this symbol is a library call that LTO code generation
178 // may emit references to. Such symbols must be considered external, as
179 // removing them or modifying their interfaces would invalidate the code
180 // generator's knowledge about them.
181 bool isLibcall(const RTLIB::RuntimeLibcallsInfo &Libcalls) const;
182 };
183
184 /// A range over the symbols in this InputFile.
185 ArrayRef<Symbol> symbols() const { return Symbols; }
186
187 /// Returns linker options specified in the input file.
188 StringRef getCOFFLinkerOpts() const { return COFFLinkerOpts; }
189
190 /// Returns dependent library specifiers from the input file.
191 ArrayRef<StringRef> getDependentLibraries() const { return DependentLibraries; }
192
193 /// Returns the path to the InputFile.
194 LLVM_ABI StringRef getName() const;
195
196 /// Returns the input file's target triple.
197 StringRef getTargetTriple() const { return TargetTriple; }
198
199 /// Returns the source file path specified at compile time.
200 StringRef getSourceFileName() const { return SourceFileName; }
201
202 // Returns a table with all the comdats used by this file.
206
207 // Returns the only BitcodeModule from InputFile.
209 // Returns the primary BitcodeModule from InputFile.
211 // Returns the memory buffer reference for this input file.
212 MemoryBufferRef getFileBuffer() const { return MbRef; }
213 // Returns true if this input should be serialized to disk for distribution.
214 // See the comment on SerializeForDistribution for details.
215 bool getSerializeForDistribution() const { return SerializeForDistribution; }
216 // Mark whether this input should be serialized to disk for distribution.
217 // See the comment on SerializeForDistribution for details.
218 void setSerializeForDistribution(bool SFD) { SerializeForDistribution = SFD; }
219 // Returns true if this bitcode came from a FatLTO object.
220 bool isFatLTOObject() const { return IsFatLTOObject; }
221 // Mark this bitcode as coming from a FatLTO object.
222 void fatLTOObject(bool FO) { IsFatLTOObject = FO; }
223
224 // Returns true if bitcode is ThinLTO.
225 bool isThinLTO() const { return IsThinLTO; }
226
227 // Store an archive path and a member name.
229 ArchivePath = Path;
230 MemberName = Name;
231 }
232 StringRef getArchivePath() const { return ArchivePath; }
233 StringRef getMemberName() const { return MemberName; }
234
235private:
236 ArrayRef<Symbol> module_symbols(unsigned I) const {
237 const auto &Indices = ModuleSymIndices[I];
238 return {Symbols.data() + Indices.first, Symbols.data() + Indices.second};
239 }
240};
241
242using IndexWriteCallback = std::function<void(const std::string &)>;
243
245
246/// This class defines the interface to the ThinLTO backend.
248protected:
249 const Config &Conf;
255 std::optional<Error> Err;
256 std::mutex ErrMu;
257
258public:
268
269 virtual ~ThinBackendProc() = default;
270 virtual void setup(unsigned ThinLTONumTasks, unsigned ThinLTOTaskOffset,
271 Triple Triple) {}
272 virtual Error start(
273 unsigned Task, BitcodeModule BM,
274 const FunctionImporter::ImportMapTy &ImportList,
275 const FunctionImporter::ExportSetTy &ExportList,
276 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
278 virtual Error wait() {
279 BackendThreadPool.wait();
280 if (Err)
281 return std::move(*Err);
282 return Error::success();
283 }
284 unsigned getThreadCount() { return BackendThreadPool.getMaxConcurrency(); }
285 virtual bool isSensitiveToInputOrder() { return false; }
286
287 // Write sharded indices and (optionally) imports to disk
289 StringRef ModulePath,
290 const std::string &NewModulePath) const;
291
292 // Write sharded indices to SummaryPath, (optionally) imports to disk, and
293 // (optionally) record imports in ImportsFiles.
295 const FunctionImporter::ImportMapTy &ImportList, StringRef ModulePath,
296 const std::string &NewModulePath, StringRef SummaryPath,
297 std::optional<std::reference_wrapper<ImportsFilesContainer>> ImportsFiles)
298 const;
299};
300
301/// This callable defines the behavior of a ThinLTO backend after the thin-link
302/// phase. It accepts a configuration \p C, a combined module summary index
303/// \p CombinedIndex, a map of module identifiers to global variable summaries
304/// \p ModuleToDefinedGVSummaries, a function to add output streams \p
305/// AddStream, and a file cache \p Cache. It returns a unique pointer to a
306/// ThinBackendProc, which can be used to launch backends in parallel.
307using ThinBackendFunction = std::function<std::unique_ptr<ThinBackendProc>(
308 const Config &C, ModuleSummaryIndex &CombinedIndex,
309 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
310 AddStreamFn AddStream, FileCache Cache)>;
311
312/// This type defines the behavior following the thin-link phase during ThinLTO.
313/// It encapsulates a backend function and a strategy for thread pool
314/// parallelism. Clients should use one of the provided create*ThinBackend()
315/// functions to instantiate a ThinBackend. Parallelism defines the thread pool
316/// strategy to be used for processing.
319 : Func(std::move(Func)), Parallelism(std::move(Parallelism)) {}
320 ThinBackend() = default;
321
322 std::unique_ptr<ThinBackendProc> operator()(
323 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
324 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
325 AddStreamFn AddStream, FileCache Cache) {
326 assert(isValid() && "Invalid backend function");
327 return Func(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
328 std::move(AddStream), std::move(Cache));
329 }
330 ThreadPoolStrategy getParallelism() const { return Parallelism; }
331 bool isValid() const { return static_cast<bool>(Func); }
332
333private:
334 ThinBackendFunction Func = nullptr;
335 ThreadPoolStrategy Parallelism;
336};
337
338/// This ThinBackend runs the individual backend jobs in-process.
339/// The default value means to use one job per hardware core (not hyper-thread).
340/// OnWrite is callback which receives module identifier and notifies LTO user
341/// that index file for the module (and optionally imports file) was created.
342/// ShouldEmitIndexFiles being true will write sharded ThinLTO index files
343/// to the same path as the input module, with suffix ".thinlto.bc"
344/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
345/// similar path with ".imports" appended instead.
347 ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite = nullptr,
348 bool ShouldEmitIndexFiles = false, bool ShouldEmitImportsFiles = false);
349
350/// This ThinBackend generates the index shards and then runs the individual
351/// backend jobs via an external process. It takes the same parameters as the
352/// InProcessThinBackend; however, these parameters only control the behavior
353/// when generating the index files for the modules. Additionally:
354/// LinkerOutputFile is a string that should identify this LTO invocation in
355/// the context of a wider build. It's used for naming to aid the user in
356/// identifying activity related to a specific LTO invocation.
357/// Distributor specifies the path to a process to invoke to manage the backend
358/// job execution.
359/// DistributorArgs specifies a list of arguments to be applied to the
360/// distributor.
361/// RemoteCompiler specifies the path to a Clang executable to be invoked for
362/// the backend jobs.
363/// RemoteCompilerPrependArgs specifies a list of prepend arguments to be
364/// applied to the backend compilations.
365/// RemoteCompilerArgs specifies a list of arguments to be applied to the
366/// backend compilations.
367/// SaveTemps is a debugging tool that prevents temporary files created by this
368/// backend from being cleaned up.
370 ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite,
371 bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles,
372 StringRef LinkerOutputFile, StringRef Distributor,
373 ArrayRef<StringRef> DistributorArgs, StringRef RemoteCompiler,
374 ArrayRef<StringRef> RemoteCompilerPrependArgs,
375 ArrayRef<StringRef> RemoteCompilerArgs, bool SaveTemps);
376
377/// This ThinBackend writes individual module indexes to files, instead of
378/// running the individual backend jobs. This backend is for distributed builds
379/// where separate processes will invoke the real backends.
380///
381/// To find the path to write the index to, the backend checks if the path has a
382/// prefix of OldPrefix; if so, it replaces that prefix with NewPrefix. It then
383/// appends ".thinlto.bc" and writes the index to that path. If
384/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
385/// similar path with ".imports" appended instead.
386/// LinkedObjectsFile is an output stream to write the list of object files for
387/// the final ThinLTO linking. Can be nullptr. If LinkedObjectsFile is not
388/// nullptr and NativeObjectPrefix is not empty then it replaces the prefix of
389/// the objects with NativeObjectPrefix instead of NewPrefix. OnWrite is
390/// callback which receives module identifier and notifies LTO user that index
391/// file for the module (and optionally imports file) was created.
393 ThreadPoolStrategy Parallelism, std::string OldPrefix,
394 std::string NewPrefix, std::string NativeObjectPrefix,
395 bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile,
396 IndexWriteCallback OnWrite);
397
398/// This class implements a resolution-based interface to LLVM's LTO
399/// functionality. It supports regular LTO, parallel LTO code generation and
400/// ThinLTO. You can use it from a linker in the following way:
401/// - Set hooks and code generation options (see lto::Config struct defined in
402/// Config.h), and use the lto::Config object to create an lto::LTO object.
403/// - Create lto::InputFile objects using lto::InputFile::create(), then use
404/// the symbols() function to enumerate its symbols and compute a resolution
405/// for each symbol (see SymbolResolution below).
406/// - After the linker has visited each input file (and each regular object
407/// file) and computed a resolution for each symbol, take each lto::InputFile
408/// and pass it and an array of symbol resolutions to the add() function.
409/// - Call the getMaxTasks() function to get an upper bound on the number of
410/// native object files that LTO may add to the link.
411/// - Call the run() function. This function will use the supplied AddStream
412/// and Cache functions to add up to getMaxTasks() native object files to
413/// the link.
414class LTO {
415 friend InputFile;
416
417public:
418 /// Unified LTO modes
419 enum LTOKind {
420 /// Any LTO mode without Unified LTO. The default mode.
422
423 /// Regular LTO, with Unified LTO enabled.
425
426 /// ThinLTO, with Unified LTO enabled.
428 };
429
430 /// Create an LTO object. A default constructed LTO object has a reasonable
431 /// production configuration, but you can customize it by passing arguments to
432 /// this constructor.
433 /// FIXME: We do currently require the DiagHandler field to be set in Conf.
434 /// Until that is fixed, a Config argument is required.
435 LLVM_ABI LTO(Config Conf, ThinBackend Backend = {},
436 unsigned ParallelCodeGenParallelismLevel = 1,
437 LTOKind LTOMode = LTOK_Default);
438 LLVM_ABI virtual ~LTO();
439
440 /// Add an input file to the LTO link, using the provided symbol resolutions.
441 /// The symbol resolutions must appear in the enumeration order given by
442 /// InputFile::symbols().
443 LLVM_ABI Error add(std::unique_ptr<InputFile> Obj,
445
446 /// Returns an upper bound on the number of tasks that the client may expect.
447 /// This may only be called after all IR object files have been added. For a
448 /// full description of tasks see LTOBackend.h.
449 LLVM_ABI unsigned getMaxTasks() const;
450
451 /// Runs the LTO pipeline. This function calls the supplied AddStream
452 /// function to add native object files to the link.
453 ///
454 /// The Cache parameter is optional. If supplied, it will be used to cache
455 /// native object files and add them to the link.
456 ///
457 /// The client will receive at most one callback (via either AddStream or
458 /// Cache) for each task identifier.
459 LLVM_ABI Error run(AddStreamFn AddStream, FileCache Cache = {});
460
461 /// Static method that returns a list of libcall symbols that can be generated
462 /// by LTO but might not be visible from bitcode symbol table.
465
466protected:
467 // Called at the start of run().
469
470 // Called before returning from run().
471 virtual void cleanup() {}
472
473private:
474 Config Conf;
475
476 struct RegularLTOState {
477 LLVM_ABI RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
478 const Config &Conf);
482 /// Record if at least one instance of the common was marked as prevailing
483 bool Prevailing = false;
484 };
485 std::map<std::string, CommonResolution> Commons;
486
487 unsigned ParallelCodeGenParallelismLevel;
488 LTOLLVMContext Ctx;
489 std::unique_ptr<Module> CombinedModule;
490 std::unique_ptr<IRMover> Mover;
491
492 // This stores the information about a regular LTO module that we have added
493 // to the link. It will either be linked immediately (for modules without
494 // summaries) or after summary-based dead stripping (for modules with
495 // summaries).
496 struct AddedModule {
497 std::unique_ptr<Module> M;
498 std::vector<GlobalValue *> Keep;
499 };
500 std::vector<AddedModule> ModsWithSummaries;
501 bool EmptyCombinedModule = true;
502 } RegularLTO;
503
504 using ModuleMapType = MapVector<StringRef, BitcodeModule>;
505
506 struct ThinLTOState {
507 LLVM_ABI ThinLTOState(ThinBackend Backend);
508
509 ThinBackend Backend;
510 ModuleSummaryIndex CombinedIndex;
511 // The full set of bitcode modules in input order.
512 ModuleMapType ModuleMap;
513 // The bitcode modules to compile, if specified by the LTO Config.
514 std::optional<ModuleMapType> ModulesToCompile;
515
516 void setPrevailingModuleForGUID(GlobalValue::GUID GUID, StringRef Module) {
517 PrevailingModuleForGUID[GUID] = Module;
518 }
519 bool isPrevailingModuleForGUID(GlobalValue::GUID GUID,
520 StringRef Module) const {
521 auto It = PrevailingModuleForGUID.find(GUID);
522 return It != PrevailingModuleForGUID.end() && It->second == Module;
523 }
524
525 private:
526 // Make this private so all accesses must go through above accessor methods
527 // to avoid inadvertently creating new entries on lookups.
528 DenseMap<GlobalValue::GUID, StringRef> PrevailingModuleForGUID;
529 } ThinLTO;
530
531 // The global resolution for a particular (mangled) symbol name. This is in
532 // particular necessary to track whether each symbol can be internalized.
533 // Because any input file may introduce a new cross-partition reference, we
534 // cannot make any final internalization decisions until all input files have
535 // been added and the client has called run(). During run() we apply
536 // internalization decisions either directly to the module (for regular LTO)
537 // or to the combined index (for ThinLTO).
538 struct GlobalResolution {
539 /// The unmangled name of the global.
540 std::string IRName;
541
542 /// Keep track if the symbol is visible outside of a module with a summary
543 /// (i.e. in either a regular object or a regular LTO module without a
544 /// summary).
545 bool VisibleOutsideSummary = false;
546
547 /// The symbol was exported dynamically, and therefore could be referenced
548 /// by a shared library not visible to the linker.
549 bool ExportDynamic = false;
550
551 bool UnnamedAddr = true;
552
553 /// True if module contains the prevailing definition.
554 bool Prevailing = false;
555
556 /// Returns true if module contains the prevailing definition and symbol is
557 /// an IR symbol. For example when module-level inline asm block is used,
558 /// symbol can be prevailing in module but have no IR name.
559 bool isPrevailingIRSymbol() const { return Prevailing && !IRName.empty(); }
560
561 /// This field keeps track of the partition number of this global. The
562 /// regular LTO object is partition 0, while each ThinLTO object has its own
563 /// partition number from 1 onwards.
564 ///
565 /// Any global that is defined or used by more than one partition, or that
566 /// is referenced externally, may not be internalized.
567 ///
568 /// Partitions generally have a one-to-one correspondence with tasks, except
569 /// that we use partition 0 for all parallel LTO code generation partitions.
570 /// Any partitioning of the combined LTO object is done internally by the
571 /// LTO backend.
572 unsigned Partition = Unknown;
573
574 /// Special partition numbers.
575 enum : unsigned {
576 /// A partition number has not yet been assigned to this global.
577 Unknown = -1u,
578
579 /// This global is either used by more than one partition or has an
580 /// external reference, and therefore cannot be internalized.
581 External = -2u,
582
583 /// The RegularLTO partition
584 RegularLTO = 0,
585 };
586 };
587
588 // GlobalResolutionSymbolSaver allocator.
589 std::unique_ptr<llvm::BumpPtrAllocator> Alloc;
590
591 // Symbol saver for global resolution map.
592 std::unique_ptr<llvm::StringSaver> GlobalResolutionSymbolSaver;
593
594 // Global mapping from mangled symbol names to resolutions.
595 // Make this an unique_ptr to guard against accessing after it has been reset
596 // (to reduce memory after we're done with it).
597 std::unique_ptr<llvm::DenseMap<StringRef, GlobalResolution>>
598 GlobalResolutions;
599
600 void releaseGlobalResolutionsMemory();
601
602 void addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
603 ArrayRef<SymbolResolution> Res, unsigned Partition,
604 bool InSummary, const Triple &TT);
605
606 // These functions take a range of symbol resolutions and consume the
607 // resolutions used by a single input module. Functions return ranges refering
608 // to the resolutions for the remaining modules in the InputFile.
609 Expected<ArrayRef<SymbolResolution>>
610 addModule(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
611 unsigned ModI, ArrayRef<SymbolResolution> Res);
612
613 Expected<std::pair<RegularLTOState::AddedModule, ArrayRef<SymbolResolution>>>
614 addRegularLTO(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
615 BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
618 bool LivenessFromIndex);
619
620 Expected<ArrayRef<SymbolResolution>>
621 addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
623
624 Error runRegularLTO(AddStreamFn AddStream);
625 Error runThinLTO(AddStreamFn AddStream, FileCache Cache,
626 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
627
628 Error checkPartiallySplit();
629
630 mutable bool CalledGetMaxTasks = false;
631
632 // LTO mode when using Unified LTO.
633 LTOKind LTOMode;
634
635 // Use Optional to distinguish false from not yet initialized.
636 std::optional<bool> EnableSplitLTOUnit;
637
638 // Identify symbols exported dynamically, and that therefore could be
639 // referenced by a shared library not visible to the linker.
640 DenseSet<GlobalValue::GUID> DynamicExportSymbols;
641
642 // Diagnostic optimization remarks file
643 LLVMRemarkFileHandle DiagnosticOutputFile;
644
645public:
646 virtual Expected<std::shared_ptr<lto::InputFile>>
647 addInput(std::unique_ptr<lto::InputFile> InputPtr) {
648 return std::shared_ptr<lto::InputFile>(InputPtr.release());
649 }
650};
651
652/// The resolution for a symbol. The linker must provide a SymbolResolution for
653/// each global symbol based on its internal resolution of that symbol.
658
659 /// The linker has chosen this definition of the symbol.
660 unsigned Prevailing : 1;
661
662 /// The definition of this symbol is unpreemptable at runtime and is known to
663 /// be in this linkage unit.
665
666 /// The definition of this symbol is visible outside of the LTO unit.
668
669 /// The symbol was exported dynamically, and therefore could be referenced
670 /// by a shared library not visible to the linker.
671 unsigned ExportDynamic : 1;
672
673 /// Linker redefined version of the symbol which appeared in -wrap or -defsym
674 /// linker option.
675 unsigned LinkerRedefined : 1;
676};
677
678} // namespace lto
679} // namespace llvm
680
681#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
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:614
MemoryBufferRef getFileBuffer() const
Definition LTO.h:212
static LLVM_ABI Expected< std::unique_ptr< InputFile > > create(MemoryBufferRef Object)
Create an InputFile.
Definition LTO.cpp:569
ArrayRef< Symbol > symbols() const
A range over the symbols in this InputFile.
Definition LTO.h:185
StringRef getCOFFLinkerOpts() const
Returns linker options specified in the input file.
Definition LTO.h:188
bool isFatLTOObject() const
Definition LTO.h:220
ArrayRef< StringRef > getDependentLibraries() const
Returns dependent library specifiers from the input file.
Definition LTO.h:191
StringRef getArchivePath() const
Definition LTO.h:232
StringRef getMemberName() const
Definition LTO.h:233
ArrayRef< std::pair< StringRef, Comdat::SelectionKind > > getComdatTable() const
Definition LTO.h:203
StringRef getTargetTriple() const
Returns the input file's target triple.
Definition LTO.h:197
LLVM_ABI StringRef getName() const
Returns the path to the InputFile.
Definition LTO.cpp:605
LLVM_ABI BitcodeModule & getSingleBitcodeModule()
Definition LTO.cpp:609
void setSerializeForDistribution(bool SFD)
Definition LTO.h:218
bool getSerializeForDistribution() const
Definition LTO.h:215
StringRef getSourceFileName() const
Returns the source file path specified at compile time.
Definition LTO.h:200
bool isThinLTO() const
Definition LTO.h:225
void fatLTOObject(bool FO)
Definition LTO.h:222
void setArchivePathAndName(StringRef Path, StringRef Name)
Definition LTO.h:228
This class implements a resolution-based interface to LLVM's LTO functionality.
Definition LTO.h:414
LLVM_ABI LTO(Config Conf, ThinBackend Backend={}, unsigned ParallelCodeGenParallelismLevel=1, LTOKind LTOMode=LTOK_Default)
Create an LTO object.
Definition LTO.cpp:629
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:755
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:1426
virtual Error handleArchiveInputs()
Definition LTO.h:468
virtual Expected< std::shared_ptr< lto::InputFile > > addInput(std::unique_ptr< lto::InputFile > InputPtr)
Definition LTO.h:647
LTOKind
Unified LTO modes.
Definition LTO.h:419
@ LTOK_UnifiedRegular
Regular LTO, with Unified LTO enabled.
Definition LTO.h:424
@ LTOK_Default
Any LTO mode without Unified LTO. The default mode.
Definition LTO.h:421
@ LTOK_UnifiedThin
ThinLTO, with Unified LTO enabled.
Definition LTO.h:427
virtual LLVM_ABI ~LTO()
virtual void cleanup()
Definition LTO.h:471
LLVM_ABI unsigned getMaxTasks() const
Returns an upper bound on the number of tasks that the client may expect.
Definition LTO.cpp:1178
LLVM_ABI Error run(AddStreamFn AddStream, FileCache Cache={})
Runs the LTO pipeline.
Definition LTO.cpp:1229
DefaultThreadPool BackendThreadPool
Definition LTO.h:254
const Config & Conf
Definition LTO.h:249
std::optional< Error > Err
Definition LTO.h:255
virtual bool isSensitiveToInputOrder()
Definition LTO.h:285
unsigned getThreadCount()
Definition LTO.h:284
const DenseMap< StringRef, GVSummaryMapTy > & ModuleToDefinedGVSummaries
Definition LTO.h:251
LLVM_ABI Error emitFiles(const FunctionImporter::ImportMapTy &ImportList, StringRef ModulePath, const std::string &NewModulePath) const
Definition LTO.cpp:1439
ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, lto::IndexWriteCallback OnWrite, bool ShouldEmitImportsFiles, ThreadPoolStrategy ThinLTOParallelism)
Definition LTO.h:259
virtual Error wait()
Definition LTO.h:278
ModuleSummaryIndex & CombinedIndex
Definition LTO.h:250
virtual void setup(unsigned ThinLTONumTasks, unsigned ThinLTOTaskOffset, Triple Triple)
Definition LTO.h:270
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:252
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:1789
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:1823
LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple)
Definition LTO.cpp:1805
LLVM_ABI Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
Definition LTO.cpp:2203
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)
This ThinBackend generates the index shards and then runs the individual backend jobs via an external...
Definition LTO.cpp:2671
std::function< void(const std::string &)> IndexWriteCallback
Definition LTO.h:242
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:1909
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:2178
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
Definition LTO.cpp:2222
llvm::SmallVector< std::string > ImportsFilesContainer
Definition LTO.h:244
std::function< std::unique_ptr< ThinBackendProc >( const Config &C, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, AddStreamFn AddStream, FileCache Cache)> ThinBackendFunction
This callable defines the behavior of a ThinLTO backend after the thin-link phase.
Definition LTO.h:307
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
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,...
LLVM_ABI void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
Definition LTO.cpp:554
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:355
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"))
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:449
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:1915
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:104
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
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:42
The purpose of this struct is to only expose the symbol information that an LTO client should need in...
Definition LTO.h:154
bool isLibcall(const RTLIB::RuntimeLibcallsInfo &Libcalls) const
Definition LTO.cpp:600
Symbol(const irsymtab::Symbol &S)
Definition LTO.h:158
A derived class of LLVMContext that initializes itself according to a given Config object.
Definition Config.h:305
std::vector< GlobalValue * > Keep
Definition LTO.h:498
std::unique_ptr< Module > M
Definition LTO.h:497
bool Prevailing
Record if at least one instance of the common was marked as prevailing.
Definition LTO.h:483
The resolution for a symbol.
Definition LTO.h:654
unsigned FinalDefinitionInLinkageUnit
The definition of this symbol is unpreemptable at runtime and is known to be in this linkage unit.
Definition LTO.h:664
unsigned ExportDynamic
The symbol was exported dynamically, and therefore could be referenced by a shared library not visibl...
Definition LTO.h:671
unsigned Prevailing
The linker has chosen this definition of the symbol.
Definition LTO.h:660
unsigned LinkerRedefined
Linker redefined version of the symbol which appeared in -wrap or -defsym linker option.
Definition LTO.h:675
unsigned VisibleToRegularObj
The definition of this symbol is visible outside of the LTO unit.
Definition LTO.h:667
This type defines the behavior following the thin-link phase during ThinLTO.
Definition LTO.h:317
std::unique_ptr< ThinBackendProc > operator()(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, AddStreamFn AddStream, FileCache Cache)
Definition LTO.h:322
bool isValid() const
Definition LTO.h:331
ThreadPoolStrategy getParallelism() const
Definition LTO.h:330
ThinBackend(ThinBackendFunction Func, ThreadPoolStrategy Parallelism)
Definition LTO.h:318