Remove an incorrect fixme.
[oota-llvm.git] / tools / gold / gold-plugin.cpp
1 //===-- 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
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/Support/Errno.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/Program.h"
23 #include "llvm/Support/ToolOutputFile.h"
24 #include <cerrno>
25 #include <cstdlib>
26 #include <cstring>
27 #include <fstream>
28 #include <list>
29 #include <plugin-api.h>
30 #include <system_error>
31 #include <vector>
32
33 // Support Windows/MinGW crazyness.
34 #ifdef _WIN32
35 # include <io.h>
36 # define lseek _lseek
37 # define read _read
38 #endif
39
40 #ifndef LDPO_PIE
41 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
42 // Precise and Debian Wheezy (binutils 2.23 is required)
43 # define LDPO_PIE 3
44 #endif
45
46 using namespace llvm;
47
48 namespace {
49   ld_plugin_status discard_message(int level, const char *format, ...) {
50     // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
51     // callback in the transfer vector. This should never be called.
52     abort();
53   }
54
55   ld_plugin_add_symbols add_symbols = NULL;
56   ld_plugin_get_symbols get_symbols = NULL;
57   ld_plugin_add_input_file add_input_file = NULL;
58   ld_plugin_add_input_library add_input_library = NULL;
59   ld_plugin_set_extra_library_path set_extra_library_path = NULL;
60   ld_plugin_get_view get_view = NULL;
61   ld_plugin_message message = discard_message;
62
63   int api_version = 0;
64   int gold_version = 0;
65
66   struct claimed_file {
67     void *handle;
68     std::vector<ld_plugin_symbol> syms;
69   };
70
71   lto_codegen_model output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
72   std::string output_name = "";
73   std::list<claimed_file> Modules;
74   std::vector<std::string> Cleanup;
75   lto_code_gen_t code_gen = NULL;
76   StringSet<> CannotBeHidden;
77 }
78
79 namespace options {
80   enum generate_bc { BC_NO, BC_ALSO, BC_ONLY };
81   static bool generate_api_file = false;
82   static generate_bc generate_bc_file = BC_NO;
83   static std::string bc_path;
84   static std::string obj_path;
85   static std::string extra_library_path;
86   static std::string triple;
87   static std::string mcpu;
88   // Additional options to pass into the code generator.
89   // Note: This array will contain all plugin options which are not claimed
90   // as plugin exclusive to pass to the code generator.
91   // For example, "generate-api-file" and "as"options are for the plugin
92   // use only and will not be passed.
93   static std::vector<std::string> extra;
94
95   static void process_plugin_option(const char* opt_)
96   {
97     if (opt_ == NULL)
98       return;
99     llvm::StringRef opt = opt_;
100
101     if (opt == "generate-api-file") {
102       generate_api_file = true;
103     } else if (opt.startswith("mcpu=")) {
104       mcpu = opt.substr(strlen("mcpu="));
105     } else if (opt.startswith("extra-library-path=")) {
106       extra_library_path = opt.substr(strlen("extra_library_path="));
107     } else if (opt.startswith("mtriple=")) {
108       triple = opt.substr(strlen("mtriple="));
109     } else if (opt.startswith("obj-path=")) {
110       obj_path = opt.substr(strlen("obj-path="));
111     } else if (opt == "emit-llvm") {
112       generate_bc_file = BC_ONLY;
113     } else if (opt == "also-emit-llvm") {
114       generate_bc_file = BC_ALSO;
115     } else if (opt.startswith("also-emit-llvm=")) {
116       llvm::StringRef path = opt.substr(strlen("also-emit-llvm="));
117       generate_bc_file = BC_ALSO;
118       if (!bc_path.empty()) {
119         (*message)(LDPL_WARNING, "Path to the output IL file specified twice. "
120                    "Discarding %s", opt_);
121       } else {
122         bc_path = path;
123       }
124     } else {
125       // Save this option to pass to the code generator.
126       extra.push_back(opt);
127     }
128   }
129 }
130
131 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
132                                         int *claimed);
133 static ld_plugin_status all_symbols_read_hook(void);
134 static ld_plugin_status cleanup_hook(void);
135
136 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
137 ld_plugin_status onload(ld_plugin_tv *tv) {
138   // We're given a pointer to the first transfer vector. We read through them
139   // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
140   // contain pointers to functions that we need to call to register our own
141   // hooks. The others are addresses of functions we can use to call into gold
142   // for services.
143
144   bool registeredClaimFile = false;
145
146   for (; tv->tv_tag != LDPT_NULL; ++tv) {
147     switch (tv->tv_tag) {
148       case LDPT_API_VERSION:
149         api_version = tv->tv_u.tv_val;
150         break;
151       case LDPT_GOLD_VERSION:  // major * 100 + minor
152         gold_version = tv->tv_u.tv_val;
153         break;
154       case LDPT_OUTPUT_NAME:
155         output_name = tv->tv_u.tv_string;
156         break;
157       case LDPT_LINKER_OUTPUT:
158         switch (tv->tv_u.tv_val) {
159           case LDPO_REL:  // .o
160           case LDPO_DYN:  // .so
161           case LDPO_PIE:  // position independent executable
162             output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
163             break;
164           case LDPO_EXEC:  // .exe
165             output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
166             break;
167           default:
168             (*message)(LDPL_ERROR, "Unknown output file type %d",
169                        tv->tv_u.tv_val);
170             return LDPS_ERR;
171         }
172         break;
173       case LDPT_OPTION:
174         options::process_plugin_option(tv->tv_u.tv_string);
175         break;
176       case LDPT_REGISTER_CLAIM_FILE_HOOK: {
177         ld_plugin_register_claim_file callback;
178         callback = tv->tv_u.tv_register_claim_file;
179
180         if ((*callback)(claim_file_hook) != LDPS_OK)
181           return LDPS_ERR;
182
183         registeredClaimFile = true;
184       } break;
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;
188
189         if ((*callback)(all_symbols_read_hook) != LDPS_OK)
190           return LDPS_ERR;
191
192         code_gen = lto_codegen_create();
193       } break;
194       case LDPT_REGISTER_CLEANUP_HOOK: {
195         ld_plugin_register_cleanup callback;
196         callback = tv->tv_u.tv_register_cleanup;
197
198         if ((*callback)(cleanup_hook) != LDPS_OK)
199           return LDPS_ERR;
200       } break;
201       case LDPT_ADD_SYMBOLS:
202         add_symbols = tv->tv_u.tv_add_symbols;
203         break;
204       case LDPT_GET_SYMBOLS_V2:
205         get_symbols = tv->tv_u.tv_get_symbols;
206         break;
207       case LDPT_ADD_INPUT_FILE:
208         add_input_file = tv->tv_u.tv_add_input_file;
209         break;
210       case LDPT_ADD_INPUT_LIBRARY:
211         add_input_library = tv->tv_u.tv_add_input_file;
212         break;
213       case LDPT_SET_EXTRA_LIBRARY_PATH:
214         set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
215         break;
216       case LDPT_GET_VIEW:
217         get_view = tv->tv_u.tv_get_view;
218         break;
219       case LDPT_MESSAGE:
220         message = tv->tv_u.tv_message;
221         break;
222       default:
223         break;
224     }
225   }
226
227   if (!registeredClaimFile) {
228     (*message)(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
229     return LDPS_ERR;
230   }
231   if (!add_symbols) {
232     (*message)(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
233     return LDPS_ERR;
234   }
235
236   return LDPS_OK;
237 }
238
239 /// claim_file_hook - called by gold to see whether this file is one that
240 /// our plugin can handle. We'll try to open it and register all the symbols
241 /// with add_symbol if possible.
242 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
243                                         int *claimed) {
244   lto_module_t M;
245   const void *view;
246   std::unique_ptr<MemoryBuffer> buffer;
247   if (get_view) {
248     if (get_view(file->handle, &view) != LDPS_OK) {
249       (*message)(LDPL_ERROR, "Failed to get a view of %s", file->name);
250       return LDPS_ERR;
251     }
252   } else {
253     int64_t offset = 0;
254     // Gold has found what might be IR part-way inside of a file, such as
255     // an .a archive.
256     if (file->offset) {
257       offset = file->offset;
258     }
259     if (std::error_code ec = MemoryBuffer::getOpenFileSlice(
260             file->fd, file->name, buffer, file->filesize, offset)) {
261       (*message)(LDPL_ERROR, ec.message().c_str());
262       return LDPS_ERR;
263     }
264     view = buffer->getBufferStart();
265   }
266
267   if (!lto_module_is_object_file_in_memory(view, file->filesize))
268     return LDPS_OK;
269
270   M = lto_module_create_from_memory(view, file->filesize);
271   if (!M) {
272     if (const char* msg = lto_get_error_message()) {
273       (*message)(LDPL_ERROR,
274                  "LLVM gold plugin has failed to create LTO module: %s",
275                  msg);
276       return LDPS_ERR;
277     }
278     return LDPS_OK;
279   }
280
281   *claimed = 1;
282   Modules.resize(Modules.size() + 1);
283   claimed_file &cf = Modules.back();
284
285   if (!options::triple.empty())
286     lto_module_set_target_triple(M, options::triple.c_str());
287
288   cf.handle = file->handle;
289   unsigned sym_count = lto_module_get_num_symbols(M);
290   cf.syms.reserve(sym_count);
291
292   for (unsigned i = 0; i != sym_count; ++i) {
293     lto_symbol_attributes attrs = lto_module_get_symbol_attribute(M, i);
294     if ((attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
295       continue;
296
297     cf.syms.push_back(ld_plugin_symbol());
298     ld_plugin_symbol &sym = cf.syms.back();
299     sym.name = const_cast<char *>(lto_module_get_symbol_name(M, i));
300     sym.name = strdup(sym.name);
301     sym.version = NULL;
302
303     int scope = attrs & LTO_SYMBOL_SCOPE_MASK;
304     bool CanBeHidden = scope == LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
305     if (!CanBeHidden)
306       CannotBeHidden.insert(sym.name);
307     switch (scope) {
308       case LTO_SYMBOL_SCOPE_HIDDEN:
309         sym.visibility = LDPV_HIDDEN;
310         break;
311       case LTO_SYMBOL_SCOPE_PROTECTED:
312         sym.visibility = LDPV_PROTECTED;
313         break;
314       case 0: // extern
315       case LTO_SYMBOL_SCOPE_DEFAULT:
316       case LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN:
317         sym.visibility = LDPV_DEFAULT;
318         break;
319       default:
320         (*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope);
321         return LDPS_ERR;
322     }
323
324     int definition = attrs & LTO_SYMBOL_DEFINITION_MASK;
325     sym.comdat_key = NULL;
326     switch (definition) {
327       case LTO_SYMBOL_DEFINITION_REGULAR:
328         sym.def = LDPK_DEF;
329         break;
330       case LTO_SYMBOL_DEFINITION_UNDEFINED:
331         sym.def = LDPK_UNDEF;
332         break;
333       case LTO_SYMBOL_DEFINITION_TENTATIVE:
334         sym.def = LDPK_COMMON;
335         break;
336       case LTO_SYMBOL_DEFINITION_WEAK:
337         sym.comdat_key = sym.name;
338         sym.def = LDPK_WEAKDEF;
339         break;
340       case LTO_SYMBOL_DEFINITION_WEAKUNDEF:
341         sym.def = LDPK_WEAKUNDEF;
342         break;
343       default:
344         (*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition);
345         return LDPS_ERR;
346     }
347
348     sym.size = 0;
349
350     sym.resolution = LDPR_UNKNOWN;
351   }
352
353   cf.syms.reserve(cf.syms.size());
354
355   if (!cf.syms.empty()) {
356     if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
357       (*message)(LDPL_ERROR, "Unable to add symbols!");
358       return LDPS_ERR;
359     }
360   }
361
362   if (code_gen) {
363     if (lto_codegen_add_module(code_gen, M)) {
364       (*message)(LDPL_ERROR, "Error linking module: %s",
365                  lto_get_error_message());
366       return LDPS_ERR;
367     }
368   }
369
370   lto_module_dispose(M);
371
372   return LDPS_OK;
373 }
374
375 static bool mustPreserve(const claimed_file &F, int i) {
376   if (F.syms[i].resolution == LDPR_PREVAILING_DEF)
377     return true;
378   if (F.syms[i].resolution == LDPR_PREVAILING_DEF_IRONLY_EXP)
379     return CannotBeHidden.count(F.syms[i].name);
380   return false;
381 }
382
383 /// all_symbols_read_hook - gold informs us that all symbols have been read.
384 /// At this point, we use get_symbols to see if any of our definitions have
385 /// been overridden by a native object file. Then, perform optimization and
386 /// codegen.
387 static ld_plugin_status all_symbols_read_hook(void) {
388   std::ofstream api_file;
389   assert(code_gen);
390
391   if (options::generate_api_file) {
392     api_file.open("apifile.txt", std::ofstream::out | std::ofstream::trunc);
393     if (!api_file.is_open()) {
394       (*message)(LDPL_FATAL, "Unable to open apifile.txt for writing.");
395       abort();
396     }
397   }
398
399   for (std::list<claimed_file>::iterator I = Modules.begin(),
400          E = Modules.end(); I != E; ++I) {
401     if (I->syms.empty())
402       continue;
403     (*get_symbols)(I->handle, I->syms.size(), &I->syms[0]);
404     for (unsigned i = 0, e = I->syms.size(); i != e; i++) {
405       if (mustPreserve(*I, i)) {
406         lto_codegen_add_must_preserve_symbol(code_gen, I->syms[i].name);
407
408         if (options::generate_api_file)
409           api_file << I->syms[i].name << "\n";
410       }
411     }
412   }
413
414   if (options::generate_api_file)
415     api_file.close();
416
417   lto_codegen_set_pic_model(code_gen, output_type);
418   lto_codegen_set_debug_model(code_gen, LTO_DEBUG_MODEL_DWARF);
419   if (!options::mcpu.empty())
420     lto_codegen_set_cpu(code_gen, options::mcpu.c_str());
421
422   // Pass through extra options to the code generator.
423   if (!options::extra.empty()) {
424     for (std::vector<std::string>::iterator it = options::extra.begin();
425          it != options::extra.end(); ++it) {
426       lto_codegen_debug_options(code_gen, (*it).c_str());
427     }
428   }
429
430   if (options::generate_bc_file != options::BC_NO) {
431     std::string path;
432     if (options::generate_bc_file == options::BC_ONLY)
433       path = output_name;
434     else if (!options::bc_path.empty())
435       path = options::bc_path;
436     else
437       path = output_name + ".bc";
438     bool err = lto_codegen_write_merged_modules(code_gen, path.c_str());
439     if (err)
440       (*message)(LDPL_FATAL, "Failed to write the output file.");
441     if (options::generate_bc_file == options::BC_ONLY) {
442       lto_codegen_dispose(code_gen);
443       exit(0);
444     }
445   }
446
447   std::string ObjPath;
448   {
449     const char *Temp;
450     if (lto_codegen_compile_to_file(code_gen, &Temp)) {
451       (*message)(LDPL_ERROR, "Could not produce a combined object file\n");
452     }
453     ObjPath = Temp;
454   }
455
456   lto_codegen_dispose(code_gen);
457   for (std::list<claimed_file>::iterator I = Modules.begin(),
458          E = Modules.end(); I != E; ++I) {
459     for (unsigned i = 0; i != I->syms.size(); ++i) {
460       ld_plugin_symbol &sym = I->syms[i];
461       free(sym.name);
462     }
463   }
464
465   if ((*add_input_file)(ObjPath.c_str()) != LDPS_OK) {
466     (*message)(LDPL_ERROR, "Unable to add .o file to the link.");
467     (*message)(LDPL_ERROR, "File left behind in: %s", ObjPath.c_str());
468     return LDPS_ERR;
469   }
470
471   if (!options::extra_library_path.empty() &&
472       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK) {
473     (*message)(LDPL_ERROR, "Unable to set the extra library path.");
474     return LDPS_ERR;
475   }
476
477   if (options::obj_path.empty())
478     Cleanup.push_back(ObjPath);
479
480   return LDPS_OK;
481 }
482
483 static ld_plugin_status cleanup_hook(void) {
484   for (int i = 0, e = Cleanup.size(); i != e; ++i) {
485     std::error_code EC = sys::fs::remove(Cleanup[i]);
486     if (EC)
487       (*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(),
488                  EC.message().c_str());
489   }
490
491   return LDPS_OK;
492 }