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 .
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ADT/Statistic.h"
15 #include "llvm/Bitcode/BitcodeReader.h"
16 #include "llvm/Bitcode/BitcodeWriter.h"
17 #include "llvm/CodeGen/CommandFlags.h"
18 #include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
19 #include "llvm/Config/llvm-config.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/LTO/LTO.h"
23 #include "llvm/Object/Error.h"
24 #include "llvm/Remarks/HotnessThresholdParser.h"
25 #include "llvm/Support/CachePruning.h"
26 #include "llvm/Support/Caching.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/Host.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/TargetSelect.h"
34 #include "llvm/Support/Threading.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <list>
37 #include <map>
38 #include <plugin-api.h>
39 #include <string>
40 #include <system_error>
41 #include <utility>
42 #include <vector>
43
44 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
45 // Precise and Debian Wheezy (binutils 2.23 is required)
46 #define LDPO_PIE 3
47
48 #define LDPT_GET_SYMBOLS_V3 28
49
50 // FIXME: Remove when binutils 2.31 (containing gold 1.16) is the minimum
51 // required version.
52 #define LDPT_GET_WRAP_SYMBOLS 32
53
54 using namespace llvm;
55 using namespace lto;
56
57 static codegen::RegisterCodeGenFlags CodeGenFlags;
58
59 // FIXME: Remove when binutils 2.31 (containing gold 1.16) is the minimum
60 // required version.
61 typedef enum ld_plugin_status (*ld_plugin_get_wrap_symbols)(
62 uint64_t *num_symbols, const char ***wrap_symbol_list);
63
64 static ld_plugin_status discard_message(int level, const char *format, ...) {
65 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
66 // callback in the transfer vector. This should never be called.
67 abort();
68 }
69
70 static ld_plugin_release_input_file release_input_file = nullptr;
71 static ld_plugin_get_input_file get_input_file = nullptr;
72 static ld_plugin_message message = discard_message;
73 static ld_plugin_get_wrap_symbols get_wrap_symbols = nullptr;
74
75 namespace {
76 struct claimed_file {
77 void *handle;
78 void *leader_handle;
79 std::vector<ld_plugin_symbol> syms;
80 off_t filesize;
81 std::string name;
82 };
83
84 /// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
85 struct PluginInputFile {
86 void *Handle;
87 std::unique_ptr<ld_plugin_input_file> File;
88
PluginInputFile__anon27a2bb4e0111::PluginInputFile89 PluginInputFile(void *Handle) : Handle(Handle) {
90 File = std::make_unique<ld_plugin_input_file>();
91 if (get_input_file(Handle, File.get()) != LDPS_OK)
92 message(LDPL_FATAL, "Failed to get file information");
93 }
~PluginInputFile__anon27a2bb4e0111::PluginInputFile94 ~PluginInputFile() {
95 // File would have been reset to nullptr if we moved this object
96 // to a new owner.
97 if (File)
98 if (release_input_file(Handle) != LDPS_OK)
99 message(LDPL_FATAL, "Failed to release file information");
100 }
101
file__anon27a2bb4e0111::PluginInputFile102 ld_plugin_input_file &file() { return *File; }
103
104 PluginInputFile(PluginInputFile &&RHS) = default;
105 PluginInputFile &operator=(PluginInputFile &&RHS) = default;
106 };
107
108 struct ResolutionInfo {
109 bool CanOmitFromDynSym = true;
110 bool DefaultVisibility = true;
111 bool CanInline = true;
112 bool IsUsedInRegularObj = false;
113 };
114
115 }
116
117 static ld_plugin_add_symbols add_symbols = nullptr;
118 static ld_plugin_get_symbols get_symbols = nullptr;
119 static ld_plugin_add_input_file add_input_file = nullptr;
120 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
121 static ld_plugin_get_view get_view = nullptr;
122 static bool IsExecutable = false;
123 static bool SplitSections = true;
124 static std::optional<Reloc::Model> RelocationModel;
125 static std::string output_name = "";
126 static std::list<claimed_file> Modules;
127 static DenseMap<int, void *> FDToLeaderHandle;
128 static StringMap<ResolutionInfo> ResInfo;
129 static std::vector<std::string> Cleanup;
130
131 namespace options {
132 enum OutputType {
133 OT_NORMAL,
134 OT_DISABLE,
135 OT_BC_ONLY,
136 OT_ASM_ONLY,
137 OT_SAVE_TEMPS
138 };
139 static OutputType TheOutputType = OT_NORMAL;
140 static unsigned OptLevel = 2;
141 // Currently only affects ThinLTO, where the default is the max cores in the
142 // system. See llvm::get_threadpool_strategy() for acceptable values.
143 static std::string Parallelism;
144 // Default regular LTO codegen parallelism (number of partitions).
145 static unsigned ParallelCodeGenParallelismLevel = 1;
146 #ifdef NDEBUG
147 static bool DisableVerify = true;
148 #else
149 static bool DisableVerify = false;
150 #endif
151 static std::string obj_path;
152 static std::string extra_library_path;
153 static std::string triple;
154 static std::string mcpu;
155 // When the thinlto plugin option is specified, only read the function
156 // the information from intermediate files and write a combined
157 // global index for the ThinLTO backends.
158 static bool thinlto = false;
159 // If false, all ThinLTO backend compilations through code gen are performed
160 // using multiple threads in the gold-plugin, before handing control back to
161 // gold. If true, write individual backend index files which reflect
162 // the import decisions, and exit afterwards. The assumption is
163 // that the build system will launch the backend processes.
164 static bool thinlto_index_only = false;
165 // If non-empty, holds the name of a file in which to write the list of
166 // oject files gold selected for inclusion in the link after symbol
167 // resolution (i.e. they had selected symbols). This will only be non-empty
168 // in the thinlto_index_only case. It is used to identify files, which may
169 // have originally been within archive libraries specified via
170 // --start-lib/--end-lib pairs, that should be included in the final
171 // native link process (since intervening function importing and inlining
172 // may change the symbol resolution detected in the final link and which
173 // files to include out of --start-lib/--end-lib libraries as a result).
174 static std::string thinlto_linked_objects_file;
175 // If true, when generating individual index files for distributed backends,
176 // also generate a "${bitcodefile}.imports" file at the same location for each
177 // bitcode file, listing the files it imports from in plain text. This is to
178 // support distributed build file staging.
179 static bool thinlto_emit_imports_files = false;
180 // Option to control where files for a distributed backend (the individual
181 // index files and optional imports files) are created.
182 // If specified, expects a string of the form "oldprefix:newprefix", and
183 // instead of generating these files in the same directory path as the
184 // corresponding bitcode file, will use a path formed by replacing the
185 // bitcode file's path prefix matching oldprefix with newprefix.
186 static std::string thinlto_prefix_replace;
187 // Option to control the name of modules encoded in the individual index
188 // files for a distributed backend. This enables the use of minimized
189 // bitcode files for the thin link, assuming the name of the full bitcode
190 // file used in the backend differs just in some part of the file suffix.
191 // If specified, expects a string of the form "oldsuffix:newsuffix".
192 static std::string thinlto_object_suffix_replace;
193 // Optional path to a directory for caching ThinLTO objects.
194 static std::string cache_dir;
195 // Optional pruning policy for ThinLTO caches.
196 static std::string cache_policy;
197 // Additional options to pass into the code generator.
198 // Note: This array will contain all plugin options which are not claimed
199 // as plugin exclusive to pass to the code generator.
200 static std::vector<const char *> extra;
201 // Sample profile file path
202 static std::string sample_profile;
203 // Debug new pass manager
204 static bool debug_pass_manager = false;
205 // Directory to store the .dwo files.
206 static std::string dwo_dir;
207 /// Statistics output filename.
208 static std::string stats_file;
209 // Asserts that LTO link has whole program visibility
210 static bool whole_program_visibility = false;
211 // Use opaque pointer types.
212 static bool opaque_pointers = true;
213
214 // Optimization remarks filename, accepted passes and hotness options
215 static std::string RemarksFilename;
216 static std::string RemarksPasses;
217 static bool RemarksWithHotness = false;
218 static std::optional<uint64_t> RemarksHotnessThreshold = 0;
219 static std::string RemarksFormat;
220
221 // Context sensitive PGO options.
222 static std::string cs_profile_path;
223 static bool cs_pgo_gen = false;
224
process_plugin_option(const char * opt_)225 static void process_plugin_option(const char *opt_)
226 {
227 if (opt_ == nullptr)
228 return;
229 llvm::StringRef opt = opt_;
230
231 if (opt.consume_front("mcpu=")) {
232 mcpu = std::string(opt);
233 } else if (opt.consume_front("extra-library-path=")) {
234 extra_library_path = std::string(opt);
235 } else if (opt.consume_front("mtriple=")) {
236 triple = std::string(opt);
237 } else if (opt.consume_front("obj-path=")) {
238 obj_path = std::string(opt);
239 } else if (opt == "emit-llvm") {
240 TheOutputType = OT_BC_ONLY;
241 } else if (opt == "save-temps") {
242 TheOutputType = OT_SAVE_TEMPS;
243 } else if (opt == "disable-output") {
244 TheOutputType = OT_DISABLE;
245 } else if (opt == "emit-asm") {
246 TheOutputType = OT_ASM_ONLY;
247 } else if (opt == "thinlto") {
248 thinlto = true;
249 } else if (opt == "thinlto-index-only") {
250 thinlto_index_only = true;
251 } else if (opt.consume_front("thinlto-index-only=")) {
252 thinlto_index_only = true;
253 thinlto_linked_objects_file = std::string(opt);
254 } else if (opt == "thinlto-emit-imports-files") {
255 thinlto_emit_imports_files = true;
256 } else if (opt.consume_front("thinlto-prefix-replace=")) {
257 thinlto_prefix_replace = std::string(opt);
258 if (thinlto_prefix_replace.find(';') == std::string::npos)
259 message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");
260 } else if (opt.consume_front("thinlto-object-suffix-replace=")) {
261 thinlto_object_suffix_replace = std::string(opt);
262 if (thinlto_object_suffix_replace.find(';') == std::string::npos)
263 message(LDPL_FATAL,
264 "thinlto-object-suffix-replace expects 'old;new' format");
265 } else if (opt.consume_front("cache-dir=")) {
266 cache_dir = std::string(opt);
267 } else if (opt.consume_front("cache-policy=")) {
268 cache_policy = std::string(opt);
269 } else if (opt.size() == 2 && opt[0] == 'O') {
270 if (opt[1] < '0' || opt[1] > '3')
271 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
272 OptLevel = opt[1] - '0';
273 } else if (opt.consume_front("jobs=")) {
274 Parallelism = std::string(opt);
275 if (!get_threadpool_strategy(opt))
276 message(LDPL_FATAL, "Invalid parallelism level: %s",
277 Parallelism.c_str());
278 } else if (opt.consume_front("lto-partitions=")) {
279 if (opt.getAsInteger(10, ParallelCodeGenParallelismLevel))
280 message(LDPL_FATAL, "Invalid codegen partition level: %s", opt_ + 5);
281 } else if (opt == "disable-verify") {
282 DisableVerify = true;
283 } else if (opt.consume_front("sample-profile=")) {
284 sample_profile = std::string(opt);
285 } else if (opt == "cs-profile-generate") {
286 cs_pgo_gen = true;
287 } else if (opt.consume_front("cs-profile-path=")) {
288 cs_profile_path = std::string(opt);
289 } else if (opt == "new-pass-manager") {
290 // We always use the new pass manager.
291 } else if (opt == "debug-pass-manager") {
292 debug_pass_manager = true;
293 } else if (opt == "whole-program-visibility") {
294 whole_program_visibility = true;
295 } else if (opt.consume_front("dwo_dir=")) {
296 dwo_dir = std::string(opt);
297 } else if (opt.consume_front("opt-remarks-filename=")) {
298 RemarksFilename = std::string(opt);
299 } else if (opt.consume_front("opt-remarks-passes=")) {
300 RemarksPasses = std::string(opt);
301 } else if (opt == "opt-remarks-with-hotness") {
302 RemarksWithHotness = true;
303 } else if (opt.consume_front("opt-remarks-hotness-threshold=")) {
304 auto ResultOrErr = remarks::parseHotnessThresholdOption(opt);
305 if (!ResultOrErr)
306 message(LDPL_FATAL, "Invalid remarks hotness threshold: %s", opt);
307 else
308 RemarksHotnessThreshold = *ResultOrErr;
309 } else if (opt.consume_front("opt-remarks-format=")) {
310 RemarksFormat = std::string(opt);
311 } else if (opt.consume_front("stats-file=")) {
312 stats_file = std::string(opt);
313 } else if (opt == "opaque-pointers") {
314 opaque_pointers = true;
315 } else if (opt == "no-opaque-pointers") {
316 opaque_pointers = false;
317 } else {
318 // Save this option to pass to the code generator.
319 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
320 // add that.
321 if (extra.empty())
322 extra.push_back("LLVMgold");
323
324 extra.push_back(opt_);
325 }
326 }
327 }
328
329 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
330 int *claimed);
331 static ld_plugin_status all_symbols_read_hook(void);
332 static ld_plugin_status cleanup_hook(void);
333
334 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
onload(ld_plugin_tv * tv)335 ld_plugin_status onload(ld_plugin_tv *tv) {
336 InitializeAllTargetInfos();
337 InitializeAllTargets();
338 InitializeAllTargetMCs();
339 InitializeAllAsmParsers();
340 InitializeAllAsmPrinters();
341
342 // We're given a pointer to the first transfer vector. We read through them
343 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
344 // contain pointers to functions that we need to call to register our own
345 // hooks. The others are addresses of functions we can use to call into gold
346 // for services.
347
348 bool registeredClaimFile = false;
349 bool RegisteredAllSymbolsRead = false;
350
351 for (; tv->tv_tag != LDPT_NULL; ++tv) {
352 // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
353 // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
354 // header.
355 switch (static_cast<int>(tv->tv_tag)) {
356 case LDPT_OUTPUT_NAME:
357 output_name = tv->tv_u.tv_string;
358 break;
359 case LDPT_LINKER_OUTPUT:
360 switch (tv->tv_u.tv_val) {
361 case LDPO_REL: // .o
362 IsExecutable = false;
363 SplitSections = false;
364 break;
365 case LDPO_DYN: // .so
366 IsExecutable = false;
367 RelocationModel = Reloc::PIC_;
368 break;
369 case LDPO_PIE: // position independent executable
370 IsExecutable = true;
371 RelocationModel = Reloc::PIC_;
372 break;
373 case LDPO_EXEC: // .exe
374 IsExecutable = true;
375 RelocationModel = Reloc::Static;
376 break;
377 default:
378 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
379 return LDPS_ERR;
380 }
381 break;
382 case LDPT_OPTION:
383 options::process_plugin_option(tv->tv_u.tv_string);
384 break;
385 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
386 ld_plugin_register_claim_file callback;
387 callback = tv->tv_u.tv_register_claim_file;
388
389 if (callback(claim_file_hook) != LDPS_OK)
390 return LDPS_ERR;
391
392 registeredClaimFile = true;
393 } break;
394 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
395 ld_plugin_register_all_symbols_read callback;
396 callback = tv->tv_u.tv_register_all_symbols_read;
397
398 if (callback(all_symbols_read_hook) != LDPS_OK)
399 return LDPS_ERR;
400
401 RegisteredAllSymbolsRead = true;
402 } break;
403 case LDPT_REGISTER_CLEANUP_HOOK: {
404 ld_plugin_register_cleanup callback;
405 callback = tv->tv_u.tv_register_cleanup;
406
407 if (callback(cleanup_hook) != LDPS_OK)
408 return LDPS_ERR;
409 } break;
410 case LDPT_GET_INPUT_FILE:
411 get_input_file = tv->tv_u.tv_get_input_file;
412 break;
413 case LDPT_RELEASE_INPUT_FILE:
414 release_input_file = tv->tv_u.tv_release_input_file;
415 break;
416 case LDPT_ADD_SYMBOLS:
417 add_symbols = tv->tv_u.tv_add_symbols;
418 break;
419 case LDPT_GET_SYMBOLS_V2:
420 // Do not override get_symbols_v3 with get_symbols_v2.
421 if (!get_symbols)
422 get_symbols = tv->tv_u.tv_get_symbols;
423 break;
424 case LDPT_GET_SYMBOLS_V3:
425 get_symbols = tv->tv_u.tv_get_symbols;
426 break;
427 case LDPT_ADD_INPUT_FILE:
428 add_input_file = tv->tv_u.tv_add_input_file;
429 break;
430 case LDPT_SET_EXTRA_LIBRARY_PATH:
431 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
432 break;
433 case LDPT_GET_VIEW:
434 get_view = tv->tv_u.tv_get_view;
435 break;
436 case LDPT_MESSAGE:
437 message = tv->tv_u.tv_message;
438 break;
439 case LDPT_GET_WRAP_SYMBOLS:
440 // FIXME: When binutils 2.31 (containing gold 1.16) is the minimum
441 // required version, this should be changed to:
442 // get_wrap_symbols = tv->tv_u.tv_get_wrap_symbols;
443 get_wrap_symbols =
444 (ld_plugin_get_wrap_symbols)tv->tv_u.tv_message;
445 break;
446 default:
447 break;
448 }
449 }
450
451 if (!registeredClaimFile) {
452 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
453 return LDPS_ERR;
454 }
455 if (!add_symbols) {
456 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
457 return LDPS_ERR;
458 }
459
460 if (!RegisteredAllSymbolsRead)
461 return LDPS_OK;
462
463 if (!get_input_file) {
464 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
465 return LDPS_ERR;
466 }
467 if (!release_input_file) {
468 message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
469 return LDPS_ERR;
470 }
471
472 return LDPS_OK;
473 }
474
diagnosticHandler(const DiagnosticInfo & DI)475 static void diagnosticHandler(const DiagnosticInfo &DI) {
476 std::string ErrStorage;
477 {
478 raw_string_ostream OS(ErrStorage);
479 DiagnosticPrinterRawOStream DP(OS);
480 DI.print(DP);
481 }
482 ld_plugin_level Level;
483 switch (DI.getSeverity()) {
484 case DS_Error:
485 Level = LDPL_FATAL;
486 break;
487 case DS_Warning:
488 Level = LDPL_WARNING;
489 break;
490 case DS_Note:
491 case DS_Remark:
492 Level = LDPL_INFO;
493 break;
494 }
495 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
496 }
497
check(Error E,std::string Msg="LLVM gold plugin")498 static void check(Error E, std::string Msg = "LLVM gold plugin") {
499 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
500 message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());
501 return Error::success();
502 });
503 }
504
check(Expected<T> E)505 template <typename T> static T check(Expected<T> E) {
506 if (E)
507 return std::move(*E);
508 check(E.takeError());
509 return T();
510 }
511
512 /// Called by gold to see whether this file is one that our plugin can handle.
513 /// We'll try to open it and register all the symbols with add_symbol if
514 /// possible.
claim_file_hook(const ld_plugin_input_file * file,int * claimed)515 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
516 int *claimed) {
517 MemoryBufferRef BufferRef;
518 std::unique_ptr<MemoryBuffer> Buffer;
519 if (get_view) {
520 const void *view;
521 if (get_view(file->handle, &view) != LDPS_OK) {
522 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
523 return LDPS_ERR;
524 }
525 BufferRef =
526 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
527 } else {
528 int64_t offset = 0;
529 // Gold has found what might be IR part-way inside of a file, such as
530 // an .a archive.
531 if (file->offset) {
532 offset = file->offset;
533 }
534 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
535 MemoryBuffer::getOpenFileSlice(sys::fs::convertFDToNativeFile(file->fd),
536 file->name, file->filesize, offset);
537 if (std::error_code EC = BufferOrErr.getError()) {
538 message(LDPL_ERROR, EC.message().c_str());
539 return LDPS_ERR;
540 }
541 Buffer = std::move(BufferOrErr.get());
542 BufferRef = Buffer->getMemBufferRef();
543 }
544
545 // Only use bitcode files for LTO. InputFile::create() will load bitcode
546 // from the .llvmbc section within a binary object, this bitcode is typically
547 // generated by -fembed-bitcode and is not to be used by LLVMgold.so for LTO.
548 if (identify_magic(BufferRef.getBuffer()) != file_magic::bitcode) {
549 *claimed = 0;
550 return LDPS_OK;
551 }
552
553 *claimed = 1;
554
555 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
556 if (!ObjOrErr) {
557 handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {
558 std::error_code EC = EI.convertToErrorCode();
559 if (EC == object::object_error::invalid_file_type ||
560 EC == object::object_error::bitcode_section_not_found)
561 *claimed = 0;
562 else
563 message(LDPL_FATAL,
564 "LLVM gold plugin has failed to create LTO module: %s",
565 EI.message().c_str());
566 });
567
568 return *claimed ? LDPS_ERR : LDPS_OK;
569 }
570
571 std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);
572
573 Modules.emplace_back();
574 claimed_file &cf = Modules.back();
575
576 cf.handle = file->handle;
577 // Keep track of the first handle for each file descriptor, since there are
578 // multiple in the case of an archive. This is used later in the case of
579 // ThinLTO parallel backends to ensure that each file is only opened and
580 // released once.
581 auto LeaderHandle =
582 FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
583 cf.leader_handle = LeaderHandle->second;
584 // Save the filesize since for parallel ThinLTO backends we can only
585 // invoke get_input_file once per archive (only for the leader handle).
586 cf.filesize = file->filesize;
587 // In the case of an archive library, all but the first member must have a
588 // non-zero offset, which we can append to the file name to obtain a
589 // unique name.
590 cf.name = file->name;
591 if (file->offset)
592 cf.name += ".llvm." + std::to_string(file->offset) + "." +
593 sys::path::filename(Obj->getSourceFileName()).str();
594
595 for (auto &Sym : Obj->symbols()) {
596 cf.syms.push_back(ld_plugin_symbol());
597 ld_plugin_symbol &sym = cf.syms.back();
598 sym.version = nullptr;
599 StringRef Name = Sym.getName();
600 sym.name = strdup(Name.str().c_str());
601
602 ResolutionInfo &Res = ResInfo[Name];
603
604 Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();
605
606 sym.visibility = LDPV_DEFAULT;
607 GlobalValue::VisibilityTypes Vis = Sym.getVisibility();
608 if (Vis != GlobalValue::DefaultVisibility)
609 Res.DefaultVisibility = false;
610 switch (Vis) {
611 case GlobalValue::DefaultVisibility:
612 break;
613 case GlobalValue::HiddenVisibility:
614 sym.visibility = LDPV_HIDDEN;
615 break;
616 case GlobalValue::ProtectedVisibility:
617 sym.visibility = LDPV_PROTECTED;
618 break;
619 }
620
621 if (Sym.isUndefined()) {
622 sym.def = LDPK_UNDEF;
623 if (Sym.isWeak())
624 sym.def = LDPK_WEAKUNDEF;
625 } else if (Sym.isCommon())
626 sym.def = LDPK_COMMON;
627 else if (Sym.isWeak())
628 sym.def = LDPK_WEAKDEF;
629 else
630 sym.def = LDPK_DEF;
631
632 sym.size = 0;
633 sym.comdat_key = nullptr;
634 int CI = Sym.getComdatIndex();
635 if (CI != -1) {
636 // Not setting comdat_key for nodeduplicate ensuress we don't deduplicate.
637 std::pair<StringRef, Comdat::SelectionKind> C = Obj->getComdatTable()[CI];
638 if (C.second != Comdat::NoDeduplicate)
639 sym.comdat_key = strdup(C.first.str().c_str());
640 }
641
642 sym.resolution = LDPR_UNKNOWN;
643 }
644
645 if (!cf.syms.empty()) {
646 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
647 message(LDPL_ERROR, "Unable to add symbols!");
648 return LDPS_ERR;
649 }
650 }
651
652 // Handle any --wrap options passed to gold, which are than passed
653 // along to the plugin.
654 if (get_wrap_symbols) {
655 const char **wrap_symbols;
656 uint64_t count = 0;
657 if (get_wrap_symbols(&count, &wrap_symbols) != LDPS_OK) {
658 message(LDPL_ERROR, "Unable to get wrap symbols!");
659 return LDPS_ERR;
660 }
661 for (uint64_t i = 0; i < count; i++) {
662 StringRef Name = wrap_symbols[i];
663 ResolutionInfo &Res = ResInfo[Name];
664 ResolutionInfo &WrapRes = ResInfo["__wrap_" + Name.str()];
665 ResolutionInfo &RealRes = ResInfo["__real_" + Name.str()];
666 // Tell LTO not to inline symbols that will be overwritten.
667 Res.CanInline = false;
668 RealRes.CanInline = false;
669 // Tell LTO not to eliminate symbols that will be used after renaming.
670 Res.IsUsedInRegularObj = true;
671 WrapRes.IsUsedInRegularObj = true;
672 }
673 }
674
675 return LDPS_OK;
676 }
677
freeSymName(ld_plugin_symbol & Sym)678 static void freeSymName(ld_plugin_symbol &Sym) {
679 free(Sym.name);
680 free(Sym.comdat_key);
681 Sym.name = nullptr;
682 Sym.comdat_key = nullptr;
683 }
684
685 /// Helper to get a file's symbols and a view into it via gold callbacks.
getSymbolsAndView(claimed_file & F)686 static const void *getSymbolsAndView(claimed_file &F) {
687 ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
688 if (status == LDPS_NO_SYMS)
689 return nullptr;
690
691 if (status != LDPS_OK)
692 message(LDPL_FATAL, "Failed to get symbol information");
693
694 const void *View;
695 if (get_view(F.handle, &View) != LDPS_OK)
696 message(LDPL_FATAL, "Failed to get a view of file");
697
698 return View;
699 }
700
701 /// Parse the thinlto-object-suffix-replace option into the \p OldSuffix and
702 /// \p NewSuffix strings, if it was specified.
getThinLTOOldAndNewSuffix(std::string & OldSuffix,std::string & NewSuffix)703 static void getThinLTOOldAndNewSuffix(std::string &OldSuffix,
704 std::string &NewSuffix) {
705 assert(options::thinlto_object_suffix_replace.empty() ||
706 options::thinlto_object_suffix_replace.find(';') != StringRef::npos);
707 StringRef SuffixReplace = options::thinlto_object_suffix_replace;
708 auto Split = SuffixReplace.split(';');
709 OldSuffix = std::string(Split.first);
710 NewSuffix = std::string(Split.second);
711 }
712
713 /// Given the original \p Path to an output file, replace any filename
714 /// suffix matching \p OldSuffix with \p NewSuffix.
getThinLTOObjectFileName(StringRef Path,StringRef OldSuffix,StringRef NewSuffix)715 static std::string getThinLTOObjectFileName(StringRef Path, StringRef OldSuffix,
716 StringRef NewSuffix) {
717 if (Path.consume_back(OldSuffix))
718 return (Path + NewSuffix).str();
719 return std::string(Path);
720 }
721
722 // Returns true if S is valid as a C language identifier.
isValidCIdentifier(StringRef S)723 static bool isValidCIdentifier(StringRef S) {
724 return !S.empty() && (isAlpha(S[0]) || S[0] == '_') &&
725 llvm::all_of(llvm::drop_begin(S),
726 [](char C) { return C == '_' || isAlnum(C); });
727 }
728
isUndefined(ld_plugin_symbol & Sym)729 static bool isUndefined(ld_plugin_symbol &Sym) {
730 return Sym.def == LDPK_UNDEF || Sym.def == LDPK_WEAKUNDEF;
731 }
732
addModule(LTO & Lto,claimed_file & F,const void * View,StringRef Filename)733 static void addModule(LTO &Lto, claimed_file &F, const void *View,
734 StringRef Filename) {
735 MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize),
736 Filename);
737 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
738
739 if (!ObjOrErr)
740 message(LDPL_FATAL, "Could not read bitcode from file : %s",
741 toString(ObjOrErr.takeError()).c_str());
742
743 unsigned SymNum = 0;
744 std::unique_ptr<InputFile> Input = std::move(ObjOrErr.get());
745 auto InputFileSyms = Input->symbols();
746 assert(InputFileSyms.size() == F.syms.size());
747 std::vector<SymbolResolution> Resols(F.syms.size());
748 for (ld_plugin_symbol &Sym : F.syms) {
749 const InputFile::Symbol &InpSym = InputFileSyms[SymNum];
750 SymbolResolution &R = Resols[SymNum++];
751
752 ld_plugin_symbol_resolution Resolution =
753 (ld_plugin_symbol_resolution)Sym.resolution;
754
755 ResolutionInfo &Res = ResInfo[Sym.name];
756
757 switch (Resolution) {
758 case LDPR_UNKNOWN:
759 llvm_unreachable("Unexpected resolution");
760
761 case LDPR_RESOLVED_IR:
762 case LDPR_RESOLVED_EXEC:
763 case LDPR_PREEMPTED_IR:
764 case LDPR_PREEMPTED_REG:
765 case LDPR_UNDEF:
766 break;
767
768 case LDPR_RESOLVED_DYN:
769 R.ExportDynamic = true;
770 break;
771
772 case LDPR_PREVAILING_DEF_IRONLY:
773 R.Prevailing = !isUndefined(Sym);
774 break;
775
776 case LDPR_PREVAILING_DEF:
777 R.Prevailing = !isUndefined(Sym);
778 R.VisibleToRegularObj = true;
779 break;
780
781 case LDPR_PREVAILING_DEF_IRONLY_EXP:
782 R.Prevailing = !isUndefined(Sym);
783 // Identify symbols exported dynamically, and that therefore could be
784 // referenced by a shared library not visible to the linker.
785 R.ExportDynamic = true;
786 if (!Res.CanOmitFromDynSym)
787 R.VisibleToRegularObj = true;
788 break;
789 }
790
791 // If the symbol has a C identifier section name, we need to mark
792 // it as visible to a regular object so that LTO will keep it around
793 // to ensure the linker generates special __start_<secname> and
794 // __stop_<secname> symbols which may be used elsewhere.
795 if (isValidCIdentifier(InpSym.getSectionName()))
796 R.VisibleToRegularObj = true;
797
798 if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
799 (IsExecutable || !Res.DefaultVisibility))
800 R.FinalDefinitionInLinkageUnit = true;
801
802 if (!Res.CanInline)
803 R.LinkerRedefined = true;
804
805 if (Res.IsUsedInRegularObj)
806 R.VisibleToRegularObj = true;
807
808 freeSymName(Sym);
809 }
810
811 check(Lto.add(std::move(Input), Resols),
812 std::string("Failed to link module ") + F.name);
813 }
814
recordFile(const std::string & Filename,bool TempOutFile)815 static void recordFile(const std::string &Filename, bool TempOutFile) {
816 if (add_input_file(Filename.c_str()) != LDPS_OK)
817 message(LDPL_FATAL,
818 "Unable to add .o file to the link. File left behind in: %s",
819 Filename.c_str());
820 if (TempOutFile)
821 Cleanup.push_back(Filename);
822 }
823
824 /// Return the desired output filename given a base input name, a flag
825 /// indicating whether a temp file should be generated, and an optional task id.
826 /// The new filename generated is returned in \p NewFilename.
getOutputFileName(StringRef InFilename,bool TempOutFile,SmallString<128> & NewFilename,int TaskID)827 static int getOutputFileName(StringRef InFilename, bool TempOutFile,
828 SmallString<128> &NewFilename, int TaskID) {
829 int FD = -1;
830 if (TempOutFile) {
831 std::error_code EC =
832 sys::fs::createTemporaryFile("lto-llvm", "o", FD, NewFilename);
833 if (EC)
834 message(LDPL_FATAL, "Could not create temporary file: %s",
835 EC.message().c_str());
836 } else {
837 NewFilename = InFilename;
838 if (TaskID > 0)
839 NewFilename += utostr(TaskID);
840 std::error_code EC =
841 sys::fs::openFileForWrite(NewFilename, FD, sys::fs::CD_CreateAlways);
842 if (EC)
843 message(LDPL_FATAL, "Could not open file %s: %s", NewFilename.c_str(),
844 EC.message().c_str());
845 }
846 return FD;
847 }
848
849 /// Parse the thinlto_prefix_replace option into the \p OldPrefix and
850 /// \p NewPrefix strings, if it was specified.
getThinLTOOldAndNewPrefix(std::string & OldPrefix,std::string & NewPrefix)851 static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
852 std::string &NewPrefix) {
853 StringRef PrefixReplace = options::thinlto_prefix_replace;
854 assert(PrefixReplace.empty() || PrefixReplace.find(';') != StringRef::npos);
855 auto Split = PrefixReplace.split(';');
856 OldPrefix = std::string(Split.first);
857 NewPrefix = std::string(Split.second);
858 }
859
860 /// Creates instance of LTO.
861 /// OnIndexWrite is callback to let caller know when LTO writes index files.
862 /// LinkedObjectsFile is an output stream to write the list of object files for
863 /// the final ThinLTO linking. Can be nullptr.
createLTO(IndexWriteCallback OnIndexWrite,raw_fd_ostream * LinkedObjectsFile)864 static std::unique_ptr<LTO> createLTO(IndexWriteCallback OnIndexWrite,
865 raw_fd_ostream *LinkedObjectsFile) {
866 Config Conf;
867 ThinBackend Backend;
868
869 Conf.CPU = options::mcpu;
870 Conf.Options = codegen::InitTargetOptionsFromCodeGenFlags(Triple());
871
872 // Disable the new X86 relax relocations since gold might not support them.
873 // FIXME: Check the gold version or add a new option to enable them.
874 Conf.Options.RelaxELFRelocations = false;
875
876 // Toggle function/data sections.
877 if (!codegen::getExplicitFunctionSections())
878 Conf.Options.FunctionSections = SplitSections;
879 if (!codegen::getExplicitDataSections())
880 Conf.Options.DataSections = SplitSections;
881
882 Conf.MAttrs = codegen::getMAttrs();
883 Conf.RelocModel = RelocationModel;
884 Conf.CodeModel = codegen::getExplicitCodeModel();
885 std::optional<CodeGenOpt::Level> CGOptLevelOrNone =
886 CodeGenOpt::getLevel(options::OptLevel);
887 assert(CGOptLevelOrNone && "Invalid optimization level");
888 Conf.CGOptLevel = *CGOptLevelOrNone;
889 Conf.DisableVerify = options::DisableVerify;
890 Conf.OptLevel = options::OptLevel;
891 Conf.PTO.LoopVectorization = options::OptLevel > 1;
892 Conf.PTO.SLPVectorization = options::OptLevel > 1;
893 Conf.AlwaysEmitRegularLTOObj = !options::obj_path.empty();
894
895 if (options::thinlto_index_only) {
896 std::string OldPrefix, NewPrefix;
897 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
898 Backend = createWriteIndexesThinBackend(OldPrefix, NewPrefix,
899 options::thinlto_emit_imports_files,
900 LinkedObjectsFile, OnIndexWrite);
901 } else {
902 Backend = createInProcessThinBackend(
903 llvm::heavyweight_hardware_concurrency(options::Parallelism));
904 }
905
906 Conf.OverrideTriple = options::triple;
907 Conf.DefaultTriple = sys::getDefaultTargetTriple();
908
909 Conf.DiagHandler = diagnosticHandler;
910
911 switch (options::TheOutputType) {
912 case options::OT_NORMAL:
913 break;
914
915 case options::OT_DISABLE:
916 Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
917 break;
918
919 case options::OT_BC_ONLY:
920 Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
921 std::error_code EC;
922 SmallString<128> TaskFilename;
923 getOutputFileName(output_name, /* TempOutFile */ false, TaskFilename,
924 Task);
925 raw_fd_ostream OS(TaskFilename, EC, sys::fs::OpenFlags::OF_None);
926 if (EC)
927 message(LDPL_FATAL, "Failed to write the output file.");
928 WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ false);
929 return false;
930 };
931 break;
932
933 case options::OT_SAVE_TEMPS:
934 check(Conf.addSaveTemps(output_name + ".",
935 /* UseInputModulePath */ true));
936 break;
937 case options::OT_ASM_ONLY:
938 Conf.CGFileType = CGFT_AssemblyFile;
939 break;
940 }
941
942 if (!options::sample_profile.empty())
943 Conf.SampleProfile = options::sample_profile;
944
945 if (!options::cs_profile_path.empty())
946 Conf.CSIRProfile = options::cs_profile_path;
947 Conf.RunCSIRInstr = options::cs_pgo_gen;
948
949 Conf.DwoDir = options::dwo_dir;
950
951 // Set up optimization remarks handling.
952 Conf.RemarksFilename = options::RemarksFilename;
953 Conf.RemarksPasses = options::RemarksPasses;
954 Conf.RemarksWithHotness = options::RemarksWithHotness;
955 Conf.RemarksHotnessThreshold = options::RemarksHotnessThreshold;
956 Conf.RemarksFormat = options::RemarksFormat;
957
958 // Debug new pass manager if requested
959 Conf.DebugPassManager = options::debug_pass_manager;
960
961 Conf.HasWholeProgramVisibility = options::whole_program_visibility;
962
963 Conf.OpaquePointers = options::opaque_pointers;
964
965 Conf.StatsFile = options::stats_file;
966 return std::make_unique<LTO>(std::move(Conf), Backend,
967 options::ParallelCodeGenParallelismLevel);
968 }
969
970 // Write empty files that may be expected by a distributed build
971 // system when invoked with thinlto_index_only. This is invoked when
972 // the linker has decided not to include the given module in the
973 // final link. Frequently the distributed build system will want to
974 // confirm that all expected outputs are created based on all of the
975 // modules provided to the linker.
976 // If SkipModule is true then .thinlto.bc should contain just
977 // SkipModuleByDistributedBackend flag which requests distributed backend
978 // to skip the compilation of the corresponding module and produce an empty
979 // object file.
writeEmptyDistributedBuildOutputs(const std::string & ModulePath,const std::string & OldPrefix,const std::string & NewPrefix,bool SkipModule)980 static void writeEmptyDistributedBuildOutputs(const std::string &ModulePath,
981 const std::string &OldPrefix,
982 const std::string &NewPrefix,
983 bool SkipModule) {
984 std::string NewModulePath =
985 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
986 std::error_code EC;
987 {
988 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
989 sys::fs::OpenFlags::OF_None);
990 if (EC)
991 message(LDPL_FATAL, "Failed to write '%s': %s",
992 (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
993
994 if (SkipModule) {
995 ModuleSummaryIndex Index(/*HaveGVs*/ false);
996 Index.setSkipModuleByDistributedBackend();
997 writeIndexToFile(Index, OS, nullptr);
998 }
999 }
1000 if (options::thinlto_emit_imports_files) {
1001 raw_fd_ostream OS(NewModulePath + ".imports", EC,
1002 sys::fs::OpenFlags::OF_None);
1003 if (EC)
1004 message(LDPL_FATAL, "Failed to write '%s': %s",
1005 (NewModulePath + ".imports").c_str(), EC.message().c_str());
1006 }
1007 }
1008
1009 // Creates and returns output stream with a list of object files for final
1010 // linking of distributed ThinLTO.
CreateLinkedObjectsFile()1011 static std::unique_ptr<raw_fd_ostream> CreateLinkedObjectsFile() {
1012 if (options::thinlto_linked_objects_file.empty())
1013 return nullptr;
1014 assert(options::thinlto_index_only);
1015 std::error_code EC;
1016 auto LinkedObjectsFile = std::make_unique<raw_fd_ostream>(
1017 options::thinlto_linked_objects_file, EC, sys::fs::OpenFlags::OF_None);
1018 if (EC)
1019 message(LDPL_FATAL, "Failed to create '%s': %s",
1020 options::thinlto_linked_objects_file.c_str(), EC.message().c_str());
1021 return LinkedObjectsFile;
1022 }
1023
1024 /// Runs LTO and return a list of pairs <FileName, IsTemporary>.
runLTO()1025 static std::vector<std::pair<SmallString<128>, bool>> runLTO() {
1026 // Map to own RAII objects that manage the file opening and releasing
1027 // interfaces with gold. This is needed only for ThinLTO mode, since
1028 // unlike regular LTO, where addModule will result in the opened file
1029 // being merged into a new combined module, we need to keep these files open
1030 // through Lto->run().
1031 DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
1032
1033 // Owns string objects and tells if index file was already created.
1034 StringMap<bool> ObjectToIndexFileState;
1035
1036 std::unique_ptr<raw_fd_ostream> LinkedObjects = CreateLinkedObjectsFile();
1037 std::unique_ptr<LTO> Lto = createLTO(
1038 [&ObjectToIndexFileState](const std::string &Identifier) {
1039 ObjectToIndexFileState[Identifier] = true;
1040 },
1041 LinkedObjects.get());
1042
1043 std::string OldPrefix, NewPrefix;
1044 if (options::thinlto_index_only)
1045 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
1046
1047 std::string OldSuffix, NewSuffix;
1048 getThinLTOOldAndNewSuffix(OldSuffix, NewSuffix);
1049
1050 for (claimed_file &F : Modules) {
1051 if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
1052 HandleToInputFile.insert(std::make_pair(
1053 F.leader_handle, std::make_unique<PluginInputFile>(F.handle)));
1054 // In case we are thin linking with a minimized bitcode file, ensure
1055 // the module paths encoded in the index reflect where the backends
1056 // will locate the full bitcode files for compiling/importing.
1057 std::string Identifier =
1058 getThinLTOObjectFileName(F.name, OldSuffix, NewSuffix);
1059 auto ObjFilename = ObjectToIndexFileState.insert({Identifier, false});
1060 assert(ObjFilename.second);
1061 if (const void *View = getSymbolsAndView(F))
1062 addModule(*Lto, F, View, ObjFilename.first->first());
1063 else if (options::thinlto_index_only) {
1064 ObjFilename.first->second = true;
1065 writeEmptyDistributedBuildOutputs(Identifier, OldPrefix, NewPrefix,
1066 /* SkipModule */ true);
1067 }
1068 }
1069
1070 SmallString<128> Filename;
1071 // Note that getOutputFileName will append a unique ID for each task
1072 if (!options::obj_path.empty())
1073 Filename = options::obj_path;
1074 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
1075 Filename = output_name + ".lto.o";
1076 else if (options::TheOutputType == options::OT_ASM_ONLY)
1077 Filename = output_name;
1078 bool SaveTemps = !Filename.empty();
1079
1080 size_t MaxTasks = Lto->getMaxTasks();
1081 std::vector<std::pair<SmallString<128>, bool>> Files(MaxTasks);
1082
1083 auto AddStream =
1084 [&](size_t Task,
1085 const Twine &ModuleName) -> std::unique_ptr<CachedFileStream> {
1086 Files[Task].second = !SaveTemps;
1087 int FD = getOutputFileName(Filename, /* TempOutFile */ !SaveTemps,
1088 Files[Task].first, Task);
1089 return std::make_unique<CachedFileStream>(
1090 std::make_unique<llvm::raw_fd_ostream>(FD, true));
1091 };
1092
1093 auto AddBuffer = [&](size_t Task, const Twine &moduleName,
1094 std::unique_ptr<MemoryBuffer> MB) {
1095 *AddStream(Task, moduleName)->OS << MB->getBuffer();
1096 };
1097
1098 FileCache Cache;
1099 if (!options::cache_dir.empty())
1100 Cache = check(localCache("ThinLTO", "Thin", options::cache_dir, AddBuffer));
1101
1102 check(Lto->run(AddStream, Cache));
1103
1104 // Write empty output files that may be expected by the distributed build
1105 // system.
1106 if (options::thinlto_index_only)
1107 for (auto &Identifier : ObjectToIndexFileState)
1108 if (!Identifier.getValue())
1109 writeEmptyDistributedBuildOutputs(std::string(Identifier.getKey()),
1110 OldPrefix, NewPrefix,
1111 /* SkipModule */ false);
1112
1113 return Files;
1114 }
1115
1116 /// gold informs us that all symbols have been read. At this point, we use
1117 /// get_symbols to see if any of our definitions have been overridden by a
1118 /// native object file. Then, perform optimization and codegen.
allSymbolsReadHook()1119 static ld_plugin_status allSymbolsReadHook() {
1120 if (Modules.empty())
1121 return LDPS_OK;
1122
1123 if (unsigned NumOpts = options::extra.size())
1124 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
1125
1126 std::vector<std::pair<SmallString<128>, bool>> Files = runLTO();
1127
1128 if (options::TheOutputType == options::OT_DISABLE ||
1129 options::TheOutputType == options::OT_BC_ONLY ||
1130 options::TheOutputType == options::OT_ASM_ONLY)
1131 return LDPS_OK;
1132
1133 if (options::thinlto_index_only) {
1134 llvm_shutdown();
1135 cleanup_hook();
1136 exit(0);
1137 }
1138
1139 for (const auto &F : Files)
1140 if (!F.first.empty())
1141 recordFile(std::string(F.first.str()), F.second);
1142
1143 if (!options::extra_library_path.empty() &&
1144 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
1145 message(LDPL_FATAL, "Unable to set the extra library path.");
1146
1147 return LDPS_OK;
1148 }
1149
all_symbols_read_hook(void)1150 static ld_plugin_status all_symbols_read_hook(void) {
1151 ld_plugin_status Ret = allSymbolsReadHook();
1152 llvm_shutdown();
1153
1154 if (options::TheOutputType == options::OT_BC_ONLY ||
1155 options::TheOutputType == options::OT_ASM_ONLY ||
1156 options::TheOutputType == options::OT_DISABLE) {
1157 if (options::TheOutputType == options::OT_DISABLE) {
1158 // Remove the output file here since ld.bfd creates the output file
1159 // early.
1160 std::error_code EC = sys::fs::remove(output_name);
1161 if (EC)
1162 message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
1163 EC.message().c_str());
1164 }
1165 exit(0);
1166 }
1167
1168 return Ret;
1169 }
1170
cleanup_hook(void)1171 static ld_plugin_status cleanup_hook(void) {
1172 for (std::string &Name : Cleanup) {
1173 std::error_code EC = sys::fs::remove(Name);
1174 if (EC)
1175 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
1176 EC.message().c_str());
1177 }
1178
1179 // Prune cache
1180 if (!options::cache_dir.empty()) {
1181 CachePruningPolicy policy = check(parseCachePruningPolicy(options::cache_policy));
1182 pruneCache(options::cache_dir, policy);
1183 }
1184
1185 return LDPS_OK;
1186 }
1187