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/Linker.h"
33 #include "llvm/MC/SubtargetFeature.h"
34 #include "llvm/Object/IRObjectFile.h"
35 #include "llvm/Support/raw_ostream.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/Transforms/IPO.h"
42 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
43 #include "llvm/Transforms/Utils/GlobalStatus.h"
44 #include "llvm/Transforms/Utils/ModuleUtils.h"
45 #include "llvm/Transforms/Utils/ValueMapper.h"
47 #include <plugin-api.h>
48 #include <system_error>
52 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
53 // Precise and Debian Wheezy (binutils 2.23 is required)
62 std::vector<ld_plugin_symbol> syms;
66 static ld_plugin_status discard_message(int level, const char *format, ...) {
67 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
68 // callback in the transfer vector. This should never be called.
72 static ld_plugin_get_input_file get_input_file = nullptr;
73 static ld_plugin_release_input_file release_input_file = nullptr;
74 static ld_plugin_add_symbols add_symbols = nullptr;
75 static ld_plugin_get_symbols get_symbols = nullptr;
76 static ld_plugin_add_input_file add_input_file = nullptr;
77 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
78 static ld_plugin_get_view get_view = nullptr;
79 static ld_plugin_message message = discard_message;
80 static Reloc::Model RelocationModel = Reloc::Default;
81 static std::string output_name = "";
82 static std::list<claimed_file> Modules;
83 static std::vector<std::string> Cleanup;
84 static llvm::TargetOptions TargetOpts;
93 static bool generate_api_file = false;
94 static OutputType TheOutputType = OT_NORMAL;
95 static unsigned OptLevel = 2;
96 static unsigned Parallelism = 1;
98 static bool DisableVerify = true;
100 static bool DisableVerify = false;
102 static std::string obj_path;
103 static std::string extra_library_path;
104 static std::string triple;
105 static std::string mcpu;
106 // Additional options to pass into the code generator.
107 // Note: This array will contain all plugin options which are not claimed
108 // as plugin exclusive to pass to the code generator.
109 // For example, "generate-api-file" and "as"options are for the plugin
110 // use only and will not be passed.
111 static std::vector<const char *> extra;
113 static void process_plugin_option(const char *opt_)
117 llvm::StringRef opt = opt_;
119 if (opt == "generate-api-file") {
120 generate_api_file = true;
121 } else if (opt.startswith("mcpu=")) {
122 mcpu = opt.substr(strlen("mcpu="));
123 } else if (opt.startswith("extra-library-path=")) {
124 extra_library_path = opt.substr(strlen("extra_library_path="));
125 } else if (opt.startswith("mtriple=")) {
126 triple = opt.substr(strlen("mtriple="));
127 } else if (opt.startswith("obj-path=")) {
128 obj_path = opt.substr(strlen("obj-path="));
129 } else if (opt == "emit-llvm") {
130 TheOutputType = OT_BC_ONLY;
131 } else if (opt == "save-temps") {
132 TheOutputType = OT_SAVE_TEMPS;
133 } else if (opt == "disable-output") {
134 TheOutputType = OT_DISABLE;
135 } else if (opt.size() == 2 && opt[0] == 'O') {
136 if (opt[1] < '0' || opt[1] > '3')
137 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
138 OptLevel = opt[1] - '0';
139 } else if (opt.startswith("jobs=")) {
140 if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
141 message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
142 } else if (opt == "disable-verify") {
143 DisableVerify = true;
145 // Save this option to pass to the code generator.
146 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
149 extra.push_back("LLVMgold");
151 extra.push_back(opt_);
156 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
158 static ld_plugin_status all_symbols_read_hook(void);
159 static ld_plugin_status cleanup_hook(void);
161 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
162 ld_plugin_status onload(ld_plugin_tv *tv) {
163 InitializeAllTargetInfos();
164 InitializeAllTargets();
165 InitializeAllTargetMCs();
166 InitializeAllAsmParsers();
167 InitializeAllAsmPrinters();
169 // We're given a pointer to the first transfer vector. We read through them
170 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
171 // contain pointers to functions that we need to call to register our own
172 // hooks. The others are addresses of functions we can use to call into gold
175 bool registeredClaimFile = false;
176 bool RegisteredAllSymbolsRead = false;
178 for (; tv->tv_tag != LDPT_NULL; ++tv) {
179 switch (tv->tv_tag) {
180 case LDPT_OUTPUT_NAME:
181 output_name = tv->tv_u.tv_string;
183 case LDPT_LINKER_OUTPUT:
184 switch (tv->tv_u.tv_val) {
186 case LDPO_DYN: // .so
187 case LDPO_PIE: // position independent executable
188 RelocationModel = Reloc::PIC_;
190 case LDPO_EXEC: // .exe
191 RelocationModel = Reloc::Static;
194 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
199 options::process_plugin_option(tv->tv_u.tv_string);
201 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
202 ld_plugin_register_claim_file callback;
203 callback = tv->tv_u.tv_register_claim_file;
205 if (callback(claim_file_hook) != LDPS_OK)
208 registeredClaimFile = true;
210 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
211 ld_plugin_register_all_symbols_read callback;
212 callback = tv->tv_u.tv_register_all_symbols_read;
214 if (callback(all_symbols_read_hook) != LDPS_OK)
217 RegisteredAllSymbolsRead = true;
219 case LDPT_REGISTER_CLEANUP_HOOK: {
220 ld_plugin_register_cleanup callback;
221 callback = tv->tv_u.tv_register_cleanup;
223 if (callback(cleanup_hook) != LDPS_OK)
226 case LDPT_GET_INPUT_FILE:
227 get_input_file = tv->tv_u.tv_get_input_file;
229 case LDPT_RELEASE_INPUT_FILE:
230 release_input_file = tv->tv_u.tv_release_input_file;
232 case LDPT_ADD_SYMBOLS:
233 add_symbols = tv->tv_u.tv_add_symbols;
235 case LDPT_GET_SYMBOLS_V2:
236 get_symbols = tv->tv_u.tv_get_symbols;
238 case LDPT_ADD_INPUT_FILE:
239 add_input_file = tv->tv_u.tv_add_input_file;
241 case LDPT_SET_EXTRA_LIBRARY_PATH:
242 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
245 get_view = tv->tv_u.tv_get_view;
248 message = tv->tv_u.tv_message;
255 if (!registeredClaimFile) {
256 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
260 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
264 if (!RegisteredAllSymbolsRead)
267 if (!get_input_file) {
268 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
271 if (!release_input_file) {
272 message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
279 static const GlobalObject *getBaseObject(const GlobalValue &GV) {
280 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
281 return GA->getBaseObject();
282 return cast<GlobalObject>(&GV);
285 static bool shouldSkip(uint32_t Symflags) {
286 if (!(Symflags & object::BasicSymbolRef::SF_Global))
288 if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
293 static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
294 if (const auto *BDI = dyn_cast<BitcodeDiagnosticInfo>(&DI)) {
295 std::error_code EC = BDI->getError();
296 if (EC == BitcodeError::InvalidBitcodeSignature)
300 std::string ErrStorage;
302 raw_string_ostream OS(ErrStorage);
303 DiagnosticPrinterRawOStream DP(OS);
306 ld_plugin_level Level;
307 switch (DI.getSeverity()) {
309 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
311 llvm_unreachable("Fatal doesn't return.");
313 Level = LDPL_WARNING;
320 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
323 /// Called by gold to see whether this file is one that our plugin can handle.
324 /// We'll try to open it and register all the symbols with add_symbol if
326 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
329 MemoryBufferRef BufferRef;
330 std::unique_ptr<MemoryBuffer> Buffer;
333 if (get_view(file->handle, &view) != LDPS_OK) {
334 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
338 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
341 // Gold has found what might be IR part-way inside of a file, such as
344 offset = file->offset;
346 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
347 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
349 if (std::error_code EC = BufferOrErr.getError()) {
350 message(LDPL_ERROR, EC.message().c_str());
353 Buffer = std::move(BufferOrErr.get());
354 BufferRef = Buffer->getMemBufferRef();
357 Context.setDiagnosticHandler(diagnosticHandler);
358 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
359 object::IRObjectFile::create(BufferRef, Context);
360 std::error_code EC = ObjOrErr.getError();
361 if (EC == object::object_error::invalid_file_type ||
362 EC == object::object_error::bitcode_section_not_found)
368 message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
369 EC.message().c_str());
372 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
374 Modules.resize(Modules.size() + 1);
375 claimed_file &cf = Modules.back();
377 cf.handle = file->handle;
379 for (auto &Sym : Obj->symbols()) {
380 uint32_t Symflags = Sym.getFlags();
381 if (shouldSkip(Symflags))
384 cf.syms.push_back(ld_plugin_symbol());
385 ld_plugin_symbol &sym = cf.syms.back();
386 sym.version = nullptr;
388 SmallString<64> Name;
390 raw_svector_ostream OS(Name);
393 sym.name = strdup(Name.c_str());
395 const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
397 sym.visibility = LDPV_DEFAULT;
399 switch (GV->getVisibility()) {
400 case GlobalValue::DefaultVisibility:
401 sym.visibility = LDPV_DEFAULT;
403 case GlobalValue::HiddenVisibility:
404 sym.visibility = LDPV_HIDDEN;
406 case GlobalValue::ProtectedVisibility:
407 sym.visibility = LDPV_PROTECTED;
412 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
413 sym.def = LDPK_UNDEF;
414 if (GV && GV->hasExternalWeakLinkage())
415 sym.def = LDPK_WEAKUNDEF;
419 assert(!GV->hasExternalWeakLinkage() &&
420 !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
421 if (GV->hasCommonLinkage())
422 sym.def = LDPK_COMMON;
423 else if (GV->isWeakForLinker())
424 sym.def = LDPK_WEAKDEF;
429 sym.comdat_key = nullptr;
431 const GlobalObject *Base = getBaseObject(*GV);
433 message(LDPL_FATAL, "Unable to determine comdat of alias!");
434 const Comdat *C = Base->getComdat();
436 sym.comdat_key = strdup(C->getName().str().c_str());
437 else if (Base->hasWeakLinkage() || Base->hasLinkOnceLinkage())
438 sym.comdat_key = strdup(sym.name);
441 sym.resolution = LDPR_UNKNOWN;
444 if (!cf.syms.empty()) {
445 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
446 message(LDPL_ERROR, "Unable to add symbols!");
454 static void keepGlobalValue(GlobalValue &GV,
455 std::vector<GlobalAlias *> &KeptAliases) {
456 assert(!GV.hasLocalLinkage());
458 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
459 KeptAliases.push_back(GA);
461 switch (GV.getLinkage()) {
464 case GlobalValue::LinkOnceAnyLinkage:
465 GV.setLinkage(GlobalValue::WeakAnyLinkage);
467 case GlobalValue::LinkOnceODRLinkage:
468 GV.setLinkage(GlobalValue::WeakODRLinkage);
472 assert(!GV.isDiscardableIfUnused());
475 static void internalize(GlobalValue &GV) {
476 if (GV.isDeclarationForLinker())
477 return; // We get here if there is a matching asm definition.
478 if (!GV.hasLocalLinkage())
479 GV.setLinkage(GlobalValue::InternalLinkage);
482 static void drop(GlobalValue &GV) {
483 if (auto *F = dyn_cast<Function>(&GV)) {
485 F->setComdat(nullptr); // Should deleteBody do this?
489 if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
490 Var->setInitializer(nullptr);
492 GlobalValue::ExternalLinkage); // Should setInitializer do this?
493 Var->setComdat(nullptr); // and this?
497 auto &Alias = cast<GlobalAlias>(GV);
498 Module &M = *Alias.getParent();
499 PointerType &Ty = *cast<PointerType>(Alias.getType());
500 GlobalValue::LinkageTypes L = Alias.getLinkage();
502 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
503 /*Initializer*/ nullptr);
504 Var->takeName(&Alias);
505 Alias.replaceAllUsesWith(Var);
506 Alias.eraseFromParent();
509 static const char *getResolutionName(ld_plugin_symbol_resolution R) {
515 case LDPR_PREVAILING_DEF:
516 return "PREVAILING_DEF";
517 case LDPR_PREVAILING_DEF_IRONLY:
518 return "PREVAILING_DEF_IRONLY";
519 case LDPR_PREEMPTED_REG:
520 return "PREEMPTED_REG";
521 case LDPR_PREEMPTED_IR:
522 return "PREEMPTED_IR";
523 case LDPR_RESOLVED_IR:
524 return "RESOLVED_IR";
525 case LDPR_RESOLVED_EXEC:
526 return "RESOLVED_EXEC";
527 case LDPR_RESOLVED_DYN:
528 return "RESOLVED_DYN";
529 case LDPR_PREVAILING_DEF_IRONLY_EXP:
530 return "PREVAILING_DEF_IRONLY_EXP";
532 llvm_unreachable("Unknown resolution");
536 class LocalValueMaterializer : public ValueMaterializer {
537 DenseSet<GlobalValue *> &Dropped;
538 DenseMap<GlobalObject *, GlobalObject *> LocalVersions;
541 LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
542 Value *materializeValueFor(Value *V) override;
546 Value *LocalValueMaterializer::materializeValueFor(Value *V) {
547 auto *GO = dyn_cast<GlobalObject>(V);
551 auto I = LocalVersions.find(GO);
552 if (I != LocalVersions.end())
555 if (!Dropped.count(GO))
558 Module &M = *GO->getParent();
559 GlobalValue::LinkageTypes L = GO->getLinkage();
560 GlobalObject *Declaration;
561 if (auto *F = dyn_cast<Function>(GO)) {
562 Declaration = Function::Create(F->getFunctionType(), L, "", &M);
564 auto *Var = cast<GlobalVariable>(GO);
565 Declaration = new GlobalVariable(M, Var->getType()->getElementType(),
566 Var->isConstant(), L,
567 /*Initializer*/ nullptr);
569 Declaration->takeName(GO);
570 Declaration->copyAttributesFrom(GO);
572 GO->setLinkage(GlobalValue::InternalLinkage);
573 GO->setName(Declaration->getName());
575 GO->replaceAllUsesWith(Declaration);
577 LocalVersions[Declaration] = GO;
582 static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
583 LocalValueMaterializer *Materializer) {
584 return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
587 static void freeSymName(ld_plugin_symbol &Sym) {
589 free(Sym.comdat_key);
591 Sym.comdat_key = nullptr;
594 static std::unique_ptr<Module>
595 getModuleForFile(LLVMContext &Context, claimed_file &F,
596 ld_plugin_input_file &Info, raw_fd_ostream *ApiFile,
597 StringSet<> &Internalize, StringSet<> &Maybe) {
599 if (get_symbols(F.handle, F.syms.size(), F.syms.data()) != LDPS_OK)
600 message(LDPL_FATAL, "Failed to get symbol information");
603 if (get_view(F.handle, &View) != LDPS_OK)
604 message(LDPL_FATAL, "Failed to get a view of file");
606 MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize),
608 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
609 object::IRObjectFile::create(BufferRef, Context);
611 if (std::error_code EC = ObjOrErr.getError())
612 message(LDPL_FATAL, "Could not read bitcode from file : %s",
613 EC.message().c_str());
615 object::IRObjectFile &Obj = **ObjOrErr;
617 Module &M = Obj.getModule();
619 M.materializeMetadata();
622 SmallPtrSet<GlobalValue *, 8> Used;
623 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
625 DenseSet<GlobalValue *> Drop;
626 std::vector<GlobalAlias *> KeptAliases;
629 for (auto &ObjSym : Obj.symbols()) {
630 if (shouldSkip(ObjSym.getFlags()))
632 ld_plugin_symbol &Sym = F.syms[SymNum];
635 ld_plugin_symbol_resolution Resolution =
636 (ld_plugin_symbol_resolution)Sym.resolution;
638 if (options::generate_api_file)
639 *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
641 GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
644 continue; // Asm symbol.
647 if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
648 // Common linkage is special. There is no single symbol that wins the
649 // resolution. Instead we have to collect the maximum alignment and size.
650 // The IR linker does that for us if we just pass it every common GV.
651 // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
652 // internalize once the IR linker has done its job.
657 switch (Resolution) {
659 llvm_unreachable("Unexpected resolution");
661 case LDPR_RESOLVED_IR:
662 case LDPR_RESOLVED_EXEC:
663 case LDPR_RESOLVED_DYN:
664 assert(GV->isDeclarationForLinker());
668 if (!GV->isDeclarationForLinker()) {
669 assert(GV->hasComdat());
674 case LDPR_PREVAILING_DEF_IRONLY: {
675 keepGlobalValue(*GV, KeptAliases);
676 if (!Used.count(GV)) {
677 // Since we use the regular lib/Linker, we cannot just internalize GV
678 // now or it will not be copied to the merged module. Instead we force
679 // it to be copied and then internalize it.
680 Internalize.insert(GV->getName());
685 case LDPR_PREVAILING_DEF:
686 keepGlobalValue(*GV, KeptAliases);
689 case LDPR_PREEMPTED_IR:
690 // Gold might have selected a linkonce_odr and preempted a weak_odr.
691 // In that case we have to make sure we don't end up internalizing it.
692 if (!GV->isDiscardableIfUnused())
693 Maybe.erase(GV->getName());
696 case LDPR_PREEMPTED_REG:
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 if (GV->hasLinkOnceODRLinkage())
706 Maybe.insert(GV->getName());
707 keepGlobalValue(*GV, KeptAliases);
715 ValueToValueMapTy VM;
716 LocalValueMaterializer Materializer(Drop);
717 for (GlobalAlias *GA : KeptAliases) {
718 // Gold told us to keep GA. It is possible that a GV usied in the aliasee
719 // expression is being dropped. If that is the case, that GV must be copied.
720 Constant *Aliasee = GA->getAliasee();
721 Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
722 GA->setAliasee(Replacement);
725 for (auto *GV : Drop)
728 return Obj.takeModule();
731 static void runLTOPasses(Module &M, TargetMachine &TM) {
732 M.setDataLayout(TM.createDataLayout());
734 legacy::PassManager passes;
735 passes.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
737 PassManagerBuilder PMB;
738 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
739 PMB.Inliner = createFunctionInliningPass();
740 // Unconditionally verify input since it is not verified before this
741 // point and has unknown origin.
742 PMB.VerifyInput = true;
743 PMB.VerifyOutput = !options::DisableVerify;
744 PMB.LoopVectorize = true;
745 PMB.SLPVectorize = true;
746 PMB.OptLevel = options::OptLevel;
747 PMB.populateLTOPassManager(passes);
751 static void saveBCFile(StringRef Path, Module &M) {
753 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
755 message(LDPL_FATAL, "Failed to write the output file.");
756 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true);
759 static void codegen(std::unique_ptr<Module> M) {
760 const std::string &TripleStr = M->getTargetTriple();
761 Triple TheTriple(TripleStr);
764 const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
766 message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
768 if (unsigned NumOpts = options::extra.size())
769 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
771 SubtargetFeatures Features;
772 Features.getDefaultSubtargetFeatures(TheTriple);
773 for (const std::string &A : MAttrs)
774 Features.AddFeature(A);
776 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
777 CodeGenOpt::Level CGOptLevel;
778 switch (options::OptLevel) {
780 CGOptLevel = CodeGenOpt::None;
783 CGOptLevel = CodeGenOpt::Less;
786 CGOptLevel = CodeGenOpt::Default;
789 CGOptLevel = CodeGenOpt::Aggressive;
792 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
793 TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
794 CodeModel::Default, CGOptLevel));
796 runLTOPasses(*M, *TM);
798 if (options::TheOutputType == options::OT_SAVE_TEMPS)
799 saveBCFile(output_name + ".opt.bc", *M);
801 SmallString<128> Filename;
802 if (!options::obj_path.empty())
803 Filename = options::obj_path;
804 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
805 Filename = output_name + ".o";
807 std::vector<SmallString<128>> Filenames(options::Parallelism);
808 bool TempOutFile = Filename.empty();
810 // Open a file descriptor for each backend thread. This is done in a block
811 // so that the output file descriptors are closed before gold opens them.
812 std::list<llvm::raw_fd_ostream> OSs;
813 std::vector<llvm::raw_pwrite_stream *> OSPtrs(options::Parallelism);
814 for (unsigned I = 0; I != options::Parallelism; ++I) {
818 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filenames[I]);
820 message(LDPL_FATAL, "Could not create temporary file: %s",
821 EC.message().c_str());
823 Filenames[I] = Filename;
824 if (options::Parallelism != 1)
825 Filenames[I] += utostr(I);
827 sys::fs::openFileForWrite(Filenames[I], FD, sys::fs::F_None);
829 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
831 OSs.emplace_back(FD, true);
832 OSPtrs[I] = &OSs.back();
835 // Run backend threads.
836 splitCodeGen(std::move(M), OSPtrs, options::mcpu, Features.getString(),
837 Options, RelocationModel, CodeModel::Default, CGOptLevel);
840 for (auto &Filename : Filenames) {
841 if (add_input_file(Filename.c_str()) != LDPS_OK)
843 "Unable to add .o file to the link. File left behind in: %s",
846 Cleanup.push_back(Filename.c_str());
850 /// gold informs us that all symbols have been read. At this point, we use
851 /// get_symbols to see if any of our definitions have been overridden by a
852 /// native object file. Then, perform optimization and codegen.
853 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
858 Context.setDiagnosticHandler(diagnosticHandler, nullptr, true);
860 std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
861 Linker L(Combined.get());
863 std::string DefaultTriple = sys::getDefaultTargetTriple();
865 StringSet<> Internalize;
867 for (claimed_file &F : Modules) {
868 ld_plugin_input_file File;
869 if (get_input_file(F.handle, &File) != LDPS_OK)
870 message(LDPL_FATAL, "Failed to get file information");
871 std::unique_ptr<Module> M =
872 getModuleForFile(Context, F, File, ApiFile, Internalize, Maybe);
873 if (!options::triple.empty())
874 M->setTargetTriple(options::triple.c_str());
875 else if (M->getTargetTriple().empty()) {
876 M->setTargetTriple(DefaultTriple);
879 if (L.linkInModule(M.get()))
880 message(LDPL_FATAL, "Failed to link module");
881 if (release_input_file(F.handle) != LDPS_OK)
882 message(LDPL_FATAL, "Failed to release file information");
885 for (const auto &Name : Internalize) {
886 GlobalValue *GV = Combined->getNamedValue(Name.first());
891 for (const auto &Name : Maybe) {
892 GlobalValue *GV = Combined->getNamedValue(Name.first());
895 GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
896 if (canBeOmittedFromSymbolTable(GV))
900 if (options::TheOutputType == options::OT_DISABLE)
903 if (options::TheOutputType != options::OT_NORMAL) {
905 if (options::TheOutputType == options::OT_BC_ONLY)
908 path = output_name + ".bc";
909 saveBCFile(path, *L.getModule());
910 if (options::TheOutputType == options::OT_BC_ONLY)
914 codegen(std::move(Combined));
916 if (!options::extra_library_path.empty() &&
917 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
918 message(LDPL_FATAL, "Unable to set the extra library path.");
923 static ld_plugin_status all_symbols_read_hook(void) {
924 ld_plugin_status Ret;
925 if (!options::generate_api_file) {
926 Ret = allSymbolsReadHook(nullptr);
929 raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
931 message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
932 EC.message().c_str());
933 Ret = allSymbolsReadHook(&ApiFile);
938 if (options::TheOutputType == options::OT_BC_ONLY ||
939 options::TheOutputType == options::OT_DISABLE) {
940 if (options::TheOutputType == options::OT_DISABLE)
941 // Remove the output file here since ld.bfd creates the output file
943 sys::fs::remove(output_name);
950 static ld_plugin_status cleanup_hook(void) {
951 for (std::string &Name : Cleanup) {
952 std::error_code EC = sys::fs::remove(Name);
954 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
955 EC.message().c_str());