xref: /llvm-project-15.0.7/lld/COFF/LTO.cpp (revision e00799ea)
1 //===- LTO.cpp ------------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "LTO.h"
11 #include "Config.h"
12 #include "InputFiles.h"
13 #include "Symbols.h"
14 #include "lld/Common/ErrorHandler.h"
15 #include "lld/Common/TargetOptionsCommandFlags.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/LTO/Caching.h"
22 #include "llvm/LTO/Config.h"
23 #include "llvm/LTO/LTO.h"
24 #include "llvm/Object/SymbolicFile.h"
25 #include "llvm/Support/CodeGen.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <algorithm>
31 #include <cstddef>
32 #include <memory>
33 #include <string>
34 #include <system_error>
35 #include <vector>
36 
37 using namespace llvm;
38 using namespace llvm::object;
39 
40 using namespace lld;
41 using namespace lld::coff;
42 
43 static void diagnosticHandler(const DiagnosticInfo &DI) {
44   SmallString<128> ErrStorage;
45   raw_svector_ostream OS(ErrStorage);
46   DiagnosticPrinterRawOStream DP(OS);
47   DI.print(DP);
48   warn(ErrStorage);
49 }
50 
51 static void checkError(Error E) {
52   handleAllErrors(std::move(E),
53                   [&](ErrorInfoBase &EIB) { error(EIB.message()); });
54 }
55 
56 static void saveBuffer(StringRef Buffer, const Twine &Path) {
57   std::error_code EC;
58   raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
59   if (EC)
60     error("cannot create " + Path + ": " + EC.message());
61   OS << Buffer;
62 }
63 
64 static std::unique_ptr<lto::LTO> createLTO() {
65   lto::Config Conf;
66   Conf.Options = InitTargetOptionsFromCodeGenFlags();
67 
68   // Always emit a section per function/datum with LTO. LLVM LTO should get most
69   // of the benefit of linker GC, but there are still opportunities for ICF.
70   Conf.Options.FunctionSections = true;
71   Conf.Options.DataSections = true;
72 
73   // Use static reloc model on 32-bit x86 because it usually results in more
74   // compact code, and because there are also known code generation bugs when
75   // using the PIC model (see PR34306).
76   if (Config->Machine == COFF::IMAGE_FILE_MACHINE_I386)
77     Conf.RelocModel = Reloc::Static;
78   else
79     Conf.RelocModel = Reloc::PIC_;
80   Conf.DisableVerify = true;
81   Conf.DiagHandler = diagnosticHandler;
82   Conf.OptLevel = Config->LTOOptLevel;
83   if (Config->SaveTemps)
84     checkError(Conf.addSaveTemps(std::string(Config->OutputFile) + ".",
85                                  /*UseInputModulePath*/ true));
86   lto::ThinBackend Backend;
87   if (Config->LTOJobs != 0)
88     Backend = lto::createInProcessThinBackend(Config->LTOJobs);
89   return llvm::make_unique<lto::LTO>(std::move(Conf), Backend,
90                                      Config->LTOPartitions);
91 }
92 
93 BitcodeCompiler::BitcodeCompiler() : LTOObj(createLTO()) {}
94 
95 BitcodeCompiler::~BitcodeCompiler() = default;
96 
97 static void undefine(Symbol *S) { replaceSymbol<Undefined>(S, S->getName()); }
98 
99 void BitcodeCompiler::add(BitcodeFile &F) {
100   lto::InputFile &Obj = *F.Obj;
101   unsigned SymNum = 0;
102   std::vector<Symbol *> SymBodies = F.getSymbols();
103   std::vector<lto::SymbolResolution> Resols(SymBodies.size());
104 
105   // Provide a resolution to the LTO API for each symbol.
106   for (const lto::InputFile::Symbol &ObjSym : Obj.symbols()) {
107     Symbol *Sym = SymBodies[SymNum];
108     lto::SymbolResolution &R = Resols[SymNum];
109     ++SymNum;
110 
111     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
112     // reports two symbols for module ASM defined. Without this check, lld
113     // flags an undefined in IR with a definition in ASM as prevailing.
114     // Once IRObjectFile is fixed to report only one symbol this hack can
115     // be removed.
116     R.Prevailing = !ObjSym.isUndefined() && Sym->getFile() == &F;
117     R.VisibleToRegularObj = Sym->IsUsedInRegularObj;
118     if (R.Prevailing)
119       undefine(Sym);
120   }
121   checkError(LTOObj->add(std::move(F.Obj), Resols));
122 }
123 
124 // Merge all the bitcode files we have seen, codegen the result
125 // and return the resulting objects.
126 std::vector<StringRef> BitcodeCompiler::compile() {
127   unsigned MaxTasks = LTOObj->getMaxTasks();
128   Buff.resize(MaxTasks);
129   Files.resize(MaxTasks);
130 
131   // The /lldltocache option specifies the path to a directory in which to cache
132   // native object files for ThinLTO incremental builds. If a path was
133   // specified, configure LTO to use it as the cache directory.
134   lto::NativeObjectCache Cache;
135   if (!Config->LTOCache.empty())
136     Cache = check(lto::localCache(
137         Config->LTOCache, [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
138           Files[Task] = std::move(MB);
139         }));
140 
141   checkError(LTOObj->run(
142       [&](size_t Task) {
143         return llvm::make_unique<lto::NativeObjectStream>(
144             llvm::make_unique<raw_svector_ostream>(Buff[Task]));
145       },
146       Cache));
147 
148   if (!Config->LTOCache.empty())
149     pruneCache(Config->LTOCache, Config->LTOCachePolicy);
150 
151   std::vector<StringRef> Ret;
152   for (unsigned I = 0; I != MaxTasks; ++I) {
153     if (Buff[I].empty())
154       continue;
155     if (Config->SaveTemps) {
156       if (I == 0)
157         saveBuffer(Buff[I], Config->OutputFile + ".lto.obj");
158       else
159         saveBuffer(Buff[I], Config->OutputFile + Twine(I) + ".lto.obj");
160     }
161     Ret.emplace_back(Buff[I].data(), Buff[I].size());
162   }
163 
164   for (std::unique_ptr<MemoryBuffer> &File : Files)
165     if (File)
166       Ret.push_back(File->getBuffer());
167 
168   return Ret;
169 }
170