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