xref: /llvm-project-15.0.7/lld/ELF/LTO.cpp (revision 9dfbccf0)
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   // Set up output file to emit statistics.
146   c.StatsFile = std::string(config->optStatsFilename);
147 
148   c.SampleProfile = std::string(config->ltoSampleProfile);
149   for (StringRef pluginFn : config->passPlugins)
150     c.PassPlugins.push_back(std::string(pluginFn));
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   c.PGOWarnMismatch = config->ltoPGOWarnMismatch;
166 
167   if (config->emitLLVM) {
168     c.PostInternalizeModuleHook = [](size_t task, const Module &m) {
169       if (std::unique_ptr<raw_fd_ostream> os =
170               openLTOOutputFile(config->outputFile))
171         WriteBitcodeToFile(m, *os, false);
172       return false;
173     };
174   }
175 
176   if (config->ltoEmitAsm)
177     c.CGFileType = CGFT_AssemblyFile;
178 
179   if (config->saveTemps)
180     checkError(c.addSaveTemps(config->outputFile.str() + ".",
181                               /*UseInputModulePath*/ true));
182   return c;
183 }
184 
185 BitcodeCompiler::BitcodeCompiler() {
186   // Initialize indexFile.
187   if (!config->thinLTOIndexOnlyArg.empty())
188     indexFile = openFile(config->thinLTOIndexOnlyArg);
189 
190   // Initialize ltoObj.
191   lto::ThinBackend backend;
192   if (config->thinLTOIndexOnly) {
193     auto onIndexWrite = [&](StringRef s) { thinIndices.erase(s); };
194     backend = lto::createWriteIndexesThinBackend(
195         std::string(config->thinLTOPrefixReplace.first),
196         std::string(config->thinLTOPrefixReplace.second),
197         config->thinLTOEmitImportsFiles, indexFile.get(), onIndexWrite);
198   } else {
199     backend = lto::createInProcessThinBackend(
200         llvm::heavyweight_hardware_concurrency(config->thinLTOJobs));
201   }
202 
203   ltoObj = std::make_unique<lto::LTO>(createConfig(), backend,
204                                        config->ltoPartitions);
205 
206   // Initialize usedStartStop.
207   if (bitcodeFiles.empty())
208     return;
209   for (Symbol *sym : symtab->symbols()) {
210     if (sym->isPlaceholder())
211       continue;
212     StringRef s = sym->getName();
213     for (StringRef prefix : {"__start_", "__stop_"})
214       if (s.startswith(prefix))
215         usedStartStop.insert(s.substr(prefix.size()));
216   }
217 }
218 
219 BitcodeCompiler::~BitcodeCompiler() = default;
220 
221 void BitcodeCompiler::add(BitcodeFile &f) {
222   lto::InputFile &obj = *f.obj;
223   bool isExec = !config->shared && !config->relocatable;
224 
225   if (config->thinLTOIndexOnly)
226     thinIndices.insert(obj.getName());
227 
228   ArrayRef<Symbol *> syms = f.getSymbols();
229   ArrayRef<lto::InputFile::Symbol> objSyms = obj.symbols();
230   std::vector<lto::SymbolResolution> resols(syms.size());
231 
232   // Provide a resolution to the LTO API for each symbol.
233   for (size_t i = 0, e = syms.size(); i != e; ++i) {
234     Symbol *sym = syms[i];
235     const lto::InputFile::Symbol &objSym = objSyms[i];
236     lto::SymbolResolution &r = resols[i];
237 
238     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
239     // reports two symbols for module ASM defined. Without this check, lld
240     // flags an undefined in IR with a definition in ASM as prevailing.
241     // Once IRObjectFile is fixed to report only one symbol this hack can
242     // be removed.
243     r.Prevailing = !objSym.isUndefined() && sym->file == &f;
244 
245     // We ask LTO to preserve following global symbols:
246     // 1) All symbols when doing relocatable link, so that them can be used
247     //    for doing final link.
248     // 2) Symbols that are used in regular objects.
249     // 3) C named sections if we have corresponding __start_/__stop_ symbol.
250     // 4) Symbols that are defined in bitcode files and used for dynamic
251     //    linking.
252     // 5) Symbols that will be referenced after linker wrapping is performed.
253     r.VisibleToRegularObj = config->relocatable || sym->isUsedInRegularObj ||
254                             sym->referencedAfterWrap ||
255                             (r.Prevailing && sym->includeInDynsym()) ||
256                             usedStartStop.count(objSym.getSectionName());
257     // Identify symbols exported dynamically, and that therefore could be
258     // referenced by a shared library not visible to the linker.
259     r.ExportDynamic =
260         sym->computeBinding() != STB_LOCAL &&
261         (config->exportDynamic || sym->exportDynamic || sym->inDynamicList);
262     const auto *dr = dyn_cast<Defined>(sym);
263     r.FinalDefinitionInLinkageUnit =
264         (isExec || sym->visibility != STV_DEFAULT) && dr &&
265         // Skip absolute symbols from ELF objects, otherwise PC-rel relocations
266         // will be generated by for them, triggering linker errors.
267         // Symbol section is always null for bitcode symbols, hence the check
268         // for isElf(). Skip linker script defined symbols as well: they have
269         // no File defined.
270         !(dr->section == nullptr && (!sym->file || sym->file->isElf()));
271 
272     if (r.Prevailing)
273       sym->replace(
274           Undefined{nullptr, StringRef(), STB_GLOBAL, STV_DEFAULT, sym->type});
275 
276     // We tell LTO to not apply interprocedural optimization for wrapped
277     // (with --wrap) symbols because otherwise LTO would inline them while
278     // their values are still not final.
279     r.LinkerRedefined = sym->scriptDefined;
280   }
281   checkError(ltoObj->add(std::move(f.obj), resols));
282 }
283 
284 // If LazyObjFile has not been added to link, emit empty index files.
285 // This is needed because this is what GNU gold plugin does and we have a
286 // distributed build system that depends on that behavior.
287 static void thinLTOCreateEmptyIndexFiles() {
288   for (BitcodeFile *f : lazyBitcodeFiles) {
289     if (!f->lazy)
290       continue;
291     std::string path = replaceThinLTOSuffix(getThinLTOOutputFile(f->getName()));
292     std::unique_ptr<raw_fd_ostream> os = openFile(path + ".thinlto.bc");
293     if (!os)
294       continue;
295 
296     ModuleSummaryIndex m(/*HaveGVs*/ false);
297     m.setSkipModuleByDistributedBackend();
298     writeIndexToFile(m, *os);
299     if (config->thinLTOEmitImportsFiles)
300       openFile(path + ".imports");
301   }
302 }
303 
304 // Merge all the bitcode files we have seen, codegen the result
305 // and return the resulting ObjectFile(s).
306 std::vector<InputFile *> BitcodeCompiler::compile() {
307   unsigned maxTasks = ltoObj->getMaxTasks();
308   buf.resize(maxTasks);
309   files.resize(maxTasks);
310 
311   // The --thinlto-cache-dir option specifies the path to a directory in which
312   // to cache native object files for ThinLTO incremental builds. If a path was
313   // specified, configure LTO to use it as the cache directory.
314   FileCache cache;
315   if (!config->thinLTOCacheDir.empty())
316     cache =
317         check(localCache("ThinLTO", "Thin", config->thinLTOCacheDir,
318                          [&](size_t task, std::unique_ptr<MemoryBuffer> mb) {
319                            files[task] = std::move(mb);
320                          }));
321 
322   if (!bitcodeFiles.empty())
323     checkError(ltoObj->run(
324         [&](size_t task) {
325           return std::make_unique<CachedFileStream>(
326               std::make_unique<raw_svector_ostream>(buf[task]));
327         },
328         cache));
329 
330   // Emit empty index files for non-indexed files but not in single-module mode.
331   if (config->thinLTOModulesToCompile.empty()) {
332     for (StringRef s : thinIndices) {
333       std::string path = getThinLTOOutputFile(s);
334       openFile(path + ".thinlto.bc");
335       if (config->thinLTOEmitImportsFiles)
336         openFile(path + ".imports");
337     }
338   }
339 
340   if (config->thinLTOIndexOnly) {
341     thinLTOCreateEmptyIndexFiles();
342 
343     if (!config->ltoObjPath.empty())
344       saveBuffer(buf[0], config->ltoObjPath);
345 
346     // ThinLTO with index only option is required to generate only the index
347     // files. After that, we exit from linker and ThinLTO backend runs in a
348     // distributed environment.
349     if (indexFile)
350       indexFile->close();
351     return {};
352   }
353 
354   if (!config->thinLTOCacheDir.empty())
355     pruneCache(config->thinLTOCacheDir, config->thinLTOCachePolicy);
356 
357   if (!config->ltoObjPath.empty()) {
358     saveBuffer(buf[0], config->ltoObjPath);
359     for (unsigned i = 1; i != maxTasks; ++i)
360       saveBuffer(buf[i], config->ltoObjPath + Twine(i));
361   }
362 
363   if (config->saveTemps) {
364     if (!buf[0].empty())
365       saveBuffer(buf[0], config->outputFile + ".lto.o");
366     for (unsigned i = 1; i != maxTasks; ++i)
367       saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.o");
368   }
369 
370   if (config->ltoEmitAsm) {
371     saveBuffer(buf[0], config->outputFile);
372     for (unsigned i = 1; i != maxTasks; ++i)
373       saveBuffer(buf[i], config->outputFile + Twine(i));
374     return {};
375   }
376 
377   std::vector<InputFile *> ret;
378   for (unsigned i = 0; i != maxTasks; ++i)
379     if (!buf[i].empty())
380       ret.push_back(createObjectFile(MemoryBufferRef(buf[i], "lto.tmp")));
381 
382   for (std::unique_ptr<MemoryBuffer> &file : files)
383     if (file)
384       ret.push_back(createObjectFile(*file));
385   return ret;
386 }
387