Coverage Report

Created: 2019-02-15 18:59

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