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/ADT/Statistic.h"
16 #include "llvm/Bitcode/BitcodeReader.h"
17 #include "llvm/Bitcode/BitcodeWriter.h"
18 #include "llvm/CodeGen/CommandFlags.h"
19 #include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/LTO/Caching.h"
23 #include "llvm/LTO/LTO.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/TargetSelect.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <list>
31 #include <map>
32 #include <plugin-api.h>
33 #include <string>
34 #include <system_error>
35 #include <utility>
36 #include <vector>
37 
38 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
39 // Precise and Debian Wheezy (binutils 2.23 is required)
40 #define LDPO_PIE 3
41 
42 #define LDPT_GET_SYMBOLS_V3 28
43 
44 using namespace llvm;
45 using namespace lto;
46 
47 static ld_plugin_status discard_message(int level, const char *format, ...) {
48   // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
49   // callback in the transfer vector. This should never be called.
50   abort();
51 }
52 
53 static ld_plugin_release_input_file release_input_file = nullptr;
54 static ld_plugin_get_input_file get_input_file = nullptr;
55 static ld_plugin_message message = discard_message;
56 
57 namespace {
58 struct claimed_file {
59   void *handle;
60   void *leader_handle;
61   std::vector<ld_plugin_symbol> syms;
62   off_t filesize;
63   std::string name;
64 };
65 
66 /// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
67 struct PluginInputFile {
68   void *Handle;
69   std::unique_ptr<ld_plugin_input_file> File;
70 
71   PluginInputFile(void *Handle) : Handle(Handle) {
72     File = llvm::make_unique<ld_plugin_input_file>();
73     if (get_input_file(Handle, File.get()) != LDPS_OK)
74       message(LDPL_FATAL, "Failed to get file information");
75   }
76   ~PluginInputFile() {
77     // File would have been reset to nullptr if we moved this object
78     // to a new owner.
79     if (File)
80       if (release_input_file(Handle) != LDPS_OK)
81         message(LDPL_FATAL, "Failed to release file information");
82   }
83 
84   ld_plugin_input_file &file() { return *File; }
85 
86   PluginInputFile(PluginInputFile &&RHS) = default;
87   PluginInputFile &operator=(PluginInputFile &&RHS) = default;
88 };
89 
90 struct ResolutionInfo {
91   bool CanOmitFromDynSym = true;
92   bool DefaultVisibility = true;
93 };
94 
95 }
96 
97 static ld_plugin_add_symbols add_symbols = nullptr;
98 static ld_plugin_get_symbols get_symbols = nullptr;
99 static ld_plugin_add_input_file add_input_file = nullptr;
100 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
101 static ld_plugin_get_view get_view = nullptr;
102 static bool IsExecutable = false;
103 static Optional<Reloc::Model> RelocationModel;
104 static std::string output_name = "";
105 static std::list<claimed_file> Modules;
106 static DenseMap<int, void *> FDToLeaderHandle;
107 static StringMap<ResolutionInfo> ResInfo;
108 static std::vector<std::string> Cleanup;
109 
110 namespace options {
111   enum OutputType {
112     OT_NORMAL,
113     OT_DISABLE,
114     OT_BC_ONLY,
115     OT_SAVE_TEMPS
116   };
117   static OutputType TheOutputType = OT_NORMAL;
118   static unsigned OptLevel = 2;
119   // Default parallelism of 0 used to indicate that user did not specify.
120   // Actual parallelism default value depends on implementation.
121   // Currently only affects ThinLTO, where the default is
122   // llvm::heavyweight_hardware_concurrency.
123   static unsigned Parallelism = 0;
124   // Default regular LTO codegen parallelism (number of partitions).
125   static unsigned ParallelCodeGenParallelismLevel = 1;
126 #ifdef NDEBUG
127   static bool DisableVerify = true;
128 #else
129   static bool DisableVerify = false;
130 #endif
131   static std::string obj_path;
132   static std::string extra_library_path;
133   static std::string triple;
134   static std::string mcpu;
135   // When the thinlto plugin option is specified, only read the function
136   // the information from intermediate files and write a combined
137   // global index for the ThinLTO backends.
138   static bool thinlto = false;
139   // If false, all ThinLTO backend compilations through code gen are performed
140   // using multiple threads in the gold-plugin, before handing control back to
141   // gold. If true, write individual backend index files which reflect
142   // the import decisions, and exit afterwards. The assumption is
143   // that the build system will launch the backend processes.
144   static bool thinlto_index_only = false;
145   // If non-empty, holds the name of a file in which to write the list of
146   // oject files gold selected for inclusion in the link after symbol
147   // resolution (i.e. they had selected symbols). This will only be non-empty
148   // in the thinlto_index_only case. It is used to identify files, which may
149   // have originally been within archive libraries specified via
150   // --start-lib/--end-lib pairs, that should be included in the final
151   // native link process (since intervening function importing and inlining
152   // may change the symbol resolution detected in the final link and which
153   // files to include out of --start-lib/--end-lib libraries as a result).
154   static std::string thinlto_linked_objects_file;
155   // If true, when generating individual index files for distributed backends,
156   // also generate a "${bitcodefile}.imports" file at the same location for each
157   // bitcode file, listing the files it imports from in plain text. This is to
158   // support distributed build file staging.
159   static bool thinlto_emit_imports_files = false;
160   // Option to control where files for a distributed backend (the individual
161   // index files and optional imports files) are created.
162   // If specified, expects a string of the form "oldprefix:newprefix", and
163   // instead of generating these files in the same directory path as the
164   // corresponding bitcode file, will use a path formed by replacing the
165   // bitcode file's path prefix matching oldprefix with newprefix.
166   static std::string thinlto_prefix_replace;
167   // Optional path to a directory for caching ThinLTO objects.
168   static std::string cache_dir;
169   // Additional options to pass into the code generator.
170   // Note: This array will contain all plugin options which are not claimed
171   // as plugin exclusive to pass to the code generator.
172   static std::vector<const char *> extra;
173   // Sample profile file path
174   static std::string sample_profile;
175 
176   static void process_plugin_option(const char *opt_)
177   {
178     if (opt_ == nullptr)
179       return;
180     llvm::StringRef opt = opt_;
181 
182     if (opt.startswith("mcpu=")) {
183       mcpu = opt.substr(strlen("mcpu="));
184     } else if (opt.startswith("extra-library-path=")) {
185       extra_library_path = opt.substr(strlen("extra_library_path="));
186     } else if (opt.startswith("mtriple=")) {
187       triple = opt.substr(strlen("mtriple="));
188     } else if (opt.startswith("obj-path=")) {
189       obj_path = opt.substr(strlen("obj-path="));
190     } else if (opt == "emit-llvm") {
191       TheOutputType = OT_BC_ONLY;
192     } else if (opt == "save-temps") {
193       TheOutputType = OT_SAVE_TEMPS;
194     } else if (opt == "disable-output") {
195       TheOutputType = OT_DISABLE;
196     } else if (opt == "thinlto") {
197       thinlto = true;
198     } else if (opt == "thinlto-index-only") {
199       thinlto_index_only = true;
200     } else if (opt.startswith("thinlto-index-only=")) {
201       thinlto_index_only = true;
202       thinlto_linked_objects_file = opt.substr(strlen("thinlto-index-only="));
203     } else if (opt == "thinlto-emit-imports-files") {
204       thinlto_emit_imports_files = true;
205     } else if (opt.startswith("thinlto-prefix-replace=")) {
206       thinlto_prefix_replace = opt.substr(strlen("thinlto-prefix-replace="));
207       if (thinlto_prefix_replace.find(';') == std::string::npos)
208         message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");
209     } else if (opt.startswith("cache-dir=")) {
210       cache_dir = opt.substr(strlen("cache-dir="));
211     } else if (opt.size() == 2 && opt[0] == 'O') {
212       if (opt[1] < '0' || opt[1] > '3')
213         message(LDPL_FATAL, "Optimization level must be between 0 and 3");
214       OptLevel = opt[1] - '0';
215     } else if (opt.startswith("jobs=")) {
216       if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
217         message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
218     } else if (opt.startswith("lto-partitions=")) {
219       if (opt.substr(strlen("lto-partitions="))
220               .getAsInteger(10, ParallelCodeGenParallelismLevel))
221         message(LDPL_FATAL, "Invalid codegen partition level: %s", opt_ + 5);
222     } else if (opt == "disable-verify") {
223       DisableVerify = true;
224     } else if (opt.startswith("sample-profile=")) {
225       sample_profile= opt.substr(strlen("sample-profile="));
226     } else {
227       // Save this option to pass to the code generator.
228       // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
229       // add that.
230       if (extra.empty())
231         extra.push_back("LLVMgold");
232 
233       extra.push_back(opt_);
234     }
235   }
236 }
237 
238 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
239                                         int *claimed);
240 static ld_plugin_status all_symbols_read_hook(void);
241 static ld_plugin_status cleanup_hook(void);
242 
243 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
244 ld_plugin_status onload(ld_plugin_tv *tv) {
245   InitializeAllTargetInfos();
246   InitializeAllTargets();
247   InitializeAllTargetMCs();
248   InitializeAllAsmParsers();
249   InitializeAllAsmPrinters();
250 
251   // We're given a pointer to the first transfer vector. We read through them
252   // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
253   // contain pointers to functions that we need to call to register our own
254   // hooks. The others are addresses of functions we can use to call into gold
255   // for services.
256 
257   bool registeredClaimFile = false;
258   bool RegisteredAllSymbolsRead = false;
259 
260   for (; tv->tv_tag != LDPT_NULL; ++tv) {
261     // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
262     // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
263     // header.
264     switch (static_cast<int>(tv->tv_tag)) {
265     case LDPT_OUTPUT_NAME:
266       output_name = tv->tv_u.tv_string;
267       break;
268     case LDPT_LINKER_OUTPUT:
269       switch (tv->tv_u.tv_val) {
270       case LDPO_REL: // .o
271       case LDPO_DYN: // .so
272         IsExecutable = false;
273         RelocationModel = Reloc::PIC_;
274         break;
275       case LDPO_PIE: // position independent executable
276         IsExecutable = true;
277         RelocationModel = Reloc::PIC_;
278         break;
279       case LDPO_EXEC: // .exe
280         IsExecutable = true;
281         RelocationModel = Reloc::Static;
282         break;
283       default:
284         message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
285         return LDPS_ERR;
286       }
287       break;
288     case LDPT_OPTION:
289       options::process_plugin_option(tv->tv_u.tv_string);
290       break;
291     case LDPT_REGISTER_CLAIM_FILE_HOOK: {
292       ld_plugin_register_claim_file callback;
293       callback = tv->tv_u.tv_register_claim_file;
294 
295       if (callback(claim_file_hook) != LDPS_OK)
296         return LDPS_ERR;
297 
298       registeredClaimFile = true;
299     } break;
300     case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
301       ld_plugin_register_all_symbols_read callback;
302       callback = tv->tv_u.tv_register_all_symbols_read;
303 
304       if (callback(all_symbols_read_hook) != LDPS_OK)
305         return LDPS_ERR;
306 
307       RegisteredAllSymbolsRead = true;
308     } break;
309     case LDPT_REGISTER_CLEANUP_HOOK: {
310       ld_plugin_register_cleanup callback;
311       callback = tv->tv_u.tv_register_cleanup;
312 
313       if (callback(cleanup_hook) != LDPS_OK)
314         return LDPS_ERR;
315     } break;
316     case LDPT_GET_INPUT_FILE:
317       get_input_file = tv->tv_u.tv_get_input_file;
318       break;
319     case LDPT_RELEASE_INPUT_FILE:
320       release_input_file = tv->tv_u.tv_release_input_file;
321       break;
322     case LDPT_ADD_SYMBOLS:
323       add_symbols = tv->tv_u.tv_add_symbols;
324       break;
325     case LDPT_GET_SYMBOLS_V2:
326       // Do not override get_symbols_v3 with get_symbols_v2.
327       if (!get_symbols)
328         get_symbols = tv->tv_u.tv_get_symbols;
329       break;
330     case LDPT_GET_SYMBOLS_V3:
331       get_symbols = tv->tv_u.tv_get_symbols;
332       break;
333     case LDPT_ADD_INPUT_FILE:
334       add_input_file = tv->tv_u.tv_add_input_file;
335       break;
336     case LDPT_SET_EXTRA_LIBRARY_PATH:
337       set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
338       break;
339     case LDPT_GET_VIEW:
340       get_view = tv->tv_u.tv_get_view;
341       break;
342     case LDPT_MESSAGE:
343       message = tv->tv_u.tv_message;
344       break;
345     default:
346       break;
347     }
348   }
349 
350   if (!registeredClaimFile) {
351     message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
352     return LDPS_ERR;
353   }
354   if (!add_symbols) {
355     message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
356     return LDPS_ERR;
357   }
358 
359   if (!RegisteredAllSymbolsRead)
360     return LDPS_OK;
361 
362   if (!get_input_file) {
363     message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
364     return LDPS_ERR;
365   }
366   if (!release_input_file) {
367     message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
368     return LDPS_ERR;
369   }
370 
371   return LDPS_OK;
372 }
373 
374 static void diagnosticHandler(const DiagnosticInfo &DI) {
375   std::string ErrStorage;
376   {
377     raw_string_ostream OS(ErrStorage);
378     DiagnosticPrinterRawOStream DP(OS);
379     DI.print(DP);
380   }
381   ld_plugin_level Level;
382   switch (DI.getSeverity()) {
383   case DS_Error:
384     message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
385             ErrStorage.c_str());
386   case DS_Warning:
387     Level = LDPL_WARNING;
388     break;
389   case DS_Note:
390   case DS_Remark:
391     Level = LDPL_INFO;
392     break;
393   }
394   message(Level, "LLVM gold plugin: %s",  ErrStorage.c_str());
395 }
396 
397 static void check(Error E, std::string Msg = "LLVM gold plugin") {
398   handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
399     message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());
400     return Error::success();
401   });
402 }
403 
404 template <typename T> static T check(Expected<T> E) {
405   if (E)
406     return std::move(*E);
407   check(E.takeError());
408   return T();
409 }
410 
411 /// Called by gold to see whether this file is one that our plugin can handle.
412 /// We'll try to open it and register all the symbols with add_symbol if
413 /// possible.
414 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
415                                         int *claimed) {
416   MemoryBufferRef BufferRef;
417   std::unique_ptr<MemoryBuffer> Buffer;
418   if (get_view) {
419     const void *view;
420     if (get_view(file->handle, &view) != LDPS_OK) {
421       message(LDPL_ERROR, "Failed to get a view of %s", file->name);
422       return LDPS_ERR;
423     }
424     BufferRef =
425         MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
426   } else {
427     int64_t offset = 0;
428     // Gold has found what might be IR part-way inside of a file, such as
429     // an .a archive.
430     if (file->offset) {
431       offset = file->offset;
432     }
433     ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
434         MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
435                                        offset);
436     if (std::error_code EC = BufferOrErr.getError()) {
437       message(LDPL_ERROR, EC.message().c_str());
438       return LDPS_ERR;
439     }
440     Buffer = std::move(BufferOrErr.get());
441     BufferRef = Buffer->getMemBufferRef();
442   }
443 
444   *claimed = 1;
445 
446   Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
447   if (!ObjOrErr) {
448     handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {
449       std::error_code EC = EI.convertToErrorCode();
450       if (EC == object::object_error::invalid_file_type ||
451           EC == object::object_error::bitcode_section_not_found)
452         *claimed = 0;
453       else
454         message(LDPL_ERROR,
455                 "LLVM gold plugin has failed to create LTO module: %s",
456                 EI.message().c_str());
457     });
458 
459     return *claimed ? LDPS_ERR : LDPS_OK;
460   }
461 
462   std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);
463 
464   Modules.resize(Modules.size() + 1);
465   claimed_file &cf = Modules.back();
466 
467   cf.handle = file->handle;
468   // Keep track of the first handle for each file descriptor, since there are
469   // multiple in the case of an archive. This is used later in the case of
470   // ThinLTO parallel backends to ensure that each file is only opened and
471   // released once.
472   auto LeaderHandle =
473       FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
474   cf.leader_handle = LeaderHandle->second;
475   // Save the filesize since for parallel ThinLTO backends we can only
476   // invoke get_input_file once per archive (only for the leader handle).
477   cf.filesize = file->filesize;
478   // In the case of an archive library, all but the first member must have a
479   // non-zero offset, which we can append to the file name to obtain a
480   // unique name.
481   cf.name = file->name;
482   if (file->offset)
483     cf.name += ".llvm." + std::to_string(file->offset) + "." +
484                sys::path::filename(Obj->getSourceFileName()).str();
485 
486   for (auto &Sym : Obj->symbols()) {
487     uint32_t Symflags = Sym.getFlags();
488 
489     cf.syms.push_back(ld_plugin_symbol());
490     ld_plugin_symbol &sym = cf.syms.back();
491     sym.version = nullptr;
492     StringRef Name = Sym.getName();
493     sym.name = strdup(Name.str().c_str());
494 
495     ResolutionInfo &Res = ResInfo[Name];
496 
497     Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();
498 
499     sym.visibility = LDPV_DEFAULT;
500     GlobalValue::VisibilityTypes Vis = Sym.getVisibility();
501     if (Vis != GlobalValue::DefaultVisibility)
502       Res.DefaultVisibility = false;
503     switch (Vis) {
504     case GlobalValue::DefaultVisibility:
505       break;
506     case GlobalValue::HiddenVisibility:
507       sym.visibility = LDPV_HIDDEN;
508       break;
509     case GlobalValue::ProtectedVisibility:
510       sym.visibility = LDPV_PROTECTED;
511       break;
512     }
513 
514     if (Symflags & object::BasicSymbolRef::SF_Undefined) {
515       sym.def = LDPK_UNDEF;
516       if (Symflags & object::BasicSymbolRef::SF_Weak)
517         sym.def = LDPK_WEAKUNDEF;
518     } else if (Symflags & object::BasicSymbolRef::SF_Common)
519       sym.def = LDPK_COMMON;
520     else if (Symflags & object::BasicSymbolRef::SF_Weak)
521       sym.def = LDPK_WEAKDEF;
522     else
523       sym.def = LDPK_DEF;
524 
525     sym.size = 0;
526     sym.comdat_key = nullptr;
527     int CI = check(Sym.getComdatIndex());
528     if (CI != -1) {
529       StringRef C = Obj->getComdatTable()[CI];
530       sym.comdat_key = strdup(C.str().c_str());
531     }
532 
533     sym.resolution = LDPR_UNKNOWN;
534   }
535 
536   if (!cf.syms.empty()) {
537     if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
538       message(LDPL_ERROR, "Unable to add symbols!");
539       return LDPS_ERR;
540     }
541   }
542 
543   return LDPS_OK;
544 }
545 
546 static void freeSymName(ld_plugin_symbol &Sym) {
547   free(Sym.name);
548   free(Sym.comdat_key);
549   Sym.name = nullptr;
550   Sym.comdat_key = nullptr;
551 }
552 
553 /// Helper to get a file's symbols and a view into it via gold callbacks.
554 static const void *getSymbolsAndView(claimed_file &F) {
555   ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
556   if (status == LDPS_NO_SYMS)
557     return nullptr;
558 
559   if (status != LDPS_OK)
560     message(LDPL_FATAL, "Failed to get symbol information");
561 
562   const void *View;
563   if (get_view(F.handle, &View) != LDPS_OK)
564     message(LDPL_FATAL, "Failed to get a view of file");
565 
566   return View;
567 }
568 
569 static void addModule(LTO &Lto, claimed_file &F, const void *View) {
570   MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize), F.name);
571   Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
572 
573   if (!ObjOrErr)
574     message(LDPL_FATAL, "Could not read bitcode from file : %s",
575             toString(ObjOrErr.takeError()).c_str());
576 
577   unsigned SymNum = 0;
578   std::vector<SymbolResolution> Resols(F.syms.size());
579   for (ld_plugin_symbol &Sym : F.syms) {
580     SymbolResolution &R = Resols[SymNum++];
581 
582     ld_plugin_symbol_resolution Resolution =
583         (ld_plugin_symbol_resolution)Sym.resolution;
584 
585     ResolutionInfo &Res = ResInfo[Sym.name];
586 
587     switch (Resolution) {
588     case LDPR_UNKNOWN:
589       llvm_unreachable("Unexpected resolution");
590 
591     case LDPR_RESOLVED_IR:
592     case LDPR_RESOLVED_EXEC:
593     case LDPR_RESOLVED_DYN:
594     case LDPR_PREEMPTED_IR:
595     case LDPR_PREEMPTED_REG:
596     case LDPR_UNDEF:
597       break;
598 
599     case LDPR_PREVAILING_DEF_IRONLY:
600       R.Prevailing = true;
601       break;
602 
603     case LDPR_PREVAILING_DEF:
604       R.Prevailing = true;
605       R.VisibleToRegularObj = true;
606       break;
607 
608     case LDPR_PREVAILING_DEF_IRONLY_EXP:
609       R.Prevailing = true;
610       if (!Res.CanOmitFromDynSym)
611         R.VisibleToRegularObj = true;
612       break;
613     }
614 
615     if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
616         (IsExecutable || !Res.DefaultVisibility))
617       R.FinalDefinitionInLinkageUnit = true;
618 
619     freeSymName(Sym);
620   }
621 
622   check(Lto.add(std::move(*ObjOrErr), Resols),
623         std::string("Failed to link module ") + F.name);
624 }
625 
626 static void recordFile(std::string Filename, bool TempOutFile) {
627   if (add_input_file(Filename.c_str()) != LDPS_OK)
628     message(LDPL_FATAL,
629             "Unable to add .o file to the link. File left behind in: %s",
630             Filename.c_str());
631   if (TempOutFile)
632     Cleanup.push_back(Filename.c_str());
633 }
634 
635 /// Return the desired output filename given a base input name, a flag
636 /// indicating whether a temp file should be generated, and an optional task id.
637 /// The new filename generated is returned in \p NewFilename.
638 static void getOutputFileName(SmallString<128> InFilename, bool TempOutFile,
639                               SmallString<128> &NewFilename, int TaskID) {
640   if (TempOutFile) {
641     std::error_code EC =
642         sys::fs::createTemporaryFile("lto-llvm", "o", NewFilename);
643     if (EC)
644       message(LDPL_FATAL, "Could not create temporary file: %s",
645               EC.message().c_str());
646   } else {
647     NewFilename = InFilename;
648     if (TaskID > 0)
649       NewFilename += utostr(TaskID);
650   }
651 }
652 
653 static CodeGenOpt::Level getCGOptLevel() {
654   switch (options::OptLevel) {
655   case 0:
656     return CodeGenOpt::None;
657   case 1:
658     return CodeGenOpt::Less;
659   case 2:
660     return CodeGenOpt::Default;
661   case 3:
662     return CodeGenOpt::Aggressive;
663   }
664   llvm_unreachable("Invalid optimization level");
665 }
666 
667 /// Parse the thinlto_prefix_replace option into the \p OldPrefix and
668 /// \p NewPrefix strings, if it was specified.
669 static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
670                                       std::string &NewPrefix) {
671   StringRef PrefixReplace = options::thinlto_prefix_replace;
672   assert(PrefixReplace.empty() || PrefixReplace.find(";") != StringRef::npos);
673   std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
674   OldPrefix = Split.first.str();
675   NewPrefix = Split.second.str();
676 }
677 
678 static std::unique_ptr<LTO> createLTO() {
679   Config Conf;
680   ThinBackend Backend;
681 
682   Conf.CPU = options::mcpu;
683   Conf.Options = InitTargetOptionsFromCodeGenFlags();
684 
685   // Disable the new X86 relax relocations since gold might not support them.
686   // FIXME: Check the gold version or add a new option to enable them.
687   Conf.Options.RelaxELFRelocations = false;
688 
689   Conf.MAttrs = MAttrs;
690   Conf.RelocModel = *RelocationModel;
691   Conf.CGOptLevel = getCGOptLevel();
692   Conf.DisableVerify = options::DisableVerify;
693   Conf.OptLevel = options::OptLevel;
694   if (options::Parallelism)
695     Backend = createInProcessThinBackend(options::Parallelism);
696   if (options::thinlto_index_only) {
697     std::string OldPrefix, NewPrefix;
698     getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
699     Backend = createWriteIndexesThinBackend(
700         OldPrefix, NewPrefix, options::thinlto_emit_imports_files,
701         options::thinlto_linked_objects_file);
702   }
703 
704   Conf.OverrideTriple = options::triple;
705   Conf.DefaultTriple = sys::getDefaultTargetTriple();
706 
707   Conf.DiagHandler = diagnosticHandler;
708 
709   switch (options::TheOutputType) {
710   case options::OT_NORMAL:
711     break;
712 
713   case options::OT_DISABLE:
714     Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
715     break;
716 
717   case options::OT_BC_ONLY:
718     Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
719       std::error_code EC;
720       raw_fd_ostream OS(output_name, EC, sys::fs::OpenFlags::F_None);
721       if (EC)
722         message(LDPL_FATAL, "Failed to write the output file.");
723       WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ false);
724       return false;
725     };
726     break;
727 
728   case options::OT_SAVE_TEMPS:
729     check(Conf.addSaveTemps(output_name + ".",
730                             /* UseInputModulePath */ true));
731     break;
732   }
733 
734   if (!options::sample_profile.empty())
735     Conf.SampleProfile = options::sample_profile;
736 
737   return llvm::make_unique<LTO>(std::move(Conf), Backend,
738                                 options::ParallelCodeGenParallelismLevel);
739 }
740 
741 // Write empty files that may be expected by a distributed build
742 // system when invoked with thinlto_index_only. This is invoked when
743 // the linker has decided not to include the given module in the
744 // final link. Frequently the distributed build system will want to
745 // confirm that all expected outputs are created based on all of the
746 // modules provided to the linker.
747 static void writeEmptyDistributedBuildOutputs(std::string &ModulePath,
748                                               std::string &OldPrefix,
749                                               std::string &NewPrefix) {
750   std::string NewModulePath =
751       getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
752   std::error_code EC;
753   {
754     raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
755                       sys::fs::OpenFlags::F_None);
756     if (EC)
757       message(LDPL_FATAL, "Failed to write '%s': %s",
758               (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
759   }
760   if (options::thinlto_emit_imports_files) {
761     raw_fd_ostream OS(NewModulePath + ".imports", EC,
762                       sys::fs::OpenFlags::F_None);
763     if (EC)
764       message(LDPL_FATAL, "Failed to write '%s': %s",
765               (NewModulePath + ".imports").c_str(), EC.message().c_str());
766   }
767 }
768 
769 /// gold informs us that all symbols have been read. At this point, we use
770 /// get_symbols to see if any of our definitions have been overridden by a
771 /// native object file. Then, perform optimization and codegen.
772 static ld_plugin_status allSymbolsReadHook() {
773   if (Modules.empty())
774     return LDPS_OK;
775 
776   if (unsigned NumOpts = options::extra.size())
777     cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
778 
779   // Map to own RAII objects that manage the file opening and releasing
780   // interfaces with gold. This is needed only for ThinLTO mode, since
781   // unlike regular LTO, where addModule will result in the opened file
782   // being merged into a new combined module, we need to keep these files open
783   // through Lto->run().
784   DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
785 
786   std::unique_ptr<LTO> Lto = createLTO();
787 
788   std::string OldPrefix, NewPrefix;
789   if (options::thinlto_index_only)
790     getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
791 
792   for (claimed_file &F : Modules) {
793     if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
794       HandleToInputFile.insert(std::make_pair(
795           F.leader_handle, llvm::make_unique<PluginInputFile>(F.handle)));
796     const void *View = getSymbolsAndView(F);
797     if (!View) {
798       if (options::thinlto_index_only)
799         // Write empty output files that may be expected by the distributed
800         // build system.
801         writeEmptyDistributedBuildOutputs(F.name, OldPrefix, NewPrefix);
802       continue;
803     }
804     addModule(*Lto, F, View);
805   }
806 
807   SmallString<128> Filename;
808   // Note that getOutputFileName will append a unique ID for each task
809   if (!options::obj_path.empty())
810     Filename = options::obj_path;
811   else if (options::TheOutputType == options::OT_SAVE_TEMPS)
812     Filename = output_name + ".o";
813   bool SaveTemps = !Filename.empty();
814 
815   size_t MaxTasks = Lto->getMaxTasks();
816   std::vector<uintptr_t> IsTemporary(MaxTasks);
817   std::vector<SmallString<128>> Filenames(MaxTasks);
818 
819   auto AddStream =
820       [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
821     IsTemporary[Task] = !SaveTemps;
822     getOutputFileName(Filename, /*TempOutFile=*/!SaveTemps, Filenames[Task],
823                       Task);
824     int FD;
825     std::error_code EC =
826         sys::fs::openFileForWrite(Filenames[Task], FD, sys::fs::F_None);
827     if (EC)
828       message(LDPL_FATAL, "Could not open file %s: %s", Filenames[Task].c_str(),
829               EC.message().c_str());
830     return llvm::make_unique<lto::NativeObjectStream>(
831         llvm::make_unique<llvm::raw_fd_ostream>(FD, true));
832   };
833 
834   auto AddFile = [&](size_t Task, StringRef Path) { Filenames[Task] = Path; };
835 
836   NativeObjectCache Cache;
837   if (!options::cache_dir.empty())
838     Cache = check(localCache(options::cache_dir, AddFile));
839 
840   check(Lto->run(AddStream, Cache));
841 
842   if (options::TheOutputType == options::OT_DISABLE ||
843       options::TheOutputType == options::OT_BC_ONLY)
844     return LDPS_OK;
845 
846   if (options::thinlto_index_only) {
847     if (llvm::AreStatisticsEnabled())
848       llvm::PrintStatistics();
849     cleanup_hook();
850     exit(0);
851   }
852 
853   for (unsigned I = 0; I != MaxTasks; ++I)
854     if (!Filenames[I].empty())
855       recordFile(Filenames[I].str(), IsTemporary[I]);
856 
857   if (!options::extra_library_path.empty() &&
858       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
859     message(LDPL_FATAL, "Unable to set the extra library path.");
860 
861   return LDPS_OK;
862 }
863 
864 static ld_plugin_status all_symbols_read_hook(void) {
865   ld_plugin_status Ret = allSymbolsReadHook();
866   llvm_shutdown();
867 
868   if (options::TheOutputType == options::OT_BC_ONLY ||
869       options::TheOutputType == options::OT_DISABLE) {
870     if (options::TheOutputType == options::OT_DISABLE) {
871       // Remove the output file here since ld.bfd creates the output file
872       // early.
873       std::error_code EC = sys::fs::remove(output_name);
874       if (EC)
875         message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
876                 EC.message().c_str());
877     }
878     exit(0);
879   }
880 
881   return Ret;
882 }
883 
884 static ld_plugin_status cleanup_hook(void) {
885   for (std::string &Name : Cleanup) {
886     std::error_code EC = sys::fs::remove(Name);
887     if (EC)
888       message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
889               EC.message().c_str());
890   }
891 
892   return LDPS_OK;
893 }
894