33156edc896d093131a612cab8fb78fb7bece6cb
[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     lto_module_t M;
60     void *handle;
61     std::vector<ld_plugin_symbol> syms;
62   };
63
64   lto_codegen_model output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
65   std::string output_name = "";
66   std::list<claimed_file> Modules;
67   std::vector<sys::Path> Cleanup;
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 as_path;
77   static std::vector<std::string> as_args;
78   static std::vector<std::string> pass_through;
79   static std::string extra_library_path;
80   static std::string triple;
81   static std::string mcpu;
82   // Additional options to pass into the code generator.
83   // Note: This array will contain all plugin options which are not claimed
84   // as plugin exclusive to pass to the code generator.
85   // For example, "generate-api-file" and "as"options are for the plugin
86   // use only and will not be passed.
87   static std::vector<std::string> extra;
88
89   static void process_plugin_option(const char* opt_)
90   {
91     if (opt_ == NULL)
92       return;
93     llvm::StringRef opt = opt_;
94
95     if (opt == "generate-api-file") {
96       generate_api_file = true;
97     } else if (opt.startswith("mcpu=")) {
98       mcpu = opt.substr(strlen("mcpu="));
99     } else if (opt.startswith("as=")) {
100       if (!as_path.empty()) {
101         (*message)(LDPL_WARNING, "Path to as specified twice. "
102                    "Discarding %s", opt_);
103       } else {
104         as_path = opt.substr(strlen("as="));
105       }
106     } else if (opt.startswith("as-arg=")) {
107       llvm::StringRef item = opt.substr(strlen("as-arg="));
108       as_args.push_back(item.str());
109     } else if (opt.startswith("extra-library-path=")) {
110       extra_library_path = opt.substr(strlen("extra_library_path="));
111     } else if (opt.startswith("pass-through=")) {
112       llvm::StringRef item = opt.substr(strlen("pass-through="));
113       pass_through.push_back(item.str());
114     } else if (opt.startswith("mtriple=")) {
115       triple = opt.substr(strlen("mtriple="));
116     } else if (opt.startswith("obj-path=")) {
117       obj_path = opt.substr(strlen("obj-path="));
118     } else if (opt == "emit-llvm") {
119       generate_bc_file = BC_ONLY;
120     } else if (opt == "also-emit-llvm") {
121       generate_bc_file = BC_ALSO;
122     } else if (opt.startswith("also-emit-llvm=")) {
123       llvm::StringRef path = opt.substr(strlen("also-emit-llvm="));
124       generate_bc_file = BC_ALSO;
125       if (!bc_path.empty()) {
126         (*message)(LDPL_WARNING, "Path to the output IL file specified twice. "
127                    "Discarding %s", opt_);
128       } else {
129         bc_path = path;
130       }
131     } else {
132       // Save this option to pass to the code generator.
133       extra.push_back(opt);
134     }
135   }
136 }
137
138 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
139                                         int *claimed);
140 static ld_plugin_status all_symbols_read_hook(void);
141 static ld_plugin_status cleanup_hook(void);
142
143 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
144 ld_plugin_status onload(ld_plugin_tv *tv) {
145   // We're given a pointer to the first transfer vector. We read through them
146   // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
147   // contain pointers to functions that we need to call to register our own
148   // hooks. The others are addresses of functions we can use to call into gold
149   // for services.
150
151   bool registeredClaimFile = false;
152
153   for (; tv->tv_tag != LDPT_NULL; ++tv) {
154     switch (tv->tv_tag) {
155       case LDPT_API_VERSION:
156         api_version = tv->tv_u.tv_val;
157         break;
158       case LDPT_GOLD_VERSION:  // major * 100 + minor
159         gold_version = tv->tv_u.tv_val;
160         break;
161       case LDPT_OUTPUT_NAME:
162         output_name = tv->tv_u.tv_string;
163         break;
164       case LDPT_LINKER_OUTPUT:
165         switch (tv->tv_u.tv_val) {
166           case LDPO_REL:  // .o
167           case LDPO_DYN:  // .so
168             output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
169             break;
170           case LDPO_EXEC:  // .exe
171             output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
172             break;
173           default:
174             (*message)(LDPL_ERROR, "Unknown output file type %d",
175                        tv->tv_u.tv_val);
176             return LDPS_ERR;
177         }
178         // TODO: add an option to disable PIC.
179         //output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC;
180         break;
181       case LDPT_OPTION:
182         options::process_plugin_option(tv->tv_u.tv_string);
183         break;
184       case LDPT_REGISTER_CLAIM_FILE_HOOK: {
185         ld_plugin_register_claim_file callback;
186         callback = tv->tv_u.tv_register_claim_file;
187
188         if ((*callback)(claim_file_hook) != LDPS_OK)
189           return LDPS_ERR;
190
191         registeredClaimFile = true;
192       } break;
193       case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
194         ld_plugin_register_all_symbols_read callback;
195         callback = tv->tv_u.tv_register_all_symbols_read;
196
197         if ((*callback)(all_symbols_read_hook) != LDPS_OK)
198           return LDPS_ERR;
199       } break;
200       case LDPT_REGISTER_CLEANUP_HOOK: {
201         ld_plugin_register_cleanup callback;
202         callback = tv->tv_u.tv_register_cleanup;
203
204         if ((*callback)(cleanup_hook) != LDPS_OK)
205           return LDPS_ERR;
206       } break;
207       case LDPT_ADD_SYMBOLS:
208         add_symbols = tv->tv_u.tv_add_symbols;
209         break;
210       case LDPT_GET_SYMBOLS:
211         get_symbols = tv->tv_u.tv_get_symbols;
212         break;
213       case LDPT_ADD_INPUT_FILE:
214         add_input_file = tv->tv_u.tv_add_input_file;
215         break;
216       case LDPT_ADD_INPUT_LIBRARY:
217         add_input_library = tv->tv_u.tv_add_input_file;
218         break;
219       case LDPT_SET_EXTRA_LIBRARY_PATH:
220         set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
221         break;
222       case LDPT_MESSAGE:
223         message = tv->tv_u.tv_message;
224         break;
225       default:
226         break;
227     }
228   }
229
230   if (!registeredClaimFile) {
231     (*message)(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
232     return LDPS_ERR;
233   }
234   if (!add_symbols) {
235     (*message)(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
236     return LDPS_ERR;
237   }
238
239   return LDPS_OK;
240 }
241
242 /// claim_file_hook - called by gold to see whether this file is one that
243 /// our plugin can handle. We'll try to open it and register all the symbols
244 /// with add_symbol if possible.
245 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
246                                         int *claimed) {
247   lto_module_t M;
248
249   if (file->offset) {
250     // Gold has found what might be IR part-way inside of a file, such as
251     // an .a archive.
252     if (lseek(file->fd, file->offset, SEEK_SET) == -1) {
253       (*message)(LDPL_ERROR,
254                  "Failed to seek to archive member of %s at offset %d: %s\n",
255                  file->name,
256                  file->offset, sys::StrError(errno).c_str());
257       return LDPS_ERR;
258     }
259     void *buf = malloc(file->filesize);
260     if (!buf) {
261       (*message)(LDPL_ERROR,
262                  "Failed to allocate buffer for archive member of size: %d\n",
263                  file->filesize);
264       return LDPS_ERR;
265     }
266     if (read(file->fd, buf, file->filesize) != file->filesize) {
267       (*message)(LDPL_ERROR,
268                  "Failed to read archive member of %s at offset %d: %s\n",
269                  file->name,
270                  file->offset,
271                  sys::StrError(errno).c_str());
272       free(buf);
273       return LDPS_ERR;
274     }
275     if (!lto_module_is_object_file_in_memory(buf, file->filesize)) {
276       free(buf);
277       return LDPS_OK;
278     }
279     M = lto_module_create_from_memory(buf, file->filesize);
280     free(buf);
281   } else {
282     // FIXME: We should not need to pass -1 as the file size, but there
283     // is a bug in BFD that causes it to pass 0 to us. Remove this once
284     // that is fixed.
285     off_t size = file->filesize ? file->filesize : -1;
286
287     // FIXME: We should not need to reset the position in the file, but there
288     // is a bug in BFD. Remove this once that is fixed.
289     off_t old_pos = lseek(file->fd, 0, SEEK_CUR);
290
291     lseek(file->fd, 0, SEEK_SET);
292     M = lto_module_create_from_fd(file->fd, file->name, size);
293
294     lseek(file->fd, old_pos, SEEK_SET);
295     if (!M)
296       return LDPS_OK;
297   }
298
299   *claimed = 1;
300   Modules.resize(Modules.size() + 1);
301   claimed_file &cf = Modules.back();
302   cf.M = M;
303
304   if (!cf.M) {
305     (*message)(LDPL_ERROR, "Failed to create LLVM module: %s",
306                lto_get_error_message());
307     return LDPS_ERR;
308   }
309
310   if (!options::triple.empty())
311     lto_module_set_target_triple(cf.M, options::triple.c_str());
312
313   cf.handle = file->handle;
314   unsigned sym_count = lto_module_get_num_symbols(cf.M);
315   cf.syms.reserve(sym_count);
316
317   for (unsigned i = 0; i != sym_count; ++i) {
318     lto_symbol_attributes attrs = lto_module_get_symbol_attribute(cf.M, i);
319     if ((attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
320       continue;
321
322     cf.syms.push_back(ld_plugin_symbol());
323     ld_plugin_symbol &sym = cf.syms.back();
324     sym.name = const_cast<char *>(lto_module_get_symbol_name(cf.M, i));
325     sym.version = NULL;
326
327     int scope = attrs & LTO_SYMBOL_SCOPE_MASK;
328     switch (scope) {
329       case LTO_SYMBOL_SCOPE_HIDDEN:
330         sym.visibility = LDPV_HIDDEN;
331         break;
332       case LTO_SYMBOL_SCOPE_PROTECTED:
333         sym.visibility = LDPV_PROTECTED;
334         break;
335       case 0: // extern
336       case LTO_SYMBOL_SCOPE_DEFAULT:
337         sym.visibility = LDPV_DEFAULT;
338         break;
339       default:
340         (*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope);
341         return LDPS_ERR;
342     }
343
344     int definition = attrs & LTO_SYMBOL_DEFINITION_MASK;
345     sym.comdat_key = NULL;
346     switch (definition) {
347       case LTO_SYMBOL_DEFINITION_REGULAR:
348         sym.def = LDPK_DEF;
349         break;
350       case LTO_SYMBOL_DEFINITION_UNDEFINED:
351         sym.def = LDPK_UNDEF;
352         break;
353       case LTO_SYMBOL_DEFINITION_TENTATIVE:
354         sym.def = LDPK_COMMON;
355         break;
356       case LTO_SYMBOL_DEFINITION_WEAK:
357         sym.comdat_key = sym.name;
358         sym.def = LDPK_WEAKDEF;
359         break;
360       case LTO_SYMBOL_DEFINITION_WEAKUNDEF:
361         sym.def = LDPK_WEAKUNDEF;
362         break;
363       default:
364         (*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition);
365         return LDPS_ERR;
366     }
367
368     sym.size = 0;
369
370     sym.resolution = LDPR_UNKNOWN;
371   }
372
373   cf.syms.reserve(cf.syms.size());
374
375   if (!cf.syms.empty()) {
376     if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
377       (*message)(LDPL_ERROR, "Unable to add symbols!");
378       return LDPS_ERR;
379     }
380   }
381
382   return LDPS_OK;
383 }
384
385 /// all_symbols_read_hook - gold informs us that all symbols have been read.
386 /// At this point, we use get_symbols to see if any of our definitions have
387 /// been overridden by a native object file. Then, perform optimization and
388 /// codegen.
389 static ld_plugin_status all_symbols_read_hook(void) {
390   lto_code_gen_t cg = lto_codegen_create();
391
392   for (std::list<claimed_file>::iterator I = Modules.begin(),
393        E = Modules.end(); I != E; ++I)
394     lto_codegen_add_module(cg, I->M);
395
396   std::ofstream api_file;
397   if (options::generate_api_file) {
398     api_file.open("apifile.txt", std::ofstream::out | std::ofstream::trunc);
399     if (!api_file.is_open()) {
400       (*message)(LDPL_FATAL, "Unable to open apifile.txt for writing.");
401       abort();
402     }
403   }
404
405   // If we don't preserve any symbols, libLTO will assume that all symbols are
406   // needed. Keep all symbols unless we're producing a final executable.
407   bool anySymbolsPreserved = false;
408   for (std::list<claimed_file>::iterator I = Modules.begin(),
409          E = Modules.end(); I != E; ++I) {
410     (*get_symbols)(I->handle, I->syms.size(), &I->syms[0]);
411     for (unsigned i = 0, e = I->syms.size(); i != e; i++) {
412       if (I->syms[i].resolution == LDPR_PREVAILING_DEF) {
413         lto_codegen_add_must_preserve_symbol(cg, I->syms[i].name);
414         anySymbolsPreserved = true;
415
416         if (options::generate_api_file)
417           api_file << I->syms[i].name << "\n";
418       }
419     }
420   }
421
422   if (options::generate_api_file)
423     api_file.close();
424
425   if (!anySymbolsPreserved) {
426     // All of the IL is unnecessary!
427     lto_codegen_dispose(cg);
428     return LDPS_OK;
429   }
430
431   lto_codegen_set_pic_model(cg, output_type);
432   lto_codegen_set_debug_model(cg, LTO_DEBUG_MODEL_DWARF);
433   if (!options::as_path.empty()) {
434     sys::Path p = sys::Program::FindProgramByName(options::as_path);
435     lto_codegen_set_assembler_path(cg, p.c_str());
436   }
437   if (!options::as_args.empty()) {
438     std::vector<const char *> as_args_p;
439     for (std::vector<std::string>::iterator I = options::as_args.begin(),
440            E = options::as_args.end(); I != E; ++I) {
441       as_args_p.push_back(I->c_str());
442     }
443     lto_codegen_set_assembler_args(cg, &as_args_p[0], as_args_p.size());
444   }
445   if (!options::mcpu.empty())
446     lto_codegen_set_cpu(cg, options::mcpu.c_str());
447
448   // Pass through extra options to the code generator.
449   if (!options::extra.empty()) {
450     for (std::vector<std::string>::iterator it = options::extra.begin();
451          it != options::extra.end(); ++it) {
452       lto_codegen_debug_options(cg, (*it).c_str());
453     }
454   }
455
456
457   if (options::generate_bc_file != options::BC_NO) {
458     std::string path;
459     if (options::generate_bc_file == options::BC_ONLY)
460       path = output_name;
461     else if (!options::bc_path.empty())
462       path = options::bc_path;
463     else
464       path = output_name + ".bc";
465     bool err = lto_codegen_write_merged_modules(cg, path.c_str());
466     if (err)
467       (*message)(LDPL_FATAL, "Failed to write the output file.");
468     if (options::generate_bc_file == options::BC_ONLY)
469       exit(0);
470   }
471   size_t bufsize = 0;
472   const char *buffer = static_cast<const char *>(lto_codegen_compile(cg,
473                                                                      &bufsize));
474
475   std::string ErrMsg;
476
477   const char *objPath;
478   if (!options::obj_path.empty()) {
479     objPath = options::obj_path.c_str();
480   } else {
481     sys::Path uniqueObjPath("/tmp/llvmgold.o");
482     if (uniqueObjPath.createTemporaryFileOnDisk(true, &ErrMsg)) {
483       (*message)(LDPL_ERROR, "%s", ErrMsg.c_str());
484       return LDPS_ERR;
485     }
486     objPath = uniqueObjPath.c_str();
487   }
488   tool_output_file objFile(objPath, ErrMsg,
489                              raw_fd_ostream::F_Binary);
490     if (!ErrMsg.empty()) {
491       (*message)(LDPL_ERROR, "%s", ErrMsg.c_str());
492       return LDPS_ERR;
493     }
494
495   objFile.os().write(buffer, bufsize);
496   objFile.os().close();
497   if (objFile.os().has_error()) {
498     (*message)(LDPL_ERROR, "Error writing output file '%s'",
499                objPath);
500     objFile.os().clear_error();
501     return LDPS_ERR;
502   }
503   objFile.keep();
504
505   lto_codegen_dispose(cg);
506
507   if ((*add_input_file)(objPath) != LDPS_OK) {
508     (*message)(LDPL_ERROR, "Unable to add .o file to the link.");
509     (*message)(LDPL_ERROR, "File left behind in: %s", objPath);
510     return LDPS_ERR;
511   }
512
513   if (!options::extra_library_path.empty() &&
514       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK) {
515     (*message)(LDPL_ERROR, "Unable to set the extra library path.");
516     return LDPS_ERR;
517   }
518
519   for (std::vector<std::string>::iterator i = options::pass_through.begin(),
520                                           e = options::pass_through.end();
521        i != e; ++i) {
522     std::string &item = *i;
523     const char *item_p = item.c_str();
524     if (llvm::StringRef(item).startswith("-l")) {
525       if (add_input_library(item_p + 2) != LDPS_OK) {
526         (*message)(LDPL_ERROR, "Unable to add library to the link.");
527         return LDPS_ERR;
528       }
529     } else {
530       if (add_input_file(item_p) != LDPS_OK) {
531         (*message)(LDPL_ERROR, "Unable to add .o file to the link.");
532         return LDPS_ERR;
533       }
534     }
535   }
536
537   if (options::obj_path.empty())
538     Cleanup.push_back(sys::Path(objPath));
539
540   return LDPS_OK;
541 }
542
543 static ld_plugin_status cleanup_hook(void) {
544   std::string ErrMsg;
545
546   for (int i = 0, e = Cleanup.size(); i != e; ++i)
547     if (Cleanup[i].eraseFromDisk(false, &ErrMsg))
548       (*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(),
549                  ErrMsg.c_str());
550
551   return LDPS_OK;
552 }