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