Truly independent web browser
LibJS/JIT: Find where values are live with one walk for each value
Andreas Kling620f6de4d6ba
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex 3b7246f0ea8..90b2f69dd17 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -416,17 +416,22 @@ struct LeaveStub {leave_arguments: Vec<(u32, bool)>,}-/// Generates code for `graph` with `allocation`, whose registers came from+/// Generates code for `graph` with the register allocation in `scratch`, whose registers came from/// `target_registers::<M>()`, and writes the sites of the code into the/// tables of `scratch`. With `verify` (and in debug builds), checks that/// every lowering matches its `lowering_info()`.pub fn generate<M: PortableMacroAssembler>(graph: &Graph,- allocation: &Allocation,snapshot: &Snapshot,verify: bool,scratch: &mut Scratch,) -> Result<GeneratedCode, CompileFailure> {+ let Scratch {+ artifact,+ sites,+ regalloc,+ } = scratch;+ let allocation = ®alloc.allocation;let (_, pinned) = target_registers::<M>();let (gpr_dump_count, fpr_dump_count) = register_dump_counts::<M>();let mut masm = M::new();@@ -500,12 +505,10 @@ pub fn generate<M: PortableMacroAssembler>(panic!("lowerings that do not match their declarations:\n{errors}");}- scratch.artifact.clear();- scratch.sites.begin(graph)?;+ artifact.clear();+ sites.begin(graph)?;for (node, kind) in &codegen.sites {- codegen.with_site_source(*node, *kind, |site| {- site.write(&mut scratch.sites, &mut scratch.artifact)- })?;+ codegen.with_site_source(*node, *kind, |site| site.write(sites, artifact))?;}let annotations = std::mem::take(&mut codegen.annotations);let invalidation_patches = codegen@@ -659,7 +662,7 @@ fn fused_probe_branch(graph: &Graph, allocation: &Allocation, block: BlockId) ->) => (*if_false, *if_true),_ => return None,};- (!allocation.live_in[failure.index()].contains(probe.index())).then_some((control, failure, success))+ (!allocation.is_live_in(failure, probe)).then_some((control, failure, success))}/// Where control that goes to each block lands: blocks that only jump on, like the edges the builder splits offdiff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rsindex ee020bbe118..e4b7bbddebb 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs@@ -1420,6 +1420,32 @@ impl Op {}}+ /// Calls `visit` with each block a control node can continue at, in the order of `successors()`.+ pub fn for_each_successor(&self, mut visit: impl FnMut(BlockId)) {+ match self {+ Op::Jump { target } => visit(*target),+ Op::Branch { if_true, if_false, .. } | Op::BranchOnPc { if_true, if_false, .. } => {+ visit(*if_true);+ visit(*if_false);+ }+ Op::BranchTruthy {+ if_true,+ if_false,+ fallback,+ } => {+ visit(*if_true);+ visit(*if_false);+ visit(*fallback);+ }+ Op::ShapeSwitch { cases } => {+ for (_, block) in cases {+ visit(*block);+ }+ }+ _ => {}+ }+ }+fn successors_mut(&mut self) -> Vec<&mut BlockId> {match self {Op::Jump { target } => vec![target],diff --git a/Libraries/LibJS/JIT/Rust/src/lib.rs b/Libraries/LibJS/JIT/Rust/src/lib.rsindex ffbc1481cc4..9b029ece52c 100644--- a/Libraries/LibJS/JIT/Rust/src/lib.rs+++ b/Libraries/LibJS/JIT/Rust/src/lib.rs@@ -29,6 +29,7 @@ pub mod regalloc;pub mod scratch;pub mod snapshot;pub mod sparse_bitset;+pub mod tables;// NB: The tests get their memory on Windows from `ak::windows_code_memory`, which is for x86-64.#[cfg(all(test, windows, not(target_arch = "x86_64")))]@@ -127,16 +128,16 @@ fn compile_into<M: asm::PortableMacroAssembler>(if snapshot.options.stress.few_registers {registers.allocatable_gprs = registers.few_registers(STRESS_EXTRA_REGISTERS);}- let allocation = regalloc::allocate(&graph, ®isters);+ regalloc::allocate(&graph, ®isters, &mut scratch.regalloc)?;if snapshot.options.verify_ir- && let Err(errors) = regalloc::verify(&graph, ®isters, &allocation)+ && let Err(errors) = regalloc::verify(&graph, ®isters, &scratch.regalloc.allocation){panic!("invalid register allocation:\n{errors}\n{}",- regalloc::dump_allocation(&graph, &allocation)+ regalloc::dump_allocation(&graph, &scratch.regalloc.allocation));}- let mut generated = codegen::generate::<M>(&graph, &allocation, snapshot, snapshot.options.verify_ir, scratch)?;+ let mut generated = codegen::generate::<M>(&graph, snapshot, snapshot.options.verify_ir, scratch)?;generated.osr_entries.sort_unstable();let layout = scratch.artifact.finish(&Tail {@@ -157,7 +158,7 @@ fn compile_into<M: asm::PortableMacroAssembler>(let mut text = pass_dumps.unwrap_or_default();if snapshot.options.dump_ir {text.push_str(&ir::dump(&graph, &executable.layout));- text.push_str(®alloc::dump_allocation(&graph, &allocation));+ text.push_str(®alloc::dump_allocation(&graph, &scratch.regalloc.allocation));}if snapshot.options.dump_asm {text.push_str(&codegen::dump_code(diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rsindex 4da925cc752..5ef0d062523 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rs@@ -18,6 +18,7 @@use super::liveness::ValueLiveness;use super::liveness::is_allocated_value;+use crate::ir::BlockId;use crate::ir::Graph;use crate::ir::NodeId;@@ -45,7 +46,8 @@ impl Interference<'_> {fn is_live_after_definition_of(&self, value: NodeId, defined: NodeId) -> bool {let at = self.definitions[defined.index()];let of_value = self.definitions[value.index()];- let available = self.liveness.live_in[at.block].contains(value.index())+ let at_block = BlockId::from_index(at.block);+ let available = self.liveness.is_live_in(at_block, value)|| (of_value.block == at.block&& match (of_value.position, at.position) {(None, _) => true,@@ -69,7 +71,7 @@ impl Interference<'_> {.any(|(_, frame_value)| frame_value == value)})};- self.liveness.live_out[at.block].contains(value.index())+ self.liveness.is_live_out(at_block, value)|| self.deaths[value.index()].iter().any(|(block, death)| {*block == at.block && (*death > position || (*death == position && read_after_definition()))})@@ -109,7 +111,7 @@ pub(super) fn spill_slot_classes(graph: &Graph, liveness: &ValueLiveness) -> Vecblock: index,position: Some(position),};- for value in &liveness.dies_at[node.index()] {+ for value in liveness.dies_at(*node) {deaths[value.index()].push((index, position));}}diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rsindex ef4451506f7..d6b8717f521 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs@@ -10,32 +10,82 @@//! used by a frame state is live at the node carrying it; for calls, frame//! state uses happen after the call returns.-use crate::bitset::BitSet;+use ak::Column;+use ak::ColumnFull;+use crate::codegen::lowering_info::Clobbers as LoweringClobbers;use crate::codegen::lowering_info::lowering_info;use crate::ir::BlockId;+use crate::ir::FrameStateId;use crate::ir::Graph;use crate::ir::NodeId;use crate::ir::Op;-use crate::sparse_bitset::SparseBitSet;-use std::cell::OnceCell;+use crate::tables::Lists;+use crate::tables::Run;+use crate::tables::pop;+use crate::tables::release;+use crate::tables::reset;++/// A value that nobody uses.+const DEAD_OUTPUT: u8 = 1 << 0;+/// A value that must have a stack slot that holds it from its definition on.+const NEEDS_SPILL: u8 = 1 << 1;++/// In place of the frame state uses of a frame state: they are not listed yet.+const NOT_LISTED: Run = Run::NOT_WRITTEN;+/// The liveness of the values of a graph, in tables that serve one compile after the other.+///+/// No table here is a set that grows. A graph in SSA form makes that possible: a value is live into exactly the blocks+/// that a walk up from its uses passes before it reaches the block of its definition, so one walk for each value+/// gives all the blocks at one time. The values are walked in the order of their indices, so the list of the values+/// that are live into a block is sorted as it is written.pub(super) struct ValueLiveness {- pub live_in: Vec<SparseBitSet>,- pub live_out: Vec<SparseBitSet>,- /// For each node, the values whose last use (on this path) it is.- pub dies_at: Vec<Vec<NodeId>>,- /// Values nobody uses.- pub dead_outputs: BitSet,- /// Values that must have a stack slot holding them from their definition- /// on: those live across a call and those live into a loop header (or a- /// merge without a state predecessor).- pub needs_spill: BitSet,+ /// The values live into each block and out of each block, sorted.+ pub live_in: Lists<NodeId>,+ live_out: Lists<NodeId>,+ /// For each node, the values whose last use (on this path) it is, as a part of `dying`.+ deaths: Column<Run>,+ dying: Column<NodeId>,+ /// For each value, `DEAD_OUTPUT` and `NEEDS_SPILL`.+ flags: Column<u8>,/// 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. 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>>,+ pub positions: Column<u32>,+ /// For each value, the positions of the nodes that use it as an input, in order, as a part of `uses`. A phi input+ /// is used at the control node of its predecessor, where the moves into the phis are.+ use_runs: Column<Run>,+ uses: Column<u32>,+ /// The blocks each block continues at.+ pub successors: Lists<BlockId>,++ // NB: Only compute() reads what is below.+ /// The block of each node.+ blocks: Column<u32>,+ /// The uses of values as inputs, as the value in the high half and the position in the low half.+ use_pairs: Column<u64>,+ /// Where the walks up start: the value in the high half, then the block, then whether the value is only known to+ /// flow out of the block (to a phi) in the lowest bit.+ seeds: Column<u64>,+ /// For each block, the value (plus one) that was last found live into it and out of it.+ in_marks: Column<u32>,+ out_marks: Column<u32>,+ /// The blocks a walk up has still to pass.+ pending: Column<u32>,+ /// What the walks found: the block in the high half and the value in the low half, in the order of the values.+ in_pairs: Column<u64>,+ out_pairs: Column<u64>,+ /// For each frame state, the allocated values that a node uses through it, as a part of `frame_uses`.+ frame_runs: Column<Run>,+ frame_uses: Column<NodeId>,+ /// For each value, the block (plus one) whose backwards walk has it live at the place it is at.+ live: Column<u32>,+ /// The values that were live at some place of the block that is walked.+ touched: Column<NodeId>,+ /// The values the node that is walked uses.+ used: Column<NodeId>,+ /// For each value, the node (plus one) that was last noted as its death.+ last_death: Column<u32>,+ live_since: Column<Option<(BlockId, Clobbers)>>,}/// Whether a node is a value the register allocator tracks.@@ -44,26 +94,6 @@ pub(super) fn is_allocated_value(graph: &Graph, node: NodeId) -> bool {node.repr.is_some() && !matches!(node.op, Op::Constant(_) | Op::VirtualObject { .. })}-/// The allocated values a node uses through its frame state, cached for both walks.-fn cached_frame_state_uses<'a>(- graph: &'a Graph,- frames: &'a [OnceCell<Vec<NodeId>>],- node: NodeId,-) -> impl Iterator<Item = NodeId> + 'a {- graph.node(node).frame_state.into_iter().flat_map(move |frame| {- frames[frame.index()]- .get_or_init(|| {- graph- .frame_state_values(frame)- .map(|(_, value)| value)- .filter(|value| is_allocated_value(graph, *value))- .collect()- })- .iter()- .copied()- })-}-/// For a merge or a loop header: the predecessor whose register state the/// block starts with, the first one in linear order, which comes before it./// Every other predecessor (another one before it, a cold one or a back@@ -117,227 +147,414 @@ struct Clobbers {float_clobbers: u32,}+fn pair(high: u32, low: u32) -> u64 {+ u64::from(high) << 32 | u64::from(low)+}++fn high(pair: u64) -> u32 {+ (pair >> 32) as u32+}++fn low(pair: u64) -> u32 {+ pair as u32+}+impl ValueLiveness {- pub fn compute(graph: &Graph) -> Self {+ // NB: A compile whose graph has more nodes or blocks, or more of what the columns hold, fails.+ const MAX_NODES: usize = 1 << 24;+ const MAX_BLOCKS: usize = 1 << 24;+ const MAX_ITEMS: usize = 1 << 26;++ /// A table for the values live into each block, with no values.+ pub fn new_live_in() -> Lists<NodeId> {+ Lists::new(Self::MAX_BLOCKS, Self::MAX_ITEMS, c"JIT live values")+ }++ pub fn new() -> Self {+ fn by_node<T: Copy>() -> Column<T> {+ Column::new(ValueLiveness::MAX_NODES, c"JIT liveness of nodes")+ }+ fn by_block<T: Copy>() -> Column<T> {+ Column::new(ValueLiveness::MAX_BLOCKS, c"JIT liveness of blocks")+ }+ Self {+ live_in: Self::new_live_in(),+ live_out: Self::new_live_in(),+ deaths: by_node(),+ dying: Column::new(Self::MAX_ITEMS, c"JIT liveness lists"),+ flags: by_node(),+ positions: by_node(),+ use_runs: by_node(),+ uses: Column::new(Self::MAX_ITEMS, c"JIT liveness lists"),+ successors: Lists::new(Self::MAX_BLOCKS, Self::MAX_ITEMS, c"JIT block successors"),+ blocks: by_node(),+ use_pairs: Column::new(Self::MAX_ITEMS, c"JIT liveness work"),+ seeds: Column::new(Self::MAX_ITEMS, c"JIT liveness work"),+ in_marks: by_block(),+ out_marks: by_block(),+ pending: by_block(),+ in_pairs: Column::new(Self::MAX_ITEMS, c"JIT liveness work"),+ out_pairs: Column::new(Self::MAX_ITEMS, c"JIT liveness work"),+ frame_runs: Column::new(Self::MAX_NODES, c"JIT liveness lists"),+ frame_uses: Column::new(Self::MAX_ITEMS, c"JIT liveness lists"),+ live: by_node(),+ touched: Column::new(Self::MAX_ITEMS, c"JIT liveness work"),+ used: Column::new(Self::MAX_ITEMS, c"JIT liveness work"),+ last_death: by_node(),+ live_since: by_node(),+ }+ }++ /// Drops the tables and gives their memory back to the system.+ pub fn release_memory(&mut self) {+ self.live_in.release_memory();+ self.live_out.release_memory();+ release(&mut self.deaths);+ release(&mut self.dying);+ release(&mut self.flags);+ release(&mut self.positions);+ release(&mut self.use_runs);+ release(&mut self.uses);+ self.successors.release_memory();+ release(&mut self.blocks);+ release(&mut self.use_pairs);+ release(&mut self.seeds);+ release(&mut self.in_marks);+ release(&mut self.out_marks);+ release(&mut self.pending);+ release(&mut self.in_pairs);+ release(&mut self.out_pairs);+ release(&mut self.frame_runs);+ release(&mut self.frame_uses);+ release(&mut self.live);+ release(&mut self.touched);+ release(&mut self.used);+ release(&mut self.last_death);+ release(&mut self.live_since);+ }++ pub fn is_live_in(&self, block: BlockId, value: NodeId) -> bool {+ self.live_in.get(block.index()).binary_search(&value).is_ok()+ }++ pub fn is_live_out(&self, block: BlockId, value: NodeId) -> bool {+ self.live_out.get(block.index()).binary_search(&value).is_ok()+ }++ /// The values whose last use (on this path) `node` is.+ pub fn dies_at(&self, node: NodeId) -> &[NodeId] {+ &self.dying[self.deaths[node.index()].range()]+ }++ /// Whether nobody uses `value`.+ pub fn is_dead_output(&self, value: NodeId) -> bool {+ self.flags[value.index()] & DEAD_OUTPUT != 0+ }++ /// Whether `value` must have a stack slot that holds it from its definition on: a value that is live across a+ /// call, or live into a loop header (or a merge without a state predecessor).+ pub fn needs_spill(&self, value: NodeId) -> bool {+ self.flags[value.index()] & NEEDS_SPILL != 0+ }++ /// The positions of the nodes that use `value` as an input, in order.+ pub fn use_positions(&self, value: NodeId) -> &[u32] {+ &self.uses[self.use_runs[value.index()].range()]+ }++ /// Lists the allocated values of the frame state `frame`, if they are not listed yet.+ fn list_frame_uses(&mut self, graph: &Graph, frame: FrameStateId) -> Result<(), ColumnFull> {+ if self.frame_runs[frame.index()] != NOT_LISTED {+ return Ok(());+ }+ let start = self.frame_uses.len();+ for (_, value) in graph.frame_state_values(frame) {+ if is_allocated_value(graph, value) {+ self.frame_uses.try_push(value)?;+ }+ }+ self.frame_runs[frame.index()] = Run::new(start, self.frame_uses.len());+ Ok(())+ }++ /// Notes that `value` is used in `block`, at a node or (`flows_out`) by a phi of a block that `block` continues+ /// at.+ fn add_seed(&mut self, value: NodeId, block: usize, flows_out: bool) -> Result<(), ColumnFull> {+ // NB: A use in the block of the definition makes the value live into no block.+ if !flows_out && self.blocks[value.index()] as usize == block {+ return Ok(());+ }+ self.seeds+ .try_push(pair(value.0, (block as u32) << 1 | u32::from(flows_out)))+ }++ pub fn compute(&mut self, graph: &Graph) -> Result<(), ColumnFull> {let value_count = graph.nodes.len();let block_count = graph.blocks.len();- // NB: Both backwards walks and spill analysis use these immutable- // dependencies. Flatten each referenced frame only once.- let frames = (0..graph.frame_states.len())- .map(|_| OnceCell::new())- .collect::<Vec<_>>();-- let mut positions = vec![0; value_count];- let mut use_positions = vec![Vec::new(); value_count];++ reset(&mut self.positions, value_count, 0)?;+ reset(&mut self.blocks, value_count, 0)?;+ reset(&mut self.frame_runs, graph.frame_states.len(), NOT_LISTED)?;+ self.frame_uses.clear();+ self.successors.begin()?;let mut position = 0;- for block in 0..block_count {- let block = BlockId::from_index(block);- for node in graph.block_nodes(block) {- positions[node.index()] = position;- for input in &graph.node(node).inputs {- if graph.node(node).op != Op::Phi && is_allocated_value(graph, *input) {- use_positions[input.index()].push(position);+ for (index, block) in graph.blocks.iter().enumerate() {+ for node in block.nodes() {+ self.positions[node.index()] = position;+ self.blocks[node.index()] = index as u32;+ position += 1;+ }+ let mut result = Ok(());+ graph+ .control(BlockId::from_index(index))+ .op+ .for_each_successor(|successor| {+ if result.is_ok() {+ result = self.successors.try_push(successor);+ }+ });+ result?;+ self.successors.end_list()?;+ }++ // The uses of each value: where it is an input, and the blocks it is used in that are not its own.+ self.use_pairs.clear();+ self.seeds.clear();+ for (index, block) in graph.blocks.iter().enumerate() {+ for node_id in block.body.iter().chain(&block.control) {+ let node = graph.node(*node_id);+ let position = self.positions[node_id.index()];+ for input in &node.inputs {+ if is_allocated_value(graph, *input) {+ self.use_pairs.try_push(pair(input.0, position))?;+ self.add_seed(*input, index, false)?;+ }+ }+ if let Some(frame) = node.frame_state {+ self.list_frame_uses(graph, frame)?;+ for use_index in self.frame_runs[frame.index()].range() {+ self.add_seed(self.frame_uses[use_index], index, false)?;}}- position += 1;}- for successor in graph.successors(block) {- for (_, input) in phi_inputs_from(graph, block, successor) {+ let block_id = BlockId::from_index(index);+ let end = self.positions[graph.control_id(block_id).index()];+ for successor_index in 0..self.successors.get(index).len() {+ let successor = self.successors.get(index)[successor_index];+ for (_, input) in phi_inputs_from(graph, block_id, successor) {if is_allocated_value(graph, input) {- use_positions[input.index()].push(position - 1);+ self.use_pairs.try_push(pair(input.0, end))?;+ self.add_seed(input, index, true)?;}}}}- let block_ids = (0..block_count).map(BlockId::from_index).collect::<Vec<_>>();- // What each block uses before defining it, and what it defines, so- // that the dataflow below only combines sets.- let mut used_before_defined = Vec::with_capacity(block_count);- let mut defined = Vec::with_capacity(block_count);- let mut used = Vec::new();- for block in &block_ids {- let mut live = SparseBitSet::new(value_count);- Self::transfer_block(graph, &frames, *block, &mut live, &mut used, |_, _, _| {});- used_before_defined.push(live);- let mut nodes = SparseBitSet::new(value_count);- for node in graph.block_nodes(*block) {- nodes.insert(node.index());+ reset(&mut self.use_runs, value_count, Run::default())?;+ self.uses.clear();+ self.use_pairs.sort_unstable();+ let mut index = 0;+ while index < self.use_pairs.len() {+ let value = high(self.use_pairs[index]);+ let start = index;+ while index < self.use_pairs.len() && high(self.use_pairs[index]) == value {+ self.uses.try_push(low(self.use_pairs[index]))?;+ index += 1;}- defined.push(nodes);+ self.use_runs[value as usize] = Run::new(start, index);}- // The inputs of the phis of each block's successors that flow in- // from it.- let phi_inputs = block_ids- .iter()- .map(|block| {- graph- .successors(*block)- .into_iter()- .flat_map(|successor| phi_inputs_from(graph, *block, successor))- .map(|(_, input)| input)- .filter(|input| is_allocated_value(graph, *input))- .collect::<Vec<_>>()- })- .collect::<Vec<_>>();-- let mut live_in = vec![SparseBitSet::new(value_count); block_count];- let mut live_out = vec![SparseBitSet::new(value_count); block_count];- let mut entering = SparseBitSet::new(value_count);- // Visit backwards initially, then only revisit predecessors whose- // successor's live-in set changed. Acyclic regions need one visit.- let mut worklist = block_ids.clone();- let mut queued = vec![true; block_count];- while let Some(block) = worklist.pop() {- queued[block.index()] = false;- let live = &mut live_out[block.index()];- for successor in graph.successors(block) {- live.union_with(&live_in[successor.index()]);- }- for input in &phi_inputs[block.index()] {- live.insert(input.index());++ // Walk up from the uses of each value, as far as the block of its definition.+ reset(&mut self.in_marks, block_count, 0)?;+ reset(&mut self.out_marks, block_count, 0)?;+ self.in_pairs.clear();+ self.out_pairs.clear();+ self.seeds.sort_unstable();+ let mut index = 0;+ while index < self.seeds.len() {+ let value = high(self.seeds[index]);+ let mark = value + 1;+ let definition = self.blocks[value as usize];+ self.pending.clear();+ while index < self.seeds.len() && high(self.seeds[index]) == value {+ let seed = low(self.seeds[index]);+ let (block, flows_out) = (seed >> 1, seed & 1 != 0);+ index += 1;+ if flows_out {+ if self.out_marks[block as usize] != mark {+ self.out_marks[block as usize] = mark;+ self.out_pairs.try_push(pair(block, value))?;+ }+ if block == definition {+ continue;+ }+ }+ if self.in_marks[block as usize] != mark {+ self.in_marks[block as usize] = mark;+ self.in_pairs.try_push(pair(block, value))?;+ self.pending.try_push(block)?;+ }}- entering.clone_from(live);- entering.subtract(&defined[block.index()]);- entering.union_with(&used_before_defined[block.index()]);- if live_in[block.index()].union_with(&entering) {- for predecessor in &graph.block(block).predecessors {- if !queued[predecessor.index()] {- queued[predecessor.index()] = true;- worklist.push(*predecessor);+ while let Some(block) = pop(&mut self.pending) {+ for predecessor in &graph.blocks[block as usize].predecessors {+ let predecessor = predecessor.0;+ if self.out_marks[predecessor as usize] != mark {+ self.out_marks[predecessor as usize] = mark;+ self.out_pairs.try_push(pair(predecessor, value))?;+ }+ if predecessor != definition && self.in_marks[predecessor as usize] != mark {+ self.in_marks[predecessor as usize] = mark;+ self.in_pairs.try_push(pair(predecessor, value))?;+ self.pending.try_push(predecessor)?;}}}}+ // NB: The pairs are in the order of the values, so the list of each block comes out sorted.+ fn lists_of_blocks(lists: &mut Lists<NodeId>, pairs: &[u64], block_count: usize) -> Result<(), ColumnFull> {+ lists.begin_counts(block_count)?;+ for pair in pairs {+ lists.count(high(*pair) as usize);+ }+ lists.end_counts(NodeId(0))?;+ for pair in pairs {+ lists.fill(high(*pair) as usize, NodeId(low(*pair)));+ }+ lists.end_fill();+ Ok(())+ }+ lists_of_blocks(&mut self.live_in, &self.in_pairs, block_count)?;+ lists_of_blocks(&mut self.live_out, &self.out_pairs, block_count)?;- let mut dies_at = vec![Vec::new(); value_count];- let mut last_death = vec![None; value_count];- let mut dead_outputs = BitSet::new(value_count);- let mut needs_spill = BitSet::new(value_count);+ reset(&mut self.deaths, value_count, Run::default())?;+ self.dying.clear();+ reset(&mut self.flags, value_count, 0)?;+ reset(&mut self.last_death, value_count, 0)?;+ reset(&mut self.live_since, value_count, None)?;+ reset(&mut self.live, value_count, 0)?;// OPTIMIZATION: Rather than marking every value live across each call or float clobbering slow path there,// which takes time quadratic in the size of code that keeps many values live past many of them// (like a large array literal of arrays), the walk counts those nodes, notes the counts where// each value becomes live, and compares them where the value is defined or the block starts.let mut clobbers = Clobbers::default();- let mut live_since: Vec<Option<(BlockId, Clobbers)>> = vec![None; value_count];- for block in &block_ids {+ for (index, block) in graph.blocks.iter().enumerate() {+ let block_id = BlockId::from_index(index);let block_start = clobbers;let since = |live_since: &[Option<(BlockId, Clobbers)>], value: usize| match live_since[value] {- Some((since_block, since)) if since_block == *block => since,+ Some((since_block, since)) if since_block == block_id => since,_ => block_start,};- let check_spill = |needs_spill: &mut BitSet, since: Clobbers, clobbers: Clobbers, value: usize| {+ let check_spill = |flags: &mut [u8], since: Clobbers, clobbers: Clobbers, value: usize| {let is_float = graph.nodes[value].repr == Some(crate::code::Repr::Float64);if clobbers.calls != since.calls || (is_float && clobbers.float_clobbers != since.float_clobbers) {- needs_spill.insert(value);+ flags[value] |= NEEDS_SPILL;}};- entering.clone_from(&live_out[block.index()]);- Self::transfer_block(- graph,- &frames,- *block,- &mut entering,- &mut used,- |node, live_after, used| {- if live_after.contains(node.index()) {- check_spill(- &mut needs_spill,- since(&live_since, node.index()),- clobbers,- node.index(),- );- } else if is_allocated_value(graph, node) {- dead_outputs.insert(node.index());+ // Walk the block backwards from the values live at its end. A value is live where the walk is if `live`+ // has the mark of the block for it.+ let mark = index as u32 + 1;+ self.touched.clear();+ for value in self.live_out.get(index) {+ self.live[value.index()] = mark;+ self.touched.try_push(*value)?;+ }+ for node_id in block.body.iter().chain(&block.control).rev() {+ let node = graph.node(*node_id);+ self.used.clear();+ for input in &node.inputs {+ if is_allocated_value(graph, *input) {+ self.used.try_push(*input)?;}- let (is_call, clobbers_floats) = match lowering_info(graph.node(node)).clobbers {- LoweringClobbers::CallerSaved => (true, false),- // NB: Their slow paths clobber the floating point registers.- LoweringClobbers::Floats => (false, true),- LoweringClobbers::Nothing => (false, false),- };- if is_call || clobbers_floats {- clobbers.float_clobbers += 1;- clobbers.calls += u32::from(is_call);- for value in cached_frame_state_uses(graph, &frames, node) {- let is_float = graph.nodes[value.index()].repr == Some(crate::code::Repr::Float64);- if value != node && (is_call || is_float) {- needs_spill.insert(value.index());- }+ }+ let frame_uses = match node.frame_state {+ Some(frame) => self.frame_runs[frame.index()].range(),+ None => 0..0,+ };+ self.used.try_extend_from_slice(&self.frame_uses[frame_uses.clone()])?;++ if self.live[node_id.index()] == mark {+ check_spill(+ &mut self.flags,+ since(&self.live_since, node_id.index()),+ clobbers,+ node_id.index(),+ );+ } else if is_allocated_value(graph, *node_id) {+ self.flags[node_id.index()] |= DEAD_OUTPUT;+ }+ let (is_call, clobbers_floats) = match lowering_info(node).clobbers {+ LoweringClobbers::CallerSaved => (true, false),+ // NB: Their slow paths clobber the floating point registers.+ LoweringClobbers::Floats => (false, true),+ LoweringClobbers::Nothing => (false, false),+ };+ if is_call || clobbers_floats {+ clobbers.float_clobbers += 1;+ clobbers.calls += u32::from(is_call);+ for value in &self.frame_uses[frame_uses] {+ let is_float = graph.nodes[value.index()].repr == Some(crate::code::Repr::Float64);+ if value != node_id && (is_call || is_float) {+ self.flags[value.index()] |= NEEDS_SPILL;}}- for value in used {- if !live_after.contains(value.index()) && last_death[value.index()] != Some(node) {- last_death[value.index()] = Some(node);- dies_at[node.index()].push(*value);- live_since[value.index()] = Some((*block, clobbers));- }+ }+ let deaths = self.dying.len();+ for value in self.used.iter() {+ if self.live[value.index()] != mark && self.last_death[value.index()] != node_id.0 + 1 {+ self.last_death[value.index()] = node_id.0 + 1;+ self.dying.try_push(*value)?;+ self.live_since[value.index()] = Some((block_id, clobbers));}- },- );+ }+ self.deaths[node_id.index()] = Run::new(deaths, self.dying.len());++ self.live[node_id.index()] = 0;+ for value in self.used.iter() {+ if self.live[value.index()] != mark {+ self.live[value.index()] = mark;+ self.touched.try_push(*value)?;+ }+ }+ }+ for phi in &block.phis {+ self.live[phi.index()] = 0;+ }+ // NB: `touched` may have a value more than one time, which does no harm here.+ for value in self.touched.iter() {+ if self.live[value.index()] == mark {+ check_spill(+ &mut self.flags,+ since(&self.live_since, value.index()),+ clobbers,+ value.index(),+ );+ }+ }// NB: The phis of the block are live from its start if anything uses them.- let live_phis = graph.block(*block).phis.iter().map(|phi| phi.index()).filter(|phi| {- live_since[*phi].is_some_and(|(since_block, _)| since_block == *block)- || live_out[block.index()].contains(*phi)- });- for value in entering.iter().chain(live_phis) {- check_spill(&mut needs_spill, since(&live_since, value), clobbers, value);+ for phi in &block.phis {+ let is_live = self.live_since[phi.index()].is_some_and(|(since_block, _)| since_block == block_id)+ || self.live_out.get(index).binary_search(phi).is_ok();+ if is_live {+ check_spill(+ &mut self.flags,+ since(&self.live_since, phi.index()),+ clobbers,+ phi.index(),+ );+ }}// NB: Most merges start with the register state of one of their// predecessors (see `state_predecessor()`).- let predecessors = &graph.block(*block).predecessors;- if (predecessors.len() > 1 || predecessors.first().is_some_and(|predecessor| predecessor >= block))- && state_predecessor(graph, *block).is_none()+ let predecessors = &block.predecessors;+ if (predecessors.len() > 1 || predecessors.first().is_some_and(|predecessor| *predecessor >= block_id))+ && state_predecessor(graph, block_id).is_none(){- for value in live_in[block.index()].iter() {- needs_spill.insert(value);+ for value in self.live_in.get(index) {+ self.flags[value.index()] |= NEEDS_SPILL;}}}-- Self {- live_in,- live_out,- dies_at,- dead_outputs,- needs_spill,- positions,- use_positions,- }- }-- /// Walks a block backwards from the values live at its end, calling- /// `visit(node, live_after, used)` for every non-phi node, and leaves- /// the values live into the block (phis excluded) in `live`.- fn transfer_block(- graph: &Graph,- frames: &[OnceCell<Vec<NodeId>>],- block: BlockId,- live: &mut SparseBitSet,- used: &mut Vec<NodeId>,- mut visit: impl FnMut(NodeId, &SparseBitSet, &[NodeId]),- ) {- let block_data = graph.block(block);- for node in block_data.body.iter().chain(&block_data.control).rev() {- used.clear();- used.extend(- graph- .node(*node)- .inputs- .iter()- .copied()- .filter(|input| is_allocated_value(graph, *input))- .chain(cached_frame_state_uses(graph, frames, *node)),- );- visit(*node, live, used);- live.remove(node.index());- for value in used.iter() {- live.insert(value.index());- }- }- for phi in &block_data.phis {- live.remove(phi.index());- }+ Ok(())}}@@ -373,11 +590,12 @@ mod tests {let constant = graph.add_node(Node::new(Op::Constant(0), vec![], Some(Repr::Tagged), 0));let returned = graph.add_node(Node::new(Op::Return, vec![constant], None, 0));graph.blocks[0].control = Some(returned);- let liveness = ValueLiveness::compute(&graph);- assert!(liveness.dies_at[checks[0].index()].is_empty());- assert_eq!(liveness.dies_at[checks[1].index()], [value]);- assert!(!liveness.dead_outputs.contains(value.index()));- assert!(liveness.live_in[0].is_empty());+ let mut liveness = ValueLiveness::new();+ liveness.compute(&graph).unwrap();+ assert!(liveness.dies_at(checks[0]).is_empty());+ assert_eq!(liveness.dies_at(checks[1]), [value]);+ assert!(!liveness.is_dead_output(value));+ assert!(liveness.live_in.get(0).is_empty());}#[test]@@ -414,24 +632,24 @@ mod tests {});graph.add_block(block);}- let liveness = ValueLiveness::compute(&graph);- assert!(liveness.live_in[0].is_empty());- assert!(liveness.live_out[block_count - 1].is_empty());- for index in 1..block_count {- assert_eq!(- liveness.live_in[index].iter().collect::<Vec<_>>(),- [values[index - 1].index()]- );+ let mut liveness = ValueLiveness::new();+ // NB: The second time, the tables hold what the first time left in them.+ for _ in 0..2 {+ liveness.compute(&graph).unwrap();+ assert!(liveness.live_in.get(0).is_empty());+ assert!(liveness.live_out.get(block_count - 1).is_empty());+ for index in 1..block_count {+ assert_eq!(liveness.live_in.get(index), [values[index - 1]]);+ assert_eq!(liveness.live_out.get(index - 1), [values[index - 1]]);+ assert!(liveness.is_live_in(BlockId::from_index(index), values[index - 1]));+ assert!(!liveness.is_live_out(BlockId::from_index(index), values[index - 1]));+ assert_eq!(liveness.dies_at(values[index]), [values[index - 1]]);+ assert!(!liveness.is_dead_output(values[index - 1]));+ }assert_eq!(- liveness.live_out[index - 1].iter().collect::<Vec<_>>(),- [values[index - 1].index()]+ liveness.dies_at(graph.blocks[block_count - 1].control.unwrap()),+ [values[block_count - 1]]);- assert_eq!(liveness.dies_at[values[index].index()], [values[index - 1]]);- assert!(!liveness.dead_outputs.contains(values[index - 1].index()));}- assert_eq!(- liveness.dies_at[graph.blocks[block_count - 1].control.unwrap().index()],- [values[block_count - 1]]- );}}diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/loops.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/loops.rsindex 6e3d0627109..43849c562d8 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/loops.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/loops.rs@@ -91,10 +91,10 @@ impl Loops {end,carried_through: SparseBitSet::new(graph.nodes.len()),};- for value in liveness.live_in[index].iter() {- let uses = &liveness.use_positions[value];+ for value in liveness.live_in.get(index) {+ let uses = liveness.use_positions(*value);if loop_.first_use_in(uses, &position_blocks, 0..uses.len()).is_none() {- loop_.carried_through.insert(value);+ loop_.carried_through.insert(value.index());}}loops.push(loop_);diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rsindex 3627f88019f..e52df3a13ec 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs@@ -58,6 +58,7 @@ mod verify;pub use moves::resolve_parallel_moves;pub use verify::verify;+use crate::CompileFailure;use crate::code::Repr;use crate::codegen::lowering_info::Clobbers;use crate::codegen::lowering_info::FixedRegister;@@ -69,6 +70,7 @@ use crate::ir::BlockId;use crate::ir::Graph;use crate::ir::NodeId;use crate::ir::Op;+use crate::tables::Lists;use liveness::ValueLiveness;use liveness::is_allocated_value;use liveness::state_predecessor;@@ -265,7 +267,6 @@ pub struct NodeAllocation {pub exit_values: Vec<(u32, Location)>,}-#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct Allocation {/// Indexed by `NodeId`.pub nodes: Vec<NodeAllocation>,@@ -274,14 +275,64 @@ pub struct Allocation {/// or a loop header have any.pub block_end_moves: Vec<Vec<Move>>,pub spill_slot_count: u32,- /// The values live into each block, indexed by `BlockId`.- pub live_in: Vec<crate::sparse_bitset::SparseBitSet>,+ /// The values live into each block, sorted.+ live_in: Lists<NodeId>,}impl Allocation {+ pub fn new() -> Self {+ Self {+ nodes: Vec::new(),+ block_end_moves: Vec::new(),+ spill_slot_count: 0,+ live_in: ValueLiveness::new_live_in(),+ }+ }+pub fn node(&self, node: NodeId) -> &NodeAllocation {&self.nodes[node.index()]}++ /// Whether `value` is live into `block`.+ pub fn is_live_in(&self, block: BlockId, value: NodeId) -> bool {+ self.live_in.get(block.index()).binary_search(&value).is_ok()+ }+}++impl Default for Allocation {+ fn default() -> Self {+ Self::new()+ }+}++/// What the register allocator works with and its result, in tables that serve one compile after the other.+pub struct Regalloc {+ pub allocation: Allocation,+ liveness: ValueLiveness,+}++impl Regalloc {+ /// Tables that take no memory before a compile uses them.+ pub fn new() -> Self {+ Self {+ allocation: Allocation::new(),+ liveness: ValueLiveness::new(),+ }+ }++ /// Drops the tables and gives their memory back to the system.+ pub fn release_memory(&mut self) {+ self.allocation.nodes = Vec::new();+ self.allocation.block_end_moves = Vec::new();+ self.allocation.live_in.release_memory();+ self.liveness.release_memory();+ }+}++impl Default for Regalloc {+ fn default() -> Self {+ Self::new()+ }}/// The slot of the compiled function's frame that holds `value` wherever it is live, if there is one: a value loaded@@ -296,17 +347,22 @@ pub fn frame_home(graph: &Graph, value: NodeId) -> Option<u32> {}}-/// Assigns locations to the values of `graph`. The verifier checks the+/// Assigns locations to the values of `graph`, into `regalloc.allocation`. The verifier checks the/// result where the IR is verified (see `verify()`).-pub fn allocate(graph: &Graph, registers: &RegisterSet) -> Allocation {- Allocator::new(graph, registers).run()+pub fn allocate(graph: &Graph, registers: &RegisterSet, regalloc: &mut Regalloc) -> Result<(), CompileFailure> {+ let Regalloc { allocation, liveness } = regalloc;+ liveness.compute(graph)?;+ Allocator::new(graph, registers, liveness, allocation).run();+ // NB: The code generator reads which values are live into a block.+ core::mem::swap(&mut allocation.live_in, &mut liveness.live_in);+ Ok(())}struct Allocator<'a> {graph: &'a Graph,registers: &'a RegisterSet,- liveness: ValueLiveness,- allocation: Allocation,+ liveness: &'a ValueLiveness,+ allocation: &'a mut Allocation,/// The value each register holds.contents: Vec<Option<NodeId>>,/// The register each value is in, if any.@@ -323,22 +379,26 @@ struct Allocator<'a> {}impl<'a> Allocator<'a> {- fn new(graph: &'a Graph, registers: &'a RegisterSet) -> Self {+ fn new(+ graph: &'a Graph,+ registers: &'a RegisterSet,+ liveness: &'a ValueLiveness,+ allocation: &'a mut Allocation,+ ) -> Self {assert!(registers.allocatable_gprs.0 >> FPR_BASE == 0);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);+ let slot_classes = coalescing::spill_slot_classes(graph, liveness);+ let loops = Loops::compute(graph, liveness);+ allocation.nodes.clear();+ allocation.nodes.resize(graph.nodes.len(), NodeAllocation::default());+ allocation.block_end_moves.clear();+ allocation.block_end_moves.resize(graph.blocks.len(), Vec::new());+ allocation.spill_slot_count = 0;Self {graph,registers,liveness,- allocation: Allocation {- nodes: vec![NodeAllocation::default(); graph.nodes.len()],- block_end_moves: vec![Vec::new(); graph.blocks.len()],- spill_slot_count: 0,- live_in: Vec::new(),- },+ allocation,contents: vec![None; REGISTER_COUNT],value_registers: vec![None; graph.nodes.len()],end_contents: vec![None; graph.blocks.len()],@@ -349,7 +409,7 @@ impl<'a> Allocator<'a> {}}- fn run(mut self) -> Allocation {+ fn run(mut self) {// Give the phis of blocks without a state predecessor their locations// up front, since their predecessors may be allocated after them.// Phis of loop headers live in registers, which the header starts@@ -387,9 +447,9 @@ impl<'a> Allocator<'a> {.any(|predecessor| predecessor.index() >= index)&& state_predecessor(self.graph, block_id).is_none(){- let live_in = self.liveness.live_in[index].iter().collect::<Vec<_>>();- for value in live_in {- self.ensure_home(NodeId::from_index(value));+ let liveness = self.liveness;+ for value in liveness.live_in.get(index) {+ self.ensure_home(*value);}}}@@ -406,8 +466,6 @@ impl<'a> Allocator<'a> {self.allocate_node(self.graph.control_id(block));self.end_contents[block.index()] = Some(self.contents.clone());}- self.allocation.live_in = self.liveness.live_in;- self.allocation}/// Gives `phi` its location: `register` if it has one, and its spill@@ -415,10 +473,7 @@ impl<'a> Allocator<'a> {/// allocated before its own) if it has no register or needs a slot.fn place_phi(&mut self, phi: NodeId, register: Option<u8>) {let slot = match register {- Some(_)- if !self.liveness.needs_spill.contains(phi.index())- && self.allocation.nodes[phi.index()].spill_slot.is_none() =>- {+ Some(_) if !self.liveness.needs_spill(phi) && self.allocation.nodes[phi.index()].spill_slot.is_none() => {None}_ => Some(self.ensure_spill_slot(phi)),@@ -478,12 +533,11 @@ impl<'a> Allocator<'a> {/// The register contents at the end of `predecessor` (which comes before/// `block` in linear order) that are live into `block`.fn contents_entering(&self, predecessor: BlockId, block: BlockId) -> Vec<Option<NodeId>> {- let live_in = &self.liveness.live_in[block.index()];let mut contents = self.end_contents[predecessor.index()].clone().expect("blocks come after the predecessor whose state they start with");for value in &mut contents {- if value.is_some_and(|value| !live_in.contains(value.index())) {+ if value.is_some_and(|value| !self.liveness.is_live_in(block, value)) {*value = None;}}@@ -496,7 +550,7 @@ impl<'a> Allocator<'a> {self.loops.headed_by(block).is_some_and(|loop_| loop_.carries_through(value.index()))- && self.liveness.needs_spill.contains(value.index())+ && self.liveness.needs_spill(value)}/// The register contents a merge with a state predecessor starts with:@@ -576,7 +630,7 @@ impl<'a> Allocator<'a> {/// 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 uses = self.liveness.use_positions(value);let index = uses.partition_point(|position| *position <= self.position);let next = uses.get(index).copied();let Some(loop_) = self.loops.innermost_at(self.position) else {@@ -585,7 +639,7 @@ impl<'a> Allocator<'a> {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())+ if self.liveness.is_live_in(loop_.header, value)&& let Some(position) = self.loops.first_use_in(loop_, uses, 0..index){return (1, position - loop_.start);@@ -639,7 +693,7 @@ impl<'a> Allocator<'a> {/// Whether `value`, which `node` uses or which is in a register at/// `node`, is still needed after it. Registers only ever hold live values.fn is_live_after(&self, value: NodeId, node: NodeId) -> bool {- !self.liveness.dies_at[node.index()].contains(&value)+ !self.liveness.dies_at(node).contains(&value)}fn exit_values(&self, node: NodeId) -> Vec<(u32, Location)> {@@ -746,7 +800,7 @@ impl<'a> Allocator<'a> {if node.frame_state.is_none()&& constraints.reuses_first_input&& is_allocated_value(self.graph, node.inputs[0])- && self.liveness.dies_at[node_id.index()].contains(&node.inputs[0])+ && self.liveness.dies_at(node_id).contains(&node.inputs[0])&& RegisterClass::of_register(*register) == RegisterClass::of(node.repr)&& !temps.contains(register) =>{@@ -795,8 +849,8 @@ impl<'a> Allocator<'a> {let exit_values = self.exit_values(node_id);// Values whose last use is this node no longer need their registers.- for index in 0..self.liveness.dies_at[node_id.index()].len() {- let value = self.liveness.dies_at[node_id.index()][index];+ let liveness = self.liveness;+ for value in liveness.dies_at(node_id) {if let Some(register) = self.value_registers[value.index()] {self.free_register(register);}@@ -804,10 +858,10 @@ impl<'a> Allocator<'a> {if let Some(register) = output {self.assign_register(register, node_id);- if self.liveness.needs_spill.contains(node_id.index()) {+ if self.liveness.needs_spill(node_id) {self.ensure_home(node_id);}- if self.liveness.dead_outputs.contains(node_id.index()) {+ if self.liveness.is_dead_output(node_id) {self.free_register(register);}}@@ -824,10 +878,11 @@ impl<'a> Allocator<'a> {/// state predecessor: registers that hold no value live into the merge/// (preferably the input's own), or stack slots if there are none.fn place_merge_phis(&mut self, predecessor: BlockId, join: BlockId) {- 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()) && !self.loop_leaves_in_stack(join, value)) {+ if value+ .is_some_and(|value| self.liveness.is_live_in(join, value) && !self.loop_leaves_in_stack(join, value))+ {taken = taken.with(u8::try_from(register).expect("register numbers fit in u8"));}}@@ -882,9 +937,10 @@ impl<'a> Allocator<'a> {/// The moves at the end of `block` that put the inputs of the phis of its/// successor in place.fn phi_moves(&mut self, block: BlockId, cycle_temp: &mut Option<u32>) -> Vec<Move> {- let successors = self.graph.successors(block);- let [successor] = &*successors else {- for successor in successors.iter() {+ let liveness = self.liveness;+ let successors = liveness.successors.get(block.index());+ let [successor] = successors else {+ for successor in successors {debug_assert!(self.graph.block(*successor).phis.is_empty(), "critical edge into a phi");}return Vec::new();diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rsindex 1ec8307cced..ba55dcd91ec 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs@@ -19,10 +19,33 @@ use crate::code::ValueLocation;use crate::codegen::sites::SiteSource;use crate::ir::value;+/// The tables of a register allocation, which the tests read as the allocation.+struct Allocated(Regalloc);++impl std::ops::Deref for Allocated {+ type Target = Allocation;++ fn deref(&self) -> &Allocation {+ &self.0.allocation+ }+}++impl std::ops::DerefMut for Allocated {+ fn deref_mut(&mut self) -> &mut Allocation {+ &mut self.0.allocation+ }+}++fn allocate_with(graph: &Graph, registers: &RegisterSet) -> Allocated {+ let mut regalloc = Regalloc::new();+ allocate(graph, registers, &mut regalloc).unwrap();+ Allocated(regalloc)+}+#[track_caller]-fn allocate_and_verify(graph: &Graph) -> Allocation {+fn allocate_and_verify(graph: &Graph) -> Allocated {let registers = RegisterSet::test_configuration();- let allocation = allocate(graph, ®isters);+ let allocation = allocate_with(graph, ®isters);if let Err(errors) = verify(graph, ®isters, &allocation) {panic!("{errors}\n{}", dump_allocation(graph, &allocation));}@@ -597,7 +620,7 @@ fn shift_amounts_are_in_the_targets_shift_register_or_immediates() {shift_amount_gpr,..RegisterSet::test_configuration()};- let allocation = allocate(&graph, ®isters);+ let allocation = allocate_with(&graph, ®isters);if let Err(errors) = verify(&graph, ®isters, &allocation) {panic!("{errors}\n{}", dump_allocation(&graph, &allocation));}@@ -746,12 +769,12 @@ fn the_verifier_finds_values_in_the_wrong_place() {});let graph = build(&program);let registers = RegisterSet::test_configuration();- let allocation = allocate(&graph, ®isters);+ let allocation = allocate_with(&graph, ®isters);verify(&graph, ®isters, &allocation).unwrap();// Forgetting to spill a value that is live across a call loses it.let argument = find_node(&graph, |node| node.op == Op::LoadSlot { slot: a(0).raw() });- let mut broken = allocation.clone();+ let mut broken = allocate_with(&graph, ®isters);broken.nodes[argument.index()].spill_slot = None;assert!(verify(&graph, ®isters, &broken).is_err());@@ -783,7 +806,7 @@ fn the_verifier_finds_values_reloaded_from_frame_slots_that_do_not_hold_them() {});let graph = build(&program);let registers = RegisterSet::test_configuration();- let allocation = allocate(&graph, ®isters);+ let allocation = allocate_with(&graph, ®isters);verify(&graph, ®isters, &allocation).unwrap();let returned = find_node(&graph, |node| matches!(node.op, Op::Return));assert_eq!(@@ -800,7 +823,7 @@ fn the_verifier_finds_values_reloaded_from_frame_slots_that_do_not_hold_them() {assert!(verify(&written, ®isters, &allocation).is_err());// Another frame slot holds another value.- let mut broken = allocation.clone();+ let mut broken = allocate_with(&graph, ®isters);broken.nodes[returned.index()].moves_before[0].from = Location::Frame(r(5).raw());assert!(verify(&graph, ®isters, &broken).is_err());@@ -1163,7 +1186,7 @@ fn random_structured_programs_with_cold_blocks_allocate_correctly() {panic!("seed {seed}: {errors}\n{}", crate::ir::dump(&graph, &layout));}let registers = RegisterSet::test_configuration();- let allocation = allocate(&graph, ®isters);+ let allocation = allocate_with(&graph, ®isters);if let Err(errors) = verify(&graph, ®isters, &allocation) {panic!("seed {seed}: {errors}\n{}\n{}",@@ -1190,7 +1213,7 @@ fn random_structured_programs_allocate_correctly() {.collect::<Vec<_>>();let graph = build_with_layout(&program, layout, &never_ran);let registers = RegisterSet::test_configuration();- let allocation = allocate(&graph, ®isters);+ let allocation = allocate_with(&graph, ®isters);if let Err(errors) = verify(&graph, ®isters, &allocation) {panic!("seed {seed}: {errors}\n{}\n{}",diff --git a/Libraries/LibJS/JIT/Rust/src/scratch.rs b/Libraries/LibJS/JIT/Rust/src/scratch.rsindex 8c180a4f91e..9cc16c50dfb 100644--- a/Libraries/LibJS/JIT/Rust/src/scratch.rs+++ b/Libraries/LibJS/JIT/Rust/src/scratch.rs@@ -8,6 +8,7 @@use crate::artifact::ArtifactWriter;use crate::codegen::sites::SiteScratch;+use crate::regalloc::Regalloc;/// What a compile keeps its data in, apart from what the heap still holds of it. A thread that compiles has one, and/// every compile of the thread uses it: a compile leaves nothing in it that the next one reads, only the memory.@@ -16,6 +17,7 @@ use crate::codegen::sites::SiteScratch;pub struct Scratch {pub(crate) artifact: ArtifactWriter,pub(crate) sites: SiteScratch,+ pub(crate) regalloc: Regalloc,}impl Default for Scratch {@@ -30,6 +32,7 @@ impl Scratch {Self {artifact: ArtifactWriter::new(),sites: SiteScratch::new(),+ regalloc: Regalloc::new(),}}@@ -37,5 +40,6 @@ impl Scratch {pub fn release_memory(&mut self) {self.artifact.release_memory();self.sites.release_memory();+ self.regalloc.release_memory();}}diff --git a/Libraries/LibJS/JIT/Rust/src/tables.rs b/Libraries/LibJS/JIT/Rust/src/tables.rsnew file mode 100644index 00000000000..0185fdb0665--- /dev/null+++ b/Libraries/LibJS/JIT/Rust/src/tables.rs@@ -0,0 +1,263 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Lists in the tables of a compile.+//!+//! The data of a compile is rows in columns (see `ak::Column`). Where a row has a list of something, the elements of+//! the list are next to each other in a column that holds the lists of all the rows, and the row says which part of+//! that column is its own. So a compile makes no block of the heap for a list, however many lists it has.++use core::ffi::CStr;+use core::ops::Range;++use ak::Column;+use ak::ColumnFull;++/// The elements of one list: a part of a column that holds many lists.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct Run {+ start: u32,+ len: u32,+}++impl Run {+ /// In place of the elements of a list that is not written yet. It is a part of no column.+ pub const NOT_WRITTEN: Run = Run {+ start: u32::MAX,+ len: 0,+ };++ /// The elements from index `start` to index `end` of a column, without the one at `end`.+ pub fn new(start: usize, end: usize) -> Self {+ // NB: The columns of a compile hold fewer elements than this (see their limits).+ let start = u32::try_from(start).expect("the columns of a compile have 32-bit indices");+ let end = u32::try_from(end).expect("the columns of a compile have 32-bit indices");+ Self {+ start,+ len: end - start,+ }+ }++ /// Where the elements are in their column.+ pub fn range(self) -> Range<usize> {+ self.start as usize..self.start as usize + self.len as usize+ }++ pub fn len(self) -> usize {+ self.len as usize+ }++ pub fn is_empty(self) -> bool {+ self.len == 0+ }+}++/// Drops the elements of `column` and gives its memory back to the system.+pub fn release<T: Copy>(column: &mut Column<T>) {+ column.clear();+ column.trim(0);+}++/// Makes `column` hold `len` copies of `value` and nothing else.+pub fn reset<T: Copy>(column: &mut Column<T>, len: usize, value: T) -> Result<(), ColumnFull> {+ column.clear();+ column.try_resize(len, value)+}++/// Takes the last element out of `column`, if it has one.+pub fn pop<T: Copy>(column: &mut Column<T>) -> Option<T> {+ let last = column.last().copied()?;+ column.truncate(column.len() - 1);+ Some(last)+}++/// A list of `T` for each index from 0 on, all in one column, in the order of the indices.+///+/// The lists are written in one of two ways. In the order of their indices: `begin()`, then for each index+/// `try_push()` for its elements and `end_list()`. Or in any order, when it is known first how long each list is:+/// `begin_counts()`, `count()` for each element, `end_counts()`, `fill()` for each element, `end_fill()`.+pub struct Lists<T: Copy> {+ /// Where the list of each index starts in `items`, and one more: where the last list ends.+ starts: Column<u32>,+ items: Column<T>,+}++impl<T: Copy> Lists<T> {+ /// Lists for up to `max_lists` indices, with up to `max_items` elements in all. They take no memory before they+ /// have elements. `name` shows up for their memory in /proc/<pid>/smaps on Linux.+ pub fn new(max_lists: usize, max_items: usize, name: &'static CStr) -> Self {+ Self {+ starts: Column::new(max_lists + 2, name),+ items: Column::new(max_items.min(u32::MAX as usize), name),+ }+ }++ /// Drops the lists and gives their memory back to the system.+ pub fn release_memory(&mut self) {+ release(&mut self.starts);+ release(&mut self.items);+ }++ /// How many indices have a list.+ pub fn len(&self) -> usize {+ self.starts.len().saturating_sub(1)+ }++ pub fn is_empty(&self) -> bool {+ self.len() == 0+ }++ /// The list of `index`.+ pub fn get(&self, index: usize) -> &[T] {+ &self.items[self.starts[index] as usize..self.starts[index + 1] as usize]+ }++ /// Drops the lists, to write new ones in the order of their indices.+ pub fn begin(&mut self) -> Result<(), ColumnFull> {+ self.starts.clear();+ self.items.clear();+ self.starts.try_push(0)+ }++ /// Adds an element to the list that is being written: the list of the first index that has none.+ pub fn try_push(&mut self, item: T) -> Result<(), ColumnFull> {+ self.items.try_push(item)+ }++ /// Ends the list that is being written.+ pub fn end_list(&mut self) -> Result<(), ColumnFull> {+ // NB: new() keeps the count of elements in 32 bits.+ self.starts.try_push(self.items.len() as u32)+ }++ /// Drops the lists, to write the lists of the indices below `count` in any order.+ pub fn begin_counts(&mut self, count: usize) -> Result<(), ColumnFull> {+ self.starts.clear();+ self.items.clear();+ // NB: While the lists are counted and filled, the entry of an index is one place further on, so that the+ // entries are where get() reads them when all the lists are full (see fill()).+ self.starts.try_resize(count + 2, 0)+ }++ /// Notes that the list of `index` gets one more element.+ pub fn count(&mut self, index: usize) {+ self.starts[index + 2] += 1;+ }++ /// Makes room for the elements that were counted, as copies of `filler`.+ pub fn end_counts(&mut self, filler: T) -> Result<(), ColumnFull> {+ let mut total = 0_u64;+ for start in self.starts.iter_mut().skip(2) {+ total += u64::from(*start);+ *start = u32::try_from(total).map_err(|_| ColumnFull)?;+ }+ self.items.try_resize(total as usize, filler)+ }++ /// Puts `item` in the next place of the list of `index`, which has a place left.+ pub fn fill(&mut self, index: usize, item: T) {+ let place = self.starts[index + 1];+ self.items[place as usize] = item;+ self.starts[index + 1] = place + 1;+ }++ /// Ends the writing of lists that were counted, when all of them are full.+ pub fn end_fill(&mut self) {+ let count = self.starts.len() - 1;+ debug_assert!(self.starts[count - 1] == self.starts[count]);+ self.starts.truncate(count);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn lists_written_in_the_order_of_their_indices() {+ let mut lists = Lists::new(8, 64, c"test");+ assert!(lists.is_empty());+ lists.begin().unwrap();+ lists.try_push(5_u32).unwrap();+ lists.try_push(6).unwrap();+ lists.end_list().unwrap();+ lists.end_list().unwrap();+ lists.try_push(7).unwrap();+ lists.end_list().unwrap();+ assert_eq!(lists.len(), 3);+ assert_eq!(lists.get(0), [5, 6]);+ assert_eq!(lists.get(1), []);+ assert_eq!(lists.get(2), [7]);+ lists.begin().unwrap();+ assert!(lists.is_empty());+ }++ #[test]+ fn lists_written_in_any_order() {+ let mut lists = Lists::new(8, 64, c"test");+ let items = [(2, 'a'), (0, 'b'), (2, 'c'), (3, 'd'), (0, 'e'), (2, 'f')];+ for _ in 0..2 {+ lists.begin_counts(5).unwrap();+ for (index, _) in items {+ lists.count(index);+ }+ lists.end_counts(' ').unwrap();+ for (index, item) in items {+ lists.fill(index, item);+ }+ lists.end_fill();+ assert_eq!(lists.len(), 5);+ assert_eq!(lists.get(0), ['b', 'e']);+ assert_eq!(lists.get(1), []);+ assert_eq!(lists.get(2), ['a', 'c', 'f']);+ assert_eq!(lists.get(3), ['d']);+ assert_eq!(lists.get(4), []);+ }+ }++ #[test]+ fn lists_with_no_room_fail() {+ let mut lists = Lists::new(2, 3, c"test");+ lists.begin_counts(2).unwrap();+ for _ in 0..4 {+ lists.count(1);+ }+ assert_eq!(lists.end_counts(0_u8), Err(ColumnFull));+ assert_eq!(lists.begin_counts(3), Err(ColumnFull));+ lists.begin().unwrap();+ for item in 0..3 {+ lists.try_push(item).unwrap();+ }+ assert_eq!(lists.try_push(3), Err(ColumnFull));+ }++ #[test]+ fn columns_are_reset_and_popped() {+ let mut column = Column::new(8, c"test");+ reset(&mut column, 3, 7_u8).unwrap();+ assert_eq!(*column, [7, 7, 7]);+ column[2] = 9;+ assert_eq!(pop(&mut column), Some(9));+ reset(&mut column, 1, 1).unwrap();+ assert_eq!(pop(&mut column), Some(1));+ assert_eq!(pop(&mut column), None);+ assert_eq!(reset(&mut column, 9, 0), Err(ColumnFull));+ column.push(5);+ release(&mut column);+ assert!(column.is_empty());+ assert_eq!(column.memory(), 0);+ }++ #[test]+ fn a_run_is_a_part_of_a_column() {+ let run = Run::new(3, 7);+ assert_eq!(run.range(), 3..7);+ assert_eq!(run.len(), 4);+ assert!(!run.is_empty());+ assert!(Run::default().is_empty());+ assert!(Run::new(9, 9).is_empty());+ }+}