1 //===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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 .
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Bitcode/BitcodeReader.h"
17 #include "llvm/Bitcode/BitcodeWriter.h"
18 #include "llvm/CodeGen/CommandFlags.inc"
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/CachePruning.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/TargetSelect.h"
32 #include "llvm/Support/raw_ostream.h"
35 #include <plugin-api.h>
37 #include <system_error>
41 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
42 // Precise and Debian Wheezy (binutils 2.23 is required)
45 #define LDPT_GET_SYMBOLS_V3 28
47 // FIXME: Remove when binutils 2.31 (containing gold 1.16) is the minimum
49 #define LDPT_GET_WRAP_SYMBOLS 32
54 // FIXME: Remove when binutils 2.31 (containing gold 1.16) is the minimum
56 typedef enum ld_plugin_status (*ld_plugin_get_wrap_symbols
)(
57 uint64_t *num_symbols
, const char ***wrap_symbol_list
);
59 static ld_plugin_status
discard_message(int level
, const char *format
, ...) {
60 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
61 // callback in the transfer vector. This should never be called.
65 static ld_plugin_release_input_file release_input_file
= nullptr;
66 static ld_plugin_get_input_file get_input_file
= nullptr;
67 static ld_plugin_message message
= discard_message
;
68 static ld_plugin_get_wrap_symbols get_wrap_symbols
= nullptr;
74 std::vector
<ld_plugin_symbol
> syms
;
79 /// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
80 struct PluginInputFile
{
82 std::unique_ptr
<ld_plugin_input_file
> File
;
84 PluginInputFile(void *Handle
) : Handle(Handle
) {
85 File
= llvm::make_unique
<ld_plugin_input_file
>();
86 if (get_input_file(Handle
, File
.get()) != LDPS_OK
)
87 message(LDPL_FATAL
, "Failed to get file information");
90 // File would have been reset to nullptr if we moved this object
93 if (release_input_file(Handle
) != LDPS_OK
)
94 message(LDPL_FATAL
, "Failed to release file information");
97 ld_plugin_input_file
&file() { return *File
; }
99 PluginInputFile(PluginInputFile
&&RHS
) = default;
100 PluginInputFile
&operator=(PluginInputFile
&&RHS
) = default;
103 struct ResolutionInfo
{
104 bool CanOmitFromDynSym
= true;
105 bool DefaultVisibility
= true;
106 bool CanInline
= true;
107 bool IsUsedInRegularObj
= false;
112 static ld_plugin_add_symbols add_symbols
= nullptr;
113 static ld_plugin_get_symbols get_symbols
= nullptr;
114 static ld_plugin_add_input_file add_input_file
= nullptr;
115 static ld_plugin_set_extra_library_path set_extra_library_path
= nullptr;
116 static ld_plugin_get_view get_view
= nullptr;
117 static bool IsExecutable
= false;
118 static bool SplitSections
= true;
119 static Optional
<Reloc::Model
> RelocationModel
= None
;
120 static std::string output_name
= "";
121 static std::list
<claimed_file
> Modules
;
122 static DenseMap
<int, void *> FDToLeaderHandle
;
123 static StringMap
<ResolutionInfo
> ResInfo
;
124 static std::vector
<std::string
> Cleanup
;
134 static OutputType TheOutputType
= OT_NORMAL
;
135 static unsigned OptLevel
= 2;
136 // Default parallelism of 0 used to indicate that user did not specify.
137 // Actual parallelism default value depends on implementation.
138 // Currently only affects ThinLTO, where the default is
139 // llvm::heavyweight_hardware_concurrency.
140 static unsigned Parallelism
= 0;
141 // Default regular LTO codegen parallelism (number of partitions).
142 static unsigned ParallelCodeGenParallelismLevel
= 1;
144 static bool DisableVerify
= true;
146 static bool DisableVerify
= false;
148 static std::string obj_path
;
149 static std::string extra_library_path
;
150 static std::string triple
;
151 static std::string mcpu
;
152 // When the thinlto plugin option is specified, only read the function
153 // the information from intermediate files and write a combined
154 // global index for the ThinLTO backends.
155 static bool thinlto
= false;
156 // If false, all ThinLTO backend compilations through code gen are performed
157 // using multiple threads in the gold-plugin, before handing control back to
158 // gold. If true, write individual backend index files which reflect
159 // the import decisions, and exit afterwards. The assumption is
160 // that the build system will launch the backend processes.
161 static bool thinlto_index_only
= false;
162 // If non-empty, holds the name of a file in which to write the list of
163 // oject files gold selected for inclusion in the link after symbol
164 // resolution (i.e. they had selected symbols). This will only be non-empty
165 // in the thinlto_index_only case. It is used to identify files, which may
166 // have originally been within archive libraries specified via
167 // --start-lib/--end-lib pairs, that should be included in the final
168 // native link process (since intervening function importing and inlining
169 // may change the symbol resolution detected in the final link and which
170 // files to include out of --start-lib/--end-lib libraries as a result).
171 static std::string thinlto_linked_objects_file
;
172 // If true, when generating individual index files for distributed backends,
173 // also generate a "${bitcodefile}.imports" file at the same location for each
174 // bitcode file, listing the files it imports from in plain text. This is to
175 // support distributed build file staging.
176 static bool thinlto_emit_imports_files
= false;
177 // Option to control where files for a distributed backend (the individual
178 // index files and optional imports files) are created.
179 // If specified, expects a string of the form "oldprefix:newprefix", and
180 // instead of generating these files in the same directory path as the
181 // corresponding bitcode file, will use a path formed by replacing the
182 // bitcode file's path prefix matching oldprefix with newprefix.
183 static std::string thinlto_prefix_replace
;
184 // Option to control the name of modules encoded in the individual index
185 // files for a distributed backend. This enables the use of minimized
186 // bitcode files for the thin link, assuming the name of the full bitcode
187 // file used in the backend differs just in some part of the file suffix.
188 // If specified, expects a string of the form "oldsuffix:newsuffix".
189 static std::string thinlto_object_suffix_replace
;
190 // Optional path to a directory for caching ThinLTO objects.
191 static std::string cache_dir
;
192 // Optional pruning policy for ThinLTO caches.
193 static std::string cache_policy
;
194 // Additional options to pass into the code generator.
195 // Note: This array will contain all plugin options which are not claimed
196 // as plugin exclusive to pass to the code generator.
197 static std::vector
<const char *> extra
;
198 // Sample profile file path
199 static std::string sample_profile
;
201 static bool new_pass_manager
= false;
202 // Debug new pass manager
203 static bool debug_pass_manager
= false;
204 // Directory to store the .dwo files.
205 static std::string dwo_dir
;
206 /// Statistics output filename.
207 static std::string stats_file
;
209 // Optimization remarks filename and hotness options
210 static std::string OptRemarksFilename
;
211 static bool OptRemarksWithHotness
= false;
213 static void process_plugin_option(const char *opt_
)
217 llvm::StringRef opt
= opt_
;
219 if (opt
.startswith("mcpu=")) {
220 mcpu
= opt
.substr(strlen("mcpu="));
221 } else if (opt
.startswith("extra-library-path=")) {
222 extra_library_path
= opt
.substr(strlen("extra_library_path="));
223 } else if (opt
.startswith("mtriple=")) {
224 triple
= opt
.substr(strlen("mtriple="));
225 } else if (opt
.startswith("obj-path=")) {
226 obj_path
= opt
.substr(strlen("obj-path="));
227 } else if (opt
== "emit-llvm") {
228 TheOutputType
= OT_BC_ONLY
;
229 } else if (opt
== "save-temps") {
230 TheOutputType
= OT_SAVE_TEMPS
;
231 } else if (opt
== "disable-output") {
232 TheOutputType
= OT_DISABLE
;
233 } else if (opt
== "emit-asm") {
234 TheOutputType
= OT_ASM_ONLY
;
235 } else if (opt
== "thinlto") {
237 } else if (opt
== "thinlto-index-only") {
238 thinlto_index_only
= true;
239 } else if (opt
.startswith("thinlto-index-only=")) {
240 thinlto_index_only
= true;
241 thinlto_linked_objects_file
= opt
.substr(strlen("thinlto-index-only="));
242 } else if (opt
== "thinlto-emit-imports-files") {
243 thinlto_emit_imports_files
= true;
244 } else if (opt
.startswith("thinlto-prefix-replace=")) {
245 thinlto_prefix_replace
= opt
.substr(strlen("thinlto-prefix-replace="));
246 if (thinlto_prefix_replace
.find(';') == std::string::npos
)
247 message(LDPL_FATAL
, "thinlto-prefix-replace expects 'old;new' format");
248 } else if (opt
.startswith("thinlto-object-suffix-replace=")) {
249 thinlto_object_suffix_replace
=
250 opt
.substr(strlen("thinlto-object-suffix-replace="));
251 if (thinlto_object_suffix_replace
.find(';') == std::string::npos
)
253 "thinlto-object-suffix-replace expects 'old;new' format");
254 } else if (opt
.startswith("cache-dir=")) {
255 cache_dir
= opt
.substr(strlen("cache-dir="));
256 } else if (opt
.startswith("cache-policy=")) {
257 cache_policy
= opt
.substr(strlen("cache-policy="));
258 } else if (opt
.size() == 2 && opt
[0] == 'O') {
259 if (opt
[1] < '0' || opt
[1] > '3')
260 message(LDPL_FATAL
, "Optimization level must be between 0 and 3");
261 OptLevel
= opt
[1] - '0';
262 } else if (opt
.startswith("jobs=")) {
263 if (StringRef(opt_
+ 5).getAsInteger(10, Parallelism
))
264 message(LDPL_FATAL
, "Invalid parallelism level: %s", opt_
+ 5);
265 } else if (opt
.startswith("lto-partitions=")) {
266 if (opt
.substr(strlen("lto-partitions="))
267 .getAsInteger(10, ParallelCodeGenParallelismLevel
))
268 message(LDPL_FATAL
, "Invalid codegen partition level: %s", opt_
+ 5);
269 } else if (opt
== "disable-verify") {
270 DisableVerify
= true;
271 } else if (opt
.startswith("sample-profile=")) {
272 sample_profile
= opt
.substr(strlen("sample-profile="));
273 } else if (opt
== "new-pass-manager") {
274 new_pass_manager
= true;
275 } else if (opt
== "debug-pass-manager") {
276 debug_pass_manager
= true;
277 } else if (opt
.startswith("dwo_dir=")) {
278 dwo_dir
= opt
.substr(strlen("dwo_dir="));
279 } else if (opt
.startswith("opt-remarks-filename=")) {
280 OptRemarksFilename
= opt
.substr(strlen("opt-remarks-filename="));
281 } else if (opt
== "opt-remarks-with-hotness") {
282 OptRemarksWithHotness
= true;
283 } else if (opt
.startswith("stats-file=")) {
284 stats_file
= opt
.substr(strlen("stats-file="));
286 // Save this option to pass to the code generator.
287 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
290 extra
.push_back("LLVMgold");
292 extra
.push_back(opt_
);
297 static ld_plugin_status
claim_file_hook(const ld_plugin_input_file
*file
,
299 static ld_plugin_status
all_symbols_read_hook(void);
300 static ld_plugin_status
cleanup_hook(void);
302 extern "C" ld_plugin_status
onload(ld_plugin_tv
*tv
);
303 ld_plugin_status
onload(ld_plugin_tv
*tv
) {
304 InitializeAllTargetInfos();
305 InitializeAllTargets();
306 InitializeAllTargetMCs();
307 InitializeAllAsmParsers();
308 InitializeAllAsmPrinters();
310 // We're given a pointer to the first transfer vector. We read through them
311 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
312 // contain pointers to functions that we need to call to register our own
313 // hooks. The others are addresses of functions we can use to call into gold
316 bool registeredClaimFile
= false;
317 bool RegisteredAllSymbolsRead
= false;
319 for (; tv
->tv_tag
!= LDPT_NULL
; ++tv
) {
320 // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
321 // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
323 switch (static_cast<int>(tv
->tv_tag
)) {
324 case LDPT_OUTPUT_NAME
:
325 output_name
= tv
->tv_u
.tv_string
;
327 case LDPT_LINKER_OUTPUT
:
328 switch (tv
->tv_u
.tv_val
) {
330 IsExecutable
= false;
331 SplitSections
= false;
333 case LDPO_DYN
: // .so
334 IsExecutable
= false;
335 RelocationModel
= Reloc::PIC_
;
337 case LDPO_PIE
: // position independent executable
339 RelocationModel
= Reloc::PIC_
;
341 case LDPO_EXEC
: // .exe
343 RelocationModel
= Reloc::Static
;
346 message(LDPL_ERROR
, "Unknown output file type %d", tv
->tv_u
.tv_val
);
351 options::process_plugin_option(tv
->tv_u
.tv_string
);
353 case LDPT_REGISTER_CLAIM_FILE_HOOK
: {
354 ld_plugin_register_claim_file callback
;
355 callback
= tv
->tv_u
.tv_register_claim_file
;
357 if (callback(claim_file_hook
) != LDPS_OK
)
360 registeredClaimFile
= true;
362 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK
: {
363 ld_plugin_register_all_symbols_read callback
;
364 callback
= tv
->tv_u
.tv_register_all_symbols_read
;
366 if (callback(all_symbols_read_hook
) != LDPS_OK
)
369 RegisteredAllSymbolsRead
= true;
371 case LDPT_REGISTER_CLEANUP_HOOK
: {
372 ld_plugin_register_cleanup callback
;
373 callback
= tv
->tv_u
.tv_register_cleanup
;
375 if (callback(cleanup_hook
) != LDPS_OK
)
378 case LDPT_GET_INPUT_FILE
:
379 get_input_file
= tv
->tv_u
.tv_get_input_file
;
381 case LDPT_RELEASE_INPUT_FILE
:
382 release_input_file
= tv
->tv_u
.tv_release_input_file
;
384 case LDPT_ADD_SYMBOLS
:
385 add_symbols
= tv
->tv_u
.tv_add_symbols
;
387 case LDPT_GET_SYMBOLS_V2
:
388 // Do not override get_symbols_v3 with get_symbols_v2.
390 get_symbols
= tv
->tv_u
.tv_get_symbols
;
392 case LDPT_GET_SYMBOLS_V3
:
393 get_symbols
= tv
->tv_u
.tv_get_symbols
;
395 case LDPT_ADD_INPUT_FILE
:
396 add_input_file
= tv
->tv_u
.tv_add_input_file
;
398 case LDPT_SET_EXTRA_LIBRARY_PATH
:
399 set_extra_library_path
= tv
->tv_u
.tv_set_extra_library_path
;
402 get_view
= tv
->tv_u
.tv_get_view
;
405 message
= tv
->tv_u
.tv_message
;
407 case LDPT_GET_WRAP_SYMBOLS
:
408 // FIXME: When binutils 2.31 (containing gold 1.16) is the minimum
409 // required version, this should be changed to:
410 // get_wrap_symbols = tv->tv_u.tv_get_wrap_symbols;
412 (ld_plugin_get_wrap_symbols
)tv
->tv_u
.tv_message
;
419 if (!registeredClaimFile
) {
420 message(LDPL_ERROR
, "register_claim_file not passed to LLVMgold.");
424 message(LDPL_ERROR
, "add_symbols not passed to LLVMgold.");
428 if (!RegisteredAllSymbolsRead
)
431 if (!get_input_file
) {
432 message(LDPL_ERROR
, "get_input_file not passed to LLVMgold.");
435 if (!release_input_file
) {
436 message(LDPL_ERROR
, "release_input_file not passed to LLVMgold.");
443 static void diagnosticHandler(const DiagnosticInfo
&DI
) {
444 std::string ErrStorage
;
446 raw_string_ostream
OS(ErrStorage
);
447 DiagnosticPrinterRawOStream
DP(OS
);
450 ld_plugin_level Level
;
451 switch (DI
.getSeverity()) {
456 Level
= LDPL_WARNING
;
463 message(Level
, "LLVM gold plugin: %s", ErrStorage
.c_str());
466 static void check(Error E
, std::string Msg
= "LLVM gold plugin") {
467 handleAllErrors(std::move(E
), [&](ErrorInfoBase
&EIB
) -> Error
{
468 message(LDPL_FATAL
, "%s: %s", Msg
.c_str(), EIB
.message().c_str());
469 return Error::success();
473 template <typename T
> static T
check(Expected
<T
> E
) {
475 return std::move(*E
);
476 check(E
.takeError());
480 /// Called by gold to see whether this file is one that our plugin can handle.
481 /// We'll try to open it and register all the symbols with add_symbol if
483 static ld_plugin_status
claim_file_hook(const ld_plugin_input_file
*file
,
485 MemoryBufferRef BufferRef
;
486 std::unique_ptr
<MemoryBuffer
> Buffer
;
489 if (get_view(file
->handle
, &view
) != LDPS_OK
) {
490 message(LDPL_ERROR
, "Failed to get a view of %s", file
->name
);
494 MemoryBufferRef(StringRef((const char *)view
, file
->filesize
), "");
497 // Gold has found what might be IR part-way inside of a file, such as
500 offset
= file
->offset
;
502 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufferOrErr
=
503 MemoryBuffer::getOpenFileSlice(file
->fd
, file
->name
, file
->filesize
,
505 if (std::error_code EC
= BufferOrErr
.getError()) {
506 message(LDPL_ERROR
, EC
.message().c_str());
509 Buffer
= std::move(BufferOrErr
.get());
510 BufferRef
= Buffer
->getMemBufferRef();
515 Expected
<std::unique_ptr
<InputFile
>> ObjOrErr
= InputFile::create(BufferRef
);
517 handleAllErrors(ObjOrErr
.takeError(), [&](const ErrorInfoBase
&EI
) {
518 std::error_code EC
= EI
.convertToErrorCode();
519 if (EC
== object::object_error::invalid_file_type
||
520 EC
== object::object_error::bitcode_section_not_found
)
524 "LLVM gold plugin has failed to create LTO module: %s",
525 EI
.message().c_str());
528 return *claimed
? LDPS_ERR
: LDPS_OK
;
531 std::unique_ptr
<InputFile
> Obj
= std::move(*ObjOrErr
);
533 Modules
.emplace_back();
534 claimed_file
&cf
= Modules
.back();
536 cf
.handle
= file
->handle
;
537 // Keep track of the first handle for each file descriptor, since there are
538 // multiple in the case of an archive. This is used later in the case of
539 // ThinLTO parallel backends to ensure that each file is only opened and
542 FDToLeaderHandle
.insert(std::make_pair(file
->fd
, file
->handle
)).first
;
543 cf
.leader_handle
= LeaderHandle
->second
;
544 // Save the filesize since for parallel ThinLTO backends we can only
545 // invoke get_input_file once per archive (only for the leader handle).
546 cf
.filesize
= file
->filesize
;
547 // In the case of an archive library, all but the first member must have a
548 // non-zero offset, which we can append to the file name to obtain a
550 cf
.name
= file
->name
;
552 cf
.name
+= ".llvm." + std::to_string(file
->offset
) + "." +
553 sys::path::filename(Obj
->getSourceFileName()).str();
555 for (auto &Sym
: Obj
->symbols()) {
556 cf
.syms
.push_back(ld_plugin_symbol());
557 ld_plugin_symbol
&sym
= cf
.syms
.back();
558 sym
.version
= nullptr;
559 StringRef Name
= Sym
.getName();
560 sym
.name
= strdup(Name
.str().c_str());
562 ResolutionInfo
&Res
= ResInfo
[Name
];
564 Res
.CanOmitFromDynSym
&= Sym
.canBeOmittedFromSymbolTable();
566 sym
.visibility
= LDPV_DEFAULT
;
567 GlobalValue::VisibilityTypes Vis
= Sym
.getVisibility();
568 if (Vis
!= GlobalValue::DefaultVisibility
)
569 Res
.DefaultVisibility
= false;
571 case GlobalValue::DefaultVisibility
:
573 case GlobalValue::HiddenVisibility
:
574 sym
.visibility
= LDPV_HIDDEN
;
576 case GlobalValue::ProtectedVisibility
:
577 sym
.visibility
= LDPV_PROTECTED
;
581 if (Sym
.isUndefined()) {
582 sym
.def
= LDPK_UNDEF
;
584 sym
.def
= LDPK_WEAKUNDEF
;
585 } else if (Sym
.isCommon())
586 sym
.def
= LDPK_COMMON
;
587 else if (Sym
.isWeak())
588 sym
.def
= LDPK_WEAKDEF
;
593 sym
.comdat_key
= nullptr;
594 int CI
= Sym
.getComdatIndex();
596 StringRef C
= Obj
->getComdatTable()[CI
];
597 sym
.comdat_key
= strdup(C
.str().c_str());
600 sym
.resolution
= LDPR_UNKNOWN
;
603 if (!cf
.syms
.empty()) {
604 if (add_symbols(cf
.handle
, cf
.syms
.size(), cf
.syms
.data()) != LDPS_OK
) {
605 message(LDPL_ERROR
, "Unable to add symbols!");
610 // Handle any --wrap options passed to gold, which are than passed
611 // along to the plugin.
612 if (get_wrap_symbols
) {
613 const char **wrap_symbols
;
615 if (get_wrap_symbols(&count
, &wrap_symbols
) != LDPS_OK
) {
616 message(LDPL_ERROR
, "Unable to get wrap symbols!");
619 for (uint64_t i
= 0; i
< count
; i
++) {
620 StringRef Name
= wrap_symbols
[i
];
621 ResolutionInfo
&Res
= ResInfo
[Name
];
622 ResolutionInfo
&WrapRes
= ResInfo
["__wrap_" + Name
.str()];
623 ResolutionInfo
&RealRes
= ResInfo
["__real_" + Name
.str()];
624 // Tell LTO not to inline symbols that will be overwritten.
625 Res
.CanInline
= false;
626 RealRes
.CanInline
= false;
627 // Tell LTO not to eliminate symbols that will be used after renaming.
628 Res
.IsUsedInRegularObj
= true;
629 WrapRes
.IsUsedInRegularObj
= true;
636 static void freeSymName(ld_plugin_symbol
&Sym
) {
638 free(Sym
.comdat_key
);
640 Sym
.comdat_key
= nullptr;
643 /// Helper to get a file's symbols and a view into it via gold callbacks.
644 static const void *getSymbolsAndView(claimed_file
&F
) {
645 ld_plugin_status status
= get_symbols(F
.handle
, F
.syms
.size(), F
.syms
.data());
646 if (status
== LDPS_NO_SYMS
)
649 if (status
!= LDPS_OK
)
650 message(LDPL_FATAL
, "Failed to get symbol information");
653 if (get_view(F
.handle
, &View
) != LDPS_OK
)
654 message(LDPL_FATAL
, "Failed to get a view of file");
659 /// Parse the thinlto-object-suffix-replace option into the \p OldSuffix and
660 /// \p NewSuffix strings, if it was specified.
661 static void getThinLTOOldAndNewSuffix(std::string
&OldSuffix
,
662 std::string
&NewSuffix
) {
663 assert(options::thinlto_object_suffix_replace
.empty() ||
664 options::thinlto_object_suffix_replace
.find(";") != StringRef::npos
);
665 StringRef SuffixReplace
= options::thinlto_object_suffix_replace
;
666 std::tie(OldSuffix
, NewSuffix
) = SuffixReplace
.split(';');
669 /// Given the original \p Path to an output file, replace any filename
670 /// suffix matching \p OldSuffix with \p NewSuffix.
671 static std::string
getThinLTOObjectFileName(StringRef Path
, StringRef OldSuffix
,
672 StringRef NewSuffix
) {
673 if (Path
.consume_back(OldSuffix
))
674 return (Path
+ NewSuffix
).str();
678 // Returns true if S is valid as a C language identifier.
679 static bool isValidCIdentifier(StringRef S
) {
680 return !S
.empty() && (isAlpha(S
[0]) || S
[0] == '_') &&
681 std::all_of(S
.begin() + 1, S
.end(),
682 [](char C
) { return C
== '_' || isAlnum(C
); });
685 static bool isUndefined(ld_plugin_symbol
&Sym
) {
686 return Sym
.def
== LDPK_UNDEF
|| Sym
.def
== LDPK_WEAKUNDEF
;
689 static void addModule(LTO
&Lto
, claimed_file
&F
, const void *View
,
690 StringRef Filename
) {
691 MemoryBufferRef
BufferRef(StringRef((const char *)View
, F
.filesize
),
693 Expected
<std::unique_ptr
<InputFile
>> ObjOrErr
= InputFile::create(BufferRef
);
696 message(LDPL_FATAL
, "Could not read bitcode from file : %s",
697 toString(ObjOrErr
.takeError()).c_str());
700 std::unique_ptr
<InputFile
> Input
= std::move(ObjOrErr
.get());
701 auto InputFileSyms
= Input
->symbols();
702 assert(InputFileSyms
.size() == F
.syms
.size());
703 std::vector
<SymbolResolution
> Resols(F
.syms
.size());
704 for (ld_plugin_symbol
&Sym
: F
.syms
) {
705 const InputFile::Symbol
&InpSym
= InputFileSyms
[SymNum
];
706 SymbolResolution
&R
= Resols
[SymNum
++];
708 ld_plugin_symbol_resolution Resolution
=
709 (ld_plugin_symbol_resolution
)Sym
.resolution
;
711 ResolutionInfo
&Res
= ResInfo
[Sym
.name
];
713 switch (Resolution
) {
715 llvm_unreachable("Unexpected resolution");
717 case LDPR_RESOLVED_IR
:
718 case LDPR_RESOLVED_EXEC
:
719 case LDPR_RESOLVED_DYN
:
720 case LDPR_PREEMPTED_IR
:
721 case LDPR_PREEMPTED_REG
:
725 case LDPR_PREVAILING_DEF_IRONLY
:
726 R
.Prevailing
= !isUndefined(Sym
);
729 case LDPR_PREVAILING_DEF
:
730 R
.Prevailing
= !isUndefined(Sym
);
731 R
.VisibleToRegularObj
= true;
734 case LDPR_PREVAILING_DEF_IRONLY_EXP
:
735 R
.Prevailing
= !isUndefined(Sym
);
736 if (!Res
.CanOmitFromDynSym
)
737 R
.VisibleToRegularObj
= true;
741 // If the symbol has a C identifier section name, we need to mark
742 // it as visible to a regular object so that LTO will keep it around
743 // to ensure the linker generates special __start_<secname> and
744 // __stop_<secname> symbols which may be used elsewhere.
745 if (isValidCIdentifier(InpSym
.getSectionName()))
746 R
.VisibleToRegularObj
= true;
748 if (Resolution
!= LDPR_RESOLVED_DYN
&& Resolution
!= LDPR_UNDEF
&&
749 (IsExecutable
|| !Res
.DefaultVisibility
))
750 R
.FinalDefinitionInLinkageUnit
= true;
753 R
.LinkerRedefined
= true;
755 if (Res
.IsUsedInRegularObj
)
756 R
.VisibleToRegularObj
= true;
761 check(Lto
.add(std::move(Input
), Resols
),
762 std::string("Failed to link module ") + F
.name
);
765 static void recordFile(const std::string
&Filename
, bool TempOutFile
) {
766 if (add_input_file(Filename
.c_str()) != LDPS_OK
)
768 "Unable to add .o file to the link. File left behind in: %s",
771 Cleanup
.push_back(Filename
);
774 /// Return the desired output filename given a base input name, a flag
775 /// indicating whether a temp file should be generated, and an optional task id.
776 /// The new filename generated is returned in \p NewFilename.
777 static int getOutputFileName(StringRef InFilename
, bool TempOutFile
,
778 SmallString
<128> &NewFilename
, int TaskID
) {
782 sys::fs::createTemporaryFile("lto-llvm", "o", FD
, NewFilename
);
784 message(LDPL_FATAL
, "Could not create temporary file: %s",
785 EC
.message().c_str());
787 NewFilename
= InFilename
;
789 NewFilename
+= utostr(TaskID
);
791 sys::fs::openFileForWrite(NewFilename
, FD
, sys::fs::CD_CreateAlways
);
793 message(LDPL_FATAL
, "Could not open file %s: %s", NewFilename
.c_str(),
794 EC
.message().c_str());
799 static CodeGenOpt::Level
getCGOptLevel() {
800 switch (options::OptLevel
) {
802 return CodeGenOpt::None
;
804 return CodeGenOpt::Less
;
806 return CodeGenOpt::Default
;
808 return CodeGenOpt::Aggressive
;
810 llvm_unreachable("Invalid optimization level");
813 /// Parse the thinlto_prefix_replace option into the \p OldPrefix and
814 /// \p NewPrefix strings, if it was specified.
815 static void getThinLTOOldAndNewPrefix(std::string
&OldPrefix
,
816 std::string
&NewPrefix
) {
817 StringRef PrefixReplace
= options::thinlto_prefix_replace
;
818 assert(PrefixReplace
.empty() || PrefixReplace
.find(";") != StringRef::npos
);
819 std::tie(OldPrefix
, NewPrefix
) = PrefixReplace
.split(';');
822 /// Creates instance of LTO.
823 /// OnIndexWrite is callback to let caller know when LTO writes index files.
824 /// LinkedObjectsFile is an output stream to write the list of object files for
825 /// the final ThinLTO linking. Can be nullptr.
826 static std::unique_ptr
<LTO
> createLTO(IndexWriteCallback OnIndexWrite
,
827 raw_fd_ostream
*LinkedObjectsFile
) {
831 Conf
.CPU
= options::mcpu
;
832 Conf
.Options
= InitTargetOptionsFromCodeGenFlags();
834 // Disable the new X86 relax relocations since gold might not support them.
835 // FIXME: Check the gold version or add a new option to enable them.
836 Conf
.Options
.RelaxELFRelocations
= false;
838 // Toggle function/data sections.
839 if (FunctionSections
.getNumOccurrences() == 0)
840 Conf
.Options
.FunctionSections
= SplitSections
;
841 if (DataSections
.getNumOccurrences() == 0)
842 Conf
.Options
.DataSections
= SplitSections
;
844 Conf
.MAttrs
= MAttrs
;
845 Conf
.RelocModel
= RelocationModel
;
846 Conf
.CodeModel
= getCodeModel();
847 Conf
.CGOptLevel
= getCGOptLevel();
848 Conf
.DisableVerify
= options::DisableVerify
;
849 Conf
.OptLevel
= options::OptLevel
;
850 if (options::Parallelism
)
851 Backend
= createInProcessThinBackend(options::Parallelism
);
852 if (options::thinlto_index_only
) {
853 std::string OldPrefix
, NewPrefix
;
854 getThinLTOOldAndNewPrefix(OldPrefix
, NewPrefix
);
855 Backend
= createWriteIndexesThinBackend(OldPrefix
, NewPrefix
,
856 options::thinlto_emit_imports_files
,
857 LinkedObjectsFile
, OnIndexWrite
);
860 Conf
.OverrideTriple
= options::triple
;
861 Conf
.DefaultTriple
= sys::getDefaultTargetTriple();
863 Conf
.DiagHandler
= diagnosticHandler
;
865 switch (options::TheOutputType
) {
866 case options::OT_NORMAL
:
869 case options::OT_DISABLE
:
870 Conf
.PreOptModuleHook
= [](size_t Task
, const Module
&M
) { return false; };
873 case options::OT_BC_ONLY
:
874 Conf
.PostInternalizeModuleHook
= [](size_t Task
, const Module
&M
) {
876 raw_fd_ostream
OS(output_name
, EC
, sys::fs::OpenFlags::F_None
);
878 message(LDPL_FATAL
, "Failed to write the output file.");
879 WriteBitcodeToFile(M
, OS
, /* ShouldPreserveUseListOrder */ false);
884 case options::OT_SAVE_TEMPS
:
885 check(Conf
.addSaveTemps(output_name
+ ".",
886 /* UseInputModulePath */ true));
888 case options::OT_ASM_ONLY
:
889 Conf
.CGFileType
= TargetMachine::CGFT_AssemblyFile
;
893 if (!options::sample_profile
.empty())
894 Conf
.SampleProfile
= options::sample_profile
;
896 Conf
.DwoDir
= options::dwo_dir
;
898 // Set up optimization remarks handling.
899 Conf
.RemarksFilename
= options::OptRemarksFilename
;
900 Conf
.RemarksWithHotness
= options::OptRemarksWithHotness
;
902 // Use new pass manager if set in driver
903 Conf
.UseNewPM
= options::new_pass_manager
;
904 // Debug new pass manager if requested
905 Conf
.DebugPassManager
= options::debug_pass_manager
;
907 Conf
.StatsFile
= options::stats_file
;
908 return llvm::make_unique
<LTO
>(std::move(Conf
), Backend
,
909 options::ParallelCodeGenParallelismLevel
);
912 // Write empty files that may be expected by a distributed build
913 // system when invoked with thinlto_index_only. This is invoked when
914 // the linker has decided not to include the given module in the
915 // final link. Frequently the distributed build system will want to
916 // confirm that all expected outputs are created based on all of the
917 // modules provided to the linker.
918 // If SkipModule is true then .thinlto.bc should contain just
919 // SkipModuleByDistributedBackend flag which requests distributed backend
920 // to skip the compilation of the corresponding module and produce an empty
922 static void writeEmptyDistributedBuildOutputs(const std::string
&ModulePath
,
923 const std::string
&OldPrefix
,
924 const std::string
&NewPrefix
,
926 std::string NewModulePath
=
927 getThinLTOOutputFile(ModulePath
, OldPrefix
, NewPrefix
);
930 raw_fd_ostream
OS(NewModulePath
+ ".thinlto.bc", EC
,
931 sys::fs::OpenFlags::F_None
);
933 message(LDPL_FATAL
, "Failed to write '%s': %s",
934 (NewModulePath
+ ".thinlto.bc").c_str(), EC
.message().c_str());
937 ModuleSummaryIndex
Index(/*HaveGVs*/ false);
938 Index
.setSkipModuleByDistributedBackend();
939 WriteIndexToFile(Index
, OS
, nullptr);
942 if (options::thinlto_emit_imports_files
) {
943 raw_fd_ostream
OS(NewModulePath
+ ".imports", EC
,
944 sys::fs::OpenFlags::F_None
);
946 message(LDPL_FATAL
, "Failed to write '%s': %s",
947 (NewModulePath
+ ".imports").c_str(), EC
.message().c_str());
951 // Creates and returns output stream with a list of object files for final
952 // linking of distributed ThinLTO.
953 static std::unique_ptr
<raw_fd_ostream
> CreateLinkedObjectsFile() {
954 if (options::thinlto_linked_objects_file
.empty())
956 assert(options::thinlto_index_only
);
958 auto LinkedObjectsFile
= llvm::make_unique
<raw_fd_ostream
>(
959 options::thinlto_linked_objects_file
, EC
, sys::fs::OpenFlags::F_None
);
961 message(LDPL_FATAL
, "Failed to create '%s': %s",
962 options::thinlto_linked_objects_file
.c_str(), EC
.message().c_str());
963 return LinkedObjectsFile
;
966 /// Runs LTO and return a list of pairs <FileName, IsTemporary>.
967 static std::vector
<std::pair
<SmallString
<128>, bool>> runLTO() {
968 // Map to own RAII objects that manage the file opening and releasing
969 // interfaces with gold. This is needed only for ThinLTO mode, since
970 // unlike regular LTO, where addModule will result in the opened file
971 // being merged into a new combined module, we need to keep these files open
972 // through Lto->run().
973 DenseMap
<void *, std::unique_ptr
<PluginInputFile
>> HandleToInputFile
;
975 // Owns string objects and tells if index file was already created.
976 StringMap
<bool> ObjectToIndexFileState
;
978 std::unique_ptr
<raw_fd_ostream
> LinkedObjects
= CreateLinkedObjectsFile();
979 std::unique_ptr
<LTO
> Lto
= createLTO(
980 [&ObjectToIndexFileState
](const std::string
&Identifier
) {
981 ObjectToIndexFileState
[Identifier
] = true;
983 LinkedObjects
.get());
985 std::string OldPrefix
, NewPrefix
;
986 if (options::thinlto_index_only
)
987 getThinLTOOldAndNewPrefix(OldPrefix
, NewPrefix
);
989 std::string OldSuffix
, NewSuffix
;
990 getThinLTOOldAndNewSuffix(OldSuffix
, NewSuffix
);
992 for (claimed_file
&F
: Modules
) {
993 if (options::thinlto
&& !HandleToInputFile
.count(F
.leader_handle
))
994 HandleToInputFile
.insert(std::make_pair(
995 F
.leader_handle
, llvm::make_unique
<PluginInputFile
>(F
.handle
)));
996 // In case we are thin linking with a minimized bitcode file, ensure
997 // the module paths encoded in the index reflect where the backends
998 // will locate the full bitcode files for compiling/importing.
999 std::string Identifier
=
1000 getThinLTOObjectFileName(F
.name
, OldSuffix
, NewSuffix
);
1001 auto ObjFilename
= ObjectToIndexFileState
.insert({Identifier
, false});
1002 assert(ObjFilename
.second
);
1003 if (const void *View
= getSymbolsAndView(F
))
1004 addModule(*Lto
, F
, View
, ObjFilename
.first
->first());
1005 else if (options::thinlto_index_only
) {
1006 ObjFilename
.first
->second
= true;
1007 writeEmptyDistributedBuildOutputs(Identifier
, OldPrefix
, NewPrefix
,
1008 /* SkipModule */ true);
1012 SmallString
<128> Filename
;
1013 // Note that getOutputFileName will append a unique ID for each task
1014 if (!options::obj_path
.empty())
1015 Filename
= options::obj_path
;
1016 else if (options::TheOutputType
== options::OT_SAVE_TEMPS
)
1017 Filename
= output_name
+ ".o";
1018 else if (options::TheOutputType
== options::OT_ASM_ONLY
)
1019 Filename
= output_name
;
1020 bool SaveTemps
= !Filename
.empty();
1022 size_t MaxTasks
= Lto
->getMaxTasks();
1023 std::vector
<std::pair
<SmallString
<128>, bool>> Files(MaxTasks
);
1026 [&](size_t Task
) -> std::unique_ptr
<lto::NativeObjectStream
> {
1027 Files
[Task
].second
= !SaveTemps
;
1028 int FD
= getOutputFileName(Filename
, /* TempOutFile */ !SaveTemps
,
1029 Files
[Task
].first
, Task
);
1030 return llvm::make_unique
<lto::NativeObjectStream
>(
1031 llvm::make_unique
<llvm::raw_fd_ostream
>(FD
, true));
1034 auto AddBuffer
= [&](size_t Task
, std::unique_ptr
<MemoryBuffer
> MB
) {
1035 *AddStream(Task
)->OS
<< MB
->getBuffer();
1038 NativeObjectCache Cache
;
1039 if (!options::cache_dir
.empty())
1040 Cache
= check(localCache(options::cache_dir
, AddBuffer
));
1042 check(Lto
->run(AddStream
, Cache
));
1044 // Write empty output files that may be expected by the distributed build
1046 if (options::thinlto_index_only
)
1047 for (auto &Identifier
: ObjectToIndexFileState
)
1048 if (!Identifier
.getValue())
1049 writeEmptyDistributedBuildOutputs(Identifier
.getKey(), OldPrefix
,
1050 NewPrefix
, /* SkipModule */ false);
1055 /// gold informs us that all symbols have been read. At this point, we use
1056 /// get_symbols to see if any of our definitions have been overridden by a
1057 /// native object file. Then, perform optimization and codegen.
1058 static ld_plugin_status
allSymbolsReadHook() {
1059 if (Modules
.empty())
1062 if (unsigned NumOpts
= options::extra
.size())
1063 cl::ParseCommandLineOptions(NumOpts
, &options::extra
[0]);
1065 std::vector
<std::pair
<SmallString
<128>, bool>> Files
= runLTO();
1067 if (options::TheOutputType
== options::OT_DISABLE
||
1068 options::TheOutputType
== options::OT_BC_ONLY
||
1069 options::TheOutputType
== options::OT_ASM_ONLY
)
1072 if (options::thinlto_index_only
) {
1078 for (const auto &F
: Files
)
1079 if (!F
.first
.empty())
1080 recordFile(F
.first
.str(), F
.second
);
1082 if (!options::extra_library_path
.empty() &&
1083 set_extra_library_path(options::extra_library_path
.c_str()) != LDPS_OK
)
1084 message(LDPL_FATAL
, "Unable to set the extra library path.");
1089 static ld_plugin_status
all_symbols_read_hook(void) {
1090 ld_plugin_status Ret
= allSymbolsReadHook();
1093 if (options::TheOutputType
== options::OT_BC_ONLY
||
1094 options::TheOutputType
== options::OT_ASM_ONLY
||
1095 options::TheOutputType
== options::OT_DISABLE
) {
1096 if (options::TheOutputType
== options::OT_DISABLE
) {
1097 // Remove the output file here since ld.bfd creates the output file
1099 std::error_code EC
= sys::fs::remove(output_name
);
1101 message(LDPL_ERROR
, "Failed to delete '%s': %s", output_name
.c_str(),
1102 EC
.message().c_str());
1110 static ld_plugin_status
cleanup_hook(void) {
1111 for (std::string
&Name
: Cleanup
) {
1112 std::error_code EC
= sys::fs::remove(Name
);
1114 message(LDPL_ERROR
, "Failed to delete '%s': %s", Name
.c_str(),
1115 EC
.message().c_str());
1119 if (!options::cache_dir
.empty()) {
1120 CachePruningPolicy policy
= check(parseCachePruningPolicy(options::cache_policy
));
1121 pruneCache(options::cache_dir
, policy
);