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/FileSystem.h"
16#include "llvm/Support/Path.h"
17#include <llvm/IR/LegacyPassManager.h>
18#include <llvm/IR/Module.h>
19#include <llvm/MC/TargetRegistry.h>
20#include <llvm/Target/TargetMachine.h>
21
23
24#include <string>
25
26namespace lld {
27enum Flavor {
29 Gnu, // -flavor gnu
30 MinGW, // -flavor gnu MinGW
31 WinLink, // -flavor link
32 Darwin, // -flavor darwin
33 Wasm, // -flavor wasm
34};
35
36using Driver = bool (*)(llvm::ArrayRef<const char *>, llvm::raw_ostream &,
37 llvm::raw_ostream &, bool, bool);
38
43
44struct Result {
47};
48
49Result lldMain(llvm::ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
50 llvm::raw_ostream &stderrOS, llvm::ArrayRef<DriverDef> drivers);
51[[noreturn]] void exitLld(int val);
52
53namespace wasm {
54bool link(llvm::ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
55 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput);
56} // namespace wasm
57} // namespace lld
58
59#include <dlfcn.h>
60
61namespace clang {
62
64 llvm::ErrorAsOutParameter EAO(&Err);
65
66 if (Err)
67 return;
68
69 if (auto EC =
70 llvm::sys::fs::createUniqueDirectory("clang-wasm-exec-", TempDir))
71 Err = llvm::make_error<llvm::StringError>(
72 "Failed to create temporary directory for Wasm executor: " +
73 EC.message(),
74 llvm::inconvertibleErrorCode());
75}
76
78
80 std::string ErrorString;
81
82 const llvm::Target *Target = llvm::TargetRegistry::lookupTarget(
83 PTU.TheModule->getTargetTriple(), ErrorString);
84 if (!Target) {
85 return llvm::make_error<llvm::StringError>("Failed to create Wasm Target: ",
86 llvm::inconvertibleErrorCode());
87 }
88
89 llvm::TargetOptions TO = llvm::TargetOptions();
90 llvm::TargetMachine *TargetMachine = Target->createTargetMachine(
91 PTU.TheModule->getTargetTriple(), "", "", TO, llvm::Reloc::Model::PIC_);
92 PTU.TheModule->setDataLayout(TargetMachine->createDataLayout());
93
94 llvm::SmallString<256> ObjectFileName(TempDir);
95 llvm::sys::path::append(ObjectFileName, PTU.TheModule->getName() + ".o");
96
97 llvm::SmallString<256> BinaryFileName(TempDir);
98 llvm::sys::path::append(BinaryFileName, PTU.TheModule->getName() + ".wasm");
99
100 std::error_code EC;
101 llvm::raw_fd_ostream ObjectFileOutput(ObjectFileName, EC);
102
103 if (EC)
104 return llvm::errorCodeToError(EC);
105
106 llvm::legacy::PassManager PM;
107 if (TargetMachine->addPassesToEmitFile(PM, ObjectFileOutput, nullptr,
108 llvm::CodeGenFileType::ObjectFile)) {
109 return llvm::make_error<llvm::StringError>(
110 "Wasm backend cannot produce object.", llvm::inconvertibleErrorCode());
111 }
112
113 if (!PM.run(*PTU.TheModule)) {
114
115 return llvm::make_error<llvm::StringError>("Failed to emit Wasm object.",
116 llvm::inconvertibleErrorCode());
117 }
118
119 ObjectFileOutput.close();
120
121 std::vector<const char *> LinkerArgs = {"wasm-ld",
122 "-shared",
123 "--import-memory",
124 "--stack-first",
125 "--allow-undefined",
126 ObjectFileName.c_str(),
127 "-o",
128 BinaryFileName.c_str()};
129
130 const lld::DriverDef WasmDriver = {lld::Flavor::Wasm, &lld::wasm::link};
131 std::vector<lld::DriverDef> WasmDriverArgs;
132 WasmDriverArgs.push_back(WasmDriver);
134 lld::lldMain(LinkerArgs, llvm::outs(), llvm::errs(), WasmDriverArgs);
135
136 // A fatal error may have recovered control flow without restoring LLD's
137 // process state. Do not allow another incremental link in that case.
138 if (!Result.canRunAgain)
139 lld::exitLld(Result.retCode);
140
141 if (Result.retCode)
142 return llvm::make_error<llvm::StringError>(
143 "Failed to link incremental module", llvm::inconvertibleErrorCode());
144
145 void *LoadedLibModule =
146 dlopen(BinaryFileName.c_str(), RTLD_NOW | RTLD_GLOBAL);
147 if (LoadedLibModule == nullptr) {
148 llvm::errs() << dlerror() << '\n';
149 return llvm::make_error<llvm::StringError>(
150 "Failed to load incremental module", llvm::inconvertibleErrorCode());
151 }
152
153 return llvm::Error::success();
154}
155
157 return llvm::make_error<llvm::StringError>("Not implemented yet",
158 llvm::inconvertibleErrorCode());
159}
160
162 // This seems to be automatically done when using dlopen()
163 return llvm::Error::success();
164}
165
167 // Can't call cleanUp through IncrementalExecutor as it
168 // tries to deinitialize JIT which hasn't been initialized
169 return llvm::Error::success();
170}
171
174 SymbolNameKind NameKind) const {
175 void *Sym = dlsym(RTLD_DEFAULT, Name.str().c_str());
176 if (!Sym) {
177 return llvm::make_error<llvm::StringError>("dlsym failed for symbol: " +
178 Name.str(),
179 llvm::inconvertibleErrorCode());
180 }
181
182 return llvm::orc::ExecutorAddr::fromPtr(Sym);
183}
184
185llvm::Error WasmIncrementalExecutor::LoadDynamicLibrary(const char *name) {
186 void *handle = dlopen(name, RTLD_NOW | RTLD_GLOBAL);
187 if (!handle) {
188 llvm::errs() << dlerror() << '\n';
189 return llvm::make_error<llvm::StringError>("Failed to load dynamic library",
190 llvm::inconvertibleErrorCode());
191 }
192 return llvm::Error::success();
193}
194} // namespace clang
llvm::Expected< llvm::orc::ExecutorAddr > getSymbolAddress(llvm::StringRef Name, SymbolNameKind NameKind) const override
Definition Wasm.cpp:173
llvm::Error addModule(PartialTranslationUnit &PTU) override
Definition Wasm.cpp:79
llvm::Error runCtors() const override
Definition Wasm.cpp:161
WasmIncrementalExecutor(llvm::Error &Err)
Definition Wasm.cpp:63
llvm::Error LoadDynamicLibrary(const char *name) override
Definition Wasm.cpp:185
llvm::Error removeModule(PartialTranslationUnit &PTU) override
Definition Wasm.cpp:156
llvm::Error cleanUp() override
Definition Wasm.cpp:166
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:26
Flavor
Definition Wasm.cpp:27
@ Darwin
Definition Wasm.cpp:32
@ MinGW
Definition Wasm.cpp:30
@ Invalid
Definition Wasm.cpp:28
@ WinLink
Definition Wasm.cpp:31
@ Gnu
Definition Wasm.cpp:29
@ Wasm
Definition Wasm.cpp:33
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:36
#define noreturn
Definition stdnoreturn.h:17
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:41
Flavor f
Definition Wasm.cpp:40
bool canRunAgain
Definition Wasm.cpp:46
int retCode
Definition Wasm.cpp:45