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 
18 #include "llvm/ADT/MapVector.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/Bitcode/BitcodeReader.h"
21 #include "llvm/IR/ModuleSummaryIndex.h"
22 #include "llvm/LTO/Config.h"
23 #include "llvm/Object/IRSymtab.h"
24 #include "llvm/Support/Caching.h"
25 #include "llvm/Support/Error.h"
26 #include "llvm/Support/thread.h"
27 #include "llvm/Transforms/IPO/FunctionAttrs.h"
28 #include "llvm/Transforms/IPO/FunctionImport.h"
29 
30 namespace llvm {
31 
32 class Error;
33 class IRMover;
34 class LLVMContext;
35 class MemoryBufferRef;
36 class Module;
37 class raw_pwrite_stream;
38 class ToolOutputFile;
39 
40 /// Resolve linkage for prevailing symbols in the \p Index. Linkage changes
41 /// recorded in the index and the ThinLTO backends must apply the changes to
42 /// the module via thinLTOFinalizeInModule.
43 ///
44 /// This is done for correctness (if value exported, ensure we always
45 /// emit a copy), and compile-time optimization (allow drop of duplicates).
46 void thinLTOResolvePrevailingInIndex(
47     const lto::Config &C, ModuleSummaryIndex &Index,
48     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
49         isPrevailing,
50     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
51         recordNewLinkage,
52     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
53 
54 /// Update the linkages in the given \p Index to mark exported values
55 /// as external and non-exported values as internal. The ThinLTO backends
56 /// must apply the changes to the Module via thinLTOInternalizeModule.
57 void thinLTOInternalizeAndPromoteInIndex(
58     ModuleSummaryIndex &Index,
59     function_ref<bool(StringRef, ValueInfo)> isExported,
60     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
61         isPrevailing);
62 
63 /// Computes a unique hash for the Module considering the current list of
64 /// export/import and other global analysis results.
65 /// The hash is produced in \p Key.
66 void computeLTOCacheKey(
67     SmallString<40> &Key, const lto::Config &Conf,
68     const ModuleSummaryIndex &Index, StringRef ModuleID,
69     const FunctionImporter::ImportMapTy &ImportList,
70     const FunctionImporter::ExportSetTy &ExportList,
71     const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
72     const GVSummaryMapTy &DefinedGlobals,
73     const std::set<GlobalValue::GUID> &CfiFunctionDefs = {},
74     const std::set<GlobalValue::GUID> &CfiFunctionDecls = {});
75 
76 namespace lto {
77 
78 /// Given the original \p Path to an output file, replace any path
79 /// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
80 /// resulting directory if it does not yet exist.
81 std::string getThinLTOOutputFile(const std::string &Path,
82                                  const std::string &OldPrefix,
83                                  const std::string &NewPrefix);
84 
85 /// Setup optimization remarks.
86 Expected<std::unique_ptr<ToolOutputFile>> setupLLVMOptimizationRemarks(
87     LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
88     StringRef RemarksFormat, bool RemarksWithHotness,
89     Optional<uint64_t> RemarksHotnessThreshold = 0, int Count = -1);
90 
91 /// Setups the output file for saving statistics.
92 Expected<std::unique_ptr<ToolOutputFile>>
93 setupStatsFile(StringRef StatsFilename);
94 
95 /// Produces a container ordering for optimal multi-threaded processing. Returns
96 /// ordered indices to elements in the input array.
97 std::vector<int> generateModulesOrdering(ArrayRef<BitcodeModule *> R);
98 
99 class LTO;
100 struct SymbolResolution;
101 class ThinBackendProc;
102 
103 /// An input file. This is a symbol table wrapper that only exposes the
104 /// information that an LTO client should need in order to do symbol resolution.
105 class InputFile {
106 public:
107   class Symbol;
108 
109 private:
110   // FIXME: Remove LTO class friendship once we have bitcode symbol tables.
111   friend LTO;
112   InputFile() = default;
113 
114   std::vector<BitcodeModule> Mods;
115   SmallVector<char, 0> Strtab;
116   std::vector<Symbol> Symbols;
117 
118   // [begin, end) for each module
119   std::vector<std::pair<size_t, size_t>> ModuleSymIndices;
120 
121   StringRef TargetTriple, SourceFileName, COFFLinkerOpts;
122   std::vector<StringRef> DependentLibraries;
123   std::vector<std::pair<StringRef, Comdat::SelectionKind>> ComdatTable;
124 
125 public:
126   ~InputFile();
127 
128   /// Create an InputFile.
129   static Expected<std::unique_ptr<InputFile>> create(MemoryBufferRef Object);
130 
131   /// The purpose of this class is to only expose the symbol information that an
132   /// LTO client should need in order to do symbol resolution.
133   class Symbol : irsymtab::Symbol {
134     friend LTO;
135 
136   public:
137     Symbol(const irsymtab::Symbol &S) : irsymtab::Symbol(S) {}
138 
139     using irsymtab::Symbol::isUndefined;
140     using irsymtab::Symbol::isCommon;
141     using irsymtab::Symbol::isWeak;
142     using irsymtab::Symbol::isIndirect;
143     using irsymtab::Symbol::getName;
144     using irsymtab::Symbol::getIRName;
145     using irsymtab::Symbol::getVisibility;
146     using irsymtab::Symbol::canBeOmittedFromSymbolTable;
147     using irsymtab::Symbol::isTLS;
148     using irsymtab::Symbol::getComdatIndex;
149     using irsymtab::Symbol::getCommonSize;
150     using irsymtab::Symbol::getCommonAlignment;
151     using irsymtab::Symbol::getCOFFWeakExternalFallback;
152     using irsymtab::Symbol::getSectionName;
153     using irsymtab::Symbol::isExecutable;
154     using irsymtab::Symbol::isUsed;
155   };
156 
157   /// A range over the symbols in this InputFile.
158   ArrayRef<Symbol> symbols() const { return Symbols; }
159 
160   /// Returns linker options specified in the input file.
161   StringRef getCOFFLinkerOpts() const { return COFFLinkerOpts; }
162 
163   /// Returns dependent library specifiers from the input file.
164   ArrayRef<StringRef> getDependentLibraries() const { return DependentLibraries; }
165 
166   /// Returns the path to the InputFile.
167   StringRef getName() const;
168 
169   /// Returns the input file's target triple.
170   StringRef getTargetTriple() const { return TargetTriple; }
171 
172   /// Returns the source file path specified at compile time.
173   StringRef getSourceFileName() const { return SourceFileName; }
174 
175   // Returns a table with all the comdats used by this file.
176   ArrayRef<std::pair<StringRef, Comdat::SelectionKind>> getComdatTable() const {
177     return ComdatTable;
178   }
179 
180   // Returns the only BitcodeModule from InputFile.
181   BitcodeModule &getSingleBitcodeModule();
182 
183 private:
184   ArrayRef<Symbol> module_symbols(unsigned I) const {
185     const auto &Indices = ModuleSymIndices[I];
186     return {Symbols.data() + Indices.first, Symbols.data() + Indices.second};
187   }
188 };
189 
190 /// A ThinBackend defines what happens after the thin-link phase during ThinLTO.
191 /// The details of this type definition aren't important; clients can only
192 /// create a ThinBackend using one of the create*ThinBackend() functions below.
193 using ThinBackend = std::function<std::unique_ptr<ThinBackendProc>(
194     const Config &C, ModuleSummaryIndex &CombinedIndex,
195     StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
196     AddStreamFn AddStream, FileCache Cache)>;
197 
198 /// This ThinBackend runs the individual backend jobs in-process.
199 /// The default value means to use one job per hardware core (not hyper-thread).
200 ThinBackend createInProcessThinBackend(ThreadPoolStrategy Parallelism);
201 
202 /// This ThinBackend writes individual module indexes to files, instead of
203 /// running the individual backend jobs. This backend is for distributed builds
204 /// where separate processes will invoke the real backends.
205 ///
206 /// To find the path to write the index to, the backend checks if the path has a
207 /// prefix of OldPrefix; if so, it replaces that prefix with NewPrefix. It then
208 /// appends ".thinlto.bc" and writes the index to that path. If
209 /// ShouldEmitImportsFiles is true it also writes a list of imported files to a
210 /// similar path with ".imports" appended instead.
211 /// LinkedObjectsFile is an output stream to write the list of object files for
212 /// the final ThinLTO linking. Can be nullptr.
213 /// OnWrite is callback which receives module identifier and notifies LTO user
214 /// that index file for the module (and optionally imports file) was created.
215 using IndexWriteCallback = std::function<void(const std::string &)>;
216 ThinBackend createWriteIndexesThinBackend(std::string OldPrefix,
217                                           std::string NewPrefix,
218                                           bool ShouldEmitImportsFiles,
219                                           raw_fd_ostream *LinkedObjectsFile,
220                                           IndexWriteCallback OnWrite);
221 
222 /// This class implements a resolution-based interface to LLVM's LTO
223 /// functionality. It supports regular LTO, parallel LTO code generation and
224 /// ThinLTO. You can use it from a linker in the following way:
225 /// - Set hooks and code generation options (see lto::Config struct defined in
226 ///   Config.h), and use the lto::Config object to create an lto::LTO object.
227 /// - Create lto::InputFile objects using lto::InputFile::create(), then use
228 ///   the symbols() function to enumerate its symbols and compute a resolution
229 ///   for each symbol (see SymbolResolution below).
230 /// - After the linker has visited each input file (and each regular object
231 ///   file) and computed a resolution for each symbol, take each lto::InputFile
232 ///   and pass it and an array of symbol resolutions to the add() function.
233 /// - Call the getMaxTasks() function to get an upper bound on the number of
234 ///   native object files that LTO may add to the link.
235 /// - Call the run() function. This function will use the supplied AddStream
236 ///   and Cache functions to add up to getMaxTasks() native object files to
237 ///   the link.
238 class LTO {
239   friend InputFile;
240 
241 public:
242   /// Create an LTO object. A default constructed LTO object has a reasonable
243   /// production configuration, but you can customize it by passing arguments to
244   /// this constructor.
245   /// FIXME: We do currently require the DiagHandler field to be set in Conf.
246   /// Until that is fixed, a Config argument is required.
247   LTO(Config Conf, ThinBackend Backend = nullptr,
248       unsigned ParallelCodeGenParallelismLevel = 1);
249   ~LTO();
250 
251   /// Add an input file to the LTO link, using the provided symbol resolutions.
252   /// The symbol resolutions must appear in the enumeration order given by
253   /// InputFile::symbols().
254   Error add(std::unique_ptr<InputFile> Obj, ArrayRef<SymbolResolution> Res);
255 
256   /// Returns an upper bound on the number of tasks that the client may expect.
257   /// This may only be called after all IR object files have been added. For a
258   /// full description of tasks see LTOBackend.h.
259   unsigned getMaxTasks() const;
260 
261   /// Runs the LTO pipeline. This function calls the supplied AddStream
262   /// function to add native object files to the link.
263   ///
264   /// The Cache parameter is optional. If supplied, it will be used to cache
265   /// native object files and add them to the link.
266   ///
267   /// The client will receive at most one callback (via either AddStream or
268   /// Cache) for each task identifier.
269   Error run(AddStreamFn AddStream, FileCache Cache = nullptr);
270 
271   /// Static method that returns a list of libcall symbols that can be generated
272   /// by LTO but might not be visible from bitcode symbol table.
273   static ArrayRef<const char*> getRuntimeLibcallSymbols();
274 
275 private:
276   Config Conf;
277 
278   struct RegularLTOState {
279     RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
280                     const Config &Conf);
281     struct CommonResolution {
282       uint64_t Size = 0;
283       MaybeAlign Align;
284       /// Record if at least one instance of the common was marked as prevailing
285       bool Prevailing = false;
286     };
287     std::map<std::string, CommonResolution> Commons;
288 
289     unsigned ParallelCodeGenParallelismLevel;
290     LTOLLVMContext Ctx;
291     std::unique_ptr<Module> CombinedModule;
292     std::unique_ptr<IRMover> Mover;
293 
294     // This stores the information about a regular LTO module that we have added
295     // to the link. It will either be linked immediately (for modules without
296     // summaries) or after summary-based dead stripping (for modules with
297     // summaries).
298     struct AddedModule {
299       std::unique_ptr<Module> M;
300       std::vector<GlobalValue *> Keep;
301     };
302     std::vector<AddedModule> ModsWithSummaries;
303     bool EmptyCombinedModule = true;
304   } RegularLTO;
305 
306   using ModuleMapType = MapVector<StringRef, BitcodeModule>;
307 
308   struct ThinLTOState {
309     ThinLTOState(ThinBackend Backend);
310 
311     ThinBackend Backend;
312     ModuleSummaryIndex CombinedIndex;
313     // The full set of bitcode modules in input order.
314     ModuleMapType ModuleMap;
315     // The bitcode modules to compile, if specified by the LTO Config.
316     Optional<ModuleMapType> ModulesToCompile;
317     DenseMap<GlobalValue::GUID, StringRef> PrevailingModuleForGUID;
318   } ThinLTO;
319 
320   // The global resolution for a particular (mangled) symbol name. This is in
321   // particular necessary to track whether each symbol can be internalized.
322   // Because any input file may introduce a new cross-partition reference, we
323   // cannot make any final internalization decisions until all input files have
324   // been added and the client has called run(). During run() we apply
325   // internalization decisions either directly to the module (for regular LTO)
326   // or to the combined index (for ThinLTO).
327   struct GlobalResolution {
328     /// The unmangled name of the global.
329     std::string IRName;
330 
331     /// Keep track if the symbol is visible outside of a module with a summary
332     /// (i.e. in either a regular object or a regular LTO module without a
333     /// summary).
334     bool VisibleOutsideSummary = false;
335 
336     /// The symbol was exported dynamically, and therefore could be referenced
337     /// by a shared library not visible to the linker.
338     bool ExportDynamic = false;
339 
340     bool UnnamedAddr = true;
341 
342     /// True if module contains the prevailing definition.
343     bool Prevailing = false;
344 
345     /// Returns true if module contains the prevailing definition and symbol is
346     /// an IR symbol. For example when module-level inline asm block is used,
347     /// symbol can be prevailing in module but have no IR name.
348     bool isPrevailingIRSymbol() const { return Prevailing && !IRName.empty(); }
349 
350     /// This field keeps track of the partition number of this global. The
351     /// regular LTO object is partition 0, while each ThinLTO object has its own
352     /// partition number from 1 onwards.
353     ///
354     /// Any global that is defined or used by more than one partition, or that
355     /// is referenced externally, may not be internalized.
356     ///
357     /// Partitions generally have a one-to-one correspondence with tasks, except
358     /// that we use partition 0 for all parallel LTO code generation partitions.
359     /// Any partitioning of the combined LTO object is done internally by the
360     /// LTO backend.
361     unsigned Partition = Unknown;
362 
363     /// Special partition numbers.
364     enum : unsigned {
365       /// A partition number has not yet been assigned to this global.
366       Unknown = -1u,
367 
368       /// This global is either used by more than one partition or has an
369       /// external reference, and therefore cannot be internalized.
370       External = -2u,
371 
372       /// The RegularLTO partition
373       RegularLTO = 0,
374     };
375   };
376 
377   // Global mapping from mangled symbol names to resolutions.
378   StringMap<GlobalResolution> GlobalResolutions;
379 
380   void addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
381                             ArrayRef<SymbolResolution> Res, unsigned Partition,
382                             bool InSummary);
383 
384   // These functions take a range of symbol resolutions [ResI, ResE) and consume
385   // the resolutions used by a single input module by incrementing ResI. After
386   // these functions return, [ResI, ResE) will refer to the resolution range for
387   // the remaining modules in the InputFile.
388   Error addModule(InputFile &Input, unsigned ModI,
389                   const SymbolResolution *&ResI, const SymbolResolution *ResE);
390 
391   Expected<RegularLTOState::AddedModule>
392   addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
393                 const SymbolResolution *&ResI, const SymbolResolution *ResE);
394   Error linkRegularLTO(RegularLTOState::AddedModule Mod,
395                        bool LivenessFromIndex);
396 
397   Error addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
398                    const SymbolResolution *&ResI, const SymbolResolution *ResE);
399 
400   Error runRegularLTO(AddStreamFn AddStream);
401   Error runThinLTO(AddStreamFn AddStream, FileCache Cache,
402                    const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols);
403 
404   Error checkPartiallySplit();
405 
406   mutable bool CalledGetMaxTasks = false;
407 
408   // Use Optional to distinguish false from not yet initialized.
409   Optional<bool> EnableSplitLTOUnit;
410 
411   // Identify symbols exported dynamically, and that therefore could be
412   // referenced by a shared library not visible to the linker.
413   DenseSet<GlobalValue::GUID> DynamicExportSymbols;
414 
415   // Diagnostic optimization remarks file
416   std::unique_ptr<ToolOutputFile> DiagnosticOutputFile;
417 };
418 
419 /// The resolution for a symbol. The linker must provide a SymbolResolution for
420 /// each global symbol based on its internal resolution of that symbol.
421 struct SymbolResolution {
422   SymbolResolution()
423       : Prevailing(0), FinalDefinitionInLinkageUnit(0), VisibleToRegularObj(0),
424         ExportDynamic(0), LinkerRedefined(0) {}
425 
426   /// The linker has chosen this definition of the symbol.
427   unsigned Prevailing : 1;
428 
429   /// The definition of this symbol is unpreemptable at runtime and is known to
430   /// be in this linkage unit.
431   unsigned FinalDefinitionInLinkageUnit : 1;
432 
433   /// The definition of this symbol is visible outside of the LTO unit.
434   unsigned VisibleToRegularObj : 1;
435 
436   /// The symbol was exported dynamically, and therefore could be referenced
437   /// by a shared library not visible to the linker.
438   unsigned ExportDynamic : 1;
439 
440   /// Linker redefined version of the symbol which appeared in -wrap or -defsym
441   /// linker option.
442   unsigned LinkerRedefined : 1;
443 };
444 
445 } // namespace lto
446 } // namespace llvm
447 
448 #endif
449