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