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