xref: /freebsd/contrib/llvm-project/lld/COFF/LTO.cpp (revision 38a52bd3b5cac3da6f7f6eef3dd050e6aa08ebb3)
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 "InputFiles.h"
12 #include "Symbols.h"
13 #include "lld/Common/Args.h"
14 #include "lld/Common/CommonLinkerContext.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/Config.h"
24 #include "llvm/LTO/LTO.h"
25 #include "llvm/Object/SymbolicFile.h"
26 #include "llvm/Support/Caching.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"
32 #include <algorithm>
33 #include <cstddef>
34 #include <memory>
35 #include <string>
36 #include <system_error>
37 #include <vector>
38 
39 using namespace llvm;
40 using namespace llvm::object;
41 using namespace lld;
42 using namespace lld::coff;
43 
44 // Creates an empty file to and returns a raw_fd_ostream to write to it.
45 static std::unique_ptr<raw_fd_ostream> openFile(StringRef file) {
46   std::error_code ec;
47   auto ret =
48       std::make_unique<raw_fd_ostream>(file, ec, sys::fs::OpenFlags::OF_None);
49   if (ec) {
50     error("cannot open " + file + ": " + ec.message());
51     return nullptr;
52   }
53   return ret;
54 }
55 
56 static std::string getThinLTOOutputFile(StringRef path) {
57   return lto::getThinLTOOutputFile(
58       std::string(path), std::string(config->thinLTOPrefixReplace.first),
59       std::string(config->thinLTOPrefixReplace.second));
60 }
61 
62 static lto::Config createConfig() {
63   lto::Config c;
64   c.Options = initTargetOptionsFromCodeGenFlags();
65   c.Options.EmitAddrsig = true;
66 
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;
71 
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;
77   else
78     c.RelocModel = Reloc::PIC_;
79   c.DisableVerify = true;
80   c.DiagHandler = diagnosticHandler;
81   c.OptLevel = config->ltoo;
82   c.CPU = getCPUStr();
83   c.MAttrs = getMAttrs();
84   c.CGOptLevel = args::getCGOptLevel(config->ltoo);
85   c.AlwaysEmitRegularLTOObj = !config->ltoObjPath.empty();
86   c.UseNewPM = config->ltoNewPassManager;
87   c.DebugPassManager = config->ltoDebugPassManager;
88   c.CSIRProfile = std::string(config->ltoCSProfileFile);
89   c.RunCSIRInstr = config->ltoCSProfileGenerate;
90   c.PGOWarnMismatch = config->ltoPGOWarnMismatch;
91 
92   if (config->saveTemps)
93     checkError(c.addSaveTemps(std::string(config->outputFile) + ".",
94                               /*UseInputModulePath*/ true));
95   return c;
96 }
97 
98 BitcodeCompiler::BitcodeCompiler() {
99   // Initialize indexFile.
100   if (!config->thinLTOIndexOnlyArg.empty())
101     indexFile = openFile(config->thinLTOIndexOnlyArg);
102 
103   // Initialize ltoObj.
104   lto::ThinBackend backend;
105   if (config->thinLTOIndexOnly) {
106     auto OnIndexWrite = [&](StringRef S) { thinIndices.erase(S); };
107     backend = lto::createWriteIndexesThinBackend(
108         std::string(config->thinLTOPrefixReplace.first),
109         std::string(config->thinLTOPrefixReplace.second),
110         config->thinLTOEmitImportsFiles, indexFile.get(), OnIndexWrite);
111   } else {
112     backend = lto::createInProcessThinBackend(
113         llvm::heavyweight_hardware_concurrency(config->thinLTOJobs));
114   }
115 
116   ltoObj = std::make_unique<lto::LTO>(createConfig(), backend,
117                                        config->ltoPartitions);
118 }
119 
120 BitcodeCompiler::~BitcodeCompiler() = default;
121 
122 static void undefine(Symbol *s) { replaceSymbol<Undefined>(s, s->getName()); }
123 
124 void BitcodeCompiler::add(BitcodeFile &f) {
125   lto::InputFile &obj = *f.obj;
126   unsigned symNum = 0;
127   std::vector<Symbol *> symBodies = f.getSymbols();
128   std::vector<lto::SymbolResolution> resols(symBodies.size());
129 
130   if (config->thinLTOIndexOnly)
131     thinIndices.insert(obj.getName());
132 
133   // Provide a resolution to the LTO API for each symbol.
134   for (const lto::InputFile::Symbol &objSym : obj.symbols()) {
135     Symbol *sym = symBodies[symNum];
136     lto::SymbolResolution &r = resols[symNum];
137     ++symNum;
138 
139     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
140     // reports two symbols for module ASM defined. Without this check, lld
141     // flags an undefined in IR with a definition in ASM as prevailing.
142     // Once IRObjectFile is fixed to report only one symbol this hack can
143     // be removed.
144     r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f;
145     r.VisibleToRegularObj = sym->isUsedInRegularObj;
146     if (r.Prevailing)
147       undefine(sym);
148 
149     // We tell LTO to not apply interprocedural optimization for wrapped
150     // (with -wrap) symbols because otherwise LTO would inline them while
151     // their values are still not final.
152     r.LinkerRedefined = !sym->canInline;
153   }
154   checkError(ltoObj->add(std::move(f.obj), resols));
155 }
156 
157 // Merge all the bitcode files we have seen, codegen the result
158 // and return the resulting objects.
159 std::vector<InputFile *> BitcodeCompiler::compile(COFFLinkerContext &ctx) {
160   unsigned maxTasks = ltoObj->getMaxTasks();
161   buf.resize(maxTasks);
162   files.resize(maxTasks);
163 
164   // The /lldltocache option specifies the path to a directory in which to cache
165   // native object files for ThinLTO incremental builds. If a path was
166   // specified, configure LTO to use it as the cache directory.
167   FileCache cache;
168   if (!config->ltoCache.empty())
169     cache =
170         check(localCache("ThinLTO", "Thin", config->ltoCache,
171                          [&](size_t task, std::unique_ptr<MemoryBuffer> mb) {
172                            files[task] = std::move(mb);
173                          }));
174 
175   checkError(ltoObj->run(
176       [&](size_t task) {
177         return std::make_unique<CachedFileStream>(
178             std::make_unique<raw_svector_ostream>(buf[task]));
179       },
180       cache));
181 
182   // Emit empty index files for non-indexed files
183   for (StringRef s : thinIndices) {
184     std::string path = getThinLTOOutputFile(s);
185     openFile(path + ".thinlto.bc");
186     if (config->thinLTOEmitImportsFiles)
187       openFile(path + ".imports");
188   }
189 
190   // ThinLTO with index only option is required to generate only the index
191   // files. After that, we exit from linker and ThinLTO backend runs in a
192   // distributed environment.
193   if (config->thinLTOIndexOnly) {
194     if (!config->ltoObjPath.empty())
195       saveBuffer(buf[0], config->ltoObjPath);
196     if (indexFile)
197       indexFile->close();
198     return {};
199   }
200 
201   if (!config->ltoCache.empty())
202     pruneCache(config->ltoCache, config->ltoCachePolicy);
203 
204   std::vector<InputFile *> ret;
205   for (unsigned i = 0; i != maxTasks; ++i) {
206     // Assign unique names to LTO objects. This ensures they have unique names
207     // in the PDB if one is produced. The names should look like:
208     // - foo.exe.lto.obj
209     // - foo.exe.lto.1.obj
210     // - ...
211     StringRef ltoObjName =
212         saver().save(Twine(config->outputFile) + ".lto" +
213                      (i == 0 ? Twine("") : Twine('.') + Twine(i)) + ".obj");
214 
215     // Get the native object contents either from the cache or from memory.  Do
216     // not use the cached MemoryBuffer directly, or the PDB will not be
217     // deterministic.
218     StringRef objBuf;
219     if (files[i])
220       objBuf = files[i]->getBuffer();
221     else
222       objBuf = buf[i];
223     if (objBuf.empty())
224       continue;
225 
226     if (config->saveTemps)
227       saveBuffer(buf[i], ltoObjName);
228     ret.push_back(make<ObjFile>(ctx, MemoryBufferRef(objBuf, ltoObjName)));
229   }
230 
231   return ret;
232 }
233