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