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