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/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/StringSet.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/CodeGen/Analysis.h"
22 #include "llvm/CodeGen/CommandFlags.h"
23 #include "llvm/CodeGen/ParallelCG.h"
24 #include "llvm/IR/AutoUpgrade.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Verifier.h"
32 #include "llvm/Linker/IRMover.h"
33 #include "llvm/MC/SubtargetFeature.h"
34 #include "llvm/Object/FunctionIndexObjectFile.h"
35 #include "llvm/Object/IRObjectFile.h"
36 #include "llvm/Support/Host.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Transforms/IPO.h"
43 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
44 #include "llvm/Transforms/Utils/GlobalStatus.h"
45 #include "llvm/Transforms/Utils/ModuleUtils.h"
46 #include "llvm/Transforms/Utils/ValueMapper.h"
48 #include <plugin-api.h>
49 #include <system_error>
53 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
54 // Precise and Debian Wheezy (binutils 2.23 is required)
63 std::vector<ld_plugin_symbol> syms;
66 struct ResolutionInfo {
67 bool IsLinkonceOdr = true;
68 bool UnnamedAddr = true;
69 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
70 bool CommonInternal = false;
71 bool UseCommon = false;
72 unsigned CommonSize = 0;
73 unsigned CommonAlign = 0;
74 claimed_file *CommonFile = nullptr;
78 static ld_plugin_status discard_message(int level, const char *format, ...) {
79 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
80 // callback in the transfer vector. This should never be called.
84 static ld_plugin_get_input_file get_input_file = nullptr;
85 static ld_plugin_release_input_file release_input_file = nullptr;
86 static ld_plugin_add_symbols add_symbols = nullptr;
87 static ld_plugin_get_symbols get_symbols = nullptr;
88 static ld_plugin_add_input_file add_input_file = nullptr;
89 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
90 static ld_plugin_get_view get_view = nullptr;
91 static ld_plugin_message message = discard_message;
92 static Reloc::Model RelocationModel = Reloc::Default;
93 static std::string output_name = "";
94 static std::list<claimed_file> Modules;
95 static StringMap<ResolutionInfo> ResInfo;
96 static std::vector<std::string> Cleanup;
97 static llvm::TargetOptions TargetOpts;
106 static bool generate_api_file = false;
107 static OutputType TheOutputType = OT_NORMAL;
108 static unsigned OptLevel = 2;
109 static unsigned Parallelism = 1;
111 static bool DisableVerify = true;
113 static bool DisableVerify = false;
115 static std::string obj_path;
116 static std::string extra_library_path;
117 static std::string triple;
118 static std::string mcpu;
119 // When the thinlto plugin option is specified, only read the function
120 // the information from intermediate files and write a combined
121 // global index for the ThinLTO backends.
122 static bool thinlto = false;
123 // Additional options to pass into the code generator.
124 // Note: This array will contain all plugin options which are not claimed
125 // as plugin exclusive to pass to the code generator.
126 // For example, "generate-api-file" and "as"options are for the plugin
127 // use only and will not be passed.
128 static std::vector<const char *> extra;
130 static void process_plugin_option(const char *opt_)
134 llvm::StringRef opt = opt_;
136 if (opt == "generate-api-file") {
137 generate_api_file = true;
138 } else if (opt.startswith("mcpu=")) {
139 mcpu = opt.substr(strlen("mcpu="));
140 } else if (opt.startswith("extra-library-path=")) {
141 extra_library_path = opt.substr(strlen("extra_library_path="));
142 } else if (opt.startswith("mtriple=")) {
143 triple = opt.substr(strlen("mtriple="));
144 } else if (opt.startswith("obj-path=")) {
145 obj_path = opt.substr(strlen("obj-path="));
146 } else if (opt == "emit-llvm") {
147 TheOutputType = OT_BC_ONLY;
148 } else if (opt == "save-temps") {
149 TheOutputType = OT_SAVE_TEMPS;
150 } else if (opt == "disable-output") {
151 TheOutputType = OT_DISABLE;
152 } else if (opt == "thinlto") {
154 } else if (opt.size() == 2 && opt[0] == 'O') {
155 if (opt[1] < '0' || opt[1] > '3')
156 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
157 OptLevel = opt[1] - '0';
158 } else if (opt.startswith("jobs=")) {
159 if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
160 message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
161 } else if (opt == "disable-verify") {
162 DisableVerify = true;
164 // Save this option to pass to the code generator.
165 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
168 extra.push_back("LLVMgold");
170 extra.push_back(opt_);
175 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
177 static ld_plugin_status all_symbols_read_hook(void);
178 static ld_plugin_status cleanup_hook(void);
180 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
181 ld_plugin_status onload(ld_plugin_tv *tv) {
182 InitializeAllTargetInfos();
183 InitializeAllTargets();
184 InitializeAllTargetMCs();
185 InitializeAllAsmParsers();
186 InitializeAllAsmPrinters();
188 // We're given a pointer to the first transfer vector. We read through them
189 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
190 // contain pointers to functions that we need to call to register our own
191 // hooks. The others are addresses of functions we can use to call into gold
194 bool registeredClaimFile = false;
195 bool RegisteredAllSymbolsRead = false;
197 for (; tv->tv_tag != LDPT_NULL; ++tv) {
198 switch (tv->tv_tag) {
199 case LDPT_OUTPUT_NAME:
200 output_name = tv->tv_u.tv_string;
202 case LDPT_LINKER_OUTPUT:
203 switch (tv->tv_u.tv_val) {
205 case LDPO_DYN: // .so
206 case LDPO_PIE: // position independent executable
207 RelocationModel = Reloc::PIC_;
209 case LDPO_EXEC: // .exe
210 RelocationModel = Reloc::Static;
213 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
218 options::process_plugin_option(tv->tv_u.tv_string);
220 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
221 ld_plugin_register_claim_file callback;
222 callback = tv->tv_u.tv_register_claim_file;
224 if (callback(claim_file_hook) != LDPS_OK)
227 registeredClaimFile = true;
229 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
230 ld_plugin_register_all_symbols_read callback;
231 callback = tv->tv_u.tv_register_all_symbols_read;
233 if (callback(all_symbols_read_hook) != LDPS_OK)
236 RegisteredAllSymbolsRead = true;
238 case LDPT_REGISTER_CLEANUP_HOOK: {
239 ld_plugin_register_cleanup callback;
240 callback = tv->tv_u.tv_register_cleanup;
242 if (callback(cleanup_hook) != LDPS_OK)
245 case LDPT_GET_INPUT_FILE:
246 get_input_file = tv->tv_u.tv_get_input_file;
248 case LDPT_RELEASE_INPUT_FILE:
249 release_input_file = tv->tv_u.tv_release_input_file;
251 case LDPT_ADD_SYMBOLS:
252 add_symbols = tv->tv_u.tv_add_symbols;
254 case LDPT_GET_SYMBOLS_V2:
255 get_symbols = tv->tv_u.tv_get_symbols;
257 case LDPT_ADD_INPUT_FILE:
258 add_input_file = tv->tv_u.tv_add_input_file;
260 case LDPT_SET_EXTRA_LIBRARY_PATH:
261 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
264 get_view = tv->tv_u.tv_get_view;
267 message = tv->tv_u.tv_message;
274 if (!registeredClaimFile) {
275 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
279 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
283 if (!RegisteredAllSymbolsRead)
286 if (!get_input_file) {
287 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
290 if (!release_input_file) {
291 message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
298 static const GlobalObject *getBaseObject(const GlobalValue &GV) {
299 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
300 return GA->getBaseObject();
301 return cast<GlobalObject>(&GV);
304 static bool shouldSkip(uint32_t Symflags) {
305 if (!(Symflags & object::BasicSymbolRef::SF_Global))
307 if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
312 static void diagnosticHandler(const DiagnosticInfo &DI) {
313 if (const auto *BDI = dyn_cast<BitcodeDiagnosticInfo>(&DI)) {
314 std::error_code EC = BDI->getError();
315 if (EC == BitcodeError::InvalidBitcodeSignature)
319 std::string ErrStorage;
321 raw_string_ostream OS(ErrStorage);
322 DiagnosticPrinterRawOStream DP(OS);
325 ld_plugin_level Level;
326 switch (DI.getSeverity()) {
328 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
330 llvm_unreachable("Fatal doesn't return.");
332 Level = LDPL_WARNING;
339 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
342 static void diagnosticHandlerForContext(const DiagnosticInfo &DI,
344 diagnosticHandler(DI);
347 static GlobalValue::VisibilityTypes
348 getMinVisibility(GlobalValue::VisibilityTypes A,
349 GlobalValue::VisibilityTypes B) {
350 if (A == GlobalValue::HiddenVisibility)
352 if (B == GlobalValue::HiddenVisibility)
354 if (A == GlobalValue::ProtectedVisibility)
359 /// Called by gold to see whether this file is one that our plugin can handle.
360 /// We'll try to open it and register all the symbols with add_symbol if
362 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
365 MemoryBufferRef BufferRef;
366 std::unique_ptr<MemoryBuffer> Buffer;
369 if (get_view(file->handle, &view) != LDPS_OK) {
370 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
374 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
377 // Gold has found what might be IR part-way inside of a file, such as
380 offset = file->offset;
382 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
383 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
385 if (std::error_code EC = BufferOrErr.getError()) {
386 message(LDPL_ERROR, EC.message().c_str());
389 Buffer = std::move(BufferOrErr.get());
390 BufferRef = Buffer->getMemBufferRef();
393 Context.setDiagnosticHandler(diagnosticHandlerForContext);
394 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
395 object::IRObjectFile::create(BufferRef, Context);
396 std::error_code EC = ObjOrErr.getError();
397 if (EC == object::object_error::invalid_file_type ||
398 EC == object::object_error::bitcode_section_not_found)
404 message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
405 EC.message().c_str());
408 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
410 Modules.resize(Modules.size() + 1);
411 claimed_file &cf = Modules.back();
413 cf.handle = file->handle;
415 // If we are doing ThinLTO compilation, don't need to process the symbols.
416 // Later we simply build a combined index file after all files are claimed.
417 if (options::thinlto)
420 for (auto &Sym : Obj->symbols()) {
421 uint32_t Symflags = Sym.getFlags();
422 if (shouldSkip(Symflags))
425 cf.syms.push_back(ld_plugin_symbol());
426 ld_plugin_symbol &sym = cf.syms.back();
427 sym.version = nullptr;
429 SmallString<64> Name;
431 raw_svector_ostream OS(Name);
434 sym.name = strdup(Name.c_str());
436 const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
438 ResolutionInfo &Res = ResInfo[sym.name];
440 sym.visibility = LDPV_DEFAULT;
442 Res.UnnamedAddr &= GV->hasUnnamedAddr();
443 Res.IsLinkonceOdr &= GV->hasLinkOnceLinkage();
444 if (GV->hasCommonLinkage()) {
445 Res.CommonAlign = std::max(Res.CommonAlign, GV->getAlignment());
446 const DataLayout &DL = GV->getParent()->getDataLayout();
447 uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
448 if (Size >= Res.CommonSize) {
449 Res.CommonSize = Size;
450 Res.CommonFile = &cf;
453 Res.Visibility = getMinVisibility(Res.Visibility, GV->getVisibility());
454 switch (GV->getVisibility()) {
455 case GlobalValue::DefaultVisibility:
456 sym.visibility = LDPV_DEFAULT;
458 case GlobalValue::HiddenVisibility:
459 sym.visibility = LDPV_HIDDEN;
461 case GlobalValue::ProtectedVisibility:
462 sym.visibility = LDPV_PROTECTED;
467 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
468 sym.def = LDPK_UNDEF;
469 if (GV && GV->hasExternalWeakLinkage())
470 sym.def = LDPK_WEAKUNDEF;
474 assert(!GV->hasExternalWeakLinkage() &&
475 !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
476 if (GV->hasCommonLinkage())
477 sym.def = LDPK_COMMON;
478 else if (GV->isWeakForLinker())
479 sym.def = LDPK_WEAKDEF;
484 sym.comdat_key = nullptr;
486 const GlobalObject *Base = getBaseObject(*GV);
488 message(LDPL_FATAL, "Unable to determine comdat of alias!");
489 const Comdat *C = Base->getComdat();
491 sym.comdat_key = strdup(C->getName().str().c_str());
494 sym.resolution = LDPR_UNKNOWN;
497 if (!cf.syms.empty()) {
498 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
499 message(LDPL_ERROR, "Unable to add symbols!");
507 static void internalize(GlobalValue &GV) {
508 if (GV.isDeclarationForLinker())
509 return; // We get here if there is a matching asm definition.
510 if (!GV.hasLocalLinkage())
511 GV.setLinkage(GlobalValue::InternalLinkage);
514 static const char *getResolutionName(ld_plugin_symbol_resolution R) {
520 case LDPR_PREVAILING_DEF:
521 return "PREVAILING_DEF";
522 case LDPR_PREVAILING_DEF_IRONLY:
523 return "PREVAILING_DEF_IRONLY";
524 case LDPR_PREEMPTED_REG:
525 return "PREEMPTED_REG";
526 case LDPR_PREEMPTED_IR:
527 return "PREEMPTED_IR";
528 case LDPR_RESOLVED_IR:
529 return "RESOLVED_IR";
530 case LDPR_RESOLVED_EXEC:
531 return "RESOLVED_EXEC";
532 case LDPR_RESOLVED_DYN:
533 return "RESOLVED_DYN";
534 case LDPR_PREVAILING_DEF_IRONLY_EXP:
535 return "PREVAILING_DEF_IRONLY_EXP";
537 llvm_unreachable("Unknown resolution");
540 static void freeSymName(ld_plugin_symbol &Sym) {
542 free(Sym.comdat_key);
544 Sym.comdat_key = nullptr;
547 static std::unique_ptr<FunctionInfoIndex>
548 getFunctionIndexForFile(claimed_file &F, ld_plugin_input_file &Info) {
550 if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
551 message(LDPL_FATAL, "Failed to get symbol information");
554 if (get_view(F.handle, &View) != LDPS_OK)
555 message(LDPL_FATAL, "Failed to get a view of file");
557 MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize),
560 // Don't bother trying to build an index if there is no summary information
561 // in this bitcode file.
562 if (!object::FunctionIndexObjectFile::hasFunctionSummaryInMemBuffer(
563 BufferRef, diagnosticHandler))
564 return std::unique_ptr<FunctionInfoIndex>(nullptr);
566 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
567 object::FunctionIndexObjectFile::create(BufferRef, diagnosticHandler);
569 if (std::error_code EC = ObjOrErr.getError())
570 message(LDPL_FATAL, "Could not read function index bitcode from file : %s",
571 EC.message().c_str());
573 object::FunctionIndexObjectFile &Obj = **ObjOrErr;
575 return Obj.takeIndex();
578 static std::unique_ptr<Module>
579 getModuleForFile(LLVMContext &Context, claimed_file &F,
580 ld_plugin_input_file &Info, raw_fd_ostream *ApiFile,
581 StringSet<> &Internalize, StringSet<> &Maybe,
582 std::vector<GlobalValue *> &Keep) {
584 if (get_symbols(F.handle, F.syms.size(), F.syms.data()) != LDPS_OK)
585 message(LDPL_FATAL, "Failed to get symbol information");
588 if (get_view(F.handle, &View) != LDPS_OK)
589 message(LDPL_FATAL, "Failed to get a view of file");
591 MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize),
593 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
594 object::IRObjectFile::create(BufferRef, Context);
596 if (std::error_code EC = ObjOrErr.getError())
597 message(LDPL_FATAL, "Could not read bitcode from file : %s",
598 EC.message().c_str());
600 object::IRObjectFile &Obj = **ObjOrErr;
602 Module &M = Obj.getModule();
604 M.materializeMetadata();
607 SmallPtrSet<GlobalValue *, 8> Used;
608 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
611 for (auto &ObjSym : Obj.symbols()) {
612 GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
613 if (GV && GV->hasAppendingLinkage())
616 if (shouldSkip(ObjSym.getFlags()))
618 ld_plugin_symbol &Sym = F.syms[SymNum];
621 ld_plugin_symbol_resolution Resolution =
622 (ld_plugin_symbol_resolution)Sym.resolution;
624 if (options::generate_api_file)
625 *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
629 continue; // Asm symbol.
632 ResolutionInfo &Res = ResInfo[Sym.name];
633 if (Resolution == LDPR_PREVAILING_DEF_IRONLY_EXP && !Res.IsLinkonceOdr)
634 Resolution = LDPR_PREVAILING_DEF;
636 GV->setUnnamedAddr(Res.UnnamedAddr);
637 GV->setVisibility(Res.Visibility);
639 // Override gold's resolution for common symbols. We want the largest
641 if (GV->hasCommonLinkage()) {
642 cast<GlobalVariable>(GV)->setAlignment(Res.CommonAlign);
643 if (Resolution == LDPR_PREVAILING_DEF_IRONLY)
644 Res.CommonInternal = true;
646 if (Resolution == LDPR_PREVAILING_DEF_IRONLY ||
647 Resolution == LDPR_PREVAILING_DEF)
648 Res.UseCommon = true;
650 if (Res.CommonFile == &F && Res.UseCommon) {
651 if (Res.CommonInternal)
652 Resolution = LDPR_PREVAILING_DEF_IRONLY;
654 Resolution = LDPR_PREVAILING_DEF;
656 Resolution = LDPR_PREEMPTED_IR;
660 switch (Resolution) {
662 llvm_unreachable("Unexpected resolution");
664 case LDPR_RESOLVED_IR:
665 case LDPR_RESOLVED_EXEC:
666 case LDPR_RESOLVED_DYN:
667 case LDPR_PREEMPTED_IR:
668 case LDPR_PREEMPTED_REG:
672 if (!GV->isDeclarationForLinker())
673 assert(GV->hasComdat());
676 case LDPR_PREVAILING_DEF_IRONLY: {
678 // The IR linker has to be able to map this value to a declaration,
679 // so we can only internalize after linking.
681 Internalize.insert(GV->getName());
685 case LDPR_PREVAILING_DEF:
687 // There is a non IR use, so we have to force optimizations to keep this.
688 switch (GV->getLinkage()) {
691 case GlobalValue::LinkOnceAnyLinkage:
692 GV->setLinkage(GlobalValue::WeakAnyLinkage);
694 case GlobalValue::LinkOnceODRLinkage:
695 GV->setLinkage(GlobalValue::WeakODRLinkage);
700 case LDPR_PREVAILING_DEF_IRONLY_EXP: {
701 // We can only check for address uses after we merge the modules. The
702 // reason is that this GV might have a copy in another module
703 // and in that module the address might be significant, but that
704 // copy will be LDPR_PREEMPTED_IR.
705 Maybe.insert(GV->getName());
714 return Obj.takeModule();
717 static void runLTOPasses(Module &M, TargetMachine &TM) {
718 M.setDataLayout(TM.createDataLayout());
720 legacy::PassManager passes;
721 passes.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
723 PassManagerBuilder PMB;
724 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
725 PMB.Inliner = createFunctionInliningPass();
726 // Unconditionally verify input since it is not verified before this
727 // point and has unknown origin.
728 PMB.VerifyInput = true;
729 PMB.VerifyOutput = !options::DisableVerify;
730 PMB.LoopVectorize = true;
731 PMB.SLPVectorize = true;
732 PMB.OptLevel = options::OptLevel;
733 PMB.populateLTOPassManager(passes);
737 static void saveBCFile(StringRef Path, Module &M) {
739 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
741 message(LDPL_FATAL, "Failed to write the output file.");
742 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true);
745 static void codegen(std::unique_ptr<Module> M) {
746 const std::string &TripleStr = M->getTargetTriple();
747 Triple TheTriple(TripleStr);
750 const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
752 message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
754 if (unsigned NumOpts = options::extra.size())
755 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
757 SubtargetFeatures Features;
758 Features.getDefaultSubtargetFeatures(TheTriple);
759 for (const std::string &A : MAttrs)
760 Features.AddFeature(A);
762 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
763 CodeGenOpt::Level CGOptLevel;
764 switch (options::OptLevel) {
766 CGOptLevel = CodeGenOpt::None;
769 CGOptLevel = CodeGenOpt::Less;
772 CGOptLevel = CodeGenOpt::Default;
775 CGOptLevel = CodeGenOpt::Aggressive;
778 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
779 TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
780 CodeModel::Default, CGOptLevel));
782 runLTOPasses(*M, *TM);
784 if (options::TheOutputType == options::OT_SAVE_TEMPS)
785 saveBCFile(output_name + ".opt.bc", *M);
787 SmallString<128> Filename;
788 if (!options::obj_path.empty())
789 Filename = options::obj_path;
790 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
791 Filename = output_name + ".o";
793 std::vector<SmallString<128>> Filenames(options::Parallelism);
794 bool TempOutFile = Filename.empty();
796 // Open a file descriptor for each backend thread. This is done in a block
797 // so that the output file descriptors are closed before gold opens them.
798 std::list<llvm::raw_fd_ostream> OSs;
799 std::vector<llvm::raw_pwrite_stream *> OSPtrs(options::Parallelism);
800 for (unsigned I = 0; I != options::Parallelism; ++I) {
804 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filenames[I]);
806 message(LDPL_FATAL, "Could not create temporary file: %s",
807 EC.message().c_str());
809 Filenames[I] = Filename;
810 if (options::Parallelism != 1)
811 Filenames[I] += utostr(I);
813 sys::fs::openFileForWrite(Filenames[I], FD, sys::fs::F_None);
815 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
817 OSs.emplace_back(FD, true);
818 OSPtrs[I] = &OSs.back();
821 // Run backend threads.
822 splitCodeGen(std::move(M), OSPtrs, options::mcpu, Features.getString(),
823 Options, RelocationModel, CodeModel::Default, CGOptLevel);
826 for (auto &Filename : Filenames) {
827 if (add_input_file(Filename.c_str()) != LDPS_OK)
829 "Unable to add .o file to the link. File left behind in: %s",
832 Cleanup.push_back(Filename.c_str());
836 /// gold informs us that all symbols have been read. At this point, we use
837 /// get_symbols to see if any of our definitions have been overridden by a
838 /// native object file. Then, perform optimization and codegen.
839 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
843 // If we are doing ThinLTO compilation, simply build the combined
844 // function index/summary and emit it. We don't need to parse the modules
845 // and link them in this case.
846 if (options::thinlto) {
847 FunctionInfoIndex CombinedIndex;
848 uint64_t NextModuleId = 0;
849 for (claimed_file &F : Modules) {
850 ld_plugin_input_file File;
851 if (get_input_file(F.handle, &File) != LDPS_OK)
852 message(LDPL_FATAL, "Failed to get file information");
854 std::unique_ptr<FunctionInfoIndex> Index =
855 getFunctionIndexForFile(F, File);
857 // Skip files without a function summary.
861 CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
863 if (release_input_file(F.handle) != LDPS_OK)
864 message(LDPL_FATAL, "Failed to release file information");
868 raw_fd_ostream OS(output_name + ".thinlto.bc", EC,
869 sys::fs::OpenFlags::F_None);
871 message(LDPL_FATAL, "Unable to open %s.thinlto.bc for writing: %s",
872 output_name.data(), EC.message().c_str());
873 WriteFunctionSummaryToFile(CombinedIndex, OS);
881 Context.setDiagnosticHandler(diagnosticHandlerForContext, nullptr, true);
883 std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
884 IRMover L(*Combined, diagnosticHandler);
886 std::string DefaultTriple = sys::getDefaultTargetTriple();
888 StringSet<> Internalize;
890 for (claimed_file &F : Modules) {
891 ld_plugin_input_file File;
892 if (get_input_file(F.handle, &File) != LDPS_OK)
893 message(LDPL_FATAL, "Failed to get file information");
894 std::vector<GlobalValue *> Keep;
895 std::unique_ptr<Module> M =
896 getModuleForFile(Context, F, File, ApiFile, Internalize, Maybe, Keep);
897 if (!options::triple.empty())
898 M->setTargetTriple(options::triple.c_str());
899 else if (M->getTargetTriple().empty())
900 M->setTargetTriple(DefaultTriple);
902 if (L.move(*M, Keep, [](GlobalValue &, IRMover::ValueAdder) {}))
903 message(LDPL_FATAL, "Failed to link module");
904 if (release_input_file(F.handle) != LDPS_OK)
905 message(LDPL_FATAL, "Failed to release file information");
908 for (const auto &Name : Internalize) {
909 GlobalValue *GV = Combined->getNamedValue(Name.first());
914 for (const auto &Name : Maybe) {
915 GlobalValue *GV = Combined->getNamedValue(Name.first());
918 GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
919 if (canBeOmittedFromSymbolTable(GV))
923 if (options::TheOutputType == options::OT_DISABLE)
926 if (options::TheOutputType != options::OT_NORMAL) {
928 if (options::TheOutputType == options::OT_BC_ONLY)
931 path = output_name + ".bc";
932 saveBCFile(path, *Combined);
933 if (options::TheOutputType == options::OT_BC_ONLY)
937 codegen(std::move(Combined));
939 if (!options::extra_library_path.empty() &&
940 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
941 message(LDPL_FATAL, "Unable to set the extra library path.");
946 static ld_plugin_status all_symbols_read_hook(void) {
947 ld_plugin_status Ret;
948 if (!options::generate_api_file) {
949 Ret = allSymbolsReadHook(nullptr);
952 raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
954 message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
955 EC.message().c_str());
956 Ret = allSymbolsReadHook(&ApiFile);
961 if (options::TheOutputType == options::OT_BC_ONLY ||
962 options::TheOutputType == options::OT_DISABLE) {
963 if (options::TheOutputType == options::OT_DISABLE)
964 // Remove the output file here since ld.bfd creates the output file
966 sys::fs::remove(output_name);
973 static ld_plugin_status cleanup_hook(void) {
974 for (std::string &Name : Cleanup) {
975 std::error_code EC = sys::fs::remove(Name);
977 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
978 EC.message().c_str());