Fix the build of 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/ADT/DenseSet.h"
17 #include "llvm/ADT/StringSet.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/CodeGen/Analysis.h"
20 #include "llvm/CodeGen/CommandFlags.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/Linker/Linker.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/Object/IRObjectFile.h"
28 #include "llvm/PassManager.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Support/TargetSelect.h"
34 #include "llvm/Target/TargetLibraryInfo.h"
35 #include "llvm/Transforms/IPO.h"
36 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
37 #include "llvm/Transforms/Utils/GlobalStatus.h"
38 #include "llvm/Transforms/Utils/ModuleUtils.h"
39 #include "llvm/Transforms/Utils/ValueMapper.h"
40 #include <list>
41 #include <plugin-api.h>
42 #include <system_error>
43 #include <vector>
44
45 #ifndef LDPO_PIE
46 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
47 // Precise and Debian Wheezy (binutils 2.23 is required)
48 # define LDPO_PIE 3
49 #endif
50
51 using namespace llvm;
52
53 namespace {
54 struct claimed_file {
55   void *handle;
56   std::vector<ld_plugin_symbol> syms;
57 };
58 }
59
60 static ld_plugin_status discard_message(int level, const char *format, ...) {
61   // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
62   // callback in the transfer vector. This should never be called.
63   abort();
64 }
65
66 static ld_plugin_get_input_file get_input_file = nullptr;
67 static ld_plugin_release_input_file release_input_file = nullptr;
68 static ld_plugin_add_symbols add_symbols = nullptr;
69 static ld_plugin_get_symbols get_symbols = nullptr;
70 static ld_plugin_add_input_file add_input_file = nullptr;
71 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
72 static ld_plugin_get_view get_view = nullptr;
73 static ld_plugin_message message = discard_message;
74 static Reloc::Model RelocationModel = Reloc::Default;
75 static std::string output_name = "";
76 static std::list<claimed_file> Modules;
77 static std::vector<std::string> Cleanup;
78 static llvm::TargetOptions TargetOpts;
79
80 namespace options {
81   enum generate_bc { BC_NO, BC_ONLY, BC_SAVE_TEMPS };
82   static bool generate_api_file = false;
83   static generate_bc generate_bc_file = BC_NO;
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<const char *> extra;
94
95   static void process_plugin_option(const char* opt_)
96   {
97     if (opt_ == nullptr)
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 == "save-temps") {
114       generate_bc_file = BC_SAVE_TEMPS;
115     } else {
116       // Save this option to pass to the code generator.
117       // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
118       // add that.
119       if (extra.empty())
120         extra.push_back("LLVMgold");
121
122       extra.push_back(opt_);
123     }
124   }
125 }
126
127 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
128                                         int *claimed);
129 static ld_plugin_status all_symbols_read_hook(void);
130 static ld_plugin_status cleanup_hook(void);
131
132 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
133 ld_plugin_status onload(ld_plugin_tv *tv) {
134   InitializeAllTargetInfos();
135   InitializeAllTargets();
136   InitializeAllTargetMCs();
137   InitializeAllAsmParsers();
138   InitializeAllAsmPrinters();
139
140   // We're given a pointer to the first transfer vector. We read through them
141   // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
142   // contain pointers to functions that we need to call to register our own
143   // hooks. The others are addresses of functions we can use to call into gold
144   // for services.
145
146   bool registeredClaimFile = false;
147   bool RegisteredAllSymbolsRead = false;
148
149   for (; tv->tv_tag != LDPT_NULL; ++tv) {
150     switch (tv->tv_tag) {
151       case LDPT_OUTPUT_NAME:
152         output_name = tv->tv_u.tv_string;
153         break;
154       case LDPT_LINKER_OUTPUT:
155         switch (tv->tv_u.tv_val) {
156           case LDPO_REL:  // .o
157           case LDPO_DYN:  // .so
158           case LDPO_PIE:  // position independent executable
159             RelocationModel = Reloc::PIC_;
160             break;
161           case LDPO_EXEC:  // .exe
162             RelocationModel = Reloc::Static;
163             break;
164           default:
165             message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
166             return LDPS_ERR;
167         }
168         break;
169       case LDPT_OPTION:
170         options::process_plugin_option(tv->tv_u.tv_string);
171         break;
172       case LDPT_REGISTER_CLAIM_FILE_HOOK: {
173         ld_plugin_register_claim_file callback;
174         callback = tv->tv_u.tv_register_claim_file;
175
176         if (callback(claim_file_hook) != LDPS_OK)
177           return LDPS_ERR;
178
179         registeredClaimFile = true;
180       } break;
181       case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
182         ld_plugin_register_all_symbols_read callback;
183         callback = tv->tv_u.tv_register_all_symbols_read;
184
185         if (callback(all_symbols_read_hook) != LDPS_OK)
186           return LDPS_ERR;
187
188         RegisteredAllSymbolsRead = true;
189       } break;
190       case LDPT_REGISTER_CLEANUP_HOOK: {
191         ld_plugin_register_cleanup callback;
192         callback = tv->tv_u.tv_register_cleanup;
193
194         if (callback(cleanup_hook) != LDPS_OK)
195           return LDPS_ERR;
196       } break;
197       case LDPT_GET_INPUT_FILE:
198         get_input_file = tv->tv_u.tv_get_input_file;
199         break;
200       case LDPT_RELEASE_INPUT_FILE:
201         release_input_file = tv->tv_u.tv_release_input_file;
202         break;
203       case LDPT_ADD_SYMBOLS:
204         add_symbols = tv->tv_u.tv_add_symbols;
205         break;
206       case LDPT_GET_SYMBOLS_V2:
207         get_symbols = tv->tv_u.tv_get_symbols;
208         break;
209       case LDPT_ADD_INPUT_FILE:
210         add_input_file = tv->tv_u.tv_add_input_file;
211         break;
212       case LDPT_SET_EXTRA_LIBRARY_PATH:
213         set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
214         break;
215       case LDPT_GET_VIEW:
216         get_view = tv->tv_u.tv_get_view;
217         break;
218       case LDPT_MESSAGE:
219         message = tv->tv_u.tv_message;
220         break;
221       default:
222         break;
223     }
224   }
225
226   if (!registeredClaimFile) {
227     message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
228     return LDPS_ERR;
229   }
230   if (!add_symbols) {
231     message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
232     return LDPS_ERR;
233   }
234
235   if (!RegisteredAllSymbolsRead)
236     return LDPS_OK;
237
238   if (!get_input_file) {
239     message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
240     return LDPS_ERR;
241   }
242   if (!release_input_file) {
243     message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
244     return LDPS_ERR;
245   }
246
247   return LDPS_OK;
248 }
249
250 static const GlobalObject *getBaseObject(const GlobalValue &GV) {
251   if (auto *GA = dyn_cast<GlobalAlias>(&GV))
252     return GA->getBaseObject();
253   return cast<GlobalObject>(&GV);
254 }
255
256 /// Called by gold to see whether this file is one that our plugin can handle.
257 /// We'll try to open it and register all the symbols with add_symbol if
258 /// possible.
259 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
260                                         int *claimed) {
261   LLVMContext Context;
262   MemoryBufferRef BufferRef;
263   std::unique_ptr<MemoryBuffer> Buffer;
264   if (get_view) {
265     const void *view;
266     if (get_view(file->handle, &view) != LDPS_OK) {
267       message(LDPL_ERROR, "Failed to get a view of %s", file->name);
268       return LDPS_ERR;
269     }
270     BufferRef = MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
271   } else {
272     int64_t offset = 0;
273     // Gold has found what might be IR part-way inside of a file, such as
274     // an .a archive.
275     if (file->offset) {
276       offset = file->offset;
277     }
278     ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
279         MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
280                                        offset);
281     if (std::error_code EC = BufferOrErr.getError()) {
282       message(LDPL_ERROR, EC.message().c_str());
283       return LDPS_ERR;
284     }
285     Buffer = std::move(BufferOrErr.get());
286     BufferRef = Buffer->getMemBufferRef();
287   }
288
289   ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
290       object::IRObjectFile::createIRObjectFile(BufferRef, Context);
291   std::error_code EC = ObjOrErr.getError();
292   if (EC == BitcodeError::InvalidBitcodeSignature ||
293       EC == object::object_error::invalid_file_type ||
294       EC == object::object_error::bitcode_section_not_found)
295     return LDPS_OK;
296
297   *claimed = 1;
298
299   if (EC) {
300     message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
301             EC.message().c_str());
302     return LDPS_ERR;
303   }
304   std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
305
306   Modules.resize(Modules.size() + 1);
307   claimed_file &cf = Modules.back();
308
309   cf.handle = file->handle;
310
311   for (auto &Sym : Obj->symbols()) {
312     uint32_t Symflags = Sym.getFlags();
313     if (!(Symflags & object::BasicSymbolRef::SF_Global))
314       continue;
315
316     if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
317       continue;
318
319     cf.syms.push_back(ld_plugin_symbol());
320     ld_plugin_symbol &sym = cf.syms.back();
321     sym.version = nullptr;
322
323     SmallString<64> Name;
324     {
325       raw_svector_ostream OS(Name);
326       Sym.printName(OS);
327     }
328     sym.name = strdup(Name.c_str());
329
330     const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
331
332     sym.visibility = LDPV_DEFAULT;
333     if (GV) {
334       switch (GV->getVisibility()) {
335       case GlobalValue::DefaultVisibility:
336         sym.visibility = LDPV_DEFAULT;
337         break;
338       case GlobalValue::HiddenVisibility:
339         sym.visibility = LDPV_HIDDEN;
340         break;
341       case GlobalValue::ProtectedVisibility:
342         sym.visibility = LDPV_PROTECTED;
343         break;
344       }
345     }
346
347     if (Symflags & object::BasicSymbolRef::SF_Undefined) {
348       sym.def = LDPK_UNDEF;
349       if (GV && GV->hasExternalWeakLinkage())
350         sym.def = LDPK_WEAKUNDEF;
351     } else {
352       sym.def = LDPK_DEF;
353       if (GV) {
354         assert(!GV->hasExternalWeakLinkage() &&
355                !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
356         if (GV->hasCommonLinkage())
357           sym.def = LDPK_COMMON;
358         else if (GV->isWeakForLinker())
359           sym.def = LDPK_WEAKDEF;
360       }
361     }
362
363     sym.size = 0;
364     sym.comdat_key = nullptr;
365     if (GV) {
366       const GlobalObject *Base = getBaseObject(*GV);
367       if (!Base)
368         message(LDPL_FATAL, "Unable to determine comdat of alias!");
369       const Comdat *C = Base->getComdat();
370       if (C)
371         sym.comdat_key = strdup(C->getName().str().c_str());
372       else if (Base->hasWeakLinkage() || Base->hasLinkOnceLinkage())
373         sym.comdat_key = strdup(sym.name);
374     }
375
376     sym.resolution = LDPR_UNKNOWN;
377   }
378
379   if (!cf.syms.empty()) {
380     if (add_symbols(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
381       message(LDPL_ERROR, "Unable to add symbols!");
382       return LDPS_ERR;
383     }
384   }
385
386   return LDPS_OK;
387 }
388
389 static void keepGlobalValue(GlobalValue &GV,
390                             std::vector<GlobalAlias *> &KeptAliases) {
391   assert(!GV.hasLocalLinkage());
392
393   if (auto *GA = dyn_cast<GlobalAlias>(&GV))
394     KeptAliases.push_back(GA);
395
396   switch (GV.getLinkage()) {
397   default:
398     break;
399   case GlobalValue::LinkOnceAnyLinkage:
400     GV.setLinkage(GlobalValue::WeakAnyLinkage);
401     break;
402   case GlobalValue::LinkOnceODRLinkage:
403     GV.setLinkage(GlobalValue::WeakODRLinkage);
404     break;
405   }
406
407   assert(!GV.isDiscardableIfUnused());
408 }
409
410 static void internalize(GlobalValue &GV) {
411   if (GV.isDeclarationForLinker())
412     return; // We get here if there is a matching asm definition.
413   if (!GV.hasLocalLinkage())
414     GV.setLinkage(GlobalValue::InternalLinkage);
415 }
416
417 static void drop(GlobalValue &GV) {
418   if (auto *F = dyn_cast<Function>(&GV)) {
419     F->deleteBody();
420     F->setComdat(nullptr); // Should deleteBody do this?
421     return;
422   }
423
424   if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
425     Var->setInitializer(nullptr);
426     Var->setLinkage(
427         GlobalValue::ExternalLinkage); // Should setInitializer do this?
428     Var->setComdat(nullptr); // and this?
429     return;
430   }
431
432   auto &Alias = cast<GlobalAlias>(GV);
433   Module &M = *Alias.getParent();
434   PointerType &Ty = *cast<PointerType>(Alias.getType());
435   GlobalValue::LinkageTypes L = Alias.getLinkage();
436   auto *Var =
437       new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
438                          /*Initializer*/ nullptr);
439   Var->takeName(&Alias);
440   Alias.replaceAllUsesWith(Var);
441   Alias.eraseFromParent();
442 }
443
444 static const char *getResolutionName(ld_plugin_symbol_resolution R) {
445   switch (R) {
446   case LDPR_UNKNOWN:
447     return "UNKNOWN";
448   case LDPR_UNDEF:
449     return "UNDEF";
450   case LDPR_PREVAILING_DEF:
451     return "PREVAILING_DEF";
452   case LDPR_PREVAILING_DEF_IRONLY:
453     return "PREVAILING_DEF_IRONLY";
454   case LDPR_PREEMPTED_REG:
455     return "PREEMPTED_REG";
456   case LDPR_PREEMPTED_IR:
457     return "PREEMPTED_IR";
458   case LDPR_RESOLVED_IR:
459     return "RESOLVED_IR";
460   case LDPR_RESOLVED_EXEC:
461     return "RESOLVED_EXEC";
462   case LDPR_RESOLVED_DYN:
463     return "RESOLVED_DYN";
464   case LDPR_PREVAILING_DEF_IRONLY_EXP:
465     return "PREVAILING_DEF_IRONLY_EXP";
466   }
467   llvm_unreachable("Unknown resolution");
468 }
469
470 static GlobalObject *makeInternalReplacement(GlobalObject *GO) {
471   Module *M = GO->getParent();
472   GlobalObject *Ret;
473   if (auto *F = dyn_cast<Function>(GO)) {
474     if (F->materialize())
475       message(LDPL_FATAL, "LLVM gold plugin has failed to read a function");
476
477     auto *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
478                                   F->getName(), M);
479
480     ValueToValueMapTy VM;
481     Function::arg_iterator NewI = NewF->arg_begin();
482     for (auto &Arg : F->args()) {
483       NewI->setName(Arg.getName());
484       VM[&Arg] = NewI;
485       ++NewI;
486     }
487
488     NewF->getBasicBlockList().splice(NewF->end(), F->getBasicBlockList());
489     for (auto &BB : *NewF) {
490       for (auto &Inst : BB)
491         RemapInstruction(&Inst, VM, RF_IgnoreMissingEntries);
492     }
493
494     Ret = NewF;
495     F->deleteBody();
496   } else {
497     auto *Var = cast<GlobalVariable>(GO);
498     Ret = new GlobalVariable(
499         *M, Var->getType()->getElementType(), Var->isConstant(),
500         Var->getLinkage(), Var->getInitializer(), Var->getName(),
501         nullptr, Var->getThreadLocalMode(), Var->getType()->getAddressSpace(),
502         Var->isExternallyInitialized());
503     Var->setInitializer(nullptr);
504   }
505   Ret->copyAttributesFrom(GO);
506   Ret->setLinkage(GlobalValue::InternalLinkage);
507   Ret->setComdat(GO->getComdat());
508
509   return Ret;
510 }
511
512 namespace {
513 class LocalValueMaterializer : public ValueMaterializer {
514   DenseSet<GlobalValue *> &Dropped;
515
516 public:
517   LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
518   Value *materializeValueFor(Value *V) override;
519 };
520 }
521
522 Value *LocalValueMaterializer::materializeValueFor(Value *V) {
523   auto *GV = dyn_cast<GlobalValue>(V);
524   if (!GV)
525     return nullptr;
526   if (!Dropped.count(GV))
527     return nullptr;
528   assert(!isa<GlobalAlias>(GV) && "Found alias point to weak alias.");
529   return makeInternalReplacement(cast<GlobalObject>(GV));
530 }
531
532 static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
533                                         LocalValueMaterializer *Materializer) {
534   return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
535 }
536
537 static std::unique_ptr<Module>
538 getModuleForFile(LLVMContext &Context, claimed_file &F, raw_fd_ostream *ApiFile,
539                  StringSet<> &Internalize, StringSet<> &Maybe) {
540   ld_plugin_input_file File;
541   if (get_input_file(F.handle, &File) != LDPS_OK)
542     message(LDPL_FATAL, "Failed to get file information");
543
544   if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
545     message(LDPL_FATAL, "Failed to get symbol information");
546
547   const void *View;
548   if (get_view(F.handle, &View) != LDPS_OK)
549     message(LDPL_FATAL, "Failed to get a view of file");
550
551   llvm::ErrorOr<MemoryBufferRef> MBOrErr =
552       object::IRObjectFile::findBitcodeInMemBuffer(
553           MemoryBufferRef(StringRef((const char *)View, File.filesize), ""));
554   if (std::error_code EC = MBOrErr.getError())
555     message(LDPL_FATAL, "Could not read bitcode from file : %s",
556             EC.message().c_str());
557
558   std::unique_ptr<MemoryBuffer> Buffer =
559       MemoryBuffer::getMemBuffer(MBOrErr->getBuffer(), "", false);
560
561   if (release_input_file(F.handle) != LDPS_OK)
562     message(LDPL_FATAL, "Failed to release file information");
563
564   ErrorOr<Module *> MOrErr = getLazyBitcodeModule(std::move(Buffer), Context);
565
566   if (std::error_code EC = MOrErr.getError())
567     message(LDPL_FATAL, "Could not read bitcode from file : %s",
568             EC.message().c_str());
569
570   std::unique_ptr<Module> M(MOrErr.get());
571
572   SmallPtrSet<GlobalValue *, 8> Used;
573   collectUsedGlobalVariables(*M, Used, /*CompilerUsed*/ false);
574
575   DenseSet<GlobalValue *> Drop;
576   std::vector<GlobalAlias *> KeptAliases;
577   for (ld_plugin_symbol &Sym : F.syms) {
578     ld_plugin_symbol_resolution Resolution =
579         (ld_plugin_symbol_resolution)Sym.resolution;
580
581     if (options::generate_api_file)
582       *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
583
584     GlobalValue *GV = M->getNamedValue(Sym.name);
585     if (!GV)
586       continue; // Asm symbol.
587
588     if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
589       // Common linkage is special. There is no single symbol that wins the
590       // resolution. Instead we have to collect the maximum alignment and size.
591       // The IR linker does that for us if we just pass it every common GV.
592       // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
593       // internalize once the IR linker has done its job.
594       continue;
595     }
596
597     switch (Resolution) {
598     case LDPR_UNKNOWN:
599       llvm_unreachable("Unexpected resolution");
600
601     case LDPR_RESOLVED_IR:
602     case LDPR_RESOLVED_EXEC:
603     case LDPR_RESOLVED_DYN:
604     case LDPR_UNDEF:
605       assert(GV->isDeclarationForLinker());
606       break;
607
608     case LDPR_PREVAILING_DEF_IRONLY: {
609       keepGlobalValue(*GV, KeptAliases);
610       if (!Used.count(GV)) {
611         // Since we use the regular lib/Linker, we cannot just internalize GV
612         // now or it will not be copied to the merged module. Instead we force
613         // it to be copied and then internalize it.
614         Internalize.insert(Sym.name);
615       }
616       break;
617     }
618
619     case LDPR_PREVAILING_DEF:
620       keepGlobalValue(*GV, KeptAliases);
621       break;
622
623     case LDPR_PREEMPTED_IR:
624       // Gold might have selected a linkonce_odr and preempted a weak_odr.
625       // In that case we have to make sure we don't end up internalizing it.
626       if (!GV->isDiscardableIfUnused())
627         Maybe.erase(Sym.name);
628
629       // fall-through
630     case LDPR_PREEMPTED_REG:
631       Drop.insert(GV);
632       break;
633
634     case LDPR_PREVAILING_DEF_IRONLY_EXP: {
635       // We can only check for address uses after we merge the modules. The
636       // reason is that this GV might have a copy in another module
637       // and in that module the address might be significant, but that
638       // copy will be LDPR_PREEMPTED_IR.
639       if (GV->hasLinkOnceODRLinkage())
640         Maybe.insert(Sym.name);
641       keepGlobalValue(*GV, KeptAliases);
642       break;
643     }
644     }
645
646     free(Sym.name);
647     free(Sym.comdat_key);
648     Sym.name = nullptr;
649     Sym.comdat_key = nullptr;
650   }
651
652   ValueToValueMapTy VM;
653   LocalValueMaterializer Materializer(Drop);
654   for (GlobalAlias *GA : KeptAliases) {
655     // Gold told us to keep GA. It is possible that a GV usied in the aliasee
656     // expression is being dropped. If that is the case, that GV must be copied.
657     Constant *Aliasee = GA->getAliasee();
658     Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
659     if (Aliasee != Replacement)
660       GA->setAliasee(Replacement);
661   }
662
663   for (auto *GV : Drop)
664     drop(*GV);
665
666   return M;
667 }
668
669 static void runLTOPasses(Module &M, TargetMachine &TM) {
670   PassManager passes;
671   PassManagerBuilder PMB;
672   PMB.LibraryInfo = new TargetLibraryInfo(Triple(TM.getTargetTriple()));
673   PMB.Inliner = createFunctionInliningPass();
674   PMB.VerifyInput = true;
675   PMB.VerifyOutput = true;
676   PMB.LoopVectorize = true;
677   PMB.SLPVectorize = true;
678   PMB.populateLTOPassManager(passes, &TM);
679   passes.run(M);
680 }
681
682 static void saveBCFile(StringRef Path, Module &M) {
683   std::error_code EC;
684   raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
685   if (EC)
686     message(LDPL_FATAL, "Failed to write the output file.");
687   WriteBitcodeToFile(&M, OS);
688 }
689
690 static void codegen(Module &M) {
691   const std::string &TripleStr = M.getTargetTriple();
692   Triple TheTriple(TripleStr);
693
694   std::string ErrMsg;
695   const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
696   if (!TheTarget)
697     message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
698
699   if (unsigned NumOpts = options::extra.size())
700     cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
701
702   SubtargetFeatures Features;
703   Features.getDefaultSubtargetFeatures(TheTriple);
704   for (const std::string &A : MAttrs)
705     Features.AddFeature(A);
706
707   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
708   std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
709       TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
710       CodeModel::Default, CodeGenOpt::Aggressive));
711
712   runLTOPasses(M, *TM);
713
714   if (options::generate_bc_file == options::BC_SAVE_TEMPS)
715     saveBCFile(output_name + ".opt.bc", M);
716
717   PassManager CodeGenPasses;
718   CodeGenPasses.add(new DataLayoutPass());
719
720   SmallString<128> Filename;
721   int FD;
722   if (options::obj_path.empty()) {
723     std::error_code EC =
724         sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
725     if (EC)
726       message(LDPL_FATAL, "Could not create temorary file: %s",
727               EC.message().c_str());
728   } else {
729     Filename = options::obj_path;
730     std::error_code EC =
731         sys::fs::openFileForWrite(Filename.c_str(), FD, sys::fs::F_None);
732     if (EC)
733       message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
734   }
735
736   {
737     raw_fd_ostream OS(FD, true);
738     formatted_raw_ostream FOS(OS);
739
740     if (TM->addPassesToEmitFile(CodeGenPasses, FOS,
741                                 TargetMachine::CGFT_ObjectFile))
742       message(LDPL_FATAL, "Failed to setup codegen");
743     CodeGenPasses.run(M);
744   }
745
746   if (add_input_file(Filename.c_str()) != LDPS_OK)
747     message(LDPL_FATAL,
748             "Unable to add .o file to the link. File left behind in: %s",
749             Filename.c_str());
750
751   if (options::obj_path.empty())
752     Cleanup.push_back(Filename.c_str());
753 }
754
755 /// gold informs us that all symbols have been read. At this point, we use
756 /// get_symbols to see if any of our definitions have been overridden by a
757 /// native object file. Then, perform optimization and codegen.
758 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
759   if (Modules.empty())
760     return LDPS_OK;
761
762   LLVMContext Context;
763   std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
764   Linker L(Combined.get());
765
766   std::string DefaultTriple = sys::getDefaultTargetTriple();
767
768   StringSet<> Internalize;
769   StringSet<> Maybe;
770   for (claimed_file &F : Modules) {
771     std::unique_ptr<Module> M =
772         getModuleForFile(Context, F, ApiFile, Internalize, Maybe);
773     if (!options::triple.empty())
774       M->setTargetTriple(options::triple.c_str());
775     else if (M->getTargetTriple().empty()) {
776       M->setTargetTriple(DefaultTriple);
777     }
778
779     if (L.linkInModule(M.get()))
780       message(LDPL_FATAL, "Failed to link module");
781   }
782
783   for (const auto &Name : Internalize) {
784     GlobalValue *GV = Combined->getNamedValue(Name.first());
785     if (GV)
786       internalize(*GV);
787   }
788
789   for (const auto &Name : Maybe) {
790     GlobalValue *GV = Combined->getNamedValue(Name.first());
791     if (!GV)
792       continue;
793     GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
794     if (canBeOmittedFromSymbolTable(GV))
795       internalize(*GV);
796   }
797
798   if (options::generate_bc_file != options::BC_NO) {
799     std::string path;
800     if (options::generate_bc_file == options::BC_ONLY)
801       path = output_name;
802     else
803       path = output_name + ".bc";
804     saveBCFile(path, *L.getModule());
805     if (options::generate_bc_file == options::BC_ONLY)
806       return LDPS_OK;
807   }
808
809   codegen(*L.getModule());
810
811   if (!options::extra_library_path.empty() &&
812       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
813     message(LDPL_FATAL, "Unable to set the extra library path.");
814
815   return LDPS_OK;
816 }
817
818 static ld_plugin_status all_symbols_read_hook(void) {
819   ld_plugin_status Ret;
820   if (!options::generate_api_file) {
821     Ret = allSymbolsReadHook(nullptr);
822   } else {
823     std::error_code EC;
824     raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
825     if (EC)
826       message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
827               EC.message().c_str());
828     Ret = allSymbolsReadHook(&ApiFile);
829   }
830
831   if (options::generate_bc_file == options::BC_ONLY)
832     exit(0);
833
834   return Ret;
835 }
836
837 static ld_plugin_status cleanup_hook(void) {
838   for (std::string &Name : Cleanup) {
839     std::error_code EC = sys::fs::remove(Name);
840     if (EC)
841       message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
842               EC.message().c_str());
843   }
844
845   return LDPS_OK;
846 }