Update the MemoryBuffer API to use ErrorOr.
[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   InitializeAllTargetInfos();
139   InitializeAllTargets();
140   InitializeAllTargetMCs();
141   InitializeAllAsmParsers();
142   InitializeAllAsmPrinters();
143
144   // We're given a pointer to the first transfer vector. We read through them
145   // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
146   // contain pointers to functions that we need to call to register our own
147   // hooks. The others are addresses of functions we can use to call into gold
148   // for services.
149
150   bool registeredClaimFile = false;
151   bool RegisteredAllSymbolsRead = false;
152
153   for (; tv->tv_tag != LDPT_NULL; ++tv) {
154     switch (tv->tv_tag) {
155       case LDPT_OUTPUT_NAME:
156         output_name = tv->tv_u.tv_string;
157         break;
158       case LDPT_LINKER_OUTPUT:
159         switch (tv->tv_u.tv_val) {
160           case LDPO_REL:  // .o
161           case LDPO_DYN:  // .so
162           case LDPO_PIE:  // position independent executable
163             output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
164             break;
165           case LDPO_EXEC:  // .exe
166             output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
167             break;
168           default:
169             (*message)(LDPL_ERROR, "Unknown output file type %d",
170                        tv->tv_u.tv_val);
171             return LDPS_ERR;
172         }
173         break;
174       case LDPT_OPTION:
175         options::process_plugin_option(tv->tv_u.tv_string);
176         break;
177       case LDPT_REGISTER_CLAIM_FILE_HOOK: {
178         ld_plugin_register_claim_file callback;
179         callback = tv->tv_u.tv_register_claim_file;
180
181         if ((*callback)(claim_file_hook) != LDPS_OK)
182           return LDPS_ERR;
183
184         registeredClaimFile = true;
185       } break;
186       case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
187         ld_plugin_register_all_symbols_read callback;
188         callback = tv->tv_u.tv_register_all_symbols_read;
189
190         if ((*callback)(all_symbols_read_hook) != LDPS_OK)
191           return LDPS_ERR;
192
193         RegisteredAllSymbolsRead = true;
194       } break;
195       case LDPT_REGISTER_CLEANUP_HOOK: {
196         ld_plugin_register_cleanup callback;
197         callback = tv->tv_u.tv_register_cleanup;
198
199         if ((*callback)(cleanup_hook) != LDPS_OK)
200           return LDPS_ERR;
201       } break;
202       case LDPT_ADD_SYMBOLS:
203         add_symbols = tv->tv_u.tv_add_symbols;
204         break;
205       case LDPT_GET_SYMBOLS_V2:
206         get_symbols = tv->tv_u.tv_get_symbols;
207         break;
208       case LDPT_ADD_INPUT_FILE:
209         add_input_file = tv->tv_u.tv_add_input_file;
210         break;
211       case LDPT_SET_EXTRA_LIBRARY_PATH:
212         set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
213         break;
214       case LDPT_GET_VIEW:
215         get_view = tv->tv_u.tv_get_view;
216         break;
217       case LDPT_MESSAGE:
218         message = tv->tv_u.tv_message;
219         break;
220       default:
221         break;
222     }
223   }
224
225   if (!registeredClaimFile) {
226     (*message)(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
227     return LDPS_ERR;
228   }
229   if (!add_symbols) {
230     (*message)(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
231     return LDPS_ERR;
232   }
233
234   if (!RegisteredAllSymbolsRead)
235     return LDPS_OK;
236
237   CodeGen = new LTOCodeGenerator();
238
239   // Pass through extra options to the code generator.
240   if (!options::extra.empty()) {
241     for (std::vector<std::string>::iterator it = options::extra.begin();
242          it != options::extra.end(); ++it) {
243       CodeGen->setCodeGenDebugOptions((*it).c_str());
244     }
245   }
246
247   CodeGen->parseCodeGenDebugOptions();
248   if (MAttrs.size()) {
249     std::string Attrs;
250     for (unsigned I = 0; I < MAttrs.size(); ++I) {
251       if (I > 0)
252         Attrs.append(",");
253       Attrs.append(MAttrs[I]);
254     }
255     CodeGen->setAttr(Attrs.c_str());
256   }
257
258   TargetOpts = InitTargetOptionsFromCodeGenFlags();
259   CodeGen->setTargetOptions(TargetOpts);
260
261   return LDPS_OK;
262 }
263
264 /// Called by gold to see whether this file is one that our plugin can handle.
265 /// We'll try to open it and register all the symbols with add_symbol if
266 /// possible.
267 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
268                                         int *claimed) {
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     ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
284         MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
285                                        offset);
286     if (std::error_code EC = BufferOrErr.getError()) {
287       (*message)(LDPL_ERROR, EC.message().c_str());
288       return LDPS_ERR;
289     }
290     buffer = std::move(BufferOrErr.get());
291     view = buffer->getBufferStart();
292   }
293
294   if (!LTOModule::isBitcodeFile(view, file->filesize))
295     return LDPS_OK;
296
297   std::string Error;
298   LTOModule *M =
299       LTOModule::createFromBuffer(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 = strdup(M->getSymbolName(i));
326     sym.version = NULL;
327
328     int scope = attrs & LTO_SYMBOL_SCOPE_MASK;
329     bool CanBeHidden = scope == LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
330     if (!CanBeHidden)
331       CannotBeHidden.insert(sym.name);
332     switch (scope) {
333       case LTO_SYMBOL_SCOPE_HIDDEN:
334         sym.visibility = LDPV_HIDDEN;
335         break;
336       case LTO_SYMBOL_SCOPE_PROTECTED:
337         sym.visibility = LDPV_PROTECTED;
338         break;
339       case 0: // extern
340       case LTO_SYMBOL_SCOPE_DEFAULT:
341       case LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN:
342         sym.visibility = LDPV_DEFAULT;
343         break;
344       default:
345         (*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope);
346         return LDPS_ERR;
347     }
348
349     int definition = attrs & LTO_SYMBOL_DEFINITION_MASK;
350     sym.comdat_key = NULL;
351     switch (definition) {
352       case LTO_SYMBOL_DEFINITION_REGULAR:
353         sym.def = LDPK_DEF;
354         break;
355       case LTO_SYMBOL_DEFINITION_UNDEFINED:
356         sym.def = LDPK_UNDEF;
357         break;
358       case LTO_SYMBOL_DEFINITION_TENTATIVE:
359         sym.def = LDPK_COMMON;
360         break;
361       case LTO_SYMBOL_DEFINITION_WEAK:
362         sym.comdat_key = sym.name;
363         sym.def = LDPK_WEAKDEF;
364         break;
365       case LTO_SYMBOL_DEFINITION_WEAKUNDEF:
366         sym.def = LDPK_WEAKUNDEF;
367         break;
368       default:
369         (*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition);
370         return LDPS_ERR;
371     }
372
373     sym.size = 0;
374
375     sym.resolution = LDPR_UNKNOWN;
376   }
377
378   cf.syms.reserve(cf.syms.size());
379
380   if (!cf.syms.empty()) {
381     if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
382       (*message)(LDPL_ERROR, "Unable to add symbols!");
383       return LDPS_ERR;
384     }
385   }
386
387   if (CodeGen) {
388     std::string Error;
389     if (!CodeGen->addModule(M, Error)) {
390       (*message)(LDPL_ERROR, "Error linking module: %s", Error.c_str());
391       return LDPS_ERR;
392     }
393   }
394
395   delete M;
396
397   return LDPS_OK;
398 }
399
400 static bool mustPreserve(const claimed_file &F, int i) {
401   if (F.syms[i].resolution == LDPR_PREVAILING_DEF)
402     return true;
403   if (F.syms[i].resolution == LDPR_PREVAILING_DEF_IRONLY_EXP)
404     return CannotBeHidden.count(F.syms[i].name);
405   return false;
406 }
407
408 /// all_symbols_read_hook - gold informs us that all symbols have been read.
409 /// At this point, we use get_symbols to see if any of our definitions have
410 /// been overridden by a native object file. Then, perform optimization and
411 /// codegen.
412 static ld_plugin_status all_symbols_read_hook(void) {
413   std::ofstream api_file;
414   assert(CodeGen);
415
416   if (options::generate_api_file) {
417     api_file.open("apifile.txt", std::ofstream::out | std::ofstream::trunc);
418     if (!api_file.is_open()) {
419       (*message)(LDPL_FATAL, "Unable to open apifile.txt for writing.");
420       abort();
421     }
422   }
423
424   for (std::list<claimed_file>::iterator I = Modules.begin(),
425          E = Modules.end(); I != E; ++I) {
426     if (I->syms.empty())
427       continue;
428     (*get_symbols)(I->handle, I->syms.size(), &I->syms[0]);
429     for (unsigned i = 0, e = I->syms.size(); i != e; i++) {
430       if (mustPreserve(*I, i)) {
431         CodeGen->addMustPreserveSymbol(I->syms[i].name);
432
433         if (options::generate_api_file)
434           api_file << I->syms[i].name << "\n";
435       }
436     }
437   }
438
439   if (options::generate_api_file)
440     api_file.close();
441
442   CodeGen->setCodePICModel(output_type);
443   CodeGen->setDebugInfo(LTO_DEBUG_MODEL_DWARF);
444   if (!options::mcpu.empty())
445     CodeGen->setCpu(options::mcpu.c_str());
446
447   if (options::generate_bc_file != options::BC_NO) {
448     std::string path;
449     if (options::generate_bc_file == options::BC_ONLY)
450       path = output_name;
451     else if (!options::bc_path.empty())
452       path = options::bc_path;
453     else
454       path = output_name + ".bc";
455     std::string Error;
456     if (!CodeGen->writeMergedModules(path.c_str(), Error))
457       (*message)(LDPL_FATAL, "Failed to write the output file.");
458     if (options::generate_bc_file == options::BC_ONLY) {
459       delete CodeGen;
460       exit(0);
461     }
462   }
463
464   std::string ObjPath;
465   {
466     const char *Temp;
467     std::string Error;
468     if (!CodeGen->compile_to_file(&Temp, /*DisableOpt*/ false, /*DisableInline*/
469                                   false, /*DisableGVNLoadPRE*/ false, Error))
470       (*message)(LDPL_ERROR, "Could not produce a combined object file\n");
471     ObjPath = Temp;
472   }
473
474   delete CodeGen;
475   for (std::list<claimed_file>::iterator I = Modules.begin(),
476          E = Modules.end(); I != E; ++I) {
477     for (unsigned i = 0; i != I->syms.size(); ++i) {
478       ld_plugin_symbol &sym = I->syms[i];
479       free(sym.name);
480     }
481   }
482
483   if ((*add_input_file)(ObjPath.c_str()) != LDPS_OK) {
484     (*message)(LDPL_ERROR, "Unable to add .o file to the link.");
485     (*message)(LDPL_ERROR, "File left behind in: %s", ObjPath.c_str());
486     return LDPS_ERR;
487   }
488
489   if (!options::extra_library_path.empty() &&
490       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK) {
491     (*message)(LDPL_ERROR, "Unable to set the extra library path.");
492     return LDPS_ERR;
493   }
494
495   if (options::obj_path.empty())
496     Cleanup.push_back(ObjPath);
497
498   return LDPS_OK;
499 }
500
501 static ld_plugin_status cleanup_hook(void) {
502   for (int i = 0, e = Cleanup.size(); i != e; ++i) {
503     std::error_code EC = sys::fs::remove(Cleanup[i]);
504     if (EC)
505       (*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(),
506                  EC.message().c_str());
507   }
508
509   return LDPS_OK;
510 }