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 "SymbolTable.h" 15 #include "Symbols.h" 16 #include "lld/Core/TargetOptionsCommandFlags.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallString.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/ADT/Twine.h" 21 #include "llvm/BinaryFormat/ELF.h" 22 #include "llvm/IR/DiagnosticPrinter.h" 23 #include "llvm/LTO/Caching.h" 24 #include "llvm/LTO/Config.h" 25 #include "llvm/LTO/LTO.h" 26 #include "llvm/Object/SymbolicFile.h" 27 #include "llvm/Support/CodeGen.h" 28 #include "llvm/Support/Error.h" 29 #include "llvm/Support/FileSystem.h" 30 #include "llvm/Support/MemoryBuffer.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include <algorithm> 33 #include <cstddef> 34 #include <memory> 35 #include <string> 36 #include <system_error> 37 #include <vector> 38 39 using namespace llvm; 40 using namespace llvm::object; 41 using namespace llvm::ELF; 42 43 using namespace lld; 44 using namespace lld::elf; 45 46 // This is for use when debugging LTO. 47 static void saveBuffer(StringRef Buffer, const Twine &Path) { 48 std::error_code EC; 49 raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None); 50 if (EC) 51 error("cannot create " + Path + ": " + EC.message()); 52 OS << Buffer; 53 } 54 55 static void diagnosticHandler(const DiagnosticInfo &DI) { 56 SmallString<128> ErrStorage; 57 raw_svector_ostream OS(ErrStorage); 58 DiagnosticPrinterRawOStream DP(OS); 59 DI.print(DP); 60 warn(ErrStorage); 61 } 62 63 static void checkError(Error E) { 64 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error { 65 error(EIB.message()); 66 return Error::success(); 67 }); 68 } 69 70 static std::unique_ptr<lto::LTO> createLTO() { 71 lto::Config Conf; 72 73 // LLD supports the new relocations. 74 Conf.Options = InitTargetOptionsFromCodeGenFlags(); 75 Conf.Options.RelaxELFRelocations = true; 76 77 // Always emit a section per function/datum with LTO. 78 Conf.Options.FunctionSections = true; 79 Conf.Options.DataSections = true; 80 81 if (Config->Relocatable) 82 Conf.RelocModel = None; 83 else if (Config->Pic) 84 Conf.RelocModel = Reloc::PIC_; 85 else 86 Conf.RelocModel = Reloc::Static; 87 Conf.CodeModel = GetCodeModelFromCMModel(); 88 Conf.DisableVerify = Config->DisableVerify; 89 Conf.DiagHandler = diagnosticHandler; 90 Conf.OptLevel = Config->LTOO; 91 92 // Set up a custom pipeline if we've been asked to. 93 Conf.OptPipeline = Config->LTONewPmPasses; 94 Conf.AAPipeline = Config->LTOAAPipeline; 95 96 // Set up optimization remarks if we've been asked to. 97 Conf.RemarksFilename = Config->OptRemarksFilename; 98 Conf.RemarksWithHotness = Config->OptRemarksWithHotness; 99 100 if (Config->SaveTemps) 101 checkError(Conf.addSaveTemps(std::string(Config->OutputFile) + ".", 102 /*UseInputModulePath*/ true)); 103 104 lto::ThinBackend Backend; 105 if (Config->ThinLTOJobs != -1u) 106 Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs); 107 return llvm::make_unique<lto::LTO>(std::move(Conf), Backend, 108 Config->LTOPartitions); 109 } 110 111 BitcodeCompiler::BitcodeCompiler() : LTOObj(createLTO()) { 112 for (Symbol *Sym : Symtab->getSymbols()) { 113 StringRef Name = Sym->body()->getName(); 114 for (StringRef Prefix : {"__start_", "__stop_"}) 115 if (Name.startswith(Prefix)) 116 UsedStartStop.insert(Name.substr(Prefix.size())); 117 } 118 } 119 120 BitcodeCompiler::~BitcodeCompiler() = default; 121 122 static void undefine(Symbol *S) { 123 replaceBody<Undefined>(S, S->body()->getName(), /*IsLocal=*/false, 124 STV_DEFAULT, S->body()->Type, nullptr); 125 } 126 127 void BitcodeCompiler::add(BitcodeFile &F) { 128 lto::InputFile &Obj = *F.Obj; 129 unsigned SymNum = 0; 130 std::vector<Symbol *> Syms = F.getSymbols(); 131 std::vector<lto::SymbolResolution> Resols(Syms.size()); 132 133 // Provide a resolution to the LTO API for each symbol. 134 for (const lto::InputFile::Symbol &ObjSym : Obj.symbols()) { 135 Symbol *Sym = Syms[SymNum]; 136 lto::SymbolResolution &R = Resols[SymNum]; 137 ++SymNum; 138 SymbolBody *B = Sym->body(); 139 140 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile 141 // reports two symbols for module ASM defined. Without this check, lld 142 // flags an undefined in IR with a definition in ASM as prevailing. 143 // Once IRObjectFile is fixed to report only one symbol this hack can 144 // be removed. 145 R.Prevailing = !ObjSym.isUndefined() && B->File == &F; 146 147 R.VisibleToRegularObj = Sym->IsUsedInRegularObj || 148 (R.Prevailing && Sym->includeInDynsym()) || 149 UsedStartStop.count(ObjSym.getSectionName()); 150 if (R.Prevailing) 151 undefine(Sym); 152 R.LinkerRedefined = Config->RenamedSymbols.count(Sym); 153 } 154 checkError(LTOObj->add(std::move(F.Obj), Resols)); 155 } 156 157 // Merge all the bitcode files we have seen, codegen the result 158 // and return the resulting ObjectFile(s). 159 std::vector<InputFile *> BitcodeCompiler::compile() { 160 std::vector<InputFile *> Ret; 161 unsigned MaxTasks = LTOObj->getMaxTasks(); 162 Buff.resize(MaxTasks); 163 Files.resize(MaxTasks); 164 165 // The --thinlto-cache-dir option specifies the path to a directory in which 166 // to cache native object files for ThinLTO incremental builds. If a path was 167 // specified, configure LTO to use it as the cache directory. 168 lto::NativeObjectCache Cache; 169 if (!Config->ThinLTOCacheDir.empty()) 170 Cache = check( 171 lto::localCache(Config->ThinLTOCacheDir, 172 [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) { 173 Files[Task] = std::move(MB); 174 })); 175 176 checkError(LTOObj->run( 177 [&](size_t Task) { 178 return llvm::make_unique<lto::NativeObjectStream>( 179 llvm::make_unique<raw_svector_ostream>(Buff[Task])); 180 }, 181 Cache)); 182 183 if (!Config->ThinLTOCacheDir.empty()) 184 pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy); 185 186 for (unsigned I = 0; I != MaxTasks; ++I) { 187 if (Buff[I].empty()) 188 continue; 189 if (Config->SaveTemps) { 190 if (I == 0) 191 saveBuffer(Buff[I], Config->OutputFile + ".lto.o"); 192 else 193 saveBuffer(Buff[I], Config->OutputFile + Twine(I) + ".lto.o"); 194 } 195 InputFile *Obj = createObjectFile(MemoryBufferRef(Buff[I], "lto.tmp")); 196 Ret.push_back(Obj); 197 } 198 199 for (std::unique_ptr<MemoryBuffer> &File : Files) 200 if (File) 201 Ret.push_back(createObjectFile(*File)); 202 203 return Ret; 204 } 205