1 //===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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 .
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Config/config.h"
16 #include "plugin-api.h"
18 #include "llvm-c/lto.h"
20 #include "llvm/Support/ToolOutputFile.h"
21 #include "llvm/Support/Errno.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/Program.h"
32 // Support Windows/MinGW crazyness.
42 ld_plugin_status discard_message(int level, const char *format, ...) {
43 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
44 // callback in the transfer vector. This should never be called.
48 ld_plugin_add_symbols add_symbols = NULL;
49 ld_plugin_get_symbols get_symbols = NULL;
50 ld_plugin_add_input_file add_input_file = NULL;
51 ld_plugin_add_input_library add_input_library = NULL;
52 ld_plugin_set_extra_library_path set_extra_library_path = NULL;
53 ld_plugin_message message = discard_message;
60 std::vector<ld_plugin_symbol> syms;
63 lto_codegen_model output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
64 std::string output_name = "";
65 std::list<claimed_file> Modules;
66 std::vector<sys::Path> Cleanup;
67 lto_code_gen_t code_gen = NULL;
71 enum generate_bc { BC_NO, BC_ALSO, BC_ONLY };
72 static bool generate_api_file = false;
73 static generate_bc generate_bc_file = BC_NO;
74 static std::string bc_path;
75 static std::string obj_path;
76 static std::string extra_library_path;
77 static std::string triple;
78 static std::string mcpu;
79 // Additional options to pass into the code generator.
80 // Note: This array will contain all plugin options which are not claimed
81 // as plugin exclusive to pass to the code generator.
82 // For example, "generate-api-file" and "as"options are for the plugin
83 // use only and will not be passed.
84 static std::vector<std::string> extra;
86 static void process_plugin_option(const char* opt_)
90 llvm::StringRef opt = opt_;
92 if (opt == "generate-api-file") {
93 generate_api_file = true;
94 } else if (opt.startswith("mcpu=")) {
95 mcpu = opt.substr(strlen("mcpu="));
96 } else if (opt.startswith("extra-library-path=")) {
97 extra_library_path = opt.substr(strlen("extra_library_path="));
98 } else if (opt.startswith("mtriple=")) {
99 triple = opt.substr(strlen("mtriple="));
100 } else if (opt.startswith("obj-path=")) {
101 obj_path = opt.substr(strlen("obj-path="));
102 } else if (opt == "emit-llvm") {
103 generate_bc_file = BC_ONLY;
104 } else if (opt == "also-emit-llvm") {
105 generate_bc_file = BC_ALSO;
106 } else if (opt.startswith("also-emit-llvm=")) {
107 llvm::StringRef path = opt.substr(strlen("also-emit-llvm="));
108 generate_bc_file = BC_ALSO;
109 if (!bc_path.empty()) {
110 (*message)(LDPL_WARNING, "Path to the output IL file specified twice. "
111 "Discarding %s", opt_);
116 // Save this option to pass to the code generator.
117 extra.push_back(opt);
122 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
124 static ld_plugin_status all_symbols_read_hook(void);
125 static ld_plugin_status cleanup_hook(void);
127 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
128 ld_plugin_status onload(ld_plugin_tv *tv) {
129 // We're given a pointer to the first transfer vector. We read through them
130 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
131 // contain pointers to functions that we need to call to register our own
132 // hooks. The others are addresses of functions we can use to call into gold
135 bool registeredClaimFile = false;
137 for (; tv->tv_tag != LDPT_NULL; ++tv) {
138 switch (tv->tv_tag) {
139 case LDPT_API_VERSION:
140 api_version = tv->tv_u.tv_val;
142 case LDPT_GOLD_VERSION: // major * 100 + minor
143 gold_version = tv->tv_u.tv_val;
145 case LDPT_OUTPUT_NAME:
146 output_name = tv->tv_u.tv_string;
148 case LDPT_LINKER_OUTPUT:
149 switch (tv->tv_u.tv_val) {
151 case LDPO_DYN: // .so
152 output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
154 case LDPO_EXEC: // .exe
155 output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
158 (*message)(LDPL_ERROR, "Unknown output file type %d",
162 // TODO: add an option to disable PIC.
163 //output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC;
166 options::process_plugin_option(tv->tv_u.tv_string);
168 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
169 ld_plugin_register_claim_file callback;
170 callback = tv->tv_u.tv_register_claim_file;
172 if ((*callback)(claim_file_hook) != LDPS_OK)
175 registeredClaimFile = true;
177 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
178 ld_plugin_register_all_symbols_read callback;
179 callback = tv->tv_u.tv_register_all_symbols_read;
181 if ((*callback)(all_symbols_read_hook) != LDPS_OK)
184 code_gen = lto_codegen_create();
186 case LDPT_REGISTER_CLEANUP_HOOK: {
187 ld_plugin_register_cleanup callback;
188 callback = tv->tv_u.tv_register_cleanup;
190 if ((*callback)(cleanup_hook) != LDPS_OK)
193 case LDPT_ADD_SYMBOLS:
194 add_symbols = tv->tv_u.tv_add_symbols;
196 case LDPT_GET_SYMBOLS:
197 get_symbols = tv->tv_u.tv_get_symbols;
199 case LDPT_ADD_INPUT_FILE:
200 add_input_file = tv->tv_u.tv_add_input_file;
202 case LDPT_ADD_INPUT_LIBRARY:
203 add_input_library = tv->tv_u.tv_add_input_file;
205 case LDPT_SET_EXTRA_LIBRARY_PATH:
206 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
209 message = tv->tv_u.tv_message;
216 if (!registeredClaimFile) {
217 (*message)(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
221 (*message)(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
228 /// claim_file_hook - called by gold to see whether this file is one that
229 /// our plugin can handle. We'll try to open it and register all the symbols
230 /// with add_symbol if possible.
231 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
236 // Gold has found what might be IR part-way inside of a file, such as
238 M = lto_module_create_from_fd_at_offset(file->fd, file->name, -1,
239 file->filesize, file->offset);
241 M = lto_module_create_from_fd(file->fd, file->name, file->filesize);
247 Modules.resize(Modules.size() + 1);
248 claimed_file &cf = Modules.back();
250 if (!options::triple.empty())
251 lto_module_set_target_triple(M, options::triple.c_str());
253 cf.handle = file->handle;
254 unsigned sym_count = lto_module_get_num_symbols(M);
255 cf.syms.reserve(sym_count);
257 for (unsigned i = 0; i != sym_count; ++i) {
258 lto_symbol_attributes attrs = lto_module_get_symbol_attribute(M, i);
259 if ((attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
262 cf.syms.push_back(ld_plugin_symbol());
263 ld_plugin_symbol &sym = cf.syms.back();
264 sym.name = const_cast<char *>(lto_module_get_symbol_name(M, i));
265 sym.name = strdup(sym.name);
268 int scope = attrs & LTO_SYMBOL_SCOPE_MASK;
270 case LTO_SYMBOL_SCOPE_HIDDEN:
271 sym.visibility = LDPV_HIDDEN;
273 case LTO_SYMBOL_SCOPE_PROTECTED:
274 sym.visibility = LDPV_PROTECTED;
277 case LTO_SYMBOL_SCOPE_DEFAULT:
278 sym.visibility = LDPV_DEFAULT;
281 (*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope);
285 int definition = attrs & LTO_SYMBOL_DEFINITION_MASK;
286 sym.comdat_key = NULL;
287 switch (definition) {
288 case LTO_SYMBOL_DEFINITION_REGULAR:
291 case LTO_SYMBOL_DEFINITION_UNDEFINED:
292 sym.def = LDPK_UNDEF;
294 case LTO_SYMBOL_DEFINITION_TENTATIVE:
295 sym.def = LDPK_COMMON;
297 case LTO_SYMBOL_DEFINITION_WEAK:
298 sym.comdat_key = sym.name;
299 sym.def = LDPK_WEAKDEF;
301 case LTO_SYMBOL_DEFINITION_WEAKUNDEF:
302 sym.def = LDPK_WEAKUNDEF;
305 (*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition);
311 sym.resolution = LDPR_UNKNOWN;
314 cf.syms.reserve(cf.syms.size());
316 if (!cf.syms.empty()) {
317 if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
318 (*message)(LDPL_ERROR, "Unable to add symbols!");
324 lto_codegen_add_module(code_gen, M);
326 lto_module_dispose(M);
331 /// all_symbols_read_hook - gold informs us that all symbols have been read.
332 /// At this point, we use get_symbols to see if any of our definitions have
333 /// been overridden by a native object file. Then, perform optimization and
335 static ld_plugin_status all_symbols_read_hook(void) {
336 std::ofstream api_file;
339 if (options::generate_api_file) {
340 api_file.open("apifile.txt", std::ofstream::out | std::ofstream::trunc);
341 if (!api_file.is_open()) {
342 (*message)(LDPL_FATAL, "Unable to open apifile.txt for writing.");
347 // If we don't preserve any symbols, libLTO will assume that all symbols are
348 // needed. Keep all symbols unless we're producing a final executable.
349 bool anySymbolsPreserved = false;
350 for (std::list<claimed_file>::iterator I = Modules.begin(),
351 E = Modules.end(); I != E; ++I) {
352 (*get_symbols)(I->handle, I->syms.size(), &I->syms[0]);
353 for (unsigned i = 0, e = I->syms.size(); i != e; i++) {
354 if (I->syms[i].resolution == LDPR_PREVAILING_DEF) {
355 lto_codegen_add_must_preserve_symbol(code_gen, I->syms[i].name);
356 anySymbolsPreserved = true;
358 if (options::generate_api_file)
359 api_file << I->syms[i].name << "\n";
364 if (options::generate_api_file)
367 if (!anySymbolsPreserved) {
368 // All of the IL is unnecessary!
369 lto_codegen_dispose(code_gen);
373 lto_codegen_set_pic_model(code_gen, output_type);
374 lto_codegen_set_debug_model(code_gen, LTO_DEBUG_MODEL_DWARF);
375 if (!options::mcpu.empty())
376 lto_codegen_set_cpu(code_gen, options::mcpu.c_str());
378 // Pass through extra options to the code generator.
379 if (!options::extra.empty()) {
380 for (std::vector<std::string>::iterator it = options::extra.begin();
381 it != options::extra.end(); ++it) {
382 lto_codegen_debug_options(code_gen, (*it).c_str());
386 if (options::generate_bc_file != options::BC_NO) {
388 if (options::generate_bc_file == options::BC_ONLY)
390 else if (!options::bc_path.empty())
391 path = options::bc_path;
393 path = output_name + ".bc";
394 bool err = lto_codegen_write_merged_modules(code_gen, path.c_str());
396 (*message)(LDPL_FATAL, "Failed to write the output file.");
397 if (options::generate_bc_file == options::BC_ONLY)
402 if (lto_codegen_compile_to_file(code_gen, &objPath)) {
403 (*message)(LDPL_ERROR, "Could not produce a combined object file\n");
406 lto_codegen_dispose(code_gen);
407 for (std::list<claimed_file>::iterator I = Modules.begin(),
408 E = Modules.end(); I != E; ++I) {
409 for (unsigned i = 0; i != I->syms.size(); ++i) {
410 ld_plugin_symbol &sym = I->syms[i];
415 if ((*add_input_file)(objPath) != LDPS_OK) {
416 (*message)(LDPL_ERROR, "Unable to add .o file to the link.");
417 (*message)(LDPL_ERROR, "File left behind in: %s", objPath);
421 if (!options::extra_library_path.empty() &&
422 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK) {
423 (*message)(LDPL_ERROR, "Unable to set the extra library path.");
427 if (options::obj_path.empty())
428 Cleanup.push_back(sys::Path(objPath));
433 static ld_plugin_status cleanup_hook(void) {
436 for (int i = 0, e = Cleanup.size(); i != e; ++i)
437 if (Cleanup[i].eraseFromDisk(false, &ErrMsg))
438 (*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(),