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/ErrorHandler.h"
15#include "lld/Common/Filesystem.h"
16#include "lld/Common/Strings.h"
17#include "lld/Common/TargetOptionsCommandFlags.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/Twine.h"
20#include "llvm/BinaryFormat/ELF.h"
21#include "llvm/Bitcode/BitcodeWriter.h"
22#include "llvm/DTLTO/DTLTO.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/MemoryBuffer.h"
28#include "llvm/Support/Path.h"
29#include <cstddef>
30#include <memory>
31#include <string>
32#include <system_error>
33#include <vector>
34
35using namespace llvm;
36using namespace llvm::object;
37using namespace llvm::ELF;
38using namespace lld;
39using namespace lld::elf;
40
41static AddBufferFn
42createAddBufferFn(std::vector<std::unique_ptr<MemoryBuffer>> &files,
43 SmallVectorImpl<std::string> &filenames) {
44 return [&files, &filenames](unsigned task, const Twine &moduleName,
45 std::unique_ptr<MemoryBuffer> mb) {
46 files[task] = std::move(mb);
47 filenames[task] = moduleName.str();
48 };
49}
50
51static std::string getThinLTOOutputFile(Ctx &ctx, StringRef modulePath) {
52 return lto::getThinLTOOutputFile(Path: modulePath, OldPrefix: ctx.arg.thinLTOPrefixReplaceOld,
53 NewPrefix: ctx.arg.thinLTOPrefixReplaceNew);
54}
55
56static lto::Config createConfig(Ctx &ctx) {
57 lto::Config c;
58 c.LibraryOptions = &ctx.arg.libraryOptions;
59 c.PTO = PipelineTuningOptions(c.LibraryOptions);
60
61 // LLD supports the new relocations and address-significance tables.
62 c.Options = initTargetOptionsFromCodeGenFlags();
63 c.Options.EmitAddrsig = true;
64 for (StringRef C : ctx.arg.mllvmOpts)
65 c.MllvmArgs.emplace_back(args: C.str());
66
67 // Always emit a section per function/datum with LTO.
68 c.Options.FunctionSections = true;
69 c.Options.DataSections = true;
70
71 // Check if basic block sections must be used.
72 // Allowed values for --lto-basic-block-sections are "all",
73 // "<file name specifying basic block ids>", or none. This is the equivalent
74 // of -fbasic-block-sections= flag in clang.
75 if (!ctx.arg.ltoBasicBlockSections.empty()) {
76 if (ctx.arg.ltoBasicBlockSections == "all") {
77 c.Options.BBSections = BasicBlockSection::All;
78 } else if (ctx.arg.ltoBasicBlockSections == "labels") {
79 c.Options.BBAddrMap = true;
80 Warn(ctx)
81 << "'--lto-basic-block-sections=labels' is deprecated; Please use "
82 "'--lto-basic-block-address-map' instead";
83 } else if (ctx.arg.ltoBasicBlockSections == "none") {
84 c.Options.BBSections = BasicBlockSection::None;
85 } else {
86 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
87 MemoryBuffer::getFile(Filename: ctx.arg.ltoBasicBlockSections.str());
88 if (!MBOrErr) {
89 ErrAlways(ctx) << "cannot open " << ctx.arg.ltoBasicBlockSections << ":"
90 << MBOrErr.getError().message();
91 } else {
92 c.Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
93 }
94 c.Options.BBSections = BasicBlockSection::List;
95 }
96 }
97
98 c.Options.BBAddrMap = ctx.arg.ltoBBAddrMap;
99
100 c.Options.UniqueBasicBlockSectionNames =
101 ctx.arg.ltoUniqueBasicBlockSectionNames;
102
103 if (auto relocModel = getRelocModelFromCMModel())
104 c.RelocModel = *relocModel;
105 else if (ctx.arg.relocatable)
106 c.RelocModel = std::nullopt;
107 else if (ctx.arg.isPic)
108 c.RelocModel = Reloc::PIC_;
109 else
110 c.RelocModel = Reloc::Static;
111
112 c.CodeModel = getCodeModelFromCMModel();
113 c.DisableVerify = ctx.arg.disableVerify;
114 c.DiagHandler = diagnosticHandler;
115 c.OptLevel = ctx.arg.ltoo;
116 c.CPU = getCPUStr();
117 c.MAttrs = getMAttrs();
118 c.CGOptLevel = ctx.arg.ltoCgo;
119
120 c.PTO.LoopVectorization = c.OptLevel > 1;
121 c.PTO.SLPVectorization = c.OptLevel > 1;
122
123 // Set up a custom pipeline if we've been asked to.
124 c.OptPipeline = std::string(ctx.arg.ltoNewPmPasses);
125 c.AAPipeline = std::string(ctx.arg.ltoAAPipeline);
126
127 // Set up optimization remarks if we've been asked to.
128 c.RemarksFilename = std::string(ctx.arg.optRemarksFilename);
129 c.RemarksPasses = std::string(ctx.arg.optRemarksPasses);
130 c.RemarksWithHotness = ctx.arg.optRemarksWithHotness;
131 c.RemarksHotnessThreshold = ctx.arg.optRemarksHotnessThreshold;
132 c.RemarksFormat = std::string(ctx.arg.optRemarksFormat);
133
134 // Set up output file to emit statistics.
135 c.StatsFile = std::string(ctx.arg.optStatsFilename);
136
137 c.SampleProfile = std::string(ctx.arg.ltoSampleProfile);
138 for (StringRef pluginFn : ctx.arg.passPlugins)
139 c.PassPluginFilenames.push_back(x: std::string(pluginFn));
140 c.DebugPassManager = ctx.arg.ltoDebugPassManager;
141 c.DwoDir = std::string(ctx.arg.dwoDir);
142
143 c.HasWholeProgramVisibility = ctx.arg.ltoWholeProgramVisibility;
144 c.ValidateAllVtablesHaveTypeInfos =
145 ctx.arg.ltoValidateAllVtablesHaveTypeInfos;
146 c.AllVtablesHaveTypeInfos = ctx.ltoAllVtablesHaveTypeInfos;
147 c.AlwaysEmitRegularLTOObj = !ctx.arg.ltoObjPath.empty();
148 c.KeepSymbolNameCopies = false;
149
150 for (const llvm::StringRef &name : ctx.arg.thinLTOModulesToCompile)
151 c.ThinLTOModulesToCompile.emplace_back(args: name);
152
153 c.TimeTraceEnabled = ctx.arg.timeTraceEnabled;
154 c.TimeTraceGranularity = ctx.arg.timeTraceGranularity;
155
156 c.CSIRProfile = std::string(ctx.arg.ltoCSProfileFile);
157 c.RunCSIRInstr = ctx.arg.ltoCSProfileGenerate;
158 c.PGOWarnMismatch = ctx.arg.ltoPGOWarnMismatch;
159
160 if (ctx.arg.emitLLVM) {
161 c.PreCodeGenModuleHook = [&ctx](size_t task, const Module &m) {
162 if (std::unique_ptr<raw_fd_ostream> os =
163 openLTOOutputFile(file: ctx.arg.outputFile))
164 WriteBitcodeToFile(M: m, Out&: *os, ShouldPreserveUseListOrder: false);
165 return false;
166 };
167 }
168
169 if (ctx.arg.ltoEmitAsm) {
170 c.CGFileType = CodeGenFileType::AssemblyFile;
171 c.Options.MCOptions.AsmVerbose = true;
172 }
173
174 if (!ctx.arg.saveTempsArgs.empty())
175 checkError(eh&: ctx.e, e: c.addSaveTemps(OutputFileName: ctx.arg.outputFile.str() + ".",
176 /*UseInputModulePath*/ true,
177 SaveTempsArgs: ctx.arg.saveTempsArgs));
178 return c;
179}
180
181BitcodeCompiler::BitcodeCompiler(Ctx &ctx) : ctx(ctx) {
182 // Initialize indexFile.
183 if (!ctx.arg.thinLTOIndexOnlyArg.empty())
184 indexFile = openFile(file: ctx.arg.thinLTOIndexOnlyArg);
185
186 // Initialize ltoObj.
187 lto::ThinBackend backend;
188 auto onIndexWrite = [&](StringRef s) { thinIndices.erase(V: s); };
189 if (ctx.arg.thinLTOIndexOnly) {
190 backend = lto::createWriteIndexesThinBackend(
191 Parallelism: llvm::hardware_concurrency(Num: ctx.arg.thinLTOJobs),
192 OldPrefix: std::string(ctx.arg.thinLTOPrefixReplaceOld),
193 NewPrefix: std::string(ctx.arg.thinLTOPrefixReplaceNew),
194 NativeObjectPrefix: std::string(ctx.arg.thinLTOPrefixReplaceNativeObject),
195 ShouldEmitImportsFiles: ctx.arg.thinLTOEmitImportsFiles, LinkedObjectsFile: indexFile.get(), OnWrite: onIndexWrite);
196 } else {
197 backend = lto::createInProcessThinBackend(
198 Parallelism: llvm::heavyweight_hardware_concurrency(Num: ctx.arg.thinLTOJobs),
199 OnWrite: onIndexWrite, ShouldEmitIndexFiles: ctx.arg.thinLTOEmitIndexFiles,
200 ShouldEmitImportsFiles: ctx.arg.thinLTOEmitImportsFiles);
201 }
202
203 constexpr llvm::lto::LTO::LTOKind ltoModes[3] = {
204 llvm::lto::LTO::LTOKind::LTOK_UnifiedThin,
205 llvm::lto::LTO::LTOKind::LTOK_UnifiedRegular,
206 llvm::lto::LTO::LTOKind::LTOK_Default};
207
208 if (ctx.arg.dtltoDistributor.empty())
209 ltoObj = std::make_unique<lto::LTO>(args: createConfig(ctx), args&: backend,
210 args&: ctx.arg.ltoPartitions,
211 args: ltoModes[ctx.arg.ltoKind]);
212 else
213 ltoObj = std::make_unique<lto::DTLTO>(
214 args: createConfig(ctx), args&: ctx.arg.ltoPartitions, args: ltoModes[ctx.arg.ltoKind],
215 args&: onIndexWrite, args&: ctx.arg.thinLTOEmitIndexFiles,
216 args&: ctx.arg.thinLTOEmitImportsFiles, args&: ctx.arg.outputFile,
217 args&: ctx.arg.dtltoDistributor, args&: ctx.arg.dtltoDistributorArgs,
218 args&: ctx.arg.dtltoCompiler, args&: ctx.arg.dtltoCompilerPrependArgs,
219 args&: ctx.arg.dtltoCompilerArgs, args: createAddBufferFn(files, filenames),
220 args: !ctx.arg.saveTempsArgs.empty());
221 // Initialize usedStartStop.
222 if (ctx.bitcodeFiles.empty())
223 return;
224 for (Symbol *sym : ctx.symtab->getSymbols()) {
225 if (sym->isPlaceholder())
226 continue;
227 StringRef s = sym->getName();
228 for (StringRef prefix : {"__start_", "__stop_"})
229 if (s.starts_with(Prefix: prefix))
230 usedStartStop.insert(V: s.substr(Start: prefix.size()));
231 }
232}
233
234BitcodeCompiler::~BitcodeCompiler() = default;
235
236void BitcodeCompiler::waitForLTOCleanup() {
237 if (ltoObj)
238 ltoObj->waitForCleanup();
239}
240
241void BitcodeCompiler::add(BitcodeFile &f) {
242 lto::InputFile &obj = *f.obj;
243 bool isExec = !ctx.arg.shared && !ctx.arg.relocatable;
244
245 if (ctx.arg.thinLTOEmitIndexFiles)
246 thinIndices.insert(V: obj.getName());
247
248 ArrayRef<Symbol *> syms = f.getSymbols();
249 ArrayRef<lto::InputFile::Symbol> objSyms = obj.symbols();
250 std::vector<lto::SymbolResolution> resols(syms.size());
251
252 // Provide a resolution to the LTO API for each symbol.
253 for (size_t i = 0, e = syms.size(); i != e; ++i) {
254 Symbol *sym = syms[i];
255 const lto::InputFile::Symbol &objSym = objSyms[i];
256 lto::SymbolResolution &r = resols[i];
257
258 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
259 // reports two symbols for module ASM defined. Without this check, lld
260 // flags an undefined in IR with a definition in ASM as prevailing.
261 // Once IRObjectFile is fixed to report only one symbol this hack can
262 // be removed.
263 r.Prevailing = !objSym.isUndefined() && sym->file == &f;
264
265 // We ask LTO to preserve following global symbols:
266 // 1) All symbols when doing relocatable link, so that them can be used
267 // for doing final link.
268 // 2) Symbols that are used in regular objects.
269 // 3) C named sections if we have corresponding __start_/__stop_ symbol.
270 // 4) Symbols that are defined in bitcode files and used for dynamic
271 // linking.
272 // 5) Symbols that will be referenced after linker wrapping is performed.
273 r.VisibleToRegularObj = ctx.arg.relocatable || sym->isUsedInRegularObj ||
274 sym->referencedAfterWrap ||
275 (r.Prevailing && sym->isExported) ||
276 usedStartStop.contains(V: objSym.getSectionName());
277 // Identify symbols exported dynamically, and that therefore could be
278 // referenced by a shared library not visible to the linker.
279 r.ExportDynamic = sym->computeBinding(ctx) != STB_LOCAL &&
280 (ctx.arg.exportDynamic || sym->isExported);
281 const auto *dr = dyn_cast<Defined>(Val: sym);
282 r.FinalDefinitionInLinkageUnit =
283 (isExec || sym->visibility() != STV_DEFAULT) && dr &&
284 // Skip absolute symbols from ELF objects, otherwise PC-rel relocations
285 // will be generated by for them, triggering linker errors.
286 // Symbol section is always null for bitcode symbols, hence the check
287 // for isElf(). Skip linker script defined symbols as well: they have
288 // no File defined.
289 !(dr->section == nullptr &&
290 (sym->file->isInternal() || sym->file->isElf()));
291
292 if (r.Prevailing)
293 Undefined(ctx.internalFile, StringRef(), STB_GLOBAL, STV_DEFAULT,
294 sym->type)
295 .overwrite(sym&: *sym);
296
297 // We tell LTO to not apply interprocedural optimization for wrapped
298 // (with --wrap) symbols because otherwise LTO would inline them while
299 // their values are still not final.
300 r.LinkerRedefined = sym->scriptDefined;
301 }
302 checkError(eh&: ctx.e, e: ltoObj->add(Obj: std::move(f.obj), Res: resols));
303}
304
305// If LazyObjFile has not been added to link, emit empty index files.
306// This is needed because this is what GNU gold plugin does and we have a
307// distributed build system that depends on that behavior.
308static void thinLTOCreateEmptyIndexFiles(Ctx &ctx) {
309 DenseSet<StringRef> linkedBitCodeFiles;
310 for (BitcodeFile *f : ctx.bitcodeFiles)
311 linkedBitCodeFiles.insert(V: f->getName());
312
313 for (BitcodeFile *f : ctx.lazyBitcodeFiles) {
314 if (!f->lazy)
315 continue;
316 if (linkedBitCodeFiles.contains(V: f->getName()))
317 continue;
318 std::string path =
319 replaceThinLTOSuffix(ctx, path: getThinLTOOutputFile(ctx, modulePath: f->obj->getName()));
320 std::unique_ptr<raw_fd_ostream> os = openFile(file: path + ".thinlto.bc");
321 if (!os)
322 continue;
323
324 ModuleSummaryIndex m(/*HaveGVs*/ false);
325 m.setSkipModuleByDistributedBackend();
326 writeIndexToFile(Index: m, Out&: *os);
327 if (ctx.arg.thinLTOEmitImportsFiles)
328 openFile(file: path + ".imports");
329 }
330}
331
332// Merge all the bitcode files we have seen, codegen the result
333// and return the resulting ObjectFile(s).
334SmallVector<std::unique_ptr<InputFile>, 0> BitcodeCompiler::compile() {
335 unsigned maxTasks = ltoObj->getMaxTasks();
336 buf.resize(N: maxTasks);
337 files.resize(new_size: maxTasks);
338 filenames.resize(N: maxTasks);
339
340 // The --thinlto-cache-dir option specifies the path to a directory in which
341 // to cache native object files for ThinLTO incremental builds. If a path was
342 // specified, configure LTO to use it as the cache directory.
343 FileCache cache;
344 if (!ctx.arg.thinLTOCacheDir.empty())
345 cache = check(e: localCache(CacheNameRef: "ThinLTO", TempFilePrefixRef: "Thin", CacheDirectoryPathRef: ctx.arg.thinLTOCacheDir,
346 AddBuffer: createAddBufferFn(files, filenames),
347 CacheFileRename: !ctx.arg.dtltoDistributor.empty()));
348
349 if (!ctx.bitcodeFiles.empty())
350 checkError(eh&: ctx.e, e: ltoObj->run(
351 AddStream: [&](size_t task, const Twine &moduleName) {
352 buf[task].first = moduleName.str();
353 return std::make_unique<CachedFileStream>(
354 args: std::make_unique<raw_svector_ostream>(
355 args&: buf[task].second));
356 },
357 Cache: cache));
358
359 // Emit empty index files for non-indexed files but not in single-module mode.
360 if (ctx.arg.thinLTOModulesToCompile.empty()) {
361 for (StringRef s : thinIndices) {
362 std::string path = getThinLTOOutputFile(ctx, modulePath: s);
363 openFile(file: path + ".thinlto.bc");
364 if (ctx.arg.thinLTOEmitImportsFiles)
365 openFile(file: path + ".imports");
366 }
367 }
368
369 if (ctx.arg.thinLTOEmitIndexFiles)
370 thinLTOCreateEmptyIndexFiles(ctx);
371
372 if (ctx.arg.thinLTOIndexOnly) {
373 if (!ctx.arg.ltoObjPath.empty())
374 saveBuffer(buffer: buf[0].second, path: ctx.arg.ltoObjPath);
375
376 // ThinLTO with index only option is required to generate only the index
377 // files. After that, we exit from linker and ThinLTO backend runs in a
378 // distributed environment.
379 if (indexFile)
380 indexFile->close();
381 return {};
382 }
383
384 if (!ctx.arg.thinLTOCacheDir.empty())
385 check(
386 e: pruneCache(Path: ctx.arg.thinLTOCacheDir, Policy: ctx.arg.thinLTOCachePolicy, Files: files));
387
388 bool savePrelink = ctx.arg.saveTempsArgs.contains(V: "prelink");
389 SmallVector<std::unique_ptr<InputFile>, 0> ret;
390 const char *ext = ctx.arg.ltoEmitAsm ? ".s" : ".o";
391 for (unsigned i = 0; i != maxTasks; ++i) {
392 StringRef bitcodeFilePath;
393 StringRef objBuf;
394 if (files[i]) {
395 // When files[i] is not null, it holds a native relocatable file provided
396 // as a MemoryBuffer, for example from the cache or from an external DTLTO
397 // backend compilation. filenames[i] contains the original BitcodeFile's
398 // identifier.
399 objBuf = files[i]->getBuffer();
400 bitcodeFilePath = filenames[i];
401 } else {
402 // Get the native relocatable file after in-process LTO compilation.
403 objBuf = buf[i].second;
404 bitcodeFilePath = buf[i].first;
405 }
406 if (!ctx.arg.ltoObjPath.empty())
407 saveBuffer(buffer: objBuf, path: ctx.arg.ltoObjPath + (i == 0 ? "" : Twine(i)));
408 if (objBuf.empty())
409 continue;
410
411 // If the input bitcode file is path/to/x.o and -o specifies a.out, the
412 // corresponding native relocatable file path will look like:
413 // path/to/a.out.lto.x.o.
414 StringRef ltoObjName;
415 if (bitcodeFilePath == "ld-temp.o") {
416 ltoObjName =
417 ctx.saver.save(S: Twine(ctx.arg.outputFile) + ".lto" +
418 (i == 0 ? Twine("") : Twine('.') + Twine(i)) + ext);
419 } else {
420 StringRef directory = sys::path::parent_path(path: bitcodeFilePath);
421 // For an archive member, which has an identifier like "d/a.a(coll.o at
422 // 8)" (see BitcodeFile::BitcodeFile), use the filename; otherwise, use
423 // the stem (d/a.o => a).
424 StringRef baseName = bitcodeFilePath.ends_with(Suffix: ")")
425 ? sys::path::filename(path: bitcodeFilePath)
426 : sys::path::stem(path: bitcodeFilePath);
427 StringRef outputFileBaseName = sys::path::filename(path: ctx.arg.outputFile);
428 SmallString<256> path;
429 sys::path::append(path, a: directory,
430 b: outputFileBaseName + ".lto." + baseName + ext);
431 sys::path::remove_dots(path, remove_dot_dot: true);
432 ltoObjName = ctx.saver.save(S: path.str());
433 }
434 if (savePrelink || ctx.arg.ltoEmitAsm)
435 saveBuffer(buffer: buf[i].second, path: ltoObjName);
436 if (!ctx.arg.ltoEmitAsm)
437 ret.push_back(Elt: createObjFile(ctx, mb: MemoryBufferRef(objBuf, ltoObjName)));
438 }
439 return ret;
440}
441
442void BitcodeCompiler::setBitcodeLibFuncs(ArrayRef<StringRef> bitcodeLibFuncs) {
443 ltoObj->setBitcodeLibFuncs(bitcodeLibFuncs);
444}
445