Truly independent web browser
LibWasm: Simplify the engine and the JIT
Andreas Klingdfd88ce8ccf0
diff --git a/Libraries/LibWasm/Engine/build.rs b/Libraries/LibWasm/Engine/build.rsindex 38074a6ca43..2fb88e6e167 100644--- a/Libraries/LibWasm/Engine/build.rs+++ b/Libraries/LibWasm/Engine/build.rs@@ -5,13 +5,13 @@*///! Compiles the interpreter, Libraries/LibWasm/Interpreter/interpreter.flap, against the layout constants of-//! src/abi.rs, and assembles it into the crate. Also generates the C++ header of the C ABI in src/capi.rs.+//! ../Module/src/abi.rs, and assembles it into the crate. Also generates the C++ header of the C ABI in src/capi.rs.use std::env;use std::fs;use std::path::PathBuf;-#[path = "src/abi.rs"]+#[path = "../Module/src/abi.rs"]mod abi;fn write_if_changed(path: &PathBuf, contents: &str) {@@ -26,7 +26,7 @@ fn main() {let output_directory = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"));let interpreter_source = manifest_directory.join("../Interpreter/interpreter.flap");println!("cargo:rerun-if-changed=build.rs");- println!("cargo:rerun-if-changed=src/abi.rs");+ println!("cargo:rerun-if-changed=../Module/src/abi.rs");println!("cargo:rerun-if-changed={}", interpreter_source.display());println!("cargo::rustc-check-cfg=cfg(wasm_interpreter)");println!("cargo:rerun-if-changed=cbindgen.toml");diff --git a/Libraries/LibWasm/Engine/src/capi.rs b/Libraries/LibWasm/Engine/src/capi.rsindex 2a63988bb62..9253383773c 100644--- a/Libraries/LibWasm/Engine/src/capi.rs+++ b/Libraries/LibWasm/Engine/src/capi.rs@@ -8,7 +8,8 @@//! access their memories, tables, and globals.//!//! Modules are reference counted and immutable, so they can be shared across threads. A store and everything in it-//! belongs to one thread. Addresses index the store's functions, tables, memories, globals, and instances.+//! belongs to one thread. Entities (functions, tables, memories, globals, tags, and instances) are the addresses of+//! their cells.use crate::module::{ExternalKind, ImportDescription, Module};use crate::runtime::entity::{Entity, Handle};@@ -251,7 +252,7 @@ impl WasmExternKind {}}-/// A function, table, memory, or global of a store.+/// A function, table, memory, global, or tag of a store.#[repr(C)]#[derive(Debug, Clone, Copy)]pub struct WasmExtern {@@ -370,8 +371,11 @@ fn extern_type_of_import(description: &ImportDescription) -> WasmExternType {// Modules.-/// A compiled module. The embedder holds it through `wasm_module_retain()` and `wasm_module_release()`.-pub struct WasmModule(Arc<Module>);+/// A compiled module, which the embedder holds a reference to until it calls `wasm_module_release()`. Its pointer is+/// that of an `Arc<Module>`, and it is never dereferenced as itself.+pub struct WasmModule {+ _opaque: [u8; 0],+}/// Decode and validate a module. Returns null and sets `error` if the module is malformed or invalid.///@@ -386,7 +390,7 @@ pub unsafe extern "C" fn wasm_module_compile() -> *const WasmModule {let bytes = unsafe { ak::slice_from_raw_parts(bytes, length) };match crate::compile(bytes) {- Ok(module) => Arc::into_raw(Arc::new(WasmModule(Arc::new(module)))),+ Ok(module) => Arc::into_raw(Arc::new(module)).cast(),Err(compile_error) => {write_string(error, &compile_error.to_string());std::ptr::null()@@ -394,24 +398,25 @@ pub unsafe extern "C" fn wasm_module_compile(}}-/// # Safety-///-/// `module` must be a live module.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn wasm_module_retain(module: *const WasmModule) {- unsafe { Arc::increment_strong_count(module) };-}-/// # Safety////// `module` must be a live module, which this releases one reference to.#[unsafe(no_mangle)]pub unsafe extern "C" fn wasm_module_release(module: *const WasmModule) {- unsafe { Arc::decrement_strong_count(module) };+ unsafe { Arc::decrement_strong_count(module.cast::<Module>()) };}fn module_of<'a>(module: *const WasmModule) -> &'a Module {- unsafe { &(*module).0 }+ unsafe { &*module.cast::<Module>() }+}++/// A reference of our own to the module of `module`.+fn module_arc(module: *const WasmModule) -> Arc<Module> {+ let module = module.cast::<Module>();+ unsafe {+ Arc::increment_strong_count(module);+ Arc::from_raw(module)+ }}/// # Safety@@ -833,7 +838,7 @@ pub unsafe extern "C" fn wasm_store_instantiate(for import in unsafe { ak::slice_from_raw_parts(imports, import_count) } {values.push(import.to_extern_value());}- let module = unsafe { (*module).0.clone() };+ let module = module_arc(module);match store_of(store).instantiate(module, &values) {Ok(address) => {unsafe { *instance = address.cell().cast() };@@ -1237,7 +1242,7 @@ pub unsafe extern "C" fn wasm_store_canonical_value_type(if ty.kind != WasmValueKind::Reference || ty.heap != WasmHeapKind::Concrete {return ty;}- let identities = store_of(store).module_type_identities(module_of(module));+ let identities = store_of(store).module_type_identities_of(&module_arc(module));WasmValueType {type_index: identities[ty.type_index as usize],..ty@@ -1442,6 +1447,16 @@ pub unsafe extern "C" fn wasm_set_host_object(cell: *mut c_void, object: *mut c_unsafe { crate::runtime::heap::set_host_object(cell.cast(), object) };}+/// The cell `wasm_set_host_object()` gave `cell` to keep alive, or null.+///+/// # Safety+///+/// `cell` must be a live cell of a store with a LibGC heap.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasm_host_object(cell: *mut c_void) -> *mut c_void {+ unsafe { crate::runtime::heap::host_object(cell) }+}+// WASI./// The state of a WASI command, whose functions a store gets with `wasm_wasi_allocate_function()`.diff --git a/Libraries/LibWasm/Engine/src/lib.rs b/Libraries/LibWasm/Engine/src/lib.rsindex 2645e4a90bb..074e138981e 100644--- a/Libraries/LibWasm/Engine/src/lib.rs+++ b/Libraries/LibWasm/Engine/src/lib.rs@@ -7,7 +7,8 @@//! # LibWasm//!//! A WebAssembly engine: the binary format decoder, the validator, which also builds the side tables the in-place-//! interpreter branches with, and (in later steps) the runtime, the interpreter, and the JIT.+//! interpreter branches with, the runtime, the interpreter, and the JIT's runtime half (the compiler is+//! libwasm_jit).#[cfg(feature = "allocator")]extern crate ladybird_allocator;diff --git a/Libraries/LibWasm/Engine/src/runtime/entity.rs b/Libraries/LibWasm/Engine/src/runtime/entity.rsindex 14e8f700aae..ef67404717a 100644--- a/Libraries/LibWasm/Engine/src/runtime/entity.rs+++ b/Libraries/LibWasm/Engine/src/runtime/entity.rs@@ -46,7 +46,8 @@ pub trait Entity: Sized {/// An entity, as the address of the entity in its cell. Function references and tag identities are the handles of/// their functions and tags, and the interpreter's views of instances, tables, memories, and globals are the first-/// fields of theirs, so the interpreter's pointers are handles too.+/// fields of theirs, so the interpreter's pointers are handles too, and a slice of handles is an array of them.+#[repr(transparent)]pub struct Handle<T>(NonNull<T>);impl<T> Clone for Handle<T> {diff --git a/Libraries/LibWasm/Engine/src/runtime/gc.rs b/Libraries/LibWasm/Engine/src/runtime/gc.rsindex ff75896f709..e2e94fd5e12 100644--- a/Libraries/LibWasm/Engine/src/runtime/gc.rs+++ b/Libraries/LibWasm/Engine/src/runtime/gc.rs@@ -13,8 +13,8 @@//! them alive; other host values are never followed.use super::heap::{- CELL_HEADER_SIZE, CellFunctions, CellType, Heap, TRACE_FUNCTION, TRACE_NONE, TRACE_REFERENCE, Visitor,- forget_host_object, object_size_class, visit_host_object,+ CELL_HEADER_SIZE, CellType, Heap, TRACE_FUNCTION, TRACE_NONE, TRACE_REFERENCE, Visitor, forget_host_object,+ object_size_class, visit_host_object,};use super::{Store, TagAddress, Value};pub use crate::abi::EXCEPTION_CELL_SIZE;@@ -32,20 +32,6 @@ const STORE_ROOT_STORE_OFFSET: usize = 16;/// The largest data an object can have.const MAX_OBJECT_DATA_SIZE: u64 = 1 << 31;-pub static CELL_FUNCTIONS: CellFunctions = CellFunctions {- object_visit_edges,- object_destroy,- object_external_memory_size,- rtt_visit_edges,- rtt_destroy,- exception_visit_edges,- exception_destroy,- store_root_visit_edges,- store_root_destroy,- entity_visit_edges: super::entity::entity_visit_edges,- entity_destroy: super::entity::entity_destroy,-};-unsafe fn read<T: Copy>(cell: *const c_void, offset: usize) -> T {unsafe { cell.cast::<u8>().add(offset).cast::<T>().read() }}@@ -170,9 +156,9 @@ pub fn allocate_rtt(store: &Store, identity: u32) -> *const Rtt {rtt}-unsafe extern "C" fn rtt_visit_edges(_: *mut c_void, _: *mut c_void) {}+pub(super) unsafe extern "C" fn rtt_visit_edges(_: *mut c_void, _: *mut c_void) {}-unsafe extern "C" fn rtt_destroy(cell: *mut c_void) {+pub(super) unsafe extern "C" fn rtt_destroy(cell: *mut c_void) {unsafe {let rtt = &*rtt_of_cell(cell.cast());free(rtt.display, rtt.depth as usize + 1);@@ -238,7 +224,7 @@ unsafe fn out_of_line_data(cell: *const c_void) -> Option<(*mut u64, usize)> {}}-unsafe extern "C" fn object_visit_edges(cell: *mut c_void, visitor: *mut c_void) {+pub(super) unsafe extern "C" fn object_visit_edges(cell: *mut c_void, visitor: *mut c_void) {let visitor = Visitor::new(visitor);unsafe {visit_host_object(cell, &visitor);@@ -266,7 +252,7 @@ unsafe extern "C" fn object_visit_edges(cell: *mut c_void, visitor: *mut c_void)}}-unsafe extern "C" fn object_destroy(cell: *mut c_void) {+pub(super) unsafe extern "C" fn object_destroy(cell: *mut c_void) {unsafe {forget_host_object(cell);if let Some((block, words)) = out_of_line_data(cell) {@@ -275,7 +261,7 @@ unsafe extern "C" fn object_destroy(cell: *mut c_void) {}}-unsafe extern "C" fn object_external_memory_size(cell: *const c_void) -> usize {+pub(super) unsafe extern "C" fn object_external_memory_size(cell: *const c_void) -> usize {unsafe { out_of_line_data(cell).map_or(0, |(_, words)| words * 8) }}@@ -317,7 +303,7 @@ pub fn exception(reference: u64) -> Exception {}}-unsafe extern "C" fn exception_visit_edges(cell: *mut c_void, visitor: *mut c_void) {+pub(super) unsafe extern "C" fn exception_visit_edges(cell: *mut c_void, visitor: *mut c_void) {let visitor = Visitor::new(visitor);unsafe {visit_host_object(cell, &visitor);@@ -332,7 +318,7 @@ unsafe extern "C" fn exception_visit_edges(cell: *mut c_void, visitor: *mut c_vo}}-unsafe extern "C" fn exception_destroy(cell: *mut c_void) {+pub(super) unsafe extern "C" fn exception_destroy(cell: *mut c_void) {unsafe {forget_host_object(cell);let length: u64 = read(cell, EXCEPTION_LENGTH_OFFSET);@@ -353,7 +339,7 @@ pub(crate) fn detach_store_root(cell: *mut u8) {unsafe { write(cell, STORE_ROOT_STORE_OFFSET, 0u64) };}-unsafe extern "C" fn store_root_destroy(cell: *mut c_void) {+pub(super) unsafe extern "C" fn store_root_destroy(cell: *mut c_void) {unsafe {let store: *mut Store = read(cell, STORE_ROOT_STORE_OFFSET);if let Some(store) = store.as_mut() {@@ -362,7 +348,7 @@ unsafe extern "C" fn store_root_destroy(cell: *mut c_void) {}}-unsafe extern "C" fn store_root_visit_edges(cell: *mut c_void, visitor: *mut c_void) {+pub(super) unsafe extern "C" fn store_root_visit_edges(cell: *mut c_void, visitor: *mut c_void) {unsafe {let store: *const Store = read(cell, STORE_ROOT_STORE_OFFSET);if let Some(store) = store.as_ref() {@@ -460,8 +446,7 @@ impl Store {}unsafe fn store_field(address: *mut u8, kind: u8, value: Value) {- let mut slots = Vec::with_capacity(2);- value.push_slots(&mut slots);+ let (slots, _) = value.to_slots();let mask = match kind {STORAGE_I8 => 0xff,STORAGE_I16 => 0xffff,diff --git a/Libraries/LibWasm/Engine/src/runtime/heap.rs b/Libraries/LibWasm/Engine/src/runtime/heap.rsindex aab8fda86f7..d138d8a4e5b 100644--- a/Libraries/LibWasm/Engine/src/runtime/heap.rs+++ b/Libraries/LibWasm/Engine/src/runtime/heap.rs@@ -129,16 +129,26 @@ pub unsafe fn set_host_object(cell: *mut u8, object: *mut c_void) {unsafe { *cell.add(CELL_FLAGS_OFFSET) |= CELL_FLAG_HOST_OBJECT };}-/// Visit the object `cell` keeps alive, if it keeps one.+/// The object `cell` keeps alive, or null if it keeps none.////// # Safety////// `cell` must be a live cell of the runtime.-pub unsafe fn visit_host_object(cell: *mut c_void, visitor: &Visitor) {+pub unsafe fn host_object(cell: *mut c_void) -> *mut c_void {if unsafe { *cell.cast::<u8>().add(CELL_FLAGS_OFFSET) } & CELL_FLAG_HOST_OBJECT == 0 {- return;+ return core::ptr::null_mut();}- if let Some(object) = HOST_OBJECTS.with_borrow(|objects| objects.get(&cell.addr()).copied()) {+ HOST_OBJECTS.with_borrow(|objects| objects.get(&cell.addr()).copied().unwrap_or(core::ptr::null_mut()))+}++/// Visit the object `cell` keeps alive, if it keeps one.+///+/// # Safety+///+/// `cell` must be a live cell of the runtime.+pub unsafe fn visit_host_object(cell: *mut c_void, visitor: &Visitor) {+ let object = unsafe { host_object(cell) };+ if !object.is_null() {visitor.visit_cell(object.cast());}}@@ -177,21 +187,6 @@ pub fn object_size_class(size: usize) -> Option<usize> {OBJECT_DATA_SIZE_CLASSES.iter().position(|&class| class >= size)}-/// What every cell type needs from the rest of the runtime.-pub struct CellFunctions {- pub object_visit_edges: unsafe extern "C" fn(*mut c_void, *mut c_void),- pub object_destroy: unsafe extern "C" fn(*mut c_void),- pub object_external_memory_size: unsafe extern "C" fn(*const c_void) -> usize,- pub rtt_visit_edges: unsafe extern "C" fn(*mut c_void, *mut c_void),- pub rtt_destroy: unsafe extern "C" fn(*mut c_void),- pub exception_visit_edges: unsafe extern "C" fn(*mut c_void, *mut c_void),- pub exception_destroy: unsafe extern "C" fn(*mut c_void),- pub store_root_visit_edges: unsafe extern "C" fn(*mut c_void, *mut c_void),- pub store_root_destroy: unsafe extern "C" fn(*mut c_void),- pub entity_visit_edges: unsafe extern "C" fn(*mut c_void, *mut c_void),- pub entity_destroy: unsafe extern "C" fn(*mut c_void),-}-/// The allocators of the runtime's cell types, which LibGC requires to outlive every heap, so there is one set of/// them for the process, made with the first interface.struct Allocators {@@ -224,84 +219,68 @@ unsafe extern "C" fn class_name(_: *const c_void, length: *mut usize) -> *constNAME.as_ptr().cast()}-fn type_info(- cell_size: usize,- visit_edges: unsafe extern "C" fn(*mut c_void, *mut c_void),- destroy: Option<unsafe extern "C" fn(*mut c_void)>,- external_memory_size: Option<unsafe extern "C" fn(*const c_void) -> usize>,-) -> &'static CellTypeInfo {- Box::leak(Box::new(CellTypeInfo {- cell_size: cell_size as u32,+/// What LibGC knows each cell type by: its size and name, and the functions it visits and destroys cells with.+fn type_info(cell_type: CellType) -> (&'static CellTypeInfo, &'static str) {+ use super::{entity, gc};+ type VisitEdges = unsafe extern "C" fn(*mut c_void, *mut c_void);+ type Destroy = unsafe extern "C" fn(*mut c_void);+ type ExternalMemorySize = unsafe extern "C" fn(*const c_void) -> usize;+ let (visit_edges, destroy, external_memory_size, name): (VisitEdges, Destroy, Option<ExternalMemorySize>, _) =+ match cell_type {+ CellType::Object(_) => (+ gc::object_visit_edges,+ gc::object_destroy,+ Some(gc::object_external_memory_size),+ "WebAssembly object",+ ),+ CellType::Rtt => (gc::rtt_visit_edges, gc::rtt_destroy, None, "WebAssembly runtime type"),+ CellType::Exception => (+ gc::exception_visit_edges,+ gc::exception_destroy,+ None,+ "WebAssembly exception",+ ),+ CellType::StoreRoot => (+ gc::store_root_visit_edges,+ gc::store_root_destroy,+ None,+ "WebAssembly store",+ ),+ CellType::Entity(kind) => (+ entity::entity_visit_edges,+ entity::entity_destroy,+ None,+ entity::ENTITY_NAMES[kind],+ ),+ };+ let info = Box::leak(Box::new(CellTypeInfo {+ cell_size: cell_size(cell_type) as u32,alignment: 16,kind: CELL_KIND_OTHER,visit_edges,finalize: None,- destroy,+ destroy: Some(destroy),external_memory_size,class_name: Some(class_name),- }))+ }));+ (info, name)}impl Allocators {- fn new(interface: &GcInterface, functions: &CellFunctions) -> Self {- let create = |info: &'static CellTypeInfo, name: &'static str| unsafe {- (interface.gc_allocator_create)(info, name.as_ptr().cast(), name.len())+ fn new(interface: &GcInterface) -> Self {+ let create = |cell_type: CellType| {+ let (info, name) = type_info(cell_type);+ unsafe { (interface.gc_allocator_create)(info, name.as_ptr().cast(), name.len()) }};- let objects = OBJECT_DATA_SIZE_CLASSES- .iter()- .map(|&data_size| {- create(- type_info(- crate::abi::OBJECT_INLINE_DATA_OFFSET + data_size,- functions.object_visit_edges,- Some(functions.object_destroy),- Some(functions.object_external_memory_size),- ),- "WebAssembly object",- )- })- .collect();Self {- objects,- rtt: create(- type_info(- CELL_HEADER_SIZE + size_of::<crate::abi::Rtt>().next_multiple_of(16),- functions.rtt_visit_edges,- Some(functions.rtt_destroy),- None,- ),- "WebAssembly runtime type",- ),- exception: create(- type_info(- super::gc::EXCEPTION_CELL_SIZE,- functions.exception_visit_edges,- Some(functions.exception_destroy),- None,- ),- "WebAssembly exception",- ),- store_root: create(- type_info(- 32,- functions.store_root_visit_edges,- Some(functions.store_root_destroy),- None,- ),- "WebAssembly store",- ),+ objects: (0..OBJECT_DATA_SIZE_CLASSES.len())+ .map(|class| create(CellType::Object(class)))+ .collect(),+ rtt: create(CellType::Rtt),+ exception: create(CellType::Exception),+ store_root: create(CellType::StoreRoot),entities: (0..super::entity::ENTITY_KIND_COUNT)- .map(|kind| {- create(- type_info(- cell_size(CellType::Entity(kind)),- functions.entity_visit_edges,- Some(functions.entity_destroy),- None,- ),- super::entity::ENTITY_NAMES[kind],- )- })+ .map(|kind| create(CellType::Entity(kind))).collect(),}}@@ -342,7 +321,7 @@ pub enum Heap {}impl Heap {- pub fn new(interface: Option<GcInterface>, functions: &CellFunctions) -> Self {+ pub fn new(interface: Option<GcInterface>) -> Self {let Some(interface) = interface else {return Self::Standalone(core::cell::RefCell::new(Vec::new()));};@@ -362,7 +341,7 @@ impl Heap {.all(|&offset| (offset as usize) < CELL_FLAGS_OFFSET),"the runtime's flags follow LibGC's cell header");- let allocators = ALLOCATORS.get_or_init(|| Allocators::new(&interface, functions));+ let allocators = ALLOCATORS.get_or_init(|| Allocators::new(&interface));FUNCTIONS.get_or_init(|| Functions(interface));Self::Gc(Box::new(GcHeap {interface,diff --git a/Libraries/LibWasm/Engine/src/runtime/helpers.rs b/Libraries/LibWasm/Engine/src/runtime/helpers.rsindex e2816a22614..aace3a65775 100644--- a/Libraries/LibWasm/Engine/src/runtime/helpers.rs+++ b/Libraries/LibWasm/Engine/src/runtime/helpers.rs@@ -7,7 +7,7 @@//! The runtime services the interpreter calls for what needs the runtime: growing memories and tables, and calling//! host functions. Each takes the execution context, whose `arguments` hold the operands.-use super::{FunctionInstance, FunctionKind, MemoryAddress, Store, TableAddress, Trap, Value};+use super::{FunctionAddress, FunctionInstance, FunctionKind, MemoryAddress, Store, TableAddress, Trap};use crate::abi::{ExecutionContext, FRAME_FUNCTION, FRAME_HEADER_SIZE, FRAME_INSTANCE, FRAME_RETURN_IP, FRAME_SAVED_FP, MemoryData,TableData,@@ -15,33 +15,7 @@ use crate::abi::{use crate::futex::{self, AtomicWaitResult, WaitWord};use crate::validator::{CatchKind, NO_EXCEPTION_LOCAL, NOT_DELEGATED};-/// Export the runtime functions under the names the interpreter calls them by. The interpreter calls them with the-/// System V calling convention on every x86-64 target, Windows included.-macro_rules! export_to_interpreter {- ($($symbol:ident => $function:ident),* $(,)?) => {- $(- /// # Safety- ///- /// Only the interpreter calls this, with the context of the store it runs in.- #[cfg(all(target_arch = "x86_64", windows))]- #[unsafe(no_mangle)]- pub unsafe extern "sysv64" fn $symbol(context: *mut ExecutionContext) -> u64 {- unsafe { $function(context) }- }-- /// # Safety- ///- /// Only the interpreter calls this, with the context of the store it runs in.- #[cfg(not(all(target_arch = "x86_64", windows)))]- #[unsafe(no_mangle)]- pub unsafe extern "C" fn $symbol(context: *mut ExecutionContext) -> u64 {- unsafe { $function(context) }- }- )*- };-}--export_to_interpreter! {+export_runtime_functions! {wasm_runtime_memory_grow => memory_grow,wasm_runtime_table_grow => table_grow,wasm_runtime_call_host => call_host,@@ -113,43 +87,26 @@ unsafe fn call_host(context: *mut ExecutionContext) -> u64 {let return_ip = (*context).arguments[2];let frame = (*context).arguments[3];let store = store_of(context);- let FunctionKind::Host(callback) = &function.kind else {- return 0;- };- let callback = callback.clone();- let parameter_slots = function.header.param_slots as usize;- let slots = ak::slice_from_raw_parts(top, parameter_slots);- // The operand stack grows down, so the first argument is in the highest slots.- let mut arguments = Vec::with_capacity(function.ty.params.len());- let mut slot = parameter_slots;- for &ty in &function.ty.params {- slot -= ty.slot_count() as usize;- arguments.push(Value::from_slots(ty, &slots[slot..]));- }- let results = match callback.call(store, &arguments) {- Ok(results) => results,+ let address = FunctionAddress::from_ptr(function);+ // The results replace the arguments, at the bottom of the arguments' slots.+ let return_top = top+ .add(function.header.param_slots as usize)+ .sub(function.header.result_slots as usize);+ match store.call_host_slots(address, top, return_top) {+ Ok(()) => return_top as u64,Err(Trap::UncaughtException(exception)) => {// The exception continues in the caller, as if the call instruction had thrown it.if unwind(context, store, exception, frame, return_ip - 1) {return 1;}store.pending_trap = Some(Trap::UncaughtException(exception));- return 0;+ 0}Err(trap) => {store.pending_trap = Some(trap);- return 0;+ 0}- };- let mut result_slots = Vec::new();- for result in results.iter().rev() {- result.push_slots(&mut result_slots);- }- let return_top = top.add(parameter_slots).sub(result_slots.len());- for (index, value) in result_slots.iter().enumerate() {- *return_top.add(index) = *value;}- return_top as u64}}diff --git a/Libraries/LibWasm/Engine/src/runtime/interpreter.rs b/Libraries/LibWasm/Engine/src/runtime/interpreter.rsindex 4eed4d685c4..09935af4212 100644--- a/Libraries/LibWasm/Engine/src/runtime/interpreter.rs+++ b/Libraries/LibWasm/Engine/src/runtime/interpreter.rs@@ -6,15 +6,10 @@//! Entering the interpreter, and turning faulting memory accesses inside it into traps.-use crate::abi::EntryRecord;+use crate::abi::{EntryRecord, OPCODE_CALL_ENTRY, OPCODE_ENTER, OPCODE_EXIT};-/// The pseudo-instructions the runtime enters the interpreter at: Enter pushes the arguments, CallEntry calls the-/// function, and the function returns to Exit, which leaves the interpreter.-static ENTRY_CODE: [u8; 3] = [0xf0, 0xf3, 0xf1];--/// The opcode of the pseudo-instruction a faulting memory access continues at.-#[cfg(wasm_interpreter)]-const MEMORY_FAULT_OPCODE: usize = 0xf2;+/// The code the runtime enters the interpreter at (see `OPCODE_ENTER`).+static ENTRY_CODE: [u8; 3] = [OPCODE_ENTER, OPCODE_CALL_ENTRY, OPCODE_EXIT];// The interpreter uses the System V calling convention on every x86-64 target, Windows included.#[cfg(all(wasm_interpreter, not(all(target_arch = "x86_64", windows))))]@@ -66,7 +61,7 @@ pub fn dispatch_table_entry(opcode: u8) -> usize {#[cfg(wasm_interpreter)]fn memory_fault_handler() -> usize {- unsafe { wasm_interpreter_dispatch_table[MEMORY_FAULT_OPCODE] }+ dispatch_table_entry(crate::abi::OPCODE_MEMORY_FAULT)}/// The CPU features the interpreter's code uses and that the target's baseline guarantees: x86-64-v3 on x86-64, anddiff --git a/Libraries/LibWasm/Engine/src/runtime/jit.rs b/Libraries/LibWasm/Engine/src/runtime/jit.rsindex 0478f969a79..d1172e6b404 100644--- a/Libraries/LibWasm/Engine/src/runtime/jit.rs+++ b/Libraries/LibWasm/Engine/src/runtime/jit.rs@@ -33,7 +33,7 @@//! default).use super::ranges::RangeSet;-use super::{FunctionAddress, FunctionInstance, FunctionKind, InstanceAddress, Store, Trap, Value};+use super::{FunctionAddress, FunctionInstance, FunctionKind, InstanceAddress, Store, Trap};use crate::abi::ExecutionContext;use crate::types::ValType;use std::sync::OnceLock;@@ -62,6 +62,7 @@ pub struct Options {pub threads: u32,}+#[cfg(all(unix, any(target_arch = "x86_64", target_arch = "aarch64")))]impl Options {fn compile_options(self) -> libwasm_jit::Options {libwasm_jit::Options {@@ -126,33 +127,7 @@ pub fn options() -> Options {})}-/// Export the runtime functions compiled code and the interpreter call, under the names the interpreter calls them-/// by, with the System V calling convention on every x86-64 target.-macro_rules! export {- ($($symbol:ident => $function:ident),* $(,)?) => {- $(- /// # Safety- ///- /// Only the interpreter and compiled code call this, with the context of the store they run in.- #[cfg(all(target_arch = "x86_64", windows))]- #[unsafe(no_mangle)]- pub unsafe extern "sysv64" fn $symbol(context: *mut ExecutionContext) -> u64 {- unsafe { $function(context) }- }-- /// # Safety- ///- /// Only the interpreter and compiled code call this, with the context of the store they run in.- #[cfg(not(all(target_arch = "x86_64", windows)))]- #[unsafe(no_mangle)]- pub unsafe extern "C" fn $symbol(context: *mut ExecutionContext) -> u64 {- unsafe { $function(context) }- }- )*- };-}--export! {+export_runtime_functions! {wasm_runtime_call_compiled => call_compiled,wasm_runtime_call_from_native => call_from_native,wasm_runtime_tier_up => tier_up,@@ -181,7 +156,7 @@ unsafe fn tier_up(context: *mut ExecutionContext) -> u64 {}let at_loop = reason == 1;// NB: The interpreter charges a call once this returns, so every budget covers that.- let state = native::compile_function(store, address);+ let state = native::compile_function(store, address, false);address.get_mut().header.tier_up_budget = match state {// A compiled function keeps a budget, so that frames of it still running in the interpreter continue// compiled at the next loop header they reach.@@ -254,6 +229,10 @@ unsafe fn throw_from_native(context: *mut ExecutionContext) -> u64 {}}+/// How many calls from compiled code into the interpreter may be in progress before the runtime compiles the+/// functions it calls that way right away.+const INTERPRETER_CALLS_FROM_NATIVE_BEFORE_COMPILING: u32 = 16;+/// The budget of a function whose compile is pending: how much it runs in the interpreter before the runtime looks/// for the compile's result again.const POLL_BUDGET: u32 = 500;@@ -404,34 +383,11 @@ pub unsafe fn redirect_fault(_context: *mut libc::c_void) -> bool {}/// Appends a line for code at `address` to the process's perf map.+#[cfg(all(unix, any(target_arch = "x86_64", target_arch = "aarch64")))]fn write_perf_map_entry(address: u64, size: usize, name: &str) {let _ = ak::perf_map::write_perf_map_entry(address as usize, size, name);}-/// The TRAP_* code a trap of the runtime continues as in the interpreter, which keeps the details in the store.-fn trap_code(trap: &Trap) -> u32 {- use crate::abi::*;- match trap {- Trap::Unreachable => TRAP_UNREACHABLE,- Trap::StackExhausted => TRAP_STACK_EXHAUSTED,- Trap::MemoryOutOfBounds => TRAP_MEMORY_OUT_OF_BOUNDS,- Trap::IntegerDivideByZero => TRAP_INTEGER_DIVIDE_BY_ZERO,- Trap::IntegerOverflow => TRAP_INTEGER_OVERFLOW,- Trap::InvalidConversion => TRAP_INVALID_CONVERSION,- Trap::UndefinedElement => TRAP_UNDEFINED_ELEMENT,- Trap::UninitializedElement => TRAP_UNINITIALIZED_ELEMENT,- Trap::IndirectCallTypeMismatch => TRAP_INDIRECT_CALL_TYPE_MISMATCH,- Trap::TableOutOfBounds => TRAP_TABLE_OUT_OF_BOUNDS,- Trap::NullReference => TRAP_NULL_REFERENCE,- Trap::CastFailure => TRAP_CAST_FAILURE,- Trap::ArrayOutOfBounds => TRAP_ARRAY_OUT_OF_BOUNDS,- Trap::UnalignedAtomic => TRAP_UNALIGNED_ATOMIC,- Trap::ExpectedSharedMemory => TRAP_EXPECTED_SHARED_MEMORY,- Trap::Host(_) => TRAP_RUNTIME,- Trap::UncaughtException(_) => TRAP_UNCAUGHT_EXCEPTION,- }-}-fn ir_type(ty: ValType) -> libwasm_jit::ir::Type {libwasm_jit::builder::ir_type(ty).expect("the JIT has a type for every value")}@@ -453,9 +409,17 @@ pub struct CallShape {/// The slots of the parameters' home area, after which the result area pointer is, and where the result area/// starts.parameter_slots: usize,+ #[cfg_attr(+ not(all(unix, any(target_arch = "x86_64", target_arch = "aarch64"))),+ allow(dead_code)+ )]result_area_slot: usize,/// The slots of the outgoing area: the home slots, and the result area pointer and the result area if there is/// one.+ #[cfg_attr(+ not(all(unix, any(target_arch = "x86_64", target_arch = "aarch64"))),+ allow(dead_code)+ )]image_slots: usize,has_result_area: bool,}@@ -608,26 +572,19 @@ unsafe fn call_from_native(context: *mut ExecutionContext) -> u64 {}}let outcome = if let FunctionKind::Host(_) = function.kind {- // NB: Host functions take and return values.- let values: Vec<Value> = function- .ty- .params- .iter()- .zip(&shape.params)- .map(|(&ty, param)| {- let start = parameter_slots - param.home - param.slots;- Value::from_slots(ty, &arguments[start..])- })- .collect();- store.invoke(address, &values).map(|values| {- let mut slots = Vec::with_capacity(result_slots);- for value in values.iter().rev() {- value.push_slots(&mut slots);- }- results.copy_from_slice(&slots);- })+ store.call_host_slots(address, arguments.as_ptr(), results.as_mut_ptr())} else {- store.invoke_slots(address, arguments, results)+ // NB: Tail calls from compiled code into the interpreter come through here, and the interpreter's tail+ // calls into compiled code go through the runtime, so functions that tail call each other across+ // the tiers keep a native frame per call until they are all compiled. Once a few such calls are in+ // progress, the function is compiled here and now instead of waiting for its compile thread.+ if store.interpreter_calls_from_native >= INTERPRETER_CALLS_FROM_NATIVE_BEFORE_COMPILING {+ native::compile_function(store, address, true);+ }+ store.interpreter_calls_from_native += 1;+ let outcome = store.invoke_slots(address, arguments, results);+ store.interpreter_calls_from_native -= 1;+ outcome};match outcome {Ok(()) => {}@@ -637,7 +594,7 @@ unsafe fn call_from_native(context: *mut ExecutionContext) -> u64 {return libwasm_jit::stubs::ADAPTER_RESUME;}Err(trap) => {- let code = trap_code(&trap);+ let code = trap.code();store.pending_trap = Some(trap);return u64::from(code);}@@ -902,7 +859,7 @@ mod native {let (outer, wide_function) = (export("outer"), export("wide"));wide.set(Some(wide_function));// The function whose frames the traps skip runs compiled, with a call image too large for the stack.- while super::compile_function(&mut store, wide_function) != super::CompileState::Compiled {+ while super::compile_function(&mut store, wide_function, false) != super::CompileState::Compiled {std::thread::sleep(std::time::Duration::from_millis(1));}store.invoke(outer, &[]).expect("the host function returns");@@ -910,6 +867,31 @@ mod native {assert_eq!(super::large_images_in_use(), 0);}+ #[test]+ fn tail_calls_across_tiers_keep_the_stack_bounded() {+ use crate::runtime::{ExternValue, Store, Value};+ if !crate::runtime::jit::enabled() {+ return;+ }+ let bytes = include_bytes!("../../tests/fixtures/tail_calls_across_tiers.wasm");+ let module = Arc::new(crate::compile(bytes).expect("the module is valid"));+ let mut store = Store::new();+ let instance = store.instantiate(module, &[]).expect("the module instantiates");+ let export = |name| match store.instance(instance).export(name) {+ Some(ExternValue::Function(function)) => function,+ _ => panic!("no function {name}"),+ };+ let (even, odd) = (export("even"), export("odd"));+ // NB: Even runs compiled, and odd runs interpreted for as long as it does not ask for its compile, as if+ // its compile thread never finished it.+ assert_eq!(+ super::compile_function(&mut store, even, true),+ super::CompileState::Compiled+ );+ unsafe { odd.get_mut() }.header.tier_up_budget = u32::MAX;+ assert_eq!(store.invoke(even, &[Value::I64(1_000_000)]), Ok(vec![Value::I64(44)]));+ }+#[test]fn a_compile_finishing_after_its_module_died_maps_nothing() {// (module (func))@@ -950,6 +932,10 @@ mod native {struct Finished {key: CompileKey,code: Option<CompiledFunction>,+ /// The module the compile is of. It keeps the module's address from going to another module until the+ /// result is installed: a store that forgot the module meanwhile would install the code for the module at+ /// that address, which the key also names.+ _module: Weak<Module>,}/// Compiles `request`, or returns None if the compile fails.@@ -997,7 +983,11 @@ mod native {};let code = compile(&mut context, &job.request);// NB: The store may be gone, and its results with it.- let _ = job.reply.send(Finished { key: job.key, code });+ let _ = job.reply.send(Finished {+ key: job.key,+ code,+ _module: Arc::downgrade(&job.request.module),+ });}});// NB: The JIT needs one thread. If the process cannot start more, it compiles on those it started.@@ -1128,6 +1118,10 @@ mod native {else {return;};+ // NB: A compile thread may finish a function that was compiled here and now while it worked on it.+ if module.code.contains_key(&(key.function, key.osr)) {+ return;+ }let entry = compiled.and_then(|compiled| Some((module.add_code(&compiled.code)?, compiled)));let Some((entry, compiled)) = entry else {module.failed.insert((key.function, key.osr));@@ -1164,21 +1158,21 @@ mod native {});}- /// Where the compile of `key` is, after compiling it here and now in sync mode, or else having it compiled- /// in the background.- fn compile(&mut self, key: CompileKey) -> CompileState {+ /// Where the compile of `key` is, after compiling it here and now in sync mode or if `now`, or else having it+ /// compiled in the background.+ fn compile(&mut self, key: CompileKey, now: bool) -> CompileState {if self.entry(key).is_some() {return CompileState::Compiled;}if self.modules[&key.module].failed.contains(&(key.function, key.osr)) {return CompileState::Failed;}- if super::options().sync {+ if super::options().sync || now {let code = self.request(key).and_then(|request| compile(&mut self.context, &request));self.finish(key, code);- return self.compile(key);+ return self.compile(key, false);}if self.pending.insert(key) {self.submit(key);@@ -1224,7 +1218,7 @@ mod native {} else {finished.extend(receiver.try_iter());}- for Finished { key, code } in finished {+ for Finished { key, code, .. } in finished {self.pending.remove(&key);self.finish(key, code);}@@ -1279,12 +1273,12 @@ mod native {let function = unsafe { address.get() };if let FunctionKind::Wasm { module, index, .. } = &function.kind {let key = jit.key(module, *index, None);- jit.compile(key);+ jit.compile(key, false);}}jit.take_finished(true);for address in functions {- if compile_function(store, address) == CompileState::Pending {+ if compile_function(store, address, false) == CompileState::Pending {// NB: Eager functions have no budget, so one whose compile is late asks for it like a hot one.unsafe { address.get_mut() }.header.tier_up_budget = super::POLL_BUDGET + crate::abi::TIER_UP_CALL_COST;}@@ -1292,8 +1286,8 @@ mod native {}/// Compiles a WebAssembly function, unless the store compiled its module's function already, and installs the- /// code once there is some.- pub fn compile_function(store: &mut Store, address: FunctionAddress) -> CompileState {+ /// code once there is some. With `now`, compiles it on this thread even if a compile thread has it.+ pub fn compile_function(store: &mut Store, address: FunctionAddress, now: bool) -> CompileState {let jit = store.jit.get_or_insert_with(Default::default);if jit.disabled {return CompileState::Failed;@@ -1304,7 +1298,7 @@ mod native {return CompileState::Failed;};let key = jit.key(module, *index, None);- let state = jit.compile(key);+ let state = jit.compile(key, now);if state == CompileState::Compiled {function.header.native_entry = jit.entry(key).expect("the function is compiled");function.header.kind = FUNCTION_KIND_COMPILED;@@ -1465,7 +1459,7 @@ mod native {return LoopEntry::Never;}let key = jit.key(module, *index, Some(offset));- match jit.compile(key) {+ match jit.compile(key, false) {CompileState::Compiled => {}CompileState::Pending => return LoopEntry::Pending,CompileState::Failed => return LoopEntry::Never,@@ -1480,7 +1474,10 @@ mod native {}}+// NB: The interface of the native module, for targets without a code generator, where the JIT is off and most of it+// goes unused.#[cfg(not(all(unix, any(target_arch = "x86_64", target_arch = "aarch64"))))]+#[allow(dead_code)]mod native {use crate::abi::ExecutionContext;use crate::runtime::{InstanceAddress, Store};@@ -1527,7 +1524,7 @@ mod native {pub fn compile_instance(_store: &mut Store, _instance: InstanceAddress) {}- pub fn compile_function(_store: &mut Store, _address: crate::runtime::FunctionAddress) -> CompileState {+ pub fn compile_function(_store: &mut Store, _address: crate::runtime::FunctionAddress, _now: bool) -> CompileState {CompileState::Failed}diff --git a/Libraries/LibWasm/Engine/src/runtime/memory.rs b/Libraries/LibWasm/Engine/src/runtime/memory.rsindex 01e57d3ebf4..5eabc818f1d 100644--- a/Libraries/LibWasm/Engine/src/runtime/memory.rs+++ b/Libraries/LibWasm/Engine/src/runtime/memory.rs@@ -201,10 +201,6 @@ impl MemoryInstance {}}- pub fn maximum_pages(&self) -> u64 {- self.maximum_pages- }-/// Grow by `delta` pages, returning the previous size in pages.pub fn grow(&mut self, delta: u64) -> Option<u64> {let previous = self.pages;diff --git a/Libraries/LibWasm/Engine/src/runtime/mod.rs b/Libraries/LibWasm/Engine/src/runtime/mod.rsindex 0366658daac..235afef4a65 100644--- a/Libraries/LibWasm/Engine/src/runtime/mod.rs+++ b/Libraries/LibWasm/Engine/src/runtime/mod.rs@@ -7,6 +7,32 @@//! The runtime: the store, which holds what the entities of a thread share (types, runtime types, the interpreter's//! context), the entities themselves (see entity.rs), instantiation, and calling into the interpreter.+/// Export the runtime functions that the interpreter and compiled code call, under the names they call them by, with+/// the System V calling convention on every x86-64 target, Windows included.+macro_rules! export_runtime_functions {+ ($($symbol:ident => $function:ident),* $(,)?) => {+ $(+ /// # Safety+ ///+ /// Only the interpreter and compiled code call this, with the context of the store they run in.+ #[cfg(all(target_arch = "x86_64", windows))]+ #[unsafe(no_mangle)]+ pub unsafe extern "sysv64" fn $symbol(context: *mut ExecutionContext) -> u64 {+ unsafe { $function(context) }+ }++ /// # Safety+ ///+ /// Only the interpreter and compiled code call this, with the context of the store they run in.+ #[cfg(not(all(target_arch = "x86_64", windows)))]+ #[unsafe(no_mangle)]+ pub unsafe extern "C" fn $symbol(context: *mut ExecutionContext) -> u64 {+ unsafe { $function(context) }+ }+ )*+ };+}+pub mod constant;pub mod entity;pub mod gc;@@ -19,7 +45,7 @@ pub mod ranges;use crate::abi::{EntryRecord, ExecutionContext, FRAME_HEADER_SIZE, FUNCTION_KIND_HOST, FUNCTION_KIND_WASM,- FUNCTION_KIND_WASM_VECTOR, FunctionHeader, InstanceData, MemoryData, SPILL_AREA_SIZE, Segment, TableData,+ FUNCTION_KIND_WASM_VECTOR, FunctionHeader, InstanceData, SPILL_AREA_SIZE, Segment, TableData,};use crate::module::{DataMode, ElementItems, ElementMode, ExternalKind, ImportDescription, Module};use crate::types::{FuncType, GlobalType, HeapType, RefType, TableType, TypeCanonicalizer, ValType};@@ -54,20 +80,23 @@ impl Value {}}- /// Append the slots of this value in memory order: a v128's low half first.- pub fn push_slots(self, slots: &mut Vec<u64>) {+ /// The value's slots in memory order (a v128's low half first), and how many of the two it takes.+ pub fn to_slots(self) -> ([u64; 2], usize) {match self {- Self::I32(value) => slots.push(u64::from(value as u32)),- Self::I64(value) => slots.push(value as u64),- Self::F32(bits) => slots.push(u64::from(bits)),- Self::F64(bits) | Self::Ref(bits) => slots.push(bits),- Self::V128(bits) => {- slots.push(bits as u64);- slots.push((bits >> 64) as u64);- }+ Self::I32(value) => ([u64::from(value as u32), 0], 1),+ Self::I64(value) => ([value as u64, 0], 1),+ Self::F32(bits) => ([u64::from(bits), 0], 1),+ Self::F64(bits) | Self::Ref(bits) => ([bits, 0], 1),+ Self::V128(bits) => ([bits as u64, (bits >> 64) as u64], 2),}}+ /// Append the slots of this value in memory order: a v128's low half first.+ pub fn push_slots(self, slots: &mut Vec<u64>) {+ let (value, count) = self.to_slots();+ slots.extend_from_slice(&value[..count]);+ }+pub fn from_slots(ty: ValType, slots: &[u64]) -> Self {match ty {ValType::I32 => Self::I32(slots[0] as u32 as i32),@@ -80,71 +109,62 @@ impl Value {}}-#[derive(Debug, Clone, PartialEq, Eq)]-pub enum Trap {- Unreachable,- StackExhausted,- MemoryOutOfBounds,- IntegerDivideByZero,- IntegerOverflow,- InvalidConversion,- UndefinedElement,- UninitializedElement,- IndirectCallTypeMismatch,- TableOutOfBounds,- NullReference,- CastFailure,- ArrayOutOfBounds,- UnalignedAtomic,- ExpectedSharedMemory,- Host(String),- UncaughtException(u64),-}--impl Trap {- fn from_code(code: u32, pending: Option<Trap>) -> Self {- use crate::abi::*;- match code {- TRAP_UNREACHABLE => Self::Unreachable,- TRAP_STACK_EXHAUSTED => Self::StackExhausted,- TRAP_MEMORY_OUT_OF_BOUNDS => Self::MemoryOutOfBounds,- TRAP_INTEGER_DIVIDE_BY_ZERO => Self::IntegerDivideByZero,- TRAP_INTEGER_OVERFLOW => Self::IntegerOverflow,- TRAP_INVALID_CONVERSION => Self::InvalidConversion,- TRAP_UNDEFINED_ELEMENT => Self::UndefinedElement,- TRAP_UNINITIALIZED_ELEMENT => Self::UninitializedElement,- TRAP_INDIRECT_CALL_TYPE_MISMATCH => Self::IndirectCallTypeMismatch,- TRAP_TABLE_OUT_OF_BOUNDS => Self::TableOutOfBounds,- TRAP_NULL_REFERENCE => Self::NullReference,- TRAP_CAST_FAILURE => Self::CastFailure,- TRAP_ARRAY_OUT_OF_BOUNDS => Self::ArrayOutOfBounds,- TRAP_UNALIGNED_ATOMIC => Self::UnalignedAtomic,- TRAP_EXPECTED_SHARED_MEMORY => Self::ExpectedSharedMemory,- _ => pending.unwrap_or_else(|| Self::Host("the runtime reported a trap without details".to_string())),+/// Declares `Trap`, with a variant for each trap that has a `TRAP_*` code and a message of its own, besides traps of+/// the host and uncaught exceptions.+macro_rules! traps {+ ($($variant:ident = $code:ident, $message:literal;)*) => {+ #[derive(Debug, Clone, PartialEq, Eq)]+ pub enum Trap {+ $($variant,)*+ Host(String),+ UncaughtException(u64),}- }- pub fn message(&self) -> String {- match self {- Self::Unreachable => "unreachable".to_string(),- Self::StackExhausted => "call stack exhausted".to_string(),- Self::MemoryOutOfBounds => "Memory access out of bounds".to_string(),- Self::IntegerDivideByZero => "integer divide by zero".to_string(),- Self::IntegerOverflow => "integer overflow".to_string(),- Self::InvalidConversion => "invalid conversion to integer".to_string(),- Self::UndefinedElement => "undefined element".to_string(),- Self::UninitializedElement => "uninitialized element".to_string(),- Self::IndirectCallTypeMismatch => "indirect call type mismatch".to_string(),- Self::TableOutOfBounds => "out of bounds table access".to_string(),- Self::NullReference => "null reference".to_string(),- Self::CastFailure => "cast failure".to_string(),- Self::ArrayOutOfBounds => "out of bounds array access".to_string(),- Self::Host(message) => message.clone(),- Self::UncaughtException(_) => "uncaught exception".to_string(),- Self::UnalignedAtomic => "Unaligned atomic memory access".to_string(),- Self::ExpectedSharedMemory => "Expected shared memory".to_string(),+ impl Trap {+ fn from_code(code: u32, pending: Option<Trap>) -> Self {+ match code {+ $(crate::abi::$code => Self::$variant,)*+ _ => pending+ .unwrap_or_else(|| Self::Host("the runtime reported a trap without details".to_string())),+ }+ }++ /// The `TRAP_*` code the interpreter and compiled code know the trap by.+ pub fn code(&self) -> u32 {+ match self {+ $(Self::$variant => crate::abi::$code,)*+ Self::Host(_) => crate::abi::TRAP_RUNTIME,+ Self::UncaughtException(_) => crate::abi::TRAP_UNCAUGHT_EXCEPTION,+ }+ }++ pub fn message(&self) -> String {+ match self {+ $(Self::$variant => $message.to_string(),)*+ Self::Host(message) => message.clone(),+ Self::UncaughtException(_) => "uncaught exception".to_string(),+ }+ }}- }+ };+}++traps! {+ Unreachable = TRAP_UNREACHABLE, "unreachable";+ StackExhausted = TRAP_STACK_EXHAUSTED, "call stack exhausted";+ MemoryOutOfBounds = TRAP_MEMORY_OUT_OF_BOUNDS, "Memory access out of bounds";+ IntegerDivideByZero = TRAP_INTEGER_DIVIDE_BY_ZERO, "integer divide by zero";+ IntegerOverflow = TRAP_INTEGER_OVERFLOW, "integer overflow";+ InvalidConversion = TRAP_INVALID_CONVERSION, "invalid conversion to integer";+ UndefinedElement = TRAP_UNDEFINED_ELEMENT, "undefined element";+ UninitializedElement = TRAP_UNINITIALIZED_ELEMENT, "uninitialized element";+ IndirectCallTypeMismatch = TRAP_INDIRECT_CALL_TYPE_MISMATCH, "indirect call type mismatch";+ TableOutOfBounds = TRAP_TABLE_OUT_OF_BOUNDS, "out of bounds table access";+ NullReference = TRAP_NULL_REFERENCE, "null reference";+ CastFailure = TRAP_CAST_FAILURE, "cast failure";+ ArrayOutOfBounds = TRAP_ARRAY_OUT_OF_BOUNDS, "out of bounds array access";+ UnalignedAtomic = TRAP_UNALIGNED_ATOMIC, "Unaligned atomic memory access";+ ExpectedSharedMemory = TRAP_EXPECTED_SHARED_MEMORY, "Expected shared memory";}pub type FunctionAddress = entity::Handle<FunctionInstance>;@@ -178,7 +198,7 @@ pub trait HostFunction {/// Visit the cells the function refers to, which its function keeps alive.fn visit_edges(&self, _visitor: &heap::Visitor) {}- /// The data of the embedder's of a function made through the C interface.+ /// The embedder's data of a function made through the C interface.fn user_data(&self) -> *mut core::ffi::c_void {core::ptr::null_mut()}@@ -277,9 +297,8 @@ impl GlobalInstance {}pub fn set(&mut self, value: Value) {- let mut slots = Vec::with_capacity(2);- value.push_slots(&mut slots);- self.value[..slots.len()].copy_from_slice(&slots);+ let (slots, count) = value.to_slots();+ self.value[..count].copy_from_slice(&slots[..count]);}}@@ -303,11 +322,6 @@ pub struct Instance {pub element_segments: Vec<Segment>,/// Each data segment, empty once dropped or used by instantiation.pub data_segments: Vec<Segment>,- function_headers: Vec<*const FunctionHeader>,- global_slots: Vec<*mut u64>,- table_datas: Vec<*mut TableData>,- memory_datas: Vec<*mut MemoryData>,- tag_identities: Vec<u64>,}impl Instance {@@ -341,10 +355,11 @@ pub struct Store {/// The type of each store-wide type identity, with its type indices replaced by identities, so that types of/// different modules can be compared.types: Vec<crate::types::SubType>,- /// The identity of each type in `types`: its index. This makes `types` usable as a type context.- identities: Vec<u32>,/// A trap a runtime function reported, which the interpreter only knows as TRAP_RUNTIME.pending_trap: Option<Trap>,+ /// The module `module_type_identities_of()` was last asked about, and its identities. An embedder asks about+ /// one module many times in a row while it links its imports.+ last_module_identities: Option<(std::sync::Weak<Module>, Rc<[u32]>)>,/// What runs after `memory.grow` grows a memory.pub memory_grow_callback: Option<Rc<dyn Fn(MemoryAddress)>>,/// Whether the agent the store runs code for may block, its [[CanBlock]]: `memory.atomic.wait` traps where it@@ -352,6 +367,8 @@ pub struct Store {pub can_block: bool,/// The store's compiled code, once it has some.jit: Option<jit::StoreJit>,+ /// How many calls from compiled code into the interpreter are in progress.+ interpreter_calls_from_native: u32,}impl Default for Store {@@ -396,15 +413,16 @@ impl Store {}),canonicalizer: TypeCanonicalizer::new(),types: Vec::new(),- identities: Vec::new(),pending_trap: None,- heap: heap::Heap::new(interface, &gc::CELL_FUNCTIONS),+ last_module_identities: None,+ heap: heap::Heap::new(interface),root_cell: std::ptr::null_mut(),root: None,rtt_pointers: Vec::new(),memory_grow_callback: None,can_block: true,jit: None,+ interpreter_calls_from_native: 0,}}@@ -478,7 +496,6 @@ impl Store {}let first = self.types.len() as u32;for sub_type in group {- self.identities.push(self.types.len() as u32);self.types.push(sub_type.clone());}// Types of a group refer to each other, so they all have to be there before their runtime types are made.@@ -511,6 +528,18 @@ impl Store {type_identities}+ /// `module_type_identities()`, remembered for the last module asked about.+ pub fn module_type_identities_of(&mut self, module: &Arc<Module>) -> Rc<[u32]> {+ if let Some((last, identities)) = &self.last_module_identities+ && last.upgrade().is_some_and(|last| Arc::ptr_eq(&last, module))+ {+ return identities.clone();+ }+ let identities: Rc<[u32]> = self.module_type_identities(module).into();+ self.last_module_identities = Some((Arc::downgrade(module), identities.clone()));+ identities+ }+/// Whether a non-null reference matches `heap`, whose concrete types are identities. References of the any/// hierarchy must be in their internal form: i31 references, GC objects, or host references.pub fn reference_matches(&self, reference: u64, heap: HeapType) -> bool {@@ -547,7 +576,7 @@ impl Store {fn type_context(&self) -> crate::validator::TypeContext<'_> {crate::validator::TypeContext {types: &self.types,- identities: &self.identities,+ identities: None,}}@@ -635,7 +664,8 @@ impl Store {return link_error("wrong number of imports");}- let type_identities = self.module_type_identities(&module);+ // NB: The embedder usually asked about the module's types while it linked its imports.+ let type_identities = self.module_type_identities_of(&module).to_vec();// Types of the store have identities where the module's types have indices.let module_identities = type_identities.clone();@@ -741,12 +771,7 @@ impl Store {length: u64::from(data.bytes.end - data.bytes.start),}).collect(),- function_headers: Vec::new(),- global_slots: Vec::new(),tags: Vec::new(),- tag_identities: Vec::new(),- table_datas: Vec::new(),- memory_datas: Vec::new(),},);let instance = unsafe { instance_address.get_mut() };@@ -1016,14 +1041,17 @@ impl Store {module: &Module,expression: &crate::module::ConstantExpression,) -> Result<u64, InstantiationError> {+ // NB: Evaluating may allocate in the store, but leaves the instance's vectors as they are.let instance = unsafe { instance.get() };- let (globals, functions, type_identities) = (- instance.globals.clone(),- instance.functions.clone(),- instance.type_identities.clone(),- );- match constant::evaluate(self, &globals, &functions, &type_identities, module, expression)- .map_err(InstantiationError::Trap)?+ match constant::evaluate(+ self,+ &instance.globals,+ &instance.functions,+ &instance.type_identities,+ module,+ expression,+ )+ .map_err(InstantiationError::Trap)?{Value::I32(value) => Ok(u64::from(value as u32)),Value::I64(value) => Ok(value as u64),@@ -1095,6 +1123,10 @@ impl Store {for argument in arguments.iter().rev() {argument.push_slots(&mut argument_slots);}+ // NB: The interpreter reads the function's parameter slots from the arguments, so they must have that many.+ if arguments.len() != function.ty.params.len() || argument_slots.len() != function.header.param_slots as usize {+ return Err(Trap::Host("the arguments do not match the function's type".to_string()));+ }let mut result_slots = vec![0u64; function.header.result_slots as usize];self.invoke_slots(address, &argument_slots, &mut result_slots)?;// The results are laid out as the operand stack holds them, the first one in the highest slots.@@ -1140,7 +1172,7 @@ impl Store {unsafe { interpreter::enter(&mut record) };// NB: A trap may have skipped calls into compiled code that held large images.jit::release_large_images(large_images);- if record.trap != 0 {+ if record.trap != crate::abi::TRAP_NONE {return Err(Trap::from_code(record.trap, self.pending_trap.take()));}Ok(())@@ -1153,37 +1185,76 @@ impl Store {let callback = callback.clone();callback.call(self, arguments)}++ /// Calls the host function at `address` with the arguments in `arguments`, its parameter slots in operand stack+ /// order (the first argument in the highest slots), and writes its result slots in that order to `results`.+ ///+ /// # Safety+ ///+ /// `arguments` must have the function's parameter slots and `results` room for its result slots. They may+ /// overlap: every argument is read before a result is written.+ pub(crate) unsafe fn call_host_slots(+ &mut self,+ address: FunctionAddress,+ arguments: *const u64,+ results: *mut u64,+ ) -> Result<(), Trap> {+ // NB: The function lives in a cell of the heap, not in the store, which the call may change.+ let function = unsafe { address.get() };+ let parameter_slots = function.header.param_slots as usize;+ let slots = unsafe { ak::slice_from_raw_parts(arguments, parameter_slots) };+ let mut values = Vec::with_capacity(function.ty.params.len());+ let mut slot = parameter_slots;+ for &ty in &function.ty.params {+ slot -= ty.slot_count() as usize;+ values.push(Value::from_slots(ty, &slots[slot..]));+ }+ let (result_count, result_slots) = (function.ty.results.len(), function.header.result_slots as usize);+ let values = self.call_host(address, &values)?;+ // NB: Results that do not match the function's type would not fit where they go.+ let slot_count: usize = values.iter().map(|value| value.to_slots().1).sum();+ if values.len() != result_count || slot_count != result_slots {+ return Err(Trap::Host(+ "a host function returned results that do not match its type".to_string(),+ ));+ }+ let mut next = results;+ for value in values.iter().rev() {+ let (value, count) = value.to_slots();+ unsafe {+ next.copy_from_nonoverlapping(value.as_ptr(), count);+ next = next.add(count);+ }+ }+ Ok(())+ }}/// Point the instance's interpreter-visible data at its current contents. The interpreter's view of each entity is at/// its handle.fn refresh_instance_data(instance: &mut Instance) {- instance.function_headers = instance- .functions- .iter()- .map(|address| address.as_ptr().cast_const().cast::<FunctionHeader>())- .collect();- instance.global_slots = instance.globals.iter().map(|address| address.as_ptr().cast()).collect();- instance.table_datas = instance.tables.iter().map(|address| address.as_ptr().cast()).collect();- instance.memory_datas = instance- .memories- .iter()- .map(|address| address.as_ptr().cast())- .collect();+ // NB: A handle is the address of its entity's interpreter view (see entity.rs), so the instance's vectors of+ // handles are the arrays of views the interpreter indexes.+ const {+ assert!(size_of::<FunctionAddress>() == size_of::<*const FunctionHeader>());+ assert!(core::mem::offset_of!(FunctionInstance, header) == 0);+ assert!(core::mem::offset_of!(GlobalInstance, value) == 0);+ assert!(core::mem::offset_of!(TableInstance, data) == 0);+ assert!(core::mem::offset_of!(memory::MemoryInstance, data) == 0);+ };let data = &mut instance.data;- data.functions = instance.function_headers.as_ptr();- data.function_count = instance.function_headers.len() as u32;- data.globals = instance.global_slots.as_ptr();- data.tables = instance.table_datas.as_ptr();- data.memories = instance.memory_datas.as_ptr();- data.memory_count = instance.memory_datas.len() as u32;+ data.functions = instance.functions.as_ptr().cast();+ data.function_count = instance.functions.len() as u32;+ data.globals = instance.globals.as_ptr().cast();+ data.tables = instance.tables.as_ptr().cast();+ data.memories = instance.memories.as_ptr().cast();+ data.memory_count = instance.memories.len() as u32;data.memory0_base = instance.memories.first().map_or(std::ptr::null_mut(), |address| unsafe { address.get() }.data.base);data.type_identities = instance.type_identities.as_ptr();- instance.tag_identities = instance.tags.iter().map(|address| address.as_ptr() as u64).collect();- instance.data.tags = instance.tag_identities.as_ptr();+ data.tags = instance.tags.as_ptr().cast();}fn limits_match(current: u64, current_max: Option<u64>, expected: &crate::types::Limits) -> bool {diff --git a/Libraries/LibWasm/Engine/src/runtime/ranges.rs b/Libraries/LibWasm/Engine/src/runtime/ranges.rsindex b84afdf0727..395f2e70d95 100644--- a/Libraries/LibWasm/Engine/src/runtime/ranges.rs+++ b/Libraries/LibWasm/Engine/src/runtime/ranges.rs@@ -4,8 +4,8 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! Sets of address ranges that the fault handler looks addresses up in: the reservations of memories, and later the-//! code of compiled functions. A lookup takes no lock and only reads memory that is never freed, so it is+//! Sets of address ranges that the fault handler looks addresses up in: the reservations of memories, and the code+//! of compiled functions. A lookup takes no lock and only reads memory that is never freed, so it is//! async-signal-safe and cannot be blocked by a thread that is adding or removing a range. Adding and removing take a//! lock among themselves.//!diff --git a/Libraries/LibWasm/Engine/src/wasi.rs b/Libraries/LibWasm/Engine/src/wasi.rsindex 18736125255..61d169c27d9 100644--- a/Libraries/LibWasm/Engine/src/wasi.rs+++ b/Libraries/LibWasm/Engine/src/wasi.rs@@ -130,7 +130,7 @@ impl Wasi {/// Add the WASI function `name` to `store`. Returns None if there is no such function.pub fn allocate_function(self: &Rc<Self>, store: &mut Store, name: &str) -> Option<FunctionAddress> {- let &(_, signature) = FUNCTIONS.iter().find(|(function, _)| *function == name)?;+ let &(name, signature) = FUNCTIONS.iter().find(|(function, _)| *function == name)?;let (parameters, result) = signature.split_once('>').unwrap_or((signature, ""));let to_types = |text: &str| -> Vec<ValType> {text.chars()@@ -142,10 +142,9 @@ impl Wasi {results: to_types(result),};let wasi = self.clone();- let name = name.to_string();Some(store.allocate_host_function(ty,- Rc::new(move |store: &mut Store, arguments: &[Value]| wasi.call(store, &name, arguments)),+ Rc::new(move |store: &mut Store, arguments: &[Value]| wasi.call(store, name, arguments)),))}@@ -182,6 +181,8 @@ impl Wasi {self.files.borrow().get(&fd).map(|file| Descriptor::Host(file.host_fd))}+ /// The host descriptor of `fd`. Paths only reach what is beneath a descriptor the guest has (the capability model):+ /// the platform functions resolve them beneath the one this returns.fn host_fd(&self, fd: u32) -> Result<i32, Errno> {match self.descriptor(fd) {Some(Descriptor::Host(host_fd)) => Ok(host_fd),@@ -190,12 +191,6 @@ impl Wasi {}}- /// The host descriptor to resolve paths relative to `fd` from. Paths only reach what is beneath a descriptor the- /// guest has (the capability model): the platform functions resolve them beneath it.- fn directory_fd(&self, fd: u32) -> Result<i32, Errno> {- self.host_fd(fd)- }-fn preopen_fd(&self, index: usize) -> Result<i32, Errno> {let preopen = &self.preopens[index];if let Some(fd) = preopen.host_fd.get() {@@ -293,17 +288,17 @@ impl Wasi {memory.write_u64(a(1), position)}"path_create_directory" => {- let directory = self.directory_fd(a(0))?;+ let directory = self.host_fd(a(0))?;platform::create_directory(directory, memory.slice(a(1), a(2))?)}"path_filestat_get" => {- let directory = self.directory_fd(a(0))?;+ let directory = self.host_fd(a(0))?;let follow_symlinks = a(1) & LOOKUP_SYMLINK_FOLLOW != 0;let status = platform::stat_at(directory, memory.slice(a(2), a(3))?, follow_symlinks)?;write_filestat(memory, a(4), &status)}"path_open" => {- let directory = self.directory_fd(a(0))?;+ let directory = self.host_fd(a(0))?;let options = OpenOptions {follow_symlinks: a(1) & LOOKUP_SYMLINK_FOLLOW != 0,open_flags: a(4) as u16,diff --git a/Libraries/LibWasm/Engine/tests/fixtures/tail_calls_across_tiers.wasm b/Libraries/LibWasm/Engine/tests/fixtures/tail_calls_across_tiers.wasmnew file mode 100644index 00000000000..8321bd71189Binary files /dev/null and b/Libraries/LibWasm/Engine/tests/fixtures/tail_calls_across_tiers.wasm differdiff --git a/Libraries/LibWasm/Engine/tests/fixtures/tail_calls_across_tiers.wat b/Libraries/LibWasm/Engine/tests/fixtures/tail_calls_across_tiers.watnew file mode 100644index 00000000000..b2612026bea--- /dev/null+++ b/Libraries/LibWasm/Engine/tests/fixtures/tail_calls_across_tiers.wat@@ -0,0 +1,14 @@+;; Two functions that tail call each other through references, once for each step down to 0.+(module+ (type $step (func (param i64) (result i64)))+ (global $even (ref $step) (ref.func $even))+ (global $odd (ref $step) (ref.func $odd))+ (elem declare func $even $odd)+ (func $even (export "even") (type $step)+ (if (result i64) (i64.eqz (local.get 0))+ (then (i64.const 44))+ (else (return_call_ref $step (i64.sub (local.get 0) (i64.const 1)) (global.get $odd)))))+ (func $odd (export "odd") (type $step)+ (if (result i64) (i64.eqz (local.get 0))+ (then (i64.const 99))+ (else (return_call_ref $step (i64.sub (local.get 0) (i64.const 1)) (global.get $even))))))diff --git a/Libraries/LibWasm/JIT/ARCHITECTURE.md b/Libraries/LibWasm/JIT/ARCHITECTURE.mdindex 13d7eb27959..9b7104bb8be 100644--- a/Libraries/LibWasm/JIT/ARCHITECTURE.md+++ b/Libraries/LibWasm/JIT/ARCHITECTURE.md@@ -21,10 +21,10 @@ reused from one compile to the next:| Decode and build | `decode.rs`, `builder/` | One forward pass over the validated, quickened body. Produces typed SSA with phis, folding and value numbering as it goes. || Cleanup | `passes/cleanup.rs` | Removes trivial phis to a fixed point, dead pure nodes, and fuses branches with the comparisons only they use. || Loop invariant code motion | `passes/licm.rs` | Finds the nodes of call-free loops that compute the same value in every iteration. |-| Scheduling | `passes/schedule.rs` | Rebuilds the node arena in linear order without the dead nodes, with the invariant nodes at the end of their loop's preheader, optionally numbering values over the dominator tree on the way (`passes/gvn.rs`). |+| Scheduling | `passes/schedule.rs` | Rebuilds the node arena in linear order without the dead nodes, with the invariant nodes at the end of their loop's preheader. || Liveness | `regalloc/liveness.rs` | One interval per value in linear order, extended over loops. || Allocation | `regalloc/` | One forward walk in linear order. Its verifier simulates every register. |-| Code generation | `codegen/x86_64/` | Lowers every node with its registers, then edge stubs, trap stubs, jump tables and constants. |+| Code generation | `codegen/x86_64/`, `codegen/aarch64/` | Lowers every node with its registers, then edge stubs, trap stubs, jump tables and constants. |`Options::verify_ir` checks the IR after building and after cleanup (`ir/verify.rs`), and theregister allocation (`regalloc/verify.rs`).@@ -170,15 +170,6 @@ terminator (the block entering a loop always ends in a jump to its header), andoutside every block's range. Inputs are renumbered, so a node's index is its position again, anddead nodes are gone for the phases after it.-**Global value numbering** (`passes/gvn.rs`, with `Options::gvn`) runs in scheduling's walk: a node-computing what a node of a dominating block computed is replaced by it, keeping entries for as long-as their block dominates the walk, unlike the builder, which forgets what a construct numbered when-it ends. Reads are numbered by alias class, with epochs that the class's writes advance: memory-loads by one that stores and calls advance, global values by one per global that its `global.set`-advances and one that calls advance; a block continues the epochs of the previous block only if-that is its only predecessor. It is off by default: real modules have almost nothing for it, 0.1%-of godot's nodes, and it costs 7 to 16 ns per code byte.-## 7. Register allocationThe allocator (`regalloc/`) follows libjs_jit's: one forward walk over the blocks in linear order.@@ -208,18 +199,23 @@ used after the loop. Values first used by a call argument or a return value pref**Spilling** happens at the definition: a value that ever needs a stack slot gets one for its wholelife, and code generation stores it right after defining it, so a slot always holds its value onceit has one. Parameters use their home slots and the instance its frame header slot. Every value-live across a call gets a slot, since calls clobber every register.+live across a call gets a slot, since calls clobber every register. A phi and its inputs (its web)+share slots wherever their intervals do not overlap, so that the moves into a spilled phi on its+edges, a loop's back edge above all, are mostly no moves at all.**Blocks.** A block with one predecessor starts with that predecessor's registers. A merge starts-with those of its last predecessor (usually the fallthrough), and a loop header with those of the-block entering the loop, without the values the loop only carries through that have a slot already.-Their phis get registers free there, preferably the input's own from that predecessor. Every other-edge moves its values into place, as parallel moves with cycles broken through a slot; back edges-get theirs when their source block ends.+with those of the predecessor that keeps the most of its values in registers, so that a path that+called a function, which leaves none in registers, does not make the others give theirs up; a loop+header starts with those of the block entering the loop, without the values the loop only carries+through that have a slot already. Their phis get registers free there, preferably the input's own+from that predecessor. Every other edge moves its values into place, as parallel moves with cycles+broken through a slot; back edges get theirs when their source block ends.**The verifier** (`regalloc/verify.rs`) simulates every register from the state each block startswith, checks that every input is where the allocation says, and that every edge's moves produce its-target's state, with phis replaced by their inputs.+target's state, with phis replaced by their inputs. It tracks what each block writes to slots, takes+a slot the block did not write to hold the one of its values live there, and checks that values+sharing a slot are never live at once.## 8. Calls and frames@@ -306,6 +302,10 @@ used, while the object is live.## 9. Code generation+There is a backend per target, with the same structure: `codegen/x86_64/` and `codegen/aarch64/`+(ARMv8.1 with LSE atomics and NEON), each with its own instruction selection for numbers, vectors,+memory, calls, tables and GC objects. The rest of this section describes the x86-64 one.+`codegen/x86_64/` lowers the blocks in linear order with x86-64-v3 instructions (VEX three-operandfloat arithmetic, BMI1/BMI2 shifts and rotates, lzcnt, tzcnt, popcnt, and AVX2 for vectors), fromlibjs_jit's encoders and the additions in its `asm/x86_64/extended.rs`, whose `vex()` encodes any@@ -380,8 +380,6 @@ the interpreter and the host. The JIT is on by default; `LIBWASM_JIT` configuresdeterministic imports, and compares results, exit codes, memories, tables and globals.- `examples/smith_check.rs` does the same for random modules from `wasm-tools smith` in the subsetthe JIT compiles, calling every exported function with random arguments.-- `examples/run_kernel.rs` times calls of one function, compiled or interpreted, for the run time- effect of optimizations while the JIT has no runtime; `examples/kernels/` has loops for them.- `examples/compile_all.rs` compiles every function of modules and reports coverage, the CPU timeof compiling the functions the JIT compiles on one thread and on several, per byte and per phase(`Options::stats`), the slowest large function, the cost of small ones, and nodes, slots and movesdiff --git a/Libraries/LibWasm/JIT/examples/compile_all.rs b/Libraries/LibWasm/JIT/examples/compile_all.rsindex 8580e1e713f..582524e7a4b 100644--- a/Libraries/LibWasm/JIT/examples/compile_all.rs+++ b/Libraries/LibWasm/JIT/examples/compile_all.rs@@ -7,7 +7,7 @@//! Compiles every function of WebAssembly modules and reports how long it took.//!//! ```text-//! compile_all [--threads N] [--runs N] [--verify] [--stress-registers] [--no-licm] [--gvn] [--quiet]+//! compile_all [--threads N] [--runs N] [--verify] [--stress-registers] [--no-licm] [--quiet]//! [--dump-ir FUNCTION [--osr PC]] [--dump-asm] MODULE|DIRECTORY...//! ```//!@@ -85,7 +85,6 @@ fn parse_arguments() -> Arguments {"--verify" => arguments.options.verify_ir = true,"--stress-registers" => arguments.options.stress_registers = true,"--no-licm" => arguments.options.no_licm = true,- "--gvn" => arguments.options.gvn = true,"--quiet" => arguments.quiet = true,"--dump-asm" => arguments.options.dump_asm = true,"--osr" => arguments.osr = Some(iterator.next().and_then(|n| n.parse().ok()).expect("--osr PC")),@@ -290,7 +289,6 @@ fn main() {stats.slots += result.stats.slots;stats.moves += result.stats.moves;stats.hoisted += result.stats.hoisted;- stats.eliminated += result.stats.eliminated;}}let mut worst = (0.0, 0, 0);@@ -377,12 +375,11 @@ fn main() {);}println!(- " per byte: {:.2} nodes, {:.3} slots, {:.3} moves; {} nodes hoisted out of loops, {} numbered away",+ " per byte: {:.2} nodes, {:.3} slots, {:.3} moves; {} nodes hoisted out of loops",stats.nodes as f64 / compiled_bytes.max(1) as f64,stats.slots as f64 / compiled_bytes.max(1) as f64,stats.moves as f64 / compiled_bytes.max(1) as f64,- stats.hoisted,- stats.eliminated+ stats.hoisted);for (what, count) in &failures {println!(" unsupported: {count} x {what}");diff --git a/Libraries/LibWasm/JIT/examples/kernels/loops.wat b/Libraries/LibWasm/JIT/examples/kernels/loops.watdeleted file mode 100644index fd62cfcc8c5..00000000000--- a/Libraries/LibWasm/JIT/examples/kernels/loops.wat+++ /dev/null@@ -1,68 +0,0 @@-;; Loops of the shapes loop invariant code motion and value numbering are for, as compilers emit them: calls in a-;; loop, which load their callee's FunctionHeader, globals the loop only reads, and repeated address arithmetic.-;; Build with `wasm-tools parse loops.wat -o loops.wasm` and time with examples/run_kernel.rs.-(module- (memory 1)- (global $offset (mut i32) (i32.const 3))- (global $base (mut i32) (i32.const 1024))- (global $scale (mut i32) (i32.const 7))-- (func $leaf (param i32) (result i32)- local.get 0- global.get $offset- i32.add)-- ;; Function 1: n calls of a leaf in a loop.- (func (export "calls") (param $n i32) (result i32)- (local $i i32) (local $sum i32)- loop $loop- local.get $sum- local.get $i- call $leaf- i32.add- local.set $sum- local.get $i- i32.const 1- i32.add- local.tee $i- local.get $n- i32.lt_u- br_if $loop- end- local.get $sum)-- ;; Function 2: a sum over memory at an address and with a factor that globals hold, n times over 256 words.- (func (export "globals") (param $n i32) (result i32)- (local $i i32) (local $j i32) (local $sum i32)- loop $outer- i32.const 0- local.set $j- loop $inner- local.get $sum- global.get $base- local.get $j- i32.const 2- i32.shl- i32.add- i32.load- global.get $scale- i32.mul- i32.add- local.set $sum- local.get $j- i32.const 1- i32.add- local.tee $j- i32.const 256- i32.lt_u- br_if $inner- end- local.get $i- i32.const 1- i32.add- local.tee $i- local.get $n- i32.lt_u- br_if $outer- end- local.get $sum))diff --git a/Libraries/LibWasm/JIT/examples/run_kernel.rs b/Libraries/LibWasm/JIT/examples/run_kernel.rsdeleted file mode 100644index cd2cc6f2e8d..00000000000--- a/Libraries/LibWasm/JIT/examples/run_kernel.rs+++ /dev/null@@ -1,113 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Times calls of one function of a module, compiled and interpreted, for evidence of what an optimization does at-//! run time while the JIT has no runtime of its own. Imported functions are stubs that return zeros.-//!-//! ```text-//! run_kernel MODULE FUNCTION [--calls N] [--runs N] [--interpreter] [--no-licm] [--gvn] ARGUMENT...-//! ```-//!-//! Arguments are `i32:5`, `i64:-1`, `f32:1.5` or `f64:2`. The time is the best of `--runs` runs of `--calls` calls.--#[path = "../tests/harness/mod.rs"]-mod harness;--use harness::{CompiledModule, Outcome, TestBinding};-use libwasm_engine::module::ImportDescription;-use libwasm_engine::runtime::{ExternValue, HostCallback, Store, Value};-use libwasm_engine::types::ValType;-use libwasm_jit::Options;-use std::rc::Rc;-use std::sync::Arc;-use std::time::Instant;--fn parse(argument: &str) -> Value {- let (ty, value) = argument.split_once(':').expect("TYPE:VALUE");- match ty {- "i32" => Value::I32(value.parse::<i64>().expect("an i32") as i32),- "i64" => Value::I64(value.parse().expect("an i64")),- "f32" => Value::F32(value.parse::<f32>().expect("an f32").to_bits()),- "f64" => Value::F64(value.parse::<f64>().expect("an f64").to_bits()),- _ => panic!("unknown type {ty}"),- }-}--fn main() {- harness::run_main(checked_main);-}--fn checked_main() {- let mut arguments = std::env::args().skip(1);- let path = arguments.next().expect("MODULE");- let function: u32 = arguments- .next()- .and_then(|function| function.parse().ok())- .expect("FUNCTION");- let (mut calls, mut runs, mut interpreter) = (100, 5, false);- let mut options = Options::default();- let mut values = Vec::new();- while let Some(argument) = arguments.next() {- match argument.as_str() {- "--calls" => calls = arguments.next().and_then(|n| n.parse().ok()).expect("--calls N"),- "--runs" => runs = arguments.next().and_then(|n| n.parse().ok()).expect("--runs N"),- "--interpreter" => interpreter = true,- "--no-licm" => options.no_licm = true,- "--gvn" => options.gvn = true,- _ => values.push(parse(&argument)),- }- }- let module = Arc::new(libwasm_engine::compile(&std::fs::read(&path).unwrap()).unwrap());- let mut store = Store::new();- let mut imports = Vec::new();- for import in &module.imports {- let ImportDescription::Function(type_index) = import.description else {- panic!("only function imports are stubbed");- };- let ty = module.types[type_index as usize].as_func().unwrap().clone();- let results = ty.results.clone();- let callback: HostCallback = Rc::new(move |_: &mut Store, _: &[Value]| {- Ok(results- .iter()- .map(|result: &ValType| Value::default_for(*result))- .collect())- });- imports.push(ExternValue::Function(store.allocate_host_function(ty, callback)));- }- let instance = store.instantiate(module.clone(), &imports).unwrap();- let address = store.instance(instance).functions[function as usize];- let compiled = CompiledModule::compile(module, options);- let mut binding = TestBinding::new(&compiled, &store, instance);- if !interpreter {- assert!(- compiled.runnable[function as usize],- "function {function} does not run compiled"- );- }- let mut best = f64::MAX;- let mut last = None;- for _ in 0..runs {- let start = Instant::now();- for _ in 0..calls {- let outcome = if interpreter {- match store.invoke(address, &values) {- Ok(values) => Outcome::Values(values),- Err(trap) => Outcome::Trap(harness::script::trap_code(&trap)),- }- } else {- binding.call(&mut store, &compiled, function, &values)- };- last = Some(outcome);- }- best = best.min(start.elapsed().as_secs_f64());- }- println!(- "{:.3} ms for {calls} calls ({:.1} us each), last outcome {:?}",- best * 1e3,- best * 1e6 / f64::from(calls),- last.unwrap()- );-}diff --git a/Libraries/LibWasm/JIT/examples/smith_check.rs b/Libraries/LibWasm/JIT/examples/smith_check.rsindex 329b165328e..af034ead773 100644--- a/Libraries/LibWasm/JIT/examples/smith_check.rs+++ b/Libraries/LibWasm/JIT/examples/smith_check.rs@@ -8,7 +8,7 @@//! the JIT compiled with random arguments, and compares results, traps, memories and globals with the interpreter.//!//! ```text-//! smith_check [--count N] [--seed S] [--keep DIRECTORY] [--wasm-tools PATH] [--stress-registers] [--no-licm] [--gvn]+//! smith_check [--count N] [--seed S] [--keep DIRECTORY] [--wasm-tools PATH] [--stress-registers] [--no-licm]//! [--simd] [--features gc,threads,memory64,multi-memory]//! ```//!@@ -132,7 +132,7 @@ impl Random {fn outcome(result: Result<Vec<Value>, Trap>) -> Outcome {match result {Ok(values) => Outcome::Values(values),- Err(trap) => Outcome::Trap(harness::script::trap_code(&trap)),+ Err(trap) => Outcome::Trap(trap.code()),}}@@ -159,7 +159,6 @@ fn checked_main() {let mut keep = None;let mut stress_registers = false;let mut no_licm = false;- let mut gvn = false;let mut simd = false;let mut features: Vec<String> = Vec::new();let mut wasm_tools = std::env::var("HOME")@@ -179,7 +178,6 @@ fn checked_main() {"--wasm-tools" => wasm_tools = arguments.next().expect("--wasm-tools PATH"),"--stress-registers" => stress_registers = true,"--no-licm" => no_licm = true,- "--gvn" => gvn = true,"--simd" => simd = true,"--features" => {features = arguments@@ -266,7 +264,6 @@ fn checked_main() {verify_ir: true,stress_registers,no_licm,- gvn,..Options::default()},);diff --git a/Libraries/LibWasm/JIT/examples/spec_check.rs b/Libraries/LibWasm/JIT/examples/spec_check.rsindex 7028ea9f210..9414cf6562f 100644--- a/Libraries/LibWasm/JIT/examples/spec_check.rs+++ b/Libraries/LibWasm/JIT/examples/spec_check.rs@@ -8,7 +8,7 @@//! with the interpreter (see `tests/harness/script.rs`).//!//! ```text-//! spec_check [--verbose] [--stress-registers] [--no-licm] [--gvn] [--runtime] [--dump FILE] DIRECTORY|SCRIPT.json...+//! spec_check [--verbose] [--stress-registers] [--no-licm] [--runtime] [--dump FILE] DIRECTORY|SCRIPT.json...//! ```//!//! `--dump FILE` writes what the interpreter did in every action to FILE, which should be the same on every@@ -38,7 +38,6 @@ fn checked_main() {"--verbose" => verbose = true,"--stress-registers" => options.stress_registers = true,"--no-licm" => options.no_licm = true,- "--gvn" => options.gvn = true,"--runtime" => runtime = true,_ => paths.push(argument),}diff --git a/Libraries/LibWasm/JIT/src/builder/calls.rs b/Libraries/LibWasm/JIT/src/builder/calls.rsindex a37a782fae2..09da3347c0b 100644--- a/Libraries/LibWasm/JIT/src/builder/calls.rs+++ b/Libraries/LibWasm/JIT/src/builder/calls.rs@@ -91,7 +91,7 @@ impl Builder {let ty = module.types[type_index as usize].as_func().expect("call_indirect has a function type");- let index = Self::resolve(func, self.pop());+ let index = func.resolve(self.pop());let table = self.table_data(func, table);let element = Self::append(func,@@ -120,7 +120,7 @@ impl Builder {let ty = module.types[type_index as usize].as_func().expect("call_ref has a function type");- let reference = Self::resolve(func, self.pop());+ let reference = func.resolve(self.pop());Self::append(func,Node::new(Op::CheckNull, Type::None, TRAP_NULL_REFERENCE as u8, [reference, 0, 0]),@@ -160,7 +160,7 @@ impl Builder {func.operands.extend_from_slice(&[header, instance, memory_base]);let top = self.stack.len() - argument_count;for position in top..self.stack.len() {- let value = Self::resolve(func, self.stack[position]);+ let value = func.resolve(self.stack[position]);func.operands.push(value);}self.stack.truncate(top);diff --git a/Libraries/LibWasm/JIT/src/builder/exceptions.rs b/Libraries/LibWasm/JIT/src/builder/exceptions.rsindex a74164ac515..419591a08ad 100644--- a/Libraries/LibWasm/JIT/src/builder/exceptions.rs+++ b/Libraries/LibWasm/JIT/src/builder/exceptions.rs@@ -125,7 +125,7 @@ impl Builder {if handler == NONE {self.terminate(func, Node::new(Op::Throw, Type::None, 0, [exception, 0, 0]), &[]);} else {- let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);+ let slot = self.jump(func, NONE);self.add_throw_edge(handler, slot, exception);}}@@ -146,7 +146,7 @@ impl Builder {// The payload is in operand stack order: the last value in the lowest slot.let mut slot = 0;for ¶m in params.iter().rev() {- let value = Self::resolve(func, self.pop());+ let value = func.resolve(self.pop());self.write_payload(func, payload, slot, param, value);slot += param.slot_count();}@@ -292,27 +292,7 @@ impl Builder {func.successors[self.edges[edge as usize].slot as usize] = block;}self.start_block(func, block);- let first = Self::resolve(- func,- self.edge_values[self.edges[self.scratch_values[0] as usize].values as usize],- );- let all_same = self- .scratch_values- .iter()- .all(|edge| Self::resolve(func, self.edge_values[self.edges[*edge as usize].values as usize]) == first);- let exception = if all_same {- first- } else {- let phi = Self::new_phi(func, block, Type::Ref);- let start = func.operands.len() as u32;- for &edge in &self.scratch_values {- let value = self.edge_values[self.edges[edge as usize].values as usize];- func.operands.push(Self::resolve(func, value));- }- func.nodes[phi as usize].args[0] = start;- func.nodes[phi as usize].args[1] = self.scratch_values.len() as u32;- phi- };+ let exception = self.merge_edge_values(func, block, Type::Ref, 0);let context = self.instance_field(func, offset_of!(InstanceData, context));let zero = self.constant(func, Type::I64, 0);Self::append(@@ -350,7 +330,7 @@ impl Builder {fn end_region(&mut self, func: &mut Func, index: usize) {let control = self.controls[index];if !control.unreachable {- let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);+ let slot = self.jump(func, NONE);self.add_edge(index, slot);self.controls[index].unreachable = true;}@@ -410,7 +390,7 @@ impl Builder {for clause_index in control.clauses.0..control.clauses.0 + control.clauses.1 {let clause = self.clauses[clause_index as usize];let (block, slot) = if clause.kind == CATCH_ALL {- let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);+ let slot = self.jump(func, NONE);(self.current_block, slot)} else {self.test_tag(func, clause.tag, exception)@@ -434,7 +414,7 @@ impl Builder {} else {// The end of the previous handler.if !control.unreachable {- let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);+ let slot = self.jump(func, NONE);self.add_edge(index, slot);}self.unnumber(control.numbering_mark);@@ -490,7 +470,7 @@ impl Builder {handler = self.controls[handler as usize].outer_handler;}if !control.unreachable {- let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);+ let slot = self.jump(func, NONE);self.add_edge(index, slot);self.controls[index].unreachable = true;}diff --git a/Libraries/LibWasm/JIT/src/builder/gc.rs b/Libraries/LibWasm/JIT/src/builder/gc.rsindex dcdcd292e4d..e2c004f42d8 100644--- a/Libraries/LibWasm/JIT/src/builder/gc.rs+++ b/Libraries/LibWasm/JIT/src/builder/gc.rs@@ -153,7 +153,7 @@ impl Builder {/// The bits of an element's value as the runtime's functions take them: the low and the high 64 bits.fn value_bits(&mut self, func: &mut Func, value: Value, storage: StorageType) -> (Value, Value) {- let value = Self::resolve(func, value);+ let value = func.resolve(value);let zero = self.constant(func, Type::I64, 0);match storage {StorageType::Val(ValType::F32) => {@@ -181,7 +181,7 @@ impl Builder {/// Whether `value` is the zero of its type, which every new object's fields start as.fn is_zero(&self, func: &Func, value: Value) -> bool {- let value = Self::resolve(func, value);+ let value = func.resolve(value);func.node(value).constant() == Some(0) || (value == self.vector_zero && value != crate::ir::NONE)}@@ -195,7 +195,7 @@ impl Builder {nullable: bool,cast: bool,) -> Value {- let reference = Self::resolve(func, reference);+ let reference = func.resolve(reference);let (test, identity, depth) = match heap {HeapType::Any | HeapType::Func | HeapType::Extern | HeapType::Exn => (HeapTest::NonNull, None, 0),HeapType::Eq => (HeapTest::Eq, None, 0),@@ -273,7 +273,7 @@ impl Builder {self.push(object);}STRUCT_GET | STRUCT_GET_S | STRUCT_GET_U => {- let object = Self::resolve(func, self.pop());+ let object = func.resolve(self.pop());Self::check_null(func, object);let count = struct_fields(module, first).len() as u32;let size = self.field_offset(module, first, count);@@ -285,7 +285,7 @@ impl Builder {}STRUCT_SET => {let value = self.pop();- let object = Self::resolve(func, self.pop());+ let object = func.resolve(self.pop());Self::check_null(func, object);let count = struct_fields(module, first).len() as u32;let size = self.field_offset(module, first, count);@@ -370,8 +370,8 @@ impl Builder {self.push(array);}ARRAY_GET | ARRAY_GET_S | ARRAY_GET_U => {- let index = Self::resolve(func, self.pop());- let array = Self::resolve(func, self.pop());+ let index = func.resolve(self.pop());+ let array = func.resolve(self.pop());let storage = array_storage(module, first);let size_log2 = storage.object_field_size().trailing_zeros() as u8;let address = Self::append(@@ -383,8 +383,8 @@ impl Builder {}ARRAY_SET => {let value = self.pop();- let index = Self::resolve(func, self.pop());- let array = Self::resolve(func, self.pop());+ let index = func.resolve(self.pop());+ let array = func.resolve(self.pop());let storage = array_storage(module, first);let size_log2 = storage.object_field_size().trailing_zeros() as u8;let address = Self::append(@@ -394,7 +394,7 @@ impl Builder {self.store_at(func, store_size_log2(storage), address, 0, value);}ARRAY_LEN => {- let array = Self::resolve(func, self.pop());+ let array = func.resolve(self.pop());Self::check_null(func, array);let length = Self::append(func,@@ -449,7 +449,7 @@ impl Builder {self.push(value);}REF_CAST | REF_CAST_NULL => {- let reference = Self::resolve(func, self.pop());+ let reference = func.resolve(self.pop());self.ref_test(func,module,@@ -480,7 +480,7 @@ impl Builder {self.push(reference);}I31_GET_S | I31_GET_U => {- let reference = Self::resolve(func, self.pop());+ let reference = func.resolve(self.pop());Self::check_null(func, reference);let flags = u8::from(sub_opcode == I31_GET_S);let value = self.pure(func, Node::new(Op::I31Get, Type::I32, flags, [reference, 0, 0]));diff --git a/Libraries/LibWasm/JIT/src/builder/memories.rs b/Libraries/LibWasm/JIT/src/builder/memories.rsindex eb3ae684222..697f3e87b06 100644--- a/Libraries/LibWasm/JIT/src/builder/memories.rs+++ b/Libraries/LibWasm/JIT/src/builder/memories.rs@@ -32,7 +32,7 @@ impl Builder {atomic: bool,) -> Value {let memory64 = module.memory_space[argument.memory as usize].limits.address_type == AddressType::I64;- let index = Self::resolve(func, index);+ let index = func.resolve(index);let data = self.memory_data(func, argument.memory);let offset = self.constant(func, Type::I64, argument.offset);let mut flags = size_log2;@@ -57,7 +57,7 @@ impl Builder {/// A store of `1 << size_log2` bytes of `value` at `address`, a pointer.pub(super) fn store_at(&mut self, func: &mut Func, size_log2: u8, address: Value, offset: u32, value: Value) {let zero = self.constant(func, Type::I32, 0);- let value = Self::resolve(func, value);+ let value = func.resolve(value);let start = func.operands.len() as u32;func.operands.extend_from_slice(&[address, zero, value]);Self::append(func, Node::new(Op::Store, Type::None, size_log2, [start, 3, offset]));@@ -144,7 +144,7 @@ impl Builder {self.push(loaded);}AtomicKind::Store { value, size } => {- let stored = Self::resolve(func, self.pop());+ let stored = func.resolve(self.pop());let index = self.pop();let size_log2 = size.trailing_zeros() as u8;let address = self.checked_address(func, module, argument, index, size_log2, true);@@ -160,7 +160,7 @@ impl Builder {);}AtomicKind::ReadModifyWrite { value, size } => {- let operand = Self::resolve(func, self.pop());+ let operand = func.resolve(self.pop());let index = self.pop();let size_log2 = size.trailing_zeros() as u8;let address = self.checked_address(func, module, argument, index, size_log2, true);@@ -172,8 +172,8 @@ impl Builder {self.push(old);}AtomicKind::CompareExchange { value, size } => {- let replacement = Self::resolve(func, self.pop());- let expected = Self::resolve(func, self.pop());+ let replacement = func.resolve(self.pop());+ let expected = func.resolve(self.pop());let index = self.pop();let size_log2 = size.trailing_zeros() as u8;let address = self.checked_address(func, module, argument, index, size_log2, true);diff --git a/Libraries/LibWasm/JIT/src/builder/mod.rs b/Libraries/LibWasm/JIT/src/builder/mod.rsindex ae21f8b220a..bc1bd53ded1 100644--- a/Libraries/LibWasm/JIT/src/builder/mod.rs+++ b/Libraries/LibWasm/JIT/src/builder/mod.rs@@ -475,7 +475,7 @@ impl Builder {self.write_local(flag, one);let stack_types = std::mem::take(&mut self.osr.as_mut().expect("this is an OSR compile").stack_types);let stack = Self::load_frame_stack(func, frame, &stack_types);- let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);+ let slot = self.jump(func, NONE);let osr = self.osr.as_mut().expect("this is an OSR compile");osr.frame = frame;osr.flag = flag;@@ -563,13 +563,6 @@ impl Builder {}/// The value a forwarded phi stands for.- fn resolve(func: &Func, mut value: Value) -> Value {- while func.nodes[value as usize].op == Op::Forward {- value = func.nodes[value as usize].args[0];- }- value- }-/// A pure node, or the value of an equal one that dominates the current position.fn pure(&mut self, func: &mut Func, node: Node) -> Value {let key = numbering_key(&node);@@ -601,7 +594,7 @@ impl Builder {}fn binary_with_flags(&mut self, func: &mut Func, op: Op, ty: Type, flags: u8, a: Value, b: Value) -> Value {- let (a, b) = (Self::resolve(func, a), Self::resolve(func, b));+ let (a, b) = (func.resolve(a), func.resolve(b));let result_type = if op == Op::Compare { Type::I32 } else { ty };match fold::binary(func, op, ty, flags, a, b) {Folded::Value(value) => value,@@ -618,7 +611,7 @@ impl Builder {}fn unary(&mut self, func: &mut Func, op: Op, ty: Type, a: Value) -> Value {- let a = Self::resolve(func, a);+ let a = func.resolve(a);match fold::unary(func, op, ty, a) {Some(Folded::Value(value)) => value,Some(Folded::Constant(bits)) => self.constant(func, ty, bits),@@ -679,11 +672,9 @@ impl Builder {fn lookup(&self, func: &Func, block: BlockId, local: u32) -> Option<Value> {let (cached_block, value) = self.current[local as usize];if cached_block == block {- return Some(Self::resolve(func, value));+ return Some(func.resolve(value));}- self.definitions- .get(key(block, local))- .map(|value| Self::resolve(func, value))+ self.definitions.get(key(block, local)).map(|value| func.resolve(value))}fn read_local(&mut self, func: &mut Func, block: BlockId, local: u32) -> Value {@@ -863,8 +854,8 @@ impl Builder {/// on, which it removes: their value if they are all the same, else a new phi of them.fn merge_collected(&mut self, func: &mut Func, block: BlockId, ty: Type, start: u32) -> Value {let values = &self.read_values[start as usize..];- let first = Self::resolve(func, values[0]);- let value = if values[1..].iter().all(|value| Self::resolve(func, *value) == first) {+ let first = func.resolve(values[0]);+ let value = if values[1..].iter().all(|value| func.resolve(*value) == first) {first} else {let phi = Self::new_phi(func, block, ty);@@ -878,27 +869,25 @@ impl Builder {value}+ /// Value `index` of each of the edges `collect_edges()` collected, merged at the start of `block`.+ fn merge_edge_values(&mut self, func: &mut Func, block: BlockId, ty: Type, index: usize) -> Value {+ let start = self.read_values.len() as u32;+ for position in 0..self.scratch_values.len() {+ let edge = self.scratch_values[position];+ let value = self.edge_values[self.edges[edge as usize].values as usize + index];+ self.read_values.push(value);+ }+ self.merge_collected(func, block, ty, start)+ }+/// Forwards `phi` if its inputs are only itself and one other value, which it returns; returns `phi` otherwise.fn try_remove_trivial_phi(func: &mut Func, phi: Value) -> Value {- let mut same = NONE;- for &input in func.inputs(phi) {- let input = Self::resolve(func, input);- if input == phi || input == same {- continue;- }- if same != NONE {- return phi;- }- same = input;- }- if same == NONE {- // Only reachable through itself: the loop is never entered with a value for it.+ // NB: A phi with no other input is only reachable through itself: the loop is never entered with a value for+ // it, and the phi stays.+ let Some(same) = func.trivial_phi_input(phi) else {return phi;- }- let node = &mut func.nodes[phi as usize];- node.op = Op::Forward;- node.args[0] = same;- node.args[1] = 0;+ };+ func.forward(phi, same);same}@@ -930,6 +919,12 @@ impl Builder {/// Records a branch from the current block to the label of `controls[index]`, carrying the top values of the/// stack, through the successor `slot`.+ /// Ends the current block with a jump to `target`, or to a block the caller sets later if it is NONE, and returns+ /// the jump's successor slot.+ fn jump(&mut self, func: &mut Func, target: BlockId) -> u32 {+ self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[target])+ }+fn add_edge(&mut self, index: usize, slot: u32) {let control = self.controls[index];let (_, arity) = control.label_arity();@@ -1075,11 +1070,11 @@ impl Builder {self.set_unreachable();}I::BrIf(depth) => {- let condition = Self::resolve(func, self.pop());+ let condition = func.resolve(self.pop());self.conditional_branch(func, depth, condition);}I::BrTable { .. } => {- let index = Self::resolve(func, self.pop());+ let index = func.resolve(self.pop());self.branch_table(func, index, decoder.targets());self.set_unreachable();}@@ -1093,9 +1088,9 @@ impl Builder {self.pop();}I::Select | I::SelectTyped(_) => {- let condition = Self::resolve(func, self.pop());- let if_false = Self::resolve(func, self.pop());- let if_true = Self::resolve(func, self.pop());+ let condition = func.resolve(self.pop());+ let if_false = func.resolve(self.pop());+ let if_true = func.resolve(self.pop());let value = match func.node(condition).constant() {Some(0) => if_false,Some(_) => if_true,@@ -1113,12 +1108,12 @@ impl Builder {self.push(value);}I::LocalSet(local) => {- let value = Self::resolve(func, self.pop());+ let value = func.resolve(self.pop());self.write_local(local, value);self.note_loop_write(func.blocks[self.current_block as usize].loop_index, local);}I::LocalTee(local) => {- let value = Self::resolve(func, *self.stack.last().expect("validated code has an operand"));+ let value = func.resolve(*self.stack.last().expect("validated code has an operand"));self.write_local(local, value);self.note_loop_write(func.blocks[self.current_block as usize].loop_index, local);}@@ -1129,15 +1124,15 @@ impl Builder {let offset = argument.offset as u32;if opcode <= opcode::I64_LOAD32_U {let (kind, ty) = load_kind(opcode);- let index = Self::resolve(func, self.pop());+ let index = func.resolve(self.pop());let value = Self::append(func,Node::new(Op::Load, ty, kind as u8, [self.memory_base, index, offset]),);self.push(value);} else {- let value = Self::resolve(func, self.pop());- let index = Self::resolve(func, self.pop());+ let value = func.resolve(self.pop());+ let index = func.resolve(self.pop());let size_log2 = store_size_log2(opcode);let start = func.operands.len() as u32;func.operands.extend_from_slice(&[self.memory_base, index, value]);@@ -1168,7 +1163,7 @@ impl Builder {opcode::misc::I64_TRUNC_SAT_F32_S | opcode::misc::I64_TRUNC_SAT_F64_S => (Op::TruncSatS, Type::I64),_ => (Op::TruncSatU, Type::I64),};- let a = Self::resolve(func, self.pop());+ let a = func.resolve(self.pop());let value = self.pure(func, Node::new(op, ty, 0, [a, 0, 0]));self.push(value);}@@ -1197,7 +1192,7 @@ impl Builder {I::Delegate(label) => self.delegate(func, label),I::Throw(tag) => self.throw_tag(func, module, tag),I::ThrowRef => {- let exception = Self::resolve(func, self.pop());+ let exception = func.resolve(self.pop());Self::append(func,Node::new(Op::CheckNull, Type::None, TRAP_NULL_REFERENCE as u8, [exception, 0, 0]),@@ -1227,7 +1222,7 @@ impl Builder {self.push(value);}I::RefAsNonNull => {- let reference = Self::resolve(func, self.pop());+ let reference = func.resolve(self.pop());Self::append(func,Node::new(Op::CheckNull, Type::None, TRAP_NULL_REFERENCE as u8, [reference, 0, 0]),@@ -1235,7 +1230,7 @@ impl Builder {self.push(reference);}I::BrOnNull(depth) => {- let reference = Self::resolve(func, self.pop());+ let reference = func.resolve(self.pop());let is_null = self.unary(func, Op::Eqz, Type::I32, reference);self.conditional_branch(func, depth, is_null);if !self.is_unreachable() {@@ -1243,7 +1238,7 @@ impl Builder {}}I::BrOnNonNull(depth) => {- let reference = Self::resolve(func, *self.stack.last().expect("br_on_non_null has an operand"));+ let reference = func.resolve(*self.stack.last().expect("br_on_non_null has an operand"));let null = self.constant(func, Type::Ref, 0);let is_not_null =self.binary_with_flags(func, Op::Compare, Type::Ref, IntCondition::Ne as u8, reference, null);@@ -1330,11 +1325,11 @@ impl Builder {match op {Compare => self.binary_with_flags(func, op, ty, flags, a, b),FloatCompare => {- let (a, b) = (Self::resolve(func, a), Self::resolve(func, b));+ let (a, b) = (func.resolve(a), func.resolve(b));self.pure(func, Node::new(op, I32, flags, [a, b, 0]))}_ if ty.is_float() => {- let (a, b) = (Self::resolve(func, a), Self::resolve(func, b));+ let (a, b) = (func.resolve(a), func.resolve(b));self.pure(func, Node::new(op, ty, 0, [a, b, 0]))}_ => self.binary(func, op, ty, a, b),@@ -1342,7 +1337,7 @@ impl Builder {} else {let a = self.pop();if ty.is_float() || matches!(op, TruncS | TruncU | Reinterpret) {- let a = Self::resolve(func, a);+ let a = func.resolve(a);let node = Node::new(op, ty, 0, [a, 0, 0]);if node.effect() == crate::ir::Effect::Pure {self.pure(func, node)@@ -1393,7 +1388,7 @@ impl Builder {block}None => {- self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[header]);+ self.jump(func, header);self.current_block}};@@ -1447,7 +1442,7 @@ impl Builder {if !first {// The way in from the frame comes from the branch of the loop around this one, through a block that loads// the operand stack this loop starts with. It goes before the loop's header, in linear order.- let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);+ let slot = self.jump(func, NONE);entry = Some((self.current_block, slot));let load = self.new_block(func);Self::set_predecessors(func, load, &[osr.block]);@@ -1461,7 +1456,7 @@ impl Builder {self.write_local(osr.flag, one);}osr.block = load;- osr.slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);+ osr.slot = self.jump(func, NONE);}// The values the loop's parameters have from the frame, which only the loop the frame is at needs.if !target {@@ -1491,7 +1486,7 @@ impl Builder {self.controls[index].edges = edge;let mut below = Vec::with_capacity(height);for position in 0..height {- let normal = Self::resolve(func, self.stack[position]);+ let normal = func.resolve(self.stack[position]);let phi = Self::new_phi(func, header, func.node(normal).ty);below.push((phi, normal, osr.stack[position]));self.stack[position] = phi;@@ -1525,7 +1520,7 @@ impl Builder {// The flag is down from here on, so that no back edge or exit of a loop carries it.let zero = self.constant(func, Type::I32, 0);self.write_local(flag, zero);- let onward_slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);+ let onward_slot = self.jump(func, NONE);let body = self.new_block(func);Self::set_predecessors(func, body, &[block]);func.successors[slot as usize + 1] = body;@@ -1538,7 +1533,7 @@ impl Builder {}fn begin_if(&mut self, func: &mut Func, params: (u32, u32), results: (u32, u32)) {- let condition = Self::resolve(func, self.pop());+ let condition = func.resolve(self.pop());let then_block = self.new_block(func);let slot = self.terminate(func,@@ -1561,7 +1556,7 @@ impl Builder {let index = self.controls.len() - 1;let control = self.controls[index];if !control.unreachable {- let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);+ let slot = self.jump(func, NONE);self.add_edge(index, slot);}self.unnumber(control.numbering_mark);@@ -1629,7 +1624,7 @@ impl Builder {return;}if reachable {- let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);+ let slot = self.jump(func, NONE);self.add_edge(index, slot);}let control = self.controls[index];@@ -1644,26 +1639,9 @@ impl Builder {}self.start_block(func, merge);for result in 0..arity {- let first = self.edge_values[self.edges[self.scratch_values[0] as usize].values as usize + result];- let first = Self::resolve(func, first);- let all_same = self.scratch_values.iter().all(|edge| {- let value = self.edge_values[self.edges[*edge as usize].values as usize + result];- Self::resolve(func, value) == first- });- if all_same {- self.stack.push(first);- continue;- }let ty = self.types[(control.results.0 + result as u32) as usize];- let phi = Self::new_phi(func, merge, ty);- let start = func.operands.len() as u32;- for &edge in &self.scratch_values {- let value = self.edge_values[self.edges[edge as usize].values as usize + result];- func.operands.push(Self::resolve(func, value));- }- func.nodes[phi as usize].args[0] = start;- func.nodes[phi as usize].args[1] = self.scratch_values.len() as u32;- self.stack.push(phi);+ let value = self.merge_edge_values(func, merge, ty, result);+ self.stack.push(value);}self.controls.pop();}@@ -1698,7 +1676,7 @@ impl Builder {let start = func.operands.len() as u32;for &edge in &edge_list {let value = self.edge_values[self.edges[edge as usize].values as usize + offset];- func.operands.push(Self::resolve(func, value));+ func.operands.push(func.resolve(value));}func.nodes[phi as usize].args[0] = start;func.nodes[phi as usize].args[1] = edge_list.len() as u32;@@ -1756,7 +1734,7 @@ impl Builder {let after = self.new_block(func);let loop_index = control.loop_index as usize;func.loops[loop_index].last = func.blocks.len() as u32 - 2;- self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[after]);+ self.jump(func, after);let from = self.current_block;Self::set_predecessors(func, after, &[from]);self.start_block(func, after);@@ -1777,7 +1755,7 @@ impl Builder {let start = func.operands.len() as u32;let top = self.stack.len() - count;for position in top..self.stack.len() {- let value = Self::resolve(func, self.stack[position]);+ let value = func.resolve(self.stack[position]);func.operands.push(value);}self.terminate(@@ -1787,11 +1765,11 @@ impl Builder {);}ControlKind::Loop => {- let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[control.block]);+ let slot = self.jump(func, control.block);self.add_edge(index, slot);}_ => {- let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);+ let slot = self.jump(func, NONE);self.add_edge(index, slot);}}@@ -1957,7 +1935,7 @@ impl Builder {}fn global_set(&mut self, func: &mut Func, global: u32) {- let value = Self::resolve(func, self.pop());+ let value = func.resolve(self.pop());let storage = self.global_storage(func, global);let ty = func.node(value).ty;Self::append(func, Node::new(Op::GlobalSet, Type::None, 0, [storage, value, global]));diff --git a/Libraries/LibWasm/JIT/src/builder/simd.rs b/Libraries/LibWasm/JIT/src/builder/simd.rsindex 176b1052760..5ee9298588d 100644--- a/Libraries/LibWasm/JIT/src/builder/simd.rs+++ b/Libraries/LibWasm/JIT/src/builder/simd.rs@@ -94,7 +94,7 @@ impl Builder {let kind = simd_kind(sub_opcode).expect("validation rejects unknown SIMD instructions");let value = match kind {SimdKind::Load { size } => {- let index = Self::resolve(func, self.pop());+ let index = func.resolve(self.pop());let argument = decoder.simd_argument();let size_log2 = size.trailing_zeros() as u8;let (base, index, offset) = self.simd_address(func, module, checked, argument, index, size_log2);@@ -104,8 +104,8 @@ impl Builder {)}SimdKind::Store { .. } => {- let value = Self::resolve(func, self.pop());- let index = Self::resolve(func, self.pop());+ let value = func.resolve(self.pop());+ let index = func.resolve(self.pop());let address = self.simd_address(func, module, checked, decoder.simd_argument(), index, 4);self.store(func, address, value, 4);return;@@ -113,8 +113,8 @@ impl Builder {SimdKind::LoadLane { size } => {// A scalar load, and its value replacing the lane.let lane = u32::from(decoder.simd_lane());- let vector = Self::resolve(func, self.pop());- let index = Self::resolve(func, self.pop());+ let vector = func.resolve(self.pop());+ let index = func.resolve(self.pop());let argument = decoder.simd_argument();let size_log2 = size.trailing_zeros() as u8;let (base, index, offset) = self.simd_address(func, module, checked, argument, index, size_log2);@@ -133,8 +133,8 @@ impl Builder {SimdKind::StoreLane { size } => {// The lane extracted, and stored as a scalar.let lane = u32::from(decoder.simd_lane());- let vector = Self::resolve(func, self.pop());- let index = Self::resolve(func, self.pop());+ let vector = func.resolve(self.pop());+ let index = func.resolve(self.pop());let (ty, extract, size_log2) = match size {1 => (Type::I32, I8X16_EXTRACT_LANE_U, 0),2 => (Type::I32, I16X8_EXTRACT_LANE_U, 1),@@ -151,8 +151,8 @@ impl Builder {self.vector_constant(func, bits)}SimdKind::Shuffle => {- let mut b = Self::resolve(func, self.pop());- let mut a = Self::resolve(func, self.pop());+ let mut b = func.resolve(self.pop());+ let mut a = func.resolve(self.pop());let mut lanes = decoder.simd_bytes();// A shuffle of one vector names it twice, with lanes 0 to 15, so that the other one need not live// on for it, and code generation sees what it is.@@ -174,25 +174,25 @@ impl Builder {} else {Type::V128};- let a = Self::resolve(func, self.pop());+ let a = func.resolve(self.pop());self.pure(func, Node::new(Op::VectorUnary, result, 0, [a, sub_opcode, 0]))}SimdKind::Binary | SimdKind::Shift => {- let b = Self::resolve(func, self.pop());- let a = Self::resolve(func, self.pop());+ let b = func.resolve(self.pop());+ let a = func.resolve(self.pop());self.pure(func, Node::new(Op::VectorBinary, Type::V128, 0, [a, b, sub_opcode]))}SimdKind::Ternary => {- let c = Self::resolve(func, self.pop());- let b = Self::resolve(func, self.pop());- let a = Self::resolve(func, self.pop());+ let c = func.resolve(self.pop());+ let b = func.resolve(self.pop());+ let a = func.resolve(self.pop());self.pure(func,Node::new(Op::VectorTernary, Type::V128, sub_opcode as u8, [a, b, c]),)}SimdKind::ExtractLane { result, .. } => {- let a = Self::resolve(func, self.pop());+ let a = func.resolve(self.pop());let lane = u32::from(decoder.simd_lane());self.pure(func,@@ -200,8 +200,8 @@ impl Builder {)}SimdKind::ReplaceLane { .. } => {- let b = Self::resolve(func, self.pop());- let a = Self::resolve(func, self.pop());+ let b = func.resolve(self.pop());+ let a = func.resolve(self.pop());let lane = u32::from(decoder.simd_lane());self.pure(func,diff --git a/Libraries/LibWasm/JIT/src/builder/tables.rs b/Libraries/LibWasm/JIT/src/builder/tables.rsindex c53e662d711..f419c75d4b8 100644--- a/Libraries/LibWasm/JIT/src/builder/tables.rs+++ b/Libraries/LibWasm/JIT/src/builder/tables.rs@@ -23,7 +23,7 @@ impl Builder {let start = func.operands.len() as u32;func.operands.push(self.instance);for &operand in operands {- func.operands.push(Self::resolve(func, operand));+ func.operands.push(func.resolve(operand));}let value = Self::append(func,@@ -83,7 +83,7 @@ impl Builder {}pub(super) fn table_get(&mut self, func: &mut Func, table: u32) {- let index = Self::resolve(func, self.pop());+ let index = func.resolve(self.pop());let data = self.table_data(func, table);let value = Self::append(func,@@ -98,8 +98,8 @@ impl Builder {}pub(super) fn table_set(&mut self, func: &mut Func, table: u32) {- let value = Self::resolve(func, self.pop());- let index = Self::resolve(func, self.pop());+ let value = func.resolve(self.pop());+ let index = func.resolve(self.pop());let data = self.table_data(func, table);Self::append(func,diff --git a/Libraries/LibWasm/JIT/src/codegen/aarch64/mod.rs b/Libraries/LibWasm/JIT/src/codegen/aarch64/mod.rsindex 802e6c8ff16..ec87cc77ece 100644--- a/Libraries/LibWasm/JIT/src/codegen/aarch64/mod.rs+++ b/Libraries/LibWasm/JIT/src/codegen/aarch64/mod.rs@@ -29,7 +29,6 @@ use crate::asm::aarch64::{Assembler, Cond, Extend, FloatSize, MemOp, MemOperand,use crate::asm::{Fpr, Gpr, Label, Width};use crate::convention::{self, Register};use crate::ir::{BlockId, FloatCondition, Func, IntCondition, NONE, Op, Type, Value};-use crate::passes::cleanup::Liveliness;use crate::regalloc::{Allocation, Location, Move, NO_REGISTER, NO_SLOT};use libwasm_module::abi::{ExecutionContext, InstanceData};use std::mem::offset_of;@@ -147,7 +146,6 @@ struct EdgeStub {pub struct CodeGenerator<'a> {func: &'a Func,- liveliness: &'a Liveliness,allocation: &'a Allocation,runtime: &'a RuntimeInfo,asm: Assembler,@@ -160,22 +158,14 @@ pub struct CodeGenerator<'a> {frame_size: u32,/// The block whose code is being generated.block: BlockId,- /// Why the function could not be compiled, if a lowering found out.- failure: Option<crate::CompileFailure>,exception_sites: Vec<u32>,}impl<'a> CodeGenerator<'a> {- pub fn new(- func: &'a Func,- liveliness: &'a Liveliness,- allocation: &'a Allocation,- runtime: &'a RuntimeInfo,- ) -> Self {+ pub fn new(func: &'a Func, allocation: &'a Allocation, runtime: &'a RuntimeInfo) -> Self {let size = convention::FRAME_HEADER_SIZE as u32 + 8 * allocation.slot_count + allocation.outgoing_size;Self {func,- liveliness,allocation,runtime,asm: Assembler::new(),@@ -186,7 +176,6 @@ impl<'a> CodeGenerator<'a> {edge_stubs: Vec::new(),frame_size: size.next_multiple_of(16),block: 0,- failure: None,exception_sites: Vec::new(),}}@@ -213,7 +202,7 @@ impl<'a> CodeGenerator<'a> {let data = func.blocks[block as usize];for value in data.start..data.end {let op = func.node(value).op;- if self.liveliness.is_dead(value) || matches!(op, Op::Phi | Op::Forward) || op.is_entry_value() {+ if op.is_entry_value() {continue;}for item in self.allocation.node_moves(value) {@@ -226,9 +215,6 @@ impl<'a> CodeGenerator<'a> {self.store_to_slot(record.output, slot, func.node(value).ty == Type::V128);}}- if let Some(failure) = self.failure {- return Err(failure);- }}self.out_of_line();let code = self.asm.finish().map_err(|_| crate::CompileFailure::CodeGeneration)?;@@ -271,7 +257,7 @@ impl<'a> CodeGenerator<'a> {let data = func.blocks[0];for value in data.start..data.end {let node = func.node(value);- if self.liveliness.is_dead(value) || !matches!(node.op, Op::Param | Op::MemoryBase) {+ if !matches!(node.op, Op::Param | Op::MemoryBase) {continue;}let record = self.allocation.node(value);@@ -785,10 +771,9 @@ impl<'a> CodeGenerator<'a> {/// Generates the code of `func`.pub fn generate(func: &Func,- liveliness: &Liveliness,allocation: &Allocation,runtime: &RuntimeInfo,) -> Result<Generated, crate::CompileFailure> {let _ = (NONE, Shift::Lsl);- CodeGenerator::new(func, liveliness, allocation, runtime).generate()+ CodeGenerator::new(func, allocation, runtime).generate()}diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rsindex f536f4a260a..00c8a9dd296 100644--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs@@ -23,7 +23,6 @@ use crate::asm::x86_64::{Assembler, BitwiseOp, Cond, Precision, VexOperand};use crate::asm::{Address, Fpr, Gpr, Label, Width};use crate::convention::{self, Register};use crate::ir::{BlockId, FloatCondition, Func, IntCondition, NONE, Op, Type, Value};-use crate::passes::cleanup::Liveliness;use crate::regalloc::{Allocation, Location, Move, NO_REGISTER, NO_SLOT};use libwasm_module::abi::{ExecutionContext, InstanceData};use std::mem::offset_of;@@ -91,7 +90,6 @@ struct EdgeStub {pub struct CodeGenerator<'a> {func: &'a Func,- liveliness: &'a Liveliness,allocation: &'a Allocation,runtime: &'a RuntimeInfo,asm: Assembler,@@ -111,16 +109,10 @@ pub struct CodeGenerator<'a> {}impl<'a> CodeGenerator<'a> {- pub fn new(- func: &'a Func,- liveliness: &'a Liveliness,- allocation: &'a Allocation,- runtime: &'a RuntimeInfo,- ) -> Self {+ pub fn new(func: &'a Func, allocation: &'a Allocation, runtime: &'a RuntimeInfo) -> Self {let size = convention::FRAME_HEADER_SIZE as u32 + 8 * allocation.slot_count + allocation.outgoing_size;Self {func,- liveliness,allocation,runtime,asm: Assembler::new(),@@ -159,7 +151,7 @@ impl<'a> CodeGenerator<'a> {let data = func.blocks[block as usize];for value in data.start..data.end {let op = func.node(value).op;- if self.liveliness.is_dead(value) || matches!(op, Op::Phi | Op::Forward) || op.is_entry_value() {+ if op.is_entry_value() {continue;}for item in self.allocation.node_moves(value) {@@ -220,7 +212,7 @@ impl<'a> CodeGenerator<'a> {let data = func.blocks[0];for value in data.start..data.end {let node = func.node(value);- if self.liveliness.is_dead(value) || !matches!(node.op, Op::Param | Op::MemoryBase) {+ if !matches!(node.op, Op::Param | Op::MemoryBase) {continue;}let record = self.allocation.node(value);@@ -727,10 +719,9 @@ impl<'a> CodeGenerator<'a> {/// Generates the code of `func`.pub fn generate(func: &Func,- liveliness: &Liveliness,allocation: &Allocation,runtime: &RuntimeInfo,) -> Result<Generated, crate::CompileFailure> {let _ = NONE;- CodeGenerator::new(func, liveliness, allocation, runtime).generate()+ CodeGenerator::new(func, allocation, runtime).generate()}diff --git a/Libraries/LibWasm/JIT/src/ir/dump.rs b/Libraries/LibWasm/JIT/src/ir/dump.rsindex 751a0e9c592..450b1ca6d16 100644--- a/Libraries/LibWasm/JIT/src/ir/dump.rs+++ b/Libraries/LibWasm/JIT/src/ir/dump.rs@@ -119,8 +119,8 @@ pub fn node_text(func: &Func, value: Value) -> String {text}-/// The whole function as text. Nodes for which `is_dead` holds are left out.-pub fn dump(func: &Func, is_dead: &dyn Fn(Value) -> bool) -> String {+/// The whole function as text.+pub fn dump(func: &Func) -> String {let mut out = String::new();let types = |types: &[Type]| types.iter().map(|ty| ty.name()).collect::<Vec<_>>().join(", ");writeln!(out, "function ({}) -> ({})", types(&func.params), types(&func.results)).unwrap();@@ -145,16 +145,13 @@ pub fn dump(func: &Func, is_dead: &dyn Fn(Value) -> bool) -> String {}out.push('\n');for phi in func.phis(block_id) {- if func.node(phi).op == Op::Phi && !is_dead(phi) {+ if func.node(phi).op == Op::Phi {writeln!(out, " v{phi} = {}", node_text(func, phi)).unwrap();}}for value in block.start..block.end {let node = func.node(value);- if is_dead(value)- || (node.op.is_entry_value() && node.op != Op::Param)- || matches!(node.op, Op::Phi | Op::Forward)- {+ if (node.op.is_entry_value() && node.op != Op::Param) || matches!(node.op, Op::Phi | Op::Forward) {continue;}if node.op.is_terminator() {diff --git a/Libraries/LibWasm/JIT/src/ir/mod.rs b/Libraries/LibWasm/JIT/src/ir/mod.rsindex 4c77a15d53e..6118f987e36 100644--- a/Libraries/LibWasm/JIT/src/ir/mod.rs+++ b/Libraries/LibWasm/JIT/src/ir/mod.rs@@ -925,15 +925,36 @@ impl Func {}}- pub fn inputs_mut(&mut self, value: Value) -> &mut [u32] {- let node = &mut self.nodes[value as usize];- match node.op.shape() {- Shape::Fixed(count) => &mut node.args[..count as usize],- Shape::Variadic => {- let start = node.args[0] as usize;- &mut self.operands[start..start + node.args[1] as usize]+ /// The value a forwarded phi stands for, or the value itself.+ pub fn resolve(&self, mut value: Value) -> Value {+ while self.nodes[value as usize].op == Op::Forward {+ value = self.nodes[value as usize].args[0];+ }+ value+ }++ /// The value a phi always has, if its inputs are only itself and one other value.+ pub fn trivial_phi_input(&self, phi: Value) -> Option<Value> {+ let mut same = NONE;+ for &input in self.inputs(phi) {+ let input = self.resolve(input);+ if input == phi || input == same {+ continue;+ }+ if same != NONE {+ return None;}+ same = input;}+ (same != NONE).then_some(same)+ }++ /// Makes `phi` stand for `value` from now on.+ pub fn forward(&mut self, phi: Value, value: Value) {+ let node = &mut self.nodes[phi as usize];+ node.op = Op::Forward;+ node.args[0] = value;+ node.args[1] = 0;}pub fn predecessors(&self, block: BlockId) -> &[BlockId] {diff --git a/Libraries/LibWasm/JIT/src/ir/verify.rs b/Libraries/LibWasm/JIT/src/ir/verify.rsindex 08af7af88a5..d13ccebcc1b 100644--- a/Libraries/LibWasm/JIT/src/ir/verify.rs+++ b/Libraries/LibWasm/JIT/src/ir/verify.rs@@ -58,9 +58,8 @@ pub fn dominates(idom: &[u32], a: u32, mut b: u32) -> bool {}}-/// Checks the function. `is_dead` tells which nodes cleanup removed; `after_cleanup` requires that no forwarded-/// phi is used.-pub fn verify(func: &Func, is_dead: &dyn Fn(Value) -> bool, after_cleanup: bool) -> Result<(), String> {+/// Checks the function. `after_cleanup` requires that no forwarded phi is used.+pub fn verify(func: &Func, after_cleanup: bool) -> Result<(), String> {let mut errors = Vec::new();let mut error = |message: String| {if errors.len() < 20 {@@ -152,7 +151,7 @@ pub fn verify(func: &Func, is_dead: &dyn Fn(Value) -> bool, after_cleanup: bool)let block_id = index as u32;for value in (block.start..block.end).chain(func.phis(block_id)) {let node = func.node(value);- if node.op.is_entry_value() || block_of[value as usize] != block_id || is_dead(value) {+ if node.op.is_entry_value() || block_of[value as usize] != block_id {continue;}if after_cleanup && node.op == Op::Forward {@@ -174,9 +173,6 @@ pub fn verify(func: &Func, is_dead: &dyn Fn(Value) -> bool, after_cleanup: bool)if after_cleanup && input_node.op == Op::Forward {error(format!("v{value} uses the forwarded phi v{input}"));}- if is_dead(input) {- error(format!("v{value} uses the dead v{input}"));- }let (use_block, position) = if node.op == Op::Phi {let predecessor = func.predecessors(block_id)[input_index];(predecessor, func.blocks[predecessor as usize].end)diff --git a/Libraries/LibWasm/JIT/src/lib.rs b/Libraries/LibWasm/JIT/src/lib.rsindex 80659faf0ab..fddf3d80964 100644--- a/Libraries/LibWasm/JIT/src/lib.rs+++ b/Libraries/LibWasm/JIT/src/lib.rs@@ -68,9 +68,6 @@ pub struct Options {pub stress_registers: bool,/// Leave loop invariant code in its loop.pub no_licm: bool,- /// Replace nodes that compute what a dominating node computed already, beyond what building does (`passes/gvn.rs`).- /// Off by default: it finds about 0.1% of the nodes of real modules redundant, for 7 to 16 ns per code byte.- pub gvn: bool,/// Refuse OSR compiles at loops in no other loop, so that tests reach the loops in them.pub stress_nested_osr: bool,}@@ -113,10 +110,9 @@ pub struct CompileRequest {pub struct CompileContext {pub func: ir::Func,builder: builder::Builder,- pub liveliness: passes::cleanup::Liveliness,+ liveliness: passes::cleanup::Liveliness,licm: passes::licm::Licm,scheduler: passes::schedule::Scheduler,- gvn: passes::gvn::Gvn,allocator: regalloc::Allocator,pub allocation: regalloc::Allocation,}@@ -137,8 +133,6 @@ pub struct Stats {pub moves: u32,/// The nodes loop invariant code motion moved out of loops.pub hoisted: u32,- /// The nodes global value numbering replaced.- pub eliminated: u32,}/// The time stamp counter, for the phase timers.@@ -203,12 +197,12 @@ pub fn compile(context: &mut CompileContext, request: &CompileRequest) -> Result}lap(0, &mut stats);if request.options.verify_ir- && let Err(errors) = ir::verify::verify(&context.func, &|_| false, false)+ && let Err(errors) = ir::verify::verify(&context.func, false){panic!("invalid IR after building function {}:\n{errors}\n{}",request.function,- ir::dump::dump(&context.func, &|_| false)+ ir::dump::dump(&context.func));}passes::cleanup::cleanup(&mut context.func, &mut context.liveliness);@@ -220,31 +214,22 @@ pub fn compile(context: &mut CompileContext, request: &CompileRequest) -> Result} else {context.licm.run(&context.func, &context.liveliness);}- let gvn = request.options.gvn.then_some(&mut context.gvn);- context.scheduler.run(- &mut context.func,- &mut context.liveliness,- &context.licm.home,- gvn,- module.global_space.len(),- );+ context+ .scheduler+ .run(&mut context.func, &mut context.liveliness, &context.licm.home);lap(1, &mut stats);- let liveliness = &context.liveliness;if request.options.verify_ir- && let Err(errors) = ir::verify::verify(&context.func, &|value| liveliness.is_dead(value), true)+ && let Err(errors) = ir::verify::verify(&context.func, true){panic!("invalid IR after cleanup and scheduling of function {}:\n{errors}\n{}",request.function,- ir::dump::dump(&context.func, &|value| liveliness.is_dead(value))+ ir::dump::dump(&context.func));}- context.allocator.allocate_with(- &context.func,- &context.liveliness,- &mut context.allocation,- request.options.stress_registers,- );+ context+ .allocator+ .allocate(&context.func, &mut context.allocation, request.options.stress_registers);lap(3, &mut stats);if timed {// NB: Liveness runs first in the allocator, which times it.@@ -252,27 +237,21 @@ pub fn compile(context: &mut CompileContext, request: &CompileRequest) -> Resultstats.ticks[3] = stats.ticks[3].saturating_sub(stats.ticks[2]);}if request.options.verify_ir- && let Err(errors) = regalloc::verify::verify(&context.func, &context.liveliness, &context.allocation)+ && let Err(errors) = regalloc::verify::verify(&context.func, &context.allocation){panic!("invalid register allocation of function {}:\n{errors}\n{}\n{}",request.function,- ir::dump::dump(&context.func, &|value| liveliness.is_dead(value)),- regalloc::verify::dump(&context.func, &context.liveliness, &context.allocation)+ ir::dump::dump(&context.func),+ regalloc::verify::dump(&context.func, &context.allocation));}- let generated = codegen::target::generate(- &context.func,- &context.liveliness,- &context.allocation,- &request.runtime,- )?;+ let generated = codegen::target::generate(&context.func, &context.allocation, &request.runtime)?;lap(4, &mut stats);stats.nodes = context.func.nodes.len() as u32;stats.slots = context.allocation.slot_count;stats.moves = context.allocation.moves.len() as u32;stats.hoisted = if no_licm { 0 } else { context.licm.hoisted };- stats.eliminated = if request.options.gvn { context.gvn.eliminated } else { 0 };let mut compiled = CompiledFunction {code: generated.code,frame_size: generated.frame_size,@@ -283,12 +262,8 @@ pub fn compile(context: &mut CompileContext, request: &CompileRequest) -> Resultif request.options.dump_ir || request.options.dump_asm {let mut text = String::new();if request.options.dump_ir {- text.push_str(&ir::dump::dump(&context.func, &|value| liveliness.is_dead(value)));- text.push_str(®alloc::verify::dump(- &context.func,- &context.liveliness,- &context.allocation,- ));+ text.push_str(&ir::dump::dump(&context.func));+ text.push_str(®alloc::verify::dump(&context.func, &context.allocation));}if request.options.dump_asm {let architecture = if cfg!(target_arch = "aarch64") {diff --git a/Libraries/LibWasm/JIT/src/passes/cleanup.rs b/Libraries/LibWasm/JIT/src/passes/cleanup.rsindex b47881f1ae4..be8f863fe39 100644--- a/Libraries/LibWasm/JIT/src/passes/cleanup.rs+++ b/Libraries/LibWasm/JIT/src/passes/cleanup.rs@@ -23,29 +23,6 @@ impl Liveliness {}}-fn resolve(func: &Func, mut value: Value) -> Value {- while func.nodes[value as usize].op == Op::Forward {- value = func.nodes[value as usize].args[0];- }- value-}--/// Whether a phi's inputs are only itself and one other value.-fn trivial_input(func: &Func, phi: Value) -> Option<Value> {- let mut same = NONE;- for &input in func.inputs(phi) {- let input = resolve(func, input);- if input == phi || input == same {- continue;- }- if same != NONE {- return None;- }- same = input;- }- (same != NONE).then_some(same)-}-pub fn cleanup(func: &mut Func, state: &mut Liveliness) {// Trivial phis, to a fixed point over the phis only.loop {@@ -55,12 +32,9 @@ pub fn cleanup(func: &mut Func, state: &mut Liveliness) {while phi != NONE {let next = func.nodes[phi as usize].args[2];if func.nodes[phi as usize].op == Op::Phi- && let Some(value) = trivial_input(func, phi)+ && let Some(value) = func.trivial_phi_input(phi){- let node = &mut func.nodes[phi as usize];- node.op = Op::Forward;- node.args[0] = value;- node.args[1] = 0;+ func.forward(phi, value);changed = true;}phi = next;@@ -85,7 +59,7 @@ pub fn cleanup(func: &mut Func, state: &mut Liveliness) {match node.op.shape() {Shape::Fixed(inputs) => {for slot in 0..inputs as usize {- let input = resolve(func, node.args[slot]);+ let input = func.resolve(node.args[slot]);func.nodes[index].args[slot] = input;state.uses[input as usize] += 1;}@@ -93,7 +67,7 @@ pub fn cleanup(func: &mut Func, state: &mut Liveliness) {Shape::Variadic => {let start = node.args[0] as usize;for slot in start..start + node.args[1] as usize {- let input = resolve(func, func.operands[slot]);+ let input = func.resolve(func.operands[slot]);func.operands[slot] = input;state.uses[input as usize] += 1;}diff --git a/Libraries/LibWasm/JIT/src/passes/gvn.rs b/Libraries/LibWasm/JIT/src/passes/gvn.rsdeleted file mode 100644index 31a6bdc9219..00000000000--- a/Libraries/LibWasm/JIT/src/passes/gvn.rs+++ /dev/null@@ -1,129 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Global value numbering, over the dominator tree, as part of scheduling's walk in linear order: a node computing-//! what a node of a block that dominates it computed already is replaced by that node.-//!-//! The builder numbers values too, but forgets what a construct numbered when it ends, even where that dominates the-//! code after it (whatever a `block` computes before its first branch out, say). This pass keeps every entry for-//! as long as its block dominates the walk.-//!-//! Reads are numbered by alias class, with epochs that the writes of the class advance: memory loads by a memory-//! epoch that stores and calls advance, and global values by an epoch of their global that its `global.set`-//! advances and one of all globals that calls advance. A block continues the epochs of the block before it only if-//! that is its only predecessor, so that a read is only ever shared with one on every path to it.--use crate::ir::{BlockId, Effect, FLAG_IMMUTABLE, Func, NONE, Op, Shape, Value};-use crate::passes::dominators::Dominators;-use crate::table::Table;--type Key = [u32; 6];--#[derive(Default)]-pub struct Gvn {- dominators: Dominators,- table: Table<Key>,- log: Vec<(Key, u32)>,- /// The blocks whose entries are in the table, from the entry down the dominator tree, and where their entries- /// start in the log.- stack: Vec<(BlockId, u32)>,- /// The node each node was replaced by, or itself.- pub canon: Vec<Value>,- memory_epoch: u32,- global_epochs: Vec<u32>,- globals_epoch: u32,- previous: BlockId,- /// How many nodes were replaced.- pub eliminated: u32,-}--impl Gvn {- pub fn start(&mut self, func: &Func, globals: usize) {- self.dominators.compute(func);- self.table.clear();- self.log.clear();- self.stack.clear();- self.canon.clear();- self.canon.extend(0..func.nodes.len() as Value);- self.memory_epoch = 0;- self.global_epochs.clear();- self.global_epochs.resize(globals, 0);- self.globals_epoch = 0;- self.previous = NONE;- self.eliminated = 0;- }-- pub fn enter_block(&mut self, func: &Func, block: BlockId) {- while let Some(&(top, mark)) = self.stack.last() {- if self.dominators.dominates(top, block) {- break;- }- while self.log.len() > mark as usize {- let (key, previous) = self.log.pop().expect("the log is longer than the mark");- self.table.insert(key, previous);- }- self.stack.pop();- }- if func.predecessors(block) != [self.previous] {- self.memory_epoch += 1;- self.globals_epoch += 1;- }- self.stack.push((block, self.log.len() as u32));- self.previous = block;- }-- /// Numbers `value`, and returns the node that computes the same, if one does.- pub fn visit(&mut self, func: &Func, value: Value) -> Option<Value> {- let node = func.node(value);- let epochs = match node.op {- Op::Store | Op::AtomicRmw | Op::AtomicCompareExchange | Op::AtomicFence => {- self.memory_epoch += 1;- return None;- }- Op::GlobalSet => {- self.global_epochs[node.args[2] as usize] += 1;- return None;- }- Op::Call | Op::Helper => {- self.memory_epoch += 1;- self.globals_epoch += 1;- return None;- }- Op::Load | Op::VectorLoad => [self.memory_epoch, 0],- Op::GlobalGet if node.flags & FLAG_IMMUTABLE == 0 => {- [self.global_epochs[node.args[1] as usize], self.globals_epoch]- }- Op::Phi | Op::Forward | Op::CallResult | Op::Const128 => return None,- _ if node.effect() == Effect::Pure && !node.op.is_entry_value() => [0, 0],- _ => return None,- };- let Shape::Fixed(inputs) = node.op.shape() else {- return None;- };- let mut arguments = node.args;- for argument in arguments.iter_mut().take(inputs as usize) {- *argument = self.canon[*argument as usize];- }- let key = [- node.op as u32 | ((node.ty as u32) << 16) | (u32::from(node.flags) << 24),- arguments[0],- arguments[1],- arguments[2],- epochs[0],- epochs[1],- ];- if let Some(existing) = self.table.get(key)- && existing != NONE- {- self.canon[value as usize] = existing;- self.eliminated += 1;- return Some(existing);- }- let previous = self.table.insert(key, value).unwrap_or(NONE);- self.log.push((key, previous));- None- }-}diff --git a/Libraries/LibWasm/JIT/src/passes/mod.rs b/Libraries/LibWasm/JIT/src/passes/mod.rsindex a7201a51f61..f29cbba1e1b 100644--- a/Libraries/LibWasm/JIT/src/passes/mod.rs+++ b/Libraries/LibWasm/JIT/src/passes/mod.rs@@ -8,6 +8,5 @@pub mod cleanup;pub mod dominators;-pub mod gvn;pub mod licm;pub mod schedule;diff --git a/Libraries/LibWasm/JIT/src/passes/schedule.rs b/Libraries/LibWasm/JIT/src/passes/schedule.rsindex 18b8e180fc8..57f73ee20ce 100644--- a/Libraries/LibWasm/JIT/src/passes/schedule.rs+++ b/Libraries/LibWasm/JIT/src/passes/schedule.rs@@ -9,12 +9,10 @@//! renumbered, so a node's index is its position again.//!//! The entry values come first, in the range of the entry block, and the phis last, outside every block's range,-//! since they are defined where their block starts wherever they are. Global value numbering (`gvn`) runs in the-//! same walk and leaves out the nodes it replaces.+//! since they are defined where their block starts wherever they are.use crate::ir::{Func, NONE, Node, Op, Shape, Value};use crate::passes::cleanup::Liveliness;-use crate::passes::gvn::Gvn;#[derive(Default)]pub struct Scheduler {@@ -25,20 +23,9 @@ pub struct Scheduler {}impl Scheduler {- /// Schedules `func`, moving nodes as `home` says, and numbering values with `gvn` if it is given, for a module- /// with `globals` globals.- pub fn run(- &mut self,- func: &mut Func,- liveliness: &mut Liveliness,- home: &[u32],- mut gvn: Option<&mut Gvn>,- globals: usize,- ) {+ /// Schedules `func`, moving nodes as `home` says.+ pub fn run(&mut self, func: &mut Func, liveliness: &mut Liveliness, home: &[u32]) {let count = func.nodes.len();- if let Some(gvn) = gvn.as_deref_mut() {- gvn.start(func, globals);- }for list in &mut self.hoisted {list.clear();}@@ -59,17 +46,6 @@ impl Scheduler {for block in 0..func.blocks.len() {let data = func.blocks[block];let start = if block == 0 { 0 } else { self.order.len() };- if let Some(gvn) = gvn.as_deref_mut() {- gvn.enter_block(func, block as u32);- }- let mut emit = |value: Value, order: &mut Vec<Value>| {- if let Some(gvn) = gvn.as_deref_mut()- && gvn.visit(func, value).is_some()- {- return;- }- order.push(value);- };for value in data.start..data.end - 1 {let op = func.nodes[value as usize].op;if live(value)@@ -77,13 +53,13 @@ impl Scheduler {&& !matches!(op, Op::Phi | Op::Forward)&& home[value as usize] == NONE{- emit(value, &mut self.order);+ self.order.push(value);}}for index in 0..self.hoisted[block].len() {- emit(self.hoisted[block][index], &mut self.order);+ self.order.push(self.hoisted[block][index]);}- emit(data.end - 1, &mut self.order);+ self.order.push(data.end - 1);func.blocks[block].start = start as u32;func.blocks[block].end = self.order.len() as u32;}@@ -100,14 +76,6 @@ impl Scheduler {for (index, value) in self.order.iter().enumerate() {self.renumbered[*value as usize] = index as Value;}- if let Some(gvn) = gvn {- for value in 0..count {- let canon = gvn.canon[value];- if canon as usize != value {- self.renumbered[value] = self.renumbered[canon as usize];- }- }- }self.nodes.clear();for &value in &self.order {let mut node = func.nodes[value as usize];diff --git a/Libraries/LibWasm/JIT/src/regalloc/liveness.rs b/Libraries/LibWasm/JIT/src/regalloc/liveness.rsindex 2b25f5fdd37..9e1ba187dd7 100644--- a/Libraries/LibWasm/JIT/src/regalloc/liveness.rs+++ b/Libraries/LibWasm/JIT/src/regalloc/liveness.rs@@ -19,7 +19,6 @@use crate::convention::{self, Place, Register};use crate::ir::{BlockId, Func, NONE, Op, Type, Value};-use crate::passes::cleanup::Liveliness;pub fn node_position(value: Value) -> u32 {4 * value + 2@@ -56,9 +55,9 @@ pub const NO_HINT: u8 = u8::MAX;/// Whether a node is a value the register allocator gives a location.#[inline]-pub fn is_allocated(func: &Func, liveliness: &Liveliness, value: Value) -> bool {+pub fn is_allocated(func: &Func, value: Value) -> bool {let node = func.node(value);- node.ty != Type::None && !node.op.is_constant() && !liveliness.is_dead(value)+ node.ty != Type::None && !node.op.is_constant()}impl Liveness {@@ -88,7 +87,7 @@ impl Liveness {uses.get(index).copied()}- pub fn compute(&mut self, func: &Func, liveliness: &Liveliness) {+ pub fn compute(&mut self, func: &Func) {let count = func.nodes.len();self.definition.clear();self.definition.resize(count, NONE);@@ -116,9 +115,6 @@ impl Liveness {}for value in data.start..data.end {let node = func.node(value);- if liveliness.is_dead(value) || matches!(node.op, Op::Phi | Op::Forward) {- continue;- }if node.op.is_entry_value() {if !node.op.is_constant() && node.ty != Type::None {self.definition[value as usize] = 0;@@ -158,7 +154,7 @@ impl Liveness {let data = &func.blocks[block as usize];for value in data.start..data.end {let node = func.node(value);- if liveliness.is_dead(value) || matches!(node.op, Op::Phi | Op::Forward) || node.op.is_entry_value() {+ if node.op.is_entry_value() {continue;}let position = node_position(value);diff --git a/Libraries/LibWasm/JIT/src/regalloc/mod.rs b/Libraries/LibWasm/JIT/src/regalloc/mod.rsindex 6c7d0554c57..03a42a6551b 100644--- a/Libraries/LibWasm/JIT/src/regalloc/mod.rs+++ b/Libraries/LibWasm/JIT/src/regalloc/mod.rs@@ -36,7 +36,6 @@ pub use aarch64::fits_immediate;use crate::codegen;use crate::convention::{self, Place, Register};use crate::ir::{BlockId, Func, NONE, Op, Type, Value};-use crate::passes::cleanup::Liveliness;use liveness::{Liveness, NO_HINT, block_start_position, node_position, predecessor_index};/// No register.@@ -50,9 +49,6 @@ pub const SLOT_INPUT: u8 = u8::MAX - 2;/// this many positions (four per node), where loading it into a register once serves both uses.const SLOT_INPUT_REUSE_DISTANCE: u32 = 4 * 8;-/// OPTIMIZATION: Parallel moves up to this many are ordered by rescanning them, more by counting their readers.-const SMALL_PARALLEL_MOVE: usize = 8;-/// No spill slot.pub const NO_SLOT: i32 = i32::MIN;@@ -81,7 +77,7 @@ pub struct Move {pub vector: bool,}-/// The storage of `resolve_many()`: the pending readers of each location, the pending move that writes each+/// The storage of `resolve()`: the pending readers of each location, the pending move that writes each/// location, the locations read as a v128, the locations whose value went to the cycle slot, which pending moves are/// placed, and the moves ready to be placed.#[derive(Default)]@@ -400,25 +396,15 @@ pub struct Allocator {use convention::{STRESS_FPRS, STRESS_GPRS};impl Allocator {- /// Allocates registers for `func` into `allocation`./// Allocates registers for `func` into `allocation`, with only a few registers if `stress`.- pub fn allocate_with(&mut self, func: &Func, liveliness: &Liveliness, allocation: &mut Allocation, stress: bool) {- if stress {- self.gprs = &STRESS_GPRS;- self.fprs = &STRESS_FPRS;- }- self.allocate(func, liveliness, allocation);- self.gprs = &convention::ALLOCATABLE_GPRS;- self.fprs = &convention::ALLOCATABLE_FPRS;- }-- pub fn allocate(&mut self, func: &Func, liveliness: &Liveliness, allocation: &mut Allocation) {- if self.gprs.is_empty() {- self.gprs = &convention::ALLOCATABLE_GPRS;- self.fprs = &convention::ALLOCATABLE_FPRS;- }+ pub fn allocate(&mut self, func: &Func, allocation: &mut Allocation, stress: bool) {+ (self.gprs, self.fprs) = if stress {+ (&STRESS_GPRS[..], &STRESS_FPRS[..])+ } else {+ (&convention::ALLOCATABLE_GPRS[..], &convention::ALLOCATABLE_FPRS[..])+ };let start = crate::ticks();- self.liveness.compute(func, liveliness);+ self.liveness.compute(func);self.liveness_ticks = crate::ticks() - start;self.dominators.compute(func);let count = func.nodes.len();@@ -443,19 +429,19 @@ impl Allocator {self.end_states.resize(func.blocks.len(), [NONE; REGISTER_COUNT]);self.header_states.clear();self.header_states.resize(func.loops.len(), [NONE; REGISTER_COUNT]);- self.find_webs(func, liveliness);+ self.find_webs(func);for block in 0..func.blocks.len() as BlockId {self.current_block = block;- self.start_block(func, liveliness, allocation, block);+ self.start_block(func, allocation, block);allocation.block_states[block as usize] = self.contents;let data = func.blocks[block as usize];for value in data.start..data.end {let op = func.node(value).op;- if liveliness.is_dead(value) || matches!(op, Op::Phi | Op::Forward) || op.is_entry_value() {+ if op.is_entry_value() {continue;}- self.allocate_node(func, liveliness, allocation, value);+ self.allocate_node(func, allocation, value);}self.end_states[block as usize] = self.contents;let successors_start = data.successors_start;@@ -531,7 +517,7 @@ impl Allocator {// Webs./// Puts each phi and its inputs in one web.- fn find_webs(&mut self, func: &Func, liveliness: &Liveliness) {+ fn find_webs(&mut self, func: &Func) {self.web_parents.clear();self.web_parents.resize(func.nodes.len(), NONE);self.web_slots.clear();@@ -539,7 +525,7 @@ impl Allocator {self.slot_values.clear();let in_web = |value: Value| {let op = func.node(value).op;- liveness::is_allocated(func, liveliness, value) && op != Op::Forward && !op.is_entry_value()+ liveness::is_allocated(func, value) && !op.is_entry_value()};for block in 0..func.blocks.len() as BlockId {for phi in func.phis(block) {@@ -733,10 +719,10 @@ impl Allocator {result}- fn start_block(&mut self, func: &Func, liveliness: &Liveliness, allocation: &mut Allocation, block: BlockId) {+ fn start_block(&mut self, func: &Func, allocation: &mut Allocation, block: BlockId) {self.position = block_start_position(func, block);if block == 0 {- self.start_entry(func, liveliness, allocation);+ self.start_entry(func, allocation);return;}let predecessors = func.predecessors(block);@@ -796,20 +782,16 @@ impl Allocator {let slot = edge_slot(func, predecessor, block);self.edge_moves(func, allocation, predecessor, block, slot, &state);}- let _ = liveliness;self.set_contents(state);}- fn start_entry(&mut self, func: &Func, liveliness: &Liveliness, allocation: &mut Allocation) {+ fn start_entry(&mut self, func: &Func, allocation: &mut Allocation) {let mut state = [NONE; REGISTER_COUNT];self.places.clear();convention::parameter_places(&func.params, &mut self.places);let data = func.blocks[0];for value in data.start..data.end {let node = func.node(value);- if liveliness.is_dead(value) {- continue;- }match node.op {Op::Instance => state[convention::INSTANCE_REGISTER as usize] = value,Op::MemoryBase => state[convention::MEMORY_BASE_REGISTER as usize] = value,@@ -935,57 +917,15 @@ impl Allocator {return;}let start = allocation.moves.len() as u32;- self.resolve(func, allocation);+ self.resolve(allocation);allocation.edge_moves[slot as usize] = (start, allocation.moves.len() as u32 - start);}/// Orders the parallel moves in `pending` into a sequence with the same effect, appended to the allocation's- /// moves. Cycles go through the cycle slot.- fn resolve(&mut self, func: &Func, allocation: &mut Allocation) {- let _ = func;- self.resolved.clear();- if self.pending.len() > SMALL_PARALLEL_MOVE {- self.resolve_many(allocation);- allocation.moves.extend_from_slice(&self.resolved);- return;- }- while !self.pending.is_empty() {- let ready = self- .pending- .iter()- .position(|candidate| self.pending.iter().all(|other| other.from != candidate.to));- if let Some(index) = ready {- let ready = self.pending.swap_remove(index);- self.resolved.push(ready);- continue;- }- // Every destination is still a source: the moves form cycles. Save one destination in the cycle slot.- if allocation.cycle_slot == NO_SLOT {- // NB: Two slots, in case the value is a v128.- allocation.slot_count += 2;- allocation.cycle_slot = convention::spill_slot_offset(allocation.slot_count - 1);- }- let saved = self.pending[0].to;- let temp = Location::Slot(allocation.cycle_slot);- let vector = self.pending[0].vector;- self.resolved.push(Move {- from: saved,- to: temp,- vector,- });- for pending in &mut self.pending {- if pending.from == saved {- pending.from = temp;- }- }- }- allocation.moves.extend_from_slice(&self.resolved);- }-- /// `resolve()` for many moves, like the edges into a merge with many phis, in linear time: it counts the pending- /// readers of each location, and places a move once nothing reads its destination any more, which may make the- /// move into its source ready in turn.- fn resolve_many(&mut self, allocation: &mut Allocation) {+ /// moves, in linear time: it counts the pending readers of each location, and places a move once nothing reads+ /// its destination any more, which may make the move into its source ready in turn. Cycles go through the cycle+ /// slot.+ fn resolve(&mut self, allocation: &mut Allocation) {fn key(location: Location) -> u64 {match location {Location::Register(register) => (1 << 40) | u64::from(register),@@ -995,6 +935,7 @@ impl Allocator {Location::Constant(value) => (5 << 40) | u64::from(value),}}+ self.resolved.clear();let scratch = &mut self.move_scratch;scratch.readers.clear();scratch.writers.clear();@@ -1073,11 +1014,12 @@ impl Allocator {scratch.ready.push(unfinished as u32);}self.pending.clear();+ allocation.moves.extend_from_slice(&self.resolved);}// Nodes.- fn allocate_node(&mut self, func: &Func, liveliness: &Liveliness, allocation: &mut Allocation, value: Value) {+ fn allocate_node(&mut self, func: &Func, allocation: &mut Allocation, value: Value) {self.position = node_position(value);let node = *func.node(value);let moves_start = allocation.moves.len() as u32;@@ -1091,7 +1033,6 @@ impl Allocator {Op::CallResult => self.allocate_call_result(func, allocation, value),_ => self.allocate_simple(func, allocation, value),}- let _ = liveliness;let record = &mut allocation.nodes[value as usize];record.moves_start = moves_start;record.moves_count = allocation.moves.len() as u32 - moves_start;@@ -1464,7 +1405,6 @@ pub fn edge_slot(func: &Func, from: BlockId, to: BlockId) -> u32 {#[cfg(test)]mod tests {use super::{Allocation, Allocator, Location, Move, NO_SLOT};- use crate::ir::Func;use std::collections::HashMap;/// Runs `moves` as `resolve()` orders them, and checks that every destination gets what its source had before.@@ -1479,7 +1419,7 @@ mod tests {to: Location::Register(to),vector: false,}));- allocator.resolve(&Func::default(), &mut allocation);+ allocator.resolve(&mut allocation);let mut state: HashMap<Location, u64> = (0..64).map(|register| (Location::Register(register), u64::from(register))).collect();@@ -1494,7 +1434,10 @@ mod tests {#[test]fn parallel_moves_keep_their_sources() {- // A long chain, one cycle through everything, two cycles, and fan-out from cycle members.+ // A swap, a short cycle and chain, a long chain, one cycle through everything, two cycles, and fan-out from+ // cycle members.+ check(&[(0, 1), (1, 0)]);+ check(&[(0, 1), (1, 2), (2, 0), (4, 3)]);check(&(0..40).map(|index| (index + 1, index)).collect::<Vec<_>>());check(&(0..40).map(|index| ((index + 1) % 40, index)).collect::<Vec<_>>());let mut two: Vec<(u8, u8)> = (0..10).map(|index| ((index + 1) % 10, index)).collect();diff --git a/Libraries/LibWasm/JIT/src/regalloc/verify.rs b/Libraries/LibWasm/JIT/src/regalloc/verify.rsindex 69442652906..546f8367247 100644--- a/Libraries/LibWasm/JIT/src/regalloc/verify.rs+++ b/Libraries/LibWasm/JIT/src/regalloc/verify.rs@@ -14,7 +14,6 @@use super::{Allocation, CONSTANT_INPUT, Location, NO_REGISTER, REGISTER_COUNT, SLOT_INPUT, call_result_types};use crate::convention::{self, Place};use crate::ir::{BlockId, Func, NONE, Op, Shape, Value};-use crate::passes::cleanup::Liveliness;use crate::regalloc::liveness::{Liveness, block_start_position, edge_position, node_position, predecessor_index};use std::collections::HashMap;@@ -85,9 +84,9 @@ impl Simulation<'_> {}}-pub fn verify(func: &Func, liveliness: &Liveliness, allocation: &Allocation) -> Result<(), String> {+pub fn verify(func: &Func, allocation: &Allocation) -> Result<(), String> {let mut liveness = Liveness::default();- liveness.compute(func, liveliness);+ liveness.compute(func);let mut simulation = Simulation {liveness: &liveness,registers: [NONE; REGISTER_COUNT],@@ -131,7 +130,7 @@ pub fn verify(func: &Func, liveliness: &Liveliness, allocation: &Allocation) ->let data = func.blocks[block as usize];for value in data.start..data.end {let node = *func.node(value);- if liveliness.is_dead(value) || matches!(node.op, Op::Phi | Op::Forward) || node.op.is_entry_value() {+ if node.op.is_entry_value() {continue;}let record = *allocation.node(value);@@ -273,7 +272,7 @@ pub fn verify(func: &Func, liveliness: &Liveliness, allocation: &Allocation) ->}/// The allocation as text, for `dump-ir` and failures.-pub fn dump(func: &Func, liveliness: &Liveliness, allocation: &Allocation) -> String {+pub fn dump(func: &Func, allocation: &Allocation) -> String {use std::fmt::Write;let name = |location: &Location| match location {Location::Register(register) if convention::is_fpr(*register) => {@@ -314,7 +313,7 @@ pub fn dump(func: &Func, liveliness: &Liveliness, allocation: &Allocation) -> Stlet data = func.blocks[block as usize];for value in data.start..data.end {let node = func.node(value);- if liveliness.is_dead(value) || matches!(node.op, Op::Phi | Op::Forward) || node.op.is_entry_value() {+ if node.op.is_entry_value() {continue;}let record = allocation.node(value);diff --git a/Libraries/LibWasm/JIT/tests/harness/mod.rs b/Libraries/LibWasm/JIT/tests/harness/mod.rsindex 5009ad97dc9..3ab28ee0149 100644--- a/Libraries/LibWasm/JIT/tests/harness/mod.rs+++ b/Libraries/LibWasm/JIT/tests/harness/mod.rs@@ -513,7 +513,7 @@ static mut PREVIOUS: libc::sigaction = unsafe { std::mem::zeroed() };static mut PREVIOUS_SIGBUS: libc::sigaction = unsafe { std::mem::zeroed() };/// The program counter of a signal handler's context, and the register the trap exit takes the trap code in.-#[cfg(target_arch = "x86_64")]+#[cfg(all(target_arch = "x86_64", target_os = "linux"))]unsafe fn fault_registers(context: *mut libc::ucontext_t) -> (*mut u64, *mut u64) {unsafe {let registers = &raw mut (*context).uc_mcontext.gregs;@@ -524,6 +524,14 @@ unsafe fn fault_registers(context: *mut libc::ucontext_t) -> (*mut u64, *mut u64}}+#[cfg(all(target_arch = "x86_64", target_os = "macos"))]+unsafe fn fault_registers(context: *mut libc::ucontext_t) -> (*mut u64, *mut u64) {+ unsafe {+ let state = &raw mut (*(*context).uc_mcontext).__ss;+ ((&raw mut (*state).__rip), (&raw mut (*state).__rdi))+ }+}+#[cfg(all(target_arch = "aarch64", target_os = "linux"))]unsafe fn fault_registers(context: *mut libc::ucontext_t) -> (*mut u64, *mut u64) {unsafe {diff --git a/Libraries/LibWasm/JIT/tests/harness/script.rs b/Libraries/LibWasm/JIT/tests/harness/script.rsindex ad46318539e..0ccd2ce8ffc 100644--- a/Libraries/LibWasm/JIT/tests/harness/script.rs+++ b/Libraries/LibWasm/JIT/tests/harness/script.rs@@ -44,33 +44,10 @@ struct LoadedModule {diverged: bool,}-pub fn trap_code(trap: &Trap) -> u32 {- use libwasm_engine::abi::*;- match trap {- Trap::Unreachable => TRAP_UNREACHABLE,- Trap::StackExhausted => TRAP_STACK_EXHAUSTED,- Trap::MemoryOutOfBounds => TRAP_MEMORY_OUT_OF_BOUNDS,- Trap::IntegerDivideByZero => TRAP_INTEGER_DIVIDE_BY_ZERO,- Trap::IntegerOverflow => TRAP_INTEGER_OVERFLOW,- Trap::InvalidConversion => TRAP_INVALID_CONVERSION,- Trap::UndefinedElement => TRAP_UNDEFINED_ELEMENT,- Trap::UninitializedElement => TRAP_UNINITIALIZED_ELEMENT,- Trap::IndirectCallTypeMismatch => TRAP_INDIRECT_CALL_TYPE_MISMATCH,- Trap::TableOutOfBounds => TRAP_TABLE_OUT_OF_BOUNDS,- Trap::NullReference => TRAP_NULL_REFERENCE,- Trap::CastFailure => TRAP_CAST_FAILURE,- Trap::ArrayOutOfBounds => TRAP_ARRAY_OUT_OF_BOUNDS,- Trap::UnalignedAtomic => TRAP_UNALIGNED_ATOMIC,- Trap::ExpectedSharedMemory => TRAP_EXPECTED_SHARED_MEMORY,- Trap::Host(_) => TRAP_RUNTIME,- Trap::UncaughtException(_) => TRAP_UNCAUGHT_EXCEPTION,- }-}-pub fn outcome(result: Result<Vec<Value>, Trap>) -> Outcome {match result {Ok(values) => Outcome::Values(values),- Err(trap) => Outcome::Trap(trap_code(&trap)),+ Err(trap) => Outcome::Trap(trap.code()),}}diff --git a/Libraries/LibWasm/JIT/tests/shuffles.rs b/Libraries/LibWasm/JIT/tests/shuffles.rsindex 20575c46f5f..5fa38295d0d 100644--- a/Libraries/LibWasm/JIT/tests/shuffles.rs+++ b/Libraries/LibWasm/JIT/tests/shuffles.rs@@ -103,10 +103,9 @@ fn shuffles_run_the_same_compiled() {};let paths = [json.to_string_lossy().into_owned()];let expected_cases = 4 * patterns().len();- for (gvn, runtime) in [(false, false), (true, false), (false, true)] {+ for runtime in [false, true] {let options = libwasm_jit::Options {verify_ir: true,- gvn,..Default::default()};let totals = harness::script::run(&paths, false, options, runtime);@@ -114,7 +113,7 @@ fn shuffles_run_the_same_compiled() {totals.cases, expected_cases,"not every call ran compiled (runtime: {runtime})");- assert_eq!(totals.failures, 0, "gvn: {gvn}, runtime: {runtime}");+ assert_eq!(totals.failures, 0, "runtime: {runtime}");}let _ = std::fs::remove_dir_all(&directory);assert_eq!(diff --git a/Libraries/LibWasm/Engine/src/abi.rs b/Libraries/LibWasm/Module/src/abi.rssimilarity index 97%rename from Libraries/LibWasm/Engine/src/abi.rsrename to Libraries/LibWasm/Module/src/abi.rsindex a46dc590a94..f21083cd8fc 100644--- a/Libraries/LibWasm/Engine/src/abi.rs+++ b/Libraries/LibWasm/Module/src/abi.rs@@ -66,6 +66,13 @@ pub const FUNCTION_KIND_COMPILED: u32 = 3;/// What a call costs of the callee's tier-up budget.pub const TIER_UP_CALL_COST: u32 = 10;+/// The pseudo-instructions the runtime enters the interpreter at: Enter pushes the arguments, CallEntry calls the+/// function, and the function returns to Exit, which leaves the interpreter.+pub const OPCODE_ENTER: u8 = 0xf0;+pub const OPCODE_EXIT: u8 = 0xf1;+pub const OPCODE_CALL_ENTRY: u8 = 0xf3;+/// The pseudo-instruction a faulting memory access continues at.+pub const OPCODE_MEMORY_FAULT: u8 = 0xf2;/// The pseudo-instruction compiled code traps through, with the trap code in the context's first argument.pub const OPCODE_TRAP_FROM_NATIVE: u8 = 0xef;@@ -279,12 +286,6 @@ pub struct EntryRecord {pub saved_entry_record: *mut EntryRecord,}-/// The pseudo-instructions the interpreter starts and ends at, behind the 0xFF opcode no WebAssembly instruction uses.-pub const INTERNAL_OPCODE: u8 = 0xff;-pub const INTERNAL_ENTER: u8 = 0;-pub const INTERNAL_EXIT: u8 = 1;-pub const INTERNAL_MEMORY_FAULT: u8 = 2;-/// The layout constants of everything above, in the format flapc reads.pub fn layout_constants() -> String {let mut text = String::from("# Generated by the libwasm_engine build script -- DO NOT EDIT\n");diff --git a/Libraries/LibWasm/Engine/src/error.rs b/Libraries/LibWasm/Module/src/error.rssimilarity index 100%rename from Libraries/LibWasm/Engine/src/error.rsrename to Libraries/LibWasm/Module/src/error.rsdiff --git a/Libraries/LibWasm/Engine/src/instruction_tables.rs b/Libraries/LibWasm/Module/src/instruction_tables.rssimilarity index 100%rename from Libraries/LibWasm/Engine/src/instruction_tables.rsrename to Libraries/LibWasm/Module/src/instruction_tables.rsdiff --git a/Libraries/LibWasm/Module/src/lib.rs b/Libraries/LibWasm/Module/src/lib.rsindex 90023fd7914..853d4d6fb7b 100644--- a/Libraries/LibWasm/Module/src/lib.rs+++ b/Libraries/LibWasm/Module/src/lib.rs@@ -6,27 +6,17 @@//! The WebAssembly module format: the binary decoder, the validator and its side tables, quickening, and the layout//! the interpreter and compiled code share (`abi`). It is the part of the engine both the engine and the JIT depend-//! on. The sources stay with the engine's, which re-exports them.+//! on, and the engine re-exports it.-#[path = "../../Engine/src/abi.rs"]pub mod abi;-#[path = "../../Engine/src/error.rs"]pub mod error;-#[path = "../../Engine/src/instruction_tables.rs"]pub mod instruction_tables;-#[path = "../../Engine/src/module.rs"]pub mod module;-#[path = "../../Engine/src/opcode.rs"]pub mod opcode;-#[path = "../../Engine/src/parser.rs"]pub mod parser;-#[path = "../../Engine/src/quickening.rs"]pub mod quickening;-#[path = "../../Engine/src/reader.rs"]pub mod reader;-#[path = "../../Engine/src/types.rs"]pub mod types;-#[path = "../../Engine/src/validator.rs"]pub mod validator;pub use error::{Error, Result};diff --git a/Libraries/LibWasm/Engine/src/module.rs b/Libraries/LibWasm/Module/src/module.rssimilarity index 97%rename from Libraries/LibWasm/Engine/src/module.rsrename to Libraries/LibWasm/Module/src/module.rsindex 7207a73d2d6..eaa7848a0d7 100644--- a/Libraries/LibWasm/Engine/src/module.rs+++ b/Libraries/LibWasm/Module/src/module.rs@@ -155,10 +155,7 @@ pub struct Module {// Index spaces, imports first.pub imported_function_count: u32,- pub imported_table_count: u32,- pub imported_memory_count: u32,pub imported_global_count: u32,- pub imported_tag_count: u32,/// The type index of every function.pub function_space: Vec<u32>,pub table_space: Vec<TableType>,diff --git a/Libraries/LibWasm/Engine/src/opcode.rs b/Libraries/LibWasm/Module/src/opcode.rssimilarity index 100%rename from Libraries/LibWasm/Engine/src/opcode.rsrename to Libraries/LibWasm/Module/src/opcode.rsdiff --git a/Libraries/LibWasm/Engine/src/parser.rs b/Libraries/LibWasm/Module/src/parser.rssimilarity index 99%rename from Libraries/LibWasm/Engine/src/parser.rsrename to Libraries/LibWasm/Module/src/parser.rsindex 2eed6160533..65a03a97065 100644--- a/Libraries/LibWasm/Engine/src/parser.rs+++ b/Libraries/LibWasm/Module/src/parser.rs@@ -439,13 +439,11 @@ fn parse_import_section(section: &mut Reader<'_>, module: &mut Module) -> Result0x01 => {let table = parse_table_type(section)?;module.table_space.push(table);- module.imported_table_count += 1;ImportDescription::Table(table)}0x02 => {let memory = parse_memory_type(section)?;module.memory_space.push(memory);- module.imported_memory_count += 1;ImportDescription::Memory(memory)}0x03 => {@@ -457,7 +455,6 @@ fn parse_import_section(section: &mut Reader<'_>, module: &mut Module) -> Result0x04 => {let tag = parse_tag_type(section)?;module.tag_space.push(tag);- module.imported_tag_count += 1;ImportDescription::Tag(tag)}_ => return Err(Error::malformed("malformed import kind")),diff --git a/Libraries/LibWasm/Engine/src/quickening.rs b/Libraries/LibWasm/Module/src/quickening.rssimilarity index 100%rename from Libraries/LibWasm/Engine/src/quickening.rsrename to Libraries/LibWasm/Module/src/quickening.rsdiff --git a/Libraries/LibWasm/Engine/src/reader.rs b/Libraries/LibWasm/Module/src/reader.rssimilarity index 100%rename from Libraries/LibWasm/Engine/src/reader.rsrename to Libraries/LibWasm/Module/src/reader.rsdiff --git a/Libraries/LibWasm/Engine/src/types.rs b/Libraries/LibWasm/Module/src/types.rssimilarity index 95%rename from Libraries/LibWasm/Engine/src/types.rsrename to Libraries/LibWasm/Module/src/types.rsindex 2d8d8df2621..fdd9ccd213f 100644--- a/Libraries/LibWasm/Engine/src/types.rs+++ b/Libraries/LibWasm/Module/src/types.rs@@ -39,10 +39,6 @@ impl RefType {nullable: true,heap: HeapType::Func,};- pub const EXTERNREF: RefType = RefType {- nullable: true,- heap: HeapType::Extern,- };pub const EXNREF: RefType = RefType {nullable: true,heap: HeapType::Exn,@@ -72,7 +68,6 @@ pub enum ValType {impl ValType {pub const FUNCREF: ValType = ValType::Ref(RefType::FUNCREF);- pub const EXTERNREF: ValType = ValType::Ref(RefType::EXTERNREF);pub fn is_reference(self) -> bool {matches!(self, Self::Ref(_))@@ -138,16 +133,6 @@ impl StorageType {Self::I8 | Self::I16 => ValType::I32,}}-- pub fn byte_size(self) -> u32 {- match self {- Self::I8 => 1,- Self::I16 => 2,- Self::Val(ValType::I32 | ValType::F32) => 4,- Self::Val(ValType::V128) => 16,- Self::Val(_) => 8,- }- }}#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]diff --git a/Libraries/LibWasm/Engine/src/validator.rs b/Libraries/LibWasm/Module/src/validator.rssimilarity index 99%rename from Libraries/LibWasm/Engine/src/validator.rsrename to Libraries/LibWasm/Module/src/validator.rsindex 3ad7e232c95..635c289cb05 100644--- a/Libraries/LibWasm/Engine/src/validator.rs+++ b/Libraries/LibWasm/Module/src/validator.rs@@ -150,7 +150,8 @@ fn type_mismatch<T>() -> Result<T> {/// The type-level view of a module that validation checks against.pub struct TypeContext<'a> {pub types: &'a [SubType],- pub identities: &'a [u32],+ /// The identity of each type, or none where the types are identities themselves, as in a store.+ pub identities: Option<&'a [u32]>,}impl TypeContext<'_> {@@ -185,7 +186,10 @@ impl TypeContext<'_> {}match (sub, sup) {(Concrete(a), Concrete(b)) => {- if self.identities[a as usize] == self.identities[b as usize] {+ if self+ .identities+ .is_some_and(|identities| identities[a as usize] == identities[b as usize])+ {return true;}self.sub_type(a)@@ -2207,7 +2211,7 @@ fn validate_types(module: &Module, identities: &mut Vec<u32>) -> Result<()> {identities.extend(group_identities);let types = TypeContext {types: &module.types,- identities,+ identities: Some(identities),};for (offset, sub_type) in sub_types.iter().enumerate() {let index = group.start + offset as u32;@@ -2234,7 +2238,7 @@ pub fn validate(module: &mut Module) -> Result<()> {module.type_identities = identities;let types = TypeContext {types: &module.types,- identities: &module.type_identities,+ identities: Some(&module.type_identities),};for import in &module.imports {@@ -2389,7 +2393,7 @@ pub fn validate(module: &mut Module) -> Result<()> {module,types: TypeContext {types: &module.types,- identities: &module.type_identities,+ identities: Some(&module.type_identities),},declared_functions: &declared,locals,diff --git a/Libraries/LibWasm/Runtime.cpp b/Libraries/LibWasm/Runtime.cppindex c190173e4b1..170ec69e71a 100644--- a/Libraries/LibWasm/Runtime.cpp+++ b/Libraries/LibWasm/Runtime.cpp@@ -11,10 +11,52 @@namespace Wasm::Runtime {+// NB: The types of Runtime.h mirror those of the C ABI, which they are bit_cast to and from.+static_assert(to_underlying(ValueKind::I32) == to_underlying(FFI::WasmValueKind::I32));+static_assert(to_underlying(ValueKind::I64) == to_underlying(FFI::WasmValueKind::I64));+static_assert(to_underlying(ValueKind::F32) == to_underlying(FFI::WasmValueKind::F32));+static_assert(to_underlying(ValueKind::F64) == to_underlying(FFI::WasmValueKind::F64));+static_assert(to_underlying(ValueKind::V128) == to_underlying(FFI::WasmValueKind::V128));+static_assert(to_underlying(ValueKind::Reference) == to_underlying(FFI::WasmValueKind::Reference));+static_assert(to_underlying(HeapKind::Function) == to_underlying(FFI::WasmHeapKind::Function));+static_assert(to_underlying(HeapKind::NoFunction) == to_underlying(FFI::WasmHeapKind::NoFunction));+static_assert(to_underlying(HeapKind::Extern) == to_underlying(FFI::WasmHeapKind::Extern));+static_assert(to_underlying(HeapKind::NoExtern) == to_underlying(FFI::WasmHeapKind::NoExtern));+static_assert(to_underlying(HeapKind::Any) == to_underlying(FFI::WasmHeapKind::Any));+static_assert(to_underlying(HeapKind::Eq) == to_underlying(FFI::WasmHeapKind::Eq));+static_assert(to_underlying(HeapKind::I31) == to_underlying(FFI::WasmHeapKind::I31));+static_assert(to_underlying(HeapKind::Struct) == to_underlying(FFI::WasmHeapKind::Struct));+static_assert(to_underlying(HeapKind::Array) == to_underlying(FFI::WasmHeapKind::Array));+static_assert(to_underlying(HeapKind::None) == to_underlying(FFI::WasmHeapKind::None));+static_assert(to_underlying(HeapKind::Exception) == to_underlying(FFI::WasmHeapKind::Exception));+static_assert(to_underlying(HeapKind::NoException) == to_underlying(FFI::WasmHeapKind::NoException));+static_assert(to_underlying(HeapKind::Concrete) == to_underlying(FFI::WasmHeapKind::Concrete));+static_assert(to_underlying(ExternKind::Function) == to_underlying(FFI::WasmExternKind::Function));+static_assert(to_underlying(ExternKind::Table) == to_underlying(FFI::WasmExternKind::Table));+static_assert(to_underlying(ExternKind::Memory) == to_underlying(FFI::WasmExternKind::Memory));+static_assert(to_underlying(ExternKind::Global) == to_underlying(FFI::WasmExternKind::Global));+static_assert(to_underlying(ExternKind::Tag) == to_underlying(FFI::WasmExternKind::Tag));static_assert(sizeof(ValueType) == sizeof(FFI::WasmValueType));+static_assert(offsetof(ValueType, kind) == offsetof(FFI::WasmValueType, kind));+static_assert(offsetof(ValueType, heap) == offsetof(FFI::WasmValueType, heap));+static_assert(offsetof(ValueType, nullable) == offsetof(FFI::WasmValueType, nullable));+static_assert(offsetof(ValueType, type_index) == offsetof(FFI::WasmValueType, type_index));static_assert(sizeof(Value) == sizeof(FFI::WasmValue));+static_assert(offsetof(Value, kind) == offsetof(FFI::WasmValue, kind));+static_assert(offsetof(Value, low) == offsetof(FFI::WasmValue, low));+static_assert(offsetof(Value, high) == offsetof(FFI::WasmValue, high));static_assert(sizeof(Limits) == sizeof(FFI::WasmLimits));+static_assert(offsetof(Limits, minimum) == offsetof(FFI::WasmLimits, minimum));+static_assert(offsetof(Limits, maximum) == offsetof(FFI::WasmLimits, maximum));+static_assert(offsetof(Limits, has_maximum) == offsetof(FFI::WasmLimits, has_maximum));+static_assert(offsetof(Limits, address64) == offsetof(FFI::WasmLimits, address64));+static_assert(offsetof(Limits, shared) == offsetof(FFI::WasmLimits, shared));static_assert(sizeof(ExternType) == sizeof(FFI::WasmExternType));+static_assert(offsetof(ExternType, kind) == offsetof(FFI::WasmExternType, kind));+static_assert(offsetof(ExternType, type_index) == offsetof(FFI::WasmExternType, type_index));+static_assert(offsetof(ExternType, limits) == offsetof(FFI::WasmExternType, limits));+static_assert(offsetof(ExternType, value_type) == offsetof(FFI::WasmExternType, value_type));+static_assert(offsetof(ExternType, is_mutable) == offsetof(FFI::WasmExternType, mutable_));static FFI::WasmValueType to_ffi(ValueType type) { return bit_cast<FFI::WasmValueType>(type); }static FFI::WasmValue to_ffi(Value value) { return bit_cast<FFI::WasmValue>(value); }@@ -451,6 +493,11 @@ void Store::set_host_object(GC::ForeignCell* cell, GC::ForeignCell& object)FFI::wasm_set_host_object(cell, &object);}+void* Store::host_object(GC::ForeignCell* cell) const+{+ return FFI::wasm_host_object(cell);+}+u64 Store::table_size(Entity table){return FFI::wasm_store_table_size(m_store, to_ffi(table));diff --git a/Libraries/LibWasm/Runtime.h b/Libraries/LibWasm/Runtime.hindex 268c71e08c4..f95b537f252 100644--- a/Libraries/LibWasm/Runtime.h+++ b/Libraries/LibWasm/Runtime.h@@ -19,6 +19,7 @@#include <LibGC/ConservativeVector.h>#include <LibGC/Forward.h>#include <LibGC/PrimitiveStorage.h>+#include <LibGC/Ptr.h>#include <LibWasm/Export.h>namespace Wasm::FFI {@@ -68,8 +69,6 @@ struct ValueType {static constexpr ValueType scalar(ValueKind kind) { return { kind, HeapKind::Function, false, 0 }; }static constexpr ValueType reference(HeapKind heap, bool nullable = true) { return { ValueKind::Reference, heap, nullable, 0 }; }-- bool is_reference() const { return kind == ValueKind::Reference; }};// A value. i32 and f32 bits are zero-extended in `low`, a v128 is `low` and `high`, and a reference is its bits, which@@ -115,7 +114,7 @@ using Entity = GC::ForeignCell*;struct Extern {ExternKind kind { ExternKind::Function };- Entity entity { nullptr };+ GC::RawPtr<GC::ForeignCell> entity;};struct Limits {@@ -293,6 +292,8 @@ public:// An object that stands for the cell and refers to it then stays the same object while the cell lives.void set_host_object(GC::ForeignCell* cell, GC::Cell& object);void set_host_object(GC::ForeignCell* cell, GC::ForeignCell& object);+ // The object set_host_object() gave the cell, or null.+ void* host_object(GC::ForeignCell* cell) const;u64 table_size(Entity table);ValueType table_element_type(Entity table);diff --git a/Libraries/LibWeb/WebAssembly/Exception.cpp b/Libraries/LibWeb/WebAssembly/Exception.cppindex 35e82f2b109..0d28a387cb4 100644--- a/Libraries/LibWeb/WebAssembly/Exception.cpp+++ b/Libraries/LibWeb/WebAssembly/Exception.cpp@@ -74,7 +74,7 @@ bool Exception::is(Tag const& tag) const{// 1. If this.[[Type]] is not equal to exceptionTag.[[Address]], return false.// 2. Return true.- return m_tag == tag.address();+ return m_tag.ptr() == tag.address();}// https://webassembly.github.io/spec/js-api/#dom-exception-stackdiff --git a/Libraries/LibWeb/WebAssembly/Exception.h b/Libraries/LibWeb/WebAssembly/Exception.hindex 14199ed3880..2eee84bdafd 100644--- a/Libraries/LibWeb/WebAssembly/Exception.h+++ b/Libraries/LibWeb/WebAssembly/Exception.h@@ -27,7 +27,7 @@ public:static GC::Ref<Exception> from_address(u64 exception);u64 address() const { return m_exception; }- Wasm::Runtime::Entity tag_address() const { return m_tag; }+ Wasm::Runtime::Entity tag_address() const { return m_tag.ptr(); }bool is(Tag const&) const;Variant<Utf16String, Empty> stack() const;@@ -38,7 +38,7 @@ private:virtual void visit_edges(Visitor&) override;u64 m_exception { 0 };- Wasm::Runtime::Entity m_tag { nullptr };+ GC::Ptr<GC::ForeignCell> m_tag;Optional<Utf16String> m_stack;};diff --git a/Libraries/LibWeb/WebAssembly/Global.cpp b/Libraries/LibWeb/WebAssembly/Global.cppindex 452ee30bf68..8d77e79595b 100644--- a/Libraries/LibWeb/WebAssembly/Global.cpp+++ b/Libraries/LibWeb/WebAssembly/Global.cpp@@ -50,7 +50,7 @@ Global::Global(Wasm::Runtime::Entity global)void Global::visit_edges(Visitor& visitor){Base::visit_edges(visitor);- visitor.visit(m_global);+ visitor.visit(m_global.ptr());}GlobalType Global::type() const@@ -59,7 +59,7 @@ GlobalType Global::type() const// 2. Let globaladdr be global.[[Global]].// 3. Let globaltype be global_type(store, globaladdr).bool is_mutable = false;- auto value_type = Detail::WebAssemblyCache::the().store().global_type(m_global, is_mutable);+ auto value_type = Detail::WebAssemblyCache::the().store().global_type(m_global.ptr(), is_mutable);return GlobalType { value_type, is_mutable };}@@ -78,28 +78,18 @@ WebIDL::ExceptionOr<Wasm::Runtime::Value> Global::value() const// 5. Let value be global_read(store, globaladdr).// 6. Return value.- return Detail::WebAssemblyCache::the().store().global_get(m_global);+ return Detail::WebAssemblyCache::the().store().global_get(m_global.ptr());}// https://webassembly.github.io/spec/js-api/#dom-global-valueWebIDL::ExceptionOr<void> Global::set_value(Wasm::Runtime::Value value){- // 1. Let store be the current agent’s associated store.- // 2. Let globaladdr be this.[[Global]].- // 3. Let mut valuetype be global_type(store, globaladdr).- // 4. If valuetype is v128, throw a TypeError.- // 5. If mut is const, throw a TypeError.- auto global_type = type();- if (global_type.value.kind == Wasm::Runtime::ValueKind::V128)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot set the value of a V128 global"_utf16 };- if (!global_type.mutable_)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot set the value of a const global"_utf16 };-+ // NB: Steps 1 to 6 run in the bindings, which check the type before converting the value.// 7. Let store be global_write(store, globaladdr, value).// 8. If store is error, throw a RangeError exception.// 9. Set the current agent’s associated store to store.- // Note: The store cannot fail, because we checked for mut/val above.- Detail::WebAssemblyCache::the().store().global_set(m_global, value);+ // NB: The store cannot fail, because the bindings checked the type.+ Detail::WebAssemblyCache::the().store().global_set(m_global.ptr(), value);return {};}@@ -172,6 +162,11 @@ WebIDL::ExceptionOr<JS::Value> value(JS::Realm& realm, WebAssembly::Global& glob// https://webassembly.github.io/spec/js-api/#dom-global-valueWebIDL::ExceptionOr<void> set_value(JS::Realm& realm, WebAssembly::Global& global, JS::Value the_given_value){+ // 1. Let store be the current agent’s associated store.+ // 2. Let globaladdr be this.[[Global]].+ // 3. Let mut valuetype be global_type(store, globaladdr).+ // 4. If valuetype is v128, throw a TypeError.+ // 5. If mut is const, throw a TypeError.auto global_type = global.type();auto value_type = global_type.value;if (value_type.kind == Wasm::Runtime::ValueKind::V128)@@ -180,6 +175,7 @@ WebIDL::ExceptionOr<void> set_value(JS::Realm& realm, WebAssembly::Global& globaif (!global_type.mutable_)return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot set the value of a const global"_utf16 };+ // 6. Let value be ? ToWebAssemblyValue(the given value, valuetype).auto value = TRY(WebAssembly::Detail::to_webassembly_value(realm.vm(), the_given_value, value_type));return global.set_value(value);}diff --git a/Libraries/LibWeb/WebAssembly/Global.h b/Libraries/LibWeb/WebAssembly/Global.hindex 823fe3efe97..8da96e2ae0e 100644--- a/Libraries/LibWeb/WebAssembly/Global.h+++ b/Libraries/LibWeb/WebAssembly/Global.h@@ -45,14 +45,14 @@ public:WebIDL::ExceptionOr<Wasm::Runtime::ValueType> value_type() const;WebIDL::ExceptionOr<void> set_value(Wasm::Runtime::Value);- Wasm::Runtime::Entity address() const { return m_global; }+ Wasm::Runtime::Entity address() const { return m_global.ptr(); }private:explicit Global(Wasm::Runtime::Entity global);virtual void visit_edges(Visitor&) override;- Wasm::Runtime::Entity m_global { nullptr };+ GC::Ptr<GC::ForeignCell> m_global;};}diff --git a/Libraries/LibWeb/WebAssembly/Instance.cpp b/Libraries/LibWeb/WebAssembly/Instance.cppindex 185ad0d0364..17bd032d449 100644--- a/Libraries/LibWeb/WebAssembly/Instance.cpp+++ b/Libraries/LibWeb/WebAssembly/Instance.cpp@@ -125,7 +125,7 @@ static GC::Ref<JS::Object> create_exports_object(JS::Realm& realm, WebAssembly::// https://webassembly.github.io/spec/js-api/#create-an-exports-objectfor (auto& export_ : WebAssembly::Detail::WebAssemblyCache::the().store().instance_exports(instance.instance_address())) {auto name = Utf16FlyString::from_utf8(export_.name);- auto address = export_.value.entity;+ auto address = export_.value.entity.ptr();switch (export_.value.kind) {case Wasm::Runtime::ExternKind::Function: {diff --git a/Libraries/LibWeb/WebAssembly/Instance.h b/Libraries/LibWeb/WebAssembly/Instance.hindex 22e557b5342..8ef9f5e810e 100644--- a/Libraries/LibWeb/WebAssembly/Instance.h+++ b/Libraries/LibWeb/WebAssembly/Instance.h@@ -24,7 +24,7 @@ public:static WebIDL::ExceptionOr<GC::Ref<Instance>> create(JS::Realm&, Module& module, GC::Ptr<JS::Object> import_object);static GC::Ref<Instance> create(JS::Realm&, Wasm::Runtime::Entity instance);- Wasm::Runtime::Entity instance_address() const { return m_instance; }+ Wasm::Runtime::Entity instance_address() const { return m_instance.ptr(); }// The world of the realm the instance was created in, the only one whose realms may read its exports.Bindings::WrapperWorld const& wrapper_world() const { return *m_wrapper_world; }GC::Ref<Global> global_instance(Wasm::Runtime::Entity);@@ -36,7 +36,7 @@ private:virtual void visit_edges(Visitor&) override;- Wasm::Runtime::Entity m_instance { nullptr };+ GC::Ptr<GC::ForeignCell> m_instance;GC::Ref<Bindings::WrapperWorld> m_wrapper_world;};diff --git a/Libraries/LibWeb/WebAssembly/Memory.h b/Libraries/LibWeb/WebAssembly/Memory.hindex b3b32bb33da..ea410bb9781 100644--- a/Libraries/LibWeb/WebAssembly/Memory.h+++ b/Libraries/LibWeb/WebAssembly/Memory.h@@ -44,7 +44,7 @@ public:WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> to_resizable_buffer(JS::Realm&);WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> buffer(JS::Realm&);- Wasm::Runtime::Entity address() const { return m_memory; }+ Wasm::Runtime::Entity address() const { return m_memory.ptr(); }bool is_shared() const { return m_shared == Shared::Yes; }static Detail::WebAssemblyCache& cache() { return Detail::WebAssemblyCache::the(); }@@ -53,7 +53,7 @@ private:virtual void visit_edges(Visitor&) override;- Wasm::Runtime::Entity m_memory { nullptr };+ GC::Ptr<GC::ForeignCell> m_memory;Shared m_shared { Shared::No };};diff --git a/Libraries/LibWeb/WebAssembly/Table.h b/Libraries/LibWeb/WebAssembly/Table.hindex 398941ba333..e931558216a 100644--- a/Libraries/LibWeb/WebAssembly/Table.h+++ b/Libraries/LibWeb/WebAssembly/Table.h@@ -31,7 +31,7 @@ public:bool is_address64() const;Wasm::Runtime::ValueType element_type() const;- Wasm::Runtime::Entity address() const { return m_table; }+ Wasm::Runtime::Entity address() const { return m_table.ptr(); }static Detail::WebAssemblyCache& cache() { return Detail::WebAssemblyCache::the(); }private:@@ -39,7 +39,7 @@ private:virtual void visit_edges(Visitor&) override;- Wasm::Runtime::Entity m_table { nullptr };+ GC::Ptr<GC::ForeignCell> m_table;};}diff --git a/Libraries/LibWeb/WebAssembly/Tag.h b/Libraries/LibWeb/WebAssembly/Tag.hindex adb73476c68..e7486ec0333 100644--- a/Libraries/LibWeb/WebAssembly/Tag.h+++ b/Libraries/LibWeb/WebAssembly/Tag.h@@ -21,7 +21,7 @@ public:// The Tag object of a tag, which is the same object for as long as it lives.static GC::Ref<Tag> from_address(JS::Realm&, Wasm::Runtime::Entity tag);- Wasm::Runtime::Entity address() const { return m_tag; }+ Wasm::Runtime::Entity address() const { return m_tag.ptr(); }private:explicit Tag(Wasm::Runtime::Entity tag);@@ -31,7 +31,7 @@ private:virtual void visit_edges(Visitor&) override;- Wasm::Runtime::Entity m_tag { nullptr };+ GC::Ptr<GC::ForeignCell> m_tag;};}diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp b/Libraries/LibWeb/WebAssembly/WebAssembly.cppindex b9bf1f3d752..8c09176ab91 100644--- a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.cpp@@ -68,84 +68,55 @@ using WasmValueType = Wasm::Runtime::ValueType;using Wasm::Runtime::HeapKind;using Wasm::Runtime::ValueKind;-template<typename T, typename Key>-GC::Ptr<T> WebAssemblyCache::ObjectCache<T, Key>::get(Key key) const-{- auto entry = m_objects.get(key);- if (!entry.has_value())- return nullptr;- return entry->ptr();-}--template<typename T, typename Key>-void WebAssemblyCache::ObjectCache<T, Key>::set(Key key, T& object)-{- // NB: Stale entries go once there are as many of them as live ones.- if (m_objects.size() >= 2 * m_live_after_pruning + 16) {- m_objects.remove_all_matching([](auto&, auto& weak) { return !weak; });- m_live_after_pruning = m_objects.size();- }- m_objects.set(key, object);-}--template<typename T, typename Key>-void WebAssemblyCache::ObjectCache<T, Key>::for_each(Function<void(T&)> const& callback) const-{- for (auto& entry : m_objects) {- if (entry.value)- callback(*entry.value);- }-}-// Exceptions and GC objects are the cells their references are the addresses of.static GC::ForeignCell* cell_of_reference(u64 reference){return reinterpret_cast<GC::ForeignCell*>(static_cast<FlatPtr>(reference));}-GC::Ptr<JS::NativeFunction> WebAssemblyCache::function_object(Entity function) const { return m_function_objects.get(function); }-void WebAssemblyCache::set_function_object(Entity function, JS::NativeFunction& object)+// NB: The objects of the caches are the ones the runtime keeps alive with their cells (Store::set_host_object()). The+// platform objects among them are C++ cells, and the others foreign cells.+template<typename T>+static GC::Ptr<T> cell_object(void* object){- m_function_objects.set(function, object);- m_store->set_host_object(function, object);+ return static_cast<T*>(static_cast<GC::Cell*>(object));}-GC::Ptr<Global> WebAssemblyCache::global_object(Entity global) const { return m_global_objects.get(global); }-void WebAssemblyCache::set_global_object(Entity global, Global& object)++template<typename T>+static GC::Ptr<T> foreign_cell_object(void* object){- m_global_objects.set(global, object);- m_store->set_host_object(global, object);+ return static_cast<T*>(static_cast<GC::ForeignCell*>(object));}-GC::Ptr<Memory> WebAssemblyCache::memory_object(Entity memory) const { return m_memory_objects.get(memory); }++GC::Ptr<JS::NativeFunction> WebAssemblyCache::function_object(Entity function) const { return foreign_cell_object<JS::NativeFunction>(m_store->host_object(function)); }+void WebAssemblyCache::set_function_object(Entity function, JS::NativeFunction& object) { m_store->set_host_object(function, object); }+GC::Ptr<Global> WebAssemblyCache::global_object(Entity global) const { return cell_object<Global>(m_store->host_object(global)); }+void WebAssemblyCache::set_global_object(Entity global, Global& object) { m_store->set_host_object(global, object); }+GC::Ptr<Memory> WebAssemblyCache::memory_object(Entity memory) const { return cell_object<Memory>(m_store->host_object(memory)); }void WebAssemblyCache::set_memory_object(Entity memory, Memory& object){- m_memory_objects.set(memory, object);m_store->set_host_object(memory, object);+ if (m_memory_objects.size() >= 2 * m_live_memory_objects_after_pruning + 16) {+ m_memory_objects.remove_all_matching([](auto& weak) { return !weak; });+ m_live_memory_objects_after_pruning = m_memory_objects.size();+ }+ m_memory_objects.append(object);}-GC::Ptr<Table> WebAssemblyCache::table_object(Entity table) const { return m_table_objects.get(table); }-void WebAssemblyCache::set_table_object(Entity table, Table& object)-{- m_table_objects.set(table, object);- m_store->set_host_object(table, object);-}-void WebAssemblyCache::for_each_memory_object(Function<void(Memory&)> const& callback) const { m_memory_objects.for_each(callback); }-GC::Ptr<Tag> WebAssemblyCache::tag_object(Entity tag) const { return m_tag_objects.get(tag); }-void WebAssemblyCache::set_tag_object(Entity tag, Tag& object)-{- m_tag_objects.set(tag, object);- m_store->set_host_object(tag, object);-}-GC::Ptr<Exception> WebAssemblyCache::exception_object(u64 exception) const { return m_exception_objects.get(exception); }-void WebAssemblyCache::set_exception_object(u64 exception, Exception& object)-{- m_exception_objects.set(exception, object);- m_store->set_host_object(cell_of_reference(exception), object);-}-GC::Ptr<JS::Object> WebAssemblyCache::gc_object(u64 object) const { return m_gc_objects.get(object); }-void WebAssemblyCache::set_gc_object(u64 object, JS::Object& gc_object)+GC::Ptr<Table> WebAssemblyCache::table_object(Entity table) const { return cell_object<Table>(m_store->host_object(table)); }+void WebAssemblyCache::set_table_object(Entity table, Table& object) { m_store->set_host_object(table, object); }+void WebAssemblyCache::for_each_memory_object(Function<void(Memory&)> const& callback) const{- m_gc_objects.set(object, gc_object);- m_store->set_host_object(cell_of_reference(object), gc_object);+ for (auto& memory : m_memory_objects) {+ if (memory)+ callback(*memory);+ }}+GC::Ptr<Tag> WebAssemblyCache::tag_object(Entity tag) const { return cell_object<Tag>(m_store->host_object(tag)); }+void WebAssemblyCache::set_tag_object(Entity tag, Tag& object) { m_store->set_host_object(tag, object); }+GC::Ptr<Exception> WebAssemblyCache::exception_object(u64 exception) const { return cell_object<Exception>(m_store->host_object(cell_of_reference(exception))); }+void WebAssemblyCache::set_exception_object(u64 exception, Exception& object) { m_store->set_host_object(cell_of_reference(exception), object); }+GC::Ptr<JS::Object> WebAssemblyCache::gc_object(u64 object) const { return foreign_cell_object<JS::Object>(m_store->host_object(cell_of_reference(object))); }+void WebAssemblyCache::set_gc_object(u64 object, JS::Object& gc_object) { m_store->set_host_object(cell_of_reference(object), gc_object); }WebAssemblyCache::~WebAssemblyCache() = default;@@ -166,8 +137,7 @@ WebAssemblyCache::WebAssemblyCache(GC::Heap& heap)m_store->set_can_block(JS::agent_can_suspend(JS::VM::the()));Array<WasmValueType, 1> js_tag_parameters { WasmValueType::reference(HeapKind::Extern) };- m_js_tag = m_store->allocate_tag(js_tag_parameters);- m_js_tag_root = GC::Root<GC::ForeignCell> { m_js_tag };+ m_js_tag_root = GC::Root<GC::ForeignCell> { m_store->allocate_tag(js_tag_parameters) };// https://webassembly.github.io/spec/js-api/#memory-objects// Whenever memory.grow is executed, refresh the memory buffer of the memory's Memory object, if it has one.@@ -333,8 +303,20 @@ private:GC_DEFINE_ALLOCATOR(ExternValueBox);-GC::Ptr<ExternValueBox> WebAssemblyCache::extern_value_box(JS::Value value) const { return m_extern_value_boxes.get(value); }-void WebAssemblyCache::set_extern_value_box(JS::Value value, ExternValueBox& box) { m_extern_value_boxes.set(value, box); }+GC::Ptr<ExternValueBox> WebAssemblyCache::extern_value_box(JS::Value value) const+{+ auto box = m_extern_value_boxes.get(value);+ return box.has_value() ? box->ptr() : nullptr;+}++void WebAssemblyCache::set_extern_value_box(JS::Value value, ExternValueBox& box)+{+ if (m_extern_value_boxes.size() >= 2 * m_live_extern_value_boxes_after_pruning + 16) {+ m_extern_value_boxes.remove_all_matching([](auto&, auto& weak) { return !weak; });+ m_live_extern_value_boxes_after_pruning = m_extern_value_boxes.size();+ }+ m_extern_value_boxes.set(value, box);+}static u64 host_reference_of(JS::VM& vm, JS::Value value){@@ -584,7 +566,7 @@ Wasm::Runtime::Entity create_host_function(JS::VM& vm, JS::FunctionObject& funct// 3. Let (store, address) be exn_alloc(store, type, « payload »).// 3. Throw a WebAssembly exception with address, which WebAssembly code can catch, and which is v again once it// leaves WebAssembly.- Array<WasmValue, 1> payload { WasmValue::from_reference(value.is_null() ? 0 : host_reference_of(vm, value)) };+ Array<WasmValue, 1> payload { MUST(to_webassembly_value(vm, value, WasmValueType::reference(HeapKind::Extern))) };return Wasm::Runtime::HostError::exception(store.allocate_exception(WebAssemblyCache::the().js_tag(), payload));};return cache.store().allocate_host_function(type, move(host_function), static_cast<u32>(function_index));@@ -911,7 +893,7 @@ public:using Behavior = AK::Function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>;- Wasm::Runtime::Entity function_address() const { return m_function; }+ Wasm::Runtime::Entity function_address() const { return m_function.ptr(); }JS::ThrowCompletionOr<JS::Value> call(JS::VM& vm) const{@@ -935,7 +917,7 @@ private:Behavior m_behavior;// The function, which an Exported Function keeps alive.- Wasm::Runtime::Entity m_function { nullptr };+ GC::Ptr<GC::ForeignCell> m_function;};GC_DEFINE_ALLOCATOR(ExportedFunctionHostData);diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.h b/Libraries/LibWeb/WebAssembly/WebAssembly.hindex f1acf53a5ba..96b19aa67f7 100644--- a/Libraries/LibWeb/WebAssembly/WebAssembly.h+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.h@@ -56,12 +56,13 @@ struct CompiledWebAssemblyModule : public RefCounted<CompiledWebAssemblyModule>// The surrounding agent's associated store, and the agent's Exported Function, Global, Memory, Table, Tag, Exception, and// Exported GC Object caches.-// The store holds no wasm entity: each lives while the objects that stand for it, or other entities, refer to it. An-// entity, exception, or GC object keeps the object of the caches that stands for it alive in turn, so that the object-// stays the same one for as long as both live, and both go away together.+// The store holds no wasm entity: each lives while the objects that stand for it, or other entities, refer to it. The+// caches are the runtime's link from a cell to the object that stands for it (Store::set_host_object()), which keeps+// the object alive in turn, so that the object stays the same one for as long as both live, and both go away together.class WebAssemblyCache {AK_MAKE_NONCOPYABLE(WebAssemblyCache);AK_MAKE_NONMOVABLE(WebAssemblyCache);+ AK_ALLOC_WITH_KMALLOC;public:using Entity = Wasm::Runtime::Entity;@@ -73,7 +74,7 @@ public:// The tag of the exceptions that carry JavaScript values through WebAssembly code, as their only (externref)// value.- Entity js_tag() const { return m_js_tag; }+ Entity js_tag() const { return m_js_tag_root.ptr(); }GC::Ptr<JS::NativeFunction> function_object(Entity function) const;void set_function_object(Entity function, JS::NativeFunction&);@@ -100,31 +101,13 @@ private:explicit WebAssemblyCache(GC::Heap&);~WebAssemblyCache();- // Objects by entity, or by reference for exceptions and GC objects. An entry whose object is gone is stale: its- // entity is gone too, and its address may be reused.- template<typename T, typename Key = Entity>- class ObjectCache {- public:- GC::Ptr<T> get(Key) const;- void set(Key, T&);- void for_each(Function<void(T&)> const&) const;-- private:- HashMap<Key, GC::Weak<T>> m_objects;- size_t m_live_after_pruning { 0 };- };-NonnullOwnPtr<Wasm::Runtime::Store> m_store;- Entity m_js_tag { nullptr };GC::Root<GC::ForeignCell> m_js_tag_root;- ObjectCache<JS::NativeFunction> m_function_objects;- ObjectCache<WebAssembly::Global> m_global_objects;- ObjectCache<WebAssembly::Memory> m_memory_objects;- ObjectCache<WebAssembly::Table> m_table_objects;- ObjectCache<WebAssembly::Tag> m_tag_objects;- ObjectCache<WebAssembly::Exception, u64> m_exception_objects;- ObjectCache<JS::Object, u64> m_gc_objects;- ObjectCache<ExternValueBox, JS::Value> m_extern_value_boxes;+ // NB: An entry whose object is gone is stale. Stale entries go once there are as many of them as live ones.+ Vector<GC::Weak<WebAssembly::Memory>> m_memory_objects;+ size_t m_live_memory_objects_after_pruning { 0 };+ HashMap<JS::Value, GC::Weak<ExternValueBox>> m_extern_value_boxes;+ size_t m_live_extern_value_boxes_after_pruning { 0 };};// https://webassembly.github.io/spec/js-api/#exported-functiondiff --git a/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp b/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cppindex fe2c45542f6..90599ce4832 100644--- a/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp+++ b/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp@@ -466,7 +466,7 @@ JS::ThrowCompletionOr<void> WebAssemblyModuleTraits::execute_module(JS::HostModu// 1. Assert: externval is of the form global globaladdr.// 2. Let global globaladdr be externval.// 3. Let global_value be global_read(store, globaladdr).- auto globaladdr = entry.value.entity;+ auto globaladdr = entry.value.entity.ptr();bool is_mutable = false;auto type = store.global_type(globaladdr, is_mutable);diff --git a/Tests/LibWasm/test-wasm.cpp b/Tests/LibWasm/test-wasm.cppindex 5068aba50ad..c88e4ba5028 100644--- a/Tests/LibWasm/test-wasm.cpp+++ b/Tests/LibWasm/test-wasm.cpp@@ -25,7 +25,13 @@#include <LibTest/JavaScriptTestHost.h>#include <LibWasm/Runtime.h>#include <string.h>-#include <sys/resource.h>++#if defined(AK_OS_WINDOWS)+# include <AK/Windows.h>+# include <psapi.h>+#else+# include <sys/resource.h>+#endifTEST_ROOT("Libraries/LibWasm/Tests");@@ -121,7 +127,7 @@ public:s_store = nullptr;}- Wasm::Runtime::Entity instance() const { return m_instance; }+ Wasm::Runtime::Entity instance() const { return m_instance.ptr(); }// Keep an entity of the current file alive, since the tests refer to entities by number.static Wasm::Runtime::Entity keep(Wasm::Runtime::Entity entity)@@ -226,7 +232,7 @@ private:// NB: The last store is left for the process to reclaim, since the heap it roots its cells in is gone at exit.static Wasm::Runtime::Store* s_store;RefPtr<Wasm::Runtime::Module> m_module;- Wasm::Runtime::Entity m_instance { nullptr };+ GC::Ptr<GC::ForeignCell> m_instance;};GC_DEFINE_ALLOCATOR(WebAssemblyModule);@@ -292,13 +298,20 @@ TESTJS_GLOBAL_FUNCTION(validate_webassembly_module, validateWebAssemblyModule)// The most memory the process has had resident, in bytes.TESTJS_GLOBAL_FUNCTION(peak_resident_memory_size, peakResidentMemorySize){+#if defined(AK_OS_WINDOWS)+ PROCESS_MEMORY_COUNTERS counters {};+ if (!GetProcessMemoryInfo(GetCurrentProcess(), &counters, sizeof(counters)))+ return vm.throw_completion<JS::TypeError>("GetProcessMemoryInfo failed"_utf16);+ return JS::Value(static_cast<double>(counters.PeakWorkingSetSize));+#elsestruct rusage usage {};if (getrusage(RUSAGE_SELF, &usage) != 0)return vm.throw_completion<JS::TypeError>("getrusage failed"_utf16);-#if defined(AK_OS_MACOS)+# if defined(AK_OS_MACOS)return JS::Value(static_cast<double>(usage.ru_maxrss));-#else+# elsereturn JS::Value(static_cast<double>(usage.ru_maxrss) * 1024);+# endif#endif}@@ -470,11 +483,11 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::get_export)return vm.throw_completion<JS::TypeError>(Utf16String::formatted("'{}' could not be found", name));// NB: A function is its entity's address, which a double holds exactly.if (value->kind == ExternKind::Function)- return JS::Value(static_cast<double>(bit_cast<FlatPtr>(value->entity)));+ return JS::Value(static_cast<double>(bit_cast<FlatPtr>(value->entity.ptr())));if (value->kind == ExternKind::Global) {bool is_mutable = false;- auto type = store().global_type(value->entity, is_mutable);- auto global = store().global_get(value->entity);+ auto type = store().global_type(value->entity.ptr(), is_mutable);+ auto global = store().global_get(value->entity.ptr());switch (type.kind) {case ValueKind::I32:return JS::Value(static_cast<double>(global.to_i32()));diff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-JSTag.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-JSTag.txtindex c7195369247..3bf9ca4d483 100644--- a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-JSTag.txt+++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-JSTag.txt@@ -2,3 +2,4 @@ accessor: function, setter: undefined, enumerable: true, configurable: truea Tag: true, the same object: trueconstructing an Exception with it: TypeErrorWebAssembly catches JavaScript exceptions by it: true+a thrown small integer is an i31 in WebAssembly: truediff --git a/Tests/LibWeb/Text/input/Wasm/WebAssembly-JSTag.html b/Tests/LibWeb/Text/input/Wasm/WebAssembly-JSTag.htmlindex 106b7ecbe64..83c55eb6c9c 100644--- a/Tests/LibWeb/Text/input/Wasm/WebAssembly-JSTag.html+++ b/Tests/LibWeb/Text/input/Wasm/WebAssembly-JSTag.html@@ -19,6 +19,24 @@0x72, 0x0b, 0x05, 0x01, 0x00, 0x02, 0x6a, 0x73,]);+ // (module+ // (import "m" "js" (tag $js (param externref)))+ // (import "m" "throws" (func $throws))+ // (func (export "caughtI31") (result i32)+ // (block $handler (result externref)+ // (try_table (catch $js $handler) (call $throws))+ // (return (i32.const -1)))+ // (any.convert_extern)+ // (ref.test (ref i31))))+ const i31Bytes = new Uint8Array([+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x0c, 0x03, 0x60, 0x01, 0x6f, 0x00, 0x60,+ 0x00, 0x00, 0x60, 0x00, 0x01, 0x7f, 0x02, 0x14, 0x02, 0x01, 0x6d, 0x02, 0x6a, 0x73, 0x04, 0x00,+ 0x00, 0x01, 0x6d, 0x06, 0x74, 0x68, 0x72, 0x6f, 0x77, 0x73, 0x00, 0x01, 0x03, 0x02, 0x01, 0x02,+ 0x07, 0x0d, 0x01, 0x09, 0x63, 0x61, 0x75, 0x67, 0x68, 0x74, 0x49, 0x33, 0x31, 0x00, 0x01, 0x0a,+ 0x18, 0x01, 0x16, 0x00, 0x02, 0x6f, 0x1f, 0x40, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x0b, 0x41,+ 0x7f, 0x0f, 0x0b, 0xfb, 0x1a, 0xfb, 0x14, 0x6c, 0x0b,+ ]);+test(() => {const descriptor = Object.getOwnPropertyDescriptor(WebAssembly, "JSTag");println(`accessor: ${typeof descriptor.get}, setter: ${descriptor.set}, enumerable: ${descriptor.enumerable}, configurable: ${descriptor.configurable}`);@@ -35,5 +53,10 @@m: { js: WebAssembly.JSTag, throws: () => { throw thrown; } },}).exports;println(`WebAssembly catches JavaScript exceptions by it: ${exports.catchJS() === thrown}`);++ const i31Exports = new WebAssembly.Instance(new WebAssembly.Module(i31Bytes), {+ m: { js: WebAssembly.JSTag, throws: () => { throw 5; } },+ }).exports;+ println(`a thrown small integer is an i31 in WebAssembly: ${i31Exports.caughtI31() === 1}`);});</script>diff --git a/Utilities/wasm.cpp b/Utilities/wasm.cppindex 73fa43ba4bb..dab40b786f0 100644--- a/Utilities/wasm.cpp+++ b/Utilities/wasm.cpp@@ -286,7 +286,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)auto vm = JS::VM::create();auto root_execution_context = JS::create_simple_execution_context<JS::GlobalObject>(*vm);auto& realm = *root_execution_context->realm;- Wasm::Runtime::Store store { vm->heap() };+ IGNORE_USE_IN_ESCAPING_LAMBDA Wasm::Runtime::Store store { vm->heap() };// NB: The entities the utility allocates live until it exits.Vector<GC::Root<GC::ForeignCell>> roots;auto keep = [&](Entity entity) {@@ -423,7 +423,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)auto callee = store.find_export(main_instance, export_name);if (!callee.has_value() || callee->kind != ExternKind::Function)return vm.throw_completion<JS::TypeError>(Utf16String::formatted("wasm reentry: no exported function '{}'", export_name));- auto type = store.function_type(callee->entity);+ auto type = store.function_type(callee->entity.ptr());Wasm::Runtime::Values wasm_arguments;for (size_t index = 0; index < type.parameters.size(); ++index) {auto value = vm.argument(index + 1);@@ -444,7 +444,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)return vm.throw_completion<JS::TypeError>("wasm reentry: unsupported parameter type"_utf16);}}- auto result = store.invoke(callee->entity, wasm_arguments);+ auto result = store.invoke(callee->entity.ptr(), wasm_arguments);if (result.is_error())return vm.throw_completion<JS::TypeError>(Utf16String::formatted("wasm reentry trapped: {}", result.error().message));if (result.value().is_empty())@@ -697,7 +697,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)main_instance = *instance;if (wasi_implementation) {if (auto memory = store.find_export(main_instance, "memory"sv); memory.has_value() && memory->kind == ExternKind::Memory)- wasi_implementation->set_memory(memory->entity);+ wasi_implementation->set_memory(memory->entity.ptr());}if (exported_function_to_execute.is_empty())@@ -709,7 +709,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)return 1;}- auto type = store.function_type(function->entity);+ auto type = store.function_type(function->entity.ptr());Wasm::Runtime::Values values;for (auto& parameter : type.parameters) {if (values_to_push.is_empty()) {@@ -722,7 +722,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)}}- auto result = timed(timings.execution, [&] { return store.invoke(function->entity, values); });+ auto result = timed(timings.execution, [&] { return store.invoke(function->entity.ptr(), values); });if (result.is_error()) {if (wasi_implementation) {if (auto exit_code = wasi_implementation->exit_code(); exit_code.has_value())