blob: f8e708076131ffe69fd2afb0ffd2c2a012f363b7 [file] [log] [blame]
Nick Lewyckyfb643e42009-02-03 07:13:24 +00001//===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization ------===//
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 is a gold plugin for LLVM. It provides an LLVM implementation of the
11// interface described in http://gcc.gnu.org/wiki/whopr/driver .
12//
13//===----------------------------------------------------------------------===//
14
Teresa Johnsonad176792016-11-11 05:34:58 +000015#include "llvm/Bitcode/BitcodeReader.h"
16#include "llvm/Bitcode/BitcodeWriter.h"
Rafael Espindola6b244b12014-06-19 21:14:13 +000017#include "llvm/CodeGen/CommandFlags.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000018#include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
Rafael Espindola890db272014-09-09 20:08:22 +000019#include "llvm/IR/Constants.h"
Rafael Espindolad0b23be2015-01-10 00:07:30 +000020#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson57891a52016-08-24 15:11:47 +000021#include "llvm/LTO/Caching.h"
Teresa Johnson683abe72016-05-26 01:46:41 +000022#include "llvm/LTO/LTO.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000023#include "llvm/Support/CommandLine.h"
Rafael Espindola947bdb62014-11-25 20:52:49 +000024#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000025#include "llvm/Support/MemoryBuffer.h"
Teresa Johnsonbbd10b42016-05-17 14:45:30 +000026#include "llvm/Support/Path.h"
Rafael Espindola6b244b12014-06-19 21:14:13 +000027#include "llvm/Support/TargetSelect.h"
Teresa Johnsonb13dbd62015-12-09 19:45:55 +000028#include "llvm/Support/raw_ostream.h"
Nick Lewyckyfb643e42009-02-03 07:13:24 +000029#include <list>
Teresa Johnson9ba95f92016-08-11 14:58:12 +000030#include <map>
Chandler Carruth07baed52014-01-13 08:04:33 +000031#include <plugin-api.h>
Teresa Johnson9ba95f92016-08-11 14:58:12 +000032#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000033#include <system_error>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000034#include <utility>
Nick Lewyckyfb643e42009-02-03 07:13:24 +000035#include <vector>
36
Sylvestre Ledru53999792014-02-11 17:30:18 +000037// FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
38// Precise and Debian Wheezy (binutils 2.23 is required)
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +000039#define LDPO_PIE 3
40
41#define LDPT_GET_SYMBOLS_V3 28
Sylvestre Ledru53999792014-02-11 17:30:18 +000042
Nick Lewyckyfb643e42009-02-03 07:13:24 +000043using namespace llvm;
Teresa Johnson9ba95f92016-08-11 14:58:12 +000044using namespace lto;
Nick Lewyckyfb643e42009-02-03 07:13:24 +000045
Teresa Johnsoncb15b732015-12-16 16:34:06 +000046static ld_plugin_status discard_message(int level, const char *format, ...) {
47 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
48 // callback in the transfer vector. This should never be called.
49 abort();
50}
51
52static ld_plugin_release_input_file release_input_file = nullptr;
53static ld_plugin_get_input_file get_input_file = nullptr;
54static ld_plugin_message message = discard_message;
55
Nick Lewyckyfb643e42009-02-03 07:13:24 +000056namespace {
Rafael Espindolabfb8b912014-06-20 01:37:35 +000057struct claimed_file {
58 void *handle;
Teresa Johnson683abe72016-05-26 01:46:41 +000059 void *leader_handle;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000060 std::vector<ld_plugin_symbol> syms;
Teresa Johnson683abe72016-05-26 01:46:41 +000061 off_t filesize;
62 std::string name;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000063};
Rafael Espindolacaabe222015-12-10 14:19:35 +000064
Teresa Johnsoncb15b732015-12-16 16:34:06 +000065/// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
66struct PluginInputFile {
Teresa Johnson031bed22015-12-16 21:37:48 +000067 void *Handle;
Teresa Johnson7cffaf32016-03-04 17:06:02 +000068 std::unique_ptr<ld_plugin_input_file> File;
Teresa Johnsoncb15b732015-12-16 16:34:06 +000069
Teresa Johnson031bed22015-12-16 21:37:48 +000070 PluginInputFile(void *Handle) : Handle(Handle) {
Teresa Johnson7cffaf32016-03-04 17:06:02 +000071 File = llvm::make_unique<ld_plugin_input_file>();
72 if (get_input_file(Handle, File.get()) != LDPS_OK)
Teresa Johnsoncb15b732015-12-16 16:34:06 +000073 message(LDPL_FATAL, "Failed to get file information");
74 }
75 ~PluginInputFile() {
Teresa Johnson7cffaf32016-03-04 17:06:02 +000076 // File would have been reset to nullptr if we moved this object
77 // to a new owner.
78 if (File)
79 if (release_input_file(Handle) != LDPS_OK)
80 message(LDPL_FATAL, "Failed to release file information");
Teresa Johnsoncb15b732015-12-16 16:34:06 +000081 }
Teresa Johnson7cffaf32016-03-04 17:06:02 +000082
83 ld_plugin_input_file &file() { return *File; }
84
85 PluginInputFile(PluginInputFile &&RHS) = default;
86 PluginInputFile &operator=(PluginInputFile &&RHS) = default;
Teresa Johnsoncb15b732015-12-16 16:34:06 +000087};
88
Rafael Espindolacaabe222015-12-10 14:19:35 +000089struct ResolutionInfo {
Teresa Johnson9ba95f92016-08-11 14:58:12 +000090 bool CanOmitFromDynSym = true;
91 bool DefaultVisibility = true;
Rafael Espindolacaabe222015-12-10 14:19:35 +000092};
Teresa Johnson7cffaf32016-03-04 17:06:02 +000093
Nick Lewyckyfb643e42009-02-03 07:13:24 +000094}
Rafael Espindolabfb8b912014-06-20 01:37:35 +000095
Rafael Espindola176e6642014-07-29 21:46:05 +000096static ld_plugin_add_symbols add_symbols = nullptr;
97static ld_plugin_get_symbols get_symbols = nullptr;
98static ld_plugin_add_input_file add_input_file = nullptr;
99static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
100static ld_plugin_get_view get_view = nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000101static bool IsExecutable = false;
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000102static Optional<Reloc::Model> RelocationModel;
Rafael Espindolabfb8b912014-06-20 01:37:35 +0000103static std::string output_name = "";
104static std::list<claimed_file> Modules;
Teresa Johnson683abe72016-05-26 01:46:41 +0000105static DenseMap<int, void *> FDToLeaderHandle;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000106static StringMap<ResolutionInfo> ResInfo;
Rafael Espindolabfb8b912014-06-20 01:37:35 +0000107static std::vector<std::string> Cleanup;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000108static llvm::TargetOptions TargetOpts;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000109
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000110namespace options {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000111 enum OutputType {
112 OT_NORMAL,
113 OT_DISABLE,
114 OT_BC_ONLY,
115 OT_SAVE_TEMPS
116 };
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000117 static OutputType TheOutputType = OT_NORMAL;
Peter Collingbourne070843d2015-03-19 22:01:00 +0000118 static unsigned OptLevel = 2;
Teresa Johnsona9f65552016-03-04 16:36:06 +0000119 // Default parallelism of 0 used to indicate that user did not specify.
120 // Actual parallelism default value depends on implementation.
Teresa Johnsonec544c52016-10-19 17:35:01 +0000121 // Currently only affects ThinLTO, where the default is
122 // llvm::heavyweight_hardware_concurrency.
Teresa Johnsona9f65552016-03-04 16:36:06 +0000123 static unsigned Parallelism = 0;
Teresa Johnson896fee22016-09-23 20:35:19 +0000124 // Default regular LTO codegen parallelism (number of partitions).
125 static unsigned ParallelCodeGenParallelismLevel = 1;
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000126#ifdef NDEBUG
127 static bool DisableVerify = true;
128#else
129 static bool DisableVerify = false;
130#endif
Shuxin Yang1826ae22013-08-12 21:07:31 +0000131 static std::string obj_path;
Rafael Espindolaef498152010-06-23 20:20:59 +0000132 static std::string extra_library_path;
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000133 static std::string triple;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000134 static std::string mcpu;
Teresa Johnson403a7872015-10-04 14:33:43 +0000135 // When the thinlto plugin option is specified, only read the function
136 // the information from intermediate files and write a combined
137 // global index for the ThinLTO backends.
138 static bool thinlto = false;
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000139 // If false, all ThinLTO backend compilations through code gen are performed
140 // using multiple threads in the gold-plugin, before handing control back to
Teresa Johnson84174c32016-05-10 13:48:23 +0000141 // gold. If true, write individual backend index files which reflect
142 // the import decisions, and exit afterwards. The assumption is
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000143 // that the build system will launch the backend processes.
144 static bool thinlto_index_only = false;
Teresa Johnson1e2708c2016-07-22 18:20:22 +0000145 // If non-empty, holds the name of a file in which to write the list of
146 // oject files gold selected for inclusion in the link after symbol
147 // resolution (i.e. they had selected symbols). This will only be non-empty
148 // in the thinlto_index_only case. It is used to identify files, which may
149 // have originally been within archive libraries specified via
150 // --start-lib/--end-lib pairs, that should be included in the final
151 // native link process (since intervening function importing and inlining
152 // may change the symbol resolution detected in the final link and which
153 // files to include out of --start-lib/--end-lib libraries as a result).
154 static std::string thinlto_linked_objects_file;
Teresa Johnson8570fe42016-05-10 15:54:09 +0000155 // If true, when generating individual index files for distributed backends,
156 // also generate a "${bitcodefile}.imports" file at the same location for each
157 // bitcode file, listing the files it imports from in plain text. This is to
158 // support distributed build file staging.
159 static bool thinlto_emit_imports_files = false;
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000160 // Option to control where files for a distributed backend (the individual
161 // index files and optional imports files) are created.
162 // If specified, expects a string of the form "oldprefix:newprefix", and
163 // instead of generating these files in the same directory path as the
164 // corresponding bitcode file, will use a path formed by replacing the
165 // bitcode file's path prefix matching oldprefix with newprefix.
166 static std::string thinlto_prefix_replace;
Teresa Johnson57891a52016-08-24 15:11:47 +0000167 // Optional path to a directory for caching ThinLTO objects.
168 static std::string cache_dir;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000169 // Additional options to pass into the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +0000170 // Note: This array will contain all plugin options which are not claimed
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000171 // as plugin exclusive to pass to the code generator.
Rafael Espindola125b9242014-07-29 19:17:44 +0000172 static std::vector<const char *> extra;
Dehao Chen27978002016-12-16 16:48:46 +0000173 // Sample profile file path
174 static std::string sample_profile;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000175
Nick Lewycky7282dd72015-08-05 21:16:02 +0000176 static void process_plugin_option(const char *opt_)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000177 {
Rafael Espindola176e6642014-07-29 21:46:05 +0000178 if (opt_ == nullptr)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000179 return;
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000180 llvm::StringRef opt = opt_;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000181
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000182 if (opt.startswith("mcpu=")) {
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000183 mcpu = opt.substr(strlen("mcpu="));
Rafael Espindolaef498152010-06-23 20:20:59 +0000184 } else if (opt.startswith("extra-library-path=")) {
185 extra_library_path = opt.substr(strlen("extra_library_path="));
Rafael Espindola148c3282010-08-10 16:32:15 +0000186 } else if (opt.startswith("mtriple=")) {
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000187 triple = opt.substr(strlen("mtriple="));
Shuxin Yang1826ae22013-08-12 21:07:31 +0000188 } else if (opt.startswith("obj-path=")) {
189 obj_path = opt.substr(strlen("obj-path="));
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000190 } else if (opt == "emit-llvm") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000191 TheOutputType = OT_BC_ONLY;
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000192 } else if (opt == "save-temps") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000193 TheOutputType = OT_SAVE_TEMPS;
194 } else if (opt == "disable-output") {
195 TheOutputType = OT_DISABLE;
Teresa Johnson403a7872015-10-04 14:33:43 +0000196 } else if (opt == "thinlto") {
197 thinlto = true;
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000198 } else if (opt == "thinlto-index-only") {
199 thinlto_index_only = true;
Teresa Johnson1e2708c2016-07-22 18:20:22 +0000200 } else if (opt.startswith("thinlto-index-only=")) {
201 thinlto_index_only = true;
202 thinlto_linked_objects_file = opt.substr(strlen("thinlto-index-only="));
Teresa Johnson8570fe42016-05-10 15:54:09 +0000203 } else if (opt == "thinlto-emit-imports-files") {
204 thinlto_emit_imports_files = true;
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000205 } else if (opt.startswith("thinlto-prefix-replace=")) {
206 thinlto_prefix_replace = opt.substr(strlen("thinlto-prefix-replace="));
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000207 if (thinlto_prefix_replace.find(';') == std::string::npos)
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000208 message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");
Teresa Johnson57891a52016-08-24 15:11:47 +0000209 } else if (opt.startswith("cache-dir=")) {
210 cache_dir = opt.substr(strlen("cache-dir="));
Peter Collingbourne070843d2015-03-19 22:01:00 +0000211 } else if (opt.size() == 2 && opt[0] == 'O') {
212 if (opt[1] < '0' || opt[1] > '3')
Peter Collingbourne87202a42015-09-01 20:40:22 +0000213 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000214 OptLevel = opt[1] - '0';
Peter Collingbourne87202a42015-09-01 20:40:22 +0000215 } else if (opt.startswith("jobs=")) {
216 if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
217 message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
Teresa Johnson896fee22016-09-23 20:35:19 +0000218 } else if (opt.startswith("lto-partitions=")) {
219 if (opt.substr(strlen("lto-partitions="))
220 .getAsInteger(10, ParallelCodeGenParallelismLevel))
221 message(LDPL_FATAL, "Invalid codegen partition level: %s", opt_ + 5);
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000222 } else if (opt == "disable-verify") {
223 DisableVerify = true;
Dehao Chen27978002016-12-16 16:48:46 +0000224 } else if (opt.startswith("sample-profile=")) {
225 sample_profile= opt.substr(strlen("sample-profile="));
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000226 } else {
227 // Save this option to pass to the code generator.
Rafael Espindola33466a72014-08-21 20:28:55 +0000228 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
229 // add that.
230 if (extra.empty())
231 extra.push_back("LLVMgold");
232
Rafael Espindola125b9242014-07-29 19:17:44 +0000233 extra.push_back(opt_);
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000234 }
235 }
236}
237
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000238static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
239 int *claimed);
240static ld_plugin_status all_symbols_read_hook(void);
241static ld_plugin_status cleanup_hook(void);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000242
243extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
244ld_plugin_status onload(ld_plugin_tv *tv) {
Peter Collingbourne1505c0a2014-07-03 23:28:03 +0000245 InitializeAllTargetInfos();
246 InitializeAllTargets();
247 InitializeAllTargetMCs();
248 InitializeAllAsmParsers();
249 InitializeAllAsmPrinters();
250
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000251 // We're given a pointer to the first transfer vector. We read through them
252 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
253 // contain pointers to functions that we need to call to register our own
254 // hooks. The others are addresses of functions we can use to call into gold
255 // for services.
256
257 bool registeredClaimFile = false;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000258 bool RegisteredAllSymbolsRead = false;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000259
260 for (; tv->tv_tag != LDPT_NULL; ++tv) {
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000261 // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
262 // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
263 // header.
264 switch (static_cast<int>(tv->tv_tag)) {
265 case LDPT_OUTPUT_NAME:
266 output_name = tv->tv_u.tv_string;
267 break;
268 case LDPT_LINKER_OUTPUT:
269 switch (tv->tv_u.tv_val) {
270 case LDPO_REL: // .o
271 case LDPO_DYN: // .so
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000272 IsExecutable = false;
273 RelocationModel = Reloc::PIC_;
274 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000275 case LDPO_PIE: // position independent executable
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000276 IsExecutable = true;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000277 RelocationModel = Reloc::PIC_;
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000278 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000279 case LDPO_EXEC: // .exe
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000280 IsExecutable = true;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000281 RelocationModel = Reloc::Static;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000282 break;
283 default:
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000284 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
285 return LDPS_ERR;
286 }
287 break;
288 case LDPT_OPTION:
289 options::process_plugin_option(tv->tv_u.tv_string);
290 break;
291 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
292 ld_plugin_register_claim_file callback;
293 callback = tv->tv_u.tv_register_claim_file;
294
295 if (callback(claim_file_hook) != LDPS_OK)
296 return LDPS_ERR;
297
298 registeredClaimFile = true;
299 } break;
300 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
301 ld_plugin_register_all_symbols_read callback;
302 callback = tv->tv_u.tv_register_all_symbols_read;
303
304 if (callback(all_symbols_read_hook) != LDPS_OK)
305 return LDPS_ERR;
306
307 RegisteredAllSymbolsRead = true;
308 } break;
309 case LDPT_REGISTER_CLEANUP_HOOK: {
310 ld_plugin_register_cleanup callback;
311 callback = tv->tv_u.tv_register_cleanup;
312
313 if (callback(cleanup_hook) != LDPS_OK)
314 return LDPS_ERR;
315 } break;
316 case LDPT_GET_INPUT_FILE:
317 get_input_file = tv->tv_u.tv_get_input_file;
318 break;
319 case LDPT_RELEASE_INPUT_FILE:
320 release_input_file = tv->tv_u.tv_release_input_file;
321 break;
322 case LDPT_ADD_SYMBOLS:
323 add_symbols = tv->tv_u.tv_add_symbols;
324 break;
325 case LDPT_GET_SYMBOLS_V2:
326 // Do not override get_symbols_v3 with get_symbols_v2.
327 if (!get_symbols)
328 get_symbols = tv->tv_u.tv_get_symbols;
329 break;
330 case LDPT_GET_SYMBOLS_V3:
331 get_symbols = tv->tv_u.tv_get_symbols;
332 break;
333 case LDPT_ADD_INPUT_FILE:
334 add_input_file = tv->tv_u.tv_add_input_file;
335 break;
336 case LDPT_SET_EXTRA_LIBRARY_PATH:
337 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
338 break;
339 case LDPT_GET_VIEW:
340 get_view = tv->tv_u.tv_get_view;
341 break;
342 case LDPT_MESSAGE:
343 message = tv->tv_u.tv_message;
344 break;
345 default:
346 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000347 }
348 }
349
Rafael Espindolae08484d2009-02-18 08:30:15 +0000350 if (!registeredClaimFile) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000351 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000352 return LDPS_ERR;
353 }
Rafael Espindolae08484d2009-02-18 08:30:15 +0000354 if (!add_symbols) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000355 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000356 return LDPS_ERR;
357 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000358
Rafael Espindolaa0d30a92014-06-19 22:20:07 +0000359 if (!RegisteredAllSymbolsRead)
360 return LDPS_OK;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000361
Rafael Espindola33466a72014-08-21 20:28:55 +0000362 if (!get_input_file) {
363 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
364 return LDPS_ERR;
Rafael Espindolac273aac2014-06-19 22:54:47 +0000365 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000366 if (!release_input_file) {
Marianne Mailhot-Sarrasina5a750e2016-03-30 12:20:53 +0000367 message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
Rafael Espindola33466a72014-08-21 20:28:55 +0000368 return LDPS_ERR;
Tom Roederb5081192014-06-26 20:43:27 +0000369 }
370
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000371 return LDPS_OK;
372}
373
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000374static void diagnosticHandler(const DiagnosticInfo &DI) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000375 std::string ErrStorage;
376 {
377 raw_string_ostream OS(ErrStorage);
378 DiagnosticPrinterRawOStream DP(OS);
379 DI.print(DP);
380 }
Rafael Espindola503f8832015-03-02 19:08:03 +0000381 ld_plugin_level Level;
382 switch (DI.getSeverity()) {
383 case DS_Error:
384 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
385 ErrStorage.c_str());
Rafael Espindola503f8832015-03-02 19:08:03 +0000386 case DS_Warning:
387 Level = LDPL_WARNING;
388 break;
389 case DS_Note:
Rafael Espindolaf3f18542015-03-04 18:51:45 +0000390 case DS_Remark:
Rafael Espindola503f8832015-03-02 19:08:03 +0000391 Level = LDPL_INFO;
392 break;
Rafael Espindola503f8832015-03-02 19:08:03 +0000393 }
394 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000395}
396
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000397static void check(Error E, std::string Msg = "LLVM gold plugin") {
Mehdi Amini48f29602016-11-11 06:04:30 +0000398 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000399 message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());
400 return Error::success();
401 });
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000402}
403
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000404template <typename T> static T check(Expected<T> E) {
405 if (E)
406 return std::move(*E);
407 check(E.takeError());
408 return T();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000409}
410
Rafael Espindolae54d8212014-07-06 14:31:22 +0000411/// Called by gold to see whether this file is one that our plugin can handle.
412/// We'll try to open it and register all the symbols with add_symbol if
413/// possible.
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000414static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
415 int *claimed) {
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000416 MemoryBufferRef BufferRef;
417 std::unique_ptr<MemoryBuffer> Buffer;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000418 if (get_view) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000419 const void *view;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000420 if (get_view(file->handle, &view) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000421 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000422 return LDPS_ERR;
423 }
Nick Lewycky7282dd72015-08-05 21:16:02 +0000424 BufferRef =
425 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
Ivan Krasin5021af52011-09-12 21:47:50 +0000426 } else {
Ivan Krasin639222d2011-09-15 23:13:00 +0000427 int64_t offset = 0;
Nick Lewycky8691c472009-02-05 04:14:23 +0000428 // Gold has found what might be IR part-way inside of a file, such as
429 // an .a archive.
Ivan Krasin5021af52011-09-12 21:47:50 +0000430 if (file->offset) {
431 offset = file->offset;
432 }
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000433 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
434 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
435 offset);
436 if (std::error_code EC = BufferOrErr.getError()) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000437 message(LDPL_ERROR, EC.message().c_str());
Ivan Krasin5021af52011-09-12 21:47:50 +0000438 return LDPS_ERR;
439 }
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000440 Buffer = std::move(BufferOrErr.get());
441 BufferRef = Buffer->getMemBufferRef();
Rafael Espindola56e41f72011-02-08 22:40:47 +0000442 }
Ivan Krasin5021af52011-09-12 21:47:50 +0000443
Rafael Espindola6c472e52014-07-29 20:46:19 +0000444 *claimed = 1;
445
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000446 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
447 if (!ObjOrErr) {
448 handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {
449 std::error_code EC = EI.convertToErrorCode();
450 if (EC == object::object_error::invalid_file_type ||
451 EC == object::object_error::bitcode_section_not_found)
452 *claimed = 0;
453 else
454 message(LDPL_ERROR,
455 "LLVM gold plugin has failed to create LTO module: %s",
456 EI.message().c_str());
457 });
458
459 return *claimed ? LDPS_ERR : LDPS_OK;
Ivan Krasind5f2d8c2011-09-09 00:14:04 +0000460 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000461
462 std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000463
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000464 Modules.resize(Modules.size() + 1);
465 claimed_file &cf = Modules.back();
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000466
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000467 cf.handle = file->handle;
Teresa Johnson683abe72016-05-26 01:46:41 +0000468 // Keep track of the first handle for each file descriptor, since there are
469 // multiple in the case of an archive. This is used later in the case of
470 // ThinLTO parallel backends to ensure that each file is only opened and
471 // released once.
472 auto LeaderHandle =
473 FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
474 cf.leader_handle = LeaderHandle->second;
475 // Save the filesize since for parallel ThinLTO backends we can only
476 // invoke get_input_file once per archive (only for the leader handle).
477 cf.filesize = file->filesize;
478 // In the case of an archive library, all but the first member must have a
479 // non-zero offset, which we can append to the file name to obtain a
480 // unique name.
481 cf.name = file->name;
482 if (file->offset)
483 cf.name += ".llvm." + std::to_string(file->offset) + "." +
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000484 sys::path::filename(Obj->getSourceFileName()).str();
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000485
Rafael Espindola33466a72014-08-21 20:28:55 +0000486 for (auto &Sym : Obj->symbols()) {
487 uint32_t Symflags = Sym.getFlags();
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000488
489 cf.syms.push_back(ld_plugin_symbol());
490 ld_plugin_symbol &sym = cf.syms.back();
Rafael Espindola176e6642014-07-29 21:46:05 +0000491 sym.version = nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000492 StringRef Name = Sym.getName();
493 sym.name = strdup(Name.str().c_str());
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000494
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000495 ResolutionInfo &Res = ResInfo[Name];
Rafael Espindola33466a72014-08-21 20:28:55 +0000496
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000497 Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000498
Rafael Espindola33466a72014-08-21 20:28:55 +0000499 sym.visibility = LDPV_DEFAULT;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000500 GlobalValue::VisibilityTypes Vis = Sym.getVisibility();
501 if (Vis != GlobalValue::DefaultVisibility)
502 Res.DefaultVisibility = false;
503 switch (Vis) {
504 case GlobalValue::DefaultVisibility:
505 break;
506 case GlobalValue::HiddenVisibility:
507 sym.visibility = LDPV_HIDDEN;
508 break;
509 case GlobalValue::ProtectedVisibility:
510 sym.visibility = LDPV_PROTECTED;
511 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000512 }
513
Rafael Espindola33466a72014-08-21 20:28:55 +0000514 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
515 sym.def = LDPK_UNDEF;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000516 if (Symflags & object::BasicSymbolRef::SF_Weak)
Rafael Espindola56548522009-04-24 16:55:21 +0000517 sym.def = LDPK_WEAKUNDEF;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000518 } else if (Symflags & object::BasicSymbolRef::SF_Common)
519 sym.def = LDPK_COMMON;
520 else if (Symflags & object::BasicSymbolRef::SF_Weak)
521 sym.def = LDPK_WEAKDEF;
522 else
Rafael Espindola33466a72014-08-21 20:28:55 +0000523 sym.def = LDPK_DEF;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000524
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000525 sym.size = 0;
Rafael Espindola33466a72014-08-21 20:28:55 +0000526 sym.comdat_key = nullptr;
Rafael Espindola79121102016-10-25 12:02:03 +0000527 int CI = check(Sym.getComdatIndex());
528 if (CI != -1) {
529 StringRef C = Obj->getComdatTable()[CI];
Rafael Espindola62382c92016-10-17 18:51:02 +0000530 sym.comdat_key = strdup(C.str().c_str());
Rafael Espindola79121102016-10-25 12:02:03 +0000531 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000532
533 sym.resolution = LDPR_UNKNOWN;
534 }
535
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000536 if (!cf.syms.empty()) {
Nick Lewycky7282dd72015-08-05 21:16:02 +0000537 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000538 message(LDPL_ERROR, "Unable to add symbols!");
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000539 return LDPS_ERR;
540 }
541 }
542
543 return LDPS_OK;
544}
545
Rafael Espindola538c9a82014-12-23 18:18:37 +0000546static void freeSymName(ld_plugin_symbol &Sym) {
547 free(Sym.name);
548 free(Sym.comdat_key);
549 Sym.name = nullptr;
550 Sym.comdat_key = nullptr;
551}
552
Teresa Johnsona9f65552016-03-04 16:36:06 +0000553/// Helper to get a file's symbols and a view into it via gold callbacks.
554static const void *getSymbolsAndView(claimed_file &F) {
Benjamin Kramer39988a02016-03-08 14:02:46 +0000555 ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000556 if (status == LDPS_NO_SYMS)
557 return nullptr;
Teresa Johnson403a7872015-10-04 14:33:43 +0000558
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000559 if (status != LDPS_OK)
Teresa Johnson403a7872015-10-04 14:33:43 +0000560 message(LDPL_FATAL, "Failed to get symbol information");
561
562 const void *View;
563 if (get_view(F.handle, &View) != LDPS_OK)
564 message(LDPL_FATAL, "Failed to get a view of file");
565
Teresa Johnsona9f65552016-03-04 16:36:06 +0000566 return View;
567}
568
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000569static void addModule(LTO &Lto, claimed_file &F, const void *View) {
Teresa Johnson683abe72016-05-26 01:46:41 +0000570 MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize), F.name);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000571 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
Teresa Johnson6290dbc2015-11-21 21:55:48 +0000572
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000573 if (!ObjOrErr)
Peter Collingbourne10039c02014-09-18 21:28:49 +0000574 message(LDPL_FATAL, "Could not read bitcode from file : %s",
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000575 toString(ObjOrErr.takeError()).c_str());
Peter Collingbourne10039c02014-09-18 21:28:49 +0000576
Rafael Espindola527e8462014-12-09 16:13:59 +0000577 unsigned SymNum = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000578 std::vector<SymbolResolution> Resols(F.syms.size());
Peter Collingbourne07586442016-09-14 02:55:16 +0000579 for (ld_plugin_symbol &Sym : F.syms) {
580 SymbolResolution &R = Resols[SymNum++];
Rafael Espindola527e8462014-12-09 16:13:59 +0000581
Rafael Espindola33466a72014-08-21 20:28:55 +0000582 ld_plugin_symbol_resolution Resolution =
583 (ld_plugin_symbol_resolution)Sym.resolution;
584
Rafael Espindolacaabe222015-12-10 14:19:35 +0000585 ResolutionInfo &Res = ResInfo[Sym.name];
Rafael Espindola890db272014-09-09 20:08:22 +0000586
Rafael Espindola33466a72014-08-21 20:28:55 +0000587 switch (Resolution) {
588 case LDPR_UNKNOWN:
589 llvm_unreachable("Unexpected resolution");
590
591 case LDPR_RESOLVED_IR:
592 case LDPR_RESOLVED_EXEC:
593 case LDPR_RESOLVED_DYN:
Rafael Espindolacaabe222015-12-10 14:19:35 +0000594 case LDPR_PREEMPTED_IR:
595 case LDPR_PREEMPTED_REG:
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000596 case LDPR_UNDEF:
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000597 break;
598
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000599 case LDPR_PREVAILING_DEF_IRONLY:
600 R.Prevailing = true;
Rafael Espindola33466a72014-08-21 20:28:55 +0000601 break;
Teresa Johnsonf99573b2016-08-11 12:56:40 +0000602
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000603 case LDPR_PREVAILING_DEF:
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000604 R.Prevailing = true;
605 R.VisibleToRegularObj = true;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000606 break;
607
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000608 case LDPR_PREVAILING_DEF_IRONLY_EXP:
609 R.Prevailing = true;
610 if (!Res.CanOmitFromDynSym)
611 R.VisibleToRegularObj = true;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000612 break;
613 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000614
615 if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
616 (IsExecutable || !Res.DefaultVisibility))
617 R.FinalDefinitionInLinkageUnit = true;
618
Rafael Espindola538c9a82014-12-23 18:18:37 +0000619 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000620 }
621
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000622 check(Lto.add(std::move(*ObjOrErr), Resols),
623 std::string("Failed to link module ") + F.name);
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000624}
625
Teresa Johnsona9f65552016-03-04 16:36:06 +0000626static void recordFile(std::string Filename, bool TempOutFile) {
627 if (add_input_file(Filename.c_str()) != LDPS_OK)
628 message(LDPL_FATAL,
629 "Unable to add .o file to the link. File left behind in: %s",
630 Filename.c_str());
631 if (TempOutFile)
632 Cleanup.push_back(Filename.c_str());
633}
Rafael Espindola33466a72014-08-21 20:28:55 +0000634
Mehdi Amini970800e2016-08-17 06:23:09 +0000635/// Return the desired output filename given a base input name, a flag
636/// indicating whether a temp file should be generated, and an optional task id.
637/// The new filename generated is returned in \p NewFilename.
638static void getOutputFileName(SmallString<128> InFilename, bool TempOutFile,
Peter Collingbourne6201d782017-01-26 02:07:05 +0000639 SmallString<128> &NewFilename, int TaskID) {
Teresa Johnsona9f65552016-03-04 16:36:06 +0000640 if (TempOutFile) {
641 std::error_code EC =
Mehdi Amini970800e2016-08-17 06:23:09 +0000642 sys::fs::createTemporaryFile("lto-llvm", "o", NewFilename);
Teresa Johnsona9f65552016-03-04 16:36:06 +0000643 if (EC)
644 message(LDPL_FATAL, "Could not create temporary file: %s",
645 EC.message().c_str());
646 } else {
647 NewFilename = InFilename;
Peter Collingbourne6201d782017-01-26 02:07:05 +0000648 if (TaskID > 0)
Teresa Johnsona9f65552016-03-04 16:36:06 +0000649 NewFilename += utostr(TaskID);
Teresa Johnsona9f65552016-03-04 16:36:06 +0000650 }
Teresa Johnsona9f65552016-03-04 16:36:06 +0000651}
652
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000653static CodeGenOpt::Level getCGOptLevel() {
654 switch (options::OptLevel) {
655 case 0:
656 return CodeGenOpt::None;
657 case 1:
658 return CodeGenOpt::Less;
659 case 2:
660 return CodeGenOpt::Default;
661 case 3:
662 return CodeGenOpt::Aggressive;
663 }
664 llvm_unreachable("Invalid optimization level");
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000665}
666
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000667/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
668/// \p NewPrefix strings, if it was specified.
669static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
670 std::string &NewPrefix) {
671 StringRef PrefixReplace = options::thinlto_prefix_replace;
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000672 assert(PrefixReplace.empty() || PrefixReplace.find(";") != StringRef::npos);
673 std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000674 OldPrefix = Split.first.str();
675 NewPrefix = Split.second.str();
676}
677
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000678static std::unique_ptr<LTO> createLTO() {
679 Config Conf;
680 ThinBackend Backend;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000681
682 Conf.CPU = options::mcpu;
683 Conf.Options = InitTargetOptionsFromCodeGenFlags();
684
685 // Disable the new X86 relax relocations since gold might not support them.
686 // FIXME: Check the gold version or add a new option to enable them.
687 Conf.Options.RelaxELFRelocations = false;
688
689 Conf.MAttrs = MAttrs;
690 Conf.RelocModel = *RelocationModel;
691 Conf.CGOptLevel = getCGOptLevel();
692 Conf.DisableVerify = options::DisableVerify;
693 Conf.OptLevel = options::OptLevel;
Teresa Johnson896fee22016-09-23 20:35:19 +0000694 if (options::Parallelism)
695 Backend = createInProcessThinBackend(options::Parallelism);
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000696 if (options::thinlto_index_only) {
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000697 std::string OldPrefix, NewPrefix;
698 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000699 Backend = createWriteIndexesThinBackend(
700 OldPrefix, NewPrefix, options::thinlto_emit_imports_files,
701 options::thinlto_linked_objects_file);
Teresa Johnson84174c32016-05-10 13:48:23 +0000702 }
703
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000704 Conf.OverrideTriple = options::triple;
705 Conf.DefaultTriple = sys::getDefaultTargetTriple();
706
707 Conf.DiagHandler = diagnosticHandler;
708
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000709 switch (options::TheOutputType) {
710 case options::OT_NORMAL:
711 break;
712
713 case options::OT_DISABLE:
Mehdi Amini6ec23332016-08-22 16:41:58 +0000714 Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000715 break;
716
717 case options::OT_BC_ONLY:
Mehdi Amini6ec23332016-08-22 16:41:58 +0000718 Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000719 std::error_code EC;
720 raw_fd_ostream OS(output_name, EC, sys::fs::OpenFlags::F_None);
721 if (EC)
722 message(LDPL_FATAL, "Failed to write the output file.");
723 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ false);
724 return false;
725 };
726 break;
727
728 case options::OT_SAVE_TEMPS:
Mehdi Aminieccffad2016-08-18 00:12:33 +0000729 check(Conf.addSaveTemps(output_name + ".",
730 /* UseInputModulePath */ true));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000731 break;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000732 }
733
Dehao Chen27978002016-12-16 16:48:46 +0000734 if (!options::sample_profile.empty())
735 Conf.SampleProfile = options::sample_profile;
736
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000737 return llvm::make_unique<LTO>(std::move(Conf), Backend,
Teresa Johnson896fee22016-09-23 20:35:19 +0000738 options::ParallelCodeGenParallelismLevel);
Teresa Johnson84174c32016-05-10 13:48:23 +0000739}
740
Teresa Johnson3f212b82016-09-21 19:12:05 +0000741// Write empty files that may be expected by a distributed build
742// system when invoked with thinlto_index_only. This is invoked when
743// the linker has decided not to include the given module in the
744// final link. Frequently the distributed build system will want to
745// confirm that all expected outputs are created based on all of the
746// modules provided to the linker.
747static void writeEmptyDistributedBuildOutputs(std::string &ModulePath,
748 std::string &OldPrefix,
749 std::string &NewPrefix) {
750 std::string NewModulePath =
751 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
752 std::error_code EC;
753 {
754 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
755 sys::fs::OpenFlags::F_None);
756 if (EC)
757 message(LDPL_FATAL, "Failed to write '%s': %s",
758 (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
759 }
760 if (options::thinlto_emit_imports_files) {
761 raw_fd_ostream OS(NewModulePath + ".imports", EC,
762 sys::fs::OpenFlags::F_None);
763 if (EC)
764 message(LDPL_FATAL, "Failed to write '%s': %s",
765 (NewModulePath + ".imports").c_str(), EC.message().c_str());
766 }
767}
768
Rafael Espindolab6393292014-07-30 01:23:45 +0000769/// gold informs us that all symbols have been read. At this point, we use
770/// get_symbols to see if any of our definitions have been overridden by a
771/// native object file. Then, perform optimization and codegen.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000772static ld_plugin_status allSymbolsReadHook() {
Rafael Espindola33466a72014-08-21 20:28:55 +0000773 if (Modules.empty())
774 return LDPS_OK;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000775
Teresa Johnsona9f65552016-03-04 16:36:06 +0000776 if (unsigned NumOpts = options::extra.size())
777 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
778
Teresa Johnson765941a2016-08-20 01:24:07 +0000779 // Map to own RAII objects that manage the file opening and releasing
780 // interfaces with gold. This is needed only for ThinLTO mode, since
781 // unlike regular LTO, where addModule will result in the opened file
782 // being merged into a new combined module, we need to keep these files open
783 // through Lto->run().
784 DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
785
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000786 std::unique_ptr<LTO> Lto = createLTO();
Teresa Johnson403a7872015-10-04 14:33:43 +0000787
Teresa Johnson3f212b82016-09-21 19:12:05 +0000788 std::string OldPrefix, NewPrefix;
789 if (options::thinlto_index_only)
790 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
791
Rafael Espindolad2aac572014-07-30 01:52:40 +0000792 for (claimed_file &F : Modules) {
Teresa Johnson765941a2016-08-20 01:24:07 +0000793 if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
794 HandleToInputFile.insert(std::make_pair(
795 F.leader_handle, llvm::make_unique<PluginInputFile>(F.handle)));
Teresa Johnsona9f65552016-03-04 16:36:06 +0000796 const void *View = getSymbolsAndView(F);
Teresa Johnson3f212b82016-09-21 19:12:05 +0000797 if (!View) {
798 if (options::thinlto_index_only)
799 // Write empty output files that may be expected by the distributed
800 // build system.
801 writeEmptyDistributedBuildOutputs(F.name, OldPrefix, NewPrefix);
Evgeniy Stepanov4dc3c8d2016-03-11 00:51:57 +0000802 continue;
Teresa Johnson3f212b82016-09-21 19:12:05 +0000803 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000804 addModule(*Lto, F, View);
Rafael Espindola77b6d012010-06-14 21:20:52 +0000805 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000806
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000807 SmallString<128> Filename;
Mehdi Amini970800e2016-08-17 06:23:09 +0000808 // Note that getOutputFileName will append a unique ID for each task
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000809 if (!options::obj_path.empty())
810 Filename = options::obj_path;
811 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
812 Filename = output_name + ".o";
813 bool SaveTemps = !Filename.empty();
Rafael Espindola33466a72014-08-21 20:28:55 +0000814
Peter Collingbourne6201d782017-01-26 02:07:05 +0000815 size_t MaxTasks = Lto->getMaxTasks();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000816 std::vector<uintptr_t> IsTemporary(MaxTasks);
817 std::vector<SmallString<128>> Filenames(MaxTasks);
818
Peter Collingbourne80186a52016-09-23 21:33:43 +0000819 auto AddStream =
820 [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
821 IsTemporary[Task] = !SaveTemps;
822 getOutputFileName(Filename, /*TempOutFile=*/!SaveTemps, Filenames[Task],
Peter Collingbourne6201d782017-01-26 02:07:05 +0000823 Task);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000824 int FD;
825 std::error_code EC =
826 sys::fs::openFileForWrite(Filenames[Task], FD, sys::fs::F_None);
827 if (EC)
Peter Collingbourne5b8a1bd2017-01-25 03:35:28 +0000828 message(LDPL_FATAL, "Could not open file %s: %s", Filenames[Task].c_str(),
829 EC.message().c_str());
Peter Collingbourne80186a52016-09-23 21:33:43 +0000830 return llvm::make_unique<lto::NativeObjectStream>(
831 llvm::make_unique<llvm::raw_fd_ostream>(FD, true));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000832 };
833
Peter Collingbourne80186a52016-09-23 21:33:43 +0000834 auto AddFile = [&](size_t Task, StringRef Path) { Filenames[Task] = Path; };
835
836 NativeObjectCache Cache;
837 if (!options::cache_dir.empty())
838 Cache = localCache(options::cache_dir, AddFile);
839
840 check(Lto->run(AddStream, Cache));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000841
842 if (options::TheOutputType == options::OT_DISABLE ||
843 options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000844 return LDPS_OK;
845
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000846 if (options::thinlto_index_only) {
847 cleanup_hook();
848 exit(0);
Rafael Espindolaba3398b2010-05-13 13:39:31 +0000849 }
Rafael Espindola143fc3b2013-10-16 12:47:04 +0000850
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000851 for (unsigned I = 0; I != MaxTasks; ++I)
852 if (!Filenames[I].empty())
853 recordFile(Filenames[I].str(), IsTemporary[I]);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000854
Rafael Espindolaef498152010-06-23 20:20:59 +0000855 if (!options::extra_library_path.empty() &&
Rafael Espindola33466a72014-08-21 20:28:55 +0000856 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
857 message(LDPL_FATAL, "Unable to set the extra library path.");
Shuxin Yang1826ae22013-08-12 21:07:31 +0000858
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000859 return LDPS_OK;
860}
861
Rafael Espindola55b32542014-08-11 19:06:54 +0000862static ld_plugin_status all_symbols_read_hook(void) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000863 ld_plugin_status Ret = allSymbolsReadHook();
Rafael Espindola947bdb62014-11-25 20:52:49 +0000864 llvm_shutdown();
865
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000866 if (options::TheOutputType == options::OT_BC_ONLY ||
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000867 options::TheOutputType == options::OT_DISABLE) {
Davide Italiano289a43e2016-03-20 20:12:33 +0000868 if (options::TheOutputType == options::OT_DISABLE) {
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000869 // Remove the output file here since ld.bfd creates the output file
870 // early.
Davide Italiano289a43e2016-03-20 20:12:33 +0000871 std::error_code EC = sys::fs::remove(output_name);
872 if (EC)
873 message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
874 EC.message().c_str());
875 }
Rafael Espindola55b32542014-08-11 19:06:54 +0000876 exit(0);
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000877 }
Rafael Espindola55b32542014-08-11 19:06:54 +0000878
879 return Ret;
880}
881
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000882static ld_plugin_status cleanup_hook(void) {
Rafael Espindolad2aac572014-07-30 01:52:40 +0000883 for (std::string &Name : Cleanup) {
884 std::error_code EC = sys::fs::remove(Name);
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000885 if (EC)
Rafael Espindolad2aac572014-07-30 01:52:40 +0000886 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000887 EC.message().c_str());
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000888 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000889
890 return LDPS_OK;
891}