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