blob: cfcb4b953710975c8dd2900ac88d3bcd2cb75fd4 [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 Johnson95597ae2017-02-02 17:33:53 +000015#include "llvm/ADT/Statistic.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000016#include "llvm/Bitcode/BitcodeReader.h"
17#include "llvm/Bitcode/BitcodeWriter.h"
Rafael Espindola6b244b12014-06-19 21:14:13 +000018#include "llvm/CodeGen/CommandFlags.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000019#include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
Rafael Espindola890db272014-09-09 20:08:22 +000020#include "llvm/IR/Constants.h"
Rafael Espindolad0b23be2015-01-10 00:07:30 +000021#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson57891a52016-08-24 15:11:47 +000022#include "llvm/LTO/Caching.h"
Teresa Johnson683abe72016-05-26 01:46:41 +000023#include "llvm/LTO/LTO.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000024#include "llvm/Support/CommandLine.h"
Rafael Espindola947bdb62014-11-25 20:52:49 +000025#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000026#include "llvm/Support/MemoryBuffer.h"
Teresa Johnsonbbd10b42016-05-17 14:45:30 +000027#include "llvm/Support/Path.h"
Rafael Espindola6b244b12014-06-19 21:14:13 +000028#include "llvm/Support/TargetSelect.h"
Teresa Johnsonb13dbd62015-12-09 19:45:55 +000029#include "llvm/Support/raw_ostream.h"
Nick Lewyckyfb643e42009-02-03 07:13:24 +000030#include <list>
Teresa Johnson9ba95f92016-08-11 14:58:12 +000031#include <map>
Chandler Carruth07baed52014-01-13 08:04:33 +000032#include <plugin-api.h>
Teresa Johnson9ba95f92016-08-11 14:58:12 +000033#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000034#include <system_error>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000035#include <utility>
Nick Lewyckyfb643e42009-02-03 07:13:24 +000036#include <vector>
37
Sylvestre Ledru53999792014-02-11 17:30:18 +000038// FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
39// Precise and Debian Wheezy (binutils 2.23 is required)
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +000040#define LDPO_PIE 3
41
42#define LDPT_GET_SYMBOLS_V3 28
Sylvestre Ledru53999792014-02-11 17:30:18 +000043
Nick Lewyckyfb643e42009-02-03 07:13:24 +000044using namespace llvm;
Teresa Johnson9ba95f92016-08-11 14:58:12 +000045using namespace lto;
Nick Lewyckyfb643e42009-02-03 07:13:24 +000046
Teresa Johnsoncb15b732015-12-16 16:34:06 +000047static ld_plugin_status discard_message(int level, const char *format, ...) {
48 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
49 // callback in the transfer vector. This should never be called.
50 abort();
51}
52
53static ld_plugin_release_input_file release_input_file = nullptr;
54static ld_plugin_get_input_file get_input_file = nullptr;
55static ld_plugin_message message = discard_message;
56
Nick Lewyckyfb643e42009-02-03 07:13:24 +000057namespace {
Rafael Espindolabfb8b912014-06-20 01:37:35 +000058struct claimed_file {
59 void *handle;
Teresa Johnson683abe72016-05-26 01:46:41 +000060 void *leader_handle;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000061 std::vector<ld_plugin_symbol> syms;
Teresa Johnson683abe72016-05-26 01:46:41 +000062 off_t filesize;
63 std::string name;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000064};
Rafael Espindolacaabe222015-12-10 14:19:35 +000065
Teresa Johnsoncb15b732015-12-16 16:34:06 +000066/// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
67struct PluginInputFile {
Teresa Johnson031bed22015-12-16 21:37:48 +000068 void *Handle;
Teresa Johnson7cffaf32016-03-04 17:06:02 +000069 std::unique_ptr<ld_plugin_input_file> File;
Teresa Johnsoncb15b732015-12-16 16:34:06 +000070
Teresa Johnson031bed22015-12-16 21:37:48 +000071 PluginInputFile(void *Handle) : Handle(Handle) {
Teresa Johnson7cffaf32016-03-04 17:06:02 +000072 File = llvm::make_unique<ld_plugin_input_file>();
73 if (get_input_file(Handle, File.get()) != LDPS_OK)
Teresa Johnsoncb15b732015-12-16 16:34:06 +000074 message(LDPL_FATAL, "Failed to get file information");
75 }
76 ~PluginInputFile() {
Teresa Johnson7cffaf32016-03-04 17:06:02 +000077 // File would have been reset to nullptr if we moved this object
78 // to a new owner.
79 if (File)
80 if (release_input_file(Handle) != LDPS_OK)
81 message(LDPL_FATAL, "Failed to release file information");
Teresa Johnsoncb15b732015-12-16 16:34:06 +000082 }
Teresa Johnson7cffaf32016-03-04 17:06:02 +000083
84 ld_plugin_input_file &file() { return *File; }
85
86 PluginInputFile(PluginInputFile &&RHS) = default;
87 PluginInputFile &operator=(PluginInputFile &&RHS) = default;
Teresa Johnsoncb15b732015-12-16 16:34:06 +000088};
89
Rafael Espindolacaabe222015-12-10 14:19:35 +000090struct ResolutionInfo {
Teresa Johnson9ba95f92016-08-11 14:58:12 +000091 bool CanOmitFromDynSym = true;
92 bool DefaultVisibility = true;
Rafael Espindolacaabe222015-12-10 14:19:35 +000093};
Teresa Johnson7cffaf32016-03-04 17:06:02 +000094
Nick Lewyckyfb643e42009-02-03 07:13:24 +000095}
Rafael Espindolabfb8b912014-06-20 01:37:35 +000096
Rafael Espindola176e6642014-07-29 21:46:05 +000097static ld_plugin_add_symbols add_symbols = nullptr;
98static ld_plugin_get_symbols get_symbols = nullptr;
99static ld_plugin_add_input_file add_input_file = nullptr;
100static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
101static ld_plugin_get_view get_view = nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000102static bool IsExecutable = false;
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000103static Optional<Reloc::Model> RelocationModel;
Rafael Espindolabfb8b912014-06-20 01:37:35 +0000104static std::string output_name = "";
105static std::list<claimed_file> Modules;
Teresa Johnson683abe72016-05-26 01:46:41 +0000106static DenseMap<int, void *> FDToLeaderHandle;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000107static StringMap<ResolutionInfo> ResInfo;
Rafael Espindolabfb8b912014-06-20 01:37:35 +0000108static std::vector<std::string> Cleanup;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000109static llvm::TargetOptions TargetOpts;
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;
Dehao Chen27978002016-12-16 16:48:46 +0000174 // Sample profile file path
175 static std::string sample_profile;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000176
Nick Lewycky7282dd72015-08-05 21:16:02 +0000177 static void process_plugin_option(const char *opt_)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000178 {
Rafael Espindola176e6642014-07-29 21:46:05 +0000179 if (opt_ == nullptr)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000180 return;
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000181 llvm::StringRef opt = opt_;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000182
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000183 if (opt.startswith("mcpu=")) {
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000184 mcpu = opt.substr(strlen("mcpu="));
Rafael Espindolaef498152010-06-23 20:20:59 +0000185 } else if (opt.startswith("extra-library-path=")) {
186 extra_library_path = opt.substr(strlen("extra_library_path="));
Rafael Espindola148c3282010-08-10 16:32:15 +0000187 } else if (opt.startswith("mtriple=")) {
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000188 triple = opt.substr(strlen("mtriple="));
Shuxin Yang1826ae22013-08-12 21:07:31 +0000189 } else if (opt.startswith("obj-path=")) {
190 obj_path = opt.substr(strlen("obj-path="));
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000191 } else if (opt == "emit-llvm") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000192 TheOutputType = OT_BC_ONLY;
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000193 } else if (opt == "save-temps") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000194 TheOutputType = OT_SAVE_TEMPS;
195 } else if (opt == "disable-output") {
196 TheOutputType = OT_DISABLE;
Teresa Johnson403a7872015-10-04 14:33:43 +0000197 } else if (opt == "thinlto") {
198 thinlto = true;
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000199 } else if (opt == "thinlto-index-only") {
200 thinlto_index_only = true;
Teresa Johnson1e2708c2016-07-22 18:20:22 +0000201 } else if (opt.startswith("thinlto-index-only=")) {
202 thinlto_index_only = true;
203 thinlto_linked_objects_file = opt.substr(strlen("thinlto-index-only="));
Teresa Johnson8570fe42016-05-10 15:54:09 +0000204 } else if (opt == "thinlto-emit-imports-files") {
205 thinlto_emit_imports_files = true;
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000206 } else if (opt.startswith("thinlto-prefix-replace=")) {
207 thinlto_prefix_replace = opt.substr(strlen("thinlto-prefix-replace="));
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000208 if (thinlto_prefix_replace.find(';') == std::string::npos)
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000209 message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");
Teresa Johnson57891a52016-08-24 15:11:47 +0000210 } else if (opt.startswith("cache-dir=")) {
211 cache_dir = opt.substr(strlen("cache-dir="));
Peter Collingbourne070843d2015-03-19 22:01:00 +0000212 } else if (opt.size() == 2 && opt[0] == 'O') {
213 if (opt[1] < '0' || opt[1] > '3')
Peter Collingbourne87202a42015-09-01 20:40:22 +0000214 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000215 OptLevel = opt[1] - '0';
Peter Collingbourne87202a42015-09-01 20:40:22 +0000216 } else if (opt.startswith("jobs=")) {
217 if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
218 message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
Teresa Johnson896fee22016-09-23 20:35:19 +0000219 } else if (opt.startswith("lto-partitions=")) {
220 if (opt.substr(strlen("lto-partitions="))
221 .getAsInteger(10, ParallelCodeGenParallelismLevel))
222 message(LDPL_FATAL, "Invalid codegen partition level: %s", opt_ + 5);
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000223 } else if (opt == "disable-verify") {
224 DisableVerify = true;
Dehao Chen27978002016-12-16 16:48:46 +0000225 } else if (opt.startswith("sample-profile=")) {
226 sample_profile= opt.substr(strlen("sample-profile="));
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000227 } else {
228 // Save this option to pass to the code generator.
Rafael Espindola33466a72014-08-21 20:28:55 +0000229 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
230 // add that.
231 if (extra.empty())
232 extra.push_back("LLVMgold");
233
Rafael Espindola125b9242014-07-29 19:17:44 +0000234 extra.push_back(opt_);
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000235 }
236 }
237}
238
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000239static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
240 int *claimed);
241static ld_plugin_status all_symbols_read_hook(void);
242static ld_plugin_status cleanup_hook(void);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000243
244extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
245ld_plugin_status onload(ld_plugin_tv *tv) {
Peter Collingbourne1505c0a2014-07-03 23:28:03 +0000246 InitializeAllTargetInfos();
247 InitializeAllTargets();
248 InitializeAllTargetMCs();
249 InitializeAllAsmParsers();
250 InitializeAllAsmPrinters();
251
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000252 // We're given a pointer to the first transfer vector. We read through them
253 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
254 // contain pointers to functions that we need to call to register our own
255 // hooks. The others are addresses of functions we can use to call into gold
256 // for services.
257
258 bool registeredClaimFile = false;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000259 bool RegisteredAllSymbolsRead = false;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000260
261 for (; tv->tv_tag != LDPT_NULL; ++tv) {
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000262 // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
263 // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
264 // header.
265 switch (static_cast<int>(tv->tv_tag)) {
266 case LDPT_OUTPUT_NAME:
267 output_name = tv->tv_u.tv_string;
268 break;
269 case LDPT_LINKER_OUTPUT:
270 switch (tv->tv_u.tv_val) {
271 case LDPO_REL: // .o
272 case LDPO_DYN: // .so
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000273 IsExecutable = false;
274 RelocationModel = Reloc::PIC_;
275 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000276 case LDPO_PIE: // position independent executable
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000277 IsExecutable = true;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000278 RelocationModel = Reloc::PIC_;
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000279 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000280 case LDPO_EXEC: // .exe
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000281 IsExecutable = true;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000282 RelocationModel = Reloc::Static;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000283 break;
284 default:
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000285 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
286 return LDPS_ERR;
287 }
288 break;
289 case LDPT_OPTION:
290 options::process_plugin_option(tv->tv_u.tv_string);
291 break;
292 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
293 ld_plugin_register_claim_file callback;
294 callback = tv->tv_u.tv_register_claim_file;
295
296 if (callback(claim_file_hook) != LDPS_OK)
297 return LDPS_ERR;
298
299 registeredClaimFile = true;
300 } break;
301 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
302 ld_plugin_register_all_symbols_read callback;
303 callback = tv->tv_u.tv_register_all_symbols_read;
304
305 if (callback(all_symbols_read_hook) != LDPS_OK)
306 return LDPS_ERR;
307
308 RegisteredAllSymbolsRead = true;
309 } break;
310 case LDPT_REGISTER_CLEANUP_HOOK: {
311 ld_plugin_register_cleanup callback;
312 callback = tv->tv_u.tv_register_cleanup;
313
314 if (callback(cleanup_hook) != LDPS_OK)
315 return LDPS_ERR;
316 } break;
317 case LDPT_GET_INPUT_FILE:
318 get_input_file = tv->tv_u.tv_get_input_file;
319 break;
320 case LDPT_RELEASE_INPUT_FILE:
321 release_input_file = tv->tv_u.tv_release_input_file;
322 break;
323 case LDPT_ADD_SYMBOLS:
324 add_symbols = tv->tv_u.tv_add_symbols;
325 break;
326 case LDPT_GET_SYMBOLS_V2:
327 // Do not override get_symbols_v3 with get_symbols_v2.
328 if (!get_symbols)
329 get_symbols = tv->tv_u.tv_get_symbols;
330 break;
331 case LDPT_GET_SYMBOLS_V3:
332 get_symbols = tv->tv_u.tv_get_symbols;
333 break;
334 case LDPT_ADD_INPUT_FILE:
335 add_input_file = tv->tv_u.tv_add_input_file;
336 break;
337 case LDPT_SET_EXTRA_LIBRARY_PATH:
338 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
339 break;
340 case LDPT_GET_VIEW:
341 get_view = tv->tv_u.tv_get_view;
342 break;
343 case LDPT_MESSAGE:
344 message = tv->tv_u.tv_message;
345 break;
346 default:
347 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000348 }
349 }
350
Rafael Espindolae08484d2009-02-18 08:30:15 +0000351 if (!registeredClaimFile) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000352 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000353 return LDPS_ERR;
354 }
Rafael Espindolae08484d2009-02-18 08:30:15 +0000355 if (!add_symbols) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000356 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000357 return LDPS_ERR;
358 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000359
Rafael Espindolaa0d30a92014-06-19 22:20:07 +0000360 if (!RegisteredAllSymbolsRead)
361 return LDPS_OK;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000362
Rafael Espindola33466a72014-08-21 20:28:55 +0000363 if (!get_input_file) {
364 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
365 return LDPS_ERR;
Rafael Espindolac273aac2014-06-19 22:54:47 +0000366 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000367 if (!release_input_file) {
Marianne Mailhot-Sarrasina5a750e2016-03-30 12:20:53 +0000368 message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
Rafael Espindola33466a72014-08-21 20:28:55 +0000369 return LDPS_ERR;
Tom Roederb5081192014-06-26 20:43:27 +0000370 }
371
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000372 return LDPS_OK;
373}
374
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000375static void diagnosticHandler(const DiagnosticInfo &DI) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000376 std::string ErrStorage;
377 {
378 raw_string_ostream OS(ErrStorage);
379 DiagnosticPrinterRawOStream DP(OS);
380 DI.print(DP);
381 }
Rafael Espindola503f8832015-03-02 19:08:03 +0000382 ld_plugin_level Level;
383 switch (DI.getSeverity()) {
384 case DS_Error:
385 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
386 ErrStorage.c_str());
Rafael Espindola503f8832015-03-02 19:08:03 +0000387 case DS_Warning:
388 Level = LDPL_WARNING;
389 break;
390 case DS_Note:
Rafael Espindolaf3f18542015-03-04 18:51:45 +0000391 case DS_Remark:
Rafael Espindola503f8832015-03-02 19:08:03 +0000392 Level = LDPL_INFO;
393 break;
Rafael Espindola503f8832015-03-02 19:08:03 +0000394 }
395 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000396}
397
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000398static void check(Error E, std::string Msg = "LLVM gold plugin") {
Mehdi Amini48f29602016-11-11 06:04:30 +0000399 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000400 message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());
401 return Error::success();
402 });
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000403}
404
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000405template <typename T> static T check(Expected<T> E) {
406 if (E)
407 return std::move(*E);
408 check(E.takeError());
409 return T();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000410}
411
Rafael Espindolae54d8212014-07-06 14:31:22 +0000412/// Called by gold to see whether this file is one that our plugin can handle.
413/// We'll try to open it and register all the symbols with add_symbol if
414/// possible.
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000415static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
416 int *claimed) {
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000417 MemoryBufferRef BufferRef;
418 std::unique_ptr<MemoryBuffer> Buffer;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000419 if (get_view) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000420 const void *view;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000421 if (get_view(file->handle, &view) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000422 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000423 return LDPS_ERR;
424 }
Nick Lewycky7282dd72015-08-05 21:16:02 +0000425 BufferRef =
426 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
Ivan Krasin5021af52011-09-12 21:47:50 +0000427 } else {
Ivan Krasin639222d2011-09-15 23:13:00 +0000428 int64_t offset = 0;
Nick Lewycky8691c472009-02-05 04:14:23 +0000429 // Gold has found what might be IR part-way inside of a file, such as
430 // an .a archive.
Ivan Krasin5021af52011-09-12 21:47:50 +0000431 if (file->offset) {
432 offset = file->offset;
433 }
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000434 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
435 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
436 offset);
437 if (std::error_code EC = BufferOrErr.getError()) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000438 message(LDPL_ERROR, EC.message().c_str());
Ivan Krasin5021af52011-09-12 21:47:50 +0000439 return LDPS_ERR;
440 }
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000441 Buffer = std::move(BufferOrErr.get());
442 BufferRef = Buffer->getMemBufferRef();
Rafael Espindola56e41f72011-02-08 22:40:47 +0000443 }
Ivan Krasin5021af52011-09-12 21:47:50 +0000444
Rafael Espindola6c472e52014-07-29 20:46:19 +0000445 *claimed = 1;
446
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000447 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
448 if (!ObjOrErr) {
449 handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {
450 std::error_code EC = EI.convertToErrorCode();
451 if (EC == object::object_error::invalid_file_type ||
452 EC == object::object_error::bitcode_section_not_found)
453 *claimed = 0;
454 else
455 message(LDPL_ERROR,
456 "LLVM gold plugin has failed to create LTO module: %s",
457 EI.message().c_str());
458 });
459
460 return *claimed ? LDPS_ERR : LDPS_OK;
Ivan Krasind5f2d8c2011-09-09 00:14:04 +0000461 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000462
463 std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000464
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000465 Modules.resize(Modules.size() + 1);
466 claimed_file &cf = Modules.back();
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000467
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000468 cf.handle = file->handle;
Teresa Johnson683abe72016-05-26 01:46:41 +0000469 // Keep track of the first handle for each file descriptor, since there are
470 // multiple in the case of an archive. This is used later in the case of
471 // ThinLTO parallel backends to ensure that each file is only opened and
472 // released once.
473 auto LeaderHandle =
474 FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
475 cf.leader_handle = LeaderHandle->second;
476 // Save the filesize since for parallel ThinLTO backends we can only
477 // invoke get_input_file once per archive (only for the leader handle).
478 cf.filesize = file->filesize;
479 // In the case of an archive library, all but the first member must have a
480 // non-zero offset, which we can append to the file name to obtain a
481 // unique name.
482 cf.name = file->name;
483 if (file->offset)
484 cf.name += ".llvm." + std::to_string(file->offset) + "." +
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000485 sys::path::filename(Obj->getSourceFileName()).str();
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000486
Rafael Espindola33466a72014-08-21 20:28:55 +0000487 for (auto &Sym : Obj->symbols()) {
488 uint32_t Symflags = Sym.getFlags();
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000489
490 cf.syms.push_back(ld_plugin_symbol());
491 ld_plugin_symbol &sym = cf.syms.back();
Rafael Espindola176e6642014-07-29 21:46:05 +0000492 sym.version = nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000493 StringRef Name = Sym.getName();
494 sym.name = strdup(Name.str().c_str());
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000495
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000496 ResolutionInfo &Res = ResInfo[Name];
Rafael Espindola33466a72014-08-21 20:28:55 +0000497
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000498 Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000499
Rafael Espindola33466a72014-08-21 20:28:55 +0000500 sym.visibility = LDPV_DEFAULT;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000501 GlobalValue::VisibilityTypes Vis = Sym.getVisibility();
502 if (Vis != GlobalValue::DefaultVisibility)
503 Res.DefaultVisibility = false;
504 switch (Vis) {
505 case GlobalValue::DefaultVisibility:
506 break;
507 case GlobalValue::HiddenVisibility:
508 sym.visibility = LDPV_HIDDEN;
509 break;
510 case GlobalValue::ProtectedVisibility:
511 sym.visibility = LDPV_PROTECTED;
512 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000513 }
514
Rafael Espindola33466a72014-08-21 20:28:55 +0000515 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
516 sym.def = LDPK_UNDEF;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000517 if (Symflags & object::BasicSymbolRef::SF_Weak)
Rafael Espindola56548522009-04-24 16:55:21 +0000518 sym.def = LDPK_WEAKUNDEF;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000519 } else if (Symflags & object::BasicSymbolRef::SF_Common)
520 sym.def = LDPK_COMMON;
521 else if (Symflags & object::BasicSymbolRef::SF_Weak)
522 sym.def = LDPK_WEAKDEF;
523 else
Rafael Espindola33466a72014-08-21 20:28:55 +0000524 sym.def = LDPK_DEF;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000525
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000526 sym.size = 0;
Rafael Espindola33466a72014-08-21 20:28:55 +0000527 sym.comdat_key = nullptr;
Rafael Espindola79121102016-10-25 12:02:03 +0000528 int CI = check(Sym.getComdatIndex());
529 if (CI != -1) {
530 StringRef C = Obj->getComdatTable()[CI];
Rafael Espindola62382c92016-10-17 18:51:02 +0000531 sym.comdat_key = strdup(C.str().c_str());
Rafael Espindola79121102016-10-25 12:02:03 +0000532 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000533
534 sym.resolution = LDPR_UNKNOWN;
535 }
536
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000537 if (!cf.syms.empty()) {
Nick Lewycky7282dd72015-08-05 21:16:02 +0000538 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000539 message(LDPL_ERROR, "Unable to add symbols!");
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000540 return LDPS_ERR;
541 }
542 }
543
544 return LDPS_OK;
545}
546
Rafael Espindola538c9a82014-12-23 18:18:37 +0000547static void freeSymName(ld_plugin_symbol &Sym) {
548 free(Sym.name);
549 free(Sym.comdat_key);
550 Sym.name = nullptr;
551 Sym.comdat_key = nullptr;
552}
553
Teresa Johnsona9f65552016-03-04 16:36:06 +0000554/// Helper to get a file's symbols and a view into it via gold callbacks.
555static const void *getSymbolsAndView(claimed_file &F) {
Benjamin Kramer39988a02016-03-08 14:02:46 +0000556 ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000557 if (status == LDPS_NO_SYMS)
558 return nullptr;
Teresa Johnson403a7872015-10-04 14:33:43 +0000559
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000560 if (status != LDPS_OK)
Teresa Johnson403a7872015-10-04 14:33:43 +0000561 message(LDPL_FATAL, "Failed to get symbol information");
562
563 const void *View;
564 if (get_view(F.handle, &View) != LDPS_OK)
565 message(LDPL_FATAL, "Failed to get a view of file");
566
Teresa Johnsona9f65552016-03-04 16:36:06 +0000567 return View;
568}
569
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000570static void addModule(LTO &Lto, claimed_file &F, const void *View) {
Teresa Johnson683abe72016-05-26 01:46:41 +0000571 MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize), F.name);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000572 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
Teresa Johnson6290dbc2015-11-21 21:55:48 +0000573
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000574 if (!ObjOrErr)
Peter Collingbourne10039c02014-09-18 21:28:49 +0000575 message(LDPL_FATAL, "Could not read bitcode from file : %s",
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000576 toString(ObjOrErr.takeError()).c_str());
Peter Collingbourne10039c02014-09-18 21:28:49 +0000577
Rafael Espindola527e8462014-12-09 16:13:59 +0000578 unsigned SymNum = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000579 std::vector<SymbolResolution> Resols(F.syms.size());
Peter Collingbourne07586442016-09-14 02:55:16 +0000580 for (ld_plugin_symbol &Sym : F.syms) {
581 SymbolResolution &R = Resols[SymNum++];
Rafael Espindola527e8462014-12-09 16:13:59 +0000582
Rafael Espindola33466a72014-08-21 20:28:55 +0000583 ld_plugin_symbol_resolution Resolution =
584 (ld_plugin_symbol_resolution)Sym.resolution;
585
Rafael Espindolacaabe222015-12-10 14:19:35 +0000586 ResolutionInfo &Res = ResInfo[Sym.name];
Rafael Espindola890db272014-09-09 20:08:22 +0000587
Rafael Espindola33466a72014-08-21 20:28:55 +0000588 switch (Resolution) {
589 case LDPR_UNKNOWN:
590 llvm_unreachable("Unexpected resolution");
591
592 case LDPR_RESOLVED_IR:
593 case LDPR_RESOLVED_EXEC:
594 case LDPR_RESOLVED_DYN:
Rafael Espindolacaabe222015-12-10 14:19:35 +0000595 case LDPR_PREEMPTED_IR:
596 case LDPR_PREEMPTED_REG:
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000597 case LDPR_UNDEF:
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000598 break;
599
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000600 case LDPR_PREVAILING_DEF_IRONLY:
601 R.Prevailing = true;
Rafael Espindola33466a72014-08-21 20:28:55 +0000602 break;
Teresa Johnsonf99573b2016-08-11 12:56:40 +0000603
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000604 case LDPR_PREVAILING_DEF:
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000605 R.Prevailing = true;
606 R.VisibleToRegularObj = true;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000607 break;
608
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000609 case LDPR_PREVAILING_DEF_IRONLY_EXP:
610 R.Prevailing = true;
611 if (!Res.CanOmitFromDynSym)
612 R.VisibleToRegularObj = true;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000613 break;
614 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000615
616 if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
617 (IsExecutable || !Res.DefaultVisibility))
618 R.FinalDefinitionInLinkageUnit = true;
619
Rafael Espindola538c9a82014-12-23 18:18:37 +0000620 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000621 }
622
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000623 check(Lto.add(std::move(*ObjOrErr), Resols),
624 std::string("Failed to link module ") + F.name);
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000625}
626
Teresa Johnsona9f65552016-03-04 16:36:06 +0000627static void recordFile(std::string Filename, bool TempOutFile) {
628 if (add_input_file(Filename.c_str()) != LDPS_OK)
629 message(LDPL_FATAL,
630 "Unable to add .o file to the link. File left behind in: %s",
631 Filename.c_str());
632 if (TempOutFile)
633 Cleanup.push_back(Filename.c_str());
634}
Rafael Espindola33466a72014-08-21 20:28:55 +0000635
Mehdi Amini970800e2016-08-17 06:23:09 +0000636/// Return the desired output filename given a base input name, a flag
637/// indicating whether a temp file should be generated, and an optional task id.
638/// The new filename generated is returned in \p NewFilename.
639static void getOutputFileName(SmallString<128> InFilename, bool TempOutFile,
Peter Collingbourne6201d782017-01-26 02:07:05 +0000640 SmallString<128> &NewFilename, int TaskID) {
Teresa Johnsona9f65552016-03-04 16:36:06 +0000641 if (TempOutFile) {
642 std::error_code EC =
Mehdi Amini970800e2016-08-17 06:23:09 +0000643 sys::fs::createTemporaryFile("lto-llvm", "o", NewFilename);
Teresa Johnsona9f65552016-03-04 16:36:06 +0000644 if (EC)
645 message(LDPL_FATAL, "Could not create temporary file: %s",
646 EC.message().c_str());
647 } else {
648 NewFilename = InFilename;
Peter Collingbourne6201d782017-01-26 02:07:05 +0000649 if (TaskID > 0)
Teresa Johnsona9f65552016-03-04 16:36:06 +0000650 NewFilename += utostr(TaskID);
Teresa Johnsona9f65552016-03-04 16:36:06 +0000651 }
Teresa Johnsona9f65552016-03-04 16:36:06 +0000652}
653
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000654static CodeGenOpt::Level getCGOptLevel() {
655 switch (options::OptLevel) {
656 case 0:
657 return CodeGenOpt::None;
658 case 1:
659 return CodeGenOpt::Less;
660 case 2:
661 return CodeGenOpt::Default;
662 case 3:
663 return CodeGenOpt::Aggressive;
664 }
665 llvm_unreachable("Invalid optimization level");
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000666}
667
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000668/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
669/// \p NewPrefix strings, if it was specified.
670static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
671 std::string &NewPrefix) {
672 StringRef PrefixReplace = options::thinlto_prefix_replace;
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000673 assert(PrefixReplace.empty() || PrefixReplace.find(";") != StringRef::npos);
674 std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000675 OldPrefix = Split.first.str();
676 NewPrefix = Split.second.str();
677}
678
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000679static std::unique_ptr<LTO> createLTO() {
680 Config Conf;
681 ThinBackend Backend;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000682
683 Conf.CPU = options::mcpu;
684 Conf.Options = InitTargetOptionsFromCodeGenFlags();
685
686 // Disable the new X86 relax relocations since gold might not support them.
687 // FIXME: Check the gold version or add a new option to enable them.
688 Conf.Options.RelaxELFRelocations = false;
689
690 Conf.MAttrs = MAttrs;
691 Conf.RelocModel = *RelocationModel;
692 Conf.CGOptLevel = getCGOptLevel();
693 Conf.DisableVerify = options::DisableVerify;
694 Conf.OptLevel = options::OptLevel;
Teresa Johnson896fee22016-09-23 20:35:19 +0000695 if (options::Parallelism)
696 Backend = createInProcessThinBackend(options::Parallelism);
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000697 if (options::thinlto_index_only) {
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000698 std::string OldPrefix, NewPrefix;
699 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000700 Backend = createWriteIndexesThinBackend(
701 OldPrefix, NewPrefix, options::thinlto_emit_imports_files,
702 options::thinlto_linked_objects_file);
Teresa Johnson84174c32016-05-10 13:48:23 +0000703 }
704
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000705 Conf.OverrideTriple = options::triple;
706 Conf.DefaultTriple = sys::getDefaultTargetTriple();
707
708 Conf.DiagHandler = diagnosticHandler;
709
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000710 switch (options::TheOutputType) {
711 case options::OT_NORMAL:
712 break;
713
714 case options::OT_DISABLE:
Mehdi Amini6ec23332016-08-22 16:41:58 +0000715 Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000716 break;
717
718 case options::OT_BC_ONLY:
Mehdi Amini6ec23332016-08-22 16:41:58 +0000719 Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000720 std::error_code EC;
721 raw_fd_ostream OS(output_name, EC, sys::fs::OpenFlags::F_None);
722 if (EC)
723 message(LDPL_FATAL, "Failed to write the output file.");
724 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ false);
725 return false;
726 };
727 break;
728
729 case options::OT_SAVE_TEMPS:
Mehdi Aminieccffad2016-08-18 00:12:33 +0000730 check(Conf.addSaveTemps(output_name + ".",
731 /* UseInputModulePath */ true));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000732 break;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000733 }
734
Dehao Chen27978002016-12-16 16:48:46 +0000735 if (!options::sample_profile.empty())
736 Conf.SampleProfile = options::sample_profile;
737
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000738 return llvm::make_unique<LTO>(std::move(Conf), Backend,
Teresa Johnson896fee22016-09-23 20:35:19 +0000739 options::ParallelCodeGenParallelismLevel);
Teresa Johnson84174c32016-05-10 13:48:23 +0000740}
741
Teresa Johnson3f212b82016-09-21 19:12:05 +0000742// Write empty files that may be expected by a distributed build
743// system when invoked with thinlto_index_only. This is invoked when
744// the linker has decided not to include the given module in the
745// final link. Frequently the distributed build system will want to
746// confirm that all expected outputs are created based on all of the
747// modules provided to the linker.
748static void writeEmptyDistributedBuildOutputs(std::string &ModulePath,
749 std::string &OldPrefix,
750 std::string &NewPrefix) {
751 std::string NewModulePath =
752 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
753 std::error_code EC;
754 {
755 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
756 sys::fs::OpenFlags::F_None);
757 if (EC)
758 message(LDPL_FATAL, "Failed to write '%s': %s",
759 (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
760 }
761 if (options::thinlto_emit_imports_files) {
762 raw_fd_ostream OS(NewModulePath + ".imports", EC,
763 sys::fs::OpenFlags::F_None);
764 if (EC)
765 message(LDPL_FATAL, "Failed to write '%s': %s",
766 (NewModulePath + ".imports").c_str(), EC.message().c_str());
767 }
768}
769
Rafael Espindolab6393292014-07-30 01:23:45 +0000770/// gold informs us that all symbols have been read. At this point, we use
771/// get_symbols to see if any of our definitions have been overridden by a
772/// native object file. Then, perform optimization and codegen.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000773static ld_plugin_status allSymbolsReadHook() {
Rafael Espindola33466a72014-08-21 20:28:55 +0000774 if (Modules.empty())
775 return LDPS_OK;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000776
Teresa Johnsona9f65552016-03-04 16:36:06 +0000777 if (unsigned NumOpts = options::extra.size())
778 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
779
Teresa Johnson765941a2016-08-20 01:24:07 +0000780 // Map to own RAII objects that manage the file opening and releasing
781 // interfaces with gold. This is needed only for ThinLTO mode, since
782 // unlike regular LTO, where addModule will result in the opened file
783 // being merged into a new combined module, we need to keep these files open
784 // through Lto->run().
785 DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
786
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000787 std::unique_ptr<LTO> Lto = createLTO();
Teresa Johnson403a7872015-10-04 14:33:43 +0000788
Teresa Johnson3f212b82016-09-21 19:12:05 +0000789 std::string OldPrefix, NewPrefix;
790 if (options::thinlto_index_only)
791 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
792
Rafael Espindolad2aac572014-07-30 01:52:40 +0000793 for (claimed_file &F : Modules) {
Teresa Johnson765941a2016-08-20 01:24:07 +0000794 if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
795 HandleToInputFile.insert(std::make_pair(
796 F.leader_handle, llvm::make_unique<PluginInputFile>(F.handle)));
Teresa Johnsona9f65552016-03-04 16:36:06 +0000797 const void *View = getSymbolsAndView(F);
Teresa Johnson3f212b82016-09-21 19:12:05 +0000798 if (!View) {
799 if (options::thinlto_index_only)
800 // Write empty output files that may be expected by the distributed
801 // build system.
802 writeEmptyDistributedBuildOutputs(F.name, OldPrefix, NewPrefix);
Evgeniy Stepanov4dc3c8d2016-03-11 00:51:57 +0000803 continue;
Teresa Johnson3f212b82016-09-21 19:12:05 +0000804 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000805 addModule(*Lto, F, View);
Rafael Espindola77b6d012010-06-14 21:20:52 +0000806 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000807
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000808 SmallString<128> Filename;
Mehdi Amini970800e2016-08-17 06:23:09 +0000809 // Note that getOutputFileName will append a unique ID for each task
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000810 if (!options::obj_path.empty())
811 Filename = options::obj_path;
812 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
813 Filename = output_name + ".o";
814 bool SaveTemps = !Filename.empty();
Rafael Espindola33466a72014-08-21 20:28:55 +0000815
Peter Collingbourne6201d782017-01-26 02:07:05 +0000816 size_t MaxTasks = Lto->getMaxTasks();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000817 std::vector<uintptr_t> IsTemporary(MaxTasks);
818 std::vector<SmallString<128>> Filenames(MaxTasks);
819
Peter Collingbourne80186a52016-09-23 21:33:43 +0000820 auto AddStream =
821 [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
822 IsTemporary[Task] = !SaveTemps;
823 getOutputFileName(Filename, /*TempOutFile=*/!SaveTemps, Filenames[Task],
Peter Collingbourne6201d782017-01-26 02:07:05 +0000824 Task);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000825 int FD;
826 std::error_code EC =
827 sys::fs::openFileForWrite(Filenames[Task], FD, sys::fs::F_None);
828 if (EC)
Peter Collingbourne5b8a1bd2017-01-25 03:35:28 +0000829 message(LDPL_FATAL, "Could not open file %s: %s", Filenames[Task].c_str(),
830 EC.message().c_str());
Peter Collingbourne80186a52016-09-23 21:33:43 +0000831 return llvm::make_unique<lto::NativeObjectStream>(
832 llvm::make_unique<llvm::raw_fd_ostream>(FD, true));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000833 };
834
Peter Collingbourne80186a52016-09-23 21:33:43 +0000835 auto AddFile = [&](size_t Task, StringRef Path) { Filenames[Task] = Path; };
836
837 NativeObjectCache Cache;
838 if (!options::cache_dir.empty())
839 Cache = localCache(options::cache_dir, AddFile);
840
841 check(Lto->run(AddStream, Cache));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000842
843 if (options::TheOutputType == options::OT_DISABLE ||
844 options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000845 return LDPS_OK;
846
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000847 if (options::thinlto_index_only) {
Teresa Johnson95597ae2017-02-02 17:33:53 +0000848 if (llvm::AreStatisticsEnabled())
849 llvm::PrintStatistics();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000850 cleanup_hook();
851 exit(0);
Rafael Espindolaba3398b2010-05-13 13:39:31 +0000852 }
Rafael Espindola143fc3b2013-10-16 12:47:04 +0000853
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000854 for (unsigned I = 0; I != MaxTasks; ++I)
855 if (!Filenames[I].empty())
856 recordFile(Filenames[I].str(), IsTemporary[I]);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000857
Rafael Espindolaef498152010-06-23 20:20:59 +0000858 if (!options::extra_library_path.empty() &&
Rafael Espindola33466a72014-08-21 20:28:55 +0000859 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
860 message(LDPL_FATAL, "Unable to set the extra library path.");
Shuxin Yang1826ae22013-08-12 21:07:31 +0000861
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000862 return LDPS_OK;
863}
864
Rafael Espindola55b32542014-08-11 19:06:54 +0000865static ld_plugin_status all_symbols_read_hook(void) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000866 ld_plugin_status Ret = allSymbolsReadHook();
Rafael Espindola947bdb62014-11-25 20:52:49 +0000867 llvm_shutdown();
868
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000869 if (options::TheOutputType == options::OT_BC_ONLY ||
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000870 options::TheOutputType == options::OT_DISABLE) {
Davide Italiano289a43e2016-03-20 20:12:33 +0000871 if (options::TheOutputType == options::OT_DISABLE) {
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000872 // Remove the output file here since ld.bfd creates the output file
873 // early.
Davide Italiano289a43e2016-03-20 20:12:33 +0000874 std::error_code EC = sys::fs::remove(output_name);
875 if (EC)
876 message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
877 EC.message().c_str());
878 }
Rafael Espindola55b32542014-08-11 19:06:54 +0000879 exit(0);
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000880 }
Rafael Espindola55b32542014-08-11 19:06:54 +0000881
882 return Ret;
883}
884
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000885static ld_plugin_status cleanup_hook(void) {
Rafael Espindolad2aac572014-07-30 01:52:40 +0000886 for (std::string &Name : Cleanup) {
887 std::error_code EC = sys::fs::remove(Name);
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000888 if (EC)
Rafael Espindolad2aac572014-07-30 01:52:40 +0000889 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000890 EC.message().c_str());
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000891 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000892
893 return LDPS_OK;
894}