1 //===- LTO.cpp ------------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
13 #include "InputFiles.h"
15 #include "lld/Core/TargetOptionsCommandFlags.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/LTO/Caching.h"
22 #include "llvm/LTO/Config.h"
23 #include "llvm/LTO/LTO.h"
24 #include "llvm/Object/SymbolicFile.h"
25 #include "llvm/Support/CodeGen.h"
26 #include "llvm/Support/ELF.h"
27 #include "llvm/Support/Error.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
35 #include <system_error>
39 using namespace llvm::object;
40 using namespace llvm::ELF;
43 using namespace lld::elf;
45 // This is for use when debugging LTO.
46 static void saveBuffer(StringRef Buffer, const Twine &Path) {
48 raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
50 error("cannot create " + Path + ": " + EC.message());
54 static void diagnosticHandler(const DiagnosticInfo &DI) {
55 SmallString<128> ErrStorage;
56 raw_svector_ostream OS(ErrStorage);
57 DiagnosticPrinterRawOStream DP(OS);
62 static void checkError(Error E) {
63 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
65 return Error::success();
69 static std::unique_ptr<lto::LTO> createLTO() {
72 // LLD supports the new relocations.
73 Conf.Options = InitTargetOptionsFromCodeGenFlags();
74 Conf.Options.RelaxELFRelocations = true;
76 Conf.RelocModel = Config->Pic ? Reloc::PIC_ : Reloc::Static;
77 Conf.CodeModel = GetCodeModelFromCMModel();
78 Conf.DisableVerify = Config->DisableVerify;
79 Conf.DiagHandler = diagnosticHandler;
80 Conf.OptLevel = Config->LTOO;
82 // Set up a custom pipeline if we've been asked to.
83 Conf.OptPipeline = Config->LTONewPmPasses;
84 Conf.AAPipeline = Config->LTOAAPipeline;
86 // Set up optimization remarks if we've been asked to.
87 Conf.RemarksFilename = Config->OptRemarksFilename;
88 Conf.RemarksWithHotness = Config->OptRemarksWithHotness;
90 if (Config->SaveTemps)
91 checkError(Conf.addSaveTemps(std::string(Config->OutputFile) + ".",
92 /*UseInputModulePath*/ true));
94 lto::ThinBackend Backend;
95 if (Config->ThinLTOJobs != -1u)
96 Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs);
97 return llvm::make_unique<lto::LTO>(std::move(Conf), Backend,
98 Config->LTOPartitions);
101 BitcodeCompiler::BitcodeCompiler() : LTOObj(createLTO()) {}
103 BitcodeCompiler::~BitcodeCompiler() = default;
105 static void undefine(Symbol *S) {
106 replaceBody<Undefined>(S, S->body()->getName(), /*IsLocal=*/false,
107 STV_DEFAULT, S->body()->Type, nullptr);
110 void BitcodeCompiler::add(BitcodeFile &F) {
111 lto::InputFile &Obj = *F.Obj;
113 std::vector<Symbol *> Syms = F.getSymbols();
114 std::vector<lto::SymbolResolution> Resols(Syms.size());
116 // Provide a resolution to the LTO API for each symbol.
117 for (const lto::InputFile::Symbol &ObjSym : Obj.symbols()) {
118 Symbol *Sym = Syms[SymNum];
119 lto::SymbolResolution &R = Resols[SymNum];
121 SymbolBody *B = Sym->body();
123 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
124 // reports two symbols for module ASM defined. Without this check, lld
125 // flags an undefined in IR with a definition in ASM as prevailing.
126 // Once IRObjectFile is fixed to report only one symbol this hack can
128 R.Prevailing = !ObjSym.isUndefined() && B->File == &F;
130 R.VisibleToRegularObj =
131 Sym->IsUsedInRegularObj || (R.Prevailing && Sym->includeInDynsym());
135 checkError(LTOObj->add(std::move(F.Obj), Resols));
138 // Merge all the bitcode files we have seen, codegen the result
139 // and return the resulting ObjectFile(s).
140 std::vector<InputFile *> BitcodeCompiler::compile() {
141 std::vector<InputFile *> Ret;
142 unsigned MaxTasks = LTOObj->getMaxTasks();
143 Buff.resize(MaxTasks);
144 Files.resize(MaxTasks);
146 // The --thinlto-cache-dir option specifies the path to a directory in which
147 // to cache native object files for ThinLTO incremental builds. If a path was
148 // specified, configure LTO to use it as the cache directory.
149 lto::NativeObjectCache Cache;
150 if (!Config->ThinLTOCacheDir.empty())
152 lto::localCache(Config->ThinLTOCacheDir,
153 [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
154 Files[Task] = std::move(MB);
157 checkError(LTOObj->run(
159 return llvm::make_unique<lto::NativeObjectStream>(
160 llvm::make_unique<raw_svector_ostream>(Buff[Task]));
164 if (!Config->ThinLTOCacheDir.empty())
165 pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy);
167 for (unsigned I = 0; I != MaxTasks; ++I) {
170 if (Config->SaveTemps) {
172 saveBuffer(Buff[I], Config->OutputFile + ".lto.o");
174 saveBuffer(Buff[I], Config->OutputFile + Twine(I) + ".lto.o");
176 InputFile *Obj = createObjectFile(MemoryBufferRef(Buff[I], "lto.tmp"));
180 for (std::unique_ptr<MemoryBuffer> &File : Files)
182 Ret.push_back(createObjectFile(*File));