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 "COFFLinkerContext.h"
11#include "Config.h"
12#include "InputFiles.h"
13#include "Symbols.h"
14#include "lld/Common/Args.h"
15#include "lld/Common/CommonLinkerContext.h"
16#include "lld/Common/Filesystem.h"
17#include "lld/Common/Strings.h"
18#include "lld/Common/TargetOptionsCommandFlags.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/Twine.h"
22#include "llvm/Bitcode/BitcodeWriter.h"
23#include "llvm/DTLTO/DTLTO.h"
24#include "llvm/IR/DiagnosticPrinter.h"
25#include "llvm/LTO/Config.h"
26#include "llvm/LTO/LTO.h"
27#include "llvm/Support/Caching.h"
28#include "llvm/Support/CodeGen.h"
29#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/TimeProfiler.h"
31#include "llvm/Support/raw_ostream.h"
32#include <cstddef>
33#include <memory>
34#include <string>
35#include <vector>
36
37using namespace llvm;
38using namespace llvm::object;
39using namespace lld;
40using namespace lld::coff;
41
42static AddBufferFn
43createAddBufferFn(std::vector<std::unique_ptr<MemoryBuffer>> &files,
44 std::vector<std::string> &filenames) {
45 return [&files, &filenames](unsigned task, const Twine &moduleName,
46 std::unique_ptr<MemoryBuffer> mb) {
47 files[task] = std::move(mb);
48 filenames[task] = moduleName.str();
49 };
50}
51
52std::string BitcodeCompiler::getThinLTOOutputFile(StringRef path) {
53 return lto::getThinLTOOutputFile(Path: path, OldPrefix: ctx.config.thinLTOPrefixReplaceOld,
54 NewPrefix: ctx.config.thinLTOPrefixReplaceNew);
55}
56
57lto::Config BitcodeCompiler::createConfig() {
58 lto::Config c;
59 c.Options = initTargetOptionsFromCodeGenFlags();
60 c.Options.EmitAddrsig = true;
61 for (StringRef C : ctx.config.mllvmOpts)
62 c.MllvmArgs.emplace_back(args: C.str());
63
64 // Always emit a section per function/datum with LTO. LLVM LTO should get most
65 // of the benefit of linker GC, but there are still opportunities for ICF.
66 c.Options.FunctionSections = true;
67 c.Options.DataSections = true;
68
69 // Use static reloc model on 32-bit x86 because it usually results in more
70 // compact code, and because there are also known code generation bugs when
71 // using the PIC model (see PR34306).
72 if (ctx.config.machine == COFF::IMAGE_FILE_MACHINE_I386)
73 c.RelocModel = Reloc::Static;
74 else
75 c.RelocModel = Reloc::PIC_;
76#ifndef NDEBUG
77 c.DisableVerify = false;
78#else
79 c.DisableVerify = true;
80#endif
81 c.DiagHandler = diagnosticHandler;
82 c.DwoDir = ctx.config.dwoDir.str();
83 c.OptLevel = ctx.config.ltoo;
84 c.CPU = getCPUStr();
85 c.MAttrs = getMAttrs();
86 std::optional<CodeGenOptLevel> optLevelOrNone = CodeGenOpt::getLevel(
87 OL: ctx.config.ltoCgo.value_or(u: args::getCGOptLevel(optLevelLTO: ctx.config.ltoo)));
88 assert(optLevelOrNone && "Invalid optimization level!");
89 c.CGOptLevel = *optLevelOrNone;
90 c.AlwaysEmitRegularLTOObj = !ctx.config.ltoObjPath.empty();
91 c.DebugPassManager = ctx.config.ltoDebugPassManager;
92 c.CSIRProfile = std::string(ctx.config.ltoCSProfileFile);
93 c.RunCSIRInstr = ctx.config.ltoCSProfileGenerate;
94 c.PGOWarnMismatch = ctx.config.ltoPGOWarnMismatch;
95 c.SampleProfile = ctx.config.ltoSampleProfileName;
96 c.TimeTraceEnabled = ctx.config.timeTraceEnabled;
97 c.TimeTraceGranularity = ctx.config.timeTraceGranularity;
98
99 if (ctx.config.emit == EmitKind::LLVM) {
100 c.PreCodeGenModuleHook = [this](size_t task, const Module &m) {
101 if (std::unique_ptr<raw_fd_ostream> os =
102 openLTOOutputFile(file: ctx.config.outputFile))
103 WriteBitcodeToFile(M: m, Out&: *os, ShouldPreserveUseListOrder: false);
104 return false;
105 };
106 } else if (ctx.config.emit == EmitKind::ASM) {
107 c.CGFileType = CodeGenFileType::AssemblyFile;
108 c.Options.MCOptions.AsmVerbose = true;
109 }
110
111 if (!ctx.config.saveTempsArgs.empty())
112 checkError(e: c.addSaveTemps(OutputFileName: std::string(ctx.config.outputFile) + ".",
113 /*UseInputModulePath*/ true,
114 SaveTempsArgs: ctx.config.saveTempsArgs));
115
116 c.PTO.LoopVectorization = c.OptLevel > 1;
117 c.PTO.SLPVectorization = c.OptLevel > 1;
118
119 return c;
120}
121
122BitcodeCompiler::BitcodeCompiler(COFFLinkerContext &c) : ctx(c) {
123 // Initialize indexFile.
124 if (!ctx.config.thinLTOIndexOnlyArg.empty())
125 indexFile = openFile(file: ctx.config.thinLTOIndexOnlyArg);
126
127 // Initialize ltoObj.
128 lto::ThinBackend backend;
129 if (ctx.config.thinLTOIndexOnly) {
130 auto OnIndexWrite = [&](StringRef S) { thinIndices.erase(V: S); };
131 backend = lto::createWriteIndexesThinBackend(
132 Parallelism: llvm::hardware_concurrency(Num: ctx.config.thinLTOJobs),
133 OldPrefix: std::string(ctx.config.thinLTOPrefixReplaceOld),
134 NewPrefix: std::string(ctx.config.thinLTOPrefixReplaceNew),
135 NativeObjectPrefix: std::string(ctx.config.thinLTOPrefixReplaceNativeObject),
136 ShouldEmitImportsFiles: ctx.config.thinLTOEmitImportsFiles, LinkedObjectsFile: indexFile.get(), OnWrite: OnIndexWrite);
137 } else {
138 backend = lto::createInProcessThinBackend(
139 Parallelism: llvm::heavyweight_hardware_concurrency(Num: ctx.config.thinLTOJobs));
140 }
141
142 if (ctx.config.dtltoDistributor.empty())
143 ltoObj = std::make_unique<lto::LTO>(args: createConfig(), args&: backend,
144 args&: ctx.config.ltoPartitions);
145 else
146 ltoObj = std::make_unique<lto::DTLTO>(
147 args: createConfig(), args&: ctx.config.ltoPartitions,
148 args: llvm::lto::LTO::LTOKind::LTOK_Default, args: nullptr,
149 args&: ctx.config.thinLTOEmitImportsFiles, args&: ctx.config.thinLTOIndexOnly,
150 args&: ctx.config.outputFile, args&: ctx.config.dtltoDistributor,
151 args&: ctx.config.dtltoDistributorArgs, args&: ctx.config.dtltoCompiler,
152 args&: ctx.config.dtltoCompilerPrependArgs, args&: ctx.config.dtltoCompilerArgs,
153 args: createAddBufferFn(files, filenames&: file_names),
154 args: !ctx.config.saveTempsArgs.empty());
155}
156
157BitcodeCompiler::~BitcodeCompiler() = default;
158
159static void undefine(Symbol *s) { replaceSymbol<Undefined>(s, arg: s->getName()); }
160
161void BitcodeCompiler::add(BitcodeFile &f) {
162 lto::InputFile &obj = *f.obj;
163 unsigned symNum = 0;
164 std::vector<Symbol *> symBodies = f.getSymbols();
165 std::vector<lto::SymbolResolution> resols(symBodies.size());
166
167 if (ctx.config.thinLTOIndexOnly)
168 thinIndices.insert(V: obj.getName());
169
170 // Provide a resolution to the LTO API for each symbol.
171 for (const lto::InputFile::Symbol &objSym : obj.symbols()) {
172 Symbol *sym = symBodies[symNum];
173 lto::SymbolResolution &r = resols[symNum];
174 ++symNum;
175
176 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
177 // reports two symbols for module ASM defined. Without this check, lld
178 // flags an undefined in IR with a definition in ASM as prevailing.
179 // Once IRObjectFile is fixed to report only one symbol this hack can
180 // be removed.
181 r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f;
182 r.VisibleToRegularObj = sym->isUsedInRegularObj;
183 if (r.Prevailing)
184 undefine(s: sym);
185
186 // We tell LTO to not apply interprocedural optimization for wrapped
187 // (with -wrap) symbols because otherwise LTO would inline them while
188 // their values are still not final.
189 r.LinkerRedefined = !sym->canInline;
190 }
191 checkError(e: ltoObj->add(Obj: std::move(f.obj), Res: resols));
192}
193
194// Merge all the bitcode files we have seen, codegen the result
195// and return the resulting objects.
196std::vector<InputFile *> BitcodeCompiler::compile() {
197 llvm::TimeTraceScope timeScope("Bitcode compile");
198 unsigned maxTasks = ltoObj->getMaxTasks();
199 buf.resize(new_size: maxTasks);
200 files.resize(new_size: maxTasks);
201 file_names.resize(new_size: maxTasks);
202
203 // The /lldltocache option specifies the path to a directory in which to cache
204 // native object files for ThinLTO incremental builds. If a path was
205 // specified, configure LTO to use it as the cache directory.
206 FileCache cache;
207 if (!ctx.config.ltoCache.empty())
208 cache = check(e: localCache(CacheNameRef: "ThinLTO", TempFilePrefixRef: "Thin", CacheDirectoryPathRef: ctx.config.ltoCache,
209 AddBuffer: createAddBufferFn(files, filenames&: file_names)));
210
211 checkError(e: ltoObj->run(
212 AddStream: [&](size_t task, const Twine &moduleName) {
213 buf[task].first = moduleName.str();
214 return std::make_unique<CachedFileStream>(
215 args: std::make_unique<raw_svector_ostream>(args&: buf[task].second));
216 },
217 Cache: cache));
218
219 // Emit empty index files for non-indexed files
220 for (StringRef s : thinIndices) {
221 std::string path = getThinLTOOutputFile(path: s);
222 openFile(file: path + ".thinlto.bc");
223 if (ctx.config.thinLTOEmitImportsFiles)
224 openFile(file: path + ".imports");
225 }
226
227 // ThinLTO with index only option is required to generate only the index
228 // files. After that, we exit from linker and ThinLTO backend runs in a
229 // distributed environment.
230 if (ctx.config.thinLTOIndexOnly) {
231 if (!ctx.config.ltoObjPath.empty())
232 saveBuffer(buffer: buf[0].second, path: ctx.config.ltoObjPath);
233 if (indexFile)
234 indexFile->close();
235 return {};
236 }
237
238 if (!ctx.config.ltoCache.empty())
239 check(e: pruneCache(Path: ctx.config.ltoCache, Policy: ctx.config.ltoCachePolicy, Files: files));
240
241 std::vector<InputFile *> ret;
242 bool emitASM = ctx.config.emit == EmitKind::ASM;
243 const char *Ext = emitASM ? ".s" : ".obj";
244 for (unsigned i = 0; i != maxTasks; ++i) {
245 StringRef bitcodeFilePath;
246 // Get the native object contents either from a MemoryBuffer, for example
247 // from the cache or an external DTLTO backend compilation, or by reading
248 // from memory. Do not use the provided MemoryBuffer directly, or the PDB
249 // will not be deterministic.
250 StringRef objBuf;
251 if (files[i]) {
252 objBuf = files[i]->getBuffer();
253 bitcodeFilePath = file_names[i];
254 } else {
255 objBuf = buf[i].second;
256 bitcodeFilePath = buf[i].first;
257 }
258 if (objBuf.empty())
259 continue;
260
261 // If the input bitcode file is path/to/a.obj, then the corresponding lto
262 // object file name will look something like: path/to/main.exe.lto.a.obj.
263 StringRef ltoObjName;
264 if (bitcodeFilePath == "ld-temp.o") {
265 ltoObjName =
266 saver().save(S: Twine(ctx.config.outputFile) + ".lto" +
267 (i == 0 ? Twine("") : Twine('.') + Twine(i)) + Ext);
268 } else {
269 StringRef directory = sys::path::parent_path(path: bitcodeFilePath);
270 StringRef baseName = sys::path::stem(path: bitcodeFilePath);
271 StringRef outputFileBaseName = sys::path::filename(path: ctx.config.outputFile);
272 SmallString<64> path;
273 sys::path::append(path, a: directory,
274 b: outputFileBaseName + ".lto." + baseName + Ext);
275 sys::path::remove_dots(path, remove_dot_dot: true);
276 ltoObjName = saver().save(S: path.str());
277 }
278 if (llvm::is_contained(Range&: ctx.config.saveTempsArgs, Element: "prelink") || emitASM)
279 saveBuffer(buffer: buf[i].second, path: ltoObjName);
280 if (!emitASM)
281 ret.push_back(x: ObjFile::create(ctx, mb: MemoryBufferRef(objBuf, ltoObjName)));
282 }
283
284 return ret;
285}
286
287void BitcodeCompiler::setBitcodeLibFuncs(ArrayRef<StringRef> bitcodeLibFuncs) {
288 ltoObj->setBitcodeLibFuncs(bitcodeLibFuncs);
289}
290