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 "SymbolTable.h" 13 #include "Symbols.h" 14 #include "lld/Common/Args.h" 15 #include "lld/Common/ErrorHandler.h" 16 #include "lld/Common/Strings.h" 17 #include "lld/Common/TargetOptionsCommandFlags.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/Bitcode/BitcodeWriter.h" 23 #include "llvm/LTO/Config.h" 24 #include "llvm/LTO/LTO.h" 25 #include "llvm/Support/Caching.h" 26 #include "llvm/Support/CodeGen.h" 27 #include "llvm/Support/Error.h" 28 #include "llvm/Support/FileSystem.h" 29 #include "llvm/Support/MemoryBuffer.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 using namespace lld; 41 using namespace lld::elf; 42 43 // Creates an empty file to store a list of object files for final 44 // linking of distributed ThinLTO. 45 static std::unique_ptr<raw_fd_ostream> openFile(StringRef file) { 46 std::error_code ec; 47 auto ret = 48 std::make_unique<raw_fd_ostream>(file, ec, sys::fs::OpenFlags::OF_None); 49 if (ec) { 50 error("cannot open " + file + ": " + ec.message()); 51 return nullptr; 52 } 53 return ret; 54 } 55 56 // The merged bitcode after LTO is large. Try opening a file stream that 57 // supports reading, seeking and writing. Such a file allows BitcodeWriter to 58 // flush buffered data to reduce memory consumption. If this fails, open a file 59 // stream that supports only write. 60 static std::unique_ptr<raw_fd_ostream> openLTOOutputFile(StringRef file) { 61 std::error_code ec; 62 std::unique_ptr<raw_fd_ostream> fs = 63 std::make_unique<raw_fd_stream>(file, ec); 64 if (!ec) 65 return fs; 66 return openFile(file); 67 } 68 69 static std::string getThinLTOOutputFile(StringRef modulePath) { 70 return lto::getThinLTOOutputFile( 71 std::string(modulePath), std::string(config->thinLTOPrefixReplace.first), 72 std::string(config->thinLTOPrefixReplace.second)); 73 } 74 75 static lto::Config createConfig() { 76 lto::Config c; 77 78 // LLD supports the new relocations and address-significance tables. 79 c.Options = initTargetOptionsFromCodeGenFlags(); 80 c.Options.RelaxELFRelocations = true; 81 c.Options.EmitAddrsig = true; 82 83 // Always emit a section per function/datum with LTO. 84 c.Options.FunctionSections = true; 85 c.Options.DataSections = true; 86 87 // Check if basic block sections must be used. 88 // Allowed values for --lto-basic-block-sections are "all", "labels", 89 // "<file name specifying basic block ids>", or none. This is the equivalent 90 // of -fbasic-block-sections= flag in clang. 91 if (!config->ltoBasicBlockSections.empty()) { 92 if (config->ltoBasicBlockSections == "all") { 93 c.Options.BBSections = BasicBlockSection::All; 94 } else if (config->ltoBasicBlockSections == "labels") { 95 c.Options.BBSections = BasicBlockSection::Labels; 96 } else if (config->ltoBasicBlockSections == "none") { 97 c.Options.BBSections = BasicBlockSection::None; 98 } else { 99 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = 100 MemoryBuffer::getFile(config->ltoBasicBlockSections.str()); 101 if (!MBOrErr) { 102 error("cannot open " + config->ltoBasicBlockSections + ":" + 103 MBOrErr.getError().message()); 104 } else { 105 c.Options.BBSectionsFuncListBuf = std::move(*MBOrErr); 106 } 107 c.Options.BBSections = BasicBlockSection::List; 108 } 109 } 110 111 c.Options.UniqueBasicBlockSectionNames = 112 config->ltoUniqueBasicBlockSectionNames; 113 114 if (auto relocModel = getRelocModelFromCMModel()) 115 c.RelocModel = *relocModel; 116 else if (config->relocatable) 117 c.RelocModel = None; 118 else if (config->isPic) 119 c.RelocModel = Reloc::PIC_; 120 else 121 c.RelocModel = Reloc::Static; 122 123 c.CodeModel = getCodeModelFromCMModel(); 124 c.DisableVerify = config->disableVerify; 125 c.DiagHandler = diagnosticHandler; 126 c.OptLevel = config->ltoo; 127 c.CPU = getCPUStr(); 128 c.MAttrs = getMAttrs(); 129 c.CGOptLevel = args::getCGOptLevel(config->ltoo); 130 131 c.PTO.LoopVectorization = c.OptLevel > 1; 132 c.PTO.SLPVectorization = c.OptLevel > 1; 133 134 // Set up a custom pipeline if we've been asked to. 135 c.OptPipeline = std::string(config->ltoNewPmPasses); 136 c.AAPipeline = std::string(config->ltoAAPipeline); 137 138 // Set up optimization remarks if we've been asked to. 139 c.RemarksFilename = std::string(config->optRemarksFilename); 140 c.RemarksPasses = std::string(config->optRemarksPasses); 141 c.RemarksWithHotness = config->optRemarksWithHotness; 142 c.RemarksHotnessThreshold = config->optRemarksHotnessThreshold; 143 c.RemarksFormat = std::string(config->optRemarksFormat); 144 145 c.SampleProfile = std::string(config->ltoSampleProfile); 146 c.UseNewPM = config->ltoNewPassManager; 147 c.DebugPassManager = config->ltoDebugPassManager; 148 c.DwoDir = std::string(config->dwoDir); 149 150 c.HasWholeProgramVisibility = config->ltoWholeProgramVisibility; 151 c.AlwaysEmitRegularLTOObj = !config->ltoObjPath.empty(); 152 153 for (const llvm::StringRef &name : config->thinLTOModulesToCompile) 154 c.ThinLTOModulesToCompile.emplace_back(name); 155 156 c.TimeTraceEnabled = config->timeTraceEnabled; 157 c.TimeTraceGranularity = config->timeTraceGranularity; 158 159 c.CSIRProfile = std::string(config->ltoCSProfileFile); 160 c.RunCSIRInstr = config->ltoCSProfileGenerate; 161 c.PGOWarnMismatch = config->ltoPGOWarnMismatch; 162 163 if (config->emitLLVM) { 164 c.PostInternalizeModuleHook = [](size_t task, const Module &m) { 165 if (std::unique_ptr<raw_fd_ostream> os = 166 openLTOOutputFile(config->outputFile)) 167 WriteBitcodeToFile(m, *os, false); 168 return false; 169 }; 170 } 171 172 if (config->ltoEmitAsm) 173 c.CGFileType = CGFT_AssemblyFile; 174 175 if (config->saveTemps) 176 checkError(c.addSaveTemps(config->outputFile.str() + ".", 177 /*UseInputModulePath*/ true)); 178 return c; 179 } 180 181 BitcodeCompiler::BitcodeCompiler() { 182 // Initialize indexFile. 183 if (!config->thinLTOIndexOnlyArg.empty()) 184 indexFile = openFile(config->thinLTOIndexOnlyArg); 185 186 // Initialize ltoObj. 187 lto::ThinBackend backend; 188 if (config->thinLTOIndexOnly) { 189 auto onIndexWrite = [&](StringRef s) { thinIndices.erase(s); }; 190 backend = lto::createWriteIndexesThinBackend( 191 std::string(config->thinLTOPrefixReplace.first), 192 std::string(config->thinLTOPrefixReplace.second), 193 config->thinLTOEmitImportsFiles, indexFile.get(), onIndexWrite); 194 } else { 195 backend = lto::createInProcessThinBackend( 196 llvm::heavyweight_hardware_concurrency(config->thinLTOJobs)); 197 } 198 199 ltoObj = std::make_unique<lto::LTO>(createConfig(), backend, 200 config->ltoPartitions); 201 202 // Initialize usedStartStop. 203 if (bitcodeFiles.empty()) 204 return; 205 for (Symbol *sym : symtab->symbols()) { 206 if (sym->isPlaceholder()) 207 continue; 208 StringRef s = sym->getName(); 209 for (StringRef prefix : {"__start_", "__stop_"}) 210 if (s.startswith(prefix)) 211 usedStartStop.insert(s.substr(prefix.size())); 212 } 213 } 214 215 BitcodeCompiler::~BitcodeCompiler() = default; 216 217 void BitcodeCompiler::add(BitcodeFile &f) { 218 lto::InputFile &obj = *f.obj; 219 bool isExec = !config->shared && !config->relocatable; 220 221 if (config->thinLTOIndexOnly) 222 thinIndices.insert(obj.getName()); 223 224 ArrayRef<Symbol *> syms = f.getSymbols(); 225 ArrayRef<lto::InputFile::Symbol> objSyms = obj.symbols(); 226 std::vector<lto::SymbolResolution> resols(syms.size()); 227 228 // Provide a resolution to the LTO API for each symbol. 229 for (size_t i = 0, e = syms.size(); i != e; ++i) { 230 Symbol *sym = syms[i]; 231 const lto::InputFile::Symbol &objSym = objSyms[i]; 232 lto::SymbolResolution &r = resols[i]; 233 234 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile 235 // reports two symbols for module ASM defined. Without this check, lld 236 // flags an undefined in IR with a definition in ASM as prevailing. 237 // Once IRObjectFile is fixed to report only one symbol this hack can 238 // be removed. 239 r.Prevailing = !objSym.isUndefined() && sym->file == &f; 240 241 // We ask LTO to preserve following global symbols: 242 // 1) All symbols when doing relocatable link, so that them can be used 243 // for doing final link. 244 // 2) Symbols that are used in regular objects. 245 // 3) C named sections if we have corresponding __start_/__stop_ symbol. 246 // 4) Symbols that are defined in bitcode files and used for dynamic linking. 247 r.VisibleToRegularObj = config->relocatable || sym->isUsedInRegularObj || 248 (r.Prevailing && sym->includeInDynsym()) || 249 usedStartStop.count(objSym.getSectionName()); 250 // Identify symbols exported dynamically, and that therefore could be 251 // referenced by a shared library not visible to the linker. 252 r.ExportDynamic = sym->computeBinding() != STB_LOCAL && 253 (config->shared || config->exportDynamic || 254 sym->exportDynamic || sym->inDynamicList); 255 const auto *dr = dyn_cast<Defined>(sym); 256 r.FinalDefinitionInLinkageUnit = 257 (isExec || sym->visibility != STV_DEFAULT) && dr && 258 // Skip absolute symbols from ELF objects, otherwise PC-rel relocations 259 // will be generated by for them, triggering linker errors. 260 // Symbol section is always null for bitcode symbols, hence the check 261 // for isElf(). Skip linker script defined symbols as well: they have 262 // no File defined. 263 !(dr->section == nullptr && (!sym->file || sym->file->isElf())); 264 265 if (r.Prevailing) 266 sym->replace( 267 Undefined{nullptr, StringRef(), STB_GLOBAL, STV_DEFAULT, sym->type}); 268 269 // We tell LTO to not apply interprocedural optimization for wrapped 270 // (with --wrap) symbols because otherwise LTO would inline them while 271 // their values are still not final. 272 r.LinkerRedefined = sym->scriptDefined; 273 } 274 checkError(ltoObj->add(std::move(f.obj), resols)); 275 } 276 277 // If LazyObjFile has not been added to link, emit empty index files. 278 // This is needed because this is what GNU gold plugin does and we have a 279 // distributed build system that depends on that behavior. 280 static void thinLTOCreateEmptyIndexFiles() { 281 for (BitcodeFile *f : lazyBitcodeFiles) { 282 if (!f->lazy) 283 continue; 284 std::string path = replaceThinLTOSuffix(getThinLTOOutputFile(f->getName())); 285 std::unique_ptr<raw_fd_ostream> os = openFile(path + ".thinlto.bc"); 286 if (!os) 287 continue; 288 289 ModuleSummaryIndex m(/*HaveGVs*/ false); 290 m.setSkipModuleByDistributedBackend(); 291 writeIndexToFile(m, *os); 292 if (config->thinLTOEmitImportsFiles) 293 openFile(path + ".imports"); 294 } 295 } 296 297 // Merge all the bitcode files we have seen, codegen the result 298 // and return the resulting ObjectFile(s). 299 std::vector<InputFile *> BitcodeCompiler::compile() { 300 unsigned maxTasks = ltoObj->getMaxTasks(); 301 buf.resize(maxTasks); 302 files.resize(maxTasks); 303 304 // The --thinlto-cache-dir option specifies the path to a directory in which 305 // to cache native object files for ThinLTO incremental builds. If a path was 306 // specified, configure LTO to use it as the cache directory. 307 FileCache cache; 308 if (!config->thinLTOCacheDir.empty()) 309 cache = 310 check(localCache("ThinLTO", "Thin", config->thinLTOCacheDir, 311 [&](size_t task, std::unique_ptr<MemoryBuffer> mb) { 312 files[task] = std::move(mb); 313 })); 314 315 if (!bitcodeFiles.empty()) 316 checkError(ltoObj->run( 317 [&](size_t task) { 318 return std::make_unique<CachedFileStream>( 319 std::make_unique<raw_svector_ostream>(buf[task])); 320 }, 321 cache)); 322 323 // Emit empty index files for non-indexed files but not in single-module mode. 324 if (config->thinLTOModulesToCompile.empty()) { 325 for (StringRef s : thinIndices) { 326 std::string path = getThinLTOOutputFile(s); 327 openFile(path + ".thinlto.bc"); 328 if (config->thinLTOEmitImportsFiles) 329 openFile(path + ".imports"); 330 } 331 } 332 333 if (config->thinLTOIndexOnly) { 334 thinLTOCreateEmptyIndexFiles(); 335 336 if (!config->ltoObjPath.empty()) 337 saveBuffer(buf[0], config->ltoObjPath); 338 339 // ThinLTO with index only option is required to generate only the index 340 // files. After that, we exit from linker and ThinLTO backend runs in a 341 // distributed environment. 342 if (indexFile) 343 indexFile->close(); 344 return {}; 345 } 346 347 if (!config->thinLTOCacheDir.empty()) 348 pruneCache(config->thinLTOCacheDir, config->thinLTOCachePolicy); 349 350 if (!config->ltoObjPath.empty()) { 351 saveBuffer(buf[0], config->ltoObjPath); 352 for (unsigned i = 1; i != maxTasks; ++i) 353 saveBuffer(buf[i], config->ltoObjPath + Twine(i)); 354 } 355 356 if (config->saveTemps) { 357 if (!buf[0].empty()) 358 saveBuffer(buf[0], config->outputFile + ".lto.o"); 359 for (unsigned i = 1; i != maxTasks; ++i) 360 saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.o"); 361 } 362 363 if (config->ltoEmitAsm) { 364 saveBuffer(buf[0], config->outputFile); 365 for (unsigned i = 1; i != maxTasks; ++i) 366 saveBuffer(buf[i], config->outputFile + Twine(i)); 367 return {}; 368 } 369 370 std::vector<InputFile *> ret; 371 for (unsigned i = 0; i != maxTasks; ++i) 372 if (!buf[i].empty()) 373 ret.push_back(createObjectFile(MemoryBufferRef(buf[i], "lto.tmp"))); 374 375 for (std::unique_ptr<MemoryBuffer> &file : files) 376 if (file) 377 ret.push_back(createObjectFile(*file)); 378 return ret; 379 } 380