1 //===- LTO.cpp ------------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "LTO.h" 10 #include "Config.h" 11 #include "InputFiles.h" 12 #include "LinkerScript.h" 13 #include "SymbolTable.h" 14 #include "Symbols.h" 15 #include "lld/Common/Args.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" 34 #include <algorithm> 35 #include <cstddef> 36 #include <memory> 37 #include <string> 38 #include <system_error> 39 #include <vector> 40 41 using namespace llvm; 42 using namespace llvm::object; 43 using namespace llvm::ELF; 44 45 using namespace lld; 46 using namespace lld::elf; 47 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) { 51 std::error_code EC; 52 auto Ret = 53 llvm::make_unique<raw_fd_ostream>(File, EC, sys::fs::OpenFlags::F_None); 54 if (EC) { 55 error("cannot open " + File + ": " + EC.message()); 56 return nullptr; 57 } 58 return Ret; 59 } 60 61 static std::string getThinLTOOutputFile(StringRef ModulePath) { 62 return lto::getThinLTOOutputFile(ModulePath, 63 Config->ThinLTOPrefixReplace.first, 64 Config->ThinLTOPrefixReplace.second); 65 } 66 67 static lto::Config createConfig() { 68 lto::Config C; 69 70 // LLD supports the new relocations and address-significance tables. 71 C.Options = initTargetOptionsFromCodeGenFlags(); 72 C.Options.RelaxELFRelocations = true; 73 C.Options.EmitAddrsig = true; 74 75 // Always emit a section per function/datum with LTO. 76 C.Options.FunctionSections = true; 77 C.Options.DataSections = true; 78 79 if (Config->Relocatable) 80 C.RelocModel = None; 81 else if (Config->Pic) 82 C.RelocModel = Reloc::PIC_; 83 else 84 C.RelocModel = Reloc::Static; 85 86 C.CodeModel = getCodeModelFromCMModel(); 87 C.DisableVerify = Config->DisableVerify; 88 C.DiagHandler = diagnosticHandler; 89 C.OptLevel = Config->LTOO; 90 C.CPU = getCPUStr(); 91 C.MAttrs = getMAttrs(); 92 C.CGOptLevel = args::getCGOptLevel(Config->LTOO); 93 94 // Set up a custom pipeline if we've been asked to. 95 C.OptPipeline = Config->LTONewPmPasses; 96 C.AAPipeline = Config->LTOAAPipeline; 97 98 // Set up optimization remarks if we've been asked to. 99 C.RemarksFilename = Config->OptRemarksFilename; 100 C.RemarksPasses = Config->OptRemarksPasses; 101 C.RemarksWithHotness = Config->OptRemarksWithHotness; 102 C.RemarksFormat = Config->OptRemarksFormat; 103 104 C.SampleProfile = Config->LTOSampleProfile; 105 C.UseNewPM = Config->LTONewPassManager; 106 C.DebugPassManager = Config->LTODebugPassManager; 107 C.DwoDir = Config->DwoDir; 108 109 C.CSIRProfile = Config->LTOCSProfileFile; 110 C.RunCSIRInstr = Config->LTOCSProfileGenerate; 111 112 if (Config->EmitLLVM) { 113 C.PostInternalizeModuleHook = [](size_t Task, const Module &M) { 114 if (std::unique_ptr<raw_fd_ostream> OS = openFile(Config->OutputFile)) 115 WriteBitcodeToFile(M, *OS, false); 116 return false; 117 }; 118 } 119 120 if (Config->SaveTemps) 121 checkError(C.addSaveTemps(Config->OutputFile.str() + ".", 122 /*UseInputModulePath*/ true)); 123 return C; 124 } 125 126 BitcodeCompiler::BitcodeCompiler() { 127 // Initialize IndexFile. 128 if (!Config->ThinLTOIndexOnlyArg.empty()) 129 IndexFile = openFile(Config->ThinLTOIndexOnlyArg); 130 131 // Initialize LTOObj. 132 lto::ThinBackend Backend; 133 if (Config->ThinLTOIndexOnly) { 134 auto OnIndexWrite = [&](StringRef S) { ThinIndices.erase(S); }; 135 Backend = lto::createWriteIndexesThinBackend( 136 Config->ThinLTOPrefixReplace.first, Config->ThinLTOPrefixReplace.second, 137 Config->ThinLTOEmitImportsFiles, IndexFile.get(), OnIndexWrite); 138 } else if (Config->ThinLTOJobs != -1U) { 139 Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs); 140 } 141 142 LTOObj = llvm::make_unique<lto::LTO>(createConfig(), Backend, 143 Config->LTOPartitions); 144 145 // Initialize UsedStartStop. 146 Symtab->forEachSymbol([&](Symbol *Sym) { 147 StringRef S = Sym->getName(); 148 for (StringRef Prefix : {"__start_", "__stop_"}) 149 if (S.startswith(Prefix)) 150 UsedStartStop.insert(S.substr(Prefix.size())); 151 }); 152 } 153 154 BitcodeCompiler::~BitcodeCompiler() = default; 155 156 void BitcodeCompiler::add(BitcodeFile &F) { 157 lto::InputFile &Obj = *F.Obj; 158 bool IsExec = !Config->Shared && !Config->Relocatable; 159 160 if (Config->ThinLTOIndexOnly) 161 ThinIndices.insert(Obj.getName()); 162 163 ArrayRef<Symbol *> Syms = F.getSymbols(); 164 ArrayRef<lto::InputFile::Symbol> ObjSyms = Obj.symbols(); 165 std::vector<lto::SymbolResolution> Resols(Syms.size()); 166 167 // Provide a resolution to the LTO API for each symbol. 168 for (size_t I = 0, E = Syms.size(); I != E; ++I) { 169 Symbol *Sym = Syms[I]; 170 const lto::InputFile::Symbol &ObjSym = ObjSyms[I]; 171 lto::SymbolResolution &R = Resols[I]; 172 173 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile 174 // reports two symbols for module ASM defined. Without this check, lld 175 // flags an undefined in IR with a definition in ASM as prevailing. 176 // Once IRObjectFile is fixed to report only one symbol this hack can 177 // be removed. 178 R.Prevailing = !ObjSym.isUndefined() && Sym->File == &F; 179 180 // We ask LTO to preserve following global symbols: 181 // 1) All symbols when doing relocatable link, so that them can be used 182 // for doing final link. 183 // 2) Symbols that are used in regular objects. 184 // 3) C named sections if we have corresponding __start_/__stop_ symbol. 185 // 4) Symbols that are defined in bitcode files and used for dynamic linking. 186 R.VisibleToRegularObj = Config->Relocatable || Sym->IsUsedInRegularObj || 187 (R.Prevailing && Sym->includeInDynsym()) || 188 UsedStartStop.count(ObjSym.getSectionName()); 189 const auto *DR = dyn_cast<Defined>(Sym); 190 R.FinalDefinitionInLinkageUnit = 191 (IsExec || Sym->Visibility != STV_DEFAULT) && DR && 192 // Skip absolute symbols from ELF objects, otherwise PC-rel relocations 193 // will be generated by for them, triggering linker errors. 194 // Symbol section is always null for bitcode symbols, hence the check 195 // for isElf(). Skip linker script defined symbols as well: they have 196 // no File defined. 197 !(DR->Section == nullptr && (!Sym->File || Sym->File->isElf())); 198 199 if (R.Prevailing) 200 Sym->replace(Undefined{nullptr, Sym->getName(), STB_GLOBAL, STV_DEFAULT, 201 Sym->Type}); 202 203 // We tell LTO to not apply interprocedural optimization for wrapped 204 // (with --wrap) symbols because otherwise LTO would inline them while 205 // their values are still not final. 206 R.LinkerRedefined = !Sym->CanInline; 207 } 208 checkError(LTOObj->add(std::move(F.Obj), Resols)); 209 } 210 211 // If LazyObjFile has not been added to link, emit empty index files. 212 // This is needed because this is what GNU gold plugin does and we have a 213 // distributed build system that depends on that behavior. 214 static void thinLTOCreateEmptyIndexFiles() { 215 for (LazyObjFile *F : LazyObjFiles) { 216 if (!isBitcode(F->MB)) 217 continue; 218 std::string Path = replaceThinLTOSuffix(getThinLTOOutputFile(F->getName())); 219 std::unique_ptr<raw_fd_ostream> OS = openFile(Path + ".thinlto.bc"); 220 if (!OS) 221 continue; 222 223 ModuleSummaryIndex M(/*HaveGVs*/ false); 224 M.setSkipModuleByDistributedBackend(); 225 WriteIndexToFile(M, *OS); 226 if (Config->ThinLTOEmitImportsFiles) 227 openFile(Path + ".imports"); 228 } 229 } 230 231 // Merge all the bitcode files we have seen, codegen the result 232 // and return the resulting ObjectFile(s). 233 std::vector<InputFile *> BitcodeCompiler::compile() { 234 unsigned MaxTasks = LTOObj->getMaxTasks(); 235 Buf.resize(MaxTasks); 236 Files.resize(MaxTasks); 237 238 // The --thinlto-cache-dir option specifies the path to a directory in which 239 // to cache native object files for ThinLTO incremental builds. If a path was 240 // specified, configure LTO to use it as the cache directory. 241 lto::NativeObjectCache Cache; 242 if (!Config->ThinLTOCacheDir.empty()) 243 Cache = check( 244 lto::localCache(Config->ThinLTOCacheDir, 245 [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) { 246 Files[Task] = std::move(MB); 247 })); 248 249 if (!BitcodeFiles.empty()) 250 checkError(LTOObj->run( 251 [&](size_t Task) { 252 return llvm::make_unique<lto::NativeObjectStream>( 253 llvm::make_unique<raw_svector_ostream>(Buf[Task])); 254 }, 255 Cache)); 256 257 // Emit empty index files for non-indexed files 258 for (StringRef S : ThinIndices) { 259 std::string Path = getThinLTOOutputFile(S); 260 openFile(Path + ".thinlto.bc"); 261 if (Config->ThinLTOEmitImportsFiles) 262 openFile(Path + ".imports"); 263 } 264 265 if (Config->ThinLTOIndexOnly) { 266 thinLTOCreateEmptyIndexFiles(); 267 268 if (!Config->LTOObjPath.empty()) 269 saveBuffer(Buf[0], Config->LTOObjPath); 270 271 // ThinLTO with index only option is required to generate only the index 272 // files. After that, we exit from linker and ThinLTO backend runs in a 273 // distributed environment. 274 if (IndexFile) 275 IndexFile->close(); 276 return {}; 277 } 278 279 if (!Config->ThinLTOCacheDir.empty()) 280 pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy); 281 282 if (!Config->LTOObjPath.empty()) { 283 saveBuffer(Buf[0], Config->LTOObjPath); 284 for (unsigned I = 1; I != MaxTasks; ++I) 285 saveBuffer(Buf[I], Config->LTOObjPath + Twine(I)); 286 } 287 288 if (Config->SaveTemps) { 289 saveBuffer(Buf[0], Config->OutputFile + ".lto.o"); 290 for (unsigned I = 1; I != MaxTasks; ++I) 291 saveBuffer(Buf[I], Config->OutputFile + Twine(I) + ".lto.o"); 292 } 293 294 std::vector<InputFile *> Ret; 295 for (unsigned I = 0; I != MaxTasks; ++I) 296 if (!Buf[I].empty()) 297 Ret.push_back(createObjectFile(MemoryBufferRef(Buf[I], "lto.tmp"))); 298 299 for (std::unique_ptr<MemoryBuffer> &File : Files) 300 if (File) 301 Ret.push_back(createObjectFile(*File)); 302 return Ret; 303 } 304