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