Skip to content

Truly independent web browser

LibJS/JIT: Keep the data of the register allocator in tables

Andreas Kling0437df55a52d
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index 90b2f69dd17..24b0a1e5cab 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -675,7 +675,7 @@ fn landing_blocks(graph: &Graph, allocation: &Allocation) -> Vec<BlockId> {
if index == 0
|| !block.phis.is_empty()
|| !block.body.is_empty()
- || !allocation.block_end_moves[index].is_empty()
+ || !allocation.block_end_moves(BlockId::from_index(index)).is_empty()
{
return None;
}
@@ -823,19 +823,20 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
registers.push(register_of(*register));
}
};
- for node in &self.allocation.nodes {
+ for node in 0..self.allocation.node_count() {
+ let node = self.allocation.node(NodeId::from_index(node));
node.inputs.iter().for_each(&mut add);
node.output.iter().for_each(&mut add);
- for m in &node.moves_before {
+ for m in node.moves_before {
add(&m.from);
add(&m.to);
}
- for temp in &node.temps {
+ for temp in node.temps {
add(&Location::Register(*temp));
}
}
- for moves in &self.allocation.block_end_moves {
- for m in moves {
+ for block in 0..self.graph.blocks.len() {
+ for m in self.allocation.block_end_moves(BlockId::from_index(block)) {
add(&m.from);
add(&m.to);
}
@@ -1275,7 +1276,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.jump_to(success);
return Ok(());
}
- let end_moves = &self.allocation.block_end_moves[block.index()];
+ let end_moves = self.allocation.block_end_moves(block);
if !end_moves.is_empty() {
self.annotate(CodeAnnotation::BlockEndMoves);
}
@@ -1398,7 +1399,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
fn emit_node(&mut self, node_id: NodeId) -> Result<(), CompileFailure> {
self.annotate(CodeAnnotation::Node(node_id));
let allocation = self.allocation.node(node_id);
- for m in &allocation.moves_before {
+ for m in allocation.moves_before {
self.emit_move(m);
}
let node = self.graph.node(node_id);
@@ -2837,9 +2838,9 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
fn save_input_registers(&mut self, node: NodeId) -> Vec<Gpr> {
let clobbered = slow_path_calls::slow_path_saved_registers::<M>();
let mut saved = Vec::new();
- for location in &self.allocation.node(node).inputs {
- if let Location::Register(register) = location
- && let Register::General(register) = register_of(*register)
+ for location in self.allocation.node(node).inputs {
+ if let Location::Register(register) = *location
+ && let Register::General(register) = register_of(register)
&& clobbered.contains(register)
&& !saved.contains(&register)
{
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs
index 1817d890e66..17062e8cf6b 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs
@@ -41,7 +41,7 @@ pub(super) fn slow_path_saved_registers<M: PortableMacroAssembler>() -> GprSet {
/// the order of their words in the saves area: those that may hold values,
/// except its output register, which is last if an input is there too, since
/// passing the other inputs to the slow path may clobber it.
-pub(super) fn slow_path_saved_registers_of<M: PortableMacroAssembler>(allocation: &NodeAllocation) -> Vec<Gpr> {
+pub(super) fn slow_path_saved_registers_of<M: PortableMacroAssembler>(allocation: NodeAllocation) -> Vec<Gpr> {
let output = match allocation.output {
Some(Location::Register(register)) => Some(Gpr(register)),
_ => None,
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
index 4a3a5689726..1056b80768a 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
@@ -2520,12 +2520,15 @@ fn slow_paths_save_no_more_registers_than_the_saves_area_holds() {
let words = slow_path_calls::slow_path_saved_registers::<M>().len();
for register in target_registers::<M>().0.allocatable_gprs.iter() {
let allocation = crate::regalloc::NodeAllocation {
- inputs: crate::inline_vec::InlineVec::from_elem(Location::Register(register), 1),
+ moves_before: &[],
+ inputs: &[Location::Register(register)],
+ temps: &[],
output: Some(Location::Register(register)),
- ..Default::default()
+ spill_slot: None,
+ exit_values: &[],
};
assert!(
- slow_path_calls::slow_path_saved_registers_of::<M>(&allocation).len() <= words,
+ slow_path_calls::slow_path_saved_registers_of::<M>(allocation).len() <= words,
"an output in register {register} that an input is in too"
);
}
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rs
index 5ef0d062523..de4053c426d 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/coalescing.rs
@@ -16,14 +16,20 @@
//! is defined. Values join a class of values sharing one slot only if they
//! overlap with no value already in it.
+use ak::Column;
+use ak::ColumnFull;
+
use super::liveness::ValueLiveness;
use super::liveness::is_allocated_value;
use crate::ir::BlockId;
use crate::ir::Graph;
use crate::ir::NodeId;
+use crate::tables::Lists;
+use crate::tables::release;
+use crate::tables::reset;
/// The most values one class holds, which keeps the pairwise checks cheap.
-const MAX_CLASS_SIZE: usize = 32;
+const MAX_CLASS_SIZE: u32 = 32;
/// Where a value is defined: its block, and its position in linear order
/// (`None` for phis, which are defined where their block starts).
@@ -33,12 +39,26 @@ struct Definition {
position: Option<u32>,
}
+/// The spill slot classes of the values of a graph, in tables that serve one compile after the other.
+pub(super) struct Coalescing {
+ /// The class of each value: values of one class share their spill slot.
+ /// Classes are named by one of their values.
+ pub classes: Column<u32>,
+ /// For each value, the next value of its class. The values of a class are a ring, so that two classes join with
+ /// no list to copy.
+ next: Column<u32>,
+ /// For each value that names a class, how many values the class has.
+ sizes: Column<u32>,
+ definitions: Column<Definition>,
+ /// For each value, the blocks where it dies and the positions there.
+ deaths: Lists<(usize, u32)>,
+}
+
struct Interference<'a> {
graph: &'a Graph,
liveness: &'a ValueLiveness,
- definitions: Vec<Definition>,
- /// For each value, the blocks where it dies and the positions there.
- deaths: Vec<Vec<(usize, u32)>>,
+ definitions: &'a [Definition],
+ deaths: &'a Lists<(usize, u32)>,
}
impl Interference<'_> {
@@ -72,7 +92,7 @@ impl Interference<'_> {
})
};
self.liveness.is_live_out(at_block, value)
- || self.deaths[value.index()].iter().any(|(block, death)| {
+ || self.deaths.get(value.index()).iter().any(|(block, death)| {
*block == at.block && (*death > position || (*death == position && read_after_definition()))
})
}
@@ -82,76 +102,138 @@ impl Interference<'_> {
}
}
-/// The class of each value: values of one class share their spill slot.
-/// Classes are named by one of their values.
-pub(super) fn spill_slot_classes(graph: &Graph, liveness: &ValueLiveness) -> Vec<u32> {
- let count = graph.nodes.len();
- let mut classes = (0..count as u32).collect::<Vec<_>>();
- let mut members = vec![Vec::new(); count];
- let mut definitions = vec![
- Definition {
- block: 0,
- position: None
- };
- count
- ];
- let mut deaths = vec![Vec::new(); count];
- let mut has_phis = false;
- for (index, block) in graph.blocks.iter().enumerate() {
- has_phis |= !block.phis.is_empty();
- for phi in &block.phis {
- definitions[phi.index()] = Definition {
- block: index,
- position: None,
- };
+/// The values of the class of `value`, which starts with `value`.
+fn members(next: &[u32], value: u32) -> impl Iterator<Item = NodeId> + '_ {
+ let mut member = Some(value);
+ std::iter::from_fn(move || {
+ let current = member?;
+ let following = next[current as usize];
+ member = (following != value).then_some(following);
+ Some(NodeId(current))
+ })
+}
+
+impl Coalescing {
+ // NB: A compile whose graph has more nodes, or more deaths of values, fails.
+ const MAX_NODES: usize = 1 << 24;
+ const MAX_DEATHS: usize = 1 << 26;
+
+ pub fn new() -> Self {
+ fn by_node<T: Copy>() -> Column<T> {
+ Column::new(Coalescing::MAX_NODES, c"JIT spill slot classes")
}
- for node in block.body.iter().chain(&block.control) {
- let position = liveness.positions[node.index()];
- definitions[node.index()] = Definition {
- block: index,
- position: Some(position),
- };
- for value in liveness.dies_at(*node) {
- deaths[value.index()].push((index, position));
- }
+ Self {
+ classes: by_node(),
+ next: by_node(),
+ sizes: by_node(),
+ definitions: by_node(),
+ deaths: Lists::new(Self::MAX_NODES, Self::MAX_DEATHS, c"JIT spill slot classes"),
}
}
- if !has_phis {
- return classes;
- }
- for (index, member) in members.iter_mut().enumerate() {
- member.push(NodeId::from_index(index));
+
+ /// Drops the tables and gives their memory back to the system.
+ pub fn release_memory(&mut self) {
+ release(&mut self.classes);
+ release(&mut self.next);
+ release(&mut self.sizes);
+ release(&mut self.definitions);
+ self.deaths.release_memory();
}
- let interference = Interference {
- graph,
- liveness,
- definitions,
- deaths,
- };
- for block in &graph.blocks {
- for phi in &block.phis {
- for input in &graph.node(*phi).inputs {
- // NB: Values with a frame slot as their home have no spill slot to share.
- if input == phi || !is_allocated_value(graph, *input) || super::frame_home(graph, *input).is_some() {
- continue;
- }
- let (a, b) = (classes[phi.index()] as usize, classes[input.index()] as usize);
- if a == b || members[a].len() + members[b].len() > MAX_CLASS_SIZE {
- continue;
+
+ /// Finds the class of each value of `graph`.
+ pub fn compute(&mut self, graph: &Graph, liveness: &ValueLiveness) -> Result<(), ColumnFull> {
+ let count = graph.nodes.len();
+ self.classes.clear();
+ for value in 0..count as u32 {
+ self.classes.try_push(value)?;
+ }
+ // NB: Without phis, each value is a class of its own.
+ if graph.blocks.iter().all(|block| block.phis.is_empty()) {
+ return Ok(());
+ }
+ reset(
+ &mut self.definitions,
+ count,
+ Definition {
+ block: 0,
+ position: None,
+ },
+ )?;
+ self.deaths.begin_counts(count)?;
+ for (index, block) in graph.blocks.iter().enumerate() {
+ for phi in &block.phis {
+ self.definitions[phi.index()] = Definition {
+ block: index,
+ position: None,
+ };
+ }
+ for node in block.body.iter().chain(&block.control) {
+ self.definitions[node.index()] = Definition {
+ block: index,
+ position: Some(liveness.positions[node.index()]),
+ };
+ for value in liveness.dies_at(*node) {
+ self.deaths.count(value.index());
}
- let overlapping = members[a]
- .iter()
- .any(|x| members[b].iter().any(|y| interference.overlap(*x, *y)));
- if overlapping {
- continue;
+ }
+ }
+ self.deaths.end_counts((0, 0))?;
+ for (index, block) in graph.blocks.iter().enumerate() {
+ for node in block.body.iter().chain(&block.control) {
+ let position = liveness.positions[node.index()];
+ for value in liveness.dies_at(*node) {
+ self.deaths.fill(value.index(), (index, position));
}
- let moved = std::mem::take(&mut members[b]);
- for value in &moved {
- classes[value.index()] = a as u32;
+ }
+ }
+ self.deaths.end_fill();
+ self.next.clear();
+ self.next.try_extend_from_slice(&self.classes)?;
+ reset(&mut self.sizes, count, 1)?;
+
+ let Self {
+ classes,
+ next,
+ sizes,
+ definitions,
+ deaths,
+ } = self;
+ let interference = Interference {
+ graph,
+ liveness,
+ definitions,
+ deaths,
+ };
+ for block in &graph.blocks {
+ for phi in &block.phis {
+ for input in &graph.node(*phi).inputs {
+ // NB: Values with a frame slot as their home have no spill slot to share.
+ if input == phi || !is_allocated_value(graph, *input) || super::frame_home(graph, *input).is_some()
+ {
+ continue;
+ }
+ let (a, b) = (classes[phi.index()], classes[input.index()]);
+ if a == b || sizes[a as usize] + sizes[b as usize] > MAX_CLASS_SIZE {
+ continue;
+ }
+ let overlapping = members(next, a).any(|x| members(next, b).any(|y| interference.overlap(x, y)));
+ if overlapping {
+ continue;
+ }
+ let mut member = b;
+ loop {
+ classes[member as usize] = a;
+ member = next[member as usize];
+ if member == b {
+ break;
+ }
+ }
+ // NB: This makes one ring of the two.
+ next.swap(a as usize, b as usize);
+ sizes[a as usize] += sizes[b as usize];
}
- members[a].extend(moved);
}
}
+ Ok(())
}
- classes
}
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
index e52df3a13ec..588e76c19e8 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
@@ -65,12 +65,17 @@ use crate::codegen::lowering_info::FixedRegister;
use crate::codegen::lowering_info::InputConstraint;
use crate::codegen::lowering_info::OutputConstraint;
use crate::codegen::lowering_info::lowering_info;
-use crate::inline_vec::InlineVec;
use crate::ir::BlockId;
use crate::ir::Graph;
use crate::ir::NodeId;
use crate::ir::Op;
use crate::tables::Lists;
+use crate::tables::Run;
+use crate::tables::release;
+use crate::tables::reset;
+use ak::Column;
+use ak::ColumnFull;
+use coalescing::Coalescing;
use liveness::ValueLiveness;
use liveness::is_allocated_value;
use liveness::state_predecessor;
@@ -248,15 +253,18 @@ pub struct Move {
pub to: Location,
}
+/// The most temps a node has (see `LoweringInfo::temps`).
+const MAX_TEMPS: usize = 4;
+
/// How the allocator placed one node.
-#[derive(Debug, Clone, Default, PartialEq, Eq)]
-pub struct NodeAllocation {
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct NodeAllocation<'a> {
/// Moves to perform, in order, right before the node.
- pub moves_before: Vec<Move>,
+ pub moves_before: &'a [Move],
/// Where the node finds each input: a register, or a constant for
/// inputs that may be immediates.
- pub inputs: InlineVec<Location, 4>,
- pub temps: InlineVec<u8, 4>,
+ pub inputs: &'a [Location],
+ pub temps: &'a [u8],
/// Where the node puts its value: a register, or a stack slot for phis.
pub output: Option<Location>,
/// If set and the output is a register, the value must be stored to this
@@ -264,33 +272,101 @@ pub struct NodeAllocation {
pub spill_slot: Option<u32>,
/// For nodes with a frame state, where the exit finds each of its values,
/// as (frame slot, location).
- pub exit_values: Vec<(u32, Location)>,
+ pub exit_values: &'a [(u32, Location)],
}
+/// The row of a node in the tables of an allocation (see `NodeAllocation`). Its lists are parts of the columns that
+/// hold the lists of all the nodes.
+#[derive(Clone, Copy, Default)]
+struct NodeRow {
+ moves_before: Run,
+ inputs: Run,
+ exit_values: Run,
+ output: Option<Location>,
+ spill_slot: Option<u32>,
+ temps: [u8; MAX_TEMPS],
+ temp_count: u8,
+}
+
+/// Where the allocator placed the values of a graph, in tables that serve one compile after the other.
pub struct Allocation {
/// Indexed by `NodeId`.
- pub nodes: Vec<NodeAllocation>,
- /// Moves to perform, in order, at the end of each block, after its body
- /// and before its control node. Only blocks ending in a jump to a merge
- /// or a loop header have any.
- pub block_end_moves: Vec<Vec<Move>>,
+ nodes: Column<NodeRow>,
+ /// The moves before the nodes and at the ends of the blocks.
+ moves: Column<Move>,
+ /// The locations of the inputs of the nodes.
+ locations: Column<Location>,
+ exit_values: Column<(u32, Location)>,
+ /// The moves at the end of each block, as a part of `moves`.
+ block_end_moves: Column<Run>,
pub spill_slot_count: u32,
/// The values live into each block, sorted.
live_in: Lists<NodeId>,
}
impl Allocation {
+ // NB: A compile whose graph needs more of these fails.
+ const MAX_NODES: usize = 1 << 24;
+ const MAX_ITEMS: usize = 1 << 26;
+
pub fn new() -> Self {
Self {
- nodes: Vec::new(),
- block_end_moves: Vec::new(),
+ nodes: Column::new(Self::MAX_NODES, c"JIT allocation of nodes"),
+ moves: Column::new(Self::MAX_ITEMS, c"JIT allocation moves"),
+ locations: Column::new(Self::MAX_ITEMS, c"JIT allocation locations"),
+ exit_values: Column::new(Self::MAX_ITEMS, c"JIT allocation exit values"),
+ block_end_moves: Column::new(Self::MAX_NODES, c"JIT allocation of blocks"),
spill_slot_count: 0,
live_in: ValueLiveness::new_live_in(),
}
}
- pub fn node(&self, node: NodeId) -> &NodeAllocation {
- &self.nodes[node.index()]
+ /// Drops the tables and gives their memory back to the system.
+ fn release_memory(&mut self) {
+ release(&mut self.nodes);
+ release(&mut self.moves);
+ release(&mut self.locations);
+ release(&mut self.exit_values);
+ release(&mut self.block_end_moves);
+ self.live_in.release_memory();
+ }
+
+ /// Starts the allocation of a graph with `node_count` nodes and `block_count` blocks, in tables that hold
+ /// nothing.
+ fn begin(&mut self, node_count: usize, block_count: usize) -> Result<(), ColumnFull> {
+ self.nodes.clear();
+ self.nodes.try_resize(node_count, NodeRow::default())?;
+ self.moves.clear();
+ self.locations.clear();
+ self.exit_values.clear();
+ self.block_end_moves.clear();
+ self.block_end_moves.try_resize(block_count, Run::default())?;
+ self.spill_slot_count = 0;
+ Ok(())
+ }
+
+ /// How many nodes have an allocation.
+ pub fn node_count(&self) -> usize {
+ self.nodes.len()
+ }
+
+ pub fn node(&self, node: NodeId) -> NodeAllocation<'_> {
+ let row = &self.nodes[node.index()];
+ NodeAllocation {
+ moves_before: &self.moves[row.moves_before.range()],
+ inputs: &self.locations[row.inputs.range()],
+ temps: &row.temps[..usize::from(row.temp_count)],
+ output: row.output,
+ spill_slot: row.spill_slot,
+ exit_values: &self.exit_values[row.exit_values.range()],
+ }
+ }
+
+ /// Moves to perform, in order, at the end of `block`, after its body
+ /// and before its control node. Only blocks ending in a jump to a merge
+ /// or a loop header have any.
+ pub fn block_end_moves(&self, block: BlockId) -> &[Move] {
+ &self.moves[self.block_end_moves[block.index()].range()]
}
/// Whether `value` is live into `block`.
@@ -305,10 +381,56 @@ impl Default for Allocation {
}
}
-/// What the register allocator works with and its result, in tables that serve one compile after the other.
+// NB: The tests of the verifier make wrong allocations with these.
+#[cfg(test)]
+impl Allocation {
+ /// All the moves of the allocation.
+ pub(crate) fn moves(&self) -> &[Move] {
+ &self.moves
+ }
+
+ pub(crate) fn set_spill_slot(&mut self, node: NodeId, slot: Option<u32>) {
+ self.nodes[node.index()].spill_slot = slot;
+ }
+
+ pub(crate) fn set_input(&mut self, node: NodeId, index: usize, location: Location) {
+ let inputs = self.nodes[node.index()].inputs.range();
+ self.locations[inputs][index] = location;
+ }
+
+ pub(crate) fn set_move_before(&mut self, node: NodeId, index: usize, new_move: Move) {
+ let moves = self.nodes[node.index()].moves_before.range();
+ self.moves[moves][index] = new_move;
+ }
+
+ /// Adds the allocation of one more node, which has `inputs` and `output` and nothing else.
+ pub(crate) fn push_node(&mut self, inputs: &[Location], output: Option<Location>) {
+ let start = self.locations.len();
+ self.locations.extend_from_slice(inputs);
+ self.nodes.push(NodeRow {
+ inputs: Run::new(start, self.locations.len()),
+ output,
+ ..NodeRow::default()
+ });
+ }
+}
+
+/// What the register allocator works with and its result, in tables that serve one compile after the other. The
+/// allocator makes no block of the heap: all its data is here.
pub struct Regalloc {
pub allocation: Allocation,
liveness: ValueLiveness,
+ coalescing: Coalescing,
+ /// The register each value is in, if any.
+ value_registers: Column<Option<u8>>,
+ /// The register contents at the end of each finished block: `REGISTER_COUNT` values for each block.
+ end_contents: Column<Option<NodeId>>,
+ /// Whether each block is finished.
+ finished: Column<bool>,
+ /// The slot of each spill slot class that has one.
+ class_slots: Column<Option<u32>>,
+ /// Moves that happen in parallel, before they are put in an order.
+ parallel_moves: Column<Move>,
}
impl Regalloc {
@@ -317,15 +439,28 @@ impl Regalloc {
Self {
allocation: Allocation::new(),
liveness: ValueLiveness::new(),
+ coalescing: Coalescing::new(),
+ value_registers: Column::new(Allocation::MAX_NODES, c"JIT allocator work"),
+ end_contents: Column::new(
+ Allocation::MAX_NODES * REGISTER_COUNT,
+ c"JIT allocator register contents",
+ ),
+ finished: Column::new(Allocation::MAX_NODES, c"JIT allocator work"),
+ class_slots: Column::new(Allocation::MAX_NODES, c"JIT allocator work"),
+ parallel_moves: Column::new(Allocation::MAX_ITEMS, c"JIT allocator work"),
}
}
/// 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.allocation.release_memory();
self.liveness.release_memory();
+ self.coalescing.release_memory();
+ release(&mut self.value_registers);
+ release(&mut self.end_contents);
+ release(&mut self.finished);
+ release(&mut self.class_slots);
+ release(&mut self.parallel_moves);
}
}
@@ -335,6 +470,9 @@ impl Default for Regalloc {
}
}
+/// The value each register holds.
+type Contents = [Option<NodeId>; REGISTER_COUNT];
+
/// The slot of the compiled function's frame that holds `value` wherever it is live, if there is one: a value loaded
/// from one of the slots whose frame memory never changes (`Graph::unwritten_slots`).
///
@@ -350,9 +488,42 @@ pub fn frame_home(graph: &Graph, value: NodeId) -> Option<u32> {
/// 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, regalloc: &mut Regalloc) -> Result<(), CompileFailure> {
- let Regalloc { allocation, liveness } = regalloc;
+ assert!(registers.allocatable_gprs.0 >> FPR_BASE == 0);
+ assert!(!registers.allocatable_gprs.contains(registers.scratch_gpr));
+ let Regalloc {
+ allocation,
+ liveness,
+ coalescing,
+ value_registers,
+ end_contents,
+ finished,
+ class_slots,
+ parallel_moves,
+ } = regalloc;
liveness.compute(graph)?;
- Allocator::new(graph, registers, liveness, allocation).run();
+ coalescing.compute(graph, liveness)?;
+ let loops = Loops::compute(graph, liveness);
+ allocation.begin(graph.nodes.len(), graph.blocks.len())?;
+ reset(value_registers, graph.nodes.len(), None)?;
+ reset(end_contents, graph.blocks.len() * REGISTER_COUNT, None)?;
+ reset(finished, graph.blocks.len(), false)?;
+ reset(class_slots, graph.nodes.len(), None)?;
+ let allocator = Allocator {
+ graph,
+ registers,
+ liveness,
+ allocation,
+ contents: [None; REGISTER_COUNT],
+ value_registers,
+ end_contents,
+ finished,
+ position: 0,
+ slot_classes: &coalescing.classes,
+ class_slots,
+ parallel_moves,
+ loops,
+ };
+ allocator.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(())
@@ -363,53 +534,22 @@ struct Allocator<'a> {
registers: &'a RegisterSet,
liveness: &'a ValueLiveness,
allocation: &'a mut Allocation,
- /// The value each register holds.
- contents: Vec<Option<NodeId>>,
- /// The register each value is in, if any.
- value_registers: Vec<Option<u8>>,
- /// The register contents at the end of each finished block.
- end_contents: Vec<Option<Vec<Option<NodeId>>>>,
+ contents: Contents,
+ value_registers: &'a mut Column<Option<u8>>,
+ end_contents: &'a mut Column<Option<NodeId>>,
+ finished: &'a mut Column<bool>,
/// The position of the node being allocated.
position: u32,
/// The spill slot class of each value (see `coalescing`), and the
/// slot of each class that has one.
- slot_classes: Vec<u32>,
- class_slots: Vec<Option<u32>>,
+ slot_classes: &'a [u32],
+ class_slots: &'a mut Column<Option<u32>>,
+ parallel_moves: &'a mut Column<Move>,
loops: Loops,
}
-impl<'a> Allocator<'a> {
- 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 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,
- contents: vec![None; REGISTER_COUNT],
- value_registers: vec![None; graph.nodes.len()],
- end_contents: vec![None; graph.blocks.len()],
- position: 0,
- slot_classes,
- class_slots: vec![None; graph.nodes.len()],
- loops,
- }
- }
-
- fn run(mut self) {
+impl Allocator<'_> {
+ fn run(mut self) -> Result<(), ColumnFull> {
// 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
@@ -460,12 +600,15 @@ impl<'a> Allocator<'a> {
self.start_block(block);
let block_data = self.graph.block(block);
for node in &block_data.body {
- self.allocate_node(*node);
+ self.allocate_node(*node)?;
}
- self.allocation.block_end_moves[block.index()] = self.phi_moves(block, &mut cycle_temp);
- self.allocate_node(self.graph.control_id(block));
- self.end_contents[block.index()] = Some(self.contents.clone());
+ self.allocation.block_end_moves[block.index()] = self.phi_moves(block, &mut cycle_temp)?;
+ self.allocate_node(self.graph.control_id(block))?;
+ let start = block.index() * REGISTER_COUNT;
+ self.end_contents[start..start + REGISTER_COUNT].copy_from_slice(&self.contents);
+ self.finished[block.index()] = true;
}
+ Ok(())
}
/// Gives `phi` its location: `register` if it has one, and its spill
@@ -518,7 +661,7 @@ impl<'a> Allocator<'a> {
}
}
- fn set_contents(&mut self, contents: Vec<Option<NodeId>>) {
+ fn set_contents(&mut self, contents: Contents) {
for value in self.contents.iter().flatten() {
self.value_registers[value.index()] = None;
}
@@ -532,10 +675,14 @@ 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 mut contents = self.end_contents[predecessor.index()]
- .clone()
- .expect("blocks come after the predecessor whose state they start with");
+ fn contents_entering(&self, predecessor: BlockId, block: BlockId) -> Contents {
+ assert!(
+ self.finished[predecessor.index()],
+ "blocks come after the predecessor whose state they start with"
+ );
+ let start = predecessor.index() * REGISTER_COUNT;
+ let mut contents = [None; REGISTER_COUNT];
+ contents.copy_from_slice(&self.end_contents[start..start + REGISTER_COUNT]);
for value in &mut contents {
if value.is_some_and(|value| !self.liveness.is_live_in(block, value)) {
*value = None;
@@ -556,7 +703,7 @@ impl<'a> Allocator<'a> {
/// The register contents a merge with a state predecessor starts with:
/// 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>>> {
+ fn merge_contents(&self, block: BlockId) -> Option<Contents> {
let predecessor = state_predecessor(self.graph, block)?;
let mut contents = self.contents_entering(predecessor, block);
for value in &mut contents {
@@ -590,7 +737,7 @@ impl<'a> Allocator<'a> {
// Merges and loop headers start with every value in its stack
// slot, and phis in their registers.
_ => {
- let mut contents = vec![None; REGISTER_COUNT];
+ let mut contents = [None; REGISTER_COUNT];
for phi in &block_data.phis {
if let Some(Location::Register(register)) = self.allocation.nodes[phi.index()].output {
contents[register as usize] = Some(*phi);
@@ -696,115 +843,117 @@ impl<'a> Allocator<'a> {
!self.liveness.dies_at(node).contains(&value)
}
- fn exit_values(&self, node: NodeId) -> Vec<(u32, Location)> {
- let Some(frame_state) = self.graph.node(node).frame_state else {
- return Vec::new();
- };
- self.graph
- .frame_state_values(frame_state)
- .map(|(slot, value)| (slot, self.current_location(value)))
- .collect()
+ /// Adds a move before the node that is being allocated.
+ fn add_move(&mut self, from: Location, to: Location) -> Result<(), ColumnFull> {
+ self.allocation.moves.try_push(Move { from, to })
}
- fn allocate_node(&mut self, node_id: NodeId) {
+ fn allocate_node(&mut self, node_id: NodeId) -> Result<(), ColumnFull> {
let node = self.graph.node(node_id);
self.position = self.liveness.positions[node_id.index()];
let constraints = lowering_info(node);
- let input_constraints = constraints
- .inputs
- .iter()
- .zip(&node.inputs)
- .map(|(constraint, input)| {
- self.registers
- .resolve(*constraint, self.graph.constant_value(*input).is_some())
- })
- .collect::<InlineVec<_, 4>>();
- let mut moves = Vec::new();
+ // NB: The moves, the input locations and the exit values of the node go to the ends of their columns, where
+ // nothing else is added while the node is allocated.
+ let moves_start = self.allocation.moves.len();
+ let inputs_start = self.allocation.locations.len();
+ self.allocation
+ .locations
+ .try_resize(inputs_start + node.inputs.len(), Location::Register(0))?;
+ let constrained_inputs = node.inputs.len().min(constraints.inputs.len());
+ let constraint_of = |allocator: &Self, index: usize| {
+ allocator.registers.resolve(
+ constraints.inputs[index],
+ allocator.graph.constant_value(node.inputs[index]).is_some(),
+ )
+ };
let mut blocked = RegisterMask::default();
- let mut inputs = InlineVec::from_elem(Location::Register(0), node.inputs.len());
// Fixed register inputs first, so that inputs in any register do not
// take their registers.
- for (index, (input, constraint)) in node.inputs.iter().zip(&input_constraints).enumerate() {
- let InputConstraint::Fixed(register) = *constraint else {
+ for index in 0..constrained_inputs {
+ let input = node.inputs[index];
+ let InputConstraint::Fixed(register) = constraint_of(self, index) else {
continue;
};
let register = self.registers.fixed(register);
- let is_value = is_allocated_value(self.graph, *input);
+ let is_value = is_allocated_value(self.graph, input);
if !is_value || self.value_registers[input.index()] != Some(register) {
debug_assert!(!blocked.contains(register), "two inputs need the same register");
self.evict(register);
- let from = self.current_location(*input);
- moves.push(Move {
- from,
- to: Location::Register(register),
- });
+ let from = self.current_location(input);
+ self.add_move(from, Location::Register(register))?;
match from {
// The value moves, unless an earlier input of this node
// needs it where it is; then this is a copy for the node.
Location::Register(previous) if !blocked.contains(previous) => {
self.free_register(previous);
- self.assign_register(register, *input);
+ self.assign_register(register, input);
}
- Location::Stack(_) => self.assign_register(register, *input),
+ Location::Stack(_) => self.assign_register(register, input),
_ => {}
}
}
blocked = blocked.with(register);
- inputs[index] = Location::Register(register);
+ self.allocation.locations[inputs_start + index] = Location::Register(register);
}
- for (index, (input, constraint)) in node.inputs.iter().zip(&input_constraints).enumerate() {
- if *constraint == InputConstraint::RegisterOrConstant
- && let Some(bits) = self.graph.constant_value(*input)
+ for index in 0..constrained_inputs {
+ let input = node.inputs[index];
+ let constraint = constraint_of(self, index);
+ if constraint == InputConstraint::RegisterOrConstant
+ && let Some(bits) = self.graph.constant_value(input)
{
- inputs[index] = Location::Constant(bits);
+ self.allocation.locations[inputs_start + index] = Location::Constant(bits);
continue;
}
- if *constraint == InputConstraint::Anywhere {
- inputs[index] = self.current_location(*input);
+ if constraint == InputConstraint::Anywhere {
+ self.allocation.locations[inputs_start + index] = self.current_location(input);
continue;
}
if matches!(constraint, InputConstraint::Fixed(_)) {
continue;
}
let register = match self.value_registers[input.index()] {
- Some(register) if is_allocated_value(self.graph, *input) => register,
+ Some(register) if is_allocated_value(self.graph, input) => register,
_ => {
- let register = self.pick_register(blocked, RegisterClass::of(self.graph.node(*input).repr));
- moves.push(Move {
- from: self.current_location(*input),
- to: Location::Register(register),
- });
- if is_allocated_value(self.graph, *input) {
- self.assign_register(register, *input);
+ let register = self.pick_register(blocked, RegisterClass::of(self.graph.node(input).repr));
+ let from = self.current_location(input);
+ self.add_move(from, Location::Register(register))?;
+ if is_allocated_value(self.graph, input) {
+ self.assign_register(register, input);
}
register
}
};
blocked = blocked.with(register);
- inputs[index] = Location::Register(register);
+ self.allocation.locations[inputs_start + index] = Location::Register(register);
}
- let mut temps = InlineVec::new();
- for _ in 0..constraints.temps {
+ let temp_count = usize::from(constraints.temps);
+ assert!(
+ temp_count <= MAX_TEMPS,
+ "a node has more temps than an allocation has room for"
+ );
+ let mut temps = [0; MAX_TEMPS];
+ for temp in &mut temps[..temp_count] {
let register = self.pick_register(blocked, RegisterClass::General);
blocked = blocked.with(register);
- temps.push(register);
+ *temp = register;
}
// NB: Two-address instructions (like those of x86) write their output
// over their first input, which then needs no copy where it dies
// here. Nodes that may exit keep their inputs for the exit.
- let first_input_register = match inputs.first() {
+ let first_input = self.allocation.locations[inputs_start..].first().copied();
+ let first_input_register = match first_input {
Some(Location::Register(register))
if node.frame_state.is_none()
&& constraints.reuses_first_input
&& is_allocated_value(self.graph, node.inputs[0])
&& self.liveness.dies_at(node_id).contains(&node.inputs[0])
- && RegisterClass::of_register(*register) == RegisterClass::of(node.repr)
- && !temps.contains(register) =>
+ && RegisterClass::of_register(register) == RegisterClass::of(node.repr)
+ && !temps[..temp_count].contains(&register) =>
{
- Some(*register)
+ Some(register)
}
_ => None,
};
@@ -846,7 +995,13 @@ impl<'a> Allocator<'a> {
let output = pick_output(self);
// Lazy exits of calls happen after the call returns, so they find
// their values after the clobber.
- let exit_values = self.exit_values(node_id);
+ let exit_values_start = self.allocation.exit_values.len();
+ if let Some(frame_state) = node.frame_state {
+ for (slot, value) in self.graph.frame_state_values(frame_state) {
+ let location = self.current_location(value);
+ self.allocation.exit_values.try_push((slot, location))?;
+ }
+ }
// Values whose last use is this node no longer need their registers.
let liveness = self.liveness;
@@ -866,12 +1021,17 @@ impl<'a> Allocator<'a> {
}
}
+ let moves_before = Run::new(moves_start, self.allocation.moves.len());
+ let inputs = Run::new(inputs_start, self.allocation.locations.len());
+ let exit_values = Run::new(exit_values_start, self.allocation.exit_values.len());
let allocation = &mut self.allocation.nodes[node_id.index()];
- allocation.moves_before = moves;
+ allocation.moves_before = moves_before;
allocation.inputs = inputs;
allocation.temps = temps;
+ allocation.temp_count = constraints.temps;
allocation.output = output.map(Location::Register);
allocation.exit_values = exit_values;
+ Ok(())
}
/// Gives the phis of the merge `join` their locations, at the end of its
@@ -908,66 +1068,71 @@ impl<'a> Allocator<'a> {
}
}
- /// The moves at the end of `block` that put the values live into the
- /// merge `join` (and its phis' inputs) where the merge expects them.
- fn merge_moves(&self, block: BlockId, join: BlockId) -> Vec<Move> {
+ /// Adds the moves into the phis of `successor` at the end of `block`, as moves that happen in parallel.
+ fn add_phi_moves(&mut self, block: BlockId, successor: BlockId) -> Result<(), ColumnFull> {
+ for (phi, input) in liveness::phi_inputs_from(self.graph, block, successor) {
+ let parallel_move = Move {
+ from: self.current_location(input),
+ to: self.allocation.nodes[phi.index()].output.expect("phis have locations"),
+ };
+ self.parallel_moves.try_push(parallel_move)?;
+ }
+ Ok(())
+ }
+
+ /// Adds the moves at the end of `block` that put the values live into the
+ /// merge `join` (and its phis' inputs) where the merge expects them, as moves that happen in parallel.
+ fn add_merge_moves(&mut self, block: BlockId, join: BlockId) -> Result<(), ColumnFull> {
let contents = self.merge_contents(join).expect("the merge has a state predecessor");
let phis = &self.graph.block(join).phis;
- contents
- .iter()
- .enumerate()
- .filter_map(|(register, value)| {
- let value = (*value)?;
- if phis.contains(&value) {
- return None;
- }
- let to = Location::Register(u8::try_from(register).expect("register numbers fit in u8"));
- let from = self.current_location(value);
- (from != to).then_some(Move { from, to })
- })
- .chain(
- liveness::phi_inputs_from(self.graph, block, join).map(|(phi, input)| Move {
- from: self.current_location(input),
- to: self.allocation.nodes[phi.index()].output.expect("phis have locations"),
- }),
- )
- .collect()
+ for (register, value) in contents.iter().enumerate() {
+ let Some(value) = *value else {
+ continue;
+ };
+ if phis.contains(&value) {
+ continue;
+ }
+ let to = Location::Register(u8::try_from(register).expect("register numbers fit in u8"));
+ let from = self.current_location(value);
+ if from != to {
+ self.parallel_moves.try_push(Move { from, to })?;
+ }
+ }
+ self.add_phi_moves(block, join)
}
/// 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> {
+ /// successor in place, as a part of the moves of the allocation.
+ fn phi_moves(&mut self, block: BlockId, cycle_temp: &mut Option<u32>) -> Result<Run, ColumnFull> {
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();
+ return Ok(Run::default());
};
- let moves = match state_predecessor(self.graph, *successor) {
- Some(predecessor) if predecessor != block => self.merge_moves(block, *successor),
+ self.parallel_moves.clear();
+ match state_predecessor(self.graph, *successor) {
+ Some(predecessor) if predecessor != block => self.add_merge_moves(block, *successor)?,
merge => {
if merge.is_some() {
self.place_merge_phis(block, *successor);
}
- liveness::phi_inputs_from(self.graph, block, *successor)
- .map(|(phi, input)| Move {
- from: self.current_location(input),
- to: self.allocation.nodes[phi.index()].output.expect("phis have locations"),
- })
- .collect::<Vec<_>>()
+ self.add_phi_moves(block, *successor)?;
}
- };
- if moves.is_empty() {
- return moves;
+ }
+ if self.parallel_moves.is_empty() {
+ return Ok(Run::default());
}
let temp = *cycle_temp.get_or_insert_with(|| {
let slot = self.allocation.spill_slot_count;
self.allocation.spill_slot_count += 1;
slot
});
- resolve_parallel_moves(&moves, Location::Stack(temp))
+ let start = self.allocation.moves.len();
+ resolve_parallel_moves(self.parallel_moves, Location::Stack(temp), &mut self.allocation.moves)?;
+ Ok(Run::new(start, self.allocation.moves.len()))
}
}
@@ -1011,12 +1176,12 @@ pub fn dump_allocation(graph: &Graph, allocation: &Allocation) -> String {
let block = BlockId::from_index(index);
writeln!(out, "b{index}:").unwrap();
for node_id in graph.block_nodes(block) {
- let node = &allocation.nodes[node_id.index()];
- if Some(node_id) == graph.block(block).control && !allocation.block_end_moves[index].is_empty() {
- writeln!(out, " moves {}", moves_text(&allocation.block_end_moves[index])).unwrap();
+ let node = allocation.node(node_id);
+ if Some(node_id) == graph.block(block).control && !allocation.block_end_moves(block).is_empty() {
+ writeln!(out, " moves {}", moves_text(allocation.block_end_moves(block))).unwrap();
}
if !node.moves_before.is_empty() {
- writeln!(out, " moves {}", moves_text(&node.moves_before)).unwrap();
+ writeln!(out, " moves {}", moves_text(node.moves_before)).unwrap();
}
write!(out, " v{} {}", node_id.0, graph.node(node_id).op.name()).unwrap();
if !node.inputs.is_empty() {
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/moves.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/moves.rs
index 56f935a95c4..b939d8ea01b 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/moves.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/moves.rs
@@ -6,37 +6,54 @@
//! Sequentializing parallel moves.
+use ak::Column;
+use ak::ColumnFull;
+
use super::Location;
use super::Move;
-/// Orders a set of moves that happen in parallel (every source is read
-/// before any destination is written) into a sequence with the same effect.
+/// Orders the moves `pending`, which happen in parallel (every source is read
+/// before any destination is written), into a sequence with the same effect, which it adds to `result`.
/// Destinations must be distinct and must not be constants. Cycles are broken
-/// through `temp`, which must not appear in `moves`.
-pub fn resolve_parallel_moves(moves: &[Move], temp: Location) -> Vec<Move> {
- let mut pending = moves.iter().copied().filter(|m| m.from != m.to).collect::<Vec<_>>();
+/// through `temp`, which must not appear in the moves. No move is left in `pending`.
+pub fn resolve_parallel_moves(
+ pending: &mut Column<Move>,
+ temp: Location,
+ result: &mut Column<Move>,
+) -> Result<(), ColumnFull> {
+ let mut kept = 0;
+ for index in 0..pending.len() {
+ let pending_move = pending[index];
+ if pending_move.from != pending_move.to {
+ pending[kept] = pending_move;
+ kept += 1;
+ }
+ }
+ pending.truncate(kept);
debug_assert!(pending.iter().all(|m| !matches!(m.to, Location::Constant(_))));
debug_assert!(pending.iter().all(|m| m.from != temp && m.to != temp));
- let mut result = Vec::with_capacity(pending.len());
while !pending.is_empty() {
let ready = pending
.iter()
.position(|candidate| pending.iter().all(|other| other.from != candidate.to));
if let Some(index) = ready {
- result.push(pending.remove(index));
+ result.try_push(pending[index])?;
+ // NB: The moves that are left stay in their order.
+ pending.copy_within(index + 1.., index);
+ pending.truncate(pending.len() - 1);
continue;
}
// Every destination is still needed as a source, so the moves form
// cycles. Save one destination's value and read it from the temp.
let saved = pending[0].to;
- result.push(Move { from: saved, to: temp });
- for pending_move in &mut pending {
+ result.try_push(Move { from: saved, to: temp })?;
+ for pending_move in pending.iter_mut() {
if pending_move.from == saved {
pending_move.from = temp;
}
}
}
- result
+ Ok(())
}
#[cfg(test)]
@@ -56,6 +73,16 @@ mod tests {
state
}
+ /// The sequence that `moves`, which happen in parallel, are put in.
+ fn resolve(moves: &[Move], temp: Location) -> Vec<Move> {
+ let mut pending = Column::new(64, c"test");
+ let mut result = Column::new(64, c"test");
+ pending.try_extend_from_slice(moves).unwrap();
+ resolve_parallel_moves(&mut pending, temp, &mut result).unwrap();
+ assert!(pending.is_empty());
+ result.to_vec()
+ }
+
fn check(moves: &[Move]) {
let temp = Location::Stack(99);
let locations = moves
@@ -71,7 +98,7 @@ mod tests {
.into_iter()
.collect::<Vec<_>>();
let before = initial.iter().copied().collect::<HashMap<_, _>>();
- let after = simulate(&initial, &resolve_parallel_moves(moves, temp));
+ let after = simulate(&initial, &resolve(moves, temp));
for m in moves {
let expected = match m.from {
Location::Constant(bits) => u32::try_from(bits).unwrap(),
@@ -105,6 +132,6 @@ mod tests {
m(Register(4), Register(3)),
]);
// Self moves disappear.
- assert!(resolve_parallel_moves(&[m(Register(1), Register(1))], Stack(9)).is_empty());
+ assert!(resolve(&[m(Register(1), Register(1))], Stack(9)).is_empty());
}
}
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
index ba55dcd91ec..cf3e9f6b23b 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
@@ -204,9 +204,8 @@ fn many_simultaneously_live_values_are_spilled() {
// Ten values are live at once, but there are only six registers.
assert!(allocation.spill_slot_count >= 4);
let reloads = allocation
- .nodes
+ .moves()
.iter()
- .flat_map(|node| &node.moves_before)
.filter(|m| matches!(m.from, Location::Stack(_)))
.count();
assert!(reloads >= 4);
@@ -304,7 +303,7 @@ fn swapping_loop_phis_go_through_a_temp_slot() {
let back_edge = graph.blocks[header].predecessors[1];
// NB: The back edge's block starts with the phis in their registers,
// like the merge it is, so the swap goes through a temp slot.
- let moves = &allocation.block_end_moves[back_edge.index()];
+ let moves = allocation.block_end_moves(back_edge);
assert_eq!(moves.len(), 3, "{moves:?}");
assert!(moves.iter().any(|m| matches!(m.to, Location::Stack(_))), "{moves:?}");
// The loop header starts with the registers of the block entering the
@@ -414,8 +413,8 @@ fn loop_phis_share_spill_slots_with_their_inputs() {
for phi in &graph.blocks[header].phis {
let input = graph.node(*phi).inputs[back_edge];
let (phi_slot, input_slot) = (
- allocation.nodes[phi.index()].spill_slot,
- allocation.nodes[input.index()].spill_slot,
+ allocation.node(*phi).spill_slot,
+ allocation.node(input).spill_slot,
);
if let (Some(phi_slot), Some(input_slot)) = (phi_slot, input_slot) {
assert_eq!(phi_slot, input_slot, "{}", dump_allocation(&graph, &allocation));
@@ -426,7 +425,7 @@ fn loop_phis_share_spill_slots_with_their_inputs() {
.node(*phi)
.inputs
.iter()
- .all(|input| allocation.nodes[input.index()].spill_slot == phi_slot)
+ .all(|input| allocation.node(*input).spill_slot == phi_slot)
{
assert_eq!(phi_spill_store(&graph, &allocation, *phi), None);
filled += 1;
@@ -518,7 +517,8 @@ fn loops_leave_the_values_they_only_carry_through_in_their_stack_slots() {
.find(|predecessor| predecessor.index() > header)
.unwrap();
assert!(
- allocation.block_end_moves[back_edge.index()]
+ allocation
+ .block_end_moves(back_edge)
.iter()
.all(|m| !matches!(m.from, Location::Stack(_)) && !matches!(m.to, Location::Stack(_))),
"{}",
@@ -572,7 +572,7 @@ fn int32_operations_write_over_their_first_input_where_it_dies() {
.map(|(index, _)| index)
.collect::<Vec<_>>();
assert_eq!(xors.len(), 2, "{}", dump_allocation(&graph, &allocation));
- let second = &allocation.nodes[xors[1]];
+ let second = allocation.node(NodeId::from_index(xors[1]));
assert_eq!(
second.output,
Some(second.inputs[0]),
@@ -671,7 +671,10 @@ fn float64_operations_write_over_their_first_input_where_it_dies() {
.map(|(index, _)| index)
.collect::<Vec<_>>();
assert_eq!(binaries.len(), 2, "{}", dump_allocation(&graph, &allocation));
- let (first, second) = (&allocation.nodes[binaries[0]], &allocation.nodes[binaries[1]]);
+ let (first, second) = (
+ allocation.node(NodeId::from_index(binaries[0])),
+ allocation.node(NodeId::from_index(binaries[1])),
+ );
assert_ne!(
first.output,
Some(first.inputs[0]),
@@ -775,16 +778,16 @@ fn the_verifier_finds_values_in_the_wrong_place() {
// 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 = allocate_with(&graph, &registers);
- broken.nodes[argument.index()].spill_slot = None;
+ broken.set_spill_slot(argument, None);
assert!(verify(&graph, &registers, &broken).is_err());
// Reading an input from a register that holds something else.
let call = find_node(&graph, |node| matches!(node.op, Op::CallSlowPath { .. }));
let mut broken = allocation;
- let Location::Register(register) = broken.nodes[call.index()].inputs[2] else {
+ let Location::Register(register) = broken.node(call).inputs[2] else {
panic!("the argument is in a register");
};
- broken.nodes[call.index()].inputs[2] = Location::Register((register + 1) % 6);
+ broken.set_input(call, 2, Location::Register((register + 1) % 6));
assert!(verify(&graph, &registers, &broken).is_err());
}
@@ -824,7 +827,11 @@ fn the_verifier_finds_values_reloaded_from_frame_slots_that_do_not_hold_them() {
// Another frame slot holds another value.
let mut broken = allocate_with(&graph, &registers);
- broken.nodes[returned.index()].moves_before[0].from = Location::Frame(r(5).raw());
+ let wrong_move = Move {
+ from: Location::Frame(r(5).raw()),
+ ..broken.node(returned).moves_before[0]
+ };
+ broken.set_move_before(returned, 0, wrong_move);
assert!(verify(&graph, &registers, &broken).is_err());
// A store to the slot, which nothing may do, makes it hold another value.
@@ -848,11 +855,8 @@ fn the_verifier_finds_values_reloaded_from_frame_slots_that_do_not_hold_them() {
.unwrap();
stored.blocks[block].body.push(store);
let mut allocation = allocation;
- allocation.nodes.push(NodeAllocation::default());
- allocation.nodes.push(NodeAllocation {
- inputs: [Location::Constant(value::UNDEFINED)].into_iter().collect(),
- ..NodeAllocation::default()
- });
+ allocation.push_node(&[], None);
+ allocation.push_node(&[Location::Constant(value::UNDEFINED)], None);
let errors = verify(&stored, &registers, &allocation).unwrap_err();
assert!(errors.contains("nothing writes"), "{errors}");
}
@@ -1251,7 +1255,7 @@ fn float64_values_get_floating_point_registers() {
let allocation = allocate_and_verify(&graph);
let mut floats = 0;
for (index, node) in graph.nodes.iter().enumerate() {
- let output = allocation.nodes[index].output;
+ let output = allocation.node(NodeId::from_index(index)).output;
match (node.repr, output) {
(Some(Repr::Float64), Some(Location::Register(register))) => {
assert!(register >= FPR_BASE, "v{index} is a float64 in r{register}");
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs
index 7f3fb205a76..d41bebdbb64 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs
@@ -256,7 +256,7 @@ impl Verifier<'_> {
return;
};
let expected_count = self.graph.frame_state_values(frame_state).count();
- let exit_values = &self.allocation.node(node).exit_values;
+ let exit_values = self.allocation.node(node).exit_values;
if expected_count != exit_values.len() {
self.error(format!(
"{context}: exit has {} values, frame state {}",
@@ -292,7 +292,7 @@ impl Verifier<'_> {
for node in &block_data.body {
self.simulate_node(&mut state, *node);
}
- let end_moves = &self.allocation.block_end_moves[block.index()];
+ let end_moves = self.allocation.block_end_moves(block);
self.apply_moves(&mut state, end_moves, &format!("end of b{}", block.0));
self.simulate_node(&mut state, self.graph.control_id(block));
state
@@ -304,7 +304,7 @@ impl Verifier<'_> {
let context = format!("v{}", node_id.0);
debug_assert!(node.op != Op::Phi);
- self.apply_moves(state, &allocation.moves_before, &context);
+ self.apply_moves(state, allocation.moves_before, &context);
if let Op::StoreSlot { slot } = node.op
&& self.graph.is_unwritten_slot(slot)
{
@@ -322,7 +322,7 @@ impl Verifier<'_> {
lowering.temps
));
}
- for (index, (input, location)) in node.inputs.iter().zip(&allocation.inputs).enumerate() {
+ for (index, (input, location)) in node.inputs.iter().zip(allocation.inputs).enumerate() {
if let Location::Constant(bits) = location {
if self.graph.constant_value(*input) != Some(*bits) {
self.error(format!("{context}: input {index} is not the constant {bits:#x}"));
@@ -346,7 +346,7 @@ impl Verifier<'_> {
// A node may exit at any point after reading its inputs, including
// after it wrote its temps and its output: exit values must survive both.
- for temp in &allocation.temps {
+ for temp in allocation.temps {
self.check_location(Location::Register(*temp), &context);
if allocation.inputs.contains(&Location::Register(*temp)) {
self.error(format!("{context}: temp r{temp} is also an input"));