LLVM 24.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
138 // bitcode file on disk identified by its ModuleID. For archive members and
139 // FatLTO objects, the input bitcode is a sub-section of a larger file. In
140 // these cases we flag that the bitcode must be written to a temporary
141 // standalone file. Effectively, extracted from its container.
142 bool ExtractForDistribution = false;
143 bool IsThinLTO = false;
144 StringRef ArchivePath;
145 StringRef MemberName;
146
147public:
149
150 /// Create an InputFile.
152 create(MemoryBufferRef Object);
153
154 /// The purpose of this struct is to only expose the symbol information that
155 /// an LTO client should need in order to do symbol resolution.
157 friend LTO;
158
159 public:
161
178
179 // Returns whether this symbol is a library call that LTO code generation
180 // may emit references to. Such symbols must be considered external, as
181 // removing them or modifying their interfaces would invalidate the code
182 // generator's knowledge about them.
183 LLVM_ABI bool isLibcall(const TargetLibraryInfo &TLI,
184 const RTLIB::RuntimeLibcallsInfo &Libcalls) const;
185 };
186
187 /// A range over the symbols in this InputFile.
188 ArrayRef<Symbol> symbols() const { return Symbols; }
189
190 /// Returns linker options specified in the input file.
191 StringRef getCOFFLinkerOpts() const { return COFFLinkerOpts; }
192
193 /// Returns dependent library specifiers from the input file.
194 ArrayRef<StringRef> getDependentLibraries() const { return DependentLibraries; }
195
196 /// Returns the path to the InputFile.
197 LLVM_ABI StringRef getName() const;
198
199 /// Returns the input file's target triple.
200 StringRef getTargetTriple() const { return TargetTriple; }
201
202 /// Returns the source file path specified at compile time.
203 StringRef getSourceFileName() const { return SourceFileName; }
204
205 // Returns a table with all the comdats used by this file.
209
210 // Returns the only BitcodeModule from InputFile.
212 // Returns the primary BitcodeModule from InputFile.
214 // Returns the memory buffer reference for this input file.
215 MemoryBufferRef getFileBuffer() const { return MbRef; }
216 // Returns true if this input should be extracted to disk for distribution.
217 // See the comment on ExtractForDistribution for details.
218 bool getExtractForDistribution() const { return ExtractForDistribution; }
219 // Mark whether this input should be extracted to disk for distribution.
220 // See the comment on ExtractForDistribution for details.
221 void setExtractForDistribution(bool EFD) { ExtractForDistribution = EFD; }
222 // Returns true if this bitcode came from a FatLTO object.
223 bool isFatLTOObject() const { return IsFatLTOObject; }
224 // Mark this bitcode as coming from a FatLTO object.
225 void fatLTOObject(bool FO) { IsFatLTOObject = FO; }
226
227 // Returns true if bitcode is ThinLTO.
228 bool isThinLTO() const { return IsThinLTO; }
229
230 // Store an archive path and a member name.
232 ArchivePath = Path;
233 MemberName = Name;
234 }
235 StringRef getArchivePath() const { return ArchivePath; }
236 StringRef getMemberName() const { return MemberName; }
237
238private:
239 ArrayRef<Symbol> module_symbols(unsigned I) const {
240 const auto &Indices = ModuleSymIndices[I];
241 return {Symbols.data() + Indices.first, Symbols.data() + Indices.second};
242 }
243};
244
245using IndexWriteCallback = std::function<void(const std::string &)>;
246
248
249/// This class defines the interface to the ThinLTO backend.
251protected:
252 const Config &Conf;
258 std::optional<Error> Err;
259 std::mutex ErrMu;
260
261public:
271
272 virtual ~ThinBackendProc() = default;
273 virtual void setup(unsigned ThinLTONumTasks, unsigned ThinLTOTaskOffset,
274 Triple Triple) {}
275 virtual Error start(
276 unsigned Task, BitcodeModule BM,
277 const FunctionImporter::ImportMapTy &ImportList,
278 const FunctionImporter::ExportSetTy &ExportList,
279 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
281 virtual Error wait() {
282 BackendThreadPool.wait();
283 if (Err)
284 return std::move(*Err);
285 return Error::success();
286 }
287 unsigned getThreadCount() { return BackendThreadPool.getMaxConcurrency(); }
288 virtual bool isSensitiveToInputOrder() { return false; }
289
290 // Write sharded indices and (optionally) imports to disk
292 unsigned Task, StringRef ModulePath,
293 const std::string &NewModulePath) const;
294
295 // Write sharded indices to SummaryPath, (optionally) imports to disk, and
296 // (optionally) record imports in ImportsFilesList.
298 unsigned Task, StringRef ModulePath,
299 const std::string &NewModulePath,
300 StringRef SummaryPath) 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 writes individual module indexes to files, instead of
355/// running the individual backend jobs. This backend is for distributed builds
356/// where separate processes will invoke the real backends.
357///
358/// To find the path to write the index to, the backend checks if the path has a
359/// prefix of OldPrefix; if so, it replaces that prefix with NewPrefix. It then
360/// appends ".thinlto.bc" and writes the index to that path. If
361/// ShouldEmitImportsFiles is true it also writes a list of imported files to a
362/// similar path with ".imports" appended instead.
363/// LinkedObjectsFile is an output stream to write the list of object files for
364/// the final ThinLTO linking. Can be nullptr. If LinkedObjectsFile is not
365/// nullptr and NativeObjectPrefix is not empty then it replaces the prefix of
366/// the objects with NativeObjectPrefix instead of NewPrefix. OnWrite is
367/// callback which receives module identifier and notifies LTO user that index
368/// file for the module (and optionally imports file) was created.
370 ThreadPoolStrategy Parallelism, std::string OldPrefix,
371 std::string NewPrefix, std::string NativeObjectPrefix,
372 bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile,
373 IndexWriteCallback OnWrite);
374
375/// This class implements a resolution-based interface to LLVM's LTO
376/// functionality. It supports regular LTO, parallel LTO code generation and
377/// ThinLTO. You can use it from a linker in the following way:
378/// - Set hooks and code generation options (see lto::Config struct defined in
379/// Config.h), and use the lto::Config object to create an lto::LTO object.
380/// - Create lto::InputFile objects using lto::InputFile::create(), then use
381/// the symbols() function to enumerate its symbols and compute a resolution
382/// for each symbol (see SymbolResolution below).
383/// - After the linker has visited each input file (and each regular object
384/// file) and computed a resolution for each symbol, take each lto::InputFile
385/// and pass it and an array of symbol resolutions to the add() function.
386/// - Call the getMaxTasks() function to get an upper bound on the number of
387/// native object files that LTO may add to the link.
388/// - Call the run() function. This function will use the supplied AddStream
389/// and Cache functions to add up to getMaxTasks() native object files to
390/// the link.
392 friend InputFile;
393
394public:
395 /// Unified LTO modes
396 enum LTOKind {
397 /// Any LTO mode without Unified LTO. The default mode.
399
400 /// Regular LTO, with Unified LTO enabled.
402
403 /// ThinLTO, with Unified LTO enabled.
405 };
406
407 /// Create an LTO object. A default constructed LTO object has a reasonable
408 /// production configuration, but you can customize it by passing arguments to
409 /// this constructor.
410 /// FIXME: We do currently require the DiagHandler field to be set in Conf.
411 /// Until that is fixed, a Config argument is required.
412 LTO(Config Conf, ThinBackend Backend = {},
413 unsigned ParallelCodeGenParallelismLevel = 1,
414 LTOKind LTOMode = LTOK_Default);
415 virtual ~LTO();
416
417 /// Add an input file to the LTO link, using the provided symbol resolutions.
418 /// The symbol resolutions must appear in the enumeration order given by
419 /// InputFile::symbols().
420 Error add(std::unique_ptr<InputFile> Obj, ArrayRef<SymbolResolution> Res);
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 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 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 virtual Error run(AddStreamFn AddStream, FileCache Cache = {});
441
442 /// Wait for cleanup work started by run() to finish.
443 ///
444 /// A client may delay this call to overlap asynchronous cleanup with later
445 /// linking work, but must call it before finalizing time trace data because
446 /// cleanup may emit time trace events. Most LTO implementations have no
447 /// asynchronous cleanup.
448 virtual void waitForCleanup() {}
449
450 /// Static method that returns a list of libcall symbols that can be generated
451 /// by LTO but might not be visible from bitcode symbol table.
452 static SmallVector<const char *> getRuntimeLibcallSymbols(const Triple &TT);
453
454 /// Static method that returns a list of library function symbols that can be
455 /// generated by LTO but might not be visible from bitcode symbol table.
456 /// Unlike the runtime libcalls, the linker can report to the code generator
457 /// which of these are actually available in the link, and the code generator
458 /// can then only reference that set of symbols.
459 static SmallVector<StringRef> getLibFuncSymbols(const Triple &TT,
460 llvm::StringSaver &Saver);
461
462protected:
463 // Called before returning from run().
464 virtual void cleanup();
465
467
470 const Config &Conf);
474 /// Record if at least one instance of the common was marked as prevailing
475 bool Prevailing = false;
476 };
477 std::map<std::string, CommonResolution> Commons;
478
481 std::unique_ptr<Module> CombinedModule;
482 std::unique_ptr<IRMover> Mover;
483
484 // This stores the information about a regular LTO module that we have added
485 // to the link. It will either be linked immediately (for modules without
486 // summaries) or after summary-based dead stripping (for modules with
487 // summaries).
488 struct AddedModule {
489 std::unique_ptr<Module> M;
490 std::vector<GlobalValue *> Keep;
491 };
492 std::vector<AddedModule> ModsWithSummaries;
494 } RegularLTO;
495
497
500
503 // The full set of bitcode modules in input order.
505 // The bitcode modules to compile, if specified by the LTO Config.
506 std::optional<ModuleMapType> ModulesToCompile;
507
509 PrevailingModuleForGUID[GUID] = Module;
510 }
512 StringRef Module) const {
513 auto It = PrevailingModuleForGUID.find(GUID);
514 return It != PrevailingModuleForGUID.end() && It->second == Module;
515 }
516
517 private:
518 // Make this private so all accesses must go through above accessor methods
519 // to avoid inadvertently creating new entries on lookups.
520 DenseMap<GlobalValue::GUID, StringRef> PrevailingModuleForGUID;
521 } ThinLTO;
522
523private:
524 // The global resolution for a particular (mangled) symbol name. This is in
525 // particular necessary to track whether each symbol can be internalized.
526 // Because any input file may introduce a new cross-partition reference, we
527 // cannot make any final internalization decisions until all input files have
528 // been added and the client has called run(). During run() we apply
529 // internalization decisions either directly to the module (for regular LTO)
530 // or to the combined index (for ThinLTO).
531 // FIXME: Make this GlobalResolution a class, it has been becoming more than
532 // just a data bag.
533 struct GlobalResolution {
534 /// The unmangled name of the global.
535 std::string IRName;
536
537 /// Keep track if the symbol is visible outside of a module with a summary
538 /// (i.e. in either a regular object or a regular LTO module without a
539 /// summary).
540 bool VisibleOutsideSummary = false;
541
542 /// The symbol was exported dynamically, and therefore could be referenced
543 /// by a shared library not visible to the linker.
544 bool ExportDynamic = false;
545
546 bool UnnamedAddr = true;
547
548 /// True if module contains the prevailing definition.
549 bool Prevailing = false;
550
551 /// Returns true if module contains the prevailing definition and symbol is
552 /// an IR symbol. For example when module-level inline asm block is used,
553 /// symbol can be prevailing in module but have no IR name.
554 bool isPrevailingIRSymbol() const { return Prevailing && !IRName.empty(); }
555
556 /// This field keeps track of the partition number of this global. The
557 /// regular LTO object is partition 0, while each ThinLTO object has its own
558 /// partition number from 1 onwards.
559 ///
560 /// Any global that is defined or used by more than one partition, or that
561 /// is referenced externally, may not be internalized.
562 ///
563 /// Partitions generally have a one-to-one correspondence with tasks, except
564 /// that we use partition 0 for all parallel LTO code generation partitions.
565 /// Any partitioning of the combined LTO object is done internally by the
566 /// LTO backend.
567 unsigned Partition = Unknown;
568
569 private:
570 GlobalValue::GUID GUID = 0;
571
572 public:
573 void setGUID(GlobalValue::GUID G) {
574 assert(G);
575 assert(!GUID || GUID == G);
576 GUID = G;
577 }
578
579 GlobalValue::GUID getGUID() const {
580 return GUID ? GUID
581 : GlobalValue::getGUIDAssumingExternalLinkage(
582 GlobalValue::getGlobalIdentifier(
583 IRName, GlobalValue::LinkageTypes::ExternalLinkage,
584 ""));
585 }
586
587 /// Special partition numbers.
588 enum : unsigned {
589 /// A partition number has not yet been assigned to this global.
590 Unknown = -1u,
591
592 /// This global is either used by more than one partition or has an
593 /// external reference, and therefore cannot be internalized.
594 External = -2u,
595
596 /// The RegularLTO partition
597 RegularLTO = 0,
598 };
599 };
600
601 // GlobalResolutionSymbolSaver allocator.
602 std::unique_ptr<llvm::BumpPtrAllocator> Alloc;
603
604 // Symbol saver for global resolution map.
605 std::unique_ptr<llvm::StringSaver> GlobalResolutionSymbolSaver;
606
607 // Global mapping from mangled symbol names to resolutions.
608 // Make this an unique_ptr to guard against accessing after it has been reset
609 // (to reduce memory after we're done with it).
610 std::unique_ptr<llvm::DenseMap<StringRef, GlobalResolution>>
611 GlobalResolutions;
612
613 void releaseGlobalResolutionsMemory();
614
615 void addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
616 ArrayRef<SymbolResolution> Res, unsigned Partition,
617 bool InSummary, const Triple &TT);
618
619 // These functions take a range of symbol resolutions and consume the
620 // resolutions used by a single input module. Functions return ranges refering
621 // to the resolutions for the remaining modules in the InputFile.
622 Expected<ArrayRef<SymbolResolution>>
623 addModule(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
624 unsigned ModI, ArrayRef<SymbolResolution> Res);
625
626 Expected<std::pair<RegularLTOState::AddedModule, ArrayRef<SymbolResolution>>>
627 addRegularLTO(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
628 BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
629 ArrayRef<SymbolResolution> Res);
630 Error linkRegularLTO(RegularLTOState::AddedModule Mod,
631 bool LivenessFromIndex);
632
633 Expected<ArrayRef<SymbolResolution>>
634 addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
635 ArrayRef<SymbolResolution> Res);
636
637 Error runRegularLTO(AddStreamFn AddStream);
638 Error runThinLTO(AddStreamFn AddStream, FileCache Cache,
639 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
640
641 Error checkPartiallySplit();
642
643 mutable bool CalledGetMaxTasks = false;
644
645protected:
646 // LTO mode when using Unified LTO.
648
649private:
650 // Use Optional to distinguish false from not yet initialized.
651 std::optional<bool> EnableSplitLTOUnit;
652
653 // Identify symbols exported dynamically, and that therefore could be
654 // referenced by a shared library not visible to the linker.
655 DenseSet<GlobalValue::GUID> DynamicExportSymbols;
656
657 // Diagnostic optimization remarks file
658 LLVMRemarkFileHandle DiagnosticOutputFile;
659
660 // A dummy module to host the dummy function.
661 std::unique_ptr<Module> DummyModule;
662
663 // A dummy function created in a private module to provide a context for
664 // LTO-link optimization remarks. This is needed for ThinLTO where we
665 // may not have any IR functions available, because the optimization remark
666 // handling requires a function.
667 Function *LinkerRemarkFunction = nullptr;
668
669 // Setup optimization remarks according to the provided configuration.
670 Error setupOptimizationRemarks();
671
672 // LibFuncs that were implemented in bitcode but were not extracted
673 // from their libraries. Such functions cannot safely be called, since
674 // they have lost their opportunity to be defined.
675 SmallVector<StringRef> BitcodeLibFuncs;
676
677public:
678 /// Helper to emit an optimization remark during the LTO link when outside of
679 /// the standard optimization pass pipeline.
681
683 addInput(std::unique_ptr<lto::InputFile> InputPtr) {
684 return std::shared_ptr<lto::InputFile>(InputPtr.release());
685 }
686};
687
688/// The resolution for a symbol. The linker must provide a SymbolResolution for
689/// each global symbol based on its internal resolution of that symbol.
694
695 /// The linker has chosen this definition of the symbol.
696 unsigned Prevailing : 1;
697
698 /// The definition of this symbol is unpreemptable at runtime and is known to
699 /// be in this linkage unit.
701
702 /// The definition of this symbol is visible outside of the LTO unit.
704
705 /// The symbol was exported dynamically, and therefore could be referenced
706 /// by a shared library not visible to the linker.
707 unsigned ExportDynamic : 1;
708
709 /// Linker redefined version of the symbol which appeared in -wrap or -defsym
710 /// linker option.
711 unsigned LinkerRedefined : 1;
712};
713
714} // namespace lto
715} // namespace llvm
716
717#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static void cleanup(BlockFrequencyInfoImplBase &BFI)
Clear all memory not needed downstream.
#define LLVM_ABI
Definition Compiler.h:215
This file defines the DenseMap class.
Provides passes for computing function attributes based on interprocedural analyses.
static void emitRemark(const Function &F, OptimizationRemarkEmitter &ORE, bool Skip)
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
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...
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
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:281
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:48
An efficient, type-erasing, non-owning reference to a callable.
LLVM_ABI BitcodeModule & getPrimaryBitcodeModule()
Definition LTO.cpp:679
MemoryBufferRef getFileBuffer() const
Definition LTO.h:215
static LLVM_ABI Expected< std::unique_ptr< InputFile > > create(MemoryBufferRef Object)
Create an InputFile.
Definition LTO.cpp:630
ArrayRef< Symbol > symbols() const
A range over the symbols in this InputFile.
Definition LTO.h:188
StringRef getCOFFLinkerOpts() const
Returns linker options specified in the input file.
Definition LTO.h:191
bool getExtractForDistribution() const
Definition LTO.h:218
bool isFatLTOObject() const
Definition LTO.h:223
ArrayRef< StringRef > getDependentLibraries() const
Returns dependent library specifiers from the input file.
Definition LTO.h:194
StringRef getArchivePath() const
Definition LTO.h:235
StringRef getMemberName() const
Definition LTO.h:236
ArrayRef< std::pair< StringRef, Comdat::SelectionKind > > getComdatTable() const
Definition LTO.h:206
void setExtractForDistribution(bool EFD)
Definition LTO.h:221
StringRef getTargetTriple() const
Returns the input file's target triple.
Definition LTO.h:200
LLVM_ABI StringRef getName() const
Returns the path to the InputFile.
Definition LTO.cpp:670
LLVM_ABI BitcodeModule & getSingleBitcodeModule()
Definition LTO.cpp:674
StringRef getSourceFileName() const
Returns the source file path specified at compile time.
Definition LTO.h:203
bool isThinLTO() const
Definition LTO.h:228
void fatLTOObject(bool FO)
Definition LTO.h:225
void setArchivePathAndName(StringRef Path, StringRef Name)
Definition LTO.h:231
This class implements a resolution-based interface to LLVM's LTO functionality.
Definition LTO.h:391
LTO(Config Conf, ThinBackend Backend={}, unsigned ParallelCodeGenParallelismLevel=1, LTOKind LTOMode=LTOK_Default)
Create an LTO object.
Definition LTO.cpp:694
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:829
virtual Expected< std::shared_ptr< lto::InputFile > > addInput(std::unique_ptr< lto::InputFile > InputPtr)
Definition LTO.h:683
Config Conf
Definition LTO.h:466
void setBitcodeLibFuncs(ArrayRef< StringRef > BitcodeLibFuncs)
Set the list of functions implemented in bitcode that were not extracted from an archive.
Definition LTO.cpp:860
MapVector< StringRef, BitcodeModule > ModuleMapType
Definition LTO.h:496
LTOKind
Unified LTO modes.
Definition LTO.h:396
@ LTOK_UnifiedRegular
Regular LTO, with Unified LTO enabled.
Definition LTO.h:401
@ LTOK_Default
Any LTO mode without Unified LTO. The default mode.
Definition LTO.h:398
@ LTOK_UnifiedThin
ThinLTO, with Unified LTO enabled.
Definition LTO.h:404
virtual ~LTO()
LTOKind LTOMode
Definition LTO.h:647
unsigned getMaxTasks() const
Returns an upper bound on the number of tasks that the client may expect.
Definition LTO.cpp:1272
virtual Error run(AddStreamFn AddStream, FileCache Cache={})
Runs the LTO pipeline.
Definition LTO.cpp:1323
virtual void waitForCleanup()
Wait for cleanup work started by run() to finish.
Definition LTO.h:448
DefaultThreadPool BackendThreadPool
Definition LTO.h:257
const Config & Conf
Definition LTO.h:252
std::optional< Error > Err
Definition LTO.h:258
virtual bool isSensitiveToInputOrder()
Definition LTO.h:288
unsigned getThreadCount()
Definition LTO.h:287
const DenseMap< StringRef, GVSummaryMapTy > & ModuleToDefinedGVSummaries
Definition LTO.h:254
ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, lto::IndexWriteCallback OnWrite, bool ShouldEmitImportsFiles, ThreadPoolStrategy ThinLTOParallelism)
Definition LTO.h:262
virtual Error wait()
Definition LTO.h:281
ModuleSummaryIndex & CombinedIndex
Definition LTO.h:253
virtual void setup(unsigned ThinLTONumTasks, unsigned ThinLTOTaskOffset, Triple Triple)
Definition LTO.h:273
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:1540
IndexWriteCallback OnWrite
Definition LTO.h:255
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:1901
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:1936
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:1918
LLVM_ABI Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
Definition LTO.cpp:2373
std::function< void(const std::string &)> IndexWriteCallback
Definition LTO.h:245
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:2043
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:2348
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
Definition LTO.cpp:2392
llvm::SmallVector< std::string > ImportsFilesContainer
Definition LTO.h:247
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"))
@ Unknown
Not known to have no common set bits.
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:394
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:494
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
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:138
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:612
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
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:173
StringRef getName() const
Returns the mangled symbol name.
Definition IRSymtab.h:187
bool canBeOmittedFromSymbolTable() const
Definition IRSymtab.h:210
bool isUsed() const
Definition IRSymtab.h:207
StringRef getSectionName() const
Definition IRSymtab.h:236
bool isTLS() const
Definition IRSymtab.h:208
bool isWeak() const
Definition IRSymtab.h:204
bool isIndirect() const
Definition IRSymtab.h:206
bool isCommon() const
Definition IRSymtab.h:205
uint32_t getCommonAlignment() const
Definition IRSymtab.h:224
bool isExecutable() const
Definition IRSymtab.h:217
uint64_t getCommonSize() const
Definition IRSymtab.h:219
storage::Symbol S
Definition IRSymtab.h:197
int getComdatIndex() const
Returns the index into the comdat table (see Reader::getComdatTable()), or -1 if not a comdat member.
Definition IRSymtab.h:195
GlobalValue::VisibilityTypes getVisibility() const
Definition IRSymtab.h:199
bool isUndefined() const
Definition IRSymtab.h:203
StringRef getIRName() const
Returns the unmangled symbol name, or the empty string if this is not an IR symbol.
Definition IRSymtab.h:191
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:231
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:156
LLVM_ABI bool isLibcall(const TargetLibraryInfo &TLI, const RTLIB::RuntimeLibcallsInfo &Libcalls) const
Definition LTO.cpp:661
Symbol(const irsymtab::Symbol &S)
Definition LTO.h:160
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:490
std::unique_ptr< Module > M
Definition LTO.h:489
bool Prevailing
Record if at least one instance of the common was marked as prevailing.
Definition LTO.h:475
std::vector< AddedModule > ModsWithSummaries
Definition LTO.h:492
std::unique_ptr< IRMover > Mover
Definition LTO.h:482
unsigned ParallelCodeGenParallelismLevel
Definition LTO.h:479
std::map< std::string, CommonResolution > Commons
Definition LTO.h:477
std::unique_ptr< Module > CombinedModule
Definition LTO.h:481
LLVM_ABI RegularLTOState(unsigned ParallelCodeGenParallelismLevel, const Config &Conf)
Definition LTO.cpp:681
ModuleMapType ModuleMap
Definition LTO.h:504
LLVM_ABI ThinLTOState(ThinBackend Backend)
Definition LTO.cpp:687
bool isPrevailingModuleForGUID(GlobalValue::GUID GUID, StringRef Module) const
Definition LTO.h:511
void setPrevailingModuleForGUID(GlobalValue::GUID GUID, StringRef Module)
Definition LTO.h:508
std::optional< ModuleMapType > ModulesToCompile
Definition LTO.h:506
ModuleSummaryIndex CombinedIndex
Definition LTO.h:502
The resolution for a symbol.
Definition LTO.h:690
unsigned FinalDefinitionInLinkageUnit
The definition of this symbol is unpreemptable at runtime and is known to be in this linkage unit.
Definition LTO.h:700
unsigned ExportDynamic
The symbol was exported dynamically, and therefore could be referenced by a shared library not visibl...
Definition LTO.h:707
unsigned Prevailing
The linker has chosen this definition of the symbol.
Definition LTO.h:696
unsigned LinkerRedefined
Linker redefined version of the symbol which appeared in -wrap or -defsym linker option.
Definition LTO.h:711
unsigned VisibleToRegularObj
The definition of this symbol is visible outside of the LTO unit.
Definition LTO.h:703
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