clang 24.0.0git
Wasm.cpp
Go to the documentation of this file.
1//===----------------- Wasm.cpp - Wasm Interpreter --------------*- C++ -*-===//
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// This file implements interpreter support for code execution in WebAssembly.
10//
11//===----------------------------------------------------------------------===//
12
13#include "Wasm.h"
14
15#include "llvm/Support/CommandLine.h"
16#include "llvm/Support/FileSystem.h"
17#include "llvm/Support/Path.h"
18#include "llvm/TargetParser/Host.h"
19#include <llvm/IR/LegacyPassManager.h>
20#include <llvm/IR/Module.h>
21#include <llvm/MC/TargetRegistry.h>
22#include <llvm/Target/TargetMachine.h>
23#include <llvm/TargetParser/Triple.h>
24
26
27#include <string>
28
29namespace lld {
30enum Flavor {
32 Gnu, // -flavor gnu
33 MinGW, // -flavor gnu MinGW
34 WinLink, // -flavor link
35 Darwin, // -flavor darwin
36 Wasm, // -flavor wasm
37};
38
39using Driver = bool (*)(llvm::ArrayRef<const char *>, llvm::raw_ostream &,
40 llvm::raw_ostream &, bool, bool);
41
46
47struct Result {
50};
51
52Result lldMain(llvm::ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
53 llvm::raw_ostream &stderrOS, llvm::ArrayRef<DriverDef> drivers);
54[[noreturn]] void exitLld(int val);
55
56namespace wasm {
57bool link(llvm::ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
58 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput);
59} // namespace wasm
60} // namespace lld
61
62#include <dlfcn.h>
63
64namespace clang {
65
66std::unique_ptr<IncrementalExecutorBuilder>
68 return std::make_unique<WasmIncrementalExecutorBuilder>();
69}
70
71llvm::Error
73 const Options &Opts) {
74 if (Opts.IsOutOfProcess)
75 return llvm::createStringError("Out-of-process execution is not supported "
76 "by the WebAssembly executor");
77 return llvm::Error::success();
78}
79
82 return llvm::Triple(llvm::sys::getProcessTriple());
83}
84
86WasmIncrementalExecutorBuilder::createExecutor(
87 llvm::orc::ThreadSafeContext &TSC, const clang::TargetInfo &TI) {
88 llvm::Error Err = llvm::Error::success();
89 std::unique_ptr<IncrementalExecutor> Executor =
90 std::make_unique<WasmIncrementalExecutor>(Err, LLVMArgs);
91 if (Err)
92 return std::move(Err);
93 return std::move(Executor);
94}
95
97 llvm::Error &Err, std::vector<std::string> LLVMArgs)
98 : StoredLLVMArgs(std::move(LLVMArgs)) {
99 llvm::ErrorAsOutParameter EAO(&Err);
100
101 if (Err)
102 return;
103
104 if (auto EC =
105 llvm::sys::fs::createUniqueDirectory("clang-wasm-exec-", TempDir))
106 Err = llvm::make_error<llvm::StringError>(
107 "Failed to create temporary directory for Wasm executor: " +
108 EC.message(),
109 llvm::inconvertibleErrorCode());
110}
111
113
115 std::string ErrorString;
116
117 const llvm::Target *Target = llvm::TargetRegistry::lookupTarget(
118 PTU.TheModule->getTargetTriple(), ErrorString);
119 if (!Target) {
120 return llvm::make_error<llvm::StringError>("Failed to create Wasm Target: ",
121 llvm::inconvertibleErrorCode());
122 }
123
124 llvm::TargetOptions TO = llvm::TargetOptions();
125 llvm::TargetMachine *TargetMachine = Target->createTargetMachine(
126 PTU.TheModule->getTargetTriple(), "", "", TO, llvm::Reloc::Model::PIC_);
127
128 llvm::SmallString<256> ObjectFileName(TempDir);
129 llvm::sys::path::append(ObjectFileName, PTU.TheModule->getName() + ".o");
130
131 llvm::SmallString<256> BinaryFileName(TempDir);
132 llvm::sys::path::append(BinaryFileName, PTU.TheModule->getName() + ".wasm");
133
134 std::error_code EC;
135 llvm::raw_fd_ostream ObjectFileOutput(ObjectFileName, EC);
136
137 if (EC)
138 return llvm::errorCodeToError(EC);
139
140 llvm::legacy::PassManager PM;
141 if (TargetMachine->addPassesToEmitFile(PM, ObjectFileOutput, nullptr,
142 llvm::CodeGenFileType::ObjectFile)) {
143 return llvm::make_error<llvm::StringError>(
144 "Wasm backend cannot produce object.", llvm::inconvertibleErrorCode());
145 }
146
147 if (!PM.run(*PTU.TheModule)) {
148
149 return llvm::make_error<llvm::StringError>("Failed to emit Wasm object.",
150 llvm::inconvertibleErrorCode());
151 }
152
153 ObjectFileOutput.close();
154
155 std::string Emulation = "-m";
156 Emulation +=
157 llvm::Triple(PTU.TheModule->getTargetTriple()).getArchName().str();
158 std::vector<const char *> LinkerArgs = {"wasm-ld",
159 Emulation.c_str(),
160 "-shared",
161 "--import-memory",
162 "--stack-first",
163 "--allow-undefined",
164 ObjectFileName.c_str(),
165 "-o",
166 BinaryFileName.c_str()};
167
168 const lld::DriverDef WasmDriver = {lld::Flavor::Wasm, &lld::wasm::link};
169 std::vector<lld::DriverDef> WasmDriverArgs;
170 WasmDriverArgs.push_back(WasmDriver);
172 lld::lldMain(LinkerArgs, llvm::outs(), llvm::errs(), WasmDriverArgs);
173
174 // A fatal error may have recovered control flow without restoring LLD's
175 // process state. Do not allow another incremental link in that case.
176 if (!Result.canRunAgain)
177 lld::exitLld(Result.retCode);
178
179 // lld::wasm::linkerMain calls cl::ResetAllOptionOccurrences() which wipes
180 // all global LLVM cl options, including mllvm flags set by the frontend
181 // (e.g. -wasm-enable-eh, -wasm-enable-sjlj). Re-apply them so the next
182 // Parse() call's WebAssemblyTargetMachine creation finds the correct state.
183 //
184 // FIXME: Remove this once library command-line options no longer rely on
185 // process-global cl::opt state. See:
186 // https://discourse.llvm.org/t/rfc-declare-library-command-line-options-in-tablegen-one-struct-per-library/91877
187 if (!StoredLLVMArgs.empty()) {
188 std::vector<const char *> ArgPtrs;
189 ArgPtrs.push_back("clang-repl (restoring LLVM options)");
190 for (const std::string &Arg : StoredLLVMArgs)
191 ArgPtrs.push_back(Arg.c_str());
192 llvm::cl::ParseCommandLineOptions(ArgPtrs.size(), ArgPtrs.data());
193 }
194
195 if (Result.retCode)
196 return llvm::make_error<llvm::StringError>(
197 "Failed to link incremental module", llvm::inconvertibleErrorCode());
198
199 void *LoadedLibModule =
200 dlopen(BinaryFileName.c_str(), RTLD_NOW | RTLD_GLOBAL);
201 if (LoadedLibModule == nullptr) {
202 llvm::errs() << dlerror() << '\n';
203 return llvm::make_error<llvm::StringError>(
204 "Failed to load incremental module", llvm::inconvertibleErrorCode());
205 }
206
207 return llvm::Error::success();
208}
209
211 return llvm::make_error<llvm::StringError>("Not implemented yet",
212 llvm::inconvertibleErrorCode());
213}
214
216 // This seems to be automatically done when using dlopen()
217 return llvm::Error::success();
218}
219
221 // Can't call cleanUp through IncrementalExecutor as it
222 // tries to deinitialize JIT which hasn't been initialized
223 return llvm::Error::success();
224}
225
228 SymbolNameKind NameKind) const {
229 void *Sym = dlsym(RTLD_DEFAULT, Name.str().c_str());
230 if (!Sym) {
231 return llvm::make_error<llvm::StringError>("dlsym failed for symbol: " +
232 Name.str(),
233 llvm::inconvertibleErrorCode());
234 }
235
236 return llvm::orc::ExecutorAddr::fromPtr(Sym);
237}
238
239llvm::Error WasmIncrementalExecutor::LoadDynamicLibrary(const char *name) {
240 void *handle = dlopen(name, RTLD_NOW | RTLD_GLOBAL);
241 if (!handle) {
242 llvm::errs() << dlerror() << '\n';
243 return llvm::make_error<llvm::StringError>("Failed to load dynamic library",
244 llvm::inconvertibleErrorCode());
245 }
246 return llvm::Error::success();
247}
248} // namespace clang
Create a pre-configured CompilerInstance for incremental processing.
Definition Interpreter.h:54
static std::unique_ptr< IncrementalExecutorBuilder > createDefault()
Create the default builder for the platform clangInterpreter is built for.
std::vector< std::string > LLVMArgs
Frontend -mllvm arguments for backends that need to restore LLVM options.
Exposes information about the current target.
Definition TargetInfo.h:228
llvm::Error configure(IncrementalCompilerBuilder &CB, const Options &Opts) override
Apply execution options and configure the compiler for this backend.
Definition Wasm.cpp:72
llvm::Expected< llvm::Triple > getHostJITTriple() const override
Return the host triple used by this backend.
Definition Wasm.cpp:81
llvm::Expected< llvm::orc::ExecutorAddr > getSymbolAddress(llvm::StringRef Name, SymbolNameKind NameKind) const override
Definition Wasm.cpp:227
llvm::Error addModule(PartialTranslationUnit &PTU) override
Definition Wasm.cpp:114
llvm::Error runCtors() const override
Definition Wasm.cpp:215
llvm::Error LoadDynamicLibrary(const char *name) override
Definition Wasm.cpp:239
llvm::Error removeModule(PartialTranslationUnit &PTU) override
Definition Wasm.cpp:210
llvm::Error cleanUp() override
Definition Wasm.cpp:220
WasmIncrementalExecutor(llvm::Error &Err, std::vector< std::string > LLVMArgs)
Definition Wasm.cpp:96
Top level wrappers for InstallAPI frontend operations.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
bool link(llvm::ArrayRef< const char * > args, llvm::raw_ostream &stdoutOS, llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput)
Definition Wasm.cpp:29
Flavor
Definition Wasm.cpp:30
@ Darwin
Definition Wasm.cpp:35
@ MinGW
Definition Wasm.cpp:33
@ Invalid
Definition Wasm.cpp:31
@ WinLink
Definition Wasm.cpp:34
@ Gnu
Definition Wasm.cpp:32
@ Wasm
Definition Wasm.cpp:36
void exitLld(int val)
Result lldMain(llvm::ArrayRef< const char * > args, llvm::raw_ostream &stdoutOS, llvm::raw_ostream &stderrOS, llvm::ArrayRef< DriverDef > drivers)
bool(*)(llvm::ArrayRef< const char * >, llvm::raw_ostream &, llvm::raw_ostream &, bool, bool) Driver
Definition Wasm.cpp:39
#define noreturn
Definition stdnoreturn.h:17
Options passed to the backend when configuring execution.
The class keeps track of various objects created as part of processing incremental inputs.
std::unique_ptr< llvm::Module > TheModule
The llvm IR produced for the input.
Driver d
Definition Wasm.cpp:44
Flavor f
Definition Wasm.cpp:43
bool canRunAgain
Definition Wasm.cpp:49
int retCode
Definition Wasm.cpp:48