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/Bitcode/ReaderWriter.h"
19 #include "llvm/CodeGen/Analysis.h"
20 #include "llvm/CodeGen/CommandFlags.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/Linker/Linker.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/Object/IRObjectFile.h"
28 #include "llvm/PassManager.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Support/TargetSelect.h"
34 #include "llvm/Target/TargetLibraryInfo.h"
35 #include "llvm/Transforms/IPO.h"
36 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
37 #include "llvm/Transforms/Utils/GlobalStatus.h"
38 #include "llvm/Transforms/Utils/ModuleUtils.h"
39 #include "llvm/Transforms/Utils/ValueMapper.h"
41 #include <plugin-api.h>
42 #include <system_error>
46 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
47 // Precise and Debian Wheezy (binutils 2.23 is required)
56 std::vector<ld_plugin_symbol> syms;
60 static ld_plugin_status discard_message(int level, const char *format, ...) {
61 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
62 // callback in the transfer vector. This should never be called.
66 static ld_plugin_get_input_file get_input_file = nullptr;
67 static ld_plugin_release_input_file release_input_file = nullptr;
68 static ld_plugin_add_symbols add_symbols = nullptr;
69 static ld_plugin_get_symbols get_symbols = nullptr;
70 static ld_plugin_add_input_file add_input_file = nullptr;
71 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
72 static ld_plugin_get_view get_view = nullptr;
73 static ld_plugin_message message = discard_message;
74 static Reloc::Model RelocationModel = Reloc::Default;
75 static std::string output_name = "";
76 static std::list<claimed_file> Modules;
77 static std::vector<std::string> Cleanup;
78 static llvm::TargetOptions TargetOpts;
87 static bool generate_api_file = false;
88 static OutputType TheOutputType = OT_NORMAL;
89 static std::string obj_path;
90 static std::string extra_library_path;
91 static std::string triple;
92 static std::string mcpu;
93 // Additional options to pass into the code generator.
94 // Note: This array will contain all plugin options which are not claimed
95 // as plugin exclusive to pass to the code generator.
96 // For example, "generate-api-file" and "as"options are for the plugin
97 // use only and will not be passed.
98 static std::vector<const char *> extra;
100 static void process_plugin_option(const char* opt_)
104 llvm::StringRef opt = opt_;
106 if (opt == "generate-api-file") {
107 generate_api_file = true;
108 } else if (opt.startswith("mcpu=")) {
109 mcpu = opt.substr(strlen("mcpu="));
110 } else if (opt.startswith("extra-library-path=")) {
111 extra_library_path = opt.substr(strlen("extra_library_path="));
112 } else if (opt.startswith("mtriple=")) {
113 triple = opt.substr(strlen("mtriple="));
114 } else if (opt.startswith("obj-path=")) {
115 obj_path = opt.substr(strlen("obj-path="));
116 } else if (opt == "emit-llvm") {
117 TheOutputType = OT_BC_ONLY;
118 } else if (opt == "save-temps") {
119 TheOutputType = OT_SAVE_TEMPS;
120 } else if (opt == "disable-output") {
121 TheOutputType = OT_DISABLE;
123 // Save this option to pass to the code generator.
124 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
127 extra.push_back("LLVMgold");
129 extra.push_back(opt_);
134 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
136 static ld_plugin_status all_symbols_read_hook(void);
137 static ld_plugin_status cleanup_hook(void);
139 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
140 ld_plugin_status onload(ld_plugin_tv *tv) {
141 InitializeAllTargetInfos();
142 InitializeAllTargets();
143 InitializeAllTargetMCs();
144 InitializeAllAsmParsers();
145 InitializeAllAsmPrinters();
147 // We're given a pointer to the first transfer vector. We read through them
148 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
149 // contain pointers to functions that we need to call to register our own
150 // hooks. The others are addresses of functions we can use to call into gold
153 bool registeredClaimFile = false;
154 bool RegisteredAllSymbolsRead = false;
156 for (; tv->tv_tag != LDPT_NULL; ++tv) {
157 switch (tv->tv_tag) {
158 case LDPT_OUTPUT_NAME:
159 output_name = tv->tv_u.tv_string;
161 case LDPT_LINKER_OUTPUT:
162 switch (tv->tv_u.tv_val) {
164 case LDPO_DYN: // .so
165 case LDPO_PIE: // position independent executable
166 RelocationModel = Reloc::PIC_;
168 case LDPO_EXEC: // .exe
169 RelocationModel = Reloc::Static;
172 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
177 options::process_plugin_option(tv->tv_u.tv_string);
179 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
180 ld_plugin_register_claim_file callback;
181 callback = tv->tv_u.tv_register_claim_file;
183 if (callback(claim_file_hook) != LDPS_OK)
186 registeredClaimFile = true;
188 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
189 ld_plugin_register_all_symbols_read callback;
190 callback = tv->tv_u.tv_register_all_symbols_read;
192 if (callback(all_symbols_read_hook) != LDPS_OK)
195 RegisteredAllSymbolsRead = true;
197 case LDPT_REGISTER_CLEANUP_HOOK: {
198 ld_plugin_register_cleanup callback;
199 callback = tv->tv_u.tv_register_cleanup;
201 if (callback(cleanup_hook) != LDPS_OK)
204 case LDPT_GET_INPUT_FILE:
205 get_input_file = tv->tv_u.tv_get_input_file;
207 case LDPT_RELEASE_INPUT_FILE:
208 release_input_file = tv->tv_u.tv_release_input_file;
210 case LDPT_ADD_SYMBOLS:
211 add_symbols = tv->tv_u.tv_add_symbols;
213 case LDPT_GET_SYMBOLS_V2:
214 get_symbols = tv->tv_u.tv_get_symbols;
216 case LDPT_ADD_INPUT_FILE:
217 add_input_file = tv->tv_u.tv_add_input_file;
219 case LDPT_SET_EXTRA_LIBRARY_PATH:
220 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
223 get_view = tv->tv_u.tv_get_view;
226 message = tv->tv_u.tv_message;
233 if (!registeredClaimFile) {
234 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
238 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
242 if (!RegisteredAllSymbolsRead)
245 if (!get_input_file) {
246 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
249 if (!release_input_file) {
250 message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
257 static const GlobalObject *getBaseObject(const GlobalValue &GV) {
258 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
259 return GA->getBaseObject();
260 return cast<GlobalObject>(&GV);
263 /// Called by gold to see whether this file is one that our plugin can handle.
264 /// We'll try to open it and register all the symbols with add_symbol if
266 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
269 MemoryBufferRef BufferRef;
270 std::unique_ptr<MemoryBuffer> Buffer;
273 if (get_view(file->handle, &view) != LDPS_OK) {
274 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
277 BufferRef = MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
280 // Gold has found what might be IR part-way inside of a file, such as
283 offset = file->offset;
285 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
286 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
288 if (std::error_code EC = BufferOrErr.getError()) {
289 message(LDPL_ERROR, EC.message().c_str());
292 Buffer = std::move(BufferOrErr.get());
293 BufferRef = Buffer->getMemBufferRef();
296 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
297 object::IRObjectFile::createIRObjectFile(BufferRef, Context);
298 std::error_code EC = ObjOrErr.getError();
299 if (EC == BitcodeError::InvalidBitcodeSignature ||
300 EC == object::object_error::invalid_file_type ||
301 EC == object::object_error::bitcode_section_not_found)
307 message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
308 EC.message().c_str());
311 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
313 Modules.resize(Modules.size() + 1);
314 claimed_file &cf = Modules.back();
316 cf.handle = file->handle;
318 for (auto &Sym : Obj->symbols()) {
319 uint32_t Symflags = Sym.getFlags();
320 if (!(Symflags & object::BasicSymbolRef::SF_Global))
323 if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
326 cf.syms.push_back(ld_plugin_symbol());
327 ld_plugin_symbol &sym = cf.syms.back();
328 sym.version = nullptr;
330 SmallString<64> Name;
332 raw_svector_ostream OS(Name);
335 sym.name = strdup(Name.c_str());
337 const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
339 sym.visibility = LDPV_DEFAULT;
341 switch (GV->getVisibility()) {
342 case GlobalValue::DefaultVisibility:
343 sym.visibility = LDPV_DEFAULT;
345 case GlobalValue::HiddenVisibility:
346 sym.visibility = LDPV_HIDDEN;
348 case GlobalValue::ProtectedVisibility:
349 sym.visibility = LDPV_PROTECTED;
354 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
355 sym.def = LDPK_UNDEF;
356 if (GV && GV->hasExternalWeakLinkage())
357 sym.def = LDPK_WEAKUNDEF;
361 assert(!GV->hasExternalWeakLinkage() &&
362 !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
363 if (GV->hasCommonLinkage())
364 sym.def = LDPK_COMMON;
365 else if (GV->isWeakForLinker())
366 sym.def = LDPK_WEAKDEF;
371 sym.comdat_key = nullptr;
373 const GlobalObject *Base = getBaseObject(*GV);
375 message(LDPL_FATAL, "Unable to determine comdat of alias!");
376 const Comdat *C = Base->getComdat();
378 sym.comdat_key = strdup(C->getName().str().c_str());
379 else if (Base->hasWeakLinkage() || Base->hasLinkOnceLinkage())
380 sym.comdat_key = strdup(sym.name);
383 sym.resolution = LDPR_UNKNOWN;
386 if (!cf.syms.empty()) {
387 if (add_symbols(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
388 message(LDPL_ERROR, "Unable to add symbols!");
396 static void keepGlobalValue(GlobalValue &GV,
397 std::vector<GlobalAlias *> &KeptAliases) {
398 assert(!GV.hasLocalLinkage());
400 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
401 KeptAliases.push_back(GA);
403 switch (GV.getLinkage()) {
406 case GlobalValue::LinkOnceAnyLinkage:
407 GV.setLinkage(GlobalValue::WeakAnyLinkage);
409 case GlobalValue::LinkOnceODRLinkage:
410 GV.setLinkage(GlobalValue::WeakODRLinkage);
414 assert(!GV.isDiscardableIfUnused());
417 static void internalize(GlobalValue &GV) {
418 if (GV.isDeclarationForLinker())
419 return; // We get here if there is a matching asm definition.
420 if (!GV.hasLocalLinkage())
421 GV.setLinkage(GlobalValue::InternalLinkage);
424 static void drop(GlobalValue &GV) {
425 if (auto *F = dyn_cast<Function>(&GV)) {
427 F->setComdat(nullptr); // Should deleteBody do this?
431 if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
432 Var->setInitializer(nullptr);
434 GlobalValue::ExternalLinkage); // Should setInitializer do this?
435 Var->setComdat(nullptr); // and this?
439 auto &Alias = cast<GlobalAlias>(GV);
440 Module &M = *Alias.getParent();
441 PointerType &Ty = *cast<PointerType>(Alias.getType());
442 GlobalValue::LinkageTypes L = Alias.getLinkage();
444 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
445 /*Initializer*/ nullptr);
446 Var->takeName(&Alias);
447 Alias.replaceAllUsesWith(Var);
448 Alias.eraseFromParent();
451 static const char *getResolutionName(ld_plugin_symbol_resolution R) {
457 case LDPR_PREVAILING_DEF:
458 return "PREVAILING_DEF";
459 case LDPR_PREVAILING_DEF_IRONLY:
460 return "PREVAILING_DEF_IRONLY";
461 case LDPR_PREEMPTED_REG:
462 return "PREEMPTED_REG";
463 case LDPR_PREEMPTED_IR:
464 return "PREEMPTED_IR";
465 case LDPR_RESOLVED_IR:
466 return "RESOLVED_IR";
467 case LDPR_RESOLVED_EXEC:
468 return "RESOLVED_EXEC";
469 case LDPR_RESOLVED_DYN:
470 return "RESOLVED_DYN";
471 case LDPR_PREVAILING_DEF_IRONLY_EXP:
472 return "PREVAILING_DEF_IRONLY_EXP";
474 llvm_unreachable("Unknown resolution");
477 static GlobalObject *makeInternalReplacement(GlobalObject *GO) {
478 Module *M = GO->getParent();
480 if (auto *F = dyn_cast<Function>(GO)) {
481 if (F->materialize())
482 message(LDPL_FATAL, "LLVM gold plugin has failed to read a function");
484 auto *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
487 ValueToValueMapTy VM;
488 Function::arg_iterator NewI = NewF->arg_begin();
489 for (auto &Arg : F->args()) {
490 NewI->setName(Arg.getName());
495 NewF->getBasicBlockList().splice(NewF->end(), F->getBasicBlockList());
496 for (auto &BB : *NewF) {
497 for (auto &Inst : BB)
498 RemapInstruction(&Inst, VM, RF_IgnoreMissingEntries);
504 auto *Var = cast<GlobalVariable>(GO);
505 Ret = new GlobalVariable(
506 *M, Var->getType()->getElementType(), Var->isConstant(),
507 Var->getLinkage(), Var->getInitializer(), Var->getName(),
508 nullptr, Var->getThreadLocalMode(), Var->getType()->getAddressSpace(),
509 Var->isExternallyInitialized());
510 Var->setInitializer(nullptr);
512 Ret->copyAttributesFrom(GO);
513 Ret->setLinkage(GlobalValue::InternalLinkage);
514 Ret->setComdat(GO->getComdat());
520 class LocalValueMaterializer : public ValueMaterializer {
521 DenseSet<GlobalValue *> &Dropped;
524 LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
525 Value *materializeValueFor(Value *V) override;
529 Value *LocalValueMaterializer::materializeValueFor(Value *V) {
530 auto *GV = dyn_cast<GlobalValue>(V);
533 if (!Dropped.count(GV))
535 assert(!isa<GlobalAlias>(GV) && "Found alias point to weak alias.");
536 return makeInternalReplacement(cast<GlobalObject>(GV));
539 static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
540 LocalValueMaterializer *Materializer) {
541 return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
544 static std::unique_ptr<Module>
545 getModuleForFile(LLVMContext &Context, claimed_file &F, raw_fd_ostream *ApiFile,
546 StringSet<> &Internalize, StringSet<> &Maybe) {
547 ld_plugin_input_file File;
548 if (get_input_file(F.handle, &File) != LDPS_OK)
549 message(LDPL_FATAL, "Failed to get file information");
551 if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
552 message(LDPL_FATAL, "Failed to get symbol information");
555 if (get_view(F.handle, &View) != LDPS_OK)
556 message(LDPL_FATAL, "Failed to get a view of file");
558 llvm::ErrorOr<MemoryBufferRef> MBOrErr =
559 object::IRObjectFile::findBitcodeInMemBuffer(
560 MemoryBufferRef(StringRef((const char *)View, File.filesize), ""));
561 if (std::error_code EC = MBOrErr.getError())
562 message(LDPL_FATAL, "Could not read bitcode from file : %s",
563 EC.message().c_str());
565 std::unique_ptr<MemoryBuffer> Buffer =
566 MemoryBuffer::getMemBuffer(MBOrErr->getBuffer(), "", false);
568 if (release_input_file(F.handle) != LDPS_OK)
569 message(LDPL_FATAL, "Failed to release file information");
571 ErrorOr<Module *> MOrErr = getLazyBitcodeModule(std::move(Buffer), Context);
573 if (std::error_code EC = MOrErr.getError())
574 message(LDPL_FATAL, "Could not read bitcode from file : %s",
575 EC.message().c_str());
577 std::unique_ptr<Module> M(MOrErr.get());
579 SmallPtrSet<GlobalValue *, 8> Used;
580 collectUsedGlobalVariables(*M, Used, /*CompilerUsed*/ false);
582 DenseSet<GlobalValue *> Drop;
583 std::vector<GlobalAlias *> KeptAliases;
584 for (ld_plugin_symbol &Sym : F.syms) {
585 ld_plugin_symbol_resolution Resolution =
586 (ld_plugin_symbol_resolution)Sym.resolution;
588 if (options::generate_api_file)
589 *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
591 GlobalValue *GV = M->getNamedValue(Sym.name);
593 continue; // Asm symbol.
595 if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
596 // Common linkage is special. There is no single symbol that wins the
597 // resolution. Instead we have to collect the maximum alignment and size.
598 // The IR linker does that for us if we just pass it every common GV.
599 // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
600 // internalize once the IR linker has done its job.
604 switch (Resolution) {
606 llvm_unreachable("Unexpected resolution");
608 case LDPR_RESOLVED_IR:
609 case LDPR_RESOLVED_EXEC:
610 case LDPR_RESOLVED_DYN:
612 assert(GV->isDeclarationForLinker());
615 case LDPR_PREVAILING_DEF_IRONLY: {
616 keepGlobalValue(*GV, KeptAliases);
617 if (!Used.count(GV)) {
618 // Since we use the regular lib/Linker, we cannot just internalize GV
619 // now or it will not be copied to the merged module. Instead we force
620 // it to be copied and then internalize it.
621 Internalize.insert(Sym.name);
626 case LDPR_PREVAILING_DEF:
627 keepGlobalValue(*GV, KeptAliases);
630 case LDPR_PREEMPTED_IR:
631 // Gold might have selected a linkonce_odr and preempted a weak_odr.
632 // In that case we have to make sure we don't end up internalizing it.
633 if (!GV->isDiscardableIfUnused())
634 Maybe.erase(Sym.name);
637 case LDPR_PREEMPTED_REG:
641 case LDPR_PREVAILING_DEF_IRONLY_EXP: {
642 // We can only check for address uses after we merge the modules. The
643 // reason is that this GV might have a copy in another module
644 // and in that module the address might be significant, but that
645 // copy will be LDPR_PREEMPTED_IR.
646 if (GV->hasLinkOnceODRLinkage())
647 Maybe.insert(Sym.name);
648 keepGlobalValue(*GV, KeptAliases);
654 free(Sym.comdat_key);
656 Sym.comdat_key = nullptr;
659 ValueToValueMapTy VM;
660 LocalValueMaterializer Materializer(Drop);
661 for (GlobalAlias *GA : KeptAliases) {
662 // Gold told us to keep GA. It is possible that a GV usied in the aliasee
663 // expression is being dropped. If that is the case, that GV must be copied.
664 Constant *Aliasee = GA->getAliasee();
665 Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
666 if (Aliasee != Replacement)
667 GA->setAliasee(Replacement);
670 for (auto *GV : Drop)
676 static void runLTOPasses(Module &M, TargetMachine &TM) {
678 PassManagerBuilder PMB;
679 PMB.LibraryInfo = new TargetLibraryInfo(Triple(TM.getTargetTriple()));
680 PMB.Inliner = createFunctionInliningPass();
681 PMB.VerifyInput = true;
682 PMB.VerifyOutput = true;
683 PMB.LoopVectorize = true;
684 PMB.SLPVectorize = true;
685 PMB.populateLTOPassManager(passes, &TM);
689 static void saveBCFile(StringRef Path, Module &M) {
691 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
693 message(LDPL_FATAL, "Failed to write the output file.");
694 WriteBitcodeToFile(&M, OS);
697 static void codegen(Module &M) {
698 const std::string &TripleStr = M.getTargetTriple();
699 Triple TheTriple(TripleStr);
702 const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
704 message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
706 if (unsigned NumOpts = options::extra.size())
707 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
709 SubtargetFeatures Features;
710 Features.getDefaultSubtargetFeatures(TheTriple);
711 for (const std::string &A : MAttrs)
712 Features.AddFeature(A);
714 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
715 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
716 TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
717 CodeModel::Default, CodeGenOpt::Aggressive));
719 runLTOPasses(M, *TM);
721 if (options::TheOutputType == options::OT_SAVE_TEMPS)
722 saveBCFile(output_name + ".opt.bc", M);
724 PassManager CodeGenPasses;
725 CodeGenPasses.add(new DataLayoutPass());
727 SmallString<128> Filename;
729 if (options::obj_path.empty()) {
731 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
733 message(LDPL_FATAL, "Could not create temporary file: %s",
734 EC.message().c_str());
736 Filename = options::obj_path;
738 sys::fs::openFileForWrite(Filename.c_str(), FD, sys::fs::F_None);
740 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
744 raw_fd_ostream OS(FD, true);
745 formatted_raw_ostream FOS(OS);
747 if (TM->addPassesToEmitFile(CodeGenPasses, FOS,
748 TargetMachine::CGFT_ObjectFile))
749 message(LDPL_FATAL, "Failed to setup codegen");
750 CodeGenPasses.run(M);
753 if (add_input_file(Filename.c_str()) != LDPS_OK)
755 "Unable to add .o file to the link. File left behind in: %s",
758 if (options::obj_path.empty())
759 Cleanup.push_back(Filename.c_str());
762 /// gold informs us that all symbols have been read. At this point, we use
763 /// get_symbols to see if any of our definitions have been overridden by a
764 /// native object file. Then, perform optimization and codegen.
765 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
770 std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
771 Linker L(Combined.get());
773 std::string DefaultTriple = sys::getDefaultTargetTriple();
775 StringSet<> Internalize;
777 for (claimed_file &F : Modules) {
778 std::unique_ptr<Module> M =
779 getModuleForFile(Context, F, ApiFile, Internalize, Maybe);
780 if (!options::triple.empty())
781 M->setTargetTriple(options::triple.c_str());
782 else if (M->getTargetTriple().empty()) {
783 M->setTargetTriple(DefaultTriple);
786 if (L.linkInModule(M.get()))
787 message(LDPL_FATAL, "Failed to link module");
790 for (const auto &Name : Internalize) {
791 GlobalValue *GV = Combined->getNamedValue(Name.first());
796 for (const auto &Name : Maybe) {
797 GlobalValue *GV = Combined->getNamedValue(Name.first());
800 GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
801 if (canBeOmittedFromSymbolTable(GV))
805 if (options::TheOutputType == options::OT_DISABLE)
808 if (options::TheOutputType != options::OT_NORMAL) {
810 if (options::TheOutputType == options::OT_BC_ONLY)
813 path = output_name + ".bc";
814 saveBCFile(path, *L.getModule());
815 if (options::TheOutputType == options::OT_BC_ONLY)
819 codegen(*L.getModule());
821 if (!options::extra_library_path.empty() &&
822 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
823 message(LDPL_FATAL, "Unable to set the extra library path.");
828 static ld_plugin_status all_symbols_read_hook(void) {
829 ld_plugin_status Ret;
830 if (!options::generate_api_file) {
831 Ret = allSymbolsReadHook(nullptr);
834 raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
836 message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
837 EC.message().c_str());
838 Ret = allSymbolsReadHook(&ApiFile);
841 if (options::TheOutputType == options::OT_BC_ONLY ||
842 options::TheOutputType == options::OT_DISABLE)
848 static ld_plugin_status cleanup_hook(void) {
849 for (std::string &Name : Cleanup) {
850 std::error_code EC = sys::fs::remove(Name);
852 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
853 EC.message().c_str());