1 //===- LTO.cpp ------------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
11 #include "InputFiles.h"
13 #include "lld/Common/Args.h"
14 #include "lld/Common/ErrorHandler.h"
15 #include "lld/Common/Strings.h"
16 #include "lld/Common/TargetOptionsCommandFlags.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Bitcode/BitcodeWriter.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/LTO/Caching.h"
24 #include "llvm/LTO/Config.h"
25 #include "llvm/LTO/LTO.h"
26 #include "llvm/Object/SymbolicFile.h"
27 #include "llvm/Support/CodeGen.h"
28 #include "llvm/Support/Error.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/raw_ostream.h"
36 #include <system_error>
40 using namespace llvm::object;
45 // Creates an empty file to and returns a raw_fd_ostream to write to it.
46 static std::unique_ptr<raw_fd_ostream> openFile(StringRef file) {
49 std::make_unique<raw_fd_ostream>(file, ec, sys::fs::OpenFlags::OF_None);
51 error("cannot open " + file + ": " + ec.message());
57 static std::string getThinLTOOutputFile(StringRef path) {
58 return lto::getThinLTOOutputFile(path,
59 config->thinLTOPrefixReplace.first,
60 config->thinLTOPrefixReplace.second);
63 static lto::Config createConfig() {
65 c.Options = initTargetOptionsFromCodeGenFlags();
67 // Always emit a section per function/datum with LTO. LLVM LTO should get most
68 // of the benefit of linker GC, but there are still opportunities for ICF.
69 c.Options.FunctionSections = true;
70 c.Options.DataSections = true;
72 // Use static reloc model on 32-bit x86 because it usually results in more
73 // compact code, and because there are also known code generation bugs when
74 // using the PIC model (see PR34306).
75 if (config->machine == COFF::IMAGE_FILE_MACHINE_I386)
76 c.RelocModel = Reloc::Static;
78 c.RelocModel = Reloc::PIC_;
79 c.DisableVerify = true;
80 c.DiagHandler = diagnosticHandler;
81 c.OptLevel = config->ltoo;
83 c.MAttrs = getMAttrs();
84 c.CGOptLevel = args::getCGOptLevel(config->ltoo);
86 if (config->saveTemps)
87 checkError(c.addSaveTemps(std::string(config->outputFile) + ".",
88 /*UseInputModulePath*/ true));
92 BitcodeCompiler::BitcodeCompiler() {
93 // Initialize indexFile.
94 if (!config->thinLTOIndexOnlyArg.empty())
95 indexFile = openFile(config->thinLTOIndexOnlyArg);
98 lto::ThinBackend backend;
99 if (config->thinLTOIndexOnly) {
100 auto OnIndexWrite = [&](StringRef S) { thinIndices.erase(S); };
101 backend = lto::createWriteIndexesThinBackend(
102 config->thinLTOPrefixReplace.first, config->thinLTOPrefixReplace.second,
103 config->thinLTOEmitImportsFiles, indexFile.get(), OnIndexWrite);
104 } else if (config->thinLTOJobs != 0) {
105 backend = lto::createInProcessThinBackend(config->thinLTOJobs);
108 ltoObj = std::make_unique<lto::LTO>(createConfig(), backend,
109 config->ltoPartitions);
112 BitcodeCompiler::~BitcodeCompiler() = default;
114 static void undefine(Symbol *s) { replaceSymbol<Undefined>(s, s->getName()); }
116 void BitcodeCompiler::add(BitcodeFile &f) {
117 lto::InputFile &obj = *f.obj;
119 std::vector<Symbol *> symBodies = f.getSymbols();
120 std::vector<lto::SymbolResolution> resols(symBodies.size());
122 if (config->thinLTOIndexOnly)
123 thinIndices.insert(obj.getName());
125 // Provide a resolution to the LTO API for each symbol.
126 for (const lto::InputFile::Symbol &objSym : obj.symbols()) {
127 Symbol *sym = symBodies[symNum];
128 lto::SymbolResolution &r = resols[symNum];
131 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
132 // reports two symbols for module ASM defined. Without this check, lld
133 // flags an undefined in IR with a definition in ASM as prevailing.
134 // Once IRObjectFile is fixed to report only one symbol this hack can
136 r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f;
137 r.VisibleToRegularObj = sym->isUsedInRegularObj;
141 checkError(ltoObj->add(std::move(f.obj), resols));
144 // Merge all the bitcode files we have seen, codegen the result
145 // and return the resulting objects.
146 std::vector<StringRef> BitcodeCompiler::compile() {
147 unsigned maxTasks = ltoObj->getMaxTasks();
148 buf.resize(maxTasks);
149 files.resize(maxTasks);
151 // The /lldltocache option specifies the path to a directory in which to cache
152 // native object files for ThinLTO incremental builds. If a path was
153 // specified, configure LTO to use it as the cache directory.
154 lto::NativeObjectCache cache;
155 if (!config->ltoCache.empty())
156 cache = check(lto::localCache(
157 config->ltoCache, [&](size_t task, std::unique_ptr<MemoryBuffer> mb) {
158 files[task] = std::move(mb);
161 checkError(ltoObj->run(
163 return std::make_unique<lto::NativeObjectStream>(
164 std::make_unique<raw_svector_ostream>(buf[task]));
168 // Emit empty index files for non-indexed files
169 for (StringRef s : thinIndices) {
170 std::string path = getThinLTOOutputFile(s);
171 openFile(path + ".thinlto.bc");
172 if (config->thinLTOEmitImportsFiles)
173 openFile(path + ".imports");
176 // ThinLTO with index only option is required to generate only the index
177 // files. After that, we exit from linker and ThinLTO backend runs in a
178 // distributed environment.
179 if (config->thinLTOIndexOnly) {
180 if (!config->ltoObjPath.empty())
181 saveBuffer(buf[0], config->ltoObjPath);
187 if (!config->ltoCache.empty())
188 pruneCache(config->ltoCache, config->ltoCachePolicy);
190 std::vector<StringRef> ret;
191 for (unsigned i = 0; i != maxTasks; ++i) {
194 if (config->saveTemps) {
196 saveBuffer(buf[i], config->outputFile + ".lto.obj");
198 saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.obj");
200 ret.emplace_back(buf[i].data(), buf[i].size());
203 for (std::unique_ptr<MemoryBuffer> &file : files)
205 ret.push_back(file->getBuffer());