Replace also-emit-llvm with save-temps.
[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->isMaterializable()) {
475       if (F->materialize())
476         message(LDPL_FATAL, "LLVM gold plugin has failed to read a function");
477
478     }
479
480     auto *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
481                                   F->getName(), M);
482
483     ValueToValueMapTy VM;
484     Function::arg_iterator NewI = NewF->arg_begin();
485     for (auto &Arg : F->args()) {
486       NewI->setName(Arg.getName());
487       VM[&Arg] = NewI;
488       ++NewI;
489     }
490
491     NewF->getBasicBlockList().splice(NewF->end(), F->getBasicBlockList());
492     for (auto &BB : *NewF) {
493       for (auto &Inst : BB)
494         RemapInstruction(&Inst, VM, RF_IgnoreMissingEntries);
495     }
496
497     Ret = NewF;
498     F->deleteBody();
499   } else {
500     auto *Var = cast<GlobalVariable>(GO);
501     Ret = new GlobalVariable(
502         *M, Var->getType()->getElementType(), Var->isConstant(),
503         Var->getLinkage(), Var->getInitializer(), Var->getName(),
504         nullptr, Var->getThreadLocalMode(), Var->getType()->getAddressSpace(),
505         Var->isExternallyInitialized());
506     Var->setInitializer(nullptr);
507   }
508   Ret->copyAttributesFrom(GO);
509   Ret->setLinkage(GlobalValue::InternalLinkage);
510   Ret->setComdat(GO->getComdat());
511
512   return Ret;
513 }
514
515 namespace {
516 class LocalValueMaterializer : public ValueMaterializer {
517   DenseSet<GlobalValue *> &Dropped;
518
519 public:
520   LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
521   Value *materializeValueFor(Value *V) override;
522 };
523 }
524
525 Value *LocalValueMaterializer::materializeValueFor(Value *V) {
526   auto *GV = dyn_cast<GlobalValue>(V);
527   if (!GV)
528     return nullptr;
529   if (!Dropped.count(GV))
530     return nullptr;
531   assert(!isa<GlobalAlias>(GV) && "Found alias point to weak alias.");
532   return makeInternalReplacement(cast<GlobalObject>(GV));
533 }
534
535 static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
536                                         LocalValueMaterializer *Materializer) {
537   return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
538 }
539
540 static std::unique_ptr<Module>
541 getModuleForFile(LLVMContext &Context, claimed_file &F, raw_fd_ostream *ApiFile,
542                  StringSet<> &Internalize, StringSet<> &Maybe) {
543   ld_plugin_input_file File;
544   if (get_input_file(F.handle, &File) != LDPS_OK)
545     message(LDPL_FATAL, "Failed to get file information");
546
547   if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
548     message(LDPL_FATAL, "Failed to get symbol information");
549
550   const void *View;
551   if (get_view(F.handle, &View) != LDPS_OK)
552     message(LDPL_FATAL, "Failed to get a view of file");
553
554   llvm::ErrorOr<MemoryBufferRef> MBOrErr =
555       object::IRObjectFile::findBitcodeInMemBuffer(
556           MemoryBufferRef(StringRef((const char *)View, File.filesize), ""));
557   if (std::error_code EC = MBOrErr.getError())
558     message(LDPL_FATAL, "Could not read bitcode from file : %s",
559             EC.message().c_str());
560
561   std::unique_ptr<MemoryBuffer> Buffer =
562       MemoryBuffer::getMemBuffer(MBOrErr->getBuffer(), "", false);
563
564   if (release_input_file(F.handle) != LDPS_OK)
565     message(LDPL_FATAL, "Failed to release file information");
566
567   ErrorOr<Module *> MOrErr = getLazyBitcodeModule(std::move(Buffer), Context);
568
569   if (std::error_code EC = MOrErr.getError())
570     message(LDPL_FATAL, "Could not read bitcode from file : %s",
571             EC.message().c_str());
572
573   std::unique_ptr<Module> M(MOrErr.get());
574
575   SmallPtrSet<GlobalValue *, 8> Used;
576   collectUsedGlobalVariables(*M, Used, /*CompilerUsed*/ false);
577
578   DenseSet<GlobalValue *> Drop;
579   std::vector<GlobalAlias *> KeptAliases;
580   for (ld_plugin_symbol &Sym : F.syms) {
581     ld_plugin_symbol_resolution Resolution =
582         (ld_plugin_symbol_resolution)Sym.resolution;
583
584     if (options::generate_api_file)
585       *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
586
587     GlobalValue *GV = M->getNamedValue(Sym.name);
588     if (!GV)
589       continue; // Asm symbol.
590
591     if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
592       // Common linkage is special. There is no single symbol that wins the
593       // resolution. Instead we have to collect the maximum alignment and size.
594       // The IR linker does that for us if we just pass it every common GV.
595       // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
596       // internalize once the IR linker has done its job.
597       continue;
598     }
599
600     switch (Resolution) {
601     case LDPR_UNKNOWN:
602       llvm_unreachable("Unexpected resolution");
603
604     case LDPR_RESOLVED_IR:
605     case LDPR_RESOLVED_EXEC:
606     case LDPR_RESOLVED_DYN:
607     case LDPR_UNDEF:
608       assert(GV->isDeclarationForLinker());
609       break;
610
611     case LDPR_PREVAILING_DEF_IRONLY: {
612       keepGlobalValue(*GV, KeptAliases);
613       if (!Used.count(GV)) {
614         // Since we use the regular lib/Linker, we cannot just internalize GV
615         // now or it will not be copied to the merged module. Instead we force
616         // it to be copied and then internalize it.
617         Internalize.insert(Sym.name);
618       }
619       break;
620     }
621
622     case LDPR_PREVAILING_DEF:
623       keepGlobalValue(*GV, KeptAliases);
624       break;
625
626     case LDPR_PREEMPTED_IR:
627       // Gold might have selected a linkonce_odr and preempted a weak_odr.
628       // In that case we have to make sure we don't end up internalizing it.
629       if (!GV->isDiscardableIfUnused())
630         Maybe.erase(Sym.name);
631
632       // fall-through
633     case LDPR_PREEMPTED_REG:
634       Drop.insert(GV);
635       break;
636
637     case LDPR_PREVAILING_DEF_IRONLY_EXP: {
638       // We can only check for address uses after we merge the modules. The
639       // reason is that this GV might have a copy in another module
640       // and in that module the address might be significant, but that
641       // copy will be LDPR_PREEMPTED_IR.
642       if (GV->hasLinkOnceODRLinkage())
643         Maybe.insert(Sym.name);
644       keepGlobalValue(*GV, KeptAliases);
645       break;
646     }
647     }
648
649     free(Sym.name);
650     free(Sym.comdat_key);
651     Sym.name = nullptr;
652     Sym.comdat_key = nullptr;
653   }
654
655   ValueToValueMapTy VM;
656   LocalValueMaterializer Materializer(Drop);
657   for (GlobalAlias *GA : KeptAliases) {
658     // Gold told us to keep GA. It is possible that a GV usied in the aliasee
659     // expression is being dropped. If that is the case, that GV must be copied.
660     Constant *Aliasee = GA->getAliasee();
661     Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
662     if (Aliasee != Replacement)
663       GA->setAliasee(Replacement);
664   }
665
666   for (auto *GV : Drop)
667     drop(*GV);
668
669   return M;
670 }
671
672 static void runLTOPasses(Module &M, TargetMachine &TM) {
673   PassManager passes;
674   PassManagerBuilder PMB;
675   PMB.LibraryInfo = new TargetLibraryInfo(Triple(TM.getTargetTriple()));
676   PMB.Inliner = createFunctionInliningPass();
677   PMB.VerifyInput = true;
678   PMB.VerifyOutput = true;
679   PMB.populateLTOPassManager(passes, &TM);
680   passes.run(M);
681 }
682
683 static void saveBCFile(StringRef Path, Module &M) {
684   std::error_code EC;
685   raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
686   if (EC)
687     message(LDPL_FATAL, "Failed to write the output file.");
688   WriteBitcodeToFile(&M, OS);
689 }
690
691 static void codegen(Module &M) {
692   const std::string &TripleStr = M.getTargetTriple();
693   Triple TheTriple(TripleStr);
694
695   std::string ErrMsg;
696   const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
697   if (!TheTarget)
698     message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
699
700   if (unsigned NumOpts = options::extra.size())
701     cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
702
703   SubtargetFeatures Features;
704   Features.getDefaultSubtargetFeatures(TheTriple);
705   for (const std::string &A : MAttrs)
706     Features.AddFeature(A);
707
708   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
709   std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
710       TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
711       CodeModel::Default, CodeGenOpt::Aggressive));
712
713   runLTOPasses(M, *TM);
714
715   if (options::generate_bc_file == options::BC_SAVE_TEMPS)
716     saveBCFile(output_name + ".opt.bc", M);
717
718   PassManager CodeGenPasses;
719   CodeGenPasses.add(new DataLayoutPass());
720
721   SmallString<128> Filename;
722   int FD;
723   if (options::obj_path.empty()) {
724     std::error_code EC =
725         sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
726     if (EC)
727       message(LDPL_FATAL, "Could not create temorary file: %s",
728               EC.message().c_str());
729   } else {
730     Filename = options::obj_path;
731     std::error_code EC =
732         sys::fs::openFileForWrite(Filename.c_str(), FD, sys::fs::F_None);
733     if (EC)
734       message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
735   }
736
737   {
738     raw_fd_ostream OS(FD, true);
739     formatted_raw_ostream FOS(OS);
740
741     if (TM->addPassesToEmitFile(CodeGenPasses, FOS,
742                                 TargetMachine::CGFT_ObjectFile))
743       message(LDPL_FATAL, "Failed to setup codegen");
744     CodeGenPasses.run(M);
745   }
746
747   if (add_input_file(Filename.c_str()) != LDPS_OK)
748     message(LDPL_FATAL,
749             "Unable to add .o file to the link. File left behind in: %s",
750             Filename.c_str());
751
752   if (options::obj_path.empty())
753     Cleanup.push_back(Filename.c_str());
754 }
755
756 /// gold informs us that all symbols have been read. At this point, we use
757 /// get_symbols to see if any of our definitions have been overridden by a
758 /// native object file. Then, perform optimization and codegen.
759 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
760   if (Modules.empty())
761     return LDPS_OK;
762
763   LLVMContext Context;
764   std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
765   Linker L(Combined.get());
766
767   std::string DefaultTriple = sys::getDefaultTargetTriple();
768
769   StringSet<> Internalize;
770   StringSet<> Maybe;
771   for (claimed_file &F : Modules) {
772     std::unique_ptr<Module> M =
773         getModuleForFile(Context, F, ApiFile, Internalize, Maybe);
774     if (!options::triple.empty())
775       M->setTargetTriple(options::triple.c_str());
776     else if (M->getTargetTriple().empty()) {
777       M->setTargetTriple(DefaultTriple);
778     }
779
780     if (L.linkInModule(M.get()))
781       message(LDPL_FATAL, "Failed to link module");
782   }
783
784   for (const auto &Name : Internalize) {
785     GlobalValue *GV = Combined->getNamedValue(Name.first());
786     if (GV)
787       internalize(*GV);
788   }
789
790   for (const auto &Name : Maybe) {
791     GlobalValue *GV = Combined->getNamedValue(Name.first());
792     if (!GV)
793       continue;
794     GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
795     if (canBeOmittedFromSymbolTable(GV))
796       internalize(*GV);
797   }
798
799   if (options::generate_bc_file != options::BC_NO) {
800     std::string path;
801     if (options::generate_bc_file == options::BC_ONLY)
802       path = output_name;
803     else
804       path = output_name + ".bc";
805     saveBCFile(path, *L.getModule());
806     if (options::generate_bc_file == options::BC_ONLY)
807       return LDPS_OK;
808   }
809
810   codegen(*L.getModule());
811
812   if (!options::extra_library_path.empty() &&
813       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
814     message(LDPL_FATAL, "Unable to set the extra library path.");
815
816   return LDPS_OK;
817 }
818
819 static ld_plugin_status all_symbols_read_hook(void) {
820   ld_plugin_status Ret;
821   if (!options::generate_api_file) {
822     Ret = allSymbolsReadHook(nullptr);
823   } else {
824     std::error_code EC;
825     raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
826     if (EC)
827       message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
828               EC.message().c_str());
829     Ret = allSymbolsReadHook(&ApiFile);
830   }
831
832   if (options::generate_bc_file == options::BC_ONLY)
833     exit(0);
834
835   return Ret;
836 }
837
838 static ld_plugin_status cleanup_hook(void) {
839   for (std::string &Name : Cleanup) {
840     std::error_code EC = sys::fs::remove(Name);
841     if (EC)
842       message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
843               EC.message().c_str());
844   }
845
846   return LDPS_OK;
847 }