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