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" // plugin-api.h requires HAVE_STDINT_H
16 #include "llvm-c/lto.h"
17 #include "llvm/ADT/StringSet.h"
18 #include "llvm/CodeGen/CommandFlags.h"
19 #include "llvm/LTO/LTOCodeGenerator.h"
20 #include "llvm/LTO/LTOModule.h"
21 #include "llvm/Support/Errno.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/Program.h"
26 #include "llvm/Support/TargetSelect.h"
27 #include "llvm/Support/ToolOutputFile.h"
32 #include <plugin-api.h>
33 #include <system_error>
36 // Support Windows/MinGW crazyness.
44 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
45 // Precise and Debian Wheezy (binutils 2.23 is required)
54 std::vector<ld_plugin_symbol> syms;
58 static ld_plugin_status discard_message(int level, const char *format, ...) {
59 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
60 // callback in the transfer vector. This should never be called.
64 static ld_plugin_add_symbols add_symbols = NULL;
65 static ld_plugin_get_symbols get_symbols = NULL;
66 static ld_plugin_add_input_file add_input_file = NULL;
67 static ld_plugin_set_extra_library_path set_extra_library_path = NULL;
68 static ld_plugin_get_view get_view = NULL;
69 static ld_plugin_message message = discard_message;
70 static lto_codegen_model output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
71 static std::string output_name = "";
72 static std::list<claimed_file> Modules;
73 static std::vector<std::string> Cleanup;
74 static LTOCodeGenerator *CodeGen = nullptr;
75 static StringSet<> CannotBeHidden;
76 static llvm::TargetOptions TargetOpts;
79 enum generate_bc { BC_NO, BC_ALSO, BC_ONLY };
80 static bool generate_api_file = false;
81 static generate_bc generate_bc_file = BC_NO;
82 static std::string bc_path;
83 static std::string obj_path;
84 static std::string extra_library_path;
85 static std::string triple;
86 static std::string mcpu;
87 // Additional options to pass into the code generator.
88 // Note: This array will contain all plugin options which are not claimed
89 // as plugin exclusive to pass to the code generator.
90 // For example, "generate-api-file" and "as"options are for the plugin
91 // use only and will not be passed.
92 static std::vector<const char *> extra;
94 static void process_plugin_option(const char* opt_)
98 llvm::StringRef opt = opt_;
100 if (opt == "generate-api-file") {
101 generate_api_file = true;
102 } else if (opt.startswith("mcpu=")) {
103 mcpu = opt.substr(strlen("mcpu="));
104 } else if (opt.startswith("extra-library-path=")) {
105 extra_library_path = opt.substr(strlen("extra_library_path="));
106 } else if (opt.startswith("mtriple=")) {
107 triple = opt.substr(strlen("mtriple="));
108 } else if (opt.startswith("obj-path=")) {
109 obj_path = opt.substr(strlen("obj-path="));
110 } else if (opt == "emit-llvm") {
111 generate_bc_file = BC_ONLY;
112 } else if (opt == "also-emit-llvm") {
113 generate_bc_file = BC_ALSO;
114 } else if (opt.startswith("also-emit-llvm=")) {
115 llvm::StringRef path = opt.substr(strlen("also-emit-llvm="));
116 generate_bc_file = BC_ALSO;
117 if (!bc_path.empty()) {
118 (*message)(LDPL_WARNING, "Path to the output IL file specified twice. "
119 "Discarding %s", opt_);
124 // Save this option to pass to the code generator.
125 extra.push_back(opt_);
130 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
132 static ld_plugin_status all_symbols_read_hook(void);
133 static ld_plugin_status cleanup_hook(void);
135 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
136 ld_plugin_status onload(ld_plugin_tv *tv) {
137 InitializeAllTargetInfos();
138 InitializeAllTargets();
139 InitializeAllTargetMCs();
140 InitializeAllAsmParsers();
141 InitializeAllAsmPrinters();
143 // We're given a pointer to the first transfer vector. We read through them
144 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
145 // contain pointers to functions that we need to call to register our own
146 // hooks. The others are addresses of functions we can use to call into gold
149 bool registeredClaimFile = false;
150 bool RegisteredAllSymbolsRead = false;
152 for (; tv->tv_tag != LDPT_NULL; ++tv) {
153 switch (tv->tv_tag) {
154 case LDPT_OUTPUT_NAME:
155 output_name = tv->tv_u.tv_string;
157 case LDPT_LINKER_OUTPUT:
158 switch (tv->tv_u.tv_val) {
160 case LDPO_DYN: // .so
161 case LDPO_PIE: // position independent executable
162 output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
164 case LDPO_EXEC: // .exe
165 output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
168 (*message)(LDPL_ERROR, "Unknown output file type %d",
174 options::process_plugin_option(tv->tv_u.tv_string);
176 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
177 ld_plugin_register_claim_file callback;
178 callback = tv->tv_u.tv_register_claim_file;
180 if ((*callback)(claim_file_hook) != LDPS_OK)
183 registeredClaimFile = true;
185 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
186 ld_plugin_register_all_symbols_read callback;
187 callback = tv->tv_u.tv_register_all_symbols_read;
189 if ((*callback)(all_symbols_read_hook) != LDPS_OK)
192 RegisteredAllSymbolsRead = true;
194 case LDPT_REGISTER_CLEANUP_HOOK: {
195 ld_plugin_register_cleanup callback;
196 callback = tv->tv_u.tv_register_cleanup;
198 if ((*callback)(cleanup_hook) != LDPS_OK)
201 case LDPT_ADD_SYMBOLS:
202 add_symbols = tv->tv_u.tv_add_symbols;
204 case LDPT_GET_SYMBOLS_V2:
205 get_symbols = tv->tv_u.tv_get_symbols;
207 case LDPT_ADD_INPUT_FILE:
208 add_input_file = tv->tv_u.tv_add_input_file;
210 case LDPT_SET_EXTRA_LIBRARY_PATH:
211 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
214 get_view = tv->tv_u.tv_get_view;
217 message = tv->tv_u.tv_message;
224 if (!registeredClaimFile) {
225 (*message)(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
229 (*message)(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
233 if (!RegisteredAllSymbolsRead)
236 CodeGen = new LTOCodeGenerator();
238 // Pass through extra options to the code generator.
239 if (!options::extra.empty()) {
240 for (const char *Opt : options::extra)
241 CodeGen->setCodeGenDebugOptions(Opt);
244 CodeGen->parseCodeGenDebugOptions();
247 for (unsigned I = 0; I < MAttrs.size(); ++I) {
250 Attrs.append(MAttrs[I]);
252 CodeGen->setAttr(Attrs.c_str());
255 TargetOpts = InitTargetOptionsFromCodeGenFlags();
256 CodeGen->setTargetOptions(TargetOpts);
261 /// Called by gold to see whether this file is one that our plugin can handle.
262 /// We'll try to open it and register all the symbols with add_symbol if
264 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
267 std::unique_ptr<MemoryBuffer> buffer;
269 if (get_view(file->handle, &view) != LDPS_OK) {
270 (*message)(LDPL_ERROR, "Failed to get a view of %s", file->name);
275 // Gold has found what might be IR part-way inside of a file, such as
278 offset = file->offset;
280 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
281 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
283 if (std::error_code EC = BufferOrErr.getError()) {
284 (*message)(LDPL_ERROR, EC.message().c_str());
287 buffer = std::move(BufferOrErr.get());
288 view = buffer->getBufferStart();
291 if (!LTOModule::isBitcodeFile(view, file->filesize))
298 LTOModule::createFromBuffer(view, file->filesize, TargetOpts, Error);
300 (*message)(LDPL_ERROR,
301 "LLVM gold plugin has failed to create LTO module: %s",
306 Modules.resize(Modules.size() + 1);
307 claimed_file &cf = Modules.back();
309 if (!options::triple.empty())
310 M->setTargetTriple(options::triple.c_str());
312 cf.handle = file->handle;
313 unsigned sym_count = M->getSymbolCount();
314 cf.syms.reserve(sym_count);
316 for (unsigned i = 0; i != sym_count; ++i) {
317 lto_symbol_attributes attrs = M->getSymbolAttributes(i);
318 if ((attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
321 cf.syms.push_back(ld_plugin_symbol());
322 ld_plugin_symbol &sym = cf.syms.back();
323 sym.name = strdup(M->getSymbolName(i));
326 int scope = attrs & LTO_SYMBOL_SCOPE_MASK;
327 bool CanBeHidden = scope == LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
329 CannotBeHidden.insert(sym.name);
331 case LTO_SYMBOL_SCOPE_HIDDEN:
332 sym.visibility = LDPV_HIDDEN;
334 case LTO_SYMBOL_SCOPE_PROTECTED:
335 sym.visibility = LDPV_PROTECTED;
338 case LTO_SYMBOL_SCOPE_DEFAULT:
339 case LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN:
340 sym.visibility = LDPV_DEFAULT;
343 (*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope);
347 int definition = attrs & LTO_SYMBOL_DEFINITION_MASK;
348 sym.comdat_key = NULL;
349 switch (definition) {
350 case LTO_SYMBOL_DEFINITION_REGULAR:
353 case LTO_SYMBOL_DEFINITION_UNDEFINED:
354 sym.def = LDPK_UNDEF;
356 case LTO_SYMBOL_DEFINITION_TENTATIVE:
357 sym.def = LDPK_COMMON;
359 case LTO_SYMBOL_DEFINITION_WEAK:
360 sym.comdat_key = sym.name;
361 sym.def = LDPK_WEAKDEF;
363 case LTO_SYMBOL_DEFINITION_WEAKUNDEF:
364 sym.def = LDPK_WEAKUNDEF;
367 (*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition);
373 sym.resolution = LDPR_UNKNOWN;
376 cf.syms.reserve(cf.syms.size());
378 if (!cf.syms.empty()) {
379 if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
380 (*message)(LDPL_ERROR, "Unable to add symbols!");
387 if (!CodeGen->addModule(M, Error)) {
388 (*message)(LDPL_ERROR, "Error linking module: %s", Error.c_str());
398 static bool mustPreserve(const claimed_file &F, int i) {
399 if (F.syms[i].resolution == LDPR_PREVAILING_DEF)
401 if (F.syms[i].resolution == LDPR_PREVAILING_DEF_IRONLY_EXP)
402 return CannotBeHidden.count(F.syms[i].name);
406 /// all_symbols_read_hook - gold informs us that all symbols have been read.
407 /// At this point, we use get_symbols to see if any of our definitions have
408 /// been overridden by a native object file. Then, perform optimization and
410 static ld_plugin_status all_symbols_read_hook(void) {
411 // FIXME: raw_fd_ostream should be able to represent an unopened file.
412 std::unique_ptr<raw_fd_ostream> api_file;
416 if (options::generate_api_file) {
418 api_file.reset(new raw_fd_ostream("apifile.txt", Error, sys::fs::F_None));
420 (*message)(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
424 for (std::list<claimed_file>::iterator I = Modules.begin(),
425 E = Modules.end(); I != E; ++I) {
428 (*get_symbols)(I->handle, I->syms.size(), &I->syms[0]);
429 for (unsigned i = 0, e = I->syms.size(); i != e; i++) {
430 if (mustPreserve(*I, i)) {
431 CodeGen->addMustPreserveSymbol(I->syms[i].name);
433 if (options::generate_api_file)
434 (*api_file) << I->syms[i].name << "\n";
439 CodeGen->setCodePICModel(output_type);
440 CodeGen->setDebugInfo(LTO_DEBUG_MODEL_DWARF);
441 if (!options::mcpu.empty())
442 CodeGen->setCpu(options::mcpu.c_str());
444 if (options::generate_bc_file != options::BC_NO) {
446 if (options::generate_bc_file == options::BC_ONLY)
448 else if (!options::bc_path.empty())
449 path = options::bc_path;
451 path = output_name + ".bc";
453 if (!CodeGen->writeMergedModules(path.c_str(), Error))
454 (*message)(LDPL_FATAL, "Failed to write the output file.");
455 if (options::generate_bc_file == options::BC_ONLY) {
465 if (!CodeGen->compile_to_file(&Temp, /*DisableOpt*/ false, /*DisableInline*/
466 false, /*DisableGVNLoadPRE*/ false, Error))
467 (*message)(LDPL_ERROR, "Could not produce a combined object file\n");
472 for (std::list<claimed_file>::iterator I = Modules.begin(),
473 E = Modules.end(); I != E; ++I) {
474 for (unsigned i = 0; i != I->syms.size(); ++i) {
475 ld_plugin_symbol &sym = I->syms[i];
480 if ((*add_input_file)(ObjPath.c_str()) != LDPS_OK) {
481 (*message)(LDPL_ERROR, "Unable to add .o file to the link.");
482 (*message)(LDPL_ERROR, "File left behind in: %s", ObjPath.c_str());
486 if (!options::extra_library_path.empty() &&
487 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK) {
488 (*message)(LDPL_ERROR, "Unable to set the extra library path.");
492 if (options::obj_path.empty())
493 Cleanup.push_back(ObjPath);
498 static ld_plugin_status cleanup_hook(void) {
499 for (int i = 0, e = Cleanup.size(); i != e; ++i) {
500 std::error_code EC = sys::fs::remove(Cleanup[i]);
502 (*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(),
503 EC.message().c_str());