1 //===- LTO.cpp ------------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 #include "InputFiles.h"
13 #include "LinkerScript.h"
14 #include "SymbolTable.h"
16 #include "lld/Common/ErrorHandler.h"
17 #include "lld/Common/TargetOptionsCommandFlags.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/BinaryFormat/ELF.h"
23 #include "llvm/Bitcode/BitcodeReader.h"
24 #include "llvm/Bitcode/BitcodeWriter.h"
25 #include "llvm/IR/DiagnosticPrinter.h"
26 #include "llvm/LTO/Caching.h"
27 #include "llvm/LTO/Config.h"
28 #include "llvm/LTO/LTO.h"
29 #include "llvm/Object/SymbolicFile.h"
30 #include "llvm/Support/CodeGen.h"
31 #include "llvm/Support/Error.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/MemoryBuffer.h"
38 #include <system_error>
42 using namespace llvm::object;
43 using namespace llvm::ELF;
46 using namespace lld::elf;
48 // Creates an empty file to store a list of object files for final
49 // linking of distributed ThinLTO.
50 static std::unique_ptr<raw_fd_ostream> openFile(StringRef File) {
53 llvm::make_unique<raw_fd_ostream>(File, EC, sys::fs::OpenFlags::F_None);
55 error("cannot open " + File + ": " + EC.message());
61 static std::string getThinLTOOutputFile(StringRef ModulePath) {
62 return lto::getThinLTOOutputFile(ModulePath,
63 Config->ThinLTOPrefixReplace.first,
64 Config->ThinLTOPrefixReplace.second);
67 static lto::Config createConfig() {
70 // LLD supports the new relocations.
71 C.Options = InitTargetOptionsFromCodeGenFlags();
72 C.Options.RelaxELFRelocations = true;
74 // Always emit a section per function/datum with LTO.
75 C.Options.FunctionSections = true;
76 C.Options.DataSections = true;
78 if (Config->Relocatable)
81 C.RelocModel = Reloc::PIC_;
83 C.RelocModel = Reloc::Static;
85 C.CodeModel = GetCodeModelFromCMModel();
86 C.DisableVerify = Config->DisableVerify;
87 C.DiagHandler = diagnosticHandler;
88 C.OptLevel = Config->LTOO;
91 // Set up a custom pipeline if we've been asked to.
92 C.OptPipeline = Config->LTONewPmPasses;
93 C.AAPipeline = Config->LTOAAPipeline;
95 // Set up optimization remarks if we've been asked to.
96 C.RemarksFilename = Config->OptRemarksFilename;
97 C.RemarksWithHotness = Config->OptRemarksWithHotness;
99 C.SampleProfile = Config->LTOSampleProfile;
100 C.UseNewPM = Config->LTONewPassManager;
101 C.DebugPassManager = Config->LTODebugPassManager;
102 C.DwoDir = Config->DwoDir;
104 if (Config->SaveTemps)
105 checkError(C.addSaveTemps(Config->OutputFile.str() + ".",
106 /*UseInputModulePath*/ true));
110 BitcodeCompiler::BitcodeCompiler() {
111 // Initialize LTOObj.
112 lto::ThinBackend Backend;
114 if (Config->ThinLTOIndexOnly) {
115 StringRef Path = Config->ThinLTOIndexOnlyArg;
117 IndexFile = openFile(Path);
119 auto OnIndexWrite = [&](const std::string &Identifier) {
120 ObjectToIndexFileState[Identifier] = true;
123 Backend = lto::createWriteIndexesThinBackend(
124 Config->ThinLTOPrefixReplace.first, Config->ThinLTOPrefixReplace.second,
125 Config->ThinLTOEmitImportsFiles, IndexFile.get(), OnIndexWrite);
126 } else if (Config->ThinLTOJobs != -1U) {
127 Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs);
130 LTOObj = llvm::make_unique<lto::LTO>(createConfig(), Backend,
131 Config->LTOPartitions);
133 // Initialize UsedStartStop.
134 for (Symbol *Sym : Symtab->getSymbols()) {
135 StringRef Name = Sym->getName();
136 for (StringRef Prefix : {"__start_", "__stop_"})
137 if (Name.startswith(Prefix))
138 UsedStartStop.insert(Name.substr(Prefix.size()));
142 BitcodeCompiler::~BitcodeCompiler() = default;
144 static void undefine(Symbol *S) {
145 replaceSymbol<Undefined>(S, nullptr, S->getName(), STB_GLOBAL, STV_DEFAULT,
149 void BitcodeCompiler::add(BitcodeFile &F) {
150 lto::InputFile &Obj = *F.Obj;
151 bool IsExec = !Config->Shared && !Config->Relocatable;
153 if (Config->ThinLTOIndexOnly)
154 ObjectToIndexFileState.insert({Obj.getName(), false});
156 ArrayRef<Symbol *> Syms = F.getSymbols();
157 ArrayRef<lto::InputFile::Symbol> ObjSyms = Obj.symbols();
158 std::vector<lto::SymbolResolution> Resols(Syms.size());
160 // Provide a resolution to the LTO API for each symbol.
161 for (size_t I = 0, E = Syms.size(); I != E; ++I) {
162 Symbol *Sym = Syms[I];
163 const lto::InputFile::Symbol &ObjSym = ObjSyms[I];
164 lto::SymbolResolution &R = Resols[I];
166 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
167 // reports two symbols for module ASM defined. Without this check, lld
168 // flags an undefined in IR with a definition in ASM as prevailing.
169 // Once IRObjectFile is fixed to report only one symbol this hack can
171 R.Prevailing = !ObjSym.isUndefined() && Sym->File == &F;
173 // We ask LTO to preserve following global symbols:
174 // 1) All symbols when doing relocatable link, so that them can be used
175 // for doing final link.
176 // 2) Symbols that are used in regular objects.
177 // 3) C named sections if we have corresponding __start_/__stop_ symbol.
178 // 4) Symbols that are defined in bitcode files and used for dynamic linking.
179 R.VisibleToRegularObj = Config->Relocatable || Sym->IsUsedInRegularObj ||
180 (R.Prevailing && Sym->includeInDynsym()) ||
181 UsedStartStop.count(ObjSym.getSectionName());
182 const auto *DR = dyn_cast<Defined>(Sym);
183 R.FinalDefinitionInLinkageUnit =
184 (IsExec || Sym->Visibility != STV_DEFAULT) && DR &&
185 // Skip absolute symbols from ELF objects, otherwise PC-rel relocations
186 // will be generated by for them, triggering linker errors.
187 // Symbol section is always null for bitcode symbols, hence the check
188 // for isElf(). Skip linker script defined symbols as well: they have
190 !(DR->Section == nullptr && (!Sym->File || Sym->File->isElf()));
195 // We tell LTO to not apply interprocedural optimization for wrapped
196 // (with --wrap) symbols because otherwise LTO would inline them while
197 // their values are still not final.
198 R.LinkerRedefined = !Sym->CanInline;
200 checkError(LTOObj->add(std::move(F.Obj), Resols));
203 static void createEmptyIndex(StringRef ModulePath) {
204 std::string Path = replaceThinLTOSuffix(getThinLTOOutputFile(ModulePath));
205 std::unique_ptr<raw_fd_ostream> OS = openFile(Path + ".thinlto.bc");
209 ModuleSummaryIndex M(/*HaveGVs*/ false);
210 M.setSkipModuleByDistributedBackend();
211 WriteIndexToFile(M, *OS);
213 if (Config->ThinLTOEmitImportsFiles)
214 openFile(Path + ".imports");
217 // Merge all the bitcode files we have seen, codegen the result
218 // and return the resulting ObjectFile(s).
219 std::vector<InputFile *> BitcodeCompiler::compile() {
220 unsigned MaxTasks = LTOObj->getMaxTasks();
221 Buf.resize(MaxTasks);
222 Files.resize(MaxTasks);
224 // The --thinlto-cache-dir option specifies the path to a directory in which
225 // to cache native object files for ThinLTO incremental builds. If a path was
226 // specified, configure LTO to use it as the cache directory.
227 lto::NativeObjectCache Cache;
228 if (!Config->ThinLTOCacheDir.empty())
230 lto::localCache(Config->ThinLTOCacheDir,
231 [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
232 Files[Task] = std::move(MB);
235 checkError(LTOObj->run(
237 return llvm::make_unique<lto::NativeObjectStream>(
238 llvm::make_unique<raw_svector_ostream>(Buf[Task]));
242 // Emit empty index files for non-indexed files
243 if (Config->ThinLTOIndexOnly) {
244 for (auto &Identifier : ObjectToIndexFileState)
245 if (!Identifier.getValue()) {
246 std::string Path = getThinLTOOutputFile(Identifier.getKey());
247 openFile(Path + ".thinlto.bc");
249 if (Config->ThinLTOEmitImportsFiles)
250 openFile(Path + ".imports");
254 // If LazyObjFile has not been added to link, emit empty index files.
255 // This is needed because this is what GNU gold plugin does and we have a
256 // distributed build system that depends on that behavior.
257 if (Config->ThinLTOIndexOnly) {
258 for (LazyObjFile *F : LazyObjFiles)
259 if (!F->AddedToLink && isBitcode(F->MB))
260 createEmptyIndex(F->getName());
262 if (!Config->LTOObjPath.empty())
263 saveBuffer(Buf[0], Config->LTOObjPath);
265 // ThinLTO with index only option is required to generate only the index
266 // files. After that, we exit from linker and ThinLTO backend runs in a
267 // distributed environment.
273 if (!Config->ThinLTOCacheDir.empty())
274 pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy);
276 std::vector<InputFile *> Ret;
277 for (unsigned I = 0; I != MaxTasks; ++I) {
280 if (Config->SaveTemps) {
282 saveBuffer(Buf[I], Config->OutputFile + ".lto.o");
284 saveBuffer(Buf[I], Config->OutputFile + Twine(I) + ".lto.o");
286 InputFile *Obj = createObjectFile(MemoryBufferRef(Buf[I], "lto.tmp"));
290 for (std::unique_ptr<MemoryBuffer> &File : Files)
292 Ret.push_back(createObjectFile(*File));