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