xref: /llvm-project-15.0.7/lld/wasm/LTO.cpp (revision 5a127cdc)
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/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/IR/DiagnosticPrinter.h"
22 #include "llvm/LTO/Caching.h"
23 #include "llvm/LTO/Config.h"
24 #include "llvm/LTO/LTO.h"
25 #include "llvm/Object/SymbolicFile.h"
26 #include "llvm/Support/CodeGen.h"
27 #include "llvm/Support/Error.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <algorithm>
32 #include <cstddef>
33 #include <memory>
34 #include <string>
35 #include <system_error>
36 #include <vector>
37 
38 using namespace llvm;
39 using namespace lld;
40 using namespace lld::wasm;
41 
42 static std::unique_ptr<lto::LTO> createLTO() {
43   lto::Config C;
44   C.Options = InitTargetOptionsFromCodeGenFlags();
45 
46   // Always emit a section per function/data with LTO.
47   C.Options.FunctionSections = true;
48   C.Options.DataSections = true;
49 
50   // Wasm currently only supports ThreadModel::Single
51   C.Options.ThreadModel = ThreadModel::Single;
52 
53   C.DisableVerify = Config->DisableVerify;
54   C.DiagHandler = diagnosticHandler;
55   C.OptLevel = Config->LTOO;
56   C.MAttrs = GetMAttrs();
57 
58   if (Config->Relocatable)
59     C.RelocModel = None;
60   else if (Config->Pic)
61     C.RelocModel = Reloc::PIC_;
62   else
63     C.RelocModel = Reloc::Static;
64 
65   if (Config->SaveTemps)
66     checkError(C.addSaveTemps(Config->OutputFile.str() + ".",
67                               /*UseInputModulePath*/ true));
68 
69   lto::ThinBackend Backend;
70   if (Config->ThinLTOJobs != -1U)
71     Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs);
72   return llvm::make_unique<lto::LTO>(std::move(C), Backend,
73                                      Config->LTOPartitions);
74 }
75 
76 BitcodeCompiler::BitcodeCompiler() : LTOObj(createLTO()) {}
77 
78 BitcodeCompiler::~BitcodeCompiler() = default;
79 
80 static void undefine(Symbol *S) {
81   if (auto F = dyn_cast<DefinedFunction>(S))
82     replaceSymbol<UndefinedFunction>(F, F->getName(), 0, F->getFile(),
83                                      F->Signature);
84   else if (isa<DefinedData>(S))
85     replaceSymbol<UndefinedData>(S, S->getName(), 0, S->getFile());
86   else
87     llvm_unreachable("unexpected symbol kind");
88 }
89 
90 void BitcodeCompiler::add(BitcodeFile &F) {
91   lto::InputFile &Obj = *F.Obj;
92   unsigned SymNum = 0;
93   ArrayRef<Symbol *> Syms = F.getSymbols();
94   std::vector<lto::SymbolResolution> Resols(Syms.size());
95 
96   // Provide a resolution to the LTO API for each symbol.
97   for (const lto::InputFile::Symbol &ObjSym : Obj.symbols()) {
98     Symbol *Sym = Syms[SymNum];
99     lto::SymbolResolution &R = Resols[SymNum];
100     ++SymNum;
101 
102     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
103     // reports two symbols for module ASM defined. Without this check, lld
104     // flags an undefined in IR with a definition in ASM as prevailing.
105     // Once IRObjectFile is fixed to report only one symbol this hack can
106     // be removed.
107     R.Prevailing = !ObjSym.isUndefined() && Sym->getFile() == &F;
108     R.VisibleToRegularObj = Config->Relocatable || Sym->IsUsedInRegularObj ||
109                             (R.Prevailing && Sym->isExported());
110     if (R.Prevailing)
111       undefine(Sym);
112   }
113   checkError(LTOObj->add(std::move(F.Obj), Resols));
114 }
115 
116 // Merge all the bitcode files we have seen, codegen the result
117 // and return the resulting objects.
118 std::vector<StringRef> BitcodeCompiler::compile() {
119   unsigned MaxTasks = LTOObj->getMaxTasks();
120   Buf.resize(MaxTasks);
121   Files.resize(MaxTasks);
122 
123   // The --thinlto-cache-dir option specifies the path to a directory in which
124   // to cache native object files for ThinLTO incremental builds. If a path was
125   // specified, configure LTO to use it as the cache directory.
126   lto::NativeObjectCache Cache;
127   if (!Config->ThinLTOCacheDir.empty())
128     Cache = check(
129         lto::localCache(Config->ThinLTOCacheDir,
130                         [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
131                           Files[Task] = std::move(MB);
132                         }));
133 
134   checkError(LTOObj->run(
135       [&](size_t Task) {
136         return llvm::make_unique<lto::NativeObjectStream>(
137             llvm::make_unique<raw_svector_ostream>(Buf[Task]));
138       },
139       Cache));
140 
141   if (!Config->ThinLTOCacheDir.empty())
142     pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy);
143 
144   std::vector<StringRef> Ret;
145   for (unsigned I = 0; I != MaxTasks; ++I) {
146     if (Buf[I].empty())
147       continue;
148     if (Config->SaveTemps) {
149       if (I == 0)
150         saveBuffer(Buf[I], Config->OutputFile + ".lto.o");
151       else
152         saveBuffer(Buf[I], Config->OutputFile + Twine(I) + ".lto.o");
153     }
154     Ret.emplace_back(Buf[I].data(), Buf[I].size());
155   }
156 
157   for (std::unique_ptr<MemoryBuffer> &File : Files)
158     if (File)
159       Ret.push_back(File->getBuffer());
160 
161   return Ret;
162 }
163