blob: 89a908aec50527dfca08521a76a0d69e8df5c859 [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
Rafael Espindola33466a72014-08-21 20:28:55 +000015#include "llvm/Bitcode/ReaderWriter.h"
Rafael Espindola6b244b12014-06-19 21:14:13 +000016#include "llvm/CodeGen/CommandFlags.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000017#include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
Rafael Espindola890db272014-09-09 20:08:22 +000018#include "llvm/IR/Constants.h"
Rafael Espindolad0b23be2015-01-10 00:07:30 +000019#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson57891a52016-08-24 15:11:47 +000020#include "llvm/LTO/Caching.h"
Teresa Johnson683abe72016-05-26 01:46:41 +000021#include "llvm/LTO/LTO.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000022#include "llvm/Support/CommandLine.h"
Rafael Espindola947bdb62014-11-25 20:52:49 +000023#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000024#include "llvm/Support/MemoryBuffer.h"
Teresa Johnsonbbd10b42016-05-17 14:45:30 +000025#include "llvm/Support/Path.h"
Rafael Espindola6b244b12014-06-19 21:14:13 +000026#include "llvm/Support/TargetSelect.h"
Teresa Johnsonb13dbd62015-12-09 19:45:55 +000027#include "llvm/Support/raw_ostream.h"
Nick Lewyckyfb643e42009-02-03 07:13:24 +000028#include <list>
Teresa Johnson9ba95f92016-08-11 14:58:12 +000029#include <map>
Chandler Carruth07baed52014-01-13 08:04:33 +000030#include <plugin-api.h>
Teresa Johnson9ba95f92016-08-11 14:58:12 +000031#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000032#include <system_error>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000033#include <utility>
Nick Lewyckyfb643e42009-02-03 07:13:24 +000034#include <vector>
35
Sylvestre Ledru53999792014-02-11 17:30:18 +000036// FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
37// Precise and Debian Wheezy (binutils 2.23 is required)
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +000038#define LDPO_PIE 3
39
40#define LDPT_GET_SYMBOLS_V3 28
Sylvestre Ledru53999792014-02-11 17:30:18 +000041
Nick Lewyckyfb643e42009-02-03 07:13:24 +000042using namespace llvm;
Teresa Johnson9ba95f92016-08-11 14:58:12 +000043using namespace lto;
Nick Lewyckyfb643e42009-02-03 07:13:24 +000044
Teresa Johnsoncb15b732015-12-16 16:34:06 +000045static ld_plugin_status discard_message(int level, const char *format, ...) {
46 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
47 // callback in the transfer vector. This should never be called.
48 abort();
49}
50
51static ld_plugin_release_input_file release_input_file = nullptr;
52static ld_plugin_get_input_file get_input_file = nullptr;
53static ld_plugin_message message = discard_message;
54
Nick Lewyckyfb643e42009-02-03 07:13:24 +000055namespace {
Rafael Espindolabfb8b912014-06-20 01:37:35 +000056struct claimed_file {
57 void *handle;
Teresa Johnson683abe72016-05-26 01:46:41 +000058 void *leader_handle;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000059 std::vector<ld_plugin_symbol> syms;
Teresa Johnson683abe72016-05-26 01:46:41 +000060 off_t filesize;
61 std::string name;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000062};
Rafael Espindolacaabe222015-12-10 14:19:35 +000063
Teresa Johnsoncb15b732015-12-16 16:34:06 +000064/// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
65struct PluginInputFile {
Teresa Johnson031bed22015-12-16 21:37:48 +000066 void *Handle;
Teresa Johnson7cffaf32016-03-04 17:06:02 +000067 std::unique_ptr<ld_plugin_input_file> File;
Teresa Johnsoncb15b732015-12-16 16:34:06 +000068
Teresa Johnson031bed22015-12-16 21:37:48 +000069 PluginInputFile(void *Handle) : Handle(Handle) {
Teresa Johnson7cffaf32016-03-04 17:06:02 +000070 File = llvm::make_unique<ld_plugin_input_file>();
71 if (get_input_file(Handle, File.get()) != LDPS_OK)
Teresa Johnsoncb15b732015-12-16 16:34:06 +000072 message(LDPL_FATAL, "Failed to get file information");
73 }
74 ~PluginInputFile() {
Teresa Johnson7cffaf32016-03-04 17:06:02 +000075 // File would have been reset to nullptr if we moved this object
76 // to a new owner.
77 if (File)
78 if (release_input_file(Handle) != LDPS_OK)
79 message(LDPL_FATAL, "Failed to release file information");
Teresa Johnsoncb15b732015-12-16 16:34:06 +000080 }
Teresa Johnson7cffaf32016-03-04 17:06:02 +000081
82 ld_plugin_input_file &file() { return *File; }
83
84 PluginInputFile(PluginInputFile &&RHS) = default;
85 PluginInputFile &operator=(PluginInputFile &&RHS) = default;
Teresa Johnsoncb15b732015-12-16 16:34:06 +000086};
87
Rafael Espindolacaabe222015-12-10 14:19:35 +000088struct ResolutionInfo {
Teresa Johnson9ba95f92016-08-11 14:58:12 +000089 bool CanOmitFromDynSym = true;
90 bool DefaultVisibility = true;
Rafael Espindolacaabe222015-12-10 14:19:35 +000091};
Teresa Johnson7cffaf32016-03-04 17:06:02 +000092
Nick Lewyckyfb643e42009-02-03 07:13:24 +000093}
Rafael Espindolabfb8b912014-06-20 01:37:35 +000094
Rafael Espindola176e6642014-07-29 21:46:05 +000095static ld_plugin_add_symbols add_symbols = nullptr;
96static ld_plugin_get_symbols get_symbols = nullptr;
97static ld_plugin_add_input_file add_input_file = nullptr;
98static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
99static ld_plugin_get_view get_view = nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000100static bool IsExecutable = false;
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000101static Optional<Reloc::Model> RelocationModel;
Rafael Espindolabfb8b912014-06-20 01:37:35 +0000102static std::string output_name = "";
103static std::list<claimed_file> Modules;
Teresa Johnson683abe72016-05-26 01:46:41 +0000104static DenseMap<int, void *> FDToLeaderHandle;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000105static StringMap<ResolutionInfo> ResInfo;
Rafael Espindolabfb8b912014-06-20 01:37:35 +0000106static std::vector<std::string> Cleanup;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000107static llvm::TargetOptions TargetOpts;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000108static size_t MaxTasks;
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 Johnson7cffaf32016-03-04 17:06:02 +0000121 // Currently, code generation defaults to no parallelism, whereas
122 // ThinLTO uses the hardware_concurrency as the default.
Teresa Johnsona9f65552016-03-04 16:36:06 +0000123 static unsigned Parallelism = 0;
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000124#ifdef NDEBUG
125 static bool DisableVerify = true;
126#else
127 static bool DisableVerify = false;
128#endif
Shuxin Yang1826ae22013-08-12 21:07:31 +0000129 static std::string obj_path;
Rafael Espindolaef498152010-06-23 20:20:59 +0000130 static std::string extra_library_path;
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000131 static std::string triple;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000132 static std::string mcpu;
Teresa Johnson403a7872015-10-04 14:33:43 +0000133 // When the thinlto plugin option is specified, only read the function
134 // the information from intermediate files and write a combined
135 // global index for the ThinLTO backends.
136 static bool thinlto = false;
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000137 // If false, all ThinLTO backend compilations through code gen are performed
138 // using multiple threads in the gold-plugin, before handing control back to
Teresa Johnson84174c32016-05-10 13:48:23 +0000139 // gold. If true, write individual backend index files which reflect
140 // the import decisions, and exit afterwards. The assumption is
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000141 // that the build system will launch the backend processes.
142 static bool thinlto_index_only = false;
Teresa Johnson1e2708c2016-07-22 18:20:22 +0000143 // If non-empty, holds the name of a file in which to write the list of
144 // oject files gold selected for inclusion in the link after symbol
145 // resolution (i.e. they had selected symbols). This will only be non-empty
146 // in the thinlto_index_only case. It is used to identify files, which may
147 // have originally been within archive libraries specified via
148 // --start-lib/--end-lib pairs, that should be included in the final
149 // native link process (since intervening function importing and inlining
150 // may change the symbol resolution detected in the final link and which
151 // files to include out of --start-lib/--end-lib libraries as a result).
152 static std::string thinlto_linked_objects_file;
Teresa Johnson8570fe42016-05-10 15:54:09 +0000153 // If true, when generating individual index files for distributed backends,
154 // also generate a "${bitcodefile}.imports" file at the same location for each
155 // bitcode file, listing the files it imports from in plain text. This is to
156 // support distributed build file staging.
157 static bool thinlto_emit_imports_files = false;
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000158 // Option to control where files for a distributed backend (the individual
159 // index files and optional imports files) are created.
160 // If specified, expects a string of the form "oldprefix:newprefix", and
161 // instead of generating these files in the same directory path as the
162 // corresponding bitcode file, will use a path formed by replacing the
163 // bitcode file's path prefix matching oldprefix with newprefix.
164 static std::string thinlto_prefix_replace;
Teresa Johnson57891a52016-08-24 15:11:47 +0000165 // Optional path to a directory for caching ThinLTO objects.
166 static std::string cache_dir;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000167 // Additional options to pass into the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +0000168 // Note: This array will contain all plugin options which are not claimed
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000169 // as plugin exclusive to pass to the code generator.
Rafael Espindola125b9242014-07-29 19:17:44 +0000170 static std::vector<const char *> extra;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000171
Nick Lewycky7282dd72015-08-05 21:16:02 +0000172 static void process_plugin_option(const char *opt_)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000173 {
Rafael Espindola176e6642014-07-29 21:46:05 +0000174 if (opt_ == nullptr)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000175 return;
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000176 llvm::StringRef opt = opt_;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000177
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000178 if (opt.startswith("mcpu=")) {
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000179 mcpu = opt.substr(strlen("mcpu="));
Rafael Espindolaef498152010-06-23 20:20:59 +0000180 } else if (opt.startswith("extra-library-path=")) {
181 extra_library_path = opt.substr(strlen("extra_library_path="));
Rafael Espindola148c3282010-08-10 16:32:15 +0000182 } else if (opt.startswith("mtriple=")) {
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000183 triple = opt.substr(strlen("mtriple="));
Shuxin Yang1826ae22013-08-12 21:07:31 +0000184 } else if (opt.startswith("obj-path=")) {
185 obj_path = opt.substr(strlen("obj-path="));
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000186 } else if (opt == "emit-llvm") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000187 TheOutputType = OT_BC_ONLY;
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000188 } else if (opt == "save-temps") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000189 TheOutputType = OT_SAVE_TEMPS;
190 } else if (opt == "disable-output") {
191 TheOutputType = OT_DISABLE;
Teresa Johnson403a7872015-10-04 14:33:43 +0000192 } else if (opt == "thinlto") {
193 thinlto = true;
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000194 } else if (opt == "thinlto-index-only") {
195 thinlto_index_only = true;
Teresa Johnson1e2708c2016-07-22 18:20:22 +0000196 } else if (opt.startswith("thinlto-index-only=")) {
197 thinlto_index_only = true;
198 thinlto_linked_objects_file = opt.substr(strlen("thinlto-index-only="));
Teresa Johnson8570fe42016-05-10 15:54:09 +0000199 } else if (opt == "thinlto-emit-imports-files") {
200 thinlto_emit_imports_files = true;
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000201 } else if (opt.startswith("thinlto-prefix-replace=")) {
202 thinlto_prefix_replace = opt.substr(strlen("thinlto-prefix-replace="));
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000203 if (thinlto_prefix_replace.find(";") == std::string::npos)
204 message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");
Teresa Johnson57891a52016-08-24 15:11:47 +0000205 } else if (opt.startswith("cache-dir=")) {
206 cache_dir = opt.substr(strlen("cache-dir="));
Peter Collingbourne070843d2015-03-19 22:01:00 +0000207 } else if (opt.size() == 2 && opt[0] == 'O') {
208 if (opt[1] < '0' || opt[1] > '3')
Peter Collingbourne87202a42015-09-01 20:40:22 +0000209 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000210 OptLevel = opt[1] - '0';
Peter Collingbourne87202a42015-09-01 20:40:22 +0000211 } else if (opt.startswith("jobs=")) {
212 if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
213 message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000214 } else if (opt == "disable-verify") {
215 DisableVerify = true;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000216 } else {
217 // Save this option to pass to the code generator.
Rafael Espindola33466a72014-08-21 20:28:55 +0000218 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
219 // add that.
220 if (extra.empty())
221 extra.push_back("LLVMgold");
222
Rafael Espindola125b9242014-07-29 19:17:44 +0000223 extra.push_back(opt_);
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000224 }
225 }
226}
227
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000228static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
229 int *claimed);
230static ld_plugin_status all_symbols_read_hook(void);
231static ld_plugin_status cleanup_hook(void);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000232
233extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
234ld_plugin_status onload(ld_plugin_tv *tv) {
Peter Collingbourne1505c0a2014-07-03 23:28:03 +0000235 InitializeAllTargetInfos();
236 InitializeAllTargets();
237 InitializeAllTargetMCs();
238 InitializeAllAsmParsers();
239 InitializeAllAsmPrinters();
240
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000241 // We're given a pointer to the first transfer vector. We read through them
242 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
243 // contain pointers to functions that we need to call to register our own
244 // hooks. The others are addresses of functions we can use to call into gold
245 // for services.
246
247 bool registeredClaimFile = false;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000248 bool RegisteredAllSymbolsRead = false;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000249
250 for (; tv->tv_tag != LDPT_NULL; ++tv) {
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000251 // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
252 // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
253 // header.
254 switch (static_cast<int>(tv->tv_tag)) {
255 case LDPT_OUTPUT_NAME:
256 output_name = tv->tv_u.tv_string;
257 break;
258 case LDPT_LINKER_OUTPUT:
259 switch (tv->tv_u.tv_val) {
260 case LDPO_REL: // .o
261 case LDPO_DYN: // .so
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000262 IsExecutable = false;
263 RelocationModel = Reloc::PIC_;
264 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000265 case LDPO_PIE: // position independent executable
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000266 IsExecutable = true;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000267 RelocationModel = Reloc::PIC_;
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000268 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000269 case LDPO_EXEC: // .exe
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000270 IsExecutable = true;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000271 RelocationModel = Reloc::Static;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000272 break;
273 default:
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000274 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
275 return LDPS_ERR;
276 }
277 break;
278 case LDPT_OPTION:
279 options::process_plugin_option(tv->tv_u.tv_string);
280 break;
281 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
282 ld_plugin_register_claim_file callback;
283 callback = tv->tv_u.tv_register_claim_file;
284
285 if (callback(claim_file_hook) != LDPS_OK)
286 return LDPS_ERR;
287
288 registeredClaimFile = true;
289 } break;
290 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
291 ld_plugin_register_all_symbols_read callback;
292 callback = tv->tv_u.tv_register_all_symbols_read;
293
294 if (callback(all_symbols_read_hook) != LDPS_OK)
295 return LDPS_ERR;
296
297 RegisteredAllSymbolsRead = true;
298 } break;
299 case LDPT_REGISTER_CLEANUP_HOOK: {
300 ld_plugin_register_cleanup callback;
301 callback = tv->tv_u.tv_register_cleanup;
302
303 if (callback(cleanup_hook) != LDPS_OK)
304 return LDPS_ERR;
305 } break;
306 case LDPT_GET_INPUT_FILE:
307 get_input_file = tv->tv_u.tv_get_input_file;
308 break;
309 case LDPT_RELEASE_INPUT_FILE:
310 release_input_file = tv->tv_u.tv_release_input_file;
311 break;
312 case LDPT_ADD_SYMBOLS:
313 add_symbols = tv->tv_u.tv_add_symbols;
314 break;
315 case LDPT_GET_SYMBOLS_V2:
316 // Do not override get_symbols_v3 with get_symbols_v2.
317 if (!get_symbols)
318 get_symbols = tv->tv_u.tv_get_symbols;
319 break;
320 case LDPT_GET_SYMBOLS_V3:
321 get_symbols = tv->tv_u.tv_get_symbols;
322 break;
323 case LDPT_ADD_INPUT_FILE:
324 add_input_file = tv->tv_u.tv_add_input_file;
325 break;
326 case LDPT_SET_EXTRA_LIBRARY_PATH:
327 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
328 break;
329 case LDPT_GET_VIEW:
330 get_view = tv->tv_u.tv_get_view;
331 break;
332 case LDPT_MESSAGE:
333 message = tv->tv_u.tv_message;
334 break;
335 default:
336 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000337 }
338 }
339
Rafael Espindolae08484d2009-02-18 08:30:15 +0000340 if (!registeredClaimFile) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000341 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000342 return LDPS_ERR;
343 }
Rafael Espindolae08484d2009-02-18 08:30:15 +0000344 if (!add_symbols) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000345 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000346 return LDPS_ERR;
347 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000348
Rafael Espindolaa0d30a92014-06-19 22:20:07 +0000349 if (!RegisteredAllSymbolsRead)
350 return LDPS_OK;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000351
Rafael Espindola33466a72014-08-21 20:28:55 +0000352 if (!get_input_file) {
353 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
354 return LDPS_ERR;
Rafael Espindolac273aac2014-06-19 22:54:47 +0000355 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000356 if (!release_input_file) {
Marianne Mailhot-Sarrasina5a750e2016-03-30 12:20:53 +0000357 message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
Rafael Espindola33466a72014-08-21 20:28:55 +0000358 return LDPS_ERR;
Tom Roederb5081192014-06-26 20:43:27 +0000359 }
360
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000361 return LDPS_OK;
362}
363
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000364static void diagnosticHandler(const DiagnosticInfo &DI) {
Rafael Espindola503f8832015-03-02 19:08:03 +0000365 if (const auto *BDI = dyn_cast<BitcodeDiagnosticInfo>(&DI)) {
366 std::error_code EC = BDI->getError();
367 if (EC == BitcodeError::InvalidBitcodeSignature)
368 return;
369 }
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000370
371 std::string ErrStorage;
372 {
373 raw_string_ostream OS(ErrStorage);
374 DiagnosticPrinterRawOStream DP(OS);
375 DI.print(DP);
376 }
Rafael Espindola503f8832015-03-02 19:08:03 +0000377 ld_plugin_level Level;
378 switch (DI.getSeverity()) {
379 case DS_Error:
380 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
381 ErrStorage.c_str());
Rafael Espindola503f8832015-03-02 19:08:03 +0000382 case DS_Warning:
383 Level = LDPL_WARNING;
384 break;
385 case DS_Note:
Rafael Espindolaf3f18542015-03-04 18:51:45 +0000386 case DS_Remark:
Rafael Espindola503f8832015-03-02 19:08:03 +0000387 Level = LDPL_INFO;
388 break;
Rafael Espindola503f8832015-03-02 19:08:03 +0000389 }
390 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000391}
392
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000393static void check(Error E, std::string Msg = "LLVM gold plugin") {
394 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
395 message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());
396 return Error::success();
397 });
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000398}
399
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000400template <typename T> static T check(Expected<T> E) {
401 if (E)
402 return std::move(*E);
403 check(E.takeError());
404 return T();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000405}
406
Rafael Espindolae54d8212014-07-06 14:31:22 +0000407/// Called by gold to see whether this file is one that our plugin can handle.
408/// We'll try to open it and register all the symbols with add_symbol if
409/// possible.
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000410static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
411 int *claimed) {
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000412 MemoryBufferRef BufferRef;
413 std::unique_ptr<MemoryBuffer> Buffer;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000414 if (get_view) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000415 const void *view;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000416 if (get_view(file->handle, &view) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000417 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000418 return LDPS_ERR;
419 }
Nick Lewycky7282dd72015-08-05 21:16:02 +0000420 BufferRef =
421 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
Ivan Krasin5021af52011-09-12 21:47:50 +0000422 } else {
Ivan Krasin639222d2011-09-15 23:13:00 +0000423 int64_t offset = 0;
Nick Lewycky8691c472009-02-05 04:14:23 +0000424 // Gold has found what might be IR part-way inside of a file, such as
425 // an .a archive.
Ivan Krasin5021af52011-09-12 21:47:50 +0000426 if (file->offset) {
427 offset = file->offset;
428 }
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000429 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
430 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
431 offset);
432 if (std::error_code EC = BufferOrErr.getError()) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000433 message(LDPL_ERROR, EC.message().c_str());
Ivan Krasin5021af52011-09-12 21:47:50 +0000434 return LDPS_ERR;
435 }
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000436 Buffer = std::move(BufferOrErr.get());
437 BufferRef = Buffer->getMemBufferRef();
Rafael Espindola56e41f72011-02-08 22:40:47 +0000438 }
Ivan Krasin5021af52011-09-12 21:47:50 +0000439
Rafael Espindola6c472e52014-07-29 20:46:19 +0000440 *claimed = 1;
441
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000442 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
443 if (!ObjOrErr) {
444 handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {
445 std::error_code EC = EI.convertToErrorCode();
446 if (EC == object::object_error::invalid_file_type ||
447 EC == object::object_error::bitcode_section_not_found)
448 *claimed = 0;
449 else
450 message(LDPL_ERROR,
451 "LLVM gold plugin has failed to create LTO module: %s",
452 EI.message().c_str());
453 });
454
455 return *claimed ? LDPS_ERR : LDPS_OK;
Ivan Krasind5f2d8c2011-09-09 00:14:04 +0000456 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000457
458 std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000459
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000460 Modules.resize(Modules.size() + 1);
461 claimed_file &cf = Modules.back();
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000462
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000463 cf.handle = file->handle;
Teresa Johnson683abe72016-05-26 01:46:41 +0000464 // Keep track of the first handle for each file descriptor, since there are
465 // multiple in the case of an archive. This is used later in the case of
466 // ThinLTO parallel backends to ensure that each file is only opened and
467 // released once.
468 auto LeaderHandle =
469 FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
470 cf.leader_handle = LeaderHandle->second;
471 // Save the filesize since for parallel ThinLTO backends we can only
472 // invoke get_input_file once per archive (only for the leader handle).
473 cf.filesize = file->filesize;
474 // In the case of an archive library, all but the first member must have a
475 // non-zero offset, which we can append to the file name to obtain a
476 // unique name.
477 cf.name = file->name;
478 if (file->offset)
479 cf.name += ".llvm." + std::to_string(file->offset) + "." +
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000480 sys::path::filename(Obj->getSourceFileName()).str();
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000481
Rafael Espindola33466a72014-08-21 20:28:55 +0000482 for (auto &Sym : Obj->symbols()) {
483 uint32_t Symflags = Sym.getFlags();
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000484
485 cf.syms.push_back(ld_plugin_symbol());
486 ld_plugin_symbol &sym = cf.syms.back();
Rafael Espindola176e6642014-07-29 21:46:05 +0000487 sym.version = nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000488 StringRef Name = Sym.getName();
489 sym.name = strdup(Name.str().c_str());
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000490
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000491 ResolutionInfo &Res = ResInfo[Name];
Rafael Espindola33466a72014-08-21 20:28:55 +0000492
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000493 Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000494
Rafael Espindola33466a72014-08-21 20:28:55 +0000495 sym.visibility = LDPV_DEFAULT;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000496 GlobalValue::VisibilityTypes Vis = Sym.getVisibility();
497 if (Vis != GlobalValue::DefaultVisibility)
498 Res.DefaultVisibility = false;
499 switch (Vis) {
500 case GlobalValue::DefaultVisibility:
501 break;
502 case GlobalValue::HiddenVisibility:
503 sym.visibility = LDPV_HIDDEN;
504 break;
505 case GlobalValue::ProtectedVisibility:
506 sym.visibility = LDPV_PROTECTED;
507 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000508 }
509
Rafael Espindola33466a72014-08-21 20:28:55 +0000510 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
511 sym.def = LDPK_UNDEF;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000512 if (Symflags & object::BasicSymbolRef::SF_Weak)
Rafael Espindola56548522009-04-24 16:55:21 +0000513 sym.def = LDPK_WEAKUNDEF;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000514 } else if (Symflags & object::BasicSymbolRef::SF_Common)
515 sym.def = LDPK_COMMON;
516 else if (Symflags & object::BasicSymbolRef::SF_Weak)
517 sym.def = LDPK_WEAKDEF;
518 else
Rafael Espindola33466a72014-08-21 20:28:55 +0000519 sym.def = LDPK_DEF;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000520
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000521 sym.size = 0;
Rafael Espindola33466a72014-08-21 20:28:55 +0000522 sym.comdat_key = nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000523 const Comdat *C = check(Sym.getComdat());
524 if (C)
525 sym.comdat_key = strdup(C->getName().str().c_str());
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000526
527 sym.resolution = LDPR_UNKNOWN;
528 }
529
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000530 if (!cf.syms.empty()) {
Nick Lewycky7282dd72015-08-05 21:16:02 +0000531 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000532 message(LDPL_ERROR, "Unable to add symbols!");
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000533 return LDPS_ERR;
534 }
535 }
536
537 return LDPS_OK;
538}
539
Rafael Espindola538c9a82014-12-23 18:18:37 +0000540static void freeSymName(ld_plugin_symbol &Sym) {
541 free(Sym.name);
542 free(Sym.comdat_key);
543 Sym.name = nullptr;
544 Sym.comdat_key = nullptr;
545}
546
Teresa Johnsona9f65552016-03-04 16:36:06 +0000547/// Helper to get a file's symbols and a view into it via gold callbacks.
548static const void *getSymbolsAndView(claimed_file &F) {
Benjamin Kramer39988a02016-03-08 14:02:46 +0000549 ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000550 if (status == LDPS_NO_SYMS)
551 return nullptr;
Teresa Johnson403a7872015-10-04 14:33:43 +0000552
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000553 if (status != LDPS_OK)
Teresa Johnson403a7872015-10-04 14:33:43 +0000554 message(LDPL_FATAL, "Failed to get symbol information");
555
556 const void *View;
557 if (get_view(F.handle, &View) != LDPS_OK)
558 message(LDPL_FATAL, "Failed to get a view of file");
559
Teresa Johnsona9f65552016-03-04 16:36:06 +0000560 return View;
561}
562
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000563static void addModule(LTO &Lto, claimed_file &F, const void *View) {
Teresa Johnson683abe72016-05-26 01:46:41 +0000564 MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize), F.name);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000565 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
Teresa Johnson6290dbc2015-11-21 21:55:48 +0000566
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000567 if (!ObjOrErr)
Peter Collingbourne10039c02014-09-18 21:28:49 +0000568 message(LDPL_FATAL, "Could not read bitcode from file : %s",
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000569 toString(ObjOrErr.takeError()).c_str());
Peter Collingbourne10039c02014-09-18 21:28:49 +0000570
Rafael Espindola527e8462014-12-09 16:13:59 +0000571 unsigned SymNum = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000572 std::vector<SymbolResolution> Resols(F.syms.size());
Peter Collingbourne07586442016-09-14 02:55:16 +0000573 for (ld_plugin_symbol &Sym : F.syms) {
574 SymbolResolution &R = Resols[SymNum++];
Rafael Espindola527e8462014-12-09 16:13:59 +0000575
Rafael Espindola33466a72014-08-21 20:28:55 +0000576 ld_plugin_symbol_resolution Resolution =
577 (ld_plugin_symbol_resolution)Sym.resolution;
578
Rafael Espindolacaabe222015-12-10 14:19:35 +0000579 ResolutionInfo &Res = ResInfo[Sym.name];
Rafael Espindola890db272014-09-09 20:08:22 +0000580
Rafael Espindola33466a72014-08-21 20:28:55 +0000581 switch (Resolution) {
582 case LDPR_UNKNOWN:
583 llvm_unreachable("Unexpected resolution");
584
585 case LDPR_RESOLVED_IR:
586 case LDPR_RESOLVED_EXEC:
587 case LDPR_RESOLVED_DYN:
Rafael Espindolacaabe222015-12-10 14:19:35 +0000588 case LDPR_PREEMPTED_IR:
589 case LDPR_PREEMPTED_REG:
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000590 case LDPR_UNDEF:
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000591 break;
592
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000593 case LDPR_PREVAILING_DEF_IRONLY:
594 R.Prevailing = true;
Rafael Espindola33466a72014-08-21 20:28:55 +0000595 break;
Teresa Johnsonf99573b2016-08-11 12:56:40 +0000596
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000597 case LDPR_PREVAILING_DEF:
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000598 R.Prevailing = true;
599 R.VisibleToRegularObj = true;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000600 break;
601
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000602 case LDPR_PREVAILING_DEF_IRONLY_EXP:
603 R.Prevailing = true;
604 if (!Res.CanOmitFromDynSym)
605 R.VisibleToRegularObj = true;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000606 break;
607 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000608
609 if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
610 (IsExecutable || !Res.DefaultVisibility))
611 R.FinalDefinitionInLinkageUnit = true;
612
Rafael Espindola538c9a82014-12-23 18:18:37 +0000613 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000614 }
615
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000616 check(Lto.add(std::move(*ObjOrErr), Resols),
617 std::string("Failed to link module ") + F.name);
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000618}
619
Teresa Johnsona9f65552016-03-04 16:36:06 +0000620static void recordFile(std::string Filename, bool TempOutFile) {
621 if (add_input_file(Filename.c_str()) != LDPS_OK)
622 message(LDPL_FATAL,
623 "Unable to add .o file to the link. File left behind in: %s",
624 Filename.c_str());
625 if (TempOutFile)
626 Cleanup.push_back(Filename.c_str());
627}
Rafael Espindola33466a72014-08-21 20:28:55 +0000628
Mehdi Amini970800e2016-08-17 06:23:09 +0000629/// Return the desired output filename given a base input name, a flag
630/// indicating whether a temp file should be generated, and an optional task id.
631/// The new filename generated is returned in \p NewFilename.
632static void getOutputFileName(SmallString<128> InFilename, bool TempOutFile,
633 SmallString<128> &NewFilename, int TaskID = -1) {
Teresa Johnsona9f65552016-03-04 16:36:06 +0000634 if (TempOutFile) {
635 std::error_code EC =
Mehdi Amini970800e2016-08-17 06:23:09 +0000636 sys::fs::createTemporaryFile("lto-llvm", "o", NewFilename);
Teresa Johnsona9f65552016-03-04 16:36:06 +0000637 if (EC)
638 message(LDPL_FATAL, "Could not create temporary file: %s",
639 EC.message().c_str());
640 } else {
641 NewFilename = InFilename;
642 if (TaskID >= 0)
643 NewFilename += utostr(TaskID);
Teresa Johnsona9f65552016-03-04 16:36:06 +0000644 }
Teresa Johnsona9f65552016-03-04 16:36:06 +0000645}
646
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000647static CodeGenOpt::Level getCGOptLevel() {
648 switch (options::OptLevel) {
649 case 0:
650 return CodeGenOpt::None;
651 case 1:
652 return CodeGenOpt::Less;
653 case 2:
654 return CodeGenOpt::Default;
655 case 3:
656 return CodeGenOpt::Aggressive;
657 }
658 llvm_unreachable("Invalid optimization level");
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000659}
660
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000661/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
662/// \p NewPrefix strings, if it was specified.
663static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
664 std::string &NewPrefix) {
665 StringRef PrefixReplace = options::thinlto_prefix_replace;
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000666 assert(PrefixReplace.empty() || PrefixReplace.find(";") != StringRef::npos);
667 std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000668 OldPrefix = Split.first.str();
669 NewPrefix = Split.second.str();
670}
671
Mehdi Amini970800e2016-08-17 06:23:09 +0000672namespace {
673// Define the LTOOutput handling
674class LTOOutput : public lto::NativeObjectOutput {
675 StringRef Path;
676
677public:
678 LTOOutput(StringRef Path) : Path(Path) {}
679 // Open the filename \p Path and allocate a stream.
680 std::unique_ptr<raw_pwrite_stream> getStream() override {
681 int FD;
682 std::error_code EC = sys::fs::openFileForWrite(Path, FD, sys::fs::F_None);
683 if (EC)
684 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
685 return llvm::make_unique<llvm::raw_fd_ostream>(FD, true);
686 }
687};
688}
689
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000690static std::unique_ptr<LTO> createLTO() {
691 Config Conf;
692 ThinBackend Backend;
693 unsigned ParallelCodeGenParallelismLevel = 1;
694
695 Conf.CPU = options::mcpu;
696 Conf.Options = InitTargetOptionsFromCodeGenFlags();
697
698 // Disable the new X86 relax relocations since gold might not support them.
699 // FIXME: Check the gold version or add a new option to enable them.
700 Conf.Options.RelaxELFRelocations = false;
701
702 Conf.MAttrs = MAttrs;
703 Conf.RelocModel = *RelocationModel;
704 Conf.CGOptLevel = getCGOptLevel();
705 Conf.DisableVerify = options::DisableVerify;
706 Conf.OptLevel = options::OptLevel;
707 if (options::Parallelism) {
708 if (options::thinlto)
709 Backend = createInProcessThinBackend(options::Parallelism);
710 else
711 ParallelCodeGenParallelismLevel = options::Parallelism;
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000712 }
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000713 if (options::thinlto_index_only) {
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000714 std::string OldPrefix, NewPrefix;
715 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000716 Backend = createWriteIndexesThinBackend(
717 OldPrefix, NewPrefix, options::thinlto_emit_imports_files,
718 options::thinlto_linked_objects_file);
Teresa Johnson84174c32016-05-10 13:48:23 +0000719 }
720
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000721 Conf.OverrideTriple = options::triple;
722 Conf.DefaultTriple = sys::getDefaultTargetTriple();
723
724 Conf.DiagHandler = diagnosticHandler;
725
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000726 switch (options::TheOutputType) {
727 case options::OT_NORMAL:
728 break;
729
730 case options::OT_DISABLE:
Mehdi Amini6ec23332016-08-22 16:41:58 +0000731 Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000732 break;
733
734 case options::OT_BC_ONLY:
Mehdi Amini6ec23332016-08-22 16:41:58 +0000735 Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000736 std::error_code EC;
737 raw_fd_ostream OS(output_name, EC, sys::fs::OpenFlags::F_None);
738 if (EC)
739 message(LDPL_FATAL, "Failed to write the output file.");
740 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ false);
741 return false;
742 };
743 break;
744
745 case options::OT_SAVE_TEMPS:
Mehdi Aminieccffad2016-08-18 00:12:33 +0000746 check(Conf.addSaveTemps(output_name + ".",
747 /* UseInputModulePath */ true));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000748 break;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000749 }
750
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000751 return llvm::make_unique<LTO>(std::move(Conf), Backend,
752 ParallelCodeGenParallelismLevel);
Teresa Johnson84174c32016-05-10 13:48:23 +0000753}
754
Teresa Johnson3f212b82016-09-21 19:12:05 +0000755// Write empty files that may be expected by a distributed build
756// system when invoked with thinlto_index_only. This is invoked when
757// the linker has decided not to include the given module in the
758// final link. Frequently the distributed build system will want to
759// confirm that all expected outputs are created based on all of the
760// modules provided to the linker.
761static void writeEmptyDistributedBuildOutputs(std::string &ModulePath,
762 std::string &OldPrefix,
763 std::string &NewPrefix) {
764 std::string NewModulePath =
765 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
766 std::error_code EC;
767 {
768 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
769 sys::fs::OpenFlags::F_None);
770 if (EC)
771 message(LDPL_FATAL, "Failed to write '%s': %s",
772 (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
773 }
774 if (options::thinlto_emit_imports_files) {
775 raw_fd_ostream OS(NewModulePath + ".imports", EC,
776 sys::fs::OpenFlags::F_None);
777 if (EC)
778 message(LDPL_FATAL, "Failed to write '%s': %s",
779 (NewModulePath + ".imports").c_str(), EC.message().c_str());
780 }
781}
782
Rafael Espindolab6393292014-07-30 01:23:45 +0000783/// gold informs us that all symbols have been read. At this point, we use
784/// get_symbols to see if any of our definitions have been overridden by a
785/// native object file. Then, perform optimization and codegen.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000786static ld_plugin_status allSymbolsReadHook() {
Rafael Espindola33466a72014-08-21 20:28:55 +0000787 if (Modules.empty())
788 return LDPS_OK;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000789
Teresa Johnsona9f65552016-03-04 16:36:06 +0000790 if (unsigned NumOpts = options::extra.size())
791 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
792
Teresa Johnson765941a2016-08-20 01:24:07 +0000793 // Map to own RAII objects that manage the file opening and releasing
794 // interfaces with gold. This is needed only for ThinLTO mode, since
795 // unlike regular LTO, where addModule will result in the opened file
796 // being merged into a new combined module, we need to keep these files open
797 // through Lto->run().
798 DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
799
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000800 std::unique_ptr<LTO> Lto = createLTO();
Teresa Johnson403a7872015-10-04 14:33:43 +0000801
Teresa Johnson3f212b82016-09-21 19:12:05 +0000802 std::string OldPrefix, NewPrefix;
803 if (options::thinlto_index_only)
804 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
805
Rafael Espindolad2aac572014-07-30 01:52:40 +0000806 for (claimed_file &F : Modules) {
Teresa Johnson765941a2016-08-20 01:24:07 +0000807 if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
808 HandleToInputFile.insert(std::make_pair(
809 F.leader_handle, llvm::make_unique<PluginInputFile>(F.handle)));
Teresa Johnsona9f65552016-03-04 16:36:06 +0000810 const void *View = getSymbolsAndView(F);
Teresa Johnson3f212b82016-09-21 19:12:05 +0000811 if (!View) {
812 if (options::thinlto_index_only)
813 // Write empty output files that may be expected by the distributed
814 // build system.
815 writeEmptyDistributedBuildOutputs(F.name, OldPrefix, NewPrefix);
Evgeniy Stepanov4dc3c8d2016-03-11 00:51:57 +0000816 continue;
Teresa Johnson3f212b82016-09-21 19:12:05 +0000817 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000818 addModule(*Lto, F, View);
Rafael Espindola77b6d012010-06-14 21:20:52 +0000819 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000820
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000821 SmallString<128> Filename;
Mehdi Amini970800e2016-08-17 06:23:09 +0000822 // Note that getOutputFileName will append a unique ID for each task
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000823 if (!options::obj_path.empty())
824 Filename = options::obj_path;
825 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
826 Filename = output_name + ".o";
827 bool SaveTemps = !Filename.empty();
Rafael Espindola33466a72014-08-21 20:28:55 +0000828
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000829 MaxTasks = Lto->getMaxTasks();
830 std::vector<uintptr_t> IsTemporary(MaxTasks);
831 std::vector<SmallString<128>> Filenames(MaxTasks);
832
Teresa Johnson57891a52016-08-24 15:11:47 +0000833 auto AddOutput =
834 [&](size_t Task) -> std::unique_ptr<lto::NativeObjectOutput> {
Mehdi Amini970800e2016-08-17 06:23:09 +0000835 auto &OutputName = Filenames[Task];
836 getOutputFileName(Filename, /*TempOutFile=*/!SaveTemps, OutputName,
837 MaxTasks > 1 ? Task : -1);
Teresa Johnson26a46282016-08-26 23:29:14 +0000838 IsTemporary[Task] = !SaveTemps && options::cache_dir.empty();
Teresa Johnson57891a52016-08-24 15:11:47 +0000839 if (options::cache_dir.empty())
840 return llvm::make_unique<LTOOutput>(OutputName);
841
842 return llvm::make_unique<CacheObjectOutput>(
Teresa Johnson26a46282016-08-26 23:29:14 +0000843 options::cache_dir,
844 [&OutputName](std::string EntryPath) { OutputName = EntryPath; });
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000845 };
846
Mehdi Amini970800e2016-08-17 06:23:09 +0000847 check(Lto->run(AddOutput));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000848
849 if (options::TheOutputType == options::OT_DISABLE ||
850 options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000851 return LDPS_OK;
852
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000853 if (options::thinlto_index_only) {
854 cleanup_hook();
855 exit(0);
Rafael Espindolaba3398b2010-05-13 13:39:31 +0000856 }
Rafael Espindola143fc3b2013-10-16 12:47:04 +0000857
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000858 for (unsigned I = 0; I != MaxTasks; ++I)
859 if (!Filenames[I].empty())
860 recordFile(Filenames[I].str(), IsTemporary[I]);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000861
Rafael Espindolaef498152010-06-23 20:20:59 +0000862 if (!options::extra_library_path.empty() &&
Rafael Espindola33466a72014-08-21 20:28:55 +0000863 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
864 message(LDPL_FATAL, "Unable to set the extra library path.");
Shuxin Yang1826ae22013-08-12 21:07:31 +0000865
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000866 return LDPS_OK;
867}
868
Rafael Espindola55b32542014-08-11 19:06:54 +0000869static ld_plugin_status all_symbols_read_hook(void) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000870 ld_plugin_status Ret = allSymbolsReadHook();
Rafael Espindola947bdb62014-11-25 20:52:49 +0000871 llvm_shutdown();
872
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000873 if (options::TheOutputType == options::OT_BC_ONLY ||
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000874 options::TheOutputType == options::OT_DISABLE) {
Davide Italiano289a43e2016-03-20 20:12:33 +0000875 if (options::TheOutputType == options::OT_DISABLE) {
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000876 // Remove the output file here since ld.bfd creates the output file
877 // early.
Davide Italiano289a43e2016-03-20 20:12:33 +0000878 std::error_code EC = sys::fs::remove(output_name);
879 if (EC)
880 message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
881 EC.message().c_str());
882 }
Rafael Espindola55b32542014-08-11 19:06:54 +0000883 exit(0);
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000884 }
Rafael Espindola55b32542014-08-11 19:06:54 +0000885
886 return Ret;
887}
888
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000889static ld_plugin_status cleanup_hook(void) {
Rafael Espindolad2aac572014-07-30 01:52:40 +0000890 for (std::string &Name : Cleanup) {
891 std::error_code EC = sys::fs::remove(Name);
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000892 if (EC)
Rafael Espindolad2aac572014-07-30 01:52:40 +0000893 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000894 EC.message().c_str());
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000895 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000896
897 return LDPS_OK;
898}