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