65092a682a446ce205882b09e4563dfdbdfbf0c3
[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 "plugin-api.h"
16
17 #include "llvm-c/lto.h"
18
19 #include "llvm/Support/raw_ostream.h"
20 #include "llvm/System/Path.h"
21
22 #include <cstdlib>
23 #include <cstring>
24 #include <list>
25 #include <vector>
26 #include <cerrno>
27
28 using namespace llvm;
29
30 namespace {
31   ld_plugin_status discard_message(int level, const char *format, ...) {
32     // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
33     // callback in the transfer vector. This should never be called.
34     abort();
35   }
36
37   ld_plugin_add_symbols add_symbols = NULL;
38   ld_plugin_get_symbols get_symbols = NULL;
39   ld_plugin_add_input_file add_input_file = NULL;
40   ld_plugin_message message = discard_message;
41
42   int api_version = 0;
43   int gold_version = 0;
44
45   struct claimed_file {
46     lto_module_t M;
47     void *handle;
48     void *buf;
49     std::vector<ld_plugin_symbol> syms;
50   };
51
52   lto_codegen_model output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
53   std::list<claimed_file> Modules;
54   std::vector<sys::Path> Cleanup;
55 }
56
57 ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
58                                  int *claimed);
59 ld_plugin_status all_symbols_read_hook(void);
60 ld_plugin_status cleanup_hook(void);
61
62 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
63 ld_plugin_status onload(ld_plugin_tv *tv) {
64   // We're given a pointer to the first transfer vector. We read through them
65   // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
66   // contain pointers to functions that we need to call to register our own
67   // hooks. The others are addresses of functions we can use to call into gold
68   // for services.
69
70   bool registeredClaimFile = false;
71   bool registeredAllSymbolsRead = false;
72   bool registeredCleanup = false;
73
74   for (; tv->tv_tag != LDPT_NULL; ++tv) {
75     switch (tv->tv_tag) {
76       case LDPT_API_VERSION:
77         api_version = tv->tv_u.tv_val;
78         break;
79       case LDPT_GOLD_VERSION:  // major * 100 + minor
80         gold_version = tv->tv_u.tv_val;
81         break;
82       case LDPT_LINKER_OUTPUT:
83         switch (tv->tv_u.tv_val) {
84           case LDPO_REL:  // .o
85           case LDPO_DYN:  // .so
86             output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
87             break;
88           case LDPO_EXEC:  // .exe
89             output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
90             break;
91           default:
92             (*message)(LDPL_ERROR, "Unknown output file type %d",
93                        tv->tv_u.tv_val);
94             return LDPS_ERR;
95         }
96         // TODO: add an option to disable PIC.
97         //output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC;
98         break;
99       case LDPT_OPTION:
100         (*message)(LDPL_WARNING, "Ignoring flag %s", tv->tv_u.tv_string);
101         break;
102       case LDPT_REGISTER_CLAIM_FILE_HOOK: {
103         ld_plugin_register_claim_file callback;
104         callback = tv->tv_u.tv_register_claim_file;
105
106         if ((*callback)(claim_file_hook) != LDPS_OK)
107           return LDPS_ERR;
108
109         registeredClaimFile = true;
110       } break;
111       case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
112         ld_plugin_register_all_symbols_read callback;
113         callback = tv->tv_u.tv_register_all_symbols_read;
114
115         if ((*callback)(all_symbols_read_hook) != LDPS_OK)
116           return LDPS_ERR;
117
118         registeredAllSymbolsRead = true;
119       } break;
120       case LDPT_REGISTER_CLEANUP_HOOK: {
121         ld_plugin_register_cleanup callback;
122         callback = tv->tv_u.tv_register_cleanup;
123
124         if ((*callback)(cleanup_hook) != LDPS_OK)
125           return LDPS_ERR;
126
127         registeredCleanup = true;
128       } break;
129       case LDPT_ADD_SYMBOLS:
130         add_symbols = tv->tv_u.tv_add_symbols;
131         break;
132       case LDPT_GET_SYMBOLS:
133         get_symbols = tv->tv_u.tv_get_symbols;
134         break;
135       case LDPT_ADD_INPUT_FILE:
136         add_input_file = tv->tv_u.tv_add_input_file;
137         break;
138       case LDPT_MESSAGE:
139         message = tv->tv_u.tv_message;
140         break;
141       default:
142         break;
143     }
144   }
145
146   if (!registeredClaimFile || !registeredAllSymbolsRead || !registeredCleanup ||
147       !add_symbols || !get_symbols || !add_input_file) {
148     (*message)(LDPL_ERROR, "Not all hooks registered for LLVMgold.");
149     return LDPS_ERR;
150   }
151
152   return LDPS_OK;
153 }
154
155 /// claim_file_hook - called by gold to see whether this file is one that
156 /// our plugin can handle. We'll try to open it and register all the symbols
157 /// with add_symbol if possible.
158 ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
159                                  int *claimed) {
160   void *buf = NULL;
161   // If set, this means gold found IR in an ELF section. LLVM doesn't wrap its
162   // IR in ELF, so we know it's not us. But it can also be an .a file containing
163   // LLVM IR.
164   if (file->offset) {
165     if (lseek(file->fd, file->offset, SEEK_SET) == -1) {
166       (*message)(LDPL_ERROR, 
167                  "Failed to seek to archive member of %s at offset %d: %s\n", 
168                  file->name,
169                  file->offset, strerror(errno));
170       return LDPS_ERR;
171     }
172     buf = malloc(file->filesize);
173     if (!buf) {
174       (*message)(LDPL_ERROR, 
175                  "Failed to allocate buffer for archive member of size: %d\n", 
176                  file->filesize);
177       return LDPS_ERR;
178     }
179     if (read(file->fd, buf, file->filesize) != file->filesize) {
180       (*message)(LDPL_ERROR, 
181                  "Failed to read archive member of %s at offset %d: %s\n", 
182                  file->name,
183                  file->offset,           
184                  strerror(errno));
185       free(buf);
186       return LDPS_ERR;
187     }
188     if (!lto_module_is_object_file_in_memory(buf, file->filesize)) {
189       free(buf);
190       return LDPS_OK;
191     }
192   } else if (!lto_module_is_object_file(file->name))
193     return LDPS_OK;
194
195   *claimed = 1;
196   Modules.resize(Modules.size() + 1);
197   claimed_file &cf = Modules.back();
198
199   cf.M = buf ?  lto_module_create_from_memory(buf, file->filesize) :
200                 lto_module_create(file->name);
201   cf.buf = buf;
202   if (!cf.M) {
203     (*message)(LDPL_ERROR, "Failed to create LLVM module: %s",
204                lto_get_error_message());
205     return LDPS_ERR;
206   }
207   cf.handle = file->handle;
208   unsigned sym_count = lto_module_get_num_symbols(cf.M);
209   cf.syms.reserve(sym_count);
210
211   for (unsigned i = 0; i != sym_count; ++i) {
212     lto_symbol_attributes attrs = lto_module_get_symbol_attribute(cf.M, i);
213     if ((attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
214       continue;
215
216     cf.syms.push_back(ld_plugin_symbol());
217     ld_plugin_symbol &sym = cf.syms.back();
218     sym.name = const_cast<char *>(lto_module_get_symbol_name(cf.M, i));
219     sym.version = NULL;
220
221     int scope = attrs & LTO_SYMBOL_SCOPE_MASK;
222     switch (scope) {
223       case LTO_SYMBOL_SCOPE_HIDDEN:
224         sym.visibility = LDPV_HIDDEN;
225         break;
226       case LTO_SYMBOL_SCOPE_PROTECTED:
227         sym.visibility = LDPV_PROTECTED;
228         break;
229       case 0: // extern
230       case LTO_SYMBOL_SCOPE_DEFAULT:
231         sym.visibility = LDPV_DEFAULT;
232         break;
233       default:
234         (*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope);
235         free(buf);
236         return LDPS_ERR;
237     }
238
239     int definition = attrs & LTO_SYMBOL_DEFINITION_MASK;
240     switch (definition) {
241       case LTO_SYMBOL_DEFINITION_REGULAR:
242         sym.def = LDPK_DEF;
243         break;
244       case LTO_SYMBOL_DEFINITION_UNDEFINED:
245         sym.def = LDPK_UNDEF;
246         break;
247       case LTO_SYMBOL_DEFINITION_TENTATIVE:
248         sym.def = LDPK_COMMON;
249         break;
250       case LTO_SYMBOL_DEFINITION_WEAK:
251         sym.def = LDPK_WEAKDEF;
252         break;
253       default:
254         (*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition);
255         free(buf);
256         return LDPS_ERR;
257     }
258
259     // LLVM never emits COMDAT.
260     sym.size = 0;
261     sym.comdat_key = NULL;
262
263     sym.resolution = LDPR_UNKNOWN;
264   }
265
266   cf.syms.reserve(cf.syms.size());
267
268   if (!cf.syms.empty()) {
269     if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
270       (*message)(LDPL_ERROR, "Unable to add symbols!");
271       free(buf);
272       return LDPS_ERR;
273     }
274   }
275
276   return LDPS_OK;
277 }
278
279 /// all_symbols_read_hook - gold informs us that all symbols have been read.
280 /// At this point, we use get_symbols to see if any of our definitions have
281 /// been overridden by a native object file. Then, perform optimization and
282 /// codegen.
283 ld_plugin_status all_symbols_read_hook(void) {
284   lto_code_gen_t cg = lto_codegen_create();
285
286   for (std::list<claimed_file>::iterator I = Modules.begin(),
287        E = Modules.end(); I != E; ++I)
288     lto_codegen_add_module(cg, I->M);
289
290   // If we don't preserve any symbols, libLTO will assume that all symbols are
291   // needed. Keep all symbols unless we're producing a final executable.
292   if (output_type == LTO_CODEGEN_PIC_MODEL_STATIC) {
293     bool anySymbolsPreserved = false;
294     for (std::list<claimed_file>::iterator I = Modules.begin(),
295          E = Modules.end(); I != E; ++I) {
296       (*get_symbols)(I->handle, I->syms.size(), &I->syms[0]);
297       for (unsigned i = 0, e = I->syms.size(); i != e; i++) {
298         (*message)(LDPL_WARNING, "def: %d visibility: %d resolution %d",
299                    I->syms[i].def, I->syms[i].visibility, I->syms[i].resolution);
300         if (I->syms[i].resolution == LDPR_PREVAILING_DEF) {
301           lto_codegen_add_must_preserve_symbol(cg, I->syms[i].name);
302           anySymbolsPreserved = true;
303         }
304       }
305     }
306
307     if (!anySymbolsPreserved) {
308       // This entire file is unnecessary!
309       lto_codegen_dispose(cg);
310       return LDPS_OK;
311     }
312   }
313
314   lto_codegen_set_pic_model(cg, output_type);
315   lto_codegen_set_debug_model(cg, LTO_DEBUG_MODEL_DWARF);
316
317   size_t bufsize = 0;
318   const char *buffer = static_cast<const char *>(lto_codegen_compile(cg,
319                                                                      &bufsize));
320
321   std::string ErrMsg;
322
323   sys::Path uniqueObjPath("/tmp/llvmgold.o");
324   if (uniqueObjPath.createTemporaryFileOnDisk(true, &ErrMsg)) {
325     (*message)(LDPL_ERROR, "%s", ErrMsg.c_str());
326     return LDPS_ERR;
327   }
328   raw_fd_ostream *objFile = new raw_fd_ostream(uniqueObjPath.c_str(), true,
329                                                ErrMsg);
330   if (!ErrMsg.empty()) {
331     delete objFile;
332     (*message)(LDPL_ERROR, "%s", ErrMsg.c_str());
333     return LDPS_ERR;
334   }
335
336   objFile->write(buffer, bufsize);
337   objFile->close();
338
339   lto_codegen_dispose(cg);
340   for (std::list<claimed_file>::iterator I = Modules.begin(),
341        E = Modules.end(); I != E; ++I) {
342     free(I->buf);
343   }
344
345   if ((*add_input_file)(const_cast<char*>(uniqueObjPath.c_str())) != LDPS_OK) {
346     (*message)(LDPL_ERROR, "Unable to add .o file to the link.");
347     (*message)(LDPL_ERROR, "File left behind in: %s", uniqueObjPath.c_str());
348     return LDPS_ERR;
349   }
350
351   Cleanup.push_back(uniqueObjPath);
352
353   return LDPS_OK;
354 }
355
356 ld_plugin_status cleanup_hook(void) {
357   std::string ErrMsg;
358
359   for (int i = 0, e = Cleanup.size(); i != e; ++i)
360     if (Cleanup[i].eraseFromDisk(false, &ErrMsg))
361       (*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(),
362                  ErrMsg.c_str());
363
364   return LDPS_OK;
365 }