xref: /llvm-project-15.0.7/lld/ELF/LTO.cpp (revision 84c152a1)
1 //===- LTO.cpp ------------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "LTO.h"
11 #include "Config.h"
12 #include "Error.h"
13 #include "InputFiles.h"
14 #include "Symbols.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/CodeGen/CommandFlags.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/LTO/Config.h"
22 #include "llvm/LTO/LTO.h"
23 #include "llvm/Object/SymbolicFile.h"
24 #include "llvm/Support/CodeGen.h"
25 #include "llvm/Support/ELF.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <algorithm>
31 #include <cstddef>
32 #include <memory>
33 #include <string>
34 #include <system_error>
35 #include <vector>
36 
37 using namespace llvm;
38 using namespace llvm::object;
39 using namespace llvm::ELF;
40 
41 using namespace lld;
42 using namespace lld::elf;
43 
44 // This is for use when debugging LTO.
45 static void saveBuffer(StringRef Buffer, const Twine &Path) {
46   std::error_code EC;
47   raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
48   if (EC)
49     error(EC, "cannot create " + Path);
50   OS << Buffer;
51 }
52 
53 static void diagnosticHandler(const DiagnosticInfo &DI) {
54   SmallString<128> ErrStorage;
55   raw_svector_ostream OS(ErrStorage);
56   DiagnosticPrinterRawOStream DP(OS);
57   DI.print(DP);
58   warn(ErrStorage);
59 }
60 
61 static void checkError(Error E) {
62   handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
63     error(EIB.message());
64     return Error::success();
65   });
66 }
67 
68 static std::unique_ptr<lto::LTO> createLTO() {
69   lto::Config Conf;
70 
71   // LLD supports the new relocations.
72   Conf.Options = InitTargetOptionsFromCodeGenFlags();
73   Conf.Options.RelaxELFRelocations = true;
74 
75   Conf.RelocModel = Config->Pic ? Reloc::PIC_ : Reloc::Static;
76   Conf.DisableVerify = Config->DisableVerify;
77   Conf.DiagHandler = diagnosticHandler;
78   Conf.OptLevel = Config->LtoO;
79 
80   // Set up a custom pipeline if we've been asked to.
81   Conf.OptPipeline = Config->LtoNewPmPasses;
82   Conf.AAPipeline = Config->LtoAAPipeline;
83 
84   if (Config->SaveTemps)
85     checkError(Conf.addSaveTemps(std::string(Config->OutputFile) + ".",
86                                  /*UseInputModulePath*/ true));
87 
88   lto::ThinBackend Backend;
89   if (Config->ThinLtoJobs != -1u)
90     Backend = lto::createInProcessThinBackend(Config->ThinLtoJobs);
91   return llvm::make_unique<lto::LTO>(std::move(Conf), Backend,
92                                      Config->LtoPartitions);
93 }
94 
95 BitcodeCompiler::BitcodeCompiler() : LtoObj(createLTO()) {}
96 
97 BitcodeCompiler::~BitcodeCompiler() = default;
98 
99 static void undefine(Symbol *S) {
100   replaceBody<Undefined>(S, S->body()->getName(), STV_DEFAULT, S->body()->Type,
101                          nullptr);
102 }
103 
104 void BitcodeCompiler::add(BitcodeFile &F) {
105   lto::InputFile &Obj = *F.Obj;
106   if (Obj.getDataLayoutStr().empty())
107     fatal("invalid bitcode file: " + F.getName() + " has no datalayout");
108 
109   unsigned SymNum = 0;
110   std::vector<Symbol *> Syms = F.getSymbols();
111   std::vector<lto::SymbolResolution> Resols(Syms.size());
112 
113   // Provide a resolution to the LTO API for each symbol.
114   for (const lto::InputFile::Symbol &ObjSym : Obj.symbols()) {
115     Symbol *Sym = Syms[SymNum];
116     lto::SymbolResolution &R = Resols[SymNum];
117     ++SymNum;
118     SymbolBody *B = Sym->body();
119 
120     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
121     // reports two symbols for module ASM defined. Without this check, lld
122     // flags an undefined in IR with a definition in ASM as prevailing.
123     // Once IRObjectFile is fixed to report only one symbol this hack can
124     // be removed.
125     R.Prevailing =
126         !(ObjSym.getFlags() & object::BasicSymbolRef::SF_Undefined) &&
127         B->File == &F;
128 
129     R.VisibleToRegularObj =
130         Sym->IsUsedInRegularObj || (R.Prevailing && Sym->includeInDynsym());
131     if (R.Prevailing)
132       undefine(Sym);
133   }
134   checkError(LtoObj->add(std::move(F.Obj), Resols));
135 }
136 
137 // Merge all the bitcode files we have seen, codegen the result
138 // and return the resulting ObjectFile(s).
139 std::vector<InputFile *> BitcodeCompiler::compile() {
140   std::vector<InputFile *> Ret;
141   unsigned MaxTasks = LtoObj->getMaxTasks();
142   Buff.resize(MaxTasks);
143 
144   checkError(LtoObj->run([&](size_t Task) {
145     return llvm::make_unique<lto::NativeObjectStream>(
146         llvm::make_unique<raw_svector_ostream>(Buff[Task]));
147   }));
148 
149   for (unsigned I = 0; I != MaxTasks; ++I) {
150     if (Buff[I].empty())
151       continue;
152     if (Config->SaveTemps) {
153       if (MaxTasks == 1)
154         saveBuffer(Buff[I], Config->OutputFile + ".lto.o");
155       else
156         saveBuffer(Buff[I], Config->OutputFile + Twine(I) + ".lto.o");
157     }
158     InputFile *Obj = createObjectFile(MemoryBufferRef(Buff[I], "lto.tmp"));
159     Ret.push_back(Obj);
160   }
161   return Ret;
162 }
163