Skip to content

Truly independent web browser

LibJS/JIT: Keep loop registers for the values loops use

Andreas Klingced813c5ee60
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/dominators.rs b/Libraries/LibJS/JIT/Rust/src/passes/dominators.rs
index f58124b7d05..bb245b716fa 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/dominators.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/dominators.rs
@@ -10,6 +10,7 @@
//! immediate dominator, and neither has a block reached from several
//! entries.
+use crate::bitset::BitSet;
use crate::ir::BlockId;
use crate::ir::Graph;
@@ -106,6 +107,23 @@ impl Dominators {
.collect()
}
+ /// The blocks of the loop that `header` heads, with back edges from
+ /// `back_edge_sources`: the header and every reachable block that reaches
+ /// one of them without going through it.
+ pub fn loop_blocks(&self, graph: &Graph, header: BlockId, back_edge_sources: &[BlockId]) -> BitSet {
+ let mut blocks = BitSet::new(graph.blocks.len());
+ blocks.insert(header.index());
+ let mut pending = back_edge_sources.to_vec();
+ while let Some(block) = pending.pop() {
+ if blocks.contains(block.index()) || !self.is_reachable(block) {
+ continue;
+ }
+ blocks.insert(block.index());
+ pending.extend(graph.block(block).predecessors.iter().copied());
+ }
+ blocks
+ }
+
/// Whether every iteration of a loop with back edges from
/// `back_edge_sources` that goes around runs `block`.
pub fn runs_every_iteration(&self, block: BlockId, back_edge_sources: &[BlockId]) -> bool {
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/licm.rs b/Libraries/LibJS/JIT/Rust/src/passes/licm.rs
index 2b3461ded5a..393128a2d39 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/licm.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/licm.rs
@@ -124,16 +124,7 @@ fn find_loops(graph: &Graph, dominators: &Dominators) -> Vec<Loop> {
if back_edge_sources.is_empty() {
continue;
}
- let mut blocks = BitSet::new(graph.blocks.len());
- blocks.insert(index);
- let mut pending = back_edge_sources.clone();
- while let Some(block) = pending.pop() {
- if blocks.contains(block.index()) {
- continue;
- }
- blocks.insert(block.index());
- pending.extend(graph.block(block).predecessors.iter().copied());
- }
+ let blocks = dominators.loop_blocks(graph, header, &back_edge_sources);
let entries = block
.predecessors
.iter()
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs
index ed77f754ec1..682e4b78e1a 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs
@@ -31,7 +31,8 @@ pub(super) struct ValueLiveness {
pub needs_spill: BitSet,
/// The position of each node in linear order.
pub positions: Vec<u32>,
- /// For each value, the positions of the nodes that use it as an input, in order.
+ /// For each value, the positions of the nodes that use it as an input, in order. A phi input is used at the
+ /// control node of its predecessor, where the moves into the phis are.
pub use_positions: Vec<Vec<u32>>,
}
@@ -130,6 +131,13 @@ impl ValueLiveness {
}
position += 1;
}
+ for successor in graph.successors(block) {
+ for (_, input) in phi_inputs_from(graph, block, successor) {
+ if is_allocated_value(graph, input) {
+ use_positions[input.index()].push(position - 1);
+ }
+ }
+ }
}
let block_ids = (0..block_count).map(BlockId::from_index).collect::<Vec<_>>();
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/loops.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/loops.rs
new file mode 100644
index 00000000000..6e3d0627109
--- /dev/null
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/loops.rs
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The loops of a graph as the register allocator sees them: which blocks
+//! each one runs, and which values it only carries through.
+//!
+//! Linear order does not keep a loop together (its exits may come before its
+//! back edges), so loops are sets of blocks. Their cold blocks are left out:
+//! those take values from where they are, and cost the loop nothing.
+
+use super::liveness::ValueLiveness;
+use crate::bitset::BitSet;
+use crate::ir::BlockId;
+use crate::ir::Graph;
+use crate::ir::NodeId;
+use crate::passes::dominators::Dominators;
+use crate::sparse_bitset::SparseBitSet;
+
+pub(super) struct Loop {
+ pub header: BlockId,
+ /// The blocks of the loop but the cold ones.
+ blocks: BitSet,
+ /// The first and last positions of its blocks.
+ pub start: u32,
+ end: u32,
+ /// The values live into the header that no node of the loop uses.
+ carried_through: SparseBitSet,
+}
+
+pub(super) struct Loops {
+ loops: Vec<Loop>,
+ /// The innermost loop around each block, as an index into `loops`.
+ innermost: Vec<Option<usize>>,
+ /// The block of each position.
+ position_blocks: Vec<u32>,
+}
+
+impl Loops {
+ pub fn compute(graph: &Graph, liveness: &ValueLiveness) -> Self {
+ let mut position_blocks = Vec::new();
+ for (index, block) in graph.blocks.iter().enumerate() {
+ position_blocks.extend(std::iter::repeat_n(index as u32, block.nodes().count()));
+ }
+ let mut loops = Vec::new();
+ let mut innermost = vec![None; graph.blocks.len()];
+ // NB: Cold blocks are left out of loops, so only the edges from hot blocks make loops. Cold blocks come after
+ // the hot ones, so their edges back into hot code would otherwise look like loops wherever they rejoin it.
+ let is_hot = |block: &BlockId| !graph.blocks[block.index()].is_cold;
+ let has_back_edges = graph.blocks.iter().enumerate().any(|(index, block)| {
+ block
+ .predecessors
+ .iter()
+ .any(|predecessor| predecessor.index() >= index && is_hot(predecessor))
+ });
+ if !has_back_edges {
+ return Self {
+ loops,
+ innermost,
+ position_blocks,
+ };
+ }
+
+ let dominators = Dominators::compute(graph);
+ for index in 0..graph.blocks.len() {
+ let header = BlockId::from_index(index);
+ let mut back_edge_sources = dominators.back_edge_sources(graph, header);
+ back_edge_sources.retain(is_hot);
+ if back_edge_sources.is_empty() {
+ continue;
+ }
+ let mut blocks = dominators.loop_blocks(graph, header, &back_edge_sources);
+ for block in blocks.iter().collect::<Vec<_>>() {
+ if graph.blocks[block].is_cold {
+ blocks.remove(block);
+ }
+ }
+ let position_of = |node: NodeId| liveness.positions[node.index()];
+ let start = position_of(graph.block_nodes(header).next().expect("blocks have a control node"));
+ let end = blocks
+ .iter()
+ .map(|block| position_of(graph.control_id(BlockId::from_index(block))))
+ .max()
+ .unwrap_or(start);
+ let mut loop_ = Loop {
+ header,
+ blocks,
+ start,
+ end,
+ carried_through: SparseBitSet::new(graph.nodes.len()),
+ };
+ for value in liveness.live_in[index].iter() {
+ let uses = &liveness.use_positions[value];
+ if loop_.first_use_in(uses, &position_blocks, 0..uses.len()).is_none() {
+ loop_.carried_through.insert(value);
+ }
+ }
+ loops.push(loop_);
+ }
+
+ // NB: A loop inside another one has fewer blocks, so the smallest loop around a block is the innermost one.
+ let mut order = (0..loops.len()).collect::<Vec<_>>();
+ order.sort_by_key(|index| std::cmp::Reverse(loops[*index].blocks.count()));
+ for index in order {
+ for block in loops[index].blocks.iter() {
+ innermost[block] = Some(index);
+ }
+ }
+ Self {
+ loops,
+ innermost,
+ position_blocks,
+ }
+ }
+
+ /// The innermost loop around the node at `position`.
+ pub fn innermost_at(&self, position: u32) -> Option<&Loop> {
+ let block = *self.position_blocks.get(position as usize)?;
+ self.innermost[block as usize].map(|index| &self.loops[index])
+ }
+
+ /// The loop that `header` heads, if it heads one.
+ pub fn headed_by(&self, header: BlockId) -> Option<&Loop> {
+ self.innermost[header.index()]
+ .map(|index| &self.loops[index])
+ .filter(|loop_| loop_.header == header)
+ }
+
+ /// The first of the use positions `uses[range]` (in order) that is in `loop_`.
+ pub fn first_use_in(&self, loop_: &Loop, uses: &[u32], range: std::ops::Range<usize>) -> Option<u32> {
+ loop_.first_use_in(uses, &self.position_blocks, range)
+ }
+}
+
+impl Loop {
+ /// Whether no node of the loop uses `value`, which is live into its header.
+ pub fn carries_through(&self, value: usize) -> bool {
+ self.carried_through.contains(value)
+ }
+
+ fn first_use_in(&self, uses: &[u32], position_blocks: &[u32], range: std::ops::Range<usize>) -> Option<u32> {
+ let uses = &uses[range];
+ let from = uses.partition_point(|position| *position < self.start);
+ let to = uses.partition_point(|position| *position <= self.end);
+ uses[from..to.max(from)]
+ .iter()
+ .copied()
+ .find(|position| self.blocks.contains(position_blocks[*position as usize] as usize))
+ }
+}
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
index a0577d3d62f..a18b10a3ae7 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
@@ -25,6 +25,11 @@
//! merges whose other predecessors do not jump to them start with every value
//! in its stack slot (see `liveness::state_predecessor()`).
//!
+//! Loops (see `loops`) keep their registers for what they use: a loop header
+//! leaves the values that the loop only carries through in their stack slots
+//! where they have them already, and inside a loop, the values it reads again
+//! in its next iteration are evicted after those used only after it.
+//!
//! Cold blocks (see `Block::is_cold`) come last in linear order and cost the
//! other blocks nothing: they start with the register state of the block
//! they branch off from, and move their values into place where they rejoin
@@ -40,6 +45,7 @@
mod coalescing;
mod liveness;
+mod loops;
mod moves;
mod verify;
@@ -57,6 +63,7 @@ use crate::ir::Op;
use liveness::ValueLiveness;
use liveness::is_allocated_value;
use liveness::state_predecessor;
+use loops::Loops;
/// The number of the first floating point register in `Location`s and
/// `RegisterMask`s: floating point register `n` is register `FPR_BASE + n`.
@@ -508,6 +515,7 @@ struct Allocator<'a> {
/// slot of each class that has one.
slot_classes: Vec<u32>,
class_slots: Vec<Option<u32>>,
+ loops: Loops,
}
impl<'a> Allocator<'a> {
@@ -516,6 +524,7 @@ impl<'a> Allocator<'a> {
assert!(!registers.allocatable_gprs.contains(registers.scratch_gpr));
let liveness = ValueLiveness::compute(graph);
let slot_classes = coalescing::spill_slot_classes(graph, &liveness);
+ let loops = Loops::compute(graph, &liveness);
Self {
graph,
registers,
@@ -532,6 +541,7 @@ impl<'a> Allocator<'a> {
position: 0,
slot_classes,
class_slots: vec![None; graph.nodes.len()],
+ loops,
}
}
@@ -668,12 +678,26 @@ impl<'a> Allocator<'a> {
contents
}
+ /// Whether the loop with the header `block`, if it is one, leaves `value` in its stack slot: a value that has one
+ /// from its definition on and that the loop only carries through, so that its register is free for the loop.
+ fn loop_leaves_in_stack(&self, block: BlockId, value: NodeId) -> bool {
+ self.loops
+ .headed_by(block)
+ .is_some_and(|loop_| loop_.carries_through(value.index()))
+ && self.liveness.needs_spill.contains(value.index())
+ }
+
/// The register contents a merge with a state predecessor starts with:
- /// those at the end of that predecessor, live into the merge, and the
- /// phis in their registers.
+ /// those at the end of that predecessor, live into the merge (but those
+ /// a loop leaves in their stack slots), and the phis in their registers.
fn merge_contents(&self, block: BlockId) -> Option<Vec<Option<NodeId>>> {
let predecessor = state_predecessor(self.graph, block)?;
let mut contents = self.contents_entering(predecessor, block);
+ for value in &mut contents {
+ if value.is_some_and(|value| self.loop_leaves_in_stack(block, value)) {
+ *value = None;
+ }
+ }
for phi in &self.graph.block(block).phis {
if let Some(Location::Register(register)) = self.allocation.nodes[phi.index()].output {
debug_assert!(contents[register as usize].is_none());
@@ -736,10 +760,25 @@ impl<'a> Allocator<'a> {
}
}
- fn next_use(&self, value: NodeId) -> u32 {
+ /// How soon `value` is needed again, as a key that orders the values by it (smaller is sooner). Inside a loop,
+ /// the uses later in the iteration come first, then the values the next iteration reads (live into the loop and
+ /// used in it before here), in the order it reads them, then the values used after the loop.
+ fn next_use(&self, value: NodeId) -> (u8, u32) {
let uses = &self.liveness.use_positions[value.index()];
let index = uses.partition_point(|position| *position <= self.position);
- uses.get(index).copied().unwrap_or(u32::MAX)
+ let next = uses.get(index).copied();
+ let Some(loop_) = self.loops.innermost_at(self.position) else {
+ return next.map_or((3, 0), |position| (0, position));
+ };
+ if let Some(position) = self.loops.first_use_in(loop_, uses, index..uses.len()) {
+ return (0, position);
+ }
+ if self.liveness.live_in[loop_.header.index()].contains(value.index())
+ && let Some(position) = self.loops.first_use_in(loop_, uses, 0..index)
+ {
+ return (1, position - loop_.start);
+ }
+ next.map_or((3, 0), |position| (2, position))
}
/// A register of `class` that is not `blocked`, freeing one if necessary
@@ -963,7 +1002,7 @@ impl<'a> Allocator<'a> {
let live_in = &self.liveness.live_in[join.index()];
let mut taken = RegisterMask::default();
for (register, value) in self.contents.iter().enumerate() {
- if value.is_some_and(|value| live_in.contains(value.index())) {
+ if value.is_some_and(|value| live_in.contains(value.index()) && !self.loop_leaves_in_stack(join, value)) {
taken = taken.with(u8::try_from(register).expect("register numbers fit in u8"));
}
}
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
index c8c093302ab..d3c61d3ae1e 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
@@ -374,6 +374,105 @@ fn loop_phis_share_spill_slots_with_their_inputs() {
assert!(filled > 0, "{}", dump_allocation(&graph, &allocation));
}
+#[test]
+fn loops_leave_the_values_they_only_carry_through_in_their_stack_slots() {
+ // r(5) to r(9) are live across the call, back in registers before the loop and used only after it. With them in
+ // registers, the six registers would not hold the counter, the bound and `last` as well. The loop leaves them in
+ // their stack slots, so that its back edge neither reloads them nor stores the counter. r(11) is live across the
+ // call too, and the loop only uses it as the input of `last`'s phi: it keeps its register.
+ let layout = FrameLayout {
+ number_of_registers: 16,
+ registers_and_locals_count: 18,
+ number_of_constants: 0,
+ number_of_arguments: 1,
+ };
+ let r = Operand::from_raw;
+ let (counter, last, argument) = (Operand::from_raw(16), Operand::from_raw(17), Operand::from_raw(18));
+ let xor = |arith_feedback, dst, lhs, rhs| Instruction::BitwiseXor {
+ arith_feedback,
+ dst,
+ lhs,
+ rhs,
+ };
+ let program = assemble(|label| {
+ vec![
+ Instruction::Enter,
+ xor(0, r(5), argument, argument),
+ xor(1, r(6), r(5), argument),
+ xor(2, r(7), r(6), argument),
+ xor(3, r(8), r(7), argument),
+ xor(4, r(9), r(8), argument),
+ xor(14, r(11), r(9), argument),
+ Instruction::Call {
+ value_feedback: 0,
+ call_feedback: 0,
+ dst: r(14),
+ callee: r(15),
+ this_value: r(15),
+ argument_count: 0,
+ expression_string: None,
+ arguments: vec![],
+ },
+ xor(5, r(10), r(5), r(6)),
+ xor(6, r(12), r(7), r(11)),
+ Instruction::Mov {
+ dst: counter,
+ src: r(10),
+ },
+ Instruction::Mov { dst: last, src: r(5) },
+ Instruction::JumpLessThan {
+ arith_feedback: 8,
+ lhs: counter,
+ rhs: r(12),
+ true_target: label(13),
+ false_target: label(16),
+ },
+ Instruction::Increment {
+ arith_feedback: 9,
+ dst: counter,
+ },
+ Instruction::Mov { dst: last, src: r(11) },
+ Instruction::Jump { target: label(12) },
+ xor(10, r(13), r(5), r(6)),
+ xor(11, r(13), r(13), r(7)),
+ xor(12, r(13), r(13), r(8)),
+ xor(13, r(13), r(13), r(9)),
+ xor(15, r(13), r(13), last),
+ Instruction::Return { value: r(13) },
+ ]
+ });
+ let mut snapshot = crate::builder::tests::snapshot_for(&program, layout);
+ snapshot.executables[0].feedback.arith = vec![crate::snapshot::arith_feedback::INT32; 16];
+ let graph = crate::builder::tests::optimized_graph(&snapshot);
+ let allocation = allocate_and_verify(&graph);
+ let header = graph.blocks.iter().position(|block| block.is_loop_header).unwrap();
+ assert_eq!(
+ graph.blocks[header].phis.len(),
+ 2,
+ "{}",
+ dump_allocation(&graph, &allocation)
+ );
+ let back_edge = *graph.blocks[header]
+ .predecessors
+ .iter()
+ .find(|predecessor| predecessor.index() > header)
+ .unwrap();
+ assert!(
+ allocation.block_end_moves[back_edge.index()]
+ .iter()
+ .all(|m| !matches!(m.from, Location::Stack(_)) && !matches!(m.to, Location::Stack(_))),
+ "{}",
+ dump_allocation(&graph, &allocation)
+ );
+ for phi in &graph.blocks[header].phis {
+ assert!(
+ matches!(allocation.node(*phi).output, Some(Location::Register(_))),
+ "{}",
+ dump_allocation(&graph, &allocation)
+ );
+ }
+}
+
#[test]
fn int32_operations_write_over_their_first_input_where_it_dies() {
// The first XOR's value dies at the second, whose output then takes its