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