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