Truly independent web browser
LibWasm: Make tail calls across the tiers in the interpreter
Andreas Kling46d97ba66788
diff --git a/Libraries/LibWasm/Engine/src/runtime/interpreter.rs b/Libraries/LibWasm/Engine/src/runtime/interpreter.rsindex 09935af4212..f8b53d4533d 100644--- a/Libraries/LibWasm/Engine/src/runtime/interpreter.rs+++ b/Libraries/LibWasm/Engine/src/runtime/interpreter.rs@@ -6,11 +6,18 @@//! Entering the interpreter, and turning faulting memory accesses inside it into traps.-use crate::abi::{EntryRecord, OPCODE_CALL_ENTRY, OPCODE_ENTER, OPCODE_EXIT};+use crate::abi::{EntryRecord, OPCODE_CALL_ENTRY, OPCODE_CALL_PENDING, OPCODE_ENTER, OPCODE_EXIT};/// The code the runtime enters the interpreter at (see `OPCODE_ENTER`).static ENTRY_CODE: [u8; 3] = [OPCODE_ENTER, OPCODE_CALL_ENTRY, OPCODE_EXIT];+/// The code the interpreter continues at to call a pending tail call (see `OPCODE_CALL_PENDING`).+static CALL_PENDING_CODE: [u8; 1] = [OPCODE_CALL_PENDING];++pub fn call_pending_code() -> u64 {+ CALL_PENDING_CODE.as_ptr() as u64+}+// 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))))]unsafe extern "C" {diff --git a/Libraries/LibWasm/Engine/src/runtime/jit.rs b/Libraries/LibWasm/Engine/src/runtime/jit.rsindex bd1fe3a088c..83864fe98c5 100644--- a/Libraries/LibWasm/Engine/src/runtime/jit.rs+++ b/Libraries/LibWasm/Engine/src/runtime/jit.rs@@ -139,7 +139,9 @@ export_runtime_functions! {/// and 1 for a loop, whose instruction `arguments[1]` points at, in the frame at `arguments[3]`. Compiles the function/// if the JIT is on, or has it compiled in the background. At a loop, continues the frame in compiled code if it can/// (OSR) and returns the top of the frame's operand stack with the results on it, or if the frame threw an exception,-/// 1 if a handler of the interpreter caught it and 2 if it left the interpreter; returns 0 otherwise.+/// 1 if a handler of the interpreter caught it and 2 if it left the interpreter, or 3 if the frame tail called a+/// function that does not run compiled, which the interpreter calls in its place at the CallPending pseudo-instruction+/// `arguments[4]` points at (see `call_compiled()`); returns 0 otherwise.unsafe fn tier_up(context: *mut ExecutionContext) -> u64 {unsafe {let [header, pc, reason, frame, ..] = (*context).arguments;@@ -181,6 +183,15 @@ unsafe fn tier_up(context: *mut ExecutionContext) -> u64 {resumed => resumed,}}+ native::LoopEntry::TailCalled => {+ let read = |offset: isize| *((frame as *const u8).offset(offset) as *const u64);+ native::pass_tail_call(store, context);+ let arguments = &mut (*context).arguments;+ arguments[2] = read(crate::abi::FRAME_RETURN_VSP);+ arguments[3] = read(crate::abi::FRAME_RETURN_IP);+ arguments[4] = super::interpreter::call_pending_code();+ 3+ }native::LoopEntry::Pending => {address.get_mut().header.tier_up_budget = POLL_BUDGET + crate::abi::TIER_UP_CALL_COST;0@@ -229,10 +240,6 @@ 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;@@ -511,14 +518,28 @@ pub fn release_large_images(in_use: usize) {/// Calls a compiled function from the interpreter: `arguments[0]` is its header and `arguments[1]` the top of the/// operand stack, where its arguments are, `arguments[2]` where the call returns to and `arguments[3]` the caller's/// frame. Replaces the arguments with its results and returns the new top, or if it threw an exception, 1 if a-/// handler of the interpreter caught it, or 0 if it left the interpreter (see `rethrow_in_interpreter`).+/// handler of the interpreter caught it, or 0 if it left the interpreter (see `rethrow_in_interpreter`). Returns 2 if+/// it tail called a function that does not run compiled, which the interpreter calls in its place at the CallPending+/// pseudo-instruction `arguments[4]` points at, with where the results go in `arguments[2]` and where the call returns+/// to in `arguments[3]`.unsafe fn call_compiled(context: *mut ExecutionContext) -> u64 {unsafe {// NB: The compiled code's calls into the runtime and the helpers it calls reuse the context's arguments.- let [_, _, return_ip, frame, ..] = (*context).arguments;+ let [header, top, return_ip, frame, ..] = (*context).arguments;match native::call_compiled(context) {- Ok(top) => top,- Err(exception) => rethrow_in_interpreter(context, store_of(context), exception, frame, return_ip - 1),+ native::Ran::Returned(top) => top,+ native::Ran::Threw(exception) => {+ rethrow_in_interpreter(context, store_of(context), exception, frame, return_ip - 1)+ }+ native::Ran::TailCalled => {+ let parameter_slots = (*(header as *const FunctionInstance)).header.param_slots;+ native::pass_tail_call(store_of(context), context);+ let arguments = &mut (*context).arguments;+ arguments[2] = top + 8 * u64::from(parameter_slots);+ arguments[3] = return_ip;+ arguments[4] = super::interpreter::call_pending_code();+ 2+ }}}}@@ -573,17 +594,13 @@ unsafe fn call_from_native(context: *mut ExecutionContext) -> u64 {let outcome = if let FunctionKind::Host(_) = function.kind {store.call_host_slots(address, arguments.as_ptr(), results.as_mut_ptr())} else {- // 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);+ // NB: A tail call from compiled code that the interpreter called returns to the interpreter, which makes+ // it in that code's place, so that functions that tail call each other across the tiers do not keep+ // a native frame per call.+ if native::defer_tail_call(store, address, frame as u64, arguments) {+ return 0;}- store.interpreter_calls_from_native += 1;- let outcome = store.invoke_slots(address, arguments, results);- store.interpreter_calls_from_native -= 1;- outcome+ store.invoke_slots(address, arguments, results)};match outcome {Ok(()) => {}@@ -884,13 +901,65 @@ mod native {};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.+ // its compile thread never finished it, or its compile failed.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)]));+ assert_ne!(unsafe { odd.get() }.header.kind, crate::abi::FUNCTION_KIND_COMPILED);+ }++ #[test]+ fn tail_calls_from_compiled_code_pass_more_arguments_to_the_interpreter() {+ 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 (few, many) = (export("few"), export("many"));+ assert_eq!(+ super::compile_function(&mut store, few, true),+ super::CompileState::Compiled+ );+ unsafe { many.get_mut() }.header.tier_up_budget = u32::MAX;+ assert_eq!(store.invoke(few, &[Value::I64(5)]), Ok(vec![Value::I64(5039)]));+ }++ #[test]+ fn frames_continued_compiled_at_a_loop_tail_call_the_interpreter() {+ use crate::runtime::{ExternValue, FunctionKind, 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 (loops, many) = (export("loops"), export("many"));+ unsafe { many.get_mut() }.header.tier_up_budget = u32::MAX;+ // NB: The loop is the function's first instruction, and its frame continues compiled there at once.+ let FunctionKind::Wasm { module, index, .. } = &unsafe { loops.get() }.kind else {+ unreachable!("the function is a WebAssembly function");+ };+ let body = &module.code[(*index - module.imported_function_count) as usize];+ let jit = store.jit.get_or_insert_with(Default::default);+ let key = jit.key(module, *index, Some(body.code.start));+ assert_eq!(jit.compile(key, true), super::CompileState::Compiled);+ unsafe { loops.get_mut() }.header.tier_up_budget = crate::abi::TIER_UP_CALL_COST;+ assert_eq!(store.invoke(loops, &[Value::I64(3)]), Ok(vec![Value::I64(6039)]));}#[test]@@ -1051,6 +1120,8 @@ mod native {Ran(u64),/// The frame threw this exception, which its own handlers did not catch.Threw(u64),+ /// The frame tail called a function that does not run compiled (see `defer_tail_call()`).+ TailCalled,/// The code for the loop is still compiling.Pending,/// The frame cannot continue compiled at this loop.@@ -1071,6 +1142,11 @@ mod native {finished: Option<(Sender<Finished>, Receiver<Finished>)>,/// How many modules gained code since the store last looked for modules that died.new_code: usize,+ /// A tail call that compiled code the entry trampoline called made of a function that does not run compiled,+ /// with its argument slots in operand stack order, which the interpreter makes once the trampoline returns+ /// (see `defer_tail_call()`).+ tail_call: Option<FunctionAddress>,+ tail_call_arguments: Vec<u64>,pub disabled: bool,}@@ -1342,7 +1418,7 @@ mod native {state}- pub unsafe fn call_compiled(context: *mut ExecutionContext) -> Result<u64, u64> {+ pub unsafe fn call_compiled(context: *mut ExecutionContext) -> Ran {unsafe {let [header, top, ..] = (*context).arguments;let function = &*(header as *const FunctionInstance);@@ -1391,9 +1467,19 @@ mod native {LARGE_IMAGES.with(|images| images.borrow().buffers.len())}+ /// How a call of compiled code through the entry trampoline ended.+ pub enum Ran {+ /// It returned, with its results on the operand stack, whose new top this is.+ Returned(u64),+ /// It threw this exception, which its own handlers did not catch.+ Threw(u64),+ /// It tail called a function that does not run compiled, which the interpreter calls in its place (see+ /// `defer_tail_call()`).+ TailCalled,+ }+/// Calls `entry`, compiled code of `function` whose values `shape` describes, with the `index`th argument at- /// `argument(index, param)`. Stores the function's results on an operand stack ending at `end`, and returns its- /// new top, or the exception it threw.+ /// `argument(index, param)`. Stores the function's results on an operand stack ending at `end`.////// NB: A trap leaves through the compiled code and does not return, skipping this frame and its callers' up to/// the interpreter, so none of them may own anything that needs dropping.@@ -1403,7 +1489,7 @@ mod native {shape: &CallShape,argument: impl Fn(usize, &super::ValueShape) -> *const u64,end: *mut u64,- ) -> Result<u64, u64> {+ ) -> Ran {unsafe {let header_data: &FunctionHeader = &function.header;let result_slots = header_data.result_slots as usize;@@ -1458,7 +1544,11 @@ mod native {}let context = (*header_data.instance).context;if (*context).exception != 0 {- return Err(std::mem::take(&mut (*context).exception));+ return Ran::Threw(std::mem::take(&mut (*context).exception));+ }+ let jit = super::store_of(context).jit.as_ref().expect("compiled code ran");+ if jit.tail_call.is_some() {+ return Ran::TailCalled;}let return_top = end.sub(result_slots);for result in &shape.results {@@ -1477,7 +1567,35 @@ mod native {*destination.add(slot) = slot_bits(result.ty, *word);}}- Ok(return_top as u64)+ Ran::Returned(return_top as u64)+ }+ }++ /// Whether the call of `address` with `arguments`, through the runtime adapter whose frame is `frame`, is a tail+ /// call of compiled code that the entry trampoline called. If so, keeps the call for the interpreter to make in+ /// place of that code once the trampoline returns, which it does when the adapter returns. The interpreter's+ /// tail calls of compiled code make their calls through the trampoline too, so functions that tail call each+ /// other across the tiers then run in constant stack space.+ pub unsafe fn defer_tail_call(store: &mut Store, address: FunctionAddress, frame: u64, arguments: &[u64]) -> bool {+ let return_address = unsafe { *(frame.wrapping_add_signed(crate::abi::FRAME_RETURN_IP as i64) as *const u64) };+ if return_address != stubs().entry_return {+ return false;+ }+ let jit = store.jit.as_mut().expect("compiled code ran");+ jit.tail_call = Some(address);+ jit.tail_call_arguments.clear();+ jit.tail_call_arguments.extend_from_slice(arguments);+ true+ }++ /// Passes the tail call `defer_tail_call()` kept to the interpreter: the callee's header in the context's first+ /// argument, and the address of its argument slots in the second.+ pub unsafe fn pass_tail_call(store: &mut Store, context: *mut ExecutionContext) {+ let jit = store.jit.as_mut().expect("compiled code ran");+ let function = jit.tail_call.take().expect("compiled code tail called");+ unsafe {+ (*context).arguments[0] = function.as_ptr() as u64;+ (*context).arguments[1] = jit.tail_call_arguments.as_ptr() as u64;}}@@ -1503,8 +1621,9 @@ mod native {let entry = jit.entry(key).expect("the loop is compiled");let base = (frame as *mut u8).sub(crate::abi::FRAME_HEADER_SIZE).cast::<u64>();match run(function, entry, &shapes(function).osr, |_, _| &raw const frame, base) {- Ok(top) => LoopEntry::Ran(top),- Err(exception) => LoopEntry::Threw(exception),+ Ran::Returned(top) => LoopEntry::Ran(top),+ Ran::Threw(exception) => LoopEntry::Threw(exception),+ Ran::TailCalled => LoopEntry::TailCalled,}}}@@ -1550,10 +1669,30 @@ mod native {pub enum LoopEntry {Ran(u64),Threw(u64),+ TailCalled,Pending,Never,}+ pub enum Ran {+ Returned(u64),+ Threw(u64),+ TailCalled,+ }++ pub unsafe fn defer_tail_call(+ _store: &mut Store,+ _address: crate::runtime::FunctionAddress,+ _frame: u64,+ _arguments: &[u64],+ ) -> bool {+ unreachable!("the JIT is off where it has no code generator")+ }++ pub unsafe fn pass_tail_call(_store: &mut Store, _context: *mut ExecutionContext) {+ unreachable!("the JIT is off where it has no code generator")+ }+pub unsafe fn unwind(_store: &mut Store, _exception: u64, _frame: u64) {unreachable!("the JIT is off where it has no code generator")}@@ -1573,7 +1712,7 @@ mod native {LoopEntry::Never}- pub unsafe fn call_compiled(_context: *mut ExecutionContext) -> Result<u64, u64> {+ pub unsafe fn call_compiled(_context: *mut ExecutionContext) -> Ran {unreachable!("the JIT is off where it has no code generator")}diff --git a/Libraries/LibWasm/Engine/src/runtime/mod.rs b/Libraries/LibWasm/Engine/src/runtime/mod.rsindex b22ee3cd69b..967d7f272a6 100644--- a/Libraries/LibWasm/Engine/src/runtime/mod.rs+++ b/Libraries/LibWasm/Engine/src/runtime/mod.rs@@ -388,8 +388,6 @@ 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 {@@ -443,7 +441,6 @@ impl Store {memory_grow_callback: None,can_block: true,jit: None,- interpreter_calls_from_native: 0,}}diff --git a/Libraries/LibWasm/Engine/tests/fixtures/tail_calls_across_tiers.wasm b/Libraries/LibWasm/Engine/tests/fixtures/tail_calls_across_tiers.wasmindex 8321bd71189..7138ced12cf 100644Binary files a/Libraries/LibWasm/Engine/tests/fixtures/tail_calls_across_tiers.wasm 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.watindex b2612026bea..5d8a52f96d8 100644--- a/Libraries/LibWasm/Engine/tests/fixtures/tail_calls_across_tiers.wat+++ b/Libraries/LibWasm/Engine/tests/fixtures/tail_calls_across_tiers.wat@@ -1,4 +1,5 @@-;; Two functions that tail call each other through references, once for each step down to 0.+;; Two functions that tail call each other through references, once for each step down to 0, and functions that tail+;; call one with many more parameters than they have, one of them after a loop.(module(type $step (func (param i64) (result i64)))(global $even (ref $step) (ref.func $even))@@ -11,4 +12,15 @@(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))))))+ (else (return_call_ref $step (i64.sub (local.get 0) (i64.const 1)) (global.get $even)))))+ (func $many (export "many") (param i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64) (result i64)+ (i64.add (i64.mul (local.get 0) (i64.const 1000)) (local.get 39)))+ (func (export "few") (param i64) (result i64)+ (return_call $many (local.get 0) (i64.const 1) (i64.const 2) (i64.const 3) (i64.const 4) (i64.const 5) (i64.const 6) (i64.const 7) (i64.const 8) (i64.const 9) (i64.const 10) (i64.const 11) (i64.const 12) (i64.const 13) (i64.const 14) (i64.const 15) (i64.const 16) (i64.const 17) (i64.const 18) (i64.const 19) (i64.const 20) (i64.const 21) (i64.const 22) (i64.const 23) (i64.const 24) (i64.const 25) (i64.const 26) (i64.const 27) (i64.const 28) (i64.const 29) (i64.const 30) (i64.const 31) (i64.const 32) (i64.const 33) (i64.const 34) (i64.const 35) (i64.const 36) (i64.const 37) (i64.const 38) (i64.const 39)))+ (func (export "loops") (param $count i64) (result i64)+ (local $sum i64)+ (loop $again+ (local.set $sum (i64.add (local.get $sum) (local.get $count)))+ (local.set $count (i64.sub (local.get $count) (i64.const 1)))+ (br_if $again (i64.ne (local.get $count) (i64.const 0))))+ (return_call $many (local.get $sum) (i64.const 1) (i64.const 2) (i64.const 3) (i64.const 4) (i64.const 5) (i64.const 6) (i64.const 7) (i64.const 8) (i64.const 9) (i64.const 10) (i64.const 11) (i64.const 12) (i64.const 13) (i64.const 14) (i64.const 15) (i64.const 16) (i64.const 17) (i64.const 18) (i64.const 19) (i64.const 20) (i64.const 21) (i64.const 22) (i64.const 23) (i64.const 24) (i64.const 25) (i64.const 26) (i64.const 27) (i64.const 28) (i64.const 29) (i64.const 30) (i64.const 31) (i64.const 32) (i64.const 33) (i64.const 34) (i64.const 35) (i64.const 36) (i64.const 37) (i64.const 38) (i64.const 39))))diff --git a/Libraries/LibWasm/Interpreter/interpreter.flap b/Libraries/LibWasm/Interpreter/interpreter.flapindex ee044b362ef..1d3eadd6618 100644--- a/Libraries/LibWasm/Interpreter/interpreter.flap+++ b/Libraries/LibWasm/Interpreter/interpreter.flap@@ -307,7 +307,8 @@ inline fn call_host_function(function: u64, return_ip: u64, context_pointer: u64# Call a function with compiled code, with its arguments on top of the operand stack. The runtime runs it and replaces# the arguments with its results; a trap in it leaves the interpreter from the compiled code. An exception it throws-# continues at the call, as with host functions.+# continues at the call, as with host functions. A tail call it makes of a function that does not run compiled comes+# back to the interpreter, which makes it in the compiled function's place (see CallPending).inline fn call_compiled_function(function: u64, return_ip: u64, context_pointer: u64) {store64([context_pointer, CONTEXT_ARGUMENTS], function);let top: u64 = vsp;@@ -323,6 +324,13 @@ inline fn call_compiled_function(function: u64, return_ip: u64, context_pointer:if new_top == 1 @cold {resume_at_handler();}+ if new_top == 2 @cold {+ let pending_context = context();+ let mut pending_ip: u64;+ load64(pending_ip, [pending_context, CONTEXT_ARGUMENT_4]);+ ip = pending_ip;+ dispatch;+ }vsp = new_top;dispatch;}@@ -676,6 +684,41 @@ inline fn tail_call(function: u64) {call_function(function, return_ip, context_pointer);}+# Call the function that compiled code tail called, which the runtime left in the context's first argument with its+# argument slots, in operand stack order, where the second points, so that its results end at `end`, and continue at+# `return_ip` when it returns. Its arguments may need more room than those of the function it replaces.+inline fn call_pending(end: u64, return_ip: u64) {+ let context_pointer = context();+ let mut function: u64;+ load64(function, [context_pointer, CONTEXT_ARGUMENTS]);+ let mut arguments_pointer: u64;+ load64(arguments_pointer, [context_pointer, CONTEXT_ARGUMENT_1]);+ let mut param_slots: u64;+ load32(param_slots, [function, FUNCTION_PARAM_SLOTS]);+ let new_top = end - (param_slots << 3);+ let current_sp: u64 = sp;+ # The handlers' spill area is right above the stack pointer, so it must stay below the arguments.+ let bottom = align_down_16(new_top - SPILL_AREA_SIZE);+ if bottom < current_sp {+ let mut limit: u64;+ load64(limit, [context_pointer, CONTEXT_STACK_LIMIT]);+ guard bottom >= limit else @cold {+ trap_with(TRAP_STACK_EXHAUSTED, context_pointer);+ };+ probe_stack(current_sp, bottom);+ sp = bottom;+ }+ let arguments: Sequence<u64> = alias(arguments_pointer);+ let slots: Sequence<u64> = alias(new_top);+ let mut index: u64 = 0;+ while index < param_slots {+ slots[index] = arguments[index];+ index = index + 1;+ }+ vsp = new_top;+ call_function(function, return_ip, context_pointer);+}+# Branches.# Take the branch whose side-table entry is at `entry`, from the instruction at `branch_ip`.@@ -814,6 +857,18 @@ handler TrapFromNative() @opcode(0xef) {trap_with(code, context_pointer);}+# Compiled code that call_compiled_function() called, or that continued a frame at a loop, tail called a function that+# does not run compiled, which the runtime left pending (see call_pending()), with where the results of the function+# it replaces go in the context's third argument and the address its call returns to in the fourth.+handler CallPending() @opcode(0xee) {+ let context_pointer = context();+ let mut end: u64;+ load64(end, [context_pointer, CONTEXT_ARGUMENT_2]);+ let mut return_ip: u64;+ load64(return_ip, [context_pointer, CONTEXT_ARGUMENT_3]);+ call_pending(end, return_ip);+}+# Bytes that are no instruction. Validation rejects every one of them, so this is never reached.handler Fallback() @fallback {trap(TRAP_UNREACHABLE);@@ -847,7 +902,7 @@ handler Loop() @opcode(0x03) {let frame: u64 = fp;store64([context_pointer, CONTEXT_ARGUMENT_3], frame);# The runtime may run the rest of the function compiled from here (OSR), leaving its results on the operand- # stack.+ # stack, or a tail call it made pending.let results_top: u64 = call_helper(wasm_runtime_tier_up, context_pointer);if results_top == 1 {resume_at_handler();@@ -855,6 +910,24 @@ handler Loop() @opcode(0x03) {if results_top == 2 {trap(TRAP_RUNTIME);}+ if results_top == 3 {+ # The frame's compiled code tail called a function that does not run compiled, which replaces the frame.+ let frame: u64 = fp;+ let mut saved_stp: u64;+ load64(saved_stp, [frame, FRAME_SAVED_STP]);+ stp = saved_stp;+ let mut saved_memory_base: u64;+ load64(saved_memory_base, [frame, FRAME_SAVED_MEMORY_BASE]);+ memory_base = saved_memory_base;+ let mut saved_fp: u64;+ load64(saved_fp, [frame, FRAME_SAVED_FP]);+ fp = saved_fp;+ let pending_context = context();+ let mut pending_ip: u64;+ load64(pending_ip, [pending_context, CONTEXT_ARGUMENT_4]);+ ip = pending_ip;+ dispatch;+ }if results_top != 0 {vsp = results_top;return_from_function();diff --git a/Libraries/LibWasm/JIT/ARCHITECTURE.md b/Libraries/LibWasm/JIT/ARCHITECTURE.mdindex 9b7104bb8be..c9c9644998f 100644--- a/Libraries/LibWasm/JIT/ARCHITECTURE.md+++ b/Libraries/LibWasm/JIT/ARCHITECTURE.md@@ -357,7 +357,12 @@ the interpreter and the host. The JIT is on by default; `LIBWASM_JIT` configures- **Compiled to the rest.** Every other function's native entry is the runtime adapter, which savesthe argument registers and calls `wasm_runtime_call_from_native`. That runs the callee through`Store::invoke` (a nested interpreter entry, or the host function) and puts the results into the- saved registers and result area, or returns a trap code, keeping the trap in the store.+ saved registers and result area, or returns a trap code, keeping the trap in the store. A tail+ call of WebAssembly code from compiled code that the entry trampoline called, whose adapter frame+ returns to the trampoline, is not made there: the runtime keeps the callee and its arguments and+ returns through the trampoline, and the interpreter calls the callee in the compiled function's+ place (its CallPending pseudo-instruction, or a tail call of the frame an OSR compile continued).+ So functions that tail call each other across the tiers run in constant stack space.- **Traps.** The trap exit stores the code in the context's first argument and the context in thetrapping frame's header, then continues at the interpreter's TrapFromNative pseudo-instruction(opcode 0xEF), which traps like the interpreter does: out of the innermost interpreter entry,diff --git a/Libraries/LibWasm/Module/src/abi.rs b/Libraries/LibWasm/Module/src/abi.rsindex f21083cd8fc..da378b84188 100644--- a/Libraries/LibWasm/Module/src/abi.rs+++ b/Libraries/LibWasm/Module/src/abi.rs@@ -75,6 +75,9 @@ pub const OPCODE_CALL_ENTRY: u8 = 0xf3;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;+/// The pseudo-instruction that calls the function a compiled function the interpreter called tail called, in that+/// function's place, when it does not run compiled.+pub const OPCODE_CALL_PENDING: u8 = 0xee;/// One function, as the interpreter sees it. Function references point at these.#[repr(C)]