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/IRMover.h"
33 #include "llvm/MC/SubtargetFeature.h"
34 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
35 #include "llvm/Object/IRObjectFile.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/Support/ThreadPool.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Support/thread.h"
44 #include "llvm/Transforms/IPO.h"
45 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
46 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
47 #include "llvm/Transforms/Utils/GlobalStatus.h"
48 #include "llvm/Transforms/Utils/ModuleUtils.h"
49 #include "llvm/Transforms/Utils/ValueMapper.h"
50 #include <list>
51 #include <plugin-api.h>
52 #include <system_error>
53 #include <vector>
54 
55 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
56 // Precise and Debian Wheezy (binutils 2.23 is required)
57 #define LDPO_PIE 3
58 
59 #define LDPT_GET_SYMBOLS_V3 28
60 
61 using namespace llvm;
62 
63 static ld_plugin_status discard_message(int level, const char *format, ...) {
64   // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
65   // callback in the transfer vector. This should never be called.
66   abort();
67 }
68 
69 static ld_plugin_release_input_file release_input_file = nullptr;
70 static ld_plugin_get_input_file get_input_file = nullptr;
71 static ld_plugin_message message = discard_message;
72 
73 namespace {
74 struct claimed_file {
75   void *handle;
76   std::vector<ld_plugin_symbol> syms;
77 };
78 
79 /// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
80 struct PluginInputFile {
81   void *Handle;
82   std::unique_ptr<ld_plugin_input_file> File;
83 
84   PluginInputFile(void *Handle) : Handle(Handle) {
85     File = llvm::make_unique<ld_plugin_input_file>();
86     if (get_input_file(Handle, File.get()) != LDPS_OK)
87       message(LDPL_FATAL, "Failed to get file information");
88   }
89   ~PluginInputFile() {
90     // File would have been reset to nullptr if we moved this object
91     // to a new owner.
92     if (File)
93       if (release_input_file(Handle) != LDPS_OK)
94         message(LDPL_FATAL, "Failed to release file information");
95   }
96 
97   ld_plugin_input_file &file() { return *File; }
98 
99   PluginInputFile(PluginInputFile &&RHS) = default;
100   PluginInputFile &operator=(PluginInputFile &&RHS) = default;
101 };
102 
103 struct ResolutionInfo {
104   uint64_t CommonSize = 0;
105   unsigned CommonAlign = 0;
106   bool IsLinkonceOdr = true;
107   bool UnnamedAddr = true;
108   GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
109   bool CommonInternal = false;
110   bool UseCommon = false;
111 };
112 
113 /// Class to own information used by a task or during its cleanup for a
114 /// ThinLTO backend instantiation.
115 class ThinLTOTaskInfo {
116   /// The input file holding the module bitcode read by the ThinLTO task.
117   PluginInputFile InputFile;
118 
119   /// The output stream the task will codegen into.
120   std::unique_ptr<raw_fd_ostream> OS;
121 
122   /// The file name corresponding to the output stream, used during cleanup.
123   std::string Filename;
124 
125   /// Flag indicating whether the output file is a temp file that must be
126   /// added to the cleanup list during cleanup.
127   bool TempOutFile;
128 
129 public:
130   ThinLTOTaskInfo(PluginInputFile InputFile, std::unique_ptr<raw_fd_ostream> OS,
131                   std::string Filename, bool TempOutFile)
132       : InputFile(std::move(InputFile)), OS(std::move(OS)), Filename(Filename),
133         TempOutFile(TempOutFile) {}
134 
135   /// Performs task related cleanup activities that must be done
136   /// single-threaded (i.e. call backs to gold).
137   void cleanup();
138 };
139 }
140 
141 static ld_plugin_add_symbols add_symbols = nullptr;
142 static ld_plugin_get_symbols get_symbols = nullptr;
143 static ld_plugin_add_input_file add_input_file = nullptr;
144 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
145 static ld_plugin_get_view get_view = nullptr;
146 static Reloc::Model RelocationModel = Reloc::Default;
147 static std::string output_name = "";
148 static std::list<claimed_file> Modules;
149 static StringMap<ResolutionInfo> ResInfo;
150 static std::vector<std::string> Cleanup;
151 static llvm::TargetOptions TargetOpts;
152 static std::string DefaultTriple = sys::getDefaultTargetTriple();
153 
154 namespace options {
155   enum OutputType {
156     OT_NORMAL,
157     OT_DISABLE,
158     OT_BC_ONLY,
159     OT_SAVE_TEMPS
160   };
161   static bool generate_api_file = false;
162   static OutputType TheOutputType = OT_NORMAL;
163   static unsigned OptLevel = 2;
164   // Default parallelism of 0 used to indicate that user did not specify.
165   // Actual parallelism default value depends on implementation.
166   // Currently, code generation defaults to no parallelism, whereas
167   // ThinLTO uses the hardware_concurrency as the default.
168   static unsigned Parallelism = 0;
169 #ifdef NDEBUG
170   static bool DisableVerify = true;
171 #else
172   static bool DisableVerify = false;
173 #endif
174   static std::string obj_path;
175   static std::string extra_library_path;
176   static std::string triple;
177   static std::string mcpu;
178   // When the thinlto plugin option is specified, only read the function
179   // the information from intermediate files and write a combined
180   // global index for the ThinLTO backends.
181   static bool thinlto = false;
182   // If false, all ThinLTO backend compilations through code gen are performed
183   // using multiple threads in the gold-plugin, before handing control back to
184   // gold. If true, exit after creating the combined index, the assuming is
185   // that the build system will launch the backend processes.
186   static bool thinlto_index_only = false;
187   // Additional options to pass into the code generator.
188   // Note: This array will contain all plugin options which are not claimed
189   // as plugin exclusive to pass to the code generator.
190   // For example, "generate-api-file" and "as"options are for the plugin
191   // use only and will not be passed.
192   static std::vector<const char *> extra;
193 
194   static void process_plugin_option(const char *opt_)
195   {
196     if (opt_ == nullptr)
197       return;
198     llvm::StringRef opt = opt_;
199 
200     if (opt == "generate-api-file") {
201       generate_api_file = true;
202     } else if (opt.startswith("mcpu=")) {
203       mcpu = opt.substr(strlen("mcpu="));
204     } else if (opt.startswith("extra-library-path=")) {
205       extra_library_path = opt.substr(strlen("extra_library_path="));
206     } else if (opt.startswith("mtriple=")) {
207       triple = opt.substr(strlen("mtriple="));
208     } else if (opt.startswith("obj-path=")) {
209       obj_path = opt.substr(strlen("obj-path="));
210     } else if (opt == "emit-llvm") {
211       TheOutputType = OT_BC_ONLY;
212     } else if (opt == "save-temps") {
213       TheOutputType = OT_SAVE_TEMPS;
214     } else if (opt == "disable-output") {
215       TheOutputType = OT_DISABLE;
216     } else if (opt == "thinlto") {
217       thinlto = true;
218     } else if (opt == "thinlto-index-only") {
219       thinlto_index_only = true;
220     } else if (opt.size() == 2 && opt[0] == 'O') {
221       if (opt[1] < '0' || opt[1] > '3')
222         message(LDPL_FATAL, "Optimization level must be between 0 and 3");
223       OptLevel = opt[1] - '0';
224     } else if (opt.startswith("jobs=")) {
225       if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
226         message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
227     } else if (opt == "disable-verify") {
228       DisableVerify = true;
229     } else {
230       // Save this option to pass to the code generator.
231       // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
232       // add that.
233       if (extra.empty())
234         extra.push_back("LLVMgold");
235 
236       extra.push_back(opt_);
237     }
238   }
239 }
240 
241 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
242                                         int *claimed);
243 static ld_plugin_status all_symbols_read_hook(void);
244 static ld_plugin_status cleanup_hook(void);
245 
246 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
247 ld_plugin_status onload(ld_plugin_tv *tv) {
248   InitializeAllTargetInfos();
249   InitializeAllTargets();
250   InitializeAllTargetMCs();
251   InitializeAllAsmParsers();
252   InitializeAllAsmPrinters();
253 
254   // We're given a pointer to the first transfer vector. We read through them
255   // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
256   // contain pointers to functions that we need to call to register our own
257   // hooks. The others are addresses of functions we can use to call into gold
258   // for services.
259 
260   bool registeredClaimFile = false;
261   bool RegisteredAllSymbolsRead = false;
262 
263   for (; tv->tv_tag != LDPT_NULL; ++tv) {
264     // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
265     // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
266     // header.
267     switch (static_cast<int>(tv->tv_tag)) {
268     case LDPT_OUTPUT_NAME:
269       output_name = tv->tv_u.tv_string;
270       break;
271     case LDPT_LINKER_OUTPUT:
272       switch (tv->tv_u.tv_val) {
273       case LDPO_REL: // .o
274       case LDPO_DYN: // .so
275       case LDPO_PIE: // position independent executable
276         RelocationModel = Reloc::PIC_;
277         break;
278       case LDPO_EXEC: // .exe
279         RelocationModel = Reloc::Static;
280         break;
281       default:
282         message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
283         return LDPS_ERR;
284       }
285       break;
286     case LDPT_OPTION:
287       options::process_plugin_option(tv->tv_u.tv_string);
288       break;
289     case LDPT_REGISTER_CLAIM_FILE_HOOK: {
290       ld_plugin_register_claim_file callback;
291       callback = tv->tv_u.tv_register_claim_file;
292 
293       if (callback(claim_file_hook) != LDPS_OK)
294         return LDPS_ERR;
295 
296       registeredClaimFile = true;
297     } break;
298     case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
299       ld_plugin_register_all_symbols_read callback;
300       callback = tv->tv_u.tv_register_all_symbols_read;
301 
302       if (callback(all_symbols_read_hook) != LDPS_OK)
303         return LDPS_ERR;
304 
305       RegisteredAllSymbolsRead = true;
306     } break;
307     case LDPT_REGISTER_CLEANUP_HOOK: {
308       ld_plugin_register_cleanup callback;
309       callback = tv->tv_u.tv_register_cleanup;
310 
311       if (callback(cleanup_hook) != LDPS_OK)
312         return LDPS_ERR;
313     } break;
314     case LDPT_GET_INPUT_FILE:
315       get_input_file = tv->tv_u.tv_get_input_file;
316       break;
317     case LDPT_RELEASE_INPUT_FILE:
318       release_input_file = tv->tv_u.tv_release_input_file;
319       break;
320     case LDPT_ADD_SYMBOLS:
321       add_symbols = tv->tv_u.tv_add_symbols;
322       break;
323     case LDPT_GET_SYMBOLS_V2:
324       // Do not override get_symbols_v3 with get_symbols_v2.
325       if (!get_symbols)
326         get_symbols = tv->tv_u.tv_get_symbols;
327       break;
328     case LDPT_GET_SYMBOLS_V3:
329       get_symbols = tv->tv_u.tv_get_symbols;
330       break;
331     case LDPT_ADD_INPUT_FILE:
332       add_input_file = tv->tv_u.tv_add_input_file;
333       break;
334     case LDPT_SET_EXTRA_LIBRARY_PATH:
335       set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
336       break;
337     case LDPT_GET_VIEW:
338       get_view = tv->tv_u.tv_get_view;
339       break;
340     case LDPT_MESSAGE:
341       message = tv->tv_u.tv_message;
342       break;
343     default:
344       break;
345     }
346   }
347 
348   if (!registeredClaimFile) {
349     message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
350     return LDPS_ERR;
351   }
352   if (!add_symbols) {
353     message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
354     return LDPS_ERR;
355   }
356 
357   if (!RegisteredAllSymbolsRead)
358     return LDPS_OK;
359 
360   if (!get_input_file) {
361     message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
362     return LDPS_ERR;
363   }
364   if (!release_input_file) {
365     message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
366     return LDPS_ERR;
367   }
368 
369   return LDPS_OK;
370 }
371 
372 static const GlobalObject *getBaseObject(const GlobalValue &GV) {
373   if (auto *GA = dyn_cast<GlobalAlias>(&GV))
374     return GA->getBaseObject();
375   return cast<GlobalObject>(&GV);
376 }
377 
378 static bool shouldSkip(uint32_t Symflags) {
379   if (!(Symflags & object::BasicSymbolRef::SF_Global))
380     return true;
381   if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
382     return true;
383   return false;
384 }
385 
386 static void diagnosticHandler(const DiagnosticInfo &DI) {
387   if (const auto *BDI = dyn_cast<BitcodeDiagnosticInfo>(&DI)) {
388     std::error_code EC = BDI->getError();
389     if (EC == BitcodeError::InvalidBitcodeSignature)
390       return;
391   }
392 
393   std::string ErrStorage;
394   {
395     raw_string_ostream OS(ErrStorage);
396     DiagnosticPrinterRawOStream DP(OS);
397     DI.print(DP);
398   }
399   ld_plugin_level Level;
400   switch (DI.getSeverity()) {
401   case DS_Error:
402     message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
403             ErrStorage.c_str());
404   case DS_Warning:
405     Level = LDPL_WARNING;
406     break;
407   case DS_Note:
408   case DS_Remark:
409     Level = LDPL_INFO;
410     break;
411   }
412   message(Level, "LLVM gold plugin: %s",  ErrStorage.c_str());
413 }
414 
415 static void diagnosticHandlerForContext(const DiagnosticInfo &DI,
416                                         void *Context) {
417   diagnosticHandler(DI);
418 }
419 
420 static GlobalValue::VisibilityTypes
421 getMinVisibility(GlobalValue::VisibilityTypes A,
422                  GlobalValue::VisibilityTypes B) {
423   if (A == GlobalValue::HiddenVisibility)
424     return A;
425   if (B == GlobalValue::HiddenVisibility)
426     return B;
427   if (A == GlobalValue::ProtectedVisibility)
428     return A;
429   return B;
430 }
431 
432 /// Called by gold to see whether this file is one that our plugin can handle.
433 /// We'll try to open it and register all the symbols with add_symbol if
434 /// possible.
435 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
436                                         int *claimed) {
437   LLVMContext Context;
438   MemoryBufferRef BufferRef;
439   std::unique_ptr<MemoryBuffer> Buffer;
440   if (get_view) {
441     const void *view;
442     if (get_view(file->handle, &view) != LDPS_OK) {
443       message(LDPL_ERROR, "Failed to get a view of %s", file->name);
444       return LDPS_ERR;
445     }
446     BufferRef =
447         MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
448   } else {
449     int64_t offset = 0;
450     // Gold has found what might be IR part-way inside of a file, such as
451     // an .a archive.
452     if (file->offset) {
453       offset = file->offset;
454     }
455     ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
456         MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
457                                        offset);
458     if (std::error_code EC = BufferOrErr.getError()) {
459       message(LDPL_ERROR, EC.message().c_str());
460       return LDPS_ERR;
461     }
462     Buffer = std::move(BufferOrErr.get());
463     BufferRef = Buffer->getMemBufferRef();
464   }
465 
466   Context.setDiagnosticHandler(diagnosticHandlerForContext);
467   ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
468       object::IRObjectFile::create(BufferRef, Context);
469   std::error_code EC = ObjOrErr.getError();
470   if (EC == object::object_error::invalid_file_type ||
471       EC == object::object_error::bitcode_section_not_found)
472     return LDPS_OK;
473 
474   *claimed = 1;
475 
476   if (EC) {
477     message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
478             EC.message().c_str());
479     return LDPS_ERR;
480   }
481   std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
482 
483   Modules.resize(Modules.size() + 1);
484   claimed_file &cf = Modules.back();
485 
486   cf.handle = file->handle;
487 
488   // If we are doing ThinLTO compilation, don't need to process the symbols.
489   // Later we simply build a combined index file after all files are claimed.
490   if (options::thinlto && options::thinlto_index_only)
491     return LDPS_OK;
492 
493   for (auto &Sym : Obj->symbols()) {
494     uint32_t Symflags = Sym.getFlags();
495     if (shouldSkip(Symflags))
496       continue;
497 
498     cf.syms.push_back(ld_plugin_symbol());
499     ld_plugin_symbol &sym = cf.syms.back();
500     sym.version = nullptr;
501 
502     SmallString<64> Name;
503     {
504       raw_svector_ostream OS(Name);
505       Sym.printName(OS);
506     }
507     sym.name = strdup(Name.c_str());
508 
509     const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
510 
511     ResolutionInfo &Res = ResInfo[sym.name];
512 
513     sym.visibility = LDPV_DEFAULT;
514     if (GV) {
515       Res.UnnamedAddr &= GV->hasUnnamedAddr();
516       Res.IsLinkonceOdr &= GV->hasLinkOnceLinkage();
517       Res.Visibility = getMinVisibility(Res.Visibility, GV->getVisibility());
518       switch (GV->getVisibility()) {
519       case GlobalValue::DefaultVisibility:
520         sym.visibility = LDPV_DEFAULT;
521         break;
522       case GlobalValue::HiddenVisibility:
523         sym.visibility = LDPV_HIDDEN;
524         break;
525       case GlobalValue::ProtectedVisibility:
526         sym.visibility = LDPV_PROTECTED;
527         break;
528       }
529     }
530 
531     if (Symflags & object::BasicSymbolRef::SF_Undefined) {
532       sym.def = LDPK_UNDEF;
533       if (GV && GV->hasExternalWeakLinkage())
534         sym.def = LDPK_WEAKUNDEF;
535     } else {
536       sym.def = LDPK_DEF;
537       if (GV) {
538         assert(!GV->hasExternalWeakLinkage() &&
539                !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
540         if (GV->hasCommonLinkage())
541           sym.def = LDPK_COMMON;
542         else if (GV->isWeakForLinker())
543           sym.def = LDPK_WEAKDEF;
544       }
545     }
546 
547     sym.size = 0;
548     sym.comdat_key = nullptr;
549     if (GV) {
550       const GlobalObject *Base = getBaseObject(*GV);
551       if (!Base)
552         message(LDPL_FATAL, "Unable to determine comdat of alias!");
553       const Comdat *C = Base->getComdat();
554       if (C)
555         sym.comdat_key = strdup(C->getName().str().c_str());
556     }
557 
558     sym.resolution = LDPR_UNKNOWN;
559   }
560 
561   if (!cf.syms.empty()) {
562     if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
563       message(LDPL_ERROR, "Unable to add symbols!");
564       return LDPS_ERR;
565     }
566   }
567 
568   return LDPS_OK;
569 }
570 
571 static void internalize(GlobalValue &GV) {
572   if (GV.isDeclarationForLinker())
573     return; // We get here if there is a matching asm definition.
574   if (!GV.hasLocalLinkage())
575     GV.setLinkage(GlobalValue::InternalLinkage);
576 }
577 
578 static const char *getResolutionName(ld_plugin_symbol_resolution R) {
579   switch (R) {
580   case LDPR_UNKNOWN:
581     return "UNKNOWN";
582   case LDPR_UNDEF:
583     return "UNDEF";
584   case LDPR_PREVAILING_DEF:
585     return "PREVAILING_DEF";
586   case LDPR_PREVAILING_DEF_IRONLY:
587     return "PREVAILING_DEF_IRONLY";
588   case LDPR_PREEMPTED_REG:
589     return "PREEMPTED_REG";
590   case LDPR_PREEMPTED_IR:
591     return "PREEMPTED_IR";
592   case LDPR_RESOLVED_IR:
593     return "RESOLVED_IR";
594   case LDPR_RESOLVED_EXEC:
595     return "RESOLVED_EXEC";
596   case LDPR_RESOLVED_DYN:
597     return "RESOLVED_DYN";
598   case LDPR_PREVAILING_DEF_IRONLY_EXP:
599     return "PREVAILING_DEF_IRONLY_EXP";
600   }
601   llvm_unreachable("Unknown resolution");
602 }
603 
604 static void freeSymName(ld_plugin_symbol &Sym) {
605   free(Sym.name);
606   free(Sym.comdat_key);
607   Sym.name = nullptr;
608   Sym.comdat_key = nullptr;
609 }
610 
611 /// Helper to get a file's symbols and a view into it via gold callbacks.
612 static const void *getSymbolsAndView(claimed_file &F) {
613   ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
614   if (status == LDPS_NO_SYMS)
615     return nullptr;
616 
617   if (status != LDPS_OK)
618     message(LDPL_FATAL, "Failed to get symbol information");
619 
620   const void *View;
621   if (get_view(F.handle, &View) != LDPS_OK)
622     message(LDPL_FATAL, "Failed to get a view of file");
623 
624   return View;
625 }
626 
627 static std::unique_ptr<ModuleSummaryIndex>
628 getModuleSummaryIndexForFile(claimed_file &F, ld_plugin_input_file &Info) {
629   const void *View = getSymbolsAndView(F);
630   if (!View)
631     return nullptr;
632 
633   MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize),
634                             Info.name);
635 
636   // Don't bother trying to build an index if there is no summary information
637   // in this bitcode file.
638   if (!object::ModuleSummaryIndexObjectFile::hasGlobalValueSummaryInMemBuffer(
639           BufferRef, diagnosticHandler))
640     return std::unique_ptr<ModuleSummaryIndex>(nullptr);
641 
642   ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
643       object::ModuleSummaryIndexObjectFile::create(BufferRef,
644                                                    diagnosticHandler);
645 
646   if (std::error_code EC = ObjOrErr.getError())
647     message(LDPL_FATAL,
648             "Could not read module summary index bitcode from file : %s",
649             EC.message().c_str());
650 
651   object::ModuleSummaryIndexObjectFile &Obj = **ObjOrErr;
652 
653   return Obj.takeIndex();
654 }
655 
656 static std::unique_ptr<Module>
657 getModuleForFile(LLVMContext &Context, claimed_file &F, const void *View,
658                  ld_plugin_input_file &Info, raw_fd_ostream *ApiFile,
659                  StringSet<> &Internalize, StringSet<> &Maybe,
660                  std::vector<GlobalValue *> &Keep,
661                  StringMap<unsigned> &Realign) {
662   MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize),
663                             Info.name);
664   ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
665       object::IRObjectFile::create(BufferRef, Context);
666 
667   if (std::error_code EC = ObjOrErr.getError())
668     message(LDPL_FATAL, "Could not read bitcode from file : %s",
669             EC.message().c_str());
670 
671   object::IRObjectFile &Obj = **ObjOrErr;
672 
673   Module &M = Obj.getModule();
674 
675   M.materializeMetadata();
676   UpgradeDebugInfo(M);
677 
678   SmallPtrSet<GlobalValue *, 8> Used;
679   collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
680 
681   unsigned SymNum = 0;
682   for (auto &ObjSym : Obj.symbols()) {
683     GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
684     if (GV && GV->hasAppendingLinkage())
685       Keep.push_back(GV);
686 
687     if (shouldSkip(ObjSym.getFlags()))
688       continue;
689     ld_plugin_symbol &Sym = F.syms[SymNum];
690     ++SymNum;
691 
692     ld_plugin_symbol_resolution Resolution =
693         (ld_plugin_symbol_resolution)Sym.resolution;
694 
695     if (options::generate_api_file)
696       *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
697 
698     if (!GV) {
699       freeSymName(Sym);
700       continue; // Asm symbol.
701     }
702 
703     ResolutionInfo &Res = ResInfo[Sym.name];
704     if (Resolution == LDPR_PREVAILING_DEF_IRONLY_EXP && !Res.IsLinkonceOdr)
705       Resolution = LDPR_PREVAILING_DEF;
706 
707     // In ThinLTO mode change all prevailing resolutions to LDPR_PREVAILING_DEF.
708     // For ThinLTO the IR files are compiled through the backend independently,
709     // so we need to ensure that any prevailing linkonce copy will be emitted
710     // into the object file by making it weak. Additionally, we can skip the
711     // IRONLY handling for internalization, which isn't performed in ThinLTO
712     // mode currently anyway.
713     if (options::thinlto && (Resolution == LDPR_PREVAILING_DEF_IRONLY_EXP ||
714                              Resolution == LDPR_PREVAILING_DEF_IRONLY))
715       Resolution = LDPR_PREVAILING_DEF;
716 
717     GV->setUnnamedAddr(Res.UnnamedAddr);
718     GV->setVisibility(Res.Visibility);
719 
720     // Override gold's resolution for common symbols. We want the largest
721     // one to win.
722     if (GV->hasCommonLinkage()) {
723       if (Resolution == LDPR_PREVAILING_DEF_IRONLY)
724         Res.CommonInternal = true;
725 
726       if (Resolution == LDPR_PREVAILING_DEF_IRONLY ||
727           Resolution == LDPR_PREVAILING_DEF)
728         Res.UseCommon = true;
729 
730       const DataLayout &DL = GV->getParent()->getDataLayout();
731       uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
732       unsigned Align = GV->getAlignment();
733 
734       if (Res.UseCommon && Size >= Res.CommonSize) {
735         // Take GV.
736         if (Res.CommonInternal)
737           Resolution = LDPR_PREVAILING_DEF_IRONLY;
738         else
739           Resolution = LDPR_PREVAILING_DEF;
740         cast<GlobalVariable>(GV)->setAlignment(
741             std::max(Res.CommonAlign, Align));
742       } else {
743         // Do not take GV, it's smaller than what we already have in the
744         // combined module.
745         Resolution = LDPR_PREEMPTED_IR;
746         if (Align > Res.CommonAlign)
747           // Need to raise the alignment though.
748           Realign[Sym.name] = Align;
749       }
750 
751       Res.CommonSize = std::max(Res.CommonSize, Size);
752       Res.CommonAlign = std::max(Res.CommonAlign, Align);
753     }
754 
755     switch (Resolution) {
756     case LDPR_UNKNOWN:
757       llvm_unreachable("Unexpected resolution");
758 
759     case LDPR_RESOLVED_IR:
760     case LDPR_RESOLVED_EXEC:
761     case LDPR_RESOLVED_DYN:
762     case LDPR_PREEMPTED_IR:
763     case LDPR_PREEMPTED_REG:
764       break;
765 
766     case LDPR_UNDEF:
767       if (!GV->isDeclarationForLinker())
768         assert(GV->hasComdat());
769       break;
770 
771     case LDPR_PREVAILING_DEF_IRONLY: {
772       Keep.push_back(GV);
773       // The IR linker has to be able to map this value to a declaration,
774       // so we can only internalize after linking.
775       if (!Used.count(GV))
776         Internalize.insert(GV->getName());
777       break;
778     }
779 
780     case LDPR_PREVAILING_DEF:
781       Keep.push_back(GV);
782       // There is a non IR use, so we have to force optimizations to keep this.
783       switch (GV->getLinkage()) {
784       default:
785         break;
786       case GlobalValue::LinkOnceAnyLinkage:
787         GV->setLinkage(GlobalValue::WeakAnyLinkage);
788         break;
789       case GlobalValue::LinkOnceODRLinkage:
790         GV->setLinkage(GlobalValue::WeakODRLinkage);
791         break;
792       }
793       break;
794 
795     case LDPR_PREVAILING_DEF_IRONLY_EXP: {
796       // We can only check for address uses after we merge the modules. The
797       // reason is that this GV might have a copy in another module
798       // and in that module the address might be significant, but that
799       // copy will be LDPR_PREEMPTED_IR.
800       Maybe.insert(GV->getName());
801       Keep.push_back(GV);
802       break;
803     }
804     }
805 
806     freeSymName(Sym);
807   }
808 
809   return Obj.takeModule();
810 }
811 
812 static void saveBCFile(StringRef Path, Module &M) {
813   std::error_code EC;
814   raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
815   if (EC)
816     message(LDPL_FATAL, "Failed to write the output file.");
817   WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ false);
818 }
819 
820 static void recordFile(std::string Filename, bool TempOutFile) {
821   if (add_input_file(Filename.c_str()) != LDPS_OK)
822     message(LDPL_FATAL,
823             "Unable to add .o file to the link. File left behind in: %s",
824             Filename.c_str());
825   if (TempOutFile)
826     Cleanup.push_back(Filename.c_str());
827 }
828 
829 void ThinLTOTaskInfo::cleanup() {
830   // Close the output file descriptor before we pass it to gold.
831   OS->close();
832 
833   recordFile(Filename, TempOutFile);
834 }
835 
836 namespace {
837 /// Class to manage optimization and code generation for a module, possibly
838 /// in a thread (ThinLTO).
839 class CodeGen {
840   /// The module for which this will generate code.
841   std::unique_ptr<llvm::Module> M;
842 
843   /// The output stream to generate code into.
844   raw_fd_ostream *OS;
845 
846   /// The task ID when this was invoked in a thread (ThinLTO).
847   int TaskID;
848 
849   /// The module summary index for ThinLTO tasks.
850   const ModuleSummaryIndex *CombinedIndex;
851 
852   /// The target machine for generating code for this module.
853   std::unique_ptr<TargetMachine> TM;
854 
855   /// Filename to use as base when save-temps is enabled, used to get
856   /// a unique and identifiable save-temps output file for each ThinLTO backend.
857   std::string SaveTempsFilename;
858 
859 public:
860   /// Constructor used by full LTO.
861   CodeGen(std::unique_ptr<llvm::Module> M)
862       : M(std::move(M)), OS(nullptr), TaskID(-1), CombinedIndex(nullptr) {
863     initTargetMachine();
864   }
865   /// Constructor used by ThinLTO.
866   CodeGen(std::unique_ptr<llvm::Module> M, raw_fd_ostream *OS, int TaskID,
867           const ModuleSummaryIndex *CombinedIndex, std::string Filename)
868       : M(std::move(M)), OS(OS), TaskID(TaskID), CombinedIndex(CombinedIndex),
869         SaveTempsFilename(Filename) {
870     assert(options::thinlto == !!CombinedIndex &&
871            "Expected module summary index iff performing ThinLTO");
872     initTargetMachine();
873   }
874 
875   /// Invoke LTO passes and the code generator for the module.
876   void runAll();
877 
878   /// Invoke the actual code generation to emit Module's object to file.
879   void runCodegenPasses();
880 
881 private:
882   /// Create a target machine for the module. Must be unique for each
883   /// module/task.
884   void initTargetMachine();
885 
886   /// Run all LTO passes on the module.
887   void runLTOPasses();
888 
889   /// Sets up output files necessary to perform optional multi-threaded
890   /// split code generation, and invokes the code generation implementation.
891   void runSplitCodeGen();
892 };
893 }
894 
895 static SubtargetFeatures getFeatures(Triple &TheTriple) {
896   SubtargetFeatures Features;
897   Features.getDefaultSubtargetFeatures(TheTriple);
898   for (const std::string &A : MAttrs)
899     Features.AddFeature(A);
900   return Features;
901 }
902 
903 static CodeGenOpt::Level getCGOptLevel() {
904   switch (options::OptLevel) {
905   case 0:
906     return CodeGenOpt::None;
907   case 1:
908     return CodeGenOpt::Less;
909   case 2:
910     return CodeGenOpt::Default;
911   case 3:
912     return CodeGenOpt::Aggressive;
913   }
914   llvm_unreachable("Invalid optimization level");
915 }
916 
917 void CodeGen::initTargetMachine() {
918   const std::string &TripleStr = M->getTargetTriple();
919   Triple TheTriple(TripleStr);
920 
921   std::string ErrMsg;
922   const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
923   if (!TheTarget)
924     message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
925 
926   SubtargetFeatures Features = getFeatures(TheTriple);
927   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
928   CodeGenOpt::Level CGOptLevel = getCGOptLevel();
929 
930   TM.reset(TheTarget->createTargetMachine(
931       TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
932       CodeModel::Default, CGOptLevel));
933 }
934 
935 void CodeGen::runLTOPasses() {
936   M->setDataLayout(TM->createDataLayout());
937 
938   legacy::PassManager passes;
939   passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
940 
941   PassManagerBuilder PMB;
942   PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
943   PMB.Inliner = createFunctionInliningPass();
944   // Unconditionally verify input since it is not verified before this
945   // point and has unknown origin.
946   PMB.VerifyInput = true;
947   PMB.VerifyOutput = !options::DisableVerify;
948   PMB.LoopVectorize = true;
949   PMB.SLPVectorize = true;
950   PMB.OptLevel = options::OptLevel;
951   PMB.ModuleSummary = CombinedIndex;
952   PMB.populateLTOPassManager(passes);
953   passes.run(*M);
954 }
955 
956 /// Open a file and return the new file descriptor given a base input
957 /// file name, a flag indicating whether a temp file should be generated,
958 /// and an optional task id. The new filename generated is
959 /// returned in \p NewFilename.
960 static int openOutputFile(SmallString<128> InFilename, bool TempOutFile,
961                           SmallString<128> &NewFilename, int TaskID = -1) {
962   int FD;
963   if (TempOutFile) {
964     std::error_code EC =
965         sys::fs::createTemporaryFile("lto-llvm", "o", FD, NewFilename);
966     if (EC)
967       message(LDPL_FATAL, "Could not create temporary file: %s",
968               EC.message().c_str());
969   } else {
970     NewFilename = InFilename;
971     if (TaskID >= 0)
972       NewFilename += utostr(TaskID);
973     std::error_code EC =
974         sys::fs::openFileForWrite(NewFilename, FD, sys::fs::F_None);
975     if (EC)
976       message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
977   }
978   return FD;
979 }
980 
981 void CodeGen::runCodegenPasses() {
982   assert(OS && "Output stream must be set before emitting to file");
983   legacy::PassManager CodeGenPasses;
984   if (TM->addPassesToEmitFile(CodeGenPasses, *OS,
985                               TargetMachine::CGFT_ObjectFile))
986     report_fatal_error("Failed to setup codegen");
987   CodeGenPasses.run(*M);
988 }
989 
990 void CodeGen::runSplitCodeGen() {
991   const std::string &TripleStr = M->getTargetTriple();
992   Triple TheTriple(TripleStr);
993 
994   SubtargetFeatures Features = getFeatures(TheTriple);
995 
996   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
997   CodeGenOpt::Level CGOptLevel = getCGOptLevel();
998 
999   SmallString<128> Filename;
1000   // Note that openOutputFile will append a unique ID for each task
1001   if (!options::obj_path.empty())
1002     Filename = options::obj_path;
1003   else if (options::TheOutputType == options::OT_SAVE_TEMPS)
1004     Filename = output_name + ".o";
1005 
1006   // Note that the default parallelism is 1 instead of the
1007   // hardware_concurrency, as there are behavioral differences between
1008   // parallelism levels (e.g. symbol ordering will be different, and some uses
1009   // of inline asm currently have issues with parallelism >1).
1010   unsigned int MaxThreads = options::Parallelism ? options::Parallelism : 1;
1011 
1012   std::vector<SmallString<128>> Filenames(MaxThreads);
1013   bool TempOutFile = Filename.empty();
1014   {
1015     // Open a file descriptor for each backend task. This is done in a block
1016     // so that the output file descriptors are closed before gold opens them.
1017     std::list<llvm::raw_fd_ostream> OSs;
1018     std::vector<llvm::raw_pwrite_stream *> OSPtrs(MaxThreads);
1019     for (unsigned I = 0; I != MaxThreads; ++I) {
1020       int FD = openOutputFile(Filename, TempOutFile, Filenames[I],
1021                               // Only append ID if there are multiple tasks.
1022                               MaxThreads > 1 ? I : -1);
1023       OSs.emplace_back(FD, true);
1024       OSPtrs[I] = &OSs.back();
1025     }
1026 
1027     // Run backend tasks.
1028     splitCodeGen(std::move(M), OSPtrs, options::mcpu, Features.getString(),
1029                  Options, RelocationModel, CodeModel::Default, CGOptLevel);
1030   }
1031 
1032   for (auto &Filename : Filenames)
1033     recordFile(Filename.c_str(), TempOutFile);
1034 }
1035 
1036 void CodeGen::runAll() {
1037   runLTOPasses();
1038 
1039   if (options::TheOutputType == options::OT_SAVE_TEMPS) {
1040     std::string OptFilename = output_name;
1041     // If the CodeGen client provided a filename, use it. Always expect
1042     // a provided filename if we are in a task (i.e. ThinLTO backend).
1043     assert(!SaveTempsFilename.empty() || TaskID == -1);
1044     if (!SaveTempsFilename.empty())
1045       OptFilename = SaveTempsFilename;
1046     saveBCFile(OptFilename + ".opt.bc", *M);
1047   }
1048 
1049   // If we are already in a thread (i.e. ThinLTO), just perform
1050   // codegen passes directly.
1051   if (TaskID >= 0)
1052     runCodegenPasses();
1053   // Otherwise attempt split code gen.
1054   else
1055     runSplitCodeGen();
1056 }
1057 
1058 /// Links the module in \p View from file \p F into the combined module
1059 /// saved in the IRMover \p L. Returns true on error, false on success.
1060 static bool linkInModule(LLVMContext &Context, IRMover &L, claimed_file &F,
1061                          const void *View, ld_plugin_input_file &File,
1062                          raw_fd_ostream *ApiFile, StringSet<> &Internalize,
1063                          StringSet<> &Maybe) {
1064   std::vector<GlobalValue *> Keep;
1065   StringMap<unsigned> Realign;
1066   std::unique_ptr<Module> M = getModuleForFile(
1067       Context, F, View, File, ApiFile, Internalize, Maybe, Keep, Realign);
1068   if (!M.get())
1069     return false;
1070   if (!options::triple.empty())
1071     M->setTargetTriple(options::triple.c_str());
1072   else if (M->getTargetTriple().empty()) {
1073     M->setTargetTriple(DefaultTriple);
1074   }
1075 
1076   if (!L.move(std::move(M), Keep, [](GlobalValue &, IRMover::ValueAdder) {}))
1077     return false;
1078 
1079   for (const auto &I : Realign) {
1080     GlobalValue *Dst = L.getModule().getNamedValue(I.first());
1081     if (!Dst)
1082       continue;
1083     cast<GlobalVariable>(Dst)->setAlignment(I.second);
1084   }
1085 
1086   return true;
1087 }
1088 
1089 /// Perform the ThinLTO backend on a single module, invoking the LTO and codegen
1090 /// pipelines.
1091 static void thinLTOBackendTask(claimed_file &F, const void *View,
1092                                ld_plugin_input_file &File,
1093                                raw_fd_ostream *ApiFile,
1094                                const ModuleSummaryIndex &CombinedIndex,
1095                                raw_fd_ostream *OS, unsigned TaskID) {
1096   // Need to use a separate context for each task
1097   LLVMContext Context;
1098   Context.setDiagnosticHandler(diagnosticHandlerForContext, nullptr, true);
1099 
1100   std::unique_ptr<llvm::Module> NewModule(new llvm::Module(File.name, Context));
1101   IRMover L(*NewModule.get());
1102 
1103   StringSet<> Dummy;
1104   if (linkInModule(Context, L, F, View, File, ApiFile, Dummy, Dummy))
1105     message(LDPL_FATAL, "Failed to rename module for ThinLTO");
1106   if (renameModuleForThinLTO(*NewModule, CombinedIndex))
1107     message(LDPL_FATAL, "Failed to rename module for ThinLTO");
1108 
1109   CodeGen codeGen(std::move(NewModule), OS, TaskID, &CombinedIndex, File.name);
1110   codeGen.runAll();
1111 }
1112 
1113 /// Launch each module's backend pipeline in a separate task in a thread pool.
1114 static void thinLTOBackends(raw_fd_ostream *ApiFile,
1115                             const ModuleSummaryIndex &CombinedIndex) {
1116   unsigned TaskCount = 0;
1117   std::vector<ThinLTOTaskInfo> Tasks;
1118   Tasks.reserve(Modules.size());
1119   unsigned int MaxThreads = options::Parallelism
1120                                 ? options::Parallelism
1121                                 : thread::hardware_concurrency();
1122 
1123   // Create ThreadPool in nested scope so that threads will be joined
1124   // on destruction.
1125   {
1126     ThreadPool ThinLTOThreadPool(MaxThreads);
1127     for (claimed_file &F : Modules) {
1128       // Do all the gold callbacks in the main thread, since gold is not thread
1129       // safe by default.
1130       PluginInputFile InputFile(F.handle);
1131       const void *View = getSymbolsAndView(F);
1132       if (!View)
1133         continue;
1134 
1135       SmallString<128> Filename;
1136       if (!options::obj_path.empty())
1137         // Note that openOutputFile will append a unique ID for each task
1138         Filename = options::obj_path;
1139       else if (options::TheOutputType == options::OT_SAVE_TEMPS) {
1140         // Use the input file name so that we get a unique and identifiable
1141         // output file for each ThinLTO backend task.
1142         Filename = InputFile.file().name;
1143         Filename += ".thinlto.o";
1144       }
1145       bool TempOutFile = Filename.empty();
1146 
1147       SmallString<128> NewFilename;
1148       int FD = openOutputFile(Filename, TempOutFile, NewFilename,
1149                               // Only append the TaskID if we will use the
1150                               // non-unique obj_path.
1151                               !options::obj_path.empty() ? TaskCount : -1);
1152       TaskCount++;
1153       std::unique_ptr<raw_fd_ostream> OS =
1154           llvm::make_unique<raw_fd_ostream>(FD, true);
1155 
1156       // Enqueue the task
1157       ThinLTOThreadPool.async(thinLTOBackendTask, std::ref(F), View,
1158                               std::ref(InputFile.file()), ApiFile,
1159                               std::ref(CombinedIndex), OS.get(), TaskCount);
1160 
1161       // Record the information needed by the task or during its cleanup
1162       // to a ThinLTOTaskInfo instance. For information needed by the task
1163       // the unique_ptr ownership is transferred to the ThinLTOTaskInfo.
1164       Tasks.emplace_back(std::move(InputFile), std::move(OS),
1165                          NewFilename.c_str(), TempOutFile);
1166     }
1167   }
1168 
1169   for (auto &Task : Tasks)
1170     Task.cleanup();
1171 }
1172 
1173 /// gold informs us that all symbols have been read. At this point, we use
1174 /// get_symbols to see if any of our definitions have been overridden by a
1175 /// native object file. Then, perform optimization and codegen.
1176 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
1177   if (Modules.empty())
1178     return LDPS_OK;
1179 
1180   if (unsigned NumOpts = options::extra.size())
1181     cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
1182 
1183   // If we are doing ThinLTO compilation, simply build the combined
1184   // module index/summary and emit it. We don't need to parse the modules
1185   // and link them in this case.
1186   if (options::thinlto) {
1187     ModuleSummaryIndex CombinedIndex;
1188     uint64_t NextModuleId = 0;
1189     for (claimed_file &F : Modules) {
1190       PluginInputFile InputFile(F.handle);
1191 
1192       std::unique_ptr<ModuleSummaryIndex> Index =
1193           getModuleSummaryIndexForFile(F, InputFile.file());
1194 
1195       // Skip files without a module summary.
1196       if (Index)
1197         CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
1198     }
1199 
1200     std::error_code EC;
1201     raw_fd_ostream OS(output_name + ".thinlto.bc", EC,
1202                       sys::fs::OpenFlags::F_None);
1203     if (EC)
1204       message(LDPL_FATAL, "Unable to open %s.thinlto.bc for writing: %s",
1205               output_name.data(), EC.message().c_str());
1206     WriteIndexToFile(CombinedIndex, OS);
1207     OS.close();
1208 
1209     if (options::thinlto_index_only) {
1210       cleanup_hook();
1211       exit(0);
1212     }
1213 
1214     thinLTOBackends(ApiFile, CombinedIndex);
1215     return LDPS_OK;
1216   }
1217 
1218   LLVMContext Context;
1219   Context.setDiagnosticHandler(diagnosticHandlerForContext, nullptr, true);
1220 
1221   std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
1222   IRMover L(*Combined);
1223 
1224   StringSet<> Internalize;
1225   StringSet<> Maybe;
1226   for (claimed_file &F : Modules) {
1227     PluginInputFile InputFile(F.handle);
1228     const void *View = getSymbolsAndView(F);
1229     if (!View)
1230       continue;
1231     if (linkInModule(Context, L, F, View, InputFile.file(), ApiFile,
1232                      Internalize, Maybe))
1233       message(LDPL_FATAL, "Failed to link module");
1234   }
1235 
1236   for (const auto &Name : Internalize) {
1237     GlobalValue *GV = Combined->getNamedValue(Name.first());
1238     if (GV)
1239       internalize(*GV);
1240   }
1241 
1242   for (const auto &Name : Maybe) {
1243     GlobalValue *GV = Combined->getNamedValue(Name.first());
1244     if (!GV)
1245       continue;
1246     GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
1247     if (canBeOmittedFromSymbolTable(GV))
1248       internalize(*GV);
1249   }
1250 
1251   if (options::TheOutputType == options::OT_DISABLE)
1252     return LDPS_OK;
1253 
1254   if (options::TheOutputType != options::OT_NORMAL) {
1255     std::string path;
1256     if (options::TheOutputType == options::OT_BC_ONLY)
1257       path = output_name;
1258     else
1259       path = output_name + ".bc";
1260     saveBCFile(path, *Combined);
1261     if (options::TheOutputType == options::OT_BC_ONLY)
1262       return LDPS_OK;
1263   }
1264 
1265   CodeGen codeGen(std::move(Combined));
1266   codeGen.runAll();
1267 
1268   if (!options::extra_library_path.empty() &&
1269       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
1270     message(LDPL_FATAL, "Unable to set the extra library path.");
1271 
1272   return LDPS_OK;
1273 }
1274 
1275 static ld_plugin_status all_symbols_read_hook(void) {
1276   ld_plugin_status Ret;
1277   if (!options::generate_api_file) {
1278     Ret = allSymbolsReadHook(nullptr);
1279   } else {
1280     std::error_code EC;
1281     raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
1282     if (EC)
1283       message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
1284               EC.message().c_str());
1285     Ret = allSymbolsReadHook(&ApiFile);
1286   }
1287 
1288   llvm_shutdown();
1289 
1290   if (options::TheOutputType == options::OT_BC_ONLY ||
1291       options::TheOutputType == options::OT_DISABLE) {
1292     if (options::TheOutputType == options::OT_DISABLE) {
1293       // Remove the output file here since ld.bfd creates the output file
1294       // early.
1295       std::error_code EC = sys::fs::remove(output_name);
1296       if (EC)
1297         message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
1298                 EC.message().c_str());
1299     }
1300     exit(0);
1301   }
1302 
1303   return Ret;
1304 }
1305 
1306 static ld_plugin_status cleanup_hook(void) {
1307   for (std::string &Name : Cleanup) {
1308     std::error_code EC = sys::fs::remove(Name);
1309     if (EC)
1310       message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
1311               EC.message().c_str());
1312   }
1313 
1314   return LDPS_OK;
1315 }
1316