Add support in the LTO library for loading an object from the middle
[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"
16 #include "plugin-api.h"
17
18 #include "llvm-c/lto.h"
19
20 #include "llvm/Support/ToolOutputFile.h"
21 #include "llvm/Support/Errno.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/Program.h"
24
25 #include <cerrno>
26 #include <cstdlib>
27 #include <cstring>
28 #include <fstream>
29 #include <list>
30 #include <vector>
31
32 // Support Windows/MinGW crazyness.
33 #ifdef _WIN32
34 # include <io.h>
35 # define lseek _lseek
36 # define read _read
37 #endif
38
39 using namespace llvm;
40
41 namespace {
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.
45     abort();
46   }
47
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;
54
55   int api_version = 0;
56   int gold_version = 0;
57
58   struct claimed_file {
59     void *handle;
60     std::vector<ld_plugin_symbol> syms;
61   };
62
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;
68 }
69
70 namespace options {
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;
85
86   static void process_plugin_option(const char* opt_)
87   {
88     if (opt_ == NULL)
89       return;
90     llvm::StringRef opt = opt_;
91
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_);
112       } else {
113         bc_path = path;
114       }
115     } else {
116       // Save this option to pass to the code generator.
117       extra.push_back(opt);
118     }
119   }
120 }
121
122 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
123                                         int *claimed);
124 static ld_plugin_status all_symbols_read_hook(void);
125 static ld_plugin_status cleanup_hook(void);
126
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
133   // for services.
134
135   bool registeredClaimFile = false;
136
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;
141         break;
142       case LDPT_GOLD_VERSION:  // major * 100 + minor
143         gold_version = tv->tv_u.tv_val;
144         break;
145       case LDPT_OUTPUT_NAME:
146         output_name = tv->tv_u.tv_string;
147         break;
148       case LDPT_LINKER_OUTPUT:
149         switch (tv->tv_u.tv_val) {
150           case LDPO_REL:  // .o
151           case LDPO_DYN:  // .so
152             output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
153             break;
154           case LDPO_EXEC:  // .exe
155             output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
156             break;
157           default:
158             (*message)(LDPL_ERROR, "Unknown output file type %d",
159                        tv->tv_u.tv_val);
160             return LDPS_ERR;
161         }
162         // TODO: add an option to disable PIC.
163         //output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC;
164         break;
165       case LDPT_OPTION:
166         options::process_plugin_option(tv->tv_u.tv_string);
167         break;
168       case LDPT_REGISTER_CLAIM_FILE_HOOK: {
169         ld_plugin_register_claim_file callback;
170         callback = tv->tv_u.tv_register_claim_file;
171
172         if ((*callback)(claim_file_hook) != LDPS_OK)
173           return LDPS_ERR;
174
175         registeredClaimFile = true;
176       } break;
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;
180
181         if ((*callback)(all_symbols_read_hook) != LDPS_OK)
182           return LDPS_ERR;
183
184         code_gen = lto_codegen_create();
185       } break;
186       case LDPT_REGISTER_CLEANUP_HOOK: {
187         ld_plugin_register_cleanup callback;
188         callback = tv->tv_u.tv_register_cleanup;
189
190         if ((*callback)(cleanup_hook) != LDPS_OK)
191           return LDPS_ERR;
192       } break;
193       case LDPT_ADD_SYMBOLS:
194         add_symbols = tv->tv_u.tv_add_symbols;
195         break;
196       case LDPT_GET_SYMBOLS:
197         get_symbols = tv->tv_u.tv_get_symbols;
198         break;
199       case LDPT_ADD_INPUT_FILE:
200         add_input_file = tv->tv_u.tv_add_input_file;
201         break;
202       case LDPT_ADD_INPUT_LIBRARY:
203         add_input_library = tv->tv_u.tv_add_input_file;
204         break;
205       case LDPT_SET_EXTRA_LIBRARY_PATH:
206         set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
207         break;
208       case LDPT_MESSAGE:
209         message = tv->tv_u.tv_message;
210         break;
211       default:
212         break;
213     }
214   }
215
216   if (!registeredClaimFile) {
217     (*message)(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
218     return LDPS_ERR;
219   }
220   if (!add_symbols) {
221     (*message)(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
222     return LDPS_ERR;
223   }
224
225   return LDPS_OK;
226 }
227
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,
232                                         int *claimed) {
233   lto_module_t M;
234
235   if (file->offset) {
236     // Gold has found what might be IR part-way inside of a file, such as
237     // an .a archive.
238     M = lto_module_create_from_fd_at_offset(file->fd, file->name, -1,
239                                             file->filesize, file->offset);
240   } else {
241     M = lto_module_create_from_fd(file->fd, file->name, file->filesize);
242   }
243   if (!M)
244     return LDPS_OK;
245
246   *claimed = 1;
247   Modules.resize(Modules.size() + 1);
248   claimed_file &cf = Modules.back();
249
250   if (!options::triple.empty())
251     lto_module_set_target_triple(M, options::triple.c_str());
252
253   cf.handle = file->handle;
254   unsigned sym_count = lto_module_get_num_symbols(M);
255   cf.syms.reserve(sym_count);
256
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)
260       continue;
261
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);
266     sym.version = NULL;
267
268     int scope = attrs & LTO_SYMBOL_SCOPE_MASK;
269     switch (scope) {
270       case LTO_SYMBOL_SCOPE_HIDDEN:
271         sym.visibility = LDPV_HIDDEN;
272         break;
273       case LTO_SYMBOL_SCOPE_PROTECTED:
274         sym.visibility = LDPV_PROTECTED;
275         break;
276       case 0: // extern
277       case LTO_SYMBOL_SCOPE_DEFAULT:
278         sym.visibility = LDPV_DEFAULT;
279         break;
280       default:
281         (*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope);
282         return LDPS_ERR;
283     }
284
285     int definition = attrs & LTO_SYMBOL_DEFINITION_MASK;
286     sym.comdat_key = NULL;
287     switch (definition) {
288       case LTO_SYMBOL_DEFINITION_REGULAR:
289         sym.def = LDPK_DEF;
290         break;
291       case LTO_SYMBOL_DEFINITION_UNDEFINED:
292         sym.def = LDPK_UNDEF;
293         break;
294       case LTO_SYMBOL_DEFINITION_TENTATIVE:
295         sym.def = LDPK_COMMON;
296         break;
297       case LTO_SYMBOL_DEFINITION_WEAK:
298         sym.comdat_key = sym.name;
299         sym.def = LDPK_WEAKDEF;
300         break;
301       case LTO_SYMBOL_DEFINITION_WEAKUNDEF:
302         sym.def = LDPK_WEAKUNDEF;
303         break;
304       default:
305         (*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition);
306         return LDPS_ERR;
307     }
308
309     sym.size = 0;
310
311     sym.resolution = LDPR_UNKNOWN;
312   }
313
314   cf.syms.reserve(cf.syms.size());
315
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!");
319       return LDPS_ERR;
320     }
321   }
322
323   if (code_gen)
324     lto_codegen_add_module(code_gen, M);
325
326   lto_module_dispose(M);
327
328   return LDPS_OK;
329 }
330
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
334 /// codegen.
335 static ld_plugin_status all_symbols_read_hook(void) {
336   std::ofstream api_file;
337   assert(code_gen);
338
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.");
343       abort();
344     }
345   }
346
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;
357
358         if (options::generate_api_file)
359           api_file << I->syms[i].name << "\n";
360       }
361     }
362   }
363
364   if (options::generate_api_file)
365     api_file.close();
366
367   if (!anySymbolsPreserved) {
368     // All of the IL is unnecessary!
369     lto_codegen_dispose(code_gen);
370     return LDPS_OK;
371   }
372
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());
377
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());
383     }
384   }
385
386   if (options::generate_bc_file != options::BC_NO) {
387     std::string path;
388     if (options::generate_bc_file == options::BC_ONLY)
389       path = output_name;
390     else if (!options::bc_path.empty())
391       path = options::bc_path;
392     else
393       path = output_name + ".bc";
394     bool err = lto_codegen_write_merged_modules(code_gen, path.c_str());
395     if (err)
396       (*message)(LDPL_FATAL, "Failed to write the output file.");
397     if (options::generate_bc_file == options::BC_ONLY)
398       exit(0);
399   }
400   size_t bufsize = 0;
401   const char *buffer = static_cast<const char *>(lto_codegen_compile(code_gen,
402                                                                      &bufsize));
403
404   std::string ErrMsg;
405
406   const char *objPath;
407   sys::Path uniqueObjPath("/tmp/llvmgold.o");
408   if (!options::obj_path.empty()) {
409     objPath = options::obj_path.c_str();
410   } else {
411     if (uniqueObjPath.createTemporaryFileOnDisk(true, &ErrMsg)) {
412       (*message)(LDPL_ERROR, "%s", ErrMsg.c_str());
413       return LDPS_ERR;
414     }
415     objPath = uniqueObjPath.c_str();
416   }
417   tool_output_file objFile(objPath, ErrMsg,
418                              raw_fd_ostream::F_Binary);
419     if (!ErrMsg.empty()) {
420       (*message)(LDPL_ERROR, "%s", ErrMsg.c_str());
421       return LDPS_ERR;
422     }
423
424   objFile.os().write(buffer, bufsize);
425   objFile.os().close();
426   if (objFile.os().has_error()) {
427     (*message)(LDPL_ERROR, "Error writing output file '%s'",
428                objPath);
429     objFile.os().clear_error();
430     return LDPS_ERR;
431   }
432   objFile.keep();
433
434   lto_codegen_dispose(code_gen);
435   for (std::list<claimed_file>::iterator I = Modules.begin(),
436          E = Modules.end(); I != E; ++I) {
437     for (unsigned i = 0; i != I->syms.size(); ++i) {
438       ld_plugin_symbol &sym = I->syms[i];
439       free(sym.name);
440     }
441   }
442
443   if ((*add_input_file)(objPath) != LDPS_OK) {
444     (*message)(LDPL_ERROR, "Unable to add .o file to the link.");
445     (*message)(LDPL_ERROR, "File left behind in: %s", objPath);
446     return LDPS_ERR;
447   }
448
449   if (!options::extra_library_path.empty() &&
450       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK) {
451     (*message)(LDPL_ERROR, "Unable to set the extra library path.");
452     return LDPS_ERR;
453   }
454
455   if (options::obj_path.empty())
456     Cleanup.push_back(sys::Path(objPath));
457
458   return LDPS_OK;
459 }
460
461 static ld_plugin_status cleanup_hook(void) {
462   std::string ErrMsg;
463
464   for (int i = 0, e = Cleanup.size(); i != e; ++i)
465     if (Cleanup[i].eraseFromDisk(false, &ErrMsg))
466       (*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(),
467                  ErrMsg.c_str());
468
469   return LDPS_OK;
470 }