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