Truly independent web browser
LibJS: Reload arguments and this from the frame in the JIT
Andreas Klingd33767294729
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.mdindex 82158174587..e7492e0c517 100644--- a/Libraries/LibJS/JIT/ARCHITECTURE.md+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md@@ -53,7 +53,9 @@ a node that writes the frame wrote, right after it. Merges and loop headers nevememory: a slot the paths disagree on (or a loop assigns) gets a phi, except that a slot every pathloaded, and memory still holds, is loaded again at the merge (loop invariant code motion takes suchloads out of loops). The loads at the start of the function move down to where their uses meet,-outside of loops, as far as nothing on the way may write the slot's memory. Frame memory is written+outside of loops, as far as nothing on the way may write the slot's memory. The arguments and the+`this` value register that no instruction writes keep the values the function started with+(`Graph::unwritten_slots`), and nothing stores to them. Frame memory is writtenonly where something reads it: before calls that read the frame and before `Suspend` (`StoreSlot`),where the compiled function assigns an argument that its legacy `arguments` shows (which any code itcalls can read), and by exits and leaves through the translator.@@ -266,7 +268,8 @@ Rules (enforced by `passes/verify.rs`):Code generation turns each point where the runtime may read the state into a **site**(`code::Site`): its kind, its chain of frame states with the location of every value (register,-stack slot, constant, an arguments object or a virtual object to create), and the virtual objects.+stack slot, a slot of the compiled function's frame that nothing writes, constant, an arguments+object or a virtual object to create), and the virtual objects.| Site kind | Where | What the runtime does ||---|---|---|@@ -447,6 +450,14 @@ the saves area. The verifier of the allocation checks that every node got the tethat inputs of a fixed register are in it, and that no value an exit needs is in the node's outputregister.+A value loaded from one of `Graph::unwritten_slots` has that frame slot as its home+(`regalloc::frame_home()`): it gets no spill slot and no store after its definition, and wherever+no register holds it, moves reload it from the frame and exits find it there+(`code::ValueLocation::Frame`). Code inside a node that published the frames of inlined calls+reads it through the compiled function's frame the entry saved, since the frame register then+holds another frame. The verifier names the value of such a slot by the slot, which holds it+everywhere, and reports stores to it.+To be written: the forward walk, spills at definition, merges and their state predecessor, coldblocks, the verifier.diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rsindex f58c464527d..d0065634608 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs@@ -317,10 +317,10 @@ fn writes_slot_memory(op: &Op, slot: u32, arguments_base: u32) -> bool {/// OPTIMIZATION: Moves the loads at the start of the compiled function (see `GraphBuilder::load_entry_slots()`) down/// the dominator tree, to the block where their uses meet, or the closest one outside of loops above-/// it: those of slots that keep their values (`unwritten_slots`, as operands) anywhere, and the others-/// where nothing on the way there may write their frame memory. Values that only code far from the-/// start or on a few paths uses then do not take registers or spill slots from the start.-fn sink_entry_loads(graph: &mut Graph, unwritten_slots: &BitSet, arguments_base: u32) {+/// it: those of slots that keep their values (`Graph::unwritten_slots`) anywhere, and the others where+/// nothing on the way there may write their frame memory. Values that only code far from the start or on+/// a few paths uses then do not take registers or spill slots from the start.+fn sink_entry_loads(graph: &mut Graph, arguments_base: u32) {let entry = BlockId(0);let loads = graph.block(entry)@@ -403,7 +403,7 @@ fn sink_entry_loads(graph: &mut Graph, unwritten_slots: &BitSet, arguments_base:let Op::LoadSlot { slot } = graph.node(load).op else {unreachable!("only loads sink");};- let keeps_value = unwritten_slots.capacity() > slot as usize && unwritten_slots.contains(slot as usize);+ let keeps_value = graph.is_unwritten_slot(slot);// NB: The other slots sink no further than the first node that may write their memory, on the way to the// target block (every block from where it can be reached, before it) or in it.let writes = |node: &NodeId| !keeps_value && writes_slot_memory(&graph.node(*node).op, slot, arguments_base);@@ -827,7 +827,8 @@ impl<'a> GraphBuilder<'a> {);}}- sink_entry_loads(&mut graph, &unwritten_slots, self.function.layout.arguments_base());+ graph.unwritten_slots = unwritten_slots;+ sink_entry_loads(&mut graph, self.function.layout.arguments_base());Ok(graph)}diff --git a/Libraries/LibJS/JIT/Rust/src/code.rs b/Libraries/LibJS/JIT/Rust/src/code.rsindex c34a88c5a8f..84baec65461 100644--- a/Libraries/LibJS/JIT/Rust/src/code.rs+++ b/Libraries/LibJS/JIT/Rust/src/code.rs@@ -293,6 +293,9 @@ pub enum ValueLocation {Register(u8, Repr),/// A stack slot at the given offset from the JIT frame.Stack(i32, Repr),+ /// A slot of the compiled function's frame (an operand) that holds the value wherever compiled code runs, which+ /// is tagged: one of its arguments or its `this` value register that nothing writes.+ Frame(u32),/// A NaN-boxed constant.Constant(u64),/// The frame's arguments object, which the compiled code never created:diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex 5e6bcf48174..8f2a8fa1512 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -917,6 +917,23 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {Ok(Address::new(self.pinned.frame, checked_i32(offset)?))}+ /// The address of the slot `slot` of the frame at `frame` that is the home of a value (see+ /// `regalloc::frame_home()`), which the value's `LoadSlot` addressed already.+ fn frame_home_address(&self, frame: Gpr, slot: u32) -> Address {+ let offset = u64::from(self.runtime.offsets.execution_context_slots) + 8 * u64::from(slot);+ Address::new(frame, i32::try_from(offset).expect("the load of the slot addressed it"))+ }++ /// Loads the value that the compiled function's frame slot `slot` holds (see `regalloc::frame_home()`) into `dst`+ /// inside the code of a node, where the frame register may hold the innermost frame of the inlined calls the node+ /// published: reads the compiled function's frame from where the entry saved it.+ fn emit_load_frame_home(&mut self, dst: Gpr, slot: u32) {+ let root_frame = self.local_address(self.locals.root_frame);+ self.masm.load64(dst, &root_frame);+ let address = self.frame_home_address(dst, slot);+ self.masm.load64(dst, &address);+ }+fn frame_field(&self, offset: u32) -> Address {Address::new(self.pinned.frame, offset as i32)}@@ -1310,7 +1327,23 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let address = self.spill_address(to);self.masm.store_imm64(&address, bits);}- (_, Location::Constant(_)) => unreachable!("moves never write constants"),+ // NB: Between nodes, the frame register holds the compiled function's frame.+ (Location::Frame(slot), Location::Register(to)) => {+ let Register::General(to) = register_of(to) else {+ unreachable!("values loaded from frame slots are tagged");+ };+ let address = self.frame_home_address(self.pinned.frame, slot);+ self.masm.load64(to, &address);+ }+ (Location::Frame(slot), Location::Stack(to)) => {+ let from = self.frame_home_address(self.pinned.frame, slot);+ let to = self.spill_address(to);+ self.masm.load64(self.pinned.scratch, &from);+ self.masm.store64(&to, self.pinned.scratch);+ }+ (_, Location::Constant(_) | Location::Frame(_)) => {+ unreachable!("moves never write constants or frame slots")+ }}}@@ -1355,7 +1388,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {Register::Float(_) => unreachable!("float64 inputs are read with `float_input()`"),},Location::Constant(bits) => InputValue::Constant(bits),- Location::Stack(_) => unreachable!("inputs are in registers or constants"),+ Location::Stack(_) | Location::Frame(_) => unreachable!("inputs are in registers or constants"),}}@@ -2935,6 +2968,12 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_box(dst, dst, repr);}Location::Constant(bits) => self.masm.move_imm64(dst, value::boxed_constant(bits, repr)),+ // NB: Nodes that publish no frames run in the compiled function's frame.+ Location::Frame(slot) if !self.publishes_frames(node) => {+ let address = self.frame_home_address(self.pinned.frame, slot);+ self.masm.load64(dst, &address);+ }+ Location::Frame(slot) => self.emit_load_frame_home(dst, slot),}}@@ -3296,6 +3335,10 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.load64(value, &Address::new(M::FRAME_POINTER, offset));self.emit_box(value, value, repr);}+ ValueLocation::Frame(slot) => {+ let address = self.slot_address(slot)?;+ self.masm.load64(value, &address);+ }ValueLocation::ArgumentsObject { .. } | ValueLocation::VirtualObject(_) => {unreachable!("frame states with objects to create leave through the runtime")}diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs b/Libraries/LibJS/JIT/Rust/src/codegen/sites.rsindex 9aca6c11dae..4f95412bc96 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs@@ -49,16 +49,16 @@ pub(crate) fn site(// NB: Stack walks and the runtime read the values of inlined call// sites from the JIT frame while the call runs, without the// registers. Values live across calls have stack slots.- Location::Register(_) if kind == SiteKind::Call => {- let slot = allocation- .node(value)- .spill_slot- .expect("values live across calls are spilled");- ValueLocation::Stack(stack_slot_offset(slot), repr)- }+ Location::Register(_) if kind == SiteKind::Call => match allocation.node(value).spill_slot {+ Some(slot) => ValueLocation::Stack(stack_slot_offset(slot), repr),+ None => ValueLocation::Frame(+ crate::regalloc::frame_home(graph, value).expect("values live across calls are spilled"),+ ),+ },// NB: Exits read float64 values from the floating point registers.Location::Register(register) => ValueLocation::Register(register % FPR_BASE, repr),Location::Stack(slot) => ValueLocation::Stack(stack_slot_offset(slot), repr),+ Location::Frame(slot) => ValueLocation::Frame(slot),Location::Constant(bits) => match crate::ir::value::virtual_arguments_kind(bits) {Some(mapped) if repr == Repr::Tagged => ValueLocation::ArgumentsObject { mapped },_ => ValueLocation::Constant(crate::ir::value::boxed_constant(bits, repr)),diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rsindex 684fb00bed6..5be1725f55c 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs@@ -420,6 +420,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.emit_box(dst, dst, repr);}Location::Constant(bits) => self.masm.move_imm64(dst, value::boxed_constant(bits, repr)),+ Location::Frame(slot) => self.emit_load_frame_home(dst, slot),}}}diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rsindex e1fd032f239..ace6a574a16 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs@@ -533,6 +533,8 @@ fn write_frame_states(vm: *mut u64, frame: *mut u64, exit_index: u32, dump: *convalue::boxed_constant(*((frame_pointer as i64 + i64::from(offset)) as *const u64), repr)}ValueLocation::Constant(bits) => bits,+ // NB: Exit stubs pass the compiled function's frame.+ ValueLocation::Frame(slot) => *frame.add(FRAME_HEADER_WORDS + slot as usize),ValueLocation::ArgumentsObject { mapped } => fake_arguments_object(mapped),ValueLocation::VirtualObject(_) => unreachable!("tests make no virtual objects"),};@@ -1578,6 +1580,27 @@ mod execution {#[test]fn exit_values_survive_in_spill_slots_across_calls() {// r6 lives across a call in a spill slot, then the next instruction exits.+ let program = assemble(|_| {+ vec![+ Instruction::Enter,+ add(r(6), a(0), c(1)),+ Instruction::ConcatString { dst: r(5), src: c(1) },+ Instruction::Mov { dst: l(0), src: r(6) },+ Instruction::Mov { dst: l(1), src: r(5) },+ add(r(7), l(0), l(1)),+ Instruction::Return { value: r(7) },+ ]+ });+ let (result, machine) = run_with(&program, test_layout(), &[value::int32(5)], &[5], |_| {});+ assert_eq!(result.status, RESUME);+ assert_eq!(machine.slot(l(0)), value::int32(15));+ // Enter emptied r5, which the fake ConcatString treats as 0.+ assert_eq!(machine.slot(l(1)), value::int32(10));+ }++ #[test]+ fn exit_values_survive_in_frame_slots_that_nothing_writes_across_calls() {+ // r6 holds the argument across a call, and its frame slot holds it for the exit after the call.let program = assemble(|_| {vec![Instruction::Enter,@@ -1589,10 +1612,16 @@ mod execution {Instruction::Return { value: r(7) },]});+ let (_, compiled) = compile_program(&program, test_layout(), &[5]);+ assert!(compiled.sites.iter().any(|site| {+ site.frames[0]+ .values+ .iter()+ .any(|(slot, location)| *slot == l(0).raw() && *location == ValueLocation::Frame(a(0).raw()))+ }));let (result, machine) = run_with(&program, test_layout(), &[value::int32(5)], &[5], |_| {});assert_eq!(result.status, RESUME);assert_eq!(machine.slot(l(0)), value::int32(5));- // Enter emptied r5, which the fake ConcatString treats as 0.assert_eq!(machine.slot(l(1)), value::int32(10));}diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rsindex 696bb3d58bf..1c468c66dd1 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs@@ -1585,6 +1585,11 @@ pub struct Graph {/// The `AssumeLegacyArgumentsUnread` nodes, each with the nodes of its/// instruction that run code.pub legacy_arguments_guards: Vec<(NodeId, Vec<NodeId>)>,+ /// The slots of the compiled function (as operands) whose frame memory holds the value the function started with+ /// wherever its code runs: the arguments and the `this` value register, unless an instruction writes them. Nothing+ /// stores to them (the verifier enforces this), so the register allocator reloads what was loaded from them from+ /// there (see `regalloc::frame_home()`).+ pub unwritten_slots: crate::bitset::BitSet,}impl Graph {@@ -1825,6 +1830,11 @@ impl Graph {self.blocks.truncate(order.len());}+ /// Whether `slot` (an operand of the compiled function) is one of `unwritten_slots`.+ pub fn is_unwritten_slot(&self, slot: u32) -> bool {+ (slot as usize) < self.unwritten_slots.capacity() && self.unwritten_slots.contains(slot as usize)+ }+/// The bits of `id` if it is a constant, or a refinement of one.pub fn constant_value(&self, id: NodeId) -> Option<u64> {match self.node(self.unrefined(id)).op {diff --git a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs b/Libraries/LibJS/JIT/Rust/src/passes/verify.rsindex 50655a4f209..ab8977f8a15 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs@@ -31,7 +31,8 @@//! - `StoreSlot` writes only written constants, the arguments the compiled//! function's legacy `arguments` shows, and slots that the next call//! reading the frame (a `Generic` node, or a call that reads its operands-//! from the frame) or `Suspend` reads (see `verify_frame_writes()`).+//! from the frame) or `Suspend` reads (see `verify_frame_writes()`), and+//! never one of `Graph::unwritten_slots`.use super::dominators::Dominators;use crate::bytecode::FrameLayout;@@ -70,6 +71,12 @@ pub fn verify_frame_writes(graph: &Graph, layout: &FrameLayout) -> Result<(), Stcontinue;};let operand = Operand::from_raw(slot).raw();+ if graph.is_unwritten_slot(operand) {+ errors.push(format!(+ "StoreSlot v{} in b{index} writes slot {operand}, which nothing writes (see `Graph::unwritten_slots`)",+ node.0+ ));+ }let is_constant = operand >= layout.registers_and_locals_count && operand < layout.arguments_base();if is_constant || graph.legacy_arguments.contains(&operand) {continue;diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rsindex 35a836c6119..4da925cc752 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rs@@ -129,7 +129,8 @@ pub(super) fn spill_slot_classes(graph: &Graph, liveness: &ValueLiveness) -> Vecfor block in &graph.blocks {for phi in &block.phis {for input in &graph.node(*phi).inputs {- if input == phi || !is_allocated_value(graph, *input) {+ // NB: Values with a frame slot as their home have no spill slot to share.+ if input == phi || !is_allocated_value(graph, *input) || super::frame_home(graph, *input).is_some() {continue;}let (a, b) = (classes[phi.index()] as usize, classes[input.index()] as usize);diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rsindex 07361e4749a..3627f88019f 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs@@ -12,7 +12,9 @@//!//! Spilling is simple: a value that ever needs a stack slot gets one slot for//! its whole life, and code generation stores it there right after its-//! definition. Values live across a call always get one.+//! definition. Values live across a call always get one. Values loaded from a+//! frame slot that nothing writes need none: they are reloaded from the frame+//! (see `frame_home()`).//! Phis share their slots with the values flowing into them where their//! lives do not overlap (see `coalescing`), so that values carried around//! loops in stack slots need no copying.@@ -225,6 +227,9 @@ pub enum Location {Stack(u32),/// A NaN-boxed constant; only ever a move source.Constant(u64),+ /// A slot of the compiled function's frame (an operand), which holds the value loaded from it wherever that value+ /// is live (see `frame_home()`); only ever a move source.+ Frame(u32),}impl Default for Location {@@ -279,6 +284,18 @@ impl Allocation {}}+/// The slot of the compiled function's frame that holds `value` wherever it is live, if there is one: a value loaded+/// from one of the slots whose frame memory never changes (`Graph::unwritten_slots`).+///+/// OPTIMIZATION: Such a value needs no spill slot, and no store right after its definition: where no register holds+/// it, it is reloaded from the frame. Exits find it there too (`code::ValueLocation::Frame`).+pub fn frame_home(graph: &Graph, value: NodeId) -> Option<u32> {+ match graph.node(value).op {+ Op::LoadSlot { slot } if graph.is_unwritten_slot(slot) => Some(slot),+ _ => None,+ }+}+/// Assigns locations to the values of `graph`. The verifier checks the/// result where the IR is verified (see `verify()`).pub fn allocate(graph: &Graph, registers: &RegisterSet) -> Allocation {@@ -372,7 +389,7 @@ impl<'a> Allocator<'a> {{let live_in = self.liveness.live_in[index].iter().collect::<Vec<_>>();for value in live_in {- self.ensure_spill_slot(NodeId::from_index(value));+ self.ensure_home(NodeId::from_index(value));}}}@@ -438,6 +455,14 @@ impl<'a> Allocator<'a> {slot}+ /// Makes sure that `value` is available outside of registers: in its frame slot (see `frame_home()`), or in a+ /// spill slot.+ fn ensure_home(&mut self, value: NodeId) {+ if frame_home(self.graph, value).is_none() {+ self.ensure_spill_slot(value);+ }+ }+fn set_contents(&mut self, contents: Vec<Option<NodeId>>) {for value in self.contents.iter().flatten() {self.value_registers[value.index()] = None;@@ -539,10 +564,10 @@ impl<'a> Allocator<'a> {}/// Removes the value in `register` from it. The value stays available in- /// its spill slot, which it gets if it had none.+ /// its frame slot or its spill slot, which it gets if it had none.fn evict(&mut self, register: u8) {if let Some(value) = self.contents[register as usize] {- self.ensure_spill_slot(value);+ self.ensure_home(value);self.free_register(register);}}@@ -602,6 +627,9 @@ impl<'a> Allocator<'a> {if let Some(register) = self.value_registers[value.index()] {return Location::Register(register);}+ if let Some(slot) = frame_home(self.graph, value) {+ return Location::Frame(slot);+ }let slot = self.allocation.nodes[value.index()].spill_slot.unwrap_or_else(|| panic!("v{} is neither in a register nor spilled", value.0));@@ -752,6 +780,7 @@ impl<'a> Allocator<'a> {if let Some(value) = self.contents.get(register as usize).copied().flatten() {debug_assert!(self.allocation.nodes[value.index()].spill_slot.is_some()+ || frame_home(self.graph, value).is_some()|| !self.is_live_after(value, node_id),"v{} is live across a call that clobbers its register without a spill slot",value.0@@ -776,7 +805,7 @@ impl<'a> Allocator<'a> {if let Some(register) = output {self.assign_register(register, node_id);if self.liveness.needs_spill.contains(node_id.index()) {- self.ensure_spill_slot(node_id);+ self.ensure_home(node_id);}if self.liveness.dead_outputs.contains(node_id.index()) {self.free_register(register);@@ -912,6 +941,7 @@ pub fn dump_allocation(graph: &Graph, allocation: &Allocation) -> String {Location::Register(register) => format!("r{register}"),Location::Stack(slot) => format!("s{slot}"),Location::Constant(bits) => format!("#{}", crate::ir::value::describe(*bits)),+ Location::Frame(slot) => format!("frame{slot}"),};let moves_text = |moves: &[Move]| {movesdiff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rsindex 2e4959d03bc..c6531329b6c 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs@@ -82,6 +82,7 @@ fn straight_line_code() {#[test]fn values_live_across_calls_are_spilled_at_their_definition() {+ // NB: The argument is written later, so its frame slot is no home for the value loaded from it.let program = assemble(|_| {vec![Instruction::Mov { dst: r(6), src: a(0) },@@ -93,12 +94,14 @@ fn values_live_across_calls_are_spilled_at_their_definition() {argument_count: 1,arguments: vec![r(6)],},+ Instruction::Mov { dst: a(0), src: r(7) },Instruction::Return { value: r(6) },]});let graph = build(&program);let allocation = allocate_and_verify(&graph);let argument = find_node(&graph, |node| node.op == Op::LoadSlot { slot: a(0).raw() });+ assert_eq!(frame_home(&graph, argument), None);assert!(allocation.node(argument).spill_slot.is_some());assert_text(&dump_allocation(&graph, &allocation),@@ -116,6 +119,43 @@ fn values_live_across_calls_are_spilled_at_their_definition() {);}+#[test]+fn values_loaded_from_unwritten_slots_are_reloaded_from_the_frame() {+ let program = assemble(|_| {+ vec![+ Instruction::Mov { dst: r(6), src: a(0) },+ Instruction::Call {+ call_feedback: 0,+ dst: r(7),+ callee: r(5),+ this_value: r(5),+ argument_count: 1,+ arguments: vec![r(6)],+ },+ Instruction::Return { value: r(6) },+ ]+ });+ let graph = build(&program);+ let allocation = allocate_and_verify(&graph);+ let argument = find_node(&graph, |node| node.op == Op::LoadSlot { slot: a(0).raw() });+ assert_eq!(frame_home(&graph, argument), Some(a(0).raw()));+ assert_eq!(allocation.node(argument).spill_slot, None);+ assert_text(+ &dump_allocation(&graph, &allocation),+ "+ b0:+ v8 Jump+ b1:+ v6 LoadSlot -> r0+ v7 LoadSlot -> r1+ v9 CallSlowPath (r0, r0, r1) -> r0 exit {6=frame12}+ moves frame12 -> r0+ v10 Return (r0)+ spill slots: 0+ ",+ );+}+#[test]fn many_simultaneously_live_values_are_spilled() {let layout = FrameLayout {@@ -691,6 +731,7 @@ fn the_verifier_finds_values_in_the_wrong_place() {argument_count: 1,arguments: vec![r(6)],},+ Instruction::Mov { dst: a(0), src: r(7) },Instruction::Return { value: r(6) },]});@@ -715,6 +756,75 @@ fn the_verifier_finds_values_in_the_wrong_place() {assert!(verify(&graph, ®isters, &broken).is_err());}+#[test]+fn the_verifier_finds_values_reloaded_from_frame_slots_that_do_not_hold_them() {+ let program = assemble(|_| {+ vec![+ Instruction::Mov { dst: r(6), src: a(0) },+ Instruction::Call {+ call_feedback: 0,+ dst: r(7),+ callee: r(5),+ this_value: r(5),+ argument_count: 1,+ arguments: vec![r(6)],+ },+ Instruction::Return { value: r(6) },+ ]+ });+ let graph = build(&program);+ let registers = RegisterSet::test_configuration();+ let allocation = allocate(&graph, ®isters);+ verify(&graph, ®isters, &allocation).unwrap();+ let returned = find_node(&graph, |node| matches!(node.op, Op::Return));+ assert_eq!(+ allocation.node(returned).moves_before,+ [Move {+ from: Location::Frame(a(0).raw()),+ to: Location::Register(0),+ }]+ );++ // A frame slot that the code may write is no home.+ let mut written = graph.clone();+ written.unwritten_slots = crate::bitset::BitSet::new(0);+ assert!(verify(&written, ®isters, &allocation).is_err());++ // Another frame slot holds another value.+ let mut broken = allocation.clone();+ broken.nodes[returned.index()].moves_before[0].from = Location::Frame(r(5).raw());+ assert!(verify(&graph, ®isters, &broken).is_err());++ // A store to the slot, which nothing may do, makes it hold another value.+ let mut stored = graph.clone();+ let undefined = stored.add_node(crate::ir::Node::new(+ Op::Constant(value::UNDEFINED),+ vec![],+ Some(Repr::Tagged),+ 0,+ ));+ let store = stored.add_node(crate::ir::Node::new(+ Op::StoreSlot { slot: a(0).raw() },+ vec![undefined],+ None,+ 0,+ ));+ let block = stored+ .blocks+ .iter()+ .position(|block| block.control == Some(returned))+ .unwrap();+ stored.blocks[block].body.push(store);+ let mut allocation = allocation;+ allocation.nodes.push(NodeAllocation::default());+ allocation.nodes.push(NodeAllocation {+ inputs: [Location::Constant(value::UNDEFINED)].into_iter().collect(),+ ..NodeAllocation::default()+ });+ let errors = verify(&stored, ®isters, &allocation).unwrap_err();+ assert!(errors.contains("nothing writes"), "{errors}");+}+/// A tiny deterministic random number generator (xorshift64).pub(crate) struct Random(pub(crate) u64);diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rsindex e474829cbd0..7f3fb205a76 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs@@ -10,6 +10,11 @@//! and stack slot, which value it holds on every path reaching each point.//! Every input, phi input and exit value must be found in the location the//! allocation claims, no matter which path led there.+//!+//! A slot of the compiled function's frame that nothing writes (see+//! `frame_home()`) holds the value the function started with everywhere, and+//! nothing on any path may store to it. Every load of such a slot loads that+//! value, so the state names it by the slot rather than by a load.use super::Allocation;use super::Location;@@ -30,6 +35,8 @@ use std::collections::BTreeMap;enum Content {Value(NodeId),Constant(u64),+ /// The value a slot that nothing writes holds, which every load of it loads.+ UnwrittenSlot(u32),}type State = BTreeMap<Location, Content>;@@ -107,15 +114,21 @@ impl Verifier<'_> {if matches!(self.graph.node(value).op, Op::VirtualObject { .. }) {return Content::Constant(crate::ir::value::EMPTY);}+ if let Op::LoadSlot { slot } = self.graph.node(value).op+ && self.graph.is_unwritten_slot(slot)+ {+ return Content::UnwrittenSlot(slot);+ }match self.graph.constant_value(value) {Some(bits) => Content::Constant(bits),None => Content::Value(value),}}- fn read(state: &State, location: Location) -> Option<Content> {+ fn read(&self, state: &State, location: Location) -> Option<Content> {match location {Location::Constant(bits) => Some(Content::Constant(bits)),+ Location::Frame(slot) if self.graph.is_unwritten_slot(slot) => Some(Content::UnwrittenSlot(slot)),_ => state.get(&location).copied(),}}@@ -139,7 +152,7 @@ impl Verifier<'_> {for (phi, input) in phi_inputs_from(self.graph, *predecessor, block) {let output = self.allocation.node(phi).output.expect("phis have a location");for location in std::iter::once(output).chain(self.filled_slot(phi)) {- if Self::read(&state, location) == Some(self.content_of_value(input)) {+ if self.read(&state, location) == Some(self.content_of_value(input)) {state.insert(location, Content::Value(phi));} else {state.remove(&location);@@ -165,7 +178,7 @@ impl Verifier<'_> {for (phi, input) in phi_inputs_from(self.graph, predecessor, block) {let output = self.allocation.node(phi).output.expect("phis have a location");for location in std::iter::once(output).chain(self.filled_slot(phi)) {- let found = Self::read(exit, location);+ let found = self.read(exit, location);if found != Some(self.content_of_value(input)) {self.error(format!("phi v{} in b{}: input from b{} should be {:?} in {location:?}, found {found:?}",@@ -196,12 +209,12 @@ impl Verifier<'_> {fn apply_moves(&mut self, state: &mut State, moves: &[Move], context: &str) {for m in moves {- if matches!(m.to, Location::Constant(_)) {- self.error(format!("{context}: move into a constant"));+ if matches!(m.to, Location::Constant(_) | Location::Frame(_)) {+ self.error(format!("{context}: move into {:?}", m.to));continue;}self.check_location(m.to, context);- match Self::read(state, m.from) {+ match self.read(state, m.from) {Some(content) => {state.insert(m.to, content);}@@ -230,7 +243,7 @@ impl Verifier<'_> {fn expect(&mut self, state: &State, location: Location, value: NodeId, context: &str) {let expected = self.content_of_value(value);- let found = Self::read(state, location);+ let found = self.read(state, location);if found != Some(expected) {self.error(format!("{context}: expected {expected:?} in {location:?}, found {found:?}"@@ -292,6 +305,11 @@ impl Verifier<'_> {debug_assert!(node.op != Op::Phi);self.apply_moves(state, &allocation.moves_before, &context);+ if let Op::StoreSlot { slot } = node.op+ && self.graph.is_unwritten_slot(slot)+ {+ self.error(format!("{context}: stores to slot {slot}, which nothing writes"));+ }if allocation.inputs.len() != node.inputs.len() {self.error(format!("{context}: wrong number of input locations"));return;@@ -361,9 +379,9 @@ impl Verifier<'_> {if super::RegisterClass::of_register(register) != super::RegisterClass::of(node.repr) {self.error(format!("{context}: the output is in a register of the other class"));}- state.insert(Location::Register(register), Content::Value(node_id));+ state.insert(Location::Register(register), self.content_of_value(node_id));if let Some(slot) = allocation.spill_slot {- state.insert(Location::Stack(slot), Content::Value(node_id));+ state.insert(Location::Stack(slot), self.content_of_value(node_id));}}(false, None) => {}diff --git a/Libraries/LibJS/Rust/src/jit/translate.rs b/Libraries/LibJS/Rust/src/jit/translate.rsindex c6f881d1d65..224b54106e2 100644--- a/Libraries/LibJS/Rust/src/jit/translate.rs+++ b/Libraries/LibJS/Rust/src/jit/translate.rs@@ -104,10 +104,12 @@ impl RegisterDump {}}-/// Reads a value that is not an object the code never created.-fn read_location(location: ValueLocation, dump: &RegisterDump) -> Value {+/// Reads a value that is not an object the code never created, with the compiled function's frame at `root`.+fn read_location(location: ValueLocation, dump: &RegisterDump, root: NonNull<ExecutionContext>) -> Value {let (bits, repr) = match location {ValueLocation::Constant(bits) => return Value::from_bits(bits),+ // NB: Nothing writes such a slot, so it still holds the value while frames are written.+ ValueLocation::Frame(slot) => return frame_of(root).slots()[slot as usize].get(),ValueLocation::Register(encoding, repr) => {let bits = if repr == Repr::Float64 {dump.fprs[usize::from(encoding)]@@ -141,7 +143,7 @@ fn read_location(location: ValueLocation, dump: &RegisterDump) -> Value {struct SiteValues<'a> {vm: &'a Vm,code: &'a JitCode,- root: *const ExecutionContext,+ root: NonNull<ExecutionContext>,site: &'a Site,dump: &'a RegisterDump,created: Deferred<'a, HashMap<u32, Gc<Object>>>,@@ -165,7 +167,7 @@ impl<'a> SiteValues<'a> {Self {vm,code,- root: root.as_ptr(),+ root,site,dump,created: defer_gc.cover(HashMap::new()),@@ -176,14 +178,17 @@ impl<'a> SiteValues<'a> {fn value(&mut self, location: ValueLocation) -> Value {let ValueLocation::VirtualObject(index) = location else {- return read_location(location, self.dump);+ return read_location(location, self.dump, self.root);};if let Some(object) = self.created.get(&index) {return Value::from_object(*object);}let description = &self.site.objects[index as usize];// NB: An object created for the frame before is the one the frame has, with whatever happened to it since.- if let Some(object) = self.code.materialized_object(self.root, description.allocation) {+ if let Some(object) = self+ .code+ .materialized_object(self.root.as_ptr(), description.allocation)+ {self.created.insert(index, object);return Value::from_object(object);}@@ -194,7 +199,7 @@ impl<'a> SiteValues<'a> {self.created.insert(index, object);if self.remember {self.code- .remember_materialized_object(self.root, description.allocation, object);+ .remember_materialized_object(self.root.as_ptr(), description.allocation, object);}let property_count = shape.property_count();for index in 0..property_count {@@ -954,7 +959,9 @@ pub fn call_site_frames<'vm>(.iter().find(|(slot, _)| *slot == CALLEE_SLOT).and_then(|(_, location)| match location {- ValueLocation::Stack(..) | ValueLocation::Constant(_) => Some(read_location(*location, &dump)),+ ValueLocation::Stack(..) | ValueLocation::Constant(_) | ValueLocation::Frame(_) => {+ Some(read_location(*location, &dump, NonNull::from(frame)))+ }_ => None,});let function = match closure {