Browse Source
This commit removes the Lightbeam backend from Wasmtime as per [RFC 14]. This backend hasn't received maintenance in quite some time, and as [RFC 14] indicates this doesn't meet the threshold for keeping the code in-tree, so this commit removes it. A fast "baseline" compiler may still be added in the future. The addition of such a backend should be in line with [RFC 14], though, with the principles we now have for stable releases of Wasmtime. I'll close out Lightbeam-related issues once this is merged. [RFC 14]: https://github.com/bytecodealliance/rfcs/pull/14pull/3392/head
Alex Crichton
3 years ago
committed by
GitHub
39 changed files with 20 additions and 12372 deletions
@ -1,36 +0,0 @@ |
|||||
[package] |
|
||||
name = "lightbeam" |
|
||||
version = "0.30.0" |
|
||||
authors = ["The Lightbeam Project Developers"] |
|
||||
description = "An optimising one-pass streaming compiler for WebAssembly" |
|
||||
license = "Apache-2.0 WITH LLVM-exception" |
|
||||
repository = "https://github.com/bytecodealliance/wasmtime" |
|
||||
readme = "README.md" |
|
||||
categories = ["wasm"] |
|
||||
keywords = ["webassembly", "wasm", "compile", "compiler", "jit"] |
|
||||
edition = "2018" |
|
||||
|
|
||||
[dependencies] |
|
||||
arrayvec = "0.5" |
|
||||
capstone = "0.9.0" |
|
||||
cranelift-codegen = { path = "../../cranelift/codegen", version = "0.77.0" } |
|
||||
derive_more = "0.99" |
|
||||
dynasm = "1.0.0" |
|
||||
dynasmrt = "1.0.0" |
|
||||
iter-enum = "1" |
|
||||
itertools = "0.10.0" |
|
||||
memoffset = "0.6.0" |
|
||||
more-asserts = "0.2.1" |
|
||||
smallvec = "1.6.1" |
|
||||
thiserror = "1.0.9" |
|
||||
typemap = "0.3" |
|
||||
wasmparser = "0.80" |
|
||||
|
|
||||
[dev-dependencies] |
|
||||
lazy_static = "1.2" |
|
||||
wat = "1.0.37" |
|
||||
quickcheck = "1.0.0" |
|
||||
anyhow = "1.0" |
|
||||
|
|
||||
[badges] |
|
||||
maintenance = { status = "experimental" } |
|
@ -1,220 +0,0 @@ |
|||||
|
|
||||
Apache License |
|
||||
Version 2.0, January 2004 |
|
||||
http://www.apache.org/licenses/ |
|
||||
|
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION |
|
||||
|
|
||||
1. Definitions. |
|
||||
|
|
||||
"License" shall mean the terms and conditions for use, reproduction, |
|
||||
and distribution as defined by Sections 1 through 9 of this document. |
|
||||
|
|
||||
"Licensor" shall mean the copyright owner or entity authorized by |
|
||||
the copyright owner that is granting the License. |
|
||||
|
|
||||
"Legal Entity" shall mean the union of the acting entity and all |
|
||||
other entities that control, are controlled by, or are under common |
|
||||
control with that entity. For the purposes of this definition, |
|
||||
"control" means (i) the power, direct or indirect, to cause the |
|
||||
direction or management of such entity, whether by contract or |
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the |
|
||||
outstanding shares, or (iii) beneficial ownership of such entity. |
|
||||
|
|
||||
"You" (or "Your") shall mean an individual or Legal Entity |
|
||||
exercising permissions granted by this License. |
|
||||
|
|
||||
"Source" form shall mean the preferred form for making modifications, |
|
||||
including but not limited to software source code, documentation |
|
||||
source, and configuration files. |
|
||||
|
|
||||
"Object" form shall mean any form resulting from mechanical |
|
||||
transformation or translation of a Source form, including but |
|
||||
not limited to compiled object code, generated documentation, |
|
||||
and conversions to other media types. |
|
||||
|
|
||||
"Work" shall mean the work of authorship, whether in Source or |
|
||||
Object form, made available under the License, as indicated by a |
|
||||
copyright notice that is included in or attached to the work |
|
||||
(an example is provided in the Appendix below). |
|
||||
|
|
||||
"Derivative Works" shall mean any work, whether in Source or Object |
|
||||
form, that is based on (or derived from) the Work and for which the |
|
||||
editorial revisions, annotations, elaborations, or other modifications |
|
||||
represent, as a whole, an original work of authorship. For the purposes |
|
||||
of this License, Derivative Works shall not include works that remain |
|
||||
separable from, or merely link (or bind by name) to the interfaces of, |
|
||||
the Work and Derivative Works thereof. |
|
||||
|
|
||||
"Contribution" shall mean any work of authorship, including |
|
||||
the original version of the Work and any modifications or additions |
|
||||
to that Work or Derivative Works thereof, that is intentionally |
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner |
|
||||
or by an individual or Legal Entity authorized to submit on behalf of |
|
||||
the copyright owner. For the purposes of this definition, "submitted" |
|
||||
means any form of electronic, verbal, or written communication sent |
|
||||
to the Licensor or its representatives, including but not limited to |
|
||||
communication on electronic mailing lists, source code control systems, |
|
||||
and issue tracking systems that are managed by, or on behalf of, the |
|
||||
Licensor for the purpose of discussing and improving the Work, but |
|
||||
excluding communication that is conspicuously marked or otherwise |
|
||||
designated in writing by the copyright owner as "Not a Contribution." |
|
||||
|
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity |
|
||||
on behalf of whom a Contribution has been received by Licensor and |
|
||||
subsequently incorporated within the Work. |
|
||||
|
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of |
|
||||
this License, each Contributor hereby grants to You a perpetual, |
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable |
|
||||
copyright license to reproduce, prepare Derivative Works of, |
|
||||
publicly display, publicly perform, sublicense, and distribute the |
|
||||
Work and such Derivative Works in Source or Object form. |
|
||||
|
|
||||
3. Grant of Patent License. Subject to the terms and conditions of |
|
||||
this License, each Contributor hereby grants to You a perpetual, |
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable |
|
||||
(except as stated in this section) patent license to make, have made, |
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work, |
|
||||
where such license applies only to those patent claims licensable |
|
||||
by such Contributor that are necessarily infringed by their |
|
||||
Contribution(s) alone or by combination of their Contribution(s) |
|
||||
with the Work to which such Contribution(s) was submitted. If You |
|
||||
institute patent litigation against any entity (including a |
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work |
|
||||
or a Contribution incorporated within the Work constitutes direct |
|
||||
or contributory patent infringement, then any patent licenses |
|
||||
granted to You under this License for that Work shall terminate |
|
||||
as of the date such litigation is filed. |
|
||||
|
|
||||
4. Redistribution. You may reproduce and distribute copies of the |
|
||||
Work or Derivative Works thereof in any medium, with or without |
|
||||
modifications, and in Source or Object form, provided that You |
|
||||
meet the following conditions: |
|
||||
|
|
||||
(a) You must give any other recipients of the Work or |
|
||||
Derivative Works a copy of this License; and |
|
||||
|
|
||||
(b) You must cause any modified files to carry prominent notices |
|
||||
stating that You changed the files; and |
|
||||
|
|
||||
(c) You must retain, in the Source form of any Derivative Works |
|
||||
that You distribute, all copyright, patent, trademark, and |
|
||||
attribution notices from the Source form of the Work, |
|
||||
excluding those notices that do not pertain to any part of |
|
||||
the Derivative Works; and |
|
||||
|
|
||||
(d) If the Work includes a "NOTICE" text file as part of its |
|
||||
distribution, then any Derivative Works that You distribute must |
|
||||
include a readable copy of the attribution notices contained |
|
||||
within such NOTICE file, excluding those notices that do not |
|
||||
pertain to any part of the Derivative Works, in at least one |
|
||||
of the following places: within a NOTICE text file distributed |
|
||||
as part of the Derivative Works; within the Source form or |
|
||||
documentation, if provided along with the Derivative Works; or, |
|
||||
within a display generated by the Derivative Works, if and |
|
||||
wherever such third-party notices normally appear. The contents |
|
||||
of the NOTICE file are for informational purposes only and |
|
||||
do not modify the License. You may add Your own attribution |
|
||||
notices within Derivative Works that You distribute, alongside |
|
||||
or as an addendum to the NOTICE text from the Work, provided |
|
||||
that such additional attribution notices cannot be construed |
|
||||
as modifying the License. |
|
||||
|
|
||||
You may add Your own copyright statement to Your modifications and |
|
||||
may provide additional or different license terms and conditions |
|
||||
for use, reproduction, or distribution of Your modifications, or |
|
||||
for any such Derivative Works as a whole, provided Your use, |
|
||||
reproduction, and distribution of the Work otherwise complies with |
|
||||
the conditions stated in this License. |
|
||||
|
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, |
|
||||
any Contribution intentionally submitted for inclusion in the Work |
|
||||
by You to the Licensor shall be under the terms and conditions of |
|
||||
this License, without any additional terms or conditions. |
|
||||
Notwithstanding the above, nothing herein shall supersede or modify |
|
||||
the terms of any separate license agreement you may have executed |
|
||||
with Licensor regarding such Contributions. |
|
||||
|
|
||||
6. Trademarks. This License does not grant permission to use the trade |
|
||||
names, trademarks, service marks, or product names of the Licensor, |
|
||||
except as required for reasonable and customary use in describing the |
|
||||
origin of the Work and reproducing the content of the NOTICE file. |
|
||||
|
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or |
|
||||
agreed to in writing, Licensor provides the Work (and each |
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS, |
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
|
||||
implied, including, without limitation, any warranties or conditions |
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A |
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the |
|
||||
appropriateness of using or redistributing the Work and assume any |
|
||||
risks associated with Your exercise of permissions under this License. |
|
||||
|
|
||||
8. Limitation of Liability. In no event and under no legal theory, |
|
||||
whether in tort (including negligence), contract, or otherwise, |
|
||||
unless required by applicable law (such as deliberate and grossly |
|
||||
negligent acts) or agreed to in writing, shall any Contributor be |
|
||||
liable to You for damages, including any direct, indirect, special, |
|
||||
incidental, or consequential damages of any character arising as a |
|
||||
result of this License or out of the use or inability to use the |
|
||||
Work (including but not limited to damages for loss of goodwill, |
|
||||
work stoppage, computer failure or malfunction, or any and all |
|
||||
other commercial damages or losses), even if such Contributor |
|
||||
has been advised of the possibility of such damages. |
|
||||
|
|
||||
9. Accepting Warranty or Additional Liability. While redistributing |
|
||||
the Work or Derivative Works thereof, You may choose to offer, |
|
||||
and charge a fee for, acceptance of support, warranty, indemnity, |
|
||||
or other liability obligations and/or rights consistent with this |
|
||||
License. However, in accepting such obligations, You may act only |
|
||||
on Your own behalf and on Your sole responsibility, not on behalf |
|
||||
of any other Contributor, and only if You agree to indemnify, |
|
||||
defend, and hold each Contributor harmless for any liability |
|
||||
incurred by, or claims asserted against, such Contributor by reason |
|
||||
of your accepting any such warranty or additional liability. |
|
||||
|
|
||||
END OF TERMS AND CONDITIONS |
|
||||
|
|
||||
APPENDIX: How to apply the Apache License to your work. |
|
||||
|
|
||||
To apply the Apache License to your work, attach the following |
|
||||
boilerplate notice, with the fields enclosed by brackets "[]" |
|
||||
replaced with your own identifying information. (Don't include |
|
||||
the brackets!) The text should be enclosed in the appropriate |
|
||||
comment syntax for the file format. We also recommend that a |
|
||||
file or class name and description of purpose be included on the |
|
||||
same "printed page" as the copyright notice for easier |
|
||||
identification within third-party archives. |
|
||||
|
|
||||
Copyright [yyyy] [name of copyright owner] |
|
||||
|
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); |
|
||||
you may not use this file except in compliance with the License. |
|
||||
You may obtain a copy of the License at |
|
||||
|
|
||||
http://www.apache.org/licenses/LICENSE-2.0 |
|
||||
|
|
||||
Unless required by applicable law or agreed to in writing, software |
|
||||
distributed under the License is distributed on an "AS IS" BASIS, |
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
||||
See the License for the specific language governing permissions and |
|
||||
limitations under the License. |
|
||||
|
|
||||
|
|
||||
--- LLVM Exceptions to the Apache 2.0 License ---- |
|
||||
|
|
||||
As an exception, if, as a result of your compiling your source code, portions |
|
||||
of this Software are embedded into an Object form of such source code, you |
|
||||
may redistribute such embedded portions in such Object form without complying |
|
||||
with the conditions of Sections 4(a), 4(b) and 4(d) of the License. |
|
||||
|
|
||||
In addition, if you combine or link compiled forms of this Software with |
|
||||
software that is licensed under the GPLv2 ("Combined Software") and if a |
|
||||
court of competent jurisdiction determines that the patent provision (Section |
|
||||
3), the indemnity provision (Section 9) or other Section of the License |
|
||||
conflicts with the conditions of the GPLv2, you may retroactively and |
|
||||
prospectively choose to deem waived or otherwise exclude such Section(s) of |
|
||||
the License, but only in their entirety and only with respect to the Combined |
|
||||
Software. |
|
||||
|
|
@ -1,168 +0,0 @@ |
|||||
# Lightbeam |
|
||||
|
|
||||
Lightbeam is an optimising one-pass streaming compiler for WebAssembly, intended for use in [Wasmtime][wasmtime]. |
|
||||
|
|
||||
[wasmtime]: https://github.com/bytecodealliance/wasmtime |
|
||||
|
|
||||
## Quality of output |
|
||||
|
|
||||
Already - with a very small number of relatively simple optimisation rules - Lightbeam produces surprisingly high-quality output considering how restricted it is. It even produces better code than Cranelift, Firefox or both for some workloads. Here's a very simple example, this recursive fibonacci function in Rust: |
|
||||
|
|
||||
```rust |
|
||||
fn fib(n: i32) -> i32 { |
|
||||
if n == 0 || n == 1 { |
|
||||
1 |
|
||||
} else { |
|
||||
fib(n - 1) + fib(n - 2) |
|
||||
} |
|
||||
} |
|
||||
``` |
|
||||
|
|
||||
When compiled with optimisations enabled, rustc will produce the following WebAssembly: |
|
||||
|
|
||||
```rust |
|
||||
(module |
|
||||
(func $fib (param $p0 i32) (result i32) |
|
||||
(local $l1 i32) |
|
||||
(set_local $l1 |
|
||||
(i32.const 1)) |
|
||||
(block $B0 |
|
||||
(br_if $B0 |
|
||||
(i32.lt_u |
|
||||
(get_local $p0) |
|
||||
(i32.const 2))) |
|
||||
(set_local $l1 |
|
||||
(i32.const 1)) |
|
||||
(loop $L1 |
|
||||
(set_local $l1 |
|
||||
(i32.add |
|
||||
(call $fib |
|
||||
(i32.add |
|
||||
(get_local $p0) |
|
||||
(i32.const -1))) |
|
||||
(get_local $l1))) |
|
||||
(br_if $L1 |
|
||||
(i32.gt_u |
|
||||
(tee_local $p0 |
|
||||
(i32.add |
|
||||
(get_local $p0) |
|
||||
(i32.const -2))) |
|
||||
(i32.const 1))))) |
|
||||
(get_local $l1))) |
|
||||
``` |
|
||||
|
|
||||
Firefox's optimising compiler produces the following assembly (labels cleaned up somewhat): |
|
||||
|
|
||||
```asm |
|
||||
fib: |
|
||||
sub rsp, 0x18 |
|
||||
cmp qword ptr [r14 + 0x28], rsp |
|
||||
jae stack_overflow |
|
||||
mov dword ptr [rsp + 0xc], edi |
|
||||
cmp edi, 2 |
|
||||
jae .Lelse |
|
||||
mov eax, 1 |
|
||||
mov dword ptr [rsp + 8], eax |
|
||||
jmp .Lreturn |
|
||||
.Lelse: |
|
||||
mov dword ptr [rsp + 0xc], edi |
|
||||
mov eax, 1 |
|
||||
mov dword ptr [rsp + 8], eax |
|
||||
.Lloop: |
|
||||
mov edi, dword ptr [rsp + 0xc] |
|
||||
add edi, -1 |
|
||||
call 0 |
|
||||
mov ecx, dword ptr [rsp + 8] |
|
||||
add ecx, eax |
|
||||
mov dword ptr [rsp + 8], ecx |
|
||||
mov ecx, dword ptr [rsp + 0xc] |
|
||||
add ecx, -2 |
|
||||
mov dword ptr [rsp + 0xc], ecx |
|
||||
cmp ecx, 1 |
|
||||
ja .Lloop |
|
||||
.Lreturn: |
|
||||
mov eax, dword ptr [rsp + 8] |
|
||||
nop |
|
||||
add rsp, 0x18 |
|
||||
ret |
|
||||
``` |
|
||||
|
|
||||
Cranelift with optimisations enabled produces similar: |
|
||||
|
|
||||
```asm |
|
||||
fib: |
|
||||
push rbp |
|
||||
mov rbp, rsp |
|
||||
sub rsp, 0x20 |
|
||||
mov qword ptr [rsp + 0x10], rdi |
|
||||
mov dword ptr [rsp + 0x1c], esi |
|
||||
mov eax, 1 |
|
||||
mov dword ptr [rsp + 0x18], eax |
|
||||
mov eax, dword ptr [rsp + 0x1c] |
|
||||
cmp eax, 2 |
|
||||
jb .Lreturn |
|
||||
movabs rax, 0 |
|
||||
mov qword ptr [rsp + 8], rax |
|
||||
.Lloop: |
|
||||
mov eax, dword ptr [rsp + 0x1c] |
|
||||
add eax, -1 |
|
||||
mov rcx, qword ptr [rsp + 8] |
|
||||
mov rdx, qword ptr [rsp + 0x10] |
|
||||
mov rdi, rdx |
|
||||
mov esi, eax |
|
||||
call rcx |
|
||||
mov ecx, dword ptr [rsp + 0x18] |
|
||||
add eax, ecx |
|
||||
mov dword ptr [rsp + 0x18], eax |
|
||||
mov eax, dword ptr [rsp + 0x1c] |
|
||||
add eax, -2 |
|
||||
mov dword ptr [rsp + 0x1c], eax |
|
||||
mov eax, dword ptr [rsp + 0x1c] |
|
||||
cmp eax, 1 |
|
||||
ja .Lloop |
|
||||
.Lreturn: |
|
||||
mov eax, dword ptr [rsp + 0x18] |
|
||||
add rsp, 0x20 |
|
||||
pop rbp |
|
||||
ret |
|
||||
``` |
|
||||
|
|
||||
Whereas Lightbeam produces smaller code with far fewer memory accesses than both (and fewer blocks than Firefox's output): |
|
||||
|
|
||||
```asm |
|
||||
fib: |
|
||||
cmp esi, 2 |
|
||||
mov eax, 1 |
|
||||
jb .Lreturn |
|
||||
mov eax, 1 |
|
||||
.Lloop: |
|
||||
mov rcx, rsi |
|
||||
add ecx, 0xffffffff |
|
||||
push rsi |
|
||||
push rax |
|
||||
push rax |
|
||||
mov rsi, rcx |
|
||||
call fib |
|
||||
add eax, [rsp + 8] |
|
||||
mov rcx, [rsp + 0x10] |
|
||||
add ecx, 0xfffffffe |
|
||||
cmp ecx, 1 |
|
||||
mov rsi, rcx |
|
||||
lea rsp, [rsp + 0x18] |
|
||||
ja .Lloop |
|
||||
.Lreturn: |
|
||||
ret |
|
||||
``` |
|
||||
|
|
||||
Now obviously I'm not advocating for replacing Firefox's optimising compiler with Lightbeam since the latter can only really produce better code when receiving optimised WebAssembly (and so debug-mode or hand-written WebAssembly may produce much worse output). However, this shows that even with the restrictions of a streaming compiler it's absolutely possible to produce high-quality assembly output. For the assembly above, the Lightbeam output runs within 15% of native speed. This is paramount for one of Lightbeam's intended usecases for real-time systems that want good runtime performance but cannot tolerate compiler bombs. |
|
||||
|
|
||||
## Specification compliance |
|
||||
|
|
||||
Lightbeam passes 100% of the specification test suite, but that doesn't necessarily mean that it's 100% specification-compliant. Hopefully as we run a fuzzer against it we can find any issues and get Lightbeam to a state where it can be used in production. |
|
||||
|
|
||||
## Getting involved |
|
||||
|
|
||||
You can file issues in the [Wasmtime issue tracker][Wasmtime issue tracker]. If you want to get involved jump into the [Bytecode Alliance Zulip][bytecodealliance-zulip] and someone can direct you to the right place. I wish I could say "the most useful thing you can do is play with it and open issues where you find problems" but until it passes the spec suite that won't be very helpful. |
|
||||
|
|
||||
[bytecodealliance-zulip]: https://bytecodealliance.zulipchat.com/ |
|
||||
[Wasmtime issue tracker]: https://github.com/bytecodealliance/wasmtime/issues |
|
@ -1,16 +0,0 @@ |
|||||
use lightbeam::translate; |
|
||||
|
|
||||
const WAT: &str = r#" |
|
||||
(module |
|
||||
(func (param i32) (param i32) (result i32) (i32.add (get_local 0) (get_local 1))) |
|
||||
) |
|
||||
"#; |
|
||||
|
|
||||
fn main() -> anyhow::Result<()> { |
|
||||
let data = wat::parse_str(WAT)?; |
|
||||
let translated = translate(&data)?; |
|
||||
let result: u32 = translated.execute_func(0, (5u32, 3u32))?; |
|
||||
println!("f(5, 3) = {}", result); |
|
||||
|
|
||||
Ok(()) |
|
||||
} |
|
File diff suppressed because it is too large
@ -1,112 +0,0 @@ |
|||||
use crate::translate; |
|
||||
|
|
||||
const FIBONACCI: &str = r#" |
|
||||
(module |
|
||||
(func $fib (param $n i32) (result i32) |
|
||||
(if (result i32) |
|
||||
(i32.eq |
|
||||
(i32.const 0) |
|
||||
(get_local $n) |
|
||||
) |
|
||||
(then |
|
||||
(i32.const 1) |
|
||||
) |
|
||||
(else |
|
||||
(if (result i32) |
|
||||
(i32.eq |
|
||||
(i32.const 1) |
|
||||
(get_local $n) |
|
||||
) |
|
||||
(then |
|
||||
(i32.const 1) |
|
||||
) |
|
||||
(else |
|
||||
(i32.add |
|
||||
;; fib(n - 1) |
|
||||
(call $fib |
|
||||
(i32.add |
|
||||
(get_local $n) |
|
||||
(i32.const -1) |
|
||||
) |
|
||||
) |
|
||||
;; fib(n - 2) |
|
||||
(call $fib |
|
||||
(i32.add |
|
||||
(get_local $n) |
|
||||
(i32.const -2) |
|
||||
) |
|
||||
) |
|
||||
) |
|
||||
) |
|
||||
) |
|
||||
) |
|
||||
) |
|
||||
) |
|
||||
) |
|
||||
"#; |
|
||||
|
|
||||
// Generated by Rust for the `fib` function in `bench_fibonacci_baseline`
|
|
||||
const FIBONACCI_OPT: &str = r" |
|
||||
(module |
|
||||
(func $fib (param $p0 i32) (result i32) |
|
||||
(local $l1 i32) |
|
||||
(set_local $l1 |
|
||||
(i32.const 1)) |
|
||||
(block $B0 |
|
||||
(br_if $B0 |
|
||||
(i32.lt_u |
|
||||
(get_local $p0) |
|
||||
(i32.const 2))) |
|
||||
(set_local $l1 |
|
||||
(i32.const 1)) |
|
||||
(loop $L1 |
|
||||
(set_local $l1 |
|
||||
(i32.add |
|
||||
(call $fib |
|
||||
(i32.add |
|
||||
(get_local $p0) |
|
||||
(i32.const -1))) |
|
||||
(get_local $l1))) |
|
||||
(br_if $L1 |
|
||||
(i32.gt_u |
|
||||
(tee_local $p0 |
|
||||
(i32.add |
|
||||
(get_local $p0) |
|
||||
(i32.const -2))) |
|
||||
(i32.const 1))))) |
|
||||
(get_local $l1)))"; |
|
||||
|
|
||||
#[bench] |
|
||||
fn bench_fibonacci_compile(b: &mut test::Bencher) { |
|
||||
let wasm = wat::parse_str(FIBONACCI).unwrap(); |
|
||||
|
|
||||
b.iter(|| test::black_box(translate(&wasm).unwrap())); |
|
||||
} |
|
||||
|
|
||||
#[bench] |
|
||||
fn bench_fibonacci_run(b: &mut test::Bencher) { |
|
||||
let wasm = wat::parse_str(FIBONACCI_OPT).unwrap(); |
|
||||
let module = translate(&wasm).unwrap(); |
|
||||
|
|
||||
b.iter(|| module.execute_func::<_, u32>(0, (20,))); |
|
||||
} |
|
||||
|
|
||||
#[bench] |
|
||||
fn bench_fibonacci_compile_run(b: &mut test::Bencher) { |
|
||||
let wasm = wat::parse_str(FIBONACCI).unwrap(); |
|
||||
|
|
||||
b.iter(|| translate(&wasm).unwrap().execute_func::<_, u32>(0, (20,))); |
|
||||
} |
|
||||
|
|
||||
#[bench] |
|
||||
fn bench_fibonacci_baseline(b: &mut test::Bencher) { |
|
||||
fn fib(n: i32) -> i32 { |
|
||||
if n == 0 || n == 1 { |
|
||||
1 |
|
||||
} else { |
|
||||
fib(n - 1) + fib(n - 2) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
b.iter(|| test::black_box(fib(test::black_box(20)))); |
|
||||
} |
|
@ -1,57 +0,0 @@ |
|||||
use capstone::prelude::*; |
|
||||
use dynasmrt::AssemblyOffset; |
|
||||
use std::error::Error; |
|
||||
use std::fmt::{Display, Write}; |
|
||||
use std::io; |
|
||||
|
|
||||
pub fn disassemble<D: Display>( |
|
||||
mem: &[u8], |
|
||||
mut ops: &[(AssemblyOffset, D)], |
|
||||
) -> Result<(), Box<dyn Error>> { |
|
||||
let cs = Capstone::new() |
|
||||
.x86() |
|
||||
.mode(arch::x86::ArchMode::Mode64) |
|
||||
.build() |
|
||||
.map_err(map_caperr)?; |
|
||||
|
|
||||
println!("{} bytes:", mem.len()); |
|
||||
let insns = cs.disasm_all(&mem, 0x0).map_err(map_caperr)?; |
|
||||
for i in insns.iter() { |
|
||||
let mut line = String::new(); |
|
||||
|
|
||||
let address = i.address(); |
|
||||
|
|
||||
while let Some((offset, op)) = ops.first() { |
|
||||
if offset.0 as u64 <= address { |
|
||||
ops = &ops[1..]; |
|
||||
println!("{}", op); |
|
||||
} else { |
|
||||
break; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
write!(&mut line, "{:4x}:\t", i.address())?; |
|
||||
|
|
||||
let mut bytes_str = String::new(); |
|
||||
for b in i.bytes() { |
|
||||
write!(&mut bytes_str, "{:02x} ", b)?; |
|
||||
} |
|
||||
write!(&mut line, "{:24}\t", bytes_str)?; |
|
||||
|
|
||||
if let Some(s) = i.mnemonic() { |
|
||||
write!(&mut line, "{}\t", s)?; |
|
||||
} |
|
||||
|
|
||||
if let Some(s) = i.op_str() { |
|
||||
write!(&mut line, "{}", s)?; |
|
||||
} |
|
||||
|
|
||||
println!("{}", line); |
|
||||
} |
|
||||
|
|
||||
Ok(()) |
|
||||
} |
|
||||
|
|
||||
fn map_caperr(err: capstone::Error) -> Box<dyn Error> { |
|
||||
Box::new(io::Error::new(io::ErrorKind::Other, err.to_string())) |
|
||||
} |
|
@ -1,29 +0,0 @@ |
|||||
use thiserror::Error; |
|
||||
use wasmparser::BinaryReaderError; |
|
||||
|
|
||||
#[derive(Error, PartialEq, Eq, Clone, Debug)] |
|
||||
pub enum Error { |
|
||||
#[error("Disassembler error: {0}")] |
|
||||
Disassembler(String), |
|
||||
|
|
||||
#[error("Assembler error: {0}")] |
|
||||
Assembler(String), |
|
||||
|
|
||||
#[error("Input error: {0}")] |
|
||||
Input(String), |
|
||||
|
|
||||
#[error("Microwasm error: {0}")] |
|
||||
Microwasm(String), |
|
||||
} |
|
||||
|
|
||||
impl From<BinaryReaderError> for Error { |
|
||||
fn from(e: BinaryReaderError) -> Self { |
|
||||
Error::Input(format!("At wasm offset {}: {}", e.offset(), e.message())) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
impl From<capstone::Error> for Error { |
|
||||
fn from(e: capstone::Error) -> Self { |
|
||||
Error::Disassembler(e.to_string()) |
|
||||
} |
|
||||
} |
|
@ -1,902 +0,0 @@ |
|||||
use crate::backend::{ |
|
||||
ret_locs, BlockCallingConvention, CodeGenSession, Context, Label, VirtualCallingConvention, |
|
||||
}; |
|
||||
#[cfg(debug_assertions)] |
|
||||
use crate::backend::{Registers, ValueLocation}; |
|
||||
use crate::{ |
|
||||
error::Error, |
|
||||
microwasm::*, |
|
||||
module::{ModuleContext, SigType, Signature}, |
|
||||
}; |
|
||||
use cranelift_codegen::{binemit, ir}; |
|
||||
use dynasmrt::DynasmApi; |
|
||||
use itertools::Either::{self, Left, Right}; |
|
||||
#[cfg(debug_assertions)] |
|
||||
use more_asserts::assert_ge; |
|
||||
use std::{collections::HashMap, fmt, hash::Hash, iter, mem}; |
|
||||
use wasmparser::FunctionBody; |
|
||||
|
|
||||
#[derive(Debug)] |
|
||||
struct Block { |
|
||||
label: BrTarget<Label>, |
|
||||
calling_convention: Option<Either<BlockCallingConvention, VirtualCallingConvention>>, |
|
||||
params: u32, |
|
||||
// TODO: Is there a cleaner way to do this? `has_backwards_callers` should always be set if `is_next`
|
|
||||
// is false, so we should probably use an `enum` here.
|
|
||||
is_next: bool, |
|
||||
num_callers: Option<u32>, |
|
||||
actual_num_callers: u32, |
|
||||
has_backwards_callers: bool, |
|
||||
} |
|
||||
|
|
||||
impl Block { |
|
||||
fn should_serialize_args(&self) -> bool { |
|
||||
self.calling_convention.is_none() |
|
||||
&& (self.num_callers != Some(1) || self.has_backwards_callers) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
pub trait OffsetSink { |
|
||||
fn offset( |
|
||||
&mut self, |
|
||||
offset_in_wasm_function: ir::SourceLoc, |
|
||||
offset_in_compiled_function: usize, |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
pub struct NullOffsetSink; |
|
||||
|
|
||||
impl OffsetSink for NullOffsetSink { |
|
||||
fn offset(&mut self, _: ir::SourceLoc, _: usize) {} |
|
||||
} |
|
||||
|
|
||||
pub struct Sinks<'a> { |
|
||||
pub relocs: &'a mut dyn binemit::RelocSink, |
|
||||
pub traps: &'a mut dyn binemit::TrapSink, |
|
||||
pub offsets: &'a mut dyn OffsetSink, |
|
||||
} |
|
||||
|
|
||||
pub fn translate_wasm<M>( |
|
||||
session: &mut CodeGenSession<M>, |
|
||||
sinks: Sinks<'_>, |
|
||||
func_idx: u32, |
|
||||
body: FunctionBody<'_>, |
|
||||
) -> Result<(), Error> |
|
||||
where |
|
||||
M: ModuleContext, |
|
||||
for<'any> &'any M::Signature: Into<OpSig>, |
|
||||
{ |
|
||||
let ty = session.module_context.defined_func_type(func_idx); |
|
||||
|
|
||||
let microwasm_conv = MicrowasmConv::new( |
|
||||
session.module_context, |
|
||||
ty.params().iter().map(SigType::to_microwasm_type), |
|
||||
ty.returns().iter().map(SigType::to_microwasm_type), |
|
||||
body, |
|
||||
session.pointer_type(), |
|
||||
)? |
|
||||
.flat_map(|ops| match ops { |
|
||||
Ok(ops) => Left(ops.into_iter().map(Ok)), |
|
||||
Err(e) => Right(iter::once(Err(Error::Microwasm(e.to_string())))), |
|
||||
}); |
|
||||
|
|
||||
translate(session, sinks, func_idx, microwasm_conv)?; |
|
||||
Ok(()) |
|
||||
} |
|
||||
|
|
||||
pub fn translate<M, I, L: Send + Sync + 'static>( |
|
||||
session: &mut CodeGenSession<M>, |
|
||||
sinks: Sinks<'_>, |
|
||||
func_idx: u32, |
|
||||
body: I, |
|
||||
) -> Result<(), Error> |
|
||||
where |
|
||||
M: ModuleContext, |
|
||||
I: IntoIterator<Item = Result<Operator<L>, Error>>, |
|
||||
L: Hash + Clone + Eq, |
|
||||
BrTarget<L>: std::fmt::Display, |
|
||||
{ |
|
||||
fn drop_elements<T>(stack: &mut Vec<T>, depths: std::ops::RangeInclusive<u32>) { |
|
||||
let _ = (|| { |
|
||||
let start = stack |
|
||||
.len() |
|
||||
.checked_sub(1)? |
|
||||
.checked_sub(*depths.end() as usize)?; |
|
||||
let end = stack |
|
||||
.len() |
|
||||
.checked_sub(1)? |
|
||||
.checked_sub(*depths.start() as usize)?; |
|
||||
let real_range = start..=end; |
|
||||
|
|
||||
stack.drain(real_range); |
|
||||
|
|
||||
Some(()) |
|
||||
})(); |
|
||||
} |
|
||||
|
|
||||
let func_type = session.module_context.defined_func_type(func_idx); |
|
||||
let mut body = body.into_iter().peekable(); |
|
||||
|
|
||||
let module_context = &*session.module_context; |
|
||||
let mut op_offset_map = mem::replace(&mut session.op_offset_map, vec![]); |
|
||||
{ |
|
||||
let ctx = &mut session.new_context(func_idx, &mut *sinks.relocs); |
|
||||
op_offset_map.push(( |
|
||||
ctx.asm.offset(), |
|
||||
Box::new(format!("Function {}:", func_idx)), |
|
||||
)); |
|
||||
|
|
||||
let params = func_type |
|
||||
.params() |
|
||||
.iter() |
|
||||
.map(|t| t.to_microwasm_type()) |
|
||||
.collect::<Vec<_>>(); |
|
||||
|
|
||||
ctx.start_function(params.iter().cloned())?; |
|
||||
|
|
||||
let mut blocks = HashMap::<BrTarget<L>, Block>::new(); |
|
||||
|
|
||||
let num_returns = func_type.returns().len(); |
|
||||
|
|
||||
let loc = ret_locs(func_type.returns().iter().map(|t| t.to_microwasm_type()))?; |
|
||||
|
|
||||
blocks.insert( |
|
||||
BrTarget::Return, |
|
||||
Block { |
|
||||
label: BrTarget::Return, |
|
||||
params: num_returns as u32, |
|
||||
calling_convention: Some(Left(BlockCallingConvention::function_start(loc))), |
|
||||
is_next: false, |
|
||||
has_backwards_callers: false, |
|
||||
actual_num_callers: 0, |
|
||||
num_callers: None, |
|
||||
}, |
|
||||
); |
|
||||
|
|
||||
while let Some(op) = body.next() { |
|
||||
let op = op?; |
|
||||
|
|
||||
if let Some(Ok(Operator::Label(label))) = body.peek() { |
|
||||
let block = match blocks.get_mut(&BrTarget::Label(label.clone())) { |
|
||||
None => { |
|
||||
return Err(Error::Microwasm( |
|
||||
"Label defined before being declared".to_string(), |
|
||||
)) |
|
||||
} |
|
||||
Some(o) => o, |
|
||||
}; |
|
||||
block.is_next = true; |
|
||||
} |
|
||||
|
|
||||
// `cfg` on blocks doesn't work in the compiler right now, so we have to write a dummy macro
|
|
||||
#[cfg(debug_assertions)] |
|
||||
macro_rules! assertions { |
|
||||
() => { |
|
||||
if let Operator::Label(label) = &op { |
|
||||
let block = &blocks[&BrTarget::Label(label.clone())]; |
|
||||
let num_cc_params = block.calling_convention.as_ref().map(|cc| match cc { |
|
||||
Left(cc) => cc.arguments.len(), |
|
||||
Right(cc) => cc.stack.len(), |
|
||||
}); |
|
||||
if let Some(num_cc_params) = num_cc_params { |
|
||||
// we can use assert here bc we are in debug mode
|
|
||||
assert_ge!(num_cc_params, block.params as usize); |
|
||||
} |
|
||||
} else { |
|
||||
let mut actual_regs = Registers::new(); |
|
||||
actual_regs.release_scratch_register()?; |
|
||||
for val in &ctx.block_state.stack { |
|
||||
if let ValueLocation::Reg(gpr) = val { |
|
||||
actual_regs.mark_used(*gpr); |
|
||||
} |
|
||||
} |
|
||||
// we can use assert here bc we are in debug mode
|
|
||||
assert_eq!(actual_regs, ctx.block_state.regs); |
|
||||
} |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
#[cfg(not(debug_assertions))] |
|
||||
macro_rules! assertions { |
|
||||
() => {}; |
|
||||
} |
|
||||
|
|
||||
assertions!(); |
|
||||
|
|
||||
struct DisassemblyOpFormatter<Label>(Operator<Label>); |
|
||||
|
|
||||
impl<Label> fmt::Display for DisassemblyOpFormatter<Label> |
|
||||
where |
|
||||
Operator<Label>: fmt::Display, |
|
||||
{ |
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
|
||||
match self.0 { |
|
||||
Operator::Label(_) => write!(f, "{}", self.0), |
|
||||
Operator::Block { .. } => write!(f, "{:5}\t{}", "", self.0), |
|
||||
_ => write!(f, "{:5}\t {}", "", self.0), |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
op_offset_map.push(( |
|
||||
ctx.asm.offset(), |
|
||||
Box::new(DisassemblyOpFormatter(op.clone())), |
|
||||
)); |
|
||||
|
|
||||
match op { |
|
||||
Operator::Unreachable => { |
|
||||
ctx.trap(ir::TrapCode::UnreachableCodeReached); |
|
||||
} |
|
||||
Operator::Label(label) => { |
|
||||
use std::collections::hash_map::Entry; |
|
||||
|
|
||||
if let Entry::Occupied(mut entry) = blocks.entry(BrTarget::Label(label.clone())) |
|
||||
{ |
|
||||
let has_backwards_callers = { |
|
||||
let block = entry.get_mut(); |
|
||||
|
|
||||
// TODO: Maybe we want to restrict Microwasm so that at least one of its callers
|
|
||||
// must be before the label. In an ideal world the restriction would be that
|
|
||||
// blocks without callers are illegal, but that's not reasonably possible for
|
|
||||
// Microwasm generated from Wasm.
|
|
||||
if block.actual_num_callers == 0 { |
|
||||
loop { |
|
||||
let done = match body.peek() { |
|
||||
Some(Ok(Operator::Label(_))) | None => true, |
|
||||
Some(_) => false, |
|
||||
}; |
|
||||
|
|
||||
if done { |
|
||||
break; |
|
||||
} |
|
||||
|
|
||||
let skipped = body.next().ok_or_else(|| { |
|
||||
Error::Assembler("Unexpected EOF".into()) |
|
||||
})??; |
|
||||
|
|
||||
// We still want to honour block definitions even in unreachable code
|
|
||||
if let Operator::Block { |
|
||||
label, |
|
||||
has_backwards_callers, |
|
||||
params, |
|
||||
num_callers, |
|
||||
} = skipped |
|
||||
{ |
|
||||
let asm_label = ctx.create_label(); |
|
||||
blocks.insert( |
|
||||
BrTarget::Label(label), |
|
||||
Block { |
|
||||
label: BrTarget::Label(asm_label), |
|
||||
params: params.len() as _, |
|
||||
calling_convention: None, |
|
||||
is_next: false, |
|
||||
has_backwards_callers, |
|
||||
actual_num_callers: 0, |
|
||||
num_callers, |
|
||||
}, |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
continue; |
|
||||
} |
|
||||
|
|
||||
block.is_next = false; |
|
||||
|
|
||||
// TODO: We can `take` this if it's a `Right`
|
|
||||
match block.calling_convention.as_ref() { |
|
||||
Some(Left(cc)) => { |
|
||||
ctx.apply_cc(cc.as_ref())?; |
|
||||
} |
|
||||
Some(Right(virt)) => { |
|
||||
ctx.set_state(virt.clone())?; |
|
||||
} |
|
||||
_ => { |
|
||||
if block.params as usize != ctx.block_state.stack.len() { |
|
||||
return Err(Error::Microwasm( |
|
||||
"Not enough block params on the stack".to_string(), |
|
||||
)); |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
ctx.define_label(block.label.label().unwrap().clone()); |
|
||||
|
|
||||
block.has_backwards_callers |
|
||||
}; |
|
||||
|
|
||||
// To reduce memory overhead
|
|
||||
if !has_backwards_callers { |
|
||||
entry.remove_entry(); |
|
||||
} |
|
||||
} else { |
|
||||
return Err(Error::Microwasm( |
|
||||
"Label defined before being declared".to_string(), |
|
||||
)); |
|
||||
} |
|
||||
} |
|
||||
Operator::Block { |
|
||||
label, |
|
||||
has_backwards_callers, |
|
||||
params, |
|
||||
num_callers, |
|
||||
} => { |
|
||||
let asm_label = ctx.create_label(); |
|
||||
blocks.insert( |
|
||||
BrTarget::Label(label), |
|
||||
Block { |
|
||||
label: BrTarget::Label(asm_label), |
|
||||
params: params.len() as _, |
|
||||
calling_convention: None, |
|
||||
is_next: false, |
|
||||
has_backwards_callers, |
|
||||
actual_num_callers: 0, |
|
||||
num_callers, |
|
||||
}, |
|
||||
); |
|
||||
} |
|
||||
Operator::Br { target } => { |
|
||||
// TODO: We should add the block to the hashmap if we don't have it already
|
|
||||
let block = blocks.get_mut(&target).unwrap(); |
|
||||
block.actual_num_callers += 1; |
|
||||
|
|
||||
let should_serialize_args = block.should_serialize_args(); |
|
||||
|
|
||||
match block { |
|
||||
Block { |
|
||||
is_next, |
|
||||
label: BrTarget::Label(l), |
|
||||
calling_convention, |
|
||||
.. |
|
||||
} => { |
|
||||
let cc = if should_serialize_args { |
|
||||
let block_conv = ctx.serialize_args(block.params)?; |
|
||||
*calling_convention = Some(Left(block_conv)); |
|
||||
None |
|
||||
} else { |
|
||||
calling_convention |
|
||||
.as_ref() |
|
||||
.map(Either::as_ref) |
|
||||
.and_then(Either::left) |
|
||||
}; |
|
||||
|
|
||||
if let Some(cc) = cc { |
|
||||
ctx.pass_block_args(cc)?; |
|
||||
} |
|
||||
|
|
||||
if !*is_next { |
|
||||
ctx.br(*l); |
|
||||
} |
|
||||
} |
|
||||
Block { |
|
||||
label: BrTarget::Return, |
|
||||
calling_convention: Some(Left(cc)), |
|
||||
.. |
|
||||
} => { |
|
||||
ctx.pass_block_args(cc)?; |
|
||||
ctx.ret(); |
|
||||
} |
|
||||
_ => return Err(Error::Microwasm("Br case unimplemented".to_string())), |
|
||||
} |
|
||||
} |
|
||||
Operator::BrIf { then, else_ } => { |
|
||||
let (then_target, mut then_block) = |
|
||||
blocks.remove_entry(&then.target).ok_or_else(|| { |
|
||||
Error::Microwasm("Programmer error: block does not exist".into()) |
|
||||
})?; |
|
||||
let (else_target, mut else_block) = |
|
||||
blocks.remove_entry(&else_.target).ok_or_else(|| { |
|
||||
Error::Microwasm("Programmer error: block does not exist".into()) |
|
||||
})?; |
|
||||
|
|
||||
// TODO: If actual_num_callers == num_callers then we can remove this block from the hashmap.
|
|
||||
// This frees memory and acts as a kind of verification that `num_callers` is set
|
|
||||
// correctly. It doesn't help for loops and block ends generated from Wasm.
|
|
||||
then_block.actual_num_callers += 1; |
|
||||
else_block.actual_num_callers += 1; |
|
||||
|
|
||||
let then_block_parts = (then_block.is_next, then_block.label); |
|
||||
let else_block_parts = (else_block.is_next, else_block.label); |
|
||||
|
|
||||
// TODO: The blocks should have compatible (one must be subset of other?) calling
|
|
||||
// conventions or else at least one must have no calling convention. This
|
|
||||
// should always be true for converting from WebAssembly AIUI.
|
|
||||
let f = |ctx: &mut Context<_>| { |
|
||||
let then_block_should_serialize_args = then_block.should_serialize_args(); |
|
||||
let else_block_should_serialize_args = else_block.should_serialize_args(); |
|
||||
let max_params = then_block.params.max(else_block.params); |
|
||||
|
|
||||
match ( |
|
||||
(&mut then_block.calling_convention, &then.to_drop), |
|
||||
(&mut else_block.calling_convention, &else_.to_drop), |
|
||||
) { |
|
||||
((Some(Left(ref cc)), _), ref mut other @ (None, _)) |
|
||||
| (ref mut other @ (None, _), (Some(Left(ref cc)), _)) => { |
|
||||
let mut cc = ctx.serialize_block_args(cc, max_params)?; |
|
||||
if let Some(to_drop) = other.1 { |
|
||||
drop_elements(&mut cc.arguments, to_drop.clone()); |
|
||||
} |
|
||||
*other.0 = Some(Left(cc)); |
|
||||
Ok(()) |
|
||||
}, |
|
||||
( |
|
||||
(ref mut then_cc @ None, then_to_drop), |
|
||||
(ref mut else_cc @ None, else_to_drop), |
|
||||
) => { |
|
||||
let virt_cc = if !then_block_should_serialize_args |
|
||||
|| !else_block_should_serialize_args |
|
||||
{ |
|
||||
Some(ctx.virtual_calling_convention()) |
|
||||
} else { |
|
||||
None |
|
||||
}; |
|
||||
|
|
||||
let cc = if then_block_should_serialize_args |
|
||||
|| else_block_should_serialize_args { let a = ctx.serialize_args(max_params)? ; Some(a) } else { None }; |
|
||||
|
|
||||
**then_cc = if then_block_should_serialize_args { |
|
||||
let mut cc = cc.clone().unwrap(); |
|
||||
if let Some(to_drop) = then_to_drop.clone() { |
|
||||
drop_elements(&mut cc.arguments, to_drop); |
|
||||
} |
|
||||
Some(Left(cc)) |
|
||||
} else { |
|
||||
let mut cc = virt_cc.clone().unwrap(); |
|
||||
if let Some(to_drop) = then_to_drop.clone() { |
|
||||
drop_elements(&mut cc.stack, to_drop); |
|
||||
} |
|
||||
Some(Right(cc)) |
|
||||
}; |
|
||||
**else_cc = if else_block_should_serialize_args { |
|
||||
let mut cc = cc.unwrap(); |
|
||||
if let Some(to_drop) = else_to_drop.clone() { |
|
||||
drop_elements(&mut cc.arguments, to_drop); |
|
||||
} |
|
||||
Some(Left(cc)) |
|
||||
} else { |
|
||||
let mut cc = virt_cc.unwrap(); |
|
||||
if let Some(to_drop) = else_to_drop.clone() { |
|
||||
drop_elements(&mut cc.stack, to_drop); |
|
||||
} |
|
||||
Some(Right(cc)) |
|
||||
}; |
|
||||
Ok(()) |
|
||||
}, |
|
||||
_ => Err(Error::Microwasm( |
|
||||
"unimplemented: Can't pass different params to different sides of `br_if` yet".to_string(), |
|
||||
)), |
|
||||
} |
|
||||
}; |
|
||||
|
|
||||
match (then_block_parts, else_block_parts) { |
|
||||
((true, _), (false, else_)) => { |
|
||||
ctx.br_if_false(else_, f)?; |
|
||||
} |
|
||||
((false, then), (true, _)) => { |
|
||||
ctx.br_if_true(then, f)?; |
|
||||
} |
|
||||
((false, then), (false, else_)) => { |
|
||||
ctx.br_if_true(then, f)?; |
|
||||
ctx.br(else_); |
|
||||
} |
|
||||
other => { |
|
||||
return Err(Error::Microwasm(format!( |
|
||||
"br_if unimplemented case: {:#?}", |
|
||||
other |
|
||||
))) |
|
||||
} |
|
||||
}; |
|
||||
|
|
||||
blocks.insert(then_target, then_block); |
|
||||
blocks.insert(else_target, else_block); |
|
||||
} |
|
||||
Operator::BrTable(BrTable { targets, default }) => { |
|
||||
use itertools::Itertools; |
|
||||
|
|
||||
let (label, num_callers, params) = { |
|
||||
let def = &blocks[&default.target]; |
|
||||
( |
|
||||
if def.is_next { None } else { Some(def.label) }, |
|
||||
def.num_callers, |
|
||||
def.params |
|
||||
+ default |
|
||||
.to_drop |
|
||||
.as_ref() |
|
||||
.map(|t| t.clone().count()) |
|
||||
.unwrap_or_default() as u32, |
|
||||
) |
|
||||
}; |
|
||||
|
|
||||
let target_labels = targets |
|
||||
.iter() |
|
||||
.map(|target| { |
|
||||
let block = &blocks[&target.target]; |
|
||||
if block.is_next { |
|
||||
None |
|
||||
} else { |
|
||||
Some(block.label) |
|
||||
} |
|
||||
}) |
|
||||
.collect::<Vec<_>>(); |
|
||||
|
|
||||
ctx.br_table(target_labels, label, |ctx| { |
|
||||
let mut cc = None; |
|
||||
let mut max_params = params; |
|
||||
let mut max_num_callers = num_callers; |
|
||||
|
|
||||
for target in targets.iter().chain(std::iter::once(&default)).unique() { |
|
||||
let block = blocks.get_mut(&target.target).unwrap(); |
|
||||
block.actual_num_callers += 1; |
|
||||
|
|
||||
if block.calling_convention.is_some() { |
|
||||
let new_cc = block.calling_convention.clone(); |
|
||||
|
|
||||
if !(cc.is_none() || cc == new_cc) { |
|
||||
return Err(Error::Microwasm( |
|
||||
"Can't pass different params to different elements of `br_table` yet" |
|
||||
.to_string())); |
|
||||
} |
|
||||
cc = new_cc; |
|
||||
} |
|
||||
|
|
||||
if let Some(max) = max_num_callers { |
|
||||
max_num_callers = block.num_callers.map(|n| max.max(n)); |
|
||||
} |
|
||||
|
|
||||
max_params = max_params.max( |
|
||||
block.params |
|
||||
+ target |
|
||||
.to_drop |
|
||||
.as_ref() |
|
||||
.map(|t| t.clone().count()) |
|
||||
.unwrap_or_default() as u32, |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
let temp: Result< |
|
||||
Either<BlockCallingConvention, VirtualCallingConvention>, |
|
||||
Error, |
|
||||
> = cc |
|
||||
.map(|cc| match cc { |
|
||||
Left(cc) => { |
|
||||
let tmp = ctx.serialize_block_args(&cc, max_params)?; |
|
||||
Ok(Left(tmp)) |
|
||||
} |
|
||||
Right(cc) => Ok(Right(cc)), |
|
||||
}) |
|
||||
.unwrap_or_else(|| { |
|
||||
if max_num_callers.map(|callers| callers <= 1).unwrap_or(false) { |
|
||||
Ok(Right(ctx.virtual_calling_convention())) |
|
||||
} else { |
|
||||
let tmp = ctx.serialize_args(max_params)?; |
|
||||
Ok(Left(tmp)) |
|
||||
} |
|
||||
}); |
|
||||
let cc = match temp.unwrap() { |
|
||||
Right(rr) => Right(rr), |
|
||||
Left(l) => Left(l), |
|
||||
}; |
|
||||
|
|
||||
for target in targets.iter().chain(std::iter::once(&default)).unique() { |
|
||||
let block = blocks.get_mut(&target.target).unwrap(); |
|
||||
let mut cc = cc.clone(); |
|
||||
if let Some(to_drop) = target.to_drop.clone() { |
|
||||
match &mut cc { |
|
||||
Left(cc) => drop_elements(&mut cc.arguments, to_drop), |
|
||||
Right(cc) => drop_elements(&mut cc.stack, to_drop), |
|
||||
} |
|
||||
} |
|
||||
block.calling_convention = Some(cc); |
|
||||
} |
|
||||
Ok(()) |
|
||||
})?; |
|
||||
} |
|
||||
Operator::Swap(depth) => ctx.swap(depth), |
|
||||
Operator::Pick(depth) => ctx.pick(depth), |
|
||||
Operator::Eq(I32) => ctx.i32_eq()?, |
|
||||
Operator::Eqz(Size::_32) => ctx.i32_eqz()?, |
|
||||
Operator::Ne(I32) => ctx.i32_neq()?, |
|
||||
Operator::Lt(SI32) => ctx.i32_lt_s()?, |
|
||||
Operator::Le(SI32) => ctx.i32_le_s()?, |
|
||||
Operator::Gt(SI32) => ctx.i32_gt_s()?, |
|
||||
Operator::Ge(SI32) => ctx.i32_ge_s()?, |
|
||||
Operator::Lt(SU32) => ctx.i32_lt_u()?, |
|
||||
Operator::Le(SU32) => ctx.i32_le_u()?, |
|
||||
Operator::Gt(SU32) => ctx.i32_gt_u()?, |
|
||||
Operator::Ge(SU32) => ctx.i32_ge_u()?, |
|
||||
Operator::Add(I32) => ctx.i32_add()?, |
|
||||
Operator::Sub(I32) => ctx.i32_sub()?, |
|
||||
Operator::And(Size::_32) => ctx.i32_and()?, |
|
||||
Operator::Or(Size::_32) => ctx.i32_or()?, |
|
||||
Operator::Xor(Size::_32) => ctx.i32_xor()?, |
|
||||
Operator::Mul(I32) => ctx.i32_mul()?, |
|
||||
Operator::Div(SU32) => ctx.i32_div_u()?, |
|
||||
Operator::Div(SI32) => ctx.i32_div_s()?, |
|
||||
Operator::Rem(sint::I32) => ctx.i32_rem_s()?, |
|
||||
Operator::Rem(sint::U32) => ctx.i32_rem_u()?, |
|
||||
Operator::Shl(Size::_32) => ctx.i32_shl()?, |
|
||||
Operator::Shr(sint::I32) => ctx.i32_shr_s()?, |
|
||||
Operator::Shr(sint::U32) => ctx.i32_shr_u()?, |
|
||||
Operator::Rotl(Size::_32) => ctx.i32_rotl()?, |
|
||||
Operator::Rotr(Size::_32) => ctx.i32_rotr()?, |
|
||||
Operator::Clz(Size::_32) => ctx.i32_clz()?, |
|
||||
Operator::Ctz(Size::_32) => ctx.i32_ctz()?, |
|
||||
Operator::Popcnt(Size::_32) => ctx.i32_popcnt()?, |
|
||||
Operator::Eq(I64) => ctx.i64_eq()?, |
|
||||
Operator::Eqz(Size::_64) => ctx.i64_eqz()?, |
|
||||
Operator::Ne(I64) => ctx.i64_neq()?, |
|
||||
Operator::Lt(SI64) => ctx.i64_lt_s()?, |
|
||||
Operator::Le(SI64) => ctx.i64_le_s()?, |
|
||||
Operator::Gt(SI64) => ctx.i64_gt_s()?, |
|
||||
Operator::Ge(SI64) => ctx.i64_ge_s()?, |
|
||||
Operator::Lt(SU64) => ctx.i64_lt_u()?, |
|
||||
Operator::Le(SU64) => ctx.i64_le_u()?, |
|
||||
Operator::Gt(SU64) => ctx.i64_gt_u()?, |
|
||||
Operator::Ge(SU64) => ctx.i64_ge_u()?, |
|
||||
Operator::Add(I64) => ctx.i64_add()?, |
|
||||
Operator::Sub(I64) => ctx.i64_sub()?, |
|
||||
Operator::And(Size::_64) => ctx.i64_and()?, |
|
||||
Operator::Or(Size::_64) => ctx.i64_or()?, |
|
||||
Operator::Xor(Size::_64) => ctx.i64_xor()?, |
|
||||
Operator::Mul(I64) => ctx.i64_mul()?, |
|
||||
Operator::Div(SU64) => ctx.i64_div_u()?, |
|
||||
Operator::Div(SI64) => ctx.i64_div_s()?, |
|
||||
Operator::Rem(sint::I64) => ctx.i64_rem_s()?, |
|
||||
Operator::Rem(sint::U64) => ctx.i64_rem_u()?, |
|
||||
Operator::Shl(Size::_64) => ctx.i64_shl()?, |
|
||||
Operator::Shr(sint::I64) => ctx.i64_shr_s()?, |
|
||||
Operator::Shr(sint::U64) => ctx.i64_shr_u()?, |
|
||||
Operator::Rotl(Size::_64) => ctx.i64_rotl()?, |
|
||||
Operator::Rotr(Size::_64) => ctx.i64_rotr()?, |
|
||||
Operator::Clz(Size::_64) => ctx.i64_clz()?, |
|
||||
Operator::Ctz(Size::_64) => ctx.i64_ctz()?, |
|
||||
Operator::Popcnt(Size::_64) => ctx.i64_popcnt()?, |
|
||||
Operator::Add(F32) => ctx.f32_add()?, |
|
||||
Operator::Mul(F32) => ctx.f32_mul()?, |
|
||||
Operator::Sub(F32) => ctx.f32_sub()?, |
|
||||
Operator::Div(SF32) => ctx.f32_div()?, |
|
||||
Operator::Min(Size::_32) => ctx.f32_min()?, |
|
||||
Operator::Max(Size::_32) => ctx.f32_max()?, |
|
||||
Operator::Copysign(Size::_32) => ctx.f32_copysign()?, |
|
||||
Operator::Sqrt(Size::_32) => ctx.f32_sqrt()?, |
|
||||
Operator::Neg(Size::_32) => ctx.f32_neg()?, |
|
||||
Operator::Abs(Size::_32) => ctx.f32_abs()?, |
|
||||
Operator::Floor(Size::_32) => ctx.f32_floor()?, |
|
||||
Operator::Ceil(Size::_32) => ctx.f32_ceil()?, |
|
||||
Operator::Nearest(Size::_32) => ctx.f32_nearest()?, |
|
||||
Operator::Trunc(Size::_32) => ctx.f32_trunc()?, |
|
||||
Operator::Eq(F32) => ctx.f32_eq()?, |
|
||||
Operator::Ne(F32) => ctx.f32_ne()?, |
|
||||
Operator::Gt(SF32) => ctx.f32_gt()?, |
|
||||
Operator::Ge(SF32) => ctx.f32_ge()?, |
|
||||
Operator::Lt(SF32) => ctx.f32_lt()?, |
|
||||
Operator::Le(SF32) => ctx.f32_le()?, |
|
||||
Operator::Add(F64) => ctx.f64_add()?, |
|
||||
Operator::Mul(F64) => ctx.f64_mul()?, |
|
||||
Operator::Sub(F64) => ctx.f64_sub()?, |
|
||||
Operator::Div(SF64) => ctx.f64_div()?, |
|
||||
Operator::Min(Size::_64) => ctx.f64_min()?, |
|
||||
Operator::Max(Size::_64) => ctx.f64_max()?, |
|
||||
Operator::Copysign(Size::_64) => ctx.f64_copysign()?, |
|
||||
Operator::Sqrt(Size::_64) => ctx.f64_sqrt()?, |
|
||||
Operator::Neg(Size::_64) => ctx.f64_neg()?, |
|
||||
Operator::Abs(Size::_64) => ctx.f64_abs()?, |
|
||||
Operator::Floor(Size::_64) => ctx.f64_floor()?, |
|
||||
Operator::Ceil(Size::_64) => ctx.f64_ceil()?, |
|
||||
Operator::Nearest(Size::_64) => ctx.f64_nearest()?, |
|
||||
Operator::Trunc(Size::_64) => ctx.f64_trunc()?, |
|
||||
Operator::Eq(F64) => ctx.f64_eq()?, |
|
||||
Operator::Ne(F64) => ctx.f64_ne()?, |
|
||||
Operator::Gt(SF64) => ctx.f64_gt()?, |
|
||||
Operator::Ge(SF64) => ctx.f64_ge()?, |
|
||||
Operator::Lt(SF64) => ctx.f64_lt()?, |
|
||||
Operator::Le(SF64) => ctx.f64_le()?, |
|
||||
Operator::Drop(range) => ctx.drop(range)?, |
|
||||
Operator::Const(val) => ctx.const_(val)?, |
|
||||
Operator::I32WrapFromI64 => ctx.i32_wrap_from_i64()?, |
|
||||
Operator::I32ReinterpretFromF32 => ctx.i32_reinterpret_from_f32()?, |
|
||||
Operator::I64ReinterpretFromF64 => ctx.i64_reinterpret_from_f64()?, |
|
||||
Operator::F32ReinterpretFromI32 => ctx.f32_reinterpret_from_i32()?, |
|
||||
Operator::F64ReinterpretFromI64 => ctx.f64_reinterpret_from_i64()?, |
|
||||
Operator::ITruncFromF { |
|
||||
input_ty: Size::_32, |
|
||||
output_ty: sint::I32, |
|
||||
} => { |
|
||||
ctx.i32_truncate_f32_s()?; |
|
||||
} |
|
||||
Operator::ITruncFromF { |
|
||||
input_ty: Size::_32, |
|
||||
output_ty: sint::U32, |
|
||||
} => { |
|
||||
ctx.i32_truncate_f32_u()?; |
|
||||
} |
|
||||
Operator::ITruncFromF { |
|
||||
input_ty: Size::_64, |
|
||||
output_ty: sint::I32, |
|
||||
} => { |
|
||||
ctx.i32_truncate_f64_s()?; |
|
||||
} |
|
||||
Operator::ITruncFromF { |
|
||||
input_ty: Size::_64, |
|
||||
output_ty: sint::U32, |
|
||||
} => { |
|
||||
ctx.i32_truncate_f64_u()?; |
|
||||
} |
|
||||
Operator::ITruncFromF { |
|
||||
input_ty: Size::_32, |
|
||||
output_ty: sint::I64, |
|
||||
} => { |
|
||||
ctx.i64_truncate_f32_s()?; |
|
||||
} |
|
||||
Operator::ITruncFromF { |
|
||||
input_ty: Size::_32, |
|
||||
output_ty: sint::U64, |
|
||||
} => { |
|
||||
ctx.i64_truncate_f32_u()?; |
|
||||
} |
|
||||
Operator::ITruncFromF { |
|
||||
input_ty: Size::_64, |
|
||||
output_ty: sint::I64, |
|
||||
} => { |
|
||||
ctx.i64_truncate_f64_s()?; |
|
||||
} |
|
||||
Operator::ITruncFromF { |
|
||||
input_ty: Size::_64, |
|
||||
output_ty: sint::U64, |
|
||||
} => { |
|
||||
ctx.i64_truncate_f64_u()?; |
|
||||
} |
|
||||
Operator::Extend { |
|
||||
sign: Signedness::Unsigned, |
|
||||
} => ctx.i32_extend_u()?, |
|
||||
Operator::Extend { |
|
||||
sign: Signedness::Signed, |
|
||||
} => ctx.i32_extend_s()?, |
|
||||
Operator::FConvertFromI { |
|
||||
input_ty: sint::I32, |
|
||||
output_ty: Size::_32, |
|
||||
} => ctx.f32_convert_from_i32_s()?, |
|
||||
Operator::FConvertFromI { |
|
||||
input_ty: sint::I32, |
|
||||
output_ty: Size::_64, |
|
||||
} => ctx.f64_convert_from_i32_s()?, |
|
||||
Operator::FConvertFromI { |
|
||||
input_ty: sint::I64, |
|
||||
output_ty: Size::_32, |
|
||||
} => ctx.f32_convert_from_i64_s()?, |
|
||||
Operator::FConvertFromI { |
|
||||
input_ty: sint::I64, |
|
||||
output_ty: Size::_64, |
|
||||
} => ctx.f64_convert_from_i64_s()?, |
|
||||
Operator::FConvertFromI { |
|
||||
input_ty: sint::U32, |
|
||||
output_ty: Size::_32, |
|
||||
} => ctx.f32_convert_from_i32_u()?, |
|
||||
Operator::FConvertFromI { |
|
||||
input_ty: sint::U32, |
|
||||
output_ty: Size::_64, |
|
||||
} => ctx.f64_convert_from_i32_u()?, |
|
||||
Operator::FConvertFromI { |
|
||||
input_ty: sint::U64, |
|
||||
output_ty: Size::_32, |
|
||||
} => ctx.f32_convert_from_i64_u()?, |
|
||||
Operator::FConvertFromI { |
|
||||
input_ty: sint::U64, |
|
||||
output_ty: Size::_64, |
|
||||
} => ctx.f64_convert_from_i64_u()?, |
|
||||
Operator::F64PromoteFromF32 => ctx.f64_from_f32()?, |
|
||||
Operator::F32DemoteFromF64 => ctx.f32_from_f64()?, |
|
||||
Operator::Load8 { |
|
||||
ty: sint::U32, |
|
||||
memarg, |
|
||||
} => ctx.i32_load8_u(memarg.offset)?, |
|
||||
Operator::Load16 { |
|
||||
ty: sint::U32, |
|
||||
memarg, |
|
||||
} => ctx.i32_load16_u(memarg.offset)?, |
|
||||
Operator::Load8 { |
|
||||
ty: sint::I32, |
|
||||
memarg, |
|
||||
} => ctx.i32_load8_s(memarg.offset)?, |
|
||||
Operator::Load16 { |
|
||||
ty: sint::I32, |
|
||||
memarg, |
|
||||
} => ctx.i32_load16_s(memarg.offset)?, |
|
||||
Operator::Load8 { |
|
||||
ty: sint::U64, |
|
||||
memarg, |
|
||||
} => ctx.i64_load8_u(memarg.offset)?, |
|
||||
Operator::Load16 { |
|
||||
ty: sint::U64, |
|
||||
memarg, |
|
||||
} => ctx.i64_load16_u(memarg.offset)?, |
|
||||
Operator::Load8 { |
|
||||
ty: sint::I64, |
|
||||
memarg, |
|
||||
} => ctx.i64_load8_s(memarg.offset)?, |
|
||||
Operator::Load16 { |
|
||||
ty: sint::I64, |
|
||||
memarg, |
|
||||
} => ctx.i64_load16_s(memarg.offset)?, |
|
||||
Operator::Load32 { |
|
||||
sign: Signedness::Unsigned, |
|
||||
memarg, |
|
||||
} => ctx.i64_load32_u(memarg.offset)?, |
|
||||
Operator::Load32 { |
|
||||
sign: Signedness::Signed, |
|
||||
memarg, |
|
||||
} => ctx.i64_load32_s(memarg.offset)?, |
|
||||
Operator::Load { ty: I32, memarg } => ctx.i32_load(memarg.offset)?, |
|
||||
Operator::Load { ty: F32, memarg } => ctx.f32_load(memarg.offset)?, |
|
||||
Operator::Load { ty: I64, memarg } => ctx.i64_load(memarg.offset)?, |
|
||||
Operator::Load { ty: F64, memarg } => ctx.f64_load(memarg.offset)?, |
|
||||
Operator::Store8 { memarg, .. } => ctx.store8(memarg.offset)?, |
|
||||
Operator::Store16 { memarg, .. } => ctx.store16(memarg.offset)?, |
|
||||
Operator::Store32 { memarg } |
|
||||
| Operator::Store { ty: I32, memarg } |
|
||||
| Operator::Store { ty: F32, memarg } => ctx.store32(memarg.offset)?, |
|
||||
Operator::Store { ty: I64, memarg } | Operator::Store { ty: F64, memarg } => { |
|
||||
ctx.store64(memarg.offset)? |
|
||||
} |
|
||||
Operator::GlobalGet(idx) => ctx.get_global(idx)?, |
|
||||
Operator::GlobalSet(idx) => ctx.set_global(idx)?, |
|
||||
Operator::Select => { |
|
||||
ctx.select()?; |
|
||||
} |
|
||||
Operator::MemorySize { .. } => { |
|
||||
ctx.memory_size()?; |
|
||||
} |
|
||||
Operator::MemoryGrow { .. } => { |
|
||||
ctx.memory_grow()?; |
|
||||
} |
|
||||
Operator::Call { function_index } => { |
|
||||
let callee_ty = module_context.func_type(function_index); |
|
||||
|
|
||||
if let Some(defined_index) = module_context.defined_func_index(function_index) { |
|
||||
if defined_index == func_idx { |
|
||||
ctx.call_direct_self( |
|
||||
defined_index, |
|
||||
callee_ty.params().iter().map(|t| t.to_microwasm_type()), |
|
||||
callee_ty.returns().iter().map(|t| t.to_microwasm_type()), |
|
||||
)?; |
|
||||
} else { |
|
||||
ctx.call_direct( |
|
||||
function_index, |
|
||||
callee_ty.params().iter().map(|t| t.to_microwasm_type()), |
|
||||
callee_ty.returns().iter().map(|t| t.to_microwasm_type()), |
|
||||
)?; |
|
||||
} |
|
||||
} else { |
|
||||
ctx.call_direct_imported( |
|
||||
function_index, |
|
||||
callee_ty.params().iter().map(|t| t.to_microwasm_type()), |
|
||||
callee_ty.returns().iter().map(|t| t.to_microwasm_type()), |
|
||||
)?; |
|
||||
} |
|
||||
} |
|
||||
Operator::CallIndirect { |
|
||||
type_index, |
|
||||
table_index, |
|
||||
} => { |
|
||||
if table_index != 0 { |
|
||||
return Err(Error::Microwasm("table_index not equal to 0".to_string())); |
|
||||
} |
|
||||
|
|
||||
let callee_ty = module_context.signature(type_index); |
|
||||
|
|
||||
ctx.call_indirect( |
|
||||
type_index, |
|
||||
callee_ty.params().iter().map(|t| t.to_microwasm_type()), |
|
||||
callee_ty.returns().iter().map(|t| t.to_microwasm_type()), |
|
||||
)?; |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
ctx.epilogue(); |
|
||||
} |
|
||||
|
|
||||
let _ = mem::replace(&mut session.op_offset_map, op_offset_map); |
|
||||
|
|
||||
Ok(()) |
|
||||
} |
|
@ -1,24 +0,0 @@ |
|||||
#![cfg_attr(test, feature(test))] |
|
||||
|
|
||||
#[cfg(test)] |
|
||||
extern crate test; |
|
||||
|
|
||||
mod backend; |
|
||||
mod disassemble; |
|
||||
mod error; |
|
||||
mod function_body; |
|
||||
pub mod microwasm; |
|
||||
mod module; |
|
||||
mod translate_sections; |
|
||||
|
|
||||
#[cfg(test)] |
|
||||
mod benches; |
|
||||
|
|
||||
pub use crate::backend::CodeGenSession; |
|
||||
pub use crate::function_body::{ |
|
||||
translate_wasm as translate_function, NullOffsetSink, OffsetSink, Sinks, |
|
||||
}; |
|
||||
pub use crate::module::{ |
|
||||
translate, ExecutableModule, ExecutionError, ModuleContext, Signature, TranslatedModule, |
|
||||
}; |
|
||||
pub use disassemble::disassemble; |
|
File diff suppressed because it is too large
@ -1,570 +0,0 @@ |
|||||
use crate::backend::TranslatedCodeSection; |
|
||||
use crate::error::Error; |
|
||||
use crate::microwasm; |
|
||||
use crate::translate_sections; |
|
||||
use cranelift_codegen::{ |
|
||||
ir::{self, AbiParam, Signature as CraneliftSignature}, |
|
||||
isa, |
|
||||
}; |
|
||||
use memoffset::offset_of; |
|
||||
|
|
||||
use std::{convert::TryInto, mem}; |
|
||||
use thiserror::Error; |
|
||||
use wasmparser::{FuncType, Parser, Payload, Type}; |
|
||||
|
|
||||
pub trait AsValueType { |
|
||||
const TYPE: Type; |
|
||||
} |
|
||||
|
|
||||
pub trait TypeList { |
|
||||
const TYPE_LIST: &'static [Type]; |
|
||||
} |
|
||||
|
|
||||
impl<T> TypeList for T |
|
||||
where |
|
||||
T: AsValueType, |
|
||||
{ |
|
||||
const TYPE_LIST: &'static [Type] = &[T::TYPE]; |
|
||||
} |
|
||||
|
|
||||
impl AsValueType for i32 { |
|
||||
const TYPE: Type = Type::I32; |
|
||||
} |
|
||||
impl AsValueType for i64 { |
|
||||
const TYPE: Type = Type::I64; |
|
||||
} |
|
||||
impl AsValueType for u32 { |
|
||||
const TYPE: Type = Type::I32; |
|
||||
} |
|
||||
impl AsValueType for u64 { |
|
||||
const TYPE: Type = Type::I64; |
|
||||
} |
|
||||
impl AsValueType for f32 { |
|
||||
const TYPE: Type = Type::F32; |
|
||||
} |
|
||||
impl AsValueType for f64 { |
|
||||
const TYPE: Type = Type::F64; |
|
||||
} |
|
||||
|
|
||||
pub trait FunctionArgs<O> { |
|
||||
type FuncType; |
|
||||
|
|
||||
unsafe fn call(self, func: Self::FuncType, vm_ctx: *const u8) -> O; |
|
||||
fn into_func(start: *const u8) -> Self::FuncType; |
|
||||
} |
|
||||
|
|
||||
type VmCtxPtr = u64; |
|
||||
|
|
||||
macro_rules! impl_function_args { |
|
||||
($first:ident $(, $rest:ident)*) => { |
|
||||
impl<Output, $first, $($rest),*> FunctionArgs<Output> for ($first, $($rest),*) { |
|
||||
type FuncType = unsafe extern "sysv64" fn(VmCtxPtr, $first $(, $rest)*) -> Output; |
|
||||
|
|
||||
#[allow(non_snake_case)] |
|
||||
unsafe fn call(self, func: Self::FuncType, vm_ctx: *const u8) -> Output { |
|
||||
let ($first, $($rest),*) = self; |
|
||||
func(vm_ctx as VmCtxPtr, $first $(, $rest)*) |
|
||||
} |
|
||||
|
|
||||
fn into_func(start: *const u8) -> Self::FuncType { |
|
||||
unsafe { mem::transmute(start) } |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
impl<$first: AsValueType, $($rest: AsValueType),*> TypeList for ($first, $($rest),*) { |
|
||||
const TYPE_LIST: &'static [Type] = &[$first::TYPE, $($rest::TYPE),*]; |
|
||||
} |
|
||||
|
|
||||
impl_function_args!($($rest),*); |
|
||||
}; |
|
||||
() => { |
|
||||
impl<Output> FunctionArgs<Output> for () { |
|
||||
type FuncType = unsafe extern "sysv64" fn(VmCtxPtr) -> Output; |
|
||||
|
|
||||
unsafe fn call(self, func: Self::FuncType, vm_ctx: *const u8) -> Output { |
|
||||
func(vm_ctx as VmCtxPtr) |
|
||||
} |
|
||||
|
|
||||
fn into_func(start: *const u8) -> Self::FuncType { |
|
||||
unsafe { mem::transmute(start) } |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
impl TypeList for () { |
|
||||
const TYPE_LIST: &'static [Type] = &[]; |
|
||||
} |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
impl_function_args!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S); |
|
||||
|
|
||||
#[derive(Default)] |
|
||||
pub struct TranslatedModule { |
|
||||
translated_code_section: Option<TranslatedCodeSection>, |
|
||||
ctx: SimpleContext, |
|
||||
// TODO: Should we wrap this in a `Mutex` so that calling functions from multiple
|
|
||||
// threads doesn't cause data races?
|
|
||||
memory: Option<(u64, Option<u64>)>, |
|
||||
} |
|
||||
|
|
||||
impl TranslatedModule { |
|
||||
pub fn instantiate(self) -> ExecutableModule { |
|
||||
let mem_size = self.memory.map(|limits| limits.0 as u32).unwrap_or(0) as usize; |
|
||||
let mem: BoxSlice<_> = vec![0u8; mem_size * WASM_PAGE_SIZE] |
|
||||
.into_boxed_slice() |
|
||||
.into(); |
|
||||
|
|
||||
let ctx = if mem.len > 0 { |
|
||||
Some(Box::new(VmCtx { mem }) as Box<VmCtx>) |
|
||||
} else { |
|
||||
None |
|
||||
}; |
|
||||
|
|
||||
ExecutableModule { |
|
||||
module: self, |
|
||||
context: ctx, |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
pub fn disassemble(&self) { |
|
||||
self.translated_code_section |
|
||||
.as_ref() |
|
||||
.expect("no code section") |
|
||||
.disassemble(); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Error)] |
|
||||
pub enum ExecutionError { |
|
||||
#[error("function index out of bounds")] |
|
||||
FuncIndexOutOfBounds, |
|
||||
#[error("type mismatch")] |
|
||||
TypeMismatch, |
|
||||
} |
|
||||
|
|
||||
pub struct ExecutableModule { |
|
||||
module: TranslatedModule, |
|
||||
context: Option<Box<VmCtx>>, |
|
||||
} |
|
||||
|
|
||||
impl ExecutableModule { |
|
||||
/// Executes the function identified by `func_idx`.
|
|
||||
///
|
|
||||
/// # Safety
|
|
||||
///
|
|
||||
/// Executes the function _without_ checking the argument types.
|
|
||||
/// This can cause undefined memory to be accessed.
|
|
||||
pub unsafe fn execute_func_unchecked<Args: FunctionArgs<T>, T>( |
|
||||
&self, |
|
||||
func_idx: u32, |
|
||||
args: Args, |
|
||||
) -> T { |
|
||||
let code_section = self |
|
||||
.module |
|
||||
.translated_code_section |
|
||||
.as_ref() |
|
||||
.expect("no code section"); |
|
||||
let start_buf = code_section.func_start(func_idx as usize); |
|
||||
|
|
||||
args.call( |
|
||||
Args::into_func(start_buf), |
|
||||
self.context |
|
||||
.as_ref() |
|
||||
.map(|ctx| (&**ctx) as *const VmCtx as *const u8) |
|
||||
.unwrap_or(std::ptr::null()), |
|
||||
) |
|
||||
} |
|
||||
|
|
||||
pub fn execute_func<Args: FunctionArgs<T> + TypeList, T: TypeList>( |
|
||||
&self, |
|
||||
func_idx: u32, |
|
||||
args: Args, |
|
||||
) -> Result<T, ExecutionError> { |
|
||||
let module = &self.module; |
|
||||
|
|
||||
if func_idx as usize >= module.ctx.func_ty_indices.len() { |
|
||||
return Err(ExecutionError::FuncIndexOutOfBounds); |
|
||||
} |
|
||||
|
|
||||
let type_ = module.ctx.func_type(func_idx); |
|
||||
|
|
||||
// TODO: Handle "compatible" types (i.e. f32 and i32)
|
|
||||
if (&type_.params[..], &type_.returns[..]) != (Args::TYPE_LIST, T::TYPE_LIST) { |
|
||||
return Err(ExecutionError::TypeMismatch); |
|
||||
} |
|
||||
|
|
||||
Ok(unsafe { self.execute_func_unchecked(func_idx, args) }) |
|
||||
} |
|
||||
|
|
||||
pub fn disassemble(&self) { |
|
||||
self.module.disassemble(); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
struct BoxSlice<T> { |
|
||||
len: usize, |
|
||||
ptr: *mut T, |
|
||||
} |
|
||||
|
|
||||
impl<T> From<Box<[T]>> for BoxSlice<T> { |
|
||||
fn from(mut other: Box<[T]>) -> Self { |
|
||||
let out = BoxSlice { |
|
||||
len: other.len(), |
|
||||
ptr: other.as_mut_ptr(), |
|
||||
}; |
|
||||
mem::forget(other); |
|
||||
out |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
unsafe impl<T: Send> Send for BoxSlice<T> {} |
|
||||
unsafe impl<T: Sync> Sync for BoxSlice<T> {} |
|
||||
|
|
||||
impl<T> Drop for BoxSlice<T> { |
|
||||
fn drop(&mut self) { |
|
||||
unsafe { Vec::from_raw_parts(self.ptr, self.len, self.len) }; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
type BoxByteSlice = BoxSlice<u8>; |
|
||||
|
|
||||
pub struct VmCtx { |
|
||||
mem: BoxByteSlice, |
|
||||
} |
|
||||
|
|
||||
impl VmCtx { |
|
||||
pub fn offset_of_memory_ptr() -> u32 { |
|
||||
(offset_of!(VmCtx, mem) + offset_of!(BoxByteSlice, ptr)) |
|
||||
.try_into() |
|
||||
.expect("Offset exceeded size of u32") |
|
||||
} |
|
||||
|
|
||||
pub fn offset_of_memory_len() -> u32 { |
|
||||
(offset_of!(VmCtx, mem) + offset_of!(BoxByteSlice, len)) |
|
||||
.try_into() |
|
||||
.expect("Offset exceeded size of u32") |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
#[derive(Default, Debug)] |
|
||||
pub struct SimpleContext { |
|
||||
types: Vec<FuncType>, |
|
||||
func_ty_indices: Vec<u32>, |
|
||||
} |
|
||||
|
|
||||
pub const WASM_PAGE_SIZE: usize = 65_536; |
|
||||
|
|
||||
pub trait Signature { |
|
||||
type Type: SigType; |
|
||||
|
|
||||
fn params(&self) -> &[Self::Type]; |
|
||||
fn returns(&self) -> &[Self::Type]; |
|
||||
} |
|
||||
|
|
||||
pub trait SigType { |
|
||||
fn to_microwasm_type(&self) -> microwasm::SignlessType; |
|
||||
} |
|
||||
|
|
||||
impl SigType for ir::Type { |
|
||||
fn to_microwasm_type(&self) -> microwasm::SignlessType { |
|
||||
use crate::microwasm::{Size::*, Type::*}; |
|
||||
|
|
||||
if self.is_int() { |
|
||||
match self.bits() { |
|
||||
32 => Int(_32), |
|
||||
64 => Int(_64), |
|
||||
_ => unimplemented!(), |
|
||||
} |
|
||||
} else if self.is_float() { |
|
||||
match self.bits() { |
|
||||
32 => Float(_32), |
|
||||
64 => Float(_64), |
|
||||
_ => unimplemented!(), |
|
||||
} |
|
||||
} else { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
impl SigType for AbiParam { |
|
||||
fn to_microwasm_type(&self) -> microwasm::SignlessType { |
|
||||
self.value_type.to_microwasm_type() |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
impl Signature for CraneliftSignature { |
|
||||
type Type = AbiParam; |
|
||||
|
|
||||
fn params(&self) -> &[Self::Type] { |
|
||||
// TODO: We want to instead add the `VMContext` to the signature used by
|
|
||||
// cranelift, removing the special-casing from the internals.
|
|
||||
assert_eq!(self.params[0].purpose, ir::ArgumentPurpose::VMContext); |
|
||||
// `self.params[1]` should be caller vmctx
|
|
||||
assert_eq!(self.call_conv, isa::CallConv::SystemV); |
|
||||
&self.params[2..] |
|
||||
} |
|
||||
|
|
||||
fn returns(&self) -> &[Self::Type] { |
|
||||
assert_eq!(self.call_conv, isa::CallConv::SystemV); |
|
||||
&self.returns |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
impl SigType for wasmparser::Type { |
|
||||
fn to_microwasm_type(&self) -> microwasm::SignlessType { |
|
||||
microwasm::Type::from_wasm(*self).unwrap() |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
impl Signature for FuncType { |
|
||||
type Type = wasmparser::Type; |
|
||||
|
|
||||
fn params(&self) -> &[Self::Type] { |
|
||||
&*self.params |
|
||||
} |
|
||||
|
|
||||
fn returns(&self) -> &[Self::Type] { |
|
||||
&*self.returns |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
pub trait ModuleContext { |
|
||||
type Signature: Signature; |
|
||||
type GlobalType: SigType; |
|
||||
|
|
||||
fn vmctx_builtin_function(&self, index: u32) -> u32; |
|
||||
fn vmctx_vmglobal_definition(&self, index: u32) -> u32; |
|
||||
fn vmctx_vmglobal_import_from(&self, index: u32) -> u32; |
|
||||
fn vmctx_vmmemory_import_from(&self, memory_index: u32) -> u32; |
|
||||
fn vmctx_vmmemory_definition(&self, defined_memory_index: u32) -> u32; |
|
||||
fn vmctx_vmmemory_definition_base(&self, defined_memory_index: u32) -> u32; |
|
||||
fn vmctx_vmmemory_definition_current_length(&self, defined_memory_index: u32) -> u32; |
|
||||
fn vmmemory_definition_base(&self) -> u8; |
|
||||
fn vmmemory_definition_current_length(&self) -> u8; |
|
||||
fn vmctx_vmtable_import_from(&self, table_index: u32) -> u32; |
|
||||
fn vmctx_vmtable_definition(&self, defined_table_index: u32) -> u32; |
|
||||
fn vmctx_vmtable_definition_base(&self, defined_table_index: u32) -> u32; |
|
||||
fn vmctx_vmtable_definition_current_elements(&self, defined_table_index: u32) -> u32; |
|
||||
fn vmctx_vmfunction_import_body(&self, func_index: u32) -> u32; |
|
||||
fn vmctx_vmfunction_import_vmctx(&self, func_index: u32) -> u32; |
|
||||
fn vmtable_definition_base(&self) -> u8; |
|
||||
fn vmtable_definition_current_elements(&self) -> u8; |
|
||||
fn vmctx_vmshared_signature_id(&self, signature_idx: u32) -> u32; |
|
||||
fn vmcaller_checked_anyfunc_type_index(&self) -> u8; |
|
||||
fn vmcaller_checked_anyfunc_func_ptr(&self) -> u8; |
|
||||
fn vmcaller_checked_anyfunc_vmctx(&self) -> u8; |
|
||||
fn size_of_vmcaller_checked_anyfunc(&self) -> u8; |
|
||||
|
|
||||
fn defined_table_index(&self, table_index: u32) -> Option<u32>; |
|
||||
fn defined_memory_index(&self, index: u32) -> Option<u32>; |
|
||||
|
|
||||
fn defined_global_index(&self, global_index: u32) -> Option<u32>; |
|
||||
fn global_type(&self, global_index: u32) -> &Self::GlobalType; |
|
||||
|
|
||||
fn func_type_index(&self, func_idx: u32) -> u32; |
|
||||
fn signature(&self, index: u32) -> &Self::Signature; |
|
||||
|
|
||||
fn func_index(&self, defined_func_index: u32) -> u32; |
|
||||
fn defined_func_index(&self, func_index: u32) -> Option<u32>; |
|
||||
|
|
||||
fn defined_func_type(&self, defined_func_idx: u32) -> &Self::Signature { |
|
||||
self.func_type(self.func_index(defined_func_idx)) |
|
||||
} |
|
||||
|
|
||||
fn func_type(&self, func_idx: u32) -> &Self::Signature { |
|
||||
self.signature(self.func_type_index(func_idx)) |
|
||||
} |
|
||||
|
|
||||
fn emit_memory_bounds_check(&self) -> bool { |
|
||||
true |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
impl ModuleContext for SimpleContext { |
|
||||
type Signature = FuncType; |
|
||||
type GlobalType = wasmparser::Type; |
|
||||
|
|
||||
// TODO: We don't support external functions yet
|
|
||||
fn func_index(&self, func_idx: u32) -> u32 { |
|
||||
func_idx |
|
||||
} |
|
||||
|
|
||||
fn defined_func_index(&self, func_idx: u32) -> Option<u32> { |
|
||||
Some(func_idx) |
|
||||
} |
|
||||
|
|
||||
fn func_type_index(&self, func_idx: u32) -> u32 { |
|
||||
self.func_ty_indices[func_idx as usize] |
|
||||
} |
|
||||
|
|
||||
fn defined_global_index(&self, _index: u32) -> Option<u32> { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn global_type(&self, _global_index: u32) -> &Self::GlobalType { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn signature(&self, index: u32) -> &Self::Signature { |
|
||||
&self.types[index as usize] |
|
||||
} |
|
||||
|
|
||||
fn vmctx_vmglobal_definition(&self, _index: u32) -> u32 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn vmctx_vmglobal_import_from(&self, _index: u32) -> u32 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn defined_memory_index(&self, _index: u32) -> Option<u32> { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn defined_table_index(&self, index: u32) -> Option<u32> { |
|
||||
Some(index) |
|
||||
} |
|
||||
|
|
||||
fn vmctx_builtin_function(&self, _index: u32) -> u32 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn vmctx_vmfunction_import_body(&self, _func_index: u32) -> u32 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
fn vmctx_vmfunction_import_vmctx(&self, _func_index: u32) -> u32 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn vmctx_vmtable_import_from(&self, _table_index: u32) -> u32 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn vmctx_vmmemory_definition(&self, _defined_memory_index: u32) -> u32 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
fn vmctx_vmmemory_import_from(&self, _memory_index: u32) -> u32 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
fn vmmemory_definition_base(&self) -> u8 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
fn vmmemory_definition_current_length(&self) -> u8 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
fn vmctx_vmmemory_definition_base(&self, defined_memory_index: u32) -> u32 { |
|
||||
assert_eq!(defined_memory_index, 0); |
|
||||
VmCtx::offset_of_memory_ptr() |
|
||||
} |
|
||||
|
|
||||
fn vmctx_vmmemory_definition_current_length(&self, defined_memory_index: u32) -> u32 { |
|
||||
assert_eq!(defined_memory_index, 0); |
|
||||
VmCtx::offset_of_memory_len() |
|
||||
} |
|
||||
|
|
||||
fn vmctx_vmtable_definition(&self, _defined_table_index: u32) -> u32 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn vmctx_vmtable_definition_base(&self, _defined_table_index: u32) -> u32 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn vmctx_vmtable_definition_current_elements(&self, _defined_table_index: u32) -> u32 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn vmtable_definition_base(&self) -> u8 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn vmtable_definition_current_elements(&self) -> u8 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn vmcaller_checked_anyfunc_vmctx(&self) -> u8 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn vmcaller_checked_anyfunc_type_index(&self) -> u8 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn vmcaller_checked_anyfunc_func_ptr(&self) -> u8 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn size_of_vmcaller_checked_anyfunc(&self) -> u8 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn vmctx_vmshared_signature_id(&self, _signature_idx: u32) -> u32 { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
// TODO: type of a global
|
|
||||
} |
|
||||
|
|
||||
pub fn translate(data: &[u8]) -> Result<ExecutableModule, Error> { |
|
||||
translate_only(data).map(|m| m.instantiate()) |
|
||||
} |
|
||||
|
|
||||
/// Translate from a slice of bytes holding a wasm module.
|
|
||||
pub fn translate_only(data: &[u8]) -> Result<TranslatedModule, Error> { |
|
||||
let mut output = TranslatedModule::default(); |
|
||||
|
|
||||
for payload in Parser::new(0).parse_all(data) { |
|
||||
match payload? { |
|
||||
Payload::TypeSection(s) => output.ctx.types = translate_sections::type_(s)?, |
|
||||
Payload::ImportSection(s) => translate_sections::import(s)?, |
|
||||
Payload::FunctionSection(s) => { |
|
||||
output.ctx.func_ty_indices = translate_sections::function(s)?; |
|
||||
} |
|
||||
Payload::TableSection(s) => { |
|
||||
translate_sections::table(s)?; |
|
||||
} |
|
||||
Payload::MemorySection(s) => { |
|
||||
let mem = translate_sections::memory(s)?; |
|
||||
|
|
||||
if mem.len() > 1 { |
|
||||
return Err(Error::Input( |
|
||||
"Multiple memory sections not yet implemented".to_string(), |
|
||||
)); |
|
||||
} |
|
||||
|
|
||||
if !mem.is_empty() { |
|
||||
let mem = mem[0]; |
|
||||
if Some(mem.initial) != mem.maximum { |
|
||||
return Err(Error::Input( |
|
||||
"Custom memory limits not supported in lightbeam".to_string(), |
|
||||
)); |
|
||||
} |
|
||||
output.memory = Some((mem.initial, mem.maximum)); |
|
||||
} |
|
||||
} |
|
||||
Payload::GlobalSection(s) => { |
|
||||
translate_sections::global(s)?; |
|
||||
} |
|
||||
Payload::ExportSection(s) => { |
|
||||
translate_sections::export(s)?; |
|
||||
} |
|
||||
Payload::StartSection { func, .. } => { |
|
||||
translate_sections::start(func)?; |
|
||||
} |
|
||||
Payload::ElementSection(s) => { |
|
||||
translate_sections::element(s)?; |
|
||||
} |
|
||||
Payload::DataSection(s) => { |
|
||||
translate_sections::data(s)?; |
|
||||
} |
|
||||
Payload::CodeSectionStart { .. } |
|
||||
| Payload::CustomSection { .. } |
|
||||
| Payload::Version { .. } => {} |
|
||||
|
|
||||
other => unimplemented!("can't translate {:?}", other), |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
Ok(output) |
|
||||
} |
|
@ -1,124 +0,0 @@ |
|||||
use crate::backend::TranslatedCodeSection; |
|
||||
use crate::error::Error; |
|
||||
use crate::module::SimpleContext; |
|
||||
use cranelift_codegen::{binemit, ir}; |
|
||||
use wasmparser::{ |
|
||||
CodeSectionReader, DataSectionReader, ElementSectionReader, ExportSectionReader, FuncType, |
|
||||
FunctionSectionReader, GlobalSectionReader, ImportSectionReader, MemorySectionReader, |
|
||||
MemoryType, TableSectionReader, TableType, TypeDef, TypeSectionReader, |
|
||||
}; |
|
||||
|
|
||||
/// Parses the Type section of the wasm module.
|
|
||||
pub fn type_(types_reader: TypeSectionReader) -> Result<Vec<FuncType>, Error> { |
|
||||
types_reader |
|
||||
.into_iter() |
|
||||
.map(|r| match r { |
|
||||
Ok(TypeDef::Func(ft)) => Ok(ft), |
|
||||
Ok(_) => unimplemented!("module linking is not implemented yet"), |
|
||||
Err(e) => Err(e.into()), |
|
||||
}) |
|
||||
.collect() |
|
||||
} |
|
||||
|
|
||||
/// Parses the Import section of the wasm module.
|
|
||||
pub fn import(imports: ImportSectionReader) -> Result<(), Error> { |
|
||||
for entry in imports { |
|
||||
entry?; // TODO
|
|
||||
} |
|
||||
Ok(()) |
|
||||
} |
|
||||
|
|
||||
/// Parses the Function section of the wasm module.
|
|
||||
pub fn function(functions: FunctionSectionReader) -> Result<Vec<u32>, Error> { |
|
||||
functions |
|
||||
.into_iter() |
|
||||
.map(|r| r.map_err(Into::into)) |
|
||||
.collect() |
|
||||
} |
|
||||
|
|
||||
/// Parses the Table section of the wasm module.
|
|
||||
pub fn table(tables: TableSectionReader) -> Result<Vec<TableType>, Error> { |
|
||||
tables.into_iter().map(|r| r.map_err(Into::into)).collect() |
|
||||
} |
|
||||
|
|
||||
/// Parses the Memory section of the wasm module.
|
|
||||
pub fn memory(memories: MemorySectionReader) -> Result<Vec<MemoryType>, Error> { |
|
||||
memories |
|
||||
.into_iter() |
|
||||
.map(|r| r.map_err(Into::into)) |
|
||||
.collect() |
|
||||
} |
|
||||
|
|
||||
/// Parses the Global section of the wasm module.
|
|
||||
pub fn global(globals: GlobalSectionReader) -> Result<(), Error> { |
|
||||
for entry in globals { |
|
||||
entry?; // TODO
|
|
||||
} |
|
||||
Ok(()) |
|
||||
} |
|
||||
|
|
||||
/// Parses the Export section of the wasm module.
|
|
||||
pub fn export(exports: ExportSectionReader) -> Result<(), Error> { |
|
||||
for entry in exports { |
|
||||
entry?; // TODO
|
|
||||
} |
|
||||
Ok(()) |
|
||||
} |
|
||||
|
|
||||
/// Parses the Start section of the wasm module.
|
|
||||
pub fn start(_index: u32) -> Result<(), Error> { |
|
||||
// TODO
|
|
||||
Ok(()) |
|
||||
} |
|
||||
|
|
||||
/// Parses the Element section of the wasm module.
|
|
||||
pub fn element(elements: ElementSectionReader) -> Result<(), Error> { |
|
||||
for entry in elements { |
|
||||
entry?; |
|
||||
} |
|
||||
|
|
||||
Ok(()) |
|
||||
} |
|
||||
|
|
||||
struct UnimplementedRelocSink; |
|
||||
|
|
||||
impl binemit::RelocSink for UnimplementedRelocSink { |
|
||||
fn reloc_external( |
|
||||
&mut self, |
|
||||
_: binemit::CodeOffset, |
|
||||
_: ir::SourceLoc, |
|
||||
_: binemit::Reloc, |
|
||||
_: &ir::ExternalName, |
|
||||
_: binemit::Addend, |
|
||||
) { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn reloc_constant(&mut self, _: binemit::CodeOffset, _: binemit::Reloc, _: ir::ConstantOffset) { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn reloc_jt(&mut self, _: binemit::CodeOffset, _: binemit::Reloc, _: ir::JumpTable) { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
/// Parses the Code section of the wasm module.
|
|
||||
#[allow(dead_code)] |
|
||||
pub fn code( |
|
||||
_code: CodeSectionReader, |
|
||||
_translation_ctx: &SimpleContext, |
|
||||
) -> Result<TranslatedCodeSection, Error> { |
|
||||
// TODO: Remove the Lightbeam harness entirely, this is just to make this compile.
|
|
||||
// We do all our testing through Wasmtime now, there's no reason to duplicate
|
|
||||
// writing a WebAssembly environment in Lightbeam too.
|
|
||||
unimplemented!("Incomplete migration to wasm-reader"); |
|
||||
} |
|
||||
|
|
||||
/// Parses the Data section of the wasm module.
|
|
||||
pub fn data(data: DataSectionReader) -> Result<(), Error> { |
|
||||
for entry in data { |
|
||||
entry?; // TODO
|
|
||||
} |
|
||||
Ok(()) |
|
||||
} |
|
@ -1,654 +0,0 @@ |
|||||
use lazy_static::lazy_static; |
|
||||
use lightbeam::{translate, ExecutableModule}; |
|
||||
use quickcheck::quickcheck; |
|
||||
|
|
||||
fn translate_wat(wat: &str) -> ExecutableModule { |
|
||||
let wasm = wat::parse_str(wat).unwrap(); |
|
||||
let compiled = translate(&wasm).unwrap(); |
|
||||
compiled |
|
||||
} |
|
||||
|
|
||||
mod op32 { |
|
||||
use super::{lazy_static, quickcheck, translate_wat, ExecutableModule}; |
|
||||
|
|
||||
macro_rules! binop_test { |
|
||||
($op:ident, $func:expr) => { |
|
||||
mod $op { |
|
||||
use super::{lazy_static, quickcheck, translate_wat, ExecutableModule}; |
|
||||
use std::sync::Once; |
|
||||
|
|
||||
const OP: &str = stringify!($op); |
|
||||
|
|
||||
lazy_static! { |
|
||||
static ref AS_PARAMS: ExecutableModule = translate_wat(&format!( |
|
||||
"(module (func (param i32) (param i32) (result i32) |
|
||||
(i32.{op} (get_local 0) (get_local 1))))", |
|
||||
op = OP |
|
||||
)); |
|
||||
} |
|
||||
|
|
||||
quickcheck! { |
|
||||
fn as_params(a: i32, b: i32) -> bool { |
|
||||
AS_PARAMS.execute_func::<(i32, i32), i32>(0, (a, b)) == Ok($func(a, b)) |
|
||||
} |
|
||||
|
|
||||
fn lit_lit(a: i32, b: i32) -> bool { |
|
||||
let translated = translate_wat(&format!(" |
|
||||
(module (func (result i32) |
|
||||
(i32.{op} (i32.const {left}) (i32.const {right})))) |
|
||||
", op = OP, left = a, right = b)); |
|
||||
static ONCE: Once = Once::new(); |
|
||||
ONCE.call_once(|| translated.disassemble()); |
|
||||
|
|
||||
translated.execute_func::<(), i32>(0, ()) == Ok($func(a, b)) |
|
||||
} |
|
||||
|
|
||||
fn lit_reg(a: i32, b: i32) -> bool { |
|
||||
let translated = translate_wat(&format!(" |
|
||||
(module (func (param i32) (result i32) |
|
||||
(i32.{op} (i32.const {left}) (get_local 0)))) |
|
||||
", op = OP, left = a)); |
|
||||
static ONCE: Once = Once::new(); |
|
||||
ONCE.call_once(|| translated.disassemble()); |
|
||||
|
|
||||
translated.execute_func::<(i32,), i32>(0, (b,)) == Ok($func(a, b)) |
|
||||
} |
|
||||
|
|
||||
fn reg_lit(a: i32, b: i32) -> bool { |
|
||||
let translated = translate_wat(&format!(" |
|
||||
(module (func (param i32) (result i32) |
|
||||
(i32.{op} (get_local 0) (i32.const {right})))) |
|
||||
", op = OP, right = b)); |
|
||||
static ONCE: Once = Once::new(); |
|
||||
ONCE.call_once(|| translated.disassemble()); |
|
||||
|
|
||||
translated.execute_func::<(i32,), i32>(0, (a,)) == Ok($func(a, b)) |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
macro_rules! unop_test { |
|
||||
($name:ident, $func:expr) => { |
|
||||
mod $name { |
|
||||
use super::{lazy_static, quickcheck, translate_wat, ExecutableModule}; |
|
||||
use std::sync::Once; |
|
||||
|
|
||||
lazy_static! { |
|
||||
static ref AS_PARAM: ExecutableModule = translate_wat(concat!( |
|
||||
"(module (func (param i32) (result i32) |
|
||||
(i32.", |
|
||||
stringify!($name), |
|
||||
" (get_local 0))))" |
|
||||
),); |
|
||||
} |
|
||||
|
|
||||
quickcheck! { |
|
||||
fn as_param(a: u32) -> bool { |
|
||||
AS_PARAM.execute_func::<(u32,), u32>(0, (a,)) == Ok($func(a)) |
|
||||
} |
|
||||
|
|
||||
fn lit(a: u32) -> bool { |
|
||||
let translated = translate_wat(&format!(concat!(" |
|
||||
(module (func (result i32) |
|
||||
(i32.",stringify!($name)," (i32.const {val})))) |
|
||||
"), val = a)); |
|
||||
static ONCE: Once = Once::new(); |
|
||||
ONCE.call_once(|| translated.disassemble()); |
|
||||
|
|
||||
translated.execute_func::<(), u32>(0, ()) == Ok($func(a)) |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
unop_test!(clz, u32::leading_zeros); |
|
||||
unop_test!(ctz, u32::trailing_zeros); |
|
||||
unop_test!(popcnt, u32::count_ones); |
|
||||
unop_test!(eqz, |a: u32| if a == 0 { 1 } else { 0 }); |
|
||||
|
|
||||
binop_test!(add, i32::wrapping_add); |
|
||||
binop_test!(sub, i32::wrapping_sub); |
|
||||
binop_test!(and, std::ops::BitAnd::bitand); |
|
||||
binop_test!(or, std::ops::BitOr::bitor); |
|
||||
binop_test!(xor, std::ops::BitXor::bitxor); |
|
||||
binop_test!(mul, i32::wrapping_mul); |
|
||||
binop_test!(eq, |a, b| if a == b { 1 } else { 0 }); |
|
||||
binop_test!(ne, |a, b| if a != b { 1 } else { 0 }); |
|
||||
binop_test!(lt_u, |a, b| if (a as u32) < (b as u32) { 1 } else { 0 }); |
|
||||
binop_test!(le_u, |a, b| if (a as u32) <= (b as u32) { 1 } else { 0 }); |
|
||||
binop_test!(gt_u, |a, b| if (a as u32) > (b as u32) { 1 } else { 0 }); |
|
||||
binop_test!(ge_u, |a, b| if (a as u32) >= (b as u32) { 1 } else { 0 }); |
|
||||
binop_test!(lt_s, |a, b| if a < b { 1 } else { 0 }); |
|
||||
binop_test!(le_s, |a, b| if a <= b { 1 } else { 0 }); |
|
||||
binop_test!(gt_s, |a, b| if a > b { 1 } else { 0 }); |
|
||||
binop_test!(ge_s, |a, b| if a >= b { 1 } else { 0 }); |
|
||||
binop_test!(shl, |a, b| (a as i32).wrapping_shl(b as _)); |
|
||||
binop_test!(shr_s, |a, b| (a as i32).wrapping_shr(b as _)); |
|
||||
binop_test!(shr_u, |a, b| (a as u32).wrapping_shr(b as _) as i32); |
|
||||
binop_test!(rotl, |a, b| (a as u32).rotate_left(b as _) as i32); |
|
||||
binop_test!(rotr, |a, b| (a as u32).rotate_right(b as _) as i32); |
|
||||
} |
|
||||
|
|
||||
mod op64 { |
|
||||
use super::{lazy_static, quickcheck, translate_wat, ExecutableModule}; |
|
||||
|
|
||||
macro_rules! binop_test { |
|
||||
($op:ident, $func:expr) => { |
|
||||
binop_test!($op, $func, i64); |
|
||||
}; |
|
||||
($op:ident, $func:expr, $retty:ident) => { |
|
||||
mod $op { |
|
||||
use super::{translate_wat, ExecutableModule, quickcheck, lazy_static}; |
|
||||
|
|
||||
const RETTY: &str = stringify!($retty); |
|
||||
const OP: &str = stringify!($op); |
|
||||
|
|
||||
lazy_static! { |
|
||||
static ref AS_PARAMS: ExecutableModule = translate_wat(&format!(" |
|
||||
(module (func (param i64) (param i64) (result {retty}) |
|
||||
(i64.{op} (get_local 0) (get_local 1)))) |
|
||||
", retty = RETTY, op = OP)); |
|
||||
} |
|
||||
|
|
||||
quickcheck! { |
|
||||
fn as_params(a: i64, b: i64) -> bool { |
|
||||
AS_PARAMS.execute_func::<(i64, i64), $retty>(0, (a, b)) == Ok($func(a, b) as $retty) |
|
||||
} |
|
||||
|
|
||||
fn lit_lit(a: i64, b: i64) -> bool { |
|
||||
translate_wat(&format!(" |
|
||||
(module (func (result {retty}) |
|
||||
(i64.{op} (i64.const {left}) (i64.const {right})))) |
|
||||
", retty = RETTY, op = OP, left = a, right = b)).execute_func::<(), $retty>(0, ()) == Ok($func(a, b) as $retty) |
|
||||
} |
|
||||
|
|
||||
fn lit_reg(a: i64, b: i64) -> bool { |
|
||||
use std::sync::Once; |
|
||||
|
|
||||
let translated = translate_wat(&format!(" |
|
||||
(module (func (param i64) (result {retty}) |
|
||||
(i64.{op} (i64.const {left}) (get_local 0)))) |
|
||||
", retty = RETTY, op = OP, left = a)); |
|
||||
static ONCE: Once = Once::new(); |
|
||||
ONCE.call_once(|| translated.disassemble()); |
|
||||
|
|
||||
translated.execute_func::<(i64,), $retty>(0, (b,)) == Ok($func(a, b) as $retty) |
|
||||
} |
|
||||
|
|
||||
fn reg_lit(a: i64, b: i64) -> bool { |
|
||||
use std::sync::Once; |
|
||||
|
|
||||
let translated = translate_wat(&format!(" |
|
||||
(module (func (param i64) (result {retty}) |
|
||||
(i64.{op} (get_local 0) (i64.const {right})))) |
|
||||
", retty = RETTY, op = OP, right = b)); |
|
||||
static ONCE: Once = Once::new(); |
|
||||
ONCE.call_once(|| translated.disassemble()); |
|
||||
|
|
||||
translated.execute_func::<(i64,), $retty>(0, (a,)) == Ok($func(a, b) as $retty) |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
macro_rules! unop_test { |
|
||||
($name:ident, $func:expr) => { |
|
||||
unop_test!($name, $func, i64); |
|
||||
}; |
|
||||
($name:ident, $func:expr, $out_ty:ty) => { |
|
||||
mod $name { |
|
||||
use super::{lazy_static, quickcheck, translate_wat, ExecutableModule}; |
|
||||
use std::sync::Once; |
|
||||
|
|
||||
lazy_static! { |
|
||||
static ref AS_PARAM: ExecutableModule = translate_wat(concat!( |
|
||||
"(module (func (param i64) (result ", |
|
||||
stringify!($out_ty), |
|
||||
") |
|
||||
(i64.", |
|
||||
stringify!($name), |
|
||||
" (get_local 0))))" |
|
||||
),); |
|
||||
} |
|
||||
|
|
||||
quickcheck! { |
|
||||
fn as_param(a: u64) -> bool { |
|
||||
AS_PARAM.execute_func::<(u64,), $out_ty>(0, (a,)) == Ok($func(a)) |
|
||||
} |
|
||||
|
|
||||
fn lit(a: u64) -> bool { |
|
||||
let translated = translate_wat(&format!(concat!(" |
|
||||
(module (func (result ",stringify!($out_ty),") |
|
||||
(i64.",stringify!($name)," (i64.const {val})))) |
|
||||
"), val = a)); |
|
||||
static ONCE: Once = Once::new(); |
|
||||
ONCE.call_once(|| translated.disassemble()); |
|
||||
|
|
||||
translated.execute_func::<(), $out_ty>(0, ()) == Ok($func(a)) |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
unop_test!(clz, |a: u64| a.leading_zeros() as _); |
|
||||
unop_test!(ctz, |a: u64| a.trailing_zeros() as _); |
|
||||
unop_test!(popcnt, |a: u64| a.count_ones() as _); |
|
||||
unop_test!(eqz, |a: u64| if a == 0 { 1 } else { 0 }, i32); |
|
||||
|
|
||||
binop_test!(add, i64::wrapping_add); |
|
||||
binop_test!(sub, i64::wrapping_sub); |
|
||||
binop_test!(and, std::ops::BitAnd::bitand); |
|
||||
binop_test!(or, std::ops::BitOr::bitor); |
|
||||
binop_test!(xor, std::ops::BitXor::bitxor); |
|
||||
binop_test!(mul, i64::wrapping_mul); |
|
||||
binop_test!(eq, |a, b| if a == b { 1 } else { 0 }, i32); |
|
||||
binop_test!(ne, |a, b| if a != b { 1 } else { 0 }, i32); |
|
||||
binop_test!( |
|
||||
lt_u, |
|
||||
|a, b| if (a as u64) < (b as u64) { 1 } else { 0 }, |
|
||||
i32 |
|
||||
); |
|
||||
binop_test!( |
|
||||
le_u, |
|
||||
|a, b| if (a as u64) <= (b as u64) { 1 } else { 0 }, |
|
||||
i32 |
|
||||
); |
|
||||
binop_test!( |
|
||||
gt_u, |
|
||||
|a, b| if (a as u64) > (b as u64) { 1 } else { 0 }, |
|
||||
i32 |
|
||||
); |
|
||||
binop_test!( |
|
||||
ge_u, |
|
||||
|a, b| if (a as u64) >= (b as u64) { 1 } else { 0 }, |
|
||||
i32 |
|
||||
); |
|
||||
binop_test!(lt_s, |a, b| if a < b { 1 } else { 0 }, i32); |
|
||||
binop_test!(le_s, |a, b| if a <= b { 1 } else { 0 }, i32); |
|
||||
binop_test!(gt_s, |a, b| if a > b { 1 } else { 0 }, i32); |
|
||||
binop_test!(ge_s, |a, b| if a >= b { 1 } else { 0 }, i32); |
|
||||
binop_test!(shl, |a, b| (a as i64).wrapping_shl(b as _)); |
|
||||
binop_test!(shr_s, |a, b| (a as i64).wrapping_shr(b as _)); |
|
||||
binop_test!(shr_u, |a, b| (a as u64).wrapping_shr(b as _) as i64); |
|
||||
binop_test!(rotl, |a, b| (a as u64).rotate_left(b as _) as i64); |
|
||||
binop_test!(rotr, |a, b| (a as u64).rotate_right(b as _) as i64); |
|
||||
} |
|
||||
|
|
||||
mod opf32 { |
|
||||
use super::{lazy_static, quickcheck, translate_wat, ExecutableModule}; |
|
||||
|
|
||||
macro_rules! binop_test { |
|
||||
($op:ident, $func:expr) => { |
|
||||
binop_test!($op, $func, f32); |
|
||||
}; |
|
||||
($op:ident, $func:expr, $retty:ident) => { |
|
||||
mod $op { |
|
||||
use super::{translate_wat, ExecutableModule, quickcheck, lazy_static}; |
|
||||
|
|
||||
const RETTY: &str = stringify!($retty); |
|
||||
const OP: &str = stringify!($op); |
|
||||
|
|
||||
lazy_static! { |
|
||||
static ref AS_PARAMS: ExecutableModule = translate_wat(&format!(" |
|
||||
(module (func (param f32) (param f32) (result {retty}) |
|
||||
(f32.{op} (get_local 0) (get_local 1)))) |
|
||||
", retty = RETTY, op = OP)); |
|
||||
} |
|
||||
|
|
||||
quickcheck! { |
|
||||
fn as_params(a: f32, b: f32) -> bool { |
|
||||
AS_PARAMS.execute_func::<(f32, f32), $retty>(0, (a, b)) == Ok($func(a, b) as $retty) |
|
||||
} |
|
||||
|
|
||||
fn lit_lit(a: f32, b: f32) -> bool { |
|
||||
translate_wat(&format!(" |
|
||||
(module (func (result {retty}) |
|
||||
(f32.{op} (f32.const {left}) (f32.const {right})))) |
|
||||
", retty = RETTY, op = OP, left = a, right = b)).execute_func::<(), $retty>(0, ()) == Ok($func(a, b) as $retty) |
|
||||
} |
|
||||
|
|
||||
fn lit_reg(a: f32, b: f32) -> bool { |
|
||||
use std::sync::Once; |
|
||||
|
|
||||
let translated = translate_wat(&format!(" |
|
||||
(module (func (param f32) (result {retty}) |
|
||||
(f32.{op} (f32.const {left}) (get_local 0)))) |
|
||||
", retty = RETTY, op = OP, left = a)); |
|
||||
static ONCE: Once = Once::new(); |
|
||||
ONCE.call_once(|| translated.disassemble()); |
|
||||
|
|
||||
translated.execute_func::<(f32,), $retty>(0, (b,)) == Ok($func(a, b) as $retty) |
|
||||
} |
|
||||
|
|
||||
fn reg_lit(a: f32, b: f32) -> bool { |
|
||||
use std::sync::Once; |
|
||||
|
|
||||
let translated = translate_wat(&format!(" |
|
||||
(module (func (param f32) (result {retty}) |
|
||||
(f32.{op} (get_local 0) (f32.const {right})))) |
|
||||
", retty = RETTY, op = OP, right = b)); |
|
||||
static ONCE: Once = Once::new(); |
|
||||
ONCE.call_once(|| translated.disassemble()); |
|
||||
|
|
||||
translated.execute_func::<(f32,), $retty>(0, (a,)) == Ok($func(a, b) as $retty) |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
macro_rules! unop_test { |
|
||||
($name:ident, $func:expr) => { |
|
||||
unop_test!($name, $func, f32); |
|
||||
}; |
|
||||
($name:ident, $func:expr, $out_ty:ty) => { |
|
||||
mod $name { |
|
||||
use super::{lazy_static, quickcheck, translate_wat, ExecutableModule}; |
|
||||
use std::sync::Once; |
|
||||
|
|
||||
lazy_static! { |
|
||||
static ref AS_PARAM: ExecutableModule = translate_wat(concat!( |
|
||||
"(module (func (param f32) (result ", |
|
||||
stringify!($out_ty), |
|
||||
") |
|
||||
(f32.", |
|
||||
stringify!($name), |
|
||||
" (get_local 0))))" |
|
||||
),); |
|
||||
} |
|
||||
|
|
||||
quickcheck! { |
|
||||
fn as_param(a: f32) -> bool { |
|
||||
static ONCE: Once = Once::new(); |
|
||||
ONCE.call_once(|| AS_PARAM.disassemble()); |
|
||||
AS_PARAM.execute_func::<(f32,), $out_ty>(0, (a,)) == Ok($func(a)) |
|
||||
} |
|
||||
|
|
||||
fn lit(a: f32) -> bool { |
|
||||
let translated = translate_wat(&format!(concat!(" |
|
||||
(module (func (result ",stringify!($out_ty),") |
|
||||
(f32.",stringify!($name)," (f32.const {val})))) |
|
||||
"), val = a)); |
|
||||
static ONCE: Once = Once::new(); |
|
||||
ONCE.call_once(|| translated.disassemble()); |
|
||||
|
|
||||
translated.execute_func::<(), $out_ty>(0, ()) == Ok($func(a)) |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
binop_test!(add, |a, b| a + b); |
|
||||
binop_test!(mul, |a, b| a * b); |
|
||||
binop_test!(sub, |a, b| a - b); |
|
||||
binop_test!(gt, |a, b| a > b, i32); |
|
||||
binop_test!(lt, |a, b| a < b, i32); |
|
||||
binop_test!(ge, |a, b| a >= b, i32); |
|
||||
binop_test!(le, |a, b| a <= b, i32); |
|
||||
|
|
||||
unop_test!(neg, |a: f32| -a); |
|
||||
unop_test!(abs, |a: f32| a.abs()); |
|
||||
} |
|
||||
|
|
||||
mod opf64 { |
|
||||
use super::{lazy_static, quickcheck, translate_wat, ExecutableModule}; |
|
||||
|
|
||||
macro_rules! binop_test { |
|
||||
($op:ident, $func:expr) => { |
|
||||
binop_test!($op, $func, f64); |
|
||||
}; |
|
||||
($op:ident, $func:expr, $retty:ident) => { |
|
||||
mod $op { |
|
||||
use super::{translate_wat, ExecutableModule, quickcheck, lazy_static}; |
|
||||
|
|
||||
const RETTY: &str = stringify!($retty); |
|
||||
const OP: &str = stringify!($op); |
|
||||
|
|
||||
lazy_static! { |
|
||||
static ref AS_PARAMS: ExecutableModule = translate_wat(&format!(" |
|
||||
(module (func (param f64) (param f64) (result {retty}) |
|
||||
(f64.{op} (get_local 0) (get_local 1)))) |
|
||||
", retty = RETTY, op = OP)); |
|
||||
} |
|
||||
|
|
||||
quickcheck! { |
|
||||
fn as_params(a: f64, b: f64) -> bool { |
|
||||
AS_PARAMS.execute_func::<(f64, f64), $retty>(0, (a, b)) == Ok($func(a, b) as $retty) |
|
||||
} |
|
||||
|
|
||||
fn lit_lit(a: f64, b: f64) -> bool { |
|
||||
translate_wat(&format!(" |
|
||||
(module (func (result {retty}) |
|
||||
(f64.{op} (f64.const {left}) (f64.const {right})))) |
|
||||
", retty = RETTY, op = OP, left = a, right = b)).execute_func::<(), $retty>(0, ()) == Ok($func(a, b) as $retty) |
|
||||
} |
|
||||
|
|
||||
fn lit_reg(a: f64, b: f64) -> bool { |
|
||||
use std::sync::Once; |
|
||||
|
|
||||
let translated = translate_wat(&format!(" |
|
||||
(module (func (param f64) (result {retty}) |
|
||||
(f64.{op} (f64.const {left}) (get_local 0)))) |
|
||||
", retty = RETTY, op = OP, left = a)); |
|
||||
static ONCE: Once = Once::new(); |
|
||||
ONCE.call_once(|| translated.disassemble()); |
|
||||
|
|
||||
translated.execute_func::<(f64,), $retty>(0, (b,)) == Ok($func(a, b) as $retty) |
|
||||
} |
|
||||
|
|
||||
fn reg_lit(a: f64, b: f64) -> bool { |
|
||||
use std::sync::Once; |
|
||||
|
|
||||
let translated = translate_wat(&format!(" |
|
||||
(module (func (param f64) (result {retty}) |
|
||||
(f64.{op} (get_local 0) (f64.const {right})))) |
|
||||
", retty = RETTY, op = OP, right = b)); |
|
||||
static ONCE: Once = Once::new(); |
|
||||
ONCE.call_once(|| translated.disassemble()); |
|
||||
|
|
||||
translated.execute_func::<(f64,), $retty>(0, (a,)) == Ok($func(a, b) as $retty) |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
macro_rules! unop_test { |
|
||||
($name:ident, $func:expr) => { |
|
||||
unop_test!($name, $func, f64); |
|
||||
}; |
|
||||
($name:ident, $func:expr, $out_ty:ty) => { |
|
||||
mod $name { |
|
||||
use super::{lazy_static, quickcheck, translate_wat, ExecutableModule}; |
|
||||
use std::sync::Once; |
|
||||
|
|
||||
lazy_static! { |
|
||||
static ref AS_PARAM: ExecutableModule = translate_wat(concat!( |
|
||||
"(module (func (param f64) (result ", |
|
||||
stringify!($out_ty), |
|
||||
") |
|
||||
(f64.", |
|
||||
stringify!($name), |
|
||||
" (get_local 0))))" |
|
||||
),); |
|
||||
} |
|
||||
|
|
||||
quickcheck! { |
|
||||
fn as_param(a: f64) -> bool { |
|
||||
static ONCE: Once = Once::new(); |
|
||||
ONCE.call_once(|| AS_PARAM.disassemble()); |
|
||||
AS_PARAM.execute_func::<(f64,), $out_ty>(0, (a,)) == Ok($func(a)) |
|
||||
} |
|
||||
|
|
||||
fn lit(a: f64) -> bool { |
|
||||
let translated = translate_wat(&format!(concat!(" |
|
||||
(module (func (result ",stringify!($out_ty),") |
|
||||
(f64.",stringify!($name)," (f64.const {val})))) |
|
||||
"), val = a)); |
|
||||
static ONCE: Once = Once::new(); |
|
||||
ONCE.call_once(|| translated.disassemble()); |
|
||||
|
|
||||
translated.execute_func::<(), $out_ty>(0, ()) == Ok($func(a)) |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
binop_test!(add, |a, b| a + b); |
|
||||
binop_test!(mul, |a, b| a * b); |
|
||||
binop_test!(sub, |a, b| a - b); |
|
||||
binop_test!(gt, |a, b| a > b, i32); |
|
||||
binop_test!(lt, |a, b| a < b, i32); |
|
||||
binop_test!(ge, |a, b| a >= b, i32); |
|
||||
binop_test!(le, |a, b| a <= b, i32); |
|
||||
|
|
||||
unop_test!(neg, |a: f64| -a); |
|
||||
unop_test!(abs, |a: f64| a.abs()); |
|
||||
} |
|
||||
|
|
||||
quickcheck! { |
|
||||
fn if_then_else(a: u32, b: u32) -> bool { |
|
||||
const CODE: &str = r#" |
|
||||
(module |
|
||||
(func (param i32) (param i32) (result i32) |
|
||||
(if (result i32) |
|
||||
(i32.eq |
|
||||
(get_local 0) |
|
||||
(get_local 1) |
|
||||
) |
|
||||
(then (get_local 0)) |
|
||||
(else (get_local 1)) |
|
||||
) |
|
||||
) |
|
||||
) |
|
||||
"#; |
|
||||
|
|
||||
lazy_static! { |
|
||||
static ref TRANSLATED: ExecutableModule = {let out = translate_wat(CODE); out.disassemble(); out}; |
|
||||
} |
|
||||
|
|
||||
let out = TRANSLATED.execute_func::<(u32, u32), u32>(0, (a, b)); |
|
||||
|
|
||||
out == Ok(if a == b { a } else { b }) |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
quickcheck! { |
|
||||
#[test] |
|
||||
fn literals(a: i32, b: i64, c: i32, d: i64) -> bool { |
|
||||
let code = format!(r#" |
|
||||
(module |
|
||||
(func (result i32) |
|
||||
(i32.const {}) |
|
||||
) |
|
||||
(func (result i64) |
|
||||
(i64.const {}) |
|
||||
) |
|
||||
(func (result f32) |
|
||||
(f32.const {}) |
|
||||
) |
|
||||
(func (result f64) |
|
||||
(f64.const {}) |
|
||||
) |
|
||||
) |
|
||||
"#, a, b, c, d); |
|
||||
|
|
||||
let translated = translate_wat(&code); |
|
||||
|
|
||||
assert_eq!(translated.execute_func::<(), i32>(0, ()), Ok(a)); |
|
||||
assert_eq!(translated.execute_func::<(), i64>(1, ()), Ok(b)); |
|
||||
assert_eq!(translated.execute_func::<(), f32>(2, ()), Ok(c as _)); |
|
||||
assert_eq!(translated.execute_func::<(), f64>(3, ()), Ok(d as _)); |
|
||||
|
|
||||
true |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
quickcheck! { |
|
||||
#[test] |
|
||||
fn params(a: i32, b: i64, c: i32, d: i64) -> bool { |
|
||||
let code = r#" |
|
||||
(module |
|
||||
(func (param i32) (param i64) (param f32) (param f64) (result i32) |
|
||||
(get_local 0) |
|
||||
) |
|
||||
(func (param i32) (param i64) (param f32) (param f64) (result i64) |
|
||||
(get_local 1) |
|
||||
) |
|
||||
(func (param i32) (param i64) (param f32) (param f64) (result f32) |
|
||||
(get_local 2) |
|
||||
) |
|
||||
(func (param i32) (param i64) (param f32) (param f64) (result f64) |
|
||||
(get_local 3) |
|
||||
) |
|
||||
) |
|
||||
"#; |
|
||||
|
|
||||
let c = c as f32; |
|
||||
let d = d as f64; |
|
||||
|
|
||||
let translated = translate_wat(&code); |
|
||||
|
|
||||
assert_eq!(translated.execute_func::<(i32, i64, f32, f64), i32>(0, (a, b, c, d)), Ok(a)); |
|
||||
assert_eq!(translated.execute_func::<(i32, i64, f32, f64), i64>(1, (a, b, c, d)), Ok(b)); |
|
||||
assert_eq!(translated.execute_func::<(i32, i64, f32, f64), f32>(2, (a, b, c, d)), Ok(c)); |
|
||||
assert_eq!(translated.execute_func::<(i32, i64, f32, f64), f64>(3, (a, b, c, d)), Ok(d)); |
|
||||
|
|
||||
true |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
macro_rules! test_select { |
|
||||
($name:ident, $ty:ident) => { |
|
||||
mod $name { |
|
||||
use super::{lazy_static, quickcheck, translate_wat, ExecutableModule}; |
|
||||
use std::sync::Once; |
|
||||
|
|
||||
lazy_static! { |
|
||||
static ref AS_PARAMS: ExecutableModule = translate_wat(&format!( |
|
||||
" |
|
||||
(module |
|
||||
(func (param {ty}) (param {ty}) (param i32) (result {ty}) |
|
||||
(select (get_local 0) (get_local 1) (get_local 2)) |
|
||||
) |
|
||||
)", |
|
||||
ty = stringify!($ty) |
|
||||
)); |
|
||||
} |
|
||||
|
|
||||
quickcheck! { |
|
||||
fn as_param(cond: bool, then: $ty, else_: $ty) -> bool { |
|
||||
let icond: i32 = if cond { 1 } else { 0 }; |
|
||||
AS_PARAMS.execute_func::<($ty, $ty, i32), $ty>(0, (then, else_, icond)) == |
|
||||
Ok(if cond { then } else { else_ }) |
|
||||
} |
|
||||
|
|
||||
fn lit(cond: bool, then: $ty, else_: $ty) -> bool { |
|
||||
let icond: i32 = if cond { 1 } else { 0 }; |
|
||||
let translated = translate_wat(&format!(" |
|
||||
(module (func (param {ty}) (param {ty}) (result {ty}) |
|
||||
(select (get_local 0) (get_local 1) (i32.const {val})))) |
|
||||
", |
|
||||
val = icond, |
|
||||
ty = stringify!($ty) |
|
||||
)); |
|
||||
static ONCE: Once = Once::new(); |
|
||||
ONCE.call_once(|| translated.disassemble()); |
|
||||
|
|
||||
translated.execute_func::<($ty, $ty), $ty>(0, (then, else_)) == |
|
||||
Ok(if cond { then } else { else_ }) |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
test_select!(select32, i32); |
|
||||
test_select!(select64, i64); |
|
@ -1,45 +0,0 @@ |
|||||
use lightbeam::{translate, ExecutableModule, ExecutionError}; |
|
||||
|
|
||||
fn translate_wat(wat: &str) -> ExecutableModule { |
|
||||
let wasm = wat::parse_str(wat).unwrap(); |
|
||||
let compiled = translate(&wasm).unwrap(); |
|
||||
compiled |
|
||||
} |
|
||||
|
|
||||
#[test] |
|
||||
fn wrong_type() { |
|
||||
let code = r#" |
|
||||
(module |
|
||||
(func (param i32) (param i64) (result i32) |
|
||||
(i32.const 228) |
|
||||
) |
|
||||
) |
|
||||
"#; |
|
||||
|
|
||||
let translated = translate_wat(code); |
|
||||
assert_eq!( |
|
||||
translated |
|
||||
.execute_func::<_, ()>(0, (0u32, 0u32)) |
|
||||
.unwrap_err(), |
|
||||
ExecutionError::TypeMismatch |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
#[test] |
|
||||
fn wrong_index() { |
|
||||
let code = r#" |
|
||||
(module |
|
||||
(func (param i32) (param i64) (result i32) |
|
||||
(i32.const 228) |
|
||||
) |
|
||||
) |
|
||||
"#; |
|
||||
|
|
||||
let translated = translate_wat(code); |
|
||||
assert_eq!( |
|
||||
translated |
|
||||
.execute_func::<_, ()>(10, (0u32, 0u32)) |
|
||||
.unwrap_err(), |
|
||||
ExecutionError::FuncIndexOutOfBounds |
|
||||
); |
|
||||
} |
|
@ -1,22 +0,0 @@ |
|||||
[package] |
|
||||
name = "wasmtime-lightbeam" |
|
||||
version = "0.30.0" |
|
||||
authors = ["The Wasmtime Project Developers"] |
|
||||
description = "Integration between Lightbeam and Wasmtime" |
|
||||
license = "Apache-2.0 WITH LLVM-exception" |
|
||||
repository = "https://github.com/bytecodealliance/wasmtime" |
|
||||
documentation = "https://docs.rs/wasmtime-lightbeam/" |
|
||||
categories = ["wasm"] |
|
||||
keywords = ["webassembly", "wasm"] |
|
||||
readme = "README.md" |
|
||||
edition = "2018" |
|
||||
|
|
||||
[dependencies] |
|
||||
anyhow = "1.0" |
|
||||
target-lexicon = "0.12" |
|
||||
gimli = "0.25" |
|
||||
lightbeam = { path = "..", version = "0.30.0" } |
|
||||
wasmparser = "0.80" |
|
||||
cranelift-codegen = { path = "../../../cranelift/codegen", version = "0.77.0" } |
|
||||
wasmtime-environ = { path = "../../environ", version = "0.30.0" } |
|
||||
object = { version = "0.26.0", default-features = false } |
|
@ -1,220 +0,0 @@ |
|||||
|
|
||||
Apache License |
|
||||
Version 2.0, January 2004 |
|
||||
http://www.apache.org/licenses/ |
|
||||
|
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION |
|
||||
|
|
||||
1. Definitions. |
|
||||
|
|
||||
"License" shall mean the terms and conditions for use, reproduction, |
|
||||
and distribution as defined by Sections 1 through 9 of this document. |
|
||||
|
|
||||
"Licensor" shall mean the copyright owner or entity authorized by |
|
||||
the copyright owner that is granting the License. |
|
||||
|
|
||||
"Legal Entity" shall mean the union of the acting entity and all |
|
||||
other entities that control, are controlled by, or are under common |
|
||||
control with that entity. For the purposes of this definition, |
|
||||
"control" means (i) the power, direct or indirect, to cause the |
|
||||
direction or management of such entity, whether by contract or |
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the |
|
||||
outstanding shares, or (iii) beneficial ownership of such entity. |
|
||||
|
|
||||
"You" (or "Your") shall mean an individual or Legal Entity |
|
||||
exercising permissions granted by this License. |
|
||||
|
|
||||
"Source" form shall mean the preferred form for making modifications, |
|
||||
including but not limited to software source code, documentation |
|
||||
source, and configuration files. |
|
||||
|
|
||||
"Object" form shall mean any form resulting from mechanical |
|
||||
transformation or translation of a Source form, including but |
|
||||
not limited to compiled object code, generated documentation, |
|
||||
and conversions to other media types. |
|
||||
|
|
||||
"Work" shall mean the work of authorship, whether in Source or |
|
||||
Object form, made available under the License, as indicated by a |
|
||||
copyright notice that is included in or attached to the work |
|
||||
(an example is provided in the Appendix below). |
|
||||
|
|
||||
"Derivative Works" shall mean any work, whether in Source or Object |
|
||||
form, that is based on (or derived from) the Work and for which the |
|
||||
editorial revisions, annotations, elaborations, or other modifications |
|
||||
represent, as a whole, an original work of authorship. For the purposes |
|
||||
of this License, Derivative Works shall not include works that remain |
|
||||
separable from, or merely link (or bind by name) to the interfaces of, |
|
||||
the Work and Derivative Works thereof. |
|
||||
|
|
||||
"Contribution" shall mean any work of authorship, including |
|
||||
the original version of the Work and any modifications or additions |
|
||||
to that Work or Derivative Works thereof, that is intentionally |
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner |
|
||||
or by an individual or Legal Entity authorized to submit on behalf of |
|
||||
the copyright owner. For the purposes of this definition, "submitted" |
|
||||
means any form of electronic, verbal, or written communication sent |
|
||||
to the Licensor or its representatives, including but not limited to |
|
||||
communication on electronic mailing lists, source code control systems, |
|
||||
and issue tracking systems that are managed by, or on behalf of, the |
|
||||
Licensor for the purpose of discussing and improving the Work, but |
|
||||
excluding communication that is conspicuously marked or otherwise |
|
||||
designated in writing by the copyright owner as "Not a Contribution." |
|
||||
|
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity |
|
||||
on behalf of whom a Contribution has been received by Licensor and |
|
||||
subsequently incorporated within the Work. |
|
||||
|
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of |
|
||||
this License, each Contributor hereby grants to You a perpetual, |
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable |
|
||||
copyright license to reproduce, prepare Derivative Works of, |
|
||||
publicly display, publicly perform, sublicense, and distribute the |
|
||||
Work and such Derivative Works in Source or Object form. |
|
||||
|
|
||||
3. Grant of Patent License. Subject to the terms and conditions of |
|
||||
this License, each Contributor hereby grants to You a perpetual, |
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable |
|
||||
(except as stated in this section) patent license to make, have made, |
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work, |
|
||||
where such license applies only to those patent claims licensable |
|
||||
by such Contributor that are necessarily infringed by their |
|
||||
Contribution(s) alone or by combination of their Contribution(s) |
|
||||
with the Work to which such Contribution(s) was submitted. If You |
|
||||
institute patent litigation against any entity (including a |
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work |
|
||||
or a Contribution incorporated within the Work constitutes direct |
|
||||
or contributory patent infringement, then any patent licenses |
|
||||
granted to You under this License for that Work shall terminate |
|
||||
as of the date such litigation is filed. |
|
||||
|
|
||||
4. Redistribution. You may reproduce and distribute copies of the |
|
||||
Work or Derivative Works thereof in any medium, with or without |
|
||||
modifications, and in Source or Object form, provided that You |
|
||||
meet the following conditions: |
|
||||
|
|
||||
(a) You must give any other recipients of the Work or |
|
||||
Derivative Works a copy of this License; and |
|
||||
|
|
||||
(b) You must cause any modified files to carry prominent notices |
|
||||
stating that You changed the files; and |
|
||||
|
|
||||
(c) You must retain, in the Source form of any Derivative Works |
|
||||
that You distribute, all copyright, patent, trademark, and |
|
||||
attribution notices from the Source form of the Work, |
|
||||
excluding those notices that do not pertain to any part of |
|
||||
the Derivative Works; and |
|
||||
|
|
||||
(d) If the Work includes a "NOTICE" text file as part of its |
|
||||
distribution, then any Derivative Works that You distribute must |
|
||||
include a readable copy of the attribution notices contained |
|
||||
within such NOTICE file, excluding those notices that do not |
|
||||
pertain to any part of the Derivative Works, in at least one |
|
||||
of the following places: within a NOTICE text file distributed |
|
||||
as part of the Derivative Works; within the Source form or |
|
||||
documentation, if provided along with the Derivative Works; or, |
|
||||
within a display generated by the Derivative Works, if and |
|
||||
wherever such third-party notices normally appear. The contents |
|
||||
of the NOTICE file are for informational purposes only and |
|
||||
do not modify the License. You may add Your own attribution |
|
||||
notices within Derivative Works that You distribute, alongside |
|
||||
or as an addendum to the NOTICE text from the Work, provided |
|
||||
that such additional attribution notices cannot be construed |
|
||||
as modifying the License. |
|
||||
|
|
||||
You may add Your own copyright statement to Your modifications and |
|
||||
may provide additional or different license terms and conditions |
|
||||
for use, reproduction, or distribution of Your modifications, or |
|
||||
for any such Derivative Works as a whole, provided Your use, |
|
||||
reproduction, and distribution of the Work otherwise complies with |
|
||||
the conditions stated in this License. |
|
||||
|
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, |
|
||||
any Contribution intentionally submitted for inclusion in the Work |
|
||||
by You to the Licensor shall be under the terms and conditions of |
|
||||
this License, without any additional terms or conditions. |
|
||||
Notwithstanding the above, nothing herein shall supersede or modify |
|
||||
the terms of any separate license agreement you may have executed |
|
||||
with Licensor regarding such Contributions. |
|
||||
|
|
||||
6. Trademarks. This License does not grant permission to use the trade |
|
||||
names, trademarks, service marks, or product names of the Licensor, |
|
||||
except as required for reasonable and customary use in describing the |
|
||||
origin of the Work and reproducing the content of the NOTICE file. |
|
||||
|
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or |
|
||||
agreed to in writing, Licensor provides the Work (and each |
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS, |
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
|
||||
implied, including, without limitation, any warranties or conditions |
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A |
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the |
|
||||
appropriateness of using or redistributing the Work and assume any |
|
||||
risks associated with Your exercise of permissions under this License. |
|
||||
|
|
||||
8. Limitation of Liability. In no event and under no legal theory, |
|
||||
whether in tort (including negligence), contract, or otherwise, |
|
||||
unless required by applicable law (such as deliberate and grossly |
|
||||
negligent acts) or agreed to in writing, shall any Contributor be |
|
||||
liable to You for damages, including any direct, indirect, special, |
|
||||
incidental, or consequential damages of any character arising as a |
|
||||
result of this License or out of the use or inability to use the |
|
||||
Work (including but not limited to damages for loss of goodwill, |
|
||||
work stoppage, computer failure or malfunction, or any and all |
|
||||
other commercial damages or losses), even if such Contributor |
|
||||
has been advised of the possibility of such damages. |
|
||||
|
|
||||
9. Accepting Warranty or Additional Liability. While redistributing |
|
||||
the Work or Derivative Works thereof, You may choose to offer, |
|
||||
and charge a fee for, acceptance of support, warranty, indemnity, |
|
||||
or other liability obligations and/or rights consistent with this |
|
||||
License. However, in accepting such obligations, You may act only |
|
||||
on Your own behalf and on Your sole responsibility, not on behalf |
|
||||
of any other Contributor, and only if You agree to indemnify, |
|
||||
defend, and hold each Contributor harmless for any liability |
|
||||
incurred by, or claims asserted against, such Contributor by reason |
|
||||
of your accepting any such warranty or additional liability. |
|
||||
|
|
||||
END OF TERMS AND CONDITIONS |
|
||||
|
|
||||
APPENDIX: How to apply the Apache License to your work. |
|
||||
|
|
||||
To apply the Apache License to your work, attach the following |
|
||||
boilerplate notice, with the fields enclosed by brackets "[]" |
|
||||
replaced with your own identifying information. (Don't include |
|
||||
the brackets!) The text should be enclosed in the appropriate |
|
||||
comment syntax for the file format. We also recommend that a |
|
||||
file or class name and description of purpose be included on the |
|
||||
same "printed page" as the copyright notice for easier |
|
||||
identification within third-party archives. |
|
||||
|
|
||||
Copyright [yyyy] [name of copyright owner] |
|
||||
|
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); |
|
||||
you may not use this file except in compliance with the License. |
|
||||
You may obtain a copy of the License at |
|
||||
|
|
||||
http://www.apache.org/licenses/LICENSE-2.0 |
|
||||
|
|
||||
Unless required by applicable law or agreed to in writing, software |
|
||||
distributed under the License is distributed on an "AS IS" BASIS, |
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
||||
See the License for the specific language governing permissions and |
|
||||
limitations under the License. |
|
||||
|
|
||||
|
|
||||
--- LLVM Exceptions to the Apache 2.0 License ---- |
|
||||
|
|
||||
As an exception, if, as a result of your compiling your source code, portions |
|
||||
of this Software are embedded into an Object form of such source code, you |
|
||||
may redistribute such embedded portions in such Object form without complying |
|
||||
with the conditions of Sections 4(a), 4(b) and 4(d) of the License. |
|
||||
|
|
||||
In addition, if you combine or link compiled forms of this Software with |
|
||||
software that is licensed under the GPLv2 ("Combined Software") and if a |
|
||||
court of competent jurisdiction determines that the patent provision (Section |
|
||||
3), the indemnity provision (Section 9) or other Section of the License |
|
||||
conflicts with the conditions of the GPLv2, you may retroactively and |
|
||||
prospectively choose to deem waived or otherwise exclude such Section(s) of |
|
||||
the License, but only in their entirety and only with respect to the Combined |
|
||||
Software. |
|
||||
|
|
@ -1,4 +0,0 @@ |
|||||
# `wasmtime-lightbeam` |
|
||||
|
|
||||
This crate provides an implementation of the `Compiler` trait which is |
|
||||
connected to Lightbeam. |
|
@ -1,370 +0,0 @@ |
|||||
//! Support for compiling with Lightbeam.
|
|
||||
//!
|
|
||||
//! This crates provides an implementation of [`Compiler`] in the form of
|
|
||||
//! [`Lightbeam`].
|
|
||||
|
|
||||
#![allow(dead_code)] |
|
||||
|
|
||||
use anyhow::Result; |
|
||||
use cranelift_codegen::binemit; |
|
||||
use cranelift_codegen::ir::{self, ExternalName}; |
|
||||
use object::write::Object; |
|
||||
use std::any::Any; |
|
||||
use std::collections::BTreeMap; |
|
||||
use wasmtime_environ::{ |
|
||||
BuiltinFunctionIndex, CompileError, Compiler, FlagValue, FunctionBodyData, FunctionInfo, |
|
||||
Module, ModuleTranslation, PrimaryMap, TrapInformation, Tunables, TypeTables, VMOffsets, |
|
||||
}; |
|
||||
use wasmtime_environ::{ |
|
||||
DefinedFuncIndex, DefinedGlobalIndex, DefinedMemoryIndex, DefinedTableIndex, FuncIndex, |
|
||||
GlobalIndex, MemoryIndex, TableIndex, Trampoline, TypeIndex, WasmFuncType, |
|
||||
}; |
|
||||
|
|
||||
/// A compiler that compiles a WebAssembly module with Lightbeam, directly translating the Wasm file.
|
|
||||
pub struct Lightbeam; |
|
||||
|
|
||||
impl Compiler for Lightbeam { |
|
||||
fn compile_function( |
|
||||
&self, |
|
||||
_translation: &ModuleTranslation, |
|
||||
_i: DefinedFuncIndex, |
|
||||
_function_body: FunctionBodyData<'_>, |
|
||||
_tunables: &Tunables, |
|
||||
_types: &TypeTables, |
|
||||
) -> Result<Box<dyn Any + Send>, CompileError> { |
|
||||
unimplemented!() |
|
||||
// if tunables.generate_native_debuginfo {
|
|
||||
// return Err(CompileError::DebugInfoNotSupported);
|
|
||||
// }
|
|
||||
// let func_index = translation.module.func_index(i);
|
|
||||
|
|
||||
// let env = FuncEnvironment::new(isa.frontend_config().pointer_bytes(), translation);
|
|
||||
// let mut codegen_session: CodeGenSession<_> = CodeGenSession::new(
|
|
||||
// translation.function_body_inputs.len() as u32,
|
|
||||
// &env,
|
|
||||
// lightbeam::microwasm::I32,
|
|
||||
// );
|
|
||||
|
|
||||
// let mut reloc_sink = RelocSink::new(func_index);
|
|
||||
// let mut trap_sink = TrapSink::new();
|
|
||||
// lightbeam::translate_function(
|
|
||||
// &mut codegen_session,
|
|
||||
// Sinks {
|
|
||||
// relocs: &mut reloc_sink,
|
|
||||
// traps: &mut trap_sink,
|
|
||||
// offsets: &mut NullOffsetSink,
|
|
||||
// },
|
|
||||
// i.as_u32(),
|
|
||||
// function_body.body,
|
|
||||
// )
|
|
||||
// .map_err(|e| CompileError::Codegen(format!("Failed to translate function: {}", e)))?;
|
|
||||
|
|
||||
// let code_section = codegen_session
|
|
||||
// .into_translated_code_section()
|
|
||||
// .map_err(|e| CompileError::Codegen(format!("Failed to generate output code: {}", e)))?;
|
|
||||
|
|
||||
// Ok(CompiledFunction {
|
|
||||
// // TODO: try to remove copy here (?)
|
|
||||
// body: code_section.buffer().to_vec(),
|
|
||||
// traps: trap_sink.traps,
|
|
||||
// relocations: reloc_sink.func_relocs,
|
|
||||
|
|
||||
// // not implemented for lightbeam currently
|
|
||||
// unwind_info: None,
|
|
||||
// stack_maps: Default::default(),
|
|
||||
// stack_slots: Default::default(),
|
|
||||
// value_labels_ranges: Default::default(),
|
|
||||
// address_map: Default::default(),
|
|
||||
// jt_offsets: Default::default(),
|
|
||||
// })
|
|
||||
} |
|
||||
|
|
||||
fn emit_obj( |
|
||||
&self, |
|
||||
_module: &ModuleTranslation, |
|
||||
_types: &TypeTables, |
|
||||
_funcs: PrimaryMap<DefinedFuncIndex, Box<dyn Any + Send>>, |
|
||||
_emit_dwarf: bool, |
|
||||
_obj: &mut Object, |
|
||||
) -> Result<(PrimaryMap<DefinedFuncIndex, FunctionInfo>, Vec<Trampoline>)> { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn emit_trampoline_obj( |
|
||||
&self, |
|
||||
_ty: &WasmFuncType, |
|
||||
_host_fn: usize, |
|
||||
_obj: &mut Object, |
|
||||
) -> Result<(Trampoline, Trampoline)> { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn triple(&self) -> &target_lexicon::Triple { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn flags(&self) -> BTreeMap<String, FlagValue> { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
|
|
||||
fn isa_flags(&self) -> BTreeMap<String, FlagValue> { |
|
||||
unimplemented!() |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
/// Implementation of a relocation sink that just saves all the information for later
|
|
||||
struct RelocSink { |
|
||||
/// Current function index.
|
|
||||
func_index: FuncIndex, |
|
||||
// /// Relocations recorded for the function.
|
|
||||
// func_relocs: Vec<Relocation>,
|
|
||||
} |
|
||||
|
|
||||
impl binemit::RelocSink for RelocSink { |
|
||||
fn reloc_external( |
|
||||
&mut self, |
|
||||
_offset: binemit::CodeOffset, |
|
||||
_srcloc: ir::SourceLoc, |
|
||||
_reloc: binemit::Reloc, |
|
||||
_name: &ExternalName, |
|
||||
_addend: binemit::Addend, |
|
||||
) { |
|
||||
unimplemented!() |
|
||||
// let reloc_target = if let ExternalName::User { namespace, index } = *name {
|
|
||||
// debug_assert_eq!(namespace, 0);
|
|
||||
// RelocationTarget::UserFunc(FuncIndex::from_u32(index))
|
|
||||
// } else if let ExternalName::LibCall(libcall) = *name {
|
|
||||
// RelocationTarget::LibCall(libcall)
|
|
||||
// } else {
|
|
||||
// panic!("unrecognized external name")
|
|
||||
// };
|
|
||||
// self.func_relocs.push(Relocation {
|
|
||||
// reloc,
|
|
||||
// reloc_target,
|
|
||||
// offset,
|
|
||||
// addend,
|
|
||||
// });
|
|
||||
} |
|
||||
|
|
||||
fn reloc_constant( |
|
||||
&mut self, |
|
||||
_code_offset: binemit::CodeOffset, |
|
||||
_reloc: binemit::Reloc, |
|
||||
_constant_offset: ir::ConstantOffset, |
|
||||
) { |
|
||||
// Do nothing for now: cranelift emits constant data after the function code and also emits
|
|
||||
// function code with correct relative offsets to the constant data.
|
|
||||
} |
|
||||
|
|
||||
fn reloc_jt( |
|
||||
&mut self, |
|
||||
_offset: binemit::CodeOffset, |
|
||||
_reloc: binemit::Reloc, |
|
||||
_jt: ir::JumpTable, |
|
||||
) { |
|
||||
unimplemented!() |
|
||||
// self.func_relocs.push(Relocation {
|
|
||||
// reloc,
|
|
||||
// reloc_target: RelocationTarget::JumpTable(self.func_index, jt),
|
|
||||
// offset,
|
|
||||
// addend: 0,
|
|
||||
// });
|
|
||||
} |
|
||||
} |
|
||||
|
|
||||
impl RelocSink { |
|
||||
/// Return a new `RelocSink` instance.
|
|
||||
fn new(func_index: FuncIndex) -> Self { |
|
||||
Self { |
|
||||
func_index, |
|
||||
// func_relocs: Vec::new(),
|
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
/// Implementation of a trap sink that simply stores all trap info in-memory
|
|
||||
#[derive(Default)] |
|
||||
struct TrapSink { |
|
||||
/// The in-memory vector of trap info
|
|
||||
traps: Vec<TrapInformation>, |
|
||||
} |
|
||||
|
|
||||
impl TrapSink { |
|
||||
/// Create a new `TrapSink`
|
|
||||
fn new() -> Self { |
|
||||
Self::default() |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
impl binemit::TrapSink for TrapSink { |
|
||||
fn trap( |
|
||||
&mut self, |
|
||||
_code_offset: binemit::CodeOffset, |
|
||||
_source_loc: ir::SourceLoc, |
|
||||
_trap_code: ir::TrapCode, |
|
||||
) { |
|
||||
unimplemented!() |
|
||||
// self.traps.push(TrapInformation {
|
|
||||
// code_offset,
|
|
||||
// trap_code,
|
|
||||
// });
|
|
||||
} |
|
||||
} |
|
||||
|
|
||||
/// The `FuncEnvironment` implementation for use by the `ModuleEnvironment`.
|
|
||||
struct FuncEnvironment<'module_environment> { |
|
||||
/// The module-level environment which this function-level environment belongs to.
|
|
||||
module: &'module_environment Module, |
|
||||
|
|
||||
/// Offsets to struct fields accessed by JIT code.
|
|
||||
offsets: VMOffsets<u8>, |
|
||||
} |
|
||||
|
|
||||
impl<'module_environment> FuncEnvironment<'module_environment> { |
|
||||
fn new(pointer_bytes: u8, translation: &'module_environment ModuleTranslation<'_>) -> Self { |
|
||||
Self { |
|
||||
module: &translation.module, |
|
||||
offsets: VMOffsets::new(pointer_bytes, &translation.module), |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
// TODO: This is necessary as if Lightbeam used `FuncEnvironment` directly it would cause
|
|
||||
// a circular dependency graph. We should extract common types out into a separate
|
|
||||
// crate that Lightbeam can use but until then we need this trait.
|
|
||||
impl lightbeam::ModuleContext for FuncEnvironment<'_> { |
|
||||
type Signature = ir::Signature; |
|
||||
type GlobalType = ir::Type; |
|
||||
|
|
||||
fn func_index(&self, defined_func_index: u32) -> u32 { |
|
||||
self.module |
|
||||
.func_index(DefinedFuncIndex::from_u32(defined_func_index)) |
|
||||
.as_u32() |
|
||||
} |
|
||||
|
|
||||
fn defined_func_index(&self, func_index: u32) -> Option<u32> { |
|
||||
self.module |
|
||||
.defined_func_index(FuncIndex::from_u32(func_index)) |
|
||||
.map(DefinedFuncIndex::as_u32) |
|
||||
} |
|
||||
|
|
||||
fn defined_global_index(&self, global_index: u32) -> Option<u32> { |
|
||||
self.module |
|
||||
.defined_global_index(GlobalIndex::from_u32(global_index)) |
|
||||
.map(DefinedGlobalIndex::as_u32) |
|
||||
} |
|
||||
|
|
||||
fn global_type(&self, _global_index: u32) -> &Self::GlobalType { |
|
||||
unimplemented!() |
|
||||
// &self.module.globals[GlobalIndex::from_u32(global_index)].ty
|
|
||||
} |
|
||||
|
|
||||
fn func_type_index(&self, func_idx: u32) -> u32 { |
|
||||
self.module.functions[FuncIndex::from_u32(func_idx)].as_u32() |
|
||||
} |
|
||||
|
|
||||
fn signature(&self, _index: u32) -> &Self::Signature { |
|
||||
panic!("not implemented") |
|
||||
} |
|
||||
|
|
||||
fn defined_table_index(&self, table_index: u32) -> Option<u32> { |
|
||||
self.module |
|
||||
.defined_table_index(TableIndex::from_u32(table_index)) |
|
||||
.map(DefinedTableIndex::as_u32) |
|
||||
} |
|
||||
|
|
||||
fn defined_memory_index(&self, memory_index: u32) -> Option<u32> { |
|
||||
self.module |
|
||||
.defined_memory_index(MemoryIndex::from_u32(memory_index)) |
|
||||
.map(DefinedMemoryIndex::as_u32) |
|
||||
} |
|
||||
|
|
||||
fn vmctx_builtin_function(&self, func_index: u32) -> u32 { |
|
||||
self.offsets |
|
||||
.vmctx_builtin_function(BuiltinFunctionIndex::from_u32(func_index)) |
|
||||
} |
|
||||
|
|
||||
fn vmctx_vmfunction_import_body(&self, func_index: u32) -> u32 { |
|
||||
self.offsets |
|
||||
.vmctx_vmfunction_import_body(FuncIndex::from_u32(func_index)) |
|
||||
} |
|
||||
fn vmctx_vmfunction_import_vmctx(&self, func_index: u32) -> u32 { |
|
||||
self.offsets |
|
||||
.vmctx_vmfunction_import_vmctx(FuncIndex::from_u32(func_index)) |
|
||||
} |
|
||||
|
|
||||
fn vmctx_vmglobal_import_from(&self, global_index: u32) -> u32 { |
|
||||
self.offsets |
|
||||
.vmctx_vmglobal_import_from(GlobalIndex::from_u32(global_index)) |
|
||||
} |
|
||||
fn vmctx_vmglobal_definition(&self, defined_global_index: u32) -> u32 { |
|
||||
self.offsets |
|
||||
.vmctx_vmglobal_definition(DefinedGlobalIndex::from_u32(defined_global_index)) |
|
||||
} |
|
||||
fn vmctx_vmmemory_import_from(&self, memory_index: u32) -> u32 { |
|
||||
self.offsets |
|
||||
.vmctx_vmmemory_import_from(MemoryIndex::from_u32(memory_index)) |
|
||||
} |
|
||||
fn vmctx_vmmemory_definition(&self, defined_memory_index: u32) -> u32 { |
|
||||
self.offsets |
|
||||
.vmctx_vmmemory_definition(DefinedMemoryIndex::from_u32(defined_memory_index)) |
|
||||
} |
|
||||
fn vmctx_vmmemory_definition_base(&self, defined_memory_index: u32) -> u32 { |
|
||||
self.offsets |
|
||||
.vmctx_vmmemory_definition_base(DefinedMemoryIndex::from_u32(defined_memory_index)) |
|
||||
} |
|
||||
fn vmctx_vmmemory_definition_current_length(&self, defined_memory_index: u32) -> u32 { |
|
||||
self.offsets |
|
||||
.vmctx_vmmemory_definition_current_length(DefinedMemoryIndex::from_u32( |
|
||||
defined_memory_index, |
|
||||
)) |
|
||||
} |
|
||||
fn vmmemory_definition_base(&self) -> u8 { |
|
||||
self.offsets.vmmemory_definition_base() |
|
||||
} |
|
||||
fn vmmemory_definition_current_length(&self) -> u8 { |
|
||||
self.offsets.vmmemory_definition_current_length() |
|
||||
} |
|
||||
fn vmctx_vmtable_import_from(&self, table_index: u32) -> u32 { |
|
||||
self.offsets |
|
||||
.vmctx_vmtable_import_from(TableIndex::from_u32(table_index)) |
|
||||
} |
|
||||
fn vmctx_vmtable_definition(&self, defined_table_index: u32) -> u32 { |
|
||||
self.offsets |
|
||||
.vmctx_vmtable_definition(DefinedTableIndex::from_u32(defined_table_index)) |
|
||||
} |
|
||||
fn vmctx_vmtable_definition_base(&self, defined_table_index: u32) -> u32 { |
|
||||
self.offsets |
|
||||
.vmctx_vmtable_definition_base(DefinedTableIndex::from_u32(defined_table_index)) |
|
||||
} |
|
||||
fn vmctx_vmtable_definition_current_elements(&self, defined_table_index: u32) -> u32 { |
|
||||
self.offsets |
|
||||
.vmctx_vmtable_definition_current_elements(DefinedTableIndex::from_u32( |
|
||||
defined_table_index, |
|
||||
)) |
|
||||
} |
|
||||
fn vmtable_definition_base(&self) -> u8 { |
|
||||
self.offsets.vmtable_definition_base() |
|
||||
} |
|
||||
fn vmtable_definition_current_elements(&self) -> u8 { |
|
||||
self.offsets.vmtable_definition_current_elements() |
|
||||
} |
|
||||
fn vmcaller_checked_anyfunc_type_index(&self) -> u8 { |
|
||||
self.offsets.vmcaller_checked_anyfunc_type_index() |
|
||||
} |
|
||||
fn vmcaller_checked_anyfunc_func_ptr(&self) -> u8 { |
|
||||
self.offsets.vmcaller_checked_anyfunc_func_ptr() |
|
||||
} |
|
||||
fn vmcaller_checked_anyfunc_vmctx(&self) -> u8 { |
|
||||
self.offsets.vmcaller_checked_anyfunc_vmctx() |
|
||||
} |
|
||||
fn size_of_vmcaller_checked_anyfunc(&self) -> u8 { |
|
||||
self.offsets.size_of_vmcaller_checked_anyfunc() |
|
||||
} |
|
||||
fn vmctx_vmshared_signature_id(&self, signature_idx: u32) -> u32 { |
|
||||
self.offsets |
|
||||
.vmctx_vmshared_signature_id(TypeIndex::from_u32(signature_idx)) |
|
||||
} |
|
||||
|
|
||||
// TODO: type of a global
|
|
||||
} |
|
Loading…
Reference in new issue