Revert r354244 "[DAGCombiner] Eliminate dead stores to stack."
[llvm-complete.git] / tools / gold / gold-plugin.cpp
blob626fb5f636347eaaebe44ae587541d35a45ca797
1 //===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This is a gold plugin for LLVM. It provides an LLVM implementation of the
10 // interface described in http://gcc.gnu.org/wiki/whopr/driver .
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/Statistic.h"
15 #include "llvm/Bitcode/BitcodeReader.h"
16 #include "llvm/Bitcode/BitcodeWriter.h"
17 #include "llvm/CodeGen/CommandFlags.inc"
18 #include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/LTO/Caching.h"
22 #include "llvm/LTO/LTO.h"
23 #include "llvm/Object/Error.h"
24 #include "llvm/Support/CachePruning.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>
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
44 #define LDPT_GET_SYMBOLS_V3 28
46 // FIXME: Remove when binutils 2.31 (containing gold 1.16) is the minimum
47 // required version.
48 #define LDPT_GET_WRAP_SYMBOLS 32
50 using namespace llvm;
51 using namespace lto;
53 // FIXME: Remove when binutils 2.31 (containing gold 1.16) is the minimum
54 // required version.
55 typedef enum ld_plugin_status (*ld_plugin_get_wrap_symbols)(
56 uint64_t *num_symbols, const char ***wrap_symbol_list);
58 static ld_plugin_status discard_message(int level, const char *format, ...) {
59 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
60 // callback in the transfer vector. This should never be called.
61 abort();
64 static ld_plugin_release_input_file release_input_file = nullptr;
65 static ld_plugin_get_input_file get_input_file = nullptr;
66 static ld_plugin_message message = discard_message;
67 static ld_plugin_get_wrap_symbols get_wrap_symbols = nullptr;
69 namespace {
70 struct claimed_file {
71 void *handle;
72 void *leader_handle;
73 std::vector<ld_plugin_symbol> syms;
74 off_t filesize;
75 std::string name;
78 /// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
79 struct PluginInputFile {
80 void *Handle;
81 std::unique_ptr<ld_plugin_input_file> File;
83 PluginInputFile(void *Handle) : Handle(Handle) {
84 File = llvm::make_unique<ld_plugin_input_file>();
85 if (get_input_file(Handle, File.get()) != LDPS_OK)
86 message(LDPL_FATAL, "Failed to get file information");
88 ~PluginInputFile() {
89 // File would have been reset to nullptr if we moved this object
90 // to a new owner.
91 if (File)
92 if (release_input_file(Handle) != LDPS_OK)
93 message(LDPL_FATAL, "Failed to release file information");
96 ld_plugin_input_file &file() { return *File; }
98 PluginInputFile(PluginInputFile &&RHS) = default;
99 PluginInputFile &operator=(PluginInputFile &&RHS) = default;
102 struct ResolutionInfo {
103 bool CanOmitFromDynSym = true;
104 bool DefaultVisibility = true;
105 bool CanInline = true;
106 bool IsUsedInRegularObj = false;
111 static ld_plugin_add_symbols add_symbols = nullptr;
112 static ld_plugin_get_symbols get_symbols = nullptr;
113 static ld_plugin_add_input_file add_input_file = nullptr;
114 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
115 static ld_plugin_get_view get_view = nullptr;
116 static bool IsExecutable = false;
117 static bool SplitSections = true;
118 static Optional<Reloc::Model> RelocationModel = None;
119 static std::string output_name = "";
120 static std::list<claimed_file> Modules;
121 static DenseMap<int, void *> FDToLeaderHandle;
122 static StringMap<ResolutionInfo> ResInfo;
123 static std::vector<std::string> Cleanup;
125 namespace options {
126 enum OutputType {
127 OT_NORMAL,
128 OT_DISABLE,
129 OT_BC_ONLY,
130 OT_ASM_ONLY,
131 OT_SAVE_TEMPS
133 static OutputType TheOutputType = OT_NORMAL;
134 static unsigned OptLevel = 2;
135 // Default parallelism of 0 used to indicate that user did not specify.
136 // Actual parallelism default value depends on implementation.
137 // Currently only affects ThinLTO, where the default is
138 // llvm::heavyweight_hardware_concurrency.
139 static unsigned Parallelism = 0;
140 // Default regular LTO codegen parallelism (number of partitions).
141 static unsigned ParallelCodeGenParallelismLevel = 1;
142 #ifdef NDEBUG
143 static bool DisableVerify = true;
144 #else
145 static bool DisableVerify = false;
146 #endif
147 static std::string obj_path;
148 static std::string extra_library_path;
149 static std::string triple;
150 static std::string mcpu;
151 // When the thinlto plugin option is specified, only read the function
152 // the information from intermediate files and write a combined
153 // global index for the ThinLTO backends.
154 static bool thinlto = false;
155 // If false, all ThinLTO backend compilations through code gen are performed
156 // using multiple threads in the gold-plugin, before handing control back to
157 // gold. If true, write individual backend index files which reflect
158 // the import decisions, and exit afterwards. The assumption is
159 // that the build system will launch the backend processes.
160 static bool thinlto_index_only = false;
161 // If non-empty, holds the name of a file in which to write the list of
162 // oject files gold selected for inclusion in the link after symbol
163 // resolution (i.e. they had selected symbols). This will only be non-empty
164 // in the thinlto_index_only case. It is used to identify files, which may
165 // have originally been within archive libraries specified via
166 // --start-lib/--end-lib pairs, that should be included in the final
167 // native link process (since intervening function importing and inlining
168 // may change the symbol resolution detected in the final link and which
169 // files to include out of --start-lib/--end-lib libraries as a result).
170 static std::string thinlto_linked_objects_file;
171 // If true, when generating individual index files for distributed backends,
172 // also generate a "${bitcodefile}.imports" file at the same location for each
173 // bitcode file, listing the files it imports from in plain text. This is to
174 // support distributed build file staging.
175 static bool thinlto_emit_imports_files = false;
176 // Option to control where files for a distributed backend (the individual
177 // index files and optional imports files) are created.
178 // If specified, expects a string of the form "oldprefix:newprefix", and
179 // instead of generating these files in the same directory path as the
180 // corresponding bitcode file, will use a path formed by replacing the
181 // bitcode file's path prefix matching oldprefix with newprefix.
182 static std::string thinlto_prefix_replace;
183 // Option to control the name of modules encoded in the individual index
184 // files for a distributed backend. This enables the use of minimized
185 // bitcode files for the thin link, assuming the name of the full bitcode
186 // file used in the backend differs just in some part of the file suffix.
187 // If specified, expects a string of the form "oldsuffix:newsuffix".
188 static std::string thinlto_object_suffix_replace;
189 // Optional path to a directory for caching ThinLTO objects.
190 static std::string cache_dir;
191 // Optional pruning policy for ThinLTO caches.
192 static std::string cache_policy;
193 // Additional options to pass into the code generator.
194 // Note: This array will contain all plugin options which are not claimed
195 // as plugin exclusive to pass to the code generator.
196 static std::vector<const char *> extra;
197 // Sample profile file path
198 static std::string sample_profile;
199 // New pass manager
200 static bool new_pass_manager = false;
201 // Debug new pass manager
202 static bool debug_pass_manager = false;
203 // Directory to store the .dwo files.
204 static std::string dwo_dir;
205 /// Statistics output filename.
206 static std::string stats_file;
208 // Optimization remarks filename and hotness options
209 static std::string OptRemarksFilename;
210 static bool OptRemarksWithHotness = false;
212 static void process_plugin_option(const char *opt_)
214 if (opt_ == nullptr)
215 return;
216 llvm::StringRef opt = opt_;
218 if (opt.startswith("mcpu=")) {
219 mcpu = opt.substr(strlen("mcpu="));
220 } else if (opt.startswith("extra-library-path=")) {
221 extra_library_path = opt.substr(strlen("extra_library_path="));
222 } else if (opt.startswith("mtriple=")) {
223 triple = opt.substr(strlen("mtriple="));
224 } else if (opt.startswith("obj-path=")) {
225 obj_path = opt.substr(strlen("obj-path="));
226 } else if (opt == "emit-llvm") {
227 TheOutputType = OT_BC_ONLY;
228 } else if (opt == "save-temps") {
229 TheOutputType = OT_SAVE_TEMPS;
230 } else if (opt == "disable-output") {
231 TheOutputType = OT_DISABLE;
232 } else if (opt == "emit-asm") {
233 TheOutputType = OT_ASM_ONLY;
234 } else if (opt == "thinlto") {
235 thinlto = true;
236 } else if (opt == "thinlto-index-only") {
237 thinlto_index_only = true;
238 } else if (opt.startswith("thinlto-index-only=")) {
239 thinlto_index_only = true;
240 thinlto_linked_objects_file = opt.substr(strlen("thinlto-index-only="));
241 } else if (opt == "thinlto-emit-imports-files") {
242 thinlto_emit_imports_files = true;
243 } else if (opt.startswith("thinlto-prefix-replace=")) {
244 thinlto_prefix_replace = opt.substr(strlen("thinlto-prefix-replace="));
245 if (thinlto_prefix_replace.find(';') == std::string::npos)
246 message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");
247 } else if (opt.startswith("thinlto-object-suffix-replace=")) {
248 thinlto_object_suffix_replace =
249 opt.substr(strlen("thinlto-object-suffix-replace="));
250 if (thinlto_object_suffix_replace.find(';') == std::string::npos)
251 message(LDPL_FATAL,
252 "thinlto-object-suffix-replace expects 'old;new' format");
253 } else if (opt.startswith("cache-dir=")) {
254 cache_dir = opt.substr(strlen("cache-dir="));
255 } else if (opt.startswith("cache-policy=")) {
256 cache_policy = opt.substr(strlen("cache-policy="));
257 } else if (opt.size() == 2 && opt[0] == 'O') {
258 if (opt[1] < '0' || opt[1] > '3')
259 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
260 OptLevel = opt[1] - '0';
261 } else if (opt.startswith("jobs=")) {
262 if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
263 message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
264 } else if (opt.startswith("lto-partitions=")) {
265 if (opt.substr(strlen("lto-partitions="))
266 .getAsInteger(10, ParallelCodeGenParallelismLevel))
267 message(LDPL_FATAL, "Invalid codegen partition level: %s", opt_ + 5);
268 } else if (opt == "disable-verify") {
269 DisableVerify = true;
270 } else if (opt.startswith("sample-profile=")) {
271 sample_profile= opt.substr(strlen("sample-profile="));
272 } else if (opt == "new-pass-manager") {
273 new_pass_manager = true;
274 } else if (opt == "debug-pass-manager") {
275 debug_pass_manager = true;
276 } else if (opt.startswith("dwo_dir=")) {
277 dwo_dir = opt.substr(strlen("dwo_dir="));
278 } else if (opt.startswith("opt-remarks-filename=")) {
279 OptRemarksFilename = opt.substr(strlen("opt-remarks-filename="));
280 } else if (opt == "opt-remarks-with-hotness") {
281 OptRemarksWithHotness = true;
282 } else if (opt.startswith("stats-file=")) {
283 stats_file = opt.substr(strlen("stats-file="));
284 } else {
285 // Save this option to pass to the code generator.
286 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
287 // add that.
288 if (extra.empty())
289 extra.push_back("LLVMgold");
291 extra.push_back(opt_);
296 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
297 int *claimed);
298 static ld_plugin_status all_symbols_read_hook(void);
299 static ld_plugin_status cleanup_hook(void);
301 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
302 ld_plugin_status onload(ld_plugin_tv *tv) {
303 InitializeAllTargetInfos();
304 InitializeAllTargets();
305 InitializeAllTargetMCs();
306 InitializeAllAsmParsers();
307 InitializeAllAsmPrinters();
309 // We're given a pointer to the first transfer vector. We read through them
310 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
311 // contain pointers to functions that we need to call to register our own
312 // hooks. The others are addresses of functions we can use to call into gold
313 // for services.
315 bool registeredClaimFile = false;
316 bool RegisteredAllSymbolsRead = false;
318 for (; tv->tv_tag != LDPT_NULL; ++tv) {
319 // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
320 // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
321 // header.
322 switch (static_cast<int>(tv->tv_tag)) {
323 case LDPT_OUTPUT_NAME:
324 output_name = tv->tv_u.tv_string;
325 break;
326 case LDPT_LINKER_OUTPUT:
327 switch (tv->tv_u.tv_val) {
328 case LDPO_REL: // .o
329 IsExecutable = false;
330 SplitSections = false;
331 break;
332 case LDPO_DYN: // .so
333 IsExecutable = false;
334 RelocationModel = Reloc::PIC_;
335 break;
336 case LDPO_PIE: // position independent executable
337 IsExecutable = true;
338 RelocationModel = Reloc::PIC_;
339 break;
340 case LDPO_EXEC: // .exe
341 IsExecutable = true;
342 RelocationModel = Reloc::Static;
343 break;
344 default:
345 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
346 return LDPS_ERR;
348 break;
349 case LDPT_OPTION:
350 options::process_plugin_option(tv->tv_u.tv_string);
351 break;
352 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
353 ld_plugin_register_claim_file callback;
354 callback = tv->tv_u.tv_register_claim_file;
356 if (callback(claim_file_hook) != LDPS_OK)
357 return LDPS_ERR;
359 registeredClaimFile = true;
360 } break;
361 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
362 ld_plugin_register_all_symbols_read callback;
363 callback = tv->tv_u.tv_register_all_symbols_read;
365 if (callback(all_symbols_read_hook) != LDPS_OK)
366 return LDPS_ERR;
368 RegisteredAllSymbolsRead = true;
369 } break;
370 case LDPT_REGISTER_CLEANUP_HOOK: {
371 ld_plugin_register_cleanup callback;
372 callback = tv->tv_u.tv_register_cleanup;
374 if (callback(cleanup_hook) != LDPS_OK)
375 return LDPS_ERR;
376 } break;
377 case LDPT_GET_INPUT_FILE:
378 get_input_file = tv->tv_u.tv_get_input_file;
379 break;
380 case LDPT_RELEASE_INPUT_FILE:
381 release_input_file = tv->tv_u.tv_release_input_file;
382 break;
383 case LDPT_ADD_SYMBOLS:
384 add_symbols = tv->tv_u.tv_add_symbols;
385 break;
386 case LDPT_GET_SYMBOLS_V2:
387 // Do not override get_symbols_v3 with get_symbols_v2.
388 if (!get_symbols)
389 get_symbols = tv->tv_u.tv_get_symbols;
390 break;
391 case LDPT_GET_SYMBOLS_V3:
392 get_symbols = tv->tv_u.tv_get_symbols;
393 break;
394 case LDPT_ADD_INPUT_FILE:
395 add_input_file = tv->tv_u.tv_add_input_file;
396 break;
397 case LDPT_SET_EXTRA_LIBRARY_PATH:
398 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
399 break;
400 case LDPT_GET_VIEW:
401 get_view = tv->tv_u.tv_get_view;
402 break;
403 case LDPT_MESSAGE:
404 message = tv->tv_u.tv_message;
405 break;
406 case LDPT_GET_WRAP_SYMBOLS:
407 // FIXME: When binutils 2.31 (containing gold 1.16) is the minimum
408 // required version, this should be changed to:
409 // get_wrap_symbols = tv->tv_u.tv_get_wrap_symbols;
410 get_wrap_symbols =
411 (ld_plugin_get_wrap_symbols)tv->tv_u.tv_message;
412 break;
413 default:
414 break;
418 if (!registeredClaimFile) {
419 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
420 return LDPS_ERR;
422 if (!add_symbols) {
423 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
424 return LDPS_ERR;
427 if (!RegisteredAllSymbolsRead)
428 return LDPS_OK;
430 if (!get_input_file) {
431 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
432 return LDPS_ERR;
434 if (!release_input_file) {
435 message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
436 return LDPS_ERR;
439 return LDPS_OK;
442 static void diagnosticHandler(const DiagnosticInfo &DI) {
443 std::string ErrStorage;
445 raw_string_ostream OS(ErrStorage);
446 DiagnosticPrinterRawOStream DP(OS);
447 DI.print(DP);
449 ld_plugin_level Level;
450 switch (DI.getSeverity()) {
451 case DS_Error:
452 Level = LDPL_FATAL;
453 break;
454 case DS_Warning:
455 Level = LDPL_WARNING;
456 break;
457 case DS_Note:
458 case DS_Remark:
459 Level = LDPL_INFO;
460 break;
462 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
465 static void check(Error E, std::string Msg = "LLVM gold plugin") {
466 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
467 message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());
468 return Error::success();
472 template <typename T> static T check(Expected<T> E) {
473 if (E)
474 return std::move(*E);
475 check(E.takeError());
476 return T();
479 /// Called by gold to see whether this file is one that our plugin can handle.
480 /// We'll try to open it and register all the symbols with add_symbol if
481 /// possible.
482 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
483 int *claimed) {
484 MemoryBufferRef BufferRef;
485 std::unique_ptr<MemoryBuffer> Buffer;
486 if (get_view) {
487 const void *view;
488 if (get_view(file->handle, &view) != LDPS_OK) {
489 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
490 return LDPS_ERR;
492 BufferRef =
493 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
494 } else {
495 int64_t offset = 0;
496 // Gold has found what might be IR part-way inside of a file, such as
497 // an .a archive.
498 if (file->offset) {
499 offset = file->offset;
501 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
502 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
503 offset);
504 if (std::error_code EC = BufferOrErr.getError()) {
505 message(LDPL_ERROR, EC.message().c_str());
506 return LDPS_ERR;
508 Buffer = std::move(BufferOrErr.get());
509 BufferRef = Buffer->getMemBufferRef();
512 *claimed = 1;
514 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
515 if (!ObjOrErr) {
516 handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {
517 std::error_code EC = EI.convertToErrorCode();
518 if (EC == object::object_error::invalid_file_type ||
519 EC == object::object_error::bitcode_section_not_found)
520 *claimed = 0;
521 else
522 message(LDPL_FATAL,
523 "LLVM gold plugin has failed to create LTO module: %s",
524 EI.message().c_str());
527 return *claimed ? LDPS_ERR : LDPS_OK;
530 std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);
532 Modules.emplace_back();
533 claimed_file &cf = Modules.back();
535 cf.handle = file->handle;
536 // Keep track of the first handle for each file descriptor, since there are
537 // multiple in the case of an archive. This is used later in the case of
538 // ThinLTO parallel backends to ensure that each file is only opened and
539 // released once.
540 auto LeaderHandle =
541 FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
542 cf.leader_handle = LeaderHandle->second;
543 // Save the filesize since for parallel ThinLTO backends we can only
544 // invoke get_input_file once per archive (only for the leader handle).
545 cf.filesize = file->filesize;
546 // In the case of an archive library, all but the first member must have a
547 // non-zero offset, which we can append to the file name to obtain a
548 // unique name.
549 cf.name = file->name;
550 if (file->offset)
551 cf.name += ".llvm." + std::to_string(file->offset) + "." +
552 sys::path::filename(Obj->getSourceFileName()).str();
554 for (auto &Sym : Obj->symbols()) {
555 cf.syms.push_back(ld_plugin_symbol());
556 ld_plugin_symbol &sym = cf.syms.back();
557 sym.version = nullptr;
558 StringRef Name = Sym.getName();
559 sym.name = strdup(Name.str().c_str());
561 ResolutionInfo &Res = ResInfo[Name];
563 Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();
565 sym.visibility = LDPV_DEFAULT;
566 GlobalValue::VisibilityTypes Vis = Sym.getVisibility();
567 if (Vis != GlobalValue::DefaultVisibility)
568 Res.DefaultVisibility = false;
569 switch (Vis) {
570 case GlobalValue::DefaultVisibility:
571 break;
572 case GlobalValue::HiddenVisibility:
573 sym.visibility = LDPV_HIDDEN;
574 break;
575 case GlobalValue::ProtectedVisibility:
576 sym.visibility = LDPV_PROTECTED;
577 break;
580 if (Sym.isUndefined()) {
581 sym.def = LDPK_UNDEF;
582 if (Sym.isWeak())
583 sym.def = LDPK_WEAKUNDEF;
584 } else if (Sym.isCommon())
585 sym.def = LDPK_COMMON;
586 else if (Sym.isWeak())
587 sym.def = LDPK_WEAKDEF;
588 else
589 sym.def = LDPK_DEF;
591 sym.size = 0;
592 sym.comdat_key = nullptr;
593 int CI = Sym.getComdatIndex();
594 if (CI != -1) {
595 StringRef C = Obj->getComdatTable()[CI];
596 sym.comdat_key = strdup(C.str().c_str());
599 sym.resolution = LDPR_UNKNOWN;
602 if (!cf.syms.empty()) {
603 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
604 message(LDPL_ERROR, "Unable to add symbols!");
605 return LDPS_ERR;
609 // Handle any --wrap options passed to gold, which are than passed
610 // along to the plugin.
611 if (get_wrap_symbols) {
612 const char **wrap_symbols;
613 uint64_t count = 0;
614 if (get_wrap_symbols(&count, &wrap_symbols) != LDPS_OK) {
615 message(LDPL_ERROR, "Unable to get wrap symbols!");
616 return LDPS_ERR;
618 for (uint64_t i = 0; i < count; i++) {
619 StringRef Name = wrap_symbols[i];
620 ResolutionInfo &Res = ResInfo[Name];
621 ResolutionInfo &WrapRes = ResInfo["__wrap_" + Name.str()];
622 ResolutionInfo &RealRes = ResInfo["__real_" + Name.str()];
623 // Tell LTO not to inline symbols that will be overwritten.
624 Res.CanInline = false;
625 RealRes.CanInline = false;
626 // Tell LTO not to eliminate symbols that will be used after renaming.
627 Res.IsUsedInRegularObj = true;
628 WrapRes.IsUsedInRegularObj = true;
632 return LDPS_OK;
635 static void freeSymName(ld_plugin_symbol &Sym) {
636 free(Sym.name);
637 free(Sym.comdat_key);
638 Sym.name = nullptr;
639 Sym.comdat_key = nullptr;
642 /// Helper to get a file's symbols and a view into it via gold callbacks.
643 static const void *getSymbolsAndView(claimed_file &F) {
644 ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
645 if (status == LDPS_NO_SYMS)
646 return nullptr;
648 if (status != LDPS_OK)
649 message(LDPL_FATAL, "Failed to get symbol information");
651 const void *View;
652 if (get_view(F.handle, &View) != LDPS_OK)
653 message(LDPL_FATAL, "Failed to get a view of file");
655 return View;
658 /// Parse the thinlto-object-suffix-replace option into the \p OldSuffix and
659 /// \p NewSuffix strings, if it was specified.
660 static void getThinLTOOldAndNewSuffix(std::string &OldSuffix,
661 std::string &NewSuffix) {
662 assert(options::thinlto_object_suffix_replace.empty() ||
663 options::thinlto_object_suffix_replace.find(";") != StringRef::npos);
664 StringRef SuffixReplace = options::thinlto_object_suffix_replace;
665 std::tie(OldSuffix, NewSuffix) = SuffixReplace.split(';');
668 /// Given the original \p Path to an output file, replace any filename
669 /// suffix matching \p OldSuffix with \p NewSuffix.
670 static std::string getThinLTOObjectFileName(StringRef Path, StringRef OldSuffix,
671 StringRef NewSuffix) {
672 if (Path.consume_back(OldSuffix))
673 return (Path + NewSuffix).str();
674 return Path;
677 // Returns true if S is valid as a C language identifier.
678 static bool isValidCIdentifier(StringRef S) {
679 return !S.empty() && (isAlpha(S[0]) || S[0] == '_') &&
680 std::all_of(S.begin() + 1, S.end(),
681 [](char C) { return C == '_' || isAlnum(C); });
684 static bool isUndefined(ld_plugin_symbol &Sym) {
685 return Sym.def == LDPK_UNDEF || Sym.def == LDPK_WEAKUNDEF;
688 static void addModule(LTO &Lto, claimed_file &F, const void *View,
689 StringRef Filename) {
690 MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize),
691 Filename);
692 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
694 if (!ObjOrErr)
695 message(LDPL_FATAL, "Could not read bitcode from file : %s",
696 toString(ObjOrErr.takeError()).c_str());
698 unsigned SymNum = 0;
699 std::unique_ptr<InputFile> Input = std::move(ObjOrErr.get());
700 auto InputFileSyms = Input->symbols();
701 assert(InputFileSyms.size() == F.syms.size());
702 std::vector<SymbolResolution> Resols(F.syms.size());
703 for (ld_plugin_symbol &Sym : F.syms) {
704 const InputFile::Symbol &InpSym = InputFileSyms[SymNum];
705 SymbolResolution &R = Resols[SymNum++];
707 ld_plugin_symbol_resolution Resolution =
708 (ld_plugin_symbol_resolution)Sym.resolution;
710 ResolutionInfo &Res = ResInfo[Sym.name];
712 switch (Resolution) {
713 case LDPR_UNKNOWN:
714 llvm_unreachable("Unexpected resolution");
716 case LDPR_RESOLVED_IR:
717 case LDPR_RESOLVED_EXEC:
718 case LDPR_RESOLVED_DYN:
719 case LDPR_PREEMPTED_IR:
720 case LDPR_PREEMPTED_REG:
721 case LDPR_UNDEF:
722 break;
724 case LDPR_PREVAILING_DEF_IRONLY:
725 R.Prevailing = !isUndefined(Sym);
726 break;
728 case LDPR_PREVAILING_DEF:
729 R.Prevailing = !isUndefined(Sym);
730 R.VisibleToRegularObj = true;
731 break;
733 case LDPR_PREVAILING_DEF_IRONLY_EXP:
734 R.Prevailing = !isUndefined(Sym);
735 if (!Res.CanOmitFromDynSym)
736 R.VisibleToRegularObj = true;
737 break;
740 // If the symbol has a C identifier section name, we need to mark
741 // it as visible to a regular object so that LTO will keep it around
742 // to ensure the linker generates special __start_<secname> and
743 // __stop_<secname> symbols which may be used elsewhere.
744 if (isValidCIdentifier(InpSym.getSectionName()))
745 R.VisibleToRegularObj = true;
747 if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
748 (IsExecutable || !Res.DefaultVisibility))
749 R.FinalDefinitionInLinkageUnit = true;
751 if (!Res.CanInline)
752 R.LinkerRedefined = true;
754 if (Res.IsUsedInRegularObj)
755 R.VisibleToRegularObj = true;
757 freeSymName(Sym);
760 check(Lto.add(std::move(Input), Resols),
761 std::string("Failed to link module ") + F.name);
764 static void recordFile(const std::string &Filename, bool TempOutFile) {
765 if (add_input_file(Filename.c_str()) != LDPS_OK)
766 message(LDPL_FATAL,
767 "Unable to add .o file to the link. File left behind in: %s",
768 Filename.c_str());
769 if (TempOutFile)
770 Cleanup.push_back(Filename);
773 /// Return the desired output filename given a base input name, a flag
774 /// indicating whether a temp file should be generated, and an optional task id.
775 /// The new filename generated is returned in \p NewFilename.
776 static int getOutputFileName(StringRef InFilename, bool TempOutFile,
777 SmallString<128> &NewFilename, int TaskID) {
778 int FD = -1;
779 if (TempOutFile) {
780 std::error_code EC =
781 sys::fs::createTemporaryFile("lto-llvm", "o", FD, NewFilename);
782 if (EC)
783 message(LDPL_FATAL, "Could not create temporary file: %s",
784 EC.message().c_str());
785 } else {
786 NewFilename = InFilename;
787 if (TaskID > 0)
788 NewFilename += utostr(TaskID);
789 std::error_code EC =
790 sys::fs::openFileForWrite(NewFilename, FD, sys::fs::CD_CreateAlways);
791 if (EC)
792 message(LDPL_FATAL, "Could not open file %s: %s", NewFilename.c_str(),
793 EC.message().c_str());
795 return FD;
798 static CodeGenOpt::Level getCGOptLevel() {
799 switch (options::OptLevel) {
800 case 0:
801 return CodeGenOpt::None;
802 case 1:
803 return CodeGenOpt::Less;
804 case 2:
805 return CodeGenOpt::Default;
806 case 3:
807 return CodeGenOpt::Aggressive;
809 llvm_unreachable("Invalid optimization level");
812 /// Parse the thinlto_prefix_replace option into the \p OldPrefix and
813 /// \p NewPrefix strings, if it was specified.
814 static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
815 std::string &NewPrefix) {
816 StringRef PrefixReplace = options::thinlto_prefix_replace;
817 assert(PrefixReplace.empty() || PrefixReplace.find(";") != StringRef::npos);
818 std::tie(OldPrefix, NewPrefix) = PrefixReplace.split(';');
821 /// Creates instance of LTO.
822 /// OnIndexWrite is callback to let caller know when LTO writes index files.
823 /// LinkedObjectsFile is an output stream to write the list of object files for
824 /// the final ThinLTO linking. Can be nullptr.
825 static std::unique_ptr<LTO> createLTO(IndexWriteCallback OnIndexWrite,
826 raw_fd_ostream *LinkedObjectsFile) {
827 Config Conf;
828 ThinBackend Backend;
830 Conf.CPU = options::mcpu;
831 Conf.Options = InitTargetOptionsFromCodeGenFlags();
833 // Disable the new X86 relax relocations since gold might not support them.
834 // FIXME: Check the gold version or add a new option to enable them.
835 Conf.Options.RelaxELFRelocations = false;
837 // Toggle function/data sections.
838 if (FunctionSections.getNumOccurrences() == 0)
839 Conf.Options.FunctionSections = SplitSections;
840 if (DataSections.getNumOccurrences() == 0)
841 Conf.Options.DataSections = SplitSections;
843 Conf.MAttrs = MAttrs;
844 Conf.RelocModel = RelocationModel;
845 Conf.CodeModel = getCodeModel();
846 Conf.CGOptLevel = getCGOptLevel();
847 Conf.DisableVerify = options::DisableVerify;
848 Conf.OptLevel = options::OptLevel;
849 if (options::Parallelism)
850 Backend = createInProcessThinBackend(options::Parallelism);
851 if (options::thinlto_index_only) {
852 std::string OldPrefix, NewPrefix;
853 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
854 Backend = createWriteIndexesThinBackend(OldPrefix, NewPrefix,
855 options::thinlto_emit_imports_files,
856 LinkedObjectsFile, OnIndexWrite);
859 Conf.OverrideTriple = options::triple;
860 Conf.DefaultTriple = sys::getDefaultTargetTriple();
862 Conf.DiagHandler = diagnosticHandler;
864 switch (options::TheOutputType) {
865 case options::OT_NORMAL:
866 break;
868 case options::OT_DISABLE:
869 Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
870 break;
872 case options::OT_BC_ONLY:
873 Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
874 std::error_code EC;
875 raw_fd_ostream OS(output_name, EC, sys::fs::OpenFlags::F_None);
876 if (EC)
877 message(LDPL_FATAL, "Failed to write the output file.");
878 WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ false);
879 return false;
881 break;
883 case options::OT_SAVE_TEMPS:
884 check(Conf.addSaveTemps(output_name + ".",
885 /* UseInputModulePath */ true));
886 break;
887 case options::OT_ASM_ONLY:
888 Conf.CGFileType = TargetMachine::CGFT_AssemblyFile;
889 break;
892 if (!options::sample_profile.empty())
893 Conf.SampleProfile = options::sample_profile;
895 Conf.DwoDir = options::dwo_dir;
897 // Set up optimization remarks handling.
898 Conf.RemarksFilename = options::OptRemarksFilename;
899 Conf.RemarksWithHotness = options::OptRemarksWithHotness;
901 // Use new pass manager if set in driver
902 Conf.UseNewPM = options::new_pass_manager;
903 // Debug new pass manager if requested
904 Conf.DebugPassManager = options::debug_pass_manager;
906 Conf.StatsFile = options::stats_file;
907 return llvm::make_unique<LTO>(std::move(Conf), Backend,
908 options::ParallelCodeGenParallelismLevel);
911 // Write empty files that may be expected by a distributed build
912 // system when invoked with thinlto_index_only. This is invoked when
913 // the linker has decided not to include the given module in the
914 // final link. Frequently the distributed build system will want to
915 // confirm that all expected outputs are created based on all of the
916 // modules provided to the linker.
917 // If SkipModule is true then .thinlto.bc should contain just
918 // SkipModuleByDistributedBackend flag which requests distributed backend
919 // to skip the compilation of the corresponding module and produce an empty
920 // object file.
921 static void writeEmptyDistributedBuildOutputs(const std::string &ModulePath,
922 const std::string &OldPrefix,
923 const std::string &NewPrefix,
924 bool SkipModule) {
925 std::string NewModulePath =
926 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
927 std::error_code EC;
929 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
930 sys::fs::OpenFlags::F_None);
931 if (EC)
932 message(LDPL_FATAL, "Failed to write '%s': %s",
933 (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
935 if (SkipModule) {
936 ModuleSummaryIndex Index(/*HaveGVs*/ false);
937 Index.setSkipModuleByDistributedBackend();
938 WriteIndexToFile(Index, OS, nullptr);
941 if (options::thinlto_emit_imports_files) {
942 raw_fd_ostream OS(NewModulePath + ".imports", EC,
943 sys::fs::OpenFlags::F_None);
944 if (EC)
945 message(LDPL_FATAL, "Failed to write '%s': %s",
946 (NewModulePath + ".imports").c_str(), EC.message().c_str());
950 // Creates and returns output stream with a list of object files for final
951 // linking of distributed ThinLTO.
952 static std::unique_ptr<raw_fd_ostream> CreateLinkedObjectsFile() {
953 if (options::thinlto_linked_objects_file.empty())
954 return nullptr;
955 assert(options::thinlto_index_only);
956 std::error_code EC;
957 auto LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
958 options::thinlto_linked_objects_file, EC, sys::fs::OpenFlags::F_None);
959 if (EC)
960 message(LDPL_FATAL, "Failed to create '%s': %s",
961 options::thinlto_linked_objects_file.c_str(), EC.message().c_str());
962 return LinkedObjectsFile;
965 /// Runs LTO and return a list of pairs <FileName, IsTemporary>.
966 static std::vector<std::pair<SmallString<128>, bool>> runLTO() {
967 // Map to own RAII objects that manage the file opening and releasing
968 // interfaces with gold. This is needed only for ThinLTO mode, since
969 // unlike regular LTO, where addModule will result in the opened file
970 // being merged into a new combined module, we need to keep these files open
971 // through Lto->run().
972 DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
974 // Owns string objects and tells if index file was already created.
975 StringMap<bool> ObjectToIndexFileState;
977 std::unique_ptr<raw_fd_ostream> LinkedObjects = CreateLinkedObjectsFile();
978 std::unique_ptr<LTO> Lto = createLTO(
979 [&ObjectToIndexFileState](const std::string &Identifier) {
980 ObjectToIndexFileState[Identifier] = true;
982 LinkedObjects.get());
984 std::string OldPrefix, NewPrefix;
985 if (options::thinlto_index_only)
986 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
988 std::string OldSuffix, NewSuffix;
989 getThinLTOOldAndNewSuffix(OldSuffix, NewSuffix);
991 for (claimed_file &F : Modules) {
992 if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
993 HandleToInputFile.insert(std::make_pair(
994 F.leader_handle, llvm::make_unique<PluginInputFile>(F.handle)));
995 // In case we are thin linking with a minimized bitcode file, ensure
996 // the module paths encoded in the index reflect where the backends
997 // will locate the full bitcode files for compiling/importing.
998 std::string Identifier =
999 getThinLTOObjectFileName(F.name, OldSuffix, NewSuffix);
1000 auto ObjFilename = ObjectToIndexFileState.insert({Identifier, false});
1001 assert(ObjFilename.second);
1002 if (const void *View = getSymbolsAndView(F))
1003 addModule(*Lto, F, View, ObjFilename.first->first());
1004 else if (options::thinlto_index_only) {
1005 ObjFilename.first->second = true;
1006 writeEmptyDistributedBuildOutputs(Identifier, OldPrefix, NewPrefix,
1007 /* SkipModule */ true);
1011 SmallString<128> Filename;
1012 // Note that getOutputFileName will append a unique ID for each task
1013 if (!options::obj_path.empty())
1014 Filename = options::obj_path;
1015 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
1016 Filename = output_name + ".o";
1017 else if (options::TheOutputType == options::OT_ASM_ONLY)
1018 Filename = output_name;
1019 bool SaveTemps = !Filename.empty();
1021 size_t MaxTasks = Lto->getMaxTasks();
1022 std::vector<std::pair<SmallString<128>, bool>> Files(MaxTasks);
1024 auto AddStream =
1025 [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
1026 Files[Task].second = !SaveTemps;
1027 int FD = getOutputFileName(Filename, /* TempOutFile */ !SaveTemps,
1028 Files[Task].first, Task);
1029 return llvm::make_unique<lto::NativeObjectStream>(
1030 llvm::make_unique<llvm::raw_fd_ostream>(FD, true));
1033 auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
1034 *AddStream(Task)->OS << MB->getBuffer();
1037 NativeObjectCache Cache;
1038 if (!options::cache_dir.empty())
1039 Cache = check(localCache(options::cache_dir, AddBuffer));
1041 check(Lto->run(AddStream, Cache));
1043 // Write empty output files that may be expected by the distributed build
1044 // system.
1045 if (options::thinlto_index_only)
1046 for (auto &Identifier : ObjectToIndexFileState)
1047 if (!Identifier.getValue())
1048 writeEmptyDistributedBuildOutputs(Identifier.getKey(), OldPrefix,
1049 NewPrefix, /* SkipModule */ false);
1051 return Files;
1054 /// gold informs us that all symbols have been read. At this point, we use
1055 /// get_symbols to see if any of our definitions have been overridden by a
1056 /// native object file. Then, perform optimization and codegen.
1057 static ld_plugin_status allSymbolsReadHook() {
1058 if (Modules.empty())
1059 return LDPS_OK;
1061 if (unsigned NumOpts = options::extra.size())
1062 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
1064 std::vector<std::pair<SmallString<128>, bool>> Files = runLTO();
1066 if (options::TheOutputType == options::OT_DISABLE ||
1067 options::TheOutputType == options::OT_BC_ONLY ||
1068 options::TheOutputType == options::OT_ASM_ONLY)
1069 return LDPS_OK;
1071 if (options::thinlto_index_only) {
1072 llvm_shutdown();
1073 cleanup_hook();
1074 exit(0);
1077 for (const auto &F : Files)
1078 if (!F.first.empty())
1079 recordFile(F.first.str(), F.second);
1081 if (!options::extra_library_path.empty() &&
1082 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
1083 message(LDPL_FATAL, "Unable to set the extra library path.");
1085 return LDPS_OK;
1088 static ld_plugin_status all_symbols_read_hook(void) {
1089 ld_plugin_status Ret = allSymbolsReadHook();
1090 llvm_shutdown();
1092 if (options::TheOutputType == options::OT_BC_ONLY ||
1093 options::TheOutputType == options::OT_ASM_ONLY ||
1094 options::TheOutputType == options::OT_DISABLE) {
1095 if (options::TheOutputType == options::OT_DISABLE) {
1096 // Remove the output file here since ld.bfd creates the output file
1097 // early.
1098 std::error_code EC = sys::fs::remove(output_name);
1099 if (EC)
1100 message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
1101 EC.message().c_str());
1103 exit(0);
1106 return Ret;
1109 static ld_plugin_status cleanup_hook(void) {
1110 for (std::string &Name : Cleanup) {
1111 std::error_code EC = sys::fs::remove(Name);
1112 if (EC)
1113 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
1114 EC.message().c_str());
1117 // Prune cache
1118 if (!options::cache_dir.empty()) {
1119 CachePruningPolicy policy = check(parseCachePruningPolicy(options::cache_policy));
1120 pruneCache(options::cache_dir, policy);
1123 return LDPS_OK;