blob: ed8d00256e7c9f8b889300eb71a583c4a6cb16a8 [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;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000109static size_t MaxTasks;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000110
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000111namespace options {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000112 enum OutputType {
113 OT_NORMAL,
114 OT_DISABLE,
115 OT_BC_ONLY,
116 OT_SAVE_TEMPS
117 };
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000118 static OutputType TheOutputType = OT_NORMAL;
Peter Collingbourne070843d2015-03-19 22:01:00 +0000119 static unsigned OptLevel = 2;
Teresa Johnsona9f65552016-03-04 16:36:06 +0000120 // Default parallelism of 0 used to indicate that user did not specify.
121 // Actual parallelism default value depends on implementation.
Teresa Johnsonec544c52016-10-19 17:35:01 +0000122 // Currently only affects ThinLTO, where the default is
123 // llvm::heavyweight_hardware_concurrency.
Teresa Johnsona9f65552016-03-04 16:36:06 +0000124 static unsigned Parallelism = 0;
Teresa Johnson896fee22016-09-23 20:35:19 +0000125 // Default regular LTO codegen parallelism (number of partitions).
126 static unsigned ParallelCodeGenParallelismLevel = 1;
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000127#ifdef NDEBUG
128 static bool DisableVerify = true;
129#else
130 static bool DisableVerify = false;
131#endif
Shuxin Yang1826ae22013-08-12 21:07:31 +0000132 static std::string obj_path;
Rafael Espindolaef498152010-06-23 20:20:59 +0000133 static std::string extra_library_path;
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000134 static std::string triple;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000135 static std::string mcpu;
Teresa Johnson403a7872015-10-04 14:33:43 +0000136 // When the thinlto plugin option is specified, only read the function
137 // the information from intermediate files and write a combined
138 // global index for the ThinLTO backends.
139 static bool thinlto = false;
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000140 // If false, all ThinLTO backend compilations through code gen are performed
141 // using multiple threads in the gold-plugin, before handing control back to
Teresa Johnson84174c32016-05-10 13:48:23 +0000142 // gold. If true, write individual backend index files which reflect
143 // the import decisions, and exit afterwards. The assumption is
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000144 // that the build system will launch the backend processes.
145 static bool thinlto_index_only = false;
Teresa Johnson1e2708c2016-07-22 18:20:22 +0000146 // If non-empty, holds the name of a file in which to write the list of
147 // oject files gold selected for inclusion in the link after symbol
148 // resolution (i.e. they had selected symbols). This will only be non-empty
149 // in the thinlto_index_only case. It is used to identify files, which may
150 // have originally been within archive libraries specified via
151 // --start-lib/--end-lib pairs, that should be included in the final
152 // native link process (since intervening function importing and inlining
153 // may change the symbol resolution detected in the final link and which
154 // files to include out of --start-lib/--end-lib libraries as a result).
155 static std::string thinlto_linked_objects_file;
Teresa Johnson8570fe42016-05-10 15:54:09 +0000156 // If true, when generating individual index files for distributed backends,
157 // also generate a "${bitcodefile}.imports" file at the same location for each
158 // bitcode file, listing the files it imports from in plain text. This is to
159 // support distributed build file staging.
160 static bool thinlto_emit_imports_files = false;
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000161 // Option to control where files for a distributed backend (the individual
162 // index files and optional imports files) are created.
163 // If specified, expects a string of the form "oldprefix:newprefix", and
164 // instead of generating these files in the same directory path as the
165 // corresponding bitcode file, will use a path formed by replacing the
166 // bitcode file's path prefix matching oldprefix with newprefix.
167 static std::string thinlto_prefix_replace;
Teresa Johnson57891a52016-08-24 15:11:47 +0000168 // Optional path to a directory for caching ThinLTO objects.
169 static std::string cache_dir;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000170 // Additional options to pass into the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +0000171 // Note: This array will contain all plugin options which are not claimed
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000172 // as plugin exclusive to pass to the code generator.
Rafael Espindola125b9242014-07-29 19:17:44 +0000173 static std::vector<const char *> extra;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000174
Nick Lewycky7282dd72015-08-05 21:16:02 +0000175 static void process_plugin_option(const char *opt_)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000176 {
Rafael Espindola176e6642014-07-29 21:46:05 +0000177 if (opt_ == nullptr)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000178 return;
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000179 llvm::StringRef opt = opt_;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000180
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000181 if (opt.startswith("mcpu=")) {
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000182 mcpu = opt.substr(strlen("mcpu="));
Rafael Espindolaef498152010-06-23 20:20:59 +0000183 } else if (opt.startswith("extra-library-path=")) {
184 extra_library_path = opt.substr(strlen("extra_library_path="));
Rafael Espindola148c3282010-08-10 16:32:15 +0000185 } else if (opt.startswith("mtriple=")) {
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000186 triple = opt.substr(strlen("mtriple="));
Shuxin Yang1826ae22013-08-12 21:07:31 +0000187 } else if (opt.startswith("obj-path=")) {
188 obj_path = opt.substr(strlen("obj-path="));
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000189 } else if (opt == "emit-llvm") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000190 TheOutputType = OT_BC_ONLY;
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000191 } else if (opt == "save-temps") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000192 TheOutputType = OT_SAVE_TEMPS;
193 } else if (opt == "disable-output") {
194 TheOutputType = OT_DISABLE;
Teresa Johnson403a7872015-10-04 14:33:43 +0000195 } else if (opt == "thinlto") {
196 thinlto = true;
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000197 } else if (opt == "thinlto-index-only") {
198 thinlto_index_only = true;
Teresa Johnson1e2708c2016-07-22 18:20:22 +0000199 } else if (opt.startswith("thinlto-index-only=")) {
200 thinlto_index_only = true;
201 thinlto_linked_objects_file = opt.substr(strlen("thinlto-index-only="));
Teresa Johnson8570fe42016-05-10 15:54:09 +0000202 } else if (opt == "thinlto-emit-imports-files") {
203 thinlto_emit_imports_files = true;
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000204 } else if (opt.startswith("thinlto-prefix-replace=")) {
205 thinlto_prefix_replace = opt.substr(strlen("thinlto-prefix-replace="));
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000206 if (thinlto_prefix_replace.find(";") == std::string::npos)
207 message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");
Teresa Johnson57891a52016-08-24 15:11:47 +0000208 } else if (opt.startswith("cache-dir=")) {
209 cache_dir = opt.substr(strlen("cache-dir="));
Peter Collingbourne070843d2015-03-19 22:01:00 +0000210 } else if (opt.size() == 2 && opt[0] == 'O') {
211 if (opt[1] < '0' || opt[1] > '3')
Peter Collingbourne87202a42015-09-01 20:40:22 +0000212 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000213 OptLevel = opt[1] - '0';
Peter Collingbourne87202a42015-09-01 20:40:22 +0000214 } else if (opt.startswith("jobs=")) {
215 if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
216 message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
Teresa Johnson896fee22016-09-23 20:35:19 +0000217 } else if (opt.startswith("lto-partitions=")) {
218 if (opt.substr(strlen("lto-partitions="))
219 .getAsInteger(10, ParallelCodeGenParallelismLevel))
220 message(LDPL_FATAL, "Invalid codegen partition level: %s", opt_ + 5);
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000221 } else if (opt == "disable-verify") {
222 DisableVerify = true;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000223 } else {
224 // Save this option to pass to the code generator.
Rafael Espindola33466a72014-08-21 20:28:55 +0000225 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
226 // add that.
227 if (extra.empty())
228 extra.push_back("LLVMgold");
229
Rafael Espindola125b9242014-07-29 19:17:44 +0000230 extra.push_back(opt_);
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000231 }
232 }
233}
234
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000235static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
236 int *claimed);
237static ld_plugin_status all_symbols_read_hook(void);
238static ld_plugin_status cleanup_hook(void);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000239
240extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
241ld_plugin_status onload(ld_plugin_tv *tv) {
Peter Collingbourne1505c0a2014-07-03 23:28:03 +0000242 InitializeAllTargetInfos();
243 InitializeAllTargets();
244 InitializeAllTargetMCs();
245 InitializeAllAsmParsers();
246 InitializeAllAsmPrinters();
247
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000248 // We're given a pointer to the first transfer vector. We read through them
249 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
250 // contain pointers to functions that we need to call to register our own
251 // hooks. The others are addresses of functions we can use to call into gold
252 // for services.
253
254 bool registeredClaimFile = false;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000255 bool RegisteredAllSymbolsRead = false;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000256
257 for (; tv->tv_tag != LDPT_NULL; ++tv) {
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000258 // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
259 // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
260 // header.
261 switch (static_cast<int>(tv->tv_tag)) {
262 case LDPT_OUTPUT_NAME:
263 output_name = tv->tv_u.tv_string;
264 break;
265 case LDPT_LINKER_OUTPUT:
266 switch (tv->tv_u.tv_val) {
267 case LDPO_REL: // .o
268 case LDPO_DYN: // .so
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000269 IsExecutable = false;
270 RelocationModel = Reloc::PIC_;
271 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000272 case LDPO_PIE: // position independent executable
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000273 IsExecutable = true;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000274 RelocationModel = Reloc::PIC_;
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000275 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000276 case LDPO_EXEC: // .exe
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000277 IsExecutable = true;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000278 RelocationModel = Reloc::Static;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000279 break;
280 default:
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000281 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
282 return LDPS_ERR;
283 }
284 break;
285 case LDPT_OPTION:
286 options::process_plugin_option(tv->tv_u.tv_string);
287 break;
288 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
289 ld_plugin_register_claim_file callback;
290 callback = tv->tv_u.tv_register_claim_file;
291
292 if (callback(claim_file_hook) != LDPS_OK)
293 return LDPS_ERR;
294
295 registeredClaimFile = true;
296 } break;
297 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
298 ld_plugin_register_all_symbols_read callback;
299 callback = tv->tv_u.tv_register_all_symbols_read;
300
301 if (callback(all_symbols_read_hook) != LDPS_OK)
302 return LDPS_ERR;
303
304 RegisteredAllSymbolsRead = true;
305 } break;
306 case LDPT_REGISTER_CLEANUP_HOOK: {
307 ld_plugin_register_cleanup callback;
308 callback = tv->tv_u.tv_register_cleanup;
309
310 if (callback(cleanup_hook) != LDPS_OK)
311 return LDPS_ERR;
312 } break;
313 case LDPT_GET_INPUT_FILE:
314 get_input_file = tv->tv_u.tv_get_input_file;
315 break;
316 case LDPT_RELEASE_INPUT_FILE:
317 release_input_file = tv->tv_u.tv_release_input_file;
318 break;
319 case LDPT_ADD_SYMBOLS:
320 add_symbols = tv->tv_u.tv_add_symbols;
321 break;
322 case LDPT_GET_SYMBOLS_V2:
323 // Do not override get_symbols_v3 with get_symbols_v2.
324 if (!get_symbols)
325 get_symbols = tv->tv_u.tv_get_symbols;
326 break;
327 case LDPT_GET_SYMBOLS_V3:
328 get_symbols = tv->tv_u.tv_get_symbols;
329 break;
330 case LDPT_ADD_INPUT_FILE:
331 add_input_file = tv->tv_u.tv_add_input_file;
332 break;
333 case LDPT_SET_EXTRA_LIBRARY_PATH:
334 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
335 break;
336 case LDPT_GET_VIEW:
337 get_view = tv->tv_u.tv_get_view;
338 break;
339 case LDPT_MESSAGE:
340 message = tv->tv_u.tv_message;
341 break;
342 default:
343 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000344 }
345 }
346
Rafael Espindolae08484d2009-02-18 08:30:15 +0000347 if (!registeredClaimFile) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000348 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000349 return LDPS_ERR;
350 }
Rafael Espindolae08484d2009-02-18 08:30:15 +0000351 if (!add_symbols) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000352 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000353 return LDPS_ERR;
354 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000355
Rafael Espindolaa0d30a92014-06-19 22:20:07 +0000356 if (!RegisteredAllSymbolsRead)
357 return LDPS_OK;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000358
Rafael Espindola33466a72014-08-21 20:28:55 +0000359 if (!get_input_file) {
360 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
361 return LDPS_ERR;
Rafael Espindolac273aac2014-06-19 22:54:47 +0000362 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000363 if (!release_input_file) {
Marianne Mailhot-Sarrasina5a750e2016-03-30 12:20:53 +0000364 message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
Rafael Espindola33466a72014-08-21 20:28:55 +0000365 return LDPS_ERR;
Tom Roederb5081192014-06-26 20:43:27 +0000366 }
367
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000368 return LDPS_OK;
369}
370
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000371static void diagnosticHandler(const DiagnosticInfo &DI) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000372 std::string ErrStorage;
373 {
374 raw_string_ostream OS(ErrStorage);
375 DiagnosticPrinterRawOStream DP(OS);
376 DI.print(DP);
377 }
Rafael Espindola503f8832015-03-02 19:08:03 +0000378 ld_plugin_level Level;
379 switch (DI.getSeverity()) {
380 case DS_Error:
381 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
382 ErrStorage.c_str());
Rafael Espindola503f8832015-03-02 19:08:03 +0000383 case DS_Warning:
384 Level = LDPL_WARNING;
385 break;
386 case DS_Note:
Rafael Espindolaf3f18542015-03-04 18:51:45 +0000387 case DS_Remark:
Rafael Espindola503f8832015-03-02 19:08:03 +0000388 Level = LDPL_INFO;
389 break;
Rafael Espindola503f8832015-03-02 19:08:03 +0000390 }
391 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000392}
393
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000394static void check(Error E, std::string Msg = "LLVM gold plugin") {
Mehdi Amini48f29602016-11-11 06:04:30 +0000395 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000396 message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());
397 return Error::success();
398 });
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000399}
400
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000401template <typename T> static T check(Expected<T> E) {
402 if (E)
403 return std::move(*E);
404 check(E.takeError());
405 return T();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000406}
407
Rafael Espindolae54d8212014-07-06 14:31:22 +0000408/// Called by gold to see whether this file is one that our plugin can handle.
409/// We'll try to open it and register all the symbols with add_symbol if
410/// possible.
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000411static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
412 int *claimed) {
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000413 MemoryBufferRef BufferRef;
414 std::unique_ptr<MemoryBuffer> Buffer;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000415 if (get_view) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000416 const void *view;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000417 if (get_view(file->handle, &view) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000418 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000419 return LDPS_ERR;
420 }
Nick Lewycky7282dd72015-08-05 21:16:02 +0000421 BufferRef =
422 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
Ivan Krasin5021af52011-09-12 21:47:50 +0000423 } else {
Ivan Krasin639222d2011-09-15 23:13:00 +0000424 int64_t offset = 0;
Nick Lewycky8691c472009-02-05 04:14:23 +0000425 // Gold has found what might be IR part-way inside of a file, such as
426 // an .a archive.
Ivan Krasin5021af52011-09-12 21:47:50 +0000427 if (file->offset) {
428 offset = file->offset;
429 }
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000430 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
431 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
432 offset);
433 if (std::error_code EC = BufferOrErr.getError()) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000434 message(LDPL_ERROR, EC.message().c_str());
Ivan Krasin5021af52011-09-12 21:47:50 +0000435 return LDPS_ERR;
436 }
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000437 Buffer = std::move(BufferOrErr.get());
438 BufferRef = Buffer->getMemBufferRef();
Rafael Espindola56e41f72011-02-08 22:40:47 +0000439 }
Ivan Krasin5021af52011-09-12 21:47:50 +0000440
Rafael Espindola6c472e52014-07-29 20:46:19 +0000441 *claimed = 1;
442
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000443 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
444 if (!ObjOrErr) {
445 handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {
446 std::error_code EC = EI.convertToErrorCode();
447 if (EC == object::object_error::invalid_file_type ||
448 EC == object::object_error::bitcode_section_not_found)
449 *claimed = 0;
450 else
451 message(LDPL_ERROR,
452 "LLVM gold plugin has failed to create LTO module: %s",
453 EI.message().c_str());
454 });
455
456 return *claimed ? LDPS_ERR : LDPS_OK;
Ivan Krasind5f2d8c2011-09-09 00:14:04 +0000457 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000458
459 std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000460
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000461 Modules.resize(Modules.size() + 1);
462 claimed_file &cf = Modules.back();
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000463
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000464 cf.handle = file->handle;
Teresa Johnson683abe72016-05-26 01:46:41 +0000465 // Keep track of the first handle for each file descriptor, since there are
466 // multiple in the case of an archive. This is used later in the case of
467 // ThinLTO parallel backends to ensure that each file is only opened and
468 // released once.
469 auto LeaderHandle =
470 FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
471 cf.leader_handle = LeaderHandle->second;
472 // Save the filesize since for parallel ThinLTO backends we can only
473 // invoke get_input_file once per archive (only for the leader handle).
474 cf.filesize = file->filesize;
475 // In the case of an archive library, all but the first member must have a
476 // non-zero offset, which we can append to the file name to obtain a
477 // unique name.
478 cf.name = file->name;
479 if (file->offset)
480 cf.name += ".llvm." + std::to_string(file->offset) + "." +
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000481 sys::path::filename(Obj->getSourceFileName()).str();
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000482
Rafael Espindola33466a72014-08-21 20:28:55 +0000483 for (auto &Sym : Obj->symbols()) {
484 uint32_t Symflags = Sym.getFlags();
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000485
486 cf.syms.push_back(ld_plugin_symbol());
487 ld_plugin_symbol &sym = cf.syms.back();
Rafael Espindola176e6642014-07-29 21:46:05 +0000488 sym.version = nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000489 StringRef Name = Sym.getName();
490 sym.name = strdup(Name.str().c_str());
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000491
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000492 ResolutionInfo &Res = ResInfo[Name];
Rafael Espindola33466a72014-08-21 20:28:55 +0000493
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000494 Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000495
Rafael Espindola33466a72014-08-21 20:28:55 +0000496 sym.visibility = LDPV_DEFAULT;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000497 GlobalValue::VisibilityTypes Vis = Sym.getVisibility();
498 if (Vis != GlobalValue::DefaultVisibility)
499 Res.DefaultVisibility = false;
500 switch (Vis) {
501 case GlobalValue::DefaultVisibility:
502 break;
503 case GlobalValue::HiddenVisibility:
504 sym.visibility = LDPV_HIDDEN;
505 break;
506 case GlobalValue::ProtectedVisibility:
507 sym.visibility = LDPV_PROTECTED;
508 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000509 }
510
Rafael Espindola33466a72014-08-21 20:28:55 +0000511 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
512 sym.def = LDPK_UNDEF;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000513 if (Symflags & object::BasicSymbolRef::SF_Weak)
Rafael Espindola56548522009-04-24 16:55:21 +0000514 sym.def = LDPK_WEAKUNDEF;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000515 } else if (Symflags & object::BasicSymbolRef::SF_Common)
516 sym.def = LDPK_COMMON;
517 else if (Symflags & object::BasicSymbolRef::SF_Weak)
518 sym.def = LDPK_WEAKDEF;
519 else
Rafael Espindola33466a72014-08-21 20:28:55 +0000520 sym.def = LDPK_DEF;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000521
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000522 sym.size = 0;
Rafael Espindola33466a72014-08-21 20:28:55 +0000523 sym.comdat_key = nullptr;
Rafael Espindola79121102016-10-25 12:02:03 +0000524 int CI = check(Sym.getComdatIndex());
525 if (CI != -1) {
526 StringRef C = Obj->getComdatTable()[CI];
Rafael Espindola62382c92016-10-17 18:51:02 +0000527 sym.comdat_key = strdup(C.str().c_str());
Rafael Espindola79121102016-10-25 12:02:03 +0000528 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000529
530 sym.resolution = LDPR_UNKNOWN;
531 }
532
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000533 if (!cf.syms.empty()) {
Nick Lewycky7282dd72015-08-05 21:16:02 +0000534 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000535 message(LDPL_ERROR, "Unable to add symbols!");
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000536 return LDPS_ERR;
537 }
538 }
539
540 return LDPS_OK;
541}
542
Rafael Espindola538c9a82014-12-23 18:18:37 +0000543static void freeSymName(ld_plugin_symbol &Sym) {
544 free(Sym.name);
545 free(Sym.comdat_key);
546 Sym.name = nullptr;
547 Sym.comdat_key = nullptr;
548}
549
Teresa Johnsona9f65552016-03-04 16:36:06 +0000550/// Helper to get a file's symbols and a view into it via gold callbacks.
551static const void *getSymbolsAndView(claimed_file &F) {
Benjamin Kramer39988a02016-03-08 14:02:46 +0000552 ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000553 if (status == LDPS_NO_SYMS)
554 return nullptr;
Teresa Johnson403a7872015-10-04 14:33:43 +0000555
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000556 if (status != LDPS_OK)
Teresa Johnson403a7872015-10-04 14:33:43 +0000557 message(LDPL_FATAL, "Failed to get symbol information");
558
559 const void *View;
560 if (get_view(F.handle, &View) != LDPS_OK)
561 message(LDPL_FATAL, "Failed to get a view of file");
562
Teresa Johnsona9f65552016-03-04 16:36:06 +0000563 return View;
564}
565
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000566static void addModule(LTO &Lto, claimed_file &F, const void *View) {
Teresa Johnson683abe72016-05-26 01:46:41 +0000567 MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize), F.name);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000568 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
Teresa Johnson6290dbc2015-11-21 21:55:48 +0000569
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000570 if (!ObjOrErr)
Peter Collingbourne10039c02014-09-18 21:28:49 +0000571 message(LDPL_FATAL, "Could not read bitcode from file : %s",
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000572 toString(ObjOrErr.takeError()).c_str());
Peter Collingbourne10039c02014-09-18 21:28:49 +0000573
Rafael Espindola527e8462014-12-09 16:13:59 +0000574 unsigned SymNum = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000575 std::vector<SymbolResolution> Resols(F.syms.size());
Peter Collingbourne07586442016-09-14 02:55:16 +0000576 for (ld_plugin_symbol &Sym : F.syms) {
577 SymbolResolution &R = Resols[SymNum++];
Rafael Espindola527e8462014-12-09 16:13:59 +0000578
Rafael Espindola33466a72014-08-21 20:28:55 +0000579 ld_plugin_symbol_resolution Resolution =
580 (ld_plugin_symbol_resolution)Sym.resolution;
581
Rafael Espindolacaabe222015-12-10 14:19:35 +0000582 ResolutionInfo &Res = ResInfo[Sym.name];
Rafael Espindola890db272014-09-09 20:08:22 +0000583
Rafael Espindola33466a72014-08-21 20:28:55 +0000584 switch (Resolution) {
585 case LDPR_UNKNOWN:
586 llvm_unreachable("Unexpected resolution");
587
588 case LDPR_RESOLVED_IR:
589 case LDPR_RESOLVED_EXEC:
590 case LDPR_RESOLVED_DYN:
Rafael Espindolacaabe222015-12-10 14:19:35 +0000591 case LDPR_PREEMPTED_IR:
592 case LDPR_PREEMPTED_REG:
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000593 case LDPR_UNDEF:
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000594 break;
595
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000596 case LDPR_PREVAILING_DEF_IRONLY:
597 R.Prevailing = true;
Rafael Espindola33466a72014-08-21 20:28:55 +0000598 break;
Teresa Johnsonf99573b2016-08-11 12:56:40 +0000599
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000600 case LDPR_PREVAILING_DEF:
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000601 R.Prevailing = true;
602 R.VisibleToRegularObj = true;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000603 break;
604
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000605 case LDPR_PREVAILING_DEF_IRONLY_EXP:
606 R.Prevailing = true;
607 if (!Res.CanOmitFromDynSym)
608 R.VisibleToRegularObj = true;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000609 break;
610 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000611
612 if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
613 (IsExecutable || !Res.DefaultVisibility))
614 R.FinalDefinitionInLinkageUnit = true;
615
Rafael Espindola538c9a82014-12-23 18:18:37 +0000616 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000617 }
618
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000619 check(Lto.add(std::move(*ObjOrErr), Resols),
620 std::string("Failed to link module ") + F.name);
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000621}
622
Teresa Johnsona9f65552016-03-04 16:36:06 +0000623static void recordFile(std::string Filename, bool TempOutFile) {
624 if (add_input_file(Filename.c_str()) != LDPS_OK)
625 message(LDPL_FATAL,
626 "Unable to add .o file to the link. File left behind in: %s",
627 Filename.c_str());
628 if (TempOutFile)
629 Cleanup.push_back(Filename.c_str());
630}
Rafael Espindola33466a72014-08-21 20:28:55 +0000631
Mehdi Amini970800e2016-08-17 06:23:09 +0000632/// Return the desired output filename given a base input name, a flag
633/// indicating whether a temp file should be generated, and an optional task id.
634/// The new filename generated is returned in \p NewFilename.
635static void getOutputFileName(SmallString<128> InFilename, bool TempOutFile,
636 SmallString<128> &NewFilename, int TaskID = -1) {
Teresa Johnsona9f65552016-03-04 16:36:06 +0000637 if (TempOutFile) {
638 std::error_code EC =
Mehdi Amini970800e2016-08-17 06:23:09 +0000639 sys::fs::createTemporaryFile("lto-llvm", "o", NewFilename);
Teresa Johnsona9f65552016-03-04 16:36:06 +0000640 if (EC)
641 message(LDPL_FATAL, "Could not create temporary file: %s",
642 EC.message().c_str());
643 } else {
644 NewFilename = InFilename;
645 if (TaskID >= 0)
646 NewFilename += utostr(TaskID);
Teresa Johnsona9f65552016-03-04 16:36:06 +0000647 }
Teresa Johnsona9f65552016-03-04 16:36:06 +0000648}
649
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000650static CodeGenOpt::Level getCGOptLevel() {
651 switch (options::OptLevel) {
652 case 0:
653 return CodeGenOpt::None;
654 case 1:
655 return CodeGenOpt::Less;
656 case 2:
657 return CodeGenOpt::Default;
658 case 3:
659 return CodeGenOpt::Aggressive;
660 }
661 llvm_unreachable("Invalid optimization level");
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000662}
663
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000664/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
665/// \p NewPrefix strings, if it was specified.
666static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
667 std::string &NewPrefix) {
668 StringRef PrefixReplace = options::thinlto_prefix_replace;
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000669 assert(PrefixReplace.empty() || PrefixReplace.find(";") != StringRef::npos);
670 std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000671 OldPrefix = Split.first.str();
672 NewPrefix = Split.second.str();
673}
674
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000675static std::unique_ptr<LTO> createLTO() {
676 Config Conf;
677 ThinBackend Backend;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000678
679 Conf.CPU = options::mcpu;
680 Conf.Options = InitTargetOptionsFromCodeGenFlags();
681
682 // Disable the new X86 relax relocations since gold might not support them.
683 // FIXME: Check the gold version or add a new option to enable them.
684 Conf.Options.RelaxELFRelocations = false;
685
686 Conf.MAttrs = MAttrs;
687 Conf.RelocModel = *RelocationModel;
688 Conf.CGOptLevel = getCGOptLevel();
689 Conf.DisableVerify = options::DisableVerify;
690 Conf.OptLevel = options::OptLevel;
Teresa Johnson896fee22016-09-23 20:35:19 +0000691 if (options::Parallelism)
692 Backend = createInProcessThinBackend(options::Parallelism);
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000693 if (options::thinlto_index_only) {
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000694 std::string OldPrefix, NewPrefix;
695 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000696 Backend = createWriteIndexesThinBackend(
697 OldPrefix, NewPrefix, options::thinlto_emit_imports_files,
698 options::thinlto_linked_objects_file);
Teresa Johnson84174c32016-05-10 13:48:23 +0000699 }
700
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000701 Conf.OverrideTriple = options::triple;
702 Conf.DefaultTriple = sys::getDefaultTargetTriple();
703
704 Conf.DiagHandler = diagnosticHandler;
705
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000706 switch (options::TheOutputType) {
707 case options::OT_NORMAL:
708 break;
709
710 case options::OT_DISABLE:
Mehdi Amini6ec23332016-08-22 16:41:58 +0000711 Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000712 break;
713
714 case options::OT_BC_ONLY:
Mehdi Amini6ec23332016-08-22 16:41:58 +0000715 Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000716 std::error_code EC;
717 raw_fd_ostream OS(output_name, EC, sys::fs::OpenFlags::F_None);
718 if (EC)
719 message(LDPL_FATAL, "Failed to write the output file.");
720 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ false);
721 return false;
722 };
723 break;
724
725 case options::OT_SAVE_TEMPS:
Mehdi Aminieccffad2016-08-18 00:12:33 +0000726 check(Conf.addSaveTemps(output_name + ".",
727 /* UseInputModulePath */ true));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000728 break;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000729 }
730
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000731 return llvm::make_unique<LTO>(std::move(Conf), Backend,
Teresa Johnson896fee22016-09-23 20:35:19 +0000732 options::ParallelCodeGenParallelismLevel);
Teresa Johnson84174c32016-05-10 13:48:23 +0000733}
734
Teresa Johnson3f212b82016-09-21 19:12:05 +0000735// Write empty files that may be expected by a distributed build
736// system when invoked with thinlto_index_only. This is invoked when
737// the linker has decided not to include the given module in the
738// final link. Frequently the distributed build system will want to
739// confirm that all expected outputs are created based on all of the
740// modules provided to the linker.
741static void writeEmptyDistributedBuildOutputs(std::string &ModulePath,
742 std::string &OldPrefix,
743 std::string &NewPrefix) {
744 std::string NewModulePath =
745 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
746 std::error_code EC;
747 {
748 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
749 sys::fs::OpenFlags::F_None);
750 if (EC)
751 message(LDPL_FATAL, "Failed to write '%s': %s",
752 (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
753 }
754 if (options::thinlto_emit_imports_files) {
755 raw_fd_ostream OS(NewModulePath + ".imports", EC,
756 sys::fs::OpenFlags::F_None);
757 if (EC)
758 message(LDPL_FATAL, "Failed to write '%s': %s",
759 (NewModulePath + ".imports").c_str(), EC.message().c_str());
760 }
761}
762
Rafael Espindolab6393292014-07-30 01:23:45 +0000763/// gold informs us that all symbols have been read. At this point, we use
764/// get_symbols to see if any of our definitions have been overridden by a
765/// native object file. Then, perform optimization and codegen.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000766static ld_plugin_status allSymbolsReadHook() {
Rafael Espindola33466a72014-08-21 20:28:55 +0000767 if (Modules.empty())
768 return LDPS_OK;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000769
Teresa Johnsona9f65552016-03-04 16:36:06 +0000770 if (unsigned NumOpts = options::extra.size())
771 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
772
Teresa Johnson765941a2016-08-20 01:24:07 +0000773 // Map to own RAII objects that manage the file opening and releasing
774 // interfaces with gold. This is needed only for ThinLTO mode, since
775 // unlike regular LTO, where addModule will result in the opened file
776 // being merged into a new combined module, we need to keep these files open
777 // through Lto->run().
778 DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
779
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000780 std::unique_ptr<LTO> Lto = createLTO();
Teresa Johnson403a7872015-10-04 14:33:43 +0000781
Teresa Johnson3f212b82016-09-21 19:12:05 +0000782 std::string OldPrefix, NewPrefix;
783 if (options::thinlto_index_only)
784 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
785
Rafael Espindolad2aac572014-07-30 01:52:40 +0000786 for (claimed_file &F : Modules) {
Teresa Johnson765941a2016-08-20 01:24:07 +0000787 if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
788 HandleToInputFile.insert(std::make_pair(
789 F.leader_handle, llvm::make_unique<PluginInputFile>(F.handle)));
Teresa Johnsona9f65552016-03-04 16:36:06 +0000790 const void *View = getSymbolsAndView(F);
Teresa Johnson3f212b82016-09-21 19:12:05 +0000791 if (!View) {
792 if (options::thinlto_index_only)
793 // Write empty output files that may be expected by the distributed
794 // build system.
795 writeEmptyDistributedBuildOutputs(F.name, OldPrefix, NewPrefix);
Evgeniy Stepanov4dc3c8d2016-03-11 00:51:57 +0000796 continue;
Teresa Johnson3f212b82016-09-21 19:12:05 +0000797 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000798 addModule(*Lto, F, View);
Rafael Espindola77b6d012010-06-14 21:20:52 +0000799 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000800
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000801 SmallString<128> Filename;
Mehdi Amini970800e2016-08-17 06:23:09 +0000802 // Note that getOutputFileName will append a unique ID for each task
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000803 if (!options::obj_path.empty())
804 Filename = options::obj_path;
805 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
806 Filename = output_name + ".o";
807 bool SaveTemps = !Filename.empty();
Rafael Espindola33466a72014-08-21 20:28:55 +0000808
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000809 MaxTasks = Lto->getMaxTasks();
810 std::vector<uintptr_t> IsTemporary(MaxTasks);
811 std::vector<SmallString<128>> Filenames(MaxTasks);
812
Peter Collingbourne80186a52016-09-23 21:33:43 +0000813 auto AddStream =
814 [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
815 IsTemporary[Task] = !SaveTemps;
816 getOutputFileName(Filename, /*TempOutFile=*/!SaveTemps, Filenames[Task],
Mehdi Amini970800e2016-08-17 06:23:09 +0000817 MaxTasks > 1 ? Task : -1);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000818 int FD;
819 std::error_code EC =
820 sys::fs::openFileForWrite(Filenames[Task], FD, sys::fs::F_None);
821 if (EC)
822 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
823 return llvm::make_unique<lto::NativeObjectStream>(
824 llvm::make_unique<llvm::raw_fd_ostream>(FD, true));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000825 };
826
Peter Collingbourne80186a52016-09-23 21:33:43 +0000827 auto AddFile = [&](size_t Task, StringRef Path) { Filenames[Task] = Path; };
828
829 NativeObjectCache Cache;
830 if (!options::cache_dir.empty())
831 Cache = localCache(options::cache_dir, AddFile);
832
833 check(Lto->run(AddStream, Cache));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000834
835 if (options::TheOutputType == options::OT_DISABLE ||
836 options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000837 return LDPS_OK;
838
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000839 if (options::thinlto_index_only) {
840 cleanup_hook();
841 exit(0);
Rafael Espindolaba3398b2010-05-13 13:39:31 +0000842 }
Rafael Espindola143fc3b2013-10-16 12:47:04 +0000843
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000844 for (unsigned I = 0; I != MaxTasks; ++I)
845 if (!Filenames[I].empty())
846 recordFile(Filenames[I].str(), IsTemporary[I]);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000847
Rafael Espindolaef498152010-06-23 20:20:59 +0000848 if (!options::extra_library_path.empty() &&
Rafael Espindola33466a72014-08-21 20:28:55 +0000849 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
850 message(LDPL_FATAL, "Unable to set the extra library path.");
Shuxin Yang1826ae22013-08-12 21:07:31 +0000851
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000852 return LDPS_OK;
853}
854
Rafael Espindola55b32542014-08-11 19:06:54 +0000855static ld_plugin_status all_symbols_read_hook(void) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000856 ld_plugin_status Ret = allSymbolsReadHook();
Rafael Espindola947bdb62014-11-25 20:52:49 +0000857 llvm_shutdown();
858
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000859 if (options::TheOutputType == options::OT_BC_ONLY ||
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000860 options::TheOutputType == options::OT_DISABLE) {
Davide Italiano289a43e2016-03-20 20:12:33 +0000861 if (options::TheOutputType == options::OT_DISABLE) {
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000862 // Remove the output file here since ld.bfd creates the output file
863 // early.
Davide Italiano289a43e2016-03-20 20:12:33 +0000864 std::error_code EC = sys::fs::remove(output_name);
865 if (EC)
866 message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
867 EC.message().c_str());
868 }
Rafael Espindola55b32542014-08-11 19:06:54 +0000869 exit(0);
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000870 }
Rafael Espindola55b32542014-08-11 19:06:54 +0000871
872 return Ret;
873}
874
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000875static ld_plugin_status cleanup_hook(void) {
Rafael Espindolad2aac572014-07-30 01:52:40 +0000876 for (std::string &Name : Cleanup) {
877 std::error_code EC = sys::fs::remove(Name);
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000878 if (EC)
Rafael Espindolad2aac572014-07-30 01:52:40 +0000879 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000880 EC.message().c_str());
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000881 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000882
883 return LDPS_OK;
884}