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/IR/Constants.h"
24 #include "llvm/IR/DiagnosticInfo.h"
25 #include "llvm/IR/DiagnosticPrinter.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Verifier.h"
29 #include "llvm/Linker/Linker.h"
30 #include "llvm/MC/SubtargetFeature.h"
31 #include "llvm/Object/IRObjectFile.h"
32 #include "llvm/PassManager.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/TargetSelect.h"
39 #include "llvm/Transforms/IPO.h"
40 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
41 #include "llvm/Transforms/Utils/GlobalStatus.h"
42 #include "llvm/Transforms/Utils/ModuleUtils.h"
43 #include "llvm/Transforms/Utils/ValueMapper.h"
45 #include <plugin-api.h>
46 #include <system_error>
50 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
51 // Precise and Debian Wheezy (binutils 2.23 is required)
60 std::vector<ld_plugin_symbol> syms;
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.
70 static ld_plugin_get_input_file get_input_file = nullptr;
71 static ld_plugin_release_input_file release_input_file = nullptr;
72 static ld_plugin_add_symbols add_symbols = nullptr;
73 static ld_plugin_get_symbols get_symbols = nullptr;
74 static ld_plugin_add_input_file add_input_file = nullptr;
75 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
76 static ld_plugin_get_view get_view = nullptr;
77 static ld_plugin_message message = discard_message;
78 static Reloc::Model RelocationModel = Reloc::Default;
79 static std::string output_name = "";
80 static std::list<claimed_file> Modules;
81 static std::vector<std::string> Cleanup;
82 static llvm::TargetOptions TargetOpts;
91 static bool generate_api_file = false;
92 static OutputType TheOutputType = OT_NORMAL;
93 static std::string obj_path;
94 static std::string extra_library_path;
95 static std::string triple;
96 static std::string mcpu;
97 // Additional options to pass into the code generator.
98 // Note: This array will contain all plugin options which are not claimed
99 // as plugin exclusive to pass to the code generator.
100 // For example, "generate-api-file" and "as"options are for the plugin
101 // use only and will not be passed.
102 static std::vector<const char *> extra;
104 static void process_plugin_option(const char* opt_)
108 llvm::StringRef opt = opt_;
110 if (opt == "generate-api-file") {
111 generate_api_file = true;
112 } else if (opt.startswith("mcpu=")) {
113 mcpu = opt.substr(strlen("mcpu="));
114 } else if (opt.startswith("extra-library-path=")) {
115 extra_library_path = opt.substr(strlen("extra_library_path="));
116 } else if (opt.startswith("mtriple=")) {
117 triple = opt.substr(strlen("mtriple="));
118 } else if (opt.startswith("obj-path=")) {
119 obj_path = opt.substr(strlen("obj-path="));
120 } else if (opt == "emit-llvm") {
121 TheOutputType = OT_BC_ONLY;
122 } else if (opt == "save-temps") {
123 TheOutputType = OT_SAVE_TEMPS;
124 } else if (opt == "disable-output") {
125 TheOutputType = OT_DISABLE;
127 // Save this option to pass to the code generator.
128 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
131 extra.push_back("LLVMgold");
133 extra.push_back(opt_);
138 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
140 static ld_plugin_status all_symbols_read_hook(void);
141 static ld_plugin_status cleanup_hook(void);
143 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
144 ld_plugin_status onload(ld_plugin_tv *tv) {
145 InitializeAllTargetInfos();
146 InitializeAllTargets();
147 InitializeAllTargetMCs();
148 InitializeAllAsmParsers();
149 InitializeAllAsmPrinters();
151 // We're given a pointer to the first transfer vector. We read through them
152 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
153 // contain pointers to functions that we need to call to register our own
154 // hooks. The others are addresses of functions we can use to call into gold
157 bool registeredClaimFile = false;
158 bool RegisteredAllSymbolsRead = false;
160 for (; tv->tv_tag != LDPT_NULL; ++tv) {
161 switch (tv->tv_tag) {
162 case LDPT_OUTPUT_NAME:
163 output_name = tv->tv_u.tv_string;
165 case LDPT_LINKER_OUTPUT:
166 switch (tv->tv_u.tv_val) {
168 case LDPO_DYN: // .so
169 case LDPO_PIE: // position independent executable
170 RelocationModel = Reloc::PIC_;
172 case LDPO_EXEC: // .exe
173 RelocationModel = Reloc::Static;
176 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
181 options::process_plugin_option(tv->tv_u.tv_string);
183 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
184 ld_plugin_register_claim_file callback;
185 callback = tv->tv_u.tv_register_claim_file;
187 if (callback(claim_file_hook) != LDPS_OK)
190 registeredClaimFile = true;
192 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
193 ld_plugin_register_all_symbols_read callback;
194 callback = tv->tv_u.tv_register_all_symbols_read;
196 if (callback(all_symbols_read_hook) != LDPS_OK)
199 RegisteredAllSymbolsRead = true;
201 case LDPT_REGISTER_CLEANUP_HOOK: {
202 ld_plugin_register_cleanup callback;
203 callback = tv->tv_u.tv_register_cleanup;
205 if (callback(cleanup_hook) != LDPS_OK)
208 case LDPT_GET_INPUT_FILE:
209 get_input_file = tv->tv_u.tv_get_input_file;
211 case LDPT_RELEASE_INPUT_FILE:
212 release_input_file = tv->tv_u.tv_release_input_file;
214 case LDPT_ADD_SYMBOLS:
215 add_symbols = tv->tv_u.tv_add_symbols;
217 case LDPT_GET_SYMBOLS_V2:
218 get_symbols = tv->tv_u.tv_get_symbols;
220 case LDPT_ADD_INPUT_FILE:
221 add_input_file = tv->tv_u.tv_add_input_file;
223 case LDPT_SET_EXTRA_LIBRARY_PATH:
224 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
227 get_view = tv->tv_u.tv_get_view;
230 message = tv->tv_u.tv_message;
237 if (!registeredClaimFile) {
238 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
242 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
246 if (!RegisteredAllSymbolsRead)
249 if (!get_input_file) {
250 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
253 if (!release_input_file) {
254 message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
261 static const GlobalObject *getBaseObject(const GlobalValue &GV) {
262 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
263 return GA->getBaseObject();
264 return cast<GlobalObject>(&GV);
267 static bool shouldSkip(uint32_t Symflags) {
268 if (!(Symflags & object::BasicSymbolRef::SF_Global))
270 if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
275 static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
276 assert(DI.getSeverity() == DS_Error && "Only expecting errors");
277 const auto &BDI = cast<BitcodeDiagnosticInfo>(DI);
278 std::error_code EC = BDI.getError();
279 if (EC == BitcodeError::InvalidBitcodeSignature)
282 std::string ErrStorage;
284 raw_string_ostream OS(ErrStorage);
285 DiagnosticPrinterRawOStream DP(OS);
288 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
292 /// Called by gold to see whether this file is one that our plugin can handle.
293 /// We'll try to open it and register all the symbols with add_symbol if
295 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
298 MemoryBufferRef BufferRef;
299 std::unique_ptr<MemoryBuffer> Buffer;
302 if (get_view(file->handle, &view) != LDPS_OK) {
303 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
306 BufferRef = MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
309 // Gold has found what might be IR part-way inside of a file, such as
312 offset = file->offset;
314 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
315 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
317 if (std::error_code EC = BufferOrErr.getError()) {
318 message(LDPL_ERROR, EC.message().c_str());
321 Buffer = std::move(BufferOrErr.get());
322 BufferRef = Buffer->getMemBufferRef();
325 Context.setDiagnosticHandler(diagnosticHandler);
326 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
327 object::IRObjectFile::create(BufferRef, Context);
328 std::error_code EC = ObjOrErr.getError();
329 if (EC == object::object_error::invalid_file_type ||
330 EC == object::object_error::bitcode_section_not_found)
336 message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
337 EC.message().c_str());
340 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
342 Modules.resize(Modules.size() + 1);
343 claimed_file &cf = Modules.back();
345 cf.handle = file->handle;
347 for (auto &Sym : Obj->symbols()) {
348 uint32_t Symflags = Sym.getFlags();
349 if (shouldSkip(Symflags))
352 cf.syms.push_back(ld_plugin_symbol());
353 ld_plugin_symbol &sym = cf.syms.back();
354 sym.version = nullptr;
356 SmallString<64> Name;
358 raw_svector_ostream OS(Name);
361 sym.name = strdup(Name.c_str());
363 const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
365 sym.visibility = LDPV_DEFAULT;
367 switch (GV->getVisibility()) {
368 case GlobalValue::DefaultVisibility:
369 sym.visibility = LDPV_DEFAULT;
371 case GlobalValue::HiddenVisibility:
372 sym.visibility = LDPV_HIDDEN;
374 case GlobalValue::ProtectedVisibility:
375 sym.visibility = LDPV_PROTECTED;
380 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
381 sym.def = LDPK_UNDEF;
382 if (GV && GV->hasExternalWeakLinkage())
383 sym.def = LDPK_WEAKUNDEF;
387 assert(!GV->hasExternalWeakLinkage() &&
388 !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
389 if (GV->hasCommonLinkage())
390 sym.def = LDPK_COMMON;
391 else if (GV->isWeakForLinker())
392 sym.def = LDPK_WEAKDEF;
397 sym.comdat_key = nullptr;
399 const GlobalObject *Base = getBaseObject(*GV);
401 message(LDPL_FATAL, "Unable to determine comdat of alias!");
402 const Comdat *C = Base->getComdat();
404 sym.comdat_key = strdup(C->getName().str().c_str());
405 else if (Base->hasWeakLinkage() || Base->hasLinkOnceLinkage())
406 sym.comdat_key = strdup(sym.name);
409 sym.resolution = LDPR_UNKNOWN;
412 if (!cf.syms.empty()) {
413 if (add_symbols(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
414 message(LDPL_ERROR, "Unable to add symbols!");
422 static void keepGlobalValue(GlobalValue &GV,
423 std::vector<GlobalAlias *> &KeptAliases) {
424 assert(!GV.hasLocalLinkage());
426 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
427 KeptAliases.push_back(GA);
429 switch (GV.getLinkage()) {
432 case GlobalValue::LinkOnceAnyLinkage:
433 GV.setLinkage(GlobalValue::WeakAnyLinkage);
435 case GlobalValue::LinkOnceODRLinkage:
436 GV.setLinkage(GlobalValue::WeakODRLinkage);
440 assert(!GV.isDiscardableIfUnused());
443 static void internalize(GlobalValue &GV) {
444 if (GV.isDeclarationForLinker())
445 return; // We get here if there is a matching asm definition.
446 if (!GV.hasLocalLinkage())
447 GV.setLinkage(GlobalValue::InternalLinkage);
450 static void drop(GlobalValue &GV) {
451 if (auto *F = dyn_cast<Function>(&GV)) {
453 F->setComdat(nullptr); // Should deleteBody do this?
457 if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
458 Var->setInitializer(nullptr);
460 GlobalValue::ExternalLinkage); // Should setInitializer do this?
461 Var->setComdat(nullptr); // and this?
465 auto &Alias = cast<GlobalAlias>(GV);
466 Module &M = *Alias.getParent();
467 PointerType &Ty = *cast<PointerType>(Alias.getType());
468 GlobalValue::LinkageTypes L = Alias.getLinkage();
470 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
471 /*Initializer*/ nullptr);
472 Var->takeName(&Alias);
473 Alias.replaceAllUsesWith(Var);
474 Alias.eraseFromParent();
477 static const char *getResolutionName(ld_plugin_symbol_resolution R) {
483 case LDPR_PREVAILING_DEF:
484 return "PREVAILING_DEF";
485 case LDPR_PREVAILING_DEF_IRONLY:
486 return "PREVAILING_DEF_IRONLY";
487 case LDPR_PREEMPTED_REG:
488 return "PREEMPTED_REG";
489 case LDPR_PREEMPTED_IR:
490 return "PREEMPTED_IR";
491 case LDPR_RESOLVED_IR:
492 return "RESOLVED_IR";
493 case LDPR_RESOLVED_EXEC:
494 return "RESOLVED_EXEC";
495 case LDPR_RESOLVED_DYN:
496 return "RESOLVED_DYN";
497 case LDPR_PREVAILING_DEF_IRONLY_EXP:
498 return "PREVAILING_DEF_IRONLY_EXP";
500 llvm_unreachable("Unknown resolution");
504 class LocalValueMaterializer : public ValueMaterializer {
505 DenseSet<GlobalValue *> &Dropped;
506 DenseMap<GlobalObject *, GlobalObject *> LocalVersions;
509 LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
510 Value *materializeValueFor(Value *V) override;
514 Value *LocalValueMaterializer::materializeValueFor(Value *V) {
515 auto *GO = dyn_cast<GlobalObject>(V);
519 auto I = LocalVersions.find(GO);
520 if (I != LocalVersions.end())
523 if (!Dropped.count(GO))
526 Module &M = *GO->getParent();
527 GlobalValue::LinkageTypes L = GO->getLinkage();
528 GlobalObject *Declaration;
529 if (auto *F = dyn_cast<Function>(GO)) {
530 Declaration = Function::Create(F->getFunctionType(), L, "", &M);
532 auto *Var = cast<GlobalVariable>(GO);
533 Declaration = new GlobalVariable(M, Var->getType()->getElementType(),
534 Var->isConstant(), L,
535 /*Initializer*/ nullptr);
537 Declaration->takeName(GO);
538 Declaration->copyAttributesFrom(GO);
540 GO->setLinkage(GlobalValue::InternalLinkage);
541 GO->setName(Declaration->getName());
543 GO->replaceAllUsesWith(Declaration);
545 LocalVersions[Declaration] = GO;
550 static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
551 LocalValueMaterializer *Materializer) {
552 return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
555 static void freeSymName(ld_plugin_symbol &Sym) {
557 free(Sym.comdat_key);
559 Sym.comdat_key = nullptr;
562 static std::unique_ptr<Module>
563 getModuleForFile(LLVMContext &Context, claimed_file &F,
564 off_t Filesize, raw_fd_ostream *ApiFile,
565 StringSet<> &Internalize, StringSet<> &Maybe) {
567 if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
568 message(LDPL_FATAL, "Failed to get symbol information");
571 if (get_view(F.handle, &View) != LDPS_OK)
572 message(LDPL_FATAL, "Failed to get a view of file");
574 MemoryBufferRef BufferRef(StringRef((const char *)View, Filesize), "");
575 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
576 object::IRObjectFile::create(BufferRef, Context);
578 if (std::error_code EC = ObjOrErr.getError())
579 message(LDPL_FATAL, "Could not read bitcode from file : %s",
580 EC.message().c_str());
582 object::IRObjectFile &Obj = **ObjOrErr;
584 Module &M = Obj.getModule();
586 SmallPtrSet<GlobalValue *, 8> Used;
587 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
589 DenseSet<GlobalValue *> Drop;
590 std::vector<GlobalAlias *> KeptAliases;
593 for (auto &ObjSym : Obj.symbols()) {
594 if (shouldSkip(ObjSym.getFlags()))
596 ld_plugin_symbol &Sym = F.syms[SymNum];
599 ld_plugin_symbol_resolution Resolution =
600 (ld_plugin_symbol_resolution)Sym.resolution;
602 if (options::generate_api_file)
603 *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
605 GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
608 continue; // Asm symbol.
611 if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
612 // Common linkage is special. There is no single symbol that wins the
613 // resolution. Instead we have to collect the maximum alignment and size.
614 // The IR linker does that for us if we just pass it every common GV.
615 // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
616 // internalize once the IR linker has done its job.
621 switch (Resolution) {
623 llvm_unreachable("Unexpected resolution");
625 case LDPR_RESOLVED_IR:
626 case LDPR_RESOLVED_EXEC:
627 case LDPR_RESOLVED_DYN:
628 assert(GV->isDeclarationForLinker());
632 if (!GV->isDeclarationForLinker()) {
633 assert(GV->hasComdat());
638 case LDPR_PREVAILING_DEF_IRONLY: {
639 keepGlobalValue(*GV, KeptAliases);
640 if (!Used.count(GV)) {
641 // Since we use the regular lib/Linker, we cannot just internalize GV
642 // now or it will not be copied to the merged module. Instead we force
643 // it to be copied and then internalize it.
644 Internalize.insert(GV->getName());
649 case LDPR_PREVAILING_DEF:
650 keepGlobalValue(*GV, KeptAliases);
653 case LDPR_PREEMPTED_IR:
654 // Gold might have selected a linkonce_odr and preempted a weak_odr.
655 // In that case we have to make sure we don't end up internalizing it.
656 if (!GV->isDiscardableIfUnused())
657 Maybe.erase(GV->getName());
660 case LDPR_PREEMPTED_REG:
664 case LDPR_PREVAILING_DEF_IRONLY_EXP: {
665 // We can only check for address uses after we merge the modules. The
666 // reason is that this GV might have a copy in another module
667 // and in that module the address might be significant, but that
668 // copy will be LDPR_PREEMPTED_IR.
669 if (GV->hasLinkOnceODRLinkage())
670 Maybe.insert(GV->getName());
671 keepGlobalValue(*GV, KeptAliases);
679 ValueToValueMapTy VM;
680 LocalValueMaterializer Materializer(Drop);
681 for (GlobalAlias *GA : KeptAliases) {
682 // Gold told us to keep GA. It is possible that a GV usied in the aliasee
683 // expression is being dropped. If that is the case, that GV must be copied.
684 Constant *Aliasee = GA->getAliasee();
685 Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
686 GA->setAliasee(Replacement);
689 for (auto *GV : Drop)
692 return Obj.takeModule();
695 static void runLTOPasses(Module &M, TargetMachine &TM) {
697 passes.add(new DataLayoutPass());
698 passes.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
700 PassManagerBuilder PMB;
701 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
702 PMB.Inliner = createFunctionInliningPass();
703 PMB.VerifyInput = true;
704 PMB.VerifyOutput = true;
705 PMB.LoopVectorize = true;
706 PMB.SLPVectorize = true;
707 PMB.populateLTOPassManager(passes);
711 static void saveBCFile(StringRef Path, Module &M) {
713 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
715 message(LDPL_FATAL, "Failed to write the output file.");
716 WriteBitcodeToFile(&M, OS);
719 static void codegen(Module &M) {
720 const std::string &TripleStr = M.getTargetTriple();
721 Triple TheTriple(TripleStr);
724 const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
726 message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
728 if (unsigned NumOpts = options::extra.size())
729 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
731 SubtargetFeatures Features;
732 Features.getDefaultSubtargetFeatures(TheTriple);
733 for (const std::string &A : MAttrs)
734 Features.AddFeature(A);
736 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
737 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
738 TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
739 CodeModel::Default, CodeGenOpt::Aggressive));
741 runLTOPasses(M, *TM);
743 if (options::TheOutputType == options::OT_SAVE_TEMPS)
744 saveBCFile(output_name + ".opt.bc", M);
746 PassManager CodeGenPasses;
747 CodeGenPasses.add(new DataLayoutPass());
749 SmallString<128> Filename;
751 if (options::obj_path.empty()) {
753 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
755 message(LDPL_FATAL, "Could not create temporary file: %s",
756 EC.message().c_str());
758 Filename = options::obj_path;
760 sys::fs::openFileForWrite(Filename.c_str(), FD, sys::fs::F_None);
762 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
766 raw_fd_ostream OS(FD, true);
767 formatted_raw_ostream FOS(OS);
769 if (TM->addPassesToEmitFile(CodeGenPasses, FOS,
770 TargetMachine::CGFT_ObjectFile))
771 message(LDPL_FATAL, "Failed to setup codegen");
772 CodeGenPasses.run(M);
775 if (add_input_file(Filename.c_str()) != LDPS_OK)
777 "Unable to add .o file to the link. File left behind in: %s",
780 if (options::obj_path.empty())
781 Cleanup.push_back(Filename.c_str());
784 /// gold informs us that all symbols have been read. At this point, we use
785 /// get_symbols to see if any of our definitions have been overridden by a
786 /// native object file. Then, perform optimization and codegen.
787 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
792 std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
793 Linker L(Combined.get());
795 std::string DefaultTriple = sys::getDefaultTargetTriple();
797 StringSet<> Internalize;
799 for (claimed_file &F : Modules) {
800 ld_plugin_input_file File;
801 if (get_input_file(F.handle, &File) != LDPS_OK)
802 message(LDPL_FATAL, "Failed to get file information");
803 std::unique_ptr<Module> M =
804 getModuleForFile(Context, F, File.filesize, ApiFile,
806 if (!options::triple.empty())
807 M->setTargetTriple(options::triple.c_str());
808 else if (M->getTargetTriple().empty()) {
809 M->setTargetTriple(DefaultTriple);
812 if (L.linkInModule(M.get()))
813 message(LDPL_FATAL, "Failed to link module");
814 if (release_input_file(F.handle) != LDPS_OK)
815 message(LDPL_FATAL, "Failed to release file information");
818 for (const auto &Name : Internalize) {
819 GlobalValue *GV = Combined->getNamedValue(Name.first());
824 for (const auto &Name : Maybe) {
825 GlobalValue *GV = Combined->getNamedValue(Name.first());
828 GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
829 if (canBeOmittedFromSymbolTable(GV))
833 if (options::TheOutputType == options::OT_DISABLE)
836 if (options::TheOutputType != options::OT_NORMAL) {
838 if (options::TheOutputType == options::OT_BC_ONLY)
841 path = output_name + ".bc";
842 saveBCFile(path, *L.getModule());
843 if (options::TheOutputType == options::OT_BC_ONLY)
847 codegen(*L.getModule());
849 if (!options::extra_library_path.empty() &&
850 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
851 message(LDPL_FATAL, "Unable to set the extra library path.");
856 static ld_plugin_status all_symbols_read_hook(void) {
857 ld_plugin_status Ret;
858 if (!options::generate_api_file) {
859 Ret = allSymbolsReadHook(nullptr);
862 raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
864 message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
865 EC.message().c_str());
866 Ret = allSymbolsReadHook(&ApiFile);
871 if (options::TheOutputType == options::OT_BC_ONLY ||
872 options::TheOutputType == options::OT_DISABLE) {
873 if (options::TheOutputType == options::OT_DISABLE)
874 // Remove the output file here since ld.bfd creates the output file
876 sys::fs::remove(output_name);
883 static ld_plugin_status cleanup_hook(void) {
884 for (std::string &Name : Cleanup) {
885 std::error_code EC = sys::fs::remove(Name);
887 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
888 EC.message().c_str());