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 unsigned Task, 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 ImportsFilesList.
297 unsigned Task, StringRef ModulePath,
298 const std::string &NewModulePath,
299 StringRef SummaryPath) const;
300};
301
302/// This callable defines the behavior of a ThinLTO backend after the thin-link
303/// phase. It accepts a configuration \p C, a combined module summary index
304/// \p CombinedIndex, a map of module identifiers to global variable summaries
305/// \p ModuleToDefinedGVSummaries, a function to add output streams \p
306/// AddStream, and a file cache \p Cache. It returns a unique pointer to a
307/// ThinBackendProc, which can be used to launch backends in parallel.
308using ThinBackendFunction = std::function<std::unique_ptr<ThinBackendProc>(
309 const Config &C, ModuleSummaryIndex &CombinedIndex,
310 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
311 AddStreamFn AddStream, FileCache Cache,
312 ArrayRef<StringRef> BitcodeLibFuncs)>;
313
314/// This type defines the behavior following the thin-link phase during ThinLTO.
315/// It encapsulates a backend function and a strategy for thread pool
316/// parallelism. Clients should use one of the provided create*ThinBackend()
317/// functions to instantiate a ThinBackend. Parallelism defines the thread pool
318/// strategy to be used for processing.
321 : Func(std::move(Func)), Parallelism(std::move(Parallelism)) {}
322 ThinBackend() = default;
323
324 std::unique_ptr<ThinBackendProc> operator()(
325 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
326 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
327 AddStreamFn AddStream, FileCache Cache,
328 ArrayRef<StringRef> BitcodeLibFuncs) {
329 assert(isValid() && "Invalid backend function");
330 return Func(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
331 std::move(AddStream), std::move(Cache), BitcodeLibFuncs);
332 }
333 ThreadPoolStrategy getParallelism() const { return Parallelism; }
334 bool isValid() const { return static_cast<bool>(Func); }
335
336private:
337 ThinBackendFunction Func = nullptr;
338 ThreadPoolStrategy Parallelism;
339};
340
341/// This ThinBackend runs the individual backend jobs in-process.
342/// The default value means to use one job per hardware core (not hyper-thread).
343/// OnWrite is callback which receives module identifier and notifies LTO user
344/// that index file for the module (and optionally imports file) was created.
345/// ShouldEmitIndexFiles being true will write sharded ThinLTO index files
346/// to the same path as the input module, with suffix ".thinlto.bc"
347/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
348/// similar path with ".imports" appended instead.
350 ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite = nullptr,
351 bool ShouldEmitIndexFiles = false, bool ShouldEmitImportsFiles = false);
352
353/// This ThinBackend writes individual module indexes to files, instead of
354/// running the individual backend jobs. This backend is for distributed builds
355/// where separate processes will invoke the real backends.
356///
357/// To find the path to write the index to, the backend checks if the path has a
358/// prefix of OldPrefix; if so, it replaces that prefix with NewPrefix. It then
359/// appends ".thinlto.bc" and writes the index to that path. If
360/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
361/// similar path with ".imports" appended instead.
362/// LinkedObjectsFile is an output stream to write the list of object files for
363/// the final ThinLTO linking. Can be nullptr. If LinkedObjectsFile is not
364/// nullptr and NativeObjectPrefix is not empty then it replaces the prefix of
365/// the objects with NativeObjectPrefix instead of NewPrefix. OnWrite is
366/// callback which receives module identifier and notifies LTO user that index
367/// file for the module (and optionally imports file) was created.
369 ThreadPoolStrategy Parallelism, std::string OldPrefix,
370 std::string NewPrefix, std::string NativeObjectPrefix,
371 bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile,
372 IndexWriteCallback OnWrite);
373
374/// This class implements a resolution-based interface to LLVM's LTO
375/// functionality. It supports regular LTO, parallel LTO code generation and
376/// ThinLTO. You can use it from a linker in the following way:
377/// - Set hooks and code generation options (see lto::Config struct defined in
378/// Config.h), and use the lto::Config object to create an lto::LTO object.
379/// - Create lto::InputFile objects using lto::InputFile::create(), then use
380/// the symbols() function to enumerate its symbols and compute a resolution
381/// for each symbol (see SymbolResolution below).
382/// - After the linker has visited each input file (and each regular object
383/// file) and computed a resolution for each symbol, take each lto::InputFile
384/// and pass it and an array of symbol resolutions to the add() function.
385/// - Call the getMaxTasks() function to get an upper bound on the number of
386/// native object files that LTO may add to the link.
387/// - Call the run() function. This function will use the supplied AddStream
388/// and Cache functions to add up to getMaxTasks() native object files to
389/// the link.
390class LTO {
391 friend InputFile;
392
393public:
394 /// Unified LTO modes
395 enum LTOKind {
396 /// Any LTO mode without Unified LTO. The default mode.
398
399 /// Regular LTO, with Unified LTO enabled.
401
402 /// ThinLTO, with Unified LTO enabled.
404 };
405
406 /// Create an LTO object. A default constructed LTO object has a reasonable
407 /// production configuration, but you can customize it by passing arguments to
408 /// this constructor.
409 /// FIXME: We do currently require the DiagHandler field to be set in Conf.
410 /// Until that is fixed, a Config argument is required.
411 LLVM_ABI LTO(Config Conf, ThinBackend Backend = {},
412 unsigned ParallelCodeGenParallelismLevel = 1,
413 LTOKind LTOMode = LTOK_Default);
414 LLVM_ABI virtual ~LTO();
415
416 /// Add an input file to the LTO link, using the provided symbol resolutions.
417 /// The symbol resolutions must appear in the enumeration order given by
418 /// InputFile::symbols().
419 LLVM_ABI Error add(std::unique_ptr<InputFile> Obj,
421
422 /// Set the list of functions implemented in bitcode that were not extracted
423 /// from an archive. Such functions may not be referenced, as they have
424 /// lost their opportunity to be defined.
425 LLVM_ABI void setBitcodeLibFuncs(ArrayRef<StringRef> BitcodeLibFuncs);
426
427 /// Returns an upper bound on the number of tasks that the client may expect.
428 /// This may only be called after all IR object files have been added. For a
429 /// full description of tasks see LTOBackend.h.
430 LLVM_ABI unsigned getMaxTasks() const;
431
432 /// Runs the LTO pipeline. This function calls the supplied AddStream
433 /// function to add native object files to the link.
434 ///
435 /// The Cache parameter is optional. If supplied, it will be used to cache
436 /// native object files and add them to the link.
437 ///
438 /// The client will receive at most one callback (via either AddStream or
439 /// Cache) for each task identifier.
440 LLVM_ABI virtual Error run(AddStreamFn AddStream, FileCache Cache = {});
441
442 /// Static method that returns a list of libcall symbols that can be generated
443 /// by LTO but might not be visible from bitcode symbol table.
446
447 /// Static method that returns a list of library function symbols that can be
448 /// generated by LTO but might not be visible from bitcode symbol table.
449 /// Unlike the runtime libcalls, the linker can report to the code generator
450 /// which of these are actually available in the link, and the code generator
451 /// can then only reference that set of symbols.
453 getLibFuncSymbols(const Triple &TT, llvm::StringSaver &Saver);
454
455protected:
456 // Called before returning from run().
457 virtual void cleanup();
458
460
463 const Config &Conf);
467 /// Record if at least one instance of the common was marked as prevailing
468 bool Prevailing = false;
469 };
470 std::map<std::string, CommonResolution> Commons;
471
474 std::unique_ptr<Module> CombinedModule;
475 std::unique_ptr<IRMover> Mover;
476
477 // This stores the information about a regular LTO module that we have added
478 // to the link. It will either be linked immediately (for modules without
479 // summaries) or after summary-based dead stripping (for modules with
480 // summaries).
481 struct AddedModule {
482 std::unique_ptr<Module> M;
483 std::vector<GlobalValue *> Keep;
484 };
485 std::vector<AddedModule> ModsWithSummaries;
488
490
493
496 // The full set of bitcode modules in input order.
498 // The bitcode modules to compile, if specified by the LTO Config.
499 std::optional<ModuleMapType> ModulesToCompile;
500
502 PrevailingModuleForGUID[GUID] = Module;
503 }
505 StringRef Module) const {
506 auto It = PrevailingModuleForGUID.find(GUID);
507 return It != PrevailingModuleForGUID.end() && It->second == Module;
508 }
509
510 private:
511 // Make this private so all accesses must go through above accessor methods
512 // to avoid inadvertently creating new entries on lookups.
513 DenseMap<GlobalValue::GUID, StringRef> PrevailingModuleForGUID;
515
516private:
517 // The global resolution for a particular (mangled) symbol name. This is in
518 // particular necessary to track whether each symbol can be internalized.
519 // Because any input file may introduce a new cross-partition reference, we
520 // cannot make any final internalization decisions until all input files have
521 // been added and the client has called run(). During run() we apply
522 // internalization decisions either directly to the module (for regular LTO)
523 // or to the combined index (for ThinLTO).
524 struct GlobalResolution {
525 /// The unmangled name of the global.
526 std::string IRName;
527
528 /// Keep track if the symbol is visible outside of a module with a summary
529 /// (i.e. in either a regular object or a regular LTO module without a
530 /// summary).
531 bool VisibleOutsideSummary = false;
532
533 /// The symbol was exported dynamically, and therefore could be referenced
534 /// by a shared library not visible to the linker.
535 bool ExportDynamic = false;
536
537 bool UnnamedAddr = true;
538
539 /// True if module contains the prevailing definition.
540 bool Prevailing = false;
541
542 /// Returns true if module contains the prevailing definition and symbol is
543 /// an IR symbol. For example when module-level inline asm block is used,
544 /// symbol can be prevailing in module but have no IR name.
545 bool isPrevailingIRSymbol() const { return Prevailing && !IRName.empty(); }
546
547 /// This field keeps track of the partition number of this global. The
548 /// regular LTO object is partition 0, while each ThinLTO object has its own
549 /// partition number from 1 onwards.
550 ///
551 /// Any global that is defined or used by more than one partition, or that
552 /// is referenced externally, may not be internalized.
553 ///
554 /// Partitions generally have a one-to-one correspondence with tasks, except
555 /// that we use partition 0 for all parallel LTO code generation partitions.
556 /// Any partitioning of the combined LTO object is done internally by the
557 /// LTO backend.
558 unsigned Partition = Unknown;
559
560 /// Special partition numbers.
561 enum : unsigned {
562 /// A partition number has not yet been assigned to this global.
563 Unknown = -1u,
564
565 /// This global is either used by more than one partition or has an
566 /// external reference, and therefore cannot be internalized.
567 External = -2u,
568
569 /// The RegularLTO partition
570 RegularLTO = 0,
571 };
572 };
573
574 // GlobalResolutionSymbolSaver allocator.
575 std::unique_ptr<llvm::BumpPtrAllocator> Alloc;
576
577 // Symbol saver for global resolution map.
578 std::unique_ptr<llvm::StringSaver> GlobalResolutionSymbolSaver;
579
580 // Global mapping from mangled symbol names to resolutions.
581 // Make this an unique_ptr to guard against accessing after it has been reset
582 // (to reduce memory after we're done with it).
583 std::unique_ptr<llvm::DenseMap<StringRef, GlobalResolution>>
584 GlobalResolutions;
585
586 void releaseGlobalResolutionsMemory();
587
588 void addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
589 ArrayRef<SymbolResolution> Res, unsigned Partition,
590 bool InSummary, const Triple &TT);
591
592 // These functions take a range of symbol resolutions and consume the
593 // resolutions used by a single input module. Functions return ranges refering
594 // to the resolutions for the remaining modules in the InputFile.
595 Expected<ArrayRef<SymbolResolution>>
596 addModule(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
597 unsigned ModI, ArrayRef<SymbolResolution> Res);
598
599 Expected<std::pair<RegularLTOState::AddedModule, ArrayRef<SymbolResolution>>>
600 addRegularLTO(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
601 BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
604 bool LivenessFromIndex);
605
606 Expected<ArrayRef<SymbolResolution>>
607 addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
609
610 Error runRegularLTO(AddStreamFn AddStream);
611 Error runThinLTO(AddStreamFn AddStream, FileCache Cache,
612 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
613
614 Error checkPartiallySplit();
615
616 mutable bool CalledGetMaxTasks = false;
617
618protected:
619 // LTO mode when using Unified LTO.
621
622private:
623 // Use Optional to distinguish false from not yet initialized.
624 std::optional<bool> EnableSplitLTOUnit;
625
626 // Identify symbols exported dynamically, and that therefore could be
627 // referenced by a shared library not visible to the linker.
628 DenseSet<GlobalValue::GUID> DynamicExportSymbols;
629
630 // Diagnostic optimization remarks file
631 LLVMRemarkFileHandle DiagnosticOutputFile;
632
633 // A dummy module to host the dummy function.
634 std::unique_ptr<Module> DummyModule;
635
636 // A dummy function created in a private module to provide a context for
637 // LTO-link optimization remarks. This is needed for ThinLTO where we
638 // may not have any IR functions available, because the optimization remark
639 // handling requires a function.
640 Function *LinkerRemarkFunction = nullptr;
641
642 // Setup optimization remarks according to the provided configuration.
643 Error setupOptimizationRemarks();
644
645 // LibFuncs that were implemented in bitcode but were not extracted
646 // from their libraries. Such functions cannot safely be called, since
647 // they have lost their opportunity to be defined.
648 SmallVector<StringRef> BitcodeLibFuncs;
649
650public:
651 /// Helper to emit an optimization remark during the LTO link when outside of
652 /// the standard optimization pass pipeline.
654
656 addInput(std::unique_ptr<lto::InputFile> InputPtr) {
657 return std::shared_ptr<lto::InputFile>(InputPtr.release());
658 }
659};
660
661/// The resolution for a symbol. The linker must provide a SymbolResolution for
662/// each global symbol based on its internal resolution of that symbol.
667
668 /// The linker has chosen this definition of the symbol.
669 unsigned Prevailing : 1;
670
671 /// The definition of this symbol is unpreemptable at runtime and is known to
672 /// be in this linkage unit.
674
675 /// The definition of this symbol is visible outside of the LTO unit.
677
678 /// The symbol was exported dynamically, and therefore could be referenced
679 /// by a shared library not visible to the linker.
680 unsigned ExportDynamic : 1;
681
682 /// Linker redefined version of the symbol which appeared in -wrap or -defsym
683 /// linker option.
684 unsigned LinkerRedefined : 1;
685};
686
687} // namespace lto
688} // namespace llvm
689
690#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...
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:289
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
RAII handle that manages the lifetime of the ToolOutputFile used to output remarks.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
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
Diagnostic information for applied optimization remarks.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
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:390
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
struct llvm::lto::LTO::RegularLTOState RegularLTO
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:1492
virtual Expected< std::shared_ptr< lto::InputFile > > addInput(std::unique_ptr< lto::InputFile > InputPtr)
Definition LTO.h:656
Config Conf
Definition LTO.h:459
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
MapVector< StringRef, BitcodeModule > ModuleMapType
Definition LTO.h:489
LTOKind
Unified LTO modes.
Definition LTO.h:395
@ LTOK_UnifiedRegular
Regular LTO, with Unified LTO enabled.
Definition LTO.h:400
@ LTOK_Default
Any LTO mode without Unified LTO. The default mode.
Definition LTO.h:397
@ LTOK_UnifiedThin
ThinLTO, with Unified LTO enabled.
Definition LTO.h:403
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
struct llvm::lto::LTO::ThinLTOState ThinLTO
LTOKind LTOMode
Definition LTO.h:620
LLVM_ABI unsigned getMaxTasks() const
Returns an upper bound on the number of tasks that the client may expect.
Definition LTO.cpp:1250
virtual 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:1505
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
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
LLVM_ABI Error emitFiles(const FunctionImporter::ImportMapTy &ImportList, unsigned Task, StringRef ModulePath, const std::string &NewModulePath) const
Definition LTO.cpp:1519
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:1880
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:1915
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:308
LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple)
Definition LTO.cpp:1897
LLVM_ABI Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
Definition LTO.cpp:2353
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:2022
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:2328
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
Definition LTO.cpp:2372
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,...
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"))
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:1916
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:861
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:329
std::vector< GlobalValue * > Keep
Definition LTO.h:483
std::unique_ptr< Module > M
Definition LTO.h:482
bool Prevailing
Record if at least one instance of the common was marked as prevailing.
Definition LTO.h:468
std::vector< AddedModule > ModsWithSummaries
Definition LTO.h:485
std::unique_ptr< IRMover > Mover
Definition LTO.h:475
unsigned ParallelCodeGenParallelismLevel
Definition LTO.h:472
std::map< std::string, CommonResolution > Commons
Definition LTO.h:470
std::unique_ptr< Module > CombinedModule
Definition LTO.h:474
LLVM_ABI RegularLTOState(unsigned ParallelCodeGenParallelismLevel, const Config &Conf)
Definition LTO.cpp:675
ModuleMapType ModuleMap
Definition LTO.h:497
LLVM_ABI ThinLTOState(ThinBackend Backend)
Definition LTO.cpp:681
bool isPrevailingModuleForGUID(GlobalValue::GUID GUID, StringRef Module) const
Definition LTO.h:504
void setPrevailingModuleForGUID(GlobalValue::GUID GUID, StringRef Module)
Definition LTO.h:501
std::optional< ModuleMapType > ModulesToCompile
Definition LTO.h:499
ModuleSummaryIndex CombinedIndex
Definition LTO.h:495
The resolution for a symbol.
Definition LTO.h:663
unsigned FinalDefinitionInLinkageUnit
The definition of this symbol is unpreemptable at runtime and is known to be in this linkage unit.
Definition LTO.h:673
unsigned ExportDynamic
The symbol was exported dynamically, and therefore could be referenced by a shared library not visibl...
Definition LTO.h:680
unsigned Prevailing
The linker has chosen this definition of the symbol.
Definition LTO.h:669
unsigned LinkerRedefined
Linker redefined version of the symbol which appeared in -wrap or -defsym linker option.
Definition LTO.h:684
unsigned VisibleToRegularObj
The definition of this symbol is visible outside of the LTO unit.
Definition LTO.h:676
This type defines the behavior following the thin-link phase during ThinLTO.
Definition LTO.h:319
bool isValid() const
Definition LTO.h:334
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:324
ThreadPoolStrategy getParallelism() const
Definition LTO.h:333
ThinBackend(ThinBackendFunction Func, ThreadPoolStrategy Parallelism)
Definition LTO.h:320