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