Truly independent web browser
LibJS/JIT: Give for-in loop bodies the key the cache holds
Andreas Klingfc24772ccc3d
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/property_iterator.rs b/Libraries/LibJS/JIT/Rust/src/builder/property_iterator.rsindex e7d9769cd85..66cd42c3f15 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/property_iterator.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/property_iterator.rs@@ -39,6 +39,10 @@ impl GraphBuilder<'_> {// the slow path writes it once done.let old_value = self.read(dst_value)?;let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;+ // NB: The cache stops holding the receiver's keys only where the loop changes the receiver's shape, which is+ // rare. Exiting there, until an exit was taken, makes the key the cache's key wherever the loop's body+ // reads it, which keyed accesses of the key rely on to read the property at its known place.+ self.exit_instead_of_slow_path(&mut slow_paths);let receiver = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, vec![receiver], true);self.branch_to_slow_path(&mut slow_paths,diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rsindex 6829ffd0b35..61fb313cdf9 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs@@ -1866,26 +1866,37 @@ impl FakeKeySnapshot {}}-/// Runs ObjectPropertyIteratorNext with `receiver`, `keys` and `cursor`;-/// returns the value, done flag and cursor it wrote, and how often the slow-/// path ran.+/// The program running ObjectPropertyIteratorNext with the arguments, which ends with `written`.+fn property_iterator_next_program(written: Operand) -> Program {+ assemble(|_| {+ vec![+ Instruction::Enter,+ Instruction::ObjectPropertyIteratorNext {+ dst_value: r(5),+ dst_done: r(6),+ receiver: argument(0),+ keys: argument(1),+ cursor: argument(2),+ },+ // NB: Unlike Return, End returns the empty value as is.+ Instruction::End { value: written },+ ]+ })+}++/// Runs ObjectPropertyIteratorNext with `receiver`, `keys` and `cursor`,+/// built with its slow path (as after an exit there); returns the value,+/// done flag and cursor it wrote, and how often the slow path ran.fn property_iterator_next(receiver: u64, keys: u64, cursor: u64) -> (u64, u64, u64, u64) {let run = |written: Operand| {- let program = assemble(|_| {- vec![- Instruction::Enter,- Instruction::ObjectPropertyIteratorNext {- dst_value: r(5),- dst_done: r(6),- receiver: argument(0),- keys: argument(1),- cursor: argument(2),- },- // NB: Unlike Return, End returns the empty value as is.- Instruction::End { value: written },- ]- });- let (result, machine) = run_program(&program, &[receiver, keys, cursor], |_| {});+ let program = property_iterator_next_program(written);+ let pc = program.offsets[1];+ let (result, machine) = run_program_with_snapshot(+ &program,+ &[receiver, keys, cursor],+ |snapshot| snapshot.executables[0].exit_sites = vec![(pc, ExitKind::SlowPath)],+ |_| {},+ );assert_eq!(result.status, RETURNED);(result.value, machine.vm[VM_SLOW_PUTS_WORD])};@@ -1893,6 +1904,19 @@ fn property_iterator_next(receiver: u64, keys: u64, cursor: u64) -> (u64, u64, u(value, run(r(6)).0, run(argument(2)).0, slow_paths)}+/// Whether ObjectPropertyIteratorNext with `receiver`, `keys` and `cursor`,+/// built before any exit there, exits instead of running its slow path.+fn property_iterator_next_exits(receiver: u64, keys: u64, cursor: u64) -> bool {+ let program = property_iterator_next_program(r(5));+ let (result, machine) = run_program(&program, &[receiver, keys, cursor], |_| {});+ assert_eq!(machine.vm[VM_SLOW_PUTS_WORD], 0);+ if result.status == crate::code::JitStatus::Resume as u64 {+ return true;+ }+ assert_eq!(result.status, RETURNED);+ false+}+#[test]fn property_iterator_next_reads_key_snapshots() {let shape = low_cell(&[0; 12]);@@ -1915,9 +1939,24 @@ fn property_iterator_next_reads_key_snapshots() {property_iterator_next(object.value(), named.value(), value::int32(2)),(empty, value::TRUE, value::int32(2), 0));- // Other shapes, cursors and receivers are slow.+ // Other shapes, cursors and receivers are slow, and exit until an exit was taken there.let other_shape = low_cell(&[0; 12]);let other = FakeKeySnapshot::new(1, other_shape, &keys);+ assert!(!property_iterator_next_exits(+ object.value(),+ named.value(),+ value::int32(0)+ ));+ assert!(property_iterator_next_exits(+ object.value(),+ other.value(),+ value::int32(0)+ ));+ assert!(property_iterator_next_exits(+ value::int32(1),+ named.value(),+ value::int32(0)+ ));assert_eq!(property_iterator_next(object.value(), other.value(), value::int32(0)).3,1diff --git a/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rs b/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rsnew file mode 100644index 00000000000..ee0ed84d8a2--- /dev/null+++ b/Libraries/LibJS/JIT/Rust/src/passes/branch_splitting.rs@@ -0,0 +1,374 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Branch splitting: a block that joins two paths only to branch on which of+//! them it came from goes away. Where an instruction's paths join with a+//! boolean phi of constants (like the "done" result of a for-in loop's next+//! key), and the next instruction branches on it, each path jumps straight+//! to its side of the branch instead, and the code there sees the values of+//! its own path rather than phis of both. A for-in loop's body then reads+//! the key the cache holds, not a phi that also holds `undefined`.++use super::dominators::Dominators;+use crate::bitset::BitSet;+use crate::ir::BlockId;+use crate::ir::BranchCondition;+use crate::ir::FrameStateId;+use crate::ir::Graph;+use crate::ir::NodeId;+use crate::ir::Op;++/// A block to split: its phis, the block that branches (itself, or the one+/// it jumps to), the nodes before that branch (which each side gets a copy+/// of), and for each side of the branch, the predecessor that takes it and+/// its target.+struct Split {+ block: BlockId,+ branch_block: BlockId,+ moved: Vec<NodeId>,+ sides: [(BlockId, BlockId); 2],+}++/// Whether a copy of `node` can run at the start of each side instead: an+/// `AssumeValid`, or a node without effects that cannot exit.+fn is_movable(graph: &Graph, node: NodeId) -> bool {+ let data = graph.node(node);+ if data.op == Op::AssumeValid {+ return true;+ }+ let properties = data.op.properties();+ data.frame_state.is_none()+ && data.op.exit_kind().is_none()+ && !data.op.is_control()+ && !properties.can_lazy_exit+ && !properties.is_call+ && !properties.runs_code+ && !properties.allocates+ && properties.reads.is_empty()+ && properties.writes.is_empty()+}++/// Which side's target dominates `block`, if one does.+fn side_of(dominators: &Dominators, split: &Split, block: BlockId) -> Option<usize> {+ (0..2).find(|side| dominators.dominates(split.sides[*side].1, block))+}++/// Whether `block` has the shape of `Split`, and its split if so.+fn find_split(graph: &Graph, dominators: &Dominators, block: BlockId) -> Option<Split> {+ let data = graph.block(block);+ if data.phis.is_empty() || data.is_loop_header || data.predecessors.len() != 2 || !dominators.is_reachable(block) {+ return None;+ }+ let movable = |body: &[NodeId]| body.iter().all(|node| is_movable(graph, *node));+ let branch_block = match graph.control(block).op {+ Op::Jump { target } if target.index() > block.index() => {+ let target_data = graph.block(target);+ if target_data.predecessors != [block] || !target_data.phis.is_empty() || target_data.is_loop_header {+ return None;+ }+ target+ }+ Op::Branch { .. } => block,+ _ => return None,+ };+ let branch_data = graph.block(branch_block);+ if !movable(&data.body) || (branch_block != block && !movable(&branch_data.body)) {+ return None;+ }+ let control = graph.control(branch_block);+ let Op::Branch {+ condition: BranchCondition::Bool,+ if_true,+ if_false,+ } = control.op+ else {+ return None;+ };+ let condition = control.inputs[0];+ if !data.phis.contains(&condition) {+ return None;+ }+ let mut sides = [None, None];+ for (predecessor, input) in data.predecessors.iter().zip(&graph.node(condition).inputs) {+ let side = match graph.constant_value(*input)? {+ 0 => 1,+ _ => 0,+ };+ if sides[side].is_some() {+ return None;+ }+ // NB: An edge is redirected by replacing its target, which must not also be the other edge of a branch.+ let control = graph.control(*predecessor);+ if !matches!(control.op, Op::Jump { .. } | Op::Branch { .. })+ || control+ .op+ .successors()+ .iter()+ .filter(|successor| **successor == block)+ .count()+ != 1+ {+ return None;+ }+ sides[side] = Some(*predecessor);+ }+ let targets = [if_true, if_false];+ if if_true == if_false {+ return None;+ }+ for target in targets {+ let target_data = graph.block(target);+ if target_data.predecessors != [branch_block]+ || !target_data.phis.is_empty()+ || target_data.is_loop_header+ || target.index() <= branch_block.index()+ {+ return None;+ }+ }+ let moved: Vec<NodeId> = if branch_block == block {+ data.body.clone()+ } else {+ data.body.iter().chain(&branch_data.body).copied().collect()+ };+ // NB: Refines must stay at the head of their block, so the copies of the moved nodes cannot go before one.+ let starts_with_refine = |target: BlockId| {+ graph+ .block(target)+ .body+ .first()+ .is_some_and(|node| matches!(graph.node(*node).op, Op::Refine { .. }))+ };+ if !moved.is_empty() && targets.into_iter().any(starts_with_refine) {+ return None;+ }+ Some(Split {+ block,+ branch_block,+ moved,+ sides: [(sides[0]?, targets[0]), (sides[1]?, targets[1])],+ })+}++/// The side of each frame state that a node or block of one side uses and+/// that holds one of the phis, or `None` if one of them cannot be renamed: a+/// node or block of another place uses it, or the phi is in a frame of its+/// chain other than its own, or in a virtual object.+fn frame_state_sides(+ graph: &Graph,+ dominators: &Dominators,+ split: &Split,+ phis: &BitSet,+) -> Option<Vec<(FrameStateId, usize)>> {+ let mut sides: Vec<(FrameStateId, usize)> = Vec::new();+ for (index, block) in graph.blocks.iter().enumerate() {+ let block_id = BlockId::from_index(index);+ if !dominators.is_reachable(block_id) || block_id == split.block || block_id == split.branch_block {+ continue;+ }+ // NB: Start frame states are renamed too: passes after this one still exit with them (see+ // `edit::frame_state_entering()`).+ let frame_states = block+ .nodes()+ .filter_map(|node| graph.node(node).frame_state)+ .chain(block.start_frame_state);+ for frame_state in frame_states {+ let holds_phi = |id| {+ graph+ .frame_state_values(id)+ .any(|(_, value)| phis.contains(value.index()))+ };+ if !holds_phi(frame_state) {+ continue;+ }+ let own_holds = graph+ .frame_state(frame_state)+ .values+ .iter()+ .any(|(_, value)| phis.contains(value.index()));+ let chain_holds = graph.frame_state_chain(frame_state)[1..].iter().any(|id| {+ graph+ .frame_state(*id)+ .values+ .iter()+ .any(|(_, value)| phis.contains(value.index()))+ });+ let all_count = graph.frame_state_values(frame_state).count();+ let chain_count: usize = graph+ .frame_state_chain(frame_state)+ .iter()+ .map(|id| graph.frame_state(*id).values.len())+ .sum();+ // NB: Virtual objects add values past those of the chain's frames.+ let virtual_holds = all_count != chain_count+ && graph+ .frame_state_values(frame_state)+ .skip(chain_count)+ .any(|(_, value)| phis.contains(value.index()));+ if !own_holds || chain_holds || virtual_holds {+ return None;+ }+ let side = side_of(dominators, split, block_id)?;+ match sides.iter().find(|(id, _)| *id == frame_state) {+ Some((_, existing)) if *existing != side => return None,+ Some(_) => {}+ None => sides.push((frame_state, side)),+ }+ }+ }+ Some(sides)+}++/// `value`, or what `renames` renames it to.+fn renamed(renames: &[(NodeId, NodeId)], value: NodeId) -> NodeId {+ renames+ .iter()+ .find(|(from, _)| *from == value)+ .map_or(value, |(_, to)| *to)+}++/// Splits one block, if any has the shape of `Split` and all uses of its+/// phis are on one side of its branch. Returns whether it split one.+fn split_one(graph: &mut Graph) -> bool {+ let dominators = Dominators::compute(graph);+ for index in 0..graph.blocks.len() {+ let Some(split) = find_split(graph, &dominators, BlockId::from_index(index)) else {+ continue;+ };+ let mut phis = BitSet::new(graph.nodes.len());+ for phi in &graph.block(split.block).phis {+ phis.insert(phi.index());+ }+ for node in &split.moved {+ phis.insert(node.index());+ }+ // Every use of a phi must be on one side. A phi's input is used at the end of its predecessor.+ let mut uses_ok = true;+ 'blocks: for (block_index, block) in graph.blocks.iter().enumerate() {+ let block_id = BlockId::from_index(block_index);+ if !dominators.is_reachable(block_id) || block_id == split.block || block_id == split.branch_block {+ continue;+ }+ for phi in &block.phis {+ for (predecessor, input) in block.predecessors.iter().zip(&graph.node(*phi).inputs) {+ if phis.contains(input.index()) && side_of(&dominators, &split, *predecessor).is_none() {+ uses_ok = false;+ break 'blocks;+ }+ }+ }+ let side = side_of(&dominators, &split, block_id);+ for node in block.body.iter().chain(block.control.iter()) {+ if graph+ .node(*node)+ .inputs+ .iter()+ .any(|input| phis.contains(input.index()))+ && side.is_none()+ {+ uses_ok = false;+ break 'blocks;+ }+ }+ }+ if !uses_ok {+ continue;+ }+ let Some(frame_state_sides) = frame_state_sides(graph, &dominators, &split, &phis) else {+ continue;+ };++ let block_phis = graph.block(split.block).phis.clone();+ let predecessors = graph.block(split.block).predecessors.clone();+ let mut renames: [Vec<(NodeId, NodeId)>; 2] = std::array::from_fn(|side| {+ let predecessor = split.sides[side].0;+ let index = predecessors+ .iter()+ .position(|block| *block == predecessor)+ .expect("the side's predecessor enters the block");+ block_phis+ .iter()+ .map(|phi| (*phi, graph.node(*phi).inputs[index]))+ .collect()+ });+ // Each side starts with copies of the moved nodes, with its values.+ for (side, side_renames) in renames.iter_mut().enumerate() {+ let target = split.sides[side].1;+ let mut copies = Vec::new();+ for moved in &split.moved {+ let mut node = graph.node(*moved).clone();+ for input in &mut node.inputs {+ *input = renamed(side_renames, *input);+ }+ node.frame_state = node.frame_state.map(|id| {+ let mut frame_state = graph.frame_state(id).clone();+ for (_, value) in &mut frame_state.values {+ *value = renamed(side_renames, *value);+ }+ graph.add_frame_state(frame_state)+ });+ let copy = graph.add_node(node);+ side_renames.push((*moved, copy));+ copies.push(copy);+ }+ let body = &mut graph.blocks[target.index()].body;+ copies.append(body);+ *body = copies;+ }+ let rename = |side: usize, value: NodeId| renamed(&renames[side], value);++ // Rename the uses of each side.+ for block_index in 0..graph.blocks.len() {+ let block_id = BlockId::from_index(block_index);+ if !dominators.is_reachable(block_id) || block_id == split.block || block_id == split.branch_block {+ continue;+ }+ let block = graph.block(block_id).clone();+ for phi in &block.phis {+ for (input_index, predecessor) in block.predecessors.iter().enumerate() {+ if let Some(side) = side_of(&dominators, &split, *predecessor) {+ let input = graph.nodes[phi.index()].inputs[input_index];+ graph.nodes[phi.index()].inputs[input_index] = rename(side, input);+ }+ }+ }+ if let Some(side) = side_of(&dominators, &split, block_id) {+ for node in block.body.iter().chain(block.control.iter()) {+ for input in &mut graph.nodes[node.index()].inputs {+ *input = rename(side, *input);+ }+ }+ }+ }+ for (frame_state, side) in frame_state_sides {+ for (_, value) in &mut graph.frame_states[frame_state.0 as usize].values {+ *value = rename(side, *value);+ }+ }++ // Each side's predecessor jumps straight to its target.+ for side in 0..2 {+ let (predecessor, target) = split.sides[side];+ graph.replace_successor(predecessor, split.block, target);+ graph.blocks[target.index()].predecessors = vec![predecessor];+ }+ graph.blocks[split.block.index()].predecessors.clear();+ for phi in block_phis {+ graph.nodes[phi.index()].inputs.clear();+ }+ super::edit::clean_up_control_flow(graph);+ return true;+ }+ false+}++pub fn run(graph: &mut Graph) {+ for _ in 0..graph.blocks.len() {+ if !split_one(graph) {+ break;+ }+ }+}diff --git a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs b/Libraries/LibJS/JIT/Rust/src/passes/mod.rsindex 25436d740dd..27f32a39f95 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/mod.rs@@ -15,6 +15,7 @@mod bounds_check_elimination;mod branch_fusion;+mod branch_splitting;mod check_elimination;mod dce;pub mod dominators;@@ -71,6 +72,10 @@ const PASSES: &[Pass] = &[name: "simplification",run: simplify::run,},+ Pass {+ name: "branch splitting",+ run: branch_splitting::run,+ },Pass {name: "global value numbering",run: gvn::run,diff --git a/Tests/LibJS/JIT/ir/for-in-keys.js b/Tests/LibJS/JIT/ir/for-in-keys.jsindex 818c9cc4c67..4309d2270f0 100644--- a/Tests/LibJS/JIT/ir/for-in-keys.js+++ b/Tests/LibJS/JIT/ir/for-in-keys.js@@ -1,7 +1,8 @@// The next key of a for-in loop is built as IR: while the property iterator// cache still holds the object's keys, the key at the cursor comes from the-// cache, and a cold block runs the slow path, whose outputs are SSA values,-// otherwise.+// cache, and the code exits otherwise. Each path then branches to its side of+// the loop's test of whether the keys are done, so the loop's body reads the+// key from the cache.function keys(o) {let s = "";@@ -17,6 +18,7 @@ jit.compile(keys);// CHECK: BranchObject ([[RECEIVER:v[0-9]+]])// CHECK: [[OBJECT:v[0-9]+]] = RefineObject ([[RECEIVER]])// CHECK-NEXT: BranchPropertyIteratorCacheValid ([[OBJECT]], [[CACHE:v[0-9]+]])+// CHECK: Exit SlowPath// CHECK: BranchNonNegativeInt32 ([[CURSOR:v[0-9]+]])// CHECK: [[REFINED:v[0-9]+]] = RefineNonNegativeInt32 ([[CURSOR]])// CHECK-NEXT: [[INDEX:v[0-9]+]]:int32 = UnboxInt32 ([[REFINED]])@@ -24,9 +26,11 @@ jit.compile(keys);// CHECK-NEXT: BranchInt32LessThan ([[INDEX]], [[COUNT]])// CHECK: [[IN_BOUNDS:v[0-9]+]]:int32 = RefineInt32LessThan ([[INDEX]], [[COUNT]])// CHECK-NEXT: LoadPropertyIteratorKey ([[CACHE]], [[IN_BOUNDS]])-// CHECK: [[CALL:v[0-9]+]] = CallSlowPath ObjectPropertyIteratorNext {{@[0-9]+}} ([[RECEIVER]], [[CACHE]], [[CURSOR]])-// CHECK-NEXT: SlowPathOutput 1 ([[CALL]])-// CHECK-NEXT: SlowPathOutput 2 ([[CALL]])+// CHECK-NOT: CallSlowPath ObjectPropertyIteratorNext+// CHECK-PASS: branch splitting+// CHECK: [[KEY:v[0-9]+]] = LoadPropertyIteratorKey+// CHECK-NOT: Phi ([[KEY]]+// CHECK: CallSlowPath Add {{@[0-9]+}} ({{v[0-9]+}}, [[KEY]])console.log(keys({ x: 1, y: 2 }));diff --git a/Tests/LibJS/JIT/programs/for-in-loops-that-change-their-objects.js b/Tests/LibJS/JIT/programs/for-in-loops-that-change-their-objects.jsnew file mode 100644index 00000000000..c2a8db86e32--- /dev/null+++ b/Tests/LibJS/JIT/programs/for-in-loops-that-change-their-objects.js@@ -0,0 +1,91 @@+// For-in loops exit where the property iterator cache stops holding their object's keys, and the keys their bodies+// read come straight from the cache. These loops change the shape of the object they iterate over while they run,+// leave early, nest, read keys after the loop, read keys of other objects, and iterate over objects with accessors,+// indices and dictionary shapes.+function keysAddingProperties(o) {+ let s = "";+ for (const k in o) {+ s += k;+ if (k === "b") o["added" + s.length] = 1;+ }+ return s;+}++function keysDeletingProperties(o) {+ let s = "";+ for (const k in o) {+ s += k + o[k];+ delete o.c;+ }+ return s;+}++function nested(a, b) {+ let n = 0;+ for (const x in a) for (const y in b) if (a.hasOwnProperty(x) && b[y] !== a[x]) n += x.length + y.length;+ return n;+}++function lastKey(o) {+ let last;+ for (var k in o) {+ if (k === "stop") break;+ last = k;+ }+ return [last, k];+}++function inherited(o) {+ let s = "";+ for (const k in o) s += k + (o.hasOwnProperty(k) ? "!" : "?") + o[k];+ return s;+}++function valuesHere(o, other) {+ let s = "";+ for (const k in o) s += k + o[k] + other[k] + o.hasOwnProperty(k) + other.hasOwnProperty(k) + ",";+ return s;+}++function withAccessors(i) {+ return {+ a: i,+ get b() {+ if (i % 4 === 0) delete this.c;+ else this.c = "set" + i;+ return "got";+ },+ c: 3,+ d: 4,+ };+}++function dictionary(i) {+ const o = { a: 1, b: 2, c: 3, d: i };+ delete o.b;+ o.e = 5;+ return o;+}++const proto = { p: 1 };+let out = [];+for (let i = 0; i < 300; i++) {+ out.push(keysAddingProperties({ a: 1, b: 2, c: 3 }));+ out.push(keysDeletingProperties({ a: 1, b: 2, c: 3, d: 4 }));+ out.push(nested({ a: 1, bb: 2 }, { a: 1, c: i }));+ out.push(lastKey(i % 3 ? { x: 1, y: 2 } : { x: 1, stop: 2, y: 3 }).join());+ const child = Object.create(proto);+ child.q = i;+ out.push(inherited(i % 2 ? child : { q: i }));+ const array = [i, 2, 3];+ array.x = "named";+ const others = [{ a: 9, b: 8, c: 7, d: 6 }, { d: 6, c: 7 }, withAccessors(i + 1), array, dictionary(i + 2)];+ const objects = [{ a: i, b: 2, c: 3, d: 4 }, withAccessors(i), array, dictionary(i), child];+ out.push(valuesHere(objects[i % objects.length], others[(i >> 2) % others.length]));+}+print(out.slice(0, 10).join("|"));+print(out.slice(-10).join("|"));+print(out.length);+let hash = 0;+for (const c of out.join("|")) hash = (hash * 31 + c.charCodeAt(0)) | 0;+print(hash);