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