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