gold-plugin.cpp: Fixup r227599 corresponding to r227685 and r227731 -- Don't lose...
[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, raw_fd_ostream *ApiFile,
564                  StringSet<> &Internalize, StringSet<> &Maybe) {
565   ld_plugin_input_file File;
566   if (get_input_file(F.handle, &File) != LDPS_OK)
567     message(LDPL_FATAL, "Failed to get file information");
568
569   if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
570     message(LDPL_FATAL, "Failed to get symbol information");
571
572   const void *View;
573   if (get_view(F.handle, &View) != LDPS_OK)
574     message(LDPL_FATAL, "Failed to get a view of file");
575
576   MemoryBufferRef BufferRef(StringRef((const char *)View, File.filesize), "");
577   ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
578       object::IRObjectFile::create(BufferRef, Context);
579
580   if (std::error_code EC = ObjOrErr.getError())
581     message(LDPL_FATAL, "Could not read bitcode from file : %s",
582             EC.message().c_str());
583
584   if (release_input_file(F.handle) != LDPS_OK)
585     message(LDPL_FATAL, "Failed to release file information");
586
587   object::IRObjectFile &Obj = **ObjOrErr;
588
589   Module &M = Obj.getModule();
590
591   SmallPtrSet<GlobalValue *, 8> Used;
592   collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
593
594   DenseSet<GlobalValue *> Drop;
595   std::vector<GlobalAlias *> KeptAliases;
596
597   unsigned SymNum = 0;
598   for (auto &ObjSym : Obj.symbols()) {
599     if (shouldSkip(ObjSym.getFlags()))
600       continue;
601     ld_plugin_symbol &Sym = F.syms[SymNum];
602     ++SymNum;
603
604     ld_plugin_symbol_resolution Resolution =
605         (ld_plugin_symbol_resolution)Sym.resolution;
606
607     if (options::generate_api_file)
608       *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
609
610     GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
611     if (!GV) {
612       freeSymName(Sym);
613       continue; // Asm symbol.
614     }
615
616     if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
617       // Common linkage is special. There is no single symbol that wins the
618       // resolution. Instead we have to collect the maximum alignment and size.
619       // The IR linker does that for us if we just pass it every common GV.
620       // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
621       // internalize once the IR linker has done its job.
622       freeSymName(Sym);
623       continue;
624     }
625
626     switch (Resolution) {
627     case LDPR_UNKNOWN:
628       llvm_unreachable("Unexpected resolution");
629
630     case LDPR_RESOLVED_IR:
631     case LDPR_RESOLVED_EXEC:
632     case LDPR_RESOLVED_DYN:
633       assert(GV->isDeclarationForLinker());
634       break;
635
636     case LDPR_UNDEF:
637       if (!GV->isDeclarationForLinker()) {
638         assert(GV->hasComdat());
639         Drop.insert(GV);
640       }
641       break;
642
643     case LDPR_PREVAILING_DEF_IRONLY: {
644       keepGlobalValue(*GV, KeptAliases);
645       if (!Used.count(GV)) {
646         // Since we use the regular lib/Linker, we cannot just internalize GV
647         // now or it will not be copied to the merged module. Instead we force
648         // it to be copied and then internalize it.
649         Internalize.insert(GV->getName());
650       }
651       break;
652     }
653
654     case LDPR_PREVAILING_DEF:
655       keepGlobalValue(*GV, KeptAliases);
656       break;
657
658     case LDPR_PREEMPTED_IR:
659       // Gold might have selected a linkonce_odr and preempted a weak_odr.
660       // In that case we have to make sure we don't end up internalizing it.
661       if (!GV->isDiscardableIfUnused())
662         Maybe.erase(GV->getName());
663
664       // fall-through
665     case LDPR_PREEMPTED_REG:
666       Drop.insert(GV);
667       break;
668
669     case LDPR_PREVAILING_DEF_IRONLY_EXP: {
670       // We can only check for address uses after we merge the modules. The
671       // reason is that this GV might have a copy in another module
672       // and in that module the address might be significant, but that
673       // copy will be LDPR_PREEMPTED_IR.
674       if (GV->hasLinkOnceODRLinkage())
675         Maybe.insert(GV->getName());
676       keepGlobalValue(*GV, KeptAliases);
677       break;
678     }
679     }
680
681     freeSymName(Sym);
682   }
683
684   ValueToValueMapTy VM;
685   LocalValueMaterializer Materializer(Drop);
686   for (GlobalAlias *GA : KeptAliases) {
687     // Gold told us to keep GA. It is possible that a GV usied in the aliasee
688     // expression is being dropped. If that is the case, that GV must be copied.
689     Constant *Aliasee = GA->getAliasee();
690     Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
691     GA->setAliasee(Replacement);
692   }
693
694   for (auto *GV : Drop)
695     drop(*GV);
696
697   return Obj.takeModule();
698 }
699
700 static void runLTOPasses(Module &M, TargetMachine &TM) {
701   PassManager passes;
702   passes.add(new DataLayoutPass());
703   passes.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
704
705   PassManagerBuilder PMB;
706   PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
707   PMB.Inliner = createFunctionInliningPass();
708   PMB.VerifyInput = true;
709   PMB.VerifyOutput = true;
710   PMB.LoopVectorize = true;
711   PMB.SLPVectorize = true;
712   PMB.populateLTOPassManager(passes);
713   passes.run(M);
714 }
715
716 static void saveBCFile(StringRef Path, Module &M) {
717   std::error_code EC;
718   raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
719   if (EC)
720     message(LDPL_FATAL, "Failed to write the output file.");
721   WriteBitcodeToFile(&M, OS);
722 }
723
724 static void codegen(Module &M) {
725   const std::string &TripleStr = M.getTargetTriple();
726   Triple TheTriple(TripleStr);
727
728   std::string ErrMsg;
729   const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
730   if (!TheTarget)
731     message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
732
733   if (unsigned NumOpts = options::extra.size())
734     cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
735
736   SubtargetFeatures Features;
737   Features.getDefaultSubtargetFeatures(TheTriple);
738   for (const std::string &A : MAttrs)
739     Features.AddFeature(A);
740
741   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
742   std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
743       TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
744       CodeModel::Default, CodeGenOpt::Aggressive));
745
746   runLTOPasses(M, *TM);
747
748   if (options::TheOutputType == options::OT_SAVE_TEMPS)
749     saveBCFile(output_name + ".opt.bc", M);
750
751   PassManager CodeGenPasses;
752   CodeGenPasses.add(new DataLayoutPass());
753
754   SmallString<128> Filename;
755   int FD;
756   if (options::obj_path.empty()) {
757     std::error_code EC =
758         sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
759     if (EC)
760       message(LDPL_FATAL, "Could not create temporary file: %s",
761               EC.message().c_str());
762   } else {
763     Filename = options::obj_path;
764     std::error_code EC =
765         sys::fs::openFileForWrite(Filename.c_str(), FD, sys::fs::F_None);
766     if (EC)
767       message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
768   }
769
770   {
771     raw_fd_ostream OS(FD, true);
772     formatted_raw_ostream FOS(OS);
773
774     if (TM->addPassesToEmitFile(CodeGenPasses, FOS,
775                                 TargetMachine::CGFT_ObjectFile))
776       message(LDPL_FATAL, "Failed to setup codegen");
777     CodeGenPasses.run(M);
778   }
779
780   if (add_input_file(Filename.c_str()) != LDPS_OK)
781     message(LDPL_FATAL,
782             "Unable to add .o file to the link. File left behind in: %s",
783             Filename.c_str());
784
785   if (options::obj_path.empty())
786     Cleanup.push_back(Filename.c_str());
787 }
788
789 /// gold informs us that all symbols have been read. At this point, we use
790 /// get_symbols to see if any of our definitions have been overridden by a
791 /// native object file. Then, perform optimization and codegen.
792 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
793   if (Modules.empty())
794     return LDPS_OK;
795
796   LLVMContext Context;
797   std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
798   Linker L(Combined.get());
799
800   std::string DefaultTriple = sys::getDefaultTargetTriple();
801
802   StringSet<> Internalize;
803   StringSet<> Maybe;
804   for (claimed_file &F : Modules) {
805     std::unique_ptr<Module> M =
806         getModuleForFile(Context, F, ApiFile, Internalize, Maybe);
807     if (!options::triple.empty())
808       M->setTargetTriple(options::triple.c_str());
809     else if (M->getTargetTriple().empty()) {
810       M->setTargetTriple(DefaultTriple);
811     }
812
813     if (L.linkInModule(M.get()))
814       message(LDPL_FATAL, "Failed to link module");
815   }
816
817   for (const auto &Name : Internalize) {
818     GlobalValue *GV = Combined->getNamedValue(Name.first());
819     if (GV)
820       internalize(*GV);
821   }
822
823   for (const auto &Name : Maybe) {
824     GlobalValue *GV = Combined->getNamedValue(Name.first());
825     if (!GV)
826       continue;
827     GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
828     if (canBeOmittedFromSymbolTable(GV))
829       internalize(*GV);
830   }
831
832   if (options::TheOutputType == options::OT_DISABLE)
833     return LDPS_OK;
834
835   if (options::TheOutputType != options::OT_NORMAL) {
836     std::string path;
837     if (options::TheOutputType == options::OT_BC_ONLY)
838       path = output_name;
839     else
840       path = output_name + ".bc";
841     saveBCFile(path, *L.getModule());
842     if (options::TheOutputType == options::OT_BC_ONLY)
843       return LDPS_OK;
844   }
845
846   codegen(*L.getModule());
847
848   if (!options::extra_library_path.empty() &&
849       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
850     message(LDPL_FATAL, "Unable to set the extra library path.");
851
852   return LDPS_OK;
853 }
854
855 static ld_plugin_status all_symbols_read_hook(void) {
856   ld_plugin_status Ret;
857   if (!options::generate_api_file) {
858     Ret = allSymbolsReadHook(nullptr);
859   } else {
860     std::error_code EC;
861     raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
862     if (EC)
863       message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
864               EC.message().c_str());
865     Ret = allSymbolsReadHook(&ApiFile);
866   }
867
868   llvm_shutdown();
869
870   if (options::TheOutputType == options::OT_BC_ONLY ||
871       options::TheOutputType == options::OT_DISABLE)
872     exit(0);
873
874   return Ret;
875 }
876
877 static ld_plugin_status cleanup_hook(void) {
878   for (std::string &Name : Cleanup) {
879     std::error_code EC = sys::fs::remove(Name);
880     if (EC)
881       message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
882               EC.message().c_str());
883   }
884
885   return LDPS_OK;
886 }