blob: dd6d47f5d708507be3cb136bd08ac5599fa608db [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
Dylan Noblesmith9e5b1782011-12-22 23:04:07 +000015#include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
Rafael Espindolaf7ecb112014-08-22 23:26:10 +000016#include "llvm/ADT/DenseSet.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000017#include "llvm/ADT/StringSet.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000018#include "llvm/Analysis/TargetLibraryInfo.h"
NAKAMURA Takumib0a52832015-02-02 05:47:30 +000019#include "llvm/Analysis/TargetTransformInfo.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000020#include "llvm/Bitcode/ReaderWriter.h"
21#include "llvm/CodeGen/Analysis.h"
Rafael Espindola6b244b12014-06-19 21:14:13 +000022#include "llvm/CodeGen/CommandFlags.h"
Rafael Espindola890db272014-09-09 20:08:22 +000023#include "llvm/IR/Constants.h"
Rafael Espindolad0b23be2015-01-10 00:07:30 +000024#include "llvm/IR/DiagnosticInfo.h"
25#include "llvm/IR/DiagnosticPrinter.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000026#include "llvm/IR/LLVMContext.h"
27#include "llvm/IR/Module.h"
28#include "llvm/IR/Verifier.h"
29#include "llvm/Linker/Linker.h"
30#include "llvm/MC/SubtargetFeature.h"
31#include "llvm/Object/IRObjectFile.h"
32#include "llvm/PassManager.h"
33#include "llvm/Support/FormattedStream.h"
34#include "llvm/Support/Host.h"
Rafael Espindola947bdb62014-11-25 20:52:49 +000035#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000036#include "llvm/Support/MemoryBuffer.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000037#include "llvm/Support/TargetRegistry.h"
Rafael Espindola6b244b12014-06-19 21:14:13 +000038#include "llvm/Support/TargetSelect.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000039#include "llvm/Transforms/IPO.h"
40#include "llvm/Transforms/IPO/PassManagerBuilder.h"
41#include "llvm/Transforms/Utils/GlobalStatus.h"
42#include "llvm/Transforms/Utils/ModuleUtils.h"
Rafael Espindolaf7ecb112014-08-22 23:26:10 +000043#include "llvm/Transforms/Utils/ValueMapper.h"
Nick Lewyckyfb643e42009-02-03 07:13:24 +000044#include <list>
Chandler Carruth07baed52014-01-13 08:04:33 +000045#include <plugin-api.h>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000046#include <system_error>
Nick Lewyckyfb643e42009-02-03 07:13:24 +000047#include <vector>
48
Sylvestre Ledru53999792014-02-11 17:30:18 +000049#ifndef LDPO_PIE
50// FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
51// Precise and Debian Wheezy (binutils 2.23 is required)
52# define LDPO_PIE 3
53#endif
54
Nick Lewyckyfb643e42009-02-03 07:13:24 +000055using namespace llvm;
56
57namespace {
Rafael Espindolabfb8b912014-06-20 01:37:35 +000058struct claimed_file {
59 void *handle;
60 std::vector<ld_plugin_symbol> syms;
61};
Nick Lewyckyfb643e42009-02-03 07:13:24 +000062}
Rafael Espindolabfb8b912014-06-20 01:37:35 +000063
64static ld_plugin_status discard_message(int level, const char *format, ...) {
65 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
66 // callback in the transfer vector. This should never be called.
67 abort();
68}
69
Rafael Espindola33466a72014-08-21 20:28:55 +000070static ld_plugin_get_input_file get_input_file = nullptr;
71static ld_plugin_release_input_file release_input_file = nullptr;
Rafael Espindola176e6642014-07-29 21:46:05 +000072static ld_plugin_add_symbols add_symbols = nullptr;
73static ld_plugin_get_symbols get_symbols = nullptr;
74static ld_plugin_add_input_file add_input_file = nullptr;
75static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
76static ld_plugin_get_view get_view = nullptr;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000077static ld_plugin_message message = discard_message;
Rafael Espindola33466a72014-08-21 20:28:55 +000078static Reloc::Model RelocationModel = Reloc::Default;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000079static std::string output_name = "";
80static std::list<claimed_file> Modules;
81static std::vector<std::string> Cleanup;
Rafael Espindola6b244b12014-06-19 21:14:13 +000082static llvm::TargetOptions TargetOpts;
Nick Lewyckyfb643e42009-02-03 07:13:24 +000083
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +000084namespace options {
Rafael Espindola6953a3a2014-11-24 21:18:14 +000085 enum OutputType {
86 OT_NORMAL,
87 OT_DISABLE,
88 OT_BC_ONLY,
89 OT_SAVE_TEMPS
90 };
Dan Gohmanebb4ae02010-04-16 00:42:57 +000091 static bool generate_api_file = false;
Rafael Espindola6953a3a2014-11-24 21:18:14 +000092 static OutputType TheOutputType = OT_NORMAL;
Shuxin Yang1826ae22013-08-12 21:07:31 +000093 static std::string obj_path;
Rafael Espindolaef498152010-06-23 20:20:59 +000094 static std::string extra_library_path;
Rafael Espindola4ef89f52010-08-09 21:09:46 +000095 static std::string triple;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +000096 static std::string mcpu;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +000097 // Additional options to pass into the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +000098 // Note: This array will contain all plugin options which are not claimed
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +000099 // as plugin exclusive to pass to the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +0000100 // For example, "generate-api-file" and "as"options are for the plugin
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000101 // use only and will not be passed.
Rafael Espindola125b9242014-07-29 19:17:44 +0000102 static std::vector<const char *> extra;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000103
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000104 static void process_plugin_option(const char* opt_)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000105 {
Rafael Espindola176e6642014-07-29 21:46:05 +0000106 if (opt_ == nullptr)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000107 return;
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000108 llvm::StringRef opt = opt_;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000109
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000110 if (opt == "generate-api-file") {
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000111 generate_api_file = true;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000112 } else if (opt.startswith("mcpu=")) {
113 mcpu = opt.substr(strlen("mcpu="));
Rafael Espindolaef498152010-06-23 20:20:59 +0000114 } else if (opt.startswith("extra-library-path=")) {
115 extra_library_path = opt.substr(strlen("extra_library_path="));
Rafael Espindola148c3282010-08-10 16:32:15 +0000116 } else if (opt.startswith("mtriple=")) {
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000117 triple = opt.substr(strlen("mtriple="));
Shuxin Yang1826ae22013-08-12 21:07:31 +0000118 } else if (opt.startswith("obj-path=")) {
119 obj_path = opt.substr(strlen("obj-path="));
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000120 } else if (opt == "emit-llvm") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000121 TheOutputType = OT_BC_ONLY;
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000122 } else if (opt == "save-temps") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000123 TheOutputType = OT_SAVE_TEMPS;
124 } else if (opt == "disable-output") {
125 TheOutputType = OT_DISABLE;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000126 } else {
127 // Save this option to pass to the code generator.
Rafael Espindola33466a72014-08-21 20:28:55 +0000128 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
129 // add that.
130 if (extra.empty())
131 extra.push_back("LLVMgold");
132
Rafael Espindola125b9242014-07-29 19:17:44 +0000133 extra.push_back(opt_);
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000134 }
135 }
136}
137
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000138static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
139 int *claimed);
140static ld_plugin_status all_symbols_read_hook(void);
141static ld_plugin_status cleanup_hook(void);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000142
143extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
144ld_plugin_status onload(ld_plugin_tv *tv) {
Peter Collingbourne1505c0a2014-07-03 23:28:03 +0000145 InitializeAllTargetInfos();
146 InitializeAllTargets();
147 InitializeAllTargetMCs();
148 InitializeAllAsmParsers();
149 InitializeAllAsmPrinters();
150
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000151 // We're given a pointer to the first transfer vector. We read through them
152 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
153 // contain pointers to functions that we need to call to register our own
154 // hooks. The others are addresses of functions we can use to call into gold
155 // for services.
156
157 bool registeredClaimFile = false;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000158 bool RegisteredAllSymbolsRead = false;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000159
160 for (; tv->tv_tag != LDPT_NULL; ++tv) {
161 switch (tv->tv_tag) {
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000162 case LDPT_OUTPUT_NAME:
163 output_name = tv->tv_u.tv_string;
164 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000165 case LDPT_LINKER_OUTPUT:
166 switch (tv->tv_u.tv_val) {
167 case LDPO_REL: // .o
168 case LDPO_DYN: // .so
Rafael Espindola76e376d2014-02-10 20:38:38 +0000169 case LDPO_PIE: // position independent executable
Rafael Espindola33466a72014-08-21 20:28:55 +0000170 RelocationModel = Reloc::PIC_;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000171 break;
172 case LDPO_EXEC: // .exe
Rafael Espindola33466a72014-08-21 20:28:55 +0000173 RelocationModel = Reloc::Static;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000174 break;
175 default:
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000176 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000177 return LDPS_ERR;
178 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000179 break;
180 case LDPT_OPTION:
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000181 options::process_plugin_option(tv->tv_u.tv_string);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000182 break;
183 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
184 ld_plugin_register_claim_file callback;
185 callback = tv->tv_u.tv_register_claim_file;
186
Rafael Espindola54f82b72014-07-30 01:36:32 +0000187 if (callback(claim_file_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000188 return LDPS_ERR;
189
190 registeredClaimFile = true;
191 } break;
192 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
193 ld_plugin_register_all_symbols_read callback;
194 callback = tv->tv_u.tv_register_all_symbols_read;
195
Rafael Espindola54f82b72014-07-30 01:36:32 +0000196 if (callback(all_symbols_read_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000197 return LDPS_ERR;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000198
Rafael Espindola6b244b12014-06-19 21:14:13 +0000199 RegisteredAllSymbolsRead = true;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000200 } break;
201 case LDPT_REGISTER_CLEANUP_HOOK: {
202 ld_plugin_register_cleanup callback;
203 callback = tv->tv_u.tv_register_cleanup;
204
Rafael Espindola54f82b72014-07-30 01:36:32 +0000205 if (callback(cleanup_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000206 return LDPS_ERR;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000207 } break;
Rafael Espindola33466a72014-08-21 20:28:55 +0000208 case LDPT_GET_INPUT_FILE:
209 get_input_file = tv->tv_u.tv_get_input_file;
210 break;
211 case LDPT_RELEASE_INPUT_FILE:
212 release_input_file = tv->tv_u.tv_release_input_file;
213 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000214 case LDPT_ADD_SYMBOLS:
215 add_symbols = tv->tv_u.tv_add_symbols;
216 break;
Rafael Espindolacda29112013-10-03 18:29:09 +0000217 case LDPT_GET_SYMBOLS_V2:
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000218 get_symbols = tv->tv_u.tv_get_symbols;
219 break;
220 case LDPT_ADD_INPUT_FILE:
221 add_input_file = tv->tv_u.tv_add_input_file;
222 break;
Rafael Espindolaef498152010-06-23 20:20:59 +0000223 case LDPT_SET_EXTRA_LIBRARY_PATH:
224 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
225 break;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000226 case LDPT_GET_VIEW:
227 get_view = tv->tv_u.tv_get_view;
228 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000229 case LDPT_MESSAGE:
230 message = tv->tv_u.tv_message;
231 break;
232 default:
233 break;
234 }
235 }
236
Rafael Espindolae08484d2009-02-18 08:30:15 +0000237 if (!registeredClaimFile) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000238 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000239 return LDPS_ERR;
240 }
Rafael Espindolae08484d2009-02-18 08:30:15 +0000241 if (!add_symbols) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000242 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000243 return LDPS_ERR;
244 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000245
Rafael Espindolaa0d30a92014-06-19 22:20:07 +0000246 if (!RegisteredAllSymbolsRead)
247 return LDPS_OK;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000248
Rafael Espindola33466a72014-08-21 20:28:55 +0000249 if (!get_input_file) {
250 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
251 return LDPS_ERR;
Rafael Espindolac273aac2014-06-19 22:54:47 +0000252 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000253 if (!release_input_file) {
254 message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
255 return LDPS_ERR;
Tom Roederb5081192014-06-26 20:43:27 +0000256 }
257
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000258 return LDPS_OK;
259}
260
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000261static const GlobalObject *getBaseObject(const GlobalValue &GV) {
262 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
263 return GA->getBaseObject();
264 return cast<GlobalObject>(&GV);
265}
266
Rafael Espindola527e8462014-12-09 16:13:59 +0000267static bool shouldSkip(uint32_t Symflags) {
268 if (!(Symflags & object::BasicSymbolRef::SF_Global))
269 return true;
270 if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
271 return true;
272 return false;
273}
274
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000275static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
276 assert(DI.getSeverity() == DS_Error && "Only expecting errors");
277 const auto &BDI = cast<BitcodeDiagnosticInfo>(DI);
278 std::error_code EC = BDI.getError();
279 if (EC == BitcodeError::InvalidBitcodeSignature)
280 return;
281
282 std::string ErrStorage;
283 {
284 raw_string_ostream OS(ErrStorage);
285 DiagnosticPrinterRawOStream DP(OS);
286 DI.print(DP);
287 }
288 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
289 ErrStorage.c_str());
290}
291
Rafael Espindolae54d8212014-07-06 14:31:22 +0000292/// Called by gold to see whether this file is one that our plugin can handle.
293/// We'll try to open it and register all the symbols with add_symbol if
294/// possible.
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000295static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
296 int *claimed) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000297 LLVMContext Context;
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000298 MemoryBufferRef BufferRef;
299 std::unique_ptr<MemoryBuffer> Buffer;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000300 if (get_view) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000301 const void *view;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000302 if (get_view(file->handle, &view) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000303 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000304 return LDPS_ERR;
305 }
Rafael Espindolab0fc4cf2014-10-22 02:23:31 +0000306 BufferRef = MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
Ivan Krasin5021af52011-09-12 21:47:50 +0000307 } else {
Ivan Krasin639222d2011-09-15 23:13:00 +0000308 int64_t offset = 0;
Nick Lewycky8691c472009-02-05 04:14:23 +0000309 // Gold has found what might be IR part-way inside of a file, such as
310 // an .a archive.
Ivan Krasin5021af52011-09-12 21:47:50 +0000311 if (file->offset) {
312 offset = file->offset;
313 }
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000314 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
315 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
316 offset);
317 if (std::error_code EC = BufferOrErr.getError()) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000318 message(LDPL_ERROR, EC.message().c_str());
Ivan Krasin5021af52011-09-12 21:47:50 +0000319 return LDPS_ERR;
320 }
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000321 Buffer = std::move(BufferOrErr.get());
322 BufferRef = Buffer->getMemBufferRef();
Rafael Espindola56e41f72011-02-08 22:40:47 +0000323 }
Ivan Krasin5021af52011-09-12 21:47:50 +0000324
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000325 Context.setDiagnosticHandler(diagnosticHandler);
David Blaikie10a27df2014-09-03 17:59:23 +0000326 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
Rafael Espindola5dec7ea2014-12-09 20:36:13 +0000327 object::IRObjectFile::create(BufferRef, Context);
Rafael Espindola33466a72014-08-21 20:28:55 +0000328 std::error_code EC = ObjOrErr.getError();
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000329 if (EC == object::object_error::invalid_file_type ||
Peter Collingbourne10039c02014-09-18 21:28:49 +0000330 EC == object::object_error::bitcode_section_not_found)
Ivan Krasin5021af52011-09-12 21:47:50 +0000331 return LDPS_OK;
332
Rafael Espindola6c472e52014-07-29 20:46:19 +0000333 *claimed = 1;
334
Rafael Espindola33466a72014-08-21 20:28:55 +0000335 if (EC) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000336 message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
Rafael Espindola33466a72014-08-21 20:28:55 +0000337 EC.message().c_str());
Rafael Espindola6c472e52014-07-29 20:46:19 +0000338 return LDPS_ERR;
Ivan Krasind5f2d8c2011-09-09 00:14:04 +0000339 }
David Blaikie10a27df2014-09-03 17:59:23 +0000340 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000341
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000342 Modules.resize(Modules.size() + 1);
343 claimed_file &cf = Modules.back();
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000344
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000345 cf.handle = file->handle;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000346
Rafael Espindola33466a72014-08-21 20:28:55 +0000347 for (auto &Sym : Obj->symbols()) {
348 uint32_t Symflags = Sym.getFlags();
Rafael Espindola527e8462014-12-09 16:13:59 +0000349 if (shouldSkip(Symflags))
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000350 continue;
351
352 cf.syms.push_back(ld_plugin_symbol());
353 ld_plugin_symbol &sym = cf.syms.back();
Rafael Espindola176e6642014-07-29 21:46:05 +0000354 sym.version = nullptr;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000355
Rafael Espindola33466a72014-08-21 20:28:55 +0000356 SmallString<64> Name;
357 {
358 raw_svector_ostream OS(Name);
359 Sym.printName(OS);
360 }
361 sym.name = strdup(Name.c_str());
362
363 const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
364
365 sym.visibility = LDPV_DEFAULT;
366 if (GV) {
367 switch (GV->getVisibility()) {
368 case GlobalValue::DefaultVisibility:
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000369 sym.visibility = LDPV_DEFAULT;
370 break;
Rafael Espindola33466a72014-08-21 20:28:55 +0000371 case GlobalValue::HiddenVisibility:
372 sym.visibility = LDPV_HIDDEN;
373 break;
374 case GlobalValue::ProtectedVisibility:
375 sym.visibility = LDPV_PROTECTED;
376 break;
377 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000378 }
379
Rafael Espindola33466a72014-08-21 20:28:55 +0000380 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
381 sym.def = LDPK_UNDEF;
382 if (GV && GV->hasExternalWeakLinkage())
Rafael Espindola56548522009-04-24 16:55:21 +0000383 sym.def = LDPK_WEAKUNDEF;
Rafael Espindola33466a72014-08-21 20:28:55 +0000384 } else {
385 sym.def = LDPK_DEF;
386 if (GV) {
387 assert(!GV->hasExternalWeakLinkage() &&
388 !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
389 if (GV->hasCommonLinkage())
390 sym.def = LDPK_COMMON;
391 else if (GV->isWeakForLinker())
392 sym.def = LDPK_WEAKDEF;
393 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000394 }
395
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000396 sym.size = 0;
Rafael Espindola33466a72014-08-21 20:28:55 +0000397 sym.comdat_key = nullptr;
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000398 if (GV) {
399 const GlobalObject *Base = getBaseObject(*GV);
400 if (!Base)
401 message(LDPL_FATAL, "Unable to determine comdat of alias!");
402 const Comdat *C = Base->getComdat();
403 if (C)
404 sym.comdat_key = strdup(C->getName().str().c_str());
405 else if (Base->hasWeakLinkage() || Base->hasLinkOnceLinkage())
406 sym.comdat_key = strdup(sym.name);
407 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000408
409 sym.resolution = LDPR_UNKNOWN;
410 }
411
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000412 if (!cf.syms.empty()) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000413 if (add_symbols(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
414 message(LDPL_ERROR, "Unable to add symbols!");
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000415 return LDPS_ERR;
416 }
417 }
418
419 return LDPS_OK;
420}
421
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000422static void keepGlobalValue(GlobalValue &GV,
423 std::vector<GlobalAlias *> &KeptAliases) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000424 assert(!GV.hasLocalLinkage());
425
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000426 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
427 KeptAliases.push_back(GA);
428
Rafael Espindola33466a72014-08-21 20:28:55 +0000429 switch (GV.getLinkage()) {
430 default:
431 break;
432 case GlobalValue::LinkOnceAnyLinkage:
433 GV.setLinkage(GlobalValue::WeakAnyLinkage);
434 break;
435 case GlobalValue::LinkOnceODRLinkage:
436 GV.setLinkage(GlobalValue::WeakODRLinkage);
437 break;
438 }
439
440 assert(!GV.isDiscardableIfUnused());
441}
442
Rafael Espindola33466a72014-08-21 20:28:55 +0000443static void internalize(GlobalValue &GV) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000444 if (GV.isDeclarationForLinker())
Rafael Espindola33466a72014-08-21 20:28:55 +0000445 return; // We get here if there is a matching asm definition.
446 if (!GV.hasLocalLinkage())
447 GV.setLinkage(GlobalValue::InternalLinkage);
448}
449
450static void drop(GlobalValue &GV) {
451 if (auto *F = dyn_cast<Function>(&GV)) {
452 F->deleteBody();
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000453 F->setComdat(nullptr); // Should deleteBody do this?
Rafael Espindola33466a72014-08-21 20:28:55 +0000454 return;
455 }
456
457 if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
458 Var->setInitializer(nullptr);
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000459 Var->setLinkage(
460 GlobalValue::ExternalLinkage); // Should setInitializer do this?
461 Var->setComdat(nullptr); // and this?
Rafael Espindola33466a72014-08-21 20:28:55 +0000462 return;
463 }
464
465 auto &Alias = cast<GlobalAlias>(GV);
466 Module &M = *Alias.getParent();
467 PointerType &Ty = *cast<PointerType>(Alias.getType());
468 GlobalValue::LinkageTypes L = Alias.getLinkage();
469 auto *Var =
470 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
471 /*Initializer*/ nullptr);
472 Var->takeName(&Alias);
473 Alias.replaceAllUsesWith(Var);
Rafael Espindola71143ed2014-09-10 19:39:41 +0000474 Alias.eraseFromParent();
Rafael Espindola33466a72014-08-21 20:28:55 +0000475}
476
477static const char *getResolutionName(ld_plugin_symbol_resolution R) {
478 switch (R) {
479 case LDPR_UNKNOWN:
480 return "UNKNOWN";
481 case LDPR_UNDEF:
482 return "UNDEF";
483 case LDPR_PREVAILING_DEF:
484 return "PREVAILING_DEF";
485 case LDPR_PREVAILING_DEF_IRONLY:
486 return "PREVAILING_DEF_IRONLY";
487 case LDPR_PREEMPTED_REG:
488 return "PREEMPTED_REG";
489 case LDPR_PREEMPTED_IR:
490 return "PREEMPTED_IR";
491 case LDPR_RESOLVED_IR:
492 return "RESOLVED_IR";
493 case LDPR_RESOLVED_EXEC:
494 return "RESOLVED_EXEC";
495 case LDPR_RESOLVED_DYN:
496 return "RESOLVED_DYN";
497 case LDPR_PREVAILING_DEF_IRONLY_EXP:
498 return "PREVAILING_DEF_IRONLY_EXP";
499 }
Rafael Espindola2754dbb2014-10-10 00:48:13 +0000500 llvm_unreachable("Unknown resolution");
Rafael Espindola33466a72014-08-21 20:28:55 +0000501}
502
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000503namespace {
504class LocalValueMaterializer : public ValueMaterializer {
505 DenseSet<GlobalValue *> &Dropped;
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000506 DenseMap<GlobalObject *, GlobalObject *> LocalVersions;
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000507
508public:
509 LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
510 Value *materializeValueFor(Value *V) override;
511};
512}
513
514Value *LocalValueMaterializer::materializeValueFor(Value *V) {
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000515 auto *GO = dyn_cast<GlobalObject>(V);
516 if (!GO)
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000517 return nullptr;
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000518
519 auto I = LocalVersions.find(GO);
520 if (I != LocalVersions.end())
521 return I->second;
522
523 if (!Dropped.count(GO))
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000524 return nullptr;
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000525
526 Module &M = *GO->getParent();
527 GlobalValue::LinkageTypes L = GO->getLinkage();
528 GlobalObject *Declaration;
529 if (auto *F = dyn_cast<Function>(GO)) {
530 Declaration = Function::Create(F->getFunctionType(), L, "", &M);
531 } else {
532 auto *Var = cast<GlobalVariable>(GO);
533 Declaration = new GlobalVariable(M, Var->getType()->getElementType(),
534 Var->isConstant(), L,
535 /*Initializer*/ nullptr);
536 }
537 Declaration->takeName(GO);
538 Declaration->copyAttributesFrom(GO);
539
540 GO->setLinkage(GlobalValue::InternalLinkage);
541 GO->setName(Declaration->getName());
542 Dropped.erase(GO);
543 GO->replaceAllUsesWith(Declaration);
544
545 LocalVersions[Declaration] = GO;
546
547 return GO;
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000548}
549
550static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
551 LocalValueMaterializer *Materializer) {
552 return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
553}
554
Rafael Espindola538c9a82014-12-23 18:18:37 +0000555static void freeSymName(ld_plugin_symbol &Sym) {
556 free(Sym.name);
557 free(Sym.comdat_key);
558 Sym.name = nullptr;
559 Sym.comdat_key = nullptr;
560}
561
Rafael Espindola33466a72014-08-21 20:28:55 +0000562static std::unique_ptr<Module>
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000563getModuleForFile(LLVMContext &Context, claimed_file &F,
564 off_t Filesize, raw_fd_ostream *ApiFile,
Rafael Espindola33466a72014-08-21 20:28:55 +0000565 StringSet<> &Internalize, StringSet<> &Maybe) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000566
567 if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
568 message(LDPL_FATAL, "Failed to get symbol information");
569
570 const void *View;
571 if (get_view(F.handle, &View) != LDPS_OK)
572 message(LDPL_FATAL, "Failed to get a view of file");
573
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000574 MemoryBufferRef BufferRef(StringRef((const char *)View, Filesize), "");
Rafael Espindola527e8462014-12-09 16:13:59 +0000575 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
Rafael Espindola5dec7ea2014-12-09 20:36:13 +0000576 object::IRObjectFile::create(BufferRef, Context);
Rafael Espindola527e8462014-12-09 16:13:59 +0000577
578 if (std::error_code EC = ObjOrErr.getError())
Peter Collingbourne10039c02014-09-18 21:28:49 +0000579 message(LDPL_FATAL, "Could not read bitcode from file : %s",
580 EC.message().c_str());
581
Rafael Espindola527e8462014-12-09 16:13:59 +0000582 object::IRObjectFile &Obj = **ObjOrErr;
Rafael Espindola33466a72014-08-21 20:28:55 +0000583
Rafael Espindola527e8462014-12-09 16:13:59 +0000584 Module &M = Obj.getModule();
Rafael Espindola33466a72014-08-21 20:28:55 +0000585
586 SmallPtrSet<GlobalValue *, 8> Used;
Rafael Espindola527e8462014-12-09 16:13:59 +0000587 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
Rafael Espindola33466a72014-08-21 20:28:55 +0000588
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000589 DenseSet<GlobalValue *> Drop;
590 std::vector<GlobalAlias *> KeptAliases;
Rafael Espindola527e8462014-12-09 16:13:59 +0000591
592 unsigned SymNum = 0;
593 for (auto &ObjSym : Obj.symbols()) {
594 if (shouldSkip(ObjSym.getFlags()))
595 continue;
596 ld_plugin_symbol &Sym = F.syms[SymNum];
597 ++SymNum;
598
Rafael Espindola33466a72014-08-21 20:28:55 +0000599 ld_plugin_symbol_resolution Resolution =
600 (ld_plugin_symbol_resolution)Sym.resolution;
601
602 if (options::generate_api_file)
603 *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
604
Rafael Espindola527e8462014-12-09 16:13:59 +0000605 GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
Rafael Espindola538c9a82014-12-23 18:18:37 +0000606 if (!GV) {
607 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000608 continue; // Asm symbol.
Rafael Espindola538c9a82014-12-23 18:18:37 +0000609 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000610
Rafael Espindola51bd8ee2014-09-17 20:41:13 +0000611 if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
Rafael Espindola890db272014-09-09 20:08:22 +0000612 // Common linkage is special. There is no single symbol that wins the
613 // resolution. Instead we have to collect the maximum alignment and size.
614 // The IR linker does that for us if we just pass it every common GV.
Rafael Espindola51bd8ee2014-09-17 20:41:13 +0000615 // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
616 // internalize once the IR linker has done its job.
Rafael Espindola538c9a82014-12-23 18:18:37 +0000617 freeSymName(Sym);
Rafael Espindola890db272014-09-09 20:08:22 +0000618 continue;
619 }
620
Rafael Espindola33466a72014-08-21 20:28:55 +0000621 switch (Resolution) {
622 case LDPR_UNKNOWN:
623 llvm_unreachable("Unexpected resolution");
624
625 case LDPR_RESOLVED_IR:
626 case LDPR_RESOLVED_EXEC:
627 case LDPR_RESOLVED_DYN:
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000628 assert(GV->isDeclarationForLinker());
Rafael Espindola33466a72014-08-21 20:28:55 +0000629 break;
630
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000631 case LDPR_UNDEF:
Rafael Espindola9e3e53f2015-01-14 20:08:46 +0000632 if (!GV->isDeclarationForLinker()) {
Rafael Espindola0fd9e5f2015-01-14 19:43:32 +0000633 assert(GV->hasComdat());
634 Drop.insert(GV);
635 }
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000636 break;
637
Rafael Espindola33466a72014-08-21 20:28:55 +0000638 case LDPR_PREVAILING_DEF_IRONLY: {
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000639 keepGlobalValue(*GV, KeptAliases);
Rafael Espindola33466a72014-08-21 20:28:55 +0000640 if (!Used.count(GV)) {
641 // Since we use the regular lib/Linker, we cannot just internalize GV
642 // now or it will not be copied to the merged module. Instead we force
643 // it to be copied and then internalize it.
Rafael Espindolaa4f104b2014-12-09 16:50:57 +0000644 Internalize.insert(GV->getName());
Rafael Espindola33466a72014-08-21 20:28:55 +0000645 }
646 break;
647 }
648
649 case LDPR_PREVAILING_DEF:
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000650 keepGlobalValue(*GV, KeptAliases);
Rafael Espindola33466a72014-08-21 20:28:55 +0000651 break;
652
Rafael Espindola33466a72014-08-21 20:28:55 +0000653 case LDPR_PREEMPTED_IR:
Rafael Espindoladfc7ed72014-10-07 04:06:13 +0000654 // Gold might have selected a linkonce_odr and preempted a weak_odr.
655 // In that case we have to make sure we don't end up internalizing it.
656 if (!GV->isDiscardableIfUnused())
Rafael Espindolaa4f104b2014-12-09 16:50:57 +0000657 Maybe.erase(GV->getName());
Rafael Espindoladfc7ed72014-10-07 04:06:13 +0000658
659 // fall-through
660 case LDPR_PREEMPTED_REG:
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000661 Drop.insert(GV);
Rafael Espindola33466a72014-08-21 20:28:55 +0000662 break;
663
664 case LDPR_PREVAILING_DEF_IRONLY_EXP: {
665 // We can only check for address uses after we merge the modules. The
666 // reason is that this GV might have a copy in another module
667 // and in that module the address might be significant, but that
668 // copy will be LDPR_PREEMPTED_IR.
669 if (GV->hasLinkOnceODRLinkage())
Rafael Espindolaa4f104b2014-12-09 16:50:57 +0000670 Maybe.insert(GV->getName());
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000671 keepGlobalValue(*GV, KeptAliases);
Rafael Espindola33466a72014-08-21 20:28:55 +0000672 break;
673 }
674 }
675
Rafael Espindola538c9a82014-12-23 18:18:37 +0000676 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000677 }
678
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000679 ValueToValueMapTy VM;
680 LocalValueMaterializer Materializer(Drop);
681 for (GlobalAlias *GA : KeptAliases) {
682 // Gold told us to keep GA. It is possible that a GV usied in the aliasee
683 // expression is being dropped. If that is the case, that GV must be copied.
684 Constant *Aliasee = GA->getAliasee();
685 Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000686 GA->setAliasee(Replacement);
Rafael Espindola33466a72014-08-21 20:28:55 +0000687 }
688
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000689 for (auto *GV : Drop)
690 drop(*GV);
691
Rafael Espindola527e8462014-12-09 16:13:59 +0000692 return Obj.takeModule();
Rafael Espindola33466a72014-08-21 20:28:55 +0000693}
694
NAKAMURA Takumib0a52832015-02-02 05:47:30 +0000695static void runLTOPasses(Module &M, TargetMachine &TM) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000696 PassManager passes;
NAKAMURA Takumib0a52832015-02-02 05:47:30 +0000697 passes.add(new DataLayoutPass());
698 passes.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
699
Rafael Espindola33466a72014-08-21 20:28:55 +0000700 PassManagerBuilder PMB;
Sylvestre Ledru450f97d2015-01-24 13:59:08 +0000701 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
Rafael Espindola33466a72014-08-21 20:28:55 +0000702 PMB.Inliner = createFunctionInliningPass();
703 PMB.VerifyInput = true;
704 PMB.VerifyOutput = true;
Rafael Espindola8391dbd2014-10-30 00:11:24 +0000705 PMB.LoopVectorize = true;
Rafael Espindola919fb532014-10-30 00:38:54 +0000706 PMB.SLPVectorize = true;
Alexey Samsonov5ce24482015-01-30 19:14:04 +0000707 PMB.populateLTOPassManager(passes);
Rafael Espindola33466a72014-08-21 20:28:55 +0000708 passes.run(M);
709}
710
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000711static void saveBCFile(StringRef Path, Module &M) {
712 std::error_code EC;
713 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
714 if (EC)
715 message(LDPL_FATAL, "Failed to write the output file.");
716 WriteBitcodeToFile(&M, OS);
717}
718
Rafael Espindola33466a72014-08-21 20:28:55 +0000719static void codegen(Module &M) {
720 const std::string &TripleStr = M.getTargetTriple();
721 Triple TheTriple(TripleStr);
722
723 std::string ErrMsg;
724 const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
725 if (!TheTarget)
726 message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
727
728 if (unsigned NumOpts = options::extra.size())
729 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
730
731 SubtargetFeatures Features;
732 Features.getDefaultSubtargetFeatures(TheTriple);
733 for (const std::string &A : MAttrs)
734 Features.AddFeature(A);
735
736 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
737 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
738 TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
739 CodeModel::Default, CodeGenOpt::Aggressive));
740
741 runLTOPasses(M, *TM);
742
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000743 if (options::TheOutputType == options::OT_SAVE_TEMPS)
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000744 saveBCFile(output_name + ".opt.bc", M);
745
Rafael Espindola33466a72014-08-21 20:28:55 +0000746 PassManager CodeGenPasses;
Rafael Espindolac435adc2014-09-10 21:27:43 +0000747 CodeGenPasses.add(new DataLayoutPass());
Rafael Espindola33466a72014-08-21 20:28:55 +0000748
749 SmallString<128> Filename;
750 int FD;
751 if (options::obj_path.empty()) {
752 std::error_code EC =
753 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
754 if (EC)
Duncan P. N. Exon Smithf6ab4702014-11-19 22:39:21 +0000755 message(LDPL_FATAL, "Could not create temporary file: %s",
Rafael Espindola33466a72014-08-21 20:28:55 +0000756 EC.message().c_str());
757 } else {
758 Filename = options::obj_path;
759 std::error_code EC =
760 sys::fs::openFileForWrite(Filename.c_str(), FD, sys::fs::F_None);
761 if (EC)
762 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
763 }
764
765 {
766 raw_fd_ostream OS(FD, true);
767 formatted_raw_ostream FOS(OS);
768
769 if (TM->addPassesToEmitFile(CodeGenPasses, FOS,
770 TargetMachine::CGFT_ObjectFile))
771 message(LDPL_FATAL, "Failed to setup codegen");
772 CodeGenPasses.run(M);
773 }
774
775 if (add_input_file(Filename.c_str()) != LDPS_OK)
776 message(LDPL_FATAL,
777 "Unable to add .o file to the link. File left behind in: %s",
778 Filename.c_str());
779
780 if (options::obj_path.empty())
781 Cleanup.push_back(Filename.c_str());
Rafael Espindola282a4702013-10-31 20:51:58 +0000782}
783
Rafael Espindolab6393292014-07-30 01:23:45 +0000784/// gold informs us that all symbols have been read. At this point, we use
785/// get_symbols to see if any of our definitions have been overridden by a
786/// native object file. Then, perform optimization and codegen.
Rafael Espindola33466a72014-08-21 20:28:55 +0000787static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
788 if (Modules.empty())
789 return LDPS_OK;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000790
Rafael Espindola33466a72014-08-21 20:28:55 +0000791 LLVMContext Context;
792 std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
793 Linker L(Combined.get());
794
795 std::string DefaultTriple = sys::getDefaultTargetTriple();
796
797 StringSet<> Internalize;
798 StringSet<> Maybe;
Rafael Espindolad2aac572014-07-30 01:52:40 +0000799 for (claimed_file &F : Modules) {
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000800 ld_plugin_input_file File;
801 if (get_input_file(F.handle, &File) != LDPS_OK)
802 message(LDPL_FATAL, "Failed to get file information");
Rafael Espindola33466a72014-08-21 20:28:55 +0000803 std::unique_ptr<Module> M =
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000804 getModuleForFile(Context, F, File.filesize, ApiFile,
805 Internalize, Maybe);
Rafael Espindola33466a72014-08-21 20:28:55 +0000806 if (!options::triple.empty())
807 M->setTargetTriple(options::triple.c_str());
808 else if (M->getTargetTriple().empty()) {
809 M->setTargetTriple(DefaultTriple);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000810 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000811
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000812 if (L.linkInModule(M.get()))
813 message(LDPL_FATAL, "Failed to link module");
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000814 if (release_input_file(F.handle) != LDPS_OK)
815 message(LDPL_FATAL, "Failed to release file information");
Rafael Espindola77b6d012010-06-14 21:20:52 +0000816 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000817
Rafael Espindola33466a72014-08-21 20:28:55 +0000818 for (const auto &Name : Internalize) {
819 GlobalValue *GV = Combined->getNamedValue(Name.first());
820 if (GV)
821 internalize(*GV);
822 }
823
824 for (const auto &Name : Maybe) {
825 GlobalValue *GV = Combined->getNamedValue(Name.first());
826 if (!GV)
827 continue;
828 GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
829 if (canBeOmittedFromSymbolTable(GV))
830 internalize(*GV);
831 }
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000832
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000833 if (options::TheOutputType == options::OT_DISABLE)
834 return LDPS_OK;
835
836 if (options::TheOutputType != options::OT_NORMAL) {
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000837 std::string path;
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000838 if (options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000839 path = output_name;
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000840 else
841 path = output_name + ".bc";
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000842 saveBCFile(path, *L.getModule());
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000843 if (options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola55b32542014-08-11 19:06:54 +0000844 return LDPS_OK;
Rafael Espindolaba3398b2010-05-13 13:39:31 +0000845 }
Rafael Espindola143fc3b2013-10-16 12:47:04 +0000846
Rafael Espindola33466a72014-08-21 20:28:55 +0000847 codegen(*L.getModule());
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000848
Rafael Espindolaef498152010-06-23 20:20:59 +0000849 if (!options::extra_library_path.empty() &&
Rafael Espindola33466a72014-08-21 20:28:55 +0000850 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
851 message(LDPL_FATAL, "Unable to set the extra library path.");
Shuxin Yang1826ae22013-08-12 21:07:31 +0000852
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000853 return LDPS_OK;
854}
855
Rafael Espindola55b32542014-08-11 19:06:54 +0000856static ld_plugin_status all_symbols_read_hook(void) {
857 ld_plugin_status Ret;
858 if (!options::generate_api_file) {
859 Ret = allSymbolsReadHook(nullptr);
860 } else {
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000861 std::error_code EC;
862 raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
863 if (EC)
Rafael Espindola55b32542014-08-11 19:06:54 +0000864 message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000865 EC.message().c_str());
Rafael Espindola33466a72014-08-21 20:28:55 +0000866 Ret = allSymbolsReadHook(&ApiFile);
Rafael Espindola55b32542014-08-11 19:06:54 +0000867 }
868
Rafael Espindola947bdb62014-11-25 20:52:49 +0000869 llvm_shutdown();
870
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000871 if (options::TheOutputType == options::OT_BC_ONLY ||
872 options::TheOutputType == options::OT_DISABLE)
Rafael Espindola55b32542014-08-11 19:06:54 +0000873 exit(0);
874
875 return Ret;
876}
877
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000878static ld_plugin_status cleanup_hook(void) {
Rafael Espindolad2aac572014-07-30 01:52:40 +0000879 for (std::string &Name : Cleanup) {
880 std::error_code EC = sys::fs::remove(Name);
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000881 if (EC)
Rafael Espindolad2aac572014-07-30 01:52:40 +0000882 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000883 EC.message().c_str());
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000884 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000885
886 return LDPS_OK;
887}