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