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 "Driver.h"
12#include "InputFiles.h"
13#include "Symbols.h"
14#include "Target.h"
15
16#include "lld/Common/CommonLinkerContext.h"
17#include "lld/Common/Filesystem.h"
18#include "lld/Common/Strings.h"
19#include "lld/Common/TargetOptionsCommandFlags.h"
20#include "llvm/Bitcode/BitcodeWriter.h"
21#include "llvm/LTO/Config.h"
22#include "llvm/LTO/LTO.h"
23#include "llvm/Support/Caching.h"
24#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/Path.h"
26#include "llvm/Support/raw_ostream.h"
27
28using namespace lld;
29using namespace lld::macho;
30using namespace llvm;
31using namespace llvm::MachO;
32using namespace llvm::sys;
33
34static std::string getThinLTOOutputFile(StringRef modulePath) {
35 return lto::getThinLTOOutputFile(Path: modulePath, OldPrefix: config->thinLTOPrefixReplaceOld,
36 NewPrefix: config->thinLTOPrefixReplaceNew);
37}
38
39static lto::Config createConfig() {
40 lto::Config c;
41 c.LibraryOptions = &config->libraryOptions;
42 c.Options = getTargetOptions(libraryOptions: config->libraryOptions);
43 c.Options.EmitAddrsig = config->icfLevel == ICFLevel::safe ||
44 config->icfLevel == ICFLevel::safe_thunks;
45 for (StringRef C : config->mllvmOpts)
46 c.MllvmArgs.emplace_back(args: C.str());
47 for (StringRef pluginFn : config->passPlugins)
48 c.PassPluginFilenames.push_back(x: std::string(pluginFn));
49 c.OptPipeline = std::string(config->ltoNewPmPasses);
50 c.CodeModel = getCodeModelFromCMModel(libraryOptions: config->libraryOptions);
51 c.CPU = getCPUStr(libraryOptions: config->libraryOptions);
52 c.MAttrs = getMAttrs(libraryOptions: config->libraryOptions);
53 c.DiagHandler = diagnosticHandler;
54
55 c.AlwaysEmitRegularLTOObj = !config->ltoObjPath.empty();
56
57 c.TimeTraceEnabled = config->timeTraceEnabled;
58 c.TimeTraceGranularity = config->timeTraceGranularity;
59 c.DebugPassManager = config->ltoDebugPassManager;
60 c.CSIRProfile = std::string(config->csProfilePath);
61 c.RunCSIRInstr = config->csProfileGenerate;
62 c.PGOWarnMismatch = config->pgoWarnMismatch;
63 c.DisableVerify = config->disableVerify;
64 c.OptLevel = config->ltoo;
65 c.CGOptLevel = config->ltoCgo;
66
67 c.PTO.LoopVectorization = c.OptLevel > 1;
68 c.PTO.SLPVectorization = c.OptLevel > 1;
69
70 if (config->saveTemps)
71 checkError(e: c.addSaveTemps(OutputFileName: config->outputFile.str() + ".",
72 /*UseInputModulePath=*/true));
73
74 if (config->emitLLVM) {
75 llvm::StringRef outputFile = config->outputFile;
76 c.PreCodeGenModuleHook = [outputFile](size_t task, const Module &m) {
77 if (std::unique_ptr<raw_fd_ostream> os = openLTOOutputFile(file: outputFile))
78 WriteBitcodeToFile(M: m, Out&: *os, ShouldPreserveUseListOrder: false);
79 return false;
80 };
81 }
82
83 return c;
84}
85
86// If `originalPath` exists, hardlinks `path` to `originalPath`. If that fails,
87// or `originalPath` is not set, saves `buffer` to `path`. Returns the
88// modification time of the resulting file.
89static uint32_t saveOrHardlinkBuffer(StringRef buffer, StringRef path,
90 std::optional<StringRef> originalPath) {
91 fs::file_status originalStat, pathStat;
92 bool haveOriginal = originalPath && !fs::status(path: *originalPath, result&: originalStat);
93 bool havePath = !fs::status(path, result&: pathStat, /*follow=*/false);
94 // A previous link already hardlinked `path` to the same cache entry.
95 if (haveOriginal && havePath && fs::equivalent(A: originalStat, B: pathStat))
96 return getModTime(stat: originalStat);
97 // Delete the hardlink if it exists. Otherwise, it is possible for the
98 // create_hard_link to fail (as the hardlink exists already), and when
99 // saveBuffer is subsequently called the hardlink'd file may get truncated
100 // and reading from it causes a crash. Even without the cache, `path` may be
101 // a hardlink to a cache entry left by an earlier link, and saveBuffer would
102 // overwrite that entry.
103 if (havePath)
104 fs::remove(path);
105 if (haveOriginal && !fs::create_hard_link(to: *originalPath, from: path))
106 return getModTime(path);
107 saveBuffer(buffer, path);
108 return getModTime(path);
109}
110
111BitcodeCompiler::BitcodeCompiler() {
112 // Initialize indexFile.
113 if (!config->thinLTOIndexOnlyArg.empty())
114 indexFile = openFile(file: config->thinLTOIndexOnlyArg);
115
116 // Initialize ltoObj.
117 lto::ThinBackend backend;
118 auto onIndexWrite = [&](StringRef S) { thinIndices.erase(V: S); };
119 if (config->thinLTOIndexOnly) {
120 backend = lto::createWriteIndexesThinBackend(
121 Parallelism: llvm::hardware_concurrency(Num: config->thinLTOJobs),
122 OldPrefix: std::string(config->thinLTOPrefixReplaceOld),
123 NewPrefix: std::string(config->thinLTOPrefixReplaceNew),
124 NativeObjectPrefix: std::string(config->thinLTOPrefixReplaceNativeObject),
125 ShouldEmitImportsFiles: config->thinLTOEmitImportsFiles, LinkedObjectsFile: indexFile.get(), OnWrite: onIndexWrite);
126 } else {
127 backend = lto::createInProcessThinBackend(
128 Parallelism: llvm::heavyweight_hardware_concurrency(Num: config->thinLTOJobs),
129 OnWrite: onIndexWrite, ShouldEmitIndexFiles: config->thinLTOEmitIndexFiles,
130 ShouldEmitImportsFiles: config->thinLTOEmitImportsFiles);
131 }
132
133 ltoObj = std::make_unique<lto::LTO>(args: createConfig(), args&: backend);
134}
135
136void BitcodeCompiler::add(BitcodeFile &f) {
137 lto::InputFile &obj = *f.obj;
138
139 if (config->thinLTOEmitIndexFiles)
140 thinIndices.insert(V: obj.getName());
141
142 ArrayRef<lto::InputFile::Symbol> objSyms = obj.symbols();
143 std::vector<lto::SymbolResolution> resols;
144 resols.reserve(n: objSyms.size());
145
146 // Provide a resolution to the LTO API for each symbol.
147 bool exportDynamic =
148 config->outputType != MH_EXECUTE || config->exportDynamic;
149 auto symIt = f.symbols.begin();
150 for (const lto::InputFile::Symbol &objSym : objSyms) {
151 resols.emplace_back();
152 lto::SymbolResolution &r = resols.back();
153 Symbol *sym = *symIt++;
154
155 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
156 // reports two symbols for module ASM defined. Without this check, lld
157 // flags an undefined in IR with a definition in ASM as prevailing.
158 // Once IRObjectFile is fixed to report only one symbol this hack can
159 // be removed.
160 r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f;
161
162 if (const auto *defined = dyn_cast<Defined>(Val: sym)) {
163 r.ExportDynamic =
164 defined->isExternal() && !defined->privateExtern && exportDynamic;
165 r.FinalDefinitionInLinkageUnit =
166 !defined->isExternalWeakDef() && !defined->interposable;
167 } else if (const auto *common = dyn_cast<CommonSymbol>(Val: sym)) {
168 r.ExportDynamic = !common->privateExtern && exportDynamic;
169 r.FinalDefinitionInLinkageUnit = true;
170 }
171
172 r.VisibleToRegularObj =
173 sym->isUsedInRegularObj || (r.Prevailing && r.ExportDynamic);
174
175 // Un-define the symbol so that we don't get duplicate symbol errors when we
176 // load the ObjFile emitted by LTO compilation.
177 if (r.Prevailing)
178 replaceSymbol<Undefined>(s: sym, arg: sym->getName(), arg: sym->getFile(),
179 arg: RefState::Strong, /*wasBitcodeSymbol=*/arg: true);
180
181 // TODO: set the other resolution configs properly
182 }
183 checkError(e: ltoObj->add(Obj: std::move(f.obj), Res: resols));
184 hasFiles = true;
185}
186
187// If LazyObjFile has not been added to link, emit empty index files.
188// This is needed because this is what GNU gold plugin does and we have a
189// distributed build system that depends on that behavior.
190static void thinLTOCreateEmptyIndexFiles() {
191 DenseSet<StringRef> linkedBitCodeFiles;
192 for (InputFile *file : inputFiles)
193 if (auto *f = dyn_cast<BitcodeFile>(Val: file))
194 if (!f->lazy)
195 linkedBitCodeFiles.insert(V: f->getName());
196
197 for (InputFile *file : inputFiles) {
198 if (auto *f = dyn_cast<BitcodeFile>(Val: file)) {
199 if (!f->lazy)
200 continue;
201 if (linkedBitCodeFiles.contains(V: f->getName()))
202 continue;
203 std::string path =
204 replaceThinLTOSuffix(path: getThinLTOOutputFile(modulePath: f->obj->getName()));
205 std::unique_ptr<raw_fd_ostream> os = openFile(file: path + ".thinlto.bc");
206 if (!os)
207 continue;
208
209 ModuleSummaryIndex m(/*HaveGVs=*/false);
210 m.setSkipModuleByDistributedBackend();
211 writeIndexToFile(Index: m, Out&: *os);
212 if (config->thinLTOEmitImportsFiles)
213 openFile(file: path + ".imports");
214 }
215 }
216}
217
218// Merge all the bitcode files we have seen, codegen the result
219// and return the resulting ObjectFile(s).
220std::vector<ObjFile *> BitcodeCompiler::compile() {
221 unsigned maxTasks = ltoObj->getMaxTasks();
222 buf.resize(new_size: maxTasks);
223 files.resize(new_size: maxTasks);
224
225 // The -cache_path_lto option specifies the path to a directory in which
226 // to cache native object files for ThinLTO incremental builds. If a path was
227 // specified, configure LTO to use it as the cache directory.
228 FileCache cache;
229 if (!config->thinLTOCacheDir.empty())
230 cache = check(e: localCache(CacheNameRef: "ThinLTO", TempFilePrefixRef: "Thin", CacheDirectoryPathRef: config->thinLTOCacheDir,
231 AddBuffer: [&](size_t task, const Twine &moduleName,
232 std::unique_ptr<MemoryBuffer> mb) {
233 files[task] = std::move(mb);
234 }));
235
236 if (hasFiles)
237 checkError(e: ltoObj->run(
238 AddStream: [&](size_t task, const Twine &moduleName) {
239 return std::make_unique<CachedFileStream>(
240 args: std::make_unique<raw_svector_ostream>(args&: buf[task]));
241 },
242 Cache: cache));
243
244 // Emit empty index files for non-indexed files
245 for (StringRef s : thinIndices) {
246 std::string path = getThinLTOOutputFile(modulePath: s);
247 openFile(file: path + ".thinlto.bc");
248 if (config->thinLTOEmitImportsFiles)
249 openFile(file: path + ".imports");
250 }
251
252 if (config->thinLTOEmitIndexFiles)
253 thinLTOCreateEmptyIndexFiles();
254
255 // In ThinLTO mode, Clang passes a temporary directory in -object_path_lto,
256 // while the argument is a single file in FullLTO mode.
257 bool objPathIsDir = true;
258 if (!config->ltoObjPath.empty()) {
259 if (std::error_code ec = fs::create_directories(path: config->ltoObjPath))
260 fatal(msg: "cannot create LTO object path " + config->ltoObjPath + ": " +
261 ec.message());
262
263 if (!fs::is_directory(Path: config->ltoObjPath)) {
264 objPathIsDir = false;
265 unsigned objCount =
266 count_if(Range&: buf, P: [](const SmallString<0> &b) { return !b.empty(); });
267 if (objCount > 1)
268 fatal(msg: "-object_path_lto must specify a directory when using ThinLTO");
269 }
270 }
271
272 auto outputFilePath = [objPathIsDir](int i) {
273 SmallString<261> filePath("/tmp/lto.tmp");
274 if (!config->ltoObjPath.empty()) {
275 filePath = config->ltoObjPath;
276 if (objPathIsDir)
277 path::append(path&: filePath, a: Twine(i) + "." +
278 getArchitectureName(Arch: config->arch()) +
279 ".lto.o");
280 }
281 return filePath;
282 };
283
284 // ThinLTO with index only option is required to generate only the index
285 // files. After that, we exit from linker and ThinLTO backend runs in a
286 // distributed environment.
287 if (config->thinLTOIndexOnly) {
288 if (!config->ltoObjPath.empty())
289 saveBuffer(buffer: buf[0], path: outputFilePath(0));
290 if (indexFile)
291 indexFile->close();
292 return {};
293 }
294
295 if (!config->thinLTOCacheDir.empty())
296 check(
297 e: pruneCache(Path: config->thinLTOCacheDir, Policy: config->thinLTOCachePolicy, Files: files));
298
299 std::vector<ObjFile *> ret;
300 for (unsigned i = 0; i < maxTasks; ++i) {
301 // Get the native object contents either from the cache or from memory. Do
302 // not use the cached MemoryBuffer directly to ensure dsymutil does not
303 // race with the cache pruner.
304 StringRef objBuf;
305 std::optional<StringRef> cachePath;
306 if (files[i]) {
307 objBuf = files[i]->getBuffer();
308 cachePath = files[i]->getBufferIdentifier();
309 } else {
310 objBuf = buf[i];
311 }
312 if (objBuf.empty())
313 continue;
314
315 // FIXME: should `saveTemps` and `ltoObjPath` use the same file name?
316 if (config->saveTemps)
317 saveBuffer(buffer: objBuf,
318 path: config->outputFile + ((i == 0) ? "" : Twine(i)) + ".lto.o");
319
320 StringRef filePath = saver().save(S: outputFilePath(i).str());
321 uint32_t modTime = 0;
322 if (!config->ltoObjPath.empty())
323 modTime = saveOrHardlinkBuffer(buffer: objBuf, path: filePath, originalPath: cachePath);
324 ret.push_back(x: make<ObjFile>(args: MemoryBufferRef(objBuf, filePath), args&: modTime,
325 /*archiveName=*/args: "", /*lazy=*/args: false,
326 /*forceHidden=*/args: false, /*compatArch=*/args: true,
327 /*builtFromBitcode=*/args: true));
328 }
329
330 return ret;
331}
332