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