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 c.RemarksFilename = ctx.config.optRemarksFilename;
99 c.RemarksPasses = ctx.config.optRemarksPasses;
100 c.RemarksWithHotness = ctx.config.optRemarksWithHotness;
101 c.RemarksHotnessThreshold = ctx.config.optRemarksHotnessThreshold;
102 c.RemarksFormat = ctx.config.optRemarksFormat;
103
104 if (ctx.config.emit == EmitKind::LLVM) {
105 c.PreCodeGenModuleHook = [this](size_t task, const Module &m) {
106 if (std::unique_ptr<raw_fd_ostream> os =
107 openLTOOutputFile(file: ctx.config.outputFile))
108 WriteBitcodeToFile(M: m, Out&: *os, ShouldPreserveUseListOrder: false);
109 return false;
110 };
111 } else if (ctx.config.emit == EmitKind::ASM) {
112 c.CGFileType = CodeGenFileType::AssemblyFile;
113 c.Options.MCOptions.AsmVerbose = true;
114 }
115
116 if (!ctx.config.saveTempsArgs.empty())
117 checkError(e: c.addSaveTemps(OutputFileName: std::string(ctx.config.outputFile) + ".",
118 /*UseInputModulePath*/ true,
119 SaveTempsArgs: ctx.config.saveTempsArgs));
120
121 c.PTO.LoopVectorization = c.OptLevel > 1;
122 c.PTO.SLPVectorization = c.OptLevel > 1;
123
124 return c;
125}
126
127BitcodeCompiler::BitcodeCompiler(COFFLinkerContext &c) : ctx(c) {
128 // Initialize indexFile.
129 if (!ctx.config.thinLTOIndexOnlyArg.empty())
130 indexFile = openFile(file: ctx.config.thinLTOIndexOnlyArg);
131
132 // Initialize ltoObj.
133 lto::ThinBackend backend;
134 if (ctx.config.thinLTOIndexOnly) {
135 auto OnIndexWrite = [&](StringRef S) { thinIndices.erase(V: S); };
136 backend = lto::createWriteIndexesThinBackend(
137 Parallelism: llvm::hardware_concurrency(Num: ctx.config.thinLTOJobs),
138 OldPrefix: std::string(ctx.config.thinLTOPrefixReplaceOld),
139 NewPrefix: std::string(ctx.config.thinLTOPrefixReplaceNew),
140 NativeObjectPrefix: std::string(ctx.config.thinLTOPrefixReplaceNativeObject),
141 ShouldEmitImportsFiles: ctx.config.thinLTOEmitImportsFiles, LinkedObjectsFile: indexFile.get(), OnWrite: OnIndexWrite);
142 } else {
143 backend = lto::createInProcessThinBackend(
144 Parallelism: llvm::heavyweight_hardware_concurrency(Num: ctx.config.thinLTOJobs));
145 }
146
147 if (ctx.config.dtltoDistributor.empty())
148 ltoObj = std::make_unique<lto::LTO>(args: createConfig(), args&: backend,
149 args&: ctx.config.ltoPartitions);
150 else
151 ltoObj = std::make_unique<lto::DTLTO>(
152 args: createConfig(), args&: ctx.config.ltoPartitions,
153 args: llvm::lto::LTO::LTOKind::LTOK_Default, args: nullptr,
154 args&: ctx.config.thinLTOEmitImportsFiles, args&: ctx.config.thinLTOIndexOnly,
155 args&: ctx.config.outputFile, args&: ctx.config.dtltoDistributor,
156 args&: ctx.config.dtltoDistributorArgs, args&: ctx.config.dtltoCompiler,
157 args&: ctx.config.dtltoCompilerPrependArgs, args&: ctx.config.dtltoCompilerArgs,
158 args: createAddBufferFn(files, filenames&: file_names),
159 args: !ctx.config.saveTempsArgs.empty());
160}
161
162BitcodeCompiler::~BitcodeCompiler() = default;
163
164void BitcodeCompiler::waitForLTOCleanup() {
165 if (ltoObj)
166 ltoObj->waitForCleanup();
167}
168
169static void undefine(Symbol *s) { replaceSymbol<Undefined>(s, arg: s->getName()); }
170
171void BitcodeCompiler::add(BitcodeFile &f) {
172 lto::InputFile &obj = *f.obj;
173 unsigned symNum = 0;
174 std::vector<Symbol *> symBodies = f.getSymbols();
175 std::vector<lto::SymbolResolution> resols(symBodies.size());
176
177 if (ctx.config.thinLTOIndexOnly)
178 thinIndices.insert(V: obj.getName());
179
180 // Provide a resolution to the LTO API for each symbol.
181 for (const lto::InputFile::Symbol &objSym : obj.symbols()) {
182 Symbol *sym = symBodies[symNum];
183 lto::SymbolResolution &r = resols[symNum];
184 ++symNum;
185
186 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
187 // reports two symbols for module ASM defined. Without this check, lld
188 // flags an undefined in IR with a definition in ASM as prevailing.
189 // Once IRObjectFile is fixed to report only one symbol this hack can
190 // be removed.
191 r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f;
192 r.VisibleToRegularObj = sym->isUsedInRegularObj;
193 if (r.Prevailing)
194 undefine(s: sym);
195
196 // We tell LTO to not apply interprocedural optimization for wrapped
197 // (with -wrap) symbols because otherwise LTO would inline them while
198 // their values are still not final.
199 r.LinkerRedefined = !sym->canInline;
200 }
201 checkError(e: ltoObj->add(Obj: std::move(f.obj), Res: resols));
202}
203
204// Merge all the bitcode files we have seen, codegen the result
205// and return the resulting objects.
206std::vector<InputFile *> BitcodeCompiler::compile() {
207 llvm::TimeTraceScope timeScope("Bitcode compile");
208 unsigned maxTasks = ltoObj->getMaxTasks();
209 buf.resize(new_size: maxTasks);
210 files.resize(new_size: maxTasks);
211 file_names.resize(new_size: maxTasks);
212
213 // The /lldltocache option specifies the path to a directory in which to cache
214 // native object files for ThinLTO incremental builds. If a path was
215 // specified, configure LTO to use it as the cache directory.
216 FileCache cache;
217 if (!ctx.config.ltoCache.empty())
218 cache = check(e: localCache(CacheNameRef: "ThinLTO", TempFilePrefixRef: "Thin", CacheDirectoryPathRef: ctx.config.ltoCache,
219 AddBuffer: createAddBufferFn(files, filenames&: file_names),
220 CacheFileRename: !ctx.config.dtltoDistributor.empty()));
221
222 checkError(e: ltoObj->run(
223 AddStream: [&](size_t task, const Twine &moduleName) {
224 buf[task].first = moduleName.str();
225 return std::make_unique<CachedFileStream>(
226 args: std::make_unique<raw_svector_ostream>(args&: buf[task].second));
227 },
228 Cache: cache));
229
230 // Emit empty index files for non-indexed files
231 for (StringRef s : thinIndices) {
232 std::string path = getThinLTOOutputFile(path: s);
233 openFile(file: path + ".thinlto.bc");
234 if (ctx.config.thinLTOEmitImportsFiles)
235 openFile(file: path + ".imports");
236 }
237
238 // ThinLTO with index only option is required to generate only the index
239 // files. After that, we exit from linker and ThinLTO backend runs in a
240 // distributed environment.
241 if (ctx.config.thinLTOIndexOnly) {
242 if (!ctx.config.ltoObjPath.empty())
243 saveBuffer(buffer: buf[0].second, path: ctx.config.ltoObjPath);
244 if (indexFile)
245 indexFile->close();
246 return {};
247 }
248
249 if (!ctx.config.ltoCache.empty())
250 check(e: pruneCache(Path: ctx.config.ltoCache, Policy: ctx.config.ltoCachePolicy, Files: files));
251
252 std::vector<InputFile *> ret;
253 bool emitASM = ctx.config.emit == EmitKind::ASM;
254 const char *Ext = emitASM ? ".s" : ".obj";
255 for (unsigned i = 0; i != maxTasks; ++i) {
256 StringRef bitcodeFilePath;
257 // Get the native object contents either from a MemoryBuffer, for example
258 // from the cache or an external DTLTO backend compilation, or by reading
259 // from memory. Do not use the provided MemoryBuffer directly, or the PDB
260 // will not be deterministic.
261 StringRef objBuf;
262 if (files[i]) {
263 objBuf = files[i]->getBuffer();
264 bitcodeFilePath = file_names[i];
265 } else {
266 objBuf = buf[i].second;
267 bitcodeFilePath = buf[i].first;
268 }
269 if (objBuf.empty())
270 continue;
271
272 // If the input bitcode file is path/to/a.obj, then the corresponding lto
273 // object file name will look something like: path/to/main.exe.lto.a.obj.
274 StringRef ltoObjName;
275 if (bitcodeFilePath == "ld-temp.o") {
276 ltoObjName =
277 saver().save(S: Twine(ctx.config.outputFile) + ".lto" +
278 (i == 0 ? Twine("") : Twine('.') + Twine(i)) + Ext);
279 } else {
280 StringRef directory = sys::path::parent_path(path: bitcodeFilePath);
281 StringRef baseName = sys::path::stem(path: bitcodeFilePath);
282 StringRef outputFileBaseName = sys::path::filename(path: ctx.config.outputFile);
283 SmallString<64> path;
284 sys::path::append(path, a: directory,
285 b: outputFileBaseName + ".lto." + baseName + Ext);
286 sys::path::remove_dots(path, remove_dot_dot: true);
287 ltoObjName = saver().save(S: path.str());
288 }
289 if (llvm::is_contained(Range&: ctx.config.saveTempsArgs, Element: "prelink") || emitASM)
290 saveBuffer(buffer: buf[i].second, path: ltoObjName);
291 if (!emitASM)
292 ret.push_back(x: ObjFile::create(ctx, mb: MemoryBufferRef(objBuf, ltoObjName)));
293 }
294
295 return ret;
296}
297
298void BitcodeCompiler::setBitcodeLibFuncs(ArrayRef<StringRef> bitcodeLibFuncs) {
299 ltoObj->setBitcodeLibFuncs(bitcodeLibFuncs);
300}
301